diff --git "a/4904.jsonl" "b/4904.jsonl" new file mode 100644--- /dev/null +++ "b/4904.jsonl" @@ -0,0 +1,760 @@ +{"seq_id":"488423445","text":"#EJEMPLO 14\r\n#Nombre: Carlos Homero Vacacela Velez\r\n#Aula: Software A1\r\n\r\n#Ejercicio 13: Elabore pseudocódigo para el caso en que se desean escribir los números del 1 al 100.\r\n\r\nclass Contar:\r\n def Variables(self):\r\n print(\"Contar los números del 1 al 100 usando While\")\r\n i=1\r\n while i <=100:\r\n print(i)\r\n i=i+1\r\n print(\"\\n\")\r\n print(\"**FIN DE LA EJECUCIÓN**\") \r\n \r\ncontar= Contar()\r\ncontar.Variables()","sub_path":"14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"482492815","text":"#!/usr/bin/env python\n\n\"\"\"main.py - This file contains handlers that are called by taskqueue and/or\ncronjobs.\"\"\"\nimport logging\n\nimport webapp2\nfrom google.appengine.api import mail, app_identity\nfrom api import SolitaireAPI\nfrom models import User\nfrom models import Game\n\n\nclass SendReminderEmail(webapp2.RequestHandler):\n def get(self):\n \"\"\"Send a reminder email to each User with an email and unfinisehd games\n about games. Called every hour using a cron job\"\"\"\n app_id = app_identity.get_application_id()\n users = User.query(User.email != None).fetch()\n have_incomplete_game = False\n for user in users:\n active_games = Game.query(ancestor=user.key).filter(Game.game_over==False).fetch()\n\n if active_games:\n subject = 'This is a reminder!'\n body = 'Hello {}, try out Solitaire Game!'.format(user.user_name)\n # This will send test emails, the arguments to send_mail are:\n # from, to, subject, body\n mail.send_mail('noreply@{}.appspotmail.com'.format(app_id),\n user.email,\n subject,\n body)\n\n\napp = webapp2.WSGIApplication([\n ('/crons/send_reminder', SendReminderEmail)\n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"361027033","text":"import subprocess\nimport time\nfrom PySide import QtCore\n\n\nclass TestHeavyLoading(QtCore.QThread):\n test_done = QtCore.Signal(object)\n\n def __init__(self, index):\n QtCore.QThread.__init__(self)\n self.index = index\n self.name = 'Heavy Loading'\n self.result = 'PASS'\n self.note = 'dummy heavy loading.'\n\n def run(self):\n print(\"TestHeavyLoading run()+\")\n\n cmd = \"adb shell ls /\"\n try:\n time.sleep(3)\n\n output = subprocess.check_output(cmd, shell=True)\n print(output)\n except subprocess.CalledProcessError:\n self.result = 'FAIL'\n self.note = 'Fail to test: ' + self.name\n\n\n self.test_done.emit('%s,%s,%s' % (self.index, self.result, self.note))\n","sub_path":"test_heavy_loading.py","file_name":"test_heavy_loading.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"87759940","text":"import numpy as np\nfrom pyscf import gto\n#from pyscf import dft\n#from pyscf import scf\n\ndef extract_ao_integrals(mol, prefix):\n \"\"\"Extracts ao integrals from pyscf and writes them to text files.\n\n mol -- the pyscf mol object (e.g. created by something like gto.M(....) )\n prefix -- A file name prefix used for writing the integrals to files.\n The file names will be:\n prefix_nuc.txt -- the nuclear repulsion energy\n prefix_ovl.txt -- the overlap matrix, created using numpy's savetxt function\n prefix_oei.txt -- the one-electron integral matrix, created using numpy's savetxt function\n prefix_tei.txt -- the two electron integrals written in our own custom format\n \"\"\"\n\n with open(prefix + \"_nuc.txt\", \"w\") as f:\n f.write(\"%.18e\\n\" % mol.energy_nuc())\n\n np.savetxt(prefix + \"_ovl.txt\", mol.intor(\"int1e_ovlp\"))\n\n np.savetxt(prefix + \"_oei.txt\", mol.intor(\"int1e_kin\") + mol.intor(\"int1e_nuc\"))\n\n tei = mol.intor(\"int2e\")\n tei = np.reshape(tei,(2,2,2,2))\n\n\n with open(prefix + \"_tei.txt\", \"w\") as f:\n for i in range(tei.shape[0]):\n for j in range(tei.shape[1]):\n for k in range(tei.shape[2]):\n for l in range(tei.shape[3]):\n f.write(\"%4i %4i %4i %4i %.18e\\n\" % (i, j, k, l, tei[i,j,k,l]))\n\n\nmol = gto.M(atom=\"He 0 0 0; H 0 0 1.4632\",charge = 1, basis='sto-3g', unit='Angstrom')\n\nextract_ao_integrals(mol, 'heh_sto3g')\n\n","sub_path":"Helium Hydride ion/heh_folder/integral_extractor_heh.py","file_name":"integral_extractor_heh.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"636005782","text":"from dataloader import DataLoader\nfrom utils import selectData\nimport numpy as np\nimport pickle as pkl\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport argparse\nimport os\n\n\ndef load(path):\n\tf = open(path, \"rb\")\n\treturn pkl.load(f)\n\n\ndef convertToColor(map):\n\tpalette = {0: (0, 0, 0)}\n\tfor k, color in enumerate(sns.color_palette(\"hls\", len(np.unique(map)))):\n\t\tpalette[k + 1] = tuple(np.asarray(255 * np.array(color), dtype='uint8'))\n\tmap = np.array(map, dtype=int)\n\tunique = np.unique(map)\n\tlut = np.zeros((int)(np.max(unique) + 1), dtype=np.int)\n\tfor it, i in enumerate(unique):\n\t\tlut[i] = it\n\tmap = lut[map]\n\ta = np.zeros(shape=(np.shape(map)[0], np.shape(map)[1], 3), dtype=np.uint8)\n\tfor i in range(np.shape(map)[0]):\n\t\tfor j in range(np.shape(map)[1]):\n\t\t\ta[i][j] = palette[map[i][j]]\n\treturn a\n\ndef draw(pic):\n\tpass\n\n\nif __name__ == \"__main__\":\n\tparser=argparse.ArgumentParser()\n\tparser.add_argument(\"-d\",\"--data\",default=\"sa\")\n\targs=parser.parse_args()\n\tdpi = 100\n\tdic = {\"pc\": 3, \"pu\": 2, \"sl\": 4, \"sa\": 5}\n\tif not os.path.exists(\"save/0313/img/dccn/\"):\n\t\tos.makedirs(\"save/0313/img/dccn/\")\n\tfor i in (args.data,):\n\t\tpath = \"./save/0312309/data/DCCN/p7/\"+i+\"/1/data/probmap.pkl\"\n\t\tspd=\"save/0313/img/dccn/\"+i+\"pdm.eps\"\n\t\tspb = \"save/0313/img/dccn/\" + i + \"pbm.eps\"\n\t\t# path=\"./save/0312309/dccn/p7/sa/1/data/probmap.pkl\"\n\t\tpmap = load(path)\n\t\tmap = np.argmax(pmap, axis=1)\n\t\tcurrentPx = 0\n\t\tpathName, matName = selectData(dic[i])\n\t\tdl = DataLoader(pathName, matName, 7, 0.1, 1)\n\t\tindex = dl.loadAllLabeledData()[-1]\n\t\tgrdt=dl.label\n\t\tprint(np.max(grdt))\n\t\tgt = np.zeros((dl.height, dl.width))\n\t\tfor i in range(len(map)):\n\t\t\tidx = index[i]\n\t\t\th = idx // dl.width\n\t\t\tw = idx % dl.width\n\t\t\tgt[h][w] = map[i] + 1\n\t\tplt.figure(figsize=(dl.width * 5 / dpi, dl.height * 5 / dpi))\n\t\tplt.tick_params(axis='both', which='both', bottom=False, top=False, labelbottom=False, right=False, left=False,\n\t\t\t\t\t\tlabelleft=False)\n\t\tplt.imshow(convertToColor(gt))\n\t\tsv = plt.gcf()\n\t\tsv.savefig(spd, format=\"eps\", dpi=dpi)\n\t\tpm=np.zeros((dl.height,dl.width))\n\t\tfor i in range(len(map)):\n\t\t\tidx=index[i]\n\t\t\th = idx // dl.width\n\t\t\tw = idx % dl.width\n\t\t\t# print(h,w)\n\t\t\tpm[h][w]=pmap[i][grdt[h][w]-1]\n\t\tplt.figure(figsize=(dl.width * 5 / dpi, dl.height * 5 / dpi))\n\t\tplt.tick_params(axis='both', which='both', bottom=False, top=False, labelbottom=False, right=False, left=False,\n\t\t labelleft=False)\n\t\tplt.imshow(pm)\n\t\tsv = plt.gcf()\n\t\tsv.savefig(spb, format=\"eps\", dpi=dpi)\n","sub_path":"draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"628509330","text":"\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\nimport sys\n\nclass resultType:\n def __init__(self, isBst, min, max):\n self.isBst = isBst\n self.min = min\n self.max = max\n\nclass Solution:\n \"\"\"\n @param: root: The root of binary tree.\n @return: True if the binary tree is BST, or false\n \"\"\"\n def isValidBST(self, root):\n # write your code here\n return self.helper(root).isBst\n\n\n def helper(self, root):\n if root is None:\n return resultType(True, sys.maxsize, -sys.maxsize)\n\n left = self.helper(root.left)\n right = self.helper(root.right)\n\n if not left.isBst or not right.isBst:\n return resultType(False, 0, 0)\n\n if root.left is not None and left.max >= root.val or root.right is not None and right.min <= root.val:\n return resultType(False, 0, 0)\n\n return resultType(True, min(left.min, root.val), max(right.max, root.val))","sub_path":"python/validateBinarySearchTree.py","file_name":"validateBinarySearchTree.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"624052983","text":"# 1st level Model Structure: Equation Block\n# import sys\n# sys.path.append('..')\n# this module define the rules for constructing a energy block in the master block\n# this is the global component set import, so that all modules uses the same set\nfrom global_sets.component import m\nfrom physics.bounds import energy_bounds3 as energy_bounds\n\n# data import and pre-processing\nfrom data import thermal_data as h\nfrom pyomo import environ as pe\n\n# import mean\nfrom statistics import mean\n\n# defile knietic block rule\ndef energy_block_rule(block):\n #-----------------------------------SETS-----------------------------------\n\n # No local SETS\n\n #-----------------------------GLOBAL VARIABLES-----------------------------\n\n # global variables\n # print('\\t'*2,'Importing Energy Block......')\n # print('\\t'*2,'Using the following parent variable:')\n # print('\\t'*2,'-'*36)\n # print('\\t'*2,block.parent_block().T.name)\n # print('\\t'*2,block.parent_block().T_F.name)\n # print('\\t'*2,block.parent_block().x.name)\n # print('\\t'*2,block.parent_block().y.name)\n # print('\\t'*2,block.parent_block().z.name)\n # print('\\t'*2,block.parent_block().H_F.name)\n # print('\\t'*2,block.parent_block().H_V.name)\n # print('\\t'*2,block.parent_block().H_L.name)\n # print('\\t'*2,'-'*36)\n # print('')\n #-----------------------------VARIABLES Bounds------------------------------\n def dH_V_bounds(model,i):\n lower = min(energy_bounds['dH_V[{}]'.format(i)])\n lower = lower - abs(lower)*0.1\n upper = max(energy_bounds['dH_V[{}]'.format(i)])\n upper = upper + abs(upper)*0.1\n return (lower,upper)\n\n def dH_L_bounds(model,i):\n lower = min(energy_bounds['dH_L[{}]'.format(i)])\n lower = lower - abs(lower)*0.1\n upper = max(energy_bounds['dH_L[{}]'.format(i)])\n upper = upper + abs(upper)*0.1\n return (lower,upper)\n\n def dH_vap_bounds(model,i):\n lower = min(energy_bounds['dH_vap[{}]'.format(i)])\n lower = lower - abs(lower)*0.1\n upper = max(energy_bounds['dH_vap[{}]'.format(i)])\n upper = upper + abs(upper)*0.1\n return (lower,upper)\n\n #------------------------------LOCAL VARIABLES------------------------------\n\n # Molar Enthalpy for gas, liquid and vaporization at temperature\n block.dH_F = pe.Var(m.COMP_FEED,within=pe.Reals) # kJ/mol\n block.dH_V = pe.Var(m.COMP_TOTAL,within=pe.Reals,bounds=dH_V_bounds)\n block.dH_L = pe.Var(m.COMP_TOTAL,within=pe.Reals,bounds=dH_L_bounds)\n block.dH_vap = pe.Var(m.COMP_TOTAL,within=pe.Reals,bounds=dH_vap_bounds)\n\n # initialize these variable: 1/2(ub+lb)\n for i in m.COMP_TOTAL:\n block.dH_V[i] = mean(energy_bounds['dH_V[{}]'.format(i)])\n block.dH_L[i] = mean(energy_bounds['dH_L[{}]'.format(i)])\n block.dH_vap[i] = mean(energy_bounds['dH_vap[{}]'.format(i)])\n\n print('>','Importing Energy Blocks......')\n print('>','Adding the following local variable:')\n print('-'*50)\n\n for i in block.component_objects(pe.Var,active=True):\n print('|',i)\n\n print('-'*50)\n print('')\n\n #---------------------------------Equations---------------------------------\n\n # Vapor\n def dH_V_rule(block,i):\n return block.dH_V[i] == h.Hf0[i] + 1e-3*(h.a0[i]*(block.parent_block().T-h.T0_f) + 1/2*h.a1[i]*(block.parent_block().T**2-h.T0_f**2) + \\\n 1/3*h.a2[i]*(block.parent_block().T**3-h.T0_f**3) + 1/4*h.a3[i]*(block.parent_block().T**4-h.T0_f**4) + 1/5*h.a4[i]*(block.parent_block().T**5-h.T0_f**5))\n block.dH_V_con = pe.Constraint(m.COMP_TOTAL,rule=dH_V_rule)\n\n def H_V_rule(block):\n return block.parent_block().H_V == sum(block.parent_block().y[i] * block.dH_V[i] for i in m.COMP_TOTAL)\n block.H_V_con = pe.Constraint(rule=H_V_rule)\n\n # Liquid\n def dH_vap_rule(block,i):\n tmp = (h.Tc[i]-block.parent_block().T)/(h.Tc[i]-h.Tb[i])\n return block.dH_vap[i] == h.HV[i] * (0.5*tmp + 0.5*(tmp**2+1e-6)**0.5)**0.38\n block.dH_vap_con = pe.Constraint(m.COMP_TOTAL,rule=dH_vap_rule)\n\n def dH_L_rule(block,i):\n return block.dH_L[i] == block.dH_V[i] - block.dH_vap[i]\n block.dH_L_con = pe.Constraint(m.COMP_TOTAL,rule=dH_L_rule)\n\n def H_L_rule(block):\n return block.parent_block().H_L == sum(block.parent_block().x[i] * block.dH_L[i] for i in m.COMP_TOTAL)\n block.H_L_con = pe.Constraint(rule=H_L_rule)\n\n # Feed\n def dH_F_rule(block,i):\n return block.dH_F[i] == h.Hf0[i] + 1e-3*(h.a0[i]*(block.parent_block().T_F-h.T0_f) + 1/2*h.a1[i]*(block.parent_block().T_F**2-h.T0_f**2) + \\\n 1/3*h.a2[i]*(block.parent_block().T_F**3-h.T0_f**3) + 1/4*h.a3[i]*(block.parent_block().T_F**4-h.T0_f**4) + 1/5*h.a4[i]*(block.parent_block().T_F**5-h.T0_f**5))\n block.dH_F_con = pe.Constraint(m.COMP_FEED,rule=dH_F_rule)\n\n def H_F_rule(block):\n return block.parent_block().H_F == sum(block.parent_block().z[i] * block.dH_F[i] for i in m.COMP_FEED)\n block.H_F_con = pe.Constraint(rule=H_F_rule)\n","sub_path":"physics/energy/energy_reboiler.py","file_name":"energy_reboiler.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"116848694","text":"from collections import defaultdict\nfrom itertools import combinations\nfrom random import randint\ndef triple_with_sum2(a, target=0):\n \"\"\"Return a tuple of three numbers in the sequence a that sum to\n target (default: 0). Raise NotFoundError if no triple sums to\n target.\n\n \"\"\" \n positions = defaultdict(set)\n for i, n in enumerate(a): \n positions[n].add(i)\n for (i, ai), (j, aj) in combinations(enumerate(a), 2):\n n = target - ai - aj \n if positions[n].difference((i, j)):\n return n, ai, aj\n raise NotFoundError('No triple sums to {}.'.format(target))\ncases = 100 \ntestcases = [randint(-200, 200) for _ in range(100000)]\n\nprint(triple_with_sum2(testcases,20)) \n \n \n","sub_path":"Miscellaneous/triple_sums.py","file_name":"triple_sums.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"316762783","text":"import re\nimport logging\n\nfrom model.dao.person_dao import PersonDAO\nfrom sqlalchemy import *\n\nimport hashlib\n\nfrom exceptions import Error, InvalidData\nfrom model.mapping.person import Person\n\n\nclass PersonController:\n \"\"\"\n Member actions\n \"\"\"\n\n def __init__(self, database_engine):\n self._database_engine = database_engine\n\n def list_persons(self, isAdmin=None):\n logging.info(\"List persons\")\n with self._database_engine.new_session() as session:\n persons = PersonDAO(session).get_all()\n persons_data = [person.to_dict() for person in persons]\n return persons_data\n\n def get_person(self, person_id, person_type=None):\n logging.info(\"Get person %s\" % person_id)\n with self._database_engine.new_session() as session:\n dao = PersonDAO(session)\n member = dao.get(person_id)\n member_data = member.to_dict()\n return member_data\n\n def get_member(self, member_id):\n return self.get_person(member_id, person_type='member')\n\n def create_person(self, data, person_type=None):\n logging.info(\"Create member with data %s\" % str(data))\n self._check_person_data(data)\n try:\n with self._database_engine.new_session() as session:\n # Save member in database\n dao = PersonDAO(session)\n \n person = session.query(Person).filter_by(email=data.get('email')).all()\n if len(person) > 0: \n raise InvalidData(\"Mail already existing\") \n\n member = dao.create(data)\n member_data = member.to_dict()\n return member_data\n except Error as e:\n # log error\n logging.error(\"An Error occured (%s)\" % str(e))\n raise e\n\n def create_member(self, data):\n return self.create_person(data, 'member')\n\n def connexion(self, email, password):\n logging.info(\"Connexion with email %s\" % str(email))\n with self._database_engine.new_session() as session:\n dao = PersonDAO(session)\n pwd = str(hashlib.sha256(password.encode('utf8')).hexdigest())\n \n try:\n person = session.query(Person).filter_by(email=email).one()\n if pwd == person.password:\n logging.info(\"Connexion success %s %s\" % (str(person.firstname), str(person.lastname)))\n return person.to_dict()\n else:\n logging.info(\"Wrong id, try again\")\n return {0}\n except:\n logging.info(\"Wrong id, try again\")\n return {0}\n\n def _update_person(self, member_id, member_data, person_type=None):\n logging.info(\"Update %s with data: %s\" % (member_id, str(member_data)))\n with self._database_engine.new_session() as session:\n dao = PersonDAO(session)\n person = dao.get(member_id)\n\n person = dao.update(person, member_data)\n return person.to_dict()\n\n def update_person(self, member_id, member_data):\n self._check_person_data(member_data, update=True)\n return self._update_person(member_id, member_data, person_type='person')\n\n def update_member(self, member_id, data):\n self._check_member_data(data, update=True)\n return self._update_person(member_id, data, person_type='member')\n\n def delete_person(self, member_id, person_type=None):\n logging.info(\"Delete person %s\" % member_id)\n with self._database_engine.new_session() as session:\n dao = PersonDAO(session)\n member = dao.get(member_id)\n dao.delete(member)\n\n def search_person(self, firstname, lastname, person_type=None):\n logging.info(\"Search person %s %s\" % (firstname, lastname))\n # Query database\n with self._database_engine.new_session() as session:\n dao = PersonDAO(session)\n member = dao.get_by_name(firstname, lastname)\n return member.to_dict()\n\n def _check_person_data(self, data, update=False):\n name_pattern = re.compile(\"^[\\S-]{2,50}$\")\n password_pattern = re.compile(\"^[\\S-]{2,256}$\")\n email_pattern = re.compile(\"^([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$\")\n specs = {\n 'firstname': {\"type\": str, \"regex\": name_pattern},\n 'lastname': {\"type\": str, \"regex\": name_pattern},\n 'email': {\"type\": str, \"regex\": email_pattern},\n 'password': {\"type\": str, \"regex\": password_pattern}\n }\n self._check_data(data, specs, update=update)\n\n def _check_data(self, data, specs, update=False):\n for mandatory, specs in specs.items():\n if not update:\n if mandatory not in data or data[mandatory] is None:\n raise InvalidData(\"Missing value %s\" % mandatory)\n else:\n if mandatory not in data:\n continue\n value = data[mandatory]\n if \"type\" in specs and not isinstance(value, specs[\"type\"]):\n raise InvalidData(\"Invalid type %s\" % mandatory)\n if \"regex\" in specs and isinstance(value, str) and not re.match(specs[\"regex\"], value):\n raise InvalidData(\"Invalid value %s\" % mandatory)","sub_path":"controller/person_controller.py","file_name":"person_controller.py","file_ext":"py","file_size_in_byte":5378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"187934793","text":"import numpy as np\nimport os\nimport torch\nfrom torch.utils.data import DataLoader, Dataset\nfrom data.provider import pc_normalize, rotate_point_cloud_with_normal, rotate_perturbation_point_cloud_with_normal, \\\n random_scale_point_cloud, shift_point_cloud, jitter_point_cloud, shuffle_points, random_point_dropout\n\n\nclass ModelNet40(Dataset):\n\n def __init__(self, data_root, split, npoints, augment=False, dp=False, normalize=True):\n assert(split == 'train' or split == 'test')\n self.npoints = npoints\n self.augment = augment\n self.dp = dp\n self.normalize = normalize\n\n cls2name, name2cls = self.decode_classes(os.path.join(data_root, 'modelnet40_shape_names.txt'))\n train_list_path = os.path.join(data_root, 'modelnet40_train.txt')\n train_files_list = self.read_list_file(train_list_path, name2cls)\n test_list_path = os.path.join(data_root, 'modelnet40_test.txt')\n test_files_list = self.read_list_file(test_list_path, name2cls)\n self.files_list = train_files_list if split == 'train' else test_files_list\n self.caches = {}\n\n def read_list_file(self, file_path, name2cls):\n base = os.path.dirname(file_path)\n files_list = []\n with open(file_path, 'r') as f:\n for line in f.readlines():\n name = '_'.join(line.strip().split('_')[:-1])\n cur = os.path.join(base, name, '{}.txt'.format(line.strip()))\n files_list.append([cur, name2cls[name]])\n return files_list\n\n def decode_classes(self, file_path):\n cls2name, name2cls = {}, {}\n with open(file_path, 'r') as f:\n for i, name in enumerate(f.readlines()):\n cls2name[i] = name.strip()\n name2cls[name.strip()] = i\n return cls2name, name2cls\n\n def augment_pc(self, pc_normal):\n rotated_pc_normal = rotate_point_cloud_with_normal(pc_normal)\n rotated_pc_normal = rotate_perturbation_point_cloud_with_normal(rotated_pc_normal)\n jittered_pc = random_scale_point_cloud(rotated_pc_normal[:, :3])\n jittered_pc = shift_point_cloud(jittered_pc)\n jittered_pc = jitter_point_cloud(jittered_pc)\n rotated_pc_normal[:, :3] = jittered_pc\n return rotated_pc_normal\n\n def __getitem__(self, index):\n if index in self.caches:\n return self.caches[index]\n file, label = self.files_list[index]\n xyz_points = np.loadtxt(file, delimiter=',')\n xyz_points = xyz_points[:self.npoints, :]\n if self.normalize:\n xyz_points[:, :3] = pc_normalize(xyz_points[:, :3])\n if self.augment:\n xyz_points = self.augment_pc(xyz_points)\n if self.dp:\n xyz_points = random_point_dropout(xyz_points)\n self.caches[index] = [xyz_points, label]\n return xyz_points, label\n\n def __len__(self):\n return len(self.files_list)\n\n\nif __name__ == '__main__':\n modelnet40 = ModelNet40(data_root='/root/Pointnet_Pointnet2_pytorch/data/modelnet40_normal_resampled', split='test')\n test_loader = DataLoader(dataset=modelnet40,\n batch_size=16,\n shuffle=True)\n for point, label in test_loader:\n print(point.shape)\n print(label.shape)\n","sub_path":"data/ModelNet40.py","file_name":"ModelNet40.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"184913662","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom .models import Task\nfrom .forms import TaskCreationForm\n\n\ndef index(request):\n latest_tasks_list = Task.objects.order_by('id')\n context_dict = {'active_tasks_list': latest_tasks_list.filter(is_done=False),\n 'completed_tasks_list': latest_tasks_list.filter(is_done=True)}\n if request.method == 'POST':\n form = TaskCreationForm(request.POST, request.FILES)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.is_done = False\n instance.save()\n return HttpResponseRedirect('')\n\n else:\n print(form.errors)\n else:\n form = TaskCreationForm()\n context_dict['task_creation_form'] = form\n return render(request, 'todolist/index.html', context_dict)\n\n\ndef task_info(request, task_id):\n try:\n task = Task.objects.get(id=task_id)\n except Task.DoesNotExist:\n raise Http404(\"Poll does not exist\")\n context_dict = {'task': task}\n\n if request.method == 'POST':\n task.is_done = True\n task.save()\n\n return render(request, 'todolist/task_info.html', context_dict)\n\ndef do_task(request, task_id):\n task = Task.objects.get(id=task_id)\n if request.method == 'POST':\n task.is_done = True\n task.save()\n return redirect('/')\n","sub_path":"task2/procrastinizer/todolist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"222156464","text":"import spacy\nfrom spacy.matcher import Matcher\nfrom spacy.matcher import PhraseMatcher\n\nfrom whoosh.qparser import QueryParser\nimport whoosh.index as index\nfrom whoosh.index import open_dir\nfrom whoosh.query import Every\n\nimport wikipedia\nimport wikipediaapi\nimport math\nimport time\n\nfrom collections import defaultdict\n\nimport itertools\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom tqdm import tqdm\nimport sys\nfrom os import path, remove\nimport copy\nimport pickle\nfrom requests import ConnectTimeout, HTTPError, ReadTimeout, Timeout, ConnectionError\n\nfrom prdualrank import prDualRank\nfrom extractor_helpers import *\nfrom wiki_score import *\n# from wiki_ir_compute import * # New Addition\n\nimport re\nimport nltk\nfrom nltk.corpus import stopwords\nfrom collections import defaultdict\n\nngram_prob_map = []\nphrase_seg_score = {}\nremoved_phrases = set()\nwiki_score_cache = {}\n# wiki_ir_cache = {}\nerror_count = 0\n\ntotal_ngram_counts = []\n\nfinal_patterns = []\nfinal_keywords = []\npattern_to_score_map = {}\nkeyword_to_score_map = {}\n\ndef get_seg_score(candidate_phrase):\n global final_patterns, final_keywords, pattern_to_score_map, keyword_to_score_map, ngram_prob_map, phrase_seg_score, removed_phrases, wiki_score_cache, error_count, total_ngram_counts\n if candidate_phrase in set(phrase_seg_score.keys()).difference(removed_phrases):\n return phrase_seg_score[candidate_phrase]\n return 0.009633215 # 1/4 of avg seg_score in the file\n\ndef run_prdualrank(T_0, unranked_patterns, unranked_phrases, file):\n global final_patterns, final_keywords, pattern_to_score_map, keyword_to_score_map, ngram_prob_map, phrase_seg_score, removed_phrases, wiki_score_cache, error_count, total_ngram_counts\n phrase2id = {}\n for i in range(len(unranked_phrases)):\n phrase2id[unranked_phrases[i]] = i\n\n id2phrase = {}\n for i in range(len(unranked_phrases)):\n id2phrase[i] = unranked_phrases[i]\n\n id2pattern = {}\n for i in range(len(unranked_patterns)):\n id2pattern[i] = unranked_patterns[i]\n\n seedIdwConfidence = {}\n for key, val in phrase2id.items():\n if key in T_0:\n seedIdwConfidence[val] = 0.0\n\n id2patterns = defaultdict(set)\n pattern2ids = defaultdict(set)\n\n context_matrix = np.zeros((len(unranked_phrases), len(unranked_patterns)))\n # find c (t, p)\n with open(file, 'r') as f:\n file_chunk = partition(f)\n matcher = Matcher(nlp.vocab)\n for t in file_chunk:\n doc = nlp(t)\n for i in range(len(unranked_patterns)):\n offset = 0\n for pattern_dict in unranked_patterns[i]:\n if 'POS' in pattern_dict:\n break\n offset += 1\n matcher.add(\"extraction\", None, unranked_patterns[i])\n matches = matcher(doc)\n for match_id, start, end in matches:\n span = doc[start+offset:end].text\n j = unranked_phrases.index(span) if span in unranked_phrases else -1\n if j == -1:\n continue\n context_matrix[j, i] += 1\n id2patterns[j].add(i)\n pattern2ids[i].add(j)\n matcher.remove(\"extraction\")\n\n\n id2sup = {}\n for i in range(len(unranked_phrases)):\n id2sup[i] = 0\n\n pattern2sup = {}\n for i in range(len(unranked_patterns)):\n pattern2sup[i] = 0\n\n for id in id2patterns.keys():\n sum = 0\n for col in range(len(unranked_patterns)):\n sum += context_matrix[id, col]\n id2sup[id] = sum\n\n for pattern in pattern2ids.keys():\n sum = 0\n for row in range(len(unranked_phrases)):\n sum += context_matrix[row, pattern]\n pattern2sup[pattern] = sum\n\n l1, l2, l3, l4, m1, m2, m3, m4 = prDualRank(seedIdwConfidence, [], id2patterns, pattern2ids, {},\n {}, {}, {}, id2phrase, context_matrix.tolist(), id2sup, pattern2sup,\n FLAGS_VERBOSE=False, FLAGS_DEBUG=False)\n\n return l1, l2, l3, l4, m1, m2, m3, m4\n\ndef get_new_patterns_and_phrases(T_0, T, file, max_patterns, max_keywords):\n global final_patterns, final_keywords, pattern_to_score_map, keyword_to_score_map, ngram_prob_map, phrase_seg_score, removed_phrases, wiki_score_cache, error_count, total_ngram_counts\n\n phrases = [keyword for keyword in T]\n unranked_patterns = []\n # find occurrences of seed phrases\n with open(file, \"r\") as f:\n file_chunk = partition(f)\n for document in file_chunk:\n print(len(document))\n document = nlp(document)\n patterns_to_process = []\n for word in document:\n children = []\n tokens = []\n for tok in word.subtree:\n children.append(tok.text)\n tokens.append(tok)\n possible_pattern = \" \".join(children)\n candidate_patterns = [(phrase, tokens) for phrase in phrases if phrase in possible_pattern and phrase != possible_pattern]\n patterns_to_process.extend(candidate_patterns)\n for chunk in document.noun_chunks:\n possible_pattern = chunk.text\n candidate_patterns = [(phrase, [w for w in chunk]) for phrase in phrases if phrase in possible_pattern and phrase != possible_pattern]\n patterns_to_process.extend(candidate_patterns) \n # patterns_to_process contains phrases and patterns. These have to be converted to usual format\n for phrase, raw_pattern in patterns_to_process:\n raw_pattern_text = [p.text for p in raw_pattern]\n phrase_len = len(phrase.split(\" \"))\n match_start = 0\n for i in range(len(raw_pattern_text)):\n if phrase == \" \".join(raw_pattern_text[i:(i+phrase_len)]):\n match_start = i\n break\n constructed_pattern = []\n for token in raw_pattern[:match_start]:\n constructed_pattern.append({\"TEXT\": token.text})\n for token in raw_pattern[match_start:(match_start+phrase_len)]:\n constructed_pattern.append({\"POS\": token.pos_})\n for token in raw_pattern[(match_start+phrase_len):]:\n constructed_pattern.append({\"TEXT\": token.text})\n \n if raw_pattern[-1].pos_ == \"PUNCT\":\n constructed_pattern = constructed_pattern[:-1]\n if raw_pattern[0].pos_ == \"PUNCT\":\n constructed_pattern = constructed_pattern[1:]\n \n if constructed_pattern not in unranked_patterns and len(constructed_pattern) <= 10 and len(constructed_pattern) > 0:\n unranked_patterns.append(constructed_pattern)\n unranked_phrases = list(getPhrases(file, unranked_patterns))\n\n # At this point, we have new unranked_patterns and unranked_phrases\n\n new_patterns = []\n new_pattern_count = 0\n for elem in unranked_patterns:\n if elem not in final_patterns:\n final_patterns.append(elem)\n new_patterns.append(elem)\n new_pattern_count += 1\n if new_pattern_count == max_patterns:\n break\n\n new_phrases = []\n new_phrase_count = 0\n for elem in unranked_phrases:\n if elem not in final_keywords:\n final_keywords.append(elem)\n new_phrases.append(elem)\n new_phrase_count += 1\n if new_phrase_count == max_keywords:\n break\n\n # print(\"New Patterns\", new_patterns)\n # print(\"New Phrases\", new_phrases)\n\n return new_patterns, new_phrases\n\ndef execute_ranking(T_0, file, scoring_mode, wiki_wiki, cs_categories):\n global final_patterns, final_keywords, pattern_to_score_map, keyword_to_score_map, ngram_prob_map, phrase_seg_score, removed_phrases, wiki_score_cache, error_count, total_ngram_counts\n\n unranked_patterns = final_patterns\n unranked_phrases = final_keywords\n\n l1, l2, l3, l4, m1, m2, m3, m4 = run_prdualrank(T_0, unranked_patterns, unranked_phrases, file)\n\n pattern_precision = m1\n pattern_recall = m2\n tuple_precision = m3\n tuple_recall = m4\n\n# pattern2fscore = {}\n# for i in range(len(unranked_patterns)):\n# precision = pattern_precision[i]\n# recall = pattern_recall[i]\n\n# f1 = 0.0\n# if (recall + precision) != 0.0:\n# f1 = ((2 * recall * precision) / (recall + precision))\n\n# pattern2fscore[i] = f1\n\n# sorted_patterns_ids = sorted(pattern2fscore, key=pattern2fscore.__getitem__, reverse=True)\n# ranked_patterns = [(unranked_patterns[i], pattern2fscore[i]) for i in sorted_patterns_ids] # All patterns are now sorted!\n ranked_patterns = unranked_patterns\n\n phrase2fscore = {}\n phrase2precision = {}\n phrase2recall = {}\n\n for i in range(len(unranked_phrases)):\n precision = tuple_precision[i]\n recall = tuple_recall[i]\n\n phrase2precision[unranked_phrases[i]] = precision\n phrase2recall[unranked_phrases[i]] = recall\n\n fscore = 0.0\n\n f1 = 0.0\n if (recall + precision) != 0.0:\n f1 = ((2 * recall * precision) / (recall + precision))\n\n if scoring_mode == 9: # Current Best Method\n if unranked_phrases[i] not in wiki_score_cache:\n try:\n wiki_score_cache[unranked_phrases[i]] = get_wiki_score(unranked_phrases[i], wiki_wiki, cs_categories, 40)\n except (ConnectTimeout, HTTPError, ReadTimeout, Timeout, ConnectionError):\n wiki_score_cache[unranked_phrases[i]] = 0.5\n error_count += 1\n fscore = 2.718 ** (wiki_score_cache[unranked_phrases[i]] * f1 * get_seg_score(unranked_phrases[i]))\n else:\n fscore = -100\n phrase2fscore[i] = fscore\n if unranked_phrases[i] in T_0:\n phrase2fscore[i] = 100\n keyword_to_score_map[unranked_phrases[i]] = fscore\n\n sorted_phrases_ids = sorted(phrase2fscore, key=phrase2fscore.__getitem__, reverse=True)\n ranked_keywords = [(unranked_phrases[i], phrase2fscore[i]) for i in sorted_phrases_ids] # All keywords are now ranked!\n\n with open('../development_ipynbs/cm_precision.pickle', 'wb') as f:\n pickle.dump(phrase2precision, f)\n print(\"[LOG] Saving precision values.\")\n with open('../development_ipynbs/cm_recall.pickle', 'wb') as f:\n pickle.dump(phrase2recall, f)\n print(\"[LOG] Saving recall values.\")\n\n return ranked_patterns, ranked_keywords\n\nif (__name__ == \"__main__\"):\n # global final_patterns, final_keywords, pattern_to_score_map, keyword_to_score_map, ngram_prob_map, phrase_seg_score, removed_phrases, wiki_score_cache, error_count, total_ngram_counts\n seed = set([\"databases\",\"algorithms\",\"machine learning\", \"artificial intelligence\",\"neural networks\",'attention mechanisms',\"constraint programming\", \"natural language processing\",'principal component analysis','long range dependencies',\"distributed database systems\", \"hierarchical deep reinforcement learning\",'supervised machine learning models',\"sequence to sequence learning\"])\n final_keywords = list(copy.deepcopy(seed))\n filename = \"./data/\" + sys.argv[1] # \"./data/\" + \"small.txt\"\n # iter_num = 5\n max_patterns = int(sys.argv[2]) # 100\n max_keywords = int(sys.argv[3]) # 500\n results_filename = \"./outputs/\" + sys.argv[4] # \"./outputs/\" + \"results_small.txt\"\n scoring_mode = int(sys.argv[5]) # int(sys.argv[5]) # 9 or 12\n iter_num = int(sys.argv[6])\n\n if (path.exists(filename) == False):\n print(\"\\nWarning: the data file does not exist!\\n\")\n sys.exit()\n if (path.exists(results_filename) == True):\n print(\"\\nWarning: the results file already exists! Do you really want to overwrite?\\n\")\n sys.exit()\n if (scoring_mode != 9):\n print(\"\\nScoring Mode is incorrect! Please retry.\\n\")\n sys.exit()\n\n print(\"\\n[LOG]: Started run for scoring method \" + str(scoring_mode) + \"\\n\")\n\n lower_filename = filename[:-4] + \"_lower.txt\"\n\n with open(lower_filename, \"w+\") as f:\n with open(filename, \"r\") as fn:\n t = fn.read().lower()\n f.write(t)\n\n with open('./data/wiki_score_cache.txt', 'rb') as f:\n wiki_score_cache = pickle.loads(f.read())\n\n wiki_wiki = None\n cs_categories = None\n wiki_wiki = wikipediaapi.Wikipedia('en') # generating wiki_wiki\n\n cs_categories = set() # obtaining cs_categories\n with open('./data/wikipedia_reference/cs_categories.txt', 'r') as f:\n for line in f:\n cs_categories.add(line[:-1])\n\n # Data regarding Phrase Segmentation Scores\n phrase_seg_score = defaultdict(float)\n with open('./data/segmentation_multi_words_0_1.txt', 'r') as f:\n lines = f.readlines()\n for line in lines:\n for phrase in (re.findall(re.compile(r\"(.+?)\", re.I|re.S), line.strip())):\n phrase_seg_score[phrase] += 1\n\n max_seg_score = 0\n for key, val in phrase_seg_score.items():\n max_seg_score = max(max_seg_score, phrase_seg_score[key])\n\n for key, val in phrase_seg_score.items():\n phrase_seg_score[key] = val/max_seg_score\n\n for stopwd in set(stopwords.words('english')):\n for wd in phrase_seg_score.keys():\n if stopwd in wd.split(' '):\n removed_phrases.add(wd)\n\n with open('./data/ngram_values.txt', 'rb') as f:\n ngram_prob_map = pickle.loads(f.read())\n\n with open('./data/total_ngram_count.txt', 'rb') as f:\n total_ngram_counts = pickle.loads(f.read())\n\n with open(results_filename, \"w+\") as f:\n f.write(\"Hyperparameters are: \\n\")\n f.write('iter_num: ' + str(iter_num) + \"\\n\")\n f.write('max_patterns ' + str(max_patterns) + \"\\n\")\n f.write('max_keywords ' + str(max_keywords) + \"\\n\")\n for i in tqdm(range(iter_num)):\n print(\"Iteration \" + str(i+1) + \"...\\n\")\n f.write(\"\\n\\nIteration \" + str(i+1) + \"...\\n\")\n start = time.time()\n new_patterns, new_phrases = get_new_patterns_and_phrases(seed, final_keywords, lower_filename, max_patterns, max_keywords) # <--- final_keywords, final_patterns updated here\n end = time.time()\n f.write(\"Iteration time taken is \" + str(end - start) + \"\\n\")\n f.write(\"New Patterns \" + str(new_patterns) + \"\\n\")\n f.write(\"New Phrases \" + str(new_phrases) + \"\\n\")\n print(\"Executing PRDualRank now...\")\n start = time.time()\n ranked_patterns, ranked_keywords = execute_ranking(seed, lower_filename, scoring_mode, wiki_wiki, cs_categories)\n end = time.time()\n f.write(\"PRDualRank time taken is \" + str(end - start) + \"\\n\")\n print(\"PRDualRank finished!\")\n\n # result_keywords_set = sorted(keyword_to_score_map, key=keyword_to_score_map.__getitem__, reverse=True)\n # result_keywords_list = [(word, keyword_to_score_map[word]) for word in result_keywords_set]\n\n f.write(\"\\nFinal Sorted Keywords:\\n\")\n f.write(str(ranked_keywords))\n\n f.write(\"\\nFinal Sorted Patterns:\\n\")\n f.write(str(ranked_patterns))\n\n with open('./data/wiki_score_cache.txt', 'wb') as f2:\n pickle.dump(wiki_score_cache, f2)\n\n f.write(\"\\n[LOG]: Error count: \" + str(error_count) + \"\\n\")\n\n remove(lower_filename)\n print(\"\\n[LOG]: Error count: \" + str(error_count) + \"\\n\")\n print(\"\\n[LOG]: Ended run for scoring method +\" + str(scoring_mode) + \"\\n\")\n","sub_path":"final_stuff/final_framework_v8.py","file_name":"final_framework_v8.py","file_ext":"py","file_size_in_byte":15702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"172559580","text":"''''''\nfrom pyspark import SparkContext,SparkConf\n\nconf=SparkConf().setMaster(\"local\").setAppName(\"Popular Movie With Name\")\nsc=SparkContext().getOrCreate(conf=conf)\n\ndef make_movie_dict():\n movies={}\n with open(\"ml-100k/u.item\", encoding = \"ISO-8859-1\") as file:\n for line in file:\n fields=line.split(\"|\")\n movies[int(fields[0])]=fields[1]\n\n return movies\n'''\n Broadcast Movies dict\n'''\nmovies=sc.broadcast(make_movie_dict())\ndef movies_mapper(line):\n fields=line.split()\n return (int(fields[1]),1)\n\nmovies_data=sc.textFile(\"ml-100k/u.data\")\nmovies_count=movies_data.map(movies_mapper).reduceByKey(lambda x,y:x+y)\nmovies_count_flipped=movies_count.map(lambda x:(x[1],x[0]))\nmovies_count_sorted=movies_count_flipped.sortByKey()\nmovies_count_with_name=movies_count_sorted.map(lambda x:(x[0],movies.value[x[1]]))\nmovies_count_with_name.foreach(lambda x:print(\"'{a}' has been reviewed by {b} people\".format(a=x[1],b=x[0])))\n","sub_path":"src/popular_movie_with_name.py","file_name":"popular_movie_with_name.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"573923119","text":"import os, markdown, json\nfrom datetime import datetime\nfrom flask import Flask\nfrom flask_restful import Resource, Api, reqparse\nfrom google.cloud import bigquery\nfrom flask_httpauth import HTTPBasicAuth\nfrom google.oauth2 import service_account\n\n\n# Get Credentials.\nwith open('./credentials.json', 'r') as file:\n json_string = json.load(file)\ncredentials = service_account.Credentials.from_service_account_info(json_string)\nproject_id = os.getenv('PROJECT_ID')\n\n\n# Get USER DATA.\nwith open('./user_data.json', 'r') as file:\n USER_DATA = json.load(file)\n\n\ndef get_db(credentials, project_id):\n # Make client.\n bqclient = bigquery.Client(\n credentials=credentials,\n project=project_id,\n )\n return bqclient\n\n\ndef query_db(query_string):\n # Initialize BigQuery client object.\n client = get_db(credentials, project_id)\n # API request\n query_job = client.query(query_string)\n # Waits for query to finish\n rows = query_job.result()\n # Download query results into list of dictionaries.\n data = list()\n for i in rows:\n dct = {\n 'latitude': i[0],\n 'longitude': i[1],\n 'avg_vehicle_count': i[2]\n }\n\n data.append(dct)\n return data\n\n\ndef get_last_update_date():\n query_string = \"\"\"\n SELECT date FROM `real-time-gbfs-feeds.gbfs_feeds.hotspots`\n ORDER BY date DESC\n LIMIT 1\n \"\"\"\n client = get_db(credentials, project_id)\n # API request\n query_job = client.query(query_string)\n # Waits for query to finish\n rows = query_job.result()\n time = ''\n for i in rows:\n time+=i[0]\n return time\n\n\n# Create an instance of Flask\napp = Flask(__name__)\n\n# Create the API\napi = Api(app, prefix=\"/api/v1\")\nauth = HTTPBasicAuth()\n\n\n@app.route(\"/\")\ndef index():\n \"\"\"Present API documentation\"\"\"\n\n # Open the README file\n with open('./API_docs.md', 'r') as markdown_file:\n\n # Read the content of the file\n content = markdown_file.read()\n\n # Convert to HTML\n return markdown.markdown(content)\n\n\n@auth.verify_password\ndef verify(username, password):\n if not (username and password):\n return False\n return USER_DATA.get(username) == password\n\n\nclass Hotposts(Resource):\n @auth.login_required\n def get(self):\n parser = reqparse.RequestParser()\n\n parser.add_argument('geofence', required=True)\n parser.add_argument('date', required=True)\n\n # Parse the arguments into an object.\n args = parser.parse_args()\n geofence = args['geofence']\n date = args['date']\n\n # If date is not a string, return a 400 error.\n if not isinstance(date, str):\n return {'message': 'date must be string', 'data': {}}, 400\n\n try:\n datetime_obj = datetime.strptime(date, '%Y-%m-%d')\n\n # If provided dat is not in %Y-%m-%d format return a 400 error\n except ValueError as error:\n return {'message': f\"time data '{date}' does not match format '%Y-%m-%d'\", 'data': {}}, 400\n\n query = f\"\"\"\n SELECT\n latitude, longitude, AVG(cnt_vehicles) AS avg_num_vehicles\n FROM\n `real-time-gbfs-feeds.gbfs_feeds.hotspots`\n WHERE date LIKE \"{date}%\"\n GROUP BY latitude, longitude\n ORDER BY AVG(cnt_vehicles) DESC\n \"\"\"\n # Get data.\n data = query_db(query)\n date_str = get_last_update_date()\n time = date_str.split('.')[0]\n timestamp = int(datetime.timestamp(datetime.strptime(time, '%Y-%m-%d %H:%M:%S')))\n # If there is no data, return a 404 error.\n if not len(data):\n return {'message': 'There is no data in this date', 'data': {}}, 404\n\n return {'message': 'data retrieved',\n 'last_updated': timestamp,\n 'data': data}, 200\n\n\napi.add_resource(Hotposts, '/hotspots')\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8000, debug=True)\n","sub_path":"api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"316266233","text":"#\n# This source file is part of appleseed.\n# Visit http://appleseedhq.net/ for additional information and resources.\n#\n# This software is released under the MIT license.\n#\n# Copyright (c) 2019 Jonathan Dent, The appleseedhq Organization\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n\nimport math\nimport os\n\nimport mathutils\n\nimport appleseed as asr\nfrom ..assethandlers import AssetType\nfrom ...logger import get_logger\nfrom ..nodetree import NodeTreeTranslator\nfrom ..textures import TextureTranslator\nfrom ..translator import Translator\nfrom ...utils.path_util import get_osl_search_paths\n\nlogger = get_logger()\n\n\nclass LampTranslator(Translator):\n def __init__(self, bl_lamp, asset_handler=None):\n logger.debug(\"Creating light translator for %s\", bl_lamp.name_full)\n super().__init__(bl_lamp, asset_handler=asset_handler)\n\n self.__lamp_model = None\n self.__as_lamp_params = None\n self.__as_area_lamp = None\n\n self.__matrices = dict()\n self.__instances = dict()\n\n self._as_lamp_radiance = None\n\n self._as_area_lamp_material = None\n self._as_area_lamp_shadergroup = None\n self.__node_tree = None\n\n @property\n def bl_lamp(self):\n return self._bl_obj\n\n def create_entities(self, bl_scene, textures_to_add, as_texture_translators):\n logger.debug(\"Creating light entity for %s\", self.bl_lamp.name_full)\n as_lamp_data = self.bl_lamp.data.appleseed\n\n self.__lamp_model = self._get_lamp_model()\n\n if self.bl_lamp.data.type != 'AREA':\n radiance = self._convert_color(as_lamp_data.radiance)\n lamp_radiance_name = f\"{self.appleseed_name}_radiance\"\n self._as_lamp_radiance = asr.ColorEntity(lamp_radiance_name,\n {'color_space': 'linear_rgb'},\n radiance)\n\n if self.__lamp_model == 'point_light':\n self.__as_lamp_params = self._get_point_lamp_params()\n if self.__lamp_model == 'spot_light':\n self.__as_lamp_params = self._get_spot_lamp_params(textures_to_add,\n as_texture_translators)\n if self.__lamp_model == 'directional_light':\n self.__as_lamp_params = self._get_directional_lamp_params()\n if self.__lamp_model == 'sun_light':\n self.__as_lamp_params = self._get_sun_lamp_params()\n\n else:\n shape_params = self._get_area_mesh_params()\n mesh_name = f\"{self.appleseed_name}_mesh\"\n\n self.__as_area_lamp = asr.create_primitive_mesh(mesh_name, shape_params)\n\n mat_name = f\"{self.appleseed_name}_mat\"\n\n shader_name = f\"{self.appleseed_name}_tree\"\n\n if not self.bl_lamp.data.use_nodes:\n self._set_shadergroup()\n else:\n self.__node_tree = NodeTreeTranslator(self.bl_lamp.data.node_tree, self._asset_handler, self.appleseed_name)\n self.__node_tree.create_entities(bl_scene)\n\n self._as_area_lamp_material = asr.Material('osl_material',\n mat_name,\n {'osl_surface': shader_name})\n\n def flush_entities(self, as_assembly, as_project):\n logger.debug(\"Flushing light entity for %s\", self.bl_lamp.name_full)\n if self.__lamp_model != 'area_lamp':\n radiance_name = self._as_lamp_radiance.get_name()\n as_assembly.colors().insert(self._as_lamp_radiance)\n self._as_lamp_radiance = as_assembly.colors().get_by_name(radiance_name)\n\n for key, transform_matrix in self.__matrices.items():\n as_lamp = asr.Light(self.__lamp_model, key, self.__as_lamp_params)\n as_lamp.set_transform(self._convert_matrix(transform_matrix))\n as_assembly.lights().insert(as_lamp)\n self.__instances[key] = as_assembly.lights().get_by_name(key)\n\n else:\n mat_name = f\"{self.appleseed_name}_mat\"\n\n mesh_name = f\"{self.appleseed_name}_mesh\"\n\n as_assembly.materials().insert(self._as_area_lamp_material)\n self._as_area_lamp_material = as_assembly.materials().get_by_name(mat_name)\n\n as_assembly.objects().insert(self.__as_area_lamp)\n self.__as_area_lamp = as_assembly.objects().get_by_name(mesh_name)\n\n if self._as_area_lamp_shadergroup is not None:\n shadergroup_name = self._as_area_lamp_shadergroup.get_name()\n as_assembly.shader_groups().insert(self._as_area_lamp_shadergroup)\n self._as_area_lamp_shadergroup = as_assembly.shader_groups().get_by_name(shadergroup_name)\n else:\n self.__node_tree.flush_entities(as_assembly, None)\n\n self.__instance_params = self._get_area_mesh_instance_params()\n for key, transform_matrix in self.__matrices.items():\n inst_name = f\"{key}_inst\"\n as_area_lamp_mesh_inst = asr.ObjectInstance(inst_name,\n self.__instance_params,\n mesh_name,\n self._convert_area_matrix(transform_matrix),\n {\"default\": mat_name},\n {\"default\": \"__null_material\"})\n\n as_assembly.object_instances().insert(as_area_lamp_mesh_inst)\n self.__instances[key] = as_assembly.object_instances().get_by_name(inst_name)\n\n def update_lamp(self, context, depsgraph, as_assembly, textures_to_add, as_texture_translators):\n logger.debug(\"Updating light translator for %s\", self.bl_lamp.name_full)\n if self.__lamp_model != 'area_lamp':\n as_assembly.colors().remove(self._as_lamp_radiance)\n for lamp in self.__instances.values():\n as_assembly.lights().remove(lamp)\n else:\n as_assembly.materials().remove(self._as_area_lamp_material)\n as_assembly.objects().remove(self.__as_area_lamp)\n if self._as_area_lamp_shadergroup is not None:\n as_assembly.shader_groups().remove(self._as_area_lamp_shadergroup)\n self._as_area_lamp_shadergroup = None\n else:\n self.__node_tree.delete(as_assembly)\n self.__node_tree = None\n for mesh_inst in self.__instances.values():\n as_assembly.object_instances().remove(mesh_inst)\n\n self.__instances.clear()\n\n self.create_entities(depsgraph.scene_eval, textures_to_add, as_texture_translators)\n self.flush_entities(as_assembly, None)\n\n def delete_instances(self, as_assembly, as_scene):\n if self.__lamp_model != 'area_lamp':\n for lamp in self.__instances.values():\n as_assembly.lights().remove(lamp)\n else:\n for mesh_inst in self.__instances.values():\n as_assembly.object_instances().remove(mesh_inst)\n\n self.__instances.clear()\n\n def xform_update(self, inst_key, bl_matrix, as_assembly, as_scene):\n logger.debug(\"Updating instances for %s\", self.bl_lamp.name_full)\n if self.__lamp_model != 'area_lamp':\n as_lamp = asr.Light(self.__lamp_model, inst_key, self.__as_lamp_params)\n as_lamp.set_transform(self._convert_matrix(bl_matrix))\n as_assembly.lights().insert(as_lamp)\n self.__instances[inst_key] = as_assembly.lights().get_by_name(inst_key)\n else:\n mat_name = f\"{self.appleseed_name}_mat\"\n mesh_name = f\"{self.appleseed_name}_mesh\"\n inst_name = f\"{inst_key}_inst\"\n as_area_lamp_mesh_inst = asr.ObjectInstance(inst_name,\n self.__instance_params,\n mesh_name,\n self._convert_area_matrix(bl_matrix),\n {\"default\": mat_name},\n {\"default\": \"__null_material\"})\n\n as_assembly.object_instances().insert(as_area_lamp_mesh_inst)\n self.__instances[inst_key] = as_assembly.object_instances().get_by_name(inst_name)\n\n def delete_lamp(self, as_scene, as_assembly):\n if self.__lamp_model != 'area_lamp':\n as_assembly.colors().remove(self._as_lamp_radiance)\n for lamp in self.__instances.values():\n as_assembly.lights().remove(lamp)\n else:\n as_assembly.materials().remove(self._as_area_lamp_material)\n as_assembly.objects().remove(self.__as_area_lamp)\n if self._as_area_lamp_shadergroup is not None:\n as_assembly.shader_groups().remove(self._as_area_lamp_shadergroup)\n else:\n self.__node_tree.delete(as_assembly)\n for mesh_inst in self.__instances.values():\n as_assembly.object_instances().remove(mesh_inst)\n\n def add_instance(self, inst_key, bl_matrix):\n logger.debug(\"Adding instance to %s\", self.bl_lamp.name_full)\n self.__matrices[inst_key] = bl_matrix\n\n def _get_point_lamp_params(self):\n as_lamp_data = self.bl_lamp.data.appleseed\n light_params = {'intensity': f\"{self.appleseed_name}_radiance\",\n 'intensity_multiplier': as_lamp_data.radiance_multiplier,\n 'exposure': as_lamp_data.exposure,\n 'cast_indirect_light': as_lamp_data.cast_indirect,\n 'importance_multiplier': as_lamp_data.importance_multiplier}\n\n return light_params\n\n def _get_spot_lamp_params(self, textures_to_add, as__texture_translators):\n as_lamp_data = self.bl_lamp.data.appleseed\n outer_angle = math.degrees(self.bl_lamp.data.spot_size)\n inner_angle = (1.0 - self.bl_lamp.data.spot_blend) * outer_angle\n\n intensity = f\"{self.appleseed_name}_radiance\"\n intensity_multiplier = as_lamp_data.radiance_multiplier\n\n if as_lamp_data.radiance_use_tex and as_lamp_data.radiance_tex is not None:\n tex_id = as_lamp_data.radiance_tex.name_full\n if tex_id not in as__texture_translators:\n textures_to_add[tex_id] = TextureTranslator(as_lamp_data.radiance_tex,\n self.asset_handler)\n intensity = f\"{as_lamp_data.radiance_tex.name_full}_inst\"\n\n if as_lamp_data.radiance_multiplier_use_tex and as_lamp_data.radiance_multiplier_tex is not None:\n tex_id = as_lamp_data.radiance_multiplier_tex.name_full\n if tex_id not in as__texture_translators:\n textures_to_add[tex_id] = TextureTranslator(as_lamp_data.radiance_multiplier_tex,\n self.asset_handler)\n intensity_multiplier = f\"{as_lamp_data.radiance_multiplier_tex.name_full}_inst\"\n\n light_params = {'intensity': intensity,\n 'intensity_multiplier': intensity_multiplier,\n 'exposure': as_lamp_data.exposure,\n 'cast_indirect_light': as_lamp_data.cast_indirect,\n 'importance_multiplier': as_lamp_data.importance_multiplier,\n 'exposure_multiplier': as_lamp_data.exposure_multiplier,\n 'tilt_angle': as_lamp_data.tilt_angle,\n 'inner_angle': inner_angle,\n 'outer_angle': outer_angle}\n\n return light_params\n\n def _get_directional_lamp_params(self):\n as_lamp_data = self.bl_lamp.data.appleseed\n light_params = {'irradiance': f\"{self.appleseed_name}_radiance\",\n 'irradiance_multiplier': as_lamp_data.radiance_multiplier,\n 'exposure': as_lamp_data.exposure,\n 'cast_indirect_light': as_lamp_data.cast_indirect,\n 'importance_multiplier': as_lamp_data.importance_multiplier}\n\n return light_params\n\n def _get_sun_lamp_params(self):\n as_lamp_data = self.bl_lamp.data.appleseed\n light_params = {'radiance_multiplier': as_lamp_data.radiance_multiplier,\n 'cast_indirect_light': as_lamp_data.cast_indirect,\n 'importance_multiplier': as_lamp_data.importance_multiplier,\n 'size_multiplier': as_lamp_data.size_multiplier,\n 'distance': as_lamp_data.distance,\n 'turbidity': as_lamp_data.turbidity}\n\n if as_lamp_data.use_edf:\n light_params['environment_edf'] = 'sky_edf'\n\n return light_params\n\n def _get_lamp_model(self):\n as_lamp_data = self.bl_lamp.data.appleseed\n lamp_type = self.bl_lamp.data.type\n\n if lamp_type == 'POINT':\n return 'point_light'\n if lamp_type == 'SPOT':\n return 'spot_light'\n if lamp_type == 'SUN' and as_lamp_data.sun_mode == 'distant':\n return 'directional_light'\n if lamp_type == 'SUN' and as_lamp_data.sun_mode == 'sun':\n return 'sun_light'\n\n return 'area_lamp'\n\n def _get_area_mesh_params(self):\n lamp_data = self.bl_lamp.data\n\n primitive = lamp_data.shape\n\n shape_params = dict()\n\n if primitive == 'RECTANGLE':\n shape_params['primitive'] = \"grid\"\n shape_params['resolution_u'] = 1\n shape_params['resolution_v'] = 1\n shape_params['width'] = lamp_data.size\n shape_params['height'] = lamp_data.size_y\n\n elif primitive == 'DISK':\n shape_params['primitive'] = \"disk\"\n shape_params['radius'] = self.bl_lamp.data.size / 2\n\n elif primitive == 'SQUARE':\n shape_params['primitive'] = \"grid\"\n shape_params['resolution_u'] = 1\n shape_params['resolution_v'] = 1\n shape_params['width'] = lamp_data.size\n shape_params['height'] = lamp_data.size\n\n return shape_params\n\n def _get_area_mesh_instance_params(self):\n lamp_data = self.bl_lamp.data\n as_lamp_data = lamp_data.appleseed\n\n lamp_inst_params = {'visibility': {'shadow': False}}\n\n if not as_lamp_data.area_visibility:\n lamp_inst_params['visibility']['camera'] = False\n\n return lamp_inst_params\n\n def _set_shadergroup(self):\n as_lamp_data = self.bl_lamp.data.appleseed\n\n shader_name = f\"{self.appleseed_name}_tree\"\n\n shader_group = asr.ShaderGroup(shader_name)\n\n shader_dir_path = self._find_shader_dir()\n shader_path = self.asset_handler.process_path(os.path.join(shader_dir_path, \"as_blender_areaLight.oso\"), AssetType.SHADER_ASSET)\n surface_path = self.asset_handler.process_path(os.path.join(shader_dir_path, \"as_closure2surface.oso\"), AssetType.SHADER_ASSET)\n\n lamp_color = \" \".join(map(str, as_lamp_data.area_color))\n\n lamp_params = {'in_color': f\"color {lamp_color}\",\n 'in_intensity': f\"float {as_lamp_data.area_intensity}\",\n 'in_intensity_scale': f\"float {as_lamp_data.area_intensity_scale}\",\n 'in_exposure': f\"float {as_lamp_data.area_exposure}\",\n 'in_normalize': f\"int {as_lamp_data.area_normalize}\"}\n\n shader_group.add_shader(\"shader\", shader_path, \"asAreaLight\", lamp_params)\n shader_group.add_shader(\"surface\", surface_path, \"asClosure2Surface\", {})\n shader_group.add_connection(\"asAreaLight\", \"out_output\", \"asClosure2Surface\", \"in_input\")\n\n self._as_area_lamp_shadergroup = shader_group\n\n def _convert_area_matrix(self, m):\n rot = mathutils.Matrix.Rotation(math.radians(-90), 4, 'X')\n m = m @ rot\n\n return self._convert_matrix(m)\n\n @staticmethod\n def _find_shader_dir():\n for directory in get_osl_search_paths():\n if os.path.basename(directory) in ('shaders', 'blenderseed'):\n\n return directory\n","sub_path":"translators/lamps/lamp.py","file_name":"lamp.py","file_ext":"py","file_size_in_byte":17421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"484716577","text":"from selenium import webdriver\n\n\n# 设置代理的目录就是为了不让浏览器知道自己的ip\n\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--proxy-server-http://125.110.74.111:9000\") # 设置代理\n\ndriver = webdriver.Chrome(chrome_options=options) # 给浏览器携带一个代理\ndriver.get(\"http://www.httpbin.org/\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"第四章爬虫进阶/selenium/01_设置代理ip.py","file_name":"01_设置代理ip.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"286429153","text":"import requests\nimport os, os.path\nfrom requests.auth import HTTPBasicAuth\n\n\ndef post(url, payload):\n try:\n r = requests.post(url, data=payload)\n code = r.status_code\n except requests.exceptions.ConnectionError as e:\n code = e.args[0].reason.errno\n return code\n\n\ndef post_multipart(url, payload, file_name):\n response = None\n try:\n files = {'upload': open(file_name, 'rb')}\n try:\n r = requests.post(url, files=files, data=payload, verify=False)\n code = r.status_code\n response = r.text\n except requests.exceptions.ConnectionError as e:\n code = e.args[0].reason.errno\n response = 'connection error'\n except IOError:\n code = -1\n response = 'I/O error'\n\n return code, response","sub_path":"modules/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"490763143","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport re\nfrom pathlib import Path\nfrom math import log\n\nfrom config import Config\n\nCONFIG = Config.get_instance()\n\nwith (CONFIG[\"datadir\"].parent / \"stopwords.txt\").open(\"r\", encoding=\"utf-8\") as f:\n STOPWORDS = set([line.strip().lower() for line in f])\n\nwith (CONFIG[\"datadir\"].parent / \"code_stopwords.txt\").open(\"r\", encoding=\"utf-8\") as f:\n STOPWORDS.update([line.strip().lower() for line in f])\n\n\ndef entropy(prob_seq):\n # entopy = tf.reduce_mean(tf.reduce_sum(-scores * tf.log(scores+1e-10), axis=2), axis=1)\n return sum([sum([-p * log(p, 2) for p in distri]) for distri in prob_seq]) / len(prob_seq)\n\n\ndef check_tagseq(tag_seq):\n beg = False\n end = True\n for tag in tag_seq:\n if tag[0] == \"B\":\n if beg:\n return False\n beg = True\n end = False\n elif tag[0] == \"I\":\n if not beg:\n return False\n elif tag[0] == \"E\":\n if not beg:\n return False\n beg = False\n end = True\n elif tag[0] == \"S\":\n if beg:\n return False\n elif tag[0] == \"O\":\n if beg:\n return False\n if not end:\n return False\n return True\n\n\ndef filter_concepts(concepts):\n '''\n token in concept must meet:\n 1. Has no stopword\n 2. Strats with [a-zA-Z], ends with [a-zA-Z0-9+], contains only [a-zA-Z0-9]\n eg. DL4J\n or contains one [-/], and the two words contain only letters and digits.\n eg. U-Net and Kullback-Leibler\n '''\n valid_set = set()\n invalid_set = set()\n\n valid_pattern = re.compile(r'^[a-zA-Z][a-zA-Z0-9]*\\+{0,2}$|^[a-zA-Z][a-zA-Z0-9]*[-/][a-zA-Z0-9]+$')\n camel_pattern = re.compile(r'^[A-Z]?[a-z]+([A-Z][a-z0-9]+)+$')\n # valid_begin = re.compile(r'^[a-zA-Z]')\n # valid_end = re.compile(r'[a-zA-Z+]$')\n for concept in concepts:\n # c = concept.strip(\" ::—-'\\\",.?*/\\\\|‘’()“”…,?()\")\n if len(concept) <= 1:\n continue\n valid = True\n for w in concept.split():\n if not valid_pattern.match(w):\n valid = False\n break\n for _w in re.split(r'[-/]', w):\n if _w.lower() in STOPWORDS:\n valid = False\n break\n if len(_w) > 5 and len(set(_w) & set('ABCDEFGHIJKLMNOPQRSTUVWXYZ')) == len(set(_w)):\n # print(_w)\n valid = False\n break\n if camel_pattern.match(_w):\n valid = False\n break\n if not valid:\n break\n if valid:\n valid_set.add(concept)\n else:\n invalid_set.add(concept)\n return valid_set, invalid_set\n\n\ndef get_concepts(token_seq, tag_seq):\n concepts = []\n temp = []\n for token, tag in zip(token_seq, tag_seq):\n if tag[0] == \"S\":\n concepts.append(token)\n elif tag[0] == \"B\":\n if len(temp) != 0:\n concepts.append(\" \".join(temp))\n temp = []\n temp.append(token)\n elif tag[0] == \"I\":\n temp.append(token)\n elif tag[0] == \"O\":\n if len(temp) != 0:\n concepts.append(\" \".join(temp))\n temp = []\n elif tag[0] == \"E\":\n temp.append(token)\n concepts.append(\" \".join(temp))\n temp = []\n return concepts\n","sub_path":"concept_recognizer/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"89662890","text":"import random\nimport sys\n\nfrom numpy.linalg import norm\nfrom numpy.lib.function_base import average\nfrom numpy import amax\n\nfrom feature_extractor import FeatureExtractor\n\n\nclass TextureFeatureExtractor(FeatureExtractor):\n ''' usecase:\n tfe = TextureFeatureExtractor()\n tfe.generate_tiles() # slow method\n features = tfe.extract(img) # very slow method\n 7 second for extracting one feature\n '''\n def __init__(self, image_loader, tile_size=50, tiles_count=1,\n images_for_tailing_count=500, delta=80.0, debug=False):\n self.il = image_loader\n self.tile_size = tile_size\n self.tiles_count = tiles_count\n self.images_for_tailing_count = images_for_tailing_count\n self.delta = delta\n self.debug = debug\n\n def extract(self, img):\n features = []\n for tile in self.tiles:\n features.append(self._img_tile_distance(img, tile))\n return features\n\n def _img_tile_distance(self, img, tile):\n '''\n distance between img and tile is defined as min of\n distances between tile and all sub-images of img\n :param img:\n :param tile:\n :return: distance in (0 ... sqrt(255**2 + 255**2 + 255**2))\n math.sqrt(255**2 + 255**2 + 255**2) = 441.67\n '''\n (img_height, img_width) = img.shape[0:2]\n (tile_height, tile_width) = tile.shape[0:2]\n result = sys.float_info.max\n for i in xrange(0, img_width - tile_width):\n for j in xrange(0, img_height - tile_height):\n sub_img = img[i:(i + tile_width), j:(j + tile_height)]\n dst = self._sub_img_tile_distance(tile, sub_img)\n result = min(dst, result)\n return result\n\n def _sub_img_tile_distance(self, tile, sub_img):\n '''\n distance between a sub-image and a texture tile are defined\n as the maximum of Euclidian distance between their pixels in RGB\n :param tile:\n :param sub_img:\n :return: distance\n '''\n return amax(norm(tile.astype(float) - sub_img.astype(float), axis=2).flat)\n\n def _tile_tile_distance(self, tile1, tile2):\n '''\n we define distance between two tiles as the average\n Euclidian distance between the pixels of the tiles in RGB(0..255, 0..255, 0..255)\n :param tile1:\n :param tile2:\n :return: distance in (0 ... sqrt(255**2 + 255**2 + 255**2))\n math.sqrt(255**2 + 255**2 + 255**2) = 441.67\n '''\n return average(norm(tile1.astype(float) - tile2.astype(float), axis=2))\n\n def _check_same_tile_exist(self, new_tile):\n for tile in self.tiles:\n dst = self._tile_tile_distance(tile, new_tile)\n self._debug_print('dst: {}'.format(dst))\n if dst < self.delta:\n return True\n return False\n\n def generate_tiles(self):\n '''\n generate tiles, and initialize self.tiles\n if images_for_tailing is too low raise exception\n :return:\n '''\n self.tiles = []\n available_images_names = self.il.available_images()\n images_for_tailing_names = random.sample(available_images_names, self.images_for_tailing_count)\n for img_name in images_for_tailing_names:\n img = self.il.load(img_name)\n new_tiles = self._divide_img_by_tiles(img)\n for new_tile in new_tiles:\n if not self._check_same_tile_exist(new_tile):\n self.tiles.append(new_tile)\n self._debug_print('tiles count: {}'.format(len(self.tiles)))\n if len(self.tiles) == self.tiles_count:\n return\n raise Exception('Tiles not generated')\n\n def _divide_img_by_tiles(self, img):\n tiles = []\n (height, width) = img.shape[0:2]\n for x in xrange(0, width, self.tile_size):\n for y in xrange(0, height, self.tile_size):\n tiles.append(img[x:(x + self.tile_size), y:(y + self.tile_size)])\n return tiles\n\n def _debug_print(self, str):\n if self.debug:\n print('TFE debug: {}'.format(str))","sub_path":"src/texture_feature_extractor.py","file_name":"texture_feature_extractor.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"173268995","text":"import os.path\nfrom absl import logging\nimport tornado.locale\nfrom tornado import queues\nimport tornado.web\nfrom icubam import base_server\nfrom icubam.db import queue_writer\nfrom icubam.www import updater\nfrom icubam.www.handlers import db\nfrom icubam.www.handlers import home\nfrom icubam.www.handlers import static\nfrom icubam.www.handlers import update\nfrom icubam.www.handlers import upload_csv\nfrom icubam.www.handlers.version import VersionHandler\n\n\nclass WWWServer(base_server.BaseServer):\n \"\"\"Serves and manipulates the ICUBAM data.\"\"\"\n\n def __init__(self, config, port=None):\n super().__init__(config, port)\n self.port = port if port is not None else self.config.server.port\n self.writing_queue = queues.Queue()\n self.callbacks = [\n queue_writer.QueueWriter(self.writing_queue, self.db_factory).process\n ]\n self.path = home.HomeHandler.PATH\n\n def make_routes(self):\n self.add_handler(\n update.UpdateHandler,\n config=self.config,\n db_factory=self.db_factory,\n queue=self.writing_queue,\n )\n kwargs = dict(config=self.config, db_factory=self.db_factory)\n self.add_handler(home.HomeHandler, **kwargs)\n self.add_handler(home.MapByAPIHandler, **kwargs)\n self.add_handler(db.DBHandler, **kwargs)\n self.add_handler(VersionHandler, **kwargs)\n self.add_handler(\n upload_csv.UploadHandler, \n **{**kwargs, **{'upload_path': self.config.server.upload_dir}})\n self.add_handler(static.NoCacheStaticFileHandler, root=self.path)\n\n def make_app(self, cookie_secret=None):\n if cookie_secret is None:\n cookie_secret = self.config.SECRET_COOKIE\n self.make_routes()\n settings = {\n \"cookie_secret\": cookie_secret,\n \"login_url\": \"/error\",\n }\n tornado.locale.load_translations(os.path.join(self.path, \"translations\"))\n return tornado.web.Application(self.routes, **settings)\n","sub_path":"icubam/www/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"141086194","text":"#!/usr/bin/env python3\n\nfrom datetime import date\nimport time\nimport lxml.html\nimport http.client\nfrom scraper_classes import Source, Writer\nfrom scrapers import ScraperChuvash\nimport re\nimport signal\nimport sys\n\nnumScrape = 50 #-1 will scrape all articles, 10 will scrape 10 newest articles\n\nurlTemplate = \"/news/%s.html\"\n\ndef getPage(conn, url, rawContent = False):\n\tconn.request(\"GET\", url)\n\tres = conn.getresponse()\n\tif res.status != 200:\n\t\tprint(url, res.status, res.reason)\n\t\treturn\n\tcontents = res.read().decode('utf-8')\n\tif rawContent:\n\t\treturn contents\n\tdoc = lxml.html.fromstring(contents)\n\treturn doc\n\ndef main(numScrape):\n\tconn = http.client.HTTPConnection(\"www.chuvash.org\")\n\tmainPage = getPage(conn, '')\n\tlatestArticleNum = int(mainPage.xpath(\"//h2[@class='hipar_head']\")[0][0].attrib['href'].split('news/')[1].replace('.html',''))\n\tprint('Scraping %s articles...' % ('all' if numScrape is -1 else numScrape))\n\tnumScraped = 0\n\tattemptScrape = 0\n\ti = latestArticleNum\n\tids = None\n\troot = None\n\tw = Writer()\n\t\n\tdef term_handler(sigNum, frame):\n\t\tprint(\"\\nReceived a SIGTERM signal. Closing the program.\")\n\t\tw.close()\n\t\tsys.exit(0)\n\n\tsignal.signal(signal.SIGTERM, term_handler)\n\t\n\ttry:\n\t\twhile i >= 1 and (numScraped < numScrape or numScrape is -1):\n\t\t\ttry:\n\t\t\t\turl = \"http://www.chuvash.org\" + (urlTemplate % i)\n\t\t\t\tsource = Source(url, scraper=ScraperChuvash, conn=conn)\n\t\t\t\tsource.makeRoot(\"./\", ids=ids, root=root, lang=\"cv\")\n\t\t\t\tsource.add_to_archive()\n\t\t\t\tif ids is None:\n\t\t\t\t\tids = source.ids\n\t\t\t\tif root is None:\n\t\t\t\t\troot = source.root\n\t\t\t\tattemptScrape += 1\n\t\t\t\tnumScraped += 1\n\t\t\t\tif source.out_content is not None and len(source.out_content) is 0:\n\t\t\t\t\tnumScraped -= 1\n\t\t\texcept Exception as e:\n\t\t\t\tprint(url + \" \" + str(e))\n\t\t\ti -= 1\n\texcept KeyboardInterrupt:\n\t\tprint(\"\\nReceived a keyboard interrupt. Closing the program.\")\n\tprint(\"Attempted to scrape %s articles.\" % attemptScrape)\t\n\tprint(\"%s articles scraped.\" % numScraped)\n\tw.close()\n\tconn.close()\n\t\nmain(numScrape)\n\n\n\n","sub_path":"apertium-tools/scraper/scrp-chuvash.py","file_name":"scrp-chuvash.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"212642658","text":"def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n**(1/2))+1):\n if n % i == 0:\n return False\n return True\n\n\nn = int(input())\nA = list(map(int, input().split()))\ncnt = 0\n\nfor x in A:\n if is_prime(x):\n cnt += 1\nprint(cnt)\n","sub_path":"BaekJoon_Py/1978.py","file_name":"1978.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"580330782","text":"\n\n\"\"\"\n创建角色页面\n\"\"\"\nfrom selenium.webdriver.common.by import By\n\nfrom base_page.base_page import BasePage\nfrom base_page.common_search import CommonButtons\n\n\nclass RolePage(BasePage,CommonButtons):\n data_path = '../test_datas/role_infor.yaml'\n #basci_mag = (By.XPATH, '//div[@id=\"app\"]/div/div[2]/div[1]/div[1]/ul/div/div[10]/li/div/span')\n role_mag = (By.XPATH, '//div[@id=\"app\"]/div/div[2]/div[1]/div[1]/ul/div/div[7]/li/ul/div[3]/li/span')\n create_role_button = (By.XPATH, '//div[@id=\"app\"]/div/div[2]/div[2]/section/div[1]/div/div[1]/div/div[1]/div/div/div[2]/span/button')\n role_name = (By.XPATH, '//div[@aria-label=\"创建\"]/div[2]/form/div[1]/div/div[1]/input')\n role_style = (By.XPATH, '//div[@aria-label=\"创建\"]/div[2]/form/div[2]/div/div/div[1]/input')\n role_value = (By.XPATH , '/html/body/div[last()]/div/div/ul/li[1]')\n role_description = (By.XPATH, '//div[@aria-label=\"创建\"]/div[2]/form/div[3]/div/div/textarea')\n saveC_button = (By.XPATH,'//div[@aria-label=\"创建\"]/div[last()]/div/span[2]/button')\n def create_role(self,role_name,role_description):\n self.wait(1)\n self.click(self.basic_management)\n self.wait(1)\n self.click(self.role_mag)\n self.wait(3)\n self.click(self.create_role_button)\n self.input(self.role_name,role_name)\n self.click(self.role_style)\n self.wait(0.5)\n self.click(self.role_value)\n self.input(self.role_description,role_description)\n self.click(self.saveC_button)\n def edit_role(self,role_name):\n self.wait(1)\n self.input(self.search_input,role_name)\n self.click(self.saveC_button)\n\n","sub_path":"pages/role_page.py","file_name":"role_page.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"296872398","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# level 6的官方参考答案,很简洁,默写一遍\n\nimport zipfile, re\n\nfindnothing = re.compile(r'Next nothing is (\\d+)').match\ncomments = []\nz = zipfile.ZipFile('channel.zip', 'r')\nseed = '90052'\nwhile True:\n\tfname = seed + '.txt'\n\tcomments.append(z.getinfo(fname).comment.decode('utf-8'))\n\tguts = z.read(fname).decode('utf-8')\n\tm = findnothing(guts)\n\tif m:\n\t\tseed = m.group(1)\n\telse:\n\t\tbreak\nprint(''.join(comments))","sub_path":"level-06-offical.py","file_name":"level-06-offical.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"10440834","text":"#!/usr/bin/env python\n\"\"\"Take NICFPS exposures in a square pattern plus a point in the middle.\n\nThis script imports the standard NICFPS exposure widget\nto allow the user to configure standard exposure options.\nIt also adds a few additional widgets that allow\nthe user to select which portions of the chip to visit.\n\nTo do:\n- Fail unless NICFPS is in imaging mode.\n\nHistory:\n2004-10-19 ROwen first cut; direct copy of GRIM:Square\n2005-01-24 ROwen Changed order to ctr, UL, UR, LR, LL.\n Changed Offset Size to Box Size (2x as big)\n and made 20\" the default box size.\n Modified to record dither points in advance\n (instead of allowing change 'on the fly').\n Renamed from Dither.py to Dither/Point Source.py\n2006-04-20 ROwen Changed to a class.\n Changed all offsets to /computed.\n2006-04-27 ROwen Bug fix: would try to run (but send bogus commands)\n if required exposure fields were blank.\n Added debug support.\n2006-12-28 ROwen Fix PR 515: modified to abort the exposure if the script is aborted.\n2008-04-17 ROwen Display order and state of execution of each node.\n2008-04-18 ROwen Added randomization option.\n2008-04-21 ROwen Simplified the code by using numExp, totNum args to expWdg.getString.\n Bug fix: needMove was comparing to begOffset, not currOffset.\n2008-09-23 ROwen Fix PR 859: never finished by restoring the initial offset because end and run\n both called needMove with self.currOffset instead of self.begOffset.\n2015-11-02 ROwen Remove unused import\n\"\"\"\nimport numpy\nimport Tkinter\nimport RO.Wdg\nimport TUI.TCC.TCCModel\nimport TUI.Inst.ExposeModel\nfrom TUI.Inst.ExposeStatusWdg import ExposeStatusWdg\nfrom TUI.Inst.ExposeInputWdg import ExposeInputWdg\n\n# constants\nInstName = \"NICFPS\"\nDefBoxSize = 20 # arcsec\nDefDoRandom = False\nRandomBoxSize = 10 # arcsec\nHelpURL = \"Scripts/BuiltInScripts/NICFPSDitherPointSource.html\"\n\nclass ScriptClass(object): \n def __init__(self, sr):\n \"\"\"The setup script; run once when the script runner\n window is created.\n \"\"\"\n # if sr.debug True, run in debug-only mode (which doesn't DO anything, it just pretends)\n sr.debug = False\n self.sr = sr\n\n self.begOffset = numpy.array((numpy.nan, numpy.nan))\n self.currOffset = self.begOffset[:]\n\n self.tccModel = TUI.TCC.TCCModel.getModel()\n self.expModel = TUI.Inst.ExposeModel.getModel(InstName)\n \n row=0\n \n # standard exposure status widget\n expStatusWdg = ExposeStatusWdg(\n master = sr.master,\n instName = InstName,\n helpURL = HelpURL,\n )\n expStatusWdg.grid(row=row, column=0, sticky=\"news\")\n row += 1\n \n # create dither node controls\n ditherFrame = Tkinter.Frame(sr.master)\n \n # information about the dither nodes; each entry is:\n # - name of quadrant\n # - boresight offset multiplier in image x, image y\n ditherNodeData = [\n (\"Ctr\", (0, 0)),\n (\"UL\", (-1, 1)),\n (\"UR\", (1, 1)),\n (\"LR\", (1, -1)),\n (\"LL\", (-1, -1)),\n ]\n self.ditherWdgSet = [] # (stateWdg, orderWdg, boolWdg), one per dither node\n for name, offMult in ditherNodeData:\n nodeFrame = Tkinter.Frame(ditherFrame)\n\n stateWdg = RO.Wdg.StrLabel(\n master = nodeFrame,\n width = 7,\n relief = \"flat\",\n helpText = \"State of node in dither sequence\",\n helpURL = HelpURL,\n )\n orderWdg = RO.Wdg.IntLabel(\n master = nodeFrame,\n width = 1,\n relief = \"flat\",\n helpText = \"Order of node in dither sequence\",\n helpURL = HelpURL,\n )\n boolWdg = RO.Wdg.Checkbutton(\n master = nodeFrame,\n text = name,\n callFunc = self.updOrder,\n defValue = True,\n relief = \"flat\",\n helpText = \"Check to use this dither node\",\n helpURL = HelpURL,\n )\n # add attribute \"offMult\" to widget\n # so it can be read by \"run\"\n boolWdg.offMult = numpy.array(offMult, dtype=float)\n \n self.ditherWdgSet.append((stateWdg, orderWdg, boolWdg))\n\n stateWdg.pack(side=\"left\")\n orderWdg.pack(side=\"left\")\n boolWdg.pack(side=\"left\")\n \n # display quadrant checkbutton in appropriate location\n row = 1 - offMult[1]\n col = 1 + offMult[0]\n nodeFrame.grid(row=row, column=col)\n \n \n ditherFrame.grid(row=row, column=0, sticky=\"news\")\n row += 1\n \n # standard exposure input widget\n self.expWdg = ExposeInputWdg(\n master = sr.master,\n instName = InstName,\n expTypes = \"object\",\n helpURL = HelpURL,\n )\n self.expWdg.numExpWdg.helpText = \"# of exposures at each point\"\n self.expWdg.grid(row=row, column=0, sticky=\"news\")\n row += 1\n \n # add controls to exposure input widget frame\n self.boxSizeWdg = RO.Wdg.IntEntry(\n master = self.expWdg,\n minValue = 0,\n defValue = DefBoxSize,\n helpText = \"size of dither box\",\n helpURL = HelpURL,\n )\n self.expWdg.gridder.gridWdg(\"Box Size\", self.boxSizeWdg, \"arcsec\")\n \n self.doRandomWdg = RO.Wdg.Checkbutton(\n master = self.expWdg,\n defValue = DefDoRandom,\n helpText = \"Add random scatter to dither pattern?\",\n helpURL = HelpURL,\n )\n self.expWdg.gridder.gridWdg(\"Randomize?\", self.doRandomWdg)\n \n if sr.debug:\n # set useful debug defaults\n self.expWdg.timeWdg.set(\"1.0\")\n self.expWdg.numExpWdg.set(2)\n self.expWdg.fileNameWdg.set(\"debug\")\n self.ditherWdgSet[1][-1].setBool(False)\n self.ditherWdgSet[3][-1].setBool(False)\n\n self.updOrder()\n \n def end(self, sr):\n \"\"\"If telescope offset, restore original position.\n \"\"\"\n self.updOrder(doForce=True)\n \n # restore original boresight position, if changed\n if self.needMove(self.begOffset):\n tccCmdStr = \"offset boresight %.7f, %.7f/pabs/vabs/computed\" % tuple(self.begOffset)\n #print \"sending tcc command %r\" % tccCmdStr\n sr.startCmd(\n actor = \"tcc\",\n cmdStr = tccCmdStr,\n )\n\n def needMove(self, desOffset):\n \"\"\"Return True if telescope not at desired offset\"\"\"\n if numpy.any(numpy.isnan(self.currOffset)):\n return False\n return not numpy.allclose(self.currOffset, desOffset) \n \n def run(self, sr):\n \"\"\"Take an exposure sequence.\n \"\"\"\n # clear node state\n for wdgSet in self.ditherWdgSet:\n wdgSet[0].set(None)\n\n # get current NICFPS focal plane geometry from the TCC\n # but first make sure the current instrument is actually NICFPS\n if not sr.debug:\n currInstName = sr.getKeyVar(self.tccModel.instName)\n if not currInstName.lower().startswith(InstName.lower()):\n raise sr.ScriptError(\"%s is not the current instrument!\" % InstName)\n \n # record the current boresight position\n begBorePVTs = sr.getKeyVar(self.tccModel.boresight, ind=None)\n if not sr.debug:\n begOffset = [pvt.getPos() for pvt in begBorePVTs]\n if None in begOffset:\n raise sr.ScriptError(\"Current boresight position unknown\")\n self.begOffset = numpy.array(begOffset, dtype=float)\n else:\n self.begOffset = numpy.zeros(2, dtype=float)\n self.currOffset = self.begOffset[:]\n #print \"self.begOffset=%r\" % self.begOffset\n \n ditherSize = self.boxSizeWdg.getNum() / 2.0\n doRandom = self.doRandomWdg.getBool()\n \n # record which points to use in the dither pattern in advance\n # (rather than allowing the user to change it during execution)\n doPtArr = [wdgs[-1].getBool() for wdgs in self.ditherWdgSet]\n\n # exposure command without startNum and totNumExp\n # get it now so that it will not change if the user messes\n # with the controls while the script is running\n numExp = self.expWdg.numExpWdg.getNumOrNone()\n if numExp is None:\n raise sr.ScriptError(\"must specify #Exp\")\n\n numNodes = sum(doPtArr)\n totNumExp = numNodes * numExp\n if doRandom:\n # use randomization: take just one exposure and then apply a random offset\n expCmdPrefix = self.expWdg.getString(numExp = 1, totNum = totNumExp)\n else:\n # no randomization: take all #Exp exposures at once\n expCmdPrefix = self.expWdg.getString(totNum = totNumExp)\n if not expCmdPrefix:\n raise sr.ScriptError(\"missing inputs\")\n\n # loop through each dither node,\n # taking numExp exposures at each node\n ditherSizeDeg = ditherSize / 3600.0\n #randomRangeDeg = ditherSizeDeg / 2.0\n randomRangeDeg = RandomBoxSize / 3600.0\n numExpTaken = 0\n for ind, wdgSet in enumerate(self.ditherWdgSet):\n stateWdg, orderWdg, boolWdg = wdgSet\n if not doPtArr[ind]:\n stateWdg.set(\"Skipped\")\n continue\n\n stateWdg.set(\"Running\")\n nodeName = str(boolWdg[\"text\"])\n \n desOffset = self.begOffset + (boolWdg.offMult * ditherSizeDeg)\n if doRandom:\n # apply random offset before each exposure at this position\n for expInd in range(numExp):\n if numExpTaken == 0:\n # do not randomize the first point; this saves a bit of time\n randomScatter = numpy.zeros(2, dtype=float)\n fullNodeName = \"%s with no random scatter\" % (nodeName,)\n else:\n randomScatter = (numpy.random.random(2) * randomRangeDeg) - (randomRangeDeg / 2.0)\n randomScatterArcSec = randomScatter * 3600.0\n fullNodeName = \"%s + %0.1f, %0.1f random scatter\" % \\\n (nodeName, randomScatterArcSec[0], randomScatterArcSec[1])\n #print \"Adding randomScatter\", randomScatter\n randomizedOffset = desOffset + randomScatter\n if self.needMove(randomizedOffset):\n # slew telescope\n randomScatterArcSec = randomScatter * 3600.0\n sr.showMsg(\"Offset to %s\" % (fullNodeName,))\n yield self.waitOffset(randomizedOffset)\n \n \n # format exposure command\n startNum = numExpTaken + 1\n expCmdStr = \"%s startNum=%d\" % (expCmdPrefix, startNum)\n \n # take exposure sequence\n sr.showMsg(\"Expose at %s\" % (fullNodeName,))\n yield sr.waitCmd(\n actor = self.expModel.actor,\n cmdStr = expCmdStr,\n abortCmdStr = \"abort\",\n )\n numExpTaken += 1\n else:\n # no randomization; take all numExp exposures at this point\n if self.needMove(desOffset):\n # slew telescope\n sr.showMsg(\"Offset to %s position\" % nodeName)\n yield self.waitOffset(desOffset)\n \n # format exposure command\n startNum = numExpTaken + 1\n expCmdStr = \"%s startNum=%d\" % (expCmdPrefix, startNum)\n \n # take exposure sequence\n sr.showMsg(\"Expose at %s position\" % nodeName)\n yield sr.waitCmd(\n actor = self.expModel.actor,\n cmdStr = expCmdStr,\n abortCmdStr = \"abort\",\n )\n \n numExpTaken += numExp\n\n stateWdg.set(\"Done\")\n \n # slew back to starting position\n if self.needMove(self.begOffset):\n sr.showMsg(\"Finishing up: slewing to initial position\")\n yield self.waitOffset(self.begOffset)\n \n def updOrder(self, wdg=None, doForce=False):\n \"\"\"Update the order widgets\n \n If the script is executing then the widgets are left untouched\n unless doForce is True. This allows the order widgets to be correct\n while running even if the user messes with the checkboxes.\n \"\"\"\n if not doForce and self.sr.isExecuting():\n return\n orderNum = 1\n for stateWdg, orderWdg, boolWdg in self.ditherWdgSet:\n if boolWdg.getBool():\n orderWdg.set(orderNum)\n orderNum += 1\n else:\n orderWdg.set(None)\n \n def waitOffset(self, desOffset):\n \"\"\"Offset the telescope\"\"\"\n tccCmdStr = \"offset boresight %.7f, %.7f/pabs/vabs/computed\" % tuple(desOffset)\n self.currOffset = desOffset[:]\n yield self.sr.waitCmd(\n actor = \"tcc\",\n cmdStr = tccCmdStr,\n )\n","sub_path":"TUI/Scripts/NICFPS/Dither/Point Source.py","file_name":"Point Source.py","file_ext":"py","file_size_in_byte":13732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"378974819","text":"from aiohttp import ClientSession\nfrom bs4 import BeautifulSoup\nimport asyncio\nimport time\n \n \n#定義協程(coroutine)\nasync def main():\n links = list()\n for page in range(1, 11):\n links.append(\n f\"https://www.104.com.tw/jobs/search/?keyword=python&order=1&page={page}&jobsource=2018indexpoc&ro=0\")\n \n async with ClientSession() as session:\n tasks = [asyncio.create_task(fetch(link, session)) for link in links] # 建立任務清單\n await asyncio.gather(*tasks) # 打包任務清單及執行\n \n#定義協程(coroutine)\nasync def fetch(link, session):\n async with session.get(link) as response: #非同步發送請求\n html_body = await response.text()\n \n soup = BeautifulSoup(html_body, \"lxml\") # 解析HTML原始碼\n \n blocks = soup.find_all(\"div\", {\"class\": \"b-block__left\"}) # 職缺區塊\n for block in blocks:\n \n job = block.find(\"a\", {\"class\": \"js-job-link\"}) # 職缺名稱\n if job is None:\n continue\n \n company = block.find_all(\"li\")[1] # 公司名稱\n salary = block.find(\"span\", {\"class\": \"b-tag--default\"}) # 待遇\n \n print((job.getText(),) + (company.getText().strip(),) + (salary.getText(),))\n \n \nstart_time = time.time() #開始執行時間\nloop = asyncio.get_event_loop() #建立事件迴圈(Event Loop)\nloop.run_until_complete(main()) #執行協程(coroutine)\nprint(\"花費:\" + str(time.time() - start_time) + \"秒\")","sub_path":"asynch2.py","file_name":"asynch2.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"389209176","text":"class Stack:\n\tdef __init__(self):\n\t\tself.stack = list()\n\n\tdef push(self,data):\n\t\tself.stack.append(data)\n\n\n\tdef pop(self):\n\t\treturn self.stack.pop()\n\n\n\tdef display(self):\n\t\tprint(\"HEAD -> \", end=\"\")\n\t\tself.stack.reverse()\n\t\tfor i in self.stack:\n\t\t\tprint(i, \" -> \" ,end=\"\")\n\n\t\tprint(\"TAIL\")\n\t\tself.stack.reverse()\n\n\tdef count(self):\n\t\treturn len(self.stack)\n\n\nclass Queue:\n\tdef __init__(self):\n\t\tself.queue = list()\n\n\tdef push(self,data):\n\t\tself.queue.insert(0,data)\n\n\n\tdef pop(self):\n\t\treturn self.queue.pop()\n\n\n\tdef display(self):\n\t\tprint(\"HEAD -> \", end=\"\")\n\t\tself.queue.reverse()\n\t\tfor i in self.queue:\n\t\t\tprint(i, \" -> \" ,end=\"\")\n\n\t\tprint(\"TAIL\")\n\t\tself.queue.reverse()\n\n\tdef count(self):\n\t\treturn len(self.queue)\n\n\n\n\nif __name__ == '__main__':\n\tstack = Stack()\n\n\tprint(\"--Stack--\")\n\tstack.push(1)\n\tstack.push(2)\n\tstack.push(3)\n\tstack.push(4)\n\n\tstack.display()\n\n\tstack.pop()\n\n\tstack.display()\n\tprint(\"No. of elements: \", stack.count())\n\n\n\tqueue = Queue()\n\n\tprint(\"--Queue--\")\n\tqueue.push(1)\n\tqueue.push(2)\n\tqueue.push(3)\n\tqueue.push(4)\n\n\tqueue.display()\n\tprint(\"No. of elements: \", queue.count())\n\n\tqueue.pop()\n\n\tqueue.display()\n\n\n","sub_path":"stack_queue.py","file_name":"stack_queue.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"541127424","text":"import numpy as np\nimport os\nimport sys\ndirname = os.path.dirname(__file__)\nfilename = os.path.join(dirname, \"../\")\nsys.path.append(filename)\nimport shapedist\nfrom shapedist import normalize\n\nfrom skimage import measure\nfrom skimage import io\nfrom tqdm import tqdm\nfrom scipy.interpolate import CubicSpline\nimport matplotlib.pyplot as plt\nimport time\n\n\ndef smooth_curve(b, iter):\n b = normalize(b)\n for k in range(iter):\n N = b.shape[0]\n b_f = rotate(b, 1)\n b_b = rotate(b, N-1)\n d = np.linalg.norm(b_f - b, axis=1)\n d_b = rotate(d, N-1)\n smoothed = 0.5 * b +0.5 * div((mult(d_b, b_f) + mult(d, b_b)), d_b + d)\n b = np.copy(smoothed)\n return smoothed\n\ndef div(b, d):\n N = d.shape[0]\n ret = np.zeros(b.shape)\n for i in range(N):\n ret[i] = b[i] / d[i]\n return ret\n\ndef mult(d, b):\n N = d.shape[0]\n ret = np.zeros(b.shape)\n for i in range(N):\n ret[i] = d[i] * b[i]\n return ret\ndef rotate(p, s):\n ret = np.copy(p)\n N = p.shape[0]\n temp = ret[N - s:]\n ret[s:N] = ret[0:N - s]\n ret[:s] = temp\n return ret\n\n\ndirname = os.path.dirname(__file__)\ndir = \"./img/BBC020_v1_outlines_cells\"\nuncoarsened = []\ncoarsened = []\nimages = os.listdir(dir)\nunsizes = []\ncoarsesizes = []\npercents = []\ntimes = []\nuniform_256 = []\nfor name in tqdm(images):\n img = io.imread(dir + \"/\" + name)\n mini = np.inf\n contours = measure.find_contours(img, level=0.8)\n max = 0\n index = 0\n for i in range(len(contours)):\n if contours[i].shape[0] > max:\n index = i\n max = contours[i].shape[0]\n if max < 100:\n continue\n\n sm = smooth_curve(contours[index], iter=10)\n t = shapedist.arclen_fct_values(sm)\n func1 = CubicSpline(t, sm[:, 0])\n func2 = CubicSpline(t, sm[:, 1])\n t_new = np.linspace(0., 1., 1024)\n sm_uniform = np.zeros((1024, 2))\n sm_uniform[:, 0] = func1(t_new)\n sm_uniform[:, 1] = func2(t_new)\n\n\n uncoarsened.append(sm_uniform)\n t_256 = np.linspace(0., 1., 256)\n sm_256 = np.zeros((256, 2))\n sm_256[:, 0] = func1(t_256)\n sm_256[:, 1] = func2(t_256)\n uniform_256.append(sm_256)\n\n temp, coarse = shapedist.build_hierarchy.coarsen_curve(t_new, sm_uniform, tol=1e-4, maxiter=15)\n unsizes.append(sm.shape[0])\n coarsesizes.append(coarse.shape[0])\n coarsened.append(coarse)\n percents.append(1 - coarse.shape[0] / sm_uniform.shape[0])\n\n for i in range(5):\n start = time.time()\n contours = measure.find_contours(img, level=0.5)\n sm = smooth_curve(contours[0], iter=10)\n\n t = np.arange(sm_uniform.shape[0])\n temp, coarse = shapedist.build_hierarchy.coarsen_curve(t, sm_uniform, tol=1e-4, maxiter=15)\n end = time.time()\n\n if end - start < mini:\n mini = end - start\n times.append(mini)\n\n#\nuniform_256 = np.array(uniform_256)\nuncoarsened = np.array(uncoarsened)\ncoarsened = np.asarray(coarsened)\nunsizes = np.array(unsizes)\ncoarsesizes = np.array(coarsesizes)\npercents = np.array(percents)\ntimes = np.array(times)\n\nnp.save(\"marrow_cell_curves_256\", uniform_256)\nnp.save(\"marrow_cell_curves_1024\", uncoarsened)\nnp.save(\"marrow_cell_curves_coarsened\", coarsened)\nnp.savetxt(\"marrow_cell_curves_full_sizes\", unsizes)\nnp.savetxt(\"marrow_cell_curves_coarsened_sizes\", coarsesizes)\nnp.savetxt(\"marrow_cell_curves_percent_red\", percents)\nnp.savetxt(\"marrow_cell_curves_process_times\", times)\n\nprint(\"Num Curves:\", uniform_256.shape[0])\nprint(\"Average full size:\", np.sum(unsizes) / unsizes.shape[0])\nprint(\"Average coarsened size (with tol 2e-3):\", np.sum(coarsesizes) / coarsesizes.shape[0])\nprint(\"Average percent reduction:\", np.sum(percents) / percents.shape[0])\nprint(\"Average Time\", np.sum(times) / times.shape[0])","sub_path":"extract_contour/find_contours.py","file_name":"find_contours.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"508279085","text":"import time\nimport json\nimport threading\nimport requests\nfrom unis.models import Node\nfrom ferry.log import log\n\nSYNC_INTERVAL=2\nSERVICE_THRESH=10\nSTYPES = [\"datalogistics:wdln:ferry\"]\n\nclass BaseFerrySync:\n def __init__(self, rt, myname):\n self.myname = myname\n self.pushed = []\n \n rt.services.addCallback(self._srv_cb)\n \n th = threading.Thread(\n name='base_sync',\n target=self._sync,\n daemon=True,\n args=(rt,)\n )\n th.start()\n\n def _srv_cb(self, s, ev):\n log.debug(\"Service update: {}\".format(s.name))\n \n def _sync(self, rt):\n while True:\n nds = []\n n5 = int((time.time() - SYNC_INTERVAL)*1e6)\n n10 = int((time.time() - SERVICE_THRESH)*1e6)\n\n for n in rt.nodes:\n if n.ts > n5:\n nds.append(n)\n\n if len(nds):\n log.debug(\"Time to sync: {}\".format(([n.name for n in nds])))\n for s in rt.services:\n if s.ts > n10 and s.serviceType in STYPES:\n # push all known nodes if we haven't\n # seen this service before\n if s.name not in self.pushed:\n nds = rt.nodes\n\n # build a list of nodes for a single post\n nlist = []\n for n in nds:\n repr = n.to_JSON()\n del repr['selfRef']\n nlist.append(repr)\n \n # finally post the node list to the endpoint\n url = \"http://{}:9000/nodes\".format(s.name)\n log.debug(\"Syncing to {}\".format(url))\n try:\n self._do_post(url, json.dumps(nlist))\n self.pushed.append(s.name)\n except:\n pass\n \n time.sleep(SYNC_INTERVAL)\n \n def _do_post(self, url, data):\n try:\n headers = {\"Content-Type\": \"application/perfsonar+json\"}\n requests.post(url, headers=headers, data=data)\n except Exception as e:\n log.error(\"Could not update node at {}: {}\".format(url, e))\n raise e\n","sub_path":"ferry/ferry/base_sync.py","file_name":"base_sync.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"511914989","text":"from __future__ import print_function\nimport requests\ndef get_psiquic_uniprot(query, **kwargs):\n\tkwargs['format'] = kwargs.get('format', 'tab27')\n\tserver = 'http://www.ebi.ac.uk/Tools/webservices/psicquic/uniprot/webservices/current/search/query'\n\treq = requests.get('%s/%s' % (server, query),\n\tparams=kwargs)\n\treturn req.content\nfrom collections import defaultdict\ngenes_species = defaultdict(set)\ninteractions = {}\ndef get_gene_name(my_id, alt_names):\n\ttoks = alt_names.split('|')\n\tfor tok in toks:\n\t\tif tok.endswith('(gene name)'):\n\t\t\treturn tok[tok.find(':') + 1: tok.find('(')]\n\treturn my_id + '?' # no name...\ndef get_vernacular_tax(tax):\n\treturn tax.split('|')[0][tax.find('(') + 1:-1]\ndef add_interactions(species):\n\tfor rec in species.split('\\n'):\n\t\ttoks = rec.rstrip().split('\\t')\n\t\tif len(toks) < 15:\n\t\t\tcontinue # empty line at the end\n\t\tid1 = toks[0][toks[0].find(':') + 1:]\n\t\tid2 = toks[1][toks[1].find(':') + 1:]\n\t\tgene1, gene2 = get_gene_name(id1, toks[4]), get_gene_name(id2, toks[5])\n\t\ttax1, tax2 = get_vernacular_tax(toks[9]), get_vernacular_tax(toks[10])\n\t\tinter_type = toks[11][toks[11].find('(') + 1:-1]\n\t\tmiscore = float(toks[14].split(':')[1])\n\t\tgenes_species[tax1].add(gene1)\n\t\tgenes_species[tax2].add(gene2)\n\t\tinteractions[((tax1, gene1), (tax2, gene2))] = {'score': miscore, 'type': inter_type}\n\nhuman = get_psiquic_uniprot('uniprotkb:P04637')\nadd_interactions(human)\nrat = get_psiquic_uniprot('uniprotkb:P10361')\nadd_interactions(rat)\nmouse = get_psiquic_uniprot('uniprotkb:P02340')\nadd_interactions(mouse)\n","sub_path":"py/cytoscape.py","file_name":"cytoscape.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"112974637","text":"import time \r\ndef errorMessage():\r\n for i in range(3):\r\n print() \r\n \r\n print(\"Please answer correctly to the question !\")\r\n print(\"Try again !\")\r\n\r\n for i in range(3):\r\n print() \r\n\r\ndef timeWaiter():\r\n for i in range(3):\r\n print() \r\n\r\n print(\"Loading .. \")\r\n time.sleep(2)\r\n\r\n for i in range(3):\r\n print() \r\n\r\ndef endQuest():\r\n for i in range(3):\r\n print() \r\n\r\n end = input(\"Press any key to close the programm -- > \")\r\n\r\nprint(\"Welcome at Python !\")\r\nprint(\"Today we will learn sets !\")\r\nprint(\"Remember that in sets, elements CANNOT repeat !\")\r\nprint()\r\n#Asking the user what does he want to enter in his set\r\nuserSet = set([])\r\nwhile True:\r\n question = input(\"Do you want to add something to your set ? -- > \")\r\n\r\n if question == \"yes\" or question == \"Yes\":\r\n element = input(\"Print here the element that you want to add to your set -- > \")\r\n try:\r\n element = eval(element)\r\n user.add(element)\r\n except:\r\n userSet.add(element)\r\n elif question == \"no\" or question == \"No\":\r\n break \r\n else:\r\n errorMessage()\r\n continue \r\n\r\ntimeWaiter()\r\n\r\nprint(\"Here we have used the \\\"add()\\\" function to add something to the set. -- > userSet.add(element)\")\r\nprint(\"Your set is now -- > {0}\".format(userSet))\r\n\r\nfor i in range(3):\r\n print()\r\n\r\n#Asking the user if he wants to delete something from his set\r\nwhile True:\r\n question = input(\"Do you want to delete something from your set ? -- > \")\r\n\r\n if question == \"yes\" or question == \"Yes\":\r\n element = input(\"Print here the element that you want to delete from your set -- > \")\r\n try:\r\n element = eval(element)\r\n except:\r\n pass \r\n \r\n if element not in userSet:\r\n errorMessage()\r\n continue \r\n else:\r\n userSet.discard(element) \r\n elif question == \"no\" or question == \"No\":\r\n break \r\n else:\r\n errorMessage()\r\n continue \r\n\r\ntimeWaiter()\r\nprint(\"Here we have used the \\\"discard()\\\" function to discard/delete something from your set -- > userSet.discard(element)\")\r\nprint(\"Your set is now -- > {0}\".format(userSet))\r\n\r\nfor i in range(3):\r\n print() \r\n\r\n#Asking the user if he wants to copy the set \r\nwhile True:\r\n question = input(\"Do you want to copy this set ? -- > \")\r\n\r\n if question == \"yes\" or question == \"Yes\":\r\n userCopySet = userSet.copy()\r\n break\r\n elif question == \"no\" or question == \"No\":\r\n break\r\n else:\r\n errorMessage()\r\n continue \r\n\r\ntimeWaiter()\r\nprint(\"Here we have used the \\\"copy\\\" function to copy a set -- > userCopySet = userSet.copy()\")\r\nprint(\"This is the copied set -- > {0}\".format(userCopySet))\r\n\r\nfor i in range(3):\r\n print() \r\n\r\n#Asking the user if he wants to clear the set \r\nwhile True:\r\n question = input(\"Do you want to clear your set ? -- > \")\r\n\r\n if question == \"Yes\" or question == \"yes\":\r\n userSet.clear()\r\n break \r\n else:\r\n break \r\n \r\nprint(\"Here we have used the \\\"clear\\\" function to clear the set -- > userSet.clear()\")\r\nprint(\"This is your set now -- > {0}\".format(userSet))\r\nendQuest()\r\n","sub_path":"LearnSets.py","file_name":"LearnSets.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"209573246","text":"\"\"\"\nReal-time video streaming sender\n- send video to server\n- send training patches to server\n\"\"\"\n\n__author__ = \"Yihang Wu\"\n\nimport argparse\nimport logging\nimport random\nimport re\nimport subprocess\nfrom fractions import Fraction\nimport pickle\nimport platform\nimport asyncio\n\nimport numpy as np\nimport cv2\n\nfrom aiortc import RTCIceCandidate, RTCPeerConnection, RTCSessionDescription, RTCDataChannel, RTCConfiguration\nfrom aiortc.contrib.signaling import BYE, TcpSocketSignaling\n\nfrom media import MediaRelay, MediaPlayerDelta, MediaStreamTrack\nfrom misc import ClassLogger, Resolution, Patch, MostRecentSlot, get_ice_servers, frame_to_ndarray, ndarray_to_bytes, cal_psnr\n\nlogger = logging.getLogger('sender')\nrelay = MediaRelay() # a media source that relays one or more tracks to multiple consumers.\n\n\nclass PatchSampler:\n def __init__(self, hr_width, hr_height, lr_width, lr_height, patch_grid_height, patch_grid_width, *,\n psnr_filter=True, strict_quantity=False):\n \"\"\"\n A patch sampler to sample training patches from given frames.\n Specifically, given a pair of high-resolution (hr) frame and low-resolution (lr) frame,\n the sampler cuts both the hr and lr frame into small patches in terms of given grid,\n and select the patches at the same position.\n The sampler allows to sample multiple patches from a frame.\n\n Examples:\n An example initialization could be PatchSampler(1920, 1080, 640, 360, 16, 9)\n\n Args:\n hr_width (int): the width of the high-resolution image\n hr_height (int): the height of the high-resolution image\n lr_width (int): the width of the low-resolution image\n lr_height (int): the height of the low-resolution image\n patch_grid_height (int): the height of the patch grid\n patch_grid_width (int): the width of the patch grid\n psnr_filter (bool): only accept the patch with PSNR lower than the average of the frame\n strict_quantity (bool): force to sample at least a specified number of patches from a single frame\n \"\"\"\n self.hr_image_width = hr_width\n self.hr_image_height = hr_height\n self.lr_image_width = lr_width\n self.lr_image_height = lr_height\n self.psnr_filter = psnr_filter\n self.strict_quantity = strict_quantity\n\n if self.strict_quantity:\n raise NotImplementedError\n\n self.hr_patch_width = hr_width // patch_grid_width\n self.hr_patch_height = hr_height // patch_grid_height\n self.lr_patch_width = lr_width // patch_grid_width\n self.lr_patch_height = lr_height // patch_grid_height\n self.num_patch_grids = patch_grid_height * patch_grid_width\n self.sampling_points = [(h, w) for h in range(patch_grid_height) for w in range(patch_grid_width)]\n\n self._hr_image = None\n self._lr_image = None\n self._global_psnr = None\n\n def place(self, hr_image: np.ndarray, lr_image: np.ndarray) -> None:\n \"\"\"\n Place a pair of hr image and lr image into the sampler.\n Later samples will be drawn from these images.\n\n Args:\n hr_image (): hr image with shape (hr_height, hr_width, *)\n lr_image (): lr image with shape (lr_height, lr_width, *)\n \"\"\"\n self._hr_image = hr_image\n self._lr_image = lr_image\n lr_image_f32 = self._lr_image.astype(np.float32)\n if self.psnr_filter:\n ip_image = cv2.resize(lr_image_f32, (self.hr_image_width, self.hr_image_height), interpolation=cv2.INTER_LINEAR)\n self._global_psnr = cal_psnr(ip_image, self._hr_image, max_val=255)\n\n def sample(self, n: int = 1, max_inspect: int = None) -> list:\n \"\"\"\n Sample a number of patches from placed images.\n\n Args:\n n (int): the number of patches to sample\n max_inspect (int): the maximum number of patches inpsected.\n If set to None, then the sampler will probably inspect every location to get the required amount of patches.\n\n Returns:\n A list of (hr_patch, lr_patch)\n \"\"\"\n # assert not self.strict_quantity or n <= max_inspect\n\n if max_inspect is None:\n max_inspect = self.num_patch_grids\n\n samples = []\n for h, w in random.sample(self.sampling_points, max_inspect):\n hr_patch = self._hr_image[\n h * self.hr_patch_height: (h + 1) * self.hr_patch_height,\n w * self.hr_patch_width: (w + 1) * self.hr_patch_width, :]\n lr_patch = self._lr_image[\n h * self.lr_patch_height: (h + 1) * self.lr_patch_height,\n w * self.lr_patch_width: (w + 1) * self.lr_patch_width, :]\n if self.psnr_filter:\n lr_patch_f32 = lr_patch.astype(np.float32)\n ip_patch = cv2.resize(lr_patch_f32, (self.hr_patch_width, self.hr_patch_height), interpolation=cv2.INTER_LINEAR)\n psnr = cal_psnr(ip_patch, hr_patch, max_val=255)\n if psnr >= self._global_psnr:\n continue\n samples.append((hr_patch, lr_patch))\n if len(samples) == n:\n break\n\n return samples\n\n\nclass PatchTransmitter(ClassLogger):\n def __init__(self, patch_sampler: PatchSampler, sample_freq, sample_num):\n \"\"\"\n PatchTransmitter at sender side.\n The PatchTransmitter has following functionality:\n - sample training patches using the provided PatchSampler object\n - deliver training patch to RTC's data channel\n\n Args:\n patch_sampler (PatchSampler): patch sampler instance\n sample_freq (float): the frequency of sampling patches\n sample_num (int): the number of patches that each sampling process gets\n \"\"\"\n super().__init__('sender')\n\n self._sampler = patch_sampler\n\n self._slot = MostRecentSlot() # a wrap to a queue object that is passed to the MediaPlayerDelta, storing the \"most recent\" pair of frames\n self._patch_channel = None # the RTC patch channel\n self._task = None\n\n self._interval = 1 / sample_freq\n self._sample_num = sample_num\n\n async def _run(self):\n while True:\n try:\n await asyncio.sleep(self._interval) # sample frames every specific second (can further adjust to listen some signal)\n hr_frame, lr_frame = await self._slot.get() # this is not the most recent frame, but the frame head of recent frame 0~0.1s\n self._sampler.place(frame_to_ndarray(hr_frame), # (hr_height, hr_width, 3)\n frame_to_ndarray(lr_frame)) # (lr_height, lr_width, 3)\n samples = self._sampler.sample(self._sample_num)\n for hr_patch, lr_patch in samples:\n hr_bytes = ndarray_to_bytes(hr_patch)\n lr_bytes = ndarray_to_bytes(lr_patch)\n patch = Patch(hr_bytes, lr_bytes)\n patch_bytes = pickle.dumps(patch)\n self._patch_channel.send(patch_bytes)\n self.log_debug(f'put {len(samples)} samples to patch channel')\n\n except asyncio.CancelledError:\n return\n\n def start(self):\n if not isinstance(self._patch_channel, RTCDataChannel):\n raise TypeError\n self._task = asyncio.create_task(self._run())\n\n def stop(self):\n if self._task is not None:\n self._task.cancel()\n\n @property\n def slot(self):\n \"\"\"\n The slot that placed the most recent frame.\n \"\"\"\n return self._slot\n\n @property\n def patch_channel(self) -> RTCDataChannel:\n return self._patch_channel\n\n @patch_channel.setter\n def patch_channel(self, channel: RTCDataChannel):\n self._patch_channel = channel\n\n\nasync def comm_server(pc, signaling, audio, video, patch_transmitter):\n \"\"\"\n Sender communicates with server.\n Send video and training patches to server.\n\n Args:\n pc (RTCPeerConnection): peer connection object\n signaling (TcpSocketSignaling): signaling proxy. Could be other signaling tool. See aiortc.contrib.signaling for more.\n audio (MediaStreamTrack or None): audio track of the media source\n video (MediaStreamTrack): video track of the media source\n patch_transmitter (PatchTransmitter):\n \"\"\"\n\n def add_senders():\n for t in pc.getTransceivers():\n if t.kind == 'audio' and audio:\n pc.addTrack(audio)\n elif t.kind == 'video' and video:\n pc.addTrack(video)\n\n @pc.on('datachannel')\n def on_datachannel(channel: RTCDataChannel):\n logger.info('Received data channel: %s', channel.label)\n\n if channel.label == 'patch':\n # if it is a patch channel, register it to the patch transmitter object\n # which will place the patches to the channel\n patch_transmitter.patch_channel = channel\n patch_transmitter.start()\n elif channel.label == 'dummy':\n pass\n else:\n raise NotImplementedError\n\n await signaling.connect()\n\n # consume signaling\n while True:\n try:\n obj = await signaling.receive()\n except ConnectionRefusedError:\n logger.info('Connection Refused by remote computer')\n logger.info('This may be becuase the signaling server has not been set up')\n break\n\n if isinstance(obj, RTCSessionDescription):\n logger.info('Received remote description')\n await pc.setRemoteDescription(obj)\n\n add_senders()\n await pc.setLocalDescription(await pc.createAnswer())\n await signaling.send(pc.localDescription)\n elif isinstance(obj, RTCIceCandidate):\n logger.info('Received remote candidate')\n await pc.addIceCandidate(obj)\n elif obj is BYE:\n logger.info('Exiting')\n break\n\n\ndef get_device_list_dshow():\n \"\"\"\n Get device name list under windows directshow\n Change\n - remove decode ascii\n References: https://pyacq.readthedocs.io/en/latest/_modules/pyacq/devices/webcam_av.html\n \"\"\"\n cmd = \"ffmpeg -list_devices true -f dshow -i dummy\"\n proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n txt = proc.stdout.read().decode() # .decode('ascii')\n txt = txt.split(\"DirectShow video devices\")[1].split(\"DirectShow audio devices\")[0]\n pattern = '\"([^\"]*)\"'\n l = re.findall(pattern, txt, )\n l = [e for e in l if not e.startswith('@')]\n return l\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Real-time video streaming sender')\n parser.add_argument('--debug', action='store_true', help='Set the logging verbosity to DEBUG')\n\n # camera\n parser.add_argument('--use-camera', action='store_true', help='Use camera (--play-from is ignored if set)')\n parser.add_argument('--cam-framerate', type=str, default='30', help='Camera ingest frame rate')\n parser.add_argument('--cam-videosize', type=str, default='640x480', help='Camera ingest resolution')\n\n # video\n parser.add_argument('--play-from', type=str, help='Read the media from a file and sent it.')\n parser.add_argument('--framerate-degradation', type=int, default=1, help='Use only 1 frame every specified frames')\n parser.add_argument('--aspect-ratio', type=str, default='4x3', help='Aspect ratio of the video given in \"[W]x[H]\"')\n parser.add_argument('--hr-height', type=int, default=480, help='Height of origin high-resolution video')\n parser.add_argument('--lr-height', type=int, default=240, help='Height of transformed low-resolution video')\n\n # patch (for SR training)\n parser.add_argument('--patch-grid-height', type=int, default=12, help='Height of the patch grid')\n parser.add_argument('--patch-grid-width', type=int, default=16, help='Width of the patch grid')\n parser.add_argument('--patch-sampling-frequency', type=float, default=2.0, help='The frequency of sampling patches')\n parser.add_argument('--patch-sampling-num', type=int, default=10, help='The number of patches that each sampling process gets')\n parser.add_argument('--apply-psnr-filter', action='store_true', help='Apply PSNR filter when sampling patches')\n\n # signaling\n parser.add_argument('--signaling-host', type=str, default='127.0.0.1', help='TCP socket signaling host')\n parser.add_argument('--signaling-port', type=int, default=9999, help='TCP socket signaling port')\n\n # ICE server\n parser.add_argument('--ice-config', type=str, help='ICE server configuration')\n parser.add_argument('--ice-provider', type=str, default='google', help='ICE server provider')\n args = parser.parse_args()\n\n # logging settings\n logging.basicConfig(level=logging.INFO)\n logger.setLevel(level=logging.DEBUG if args.debug else logging.INFO)\n\n # RTC\n signaling = TcpSocketSignaling(args.signaling_host, args.signaling_port)\n\n if args.ice_config is None:\n logger.info('ice server is not configured')\n ice_servers = None\n else:\n logger.info(f'configure ice server from {args.ice_provider}')\n ice_servers = get_ice_servers(args.ice_config, args.ice_provider) # a list of ice servers (might be empty)\n rtc_config = RTCConfiguration(iceServers=ice_servers)\n\n pc = RTCPeerConnection(rtc_config)\n\n # determine resolution for both high- and low-quality streams\n aspect_ratio = Fraction(*map(int, args.aspect_ratio.split('x')))\n high_resolution = Resolution.get(args.hr_height, aspect_ratio)\n low_resolution = Resolution.get(args.lr_height, aspect_ratio)\n\n patch_sampler = PatchSampler(hr_width=high_resolution.width, hr_height=high_resolution.height,\n lr_width=low_resolution.width, lr_height=low_resolution.height,\n patch_grid_height=args.patch_grid_height, patch_grid_width=args.patch_grid_width,\n psnr_filter=args.apply_psnr_filter)\n patch_transmitter = PatchTransmitter(patch_sampler,\n sample_freq=args.patch_sampling_frequency,\n sample_num=args.patch_sampling_num)\n\n \"\"\"\n Framerate degradation\n \n When the capability of the receiving device is insufficient,\n degrade the framerate of the original stream with level FR_DEG.\n The player will then sample only one frame every FR_DEG frames.\n For example, when the origin video is 30 fps,\n setting FR_DEG to 3 degrades the video to 10 fps;\n setting FR_DEG to 6 degrades the video to 5 fps;\n setting FR_DEG to 1 imposes nothing to the original video.\n \"\"\"\n fr_deg = args.framerate_degradation\n logger.info(f'Framerate degradation level is set to {fr_deg}')\n\n # media source\n audio_track = None\n video_track = None\n if args.use_camera:\n # camera options (not all options are supported)\n options = {'framerate': args.cam_framerate, 'video_size': args.cam_videosize}\n if platform.system() == 'Linux':\n webcam = MediaPlayerDelta('/dev/video0', frame_width=low_resolution.width, frame_height=low_resolution.height,\n slot=patch_transmitter.slot, framerate_degradation=fr_deg, format='v4l2', options=options)\n elif platform.system() == 'Windows':\n device = get_device_list_dshow()[0]\n webcam = MediaPlayerDelta(f'video={device}', frame_width=low_resolution.width, frame_height=low_resolution.height,\n slot=patch_transmitter.slot, framerate_degradation=fr_deg, format='dshow', options=options)\n else:\n raise NotImplementedError\n # audio_track = None\n video_track = relay.subscribe(webcam.video)\n else: # play from local file\n if args.play_from is None:\n logger.info('need to specify local media file. Exit.')\n exit(0)\n player = MediaPlayerDelta(args.play_from, frame_width=low_resolution.width, frame_height=low_resolution.height,\n slot=patch_transmitter.slot, framerate_degradation=fr_deg)\n # audio_track = player.audio\n video_track = player.video\n\n # run sender\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(comm_server(pc, signaling, audio_track, video_track, patch_transmitter))\n except KeyboardInterrupt:\n logger.info('keyboard interrupt while running sender')\n finally:\n # cleanup\n patch_transmitter.stop()\n loop.run_until_complete(signaling.close())\n loop.run_until_complete(pc.close())\n","sub_path":"sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":16863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"57059097","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom scipy.ndimage import interpolation\nimport csv\n\n# Helper function for deskew\ndef moments(image):\n c0,c1 = np.mgrid[:image.shape[0],:image.shape[1]] # A trick in numPy to create a mesh grid\n totalImage = np.sum(image) #sum of pixels\n m0 = np.sum(c0*image)/totalImage #mu_x\n m1 = np.sum(c1*image)/totalImage #mu_y\n m00 = np.sum((c0-m0)**2*image)/totalImage #var(x)\n m11 = np.sum((c1-m1)**2*image)/totalImage #var(y)\n m01 = np.sum((c0-m0)*(c1-m1)*image)/totalImage #covariance(x,y)\n mu_vector = np.array([m0,m1]) # Notice that these are \\mu_x, \\mu_y respectively\n covariance_matrix = np.array([[m00,m01],[m01,m11]]) # Do you see a similarity between the covariance matrix\n return mu_vector, covariance_matrix\n\n# Deskew Image\ndef deskew(image):\n c,v = moments(image)\n alpha = v[0,1]/v[0,0]\n affine = np.array([[1,0],[alpha,1]])\n ocenter = np.array(image.shape)/2.0\n offset = c-np.dot(affine,ocenter)\n return interpolation.affine_transform(image,affine,offset=offset)\n \n# WRITE Function\ndef write(pred):\n file = open(\"knn.csv\", \"w\")\n writer = csv.writer(file, delimiter=',')\n writer.writerow(['ImageID', 'Digit'])\n for i, y in enumerate(pred):\n n = i + 1\n writer.writerow([n, y])\n\n# WRITE Accuracy Function\ndef writeAcc(scores):\n file = open(\"knnScores.csv\", \"w\")\n writer = csv.writer(file, delimiter=',')\n writer.writerow(['No', 'Score'])\n for i, y in enumerate(scores):\n n = i + 1\n writer.writerow([n, y])\n\n# Load dataset\nfileName = ['res/MNIST_Xtrain.csv', 'res/MNIST_ytrain.csv', 'res/MNIST_Xtestp.csv']\n\ndf = pd.read_csv(\"res/MNIST_Xtrain.csv\", header=None)\nX = df.values\n\ndf = pd.read_csv(\"res/MNIST_ytrain.csv\", header=None)\ny = df.values\n\ndf = pd.read_csv(\"res/MNIST_Xtestp.csv\", header=None)\nX_t = df.values\n\nprint(\"Done loading\")\n\nX_deskew = []\nX_deskew_t = []\n\n# Deskew\nfor i in range(X.shape[0]):\n print(i)\n img = deskew(X[i].reshape(28, 28)).reshape(784)\n img = (img - img.min()) / (img.max() - img.min())\n X_deskew.append(img)\n\nfor i in range(X_t.shape[0]):\n print(i)\n img_t = deskew(X_t[i].reshape(28, 28)).reshape(784)\n img_t = (img_t - img_t.min()) / (img_t.max() - img_t.min())\n X_deskew_t.append(img_t)\n\nX_deskew = np.array(X_deskew)\nX_deskew_t = np.array(X_deskew_t)\n\nneighbors = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n\nbestScore = 0\nscores = []\nbestN = -1\n\n# Cross Validate\nfor n in neighbors:\n clf = KNeighborsClassifier(n_neighbors=n, weights='distance', p=3, n_jobs=70)\n validationScores = cross_val_score(clf, X, y, cv=10)\n score = validationScores.mean()\n scores.append(score)\n if score > bestScore:\n bestScore = score\n bestN = n\n print(\"k=\", n, \", accuracy=\", score)\n\n# Fit the classifier with best hyperparameter\nclf = KNeighborsClassifier(n_neighbors=bestN, weights='distance', p=3, n_jobs=70)\nclf.fit(X, y.ravel())\ny_pred = clf.predict(X_t)\n\n# Write results\nwriteAcc(scores)\nwrite(y_pred)","sub_path":"a2/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"488134280","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\nName:Henry\nDate: 25/Tan/2018\nProgram Title: Assignment8:Photo Processing\n\nPurpose: \n(1) Start with the BasicFilter.py program in the Vision Apps repository from GitHub.\n(2) Convert the program to work with Python 3 and OpenCV\n(3) Use the program to take two similar photos, process them and produce an image that highlights the difference between the photos.\n\n\n\n\"\"\"\n\n#Photo Analysis Program - Isolates an object using a base picture and an active picture\n#Modification - filter out noise by combining two pictures processed to optimize background and foreground detection\n\n#Setup:\n#Graphics modules\nimport numpy as np\nimport cv2\n#Random and Datetime\nfrom random import *\nfrom datetime import *\n\n#Subroutines:\ndef ComparePixels(P1,P2,tolerance):\n t1 = abs(P1[0]-P2[0])\n t2 = abs(P1[1]-P2[1])\n t3 = abs(P1[2]-P2[2])\n if t1<= tolerance and t2 <=tolerance and t3 <=tolerance:\n return True\n else:\n return False\n\ndef ProcessPhoto(BasePhoto, ActivePhoto, Tolerance, BackgroundColour, ForegroundColour, X_SIZE, Y_SIZE, filename):\n ResultPhotoRaw = np.zeros((X_SIZE,Y_SIZE,3), np.uint8)\n cv2.imwrite(\"ResultPhoto.PNG\",ResultPhotoRaw)\n ResultPhoto=cv2.imread(\"ResultPhoto.PNG\")\n BasePhoto=cv2.imread(\"BasePhoto.PNG\")\n ActivePhoto=cv2.imread(\"ActivePhoto.PNG\")\n #This loop scans through all the pixel in the picture\n for x in range(0, X_SIZE):\n for y in range(0, Y_SIZE):\n Base = BasePhoto[x,y]\n Active = ActivePhoto[x,y]\n if ComparePixels(Base, Active, Tolerance):\n ResultPhoto[x,y] = PositiveColour\n else:\n ResultPhoto[x,y]= NegativeColour\n cv2.imwrite(\"Testing.PNG\",ResultPhoto)\n return ResultPhoto\n\ndef NeighborhoodScan(ScanRadius, Photo, ForegroundColour, BackgroundColour, x, y):\n #Takes a photo in two RGB colours, ForegroundColour and BackgroundColour and scans pixels in the neighborhood to determine \n #to determine whether to keep the pixel colour the same or change it based on the colours of other nearby pixels\n Sum = 0\n #The following nested loop adds one for Foreground Colour and Subtracts one for background colour\n for X in range(x-ScanRadius, x+ScanRadius):\n for Y in range(y-ScanRadius, y+ScanRadius):\n if Photo[X,Y] == ForegroundColour:\n Sum+=1\n else:\n Sum-=1\n #If the sum is positive, then the foreground colour wins and vice versa\n if Sum >=0:\n return ForegroundColour\n else:\n return BackgroundColour\t\t\n\t\t\t\ndef PixelDecision(NeighborhoodForeground, NeighborhoodBackground, PositiveColour, NegativeColour):\n if NeighborhoodForeground == PositiveColour and NeighborhoodBackground == PositiveColour:\n return PositiveColour\n elif NeighborhoodForeground == PositiveColour and NeighborhoodBackground == NegativeColour:\n return PositiveColour\n elif NeighborhoodForeground == NegativeColour and NeighborhoodBackground == PositiveColour:\n return PositiveColour\n else:\t\n return NegativeColour\n\ndef SquareOverlay(ForegroundPhoto, BackgroundPhotoRaw, PositiveColour, NegativeColour, Size, X_SIZE, Y_SIZE):\n\t #Check for square regions in the Foreground Photo within 'Size' of point (x,y) that are only of the foreground colour.\n\t #Paste these into the BackgroundPhoto to create the ResultPhoto\n X_Squares = int(X_SIZE/(2*Size+1))\n Y_Squares = int(Y_SIZE/(2*Size+1))\n ResultPhotoRaw = np.zeros((X_SIZE, Y_SIZE,3), np.uint8)\n\t #ResultPhotoRaw = Image.new(\"RGB\", (X_SIZE, Y_SIZE), (0,0,0))\n cv2.imwrite(\"TestSquareOverlay.png\",ResultPhotoRaw)\n #ResultPhotoRaw.save(\"TestSquareOverlay.PNG\")\n #draw = ImageDraw.Draw(ResultPhotoRaw)\n ResultPhotoRaw=cv2.imread('Foreground.PNG')#This reads the foreground photo.\n for x in range(0, X_Squares):\n for y in range(0, Y_Squares):\n X = (2*Size+1)*x+Size\n Y = (2*Size+1)*y+Size\n Check = True\n for xi in range(X-Size, X+Size):\n for yi in range(Y-Size, Y+Size):\n if np.all(ForegroundPhoto[xi,yi] == 255):\n Check = False\n if Check == False:\n cv2.rectangle(ResultPhotoRaw,(Y-Size,X-Size),(Y+Size,X+Size),(255,255,255),3)\n cv2.imwrite(\"Testing.PNG\",ResultPhotoRaw)\n return ResultPhotoRaw\n\ndef photoTaking():\n cam = cv2.VideoCapture(0)\n cv2.namedWindow(\"test\")\n count = 0\n print(\"Press SPACE twice to take base and active photoes and press ESC to exit.\") #This could give the user some instructions.\n while True:\n ret, frame = cam.read()\n cv2.imshow(\"test\", frame)\n if not ret:\n break\n k = cv2.waitKey(1)\n if k%256 == 27:\n # When ESC is pressed, the camera will be exited.\n print(\"The camera will be closed.\")\n break\n elif k%256 == 32:\n # When SPACE is pressed, the photo will be taken.\n name = \"Photo{}.png\".format(count)\n cv2.imwrite(name, frame)\n print(\"{} written!\".format(name))\n count += 1 \n cam.release()\n cv2.destroyAllWindows()\n\n\n#Take a Base image\nphotoTaking()\n\n#def getPixel(X, Y)\n\t#return - RGB colour of Pixel\n\t#scan photo and compare\nScanRadius = 2 #This checks adjacent pixels\nToleranceBackground = 40 #Set to an arbitrary quantity for later calibration\nToleranceForeground = 2\nPositiveColour = [0,0,0] #Black\nNegativeColour = [255,255,255] #White\n\nBasePhoto = cv2.imread('Photo0.PNG')\nActivePhoto = cv2.imread('Photo1.PNG')\n\n#Determine the size of the photos\nX_SIZE = BasePhoto.shape[0]\nY_SIZE = BasePhoto.shape[1]\n\ncv2.imwrite('BasePhoto.PNG', BasePhoto)\ncv2.imwrite('ActivePhoto.PNG', ActivePhoto)\n\n\nResultPhotoRaw = np.zeros((X_SIZE,Y_SIZE,3), np.uint8)\nResultPhotoRaw[np.where((ResultPhotoRaw==[0,0,0]).all(axis=2))] = [255,255,255]\ncv2.imwrite(\"ResultPhotoRaw.PNG\", ResultPhotoRaw)\n#Save a photo processed with ForegroundTolerance:\nForegroundPhotoRaw = ProcessPhoto(BasePhoto, ActivePhoto, ToleranceForeground, PositiveColour, NegativeColour, X_SIZE, Y_SIZE, 'F.PNG') \ncv2.imwrite('Foreground.PNG', ForegroundPhotoRaw)\nForegroundPhoto = cv2.imread('Foreground.PNG')\n#ForegroundPhoto = ForegroundPhotoRaw.load()\n#Save a photo processed with BackgroundTolerance:\nBackgroundPhotoRaw = ProcessPhoto(BasePhoto, ActivePhoto, ToleranceBackground, PositiveColour, NegativeColour, X_SIZE, Y_SIZE, 'B.PNG')\ncv2.imwrite('Background.PNG', BackgroundPhotoRaw)\n\nSquareSize = 5\nResultPhoto = SquareOverlay(ForegroundPhoto, BackgroundPhotoRaw, PositiveColour, NegativeColour, SquareSize, X_SIZE, Y_SIZE)\n\ndatenow = date.today()\ntimenow = str(datetime.now()).strip('.')\n#print timenow\nfilename = \"Result\"+str(ToleranceForeground)+\"_\"+str(ToleranceBackground)+\"_\"+str(timenow)+'.PNG'\nprint (filename)\ncv2.imwrite(\"{0}.png\".format(filename),ResultPhoto)\n\n\n\n\n\n\n \n \n\n","sub_path":"parents of henry/Henry/Photo processing/henry8.py","file_name":"henry8.py","file_ext":"py","file_size_in_byte":6982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"339249165","text":"#!python3\n\n'''\n\n Write a timeit function!\n\n similar to the jupyter %timeit\n\n'''\n\nfrom functools import wraps\nimport time\n\n\n\ndef timeit(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n\n # before\n print(f'== start timer')\n start_time = time.time()\n\n result = func(*args, **kwargs)\n\n # after\n end_time = time.time()\n print(f'== {func.__name__} took {int(end_time - start_time)} seconds to complete.')\n\n # return\n return result\n\n return wrapper\n\n\n@timeit\ndef do_something(n=10000):\n\n sum = 0\n for i in range(0, n):\n sum += i\n\n@timeit\ndef generate_report():\n ''' Function to generate revenue report'''\n time.sleep(2)\n print('{actual function} Done, report links ...')\n\n\ndef main():\n print(f'--------------------------------')\n do_something(n=12345678)\n print(f'--------------------------------')\n generate_report()\n print(f'--------------------------------')\n\n print(f'{generate_report.__doc__}')\n\n\nif __name__ == '__main__':\n print()\n main()\n print()\n\n\n\n#EOF\n","sub_path":"day22-24/day22_timeIt.py","file_name":"day22_timeIt.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"36117401","text":"# -*- coding: utf-8 -*-\n\n# -*- coding: utf-8 -*-\n\n##############################################################################\n#\n#\n# Copyright (C) 2018-TODAY .\n# Author: Eng.Ramadan Khalil ()\n#\n# It is forbidden to publish, distribute, sublicense, or sell copies\n# of the Software or modified copies of the Software.\n#\n##############################################################################\n\nfrom odoo import api, fields, models,_\nfrom odoo.exceptions import ValidationError,UserError\n\n\n\nclass HrEmployee(models.Model):\n _inherit = 'hr.employee'\n\n sec_name=fields.Char(string='Arabic Name')\n @api.constrains(\"sec_name\")\n def name_get(self):\n res = []\n for emp in self:\n name = emp.name\n if emp.sec_name:\n name = '%s[%s]' % (emp.name, emp.sec_name)\n res.append((emp.id, name))\n print('iam on the name get',res)\n return res\n","sub_path":"addons/danfresh_hr_update_Removed/models/hr_employee.py","file_name":"hr_employee.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"532047794","text":"from bs4 import BeautifulSoup\r\nfrom bs4.element import Tag\r\nimport requests\r\nimport json\r\nimport sys\r\nimport time\r\nimport os\r\nimport re\r\n\r\nfile_name = 'links.json'\r\nsong_urls = json.loads(open(file_name).read())\r\n\r\n# Creates a 'websites' folder if it doesn't already exist.\r\nif not os.path.exists('songs'):\r\n os.makedirs('songs')\r\n\r\nrequestCount = 0\r\nfor url in song_urls:\r\n page = ''\r\n while page == '':\r\n try:\r\n page = requests.get(url)\r\n except:\r\n time.sleep(5)\r\n continue\r\n # file_name is artist + song name\r\n file_name = 'songs/' + url[19:] + '.txt'\r\n # get html from URL\r\n html = page.text\r\n soup = BeautifulSoup(html, 'html5lib')\r\n # extract text from lyrics paragraph\r\n lyrics_div = soup.find_all('div', class_=\"lyrics\")\r\n lyrics_p = lyrics_div[0].find('p')\r\n lyrics_text = lyrics_p.text\r\n # Remove [Verse], etc. labels\r\n lyrics_text = re.sub(r'(?is)\\[.*?\\]\\n', '', lyrics_text)\r\n\r\n # Writes the lyrics to a '.txt' file.\r\n with open(file_name, 'w') as outfile:\r\n outfile.write(lyrics_text.encode('utf-8'))\r\n","sub_path":"scrape_lyrics.py","file_name":"scrape_lyrics.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"262613714","text":"# -*- coding: utf-8 -*-\n\nGPU_ID = 0\nTRAIN_BATCH_SIZE = 32\nTEST_BATCH_SIZE = 32\nTRIPLET_BATCH_SIZE = 32\nTEST_BATCH_COUNT = 30\nNUM_WORKERS = 4\nLR = 0.001\nMOMENTUM = 0.5\nEPOCH = 10\nDUMPED_MODEL = \"model_1_2000.pth.tar\"\n\nLOG_INTERVAL = 10\nDUMP_INTERVAL = 500\nTEST_INTERVAL = 100\n\nDATASET_BASE = r'/DATACETNER/1/ch/deepfashion_data'\nIMG_SIZE = 256\nCROP_SIZE = 224\nINTER_DIM = 512\nCATEGORIES = 20\nTRIPLET_WEIGHT = 0.5\nFREEZE_PARAM = False\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"562597705","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nname = \"R_Addition_MultipleBond/training\"\nshortDesc = u\"Kinetics used to train group additivity values\"\nlongDesc = u\"\"\"\nPut kinetic parameters for reactions to use as a training set for fitting\ngroup additivity values in this file.\n\"\"\"\nentry(\n index = 1,\n label = \"C2H2 + C4H9 <=> C6H11\",\n degeneracy = 2,\n kinetics = Arrhenius(\n A = (5.01e+10, 'cm^3/(mol*s)'),\n n = 0,\n Ea = (5.31, 'kcal/mol'),\n T0 = (1, 'K'),\n Tmin = (373, 'K'),\n Tmax = (493, 'K'),\n ),\n reference = Article(\n authors = [\"Garcia Dominguez, J.A.\", \"Trotman-Dickenson, A.F.\"],\n title = u'The reactions of alkyl radicals. Part IX. The addition of methyl, ethyl, isopropyl, and t-butyl radicals to acetylene and the isomerization of alkenyl radicals',\n journal = \"J. Chem. Soc.\",\n pages = \"\"\"940-944\"\"\",\n year = \"1962\",\n url = \"http://kinetics.nist.gov/kinetics/Detail?id=1962GAR/TRO940-944:1\",\n ),\n longDesc = \nu\"\"\"\nDominguez et al. Data derived from fitting to a complex mechanism.\nPressure 0.01-0.32 atm. Excitation : direct photolysis, analysis : GC. \nC2H2 + Tert-C4H9 --> (CH3)3CCH=CH\n\nWas in the rules database with rank=4. Richard moved to the training database and checked with NIST database. NIST squib: 1962GAR/TRO940-944\nA=5.01e+10 cm^3/(mol*s) is the full rate; NB the degeneracy=2 so the per-site rate is half this.\n\"\"\",\n)\n\nentry(\n index = 2,\n label = \"C2H3O3 <=> C2H2O + HO2\",\n degeneracy = 1,\n kinetics = Arrhenius(\n A = (5.3e+16, 's^-1', '*|/', 2.51189),\n n = -1,\n Ea = (29.5, 'kcal/mol'),\n T0 = (1, 'K'),\n ),\n reference = Article(\n authors = [\"J. W. Allen\", \"C. F. Goldsmith\", \"W. H. Green\"],\n title = u'Automatic Estimation of Pressure-Dependent Rate Coefficients',\n journal = \"Phys. Chem. Chem. Phys.\",\n volume = \"???\",\n pages = \"\"\"???-???\"\"\",\n year = \"2011 (accepted)\",\n ),\n referenceType = \"theory\",\n shortDesc = u\"\"\"CFG VTST calculations at RQCISD(T)/CBS//B3LYP/6-311++G(d,p) level\"\"\",\n longDesc = \nu\"\"\"\nQuantum chemistry calculations at the RQCISD(T)/CBS//B3LYP/6-311++G(d,p) level\nusing Gaussian 03 and MOLPRO. High-pressure-limit rate coefficient computed\nusing Variflex.\n\"\"\",\n)\n\n","sub_path":"input/kinetics/families/R_Addition_MultipleBond/training/reactions.py","file_name":"reactions.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"180324701","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 14 16:39:27 2021\n\n@author: qiang\n\"\"\"\n\nimport sim\nimport math\nimport time\n\n# TODO: These API function still need to be improved and modified. Some variables' defination are not uniformed. For example: position & pos\n# TODO: Set raising error system to raise error for some condition. For example when the simulation is not start but users want to movej\n\njoint_angle = [0, 0, 0, 0, 0, 0] # each angle of joint\nRAD2DEG = 180 / math.pi # transform radian to degrees\n\nclass CoppeliaSim_env():\n def __init__(self,\n scene_path = None,\n scene_side = None,\n commThreadCycleInMs = 5,\n timeOutInMs = 5000):\n\n self.timeOutInMs = timeOutInMs\n self.commThreadCycleInMs = commThreadCycleInMs\n self.scene_path = scene_path\n self.scene_side = scene_side\n self.sim_activate()\n \n if self.scene_path:\n assert self.scene_path and self.scene_side, \"Miss the Argument 'scene_side', you must specify which side the file is located\"\n sim.simxLoadScene(self.clientID,self.scene_path,self.scene_side,sim.simx_opmode_blocking)\n \n self.sim_is_running = 0\n \n \n def sim_activate(self):\n sim.simxFinish(-1)\n # Close the potential connection\n while True:\n # simxStart的参数分别为:服务端IP地址(连接本机用127.0.0.1);端口号;是否等待服务端开启;连接丢失时是否尝试再次连接;超时时间(ms);数据传输间隔(越小越快)\n self.clientID = sim.simxStart('127.0.0.1', 19998, True, True, self.timeOutInMs, self.commThreadCycleInMs)\n if self.clientID > -1:\n print(\"Connection success!\")\n break\n else:\n time.sleep(0.2)\n print(\"Failed connecting to remote API server!\")\n print(\"Maybe you forget to open CoppliaSim, please check\")\n self.sim_is_activate = 1\n \n def sim_finish(self):\n if self.sim_is_running:\n self.sim_stop()\n time.sleep(0.5)\n sim.simxFinish(self.clientID)\n self.sim_is_activate = 0\n \n def sim_start(self):\n if self.sim_is_activate:\n sim.simxStartSimulation(self.clientID, sim.simx_opmode_oneshot)\n self.sim_is_running = 1\n else:\n print('You need to activate the simulation before start it')\n \n def sim_pause(self):\n if self.sim_is_activate:\n if self.sim_is_running:\n sim.simxPauseSimulation(self.clientID, sim.simx_opmode_oneshot)\n self.sim_is_running = 0\n else:\n print('Simulation was not started')\n else:\n print('You need to activate the simulation before pause it')\n \n def sim_stop(self):\n if self.sim_is_activate:\n if self.sim_is_running:\n sim.simxStopSimulation(self.clientID, sim.simx_opmode_oneshot)\n self.sim_is_running = 0\n else:\n print('Simulation was not started')\n else:\n print('You need to activate the simulation before stop it')\n \n def sim_recover(self):\n if self.sim_is_activate:\n if self.sim_is_running:\n sim.simxStopSimulation(self.clientID, sim.simx_opmode_oneshot)\n time.sleep(0.5)\n sim.simxStartSimulation(self.clientID, sim.simx_opmode_oneshot)\n else:\n print('Simulation was not started')\n else:\n print('You need to activate the simulation before recover it')\n \n\n \n","sub_path":"Simulation/CoppeliaSim_env.py","file_name":"CoppeliaSim_env.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"241082051","text":"import datetime\nimport os\nimport uuid\nfrom django.contrib.auth import get_user_model\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom markdown2 import markdown\nfrom martor.models import MartorField\nfrom mptt.models import MPTTModel, TreeForeignKey\nfrom django.utils.translation import ugettext_lazy as _\n\nIMAGES_UPLOAD_FOLDER = 'uploads/news'\n\n\ndef get_image_upload_path(instance, filename):\n ext = filename.split('.')[-1]\n filename = \"%s.%s\" % (uuid.uuid4(), ext)\n path_by_date = datetime.datetime.today().strftime('/%Y/%m/%d/')\n path = \"{0}{1}\".format(IMAGES_UPLOAD_FOLDER, path_by_date)\n os.makedirs(path, mode=0o755, exist_ok=True)\n return os.path.join(path, filename)\n\n\nclass PostQuerySet(models.QuerySet):\n def published(self):\n return self.filter(is_published=True)\n\n\nclass Post(models.Model):\n CONTENT_SEPARATOR = ''\n category = TreeForeignKey('Category',\n null=True,\n blank=True,\n on_delete=models.CASCADE)\n author = models.ForeignKey(get_user_model(),\n editable=False,\n verbose_name=_('Author'),\n related_name='posts', # user.entries.posts()\n on_delete=models.CASCADE)\n image = models.ImageField(upload_to=get_image_upload_path,\n blank=True,\n help_text=_('Post image'),\n verbose_name=_('Post image'))\n title = models.CharField(max_length=255,\n help_text=_('255 characters'),\n verbose_name=_('Title'))\n slug = models.SlugField(unique_for_date='created_at',\n help_text=_('Post slug, unique for post date'),\n verbose_name=_('Slug'))\n markdown_content = MartorField()\n html_excerpt = models.TextField(editable=False,\n blank=True)\n html_content = models.TextField(editable=False,\n blank=True)\n tags = models.ManyToManyField('Tag',\n verbose_name=_('Tags'),\n blank=True,\n related_name='all') # tag.entries.all()\n created_at = models.DateTimeField(auto_now=False,\n auto_now_add=False,\n default=timezone.now,\n verbose_name=_('Publication date'))\n is_published = models.BooleanField(default=False,\n verbose_name=_('Published'))\n hits = models.IntegerField(default=0, editable=False)\n objects = PostQuerySet.as_manager()\n\n class Meta:\n verbose_name = _('Post')\n verbose_name_plural = _('Posts')\n ordering = ('-created_at',)\n\n def __str__(self):\n return self.title\n\n def get_absolute_url(self):\n return reverse('news:post-details', args=[\n int(self.created_at.year), int(self.created_at.month),\n int(self.created_at.day), str(self.slug)\n ])\n\n def add_hits(self):\n # Posts view counter\n if self.hits is not None:\n self.hits += 1\n self.save()\n else:\n self.hits = 0\n\n def save(self, *args, **kwargs):\n extras = {\n 'fenced-code-blocks': None,\n 'highlightjs-lang': None,\n 'html-classes': {'img': 'img-fluid'},\n 'spoiler': None,\n 'strike': None,\n 'tables': None,\n }\n if self.CONTENT_SEPARATOR in self.markdown_content:\n excerpt, content = self.markdown_content.split(\n self.CONTENT_SEPARATOR, 1)\n self.html_excerpt = markdown(excerpt, extras=extras)\n self.html_content = markdown(content, extras=extras)\n else:\n self.html_excerpt = ''\n self.html_content = markdown(self.markdown_content, extras=extras)\n\n super(Post, self).save()\n\n\nclass Category(MPTTModel):\n title = models.CharField(max_length=50, unique=True)\n parent = TreeForeignKey('self', null=True, blank=True,\n related_name='children',\n db_index=True,\n on_delete=models.CASCADE)\n slug = models.SlugField()\n path = models.TextField(unique=True, null=True, editable=False) # full category path\n\n class MPTTMeta:\n order_insertion_by = ['title']\n\n class Meta:\n unique_together = ('parent', 'slug',)\n verbose_name = _('Category')\n verbose_name_plural = _('Categories')\n\n def get_path(self):\n try:\n ancestors = self.get_ancestors(include_self=True)\n except self.DoesNotExist:\n ancestors = []\n else:\n ancestors = [item.slug for item in ancestors]\n return '/'.join(ancestors)\n\n def save(self, *args, **kwargs):\n super(Category, self).save()\n self.path = self.get_path()\n super(Category, self).save()\n\n def __str__(self):\n return self.title\n\n\nclass Tag(models.Model):\n tag_title = models.CharField(max_length=255,\n help_text=_('255 symbols max'),\n verbose_name=_('Tag name'))\n tag_slug = models.SlugField(unique=True,\n verbose_name=_('Slug'))\n\n class Meta:\n verbose_name = _('Tag')\n verbose_name_plural = _('Tags')\n\n def __str__(self):\n return self.tag_title\n","sub_path":"news/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"340468051","text":"#!/usr/bin/python\nimport os\nimport random\nimport dircache\nimport urllib2\nimport urllib\nfrom xml.etree import ElementTree as ET\n\n# this script will grab a heap of images from sources and then randomly change them\n# Chris Harris\n# 2016\n\npicDir = '/home/charris/Pictures/wallpapers'\ncmd = '/usr/bin/gsettings set org.gnome.desktop.background picture-uri file://$(find DIR -type f | shuf -n1`)'\nfilename = random.choice(dircache.listdir(picDir))\npic = os.path.join(picDir, filename)\ncmd = '/usr/bin/gsettings set org.gnome.desktop.background picture-uri file://%s' % pic\n#src_url = 'http://www.bing.com/HPImageArchive.aspx?format=xml&idx=16&n=8&mkt=en-AU'\nsrc_url = 'http://www.bing.com/HPImageArchive.aspx?format=xml&idx=16&n=8&mkt=en-CZ'\ntarget_url = 'http://www.bing.com'\nfiles_to_get = []\n\ndef get_tags(xml_object):\n ftg = []\n doc = ET.fromstring(xml_object)\n for server in doc.findall('image'):\n host = server.find('./url').text\n ftg.append(host)\n return ftg\n \ndef html_get(url):\n res = urllib2.urlopen(url)\n xml = res.read()\n return xml\n\ndef download_files():\n for files in files_to_get:\n src = target_url + '/' + files\n dest = picDir + '/' + os.path.basename(files)\n if not os.path.isfile(dest): # if the file already exists dont download it\n urllib.urlretrieve( src, dest )\n\n# grab the webpage that has the files to download\n# if there is data to parse then parse the file\n# and download files if they dont already exist\nxml_data = html_get(src_url)\nif len(xml_data) > 39:\n files_to_get = get_tags(xml_data)\n if len(files_to_get) > 0:\n download_files()\n \n#change the desktop wallpaper to a random one from the wallpapers directory\nos.system(cmd)\n\n","sub_path":"gnome3-switcher.py","file_name":"gnome3-switcher.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"276892280","text":"import os\n\ndef touch_dirname(path):\n \"\"\"Ensure that the directory part of a path exists.\"\"\"\n dn = os.path.dirname(path) \n if not os.path.isdir(dn):\n os.makedirs(dn)\n\ndef get_nodefile_path(root, nodename, timestamp):\n \"\"\"Get nodefile path as a function of the date and time.\"\"\"\n parts = dict((k, getattr(timestamp, k)) for k in ('year', 'month', 'day', 'hour'))\n parts.update(nodename = nodename)\n format = \"%(year)4d_%(month)02d/%(nodename)s-%(year)4d_%(month)02d_%(day)02d-%(hour)02d.csv\"\n subdir = format % parts\n path = os.path.join(root, subdir)\n touch_dirname(path)\n return path","sub_path":"storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"467718146","text":"import re\nimport time\nfrom pymysql import *\nimport urllib.parse\nimport json\n\n\n\"\"\"\ng_url_func = {\n \"/index.py\": index,\n \"/center.py\": center\n}\n\"\"\"\ng_url_func = dict()\n\ndef route(url):\n def set_func(func):\n\n # key:/index.py\n # value: index\n g_url_func[url] = func\n\n def call_func():\n func()\n return call_func\n return set_func\n\n# ajax接口\n@route(r\"/index_data\")\ndef index(file_name,url_param=None,url=None): \n \n db = connect(host='localhost',port=3306,user='root',password='mysql',database='stock_db',charset='utf8')\n # 获得Cursor对象\n cursor = db.cursor()\n sql = \"\"\"select * from info;\"\"\"\n cursor.execute(sql)\n data_from_mysql = cursor.fetchall()\n cursor.close()\n db.close()\n\n jsonData = []\n\n for row in data_from_mysql:\n result = {}\n result['id'] = str(row[0])\n result['code'] = str(row[1])\n result['sname'] = str(row[2])\n result['rate01'] = str(row[3])\n result['rate02'] = str(row[4])\n result['new_prize'] = str(row[5])\n result['high'] = str(row[6])\n result['date'] = str(row[7])\n jsonData.append(result)\n\n content = json.dumps(jsonData)\n return content\n\n# jsonp接口\n@route(r\"/index_jsonp_data\")\ndef index_jsonp(file_name,url_param,url=None):\n\n # callback=jQuery1124018787969015631711_1522330257607&_=1522330257608\n dat_arr = re.split('[=&]',url_param)\n fnName = dat_arr[1] \n \n db = connect(host='localhost',port=3306,user='root',password='mysql',database='stock_db',charset='utf8')\n # 获得Cursor对象\n cursor = db.cursor()\n sql = \"\"\"select * from info;\"\"\"\n cursor.execute(sql)\n data_from_mysql = cursor.fetchall()\n cursor.close()\n db.close()\n\n jsonData = []\n\n for row in data_from_mysql:\n result = {}\n result['id'] = str(row[0])\n result['code'] = str(row[1])\n result['sname'] = str(row[2])\n result['rate01'] = str(row[3])\n result['rate02'] = str(row[4])\n result['new_prize'] = str(row[5])\n result['high'] = str(row[6])\n result['date'] = str(row[7])\n jsonData.append(result)\n\n content = json.dumps(jsonData)\n content = fnName + '(' + str(content) + ')'\n return content\n\n# ajax接口\n@route(r\"/center_data\")\ndef center(file_name,url_param=None,url=None):\n\n # data_from_mysql = \"这是数据库中的数据信息。。。。。。\"\n # 创建Connection连接\n db = connect(host='localhost',port=3306,user='root',password='mysql',database='stock_db',charset='utf8')\n # 获得Cursor对象\n cursor = db.cursor()\n sql = \"\"\"select i.code,i.short,i.chg,i.turnover,i.price,i.highs,f.note_info from info as i inner join focus as f on f.info_id=i.id;\"\"\"\n cursor.execute(sql)\n data_from_mysql = cursor.fetchall()\n cursor.close()\n db.close()\n\n jsonData = []\n\n for row in data_from_mysql:\n result = {}\n result['code'] = str(row[0])\n result['sname'] = str(row[1])\n result['rate01'] = str(row[2])\n result['rate02'] = str(row[3])\n result['new_prize'] = str(row[4])\n result['high'] = str(row[5])\n result['bak'] = str(row[6])\n jsonData.append(result)\n\n content = json.dumps(jsonData)\n return content\n\n# ajax接口\n@route(r\"/update_data\")\ndef update(file_name,url_param,url=None):\n \"\"\"显示修改新的页面\"\"\"\n\n stock_code = url_param.split('=')[1] \n\n db = connect(host='localhost',port=3306,user='root',password='mysql',database='stock_db',charset='utf8')\n # 获得Cursor对象\n cursor = db.cursor()\n sql = \"\"\"select note_info from focus where info_id = (select id from info where code=\"%s\");\"\"\" % stock_code\n cursor.execute(sql)\n data_from_mysql = cursor.fetchone() # ----> (\"描述\",)\n cursor.close()\n db.close()\n\n result = {}\n result['code'] = stock_code\n result['info'] = data_from_mysql[0]\n\n content = json.dumps(result) \n\n return content\n\n\n# ajax接口\n@route(r\"/change_data\")\ndef update_note_info(file_name,url_param,url=None):\n \"\"\"显示修改新的页面\"\"\"\n dat_arr = re.split('[=&]',url_param)\n stock_code = dat_arr[1]\n stock_note_info = urllib.parse.unquote(dat_arr[3])\n\n # data_from_mysql = \"这是数据库中的数据信息。。。。。。\"\n # 创建Connection连接\n db = connect(host='localhost',port=3306,user='root',password='mysql',database='stock_db',charset='utf8')\n # 获得Cursor对象\n cursor = db.cursor()\n sql = \"\"\"update focus set note_info = \"%s\" where info_id = (select id from info where code=\"%s\");\"\"\" % (stock_note_info, stock_code)\n cursor.execute(sql)\n db.commit()\n cursor.close()\n db.close()\n\n return \"更新成功\"\n\n\n# ajax接口\n@route(r\"/add_data\")\ndef update_note_info(file_name, url_param, url=None):\n \n stock_code = url_param.split('=')[1] \n\n # 创建Connection连接\n db = connect(host='localhost',port=3306,user='root',password='mysql',database='stock_db',charset='utf8')\n # 获得Cursor对象\n cursor = db.cursor()\n sql = \"\"\"select * from focus where info_id = (select id from info where code=\"%s\");\"\"\" % (stock_code)\n cursor.execute(sql)\n\n if cursor.fetchone():\n cursor.close()\n db.close()\n return \"请不要重复添加\"\n\n sql = \"\"\"insert into focus (info_id) select id from info where code=\"%s\";\"\"\" % (stock_code)\n cursor.execute(sql)\n db.commit()\n cursor.close()\n db.close()\n\n return \"关注成功\"\n\n# ajax接口\n@route(r\"/del_data\")\ndef delete(file_name, url_param, url=None):\n\n stock_code = url_param.split('=')[1]\n\n # 创建Connection连接\n db = connect(host='localhost',port=3306,user='root',password='mysql',database='stock_db',charset='utf8')\n # 获得Cursor对象\n cursor = db.cursor()\n sql = \"\"\"delete from focus where info_id = (select id from info where code=\"%s\");\"\"\" % (stock_code)\n cursor.execute(sql)\n db.commit()\n cursor.close()\n db.close()\n\n return \"取消关注成功\"\n\n\ndef app(environ, start_response):\n status = '200 OK'\n response_headers = [('Content-Type', 'text/html')]\n start_response(status, response_headers)\n\n # 取出浏览器传递给web服务器的url中的 请求资源路径\n # /a/b/c/index.html\n file_name = environ['PATH_INFO']\n url_param = environ['URL_DAT'] \n\n try:\n # /update/300268.html\n # r\"/update/\\d*\\.html\"\n # g_url_func = {\n # r\"/index\\.html\":index,\n # r\"/center\\.html\":center,\n # r\"/update/\\d*\\.html\":update,\n # }\n\n for url, call_func in g_url_func.items():\n ret = re.match(url, file_name)\n if ret:\n return call_func(file_name,url_param,url)\n else:\n return \"没有要访问的页面,请求的页面是:%s\" % file_name\n except Exception as ret:\n return \"%s,,,,,%s\" % (str(environ), ret)\n","sub_path":"front-end_day11_code_vue/miniweb/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":6937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"476274294","text":"import numpy\r\nimport pyaudio\r\nimport nidaqmx as dq\r\nimport math\r\nimport time\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\nfrom tkinter import filedialog\r\nfrom tkinter import simpledialog\r\nfrom tkinter import font\r\nfrom tkinter import ttk\r\nimport _thread\r\n#---------------------------------------------------------#\r\nGRW = 1000\r\nGRH = 500\r\nXOL = 20\r\nYOT = 25\r\nCANVASwidth = GRW + 2 * XOL\r\nCANVASheight = GRH + 2 * YOT + 48\r\nYmin = YOT\r\nYmax = YOT + GRH\r\nLONGsweep = False\r\nLONGchunk = LONGsweep\r\nSamplelist = [1000, 2000, 2500, 5000, 7500, 10000, 20000, 40000]\r\nCHvdiv = [0.01, 0.1, 1.0, 10.0, 20.0, 50.0, 100.0, 1000.0] # Sensitivity list in mv/div\r\nTIMEdiv = [0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0] # Time list in ms/div\r\nADzero = False\r\nCOLORframes = \"#000080\" # Color = \"#rrggbb\" rr=red gg=green bb=blue, Hexadecimal values 00 - ff\r\nCOLORcanvas = \"#000000\"\r\nCOLORgrid = \"#808080\"\r\nCOLORzeroline = \"#0000ff\"\r\nCOLORtrace1 = \"#00ff00\"\r\nCOLORtrace2 = \"#ff8000\"\r\nCOLORtext = \"#ffffff\"\r\nCOLORtrigger = \"#ff0000\"\r\nButtonwidth1 = 12\r\nButtonwidth2 = 12\r\nTRACES = 1\r\nTRACESread = 0\r\nRUNstatus = 1\r\nSAMPLErate = 15000\r\nDevicedict = {}\r\noutput = True\r\nflag = True\r\nmode = 0\r\n#-------------------------------------------------------------------------------\r\nDevicename1 = []\r\nDevicename2 = []\r\nDevicedict = {}\r\n\r\n\r\n\r\nclass channels:\r\n global NItask\r\n def __init__(self):\r\n self.timediv = 6\r\n self.chdiv = len(CHvdiv) - 1\r\n self.Tline = []\r\n self.AUDIOsignal = []\r\n self.Triggerline = []\r\n self.SHOWsamples = GRW\r\n self.NItask = None\r\n self.stream = None\r\n self.CurDeviceName = None\r\n self.offset = 0\r\n self.AUDIOdevin = None\r\n self.ADsens = 1000\r\n self.audiosize = int (SAMPLErate * TIMEdiv[self.timediv] * 10 /1000)\r\n self.PA = None\r\n self.triggerlevel = -200\r\n self.outputtask = dq.Task()\r\n def setaudiosize(self):\r\n self.audiosize = int (SAMPLErate * TIMEdiv[self.timediv] * 10 / 1000)\r\n def maketrace(self, c):\r\n global XOL\r\n global YOT\r\n global GRW\r\n global GRH\r\n global Ymin\r\n global Ymax\r\n global TRACES\r\n global RUNstatus\r\n global CHvdiv\r\n global TIMEdiv\r\n global SAMPLErate\r\n TRACEsize = len(self.AUDIOsignal)\r\n # print(TRACEsize)\r\n # print(self.AUDIOsignal)\r\n if TRACEsize == 0:\r\n self.Tline = []\r\n return()\r\n Yconv = float(GRH / 10) * 1000 / (self.ADsens * CHvdiv[self.chdiv])\r\n self.SHOWsamples = SAMPLErate * 10 * TIMEdiv[self.timediv] / 1000\r\n self.Tline = []\r\n t = 0\r\n x = 0\r\n Tstep = 0\r\n if (self.SHOWsamples >= GRW):\r\n self.SHOWsamples = GRW\r\n Tstep = (int)(self.SHOWsamples/ GRW)\r\n if (self.SHOWsamples < GRW):\r\n expand = []\r\n n = int(GRW / self.SHOWsamples) + 1\r\n for o in range(0, len(self.AUDIOsignal)):\r\n for i in range(0,n):\r\n expand.append(self.AUDIOsignal[o])\r\n self.AUDIOsignal = expand\r\n Tstep = 1\r\n Xstep = 1\r\n x1 = 0\r\n y1 = 0.0\r\n while(x <= GRW):\r\n x1 = x + XOL\r\n y = float(self.AUDIOsignal[t])\r\n ytemp = int(c - Yconv * y)\r\n if (ytemp < Ymin):\r\n ytemp = Ymin\r\n if (ytemp > Ymax):\r\n ytemp = Ymax\r\n self.Tline.append(int(x1))\r\n self.Tline.append(int(ytemp))\r\n t = t + Tstep\r\n x = x + Xstep\r\n x1 = XOL\r\n y1 =int(c - Yconv * float(0))\r\n if (y1 < Ymin):\r\n y1 = Ymin\r\n if (y1 > Ymax):\r\n y1 = Ymax\r\n print(self.Tline)\r\n self.Triggerline.append(int(XOL - 5))\r\n self.Triggerline.append(int(y1))\r\n self.Triggerline.append(int(XOL + 5))\r\n self.Triggerline.append(int(y1))\r\nchannel1 = channels()\r\n# channel2 = channels()\r\n\r\ndef generate():\r\n global channel1\r\n global mode\r\n global RUNstatus\r\n while True:\r\n if mode == 1 or mode == 2:\r\n width = 0.01\r\n period = 0.1 - (width*6)\r\n if (RUNstatus == 0):\r\n while True:\r\n a = 0\r\n if RUNstatus == 1:\r\n while channel1.CurDeviceName == None or channel1.outputtask == None:\r\n a = 0\r\n try:\r\n channel1.outputtask.close()\r\n except:\r\n pass\r\n try:\r\n channel1.outputtask = dq.Task()\r\n channel1.outputtask.do_channels.add_do_chan(channel1.CurDeviceName[:-3] + \"port0/line0\")\r\n except:\r\n pass\r\n if RUNstatus == 2 :\r\n channel1.outputtask.start()\r\n start0 = time.time()\r\n for i in range(0, 3):\r\n start = time.time()\r\n channel1.outputtask.write(True)\r\n while (time.time() - start < width):\r\n a = 1\r\n # time.sleep(width - 0.0025)\r\n start = time.time()\r\n channel1.outputtask.write(False)\r\n while (time.time() - start < width):\r\n a = 1\r\n\r\n while (time.time() - start0 < period):\r\n a = 1\r\n # time.sleep( period - 2*width*3)\r\n channel1.outputtask.stop()\r\n if RUNstatus == 3 or RUNstatus == 4:\r\n channel1.outputtask.close()\r\n channel1.outputtask = None\r\n\r\n\r\ndef BTrigger1():\r\n channel1.triggerlevel -= CHvdiv[channel1.chdiv] / 10\r\n print(channel1.triggerlevel)\r\n RUNstatus = 1\r\n UpdateScreen()\r\n\r\ndef BTrigger2():\r\n channel1.triggerlevel += CHvdiv[channel1.chdiv] / 10\r\n print(channel1.triggerlevel)\r\n RUNstatus = 1\r\n UpdateScreen()\r\n\r\ndef BStart():\r\n global RUNstatus\r\n if (RUNstatus == 0):\r\n RUNstatus = 1\r\n UpdateScreen()\r\n\r\n\r\ndef BTime1(channel : channels):\r\n global RUNstatus\r\n if (channel.timediv >= 1):\r\n channel.timediv = channel.timediv - 1\r\n if RUNstatus == 2:\r\n RUNstatus = 4\r\n UpdateTrace()\r\n\r\ndef BTime2(channel : channels):\r\n global RUNstatus\r\n global TIMEdiv\r\n if (channel.timediv < len(TIMEdiv) - 1):\r\n channel.timediv = channel.timediv + 1\r\n if RUNstatus == 2:\r\n RUNstatus = 4\r\n UpdateTrace()\r\n\r\ndef BCHlevel1(channel : channels):\r\n global RUNstatus\r\n if (channel.chdiv >= 1):\r\n channel.chdiv = channel.chdiv - 1\r\n UpdateTrace()\r\n\r\ndef BCHlevel2(channel : channels):\r\n global RUNstatus\r\n if (channel.chdiv < len(CHvdiv) - 1):\r\n channel.chdiv = channel.chdiv + 1\r\n UpdateTrace()\r\n\r\n\r\ndef BSetup(*args):\r\n global ADzero\r\n global SAMPLErate\r\n global RUNstatus\r\n\r\n\r\n s = title.get()\r\n if (s == None): # If Cancel pressed, then None\r\n return ()\r\n\r\n try: # Error if for example no numeric characters or OK pressed without input (s = \"\"), then v = 0\r\n v = int(s)\r\n except:\r\n v = 0\r\n\r\n if v != 0:\r\n SAMPLErate = v\r\n print(SAMPLErate)\r\n if (RUNstatus == 2):\r\n RUNstatus = 4\r\n UpdateScreen()\r\n\r\ndef AUDIOin():\r\n global channel1\r\n global channel2\r\n global RUNstatus\r\n global mode\r\n while(True):\r\n channel1.setaudiosize()\r\n # channel2.setaudiosize()\r\n if (channel1.AUDIOdevin == None):\r\n RUNstatus = 0\r\n if (RUNstatus == 1):\r\n Action1(channel1)\r\n #UpdateScreen()\r\n if (RUNstatus == 2 ):\r\n if mode == 2 or mode == 0:\r\n Action2(channel1)\r\n elif mode == 1:\r\n channel1.AUDIOsignal = numpy.zeros(int(1.5 * channel1.audiosize),dtype=numpy.bool)\r\n MakeScreen()\r\n # if (TRACES == 2):\r\n # Action2(channel2)\r\n if (RUNstatus == 3) or (RUNstatus == 4):\r\n Action3(channel1)\r\n if (TRACES == 2):\r\n Action3(channel2)\r\n UpdateAll()\r\n root.update_idletasks()\r\n root.update()\r\n\r\ndef Action1(channel : channels):\r\n global RUNstatus\r\n global output\r\n global flag\r\n if (channel.AUDIOdevin != None):\r\n PA = pyaudio.PyAudio()\r\n FORMAT = pyaudio.paInt16\r\n chunkbuffer = int(3000)\r\n if (channel.AUDIOdevin < 15):\r\n try:\r\n channel.stream = PA.open(format=FORMAT,\r\n channels=TRACES,\r\n rate=SAMPLErate,\r\n input=True,\r\n output=False,\r\n frames_per_buffer=int(chunkbuffer),\r\n input_device_index=channel.AUDIOdevin)\r\n RUNstatus = 2\r\n except:\r\n RUNstatus = 0\r\n txt = \"Something wrong when creating stream for the device\"\r\n messagebox.showerror(\"Cannot open Audio Stream\", txt)\r\n else:\r\n try:\r\n channel.NItask.close()\r\n except:\r\n pass\r\n channel.NItask = dq.Task()\r\n for i in Devicedict.keys():\r\n if Devicedict.get(i) == channel.AUDIOdevin:\r\n channel.CurDeviceName = i\r\n break\r\n try:\r\n addedChan = False\r\n for i in channel.NItask.ai_channels:\r\n if i.name == channel.CurDeviceName:\r\n addedChan = True\r\n if addedChan == False:\r\n channel.NItask.ai_channels.add_ai_voltage_chan(channel.CurDeviceName)\r\n channel.NItask.start()\r\n flag = True\r\n RUNstatus = 2\r\n except Exception as e:\r\n RUNstatus = 0\r\n txt = \"Task cannot be created, check the device connection and channel name\"\r\n messagebox.showerror(\"Error when creating NI tasks\", txt)\r\n print(e)\r\n\r\n\r\n\r\ndef Action2(channel : channels):\r\n global RUNstatus\r\n global output\r\n AUDIOsignals = []\r\n if (channel.AUDIOdevin != None):\r\n if (channel.AUDIOdevin < 15):\r\n while len(AUDIOsignals) < channel.audiosize:\r\n buffervalue = channel.stream.get_read_available()\r\n if buffervalue > 1024:\r\n signals = channel.stream.read(buffervalue)\r\n AUDIOsignals.extend(numpy.fromstring(signals, \"Int16\"))\r\n else:\r\n while len(AUDIOsignals) < 1.5 * channel.audiosize:\r\n signals = channel.NItask.read(80)\r\n for i in range(0, len(signals)):\r\n signals[i] = signals[i] * 1000\r\n AUDIOsignals.extend(signals)\r\n channel.NItask.stop()\r\n while (len(AUDIOsignals) > 0 and AUDIOsignals[0] < channel.triggerlevel):\r\n del AUDIOsignals[0]\r\n channel.AUDIOsignal = AUDIOsignals\r\n # MakeScreen()\r\ndef Action3(channel : channels):\r\n global RUNstatus\r\n global flag\r\n if (channel.AUDIOdevin != None):\r\n if (channel.AUDIOdevin < 15):\r\n channel.stream.stop_stream()\r\n channel.stream.close()\r\n else:\r\n channel.NItask.close()\r\n channel.NItask = None\r\n # flag = False\r\n\r\n if (channel.PA != None):\r\n channel.PA.terminate()\r\n if RUNstatus == 3:\r\n RUNstatus = 0\r\n if RUNstatus == 4:\r\n RUNstatus = 1\r\n\r\ndef UpdateAll():\r\n CalculateData()\r\n MakeTrace()\r\n UpdateScreen()\r\n\r\ndef UpdateTrace():\r\n MakeTrace()\r\n UpdateScreen()\r\n\r\ndef UpdateScreen():\r\n MakeScreen()\r\n root.update()\r\n\r\ndef MakeScreen():\r\n global XOL\r\n global YOT\r\n global GRW\r\n global GRH\r\n global Ymin\r\n global Ymax\r\n global CHvdiv\r\n global TIMEdiv\r\n global CANVASwidth\r\n global CANVASheight\r\n global ADsens\r\n global SAMPLErate\r\n global channel1\r\n global channel2\r\n de = ca.find_enclosed(0, 0, CANVASwidth + 1000, CANVASheight + 1000)\r\n for n in de:\r\n ca.delete(n)\r\n i = 0\r\n x1 = XOL\r\n x2 = XOL + GRW\r\n while (i < 11):\r\n y = YOT + i * GRH / 10\r\n Dline = [x1, y, x2, y]\r\n ca.create_line(Dline, fill=COLORgrid)\r\n i = i + 1\r\n if TRACES == 1:\r\n y = YOT + 5 * GRH / 10\r\n Dline = [x1, y, x2, y]\r\n ca.create_line(Dline, fill = COLORzeroline)\r\n if TRACES == 2:\r\n y = YOT + GRH / 4\r\n Dline = [x1,y,x2,y]\r\n ca.create_line(Dline, fill=COLORzeroline) # Blue horizontal line 1 for 2 traces\r\n y = YOT + 3 * GRH / 4\r\n Dline = [x1,y,x2,y]\r\n ca.create_line(Dline, fill=COLORzeroline)\r\n i = 0\r\n y1 = YOT\r\n y2 = YOT + GRH\r\n while (i < 11):\r\n x = XOL + i * GRW / 10\r\n Dline = [x, y1, x, y2]\r\n ca.create_line(Dline, fill=COLORgrid)\r\n i = i + 1\r\n vx = TIMEdiv[channel1.timediv]\r\n if vx >= 1000:\r\n txt = str(int(vx / 1000)) + \"s/div\"\r\n if vx < 1000 and vx >= 1:\r\n txt = str(int(vx)) + \"ms/div\"\r\n if vx < 1:\r\n txt = \"0.\" + str(int(vx * 10)) + \"ms/div\"\r\n if vx <= 0.01:\r\n txt = \"0.\" + \"0\" + str(int(vx * 100)) + \"ms/div\"\r\n x = XOL\r\n y = YOT + GRH + 12\r\n ca.create_text(x, y, text= txt, anchor = W, fill = COLORtext)\r\n vy = CHvdiv[channel1.chdiv]\r\n txt = \"\"\r\n if vy >= 1000:\r\n txt = txt + str(int(vy/1000)) + \" V/div\"\r\n if vy < 1000 and vy >= 1:\r\n txt = txt + str(int(vy)) + \" mV/div\"\r\n if vy < 1:\r\n txt = txt + \"0.\" + str(int(vy * 10)) + \" mV/div\"\r\n x = XOL\r\n y = YOT+GRH+24\r\n idTXT = ca.create_text (x, y, text=txt, anchor=W, fill=COLORtext)\r\n txt = \"\"\r\n # vx = TIMEdiv[channel2.timediv]\r\n # if vx >= 1000:\r\n # txt = str(int(vx / 1000)) + \"s/div\"\r\n # if vx < 1000 and vx >= 1:\r\n # txt = str(int(vx)) + \"ms/div\"\r\n # if vx < 1:\r\n # txt = \"0.\" + str(int(vx * 10)) + \"ms/div\"\r\n # if vx <= 0.01:\r\n # txt = \"0.\" + \"0\" + str(int(vx * 100)) + \"ms/div\"\r\n # x = XOL\r\n # y = YOT + GRH + 36\r\n # ca.create_text(x, y, text= txt, anchor = W, fill = COLORtext)\r\n # txt = \"\"\r\n # vy = CHvdiv[channel2.chdiv]\r\n # txt = \"\"\r\n # if vy >= 1000:\r\n # txt = txt + str(int(vy/1000)) + \" V/div\"\r\n # if vy < 1000 and vy >= 1:\r\n # txt = txt + str(int(vy)) + \" mV/div\"\r\n # if vy < 1:\r\n # txt = txt + \"0.\" + str(int(vy * 10)) + \" mV/div\"\r\n # x = XOL\r\n # y = YOT+GRH+48\r\n # idTXT = ca.create_text (x, y, text=txt, anchor=W, fill=COLORtext)\r\n if (len(channel1.Tline) > 4):\r\n ca.create_line(channel1.Tline, fill = COLORtrace1)\r\n # if (TRACES == 2):\r\n # if (len(channel2.Tline) > 4):\r\n # ca.create_line(channel2.Tline, fill = COLORtrace2)\r\n i = 0\r\ndef MakeTrace():\r\n global channel1\r\n global channel2\r\n global XOL\r\n global YOT\r\n global GRW\r\n global GRH\r\n global Ymin\r\n global Ymax\r\n global TRACES\r\n global RUNstatus\r\n global CHvdiv\r\n global TIMEdiv\r\n global SAMPLErate\r\n if len(channel1.AUDIOsignal) == 0:\r\n return\r\n Yconv1 = float(GRH / 10) * 1000 / (channel1.ADsens * CHvdiv[channel1.chdiv])\r\n if (TRACES == 1):\r\n c1 = GRH / 2 + YOT - channel1.offset\r\n if (TRACES == 2):\r\n c1 = GRH / 4 + YOT - channel1.offset\r\n c2 = 3 * GRH / 4 + YOT - channel2.offset\r\n channel2.maketrace(c = c2)\r\n channel1.maketrace(c = c1)\r\n\r\n\r\n\r\n\r\n\r\ndef ReadInDevice():\r\n global Devicename1\r\n global Devicename2\r\n global Devicedict\r\n Devicename1 = []\r\n Devicename2 = []\r\n PA = pyaudio.PyAudio()\r\n s = PA.get_device_info_by_index(0)\r\n Devicedict[s['name']] = s['index']\r\n Devicename1.append(s['name'])\r\n nisystem = dq.system.System.local()\r\n nidenum = len(nisystem.devices)\r\n n = 15\r\n for i in range(nidenum):\r\n channels = nisystem.devices[i].ai_physical_chans\r\n cnum = len(channels)\r\n for j in range(cnum):\r\n Devicename1.append(channels[j].name)\r\n Devicedict[channels[j].name] = n\r\n n = n + 1\r\n PA.terminate()\r\n Devicename2 = Devicename1\r\n Devicebox1['values'] = Devicename1\r\n # Devicebox2['values'] = Devicename2\r\n\r\ndef change(*args):\r\n global channel1\r\n global RUNstatus\r\n s = Devicebox1.get()\r\n channel1.AUDIOdevin = Devicedict[s]\r\n print(s + \":\" + str(channel1.AUDIOdevin))\r\n if (RUNstatus == 2) or RUNstatus == 1:\r\n RUNstatus = 4\r\n RUNstatus = 1\r\n\r\ndef Bmode0():\r\n global mode\r\n global RUNstatus\r\n mode = 0\r\n if RUNstatus == 2 or RUNstatus == 1:\r\n RUNstatus = 4\r\n RUNstatus = 1\r\n\r\ndef Bmode1():\r\n global mode\r\n global RUNstatus\r\n mode = 1\r\n if RUNstatus == 2 or RUNstatus == 1:\r\n RUNstatus = 4\r\n RUNstatus = 1\r\ndef Bmode2():\r\n global mode\r\n global RUNstatus\r\n mode = 1\r\n if RUNstatus == 2 or RUNstatus == 1:\r\n RUNstatus = 4\r\n RUNstatus = 1\r\n mode = 2\r\n\r\n# def change_1(*args):\r\n# global channel2\r\n# global RUNstatus\r\n# s = Devicebox2.get()\r\n# channel2.AUDIOdevin = Devicedict[s]\r\n# print(s + \":\" + str(channel2.AUDIOdevin))\r\n# if (RUNstatus == 2):\r\n# RUNstatus = 4\r\n# RUNstatus = 1\r\n\r\n\r\ndef CalculateData():\r\n return()\r\n\r\ndef BStop():\r\n global RUNstatus\r\n if (RUNstatus == 1):\r\n RUNstatus = 0\r\n elif (RUNstatus == 2):\r\n RUNstatus = 3\r\n elif (RUNstatus == 3):\r\n RUNstatus = 3\r\n elif (RUNstatus == 4):\r\n RUNstatus = 3\r\n\r\n# def BTraces():\r\n# global TRACES\r\n# global RUNstatus\r\n#\r\n# if (TRACES == 1):\r\n# TRACES = 2\r\n# else:\r\n# TRACES = 1\r\n#\r\n# if RUNstatus == 2: # Restart if running\r\n# RUNstatus = 1\r\n\r\nroot = Tk()\r\nroot.title(\"OscilloscopeV02a.py(w) (13-10-2018): Audio Oscilloscope\")\r\nroot.minsize(100, 100)\r\ntitle = StringVar()\r\ntitle.set(10000)\r\nframe1 = Frame(root, background=COLORframes, borderwidth=5, relief=RIDGE)\r\nframe1.pack(side=LEFT, expand=1, fill=Y)\r\n\r\nframe2 = Frame(root, background=\"black\", borderwidth=5, relief=RIDGE)\r\nframe2.pack(side=TOP, expand=1, fill=X)\r\n\r\nframe3 = Frame(root, background=COLORframes, borderwidth=5, relief=RIDGE)\r\nframe3.pack(side=TOP, expand=1, fill=X)\r\n\r\nca = Canvas(frame2, width=CANVASwidth, height=CANVASheight, background=COLORcanvas)\r\nca.pack(side=TOP)\r\n\r\n# b = Button(frame1, text=\"1/2 Channels\", width=Buttonwidth1, command=BTraces)\r\n# b.pack(side=LEFT, padx=5, pady=5)\r\nb = Button(frame1, text = \"trigger+\", width = Buttonwidth2, command = BTrigger2)\r\nb.pack(side = TOP, padx = 10, pady = 10)\r\nb = Button(frame1, text = \"trigger-\", width = Buttonwidth2, command = BTrigger1)\r\nb.pack(side = TOP, padx = 10, pady = 10)\r\nb = Button(frame1, text=\"mode1\", width=Buttonwidth2, command=Bmode0)\r\nb.pack(side= TOP, padx=10, pady=10)\r\nb = Button(frame1, text=\"mode2\", width=Buttonwidth2, command=Bmode1)\r\nb.pack(side= TOP, padx=10, pady=10)\r\nb = Button(frame1, text=\"mode3\", width=Buttonwidth2, command=Bmode2)\r\nb.pack(side= TOP, padx=10, pady=10)\r\nb = Label(frame1, text = \"Samplerate\", width = Buttonwidth2,bg = COLORframes, fg = COLORtext)\r\nb.pack(side = TOP, padx = 5, pady = 2)\r\nm=OptionMenu(frame1,title,*Samplelist)\r\nm.config(width=Buttonwidth2-5)\r\nm.pack(side=TOP,padx=5,pady=5)\r\nb = Label(frame1, text = \"Devices\", width = Buttonwidth2,bg = COLORframes, fg = COLORtext)\r\nb.pack(side = TOP, padx = 5, pady = 2)\r\nDevicebox1=ttk.Combobox(frame1, width=Buttonwidth2 - 2, postcommand=ReadInDevice, values=Devicename1, )\r\nDevicebox1.pack(side=TOP, padx=5, pady=2)\r\nDevicebox1.bind(\"<>\",change)\r\n\r\n\r\n\r\nb = Button(frame3, text=\"Start\", width=Buttonwidth2, command=BStart)\r\nb.pack(side=LEFT, padx=5, pady=5)\r\nb = Button(frame3, text=\"Stop\", width=Buttonwidth2, command=BStop)\r\nb.pack(side=LEFT, padx=5, pady=5)\r\n\r\nb = Button(frame3, text=\"-Time\", width=Buttonwidth2, command=lambda : BTime1(channel1))\r\nb.pack(side=LEFT, padx=5, pady=5)\r\n\r\nb = Button(frame3, text=\"+Time\", width=Buttonwidth2, command=lambda : BTime2(channel1))\r\nb.pack(side=LEFT, padx=5, pady=5)\r\n\r\nb = Button(frame3, text=\"-CH1\", width=Buttonwidth2, command= lambda : BCHlevel1(channel1))\r\nb.pack(side=LEFT, padx=5, pady=5)\r\n\r\nb = Button(frame3, text=\"+CH1\", width=Buttonwidth2, command= lambda : BCHlevel2(channel1))\r\nb.pack(side=LEFT, padx=5, pady=5)\r\n# Devicebox2=ttk.Combobox(frame1, width=Buttonwidth1, postcommand=ReadInDevice, values=Devicename2, )\r\n# Devicebox2.pack(side=RIGHT, padx=5, pady=5)\r\n# Devicebox2.bind(\"<>\",change_1)\r\n#l = Label(frame1,text=\"Devices:\",background=\"#000080\",fg=\"#ffffff\")\r\n#l.pack(side=RIGHT, padx=5, pady=5)\r\ntitle.trace_variable('w', BSetup)\r\nif __name__ == '__main__':\r\n root.update()\r\n _thread.start_new(generate, ())\r\n AUDIOin()\r\n\r\n\r\n","sub_path":"4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":20921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"26943184","text":"# 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 preorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n nums = []\n def pre(root):\n if not root:return\n nums.append(root.val)\n pre(root.left)\n pre(root.right)\n pre(root)\n return nums","sub_path":"144_Binary_Tree_Preorder_Traversal.py","file_name":"144_Binary_Tree_Preorder_Traversal.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"250095054","text":"from autoprotocol.protocol import Protocol\n\ndef absorbance(protocol, params):\n plate = protocol.ref(\"new_plate\", None, \"96-flat\", storage=\"cold_4\")\n\n protocol.absorbance(plate, plate.wells_from(0, 1), \"600:nanometer\", \"test_reading\")\n\nif __name__ == '__main__':\n from autoprotocol.harness import run\n run(absorbance, \"Absorbance\")\n","sub_path":"absorbance/absorbance.py","file_name":"absorbance.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"403646871","text":"\"\"\"\n------------------------------------------------------------------------\nLab 3, Task 15\n------------------------------------------------------------------------\nAuthor: Nicolas Mills\nID: 180856100\nEmail: mill6100@mylaurier.ca\n__updated__ = 2018-09-20\n------------------------------------------------------------------------\n\"\"\"\nx_coord = float(input(\"Enter the x coordinate: \"))\ny_coord = float(input(\"Enter the y coordinate: \"))\nquadrant = None\n\nif x_coord > 0: # Left of origin (pos.)\n if y_coord > 0: # Above x-axis (pos.)\n quadrant = \"quadrant 1\"\n elif y_coord < 0: # Below x-axis (neg.)\n quadrant = \"quadrant 4\"\n else: # y-coord = 0\n quadrant = \"x-axis\"\nelif x_coord < 0: # Right of origin (neg.)\n if y_coord > 0: # Above x-axis (pos.)\n quadrant = \"quadrant 2\"\n elif y_coord < 0: # Below x-axis (neg.)\n quadrant = \"quadrant 3\"\n else: # y-coord = 0\n quadrant = \"x-axis\"\nelif x_coord == 0: # On origin OR on y-axis\n if y_coord == 0:\n quadrant = \"origin\"\n else:\n quadrant = \"y-axis\"\n \nprint(\"({:.2f},{:.2f}) is in/on the {}\".format(x_coord, y_coord, quadrant))","sub_path":"workspace/CP104/mill6100_l3/src/t15 - Copy.py","file_name":"t15 - Copy.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"19398046","text":"from functions import *\nfrom module import *\nimport sys\n\n'''The main program imports self-defined functions and module, which load two files to visualize economic data\nby a given year input by users. Boxplots illustrate the median, average, 1st and 3rd quartiles, and histograms of\nincome conditions shows the numbers of countries in different continents.'''\n\nload_data()\ndef main():\n try:\n inp = input(\n \"Input a year in which the yearly income per person you would like to see(Between 1800 and 2012). \"\n \"Input 'finish' to stop the program.\\n\")\n while inp != 'finish':\n input_year = int(inp)\n if input_year > 2012 or input_year < 1800:\n raise ValueError('Invalid input!')\n\n else:\n try:\n data = merge_by_year(input_year)\n graph = tool(input_year, data)\n graph.histogram() and graph.boxplot()\n plt.close()\n sys.exit(0)\n except ValueError:\n print('Invalid input!')\n\n except KeyboardInterrupt:\n sys.exit(1)\n\n except EOFError:\n sys.exit(2)\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"assignment9.py","file_name":"assignment9.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"398725692","text":"# Django-CIM-Forms\n# Copyright (c) 2012 CoG. All rights reserved.\n#\n# Developed by: Earth System CoG\n# University of Colorado, Boulder\n# http://cires.colorado.edu/\n#\n# This project is distributed according to the terms of the MIT license [http://www.opensource.org/licenses/MIT].\n\nfrom django.contrib import admin\n\nfrom models import *\n\n################################################################################################\n# this admin function gets rid of \"dangling\" properties; properties that no models reference #\n# every property maintains a set of model class names that can reference it, (that list is set #\n# explicitly in the property's __init__ fn, as well as dynamically when a model is initialized #\n# with a set of properties). this code checks the objects of each named class to see if the #\n# selected property is referenced by it. if no named models reference the property, it can be #\n# safely deleted from the db. #\n################################################################################################\n\ndef delete_danglers(modeladmin, request, queryset):\n for property in queryset:\n property_dangles = True\n for referencingModel in property.getReferencingModels():\n (app_name,model_name) = referencingModel.split('.')\n try:\n ModelType = ContentType.objects.get(app_label=app_name.lower(),model=model_name.lower())\n except ObjectDoesNotExist:\n msg = \"invalid model type '%s' in application '%s'\" % (model_name, app_name)\n return MetadataError(msg)\n ModelClass = ModelType.model_class()\n # this assumes that the model field referencing the property is called \"properties\"\n # ...that a pretty big assumption\n if ModelClass.objects.filter(properties__id=property.id).exists():\n property_dangles = False\n # as soon as I find a model that references this property, there's no point in continuing\n break\n if property_dangles:\n property.delete()\n\n\ndelete_danglers.short_description = \"Delete any of the selected properties that are not currently referenced by a model\"\n\nclass PropertyAdmin(admin.ModelAdmin):\n actions = [delete_danglers]\n\n# registration must be done w/ _concrete_ classes in their own applications\n#admin.site.register(MetadataProperty, PropertyAdmin)\n","sub_path":"CIM_Questionnaire/django_cim_forms/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"193309015","text":"##############################################################\n# KMGstretchyIK 0.1(c) Kyle Masters-Gutierrez\n# quick script to make a simple stretchy IK chain\n#\n# to use: \n# make joint chain and set up ik handles,\n# then either select the handle and run makeStretchyIK(),\n# or run makeStretchyIK(handle='handleName')\n#\n#\n#release history:\n# 0.1: (9-30) initial release\n\n\nimport maya.cmds as mc\n\ndef makeStretchyIK(handle=''):\n '''to use: make joint chain and set up ik handles, then either select the handle and run makeStretchyIK(), or run makeStretchyIK(handle='handleName')\n \n '''\n #figure out what the selections should be\n if not handle:\n handle = mc.ls(sl=True)[0]\n\n #fix joint jumps\n mc.setAttr(handle + '.snapEnable', 0)\n \n jointList= mc.ikHandle(handle, q=True, jointList=True)\n #print 'the joinList:'\n jointList.extend(mc.listRelatives(jointList[-1], type='joint'))\n #print jointList\n\n \n locatorList = []\n\n #create locator assembly\n locatorList.append(mc.spaceLocator(name = jointList[0] + '_locator',)[0])\n locatorList.append(mc.spaceLocator(name = jointList[-1] + '_locator',)[0])\n\n mc.pointConstraint(jointList[0],locatorList[0],offset=[0,0,0,])\n mc.pointConstraint(handle,locatorList[1],offset=[0,0,0,]) \n \n #measure system\n bone1len = mc.createNode('distanceBetween', name=handle + '_measure')\n\n mc.connectAttr(locatorList[0] + 'Shape.worldPosition[0]', bone1len + '.point1')\n mc.connectAttr(locatorList[-1] + 'Shape.worldPosition[0]', bone1len + '.point2')\n\n #calculate length of joints\n maxDist = 0\n jntLen = []\n \n for jntA in jointList[1:]:\n #print jntA\n length = mc.getAttr(jntA + '.translateX')\n jntLen.append(length)\n length = abs(length)\n maxDist += length\n mc.createNode('multiplyDivide', name=jntA + '_StretchDRVR')\n\n #build out nodes for stretch ratio and range clamping \n stretchGain = mc.createNode('multiplyDivide', name=handle + '_stretchGain')\n mc.setAttr(stretchGain + '.operation' , 2)\n mc.connectAttr(bone1len+ '.distance' ,stretchGain + '.input1.input1X')\n mc.setAttr(stretchGain + '.input2.input2X', maxDist)\n\n clampNode = mc.createNode('clamp', name=handle + '_clamp')\n mc.connectAttr( stretchGain + '.outputX', clampNode + '.inputR')\n mc.setAttr(clampNode + '.minR', 1)\n mc.setAttr(clampNode + '.maxR', 4)\n\n\n #connect joint sizer to joints\n for jntB, jntBlen in zip(jointList[1:],jntLen):\n\n mc.setAttr(jntB +'_StretchDRVR' + '.input2.input2X', jntBlen)\n \n mc.connectAttr(clampNode + '.outputR' , jntB +'_StretchDRVR' + '.input1.input1X')\n\n mc.connectAttr(jntB +'_StretchDRVR' + '.outputX', jntB + '.translateX')\n\n return [locatorList[0],locatorList[-1]]\n #mc.spaceLocator()","sub_path":"ToolBox/Utilities/KMGstretchyIK.py","file_name":"KMGstretchyIK.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"313235536","text":"import csv\r\n\r\nimport os\r\n\r\nfrom pathlib import Path\r\n\r\n\r\n\r\n#set path\r\n\r\nfilepath = Path(\"downloads\\election_data.csv\")\r\n\r\nprint('Election Results\\n')\r\n\r\nprint('---------------------------\\n')\r\n\r\n#open the file\r\n\r\nwith open(filepath, newline=\"\",encoding='utf-8') as csvfile:\r\n\r\n csvreader = csv.reader(csvfile, delimiter=\",\")\r\n\r\n #Initialize variables to empty lists and dictionary\r\n\r\n votes = []\r\n\r\n total_votes = 0\r\n\r\n candidates = []\r\n\r\n candidates_dict = {}\r\n\r\n winning_votes = 0\r\n\r\n next(csvreader)\r\n\r\n #go line by line and process each vote\r\n\r\n for row in csvreader:\r\n\r\n #add to total number of votes\r\n\r\n total_votes += 1\r\n\r\n if row[2] not in candidates:\r\n\r\n #add candidates to the empty list\r\n\r\n candidates.append(row[2])\r\n\r\n #to make candidate name as the key\r\n\r\n candidates_dict[row[2]] = 0\r\n\r\n candidates_dict[row[2]] = candidates_dict[row[2]] + 1\r\n\r\n else: \r\n\r\n candidates_dict[row[2]] +=1\r\n\r\n #print(candidates_dict)\r\n\r\n for candidates in candidates_dict:\r\n\r\n votes = candidates_dict.get(candidates)\r\n\r\n percentage = (votes / total_votes)*100\r\n\r\n print(str(candidates) + ':' + str(round(percentage,3)) + (\"%\") + ' (' + str(votes) + ')' '\\n')\r\n\r\n if votes > winning_votes:\r\n\r\n winning_votes = votes\r\n\r\n winner = candidates\r\n\r\n \r\n\r\nprint(\"Total Votes: \" + str(total_votes) + '\\n')\r\n\r\nprint('----------------------------\\n')\r\n\r\nprint(\"Winner: \" + str(winner) +'\\n')\r\n\r\nprint(\"Winning Votes: \" + str(winning_votes) +'\\n')\r\n\r\nprint('----------------------------\\n')\r\n\r\n\r\n\r\n#set path for output file\r\n\r\nfilepath_1 = (\"downloads\\output_pypoll.txt\")\r\n\r\n# opens the output destination in write mode and prints the summary\r\n\r\nwith open(filepath_1, 'w+') as writefile:\r\n\r\n csvwriter = csv.writer(writefile, delimiter=\",\")\r\n\r\n writefile.writelines('Election Results\\n')\r\n\r\n writefile.writelines('----------------------------\\n')\r\n\r\n for candidates in candidates_dict:\r\n\r\n votes = candidates_dict.get(candidates)\r\n\r\n percentage = (votes / total_votes)*100\r\n\r\n writefile.writelines(str(candidates) + ':' + str(round(percentage,3)) + (\"%\") + ' (' + str(votes) + ')' '\\n')\r\n\r\n writefile.writelines(\"Total Votes: \" + str(total_votes) + '\\n')\r\n\r\n writefile.writelines('----------------------------\\n')\r\n\r\n writefile.writelines(\"Winner: \" + str(winner) +'\\n')\r\n\r\n writefile.writelines(\"Winning Votes: \" + str(winning_votes) +'\\n')\r\n\r\n writefile.writelines('----------------------------\\n')","sub_path":"Polls.py","file_name":"Polls.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"238045571","text":"from __future__ import unicode_literals\n\nfrom django.db.models import Sum\n\nfrom documents.models import AlignedExpense\nfrom documents.reports import Report, InfiniteCounter\nfrom money.models import Certificate, Service\n\n\nclass CertificateDataProvider(object):\n def __init__(self, certificate):\n assert certificate\n assert isinstance(certificate, Certificate)\n\n self.certificate = certificate\n\n @property\n def is_valid(self):\n return self.get_aligned_expenses().exists()\n\n @property\n def total_amount(self):\n result = AlignedExpense.objects.filter(certificate=self.certificate).aggregate(total=Sum('amount'))\n return result['total']\n\n def get_aligned_expenses(self):\n \"\"\"\n Get aligned expenses, linked to this certificate.\n :param query: Query parameters\n :return:\n \"\"\"\n return AlignedExpense.objects.filter(certificate=self.certificate)\n\n def get_grouped_expenses(self, **query):\n \"\"\"\n Returns grouped services list in format:\n [\n {\n service: Service object,\n amount: SUM of all expenses by the Service during Certificate period,\n count: SUM of all counts of the Services during Certificate period\n }\n ]\n :param query: Additional filtering.\n :return: Array of dicts.\n \"\"\"\n flat_expenses = self.get_aligned_expenses()\n\n grouped_aligned_expenses = flat_expenses.filter(\n parent_expense__service__contract=self.certificate.contract).values('parent_expense__service').annotate(\n total_amount=Sum('amount'),\n total_count=Sum('count')\n )\n\n result = []\n for grouped_aligned_expense in grouped_aligned_expenses:\n result.append({\n 'service': Service.objects.get(pk=grouped_aligned_expense['parent_expense__service']),\n 'amount': grouped_aligned_expense['total_amount'],\n 'count': grouped_aligned_expense['total_count']\n })\n\n return result\n\n\nclass CertificateReport(Report):\n def __init__(self, certificate, is_scan=False):\n assert certificate\n assert isinstance(certificate, Certificate)\n\n super(CertificateReport, self).__init__('certificate.html')\n\n self.certificate = certificate\n self.is_scan = is_scan\n\n def get_context(self):\n cdp = CertificateDataProvider(self.certificate)\n if not cdp.is_valid:\n raise ValueError('Certificate must have expenses in the period.')\n\n return {\n 'is_scan': self.is_scan,\n 'certificate': self.certificate,\n 'data_provider': CertificateDataProvider(self.certificate),\n 'counter': InfiniteCounter(1)\n }\n","sub_path":"pybilling/documents/reports/certificate.py","file_name":"certificate.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"482122913","text":"# ***********************************************************************\n# * *\n# * EuCorrijo.com *\n# * *\n# * Software Processador OMR *\n# * *\n# * Versao CEM404 / 2o Bim / 2016 *\n# * *\n# ***********************************************************************\n# * $Id: Processador_CEM404.py 464 2016-07-10 03:12:49Z tiago.ventura $ *\n# ***********************************************************************\n\nimport os\nimport sys\nimport csv\nimport cv2\nimport argparse as ap\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n# ******************************************************************************\n# * Variaveis Globais *\n# ******************************************************************************\n\n# Pixels por celula da ROI\nppc = 30\n\n# Dimensoes da ROI\nroi_height = 30\nroi_width = 26\n\n# Tamanho da borda da celula que sera ignorada pelo detector\ncbrd = int( ppc * .30 )\n\n\n# ******************************************************************************\n# * Constantes *\n# ******************************************************************************\n\n# Cores\ncolor_black = (0,0,0)\ncolor_white = (255,255,255)\ncolor_gray = (127,127,127)\ncolor_red = (255,0,0)\ncolor_green = (0,255,0)\ncolor_blue = (0,0,255)\ncolor_pink = (255,0,255)\ncolor_yellow = (255,255,0)\ncolor_dark_gray = (64,64,64)\ncolor_light_gray = (192,192,192)\n\n\n# ******************************************************************************\n# * Controle de argumentos passados na linha de comando *\n# ******************************************************************************\ndef parseArguments():\n\n\tp = ap.ArgumentParser( description='Processador de Formularios OMR - Eucorrijo.com' )\n\t\n\tp.add_argument('-o', '--output-file', help='arquivo de saida (.csv)', default='-' )\n\tp.add_argument('-img', '--input-image', help='arquivo de imagem', default='' )\n\tp.add_argument('-dir', '--image-directory', help='diretorio contendo multiplas imagens', default='' )\n\tp.add_argument('-tmpl', '--template-file', help='arquivo de gabarito em formato .csv', default='' )\n\tp.add_argument('-hdr', '--add-csv-header', help='inclusao de cabecalho no arquivo de saida (.csv)', action='store_true', default=0 )\n\tp.add_argument('-mth', '--mark-threshold', help='porcentagem do preenchimento necessario para deteccao de uma marcacao (default: 50%%)', default=50 )\n\tp.add_argument('-dbg', '--enable-debug', help='habilita o modo de debug', action='store_true', default=0 )\n\t\n\targs = p.parse_args()\n\n\treturn args\t\n\n\n# ******************************************************************************\n# * Plota Grid Imaginario da ROI (MODO DEBUG) *\n# ******************************************************************************\ndef drawROIGrid( roi, x, y, w, h ):\n\t\n\tfor y in range(h):\n\t\n\t\tfor x in range(w):\n\t\n\t\t\tx1 = (ppc * x)\n\t\t\ty1 = (ppc * y)\n\t\t\tx2 = x1 + ppc\n\t\t\ty2 = y1 + ppc\n\t\n\t\t\t# Celula Imaginaria\n\t\t\tcv2.rectangle( roi, (x1,y1), (x2,y2), color_dark_gray, 1 )\n\t\t\t\n\t\t\t# Celula usada na Deteccao\n\t\t\tcv2.rectangle( roi, (x1 + cbrd,y1 + cbrd), (x2 - cbrd, y2 - cbrd), color_light_gray, 1 )\n\n\n# ******************************************************************************\n# * Grava o arquivo CSV de Saida *\n# ******************************************************************************\ndef writeOutputCSV( f, data, hdr ):\n\n\tdata = sorted( data, key=lambda z:int(z[2]) )\n\n\twrtr = csv.writer( f, delimiter=';', lineterminator='\\n' )\n\n\tif( hdr ):\n\t\twrtr.writerow( [ 'IMAGEM', 'GABARITO', 'ID_OBJETO', 'TIPO_OBJETO', 'ACERTO', 'LEITURA/STATUS' ] );\n\n\tfor d in data :\n\t\twrtr.writerow( d )\n\n\n# ******************************************************************************\n# * Processa as Celulas Contidas em um Retangulo e *\n# * retorna uma array bidimensional de booleanos *\n# ******************************************************************************\ndef proccessCells( rect, w, h ):\n\n\tcells = []\n\n\tfor y in range(h):\n\n\t\tfor x in range(w):\n\n\t\t\tx1 = (x * ppc) + cbrd\n\t\t\ty1 = (y * ppc) + cbrd\n\n\t\t\tx2 = ((x * ppc) + ppc) - cbrd\n\t\t\ty2 = ((y * ppc) + ppc) - cbrd\n\n\t\t\tc = rect[ y1:y2, x1:x2 ]\n\n\t\t\tsz = c.size\n\t\t\tnz = np.count_nonzero( c )\n\n\t\t\tfl = (nz * 100) / sz\n\n\t\t\tif( g_debug_enabled ) :\n\t\t\t\tsys.stderr.write( \"\t\tCelula: x=%d y=%d nonzero=%d total=%d fill=%d%% threshold=%d%%\\n\" % (x, y, nz, sz, fl, g_mark_threshold) )\n\n\t\t\tcells.append( (x, y, int( fl > g_mark_threshold ) ) )\n\n\treturn cells;\n\n\n# ******************************************************************************\n# * Identifica cada tipo de Objeto *\n# ******************************************************************************\ndef parseObject( cells, tp ):\n\n\tn = 0;\n\tId = '';\n\n\t#\n\t# Verificando o Identificador de Cartao\n\t#\n\tif ( tp == 'ID' ) :\n\n\t\t# Recupera identificador do cartao\n\t\tfor x, y, value in cells :\n\t\t\tId = Id + str(int( value > 0 ))\n\n\t\t# Converte String para Inteiro usando base2\n\t\treturn int( Id, 2 );\n\n\t#\n\t# Verificando o Objeto de Clock\n\t#\n\tif( tp == 'CLK' ) :\n\n\t\t# Verifica integridade da barra de clock\n\t\tfor x, y, value in cells :\n\t\t\tif ( value == 0 ) :\n\t\t\t\treturn 'INV'\n\n\t\treturn 'OK'\n\n\t#\n\t# Tratamento de Respostas do tipo 'A'\n\t#\n\tif( tp == 'A' ) :\n\n\t\t# Verifica Integridade da resposta de tipo A\n\t\tfor x, y, value in cells :\n\t\t\tif( value ):\n\t\t\t\tif ( x > 0 ) :\n\t\t\t\t\tn = n + 1;\n\n\t\t# Verifica o nao preenchimento\n\t\tif( n == 0 ): return 'NP';\n\n\t\t# Verifica o preenchimento incorreto\n\t\tif( n > 1 ): return 'INV'\n\n\t\t# Le o preenchimento\n\t\tfor x, y, value in cells :\n\t\t\tif ( value ) :\n\t\t\t\tif( (x,y) == (1,0) ): return 'C'\n\t\t\t\tif( (x,y) == (2,0) ): return 'E'\n\n\t#\n\t# Tratamento de Respostas do tipo 'B'\n\t#\n\tif( tp == 'B' ) :\n\n\t\tc = 0; d = 0; u = 0;\n\n\t\t# Verifica Integridade da resposta de tipo B\n\t\tfor x, y, value in cells :\n\t\t\tif( value ) :\n\t\t\t\tfor i in range( 10 ):\n\t\t\t\t\tif( (x,y) == (1,i+2) ) : c = c + 1\n\t\t\t\t\tif( (x,y) == (2,i+2) ) : d = d + 1\n\t\t\t\t\tif( (x,y) == (3,i+2) ) : u = u + 1\n\n\t\t# Verifica o nao preenchimento\n\t\tif( (c == 0) and (d == 0) and (u == 0) ): return 'NP'\n\n\t\t# Verifica o preenchimento invalido\n\t\tif( (c == 0) or (d == 0) or (u == 0) ): return 'INV'\n\n\t\t# Verifica o preenchimento invalido\n\t\tif( (c > 1) or (d > 1) or (u > 1) ): return 'INV'\n\n\t\t# Le o numero preenchido\n\t\tfor x, y, value in cells :\n\t\t\tif( value ):\n\t\t\t\tfor i in range( 10 ):\n\t\t\t\t\tif( (x,y) == (1,i+2) ) : c = i * 100\n\t\t\t\t\tif( (x,y) == (2,i+2) ) : d = i * 10\n\t\t\t\t\tif( (x,y) == (3,i+2) ) : u = i\n\n\t\t# Retorna valor lido\n\t\treturn str( c + d + u )\n\n\t#\n\t# Tratamento de Respostas do tipo C\n\t#\n\tif( tp == 'C' ):\n\n\t\t# Verifica Integridade do preenchimento da resposta de tipo C\n\t\tfor x, y, value in cells :\n\t\t\tif ( value ) :\n\t\t\t\tif( x > 0 ) :\n\t\t\t\t\tn = n + 1\n\n\t\t# Verifica o nao preenchimeto\n\t\tif( n == 0 ): return 'NP'\n\n\t\t# Verifica o preenchimento incorreto\n\t\tif( n > 1 ): return 'INV'\n\n\t\t# Le a resposta marcada\n\t\tfor x, y, value in cells :\n\t\t\tif( value ):\n\t\t\t\tif( (x,y) == (1,0) ): return 'A'\n\t\t\t\tif( (x,y) == (2,0) ): return 'B'\n\t\t\t\tif( (x,y) == (3,0) ): return 'C'\n\t\t\t\tif( (x,y) == (4,0) ): return 'D'\n\n\t# Tipo de Objeto Desconhecido\n\treturn 'ERR'\n\n\n# ******************************************************************************\n# * Processa um objeto de um determindado tipo em uma *\n# * das coordenadas da ROI *\n# ******************************************************************************\ndef proccessROIObject( roi, x, y, tp ):\n\n\t# Calcula dimensao em celulas da ROI conforme o tipo de questao\n\tif ( tp == 'A' ) : w = 3; h = 1; cl = color_red\n\telif ( tp == 'B' ) : w = 4; h = 12; cl = color_green\n\telif ( tp == 'C' ) : w = 5; h = 1; cl = color_blue\n\telif ( tp == 'ID' ) : w = 1; h = 16; cl = color_yellow\n\telif ( tp == 'CLK' ) : w = 1; h = 30; cl = color_pink\n\telse:\n\t\treturn 'ERR';\n\n\t# Converte Coordenadas da ROI para coordenadas da Imagem\n\tx1 = (x * ppc)\n\ty1 = (y * ppc)\n\tx2 = x1 + (w * ppc)\n\ty2 = y1 + (h * ppc)\n\n\t# Recorta da ROI apenas a regiao onde esta a questao a ser processada\n\tobj = roi[ y1:y2, x1:x2 ]\n\n\t# Exibe Retangulo de Trabalho (DEBUG)\n\tif( g_debug_enabled and g_input_file ):\n\t\tcv2.rectangle( roi_debug, (x1,y1), (x2,y2), cl, 3 )\n\n\t# Transforma o Retangulo com a ROI da questao em uma array contendo os resultados processados\n\tcells = proccessCells( obj, w, h );\n\n\t# Efetua o parser de um objeto ROI\n\tdata = parseObject( cells, tp )\n\n\treturn data;\n\n\n# ******************************************************************************\n# * Processa a ROI de acordo com os objetos contido no arquivo CSV *\n# ******************************************************************************\ndef startProcessor( roi, csvfile, imgfile ):\n\n\tres = []\n\n\tif( g_debug_enabled ) :\n\t\tsys.stderr.write(\"Processando imagem/template: imagem='%s', template='%s'\\n\" % ( imgfile, csvfile ))\n\n\t# Aplica Threshold na imagem corrigida\n\t_,roi_seg = cv2.threshold( roi, 127, 255, cv2.THRESH_BINARY_INV )\n\n\t# Abre o arquivo CSV contendo a lista de objetos\n\tf = open( csvfile , 'rt' )\n\n\t# Carrega Dados do arquivo de Gabarito\n\ttemplate = csv.reader( f, delimiter=';' )\n\n\t# Para cada objeto contido no CSV...\n\tfor obj in template:\n\n\t\tn, tp, ca, x, y = obj;\n\n\t\tif( g_debug_enabled ) :\n\t\t\tsys.stderr.write(\"\tProcessando Objeto: n=%s, tp=%s, x=%s, y=%s\\n\" % ( n, tp, x, y ))\n\n\t\ta = proccessROIObject( roi_seg, int(x), int(y), tp )\n\n\t\tres.append( ( imgfile, csvfile, n, tp, int( a == ca ), a ) )\n\n\t# Fecha Arquivo CSV\n\tf.close()\n\n\treturn res;\n\n\n# ******************************************************************************\n# * Detecta e recorta a ROI de uma Imagem *\n# ******************************************************************************\ndef getROIFromImage( img_gray ):\n\n\t# Aplica Median Blur (Smoothing)\n\timg_blur = cv2.blur( img_gray, (3,3) )\n\n\t# Aplica Threshold na imagem\n\tret,img_threshold = cv2.threshold( img_blur, 127, 255, cv2.THRESH_TOZERO_INV )\n\n\t# Encontra os contornos da imagem\n\tcontours,hierarchy = cv2.findContours( img_threshold, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE )\n\n\t# Recupera todos os contornos que podem ser representados como poligonos de 4 lados (Quadrilateros)\n\tarea_array = []\n\tapprox_array = []\n\n\t# Para cada contorno detectado...\n\tfor cnt in contours:\n\n\t\t# Aproxima contorno\n\t\tperim = 0.1 * cv2.arcLength( cnt, True )\n\t\tapprox = cv2.approxPolyDP( cnt, perim, True )\n\n\t\t# Se a aproximacao do contorno possuir 4 vertices inclui na array\n\t\tif len(approx) == 4:\n\t\t\tarea_array.append(cv2.contourArea(approx))\n\t\t\tapprox_array.append(approx)\n\n\t# Ordena array de quadrilateros pela area (da maior para a menor)\n\tsrt = sorted( zip( area_array, contours, approx_array ), key=lambda x:x[0], reverse=True )\n\n\t# Recupera o quadrilatero da ROI [Isso precisa ser melhorado!]\n\tarea,cnt,approx = srt[1]\n\n\t# Corrige perspectiva do Quadrilatero da ROI\n\tpts = approx.reshape( 4, 2 )\n\tsrc_quad = np.zeros( (4, 2), dtype = \"float32\" )\n\n\ts = pts.sum(axis = 1)\n\tsrc_quad[0] = pts[ np.argmin(s) ]\n\tsrc_quad[2] = pts[ np.argmax(s) ]\n\n\tdiff = np.diff(pts, axis = 1)\n\tsrc_quad[1] = pts[ np.argmin(diff) ]\n\tsrc_quad[3] = pts[ np.argmax(diff) ]\n\n\t# Constroi array de destino\n\twmax = ppc * roi_width\n\thmax = ppc * roi_height\n\n\tdst_array = np.array( [ [0, 0], [wmax - 1, 0], [wmax - 1, hmax - 1], [0, hmax - 1] ], dtype = \"float32\" )\n\n\t# Calcula array de transformacao\n\ttrnsfrm_array = cv2.getPerspectiveTransform( src_quad, dst_array )\n\n\t# Corrige a deformacao perspectiva a partir da array de transformacao\n\timg_roi = cv2.warpPerspective( img_gray, trnsfrm_array, (wmax, hmax) )\n\n\treturn img_roi;\n\n\n# ******************************************************************************\n# * MAIN *\n# ******************************************************************************\n\n# Inicializa variaveis globais atraves dos argumentos passados na linha de comado\nargs = parseArguments()\n\ng_debug_enabled = args.enable_debug\ng_template_file = args.template_file \ng_input_file = args.input_image\ng_input_directory = args.image_directory\ng_output_file = args.output_file\ng_add_csv_header = args.add_csv_header\ng_mark_threshold = int(args.mark_threshold)\n\n\n# Verifica se o arquivo de template eh valido\ntry:\n\topen( g_template_file, 'r' ).close()\nexcept IOError:\n\tsys.stderr.write( \"FATAL: Erro abrindo arquivo de template para leitura: %s\\n\" % g_template_file );\n\tsys.exit(1)\n\n\n# Determina o stream que sera usado pelo arquivo de saida\nf = sys.stdout\nif ( g_output_file and g_output_file != '-' ) :\n\ttry:\n\t\tf = open( g_output_file, 'w' )\n\texcept IOError:\n\t\tsys.stderr.write( \"FATAL: Erro abrindo arquivo de saida para gravacao: %s\\n\" % g_output_file );\n\t\tsys.exit(1)\n\n\n# Processando um Arquivo isolado\nif( g_input_file ):\n\t\n\t# Carrega imagem original em tons de cinza\n\timg_input = cv2.imread( g_input_file, cv2.IMREAD_GRAYSCALE )\n\t\n\t# Verifica se a imagem foi carregada\n\tif( img_input is None ) :\n\t\tsys.stderr.write( \"FATAL: Erro abrindo arquivo de imagem para leitura: %s\\n\" % g_input_file );\n\t\tsys.exit(1)\n\n\t# Detecta e Recupera a ROI contida na imagem\n\timg_roi = getROIFromImage( img_input );\n\n\t# DEBUG\n\tif ( g_debug_enabled ):\n\t\t# Converte ROI de GRAYSCALE para RGB (DEBUG)\n\t\troi_debug = cv2.cvtColor( img_roi, cv2.COLOR_GRAY2BGR )\n\t\tcv2.bitwise_not( roi_debug, roi_debug )\n\t\tdrawROIGrid( roi_debug, 0, 0, roi_width, roi_height );\n\n\t# Processa imagem\n\tres = startProcessor( img_roi, g_template_file, g_input_file )\n\n\t# Gera Saida\n\twriteOutputCSV( f, res, g_add_csv_header )\n\n# Processando diretorio (Batch Processing - NAO RECURSIVO!!!)\nelif( g_input_directory ):\n\t\n\t# Processa Diretorio de Imagens\n\tfor fname in os.listdir( g_input_directory ): \n\t\n\t\t# Verifica se o arquivo nao eh uma imagem suportada\n\t\tif( not( fname.endswith(\".tif\") or fname.endswith(\".png\") or fname.endswith(\".jpg\") ) ):\n\t\t\tcontinue\n\n\t\t# Monta o path da imagem\n\t\timgpath = g_input_directory + '/' + fname\n\t\n\t\t# Carrega imagem original em tons de cinza\n\t\timg_input = cv2.imread( imgpath, cv2.IMREAD_GRAYSCALE )\n\n\t\t# Verifica se a imagem foi carregada\n\t\tif( img_input is None ) :\n\t\t\tsys.stderr.write( \"WARNING: Erro carregando arquivo de imagem: %s\\n\" % imgpath );\n\t\t\tcontinue;\n\n\t\t# Detecta e Recupera a ROI contida na imagem\n\t\timg_roi = getROIFromImage( img_input );\n\n\t\t# Processa imagem\n\t\tres = startProcessor( img_roi, g_template_file, imgpath )\n\n\t\t# Gera Saida\n\t\twriteOutputCSV( f, res, g_add_csv_header )\n\t\t\n\t\t# Desabilita header depois do primeiro registro\n\t\tg_add_csv_header = 0;\n\n\n# Fecha arquivo CSV de saida\nf.close()\n\n# DEBUG - somente para imagens isoladas\nif ( (not g_debug_enabled) or (g_input_directory) ):\n\tsys.exit(0)\n\n\n# ******************************************************************************\n# * DEBUG *\n# ******************************************************************************\n\n# DEBUG - Exibe Processamento passo-a-passo\ntit = plt.figure()\ntit.canvas.set_window_title('DEBUGGER')\n\n# DEBUG - Monta array com as imagens e suas respectivas descricoes\nimages = [ ('INPUT IMAGE',img_input),\n ('ROI',img_roi),\n ('DEBUG IMAGE',roi_debug) ]\n\n# DEBUG - Monta grid com as imagens\ni = 0\nfor title,img in images:\n\tplt.subplot( 1, 3, i + 1 )\n\tplt.imshow( img,'gray' )\n\tplt.title( title )\n\ti = i + 1\n\n# DEBUG - Exibe janela com as imagens\nplt.show()\n\n# ******************************************************************************\n# $Id: Processador_CEM404.py 464 2016-07-10 03:12:49Z tiago.ventura $\n","sub_path":"Processador_CEM404.py","file_name":"Processador_CEM404.py","file_ext":"py","file_size_in_byte":16182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"555074866","text":"from debug import *\nimport numpy as np\nimport getData\nimport math\nimport FlexDAG\nimport entropy_estimators as ee\nimport CaIC\nimport IndHSIC\n#import CaPC\nimport statsmodels.nonparametric.kernel_regression as kr\nfrom scipy.stats.distributions import norm\nfrom scipy.linalg import lstsq\n\n# Pruning Tuning Parameters:\n# Eliminate any parents with relative total effect less than PRUNING_THRESHOLD\nPRUNING_THRESHOLD = .03\n# Void parent groups that include any parent with less than PRUNING_THRESHOLD2 coefficient\nPRUNING_THRESHOLD2 = .001\n# Penalize larger number of parents by multiplying the score by PARENT_COUNT_FACTOR**N; where N is the number of parents\nPARENT_COUNT_FACTOR = 1.001\n# Maximum parent count to consider. This primarily affects performance with large numbers of variables\nMAX_PARENTAGE = 5\n\n# Direction Test Method: ('PL'--Pairwise Lingam, 'MI' -- Mutual Information, 'HSIC' -- Hilbert Space Independence Test)\nDIR_TEST = 'PL'\n\nclass IC(CaIC.IC):\n\t# See above (DIR_TEST) for valid values for method\n\t# Set adjustData True to perform adjustments to the data series to make it stationary or to linearize relationships.\n\tdef __init__(self, dataFileName, limit=None, prune=True, method='PL', adjustData=True):\n\t\tglobal DIR_TEST\n\t\tDIR_TEST = method\n\t\tself.entropies = {}\n\t\tsuper().__init__(dataFileName, limit=limit, prune=prune, adjustData=adjustData)\n\t\tself.doPrune = prune\n\t\tself.entropies = {}\n\t\t#self.computeEntropies()\n\t\treturn\n\t\n\tdef computeEntropies(self):\n\t\teList = []\n\t\teList2 = []\n\t\tfor var in self.data.getSeriesNames():\n\t\t\td = self.data.getSeries(var)\n\t\t\t#print('len = ', len(d))\n\t\t\t#print('p1')\n\t\t\tp = self.mi_prepare(d)\n\t\t\t#print('p2')\n\t\t\tentropy = ee.entropy(p, base=math.e)\n\t\t\tself.entropies[var] = entropy\n\t\t\tdentropy = self.dentropy(var)\n\t\t\t#print(\"Entropy, dentropy of \", var, \"=\", entropy, dentropy)\n\t\t\teList.append((dentropy, var))\n\t\t\teList2.append((entropy, var))\n\t\teList.sort()\n\t\t#print('eList = ', eList)\n\t\teList2.sort()\n\t\t#print('eList2 = ', eList2)\n\t\treturn\n\t\t\n\tdef getEntropy(self, varName):\n\t\treturn self.entropies[varName]\n\t\t\n\tdef getDAG(self):\n\t\tdag = FlexDAG.FlexDAG()\n\t\t# Order the vars in causal order\n\t\toVars = self.getVarOrder()\n\t\t#print('Causal Order is: ', oVars)\n\t\t# Build the DAG based on the order with all possible edges\n\t\tfor v in oVars:\n\t\t\tdag.addNode(v)\n\t\tfor i in range(len(oVars)):\n\t\t\tv1 = oVars[i]\n\t\t\tfor j in range(i+1, len(oVars)):\n\t\t\t\tv2 = oVars[j]\n\t\t\t\t#print(v, '<==>', v2, ' = ', self.scoreDependence(self.data.getSeries(v), self.data.getSeries(v2)))\n\t\t\t\t#if not self.isIndependent(v1, v2):\n\t\t\t\tdag.addEdge(v1, v2, 'D')\n\t\tDprint('Raw Dag = ', str(dag))\n\t\tif self.doPrune:\n\t\t\t# Allow pruning to be turned off to increase perf when only order testing\n\t\t\tdag = self.prune(dag)\n\t\t\tDprint('Pruned Dag = ', str(dag))\n\t\treturn dag\n\t\n\tdef prune_quick(self, dag):\n\t\tfor node in dag.getVarOrder():\n\t\t\t#print('\\nnode=', node)\n\t\t\tnodeD = np.array(self.getStandardSeries(node))\n\t\t\tnodeStd = nodeD.std()\n\t\t\tparents = dag.getParents(node)\n\t\t\twhile len(parents) > 0:\n\t\t\t\trelStrengths = []\n\t\t\t\tcoefs = []\n\t\t\t\tparentDs = []\n\t\t\t\t# Calculate coefs and relative strengths of affect for each parent\n\t\t\t\tfor i in range(len(parents)):\n\t\t\t\t\tparentD = np.array(self.getStandardSeries(parents[i]))\n\t\t\t\t\tresults = np.polyfit(parentD, nodeD.T, 1, full=True)\n\t\t\t\t\tfit, residuals = results[:2]\n\t\t\t\t\tcoefs.append(fit)\n\t\t\t\t\t# Calculate relative strength of the effect for this parent\n\t\t\t\t\tx1coef = fit[0]\n\t\t\t\t\tabsCoef = math.fabs(x1coef)\n\t\t\t\t\tnodeStd = nodeD.std()\n\t\t\t\t\tparentStd = parentD.std()\n\t\t\t\t\trelStrength = parentStd * absCoef / nodeStd\n\t\t\t\t\trelStrengths.append(relStrength)\n\t\t\t\t\tparentDs.append(parentD)\n\t\t\t\t# Sort parents in order of relative magnitude of effect\n\t\t\t\tzipped = list(zip(relStrengths, parentDs, parents, coefs))\n\t\t\t\tzipped.sort()\n\t\t\t\tzipped.reverse()\n\t\t\t\tstrongestParentData = zipped[0]\n\t\t\t\trelStrength, parentD, parent, coef = strongestParentData\n\t\t\t\tx1coef, x0coef = coef\n\t\t\t\tdep = self.scoreDependence(parentD, nodeD)\n\t\t\t\tDprint('Prune: relStrength (', parent, ' --> ', node, ') = ', relStrength, ', coefs = ', coef, ', dep = ', dep)\n\t\t\t\tif relStrength > PRUNING_THRESHOLD:\n\t\t\t\t\t# This parent is significant\n\t\t\t\t\t# Regress this parent's data from node data and then repeat the loop to find the next parent\n\t\t\t\t\tycDSlope = parentD * x1coef\n\t\t\t\t\tycD = ycDSlope + x0coef\n\t\t\t\t\tresD = nodeD - ycD\n\t\t\t\t\tnodeD = resD\n\t\t\t\t\tparents.remove(parent)\n\t\t\t\t\tDprint('parent alllowed')\n\t\t\t\telse:\n\t\t\t\t\t# This parent is not significant. This means that none that follow will be. We've got\n\t\t\t\t\t# all significant parents now in outParents. End the loop by settings parents to empty.\n\t\t\t\t\t# Remove edges from this parent and any subsequent parents to this node\n\t\t\t\t\tfor parent in parents:\n\t\t\t\t\t\tdag.removeEdges(parent, node)\n\t\t\t\t\tparents = []\n\t\treturn dag\n\n\tdef prune(self, dag):\n\t\tdeletes = []\n\t\tlowestError = 10**20\n\t\tlowestCombo = None\n\t\t# Remove independent edges\n\t\tfor node in dag.getVarOrder():\n\t\t\tparentD = []\n\t\t\torigParents = dag.getParents(node)\n\t\t\tparents = origParents\n\t\t\tnodeD = self.getStandardSeries(node)\n\t\t\tfor parent in parents:\n\t\t\t\tparentD.append(self.getStandardSeries(parent))\n\t\t\tif len(parents) > 0:\n\t\t\t\tcoefs = []\n\t\t\t\trawError = 0\n\t\t\t\ttempNodeD = np.array(nodeD)\n\t\t\t\t# Calculate coefs for each parent\n\t\t\t\tfor i in range(len(parents)):\n\t\t\t\t\tresults = np.polyfit(np.array(parentD[i]), tempNodeD, 1, full=True)\n\t\t\t\t\tfit, residuals = results[:2]\n\t\t\t\t\tcoefs.append(fit)\n\t\t\t\t\t#print('Original coef for ', parents[i], ' --> ', node, ' = ', fit[0])\n\t\t\t\t\t#print('Original resid = ', residuals[0])\n\t\t\t\t# Sort parents in order of magnitude of coefs\n\t\t\t\trelStrengths = []\n\t\t\t\toutParents = []\n\t\t\t\tfor i in range(len(parents)):\n\t\t\t\t\tcoef = coefs[i][0]\n\t\t\t\t\tabsCoef = math.fabs(coef)\n\t\t\t\t\t# Calculate relative strength of the affect\n\t\t\t\t\tnodeStd = tempNodeD.std()\n\t\t\t\t\tparentStd = np.array(self.getStandardSeries(parents[i])).std()\n\t\t\t\t\trelStrength = parentStd * absCoef / nodeStd\n\t\t\t\t\t#print('relStrength (', parents[i], ' --> ', node, ') = ', relStrength)\n\t\t\t\t\tif relStrength >= PRUNING_THRESHOLD:\n\t\t\t\t\t#if not self.isIndependent(node, parents[i]) and relStrength >= PRUNING_THRESHOLD:\n\t\t\t\t\t\toutParents.append(parents[i])\n\t\t\t\t\t\trelStrengths.append(relStrength)\n\t\t\t\t\t\t#Dprint('coef = ', absCoef)\n\t\t\t\t\telse:\n\t\t\t\t\t\tDprint('CaLingam.prune: Deleting edge(1)', parents[i], ' --> ', node, '. Coef = ', coef)\n\t\t\t\t\t\tdeletes.append((parents[i], node))\n\t\t\t\tzipped = list(zip(relStrengths, outParents))\n\t\t\t\tzipped.sort()\n\t\t\t\tzipped.reverse()\n\t\t\t\tparents = [parent for (coef, parent) in zipped]\n\t\t\t\t#print('Significant Parents = ', parents)\n\t\t\t\tparentIter = self.expandParentList(parents)\n\t\t\t\t#print('parentIter = ', parentIter)\n\t\t\t\tlowestError = 10**20\n\t\t\t\tlowestCombo = parents\n\t\t\t\tfor parentCombo in parentIter:\n\t\t\t\t\t#print('parentCombo = ', parentCombo)\n\t\t\t\t\ttempParents = list(parentCombo)\n\t\t\t\t\ttempParentD = []\n\t\t\t\t\tfor tempParent in tempParents:\n\t\t\t\t\t\ttempParentD.append(self.getStandardSeries(tempParent))\n\t\t\t\t\tcoefs = []\n\t\t\t\t\trawError = 0\n\t\t\t\t\ttempNodeD = np.array(nodeD)\n\t\t\t\t\tfor i in range(len(tempParents)):\n\t\t\t\t\t\ttempParentArray = np.array(tempParentD[i])\n\t\t\t\t\t\tresults = np.polyfit(tempParentArray, tempNodeD.T, 1, full=True)\n\t\t\t\t\t\tfit, residuals = results[:2]\n\t\t\t\t\t\t#print('fit, residuals for ', tempParents[i], ' = ', fit, residuals)\n\t\t\t\t\t\tx1coef = fit[0]\n\t\t\t\t\t\tx0coef = fit[1]\n\t\t\t\t\t\t# If any parent has an X coef that is less than the threshold, then bail out. It means that one of the parents is redundant.\n\t\t\t\t\t\tif x1coef < PRUNING_THRESHOLD2:\n\t\t\t\t\t\t\t# Don't consider this group\n\t\t\t\t\t\t\trawError = 10**20 # Infinity\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\ttempNodeD = tempNodeD - (tempParentArray * x1coef)\n\t\t\t\t\t\tcoefs.append(fit)\n\t\t\t\t\t\trawError = residuals[0] # Resids after regressing all parents. The residuals are inherently cumulative, so we only care about the last one.\n\t\t\t\t\t\t#print('coef for ', tempParents[i], ' --> ', node, ' = ', fit[0])\n\t\t\t\t\t\t#print('resid = ', residuals[0])\n\t\t\t\t\terror = self.scaleError(rawError, len(tempParents), self.data.sampleCount)\n\t\t\t\t\t#error = rawError\n\t\t\t\t\t\n\t\t\t\t\tDprint('Evaluating Edges = ', tempParents, '-->', node, '. Error = ', error)\n\n\t\t\t\t\t#print('error = ', error)\n\t\t\t\t\t#print('coefs = ', coefs)\n\t\t\t\t\tif error < lowestError:\n\t\t\t\t\t\tlowestError = error\n\t\t\t\t\t\tlowestCombo = tempParents\n\t\t\t\t\t\tDprint('Best combo so far')\n\t\t\t\t\t\t\n\t\t\t\t\t# if (error2 - error)/error < .01:\n\t\t\t\t\t\t# for parent in parentCombo:\n\t\t\t\t\t\t\t# deletes.append((node, parent))\n\t\t\t\t\t\t\t# print('**** Print Deleting Edge = ', parent, '-->', node)\n\t\t\t\t\t\t# parents = tempParents\n\t\t\t\t\t\t# parentD = tempParentD\n\t\t\t\t\t\t# coefs = coefs2\n\t\t\t\t\t\t# error = error2\n\t\t\t\t\t\t# parentIter = self.expandParentList(parents)\n\t\t\t\t\t\t# print('parentIter = ', parentIter)\n\t\t\t#print('Best fit is: ', lowestCombo)\n\t\t\t# Prune out the parents not in this combo\n\t\t\tfor parent in parents:\n\t\t\t\tif parent not in lowestCombo:\n\t\t\t\t\tdeletes.append((parent, node))\n\t\t\t\t\tDprint('CaLingam.prune: Deleting Edge(2) = ', parent, '-->', node)\n\t\t\t# if len(parents) == 1:\n\t\t\t\t# pNode = parents[0]\n\t\t\t\t# print('Evaluating Edge = ', pNode, '-->', node, coefs[0])\n\n\t\t\t\t# if math.fabs(coefs[0]) <= .2:\n\t\t\t\t\t#Special case for the last parent\n\t\t\t\t\t# deletes.append((node, pNode))\n\t\t\t\t\t# print('**** Print Deleting Edge = ', pNode, '-->', node)\n\n\t\t\t\t\t\n\t\tfor delete in deletes:\n\t\t\tnode, child = delete\n\t\t\tdag.removeEdges(node, child)\n\t\treturn dag\t\t\n\t\t\n\tdef parameterizeLinearModel(self, dag):\n\t\t# First set node values\n\t\tfor node in dag.getNodes():\n\t\t\tnodeD = np.array(self.data.getSeries(node))\n\t\t\tmean = nodeD.mean()\n\t\t\t#print('mean = ', mean)\n\t\t\tstd = nodeD.std(ddof=1)\n\t\t\tdag.setNodeValue(node, (mean,std))\n\t\t\t# Set the weights for each parent edge\n\t\t\tparentEdges = dag.getParentEdges(node)\n\t\t\tfor edge in parentEdges:\n\t\t\t\tn1, n2, eT, eW = edge\n\t\t\t\tparent = n1\n\t\t\t\tparentD = np.array(self.data.getSeries(parent))\n\t\t\t\tresults = np.polyfit(parentD, nodeD, 1, full=True)\n\t\t\t\tfit = results[0]\n\t\t\t\tx1coef, x0coef = fit\n\t\t\t\tdag.setEdgeWeight(parent, node, fit)\n\t\t\t\tnodeD = nodeD - (parentD * x1coef + x0coef)\n\t\t\tdag.nodeD[node] = nodeD\n\t\tmodel = dag\n\t\treturn model\n\n\t\t\t\t\n\t\t\t\n\tdef getStandardSeries(self, seriesName):\n\t\t#return self.standardize(self.data.getSeries(seriesName))\n\t\treturn self.getDataSeries(seriesName)\n\t\t\n\tdef scaleError(self, raw, parentCount, dataCount):\n\t\terror = raw * PARENT_COUNT_FACTOR**(parentCount-1)\n\t\t#error = raw / (parentCount * dataCount) / (1+(parentCount * PARENT_COUNT_FACTOR))\n\t\treturn error\n\t\t\n\tdef expandParentList(self, parents):\n\t\timport itertools\n\t\tout = []\n\t\tfor i in range(1,min([len(parents),MAX_PARENTAGE])):\n\t\t\tcombinations = itertools.combinations(parents, i)\n\t\t\tout.extend(combinations)\n\t\tout.append(tuple(parents))\n\t\treturn out\n\t\t\n\t# Return vars in causal order\n\tdef getVarOrder(self):\n\t\toVars = []\n\t\tR={}\n\t\tD = {}\n\t\tvNames = self.data.getSeriesNames()\n\t\tfor vName in vNames:\n\t\t\t#D[vName] = self.standardize(self.data.getSeries(vName))\n\t\t\tD[vName] = self.data.getSeries(vName)\n\t\twhile len(oVars) < len(vNames) - 1:\n\t\t\tdirM = {} # Direction matrix\n\t\t\tR = {}\n\t\t\tmiCum = {}\n\t\t\tmostIndependent = None\n\t\t\tmiMin = 10.0**100\n\t\t\tfor j in range(len(vNames)):\n\t\t\t\tyD = []\n\t\t\t\tyNames = []\n\t\t\t\txName = vNames[j]\n\t\t\t\tif xName in oVars:\n\t\t\t\t\tcontinue\n\t\t\t\txD = D[xName]\n\t\t\t\tfor vName in vNames:\n\t\t\t\t\tif vName == xName:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif vName in oVars:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\td = D[vName]\n\t\t\t\t\tyNames.append(vName)\n\t\t\t\t\tyD.append(d)\n\t\t\t\tR[xName] = {}\n\t\t\t\tif xName not in miCum:\n\t\t\t\t\tmiCum[xName] = 0\n\t\t\t\tfor i in range(0, len(yNames)):\n\t\t\t\t\tyName = yNames[i]\n\t\t\t\t\t#if yName not in R:\n\t\t\t\t\t#\tR[yName] = {}\n\t\t\t\t\tayD = yD[i]\n\t\t\t\t\taxD = xD\n\t\t\t\t\t#depXY = self.scoreDependence(axD, ayD)\n\t\t\t\t\t#Dprint('depXY = ', depXY)\n\t\t\t\t\tdirKey = xName + '|' + yName\n\t\t\t\t\tif dirKey not in dirM:\n\t\t\t\t\t\tdirection = self.direction2(axD, ayD)\n\t\t\t\t\t\tdirM[dirKey] = direction\n\t\t\t\t\telse:\n\t\t\t\t\t\tdirection = dirM[dirKey]\n\t\t\t\t\t\n\t\t\t\t\tDprint('xName, yName, direction = ', xName, yName, direction)\n\t\t\t\t\t\n\t\t\t\t\tif direction > 0:\n\t\t\t\t\t\t# First direction is correct\n\t\t\t\t\t\t# Penalize the more dependent direction (Y)\n\t\t\t\t\t\tloserName = yName\n\t\t\t\t\t\twinnerName = xName\n\t\t\t\t\t\tloserScore = direction\n\t\t\t\t\t\twinnerScore = 0\n\t\t\t\t\telif direction < 0 :\n\t\t\t\t\t\tloserName = xName\n\t\t\t\t\t\twinnerName = yName\n\t\t\t\t\t\tloserScore = -direction\n\t\t\t\t\t\twinnerScore = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tloserName = None # If equal (unlikely), don't penalize anyone, or we could create some bias\n\t\t\t\t\t\twinnerName = None\n\t\t\t\t\t\tprint('Warning: Direction score is equal. This is an unusual situation', winnerScore, loserScore)\n\t\t\t\t\tDprint('Predecessor = ', winnerName)\n\t\t\t\t\tif loserName is not None:\n\t\t\t\t\t\tif loserName not in miCum:\n\t\t\t\t\t\t\tmiCum[loserName] = 0\n\t\t\t\t\t\tcum = miCum[loserName]\n\t\t\t\t\t\tcum += loserScore\n\t\t\t\t\t\tmiCum[loserName] = cum\n\t\t\t\t\t\tif winnerName not in miCum:\n\t\t\t\t\t\t\tmiCum[winnerName] = 0\n\t\t\t\t\t\t\n\t\t\t\t\t\tcum = miCum[winnerName]\n\t\t\t\t\t\tcum += winnerScore\n\t\t\t\t\t\tmiCum[winnerName] = cum\n\t\t\t\t\telse:\n\t\t\t\t\t\t5/0\n\t\t\t\t\tR[xName][yName] = ayD # residV1\n\t\t\t\t\tif yName not in R:\n\t\t\t\t\t\tR[yName] = {}\n\t\t\t\t\tR[yName][xName] = axD # residV2\n\t\t\t\t\tDprint('R = ', R.keys())\n\n\t\t\tlowestCorr = 10**20\n\t\t\tmostIndependent = None\n\t\t\t#print ('miCum = ', miCum)\n\t\t\tzipped = list(zip(list(miCum.values()), list(miCum.keys())))\n\t\t\tzipped.sort()\n\t\t\tscores = [key for (value, key) in zipped]\n\t\t\tDprint('score order = ', scores)\n\t\t\tkeys = list(miCum.keys())\n\t\t\tkeys.sort()\n\t\t\tfor k in keys:\n\t\t\t\tcum = miCum[k]\n\t\t\t\tDprint('cum(', k, ')=', cum)\n\t\t\tfor k in miCum.keys():\n\t\t\t\tcum = miCum[k]\n\t\t\t\tif cum < lowestCorr:\n\t\t\t\t\tlowestCorr = cum\n\t\t\t\t\tmostIndependent = k\n\t\t\tDprint('mostIndependent2 = ', mostIndependent, lowestCorr)\n\t\t\tDprint()\n\t\t\toVars.append(mostIndependent)\n\t\t\t# Regress all variables on the mostIndependent\n\t\t\tvarReg = R[mostIndependent]\n\t\t\tD = varReg \n\t\t\t#Dprint('D = ', keys)\n\t\t\t\n\t\tfor v in D.keys():\n\t\t\tif v != mostIndependent:\n\t\t\t\toVars.append(v)\n\t\tDprint('oVars = ', oVars)\n\t\treturn oVars\n\n\tdef getVarOrder_2_9(self):\n#\tdef getVarOrder(self):\n\t\toVars = []\n\t\tR={}\n\t\tD = {}\n\t\tvNames = self.data.getSeriesNames()\n\t\tfor vName in vNames:\n\t\t\t#D[vName] = self.standardize(self.data.getSeries(vName))\n\t\t\tD[vName] = self.data.getSeries(vName)\n\t\twhile len(oVars) < len(vNames) - 1:\n\t\t\tR = {}\n\t\t\tmiCum = {}\n\t\t\tmostIndependent = None\n\t\t\tmiMin = 10.0**100\n\t\t\tfor j in range(len(vNames)):\n\t\t\t\tyD = []\n\t\t\t\tyNames = []\n\t\t\t\txName = vNames[j]\n\t\t\t\tif xName in oVars:\n\t\t\t\t\tcontinue\n\t\t\t\txD = D[xName]\n\t\t\t\tfor vName in vNames:\n\t\t\t\t\tif vName == xName:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif vName in oVars:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\td = D[vName]\n\t\t\t\t\tyNames.append(vName)\n\t\t\t\t\tyD.append(d)\n\t\t\t\tR[xName] = {}\n\t\t\t\tif xName not in miCum:\n\t\t\t\t\tmiCum[xName] = 0\n\t\t\t\tfor i in range(0, len(yNames)):\n\t\t\t\t\tyName = yNames[i]\n\t\t\t\t\t#if yName not in R:\n\t\t\t\t\t#\tR[yName] = {}\n\t\t\t\t\tayD = np.array(yD[i])\n\t\t\t\t\taxD = np.array(xD)\n\t\t\t\t\tdepXY = self.scoreDependence(axD, ayD)\n\t\t\t\t\tDprint('depXY = ', depXY)\n\t\t\t\t\t\n\t\t\t\t\t#coefs = lstsq(np.array([axD]).T, ayD)[0]\n\t\t\t\t\tcoefs = np.polyfit(axD, ayD.T,1)\n\t\t\t\t\tx1coef = coefs[0]\n\t\t\t\t\tx0coef = coefs[1]\n\t\t\t\t\tDprint('xname, yname, x1coef = ', xName, yName, x1coef)\n\t\t\t\t\tycD = axD * x1coef + x0coef\n\t\t\t\t\tresidV1 = ayD - ycD\n\t\t\t\t\tdep1 = self.scoreDependence(axD, residV1)\n\t\t\t\t\t\n\t\t\t\t\t#coefs2 = lstsq(np.array([ayD]).T, axD)[0]\n\t\t\t\t\tcoefs2 = np.polyfit(ayD, axD.T,1)\n\t\t\t\t\tx1coef2 = coefs2[0]\n\t\t\t\t\tx0coef2 = coefs2[1]\n\t\t\t\t\tDprint('xname2, yname2, x1coef2 = ', yName, xName, x1coef2)\n\t\t\t\t\txcD2 = ayD * x1coef2 + x0coef\n\t\t\t\t\tresidV2 = axD - xcD2\n\t\t\t\t\tdep2 = self.scoreDependence(ayD, residV2)\n\t\t\t\t\tDprint(xName, '-->', yName, ': dep1 = ', dep1)\n\t\t\t\t\tDprint(yName, '-->', xName, ': dep2 = ', dep2)\n\t\t\t\t\tdirection = self.direction(xName, yName)\n\t\t\t\t\tDprint('direction = ', direction)\n\t\t\t\t\tif dep1 < dep2:\n\t\t\t\t\t\t# First direction is correct\n\t\t\t\t\t\t# Penalize the more dependent direction (Y)\n\t\t\t\t\t\tloserName = yName\n\t\t\t\t\t\twinnerName = xName\n\t\t\t\t\t\tloserScore = math.fabs((dep1-dep2)/(dep1 + dep2)/2 ) + direction\n\t\t\t\t\t\twinnerScore = dep1\n\t\t\t\t\telif dep2 < dep1:\n\t\t\t\t\t\tloserName = xName\n\t\t\t\t\t\twinnerName = yName\n\t\t\t\t\t\tloserScore = math.fabs((dep1-dep2)/(dep1 + dep2)/2) - direction\n\t\t\t\t\t\twinnerScore = dep2\n\t\t\t\t\telse:\n\t\t\t\t\t\tloserName = None # If equal (unlikely), don't penalize anyone, or we could create some bias\n\t\t\t\t\t\twinnerName = None\n\t\t\t\t\t\t5/0\n\t\t\t\t\tDprint('Predecessor = ', winnerName, 'dep1, dep2 = ', dep1, dep2)\n\t\t\t\t\tif loserName is not None:\n\t\t\t\t\t\tif loserName not in miCum:\n\t\t\t\t\t\t\tmiCum[loserName] = 0\n\t\t\t\t\t\tcum = miCum[loserName]\n\t\t\t\t\t\tif loserScore > cum:\n\t\t\t\t\t\t\tcum = loserScore\n\t\t\t\t\t\t\tmiCum[loserName] = cum\n\t\t\t\t\t\tif winnerName not in miCum:\n\t\t\t\t\t\t\tmiCum[winnerName] = 0\n\t\t\t\t\t\t#cum = miCum[winnerName]\n\t\t\t\t\t\t#if winnerScore > cum:\n\t\t\t\t\t\t#\tcum = winnerScore\n\t\t\t\t\t\t#\tmiCum[winnerName] = cum\n\t\t\t\t\telse:\n\t\t\t\t\t\t5/0\n\t\t\t\t\tR[xName][yName] = ayD # residV1\n\t\t\t\t\tif yName not in R:\n\t\t\t\t\t\tR[yName] = {}\n\t\t\t\t\tR[yName][xName] = axD # residV2\n\t\t\t\t\tDprint('R = ', R.keys())\n\n\t\t\tlowestCorr = 10**20\n\t\t\tmostIndependent = None\n\t\t\t#print ('miCum = ', miCum)\n\t\t\tzipped = list(zip(list(miCum.values()), list(miCum.keys())))\n\t\t\tzipped.sort()\n\t\t\tscores = [key for (value, key) in zipped]\n\t\t\tDprint('score order = ', scores)\n\t\t\tkeys = list(miCum.keys())\n\t\t\tkeys.sort()\n\t\t\tfor k in keys:\n\t\t\t\tcum = miCum[k]\n\t\t\t\tDprint('cum(', k, ')=', cum)\n\t\t\tfor k in miCum.keys():\n\t\t\t\tcum = miCum[k]\n\t\t\t\tif cum < lowestCorr:\n\t\t\t\t\tlowestCorr = cum\n\t\t\t\t\tmostIndependent = k\n\t\t\tDprint('mostIndependent2 = ', mostIndependent, lowestCorr)\n\t\t\tDprint()\n\t\t\toVars.append(mostIndependent)\n\t\t\t# Regress all variables on the mostIndependent\n\t\t\tvarReg = R[mostIndependent]\n\t\t\tD = varReg \n\t\t\tDprint('D = ', D.keys())\n\t\tfor v in D.keys():\n\t\t\tif v != mostIndependent:\n\t\t\t\toVars.append(v)\n\t\tDprint('oVars = ', oVars)\n\t\treturn oVars\n\n\t# Return vars in causal order\n\tdef getVarOrder_2_5(self):\n\t\toVars = []\n\t\tR={}\n\t\tD = {}\n\t\tvNames = self.data.getSeriesNames()\n\t\tfor vName in vNames:\n\t\t\t#D[vName] = self.standardize(self.data.getSeries(vName))\n\t\t\tD[vName] = self.data.getSeries(vName)\n\t\twhile len(oVars) < len(vNames) - 1:\n\t\t\tR = {}\n\t\t\tmiCum = {}\n\t\t\tmostIndependent = None\n\t\t\tmiMin = 10.0**100\n\t\t\tfor j in range(len(vNames)):\n\t\t\t\tyD = []\n\t\t\t\tyNames = []\n\t\t\t\txName = vNames[j]\n\t\t\t\tif xName in oVars:\n\t\t\t\t\tcontinue\n\t\t\t\txD = D[xName]\n\t\t\t\tfor vName in vNames:\n\t\t\t\t\tif vName == xName:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif vName in oVars:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\td = D[vName]\n\t\t\t\t\tyNames.append(vName)\n\t\t\t\t\tyD.append(d)\n\t\t\t\tR[xName] = {}\n\t\t\t\tmiCum[xName] = 0\n\t\t\t\tfor i in range(len(yNames)):\n\t\t\t\t\tyName = yNames[i]\n\t\t\t\t\t#if yName not in R:\n\t\t\t\t\t#\tR[yName] = {}\n\t\t\t\t\tayD = np.array(yD[i])\n\t\t\t\t\taxD = np.array(xD)\n\t\t\t\t\tdepXY = self.scoreDependence(axD, ayD)\n\t\t\t\t\t#coefs = lstsq(np.array([axD]).T, ayD)[0]\n\t\t\t\t\tcoefs = np.polyfit(axD, ayD.T,1)\n\t\t\t\t\tx1coef = coefs[0]\n\t\t\t\t\tx0coef = coefs[1]\n\t\t\t\t\tDprint('xname, yname, x1coef = ', xName, yName, x1coef, x0coef)\n\t\t\t\t\tDprint('depXY = ', depXY)\n\t\t\t\t\tycD = axD * x1coef + x0coef\n\t\t\t\t\tresidV = ayD - ycD\n\n\t\t\t\t\tdep = self.scoreDependence(axD, residV)\n\t\t\t\t\tcum = miCum[xName]\n\t\t\t\t\tif dep > cum:\n\t\t\t\t\t\tcum = dep\n\t\t\t\t\t\tmiCum[xName] = cum\n\t\t\t\t\t#R[xName][yName] = ayD\n\t\t\t\t\tR[xName][yName] = ayD\n\t\t\t\t\tDprint(xName, '-->', yName, ': dep = ', dep)\n\t\t\t\t\t#print()\n\t\t\tlowestCorr = 10**20\n\t\t\tmostIndependent = None\n\t\t\t#Dprint ('miCum = ', miCum)\n\t\t\tkeys = list(miCum.keys())\n\t\t\tkeys.sort()\n\t\t\tfor k in keys:\n\t\t\t\tcum = miCum[k]\n\t\t\t\tDprint('cum(', k, ')=', cum)\n\t\t\tfor k in miCum.keys():\n\t\t\t\tcum = miCum[k]\n\t\t\t\tif cum < lowestCorr:\n\t\t\t\t\tlowestCorr = cum\n\t\t\t\t\tmostIndependent = k\n\t\t\tDprint('mostIndependent2 = ', mostIndependent, lowestCorr)\n\t\t\tDprint()\n\t\t\toVars.append(mostIndependent)\n\t\t\t# Regress all variables on the mostIndependent\n\t\t\tvarReg = R[mostIndependent]\n\t\t\tD = varReg \n\t\t\t#print('D = ', len(D), D.keys())\n\t\tfor v in D.keys():\n\t\t\tif v != mostIndependent:\n\t\t\t\toVars.append(v)\n\t\tDprint('oVars = ', oVars)\n\t\treturn oVars\n\n\t\t\n\tdef isIndependent(self, v1, v2):\n\t\td1 = self.getDataSeries(v1)\n\t\td2 = self.getDataSeries(v2)\n\t\tresult = self.isIndependent2(d1, d2)\t\t\n\t\tDprint('isIndependent ', v1, '<==>', v2, ' = ', result)\n\t\treturn result\n\t\t\n\tdef isIndependent2(self, d1, d2):\n\t\timport IndGauss\n\t\tresult = IndGauss.isIndependent(d1,d2)\n\t\treturn result\n\t\n\tdef scoreDependencexxx(self, d1, d2):\n\t\t#d = norm.cdf(self.direction2(d1, d2) * 1000.0, scale=1)\n\t\t\n\t\t#d = self.direction2(d1, d2)\n\t\t#print ('d =', d)\n\t\td1s = self.standardize(d1)\n\t\td2s = self.standardize(d2)\n\t\t\n\t\t#score = self.scoreDependence4(d1, d2)\n\t\tscore = self.scoreDependence1(d1s, d2s)\n\t\t\n\t\t#score += 10\n\t\t#if score < 0:\n\t\t#\tscore = 0\n\t\t#score = score -min([-d, 0])**2\n\t\t#print('master score = ', score)\n\t\treturn score\n\t\t\n\tdef scoreDependence3(self, d1, d2):\n\t\t#self.genCorrMatrix()\n\t\td1 = self.standardize(d1)\n\t\td2 = self.standardize(d2)\n\t\tarrayData = [d1, d2]\n\t\ta = np.array(arrayData)\n\t\tcorrMatrix = np.corrcoef(a)\n\t\t#print ('corrM = ', corrMatrix)\n\t\tcc = corrMatrix[1,0]\n\t\tn = len(d1)\n\n\t\tcorr = math.fabs(cc * ((n-2) / (1-cc**2))**.5)\n\t\treturn corr\t\n\t\n\tdef getVarOrderOrg(self):\n\t\toVars = []\n\t\tR={}\n\t\tD = {}\n\t\tvNames = self.data.getSeriesNames()\n\t\tfor vName in vNames:\n\t\t\t#D[vName] = self.standardize(self.data.getSeries(vName))\n\t\t\tD[vName] = self.data.getSeries(vName)\n\t\twhile len(oVars) < len(vNames) - 1:\n\t\t\tR = {}\n\t\t\tmiCum = {}\n\t\t\tmostIndependent = None\n\t\t\tmiMin = 10.0**20\n\t\t\tfor j in range(len(vNames)):\n\t\t\t\tyD = []\n\t\t\t\tyNames = []\n\t\t\t\txName = vNames[j]\n\t\t\t\tif xName in oVars:\n\t\t\t\t\tcontinue\n\t\t\t\txD = D[xName]\n\t\t\t\tfor vName in vNames:\n\t\t\t\t\tif vName == xName:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif vName in oVars:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\td = D[vName]\n\t\t\t\t\tyNames.append(vName)\n\t\t\t\t\tyD.append(d)\n\t\t\t\t#coefs, resids = np.polyfit(xD, np.array(yD).T, 1, full=True)[:2]\n\t\t\t\t#print('coefs = ', coefs)\n\t\t\t\t#xcoefs = coefs[0]\n\t\t\t\t#kcoefs = coefs[1]\n\t\t\t\tR[xName] = {}\n\t\t\t\tmiCum[xName] = 0\n\t\t\t\tfor i in range(len(yNames)):\n\t\t\t\t\tyName = yNames[i]\n\t\t\t\t\tayD = np.array(yD[i])\n\t\t\t\t\taxD = np.array(xD)\n\t\t\t\t\t#coefs, resid = np.polyfit(yD[i], xD, 1, full=True)[:2]\n\t\t\t\t\txcoef = lstsq(np.array([yD[i]]).T, xD)[0][0]\n\t\t\t\t\t#txcoef = coefs[0]\n\t\t\t\t\t#print('coefs = ', coefs)\n\t\t\t\t\t#xcoef =\txcoefs[i]\n\t\t\t\t\t#kcoef = kcoefs[i]\n\t\t\t\t\t#resid = resids[i]\n\t\t\t\t\t#print('xcoef = ', xcoef,1/xcoef )\n\t\t\t\t\t\n\t\t\t\t\t# if not yName in R:\n\t\t\t\t\t\t# R[yName] = {}\n\t\t\t\t\t# if not yName in miCum:\n\t\t\t\t\t\t# miCum[yName] = 0\n\t\t\t\t\tycD = axD * xcoef\n\t\t\t\t\t#print('ycD = ', len(ycD))\n\t\t\t\t\tresidV = ayD - ycD\n\t\t\t\t\t#temp\n\t\t\t\t\t# testxcoef = 10**20\n\t\t\t\t\t# best = 10**20\n\t\t\t\t\t# bestR = None\n\t\t\t\t\t# count = 0\n\t\t\t\t\t# while math.fabs(testxcoef) > .01 and count < 5:\n\t\t\t\t\t\t# coefs2, resid2 = np.polyfit(residV, xD, 1, full=True)[:2]\n\t\t\t\t\t\t# testxcoef = coefs2[0]\n\t\t\t\t\t\t# axD2 = np.array(xD)\n\t\t\t\t\t\t# ayD2 = np.array(yD)\n\t\t\t\t\t\t# ycD2 = axD2 * testxcoef\n\t\t\t\t\t\t# r = ayD2 - ycD2\n\t\t\t\t\t\t# print ('testxcoef = ', testxcoef)\n\t\t\t\t\t\t# count += 1\n\t\t\t\t\t\t# if math.fabs(testxcoef) < best:\n\t\t\t\t\t\t\t# residV = r\n\t\t\t\t\t\n\t\t\t\t\t#print ('residV = ', residV.sum(), residV.mean(), residV.std())\n\t\t\t\t\t#print ('xName,yName, xcoef= ', xName, yName, xcoef)\n\t\t\t\t\t#print('xD, residV, yD[i] = ', xD, residV, yD[i])\n\t\t\t\t\tcorr = self.scoreDependence(xD, residV)\n\t\t\t\t\tcum = miCum[xName]\n\t\t\t\t\tif corr > cum:\n\t\t\t\t\t\tcum = corr\n\t\t\t\t\tmiCum[xName] = cum\n\t\t\t\t\tR[xName][yName] = residV\n\t\t\t\t\t#print(xName, '-->', yName, ': corr = ', corr)\n\t\t\t\t\t#print()\n\t\t\tlowestCorr = 10**20\n\t\t\tmostIndependent = None\n\t\t\t#print ('miCum = ', miCum)\n\t\t\tkeys = list(miCum.keys())\n\t\t\tkeys.sort()\n\t\t\tfor k in keys:\n\t\t\t\tcum = miCum[k]\n\t\t\t\t#print('cum(', k, ')=', cum)\n\t\t\tfor k in miCum.keys():\n\t\t\t\tcum = miCum[k]\n\t\t\t\tif cum < lowestCorr:\n\t\t\t\t\tlowestCorr = cum\n\t\t\t\t\tmostIndependent = k\n\t\t\t#print('mostIndependent2 = ', mostIndependent, lowestCorr)\n\t\t\t#print()\t\n\t\t\toVars.append(mostIndependent)\n\t\t\t# Regress all variables on the mostIndependent\n\t\t\tvarReg = R[mostIndependent]\n\t\t\tD = varReg \n\t\t\t#print('D = ', len(D), D.keys())\n\t\tfor v in D.keys():\n\t\t\tif v != mostIndependent:\n\t\t\t\toVars.append(v)\n\t\t#print('oVars = ', oVars)\n\t\treturn oVars\n\n\tdef getVarOrder_org(self):\n\t\toVars = self.data.getSeriesNames()\n\t\tscores = []\n\t\tfor i in range(len(oVars)):\n\t\t\tscore = 0\n\t\t\tvar = oVars[i]\n\t\t\td1 = self.data.getSeries(var)\n\t\t\tfor j in range(len(oVars)):\n\t\t\t\tif i == j:\n\t\t\t\t\tcontinue\n\t\t\t\td2 = self.data.getSeries(oVars[j])\n\t\t\t\tdirection = self.direction(var, oVars[j])\n\t\t\t\tif direction < 0:\n\t\t\t\t\tscore += 1\n\t\t\tscores.append((score, var))\n\t\t\t\t# nw = kr.KernelReg([d1], [d2], 'c', reg_type='ll', bw=[.002])\n\t\t\t\t# means, marginals = nw.fit()\n\t\t\t\t# r2 = nw.r_squared()\n\t\t\t\t# print('r2 = ', r2)\n\t\t\t\t# print ('means, marginals = ', means, marginals, var, oVars[j])\n\t\t\t\t# print ('mean = ', means.mean(), var, oVars[j])\n\t\t\t\t# break\n\t\t\t#break\n\t\tscores.sort()\n\t\t#print('scoreArray = ', scores)\n\t\treturn oVars\n\t\n\t\n\t\n\t# Calculate causal direction of between two vars using PairwiseLiNGAM tanh method\n\t# Returns: direction := > 0 if Var1 causes Var2 or < 0 if Var2 causes Var1. \n\t# Undefined if Var1 and Var2 are not causally related.\n\t\n\tdef direction(self, var1, var2):\n\t\ts1 = self.getDataSeries(var1)\n\t\ts2 = self.getDataSeries(var2)\n\t\tresult = self.direction2(s1, s2)\n\t\t#print ('R(', var1,'->', var2, ') =', result)\n\t\treturn result\n\t\n\tdef direction2(self, s1, s2):\n\t\ts1 = self.standardize(s1)\n\t\ts2 = self.standardize(s2)\n\t\tif DIR_TEST == 'PL':\n\t\t\t# Use pairwise direction determination\n\t\t\tdir = self.direction_PW(s1, s2)\n\t\telse:\n\t\t\t# Use the Darmois-Skitovich Theorem to determine pairwise direction based on a dependence test\n\t\t\tdir = self.direction_DS(s1, s2)\n\t\treturn dir\n\n\tdef direction_PW(self, s1, s2):\n\t\t# Pairwise Lingam Algorithm\n\t\tcum = 0\n\t\tfor i in range(len(s1)):\n\t\t\tv1 = s1[i]\n\t\t\tv2 = s2[i]\n\t\t\tcumulant = v1*math.tanh(v2) - v2*math.tanh(v1)\n\t\t\tcum += cumulant\n\t\tavg = cum / float(len(s1))\n\t\trho = self.getCorrCoef2(s1, s2)\n\t\tR = rho * avg\n\t\tDprint('R = ', R)\n\t\treturn R\n\n\tdef direction_DS(self, s1, s2):\n\t\t# Darmois-Skitovich method for determining pairwise causal direction based on independence of residuals\n\t\tres1 = self.calcResidual(s1, s2)\n\t\tres2 = self.calcResidual(s2, s1)\n\t\tif DIR_TEST == 'MI':\n\t\t\timport IndMI\n\t\t\tindMod = IndMI\n\t\telif DIR_TEST == 'HSIC':\n\t\t\timport IndHSIC\n\t\t\tindMod = IndHSIC\n\t\tdep1 = indMod.scoreDependence(s1, res1)\n\t\tdep2 = indMod.scoreDependence(s2, res2)\n\t\t# Direction is indicated by the order with the least dependence\n\t\tdir = dep2 - dep1\n\t\treturn dir\n\n\tdef calcResidual(self, s1, s2):\n\t\tcoefs = np.polyfit(s1, s2.T, 1)\n\t\tx1coef, x0coef = coefs\n\t\t#Dprint('coefs = ', coefs)\n\t\tcs2 = s1 * x1coef + x0coef\n\t\tres = s2 - cs2\n\t\treturn res\n\n\tdef getCorrCoef2(self, s1, s2):\n\t\tcc = np.corrcoef([s1,s2])\n\t\treturn cc[1,0]\n\n\tdef mi(self, d1, d2):\n\t\th1 = self.dentropy2(d1)\n\t\th2 = self.dentropy2(d2)\n\t\th3 = self.dentropy2(d1 + d2)\n\t\tresult = h1 + h2 - h3\n\t\t#print('dmi = ', result)\n\t\treturn result\n\t\t\n\tdef dentropy(self, var):\n\t\td = self.data.getSeries(var)\n\t\treturn self.dentropy2(d)\n\t\t\n\tdef dentropy2(self, d):\n\t\td = self.standardize(d)\n\t\tt1 = (math.log(math.pi*2)+1) / 2\n\t\tt2a = 0\n\t\tt3a = 0\n\t\tfor i in range(len(d)):\n\t\t\tt2a += math.log(math.cosh(d[i]))\n\t\t\tt3a += d[i]*math.e**((-d[i]**2)/2.0)\n\t\tt2 = 79.047*(t2a/float(len(d)) - .37457)**2\n\t\tt3 = 7.4129 * (t3a / float(len(d)))**2\n\t\tent = t1 - t2 -t3\n\t\t#print ('t1, t2, t3 = ', t1, t2, t3, t3a)\n\t\t#print ('ent = ', ent)\n\t\treturn ent\n\t\t\n#inputFileName = '..\\data\\synthData1.csv'\t\n#cal = IC(inputFileName)\n#print('dir(F,E) = ',cal.direction('F', 'E'))\n#cal.plotData()\n#print('dep = ', cal.scoreDependence(cal.data.getSeries('A'),cal.data.getSeries('E')))\n#dag = cal.getDAG()\n#print(dag)\n\n# cal.direction('138.42.94.173|Fa3/1/0|bytesIn', '138.42.94.173|Gi0/0/0|bytesOut')\n\n# cal.direction('A', 'E')\n# cal.direction('E', 'F')\n# cal.direction('G', 'F')\n# cal.direction('A', 'I')\n# cal.direction('E', 'D')\n# cal.direction('F', 'E')\n","sub_path":"py-archive/Lingam.py","file_name":"Lingam.py","file_ext":"py","file_size_in_byte":27492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"277608568","text":"#Voy a desarrollar los complementarios mas fáciles en forma de Funciones\n\n#1_Determinar el número mayor de 10 números ingresados.\ndef mayordetodos(lista):\n mayor = 0\n for i in range(len(lista)):\n if i > mayor:\n mayor = i\n return(mayor)\n\n#2) Desarrollar una solución que calcule la suma de los cuadrados de los n primeros números naturales: 1 + 22 + 32 +… + n2.\ndef sumadecuadrados(n):\n suma = 0\n for i in range(n):\n suma = suma + i**2\n return suma\n\n#3) Diseñar un programa que permita obtener el producto entre A y B mediante sumas sucesivas.\ndef sumasucesivas(A,B):\n producto = 0\n for i in range(B):\n producto = producto + A\n return producto\n\n#4) Diseñar un programa que imprima los números del 100 al 0 en orden decreciente.\ndef cienacero():\n imprimido = 100\n for i in range(100):\n print(imprimido)\n imprimido -=1\n\n#5) Solicitar el ingreso de números al usuario y emitir un mensaje para determinar si es par o impar. El ciclo debe finalizar cuando el usuario ingresa 0.\ndef paroimpar(op):\n while op != 0:\n if op %2 == 0:\n return('Es par')\n else:\n return('Es impar')\n if op == 0:\n return('Gracias por usar nuestros servicios')\n\n#6) Imprimir, contar y sumar los múltiplos de 2 que hay entre una serie de números, tal que el segundo sea mayor o igual que el primero.\n#18 24 === 20 22\ndef multiplo2(a, b):\n contador = 0\n suma = 0\n for i in range(a, b):\n if i % 2 == 0:\n print(i)\n contador +=1\n suma = suma + i\n\n# 7) Realizar un programa que calcule y muestre la suma de los múltiplos de 5 comprendidos \n# entre dos valores A y B. El programa no permitirá introducir valores negativos para A y B \n# y verificará que A es menor que B. \n# Si A es mayor que B, se deben intercambiar los valores.\ndef multiplo5(A,B):\n suma = 0\n if A >= 0 and B >= 0:\n if B > A:\n for i in range (A, B):\n if i % 5 == 0:\n suma = suma + i\n elif A > B:\n for j in range(B, A):\n if j % 5 == 0:\n suma = suma + j\n return(suma)\n\n\n# 8) Diseñar un programa que permita calcular el total de una compra, \n# ingresando cantidad y precio de los productos. \n# El programa debe estar preparado para que el ingreso de los datos se produzca hasta que \n# el usuario lo desee\n\ndef compra(opcion):\n total = 0\n cantidad = 0\n precio = 0\n while opcion == '1':\n precio = int(input('Ingrese el precio de su producto'))\n cantidad = int(input('Ingrese la cantidad que lleva'))\n total = total + (precio * cantidad)\n opcion = input('Presione 1 si desea seguir cargando productos')\n\n\n\n \n\n\n\n\n\n\n\n","sub_path":"Estructuras iterativas/Complementarios/complementarios_faciles.py","file_name":"complementarios_faciles.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"375302479","text":"# coding:utf-8\n\nimport torch.nn as nn\n\n\nclass ConvNet(nn.Module):\n def __init__(self):\n super(ConvNet, self).__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(1, 16, 3, 1),\n nn.ReLU()\n )\n self.conv2 = nn.Sequential(\n nn.Conv2d(16, 32, 3, 2),\n nn.ReLU()\n )\n self.conv3 = nn.Sequential(\n nn.Conv2d(32, 64, 3),\n nn.ReLU(),\n nn.MaxPool2d(3, 3)\n )\n self.fc1 = nn.Sequential(\n nn.Linear(384, 256),\n nn.Dropout(0.5)\n )\n self.fc2 = nn.Sequential(\n nn.Linear(256, 128)\n )\n self.fc3 = nn.Linear(128, 47)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n x = x.view(x.size(0), -1)\n x = self.fc1(x)\n x = self.fc2(x)\n return self.fc3(x)\n","sub_path":"com/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"298280179","text":"import time\r\nimport urllib.parse\r\nimport urllib.request\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium import webdriver\r\n\r\n\r\n# 사용자의 입력과 선택을 받는 함수\r\nclass Crawl:\r\n\r\n def __init__(self, search_word, start_date, end_date, choose):\r\n self.search_word = search_word\r\n self.start_date = start_date\r\n self.end_date = end_date\r\n self.choose = choose\r\n\r\n def mini(self):\r\n # 사용자의 선택에 따라 실행되는 함수\r\n if self.choose == 1:\r\n return self.search_image(self.search_word, self.start_date, self.end_date)\r\n if self.choose == 2:\r\n return self.search_text(self.search_word, self.start_date, self.end_date)\r\n\r\n # 입력을 전달받아 이미지를 검색하는 함수\r\n def search_image(self, search_word, start_date, end_date):\r\n binary = 'C:\\\\chromedriver\\\\chromedriver.exe'\r\n browser = webdriver.Chrome(binary)\r\n url = \"https://search.naver.com/search.naver?where=image&sm=tab_jum&query={0}&nso=p%3Afrom{1}to{2}\" \\\r\n .format(search_word, start_date, end_date)\r\n browser.get(url)\r\n # 무한 스크롤\r\n prev_height = browser.execute_script(\"return document.body.scrollHeight\")\r\n\r\n while True:\r\n # 스크롤을 화면 가장 아래로 내린다\r\n browser.execute_script(\"window.scrollTo(0,document.body.scrollHeight)\")\r\n time.sleep(3)\r\n curr_height = browser.execute_script(\"return document.body.scrollHeight\")\r\n if (curr_height == prev_height):\r\n break\r\n else:\r\n prev_height = curr_height\r\n time.sleep(3)\r\n # 소스코드 다운 & 원하는 값 추출\r\n html = browser.page_source\r\n browser.close()\r\n soup = BeautifulSoup(html, \"lxml\")\r\n img_list = soup.find_all(\"img\", class_=\"_image _listImage\")\r\n\r\n params = []\r\n for idx, val in enumerate(img_list):\r\n if val.get(\"data-lazy-src\") is not None:\r\n params.append(val.get(\"data-lazy-src\"))\r\n else:\r\n params.append(val.get(\"src\"))\r\n # 이미지 다운로드\r\n self.img_num = self.download_image(params, search_word)\r\n return params, self.img_num\r\n\r\n # 입력을 전달받아 뉴스를 검색하는 함수\r\n\r\n def search_text(self, search_word, start_date, end_date):\r\n list_title = []\r\n address = []\r\n idx = 1 # url 페이지 넘기기 위한 인덱스\r\n parse_word = urllib.parse.quote(search_word) # 한글인식이 안되서 url 파싱\r\n # 소스코드 다운 & 원하는 값 추출 반복\r\n while True:\r\n url_str = 'https://search.naver.com/search.naver?where=news&sm=tab_pge&query={0}&sort=0&' \\\r\n 'photo=0&field=0&pd=3&ds={1}&de={2}&cluster_rank=46&mynews=0&office_type=0&' \\\r\n 'office_section_code=0&news_office_checked=&nso=so:r,p:from20200101to20200201,a:all&' \\\r\n 'start={3}'.format(parse_word, start_date, end_date, idx)\r\n url = urllib.request.Request(url_str)\r\n result = urllib.request.urlopen(url).read().decode('utf-8')\r\n soup = BeautifulSoup(result, \"html.parser\")\r\n title = soup.find_all(\"a\", class_=\"news_tit\")\r\n for val in title:\r\n list_title.append(val[\"title\"])\r\n address.append(val[\"href\"])\r\n # 반복 여부 체크\r\n check = soup.find(\"a\", class_=\"btn_next\")\r\n if check[\"aria-disabled\"] == \"true\":\r\n break\r\n else:\r\n idx += 10\r\n cnt = len(list_title)\r\n return address, list_title, cnt\r\n\r\n def download_image(self, params, search_word):\r\n a = 0\r\n for idx, p in enumerate(params, 1):\r\n # 다운받을 폴더 경로 입력\r\n urllib.request.urlretrieve(p, \"C:\\\\image\\\\{}{}.jpg\".format(search_word, str(idx)))\r\n a = idx\r\n if idx == 50:\r\n break\r\n return a\r\n","sub_path":"first_project_class.py","file_name":"first_project_class.py","file_ext":"py","file_size_in_byte":4104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"624555511","text":"api_key = \"본인 키 입력\"\r\nfrom apiclient.discovery import build\r\nyoutube = build('youtube', 'v3', developerKey=api_key)\r\n\r\nres=youtube.channels().list(id='UCkUq-s6z57uJFUFBvZIVTyg',\r\n part='contentDetails').execute()\r\nprint(res)\r\n\r\nree = youtube.playlistItems().list(playlistId='UUkUq-s6z57uJFUFBvZIVTyg',\r\n part='snippet',\r\n maxResults=50).execute()\r\n\r\n\r\ndef get_channel_videos(channel_id):\r\n # get Uploads playlist id\r\n res = youtube.channels().list(id=channel_id,\r\n part='contentDetails').execute()\r\n playlist_id = res['items'][0]['contentDetails']['relatedPlaylists']['uploads']\r\n\r\n videos = []\r\n next_page_token = None\r\n\r\n while 1:\r\n res = youtube.playlistItems().list(playlistId=playlist_id,\r\n part='snippet',\r\n maxResults=50,\r\n pageToken=next_page_token).execute()\r\n videos += res['items']\r\n next_page_token = res.get('nextPageToken')\r\n\r\n if next_page_token is None:\r\n break\r\n\r\n return videos\r\n\r\nvideos = get_channel_videos('UCkUq-s6z57uJFUFBvZIVTyg')\r\nprint(len(videos))\r\n\r\nfor video in videos:\r\n print(video['snippet']['title'])\r\n\r\nres = youtube.videos().list(id=videos[0]['snippet']['resourceId']['videoId'], part= 'statistics').execute()\r\n\r\nprint(res)\r\n\r\n\r\ndef get_videos_stats(video_ids):\r\n stats = []\r\n for i in range(0, len(video_ids), 50):\r\n res = youtube.videos().list(id=','.join(video_ids[i:i + 50]),\r\n part='statistics').execute()\r\n stats += res['items']\r\n\r\n return stats\r\n\r\n\r\nvideo_ids = list(map(lambda x:x['snippet']['resourceId']['videoId'], videos))\r\nstats = get_videos_stats(video_ids)\r\nprint(len(stats))\r\nmost_disliked = sorted(stats, key=lambda x:int(x['statistics']['dislikeCount']), reverse=True)\r\nfor video in most_disliked:\r\n print(video['id'], video['statistics']['dislikeCount'])\r\n","sub_path":"API_channel.py","file_name":"API_channel.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"457542816","text":"\"\"\"\nLast update: 24 August 2020\nCreated: 24 August 2020\n\nGUI to control motorised VAT valve series 590\n\n@author: Victor Rogalev\n\"\"\"\n\nimport sys\nimport PyQt5.QtWidgets\nimport ValveUI\n\n\ndef main():\n app = PyQt5.QtWidgets.QApplication(sys.argv) # A new instance of QApplication\n form = ValveUI.ValveControlApp() # We set the form\n form.setWindowTitle('Valve Control 2020') # Change window name\n # form.resize(500, 500) # Resize the form\n form.show() # Show the form\n sys.exit(app.exec_()) # Handle exit case\n\n\nif __name__ == '__main__': # if we're running file directly and not importing it\n main() # run the main function","sub_path":"ValveGUI.py","file_name":"ValveGUI.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"227290953","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom extractor import *\n\nextractor = CLAbstractExtractor()\nparent_folder = \"../articles\"\noutput_folder = \"../output\"\n\nwith open(output_folder + \"/\" + \"log.txt\", \"w\") as log:\n for (_, _, filenames) in os.walk(parent_folder):\n for filename in filenames:\n try:\n candidates = extractor.read_from(filename, parent_folder)\n for i in range(0, len(candidates)):\n if len(candidates[i]) >= 200:\n last_stop = candidates[i].rfind(\".\")\n if last_stop == -1:\n raise ValueError(\"No stops found\")\n with open(output_folder + \"/\" + filename + \".txt\", \"w\")\\\n as result:\n result.write(candidates[i][0:last_stop + 1])\n result.flush()\n break\n except:\n log.write(filename + \"\\n\")\n log.flush()\n print(\"Couldn't process \" + filename)\n","sub_path":"abstractextractor/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"266688787","text":"\"\"\"\nInitialize a window with PyQt\n\"\"\"\n\nimport PyQt5.QtWidgets as qtw\n\nclass MainWindow(qtw.QWidget):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.setWindowTitle(\"my pyQt app\")\n\t\tself.show()\n\napp = qtw.QApplication([])\nmw = MainWindow()\napp.exec_()\n","sub_path":"course/01_init.py","file_name":"01_init.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"578790715","text":"# SI 206 Final Project\n# Cryptocurrency Project\n# Ari Feldberg, Alaa Shahin, Nick Sidor\n\nfrom pycoingecko import CoinGeckoAPI\nimport datetime\nimport time\nimport sqlite3\nimport os\nfrom pytrends.request import TrendReq\nfrom pytrends import dailydata\n\npytrends = TrendReq(hl='en-US', tz=360)\n\ncg = CoinGeckoAPI()\n\n\n# returns the last 100 days of Google Trends values for Dogecoin\ndef getDogecoinTrends():\n kw_list = \"dogecoin\"\n info = dailydata.get_daily_data(kw_list, 2021, 1, 2021, 4)\n info.reset_index(inplace=True)\n\n info['date'] = info['date'].astype(str)\n subset = info[[\"date\", \"dogecoin_unscaled\"]]\n\n tuples = [tuple(x) for x in subset.to_numpy()]\n tuples = tuples[-100:]\n\n return tuples\n\n\n# returns the last 25 days of doge price (in USD) that were not already added to the table from coingecko\ndef getPrevDOGE(cur, conn):\n cur.execute('SELECT date FROM DogeDateIDs')\n results = cur.fetchall()\n\n date_list = []\n for i in results:\n date_list.append(i[0])\n date_list = date_list[-25:]\n\n prevPrices = []\n for i in range(0, len(date_list)):\n date = date_list[i]\n format_str = '%Y-%m-%d'\n datetime_obj = datetime.datetime.strptime(date, format_str)\n date = str(datetime_obj.strftime('%d-%m-%Y')) + \" 00:00:00\"\n\n history = cg.get_coin_history_by_id(id='dogecoin', date=date, vs_currencies='usd', localization='false')\n\n price = history['market_data']['current_price']['usd']\n price = str(round(price, 5))\n\n prevPrices.append((price, date))\n\n time.sleep(0.3)\n\n return prevPrices\n\n\n# adds Google Trends values to tables and also adds dates to a separate table, with both having the same id/key\ndef addTrendsToTable(cur, conn):\n trendsData = getDogecoinTrends()\n cur.execute('SELECT id FROM DogecoinTrends')\n trend_list = cur.fetchall()\n\n x = 1\n count = len(trend_list)\n\n for x in range(25):\n x = count\n\n cur.execute(\"INSERT OR IGNORE INTO DogecoinTrends (id, trend_value) VALUES (?, ?)\", (count, trendsData[x][1]))\n cur.execute(\"INSERT OR IGNORE INTO DogeDateIDs (id, date) VALUES (?, ?)\", (count, trendsData[x][0]))\n count += 1\n\n conn.commit()\n\n\n# adds dogecoin price to DogecoinUSDPast table 25 prices at a time\ndef addPriceToTable(cur, conn):\n priceData = getPrevDOGE(cur, conn)\n cur.execute('SELECT id FROM DogecoinUSDPast')\n price_list = cur.fetchall()\n\n count = len(price_list)\n\n for i in range(25):\n cur.execute(\"INSERT OR IGNORE INTO DogecoinUSDPast (id, usd_price) VALUES (?, ?)\", (count, priceData[i][0]))\n count += 1\n\n conn.commit()\n\n\n# sets up three tables within crypto.db\ndef setUpTables(cur, conn):\n cur.execute(\"CREATE TABLE IF NOT EXISTS DogecoinUSDPast (id INTEGER PRIMARY KEY, usd_price INTEGER)\")\n cur.execute(\"CREATE TABLE IF NOT EXISTS DogecoinTrends (id INTEGER PRIMARY KEY, trend_value INTEGER)\")\n cur.execute(\"CREATE TABLE IF NOT EXISTS DogeDateIDs (id INTEGER PRIMARY KEY, date TEXT)\")\n conn.commit()\n\n\n# main executes the necessary functions to properly run doge.py\ndef main():\n path = os.path.dirname(os.path.abspath(__file__))\n conn = sqlite3.connect(path + '/crypto.db')\n cur = conn.cursor()\n\n setUpTables(cur, conn)\n\n addTrendsToTable(cur, conn)\n\n addPriceToTable(cur, conn)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"doge.py","file_name":"doge.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"149297647","text":"# -*- encoding: utf-8\n\nimport markdown\nfrom markdown.extensions.smarty import SmartyExtension\n\n\ndef title_markdown(md):\n \"\"\"Renders a Markdown string as HTML for use in a bookmark title.\"\"\"\n if len(md.splitlines()) != 1:\n raise ValueError(f\"Title must be at most one line; got {md!r}\")\n\n # We don't want titles to render with

or similar tags if they start\n # with a '#', so escape that if necessary.\n if md.startswith('#'):\n md = f'\\\\{md}'\n\n res = markdown.markdown(md, extensions=[SmartyExtension()])\n return res.replace('

', '').replace('

', '')\n","sub_path":"examples/images/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"380418220","text":"import json\nimport os\nimport pickle\nimport re\nimport time\nfrom operator import attrgetter\nfrom pathlib import Path\nfrom typing import Any, Iterable, Optional\n\nfrom libsyntyche.widgets import mk_signal2\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtCore import Qt\n\nfrom .. import declin, declin_qt\nfrom ..common import (CACHE_DIR, STATE_FILTER_KEY, STATE_SORT_KEY, Settings,\n SortBy, read_data_file)\nfrom ..taggedlist import (ATTR_BACKSTORY_PAGES, ATTR_BACKSTORY_WORDCOUNT,\n ATTR_FILE, ATTR_INDEX, ATTR_LAST_MODIFIED,\n ATTR_METADATA_FILE, ATTR_TITLE, ATTR_WORDCOUNT,\n AttributeData, AttrType, Entries, Entry,\n builtin_attrs, edit_entry, filter_entry)\n\nDECLIN_FILE = 'entry_layout.decl'\n\n\ndef calc_entry_layout(entry: Entry, visible_pos: int,\n m: declin_qt.Model, y: int, width: int,\n ) -> Optional[declin_qt.DrawGroup]:\n entry_dict = entry.as_dict()\n entry_dict['pos'] = visible_pos\n rect = declin_qt.StretchableRect(0, y, width=width)\n result = declin_qt.calc_size(entry_dict, m.sections[m.main], m, rect, 0)\n if result is not None:\n result.drawable.width = width\n return result\n\n\nclass EntryItem:\n def __init__(self, entry: Entry, real_pos: int) -> None:\n self.entry = entry\n self.group: Optional[declin_qt.DrawGroup]\n self.id_ = real_pos\n self.visible_pos = real_pos\n self.hidden = False\n self.needs_refresh = True\n self.y: int\n\n def height(self) -> int:\n if self.group is not None:\n return self.group.drawable.height\n return 0\n\n def change_data(self, *, entry: Optional[Entry] = None,\n visible_pos: Optional[int] = None,\n hidden: Optional[bool] = None) -> None:\n if entry is not None and entry != self.entry:\n self.needs_refresh = True\n self.entry = entry\n if visible_pos is not None and visible_pos != self.visible_pos:\n self.needs_refresh = True\n self.visible_pos = visible_pos\n if hidden is not None and hidden != self.hidden:\n self.needs_refresh = True\n self.hidden = hidden\n\n\nclass EntryList(QtWidgets.QWidget):\n\n visible_count_changed = mk_signal2(int, int)\n\n def __init__(self, parent: QtWidgets.QWidget, settings: Settings,\n dry_run: bool, statepath: Path, progress: QtWidgets.QProgressDialog) -> None:\n super().__init__(parent)\n self.setFocusPolicy(Qt.NoFocus)\n self._visible_to_real_pos: dict[int, int] = {}\n self._minimum_height = 0\n self.dry_run = dry_run\n self.settings = settings\n self.image_loader = declin_qt.ImageLoader(self.settings.path.value)\n self.progress = progress\n # Model values\n self.undostack: list[Entries] = []\n self.entry_items: list[EntryItem] = []\n # Attribute data\n self.gui = ''\n self.gui_model: declin_qt.Model\n self.attribute_data: AttributeData\n self.update_gui(recalc_and_redraw=False)\n state: dict[str, Any]\n try:\n state = pickle.loads(statepath.read_bytes())\n except FileNotFoundError:\n state = {\n STATE_FILTER_KEY: '',\n STATE_SORT_KEY: (ATTR_TITLE, False)\n }\n\n self.active_filter = state[STATE_FILTER_KEY]\n self.sorted_by = SortBy(*state[STATE_SORT_KEY])\n self.recalc_sizes()\n self.update()\n\n def count(self) -> int:\n return len(self.entry_items)\n\n def resizeEvent(self, ev: QtGui.QResizeEvent) -> None:\n super().resizeEvent(ev)\n if self.width() != ev.oldSize().width():\n self.update_gui(reload_file=False)\n\n def paintEvent(self, ev: QtGui.QPaintEvent) -> None:\n painter = QtGui.QPainter(self)\n painter.setRenderHint(QtGui.QPainter.Antialiasing, on=True)\n painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform, on=True)\n min_y = ev.rect().y()\n max_y = ev.rect().y() + ev.rect().height()\n for n, real_pos in sorted(self._visible_to_real_pos.items()):\n item = self.entry_items[real_pos]\n if item.group is None:\n continue\n r = item.group.drawable\n if item.y + r.height < min_y or item.y > max_y:\n continue\n for drawitem in sorted(item.group.flatten(),\n key=attrgetter('depth'), reverse=True):\n if item.y + drawitem.y + drawitem.height < min_y or item.y + drawitem.y > max_y:\n continue\n drawitem.draw(painter, item.y, self.image_loader)\n\n def recalc_sizes(self) -> None:\n y = 0\n width = self.width()\n for n, real_pos in sorted(self._visible_to_real_pos.items()):\n item = self.entry_items[real_pos]\n group = calc_entry_layout(item.entry, n, self.gui_model, 0, width)\n item.y = y\n item.group = group\n y += item.height()\n self._minimum_height = y\n self.updateGeometry()\n\n def minimumSizeHint(self) -> QtCore.QSize:\n return QtCore.QSize(0, self._minimum_height)\n\n def update_gui(self, reload_file: bool = True,\n recalc_and_redraw: bool = True) -> None:\n if reload_file:\n user_gui_file = self.settings.config_dir / DECLIN_FILE\n if user_gui_file.exists():\n new_gui = user_gui_file.read_text()\n else:\n new_gui = read_data_file(DECLIN_FILE)\n if new_gui == self.gui:\n return\n self.gui = new_gui\n try:\n gui_model = declin.parse(self.gui)\n except declin.common.ParsingError as e:\n print('GUI PARSING ERROR', e)\n else:\n self.attribute_data = builtin_attrs.copy()\n if not self.settings.use_text_file.value:\n del self.attribute_data[ATTR_WORDCOUNT]\n del self.attribute_data[ATTR_LAST_MODIFIED]\n self.attribute_data.update(gui_model.attributes)\n self.gui_model = declin_qt.Model(main=gui_model.main, sections=gui_model.sections)\n if recalc_and_redraw:\n self.recalc_sizes()\n self.update()\n\n @property\n def entries(self) -> Iterable[Entry]:\n return (i.entry for i in self.entry_items)\n\n @property\n def visible_entries(self) -> Iterable[Entry]:\n entries = []\n for n in self._visible_to_real_pos.values():\n entries.append(self.entry_items[n].entry)\n return entries\n\n def set_entries(self, new_entries: Entries) -> None:\n self.entry_items.clear()\n for n, entry in enumerate(new_entries):\n self.entry_items.append(EntryItem(entry, n))\n self.reorder(sort=True, filter_=True)\n\n def visible_entry(self, pos: int) -> Entry:\n return self.entry_items[self._visible_to_real_pos[pos]].entry\n\n def visible_count(self) -> int:\n return len(self._visible_to_real_pos)\n\n def reorder(self, *, sort: bool = False, filter_: bool = False) -> None:\n if not sort and not filter_:\n return\n\n sort_type = self.attribute_data[self.sorted_by.key].type_\n default_sort_value: Any = None\n if sort_type == AttrType.TEXT:\n default_sort_value = ''\n elif sort_type in {AttrType.INT, AttrType.FLOAT}:\n default_sort_value = -1\n\n def getter(entry_item: EntryItem) -> Any:\n return entry_item.entry.get(self.sorted_by.key, default_sort_value)\n\n sort_order_changed = False\n if sort:\n old_order = tuple(e.id_ for e in self.entry_items)\n self.entry_items.sort(\n key=getter,\n reverse=self.sorted_by.descending\n )\n new_order = tuple(e.id_ for e in self.entry_items)\n sort_order_changed = old_order != new_order\n if not sort_order_changed and not filter_:\n return\n pos = 0\n y = 0\n width = self.width()\n new_visible_to_real_pos = {}\n start_time = time.monotonic()\n progress_showing = False\n for n, item in enumerate(self.entry_items):\n if not progress_showing and time.monotonic() - start_time > 0.2:\n progress_showing = True\n self.progress.setLabelText('Redrawing entries...')\n self.progress.setMaximum(len(self.entry_items))\n self.progress.setValue(n)\n elif progress_showing:\n self.progress.setValue(n)\n if filter_:\n show_item = filter_entry(item.entry, self.active_filter, self.attribute_data,\n self.settings.tag_macros.value)\n item.change_data(hidden=not show_item)\n else:\n show_item = not item.hidden\n if show_item:\n item.change_data(visible_pos=pos)\n new_visible_to_real_pos[pos] = n\n item.y = y\n if item.needs_refresh:\n item.group = calc_entry_layout(item.entry, pos, self.gui_model, 0, width)\n item.needs_refresh = False\n y += item.height()\n pos += 1\n self.progress.reset()\n if len(self._visible_to_real_pos) != len(new_visible_to_real_pos):\n self.visible_count_changed.emit(pos, len(self.entry_items))\n self._visible_to_real_pos = new_visible_to_real_pos\n self._minimum_height = y\n self.updateGeometry()\n self.update()\n\n def undo(self) -> int:\n if not self.undostack:\n return 0\n items = {item.entry[ATTR_INDEX]: item for item in self.entry_items}\n undo_batch = self.undostack.pop()\n for entry in undo_batch:\n item = items[entry[ATTR_INDEX]]\n item.change_data(entry=entry)\n if not self.dry_run:\n write_metadata(undo_batch, self.attribute_data)\n self.reorder(sort=True, filter_=True)\n return len(undo_batch)\n\n def edit_(self, poses: Iterable[int], attribute: str, new_value: str) -> int:\n \"\"\"\n Edit one or more entries and return how many were changed.\n \"\"\"\n entry_undos = []\n do_filter = do_sort = False\n for pos in poses:\n real_pos = self._visible_to_real_pos[pos]\n item = self.entry_items[real_pos]\n old_entry = item.entry\n new_entry = edit_entry(old_entry, attribute, new_value, self.attribute_data)\n if new_entry != old_entry:\n entry_undos.append(old_entry)\n item.change_data(entry=new_entry)\n if not self.dry_run:\n write_metadata([new_entry], self.attribute_data)\n old_filter = filter_entry(old_entry, self.active_filter, self.attribute_data,\n self.settings.tag_macros.value)\n new_filter = filter_entry(new_entry, self.active_filter, self.attribute_data,\n self.settings.tag_macros.value)\n do_filter = do_filter or (old_filter != new_filter)\n do_sort = do_sort or (attribute == self.sorted_by.key)\n if not (do_filter or do_sort):\n old_height = item.height()\n item.group = calc_entry_layout(item.entry, item.visible_pos,\n self.gui_model, 0, self.width())\n new_height = item.height()\n item.needs_refresh = False\n if old_height != new_height:\n y_diff = new_height - old_height\n for visible_pos, real_pos in self._visible_to_real_pos.items():\n if visible_pos > item.visible_pos:\n self.entry_items[real_pos].y += y_diff\n self.update()\n if do_filter or do_sort:\n self.reorder(sort=do_sort, filter_=do_filter)\n if entry_undos:\n self.undostack.append(tuple(entry_undos))\n return len(entry_undos)\n\n\ndef get_backstory_data(file: Path, cached_data: dict[str, Any]) -> tuple[int, int]:\n root = file.with_name(f'{file.name}.metadir')\n if not root.is_dir():\n return 0, 0\n wordcount = 0\n pages = 0\n for dirpath, _, filenames in os.walk(root):\n dir_root = Path(dirpath)\n for fname in filenames:\n # Skip old revision files\n if re.search(r'\\.rev\\d+$', fname) is not None:\n continue\n try:\n words = len((dir_root / fname).read_text().split('\\n', 1)[1].split())\n except Exception:\n # Just ignore the file if something went wrong\n # TODO: add something here if being verbose?\n pass\n else:\n wordcount += words\n pages += 1\n return wordcount, pages\n\n\nclass UnrecognizedAttributeError(Exception):\n def __init__(self, key: str, file: Path) -> None:\n self.key = key\n self.file = file\n\n\ndef index_stories(root: Path, progress: QtWidgets.QProgressDialog,\n attributes: AttributeData, use_text_file: bool,\n ignore_path_dict: dict[str, str]) -> Entries:\n progress.setLabelText('Loading cache...')\n cache_file = CACHE_DIR / 'index.pickle'\n if cache_file.exists():\n cached_data = pickle.loads(cache_file.read_bytes())\n else:\n cache_file.parent.mkdir(parents=True, exist_ok=True)\n cached_data = {}\n root = root.resolve()\n entries = []\n ignore_paths = set(ignore_path_dict.values())\n i = 0\n progress.setLabelText('Indexing files...')\n hits = list(os.walk(root))\n progress.setLabelText('Reading file data...')\n progress.setMaximum(sum(len(fnames) for _, _, fnames in hits))\n n = 0\n for dirpath, _, filenames in hits:\n dir_root = Path(dirpath)\n if ignore_paths and dir_root != root and dir_root.name in ignore_paths:\n continue\n for meta_fname in filenames:\n progress.setValue(n)\n if not (meta_fname.startswith('.') and meta_fname.endswith('.metadata')):\n n += 1\n continue\n metafile = dir_root / meta_fname\n metadata = json.loads(metafile.read_text(encoding='utf-8'))\n entry_dict: dict[str, Any] = {}\n for key, value in metadata.items():\n if key not in attributes:\n raise UnrecognizedAttributeError(key, dir_root / meta_fname)\n entry_dict[key] = attributes[key]._load_value(value)\n entry_dict[ATTR_INDEX] = i\n text_fname = meta_fname[1:].rsplit('.', 1)[0]\n file = dir_root / text_fname\n entry_dict[ATTR_FILE] = file\n if use_text_file:\n stat = file.stat()\n if file in cached_data and cached_data[file]['modified'] == stat.st_mtime:\n wordcount = cached_data[file]['wordcount']\n else:\n wordcount = len(file.read_text().split())\n cached_data[file] = {'modified': stat.st_mtime, 'wordcount': wordcount}\n entry_dict[ATTR_WORDCOUNT] = wordcount\n entry_dict[ATTR_LAST_MODIFIED] = stat.st_mtime\n (entry_dict[ATTR_BACKSTORY_WORDCOUNT],\n entry_dict[ATTR_BACKSTORY_PAGES]) = get_backstory_data(file, cached_data)\n entry_dict[ATTR_METADATA_FILE] = metafile\n entries.append(Entry(entry_dict))\n i += 1\n n += 1\n progress.setMaximum(0)\n progress.setValue(0)\n progress.setLabelText('Saving cache...')\n cache_file.write_bytes(pickle.dumps(cached_data))\n return tuple(entries)\n\n\ndef write_metadata(entries: Iterable[Entry], attributes: AttributeData) -> None:\n for entry in entries:\n metadata = {\n name: attr._encode_value(entry)\n for name, attr in attributes.items()\n if attr.editable\n }\n entry[ATTR_METADATA_FILE].write_text(json.dumps(metadata), encoding='utf-8')\n","sub_path":"sapfo/index/entrylist.py","file_name":"entrylist.py","file_ext":"py","file_size_in_byte":16390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"593593735","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport os\n\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('utf8')\nfrom setuptools import setup, find_packages\n\nlong_description = ''\nif os.path.exists(\"PIP_README.md\"):\n with open(\"PIP_README.md\", \"r\") as fh:\n long_description = fh.read()\nsetup(\n name=\"guozhi\",\n version=\"0.1.6\",\n author=\"yebing\",\n author_email=\"cui_com@qq.com\",\n maintainer_email=\"cui_com@qq.com\",\n description=\"python-iot-sdk for guozhiyun\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://gitee.com/cui_com/jucie-python-sdk.git\",\n package_dir={\"\": \"src\"},\n packages=find_packages(where=\"src\"),\n install_requires=[\n 'paho-mqtt>=1.4.0'\n 'Adafruit-DHT>=1.4.0'\n ],\n zip_safe=False\n)\n","sub_path":"pypi_install_script/guozhi-0.1.6.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"646304085","text":"#!/usr/bin/python3\n\"\"\" The file that will be used to store in MYSQL with sqlalchemy\"\"\"\n\nfrom models.base_model import BaseModel, Base\nfrom models.user import User\nfrom models.state import State\nimport os\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, scoped_session\n\n\nclass DBStorage:\n \"\"\"the storage engine for mySQL using MYsqlALchemy\"\"\"\n __engine = None\n __session = None\n\n def __init__(self):\n \"\"\"initializes the engine\"\"\"\n user = os.getenv(\"HBNB_MYSQL_USER\")\n psswd = os.getenv(\"HBNB_MYSQL_PWD\")\n host = os.getenv(\"HBNB_MYSQL_HOST\")\n db = os.getenv(\"HBNB_MYSQL_DB\")\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'\n .format(user, psswd, host, db),\n pool_pre_ping=True)\n\n if os.getenv(\"HBNB_ENV\") == \"test\":\n Base.metadata.drop_all(self.__engine)\n\n def all(self, cls=None):\n class_list = [\"State\", \"City\", \"User\", \"Place\", \"Review\", \"Amenity\"]\n class_info = {}\n if cls:\n for data in self.__session.query(eval(cls)).all():\n info = type(data).__name__ + '.' + data.id\n class_info[info] = data\n else:\n for classes in class_list:\n for data in self.__session.query(eval(classes)).all():\n info = type(data).__name__ + '.' + data.id\n class_info[info] = data\n return class_info\n\n def new(self, obj):\n \"\"\"adds a new object to the database,\n keep im mind is not yet commited\"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"saves everything made in the session to the database\"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"deletes the object if it exist\"\"\"\n if obj is not None:\n self.__session.delete(obj)\n\n def reload(self):\n \"\"\"creates the sesssion so we can make changes\"\"\"\n Base.metadata.create_all(self.__engine)\n session_maker = sessionmaker(bind=self.__engine,\n expire_on_commit=False)\n session = scoped_session(session_maker)\n self.__session = session()\n\n def close(self):\n self.__session.close()\n","sub_path":"models/engine/db_storage.py","file_name":"db_storage.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"434727582","text":"from pymongo import MongoClient\n\nclient = MongoClient()\nconnection = client.test\n\nconnection.create_collection(\"projects\")\nconnection.create_collection(\"users\")\nconnection.create_collection(\"roles\")\nconnection.create_collection(\"paygrades\")\n\nprojects = connection.projects\nusers = connection.users\nroles = connection.roles\npaygrades = connection.paygrades\n\nroles.insert_one({\"title\": \"Admin\"})\nroles.insert_one({\"title\": \"All Staff\"})\nroles.insert_one({\"title\": \"Delivery Manager\"})\n\nusers.insert_one({ \"_id\" : \"ADMIN\", \"password\" : \"pbkdf2:sha1:1000$l6RzU94o$dd8d80a18509fa2f3d1f6f5b6ed9d42bf3b41bab\", \"paygrade\" : \"RE1\", \"workdays\" : { \"Thursday\" : \"7.5\", \"Wednesday\" : \"7.5\", \"Friday\" : \"7.5\", \"Monday\" : \"7.5\", \"Tuesday\" : \"7.5\" }, \"lastname\" : \"User\", \"role\" : \"Admin\", \"firstname\" : \"Admin\" })\n\npaygrades.insert_one({ \"_id\" : \"RE2L\", \"hourly_rate\" : 12 })\npaygrades.insert_one({ \"_id\" : \"RO\", \"hourly_rate\" : 10 })\npaygrades.insert_one({ \"_id\" : \"RE2U\", \"hourly_rate\" : 14 })\npaygrades.insert_one({ \"_id\" : \"RE1\", \"hourly_rate\" : 16 })\n\nprojects.insert_one({ \"_id\" : \"P1\", \"name\" : \"Project 1\" })\nprojects.insert_one({ \"_id\" : \"P2\", \"name\" : \"Project 2\" })\nprojects.insert_one({ \"_id\" : \"P3\", \"name\" : \"Project 3\" })\nprojects.insert_one({ \"_id\" : \"P4\", \"name\" : \"Project 4\" })\nprojects.insert_one({ \"_id\" : \"P5\", \"name\" : \"Project 5\" })\nprojects.insert_one({ \"_id\" : \"LEAVE\", \"name\" : \"Leave\" })\nprojects.insert_one({ \"_id\" : \"OLEAVE\", \"name\" : \"Other Leave\" })\n\n","sub_path":"scripts/setup-db.py","file_name":"setup-db.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"264013124","text":"from __future__ import absolute_import # fixes oddball warnings in pycharm\nimport unittest\nimport main\nimport proj1\nimport pandas as pd\n\n\nclass TestProject1(unittest.TestCase):\n\n def test_direct_left_single(self):\n episodes = [[3, 2, 1, 0]]\n weights, episode_count = proj1.experiment(episodes, lmda=0.5, alpha=1., w0=0.)\n self.assertListEqual(list(weights), [1., 1., 0.5, 0.25, 0., 0., 0.])\n\n def test_direct_right_single(self):\n episodes = [[3, 4, 5, 6]]\n weights, episode_count = proj1.experiment(episodes, lmda=0.5, alpha=1., num_batches=1, batch_size=1, update_freq='batch', repeat=False)\n self.assertListEqual(list(weights), [1., 0., 0., 0., 0., 0, 0])\n\n def test_right_then_left_single(self):\n episodes = [[3, 4, 5, 4, 3, 2, 1, 0]]\n weights, episode_count = proj1.experiment(episodes, 0.5, 1.)\n self.assertListEqual(list(weights), [1.0, 1.0, 0.5, 0.265625, 0.15625, 0.0625, 0.0])\n\n def test_direct_left_lambda1(self):\n episodes = [[3,2,1,0]]\n weights, episode_count = proj1.experiment(episodes=episodes, lmda=1., alpha=1., num_batches=1, batch_size=1, update_freq='episode', repeat=False)\n self.assertListEqual([1.,1.,1.,1.,0.,0.,0.], list(weights))\n\n def test_direct_right_direct_left_1_batch_lambda1(self):\n episodes = [[3, 2, 1, 0], [3, 4, 5, 6]]\n weights, episode_count = proj1.experiment(episodes=episodes, lmda=1., alpha=1., num_batches=1, batch_size=2, update_freq='episode', repeat=False)\n self.assertListEqual(list(weights), [1.,1.,1.,0.,0.,0.,0.])\n\n def test_direct_right_4_episodes_1_batch_lambda0(self):\n episodes = [[3, 2, 1, 0], [3, 2, 1, 0], [3, 2, 1, 0], [3, 2, 1, 0]]\n weights, episode_count = proj1.experiment(episodes=episodes, lmda=0., alpha=1., num_batches=1, batch_size=4,\n update_freq='episode', repeat=False)\n self.assertListEqual(list(weights), [1.,1.,1.,1.,0.,0.,0.])\n\n def test_repeat_3210_converges(self):\n episodes = [[3,2,1,0]]\n weights, episode_count = proj1.experiment(episodes=episodes, lmda=0.5, alpha=0.5, w0=0., num_batches=1, batch_size=1, update_tol=0.000001,\n update_freq='batch', repeat=True)\n self.assertAlmostEqual(1.,weights[1], places=3)\n self.assertAlmostEqual(1., weights[2], places=3)\n self.assertAlmostEqual(1., weights[3], places=2)\n self.assertEqual(0., weights[4])\n\ndef suite():\n tests = ['test_direct_right_single', 'test_direct_right_single', 'test_right_then_left_single' 'test_direct_left_lambda1', 'test_direct_right_direct_left_1_batch_lambda1', 'test_direct_right_4_episodes_1_batch_lambda0']\n return unittest.TestSuite(tests)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tdl/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"126351762","text":"\"\"\"Chrome Version History API calls\"\"\"\n\nimport re\nimport sys\n\nimport gam\nfrom gam.var import *\nfrom gam import controlflow\nfrom gam import display\nfrom gam import gapi\nfrom gam import utils\n\n\ndef build():\n return gam.buildGAPIObjectNoAuthentication('versionhistory')\n\n\nCHROME_HISTORY_ENTITY_CHOICES = {\n 'platforms',\n 'channels',\n 'versions',\n 'releases',\n }\n\nCHROME_VERSIONHISTORY_ORDERBY_CHOICE_MAP = {\n 'versions': {\n 'channel': 'channel',\n 'name': 'name',\n 'platform': 'platform',\n 'version': 'version'\n },\n 'releases': {\n 'channel': 'channel',\n 'endtime': 'endtime',\n 'fraction': 'fraction',\n 'name': 'name',\n 'platform': 'platform',\n 'starttime': 'starttime',\n 'version': 'version'\n }\n }\n\nCHROME_VERSIONHISTORY_TITLES = {\n 'platforms': ['platform'],\n 'channels': ['channel', 'platform'],\n 'versions': ['version', 'channel', 'platform',\n 'major_version', 'minor_version', 'build', 'patch'],\n 'releases': ['version', 'channel', 'platform',\n 'major_version', 'minor_version', 'build', 'patch',\n 'fraction', 'serving.startTime','serving.endTime']\n }\n\ndef get_relative_milestone(channel='stable', minus=0):\n '''\n takes a channel and minus like stable and -1.\n returns current given milestone number\n '''\n cv = build()\n parent = f'chrome/platforms/all/channels/{channel}/versions/all'\n releases = gapi.get_all_pages(cv.platforms().channels().versions().releases(),\n 'list',\n 'releases',\n parent=parent,\n fields='releases/version,nextPageToken')\n milestones = []\n # Note that milestones are usually sequential but some numbers\n # may be skipped. For example, there was no Chrome 82 stable.\n # Thus we need to do more than find the latest version and subtract.\n for release in releases:\n milestone = release.get('version').split('.')[0]\n if milestone not in milestones:\n milestones.append(milestone)\n milestones.sort(reverse=True)\n try:\n return milestones[minus]\n except IndexError:\n return ''\n\ndef get_platform_map(cv=None):\n '''returns dict mapping of platform choices'''\n if cv is None:\n cv = build()\n result = gapi.get_all_pages(cv.platforms(),\n 'list',\n 'platforms',\n parent='chrome')\n platforms = [p.get('platformType', '').lower() for p in result]\n platform_map = {'all': 'all'}\n for cplatform in platforms:\n key = cplatform.replace('_', '')\n platform_map[key] = cplatform\n return platform_map\n\n\ndef get_channel_map(cv=None):\n '''returns dict mapping of channel choices'''\n if cv is None:\n cv = build()\n result = gapi.get_all_pages(cv.platforms().channels(),\n 'list',\n 'channels',\n parent='chrome/platforms/all')\n channels = [c.get('channelType', '').lower() for c in result]\n channels = list(set(channels))\n channel_map = {'all': 'all'}\n for channel in channels:\n key = channel.replace('_', '')\n channel_map[key] = channel\n return channel_map\n\ndef printHistory():\n cv = build()\n entityType = sys.argv[3].lower().replace('_', '')\n if entityType not in CHROME_HISTORY_ENTITY_CHOICES:\n msg = f'{entityType} is not a valid argument to \"gam print chromehistory\"'\n controlflow.system_error_exit(3, msg)\n todrive = False\n csvRows = []\n cplatform = 'all'\n channel = 'all'\n version = 'all'\n kwargs = {}\n orderByList = []\n i = 4\n while i < len(sys.argv):\n myarg = sys.argv[i].lower().replace('_', '')\n if myarg == 'todrive':\n todrive = True\n i += 1\n elif entityType != 'platforms' and myarg == 'platform':\n cplatform = sys.argv[i + 1].lower().replace('_', '')\n platform_map = get_platform_map(cv)\n if cplatform not in platform_map:\n controlflow.expected_argument_exit('platform',\n ', '.join(platform_map),\n cplatform)\n cplatform = platform_map[cplatform]\n i += 2\n elif entityType in {'versions', 'releases'} and myarg == 'channel':\n channel = sys.argv[i + 1].lower().replace('_', '')\n channel_map = get_channel_map(cv)\n if channel not in channel_map:\n controlflow.expected_argument_exit('channel',\n ', '.join(channel_map),\n channel)\n channel = channel_map[channel]\n i += 2\n elif entityType == 'releases' and myarg == 'version':\n version = sys.argv[i + 1]\n i += 2\n elif entityType in {'versions', 'releases'} and myarg == 'orderby':\n fieldName = sys.argv[i + 1].lower().replace('_', '')\n i += 2\n if fieldName in CHROME_VERSIONHISTORY_ORDERBY_CHOICE_MAP[entityType]:\n fieldName = CHROME_VERSIONHISTORY_ORDERBY_CHOICE_MAP[entityType][fieldName]\n orderBy = ''\n if i < len(sys.argv):\n orderBy = sys.argv[i].lower()\n if orderBy in SORTORDER_CHOICES_MAP:\n orderBy = SORTORDER_CHOICES_MAP[orderBy]\n i += 1\n if orderBy != 'DESCENDING':\n orderByList.append(fieldName)\n else:\n orderByList.append(f'{fieldName} desc')\n else:\n controlflow.expected_argument_exit('orderby',\n ', '.join(CHROME_VERSIONHISTORY_ORDERBY_CHOICE_MAP[entityType]),\n fieldName)\n elif entityType in {'versions', 'releases'} and myarg == 'filter':\n kwargs['filter'] = sys.argv[i + 1]\n i += 2\n else:\n msg = f'{myarg} is not a valid argument to \"gam print chromehistory {entityType}\"'\n controlflow.system_error_exit(3, msg)\n if orderByList:\n kwargs['orderBy'] = ','.join(orderByList)\n if entityType == 'platforms':\n svc = cv.platforms()\n parent = 'chrome'\n elif entityType == 'channels':\n svc = cv.platforms().channels()\n parent = f'chrome/platforms/{cplatform}'\n elif entityType == 'versions':\n svc = cv.platforms().channels().versions()\n parent = f'chrome/platforms/{cplatform}/channels/{channel}'\n else: #elif entityType == 'releases'\n svc = cv.platforms().channels().versions().releases()\n parent = f'chrome/platforms/{cplatform}/channels/{channel}/versions/{version}'\n reportTitle = f'Chrome Version History {entityType.capitalize()}'\n page_message = gapi.got_total_items_msg(reportTitle, '...\\n')\n gam.printGettingAllItems(reportTitle, None)\n citems = gapi.get_all_pages(svc, 'list', entityType,\n page_message=page_message,\n parent=parent,\n fields=f'nextPageToken,{entityType}',\n **kwargs)\n for citem in citems:\n for key in list(citem):\n if key.endswith('Type'):\n newkey = key[:-4]\n citem[newkey] = citem.pop(key)\n if 'channel' in citem:\n citem['channel'] = citem['channel'].lower()\n else:\n channel_match = re.search(r'\\/channels\\/([^/]*)', citem['name'])\n if channel_match:\n try:\n citem['channel'] = channel_match.group(1)\n except IndexError:\n pass\n if 'platform' in citem:\n citem['platform'] = citem['platform'].lower()\n else:\n platform_match = re.search(r'\\/platforms\\/([^/]*)', citem['name'])\n if platform_match:\n try:\n citem['platform'] = platform_match.group(1)\n except IndexError:\n pass\n\n if citem.get('version', '').count('.') == 3:\n citem['major_version'], \\\n citem['minor_version'], \\\n citem['build'], \\\n citem['patch'] = citem['version'].split('.')\n citem.pop('name')\n csvRows.append(utils.flatten_json(citem))\n display.write_csv_file(csvRows, CHROME_VERSIONHISTORY_TITLES[entityType], reportTitle, todrive)\n","sub_path":"src/gam/gapi/chromehistory.py","file_name":"chromehistory.py","file_ext":"py","file_size_in_byte":8718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"90912237","text":"\"\"\"\n\n\"\"\"\n\nclass ListNode(object):\n\tdef __init__(self,x):\n\t\tself.val = x\n\t\tself.next = None\n\tdef __repr__(self):\n\t\tif self:\n\t\t\treturn \"{}->{}\".format(self.val,repr(self.next))\nclass Solution(object):\n\tdef deleteNode(self,head,node):\n\t\t\"\"\"\n\t\t:type node: ListNode\n\t\t\"\"\"\n\t\tprint(head)\n\t\tif node.next:\n\t\t\tnode.val = node.next.val\n\t\t\tnode.next = node.next.next\n\t\treturn head\n\nhead = ListNode(3)\nhead.next = ListNode(5)\nhead.next.next = ListNode(7)\nhead.next.next.next = ListNode(10)\nsolution = Solution()\nprint(solution.deleteNode(head,head.next))\n","sub_path":"linkedlist/leetcode/deletenode/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"89978129","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport ctypes\nimport time\nimport platform\n\nimport os\nimport sys\nimport tempfile\nimport re\n\nif sys.version_info >= (3, 0):\n import urllib.parse\n\n\nfrom hardware.XYStage import XYStage\n\nfrom hardware.standa.pyximc import *\n\nclass Standa_XY(XYStage):\n def __init__(self, mac_guiver):\n self.lib = None\n self.device_id = None\n self.step_multiplier = 40\n super(Standa_XY, self).__init__(mac_guiver, frameName=\"Standa_XY\", mm_name=\"StandaXY\")\n\n\n def load_device(self, params=None):\n \"\"\"\n * Device name has form \"xi-com:port\" or \"xi-net://host/serial\" or \"xi-emu://file\".\n\t\t* In case of USB-COM port the \"port\" is the OS device name.\n\t\t* For example \"xi-com:\\\\\\.\\COM3\" in Windows or \"xi-com:/dev/tty.s123\" in Linux/Mac.\n\n\t\tLokk in the gestionnaire de périphérique\n :return:\n \"\"\"\n # self.mmc.loadDevice(self.mm_name, \"Standa8SMC4\", \"Standa8SMC4XY\")\n #\n # self.mmc.setProperty(self.mm_name, \"Port X\", \"xi-com:%5C%5C.%5CCOM6\")\n # self.mmc.setProperty(self.mm_name, \"Port Y\", \"xi-com:%5C%5C.%5CCOM7\")\n # self.mmc.setProperty(self.mm_name, \"UnitMultiplierX\", \"0.054\")\n # self.mmc.setProperty(self.mm_name, \"UnitMultiplierY\", \"0.054\")\n # self.mmc.initializeDevice(self.mm_name)\n\n self.mac_guiver.write_to_splash_screen(\"Loading XY standa\")\n\n # Load library\n def __ximc_shared_lib(dll_path):\n try:\n # if platform.system() == \"Linux\":\n # return CDLL(\"libximc.so\")\n # elif platform.system() == \"FreeBSD\":\n # return CDLL(\"libximc.so\")\n # elif platform.system() == \"Darwin\":\n # return CDLL(\"libximc.framework/libximc\")\n # elif platform.system() == \"Windows\":\n # return WinDLL(\"standa/libximc.dll\")\n # else:\n # return None\n return ctypes.WinDLL(dll_path)\n\n # except ImportError as err:\n # self.mac_guiver.write_to_splash_screen(\n # \"Can't import pyximc module. The most probable reason is that you changed the relative location \"\n # \"of the Standa_XY.py and pyximc.py files. See developers' documentation for details.\",\n # type=\"warn\")\n # return None\n except OSError as err:\n self.mac_guiver.write_to_splash_screen(\n \"Can't load libximc library. Please add all shared libraries to the appropriate places. It is \"\n \"decribed in detail in developers' documentation. On Linux make sure you installed libximc-dev \"\n \"package.\\nmake sure that the architecture of the system and the interpreter is the same\",\n type=\"warn\")\n return None\n\n\n # TODO direct to the standa repertory for the dll\n cur_dir = os.path.abspath(os.path.dirname(__file__))\n # ximc_dir = os.path.join(cur_dir, \"..\", \"..\", \"ximc\")\n # ximc_package_dir = os.path.join(ximc_dir, \"crossplatform\", \"wrappers\", \"python\")\n ximc_dir = os.path.normpath(os.path.join(cur_dir, \"standa\"))\n ximc_package_dir = ximc_dir\n sys.path.append(ximc_package_dir) # add ximc.py wrapper to python path\n\n # variable 'lib' points to a loaded library\n # note that ximc uses stdcall on win\n # if sys.platform in (\"win32\", \"win64\"):\n # libdir = os.path.join(ximc_dir, sys.platform)\n # os.environ[\"Path\"] = libdir + \";\" + os.environ[\"Path\"] # add dll\n\n # test if lib file exits\n ximc_file_path = os.path.normpath(os.path.join(ximc_dir, \"libximc.dll\"))\n file_exist = os.path.isfile(ximc_file_path)\n\n # The libximc.dll depends on other dll, and we need to change the working directory for the program to find them\n os.chdir(ximc_dir)\n\n self.lib = __ximc_shared_lib(ximc_file_path)\n root_path = os.path.dirname(sys.modules['__main__'].__file__)\n os.chdir(root_path)\n if self.lib is None:\n return False\n\n self.mac_guiver.write_to_splash_screen(\"ximc.dll found\")\n\n # Clarify function types\n self.lib.enumerate_devices.restype = POINTER(device_enumeration_t)\n self.lib.get_device_name.restype = c_char_p\n\n # print(\"Library loaded\")\n self.sbuf = create_string_buffer(64)\n self.lib.ximc_version(self.sbuf)\n # print(\"Library version: \" + self.sbuf.raw.decode().rstrip(\"\\0\"))\n\n self.mac_guiver.write_to_splash_screen(\"Searching for devices. Wait 1 or 2 s\")\n\n # Set bindy (network) keyfile. Must be called before any call to \"enumerate_devices\" or \"open_device\" if you\n # wish to use network-attached controllers. Accepts both absolute and relative paths, relative paths are resolved\n # relative to the process working directory. If you do not need network devices then \"set_bindy_key\" is optional.\n # In Python make sure to pass byte-array object to this function (b\"string literal\").\n # lib.set_bindy_key(os.path.join(ximc_dir, \"win32\", \"keyfile.sqlite\").encode(\"utf-8\"))\n self.lib.set_bindy_key(os.path.join(ximc_dir, \"keyfile.sqlite\").encode(\"utf-8\"))\n\n # This is device search and enumeration with probing. It gives more information about devices.\n probe_flags = EnumerateFlags.ENUMERATE_PROBE + EnumerateFlags.ENUMERATE_NETWORK\n enum_hints = b\"addr=192.168.0.1,172.16.2.3\"\n # enum_hints = b\"addr=\" # Use this hint string for broadcast enumerate\n self.devenum = self.lib.enumerate_devices(probe_flags, enum_hints)\n # print(\"Device enum handle: \" + repr(self.devenum))\n # print(\"Device enum handle type: \" + repr(type(self.devenum)))\n\n self.dev_count = self.lib.get_device_count(self.devenum)\n\n if self.dev_count == 0 :\n self.mac_guiver.write_to_splash_screen(\"No device found. Check connections\", type=\"warn\")\n return False\n\n self.mac_guiver.write_to_splash_screen(\"Device count: \" + repr(self.dev_count))\n\n self.controller_name = controller_name_t()\n for dev_ind in range(0, self.dev_count):\n self.enum_name = self.lib.get_device_name(self.devenum, dev_ind)\n result = self.lib.get_enumerate_device_controller_name(self.devenum, dev_ind, byref(self.controller_name))\n if result == Result.Ok:\n self.mac_guiver.write_to_splash_screen(\"Enumerated device #{} name (port name): \".format(dev_ind) + repr(\n self.enum_name) + \". Friendly name: \" + repr(self.controller_name.ControllerName) + \".\")\n\n self.open_name = None\n # if len(sys.argv) > 1:\n # self.open_name = sys.argv[1]\n # elif self.dev_count > 0:\n # self.open_name = self.lib.get_device_name(self.devenum, 0)\n # elif sys.version_info >= (3, 0):\n # # use URI for virtual device when there is new urllib python3 API\n # self.tempdir = tempfile.gettempdir() + \"/testdevice.bin\"\n # if os.altsep:\n # self.tempdir = self.tempdir.replace(os.sep, os.altsep)\n # # urlparse build wrong path if scheme is not file\n # uri = urllib.parse.urlunparse(urllib.parse.ParseResult(scheme=\"file\", \\\n # netloc=None, path=self.tempdir, params=None, query=None,\n # fragment=None))\n # open_name = re.sub(r'^file', 'xi-emu', uri).encode()\n\n self.open_name_x = self.lib.get_device_name(self.devenum, 0)\n self.open_name_y = self.lib.get_device_name(self.devenum, 1)\n\n\n # if type(self.open_name) is str:\n self.open_name_x = self.open_name_x.encode()\n self.open_name_y = self.open_name_y.encode()\n\n self.mac_guiver.write_to_splash_screen(\"Open device \" + repr(self.open_name_x))\n self.device_id_x = self.lib.open_device(self.open_name_x)\n self.mac_guiver.write_to_splash_screen(\"Device id: \" + repr(self.device_id_x))\n\n self.mac_guiver.write_to_splash_screen(\"Open device \" + repr(self.open_name_y))\n self.device_id_y = self.lib.open_device(self.open_name_y)\n self.mac_guiver.write_to_splash_screen(\"Device id: \" + repr(self.device_id_y))\n\n return True\n\n\n def move_absolute(self, pos_micron):\n \"\"\"\n result t XIMC API command move ( device t id, int Position, int uPosition )\n Position position to move.\n uPosition part of the position to move, microsteps. Range: -255..255.\n\n Upon receiving the command ”move” the engine starts to move with pre-set parameters (speed, acceleration, retention),\n to the point specified to the Position, uPosition.\n For stepper motor uPosition sets the microstep, for DC motor this field is not used.\n\n :param pos_micron:\n :return:\n \"\"\"\n nb_of_step_x = int(pos_micron[0])\n nb_of_step_y = int(pos_micron[1])\n\n result = self.lib.command_move(self.device_id_x, nb_of_step_x[0], 0)\n self.lib.command_move(self.device_id_y, nb_of_step_y[1], 0)\n return result\n\n\n def move_relative(self, pos_micron):\n \"\"\"\n result t XIMC API command move ( device t id, int Position, int uPosition )\n Position position to move.\n uPosition part of the position to move, microsteps. Range: -255..255.\n\n Upon receiving the command ”movr” engine starts to move with pre-set parameters (speed, acceleration, hold),\n left or right (depending on the sign of DeltaPosition) by the number of pulses specified in the fields DeltaPosition,\n uDeltaPosition.\n\n DeltaPosition shift from initial position\n uDeltaPosition part of the offset shift, microsteps. Range: -255..255.\n\n :param pos_micron:\n :return:\n \"\"\"\n\n #TODO WHAT IS THE UNIT for DC Motor ???? -> counts\n nb_of_step_x = int(pos_micron[0] * self.step_multiplier)\n nb_of_step_y = int(pos_micron[1] * self.step_multiplier)\n\n result = self.lib.command_movr(self.device_id_x, nb_of_step_x, 0)\n self.lib.command_movr(self.device_id_y, nb_of_step_y, 0)\n # self.get_position()\n # result = self.lib.command_move(self.device_id_x, self.posMicron[0] + pos_micron[0], 0)\n # result = self.lib.command_move(self.device_id_y, self.posMicron[1] + pos_micron[1], 0)\n print(result)\n # return result\n\n def continous_move(self):\n \"\"\"\n result t XIMC API command_right ( device t id )\n Start continous moving to the right.\n\n result t XIMC API command_left ( device t id )\n\n Start continous moving to the left.\n\n :return:\n \"\"\"\n #TODO\n pass\n\n\n def wait_for_device(self):\n \"\"\"\n result t XIMC API command wait for stop ( device t id, uint32 t refresh interval ms )\n\n Status refresh interval. The function waits this number of milliseconds between\n get status requests to the controller. Recommended value of this parameter\n is 10 ms. Use values of less than 3 ms only when necessary - small refresh\n interval values do not significantly increase response time of the function, but\n they create substantially more traffic in controller-computer data channel.\n\n RESULT OK if controller has stopped and result of the first get status command\n which returned anything other than RESULT OK otherwise.\n\n :return:\n \"\"\"\n self.is_busy_ = True\n interval = 10\n\n result = -1\n\n while result != 0:\n result_x = self.lib.command_wait_for_stop(self.device_id_x, interval)\n result_y = self.lib.command_wait_for_stop(self.device_id_y, interval)\n result = result_x and result_y\n\n self.is_busy_ = False\n\n def stop(self):\n \"\"\"\n result t XIMC API command sstp ( device t id )\n Soft stop engine.\n The motor stops with deceleration speed.\n\n\n result t XIMC API command stop ( device t id )\n Immediately stop the engine, the transition to the STOP, mode key BREAK (winding short-circuited), the regime\n ”retention” is deactivated for DC motors, keeping current in the windings for stepper motors (with Power management\n settings).\n\n :return:\n \"\"\"\n result = self.lib.command_stop(self.device_id_x)\n self.lib.command_stop(self.device_id_y)\n return result\n\n def is_busy(self):\n return self.is_busy_\n\n def close_device(self, params=None):\n result = self.lib.close_device(byref(cast(self.device_id_x, POINTER(c_int))))\n result = self.lib.close_device(byref(cast(self.device_id_y, POINTER(c_int))))\n # self.lib.close_device(self.device_id_y)\n return result\n\n\n def get_position(self):\n # print(\"\\nRead position\")\n x_pos = get_position_t()\n result = self.lib.get_position(self.device_id_x, byref(x_pos))\n if result == Result.Ok:\n self.posMicron[0] = x_pos.Position\n result = self.lib.get_position(self.device_id_y, byref(x_pos))\n if result == Result.Ok:\n self.posMicron[1] = x_pos.Position\n\n # print(\"Result: \" + repr(result))\n #\n # print(\"Position: {0} steps, {1} microsteps\".format(x_pos.Position, x_pos.uPosition))\n # return x_pos.Position, x_pos.uPosition\n\n\n def get_info(self):\n print(\"\\nGet device info\")\n x_device_information = device_information_t()\n result = self.lib.get_device_information(self.device_id, byref(x_device_information))\n print(\"Result: \" + repr(result))\n if result == Result.Ok:\n print(\"Device information:\")\n print(\" Manufacturer: \" +\n repr(string_at(x_device_information.Manufacturer).decode()))\n print(\" ManufacturerId: \" +\n repr(string_at(x_device_information.ManufacturerId).decode()))\n print(\" ProductDescription: \" +\n repr(string_at(x_device_information.ProductDescription).decode()))\n print(\" Major: \" + repr(x_device_information.Major))\n print(\" Minor: \" + repr(x_device_information.Minor))\n print(\" Release: \" + repr(x_device_information.Release))\n\n def test_status(self):\n print(\"Get status\\n\")\n x_status = status_t()\n result = self.lib.get_status(self.device_id, byref(x_status))\n print(\"Result: \" + repr(result))\n if result == Result.Ok:\n print(\"Status.Ipwr: \" + repr(x_status.Ipwr))\n print(\"Status.Upwr: \" + repr(x_status.Upwr))\n print(\"Status.Iusb: \" + repr(x_status.Iusb))\n print(\"Status.Flags: \" + repr(hex(x_status.Flags)))\n\n def test_serial(self):\n print(\"\\nReading serial\")\n x_serial = c_uint()\n result = self.lib.get_serial_number(self.device_id, byref(x_serial))\n if result == Result.Ok:\n print(\"Serial: \" + repr(x_serial.value))\n\n\n def get_speed(self):\n print(\"\\nGet speed\")\n # Create move settings structure\n mvst = move_settings_t()\n # Get current move settings from controller\n result = self.lib.get_move_settings(self.device_id, byref(mvst))\n # Print command return status. It will be 0 if all is OK\n print(\"Read command result: \" + repr(result))\n\n return mvst.Speed\n\n\n def test_set_speed(self, speed):\n print(\"\\nSet speed\")\n # Create move settings structure\n mvst = move_settings_t()\n # Get current move settings from controller\n result = self.lib.get_move_settings(self.device_id, byref(mvst))\n # Print command return status. It will be 0 if all is OK\n print(\"Read command result: \" + repr(result))\n print(\"The speed was equal to {0}. We will change it to {1}\".format(mvst.Speed, speed))\n # Change current speed\n mvst.Speed = int(speed)\n # Write new move settings to controller\n result = self.lib.set_move_settings(self.device_id, byref(mvst))\n # Print command return status. It will be 0 if all is OK\n print(\"Write command result: \" + repr(result))\n\n\n\nif __name__ == \"__main__\":\n\n class macGuiver():\n def __init__(self):\n self.mmc = None\n self.root = None\n\n macGuiver = macGuiver()\n standa = Standa_XY(macGuiver)\n standa.load_device()\n","sub_path":"hardware/Standa_XY.py","file_name":"Standa_XY.py","file_ext":"py","file_size_in_byte":16612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"167155370","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 17 18:51:18 2021\n\n@author: Administrator\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom MotorDriver import motor\nfrom MMC5603 import Mag\nfrom KNNscikitlearn import KNN\nfrom ssd_class import SSD\nimport time\n\nMotor = motor()\nsensor = Mag()\nalgorithm = KNN()\nssd = SSD()\n## setting\ndis_total = 30\ndis_increment = 0.5\nsteps = round(dis_increment*3*250/5.3)\ndata_points = int(dis_total/dis_increment)\n\n#%% start measuring\ndirec = 1\nwarmup = sensor.all_data()\nenv = np.load('env.npy')\ndata = []\nlocation = []\n\nfor i in range(data_points):\n Motor.move(steps,direc)\n time.sleep(0.1)\n reading = sensor.all_data() - env[i]\n loc = algorithm.search(reading)\n data.append(reading)\n location.append(loc)\n disp_loc = round(loc[0][0][0],2)\n ssd.display(disp_loc)\n time.sleep(0.5)\n \n#%% return\ndirec = 0\nMotor.move(steps*data_points,direc)\n\n#%% plot\nx = np.arange(len(data))\nnpData = np.array(data)\ny = npData[:,2]\nplt.plot(x,y)\nplt.show()\n\n#%% save the data\nfilename = input('enter the file name ')\nfile = open(filename + '.txt', 'w')\nnp.savetxt(file, np.array(data))\nfile.close()","sub_path":"A_main.py","file_name":"A_main.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"643019319","text":"# 63. オブジェクトを値に格納したKVS\n# KVSを用い,アーティスト名(name)からタグと被タグ数(タグ付けされた回数)のリストを\n# 検索するためのデータベースを構築せよ.さらに,ここで構築したデータベースを用い,\n# アーティスト名からタグと被タグ数を検索せよ.\n\nimport json\nimport redis\nimport sys\nfrom tqdm import tqdm\n\nif __name__ == '__main__':\n my_redis = redis.Redis(host='localhost', port=6379, db=0)\n\n # データベース登録した部分\n with open('resources/artist.json',\n encoding='utf-8', mode='r') \\\n as json_file:\n\n for line in tqdm(json_file):\n json_dict = json.loads(line)\n\n if \"tags\" in json_dict:\n my_redis.set(json_dict[\"name\"],\n json.dumps(json_dict[\"tags\"]))\n else:\n pass\n\n # 対話的に検索する部分\n while True:\n sys.stdout.write(\">>>\")\n\n artist_name = input()\n END_WORD = [\"end\", \"END\", \"End\"]\n\n if artist_name in END_WORD:\n sys.exit(0)\n\n tags = my_redis.get(artist_name)\n\n if not tags:\n print(\"Sorry, not found.\")\n else:\n tags = json.loads(tags.decode(\"utf-8\"))\n for tag_dict in tags:\n print(tag_dict[\"count\"], tag_dict[\"value\"])\n\n\"\"\"\n出力結果\n\n>>>Rezerwat\n1 polish rock\n1 new wave\n>>>end\n\nProcess finished with exit code 0\n\"\"\"","sub_path":"60-69/knock_63.py","file_name":"knock_63.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"118772149","text":"from .fileManagement import readPropFile, get_xH_data\nimport os, sys\nimport numpy as np\nfrom scipy import interpolate\n\n\ndef interpolateSime2Exp(ySim, yExp, uSim, uExp):\n f = interpolate.interp1d(ySim,uSim)\n ySimInterp = yExp\n uSimInterp = f(ySimInterp) \n return ySimInterp, uSimInterp\n\n\ndef compareSimAndExp(ySim, yExp, uSim, uExp):\n ySimInterp, uSimInterp = interpolateSime2Exp(ySim, yExp, uSim, uExp)\n delta=uSimInterp-uExp\n return ySimInterp, delta\n\n\n\nclass Slicedata:\n \n def __init__(self):\n self.xh = []\n self.y = []\n self.u = []\n self.v = []\n self.uav = 0\n self.ps = []\n self.psav = []\n self.pt = []\n self.ptav = []\n self.path = \"\"\n self.vfr = -1\n \n def calcAbsoluteVelocity(self):\n if self.u and self.v:\n for (u, v) in zip(self.u, self.v):\n self.c = np.sqrt(u**2+v**2)\n else:\n print(\" [ERROR in calcAbsoluteVelocity]: Not enough data\")\n \n def volumeFlowRate(self, rho):\n dy = [(b-a) for (a, b) in zip(self.y[:-1], self.y[1:])]\n umid = [(a+b)/2 for (a, b) in zip(self.u[:-1], self.u[1:])]\n self.vfr = sum([a*b for (a, b) in zip(umid, dy)])\n print(self.vfr)\n \n def averagePt(self, rho):\n dy = [(b-a) for (a, b) in zip(self.y[:-1], self.y[1:])]\n umid = [(a+b)/2 for (a, b) in zip(self.u[:-1], self.u[1:])]\n ptmid = [(a+b)/2 for (a, b) in zip(self.pt[:-1], self.pt[1:])]\n self.ptav = sum([a*b*u for (a, b, u) in zip(ptmid, dy, umid)])*rho/self.vfr\n \n def averagePs(self, rho):\n dy = [(b-a) for (a, b) in zip(self.y[:-1], self.y[1:])]\n umid = [(a+b)/2 for (a, b) in zip(self.u[:-1], self.u[1:])]\n ptmid = [(a+b)/2 for (a, b) in zip(self.ps[:-1], self.ps[1:])]\n self.psav = sum([a*b*u for (a, b, u) in zip(ptmid, dy, umid)])*rho/self.vfr\n \n \n\nclass Result:\n\n def __init__(self, path, geomtype, casename = \"\"):\n self.path = path\n self.geomtype = geomtype\n self.casename = casename\n self.slicedata = []\n self.h_step = 0\n self.h_out = 0\n self.L1 = 0\n self.L2 = 0\n self.rho = -1\n self.mu = -1\n self.Re = -1\n \n \n def setFlowProp(self, flname):\n flProp = readPropFile(flname)\n self.rho = float(flProp[0][1])\n self.mu = float(flProp[1][1])\n \n \n def calc_Re_from_slice(self,x):\n print(\" > Calculating Reynolds number from slice x/h=%i ...\" % x)\n for (i, sl) in enumerate(self.slicedata):\n if sl.xh == x:\n break;\n \n if self.slicedata:\n D = max(self.slicedata[i].y)-min(self.slicedata[i].y)\n Umax = max(self.slicedata[i].u)\n if abs(self.slicedata[i].u[0])>0 or abs(self.slicedata[i].u[-1])>0:\n D = 2*D\n self.Re = self.rho*Umax*D/self.mu\n print(\" ... Re=%f\" % self.Re)\n else:\n print(\" [Error in calc_Re_from_slice]: no slice data. Unable to calculate Re for slice x/h=%i\" % x)\n sys.exit()\n \n \nclass Simulation(Result):\n \n def __init__(self, path, geomtype, casename = \"\"):\n Result.__init__(self, path, geomtype, casename)\n self.rtype = 'sim'\n self.taux = []\n self.xtaux = []\n self.ytaux = []\n \n \n def readSliceData(self):\n # 1.) read *.slice:\n flname = os.path.join(self.path, \"config\", \"slice\")\n sliceXYData = readPropFile(flname)\n self.slicedata = []\n for d in sliceXYData:\n self.slicedata.append(Slicedata())\n self.slicedata[-1].xh = float(d[0])\n \n for sl in self.slicedata:\n sliceName = \"XH%i.csv\" % (sl.xh)\n flname = os.path.join(self.path, \"post\", sliceName)\n sl.path=flname\n sl.y, sl.ps = get_xH_data(flname, 1, 2, ',')\n sl.y, sl.pt = get_xH_data(flname, 1, 3, ',')\n sl.y, sl.u = get_xH_data(flname, 1, 5, ',')\n \n \n def readTauX(self):\n tauxname=\"taux.csv\"\n flname = os.path.join(self.path, \"post\", tauxname)\n print(flname)\n self.xtaux, self.taux = get_xH_data(flname, 0, 2, ',')\n self.xtaux, self.ytaux = get_xH_data(flname, 0, 1, ',')\n \n\n \n def setGeomProp(self, flname):\n bfsGeom = readPropFile(flname)\n self.h_step = float(bfsGeom[0][1])\n self.h_out = float(bfsGeom[1][1])\n self.L1 = float(bfsGeom[2][1])\n self.L2 = float(bfsGeom[3][1]) \n if self.geomtype == \"pocket\":\n self.b = float(bfsGeom[4][1]) \n self.f = float(bfsGeom[5][1]) \n self.d = float(bfsGeom[6][1]) \n self.e = float(bfsGeom[7][1]) \n self.expansion = self.h_out/self.h_step\n \n \n def plot_geometry(self, ax):\n if self.geomtype == \"classic\":\n ax.plot([0, 0], [0, 1], 'k-', linewidth=2)\n ax.plot([-2.5, 0], [1, 1], 'k-', linewidth=2)\n ax.plot([0, 17.5], [0, 0], 'k-', linewidth=2)\n ax.plot([-2.5, 17.5], [2, 2], 'k-', linewidth=2)\n elif self.geomtype == \"pocket\":\n ax.plot([0, -2.5], [1, 1], 'k-', linewidth=2)\n ax.plot([-2.5, 17.5], [2, 2], 'k-', linewidth=2)\n ax.plot([17.5, 17.5], [2, 0.0], 'k-', linewidth=2)\n ax.plot([17.5, self.f], [0.0,0.0], 'k-', linewidth=2)\n ax.plot([self.f,self.f], [0, -self.d], 'k-', linewidth=2)\n ax.plot([self.f, -self.b], [-self.d,-self.d], 'k-', linewidth=2)\n ax.plot([-self.b, -self.b], [-self.d, 1-self.e*self.h_step], 'k-', linewidth=2)\n ax.plot([-self.b, 0], [1-self.e*self.h_step, 1-self.e*self.h_step], 'k-', linewidth=2)\n ax.plot([0, 0], [1-self.e*self.h_step,1], 'k-', linewidth=2)\n \n \n \nclass Experiment(Result):\n \n def __init__(self, path, geomtype, casename = \"\"):\n Result.__init__(self, path, geomtype, casename)\n self.rtype = 'exp'\n \n \n def setSlicePositions(self, xh_ls):\n self.slicedata = []\n for xh in xh_ls:\n self.slicedata.append(Slicedata())\n self.slicedata[-1].xh = xh\n \n \n def readSliceData(self): \n for sl in self.slicedata:\n sliceName = \"XH%i.exp\" % (sl.xh)\n flname = os.path.join(self.path, sliceName)\n sl.path=flname\n sl.y, sl.u = get_xH_data(flname, 0, 1, ',')\n \n \n def checkExpData(self):\n print(\"checking experimental data ...\")\n for sl in self.slicedata:\n try:\n f = open(sl.path)\n f.close()\n print(\" > %s successful\" % sl.path)\n except:\n print(\" > %s failed\" % sl.path)\n","sub_path":"bin/lib/py/result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":6971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"405153894","text":"from django.template.response import TemplateResponse\nfrom django.template.loader import get_template\nfrom django.views import View\n\nfrom .models import Actor, Movie\nfrom utils import normalize\n\n\nclass ActorDetail(View):\n def get(self, request, pk):\n queryset = Actor.objects.get(pk=pk)\n template = get_template(\"detail.html\")\n context = {\n \"name\": queryset.name,\n \"link_name\": \"movie_detail\",\n \"objects\": queryset.movies.all(),\n }\n return TemplateResponse(request, template, context=context)\n\nclass MovieDetail(View):\n def get(self, request, pk):\n queryset = Movie.objects.get(pk=pk)\n template = get_template(\"detail.html\")\n context = {\n \"name\": queryset.name,\n \"link_name\": \"actor_detail\",\n \"objects\": queryset.actors.all(),\n }\n return TemplateResponse(request, template, context=context)\n\n\nclass Search(View):\n def get(self, request):\n term = request.GET.get(\"search\")\n if term is not None:\n search_term = normalize(term)\n actor_query_set = Actor.objects.filter(search_name__contains=search_term)\n movies_query_set = Movie.objects.filter(search_name__contains=search_term)\n context = {\n \"actors\": actor_query_set,\n \"movies\": movies_query_set,\n \"search_term\": search_term,\n }\n else:\n context = {\n \"actors\": [],\n \"movies\": [],\n \"search_term\": \"\",\n }\n template = get_template(\"search.html\")\n return TemplateResponse(request, template, context=context)\n","sub_path":"movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"167079729","text":"# pylint:disable=E1101\nimport nsepy\n\nimport datetime\n\n# df = nsepy.get_history(symbol='SBIN', start=date(2020,4,1), end=date(2020,5,30))\ndf = nsepy.get_history(symbol='SBIN', start=datetime.date(2020, 4, 1), end=datetime.date.today())\nprint(type(df))\ndf.reset_index('Date', inplace=True)\ndf['Date'] = df['Date'].astype(str)\ndf['Date'] = df['Date'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d'))\ndf.set_index('Date', inplace=True)\n\nohlc_dict = {'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last'}\n\ndf = df.resample('W', how=ohlc_dict).dropna(how='any')\n\n# cols=['Open', 'High', 'Low', 'Close']\n# df = df[cols]\n# df = df['Close'].resample('W').ohlc()\nprint(df.info())\n","sub_path":"dfr.py","file_name":"dfr.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"366229006","text":"#!/usr/bin/env python3\nimport fileinput\nimport os\nimport sys\nimport json\n\ndef cleanup():\n os.system('rm -rf files')\n os.system('rm -rf tasks')\n os.system('rm -rf vars')\n os.system('cp -R files-default files')\n os.system('mkdir tasks')\n os.system('cp -R vars-default vars')\n\ndef retrieve_projects():\n projects = []\n\n for subdir, dirs, files in os.walk('tasks-default'):\n for file in files:\n if not \"local\" in file[0:5]:\n projects.append(file[0:-4])\n\n return projects\n\ndef get_answer(question):\n return input(\"%s \" % question)\n\ndef get_answer_with_default(question, default):\n answer = input(\"%s [%s] \" % (question, default))\n\n if answer == \"\":\n answer = default\n\n return answer\n\ndef get_yn_answer(question):\n while True:\n answer = input(\"%s [y/n] \" % question).lower()\n\n if answer == \"y\":\n return True\n elif answer == \"n\":\n return False\n\ndef get_options_answer(question, options):\n answer = None\n\n while answer not in options:\n print(\"Options: \" + \", \".join(options))\n\n answer = input(\"%s \" % question)\n\n return answer\n\ndef get_template_data(projects):\n git_repo = \"\"\n project = \"local\"\n\n try:\n ip_address = get_answer_with_default(\"Ip address?\", \"192.168.33.10\")\n\n mysql_root_pass = get_answer_with_default(\"Mysql root password?\", \"123\")\n\n is_project = get_yn_answer(\"Special project?\")\n\n if is_project:\n project = get_options_answer(\"Which project?\", projects)\n else:\n git_repo = get_answer(\"Git repo to use?\")\n\n project_name = get_answer(\"Project name?\")\n\n project_pass = get_answer_with_default(\"Project database password?\", \"321\")\n\n tld = get_answer_with_default(\"Tld?\", \"dev\")\n\n except KeyboardInterrupt:\n print(\"\\nNothing is modified.\")\n sys.exit(1)\n\n return {\n 'project': project,\n 'git_repo': git_repo,\n 'project_name': project_name,\n 'project_pass': project_pass,\n 'tld': tld,\n 'mysql_root_pass': mysql_root_pass,\n 'ip_address': ip_address,\n }\n\ndef multiple_replace(text, word_dict):\n for key, value in word_dict.items():\n text = text.replace(\"{{%s}}\" % key, value)\n\n return text\n\ndef update_vagrantfile(word_dict):\n os.system('cp Vagrantfile.template Vagrantfile')\n\n for line in fileinput.input('Vagrantfile', inplace=True):\n sys.stdout.write(multiple_replace(line, word_dict))\n\ndef update_files(word_dict):\n for subdir, dirs, files in os.walk('files'):\n for file in files:\n for line in fileinput.input(subdir + '/' + file, inplace=True):\n sys.stdout.write(multiple_replace(line, word_dict))\n\ndef update_tasks(word_dict):\n os.system('cp tasks-default/' + word_dict['project'] + '.yml tasks/local.yml')\n\n for line in fileinput.input('tasks/local.yml', inplace=True):\n sys.stdout.write(multiple_replace(line, word_dict))\n\ndef update_vars(word_dict):\n for subdir, dirs, files in os.walk('vars'):\n for file in files:\n for line in fileinput.input(subdir + '/' + file, inplace=True):\n sys.stdout.write(multiple_replace(line, word_dict))\n\ndef update_etc_hosts(word_dict):\n should_update = get_yn_answer(\"Would you like to update /etc/hosts?\")\n\n host = \"%s.%s\" % (word_dict[\"project_name\"], word_dict[\"tld\"])\n line = \"%s\\t%s\" % (word_dict[\"ip_address\"], host)\n\n if should_update:\n os.system('sudo cp /etc/hosts /etc/hosts.bak')\n os.system('sudo echo \"%s\" >> /etc/hosts' % line)\n else:\n print(\"Add the following line to /etc/hosts\")\n print('%s' % line)\n\ndef update_all(word_dict):\n update_vagrantfile(word_dict)\n update_files(word_dict)\n update_tasks(word_dict)\n update_vars(word_dict)\n update_etc_hosts(word_dict)\n\ndef write_conf(word_dict):\n with open('conf.json', 'w') as f:\n f.write(json.dumps(word_dict, sort_keys=True, indent=4, separators=(',', ': ')))\n\ndef read_conf():\n try:\n content = open('conf.json').read(1000)\n except FileNotFoundError:\n print(\"conf.json is not found.\")\n sys.exit(1)\n\n data = json.loads(content)\n\n return data\n\ndef main():\n cleanup()\n\n conf = len(sys.argv) > 1 and sys.argv[1] == \"conf\"\n\n if conf:\n word_dict = read_conf()\n else:\n projects = retrieve_projects()\n word_dict = get_template_data(projects)\n write_conf(word_dict)\n\n update_all(word_dict)\n\nmain()\n","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"490052361","text":"# $language = \"Python\"\n# $interface = \"1.0\"\n\n# RPI Cisco Networking Academy\n# Pod Connection Script for SecureCRT\n# Created by Matthew Heffler and Joseph W. Dougherty\n# Version 1.0\n\ndef main():\n\n\t# Tab captions\n\tcaptions = [\"R1\",\"R2\",\"R3\",\"R4\",\"R5\",\"R6\",\"FRS\",\"S1\",\"S2\",\"S3\",\"S4\"]\n\t\n\t# Get pod number\n\tpod = crt.Dialog.Prompt(\"Enter your pod number\",\"Connect to pod\",\"\")\n\tif pod == \"\":\n\t\treturn\n\t\n\t# Get pod password\n\tlinepw = crt.Dialog.Prompt(\"Enter line password:\",\"Device Authentication\",\"\",True)\t\t\t\t\t\n\tif linepw == \"\": \n\t\treturn\n\t\n\t\n\t# Store offset for opening additional pods\n\tj=crt.GetTabCount()\n\t\n\tif crt.GetTab(j).Caption == \"Script Tab\" or crt.GetTab(j).Caption == \"\":\n\t\tj=0\n\tk=j\n\t\n\t# Loop through each port to open connection\n\ti=2001\n\twhile(i<=2012):\n\t\t# Skip 2008\n\t\tif i==2008:\n\t\t\ti=i+1\n\t\tcrt.Session.ConnectInTab(\"/TELNET 128.213.10.\" + str(100+int(pod)) + \" \" + str(i))\n\t\ti=i+1\n\t\n\t# Cycle back through and apply captions and passwords\n\twhile(j 20:\n ICON = 'audio-volume-medium'\nelif volume > 40:\n ICON = 'audio-volume-high'\nelse:\n ICON = 'audio-volume-low'\nif mute == 'off':\n ICON = 'audio-volume-muted'\nos.popen(\n \"notify-send.py \\\"Volume\\\" \\\"%s/100\\\" --hint string:image-path:%s boolean:transient:true --replaces-process \\\"volume-popup\\\"\"\n % (volume, ICON))\n","sub_path":"dotfiles/i3/volume_indicator.py","file_name":"volume_indicator.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"190888381","text":"#!/usr/bin/env python\n\nimport csv\nimport re\nimport argparse\nimport os\nimport subprocess\nimport logging\nimport sys\n\ncacao_version = '1.0.0'\n\n\ndef __main__():\n \n parser = argparse.ArgumentParser(description='cacao - assessment of sequencing coverage at pathogenic and actionable loci in cancer',formatter_class=argparse.ArgumentDefaultsHelpFormatter, usage=\"%(prog)s [options] OUTPUT_DIR> \")\n parser.add_argument('aln',help='Alignment file (BAM/CRAM)')\n parser.add_argument('bed_track_directory', help='Directory with BED tracks of pathogenic/actionable cancer loci for grch37/grch38')\n parser.add_argument('output_directory', help='Output directory')\n parser.add_argument('genome_assembly',choices = ['grch37','grch38'], help='Human genome assembly build: grch37 or grch38')\n parser.add_argument('mode',choices=['hereditary','somatic','any'],help=\"Choice of clinical cancer context (hereditary/somatic/any)\")\n parser.add_argument('sample_id', help=\"Sample identifier - prefix for output files\")\n parser.add_argument('mapq', default = 0, type=int, help=\"mapping quality threshold\")\n parser.add_argument('threads',default = 0, type=int, help='Number of mosdepth BAM decompression threads. (use 4 or fewer)')\n parser.add_argument('callability_levels_germline', default=\"0:10:100\", help=\"Intervals of sequencing depth denoting e.g. NO_COVERAGE (0), LOW_COVERAGE (1-9), CALLABLE (10-99), HIGH_COVERAGE (>= 100)\")\n parser.add_argument('callability_levels_somatic', default=\"0:30:200\", help=\"Intervals of sequencing depth denoting e.g. NO_COVERAGE (0), LOW_COVERAGE (1-29), CALLABLE (30-199), HIGH_COVERAGE (>= 200)\")\n\n\n args = parser.parse_args()\n\n logger = getlogger('cacao-get-track')\n track_info = get_track_file(args.aln, args.sample_id, args.output_directory, args.genome_assembly, args.mode, logger)\n logger = getlogger('cacao-coverage-assessment')\n coverage_bed_tracks = {}\n coverage_tsv_tracks = {}\n for m in ['hereditary','somatic_actionable','somatic_hotspot']:\n \n coverage_bed_tracks[m] = \"NA\"\n coverage_tsv_tracks[m] = os.path.join(str(args.bed_track_directory),track_info['tsv'][m])\n sample_postfix = \"_\" + str(m)\n\n coverage_description = \"pathogenic loci in hereditary cancer\"\n if m == \"somatic_actionable\":\n coverage_description = \"actionable somatic mutations - implications for prognosis/diagnosis/drug response\"\n if m == \"somatic_hotspot\":\n coverage_description = \"somatic mutation hotspots - driver events in cancer\"\n if track_info['bed'][m] != \"NA\":\n logger.info(\"Determination of coverage in target regions with https://github.com/brentp/mosdepth: \" + str(coverage_description))\n mosdepth_cmd = 'mosdepth --no-per-base --by ' + os.path.join(str(args.bed_track_directory),str(track_info['bed'][m])) + ' --mapq ' + str(args.mapq) + ' --threads ' + str(args.threads) + ' ' + str(args.sample_id) + str(sample_postfix) + ' ' + str(args.aln)\n logger.info('command: ' + str(mosdepth_cmd))\n check_subprocess(mosdepth_cmd)\n bed_coverage_track_gz = str(args.sample_id) + str(sample_postfix) + '.regions.bed.gz'\n coverage_bed_tracks[m] = os.path.join(str(args.output_directory),str(args.sample_id) + str(sample_postfix) + '.regions.bed')\n\n if os.path.exists(bed_coverage_track_gz) and os.path.getsize(bed_coverage_track_gz) > 0:\n logger.info('Decompressing BED file (' + str(bed_coverage_track_gz) + ') with coverage pr. loci')\n check_subprocess('bgzip -dc ' + str(bed_coverage_track_gz) + ' > ' + coverage_bed_tracks[m])\n else:\n coverage_bed_tracks[m] = \"NA\"\n \n cacao_report_parameters = []\n cacao_report_parameters.append(coverage_bed_tracks['hereditary'])\n cacao_report_parameters.append(coverage_tsv_tracks['hereditary'])\n cacao_report_parameters.append(coverage_bed_tracks['somatic_actionable'])\n cacao_report_parameters.append(coverage_tsv_tracks['somatic_actionable'])\n cacao_report_parameters.append(coverage_bed_tracks['somatic_hotspot'])\n cacao_report_parameters.append(coverage_tsv_tracks['somatic_hotspot'])\n cacao_report_parameters.append(str(args.sample_id))\n cacao_report_parameters.append(str(args.mode))\n cacao_report_parameters.append(str(args.callability_levels_germline))\n cacao_report_parameters.append(str(args.callability_levels_somatic))\n cacao_report_parameters.append(str(args.mapq))\n cacao_report_parameters.append(str(args.genome_assembly))\n cacao_report_parameters.append(str(cacao_version))\n cacao_report_parameters.append(str(args.output_directory))\n\n report_R_command = \"/cacao.R \" + \" \".join(cacao_report_parameters)\n check_subprocess(report_R_command)\n\n logger.info('Finished')\n\n\ndef get_track_file(aln_fname, sample_id, output_directory, genome_assembly, mode, logger):\n\n logger.info('Determination of BED region file - considering genome assembly, cancer mode, and chromosome naming convention')\n idxstats_fname = os.path.join(output_directory, str(sample_id) + '.idxstats.tsv')\n chrnaming_cmd = 'samtools idxstats ' + str(aln_fname) + ' > ' + idxstats_fname\n check_subprocess(chrnaming_cmd)\n\n chr_naming = False\n if os.path.exists(idxstats_fname) and os.path.getsize(idxstats_fname) > 0:\n f = open(idxstats_fname,'r')\n for line in f:\n chrom_stats = line.rstrip().split('\\t')\n if len(chrom_stats) > 0:\n if chrom_stats[0].startswith('chr'):\n chr_naming = True\n \n f.close()\n \n track_info = {}\n track_info['bed'] = {}\n track_info['tsv'] = {}\n for m in ['hereditary','somatic_hotspot','somatic_actionable']:\n track_info['bed'][m] = \"NA\"\n track_info['tsv'][m] = \"NA\"\n\n if mode == 'hereditary' or mode == 'any':\n bed_track = 'cancer_hereditary_pathogenic_loci.' + str(genome_assembly) + '.bed'\n if chr_naming is True:\n bed_track = 'cancer_hereditary_pathogenic_loci.' + str(genome_assembly) + '.chr.bed'\n tsv_fname = 'cancer_hereditary_pathogenic_loci.' + str(genome_assembly) + '.tsv'\n track_info['bed']['hereditary'] = bed_track\n track_info['tsv']['hereditary'] = tsv_fname\n if mode == 'somatic' or mode == 'any':\n bed_track = 'cancer_somatic_actionable_loci.' + str(genome_assembly) + '.bed'\n if chr_naming is True:\n bed_track = 'cancer_somatic_actionable_loci.' + str(genome_assembly) + '.chr.bed'\n tsv_fname = 'cancer_somatic_actionable_loci.' + str(genome_assembly) + '.tsv'\n track_info['bed']['somatic_actionable'] = bed_track\n track_info['tsv']['somatic_actionable'] = tsv_fname\n\n bed_track = 'cancer_somatic_hotspot_loci.' + str(genome_assembly) + '.bed'\n if chr_naming is True:\n bed_track = 'cancer_somatic_hotspot_loci.' + str(genome_assembly) + '.chr.bed'\n tsv_fname = 'cancer_somatic_hotspot_loci.' + str(genome_assembly) + '.tsv'\n track_info['bed']['somatic_hotspot'] = bed_track\n track_info['tsv']['somatic_hotspot'] = tsv_fname\n\n return track_info\n\n\ndef check_subprocess(command):\n #print(command)\n try:\n output = subprocess.check_output(str(command), stderr=subprocess.STDOUT, shell=True)\n if len(output) > 0:\n print (str(output.decode()).rstrip())\n except subprocess.CalledProcessError as e:\n print (e.output.decode())\n exit(0)\n\ndef error_message(message, logger):\n logger.error('')\n logger.error(message)\n logger.error('')\n exit(0)\n\ndef warn_message(message, logger):\n logger.warning(message)\n\n\ndef getlogger(logger_name):\n logger = logging.getLogger(logger_name)\n logger.setLevel(logging.DEBUG)\n\n # create console handler and set level to debug\n ch = logging.StreamHandler(sys.stdout)\n ch.setLevel(logging.DEBUG)\n\n # add ch to logger\n logger.addHandler(ch)\n\n # create formatter\n formatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", \"20%y-%m-%d %H:%M:%S\")\n\n #add formatter to ch\n ch.setFormatter(formatter)\n\n return logger\n\nif __name__==\"__main__\": __main__()\n\n","sub_path":"src/cacao.py","file_name":"cacao.py","file_ext":"py","file_size_in_byte":8168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"339120142","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom keras.models import load_model\nfrom keras.utils import np_utils\n\nFILENAME = './models/gan-200000-iter.h5'\n\nmodel = load_model(FILENAME)\n\nprint('OK')\nlabel = int(input())\n\nwhile label:\n noise = np.random.uniform(-1,1,(1,100))\n label = np_utils.to_categorical(label,10).reshape((1,10))\n img = model.predict([noise,label]).reshape((28,28))\n img = 0.5 * img + 0.5\n print(img.shape)\n plt.imshow(img)\n plt.show()\n label = int(input())\n","sub_path":"gan_labeled_mnist_better/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"15457076","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 10 12:33:14 2018\n\n@author: xad\n\"\"\"\nimport os\n\npath='./微博数据集/new_weibo_13638'\nbig_dir=os.listdir(path)\ndir_path=[path+'/'+dirname for dirname in big_dir]\n\nall_word_list=[]#used to sore all the kind of words and it contain word_list\n\nfor dirname in dir_path:#to get the all_word_list\n files_name=os.listdir(dirname)\n word_list=[]\n for filename in files_name:\n f=open(dirname+'/'+filename,'r',encoding='utf8')\n words=f.read() #delete '/t' and '/n' \n target_words=[]\n word_str=''\n for word in words:\n if word=='\\t' or word=='\\n':\n target_words += [word_str]\n word_str=''\n else:\n word_str += word\n word_list += target_words\n f.close()\n all_word_list += [word_list]\n\n \n\n\n\n\n","sub_path":"weibo.py","file_name":"weibo.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"552659340","text":"'''Test package.'''\n\nimport xroms\nfrom glob import glob\nimport os\n\n\ndef test_open_netcdf():\n '''Test xroms.open_netcdf().'''\n \n base = os.path.join(xroms.__path__[0],'..','tests','input')\n files = glob('%s/ocean_his_000?.nc' % base)\n ds = xroms.open_netcdf(files)\n \n assert ds\n \ndef test_open_zarr():\n '''Test xroms.open_zarr().'''\n \n base = os.path.join(xroms.__path__[0],'..','tests','input')\n files = glob('%s/ocean_his_000?' % base)\n ds = xroms.open_zarr(files, chunks={'ocean_time':2})\n \n assert ds\n \n","sub_path":"tests/test_load.py","file_name":"test_load.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"3351402","text":"import subprocess\nimport threading\nimport asyncio\nimport logging\nimport numpy as np\nimport time\nimport sys\nimport csv\nimport re\nimport os\n\nfrom unittest import TestCase\n\n\nclass Parameter:\n\n def __init__(self, wifi_name):\n self.wifi_name = wifi_name\n\n\nclass File_Decode:\n\n # @staticmethod\n def decode_info_speedtest(self, cmd_info):\n '''\n ! ! ! Please pay attention to line 51(or 52), in here, it is usually occur error(UnicodeDecodeError).\n I think I have to write some mechanism to prevent to error situation\n\n Note:\n 1. use the parameter \"errors\" of method \"decode\"\n * 'strict' (raise a UnicodeDecodeError exception)\n * 'replace' (use U+FFFD, REPLACEMENT CHARACTER)\n * 'ignore' (just leave the character out of the Unicode result)\n * 'backslashreplace' (inserts a \\ xNN escape sequence)\n 2. use syntax \"try catch\"\n\n I think method 1, use the parameter \"errors\" is better.\n '''\n\n decoding_info = cmd_info[:-2].decode('utf-8', errors='backslashreplace').split(',')\n return decoding_info\n\n\n def decode_info_general(self, cmd_info):\n decode_info = cmd_info.decode('utf-8', errors='backslashreplace')\n split_info_list = decode_info.split('\\r\\n')\n decode_string = ''\n for i in range(len(split_info_list)):\n decode_string = decode_string + str(split_info_list[i]) + '\\n'\n return decode_string, split_info_list\n\n\n def build_file(self, wifi_ssid):\n save_file_path = r\"C:\\Users\\sugar\\OneDrive\\Desktop\\DWL-speedtest\\{}_speedtest.csv\".format(wifi_ssid)\n file_obj = open(save_file_path, \"a+\", encoding='utf-8', newline='')\n # file_obj = open(save_file_path, \"ab+\")\n csv_obj = csv.writer(file_obj)\n return file_obj, csv_obj\n\n\nclass Profiles:\n\n def get_all_profile(self):\n\n '''\n\n :return: decode_profile - The network profile information had been decoded.\n split_decode_list - The network profile information had been decoded and split it to a list.\n all_visible_profile_list - Catch all of SSID in air. Just save the Wi-Fi name in a list.\n\n '''\n\n all_profile = subprocess.check_output(\"netsh wlan show network\")\n decode_obj = File_Decode()\n decode_profile, split_decode_list = decode_obj.decode_info_general(all_profile)\n\n '''Get all air SSID we can find to connect to these profile SSID and show these in tab completion'''\n all_visible_profile_list = []\n find_all_air_ssid = re.findall(r\"SSID.{1,100}\", decode_profile)\n for find_air_ssid in find_all_air_ssid:\n # air_ssid = str(find_air_ssid)[9:]\n # all_visible_profile_list.append(air_ssid)\n all_visible_profile_list.append(find_air_ssid)\n\n return decode_profile, split_decode_list, all_visible_profile_list\n\n\n def keyword(self, wifi_name):\n keyword = str(wifi_name)\n all_ssid, all_ssid_list, all_air_ssid = self.get_all_profile()\n result_reach = re.search(str(keyword) + \".{0,100}\", all_ssid)\n if result_reach:\n return 1\n else:\n return -1\n\n\nclass ClientInfo:\n\n def ipconfig_info(self):\n '''\n\n :return: decode_ip_info - String type. The information had been decoded successfully.\n split_ip_list - List type. The information had been decoded successfully and split to a list.\n\n After decoding the return value and split it by default, in Wireless LAN interface, you will get these information.\n And the index first in every line is tell you the number need to add to get the line specific information.\n\n version 1:\n\n Wireless LAN adapter Wi-Fi:',\n 1 '',\n 2 ' Connection-specific DNS Suffix . : dlink.com.tw',\n 3 ' Description . . . . . . . . . . . : Intel(R) Dual Band Wireless-AC 8265',\n 4 ' Physical Address. . . . . . . . . : 88-B1-11-A6-38-3F',\n 5 ' DHCP Enabled. . . . . . . . . . . : Yes',\n 6 ' Autoconfiguration Enabled . . . . : Yes',\n *7 ' Link-local IPv6 Address . . . . . : fe80::750e:7941:6b2f:ae4c%10(Preferred) ',\n 8 ' IPv4 Address. . . . . . . . . . . : 192.166.13.76(Preferred) ',\n 9 ' Subnet Mask . . . . . . . . . . . : 255.255.255.0',\n 10 ' Lease Obtained. . . . . . . . . . : Wednesday, April 3, 2019 10:35:28 AM',\n 11 ' Lease Expires . . . . . . . . . . : Thursday, April 4, 2019 3:27:40 PM',\n 12 ' Default Gateway . . . . . . . . . : 192.166.13.200',\n 13 ' DHCP Server . . . . . . . . . . . : 192.166.13.200',\n 14 ' DHCPv6 IAID . . . . . . . . . . . : 109621521',\n 15 ' DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-24-1F-D8-3C-88-B1-11-A6-38-3F',\n 16 ' DNS Servers . . . . . . . . . . . : 192.168.168.201',\n 17 ' 192.168.168.210',\n 18 ' Primary WINS Server . . . . . . . : 192.168.168.210',\n 19 ' Secondary WINS Server . . . . . . : 192.168.168.250',\n 20 ' NetBIOS over Tcpip. . . . . . . . : Enabled',\n\n version 2:\n\n Wireless LAN adapter Wi-Fi:\n 1\n 2 Connection-specific DNS Suffix . :\n 3 Description . . . . . . . . . . . : Intel(R) Dual Band Wireless-AC 8265\n 4 Physical Address. . . . . . . . . : 88-B1-11-A6-38-3F\n 5 DHCP Enabled. . . . . . . . . . . : Yes\n 6 Autoconfiguration Enabled . . . . : Yes\n *7 IPv6 Address. . . . . . . . . . . : 2402:7500:444:e82:750e:7941:6b2f:ae4c(Preferred)\n 8 Temporary IPv6 Address. . . . . . : 2402:7500:444:e82:ec50:2d0d:f485:340d(Preferred)\n 9 Link-local IPv6 Address . . . . . : fe80::750e:7941:6b2f:ae4c%10(Preferred)\n 10 IPv4 Address. . . . . . . . . . . : 172.20.10.6(Preferred)\n 11 Subnet Mask . . . . . . . . . . . : 255.255.255.240\n 12 Lease Obtained. . . . . . . . . . : Thursday, April 4, 2019 12:21:37 PM\n 13 Lease Expires . . . . . . . . . . : Friday, April 5, 2019 12:14:03 PM\n 14 Default Gateway . . . . . . . . . : fe80::3f:b672:391a:e9af%10\n 15 172.20.10.1\n 16 DHCP Server . . . . . . . . . . . : 172.20.10.1\n 17 DHCPv6 IAID . . . . . . . . . . . : 109621521\n 18 DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-24-1F-D8-3C-88-B1-11-A6-38-3F\n 19 DNS Servers . . . . . . . . . . . : fe80::3f:b672:391a:e9af%10\n 20 172.20.10.1\n 21 NetBIOS over Tcpip. . . . . . . . : Enabled\n\n '''\n\n decode_obj = File_Decode()\n\n ip_info = subprocess.check_output(\"ipconfig /all\", shell=True)\n decode_ip_info, split_ip_list = decode_obj.decode_info_general(ip_info)\n return decode_ip_info, split_ip_list\n\n\n def wlan_info(self):\n '''All connection information of WLAN interface'''\n decode_obj = File_Decode()\n\n wlan_info = subprocess.check_output(\"netsh wlan show interface\", shell=True)\n decode_wlan_info, split_wlan_list = decode_obj.decode_info_general(wlan_info)\n return decode_wlan_info, split_wlan_list\n\n\n def check_info_correct(self, target_keyword, info, split_list, wlan_info_index):\n\n '''\n\n :param target_keyword: The target information name or keyword we want to get.\n :param info: The element had been choice and we want to check it is correct or not.\n :param split_list: The list had been deocde successfully and split it to a list.\n :param wlan_info_index: Because you send command line \"ipconfig /all\" in terminal, it will show you all interface\n information to you. But I just only need to observe one specific interface - Wireless LAN.\n And every interface information have most about 20 lines(If it got connection). So base on\n this index variable to find and get the target information.\n :return: 1 - The target information we got correctly.\n -1 - The target information we want to get doesn't exist.\n\n Because PC may be get IPv6 address information, if it happen, then the index of every target information we want\n to get will be changed. So to prevent to match wrong information to user. Unfortunately, if it happen, this methanism\n will check it is correct or not and find the correct information if it is wrong.\n\n '''\n\n if str(target_keyword) in info:\n return 1\n else:\n index = 7\n for ele in split_list[wlan_info_index + index]:\n if target_keyword in ele:\n return 1\n else:\n index += 1\n if index == 14:\n return -1\n\n\n def interface_info(self):\n\n '''\n\n :return: version 1:\n ipv4.group(0) - IPv4 address you got\n mask.group(0) - Subnet mask of the IP\n gateway.group(0) - Gateway of the IP\n dhcp_status.group(0) - Get IP address by DHCP or not\n pc_phy_addr.group(0) - Physical address of the WLAN interface of PC\n bssid_re.group(0) - BSSID\n authen_re.group(0) - Authentication of the Wi-Fi\n channel_re.group(0) - Channel\n\n version 2:\n wlan_ipconfig_info - Return a dictionary and save all information in it. It's more convenience to let\n other function to use this objection.\n\n To get all information I need with using command line like \"netsh wlan show interface\" or \"ipconfig /all\".\n This function just integrate the information from some command in Win10 or else operator with automation something\n to help me that I can finish one movement and I get the information I need.\n\n '''\n\n wlan_ipconfig_info = {}\n\n '''WLAN interface information'''\n decode_ip_info, split_ip_info_list = self.ipconfig_info()\n\n wlan_info_index = split_ip_info_list.index(\"Wireless LAN adapter Wi-Fi:\")\n\n '''IPv4 address'''\n ipv4_index = wlan_info_index + 8\n ipv4 = split_ip_info_list[ipv4_index]\n ipv4_checksum = self.check_info_correct('IPv4 Address', ipv4, split_ip_info_list, wlan_info_index)\n if ipv4_checksum == 1:\n ipv4 = re.search(r\"[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}\", ipv4)\n ipv4 = str(ipv4.group(0))\n wlan_ipconfig_info['ipv4'] = ipv4\n else:\n '''It doesn't find the target information'''\n wlan_ipconfig_info['ipv4'] = None\n pass\n\n '''IPv6'''\n ipv6_index = wlan_info_index + 7\n ipv6 = split_ip_info_list[ipv6_index]\n ipv6_checksum = self.check_info_correct('IPv6 Address', ipv6, split_ip_info_list, wlan_info_index)\n if ipv6_checksum == 1:\n ipv6 = re.search(r\"[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}\", ipv6)\n ipv6 = str(ipv6.group(0))\n wlan_ipconfig_info['ipv6'] = ipv6\n else:\n '''It doesn't find the target information'''\n wlan_ipconfig_info['ipv6'] = None\n pass\n\n '''Subnet Mask Address'''\n mask_index = wlan_info_index + 9\n mask = split_ip_info_list[mask_index]\n mask_checksum = self.check_info_correct('Subnet Mask', mask, split_ip_info_list, wlan_info_index)\n if mask_checksum == 1:\n mask = re.search(r\"[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}\", mask)\n mask = str(mask.group(0))\n wlan_ipconfig_info['mask'] = mask\n else:\n '''It doesn't find the target information'''\n wlan_ipconfig_info['mask'] = None\n pass\n\n '''Gateway address'''\n gateway_index = wlan_info_index + 12\n gateway = split_ip_info_list[gateway_index]\n gateway_checksum = self.check_info_correct('Default Gateway', gateway, split_ip_info_list, wlan_info_index)\n if gateway_checksum == 1:\n gateway = re.search(r\"[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}\", gateway)\n gateway = str(gateway.group(0))\n wlan_ipconfig_info['gateway'] = gateway\n else:\n '''It doesn't find the target information'''\n wlan_ipconfig_info['gateway'] = None\n pass\n\n '''DHCP information'''\n dhcp_status_index = split_ip_info_list.index(\"Wireless LAN adapter Wi-Fi:\") + 5\n dhcp_status = split_ip_info_list[dhcp_status_index]\n dhcp_status = re.search(r\"[YN].{1,3}\", dhcp_status)\n if dhcp_status:\n dhcp_status = str(dhcp_status.group(0))\n wlan_ipconfig_info['dhcp_status'] = dhcp_status\n else:\n wlan_ipconfig_info['dhcp_status'] = dhcp_status\n\n '''Information of connection with Wi-Fi'''\n wlan_info, split_wlan_list = self.wlan_info()\n\n '''Physical address'''\n phy_addr = re.search(r\"Physical address.{1,100}\", wlan_info)\n pc_phy_addr = re.search(r\"\\w{1,2}:\\w{1,2}:\\w{1,2}:\\w{1,2}:\\w{1,2}:\\w{1,2}\", str(phy_addr))\n if pc_phy_addr:\n pc_phy_addr = str(pc_phy_addr.group(0))\n wlan_ipconfig_info['phy_addr'] = pc_phy_addr\n else:\n wlan_ipconfig_info['phy_addr'] = None\n\n '''Profile'''\n profile = re.search(r\"Profile.{1,100}\", wlan_info)\n if profile:\n profile = str(profile)[25:]\n wlan_ipconfig_info['profile'] = profile\n else:\n wlan_ipconfig_info['profile'] = None\n\n '''SSID'''\n ssid = re.search(r\"SSID.{1,100}\", wlan_info)\n if ssid:\n ssid = str(ssid)[25:]\n wlan_ipconfig_info['ssid'] = ssid\n else:\n wlan_ipconfig_info['ssid'] = None\n\n '''BSSID'''\n bssid = re.search(r\"BSSID.{1,100}\", wlan_info)\n bssid_re = re.search(r\"\\w{1,2}:\\w{1,2}:\\w{1,2}:\\w{1,2}:\\w{1,2}:\\w{1,2}\", str(bssid))\n if bssid:\n bssid = str(bssid_re.group(0))\n wlan_ipconfig_info['bssid'] = bssid\n else:\n wlan_ipconfig_info['bssid'] = None\n\n '''Authentication'''\n # authen = re.search(r\"Authentication.{1,100}\", wlan_info)\n # authen_re = re.search(r\"\\w{1,10}-\\w{1,10}\", str(authen))\n # if authen:\n # authen = str(authen_re.group(0))\n # wlan_ipconfig_info['authen'] = authen\n # else:\n # wlan_ipconfig_info['authen'] = None\n\n '''Radio Type'''\n radio_type = re.search(r\"Radio Type.{1,100}\", wlan_info)\n radio_type_re = re.search(r\"[0-9]{1,3}.[0-9]{1,3}\\w{1,3}\", str(radio_type))\n if radio_type:\n radio_type = str(radio_type_re.group(0))\n wlan_ipconfig_info['radio_type'] = radio_type\n else:\n wlan_ipconfig_info['radio_type'] = None\n\n '''Channel'''\n channel = re.search(r\"Channel.{1,100}\", wlan_info)\n channel_re = re.search(r\"[0-9]{1,3}\", str(channel))\n if channel:\n channel = str(channel_re.group(0))\n wlan_ipconfig_info['channel'] = channel\n else:\n wlan_ipconfig_info['channel'] = None\n\n '''Signal'''\n signal = re.search(r\"Signal.{1,100}\", wlan_info)\n signal_re = re.search(r\"[0-9]{1,3}.\", str(signal))\n if signal:\n signal = str(signal_re.group(0))\n wlan_ipconfig_info['signal'] = signal\n else:\n wlan_ipconfig_info['signal'] = None\n\n return wlan_ipconfig_info\n\n\nclass Certificate:\n\n def build_ssid_profile(self, target_profile, profile_password):\n\n '''\n\n :param target_profile: The profile of target SSID user want to connect to it.\n :param profile_password: The password of the secure Wi-Fi.\n :return: 1 - Build profile successfully.\n -1 - It's fail to build profile.\n\n Because the secured Wi-Fi has password we need to enter it, before that, we cannot connect to the SSID. So we build\n a xml type file to define a profile we need that include the SSID and the password of it, and we add the profile\n to PC. Therefore, we have the profile with password to connect to it.\n And this profile type is for general secured Wi-Fi with like password authentication.\n\n '''\n\n import binascii\n\n target_profile_bytes = bytes(target_profile, encoding='utf-8')\n target_profile_hex = binascii.hexlify(target_profile_bytes)\n target_profile_hex_value = str(target_profile_hex.decode('utf-8'))\n\n currently_file_path = os.path.abspath('.')\n ssid_profile_dir = currently_file_path + r'\\SSID_Profile'\n if os.path.exists(ssid_profile_dir):\n pass\n else:\n os.mkdir(ssid_profile_dir)\n # file_path = r\"C:\\Users\\bulls\\OneDrive\\Desktop\\Wi-Fi-\" + str(target_profile) + \".xml\"\n file_path = ssid_profile_dir + r\"\\Wi-Fi-\" + str(target_profile) + \".xml\"\n ssid_profile_file = open(file_path, 'w+', encoding='utf-8')\n ssid_profile_file.write('\\n')\n ssid_profile_file.write('\\n')\n ssid_profile_file.write('\t' + str(target_profile) + '\\n')\n ssid_profile_file.write('\t\\n')\n ssid_profile_file.write('\t\t\\n')\n ssid_profile_file.write('\t\t\t' + target_profile_hex_value + '\\n')\n ssid_profile_file.write('\t\t\t' + str(target_profile) + '\\n')\n ssid_profile_file.write('\t\t\\n')\n ssid_profile_file.write('\t\\n')\n ssid_profile_file.write('\tESS\\n')\n ssid_profile_file.write('\tmanual\\n')\n ssid_profile_file.write('\t\\n')\n ssid_profile_file.write('\t\t\\n')\n ssid_profile_file.write('\t\t\t\\n')\n ssid_profile_file.write('\t\t\t\tWPA2PSK\\n')\n ssid_profile_file.write('\t\t\t\tAES\\n')\n ssid_profile_file.write('\t\t\t\tfalse\\n')\n ssid_profile_file.write('\t\t\t\\n')\n ssid_profile_file.write('\t\t\t\\n')\n ssid_profile_file.write('\t\t\t\tpassPhrase\\n')\n ssid_profile_file.write('\t\t\t\tfalse\\n')\n ssid_profile_file.write('\t\t\t\t' + str(profile_password) + '\\n')\n ssid_profile_file.write('\t\t\t\\n')\n ssid_profile_file.write('\t\t\\n')\n ssid_profile_file.write('\t\\n')\n ssid_profile_file.write('\\n')\n ssid_profile_file.write('\\n')\n ssid_profile_file.close()\n\n build_profile_result = subprocess.call('netsh wlan add profile filename=\"' + str(file_path) + '\" user=all',\n shell=True)\n time.sleep(0.1)\n if 'error' in str(build_profile_result):\n return -1\n else:\n build_profile_result_check = subprocess.check_output('netsh wlan show profile', shell=True)\n if str(target_profile) in str(build_profile_result_check):\n return 1\n\n\n def check_profile_authentication(self, target_ssid):\n '''\n\n :param target_ssid: The target SSID user want to connect to it.\n :return: 1 - It's a secure Wi-Fi, user have to enter password to connect to Wi-Fi.\n 0 - It's a open Wi-Fi, user can connect to Wi-Fi without password.\n -1 - This SSID doesn't exist.\n\n This function help user to check the authentication of target SSID. If the SSID is secured, then user need to\n enter password to connect ot it. If it isn't, then user can connect to SSID without password.\n\n '''\n\n completion = Profiles()\n decode_all_profile, split_decode_list, all_visible_profile_list = completion.get_all_profile()\n exist_checksum = completion.keyword(target_ssid)\n if exist_checksum == 1:\n for ele in split_decode_list:\n if str(target_ssid) in ele:\n target_ssid_index = split_decode_list.index(ele)\n authentication_type = split_decode_list[target_ssid_index + 2]\n if 'WPA' in authentication_type:\n if 'WPA2-Personal' in authentication_type:\n return 1\n elif 'WPA2-Enterprise' in authentication_type:\n return 2\n else:\n return -1\n else:\n return 0\n else:\n continue\n else:\n return -1\n\n\nclass WiFi(Parameter):\n\n def __init__(self, wifi_name, interface_card):\n super(WiFi, self).__init__(wifi_name=wifi_name)\n self.interface_card = interface_card\n\n\n def connection_request_Open(self):\n\n '''\n\n :param wifi_name: Target Wi-Fi you want to connect to it.\n :return: 1 - Send connection request successfully.\n 0 - The password user enter is incorrect, it will ask user enter password again.\n -1 - Get a failure when send connection request.\n\n Just send connection request to target Wi-Fi and check the result.\n This is authentication Open mode.\n\n '''\n\n try:\n connection_cmd = \"netsh wlan connect name=\\\"{}\\\" interface=\\\"{}\\\"\".format(self.wifi_name, self.interface_card)\n # connection_cmd = \"netsh wlan connect name=\\\"\" + str(wifi_name) + \"\\\" interface=\\\"\" + str(interface) + \"\\\"\"\n subprocess.check_output(connection_cmd, shell=True)\n return 1\n\n except Exception as e:\n # print(e)\n print(\"You should connect to a Wi-Fi profile and check information again.\")\n # sys.exit(0)\n return -1\n\n\n def check_all_profile(self, wifi_name):\n\n '''\n\n :param wifi_name: Target Wi-Fi you want to connect to it.\n :return: 1 - Find the target Wi-Fi successfully.\n 2 - Try to find Wi-Fi again.\n -2 - Start program again because user enter invalid argument.\n\n This function just to check the target Wi-Fi exists or not. If it does, great, we can continue to next step. If\n it doesn't, unfortunately, you have to make sure you enter correctly or tell program what you do next step.\n\n '''\n\n time_stamp = 0\n while True:\n all_profile = subprocess.check_output(\"netsh wlan show networks\", shell=True)\n decode_profile, split_decode_list = self.decode_info(all_profile)\n '''check the target ssid in all profile or not'''\n find_result = decode_profile.find(str(wifi_name))\n if find_result == -1:\n '''If the wifi can not been found what thing you want to handle with this'''\n print('Unfortunately, the SSID you find maybe doesn\\'t exist.')\n fail_index = self.failure_mechanism()\n time_stamp += 1\n if time_stamp == 10:\n '''Exceed the time to retry'''\n answer = input(\"Do you sure you input the right target Wi-Fi name?(y/n)\\n\")\n '''Here, default answer is yes'''\n answer_re = re.search(\"n\", answer, re.IGNORECASE)\n if answer_re:\n new_answer = input('Please enter a new Wi-Fi name to continue, or you can enter \\'n\\' to exit '\n 'program.\\n')\n new_answer_re = re.search('n', new_answer, re.IGNORECASE)\n if new_answer_re:\n sys.exit(0)\n else:\n '''Change to a new Wi-Fi name and try to find it again.'''\n wifi_name = new_answer\n time_stamp = 0\n else:\n time_stamp = 0\n else:\n if fail_index == 1:\n '''1. Enter a new Wi-Fi name'''\n return 2\n elif fail_index == 2:\n '''2. Try again.'''\n time_stamp = 0\n elif fail_index == -2:\n '''-2. Start program again because user input invalid argument.'''\n return -2\n else:\n '''\n In general, it is impossible to run this code here. If it's correct, developer will have \n a green face.\n '''\n print(\"Something Error happen......\")\n '''It's time to start Log mechanism to save information about bug'''\n sys.exit(0)\n else:\n '''If it can been found, what thing you want to do.'''\n # print('The SSID ' + str(wifi_name) + ' you find exists !')\n return 1\n\n\n def mechanism(self, wifi_name):\n\n '''\n\n :param wifi_name: Target Wi-Fi you want to connect to it.\n :return: -1 - Get failure about send connection request to target Wi-Fi.\n 1 - Connect to target Wi-Fi successfully.\n 2 - (Thinking)User want to enter a new Wi-Fi name and try again.\n\n The main job about PC connects to Wi-Fi here. It will send connection request first. And check the connection is\n successful. If it isn't, program will try to do for 45 times. If it still isn't, then it will run fail mechanism\n to handle with this problem.\n\n '''\n\n result_number = self.connection_request_Open(wifi_name)\n if result_number == 1:\n '''\n In here, At 0.3 second, state is disconnected. In 0.4 second, state is associated.\n So I let it (this program) sleep for 0.5 seconds to connect to the WiFi.\n '''\n time.sleep(0.5)\n time_stamp = 0\n while True:\n wlan_info = subprocess.check_output('netsh wlan show interface', shell=True)\n fin_wlan_info, split_wlan_list = self.decode_info(wlan_info)\n # compile_info = re.compile(\"(.{1,3}connected)\")\n # connect_state = compile_info.search(fin_wlan_info)\n # print(fin_wlan_info)\n connect_state = re.search(r\"(.{1,3}connected)\", fin_wlan_info)\n # print(connect_state)\n if \"disconnected\" in str(connect_state):\n if time_stamp == 45:\n print(\"Wi-Fi had connected failure !\")\n print(\"Are you sure the Wi-Fi name enter is correct?\")\n '''Because this have something wrong, so we call failure method'''\n '''? In here, I have to think about that how to let fail mechanism to face problem had occur and\n solute that'''\n fail_index = self.failure_mechanism()\n if fail_index == 1:\n '''1. Enter a new Wi-Fi name and try again.'''\n return 2 # Confuse about this return value\n elif fail_index == 2:\n '''2. Try again'''\n time_stamp = 0\n continue # Because program has to keep running, so function does't need to return any value\n elif fail_index == -2:\n '''-2. Start program again.'''\n return -2\n else:\n '''\n In general, it is impossible to run this code here. If it's correct, developer will have \n a green face.\n '''\n print(\"Something Error happen......\")\n '''It's time to start Log mechanism to save information about bug'''\n sys.exit(0)\n else:\n time.sleep(0.1)\n time_stamp += 1\n else:\n '''Wi-Fi connected successfully'''\n return 1\n else:\n return -1\n\n\nclass SpeedTest(Parameter, threading.Thread):\n\n # def __init__(self, wifi_name, thread_lock):\n # threading.Thread.__init__(self)\n # super(SpeedTest, self).__init__(wifi_name)\n # self.wifi_name = wifi_name\n # self.thread_lock = thread_lock\n\n def __init__(self, wifi_name):\n super(SpeedTest, self).__init__(wifi_name)\n self.wifi_name = wifi_name\n\n\n def internet_speed_test(self, module):\n # if self.getName()[-1:] == \"1\":\n # interface_card = \"Wi-Fi\"\n # else:\n # interface_card = \"Wi-Fi {}\".format(self.getName()[-1:])\n\n decode_obj = File_Decode()\n file_obj, csv_obj = decode_obj.build_file(self.wifi_name)\n\n print(\"======Start to test module {} internet speed with SSID \\\"{}\\\" ======\".format(module, self.wifi_name))\n start_time = time.time()\n\n wireless_client_info_obj = ClientInfo()\n wireless_client_info = wireless_client_info_obj.interface_info()\n\n speedtest_headers_csv = decode_obj.decode_info_speedtest(subprocess.check_output(\"speedtest-cli --csv-header\"))\n\n '''\n Here I want to determine that if one od multiple threading had write the csv header in file header, then other \n threading don't need to write t again.\n\n coding my description:\n if \"\"Server ID\" had exist in my csv file some line:\n The thread doesn't write the csv header to file again.\n else:\n Because the csv header doesn't exist, so the thread will write the csv header to file. \n\n '''\n # if \"Server ID\" in file_obj.read():\n # pass\n # else:\n # csv_obj.writerow(speedtest_headers_csv)\n\n csv_obj.writerow([module + \"-speed-test\"])\n csv_obj.writerow([])\n csv_obj.writerow(speedtest_headers_csv)\n speedtest_download_data_list = []\n speedtest_upload_data_list = []\n\n test_time = 15\n\n for _ in range(test_time):\n speedtest_time_stamp = 0\n while True:\n try:\n speedtest_time_stamp += 1\n if speedtest_time_stamp < 10:\n speedtest_data_csv = decode_obj.decode_info_speedtest(\n subprocess.check_output(\"speedtest-cli --csv --server 2133\"))\n csv_obj.writerow(speedtest_data_csv)\n speedtest_download_data_list.append(speedtest_data_csv[-4])\n speedtest_upload_data_list.append(speedtest_data_csv[-3])\n # print(\"test for {} time\".format(i))\n break\n else:\n internet_serveice_answer = input(\n \"[SpeedTest Manager:] Please check your internet service is okay or not. (y/n) \\n\")\n det_answer = re.search('n', internet_serveice_answer, re.IGNORECASE)\n if det_answer:\n answer = input(\"Do you want to continue? (y/n) \\n\")\n det_answer = re.search('n', answer, re.IGNORECASE)\n if det_answer:\n return -1\n else:\n speedtest_time_stamp = 0\n else:\n speedtest_time_stamp = 0\n # raise subprocess.CalledProcessError\n except subprocess.CalledProcessError as speedtest_error:\n print(speedtest_error)\n return -1\n\n download_average = np.average(np.array(speedtest_download_data_list, dtype=np.float)) / 1000000\n upload_average = np.average(np.array(speedtest_upload_data_list, dtype=np.float)) / 1000000\n\n download_max = np.max(np.array(speedtest_download_data_list, dtype=np.float)) / 1000000\n upload_max = np.max(np.array(speedtest_upload_data_list, dtype=np.float)) / 1000000\n\n download_min = np.min(np.array(speedtest_download_data_list, dtype=np.float)) / 1000000\n upload_min = np.min(np.array(speedtest_upload_data_list, dtype=np.float)) / 1000000\n\n csv_obj.writerow([])\n result_header = (\n \"download_average\", \"upload_average\", \"download_max\", \"upload_max\", \"download_min\", \"upload_min\", \"channel\")\n csv_obj.writerow(result_header)\n csv_obj.writerow([download_average, upload_average, download_max, upload_max, download_min, upload_min,\n wireless_client_info[\"channel\"]])\n csv_obj.writerow([])\n csv_obj.writerow([])\n\n end_time = time.time()\n\n print(\"============= {} Test Result==============\".format(module))\n print(\"This test for {} time to test internet speed.\".format(test_time))\n print(\"Channel: {}\".format(wireless_client_info[\"channel\"]))\n print(\"Download Average: {} Mbit/s\".format(download_average))\n print(\"Upload Average: {} Mbit/s\".format(upload_average))\n print(\"Download Max: {} Mbit/s\".format(download_max))\n print(\"Upload Max: {} Mbit/s\".format(upload_max))\n print(\"Download Min: {} Mbit/s\".format(download_min))\n print(\"Upload Min: {} Mbit/s\".format(upload_min))\n\n total_time = end_time - start_time\n total_time_seconds = total_time % 60\n total_time_minutes = total_time / 60\n total_time_hours = total_time_minutes / 60\n print(\"Test Time: {} hours {} minutes {} seconds\".format(total_time_hours, total_time_minutes,\n total_time_seconds))\n\n print(\"===============================\")\n\n return speedtest_download_data_list, speedtest_upload_data_list\n\n\n def main_test_script(self):\n '''Here is the main code to run all class or funcion'''\n\n\nif __name__ == \"__main__\":\n '''start your program'''\n\n # wifi = \"iAirJordan\"\n\n '''Method 1. : In one threading to work'''\n # speedtest_obj = SpeedTest(wifi)\n # test_result = speedtest_obj.internet_speed_test()\n # if test_result == 1:\n # print(\"successful\")\n # else:\n # print(\"error\")\n\n '''Method 2. : In one threading to work'''\n # Your DUT module list\n module_list = [\"DWL-6620AP\", \"DWL-7620AP\", \"DWL-8620AP\", \"DWL-6610AP\"]\n # Your target SSID that will be connected to and test internet speed\n wifi_list = [\"6620-speed-test-2.4g\", \"7620-speed-test-2.4g\", \"8620-speed-test-2.4g\", \"6610-speed-test-2.4g\",\n \"6620-speed-test-5g\", \"7620-speed-test-5g\", \"8620-speed-test-5g\", \"6610-speed-test-5g\"]\n # module_list = [\"DWL-6620AP\"]\n # wifi_list = [\"6620-speed-test-2.4g\"]\n # module_list = [\"test\"]\n # wifi_list = [\"TSD-V13-lab-5G\"]\n\n for index in range(len(wifi_list)):\n wifi_obj = WiFi(wifi_list[index], \"Wi-Fi\")\n send_request_index = wifi_obj.connection_request_Open()\n '''Add function to determine the SSID had been connected successfully or not'''\n if send_request_index == 1:\n time.sleep(5)\n speedtest_obj = SpeedTest(wifi_list[index])\n speedtest_obj.internet_speed_test(module_list[0])\n print(\"==================== Finish ====================\")\n # if index > 3:\n # speedtest_obj.internet_speed_test(module_list[index-4])\n # print(\"================ module {} with SSID \\\"{}\\\" test Finish.================\".format(\n # module_list[index-4], wifi_list[index]))\n # else:\n # speedtest_obj.internet_speed_test(module_list[index])\n # print(\"================ module {} with SSID \\\"{}\\\" test Finish.================\".format(\n # module_list[index], wifi_list[index]))\n\n # test_result = speedtest_obj.internet_speed_test(module_list[index])\n # if test_result == 1:\n # print(\"successful\")\n # else:\n # print(\"error\")\n else:\n print(\"Error happen\")\n\n '''Method 3 : Work with multiple threading'''\n # thread_number = 10\n #\n # thread_obj = threading.Thread()\n # thread_lock = threading.Lock()\n #\n # thread_list = []\n # for j in range(thread_number):\n # thread_list.append(SpeedTest(wifi, thread_lock))\n # thread_list[j].setName(\"thread-{}\".format(str(j)))\n # thread_list[j].start()\n #\n # for j in range(thread_number):\n # thread_list[j].join()\n","sub_path":"Network_Tools_Development/networks_speed_test.py","file_name":"networks_speed_test.py","file_ext":"py","file_size_in_byte":37180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"432000738","text":"import cv2\nimport numpy as np\nimport subprocess\nimport time\n\ngain = 35\nexposure = 100\nfps = 30\ncam_props = {'horizontal_flip': 0, 'gain_automatic': 0, 'auto_exposure': 1, 'gain': gain, 'exposure': exposure}\nfor key in cam_props:\n subprocess.call(['v4l2-ctl -d /dev/video2 -c {}={}'.format(key, str(cam_props[key]))], shell=True)\n# Create a VideoCapture object\ncap = cv2.VideoCapture(2)\ncap.set(cv2.CAP_PROP_FPS, 60)\ncap2 = cv2.VideoCapture(3)\ncap2.set(cv2.CAP_PROP_FPS, 60)\n# Check if camera opened successfully\nif (cap.isOpened() == False or cap2.isOpened() == False):\n print(\"Unable to read camera feed\")\n\n# Default resolutions of the frame are obtained.The default resolutions are system dependent.\n# We convert the resolutions from float to integer.\nframe_width = int(cap.get(3))\nframe_height = int(cap.get(4))\nframe_width2 = int(cap2.get(3))\nframe_height2 = int(cap2.get(4))\n\n# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.\nout = cv2.VideoWriter(f'videos/cam1_stairs5.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps, (frame_width, frame_height))\n\n#out2 = cv2.VideoWriter(f'videos/cam2_802light_ccw.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps, (frame_width2, frame_height2))\nout2 = cv2.VideoWriter(f'videos/cam2_stairs5.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps, (frame_width2, frame_height2))\n\n\nstart = 0\njunk = 0\nwhile (True):\n\n while (time.time()-start) < 1/fps:\n pass\n end = time.time()\n seconds = end - start\n print(seconds)\n ret, frame = cap.read()\n ret2, frame2 = cap2.read()\n start = time.time()\n if ret:\n\n # Write the frame into the file 'output.avi'\n out.write(frame)\n out2.write(frame2)\n\n # Display the resulting frame\n cv2.imshow('frame', frame)\n cv2.imshow('frame2', frame2)\n # Press Q on keyboard to stop recording\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n # Break the loop\n else:\n break\n\n # When everything done, release the video capture and video write objects\ncap.release()\nout.release()\ncap2.release()\nout2.release()\n# Closes all the frames\ncv2.destroyAllWindows()\n","sub_path":"videocapture2cam.py","file_name":"videocapture2cam.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"569139625","text":"import random, sys, string, subprocess\nimport uuid\nimport numpy as np\n\n# # Globals # #\n\nQUIET = False # Global verbosity flag\nLOGGING = False # Global file logging flag\nTEMP_ID = '%s' % uuid.uuid4()\n\nLOG_FILE_PATH = 'nuc-tools-out-%s.log' % TEMP_ID\nLOG_FILE_OBJ = None # Created when needed\n\nimport core.nuc_parallel as parallel\n\n# # Srcreen reporting # # \n\ndef report(msg):\n \n global LOG_FILE_OBJ\n \n if LOGGING:\n if not LOG_FILE_OBJ:\n LOG_FILE_OBJ = open(LOG_FILE_PATH, 'w')\n \n LOG_FILE_OBJ.write(msg)\n \n if not QUIET:\n print(msg)\n \n\ndef warn(msg, prefix='WARNING'):\n\n report('%s: %s' % (prefix, msg))\n\n \ndef critical(msg, prefix='FAILURE'):\n\n report('%s: %s' % (prefix, msg))\n sys.exit(0)\n\n\ndef info(msg, prefix='INFO'):\n\n report('%s: %s' % (prefix, msg))\n\n\n# # Run # # \n \ndef call(cmd_args, stdin=None, stdout=None, stderr=None, verbose=True, wait=True, path=None, shell=False):\n \"\"\"\n Wrapper for external calls to log and report commands,\n open stdin, stderr and stdout etc.\n \"\"\"\n \n if verbose:\n info(' '.join(cmd_args))\n \n if path:\n env = dict(os.environ)\n prev = env.get('PATH', '')\n \n if path not in prev.split(':'):\n env['PATH'] = prev + ':' + path\n \n else:\n env = None # Current environment variables \n \n if shell:\n cmd_args = ' '.join(cmd_args)\n \n if stdin and isinstance(stdin, str):\n stdin = open(stdin)\n\n if stdout and isinstance(stdout, str):\n stdout = open(stdout, 'w')\n\n if stderr and isinstance(stderr, str):\n stderr = open(stderr, 'a')\n \n if stderr is None and LOGGING:\n logging()\n stderr = LOG_FILE_OBJ\n \n if wait:\n subprocess.call(cmd_args, stdin=stdin, stdout=stdout, stderr=stderr, env=env, shell=shell)\n \n else:\n subprocess.Popen(cmd_args, stdin=stdin, stdout=stdout, stderr=stderr, env=env, shell=shell)\n\n\n# # Strings # #\n\n \ndef get_rand_string(size):\n \n return ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for i in range(size))\n\n\n# # Kmeans # #\n\ndef kMeansSpread(data, k, thresh=1e-10, verbose=False):\n \"\"\"k-means with better spread starting values\"\"\"\n \n n = len(data)\n index = np.random.randint(0, n)\n indices = set([index])\n \n influence = np.zeros(n)\n while len(indices) < k:\n diff = data - data[index]\n sumSq = (diff * diff).sum(axis=1) + 1.0\n influence += 1.0 / sumSq\n index = influence.argmin()\n \n while index in indices:\n index = np.random.randint(0, n)\n \n indices.add(index) \n \n centers = np.vstack([data[i] for i in indices])\n \n return kMeans(data, k, centers, thresh, verbose)\n\n\ndef kMeans(data, k, centers=None, thresh=1e-10, verbose=False):\n \"\"\"k-means clustering\"\"\"\n \n if centers is None:\n centers = np.array( np.random.choice(list(data), k, replace=False) ) # list() not needed in Python 2\n\n labels = np.empty(len(data), float)\n change = 1.0\n prev = []\n\n j = 0\n while change > thresh:\n\n clusters = [[] for x in range(k)]\n for i, vector in enumerate(data):\n diffs = centers - vector\n dists = (diffs * diffs).sum(axis=1)\n closest = dists.argmin()\n labels[i] = closest\n clusters[closest].append(vector)\n \n change = 0\n for i, cluster in enumerate(clusters):\n cluster = np.array(cluster)\n n = max(len(cluster), 1) # protect against being 0\n center = cluster.sum(axis=0)/n\n diff = center - centers[i]\n change += (diff * diff).sum()\n centers[i] = center\n \n j += 1\n \n if verbose:\n print(j, change) \n \n return centers, clusters, labels\n\n\n","sub_path":"core/nuc_util.py","file_name":"nuc_util.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"628896358","text":"import os\nfrom pathlib import Path\nfrom loguru import logger\nfrom dotenv import load_dotenv\n# from vault_client.client import VaultClient\n\n\ndef init_env_and_logger():\n APP_ENV = os.environ.get('APP_ENV', 'DEV')\n env = f\"{APP_ENV}.env\".lower()\n src_path = Path.cwd()\n path_file = src_path.joinpath('.deploy', '.envs', env)\n load_dotenv(path_file)\n cfg_env = os.environ\n cfg = dict()\n cfg['env'] = env\n cfg['stage'] = APP_ENV.lower()\n service_name = \"SERVICES_INFO\"\n cfg[\"service\"] = service_name.lower()\n cfg['log_file'] = os.environ.get(f\"SERVICE_{service_name}_LOG_FILE\", \"services_info\")\n cfg['log_file'] = src_path.joinpath('logs', cfg['log_file'])\n\n cfg['base_name'] = os.environ.get(f\"SERVICE_{service_name}_BASE_NAME\", \"services_info_dev\")\n cfg['table_name'] = os.environ.get(f\"SERVICE_{service_name}_BASE_NAME\", \"services_dev\")\n\n logger.info(f\"SERVICE: {service_name}\")\n logger.info(f\"APP_ENV: {APP_ENV}\")\n logger.info(f\"cfg_env: {env}\")\n\n cfg['log_level'] = os.environ.get(f\"SERVICE_{service_name}_LOG_LEVEL\", \"INFO\")\n log_level_list = cfg['log_level'].split(\",\")\n if len(log_level_list) > 1:\n serialize = True\n else:\n serialize = False\n cfg['log_level'] = log_level_list[0]\n logger.add(cfg['log_file'], level=cfg['log_level'], serialize=serialize)\n cfg[\"logger\"] = logger\n # # logger.add(sys.stderr, level=log_level, serialize=serialize)\n #\n #\n # logger.info(f\"Service {course_creator_service}: host: {course_creator_host} port: {course_creator_port}\")\n # logger.info(f\"Service {course_creator_service}: src_path: {src_path} log_file_name: {log_file_name}\")\n logger.info(f\"Service {service_name}: log_level: {cfg['log_level']} serialize: {serialize}\")\n cfg['service_port'] = os.environ.get(f\"SERVICE_{service_name}_PORT\", 50100)\n\n cfg['service_host'] = os.environ.get(f\"SERVICE_{service_name}_HOST\", \"0.0.0.0\")\n\n #\n # storage_service = \"STORAGE\"\n # storage_port = client.get(storage_service, \"port\")\n # assert storage_port is not None, f\"Service {storage_service} port not set.\"\n #\n # storage_host = client.get(storage_service, \"host\")\n # assert storage_host is not None, f\"Service {storage_service} host not set.\"\n #\n # storage_schema = client.get(storage_service, \"schema\")\n # assert storage_schema is not None, f\"Service {storage_service} schema not set.\"\n #\n # logger.info(f\"Service {storage_service}: host: {storage_host} port: {storage_port}\")\n #\n # parser_service = \"PARSER\"\n # parser_port = client.get(parser_service, \"port\")\n # assert parser_port is not None, f\"Service {parser_service} port not set.\"\n #\n # parser_host = client.get(parser_service, \"host\")\n # assert parser_host is not None, f\"Service {parser_service} host not set.\"\n #\n # parser_schema = client.get(parser_service, \"schema\")\n # assert parser_schema is not None, f\"Service {parser_service} schema not set.\"\n return cfg\n # return {\"logger\": logger,\n # \"service\": service_name,\n # \"stage\": APP_ENV,\n # \"service_port\": service_port,\n # \"service_host\": service_host,\n # # \"course_creator_host\": course_creator_host, \"course_creator_port\": course_creator_port,\n # # \"course_creator_schema\": course_creator_schema,\n # # \"course_creator_token\": course_creator_token,\n # # \"parser_port\": parser_port, \"parser_host\": parser_host, \"parser_schema\": parser_schema,\n # # \"storage_port\": storage_port, \"storage_host\": storage_host, \"storage_schema\": storage_schema,\n # }","sub_path":"opentelemetry_examples/services_info/app/internal/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"409319588","text":"import os\nimport secrets\nfrom secretgraph.settings.withclient import * # noqa: F403, F401, E402\n\nDOCKER_VOLUME_DIR = \"/var/lib/secretgraph\"\n\nDATABASES = {\n \"default\": {\n \"ENGINE\": os.environ.get(\"DB_ENGINE\", \"django.db.backends.sqlite3\"),\n \"NAME\": os.environ.get(\n \"DB_NAME\", os.path.join(DOCKER_VOLUME_DIR, \"db.sqlite3\")\n ),\n \"USER\": os.environ.get(\"DB_USER\", \"\"),\n \"PASSWORD\": os.environ.get(\"DB_PASSWORD\", \"\"),\n \"HOST\": os.environ.get(\"DB_HOST\", \"\"),\n \"PORT\": os.environ.get(\"DB_PORT\", \"\"),\n }\n}\n\nSECRET_KEY = os.environ.get(\"SECRET_KEY\", secrets.token_hex(32))\n\n\nINSTALLED_APPS += [ # noqa F405\n \"django.contrib.auth\", # required for user\n \"django.contrib.contenttypes\", # required for auth\n \"secretgraph.server\",\n]\n\nDEFAULT_AUTO_FIELD = \"django.db.models.BigAutoField\"\n# requires auth app\nSECRETGRAPH_BIND_TO_USER = True\nSECRETGRAPH_ALLOW_REGISTER = (\n os.environ.get(\"ALLOW_REGISTER\", \"false\").lower() == \"true\"\n)\n\nMEDIA_ROOT = os.path.join(DOCKER_VOLUME_DIR, \"media/\")\nALLOWED_HOSTS = os.environ.get(\"ALLOWED_HOSTS\", \"localhost\").split(\",\")\n","sub_path":"secretgraph/settings/docker.py","file_name":"docker.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"565722554","text":"import sqlite3\nfrom time import gmtime, strftime\nimport json\nimport os\n\ndb = sqlite3.connect(\"data.db\")\ndb.row_factory = sqlite3.Row\ncursor = db.cursor()\n\n\nprint(\"Building JSON from DB... \")\n\ndef clear():\n os.system('cls||clear')\n\ndef check_same(subreddits, subreddits_allowed):\n \"\"\"\n TODO: Improve performance here (currently we're running as worst case n1^n2 with n1 being the subreddits and n2 being subreddits_allowed)\n \"\"\"\n for subreddit in subreddits:\n for subreddit_allowed in subreddits_allowed:\n if subreddit.lower() == subreddit_allowed.lower():\n return True\n return False\n\n\ndef build_data(subreddits_allowed=[]):\n cursor.execute(\n \"SELECT SUM(score) as score, SUM(num_comments) as num_comments, author, COUNT(author) AS num_posts FROM posts GROUP BY (author) ORDER BY SUM(score)\")\n\n rows = cursor.fetchall()\n users = []\n for row in rows:\n user = dict()\n row = dict(row)\n cursor.execute(\n \"SELECT DISTINCT(subreddits.displayname) AS displayname FROM (posts INNER JOIN subreddits ON subreddits.subname = posts.subname) WHERE author = ?\", (row['author'], ))\n subreddits = [dict(sub_row)['displayname']\n for sub_row in cursor.fetchall()]\n if subreddits_allowed == [] or check_same(subreddits, subreddits_allowed):\n cursor.execute(\n \"SELECT posts.title, posts.permalink, posts.score, posts.upvote_ratio, subreddits.displayname as subname FROM (posts INNER JOIN subreddits ON subreddits.subname = posts.subname) WHERE author = ?\", (row['author'], ))\n posts = [dict(title=dict(post_row)['title'], subreddit=dict(post_row)['subname'], link=dict(post_row)['permalink'], score=dict(post_row)[\n 'score'], upvote_ratio=dict(post_row)['upvote_ratio']) for post_row in cursor.fetchall()]\n user['username'] = row['author']\n user['score'] = row['score']\n user['post_count'] = row['num_posts']\n user['comment_count'] = row['num_comments']\n user['subreddits'] = subreddits\n user['posts'] = posts\n users.append(user)\n return users\n\n\ndef write_json(users, filename=None):\n if filename is None:\n filename = \"users-{}\".format(\n strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime()))\n file = open(\n \"exports/{}.json\".format(filename), \"w\")\n file.write(json.dumps(users, indent=4))\n file.close()\n print(\"Saved to exports/{}.json\".format(filename))\n\n\ndef query_entry():\n user_input = \"replaceme\"\n while user_input != \"\":\n print(\n \"[B] : Build JSON file\\n[S] Search data\\n[Q] Execute query\\n[C] Clear terminal\\nPress enter with no input to quit\")\n\n user_input = input(\"Choice: \")\n if user_input.lower() == \"b\":\n filename = input(\n \"Name of dump (leave blank to autoname dump with timestamp):\")\n subreddits = input(\n \"Comma seperated list of subreddits to filter to (leave blank to disable filtering):\")\n subreddits = subreddits.split(\",\")\n if subreddits == ['']:\n subreddits = []\n if filename == \"\":\n write_json(build_data(\n subreddits_allowed=subreddits))\n else:\n write_json(build_data(\n subreddits_allowed=subreddits), filename=filename)\n elif user_input.lower() == \"s\":\n search_term = input(\"Enter a search term in titles: \")\n cursor.execute(\n \"SELECT posts.title, posts.permalink, posts.score, posts.upvote_ratio, subreddits.displayname as subname FROM (posts INNER JOIN subreddits ON subreddits.subname = posts.subname) WHERE posts.title LIKE ?\", (\"%{}%\".format(search_term), ))\n\n posts = [dict(title=dict(post_row)['title'], subreddit=dict(post_row)['subname'], link=dict(post_row)['permalink'], score=dict(post_row)[\n 'score'], upvote_ratio=dict(post_row)['upvote_ratio']) for post_row in cursor.fetchall()]\n confirmed = False\n while not confirmed:\n \tif len(posts) > 10:\n confirm = input(\"There are {} posts in the result set. Are you sure you want to display them? [y/N]\".format(len(posts)))\n if confirm.lower() == \"y\":\n confirmed = True\n break\n \telse:\n confirmed = True\n if confirmed:\n print(json.dumps(posts, indent=4))\n print(\"Found {} posts\".format(len(posts)))\n\n elif user_input.lower() == \"q\":\n query_input = input(\"Query: \")\n try:\n cursor.execute(query_input)\n rows = cursor.fetchall()\n to_print = []\n for row in rows:\n to_print.append(dict(row))\n print(json.dumps(to_print, indent=4))\n except Exception as e:\n print(\"===ERROR===\\n{}\\n=========\".format(e))\n elif user_input.lower() == \"c\":\n clear()\n print(\"Goodbye!\")\n\n\nif __name__ == \"__main__\":\n query_entry()\n\n","sub_path":"analyse_data.py","file_name":"analyse_data.py","file_ext":"py","file_size_in_byte":5204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"403951182","text":"import sys\nimport numpy as np\nimport heapq\n\n\ndef rectOk(r1,c1,r2,c2,skip,grid):\n\tfor r in range(r1,r2+1):\n\t\tfor c in range(c1,c2+1):\n\t\t\tif grid[r][c] != '?' and grid[r][c] != skip:\n\t\t\t\treturn False\n\treturn True\n\ndef solve(R,C,grid):\n\tprocessed = set()\n\tfor r in range(R):\n\t\tfor c in range(C):\n\t\t\tcurrent = grid[r][c]\n\t\t\tif current == '?' or current in processed:\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tprocessed.add(current)\n\t\t\tmaxRect = (r,c,r,c)\n\t\t\tmaxArea = 1\n\n\n\t\t\tfor r1 in range(0,r+1):\n\t\t\t\tfor r2 in range(r,R):\n\t\t\t\t\tfor c1 in range(0,c+1):\n\t\t\t\t\t\tfor c2 in range(c,C):\n\t\t\t\t\t\t\tarea = (r2-r1+1)*(c2-c1+1)\n\t\t\t\t\t\t\tif area > maxArea:\n\t\t\t\t\t\t\t\tif rectOk(r1,c1,r2,c2,current,grid):\n\t\t\t\t\t\t\t\t\tmaxArea = area\n\t\t\t\t\t\t\t\t\tmaxRect = (r1,c1,r2,c2)\n\n\t\t\tr1,c1,r2,c2 = maxRect\n\t\t\tfor rp in range(r1,r2+1):\n\t\t\t\tfor cp in range(c1,c2+1):\n\t\t\t\t\tgrid[rp][cp] = current\n\n\n\treturn grid\n\n\nt = int(raw_input())\nfor i in range(1, t + 1):\n\n\tR, C = [int(s) for s in raw_input().split(\" \")]\n\tgrid = []\n\tfor r in range(R):\n\t\tgrid.append([c for c in raw_input()])\n\n\t\n\tresult = solve(R, C, grid)\n\n\tprint(\"Case #{}:\".format(i))\n\tfor el in result:\n\t\tprint(\"{}\".format(\"\".join(el)))\n","sub_path":"solutions_python/Problem_203/737.py","file_name":"737.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"338741597","text":"from django.conf.urls import patterns, include, url\nfrom django.conf.urls.i18n import i18n_patterns\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns, static\n\n\nurlpatterns = patterns(\n url(r'^i18n/', include('django.conf.urls.i18n')),\n)\n\nurlpatterns += i18n_patterns('',\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n (r'^ckeditor/', include('ckeditor_uploader.urls')),\n url(r'^bcks/', include('bcks_files.urls', namespace='bcks')),\n url(r'^d_files/', include('d_files.urls', namespace='d_files')),\n url(r'^', include('pages.urls', namespace='pages')),\n )\n\nif 'rosetta' in settings.INSTALLED_APPS:\n urlpatterns += patterns('',\n url(r'^rosetta/', include('rosetta.urls')),\n )\n\nif settings.DEBUG:\n urlpatterns += staticfiles_urlpatterns()\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"bitnik_pw/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"553606764","text":"import plotly_express as px \r\nimport csv\r\nimport numpy as np\r\ndef getDataSource(data_path):\r\n marks_percentage=[]\r\n days_present=[]\r\n with open(data_path)as f:\r\n # this will read the document in the form of dictionary\r\n csv_reader=csv.DictReader(f)\r\n for row in csv_reader:\r\n marks_percentage.append(float(row['Marks In Percentage']))\r\n days_present.append(float(row['Days Present']))\r\n return {'x':marks_percentage,'y':days_present} \r\ndef findCorrelation(datasource):\r\n correlation=np.corrcoef(datasource['x'],datasource['y']) \r\n print('The correlation between the marks in percentage and days present is:',correlation[0,1]) \r\ndef setUp(): \r\n data_path='C:/Users/Bajwa/Downloads/CSV_Files (2)/Student Marks vs Days Present.csv'\r\n datasource=getDataSource(data_path)\r\n findCorrelation(datasource)\r\nsetUp() \r\n","sub_path":"Correlation.py","file_name":"Correlation.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"7649399","text":"\n\n#calss header\nclass _FORGIVE():\n\tdef __init__(self,): \n\t\tself.name = \"FORGIVE\"\n\t\tself.definitions = [u'to stop blaming or being angry with someone for something that person has done, or not punish them for something: ', u'used before you ask or say something that might seem rude: ', u'to say that money does not have to be paid back: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_forgive.py","file_name":"_forgive.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"425067577","text":"import pathlib\nimport setuptools\n\nHERE = pathlib.Path(__file__).parent\nREADME = (HERE / \"README.md\").read_text()\n\nsetuptools.setup(\n name=\"discorpy\",\n version=\"1.3\",\n author=\"Nghia Vo\",\n author_email=\"nghia.vo@diamond.ac.uk\",\n description='Radial lens distortion correction in Python',\n long_description=README,\n long_description_content_type=\"text/markdown\",\n keywords=['Distortion correction', 'Tomography', 'Radial lens distortion',\n 'Camera calibration'],\n url=\"https://github.com/DiamondLightSource/discorpy\",\n download_url='https://github.com/DiamondLightSource/discorpy.git',\n license=\"Apache 2.0\",\n platforms=\"Any\",\n packages=setuptools.find_packages(include=[\"discorpy\", \"discorpy.*\"],\n exclude=['test*', 'doc*', 'data*',\n 'example*']),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Intended Audience :: Science/Research\",\n \"Operating System :: OS Independent\",\n \"Natural Language :: English\",\n \"Topic :: Scientific/Engineering :: Image Processing\"\n ],\n install_requires=[\n \"matplotlib\",\n \"numpy\",\n \"scipy\",\n \"scikit-image\",\n \"h5py\",\n \"pillow\"\n ],\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"262233830","text":"import inspect\nimport re\nfrom django import template\nfrom django.conf import settings\nfrom django.core import urlresolvers\nfrom django.utils.translation import ugettext as _\nfrom django.contrib.admin.views.main import PAGE_VAR\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import get_language\nfrom yawdadmin import admin_site\nfrom yawdadmin.conf import settings as ls\n\n\nregister = template.Library()\n\n\n@register.inclusion_tag('admin/includes/topmenu.html', takes_context=True)\ndef admin_top_menu(context):\n return {\n 'perms' : context['perms'],\n 'top_menu' : admin_site.top_menu(context['request']),\n 'homeurl' : urlresolvers.reverse('admin:index'),\n 'user' : context['user'],\n 'langs' : context['langs'] if 'langs' in context else [],\n 'default_lang': context['default_lang'] if 'default_lang' in context else None,\n 'clean_url' : context['clean_url'] if 'clean_url' in context else '',\n 'LANGUAGE_CODE' : get_language(),\n 'optionset_labels' : admin_site.get_option_admin_urls(),\n 'analytics' : context['user'].is_superuser and ls.ADMIN_GOOGLE_ANALYTICS_FLOW,\n }\n\n\n@register.simple_tag\ndef clean_media(media):\n if hasattr(media, '_js'):\n media._js = [i for i in media._js if not re.match(\n r'%sadmin/js/((jquery(\\.init)?|collapse|admin/RelatedObjectLookups)(\\.min)?\\.)js' % settings.STATIC_URL, i)]\n return media\n\n\n@register.simple_tag\ndef yawdadmin_paginator_number(cl,i):\n \"\"\"\n Generates an individual page index link in a paginated list.\n \"\"\"\n if i == '.':\n return mark_safe('
  • ...
  • ')\n elif i == cl.page_num:\n return mark_safe('
  • %s
  • ' % str(i+1))\n else:\n return '
  • %s
  • ' % (\n cl.get_query_string({PAGE_VAR: i}),\n mark_safe(' class=\"end\"' if i == cl.paginator.num_pages-1 else ''),\n i+1)\n\n\n@register.simple_tag(takes_context=True)\ndef get_admin_site_meta(context):\n context['ADMIN_SITE_NAME'] = getattr(settings, 'ADMIN_SITE_NAME',\n _('Django Administration'))\n context['ADMIN_SITE_DESCRIPTION'] = getattr(settings, 'ADMIN_SITE_DESCRIPTION',\n _('Welcome to the yawd-admin administration page. Please sign in to manage your website.'))\n context['ADMIN_DISABLE_APP_INDEX'] = getattr(settings, 'ADMIN_DISABLE_APP_INDEX', False)\n return ''\n\n\n@register.simple_tag\ndef get_admin_logo():\n return getattr(settings, 'ADMIN_SITE_LOGO_HTML', '')\n\n\n@register.simple_tag\ndef get_object_icon(obj, default_icon=''):\n try:\n return admin_site._registry[obj if inspect.isclass(obj) else obj.__class__].title_icon\n except:\n return default_icon\n","sub_path":"yawdadmin/templatetags/yawdadmin_tags.py","file_name":"yawdadmin_tags.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"455200994","text":"import os\nimport sys\nimport constants\nimport mountpoint\nimport pytsk3\nfrom afip.metatag import HiveFileLocationsWindowsNT\nfrom Registry import Registry\nimport tempfile\nfrom collections import OrderedDict\n\n\nclass Index(object):\n \"\"\"\n Base class\n \"\"\"\n def __init__(self, image_path):\n self.image_path = image_path\n self.mount = mountpoint.MountPoint(self.image_path)\n self.type = self.mount.mount_type()\n self.mountobject_img = self.mount.mount_img_info(self.type)\n\n def partition_table(self):\n \"\"\"\n Retrieve Partition tables by using Pytsk3 VolumeObjects\n \"\"\"\n mountobject_volume = self.mount.mount_volume_info(self.mountobject_img)\n tables = self.mount.partitiontable(mountobject_volume)\n\n #Retrieve partition tables\n for table in tables:\n yield table\n\n def image_metadata(self):\n \"\"\"\n Retrieve Disk Meta information from Pytsk3 VolumeObject\n \"\"\"\n mountobject_volume = self.mount.mount_volume_info(self.mountobject_img)\n \"\"\"\n Create python generator to prevent memory spikes\n \"\"\"\n generator = self.mount.ntfs_partition_offset(mountobject_volume)\n for entry in generator:\n filesystem = pytsk3.FS_Info(self.mountobject_img, offset=(entry*512))\n yield filesystem.info.block_count, \\\n filesystem.info.block_post_size, \\\n filesystem.info.block_size, \\\n filesystem.info.dev_bsize, \\\n filesystem.info.first_block, \\\n filesystem.info.first_inum, \\\n filesystem.info.fs_id_used, \\\n filesystem.info.inum_count, \\\n filesystem.info.journ_inum, \\\n filesystem.info.last_block, \\\n filesystem.info.last_block_act, \\\n filesystem.info.root_inum, \\\n filesystem.info.tag, \\\n\n def root_directory(self, type):\n \"\"\"\n Retrieve root directory by using root_inode number\n \"\"\"\n mountobject_volume = self.mount.mount_volume_info(self.mountobject_img)\n\n if type == 'NTFS':\n generator = self.mount.ntfs_partition_offset(mountobject_volume)\n\n for ntfsentry in generator:\n yield ntfsentry\n fileSystemObject = pytsk3.FS_Info(self.mountobject_img, offset=(ntfsentry*512))\n #Get root_inode\n root_inode = fileSystemObject.info.root_inum\n for item in fileSystemObject.open_dir(inode=root_inode):\n yield item\n\n def get_image_os_version(self):\n \"\"\"\n Retrieve OS Information from filesystem by using registry keys\n \"\"\"\n mountobject_volume = self.mount.mount_volume_info(self.mountobject_img)\n \"\"\"\n Usage of python generator to prevent memory spikes\n \"\"\"\n generator = self.mount.ntfs_partition_offset(mountobject_volume)\n for entry in generator:\n #Create Pytsk3 file system\n filesystem = pytsk3.FS_Info(self.mountobject_img, offset=(entry*512))\n try:\n #HiveFile location for windows systems SOFTWARE hive\n HiveLocation = filesystem.open_dir(\"Windows/System32/Config\")\n for hive in HiveLocation:\n\n if hive.info.name.name == 'SOFTWARE':\n #Create temporary file of Software Hive\n hivefile = filesystem.open_meta(hive.info.meta.addr)\n temporaryfile = tempfile.TemporaryFile(mode = 'w+r')\n filedata = hivefile.read_random(0,hivefile.info.meta.size)\n temporaryfile.write(filedata)\n temporaryfile.seek(0)\n\n reg = Registry.Registry(temporaryfile)\n #Find Registry Key\n try:\n key = reg.open(\"Microsoft\\\\Windows NT\\\\CurrentVersion\")\n except Registry.RegistryKeyNotFoundException:\n sys.exit(-1)\n\n #Loop through registry keys and find RegistryKeys and DWORDs\n WindowsVersionDict = {}\n try:\n for v in key.values():\n\n if v.value_type() == 1:\n if v.name() == 'CSDBuildNumber':\n WindowsVersionDict[v.name()] = v.value()\n if v.name() == 'CSDVersion':\n WindowsVersionDict[v.name()] = v.value()\n if v.name() == 'CurrentBuild':\n WindowsVersionDict[v.name()] = v.value()\n if v.name() == 'CurrentVersion':\n WindowsVersionDict[v.name()] = v.value()\n if v.name() == 'EditionID':\n WindowsVersionDict[v.name()] = v.value()\n if v.name() == 'ProductId':\n WindowsVersionDict[v.name()] = v.value()\n if v.name() == 'ProductName':\n WindowsVersionDict[v.name()] = v.value()\n if v.name() == 'RegisteredOwner':\n WindowsVersionDict[v.name()] = v.value()\n if v.name() == 'SystemRoot':\n WindowsVersionDict[v.name()] = v.value()\n elif v.value_type() == 4:\n if v.name() == 'InstallDate':\n WindowsVersionDict[v.name()] = v.value()\n\n except Registry.Registry.RegistryValueNotFoundException:\n sys.__stdout__('Key not found')\n\n\n #Order Dictionary for standard output\n WindowsVersionDict = OrderedDict(sorted(WindowsVersionDict.items(), key=lambda t: t[0]))\n return WindowsVersionDict\n\n except BaseException:\n pass\n\n","sub_path":"afip/imagemetadata.py","file_name":"imagemetadata.py","file_ext":"py","file_size_in_byte":6456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"50182862","text":"# Created byMartin.cz\n# Copyright (c) Martin Strohalm. All rights reserved.\n\nimport math\nfrom . values import *\nfrom . enum import Enum\n\n# define pi\nPI2X = math.pi*2 # 360\nPI = math.pi # 180\nPI2 = math.pi/2 # 90\nPI3 = math.pi/3 # 60\nPI4 = math.pi/4 # 45\nPI6 = math.pi/6 # 30\nPI12 = math.pi/12 # 15\n\n# define angle units\nANGLE_DEG = DEG\nANGLE_RAD = RAD\n\nANGLE = Enum(\n DEG = ANGLE_DEG,\n RAD = ANGLE_RAD)\n\n# define engineering prefixes\nENG_PREFIXES = {\n \"y\": -24,\n \"z\": -21,\n \"a\": -18,\n \"f\": -15,\n \"p\": -12,\n \"n\": -9,\n \"u\": -6,\n \"m\": -3,\n \"\": 0,\n \"k\": 3,\n \"M\": 6,\n \"G\": 9,\n \"T\": 12,\n \"P\": 15,\n \"E\": 18,\n \"Z\": 21,\n \"Y\": 24}\n\n# define rounding\nROUND_CEIL = CEIL\nROUND_FLOOR = FLOOR\nROUND_HALFUP = HALFUP\n\nROUNDING = Enum(\n CEIL = ROUND_CEIL,\n FLOOR = ROUND_FLOOR,\n HALFUP = ROUND_HALFUP)\n\n# define time units\nTIME_DAYS = DAYS\nTIME_HOURS = HOURS\nTIME_MINUTES = MINUTES\nTIME_SECONDS = SECONDS\nTIME_MSECONDS = MSECONDS\nTIME_USECONDS = USECONDS\nTIME_NSECONDS = NSECONDS\n\nTIME = Enum(\n DAYS = TIME_DAYS,\n HOURS = TIME_HOURS,\n MINUTES = TIME_MINUTES,\n SECONDS = TIME_SECONDS,\n MSECONDS = TIME_MSECONDS,\n USECONDS = TIME_USECONDS,\n NSECONDS = TIME_NSECONDS)\n\n# define time conversion factors to seconds\nTIME_FACTORS = {\n TIME_DAYS: 24*60*60,\n TIME_HOURS: 60*60,\n TIME_MINUTES: 60,\n TIME_SECONDS: 1,\n TIME_MSECONDS: 1e-3,\n TIME_USECONDS: 1e-6,\n TIME_NSECONDS: 1e-9}\n","sub_path":"pero/enums/maths.py","file_name":"maths.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"163377826","text":"from django.contrib import admin\nfrom django import forms\nfrom .models import Customer, Order, Products\n\nclass CustomerAdminForm(forms.ModelForm):\n\n class Meta:\n model = Customer\n fields = '__all__'\n\n\nclass CustomerAdmin(admin.ModelAdmin):\n form = CustomerAdminForm\n list_display = ['name', 'email', 'phone']\n readonly_fields = ['name', 'email', 'phone']\n\nadmin.site.register(Customer, CustomerAdmin)\n\n\nclass OrderAdminForm(forms.ModelForm):\n\n class Meta:\n model = Order\n fields = '__all__'\n\n\nclass OrderAdmin(admin.ModelAdmin):\n form = OrderAdminForm\n list_display = ['name', 'created']\n readonly_fields = ['name', 'created']\n\nadmin.site.register(Order, OrderAdmin)\n\n\nclass ProductsAdminForm(forms.ModelForm):\n\n class Meta:\n model = Products\n fields = '__all__'\n\n\nclass ProductsAdmin(admin.ModelAdmin):\n form = ProductsAdminForm\n list_display = ['Category', 'name', 'metal', 'stone']\n readonly_fields = ['Category', 'name', 'metal', 'stone']\n\nadmin.site.register(Products, ProductsAdmin)\n","sub_path":"Magic/shop/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"148454250","text":"\n'''\nCreate a class called Hero.\nUpon initialization it should receive a name (string) and health (number).\nCreate two functions:\n- defend(damage) - Deal the given damage to the hero;\n if the health is 0 or less, set it to 0 and return \"{name} was defeated\".\n- heal(amount) - Increase the health of the hero with the given amount.\n\n'''\n\n\nclass Hero:\n def __init__(self, name, health):\n self.name = name\n self.health = health\n\n def defend(self, damage):\n self.health -= damage\n\n if self.health <= 0:\n self.health = 0\n return f\"{self.name} was defeated\"\n\n def heal(self, amount):\n self.health += amount\n\nhero = Hero(\"Peter\", 100)\nprint(hero.defend(50))\nhero.heal(50)\nprint(hero.defend(99))\nprint(hero.defend(1))\n","sub_path":"3_OOP/01_defining_classes/ex_03_hero.py","file_name":"ex_03_hero.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"258112036","text":"from __future__ import with_statement\n\nimport os\nimport subprocess\n\nfrom flask import current_app\n\nmapping = []\n\n\ndef extend(accept, export):\n def _wrapper(func):\n mapping.append((accept, export, func))\n return func\n return _wrapper\n\n\n@extend(accept=\".css\", export=\".css\")\n@extend(accept=\".js\", export=\".js\")\ndef base(sin, sout, **kw):\n # if you want use the sourcemap\n # you could use `scss --sourcemap` of `coffee -m` to \n # generate the target script file that include the source map tag\n subprocess.call([\"cp\", sin, sout])\n\n\n@extend(accept=\".coffee\", export=\".js\")\ndef coffee(sin, sout, **kw):\n subprocess.call([current_app.config.get(\"COFFEE_BIN\", \"coffee\"), \"-c\", \"-o\", sout, sin])\n\n\n@extend(accept=\".less\", export=\".css\")\ndef less(sin, sout, **kw):\n subprocess.call([current_app.config.get(\"LESS_BIN\", \"lessc\"), sin, sout])\n\n\n@extend(accept=\".scss\", export=\".css\")\ndef scss(sin, sout, **kw):\n subprocess.call([current_app.config.get(\"SCSS_BIN\", \"scss\"), \"--sourcemap\", sin, sout])\n\ndef produce(filepath, relate_filepath=None):\n \"\"\" return processed filepath \"\"\"\n name, postfix = os.path.splitext(filepath)\n if relate_filepath is None:\n # optional relate_filepath\n relate_filedir = os.path.join(current_app.static_folder,\n current_app.config.get('BUNDLES_DIR'),\n \"tmp\")\n if not os.path.exists(relate_filedir):\n os.makedirs(relate_filedir)\n relate_filepath = os.path.join(relate_filedir, name)\n else:\n # remove the postfix\n relate_filepath, _ = os.path.splitext(relate_filepath)\n\n for accept, export, func in mapping:\n if accept == postfix:\n relate_filepath = relate_filepath + export\n source_path = os.path.join(current_app.static_folder, filepath)\n target_path = os.path.join(current_app.static_folder,\n relate_filepath)\n if source_path == target_path:\n # ignore the rewrite original file\n return relate_filepath\n directory_path = os.path.dirname(target_path)\n if not os.path.exists(source_path):\n # if you want ignore it\n #continue\n return relate_filepath\n if not os.path.exists(os.path.dirname(target_path)):\n os.makedirs(os.path.dirname(target_path))\n\n if not os.path.exists(directory_path):\n os.makedirs(directory_path)\n func(source_path, target_path)\n return relate_filepath\n\n raise NotImplementedError(\"did not support the file type of %s\" % filepath)\n","sub_path":"flask_funnel/extends.py","file_name":"extends.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"79203396","text":"import requests\nfrom requests.exceptions import ConnectionError\nfrom django.db.utils import IntegrityError\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom rest_framework import status, filters\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ModelViewSet\nfrom rest_framework.views import APIView\n\nfrom .models import Story, Comment\nfrom .serializers import StorySerializer\n\n# Create your views here.\ntop_stories_url = 'https://hacker-news.firebaseio.com/v0/topstories.json'\nnews = 'https://hacker-news.firebaseio.com/v0/item/{}.json'\n\n\ndef index(request):\n latest_news = Story.objects.order_by('id')[:20]\n output = ', '.join([q.url for q in latest_news])\n return HttpResponse(output)\n\nclass StoryViewSet(ModelViewSet):\n queryset = Story.objects.filter(editable=True)\n serializer_class = StorySerializer\n filter_backends = [filters.SearchFilter]\n search_fields = ['story_type']\n\n def list(self, request):\n queryset = Story.objects.all()\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(queryset, many=True)\n return Response(serializer.data)\n\n def retrieve(self, request, pk):\n story = Story.objects.get(pk=pk)\n return Response(StorySerializer(story).data, status=status.HTTP_200_OK)\n\n\nclass LatestNews(APIView):\n def get(self, request):\n try:\n r = requests.get(top_stories_url)\n if r.status_code == 200:\n top_stories = r.json()\n for item in top_stories[:20]:\n r = requests.get(news.format(item))\n if r.status_code == 200:\n res = r.json()\n try:\n Story.objects.create(\n by=res['by'] if 'by' in res else None,\n descendants=res['descendants'] if 'descendants' in res else None,\n story_id=res['id'],\n kids=res['kids'] if 'kids' in res else None,\n score=res['score'] if 'score' in res else None,\n time=res['time'] if 'time' in res else None,\n title=res['title'] if 'title' in res else None,\n story_type=res['type'],\n url=res['url'] if 'url' in res else None,\n dead=res['dead'] if 'dead' in res else None,\n deleted=res['deleted'] if 'deleted' in res else None,\n editable=False\n )\n except IntegrityError:\n print(\"Story saved already\")\n pass\n else:\n return Response({\n 'status':'success',\n 'message':'Data saved to database'\n }, status=status.HTTP_201_CREATED)\n else:\n return Response({\n 'status':'failed',\n 'message':'Unable to connect to hacker news'\n }, status=status.HTTP_408_REQUEST_TIMEOUT)\n except ConnectionError:\n return Response({\n 'status': 'failed',\n 'message': 'Unable to connect to hacker news'\n }, status=status.HTTP_408_REQUEST_TIMEOUT)","sub_path":"story/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"633853106","text":"from collections import deque\n\n\nclass Solution:\n def totalFruit(self, tree):\n \"\"\"\n :type tree: List[int]\n :rtype: int\n \"\"\"\n n = len(tree)\n\n if n == 1:\n return 1\n\n queue = deque()\n tag_first = 0\n tag_second = 0\n cur_length = 0\n max_length = 0\n\n for index, item in enumerate(tree):\n if index == 0:\n queue.append(tree[index])\n cur_length += 1\n max_length = max(cur_length, max_length)\n continue\n\n if len(queue) == 1:\n if item != queue[0]:\n queue.append(item)\n tag_second = index\n cur_length += 1\n else:\n if item == queue[0]:\n queue.popleft()\n queue.append(item)\n tag_first, tag_second = tag_second, index\n cur_length += 1\n elif item == queue[1]:\n cur_length += 1\n else:\n queue.popleft()\n queue.append(item)\n tag_first, tag_second = tag_second, index\n cur_length = index - tag_first + 1\n max_length = max(cur_length, max_length)\n\n return max_length\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.totalFruit([3,3,3,1,2,1,1,2,3,3,4]))\n","sub_path":"LeetCode(Python)/904. Fruit Into Baskets.py","file_name":"904. Fruit Into Baskets.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"408994853","text":"from fastapi import APIRouter, Request, Depends, Response\nimport typing as t\n\nfrom db.session import get_db\nfrom db.habilidade.crud import (\n get_habilidades,\n create_habilidades,\n get_habilidades_by_id,\n edit_habilidades,\n delete_habilidades,\n get_habilidade_by_name\n)\nfrom db.habilidade.schemas import (\n HabilidadesCreate,\n Habilidades,\n HabilidadesEdit\n)\nfrom core.auth import (\n get_current_active_pessoa,\n get_current_active_superuser,\n)\n\nhabilidades_router = r = APIRouter()\n\n\n@r.get(\n \"/habilidades\",\n response_model=t.List[Habilidades],\n response_model_exclude_none=True,\n)\nasync def habilidades_list(\n response: Response,\n db=Depends(get_db),\n current_pessoa=Depends(get_current_active_pessoa),\n):\n \"\"\"\n Get all habilidades\n \"\"\"\n habilidades = get_habilidades(db)\n # This is necessary for react-admin to work\n response.headers[\"Content-Range\"] = f\"0-9/{len(habilidades)}\"\n return habilidades\n\n\n@r.get(\n \"/habilidades/name/{habilidades_name}\",\n response_model=t.List[Habilidades],\n response_model_exclude_none=True,\n)\nasync def habilidades_details_name(\n request: Request,\n habilidades_name: str,\n db=Depends(get_db),\n current_pessoa=Depends(get_current_active_pessoa),\n):\n \"\"\"\n Get any habilidades details by its name\n \"\"\"\n\n habilidades = get_habilidade_by_name(db, habilidades_name)\n\n return habilidades\n\n\n@r.post(\n \"/habilidades\",\n\n response_model=Habilidades,\n response_model_exclude_none=True,\n)\nasync def habilidades_create(\n request: Request,\n habilidades: HabilidadesCreate,\n db=Depends(get_db),\n):\n \"\"\"\n Create a new habilidades\n \"\"\"\n return create_habilidades(db, habilidades)\n\n@r.put(\n \"/habilidades/{habilidade_id}\",\n response_model=Habilidades,\n response_model_exclude_none=True,\n)\nasync def habilidade_edit(\n request: Request,\n habilidade_id: int,\n habilidades: HabilidadesEdit,\n db=Depends(get_db),\n current_pessoa=Depends(get_current_active_pessoa),\n):\n \"\"\"\n Update existing habilidades\n \"\"\"\n return edit_habilidades(db, habilidade_id, habilidades)\n\n\n@r.delete(\n \"/habilidade/{habilidade_id}\",\n response_model=Habilidades,\n response_model_exclude_none=True,\n)\nasync def habilidade_pessoa_delete(\n request: Request,\n habilidade_id: int,\n db=Depends(get_db),\n current_pessoa=Depends(get_current_active_pessoa),\n):\n \"\"\"\n Delete existing habilidades\n \"\"\"\n return delete_habilidades(db, habilidade_id)\n","sub_path":"{{cookiecutter.project_slug}}/backend/app/api/api_v1/routers/habilidade.py","file_name":"habilidade.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"409082381","text":"import psonic\n\nclapping = [1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0]\n\nfor i in range(13):\n for j in range(4):\n for k in range(12):\n if clapping[k] == 1:\n psonic.sample(psonic.DRUM_SNARE_SOFT,pan=-0.5)\n if clapping[(i+k)%12] == 1:\n psonic.sample(psonic.DRUM_HEAVY_KICK,pan=0.5)\n psonic.sleep(0.25)\n","sub_path":"course-files/lectures/lecture21/03_pip/04_music_demos/rhythm.py","file_name":"rhythm.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"422320631","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom apps.products.models import *\n\ndef index(request):\n products = Product.objects.all()\n context = {\n 'products': products\n }\n return render(request, 'products/index.html', context)\n\ndef purchase(request):\n\n if request.method == 'POST':\n purchase = request.POST\n # Form validation\n errors = Product.objects.validate(purchase)\n if errors:\n for error in errors:\n messages.error(request,error)\n return redirect('products:index')\n else:\n \n # Determine total price and remove the amount purchased from available inventory numbers.\n purchasedItem = Product.objects.get(id=int(purchase['id']))\n purchasedItemPrice = float(purchasedItem.price)\n numPurchase = float(purchase['numPurchase'])\n\n request.session['priceCharged'] = purchasedItemPrice * numPurchase\n \n numAvail = purchasedItem.numAvail\n numAvail -= numPurchase\n purchasedItem.numAvail = numAvail\n purchasedItem.save()\n \n # Create or add to session-stored information of total purchases. This would be more suited to the database if the project were fully developed.\n if 'totalCharged' not in request.session:\n request.session['totalCharged'] = request.session['priceCharged']\n else:\n chargeThisPurchase = request.session['priceCharged']\n totalCharged = request.session['totalCharged']\n totalCharged += chargeThisPurchase\n totalCharged = round(totalCharged, 2)\n request.session['totalCharged'] = totalCharged\n \n # Create or add to total number of items purchased for this session.\n if 'numItemsPurchased' not in request.session:\n request.session['numItemsPurchased'] = int(numPurchase)\n else:\n numItemsPurchased = int(request.session['numItemsPurchased'])\n numItemsPurchased += int(numPurchase)\n request.session['numItemsPurchased'] = numItemsPurchased\n return redirect('products:thankyou')\n else: \n return redirect('products:index')\n\ndef thankyou(request):\n return render(request, 'products/thankyou.html')","sub_path":"Python/Django/amadon/apps/products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"453370412","text":"from selenium.webdriver import Chrome, ChromeOptions\n\n\n# 爬取百度热搜数据\ndef get_hot_search():\n url = 'http://top.baidu.com/buzz?b=341&c=513&fr=topbuzz_b1'\n\n option = ChromeOptions()\n option.add_argument(\"--headless\")\n option.add_argument(\"--no-sandbox\")\n brower = Chrome(options=option)\n brower.get(url)\n title = brower.find_elements_by_xpath('//*[@id=\"main\"]/div[2]/div/table/tbody/tr/td[2]/a[1]')\n\n count = 0\n content = []\n for i in title:\n content.append(i.text)\n count += 1\n if count == 20:\n break\n\n return content\n\n\nif __name__ == '__main__':\n get_hot_search()\n","sub_path":"get_data/get_hot_search.py","file_name":"get_hot_search.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"104032903","text":"\"\"\"CIM binary encoding functions.\n\n\"\"\"\n\n# Module imports.\nimport base64\n\nfrom pycim.core.cim_exception import CIMException\nfrom pycim.cim_constants import CIM_SCHEMAS\nfrom pycim.core.encoding.cim_encoder_binary import encode as encode_to_binary\n\n# Module exports.\n__all__ = ['encode']\n\n\n# Module provenance info.\n__author__=\"markmorgan\"\n__copyright__ = \"Copyright 2010, Insitut Pierre Simon Laplace - Prodiguer\"\n__date__ =\"$Jun 28, 2010 2:52:22 PM$\"\n__license__ = \"GPL\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Sebastien Denvil\"\n__email__ = \"sdipsl@ipsl.jussieu.fr\"\n__status__ = \"Production\"\n\n\ndef encode(instance, version):\n \"\"\"Encodes a binary representation of passed CIM instance.\n\n Keyword arguments:\n instance -- instance of a CIM type.\n version -- cim version that instance conforms to.\n\n \"\"\"\n # Defensive programming.\n if instance is None:\n raise CIMException('Cannot encode null instances.')\n if version not in CIM_SCHEMAS:\n raise CIMException('{0} is an unsupported CIM version.'.format(version))\n\n as_binary = encode_to_binary(instance, version)\n return base64.b64encode(as_binary)\n","sub_path":"pycim/core/encoding/cim_encoder_base64.py","file_name":"cim_encoder_base64.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"483124339","text":"import os\nos.system(\"cls\") #limpa janela terminal antes da execução\n\nwhile True:\n num = int(input(\"Digite um número para ver a sua tabuada: \"))\n\n if num < 0:\n break\n\n print(\"-\" * 12)\n for c in range(1,11):\n print(f'{num} x {c:2} = {num*c}')\n print(\"-\" * 12)\n\nprint(\"PROGRAMA TABUADA ENCERRADO! Volte sempre!\")","sub_path":"ex067.py","file_name":"ex067.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"266283076","text":"import cv2\nimport numpy as np \n\n\nmax_distance_between_points = 30\n\ndef euclidean_distance(detection, tracked_object):\n return np.linalg.norm(detection.points - tracked_object.estimate)\n\ndef draw_border(img, box, line_length = 15):\n\n x1, y1 = box[0], box[1]\n x2, y2 = box[0], box[3]\n x3, y3 = box[2], box[1]\n x4, y4 = box[2], box[3] \n \n cv2.line(img, (x1, y1), (x1 , y1 + line_length), (127, 0, 127), 5) #-- top-left\n cv2.line(img, (x1, y1), (x1 + line_length , y1), (127, 0, 127), 5)\n\n cv2.line(img, (x2, y2), (x2 , y2 - line_length), (127, 0, 127), 5) #-- bottom-left\n cv2.line(img, (x2, y2), (x2 + line_length , y2), (127, 0, 127), 5)\n\n cv2.line(img, (x3, y3), (x3 - line_length, y3), (127, 0, 127), 5) #-- top-right\n cv2.line(img, (x3, y3), (x3, y3 + line_length), (127, 0, 127), 5)\n\n cv2.line(img, (x4, y4), (x4 , y4 - line_length), (127, 0, 127), 5) #-- bottom-right\n cv2.line(img, (x4, y4), (x4 - line_length , y4), (127, 0, 127), 5)\n\n sub_img = img[box[1]: box[3], box[0]: box[2], :]\n white_rect = np.zeros(sub_img.shape, dtype=np.uint8) + 255\n res = cv2.addWeighted(sub_img, 0.7, white_rect, 0.3, 1.0)\n img[box[1]: box[3], box[0]: box[2], :] = res\n return img\n\ndef get_center(bbox):\n x1 = bbox[0]\n y1 = bbox[1]\n x2 = bbox[2]\n y2 = bbox[3]\n return np.array([(x1 + x2) / 2, (y1 + y2) / 2])\n\ndef get_centroid(yolo_box, img_height, img_width):\n x1 = yolo_box[0] * img_width\n y1 = yolo_box[1] * img_height\n x2 = yolo_box[2] * img_width\n y2 = yolo_box[3] * img_height\n return np.array([(x1 + x2) / 2, (y1 + y2) / 2])","sub_path":"threads/process_track.py","file_name":"process_track.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"68787580","text":"import csv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef haar_transform(x, n):\n y = []\n for i in range(0, int((n/2)-1)):\n y.append((x[2*i] + x[(2*i) + 1]) / 2)\n\n return y\n\n\ndef non_linear_quantization(a):\n if (abs(a) < 0.05):\n return_value = 0\n elif (abs(a) < 1.0):\n if (a > 0.0):\n return_value = (int((a + 0.1) * 10))\n else:\n return_value = (int((a - 0.1) * 10))\n elif ((a > 0.0)):\n if (abs(a) < 1.2):\n return_value = 11\n elif (abs(a) < 1.4):\n return_value = 12\n elif (abs(a) < 1.6):\n return_value = 13\n elif (abs(a) < 1.8):\n return_value = 14\n elif (abs(a) < 2.0):\n return_value = 15\n else:\n return_value = 16\n else:\n if (abs(a) < 1.2):\n return_value = -11\n elif (abs(a) < 1.4):\n return_value = -12\n elif (abs(a) < 1.6):\n return_value = -13\n elif (abs(a) < 1.8):\n return_value = -14\n elif (abs(a) < 2.0):\n return_value = -15\n else:\n return_value = -16\n\n return return_value\n\nresults = []\nwith open(\"left_arrow_2.csv\") as csvfile:\n reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC) # change contents to floats\n for row in reader: # each row is a list\n results.append(row)\n\nX_raw = np.zeros((1, 384))\nfor i in range(0, 128):\n X_raw[0][i%128] = results[i][0]\n X_raw[0][128 + (i%128)] = results[i][1]\n X_raw[0][256 + (i%128)] = results[i][2]\n\n\n\nX = np.zeros((1, 93))\nx_haar_1 = haar_transform(X_raw[0][0:128], 128)\nX[0][0:31] = haar_transform(x_haar_1, 64)\n\ny_haar_1 = haar_transform(X_raw[0][128:256], 128)\nX[0][31:62] = haar_transform(y_haar_1, 64)\n\nz_haar_1 = haar_transform(X_raw[0][256:384], 128)\nX[0][62:93] = haar_transform(z_haar_1, 64)\n\nX_q = np.zeros((1, 93))\nfor i in range(0, 93):\n X_q[0][i] = non_linear_quantization(X[0][i])\n\nplt.plot(range(1, 32), X_q[0][0:31], label=\"X\")\nplt.plot(range(1, 32), X_q[0][31:62], label=\"Y\")\nplt.plot(range(1, 32), X_q[0][62:93], label=\"Z\")\nplt.legend()\nplt.show()\n\n\n\nfor i in range(0, 31):\n #print(\"{\" + str(int(results[i][0])) + \", \" + str(int(results[i][1])) + \", \" + str(int(results[i][2])) + \"},\")\n print(\"{\" + str(int(X_q[0][i])) + \", \" + str(int(X_q[0][i + 31])) + \", \" + str(int(X_q[0][i + 62])) + \"},\")\n\n\n\n'''\nfor i in range(len(results)):\n #print(\"{\" + str(int(results[i][0])) + \", \" + str(int(results[i][1])) + \", \" + str(int(results[i][2])) + \"},\")\n print(\"{\" + str(non_linear_quantization(results[i][0])) + \", \" + str(non_linear_quantization(results[i][1])) + \", \" + str(non_linear_quantization(results[i][2])) + \"},\")\n'''\n","sub_path":"Dynamic Time Warping/Training Data/DTW_Converter.py","file_name":"DTW_Converter.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"17234964","text":"import sys\ncount0 = 0\ncount1 = 0\ndef fibonacci(n):\n global count0\n global count1\n if n == 0:\n count0 += 1\n return 0\n elif n == 1:\n count1 += 1\n return 1\n else:\n return fibonacci(n-1) + fibonacci(n-2)\nT = int(sys.stdin.readline().rstrip())\ni = 0\nwhile i < T:\n a = int(sys.stdin.readline().rstrip())\n if 0 <= a <= 40:\n fibonacci(a)\n print(\"{0} {1}\".format(count0, count1))\n count0 = 0\n count1 = 0\n i += 1","sub_path":"baekjoon/_1003.py","file_name":"_1003.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"284833553","text":"from selenium import webdriver\nfrom bs4 import BeautifulSoup\ndriver = webdriver.Chrome('chromedriver')\nurl = 'https://www.amazon.com/Samsung-Chromebook-Plus-Camera-Chrome/product-reviews/B07J1SY5QQ/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber='\ndriver.get(url)\nall_user = []\nall_star = []\nall_date = []\nall_review = []\npage = driver.page_source\nsoup = BeautifulSoup(page,'html.parser')\nreviews = soup.select('#cm_cr-review_list > div')\nfor review in reviews:\n try:\n iname=review.select_one('div.a-profile-content > span').text\n istar=review.select_one('div:nth-child(2) > a:nth-child(1) > i > span').text\n idate=review.select_one('span.a-size-base').text\n iview=review.select_one('span.a-size-base > span').text\n all_user.append(iname)\n all_star.append(istar)\n all_date.append(idate)\n all_review.append(iview)\n print(iname,istar)\n except Exception as e:\n continue","sub_path":"week3/21day/01_21-1.py","file_name":"01_21-1.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"448470930","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# boj 14226 이모티콘\n\nimport sys\ninput = sys.stdin.readline\n\nn = int(input().strip())\nclipboard = 1\ncnt = 2\nresult = 0\ndp = [0 for _ in range(n + 1)]\ndp[2] = 2\n\nif n % 2 == 0:\n while cnt == n // 2:\n dp[cnt]\n cnt += 1\n\nwhile cnt != n:\n\n # 기존 클립보드 붙여넣기\n if dp[cnt] + clipboard == n:\n result += 1\n cnt += clipboard\n dp[cnt] += clipboard\n continue\n\n # 복사 후 + 붙여넣기\n if dp[cnt] + clipboard < n:\n clipboard = dp[cnt] # 클립보드 덮어쓰기 (복사 수행)\n cnt += clipboard # 붙여넣기 수행\n result += 2 # 연산 시간 더하기 (복사 + 붙여넣기 = 2초)\n dp[cnt] = result\n continue\n\nprint(result)","sub_path":"boj_14226.py","file_name":"boj_14226.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"414514423","text":"# os imports\nimport os\n\n# timestamp\nimport time\nimport datetime\n\n# open url\nimport webbrowser\n\n# encryption\nimport hmac\nimport hashlib\nimport base64\nfrom Crypto.Hash import SHA256 as sha256\n\nfrom settings import AWS_ACCESS_KEY_ID, AWS_ASSOCIATE_TAG, AWS_SECRET_ACCESS_KEY\n\nkey = AWS_ACCESS_KEY_ID\nsecret = AWS_SECRET_ACCESS_KEY\ntag = AWS_ASSOCIATE_TAG\n\n###################################\n# 1. Define Constants and audibles#\n###################################\n\nservice = \"AWSECommerceService\"\nAWS_ACCESS_KEY_ID= key\nAWS_SECRET_KEY= secret\nASSOCIATE_TAG = tag\noperation = \"ItemSearch\"\nbrand = \"Coleman\"\n# MY VERSION response = \"Images%2CItemAttributes%2COffers\"\nresponse = \"Images%2CItemAttributes%2COffers\"\nversion = \"2013-08-01\"\nservice = \"AWSECommerceService\"\n\n# base url\nbase_url = \"webservices.amazon.com/onca/xml?\"\n\n# Prepare for encoding parameter string\nhttp_prefix = \"http://\"\ncomma =\"%2C\"\ncolon= \"%3A\"\n\n# generate time stamp, format utc iso... YOU HAVE 20 MICROSECONDS TO GET THIS THING GOING\ntime_stamp = datetime.datetime.utcnow().isoformat()\n\n##########################\n# 2. Build our parameters#\n##########################\n\n# # # # ORDER OF THINGS\n# 1. AWS_ACCESS_KEY_ID\n# 2. AssociateTag\n# 3. IdType=ASIN\n# 4. ItemId=B071V82JJG\n# 5. Operation=ItemLookup\n# 6. ResponseGroup=\n# 7. Service=AWSECommerceService\n# 8. Timestamp=2017-10-06T02%3A42%3A53.000Z\n# 9. Signature=EfLYYlVHWqxaZZjC0HX%2FFraOB4bHKYjk8%2FkJXi1IESM%3D\n\nkey_param = \"AWS_ACCESS_KEY_ID={}\".format(AWS_ACCESS_KEY_ID)\nassociate_param = \"AssociateTag={}\".format(ASSOCIATE_TAG)\nbrand_param = \"Brand={}\".format(brand)\noperation_param = \"Operation={}\".format(operation)\nresponse_param = \"ResponseGroup={}\".format(response)\nservice_param = \"Service={}\".format(service)\ntime_stamp_param = \"Timestamp={}\".format(time_stamp)\nversion_param = \"Version={}\".format(version)\n\n#################################\n# 3. Assemble/Format our Request#\n#################################\n\n# Format parameter string\nparams = [key_param, associate_param, brand_param, operation_param, response_param, service_param, time_stamp_param, version_param]\nparams_string = \"&\".join(params)\n\n# Build GET REQUEST\nurl = base_url + params_string\n\n# Encode commas and colons\nencoded_commas = url.replace(\",\", comma)\nencoded_colons = encoded_commas.replace(\":\", colon)\n\n# Stage GET request for encryption\ndig_string = \"GET\\nwebservices.amazon.com\\n/onca/xml\\n\" + \"AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE&AssociateTag=mytag-20&ItemId=0679722769&Operation=ItemLookup&ResponseGroup=Images%2CItemAttributes%2COffers%2CReviews&Service=AWSECommerceService&Timestamp=2014-08-18T12%3A00%3A00Z&Version=2013-08-01\"\n\n# Encode request\ndig_string_encoded = dig_string.encode('utf-8')\n\n# Encrypt request\ndig = hmac.new(b'+DwXFtp4/KFpAFe/2FeGfMv0Rn4kim4/vNzawe36', msg=dig_string_encoded, digestmod=hashlib.sha256).digest()\n\nsignature = quote(\n b64encode(hmac.new(AWS_SECRET_KEY, dig_string, sha256).digest()))\n\nprint(signature)\n\n\n# This doesn't work unless I decode it,,, but I just encoded it.. wtf\nhash_string = base64.b64encode(dig).decode()\n\n# Stage for hash encoding\nplus = \"%2B\"\nequal_sign = \"%3D\"\n\n# Encode Hash\nhash_string_plus = hash_string.replace(\"+\", plus)\nhash_string = hash_string_plus.replace(\"=\", equal_sign)\n\n# Stage final URL\nfinal_url = http_prefix + encoded_colons + \"&Signature=\" + hash_string\n\n# Check your work\nprint(final_url)\n# Send your request\nwebbrowser.open(final_url)\n","sub_path":"services/amazon_product_api.py","file_name":"amazon_product_api.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"593451747","text":"# coding: utf-8\n\n\"\"\"\nModel field definitions\n\"\"\"\n\nfrom autoslug import AutoSlugField as BaseSlugField\n\n\nclass AutoSlugField(BaseSlugField):\n \"\"\"\n Redefined AutoSlugField with defaults selected\n\n - unique: True\n \"\"\"\n def __init__(self, *args, **kwargs):\n if \"unique\" not in kwargs and \"unique_with\" not in kwargs:\n kwargs[\"unique\"] = True\n super(AutoSlugField, self).__init__(*args, **kwargs)\n","sub_path":"bookmark/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"399297046","text":"from __future__ import print_function, division, absolute_import\n\nimport json\nimport sys\n\nfrom tornado.ioloop import IOLoop\nfrom tornado import web, gen\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.httpserver import HTTPServer\n\nfrom distributed import Scheduler, Executor\nfrom distributed.executor import _wait\nfrom distributed.sizeof import getsizeof\nfrom distributed.utils_test import gen_cluster, gen_test, inc, div\nfrom distributed.http.scheduler import HTTPScheduler\nfrom distributed.http.worker import HTTPWorker\n\n\n@gen_cluster()\ndef test_simple(s, a, b):\n server = HTTPScheduler(s)\n server.listen(0)\n client = AsyncHTTPClient()\n\n response = yield client.fetch('http://localhost:%d/info.json' % server.port)\n response = json.loads(response.body.decode())\n assert response == {'ncores': s.ncores,\n 'status': s.status}\n\n server.stop()\n\n\n@gen_cluster()\ndef test_processing(s, a, b):\n server = HTTPScheduler(s)\n server.listen(0)\n client = AsyncHTTPClient()\n\n s.processing[a.address][('foo-1', 1)] = 1\n\n response = yield client.fetch('http://localhost:%d/processing.json' % server.port)\n response = json.loads(response.body.decode())\n assert response == {a.address: ['foo'], b.address: []}\n\n server.stop()\n\n\n@gen_cluster()\ndef test_proxy(s, a, b):\n server = HTTPScheduler(s)\n server.listen(0)\n worker = HTTPWorker(a)\n worker.listen(0)\n client = AsyncHTTPClient()\n\n c_response = yield client.fetch('http://localhost:%d/info.json' % worker.port)\n s_response = yield client.fetch('http://localhost:%d/proxy/%s:%d/info.json'\n % (server.port, a.ip, worker.port))\n assert s_response.body.decode() == c_response.body.decode()\n server.stop()\n worker.stop()\n\n\n@gen_cluster()\ndef test_broadcast(s, a, b):\n ss = HTTPScheduler(s)\n ss.listen(0)\n s.services['http'] = ss\n\n aa = HTTPWorker(a)\n aa.listen(0)\n a.services['http'] = aa\n a.service_ports['http'] = aa.port\n s.worker_info[a.address]['services']['http'] = aa.port\n\n bb = HTTPWorker(b)\n bb.listen(0)\n b.services['http'] = bb\n b.service_ports['http'] = bb.port\n s.worker_info[b.address]['services']['http'] = bb.port\n\n client = AsyncHTTPClient()\n\n a_response = yield client.fetch('http://localhost:%d/info.json' % aa.port)\n b_response = yield client.fetch('http://localhost:%d/info.json' % bb.port)\n s_response = yield client.fetch('http://localhost:%d/broadcast/info.json'\n % ss.port)\n assert (json.loads(s_response.body.decode()) ==\n {a.address: json.loads(a_response.body.decode()),\n b.address: json.loads(b_response.body.decode())})\n\n ss.stop()\n aa.stop()\n bb.stop()\n\n\n@gen_test()\ndef test_services():\n s = Scheduler(services={'http': HTTPScheduler})\n assert isinstance(s.services['http'], HTTPServer)\n assert s.services['http'].port\n\n\n@gen_test()\ndef test_services_with_port():\n s = Scheduler(services={('http', 9999): HTTPScheduler})\n assert isinstance(s.services['http'], HTTPServer)\n assert s.services['http'].port == 9999\n\n\n@gen_cluster(executor=True)\ndef test_with_data(e, s, a, b):\n ss = HTTPScheduler(s)\n ss.listen(0)\n\n L = e.map(inc, [1, 2, 3])\n L2 = yield e._scatter(['Hello', 'world!'])\n yield _wait(L)\n\n client = AsyncHTTPClient()\n response = yield client.fetch('http://localhost:%d/memory-load.json' %\n ss.port)\n out = json.loads(response.body.decode())\n\n assert all(isinstance(v, int) for v in out.values())\n assert set(out) == {a.address, b.address}\n assert sum(out.values()) == sum(map(getsizeof,\n [1, 2, 3, 'Hello', 'world!']))\n\n response = yield client.fetch('http://localhost:%s/memory-load-by-key.json'\n % ss.port)\n out = json.loads(response.body.decode())\n assert set(out) == {a.address, b.address}\n assert all(isinstance(v, dict) for v in out.values())\n assert all(k in {'inc', 'data'} for d in out.values() for k in d)\n assert all(isinstance(v, int) for d in out.values() for v in d.values())\n\n assert sum(v for d in out.values() for v in d.values()) == \\\n sum(map(getsizeof, [1, 2, 3, 'Hello', 'world!']))\n\n ss.stop()\n\n\n@gen_cluster(executor=True)\ndef test_with_status(e, s, a, b):\n ss = HTTPScheduler(s)\n ss.listen(0)\n\n client = AsyncHTTPClient()\n response = yield client.fetch('http://localhost:%d/tasks.json' %\n ss.port)\n out = json.loads(response.body.decode())\n assert out['total'] == 0\n assert out['processing'] == 0\n assert out['failed'] == 0\n assert out['in-memory'] == 0\n assert out['ready'] == 0\n assert out['waiting'] == 0\n\n L = e.map(div, range(10), range(10))\n yield _wait(L)\n\n client = AsyncHTTPClient()\n response = yield client.fetch('http://localhost:%d/tasks.json' %\n ss.port)\n out = json.loads(response.body.decode())\n assert out['failed'] == 1\n assert out['in-memory'] == 9\n assert out['ready'] == 0\n assert out['total'] == 10\n assert out['waiting'] == 0\n\n ss.stop()\n\n\n\n@gen_cluster(executor=True)\ndef test_basic(e, s, a, b):\n ss = HTTPScheduler(s)\n ss.listen(0)\n\n client = AsyncHTTPClient()\n for name in ['tasks', 'workers']:\n response = yield client.fetch('http://localhost:%d/%s.json' %\n (ss.port, name))\n data = json.loads(response.body.decode())\n assert isinstance(data, dict)\n","sub_path":"distributed/http/tests/test_scheduler_http.py","file_name":"test_scheduler_http.py","file_ext":"py","file_size_in_byte":5634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"287401382","text":"import sys\nimport pdb\nimport functools\nimport traceback\nimport unittest\nimport json\nimport itertools\nfrom collections import defaultdict\n\nimport pygly2\nfrom pygly2.structure import constants, substituent, glycan, monosaccharide\nfrom pygly2.structure import link, named_structures, structure_composition\nfrom pygly2.structure import crossring_fragments\nfrom pygly2.io import glycoct, linear_code\nfrom pygly2.io.nomenclature import identity, synonyms\nfrom pygly2.utils import StringIO, identity as ident_op, multimap, pickle, ET, enum\nfrom pygly2.composition import Composition, composition_transform\nfrom pygly2.algorithms import subtree_search\nfrom pygly2.algorithms import similarity\n\nfrom common import emit, load\n\nReducedEnd = monosaccharide.ReducedEnd\nSubstituent = pygly2.Substituent\nGlycan = glycan.Glycan\n\ndef debug_on(*exceptions):\n if not exceptions:\n exceptions = (AssertionError, )\n\n def decorator(f):\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n try:\n return f(*args, **kwargs)\n except exceptions:\n info = sys.exc_info()\n traceback.print_exception(*info)\n pdb.post_mortem(info[2])\n return wrapper\n return decorator\nmonosaccharides = named_structures.monosaccharides\nglycans = named_structures.glycans\n\n# monosaccharide_masses = json.load(open(\"./test_data/monosaccharide_masses.json\"))\nmonosaccharide_structures = json.load(\n open(\"./pygly2/structure/data/monosaccharides.json\"))\n\nwiki_masses = {\n \"Iduronic Acid\": 194.04,\n \"Bacillosamine\": 162.10,\n \"Allose\": 180.06,\n}\n\n#: Not common in any way other than\n#: reused in many tests\ncommon_glycan = '''\nRES\n1b:b-dglc-HEX-1:5\n2b:b-dgal-HEX-1:5\n3b:b-dglc-HEX-1:5\n4s:n-acetyl\n5b:a-lgal-HEX-1:5|6:d\n6b:b-dgal-HEX-1:5\n7b:b-dglc-HEX-1:5\n8s:n-acetyl\n9b:a-lgal-HEX-1:5|6:d\n10b:b-dgal-HEX-1:5\nLIN\n1:1o(4+1)2d\n2:2o(3+1)3d\n3:3d(2+1)4n\n4:3o(3+1)5d\n5:3o(4+1)6d\n6:6o(3+1)7d\n7:7d(2+1)8n\n8:7o(3+1)9d\n9:7o(4+1)10d'''\n\nbranchy_glycan = '''\nRES\n1b:x-dglc-HEX-x:x\n2s:n-acetyl\n3b:b-dman-HEX-1:5\n4b:a-dman-HEX-1:5\n5b:b-dglc-HEX-1:5\n6s:n-acetyl\n7b:b-dgal-HEX-1:5\n8b:b-dglc-HEX-1:5\n9s:n-acetyl\n10b:b-dgal-HEX-1:5\n11b:a-dman-HEX-1:5\n12b:b-dglc-HEX-1:5\n13s:n-acetyl\n14b:b-dgal-HEX-1:5\nLIN\n1:1d(2+1)2n\n2:1o(4+1)3d\n3:3o(3+1)11d\n4:3o(6+1)4d\n5:4o(2+1)8d\n6:4o(6+1)5d\n7:5d(2+1)6n\n8:5o(4+1)7d\n9:8d(2+1)9n\n10:8o(4+1)10d\n11:11o(2+1)12d\n12:12d(2+1)13n\n13:12o(4+1)14d'''\n\nbroad_n_glycan = '''\nRES\n1b:b-dglc-HEX-1:5\n2s:n-acetyl\n3b:b-dglc-HEX-1:5\n4s:n-acetyl\n5b:b-dman-HEX-1:5\n6b:a-dman-HEX-1:5\n7b:b-dglc-HEX-1:5\n8s:n-acetyl\n9b:b-dgal-HEX-1:5\n10b:a-lgal-HEX-1:5|6:d\n11b:b-dglc-HEX-1:5\n12s:n-acetyl\n13b:b-dgal-HEX-1:5\n14b:a-dman-HEX-1:5\n15b:b-dglc-HEX-1:5\n16s:n-acetyl\n17b:b-dgal-HEX-1:5\n18b:b-dglc-HEX-1:5\n19s:n-acetyl\n20b:b-dgal-HEX-1:5\nLIN\n1:1d(2+1)2n\n2:1o(4+1)3d\n3:3d(2+1)4n\n4:3o(4+1)5d\n5:5o(3+1)14d\n6:5o(6+1)6d\n7:6o(2+1)11d\n8:6o(6+1)7d\n9:7d(2+1)8n\n10:7o(3+1)10d\n11:7o(4+1)9d\n12:11d(2+1)12n\n13:11o(4+1)13d\n14:14o(2+1)18d\n15:14o(4+1)15d\n16:15d(2+1)16n\n17:15o(4+1)17d\n18:18d(2+1)19n\n19:18o(4+1)20d'''\n\nsulfated_glycan = '''\nRES\n1b:o-dgal-HEX-0:0|1:aldi\n2b:b-dglc-HEX-1:5\n3s:n-acetyl\n4b:b-dgal-HEX-1:5\n5b:b-dglc-HEX-1:5\n6s:n-acetyl\n7b:b-dgal-HEX-1:5\n8b:a-dgro-dgal-NON-2:6|1:a|2:keto|3:d\n9s:n-acetyl\n10s:sulfate\n11s:sulfate\n12s:sulfate\nLIN\n1:1o(3+1)2d\n2:2d(2+1)3n\n3:2o(4+1)4d\n4:4o(3+1)5d\n5:5d(2+1)6n\n6:5o(4+1)7d\n7:7o(6+2)8d\n8:8d(5+1)9n\n9:5o(6+1)10n\n10:4o(6+1)11n\n11:2o(6+1)12n\n'''\n\ncomplex_glycan = '''\nRES\n1b:x-dglc-HEX-1:5\n2s:n-acetyl\n3b:b-dglc-HEX-1:5\n4s:n-acetyl\n5b:b-dman-HEX-1:5\n6b:a-dman-HEX-1:5\n7b:b-dglc-HEX-1:5\n8s:n-acetyl\n9b:a-lgal-HEX-1:5|6:d\n10b:b-dgal-HEX-1:5\n11b:a-dgro-dgal-NON-2:6|1:a|2:keto|3:d\n12s:n-glycolyl\n13b:b-dglc-HEX-1:5\n14s:n-acetyl\n15b:b-dgal-HEX-1:5\n16s:n-acetyl\n17b:b-dglc-HEX-1:5\n18s:n-acetyl\n19b:a-dman-HEX-1:5\n20b:b-dglc-HEX-1:5\n21s:n-acetyl\n22b:a-lgal-HEX-1:5|6:d\n23b:b-dgal-HEX-1:5\n24b:a-dgro-dgal-NON-2:6|1:a|2:keto|3:d\n25s:n-glycolyl\n26b:b-dglc-HEX-1:5\n27s:n-acetyl\n28b:a-lgal-HEX-1:5|6:d\n29b:b-dgal-HEX-1:5\n30b:a-dgro-dgal-NON-2:6|1:a|2:keto|3:d\n31s:n-acetyl\n32b:a-lgal-HEX-1:5|6:d\nLIN\n1:1d(2+1)2n\n2:1o(4+1)3d\n3:3d(2+1)4n\n4:3o(4+1)5d\n5:5o(3+1)6d\n6:6o(2+1)7d\n7:7d(2+1)8n\n8:7o(3+1)9d\n9:7o(4+1)10d\n10:10o(3+2)11d\n11:11d(5+1)12n\n12:6o(4+1)13d\n13:13d(2+1)14n\n14:13o(4+1)15d\n15:15d(2+1)16n\n16:5o(4+1)17d\n17:17d(2+1)18n\n18:5o(6+1)19d\n19:19o(2+1)20d\n20:20d(2+1)21n\n21:20o(3+1)22d\n22:20o(4+1)23d\n23:23o(3+2)24d\n24:24d(5+1)25n\n25:19o(6+1)26d\n26:26d(2+1)27n\n27:26o(3+1)28d\n28:26o(4+1)29d\n29:29o(3+2)30d\n30:30d(5+1)31n\n31:1o(6+1)32d\n'''\n\n\nclass GlycoCTParserTests(unittest.TestCase):\n _file_path = \"./test_data/glycoct.txt\"\n\n def test_parse_file(self):\n for g in glycoct.read(self._file_path):\n self.assertTrue(isinstance(g, glycan.Glycan))\n\n\nclass NamedStructureTests(unittest.TestCase):\n\n def test_accessors(self):\n self.assertEqual(named_structures.monosaccharides.Fucose,\n named_structures.monosaccharides[\"Fucose\"])\n self.assertNotEqual(named_structures.monosaccharides.Man,\n named_structures.monosaccharides.Hex)\n self.assertEqual(named_structures.glycans[\"N-Linked Core\"],\n named_structures.glycans[\"N-Linked Core\"])\n\n\nclass StructureCompositionTests(unittest.TestCase):\n\n def test_missing_composition(self):\n import warnings\n warnings.filterwarnings('ignore')\n self.assertEqual(\n {}, structure_composition.monosaccharide_composition['hexadodecose'])\n warnings.filterwarnings('always')\n\n\nclass MonosaccharideTests(unittest.TestCase):\n _file_path = \"./test_data/glycoct.txt\"\n glycan = iter(glycoct.read(_file_path)).next()\n\n def test_from_glycoct(self):\n s = self.glycan.root.to_glycoct()\n b = StringIO(s)\n g = iter(glycoct.read(b)).next()\n self.assertEqual(g.root.to_glycoct(), s)\n\n def test_named_structure_masses(self):\n for name, mass in wiki_masses.items():\n structure = named_structures.monosaccharides[name]\n self.assertAlmostEqual(mass, structure.mass(), 2)\n\n def test_named_structure_glycoct(self):\n for name, glycoct_str in monosaccharide_structures.items():\n structure = named_structures.monosaccharides[name]\n test, ref = (structure.to_glycoct(), glycoct_str)\n i = 0\n for j, k in zip(test, ref):\n if j != k:\n test_loc = test.replace('\\n', ' ')[i - 10:i + 10]\n ref_loc = ref.replace('\\n', ' ')[i - 10:i + 10]\n raise AssertionError(\n \"{j} != {k} at {i} in {name}\\n{test_loc}\\n{ref_loc}\".format(**locals()))\n i += 1\n\n def test_ring_limit_modification(self):\n structure = named_structures.monosaccharides['Hex']\n self.assertRaises(\n IndexError, lambda: structure.add_modification('d', 8))\n\n def test_occupancy_limit_modification(self):\n structure = named_structures.monosaccharides['Hex']\n structure.add_modification('d', 4)\n self.assertRaises(\n ValueError, lambda: structure.add_modification('d', 4))\n\n def test_ring_limit_substituent(self):\n structure = named_structures.monosaccharides['Hex']\n self.assertRaises(\n IndexError, lambda: structure.add_substituent('methyl', 8))\n\n def test_occupancy_limit_substituent(self):\n structure = named_structures.monosaccharides['Hex']\n structure.add_substituent('methyl', 4)\n self.assertRaises(\n ValueError, lambda: structure.add_substituent('methyl', 4))\n\n def test_add_remove_modifcations(self):\n for name, mass in wiki_masses.items():\n structure = named_structures.monosaccharides[name]\n ref = structure.clone()\n self.assertAlmostEqual(ref.mass(), structure.mass())\n open_sites, unknowns = structure.open_attachment_sites()\n n_sites = len(open_sites)\n comp_delta = n_sites * \\\n structure_composition.modification_compositions[\n constants.Modification.d]()\n for site in open_sites:\n structure.add_modification(constants.Modification.d, site)\n self.assertEqual(\n structure.total_composition(), ref.total_composition() + comp_delta)\n self.assertEqual([], structure.open_attachment_sites()[0])\n for site in open_sites:\n structure.drop_modification(site, constants.Modification.d)\n self.assertEqual(\n structure.total_composition(), ref.total_composition())\n\n def test_add_remove_substituents(self):\n for name, mass in wiki_masses.items():\n structure = named_structures.monosaccharides[name]\n ref = structure.clone()\n self.assertAlmostEqual(ref.mass(), structure.mass())\n open_sites, unknowns = structure.open_attachment_sites()\n n_sites = len(open_sites)\n mass_delta = substituent.Substituent(\n 'methyl').mass() * n_sites - Composition(\"H2\").mass * n_sites\n ping = True\n for site in open_sites:\n if ping:\n structure.add_substituent(\n substituent.Substituent('methyl'), position=site)\n ping = False\n else:\n structure.add_substituent('methyl', position=site)\n ping = True\n self.assertAlmostEqual(structure.mass(), ref.mass() + mass_delta)\n for site in open_sites:\n structure.drop_substituent(\n site, substituent.Substituent('methyl'))\n self.assertAlmostEqual(structure.mass(), ref.mass())\n\n def test_validate_drop_substituents(self):\n structure = named_structures.monosaccharides['Hex']\n self.assertRaises(IndexError, lambda: structure.drop_substituent(99))\n self.assertRaises(IndexError, lambda: structure.drop_substituent(4))\n self.assertRaises(IndexError, lambda: structure.add_substituent(\n \"n-acetyl\", 3, max_occupancy=4).add_substituent(\n \"methyl\", 3, max_occupancy=4).drop_substituent(3, \"n-glycolyl\"))\n\n def test_add_remove_monosaccharides(self):\n for name, mass in wiki_masses.items():\n structure = named_structures.monosaccharides[name]\n ref = structure.clone()\n self.assertAlmostEqual(ref.mass(), glycan.Glycan(structure).mass())\n open_sites, unknowns = structure.open_attachment_sites()\n n_sites = len(open_sites)\n mass_delta = named_structures.monosaccharides[\n \"Hex\"].mass() * n_sites - Composition(\"H2O\").mass * n_sites\n for site in open_sites:\n structure.add_monosaccharide(\n named_structures.monosaccharides[\"Hex\"], position=site, child_position=3)\n self.assertAlmostEqual(\n glycan.Glycan(structure).mass(), ref.mass() + mass_delta)\n for site in open_sites:\n structure.drop_monosaccharide(site)\n self.assertAlmostEqual(glycan.Glycan(structure).mass(), ref.mass())\n\n def test_validate_drop_monosacharide(self):\n structure = named_structures.monosaccharides['Hex']\n self.assertRaises(\n IndexError, lambda: structure.drop_monosaccharide(99))\n self.assertRaises(ValueError, lambda: structure.drop_monosaccharide(4))\n self.assertRaises(ValueError, lambda: structure.add_monosaccharide(\n named_structures.monosaccharides[\"Hex\"], 3, max_occupancy=4).add_monosaccharide(\n named_structures.monosaccharides[\"Hex\"], 3, max_occupancy=4).drop_monosaccharide(3))\n\n def test_validate_enums(self):\n structure = named_structures.monosaccharides['Hex']\n\n def t():\n structure.anomer = 5\n self.assertRaises(KeyError, t)\n\n def t():\n structure.stem = \"gibberish\"\n self.assertRaises(KeyError, t)\n\n def t():\n structure.superclass = \"monose\"\n self.assertRaises(KeyError, t)\n\n def t():\n structure.configuration = 'not-real'\n self.assertRaises(KeyError, t)\n\n def test_validate_reducing_end(self):\n structure = named_structures.monosaccharides['Hex']\n composition = structure.total_composition()\n structure.reducing_end = ReducedEnd()\n self.assertEqual(structure.total_composition(), composition + Composition(\"H2\"))\n structure.reducing_end = True\n self.assertEqual(structure.total_composition(), composition + Composition(\"H2\"))\n self.assertEqual(structure.total_composition(), structure.clone().total_composition())\n self.assertEqual(structure.total_composition(), pickle.loads(pickle.dumps(structure)).total_composition())\n structure.reducing_end = None\n self.assertEqual(structure.total_composition(), composition)\n\n def test_low_level_traverse(self):\n branchy = load(\"branchy_glycan\")\n t1 = monosaccharide.traverse(branchy.root)\n t2 = branchy.dfs()\n for a, b in itertools.izip(list(t1), list(t2)):\n self.assertEqual(a, b)\n\n def test_low_level_graph_clone(self):\n branchy = load(\"branchy_glycan\")\n self.assertEqual(branchy.root, monosaccharide.graph_clone(branchy.root))\n\n\nclass CrossRingTests(unittest.TestCase):\n\n\n def test_unroll_ring(self):\n linear = crossring_fragments.unroll_ring(monosaccharides.GlcNAc)\n for i in range(len(linear)):\n self.assertEqual(linear[i]['backbone'], Composition(\"CH2O\"))\n if i == 1:\n self.assertTrue(len(linear[i]['substituent_links']) > 0)\n\n class FragmentRecord(object):\n def __init__(self, name, mass, permethylated_mass, cleave_1, cleave_2, kind):\n self.name = name\n self.mass = float(mass)\n self.permethylated_mass = float(permethylated_mass)\n self.cleave_1 = int(cleave_1)\n self.cleave_2 = int(cleave_2)\n self.kind = kind\n self.composition = {}\n\n def __repr__(self):\n return \"FragmentRecord({name} {mass})\".format(**self.__dict__)\n\n def load_all(self):\n tree = ET.parse('./test_data/Cross-ring-data.xml')\n sugars = {}\n by_name = {}\n for cls in tree.iterfind(\".//class\"):\n sugar_class = {}\n for case in cls.iterfind(\".//sugar\"):\n isomers = [tag.attrib['abbr'] for tag in case.findall(\".//isomer\")]\n frags = defaultdict(dict)\n for frag in case.iterfind(\".//fragment\"):\n data = [frag.attrib[n] for n in [\"name\", \"mass_mono\", \"mass_pm_mono\", \"cleav1\", \"cleav2\", \"type\"]]\n rec = self.FragmentRecord(*data)\n rec.composition = dict(map(\n lambda x: (x.attrib['element'], x.attrib['count']), frag.findall(\".//composition\")))\n frags[rec.cleave_1, rec.cleave_2][rec.kind] = rec\n sugar_class[case.attrib['subclass']] = frags\n for name in isomers:\n by_name[name] = frags\n sugars[cls.attrib['name']] = sugar_class\n return by_name\n\n def test_monosacchide_crossring(self):\n test_cases = [\n 'Glc',\n \"GlcNAc\",\n \"Xyl\",\n 'GalA',\n 'Fuc',\n 'IdoA',\n \"KDN\"\n ]\n store = self.load_all()\n for case in test_cases:\n test = store[case]\n target = monosaccharides[case]\n for k, v in test.items():\n target_d = {t.kind: t for t in crossring_fragments.crossring_fragments(target, k[0], k[1])}\n target_d_permethylated = {t.kind: t for t in crossring_fragments.crossring_fragments(\n composition_transform.derivatize(target.clone(), \"methyl\"), k[0], k[1])}\n for kind in {\"A\", \"X\"}:\n self.assertAlmostEqual(v[kind].mass, target_d[kind].mass(), 3)\n self.assertAlmostEqual(v[kind].permethylated_mass, target_d_permethylated[kind].mass(), 3)\n\n\nclass SubstituentTests(unittest.TestCase):\n\n def test_substituent_substituent(self):\n parent = substituent.Substituent(\"n-acetyl\")\n pmass = parent.mass()\n child = substituent.Substituent(\"methyl\")\n cmass = child.mass()\n\n parent.add_substituent(child, 2)\n self.assertAlmostEqual(\n parent.mass(), (pmass + cmass - Composition(H=2).mass))\n self.assertEqual(\n parent.total_composition(), parent.composition + child.composition)\n self.assertEqual(parent.children().next()[1], child)\n self.assertEqual(child.parents().next()[1], parent)\n parent.drop_substituent(2)\n self.assertAlmostEqual(parent.mass(), pmass)\n\n def test_equality(self):\n sub_1 = substituent.Substituent(\"n-acetyl\")\n sub_2 = substituent.Substituent(\"n-acetyl\")\n self.assertEqual(sub_1, sub_2)\n parent = named_structures.monosaccharides['Hex']\n parent.add_substituent(sub_1, 3)\n self.assertNotEqual(sub_1, sub_2)\n\n def test_clone(self):\n parent = substituent.Substituent(\"n-acetyl\")\n child = substituent.Substituent(\"methyl\")\n\n parent.add_substituent(child, 2)\n\n dup = parent.clone()\n self.assertEqual(parent, dup)\n self.assertNotEqual(child, child.clone())\n\n def test_derivatize_pathway_setter(self):\n substituent.Substituent(\"not-real\", None, Composition(\"H2O\"), can_nh_derivatize=False, is_nh_derivatizable=True)\n self.assertRaises(KeyError, lambda: substituent.Substituent(\"not-real\", None, Composition(\"H2O\")))\n substituent.DerivatizePathway.register(\"not-real\", False, True)\n substituent.Substituent(\"not-real\", None, Composition(\"H2O\"))\n\n\nclass MultiMapTests(unittest.TestCase):\n\n def test_iterators(self):\n from collections import Counter\n mm = multimap.MultiMap(a=1, b=3)\n mm['a'] = 3\n self.assertTrue(set(mm.keys()) == {'a', 'b'})\n self.assertTrue(set(mm.items()) == {('a', 1), ('a', 3), ('b', 3)})\n self.assertTrue(Counter(mm.values()) == Counter({1: 1, 3: 2}))\n\n def test_ordered_multimap(self):\n mm = multimap.MultiMap(a=1, b=3)\n mm['a'] = 3\n omm = multimap.OrderedMultiMap(a=1, b=3)\n omm['a'] = 3\n self.assertEqual(mm, omm)\n omm['c'] = 1\n self.assertNotEqual(mm, omm)\n self.assertNotEqual(omm, mm)\n self.assertFalse('c' in mm)\n\n\nclass ConstantTests(unittest.TestCase):\n\n def test_translate(self):\n self.assertTrue(\n constants.Modification.d == constants.Modification['d'])\n self.assertTrue(constants.Modification.d == constants.Modification[\n constants.Modification.d.value])\n\n def test_compare(self):\n self.assertTrue(constants.Modification.d == 'd')\n self.assertTrue(\n constants.Modification.d == constants.Modification.d.value)\n self.assertNotEqual(\n constants.Modification.d, constants.Stem[constants.Modification.d.value])\n self.assertRaises(KeyError, lambda: constants.SuperClass[1])\n self.assertNotEqual(constants.Modification.d, constants.Modification.a)\n\n def test_multiname(self):\n Modification = constants.Modification\n self.assertTrue(Modification.d == 'd')\n self.assertFalse(Modification.d == 'Deoxidation')\n # Add new name to existing EnumValue\n Modification.d.add_name(\"Deoxidation\")\n self.assertTrue(Modification.d == 'Deoxidation')\n\n # Add new name to class by re-using EnumValue\n self.assertFalse(Modification.d == \"deoxy\")\n Modification.deoxy = Modification.d\n self.assertTrue(Modification.d == \"deoxy\")\n self.assertEqual(Modification.deoxy, Modification.Deoxidation)\n\n # Add new name to class and EnumValue by interpolating value\n self.assertFalse(Modification.deoxy == 'deoxy2')\n Modification.deoxy2 = Modification.d.value\n self.assertTrue(Modification.deoxy == 'deoxy2')\n self.assertRaises(KeyError, lambda: Modification.d.add_name('a'))\n\n def test_wrap_value(self):\n constants.Modification.not_a_real_modification = -5\n self.assertTrue(isinstance(constants.Modification.not_a_real_modification, enum.EnumValue))\n self.assertEqual(constants.Modification.not_a_real_modification.resolve(\n constants.Modification), -5)\n\n def test_resolve_failure(self):\n mapping = {'d': 5}\n self.assertTrue(constants.Modification.d.resolve(mapping) == 5)\n self.assertRaises(KeyError, lambda: constants.Modification.aldi.resolve(mapping))\n\n def test_instantiate_error(self):\n self.assertRaises(Exception, enum.Enum)\n\n def test_crossclass_inequality(self):\n class E1(enum.Enum):\n A = 1\n\n class E2(enum.Enum):\n A = 1\n self.assertNotEqual(E1.A, E2.A)\n\n\nclass LinkTests(unittest.TestCase):\n\n def test_link_equality(self):\n parent = named_structures.monosaccharides['Hex']\n child = named_structures.monosaccharides['Hex']\n other = named_structures.monosaccharides['Hex']\n link_1 = link.Link(parent, child, parent_position=3,\n child_position=3, parent_loss='H', child_loss='OH')\n link_2 = link.Link(child, other, parent_position=6,\n child_position=3, parent_loss='H', child_loss='OH')\n self.assertEqual(link_1, link_1)\n self.assertNotEqual(link_1, link_2)\n self.assertFalse(link_1 is None)\n\n def test_loss_composition(self):\n parent = named_structures.monosaccharides['Hex']\n child = named_structures.monosaccharides['Hex']\n\n link_1 = link.Link(parent, child, parent_position=3,\n child_position=3, parent_loss='H', child_loss='OH')\n\n self.assertEqual(link_1.parent_loss, Composition(formula=\"H\"))\n self.assertEqual(link_1.child_loss, Composition(formula=\"OH\"))\n\n def test_break_and_reconnect(self):\n parent = named_structures.monosaccharides['Hex']\n child = named_structures.monosaccharides['Hex']\n\n link_1 = link.Link(parent, child, parent_position=3,\n child_position=3, parent_loss='H', child_loss='OH')\n link_1.break_link(refund=True)\n self.assertTrue(len(parent.links[3]) == 0)\n self.assertTrue(len(child.links[3]) == 0)\n\n link_1.reconnect(refund=True)\n self.assertTrue(len(parent.links[3]) == 1)\n self.assertTrue(len(child.links[3]) == 1)\n\n def test_traversal(self):\n parent = named_structures.monosaccharides['Hex']\n child = named_structures.monosaccharides['Hex']\n\n link_1 = link.Link(parent, child, parent_position=3,\n child_position=3, parent_loss='H', child_loss='OH')\n self.assertTrue(link_1.is_parent(parent))\n self.assertTrue(link_1.is_child(child))\n self.assertEqual(link_1.to(parent), child)\n self.assertEqual(link_1.to(child), parent)\n self.assertRaises(KeyError, lambda: link_1.to(1))\n\n\nclass SubtreeSearchTests(unittest.TestCase):\n\n def test_subtree_inclusion(self):\n core = glycans['N-Linked Core']\n tree = glycoct.loads(broad_n_glycan).next()\n self.assertTrue(subtree_search.subtree_of(core, tree))\n self.assertTrue(subtree_search.subtree_of(tree, core) is None)\n\n def test_maximum_common_subtree(self):\n core = glycans['N-Linked Core']\n tree = glycoct.loads(branchy_glycan).next()\n res = subtree_search.maximum_common_subgraph(core, tree)\n self.assertEqual(res.score, 6.2)\n\n def test_is_n_glycan(self):\n core = glycans['N-Linked Core']\n tree = glycoct.loads(broad_n_glycan).next()\n result = (subtree_search.subtree_of(core, tree))\n self.assertTrue(result == 1)\n tree = glycoct.loads(complex_glycan).next()\n result = (subtree_search.subtree_of(core, tree, exact=False))\n self.assertTrue(result == 1)\n tree = glycoct.loads(branchy_glycan).next()\n result = (subtree_search.subtree_of(core, tree, exact=False))\n self.assertTrue(result is None)\n\n\nclass IdentifyTests(unittest.TestCase):\n\n def test_is_a_predicate(self):\n for name, monosaccharide in monosaccharides.items():\n self.assertTrue(identity.is_a(monosaccharide, name))\n\n @debug_on()\n def test_identify_as(self):\n for name, monosaccharide in monosaccharides.items():\n if monosaccharide == monosaccharides.Hex:\n continue\n pref_name = identity.identify(monosaccharide)\n if not (name == pref_name or name in synonyms.monosaccharides[pref_name]):\n raise AssertionError(\n \"{}\".format((name, pref_name, synonyms.monosaccharides[pref_name])))\n\n def test_identify_substituents(self):\n self.assertTrue(\n identity.is_a(Substituent(\"n-acetyl\"), Substituent('n-acetyl')))\n self.assertFalse(\n identity.is_a(Substituent('methyl'), Substituent('n-acetyl')))\n self.assertFalse(\n identity.is_a(monosaccharides.Man, Substituent('n-acetyl')))\n self.assertFalse(\n identity.is_a(Substituent('n-acetyl'), monosaccharides.Man))\n\n def test_get_preferred_name(self):\n self.assertTrue(identity.get_preferred_name('bdMan') == 'Man')\n\n def test_identify_failure(self):\n # Will fail because Hex is blacklisted\n self.assertRaises(\n identity.IdentifyException, lambda: identity.identify(monosaccharides.Hex))\n\n\nclass LinearCodeTests(unittest.TestCase):\n\n def test_translate(self):\n broad = glycoct.loads(broad_n_glycan).next()\n dup = linear_code.loads(linear_code.dumps(broad))\n self.assertEqual(broad, dup)\n\n # linear code doesn't know about modifications or\n # ring shape\n sulfated = glycoct.loads(sulfated_glycan).next()\n sulfated.reducing_end = None\n sulfated.root.ring_start = 1\n sulfated.root.ring_end = 5\n dup = linear_code.loads(linear_code.dumps(sulfated))\n self.assertEqual(dup, sulfated)\n\n sulfated = glycoct.loads(sulfated_glycan).next()\n dup = linear_code.loads(linear_code.dumps(sulfated))\n self.assertNotEqual(sulfated, dup)\n\n\nclass SimilarityTests(unittest.TestCase):\n\n def test_deep_similarity(self):\n branchy = glycoct.loads(branchy_glycan).next()\n broad = glycoct.loads(broad_n_glycan).next()\n ref = broad.clone()\n self.assertEqual(similarity.monosaccharide_similarity(branchy.root, branchy.root), (5, 5))\n self.assertEqual(\n similarity.monosaccharide_similarity(branchy.root, branchy.root, include_children=True),\n (26, 26))\n self.assertEqual(similarity.monosaccharide_similarity(branchy.root, broad.root), (4, 5))\n self.assertEqual(\n similarity.monosaccharide_similarity(branchy.root, broad.root, include_children=True),\n (7, 10))\n self.assertEqual(\n similarity.monosaccharide_similarity(broad.root, branchy.root, include_children=True),\n (11, 14))\n self.assertEqual(similarity.monosaccharide_similarity(broad.root, broad.root, include_children=True), (54, 54))\n self.assertEqual(ref, broad)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"pygly2/tests/tests_legacy.py","file_name":"tests_legacy.py","file_ext":"py","file_size_in_byte":27657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"617583016","text":"import element.node\n\nclass SeoHandler(element.node.NodeHandler):\n def get_defaults(self, node):\n return {\n 'template': 'element.plugins.seo:headers.html'\n }\n\n def get_name(self):\n return 'Seo'\n\n def execute(self, context, flask):\n params = {\n 'context': context,\n 'seo': context.node.seo\n }\n\n return flask.make_response(flask.render_template(context.settings['template'], **params))\n\n def listener(self, event):\n if 'seo' not in event.get('subject').data:\n return\n\n node = element.node.Node('seo://%s' % event.get('subject').id, 'seo.headers', {\n 'seo': event.get('subject').data['seo'],\n })\n\n event.set('node', node)","sub_path":"element/plugins/seo/seo.py","file_name":"seo.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"419679077","text":"import re, sys\nimport matplotlib.pyplot as plt\nif len(sys.argv) < 3:\n print(f\"usage: {sys.argv[0]} \")\n exit()\nwith open(sys.argv[1], 'r') as f:\n lines = [line for line in f.readlines() if line.startswith('Test set: Accuracy:')]\naccuracy = [re.search('([\\d\\.]*)%', line).group(1) for line in lines]\naccuracy = [round(float(a), 5) for a in accuracy]\naccuracy.insert(0, 50)\nplt.figure(figsize=(50,50))\nplt.plot(accuracy)\nplt.ylim(bottom=50, top=100)\nplt.ylabel('Accuracy (%)', fontsize=20)\nplt.xlabel('Number of epochs', fontsize=20)\nplt.xticks(fontsize=20)\nplt.yticks(fontsize=20)\nplt.title(sys.argv[2], fontsize=25)\nplt.show()\n","sub_path":"src/graphGenerator.py","file_name":"graphGenerator.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"546634070","text":"\"\"\"CSC 161 Lab: Simulation & Design\n\nThis lab helps estimate the expected distance a man would move from a\nstarting point with a random walk.\n\nBorja Rojo\nLab Section TR 2:00-3:15pm\nFall 2016\n\"\"\"\n\nimport random\n\n# Returns a list of ints from 0-3 which represent the 4 directions\n# someone could walk in a grid pattern\n\n\ndef random_walk_2d(step_count):\n path = []\n\n # Generate random ints between 0 and 3\n for i in range(step_count):\n path.append(random.randrange(0, 4))\n\n return path\n\n\n\"\"\"This funciton takes a path which is a list of numbers 0-3 and\ncalculates the distance from it's start point.\n\n0 = up, 1 = right, 2 = down, 3 = left\n\"\"\"\n\n\ndef distance_walked(path):\n # Distance Vars\n x_distance = 0\n y_distance = 0\n\n # Path eval\n for i in range(len(path)):\n if path[i] == 0:\n y_distance += 1\n elif path[i] == 1:\n x_distance += 1\n elif path[i] == 2:\n y_distance -= 1\n elif path[i] == 3:\n x_distance -= 1\n\n # Distance Eval\n distance = (x_distance ** 2 + y_distance ** 2)**(1 / 2)\n\n return distance\n\n\ndef average_walk_distance(walk_count, step_count):\n average_distance = 0\n\n # Calculate total\n for i in range(walk_count):\n average_distance += distance_walked(random_walk_2d(step_count))\n\n # Divide to get average\n average_distance /= walk_count\n\n return average_distance\n\n\ndef main():\n print(\"Simulation of two dimensional random walk\")\n\n walks = eval(input(\"How many walks should I do? \"))\n steps = eval(input(\"How many steps should I take on each? \"))\n\n av_dist = average_walk_distance(walks, steps)\n print(\"Average distance from start: {0:0.2f}\".format(av_dist))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"labs/lab_simulation_design.py","file_name":"lab_simulation_design.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"245756491","text":"#\nimport torch, torchvision\nimport detectron2\nfrom detectron2.utils.logger import setup_logger\nsetup_logger()\nimport numpy as np\nimport os, json, cv2, random\nfrom detectron2 import model_zoo\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.data import MetadataCatalog, DatasetCatalog\nimport sys\n\n\ndef get_masked_image(image):\n cfg = get_cfg()\n cfg.MODEL.DEVICE='cpu'\n # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library\n cfg.merge_from_file(model_zoo.get_config_file(\"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml\"))\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model\n # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well\n cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(\"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml\")\n predictor = DefaultPredictor(cfg)\n outputs = predictor(image)\n predicted_classes = outputs[\"instances\"].pred_classes.numpy()\n if not (0 in predicted_classes):\n return False\n mask = outputs[\"instances\"].pred_masks.numpy()[0].astype('uint8')*255\n\n #m3chan = cv2.merge((mask,mask,mask))\n #masked = cv2.bitwise_and(image,m4chan)\n\n #Transparency\n b_channel, g_channel, r_channel = cv2.split(image)\n #mask,_,_ = cv2.split(cropped_mask)\n \n #alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255 #creating a dummy alpha channel image.\n img_BGRA = cv2.merge((b_channel, g_channel, r_channel,mask))\n #cv2_imshow(img_BGRA)\n return img_BGRA\n\ndef crop_image(res):\n image_data_bw = res.max(axis=2)\n non_empty_columns = np.where(image_data_bw.max(axis=0)>0)[0]\n non_empty_rows = np.where(image_data_bw.max(axis=1)>0)[0]\n cropBox = (min(non_empty_rows), max(non_empty_rows), min(non_empty_columns), max(non_empty_columns))\n cropped_key_points = res[cropBox[0]:cropBox[1]+1, cropBox[2]:cropBox[3]+1 , :]\n return cropped_key_points\n\ndef get_key_points(image):\n cfg = get_cfg()\n cfg.MODEL.DEVICE='cpu'\n # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library\n cfg.merge_from_file(model_zoo.get_config_file(\"COCO-Keypoints/keypoint_rcnn_R_50_FPN_1x.yaml\"))\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model\n # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well\n cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(\"COCO-Keypoints/keypoint_rcnn_R_50_FPN_1x.yaml\")\n predictor = DefaultPredictor(cfg)\n outputs = predictor(image)\n kpoints = outputs['instances'].pred_keypoints[0].numpy()\n knames = [\"nose\",\"left_eye\",\"right_eye\",\"left_ear\",\"right_ear\",\"left_shoulder\",\\\n \"right_shoulder\",\"left_elbow\",\"right_elbow\",\"left_wrist\",\"right_wrist\",\"left_hip\",\\\n \"right_hip\",\"left_knee\",\"right_knee\",\"left_ankle\",\"right_ankle\"]\n kdict = {p:k[0:2] for k,p in zip(kpoints,knames)}\n return kdict\n \ndef rotate_image(image, angle):\n image_center = tuple(np.array(image.shape[1::-1]) / 2)\n rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)\n return result\n","sub_path":"sprite_helper.py","file_name":"sprite_helper.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"286053151","text":"from flask import Flask, render_template, request\nfrom wikipedia import * \n\napp = Flask(__name__)\n\n@app.route('/', methods=['GET','POST'])\ndef index():\n if request.method == 'GET':\n return render_template('index.html')\n else:\n word = request.form.get('word')\n wiki_page = page(word) \n try: \n title = wiki_page.title\n url = wiki_page.url\n summary = wiki_page.summary \n except exceptions as e:\n summary = e.options\n return render_template('index.html', title = title, url = url, summary = summary)\n \n\n\nif __name__ == '__main__':\n app.run(use_reloader = True, debug = True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"153536400","text":"# Copyright 2013 Open Cloud Consortium\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''' The Flask HTTP API for Metadata service. '''\n\nimport json\nimport flask\nimport xmldict\nimport socket\n\nfrom .metadata import update_metadata, list_projects\nfrom flask import request, g\nfrom functools import partial\nfrom tukey_middleware.couch import Couch\nfrom tukey_middleware.flask_utils import return_error, with_user, same_server\nfrom tukey_middleware.local_settings import metadata as settings\nfrom tukey_middleware.modules.ids.client import Client as IdServiceClient\nfrom tukey_middleware.modules.ids.ids import create_id\n\nrest = flask.Blueprint(\"metadata\", \"name\")\n\nID_SERVICE = \"http://localhost:8774\"\nID_SERVICES = [\"http://localhost:8774\", \"http://172.16.1.76:8774\"]\n\n\n@rest.route(\"/clouds/\")\n@return_error\n@with_user(rest)\ndef get_cloud_info(cloud):\n ''' Return info about the cloud '''\n\n couch = Couch(\"clouds\")\n return json.dumps(couch[cloud])\n\n\n@rest.route(\"/\", methods=[\"GET\"])\n@return_error\n@with_user(rest)\ndef get_metadata(project_name):\n ''' Return the full metadata of the project '''\n couch = Couch(project_name)\n # Wrong!\n # TOOD: fix this\n return json.dumps(couch)\n\n@rest.route(\"/\", methods=[\"GET\"])\n@return_error\n@with_user(rest)\ndef get_projects():\n ''' List of projects that this user can write to'''\n return json.dumps(list_projects(g.user,\n request.args.get('write', False)))\n\n\ndef _create_id():\n ''' Note the else branch has not been tested!'''\n for service in settings[\"id_services\"]:\n if same_server(service):\n return partial(create_id, g.user)\n else:\n id_client = IdServiceClient(settings[\"id_services\"][0],\n id_service_auth_token=g.user.id_auth_token)\n return lambda record, acl: id_client.register_collection(record,\n extra={\"acl\": acl})\n\n\n@rest.route(\"/\", methods=[\"PUT\"])\n@return_error\n@with_user(rest)\ndef put_metadata(project_name):\n ''' Return info about the cloud '''\n\n if request.headers[\"content-type\"] in [\"xml\", \"text/xml\",\n \"application/xml\"]:\n raw_metadata = xmldict.xml_to_dict(request.data)\n elif request.headers[\"content-type\"] in [\"json\", \"text/json\",\n \"application/json\"]:\n raw_metadata = json.loads(request.data)\n\n host, port = request.host.split(\":\")\n metadata_service = \"http://%s:%s\" % (socket.gethostbyaddr(host)[0], port)\n return update_metadata(g.user, project_name, raw_metadata, metadata_service,\n _create_id())\n","sub_path":"Tukey/tukey_middleware/tukey_middleware/modules/metadata/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"556842524","text":"#! /usr/bin/env python\n\n__author__='Gustavo Arango'\n__version__=\"0.0.1\"\n__date__=\"2015\"\n\n\nUSAGE = \\\n\"\"\"Usage \"\"\"\n\n\n\n\n\n\n\n\ndb=root.dataset(\"silva\")\n\ninputfile=\"/research/gustavo1/Dropbox/PhDProjects/metagenomics/Xiao/S2.extendedFrags.fastq\"\noutputfile=\"/research/gustavo1/metagenomics/MetaGenFiles/PROJECTS/XIAO/BOWTIE/\"\nsamplename=\"S2\"\n\ntaxonomy_reads_pipeline(db,inputfile,outputfile,samplename)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# here\n","sub_path":"app/lib/run/execute.py","file_name":"execute.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"53233759","text":"#!/usr/bin/env python3\n\ndonors = [(\"Bill Gates\", [653772.32, 12.17]),\n (\"Jeff Bezos\", [877.33]),\n (\"Paul Allen\", [663.23, 43.87, 1.32]),\n (\"Mark Zuckerberg\", [1663.23, 4300.87, 10432.0]),\n (\"Tim Cook\", [1563.32, 8976.54])]\n\nprompt = \"\\n\".join((\"Welcome to the mailroom!\",\n \"Please choose from below options:\",\n \"1 - Send a thank you\",\n \"2 - Create a report\",\n \"3 - Quit\",\n \">>> \"))\n\n\ndef donor_list():\n \"\"\"Returns a list of the donor names from donors\"\"\"\n donor_names = [i[0] for i in donors]\n return donor_names\n \n\ndef add_donation(name, donation):\n \"\"\"\n Appends the donation to the donation list in the donor tuple\n \n Parameters:\n name(str): name of the donor\n donation(int): value of the donation\n \n Returns:\n list with new donation added\n \"\"\"\n for i in donors:\n if name in i:\n place = donors.index(i)\n thankyou_email(name, donation)\n return donors[place][1].append(donation)\n\ndef thankyou_email(name, donation):\n \"\"\"Prints the letter with the user inputted name and donation \"\"\"\n\n print(\"\"\"\n Dear {},\n Thank you very much for the generous donation of ${:,.2f}\n It is very much appreciated. \n Respectfully,\n \n Eric G.\n \"\"\".format(name, donation))\n\n\ndef thank_you():\n \"\"\"\n Asks user for a name, list of donors, or to quit.\n If a name, prompts user for a donation and prints \n the tahnk you email\n \n \"\"\"\n complete = False\n \n while not complete:\n thanks = input(\"Please enter full name, type 'list' to see all names, or enter 'q' to quit: \").title()\n if thanks == 'Q':\n break\n if thanks == 'List':\n print(donor_list())\n continue\n if thanks not in [x[0] for x in donors]:\n donors.append((thanks,list()))\n \n donation = input(\"Please enter in a donation, or 'q' to quit: \")\n if donation == 'q':\n break\n else:\n add_donation(thanks,float(donation))\n complete = True\n \n \ndef sort_key(items):\n \"\"\"Sort key for the sorted list in create report\"\"\"\n return items[1]\n\ndef create_report():\n \"\"\"\n Creates a formatted and aligned report of each donor,\n total given, number of gifts, and average gift, sorted\n by total given (large to small)\n\n \"\"\"\n\n new_list = []\n for i in range(len(donors)):\n sum_don = sum(donors[i][1])\n len_don = len(donors[i][1])\n average = sum_don/len_don\n new_list.append([donors[i][0], sum_don, len_don, average])\n sorted_list = sorted(new_list, key=sort_key, reverse=True)\n print()\n print(\"{:<25s}|{:>15s} |{:>10s} | {:>12s}\".format(\"Donor Name\", \"Total Given\", \"Num Gifts\", \"Average Gift\"))\n print(68 * '-')\n for x in sorted_list:\n print(\"{:<25s}|${:>14.2f} |{:>10.0f} |${:>12.2f}\".format(*x))\n print()\n\n\n\ndef main():\n \"\"\"Controls flow of program; prompts user for selection and breaks if quit\"\"\"\n while True:\n response = input(prompt)\n if response == '1':\n thank_you()\n if response == '2':\n create_report()\n if response == '3':\n break\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"students/eric_grandeo/lesson03/mailroom.py","file_name":"mailroom.py","file_ext":"py","file_size_in_byte":3296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"116840852","text":"# python 2.7\nimport os\nimport shutil\nimport json\nimport re\nimport urllib\nimport zipfile\nfrom PIL import Image\nfrom module_data import ModuleData\nfrom bs4 import BeautifulSoup\n\nmodulePageUrl = \"http://www.vassalengine.org/wiki/Module:Star_Wars:_X-Wing_Miniatures_Game\"\n\ndef pilot_name_to_vassalmod(name):\n\toutput = xml.find_pilot_image_name(name)\n\treturn output\n\n\ndef upgrade_name_to_vassalmod(name):\n\toutput = xml.find_upgrade_image_name(name)\n\treturn output\n\ndef condition_name_to_vassalmod(name):\n\toutput = xml.find_condition_image_name(name)\n\treturn output\n\ndef normal_string_format(name):\n\toutput = name.replace(\"\\\"\", \"\") \\\n\t\t.replace(\"(\", \"\").replace(\")\", \"\")\n\treturn output\n\n\ndef download_module():\n\tmodulePageContent = urllib.urlopen(modulePageUrl).read()\n\thtml = BeautifulSoup(modulePageContent, \"lxml\")\n\ta = html.find('a', string=re.compile(\"Star_Wars_X-Wing_Miniatures_Game-(.*?).vmod\"))\n\turl = \"http://www.vassalengine.org\" + a.attrs['href']\n\tfilename = a.string\n\tmodule_file = urllib.URLopener()\n\tmodule_file.retrieve(url, filename)\n\textract_buildfile_from_vmod(filename)\n\ndef extract_buildfile_from_vmod(vmod_filename):\n\twith zipfile.ZipFile(vmod_filename) as z:\n\t\twith open(os.path.basename(\"buildfile\"), 'wb') as f:\n\t\t\tf.write(z.read(\"buildFile\"))\n\t\t\tf.close()\n\ndef cleanup():\n\ttry:\n\t\tfor this_file in os.listdir('output'):\n\t\t\tfile_path = os.path.join('output', this_file)\n\t\t\tif os.path.isfile(file_path):\n\t\t\t\tos.unlink(file_path)\n\t\t\telif os.path.isdir(file_path):\n\t\t\t\tshutil.rmtree(file_path)\n\t\t# shutil.rmtree('output')\n\texcept:\n\t\tpass\n\t# os.mkdir('output')\n\ncleanup()\ndownload_module()\nxml = ModuleData('buildfile')\n\n# load the JSON data\nwith open('..\\data\\pilots.js') as pilot_data_file:\n\tpilot_data = json.load(pilot_data_file)\n\n# copy image to new path based on name\nfor pilot in pilot_data:\n\timage = pilot.get('image', \"\")\n\tif image == \"\":\n\t\tprint(\"Missing Image: \" + pilot[\"name\"])\n\t\tcontinue\n\ttry:\n\t\tif pilot[\"id\"] == 194:\n\t\t\tpilot[\"name\"] = \"Poe Dameron 2\"\n\t\telif pilot[\"id\"] == 219:\n\t\t\tpilot[\"name\"] = \"Han Solo 2\"\n\t\telif pilot[\"id\"] == 220:\n\t\t\tpilot[\"name\"] = \"Chewbacca 2\"\n\n\t\tpilot_module_image = pilot_name_to_vassalmod(normal_string_format(pilot[\"name\"]))\n\t\tif pilot_module_image == None:\n\t\t\tprint(\"Could not find module image for pilot \" + normal_string_format(pilot[\"name\"]))\n\t\t\tcontinue\n\n\t\tif pilot[\"id\"] in [97]:\n\t\t\tpilot_module_image = pilot_module_image.replace(\".jpg\", \"_S&V.jpg\")\n\t\telif pilot[\"id\"] == 99:\n\t\t\tpilot_module_image = \"Pilot-Kat_Scarlet_Scum.jpg\"\n\t\telif pilot[\"id\"] == 198:\n\t\t\tpilot_module_image = \"Pilot-Sabine_Wren_S&V.jpg\"\n\t\telif pilot[\"id\"] == 160:\n\t\t\tpilot_module_image = \"Pilot-Hera_Syndulla.jpg\"\n\t\t#elif pilot[\"id\"] == 19:\n\t\t# pilot_module_image = \"Pilot-Maarek_Stele.jpg\"\n\t\telif pilot[\"id\"] == 192:\n\t\t\tpilot_module_image = \"Pilot-Maarek_Stele_Defender.jpg\"\n\t\telif pilot[\"id\"] == 214:\n\t\t\tpilot_module_image = \"Pilot-Sabine_Wren_TF.jpg\"\n\t\telif pilot[\"id\"] == 175:\n\t\t\tpilot_module_image = \"Pilot-Sabine_Wren_Shuttle.jpg\"\n\n\t\tsrc = \"../images/\" + pilot[\"image\"]\n\t\tdst = \"output/\" + pilot_module_image\n\t\t# have to do the convert call because Pillow did not like the png format or something\n\t\tImage.open(src).convert('RGBA').save(dst)\n\t\tpass\n\texcept Exception:\n\t\tprint(\"Problem with \" + pilot[\"name\"])\n\t\tprint(\"Source: \" + src)\n\t\tprint(\"Destination: \" + dst)\n\t\traise\n\nwith open('..\\data\\\\upgrades.js') as upgrade_data_file:\n\tupgrade_data = json.load(upgrade_data_file)\n\nfor upgrade in upgrade_data:\n\timage = upgrade.get('image', \"\")\n\tif image == \"\":\n\t\tprint(\"Missing Image: \" + upgrade[\"name\"])\n\t\tcontinue\n\ttry:\n\t\t# deal with Falcon titles\n\t\tif upgrade[\"id\"] == 243:\n\t\t\tupgrade[\"name\"] = \"Millenium Falcon 2\" \n\t\tif upgrade[\"id\"] == 270:\n\t\t\tupgrade[\"name\"] = \"Adaptative Ailerons\"\n\n\t\tupgrade_module_image = upgrade_name_to_vassalmod(normal_string_format(upgrade[\"name\"]))\n\t\tif upgrade_module_image == None:\n\t\t\tprint(\"Could not find module image for upgrade \" + normal_string_format(upgrade[\"name\"]))\n\t\t\tcontinue\n\n\t\tif upgrade[\"id\"] == 62:\n\t\t\tupgrade_module_image = \"Up-R2-D2_Crew.jpg\"\n\n\t\tsrc = \"../images/\" + upgrade[\"image\"]\n\t\tdst = \"output/\" + upgrade_module_image\n\t\tImage.open(src).convert('RGBA').save(dst)\n\t\tpass\n\texcept TypeError:\n\t\tpass\n\texcept Exception as e:\n\t\tprint(\"Problem with \" + upgrade[\"name\"] + \": {0}\".format(e))\n\t\tprint(\"Source: \" + src)\n\t\tprint(\"Destination: \" + dst)\n\t# raise\n\nwith open('..\\data\\conditions.js') as condition_data_file:\n\tcondition_data = json.load(condition_data_file)\n\nfor condition in condition_data:\n\timage = condition.get('image', \"\")\n\tif image == \"\":\n\t\tprint(\"Missing Image: \" + condition[\"name\"])\n\t\tcontinue\n\ttry:\n\t\tcondition_module_image = condition_name_to_vassalmod(normal_string_format(condition[\"name\"]))\n\t\tif condition_module_image == None:\n\t\t\tprint(\"Could not find module image for condition \" + normal_string_format(condition[\"name\"]))\n\t\t\tcontinue\n\n\t\tsrc = \"../images/\" + condition[\"image\"]\n\t\tdst = \"output/\" + condition_module_image\n\t\tImage.open(src).convert('RGBA').save(dst)\n\t\tpass\n\texcept TypeError:\n\t\tpass\n\texcept Exception as e:\n\t\tprint(\"Problem with \" + condition[\"name\"] + \": {0}\".format(e))\n\t\tprint(\"Source: \" + src)\n\t\tprint(\"Destination: \" + dst)\n","sub_path":"vassalize/vassalize.py","file_name":"vassalize.py","file_ext":"py","file_size_in_byte":5182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"475840436","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 26 18:30:26 2015\n\n@author: vh, shardul and svs\n\"\"\"\nimport os, sys\nhome = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nos.sys.path.append(home)\n\nimport csv, json, time\nfrom itertools import islice\nfrom joblib import Parallel, delayed\nimport metaclassifier.mcServicesAPI as mcapi\nimport numpy as np\nimport cPickle as pickle\ncsv.field_size_limit(sys.maxsize)\n\ndef callMC(line, docid_idxs, txtcol_idx, serializer = json.dumps): \n docid = [line[idx] for idx in docid_idxs]\n txt = line[txtcol_idx]\n res ={}\n #rv = [serializer(docid), serializer([{}])] \n if txt: \n res = mcapi._mcNLPipeline(txt) #, ['sentiment', 'entitySentiment'])\n #rv[-1] = serializer(res)\n \n return res\n\ndef _mc_CSVPBSW(func, ifname, docid_cols, txtcol, rfname , dbase, serializer = json.dumps):\n '''\n CSV parallel batch processing and serialized writer \n ''' \n \n with open(ifname) as dfile:\n ipreader = csv.reader(dfile, delimiter='|')\n \n #header parse and find indices.\n header = ipreader.next()\n docid_idxs = [header.index(dc) for dc in docid_cols]\n txtcol_idx = header.index(txtcol) \n ##print docid_idxs, txtcol_idx\n \n part = 0\n ink=0\n while True:\n ink+=1\n \n n_lines = list(islice(ipreader, 1000))\n if not n_lines:\n break \n resps = [callMC(line, docid_idxs, txtcol_idx) for line in n_lines] #if \"439293759\" in line[docid_idxs[0]] \n st = time.time()\n makeCoLocation(resps)\n print(collocation_matrix.shape)\n #print(collocation_matrix.shape)\n #print '%3d %4d %4.3f' % (part, len(n_lines), time.time() - st)\n\n part += 1 \n coloc_adj_noun=AdjNounColocMatrix()\n pickle.dump(coloc_adj_noun,open(dbase+\"Coloc_adj_noun.pickle\",\"wb\")) \n colloation_result=adjectiveAndNounSimilarityMatrix()\n writerColl(colloation_result,dbase)\n pickle.dump(colloation_result,open(dbase+\"all_adj_given_noun.pickle\",\"wb\"))\n \nnounTags=['N','S','Z','^']\nadjectiveList = []\nnounList = []\ncollocation_matrix=np.zeros([1,1])\ndef makeCoLocation(res):\n global collocation_matrix\n for text in res:\n if(len(text)==0):\n continue\n for chunkSentences in text[\"chunkedSentences\"]:\n for indc,chunk in enumerate(chunkSentences):\n if chunk.chunkType in [\"NP\",\"ADJP\"]:\n for ind,tags in enumerate(chunk.tags):\n if tags == \"A\":\n #print(chunk)\n presence_N=-1\n presence_A=-1\n assocNoun=-1\n current_noun = []\n for i in xrange(ind+1,chunk.tags.__len__()):\n if chunk.tags[i] in nounTags:\n assocNoun=i\n current_noun=\"/\".join((chunk.tokens[i],chunk.tags[i]))\n elif chunk.tags[i] == \"P\":\n break\n #print(\"0\") \n if assocNoun == -1:\n if indc >= 2:\n if ((chunkSentences[indc-1].chunkType == \"VP\") and (chunkSentences[indc-2].chunkType == \"NP\")):\n if chunkSentences[indc-1].tprops[0].has_key(\"AUXVERB\"):\n for j in xrange(chunkSentences[indc-2].tags.__len__()):\n if chunkSentences[indc-2].tags[j] in nounTags:\n assocNoun=j\n current_noun=\"/\".join((chunkSentences[indc-2].tokens[j],chunkSentences[indc-2].tags[j]))\n elif chunkSentences[indc-2].tags[j] == \"P\":\n break \n \n if assocNoun != -1: \n if(\"/\".join((chunk.tokens[ind],chunk.tags[ind])) not in adjectiveList):\n adjectiveList.append(\"/\".join((chunk.tokens[ind],chunk.tags[ind])))\n else:\n presence_A=adjectiveList.index(\"/\".join((chunk.tokens[ind],chunk.tags[ind])))\n \n if current_noun not in nounList:\n nounList.append(current_noun) \n else:\n presence_N=nounList.index(current_noun)\n if assocNoun != -1:\n if((len(adjectiveList)==1) and (len(nounList)==1)):\n collocation_matrix[0][0]=1\n else:\n if((presence_N!=-1) and (presence_A!=-1)):\n collocation_matrix[presence_N][presence_A]+=1\n elif((presence_N==-1) and (presence_A==-1)):\n seq=np.array([0 for k in xrange(collocation_matrix.shape[1])])\n collocation_matrix=np.vstack((collocation_matrix,seq))\n seq=np.array([0 for k in xrange(collocation_matrix.shape[0])])\n seq[-1]=1\n collocation_matrix=np.column_stack((collocation_matrix,seq))\n elif((presence_N!=-1) and (presence_A==-1)): \n seq=np.array([0 for k in xrange(collocation_matrix.shape[0])])\n collocation_matrix=np.column_stack((collocation_matrix,seq))\n collocation_matrix[presence_N][-1]=1\n elif((presence_N==-1) and (presence_A!=-1)): \n seq=np.array([0 for k in xrange(collocation_matrix.shape[1])])\n collocation_matrix=np.vstack((collocation_matrix,seq)) \n collocation_matrix[-1][presence_A]=1\n \ndef top_members_extract(collocation_matrix, rev=0):\n collocation_result={}\n if(rev==0):\n for j in xrange(collocation_matrix.shape[0]):\n ind_non_zero=sorted(collocation_matrix[j],reverse=True).index(0)\n noun_max = sorted(collocation_matrix[j],reverse=True)[0:ind_non_zero]\n noun_index=np.argsort(collocation_matrix[j])[-ind_non_zero:]\n noun_index=list(noun_index)\n noun_index.reverse()\n noun_names=[nounList[m] for m in noun_index]\n collocation_result[adjectiveList[j]]=[noun_names,noun_max]\n else:\n for j in xrange(collocation_matrix.shape[0]):\n ind_non_zero=sorted(collocation_matrix[j],reverse=True).index(0)\n adjective_max = sorted(collocation_matrix[j],reverse=True)[0:ind_non_zero]\n adjective_index=np.argsort(collocation_matrix[j])[-ind_non_zero:]\n adjective_index=list(adjective_index)\n adjective_index.reverse()\n adjective_names=[adjectiveList[m] for m in adjective_index]\n collocation_result[nounList[j]]=[adjective_names,adjective_max]\n return collocation_result\n \n#calculates the conditional probability of a noun given adjective \ndef nounAndAdjectiveSimilarityMatrix():\n #calculating sum of the matrix\n sum_of_adj=collocation_matrix.sum(0)\n sum_of_array=sum(sum_of_adj)\n #normalizing the array\n collocation_matrix1=collocation_matrix/sum_of_array\n sum_normal_adj=collocation_matrix1.sum(0)\n collocation_matrix1 = collocation_matrix1.transpose()\n \n for i in xrange(collocation_matrix1.shape[0]):\n collocation_matrix1[i] = collocation_matrix1[i]/sum_normal_adj[i]\n collocation_result =top_members_extract(collocation_matrix1, rev=0)\n return collocation_result\n \n#calculates the conditional probability of an adjective given noun \ndef adjectiveAndNounSimilarityMatrix():\n #calculating sum of the matrix\n sum_of_adj=collocation_matrix.sum(0)\n sum_of_array=sum(sum_of_adj)\n #normalizing the array\n collocation_matrix1=collocation_matrix/sum_of_array\n sum_normal_noun=collocation_matrix1.sum(1)\n for i in xrange(collocation_matrix1.shape[0]):\n collocation_matrix1[i] = collocation_matrix1[i]/sum_normal_noun[i]\n collocation_result =top_members_extract(collocation_matrix1, rev=1)\n return collocation_result\n \n \ndef AdjNounColocMatrix():\n collocation_result =top_members_extract(collocation_matrix.copy(), rev=1)\n return collocation_result \n \ndef writerColl(write_dictionary,dbase):\n tmp=open(dbase+\"all_adj_given_noun.txt\",\"wb\")\n logger = tmp.write\n for k in write_dictionary:\n logger(\"%s|%s|%s\\n\" %(k,\" \".join(write_dictionary[k][0]),write_dictionary[k][1]))\n \n tmp.close()\n \n \n\ndef makeMCRes(ifname, docid_cols, txtcol, rfname, dbase, serializer = json.dumps):\n _mc_CSVPBSW(callMC, ifname, docid_cols, txtcol, rfname, dbase, serializer = json.dumps)\n \nif __name__ == \"__main__\":\n import time, os\n import csv\n\n \n dataset_name = 'DIL'\n docid_cols = ['SRV_ACCT_ID', 'YYYYMM'] #['PERIOD', 'WTR1_VIDEO', 'WTR2_1_INTERNET', 'WTR3_1_VOICE', 'WTR4_1_ATT', 'ACCT']\n txt_cols = ['SRV_Q21A_ISSUE_VERBATIM'] \n tmp_home = \"/home/user/Desktop/mcSurveyAnalysis/tmp\" \n dhome = os.path.join(tmp_home, dataset_name)\n\n for col in txt_cols:\n dbase = os.path.join(dhome, col, col)\n ifname = dbase + '.verbatims'\n rfname = dbase + '.mcres.csv'\n #print 'Extracting Surface Properties & Polarities'\n makeMCRes(ifname, docid_cols, col, rfname, dbase,serializer = json.dumps)\n #print(collocation_matrix.shape())\n","sub_path":"mcsurvey/scripts/scripts/colocationMatrix.py","file_name":"colocationMatrix.py","file_ext":"py","file_size_in_byte":10387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"186269574","text":"\"\"\"\r\nCopy Right : IBI.ibi \r\nThis file read configid (exaple : 'wf3') information from CVS \r\n\"\"\"\r\nfrom urllib import request \r\nfrom urllib.error import URLError, HTTPError\r\n\r\nclass SetupInfo(object) :\r\n \r\n def __init__(self, config_id, release_id, project_id):\r\n \"\"\"\r\n Arguments :\r\n config_id ='wf3'\r\n release_id ='8202'\r\n project_id ='wf' \r\n \"\"\"\r\n self.__prodid=project_id\r\n self.__confid=config_id\r\n self.__relid=release_id\r\n \r\n def __request_to_cvs(self) :\r\n \"\"\"\r\n Request to CVS with valid Project Id, Configuration Id and release id and get info \r\n \"\"\"\r\n CVS_URL='http://cvs.ibi.ibi:3007/pkg_cgi/confCgi.pl?prodid='+self.__prodid+'&confid='+self.__confid+'&relid='+self.__relid\r\n try :\r\n response_value=request.urlopen(CVS_URL).read()\r\n except HTTPError :\r\n raise ConnectionError (\"\") \r\n except URLError :\r\n raise ConnectionRefusedError (\"Could not open given '\"+ CVS_URL + \"' URL\") \r\n configid_info=response_value.decode('utf-8')\r\n if 'ERROR' in configid_info :\r\n raise KeyError(\"Error Reason : \", configid_info)\r\n else :\r\n return configid_info\r\n \r\n def get_as_dictionay(self) :\r\n \"\"\"\r\n Return configid info as dictionary format\r\n \"\"\"\r\n configid_info=self.__request_to_cvs()\r\n configid_info_list=configid_info.split('\\n')\r\n cofigid_key_and_value={}\r\n for index_value in configid_info_list :\r\n key_and_value=index_value.split(' ')\r\n if len(key_and_value)==2 :\r\n cofigid_key_and_value[key_and_value[0]]=key_and_value[1]\r\n return cofigid_key_and_value\r\n \r\n def get_key_value(self, key):\r\n \"\"\"\r\n Return specific configid key value (example key's : 'httpport', 'nodeid', 'mrpass', 'mruser') \r\n Argument :\r\n key ='nodeid'\r\n example : get_key_value('nodeid')\r\n \"\"\"\r\n configid_info_dictionay=self.get_as_dictionay()\r\n return configid_info_dictionay[key]\r\n","sub_path":"Appium/ibi/testrunner/get_setup_info.py","file_name":"get_setup_info.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"317417296","text":"import autograd.numpy as np\nfrom .activations import *\n\nclass NN:\n def __init__(self, layer_sizes, activations):\n self.num_layers = len(layer_sizes)\n self.layer_sizes = np.copy(layer_sizes)\n self.activations = np.copy(activations)\n\n def num_param(self, dim):\n xs = [dim]\n for i in range(self.num_layers):\n xs.append(self.layer_sizes[i])\n results = 0\n for i in range(self.num_layers):\n results += (1+xs[i])*xs[i+1]\n return results\n\n def w_nobias(self, w, dim):\n prev_size = dim\n start_idx = 0\n wnb = np.array([])\n for i in range(self.num_layers):\n current_size = self.layer_sizes[i]\n num_w_layer = (1+prev_size)*current_size\n w_layer = np.reshape(w[start_idx:start_idx+num_w_layer],(1+prev_size,current_size))[:prev_size]\n wnb = np.concatenate((wnb, w_layer.reshape(w_layer.size)))\n start_idx += num_w_layer\n prev_size = current_size\n return wnb\n\n def predict(self, w, x):\n dim, num_train = x.shape\n start_idx = 0\n prev_size = dim\n out = x\n bias = np.ones((1,num_train))\n for i in range(self.num_layers):\n current_size = self.layer_sizes[i]\n num_w_layer = (1+prev_size)*current_size\n w_layer = np.reshape(w[start_idx:start_idx+num_w_layer],(1+prev_size,current_size))\n out = np.concatenate((out,bias))\n out = self.activations[i](np.dot(w_layer.T, out))\n prev_size = current_size\n start_idx += num_w_layer\n return out\n\n\n","sub_path":"Multi-fidelity/code/src/NN_GP/NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"408112859","text":"from models.movable import MovableObj\nfrom models.bullet import Bullet\nfrom AI.tank import AI\nfrom PIL import Image, ImageTk\nimport settings\nimport random\nimport time\n\n\nclass Tank(MovableObj):\n def __init__(self, x1=None, y1=None, player_tank=False):\n MovableObj.__init__(self)\n self.player_tank = player_tank\n self.image_file = 'images/standard_tank.png'\n if self.player_tank:\n self.image_file = 'images/player_tank.png'\n else:\n self.ai = AI(self)\n self.image = Image.open(self.image_file)\n self.image_tk = ImageTk.PhotoImage(Image.open(self.image_file).rotate(self.angle))\n self.direction = 'Up'\n self.size = 50\n self.b = None\n self.canvas_obj = None\n if x1 is None or y1 is None:\n x1 = random.randint(0, settings.width - settings.tank_size)\n y1 = random.randint(0, settings.height - settings.tank_size)\n self.coords = x1, y1, x1 + self.size, y1 + self.size\n self.blocked_by_border = False\n self.blocked = None\n self.reloaded = True\n self.shoot_timer = 0\n self.old_shoot_timer = time.time_ns()\n\n def border_unblock(self):\n if self.blocked_by_border:\n x1, y1, x2, y2 = self.coords\n if y1 < 0:\n self.coords = x1, 0, x2, self.size\n elif y2 > settings.height:\n self.coords = x1, settings.height - self.size, x2, settings.height\n if x2 > settings.width:\n self.coords = settings.width - self.size, y1, settings.width, y2\n elif x1 < 0:\n self.coords = 0, y1, self.size, y2\n if not self.player_tank:\n self.ai.random_other_direction()\n self.rotate_image()\n\n def unblock(self, coords: tuple):\n if self.blocked:\n self.speed = 0, 0, 0, 0\n x1, y1, x2, y2 = self.coords\n if self.direction == 'Up':\n self.coords = x1, coords[3], x2, coords[3] + self.size\n elif self.direction == 'Down':\n self.coords = x1, coords[1] - self.size, x2, y1\n elif self.direction == 'Left':\n self.coords = coords[2], y1, coords[2] + self.size, y2\n elif self.direction == 'Right':\n self.coords = coords[0] - self.size, y1, coords[0], y2\n if self.player_tank:\n self.blocked = False\n\n def shoot(self):\n if self.reloaded:\n self.reloaded = False\n x1 = self.coords[0] + self.size / 2\n y1 = self.coords[1] + self.size / 2\n self.b = Bullet(x1, y1, self.direction)\n return self.b\n\n def reload_timer(self):\n self.shoot_timer = time.time_ns()\n if self.shoot_timer - self.old_shoot_timer > 1000000000:\n self.reloaded = True\n self.old_shoot_timer = self.shoot_timer\n","sub_path":"models/tank.py","file_name":"tank.py","file_ext":"py","file_size_in_byte":2909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"243778290","text":"import math\nimport time\nstart = time.time()\ndef isPrime(a):\n b=2\n while a%b!=0 and b= ret:\n ret += digit\n else:\n if sign == 1:\n return INT_MAX\n else:\n return INT_MIN\n i += 1\n return ret*sign\n \n \nif __name__ == '__main__':\n pass","sub_path":"s/string_to_integer.py","file_name":"string_to_integer.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"362828748","text":"'''\nCreate a simple lstm net for testing Keras model import. Run\nKeras simple_lstm.py example and then save that model and its\noutputs to disk.\n'''\nfrom __future__ import print_function\nfrom keras import Sequential, Model\nfrom keras.layers import Dense, Activation\n\nimport imp\nimport keras.backend as K\nimport keras\nimport numpy as np\nfrom util import save_model_details, save_model_output\n\nKERAS_VERSION = '_keras_2'\nPREFIX = 'simple_sparse_xent_mlp' + KERAS_VERSION\nOUT_DIR = 'output'\n\nprint('Entering Keras script')\nfeatures = np.random.uniform(size=[3,4])\nlabels = np.array([0,1,2])\n\nmodel = Sequential()\nmodel.add(Dense(3, input_shape=[4]))\nmodel.add(Activation('softmax'))\n\nopt = keras.optimizers.RMSprop(learning_rate=0.0001, decay=1e-6)\nmodel.compile(loss='sparse_categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])\n\nprint('Saving model details')\nsave_model_details(model, prefix=PREFIX, out_dir=OUT_DIR)\n\nexp_out = model.predict(features)\n\nprint('Saving model outputs')\nsave_model_output(model, features, exp_out, nb_examples=None, prefix=PREFIX, out_dir=OUT_DIR, labels=labels)\n\nprint('DONE!')\n","sub_path":"keras-tests/make_sparsexent_mlp.py","file_name":"make_sparsexent_mlp.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"527408630","text":"\nimport pymongo\nimport tweepy\nfrom tweepy import API, OAuthHandler\n\nfrom ramjet.engines import ioloop, thread_executor\nfrom ramjet.settings import CONSUMER_KEY, CONSUMER_SECRET, \\\n ACCESS_TOKEN, ACCESS_TOKEN_SECRET\nfrom ramjet.utils import get_conn\nfrom .base import twitter_api_parser, logger\n\n\ndef bind_task():\n def run():\n logger.info('run')\n twitter = TwitterAPI()\n thread_executor.submit(twitter.run)\n\n later = 3600\n ioloop.call_later(later, run)\n\n run()\n\n\nclass TwitterAPI:\n\n __api = None\n __auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n\n @property\n def api(self):\n logger.debug('get api')\n if self.__api:\n return self.__api\n\n return self.set_api()\n\n def set_api(self, access_token=ACCESS_TOKEN, access_token_secret=ACCESS_TOKEN_SECRET):\n self.__auth.set_access_token(access_token, access_token_secret)\n self.__api = API(self.__auth, wait_on_rate_limit=True, parser=tweepy.parsers.JSONParser())\n return self.__api\n\n def g_load_tweets(self, last_id):\n \"\"\"\n Twitter 只能反向回溯,从最近的推文开始向前查找\n \"\"\"\n logger.debug('g_load_tweets for last_id {}'.format(last_id))\n last_tweets = self.api.user_timeline(count=1)\n if not last_tweets:\n return\n\n yield last_tweets[0]\n current_id = last_tweets[0][\"id\"]\n while True:\n tweets = self.api.user_timeline(max_id=current_id, count=100)\n if len(tweets) == 1: # 到头了\n return\n\n for s in tweets:\n if s['id'] <= last_id: # 已存储\n return\n\n yield s\n if s['id'] < current_id:\n current_id = s['id']\n\n @property\n def col(self):\n return get_conn()['twitter']['tweets']\n\n @property\n def db(self):\n return get_conn()['twitter']\n\n def parse_tweet(self, tweet):\n logger.debug('parse_tweet')\n return twitter_api_parser(tweet)\n\n def get_last_tweet_id(self):\n \"\"\"\n 获取数据库里存储的最后一条推文\n \"\"\"\n logger.debug('get_last_tweet_id')\n docu = self.db['tweets'].find_one(\n {'user.id': self.current_user_id},\n sort=[('id', pymongo.DESCENDING)]\n )\n return docu and docu['id']\n\n def save_tweet(self, tweet):\n logger.debug('save_tweet')\n docu = self.parse_tweet(tweet)\n self.db['tweets'].update_one(\n {'id': docu['id']},\n {'$set': docu},\n upsert=True\n )\n\n def g_load_user(self):\n logger.debug('g_load_user_auth')\n\n for u in self.db['account'].find():\n yield u\n\n def _save_relate_tweets(self, status):\n related_ids = []\n status.get(\"in_reply_to_status_id\") and related_ids.append(status['in_reply_to_status_id'])\n status.get(\"retweeted\") and related_ids.append(status['retweeted_status']['id'])\n related_ids = filter(lambda id_: not self.db['tweets'].find_one({\"id\": id_}), related_ids)\n\n for id_ in related_ids:\n try:\n docu = self.api.get_status(id_)\n except Exception:\n logger.exception(f\"load tweet {id_} got error\")\n else:\n logger.info(f\"save tweet [{docu['user']['screen_name']}]{docu['id']}\")\n self.save_tweet(docu)\n self._save_relate_tweets(docu)\n\n def run(self):\n logger.debug('run TwitterAPI')\n count = 0\n try:\n for u in self.g_load_user():\n self.current_user_id = u['id']\n self.set_api(u['access_token'], u['access_token_secret'])\n last_id = self.get_last_tweet_id() or 1\n for count, status in enumerate(self.g_load_tweets(last_id)):\n self._save_relate_tweets(status)\n self.save_tweet(status)\n except Exception as err:\n logger.exception(err)\n else:\n logger.info('save {} tweets'.format(count))\n","sub_path":"ramjet/tasks/twitter/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"557078297","text":"from scipy.spatial import distance \nimport random\n# this function will be used to match the first user in the queue with other users in the queue.\n# it returns the index for the matched user to be popped. Match_user_dict will get a new key (user_id for one of the indivs in the pair)\n# and the value will be the user_id for the other party + chat_id (the concatenation of their user_ids)\ndef find_match_in_group(user_group, match_user_dict):\n current_user_detail = user_group[0][1]\n match_rank_dataset = [(None, None, None), (None, None, None), (None, None, None)] # Inside each tuple, [0]: euclidean distance score, [1]: match's id, [2]: match's index\n for i in range(1, len(user_group)):\n if user_group[0][0] in user_group[i][2]: # if current user has already been matched with this user, skip\n continue \n dst = distance.euclidean(user_group[0][1]['questionnaire_scores'], user_group[i][1]['questionnaire_scores'])\n if match_rank_dataset[0][0] is None: # fill up the three slots first before we start comparing distance values\n match_rank_dataset[0] = (dst, user_group[i][0], i)\n elif match_rank_dataset[1][0] is None:\n match_rank_dataset[1] = (dst, user_group[i][0], i)\n elif match_rank_dataset[2][0] is None:\n match_rank_dataset[2] = (dst, user_group[i][0], i)\n else:\n if dst < match_rank_dataset[0][0]: # shuffle the ranking depending on the distance score for the matches\n match_rank_dataset[1], match_rank_dataset[2] = match_rank_dataset[0], match_rank_dataset[1]\n match_rank_dataset[0] = (dst, user_group[i][0], i)\n elif dst < match_rank_dataset[1][0]:\n match_rank_dataset[2] = match_rank_dataset[1]\n match_rank_dataset[1] = (dst, user_group[i][0], i)\n elif dst < match_rank_dataset[2][0]:\n match_rank_dataset[2] = (dst, user_group[i][0], i)\n if match_rank_dataset[0][0] == 0 and match_rank_dataset[1][0] == 0 and match_rank_dataset[2][0] == 0: # If we have found three matches with perfect score, we stop looking for people\n break\n # compile final matches (removing None data if we were not able to find 3 matches) as (user_id, chat_id)\n final_matches_for_current_user = [(x[1], str(min(x[1], user_group[0][0])) + '_' + str(max(x[1], user_group[0][0]))) for x in match_rank_dataset if x[0] is not None]\n # add final matches to match_uer_dict[current_user]. At the api level, the dictionary will be iterated through and match relationship will be updated and mirrored\n match_user_dict[user_group[0][0]] = final_matches_for_current_user\n # append matched user_ids for all involved users to track accumulated matches for this cycle\n user_group[0][2].append([x[0] for x in final_matches_for_current_user])\n\n other_users_to_be_removed_from_user_group = [] # basically all users that do not need matches anymore. \n for user in match_rank_dataset: # add one more match (current user) to the other users\n if user[2] is not None:\n user_group[user[2]][2].append(user_group[0][0]) \n if len(user_group[user[2]][2]) >= 3:\n other_users_to_be_removed_from_user_group.append(user[2]) # add user to list of users who don't need matches\n return other_users_to_be_removed_from_user_group\n\ndef form_groups(all_users_dict):\n platonic_users = []\n non_platonic_users = []\n for user_id, user_details in all_users_dict.items():\n if user_details['want_match'] and len(user_details['questionnaire_scores']) == 17:\n if user_details['want_platonic']:\n platonic_users.append((user_id, user_details, [])) # the empty list added in the tuple is meant to track the number of new matches a user has\n else:\n non_platonic_users.append((user_id, user_details, []))\n return platonic_users, non_platonic_users\n\ndef find_unmatched_users(user_group):\n main_user = user_group[0]\n other_users = user_group[1:]\n former_matches_of_main_user = set(main_user[1]['active_chat_partners'])\n unmatched_users = [main_user]\n unmatched_user_indexes = [0]\n for index, other_user in enumerate(other_users):\n other_user_id = other_user[0]\n other_user_new_matches = other_user[2]\n if other_user_id not in former_matches_of_main_user and len(other_user_new_matches) < 3: # make sure we only matched people whom the main user have not interacted with before and the person must also not have 3 matches in this matching cycle\n unmatched_users.append(other_user)\n unmatched_user_indexes.append(index+1)\n return unmatched_user_indexes, unmatched_users\n\ndef matching_algo_for_user_group(usergroup, match_user_dict):\n user_group = usergroup.copy()\n while len(user_group) > 0:\n unmatched_user_indexes, unmatched_users = find_unmatched_users(user_group)\n if len(unmatched_users) == 1 and len(unmatched_users[0][2]) == 0:\n if match_user_dict.get('unmatched') is None:\n match_user_dict['unmatched'] = [unmatched_users[0]]\n else:\n match_user_dict['unmatched'].append(unmatched_users[0])\n del user_group[0]\n else:\n index_to_be_removed = find_match_in_group(unmatched_users, match_user_dict) #the index here refers to the index of the unmatched_users list\n # print('index_to_be_removed', index_to_be_removed)\n # print('unmatched_user_indexes', unmatched_user_indexes)\n # print('user_group', user_group)\n for index in sorted(index_to_be_removed, reverse=True): # sort the indices so that we remove from the back so we don't mess up the order/index\n del user_group[unmatched_user_indexes[index]] # translate unmatched_user_group id to normal user id and delete user from user_group\n del user_group[0] # removed current user from user_group since they either have 3 matches or can't be matched with anyone already (not enough people)\n\n\n\n# takes in a dictionary with user_ids as keys and user_details as value\n# returns a dictionary with key (user_id for one of the indivs in the pair)\n# and the value will be the user_id for the other party + chat_id (the concatenation of their user_ids)\n# it also returns a list of tuples (user_id, user_details) that contain individuals who are not matched\ndef matching_algo(all_users_dict):\n match_user_dict = dict()\n platonic_users, non_platonic_users = form_groups(all_users_dict)\n matching_algo_for_user_group(platonic_users, match_user_dict)\n matching_algo_for_user_group(non_platonic_users, match_user_dict)\n still_unmatched = []\n if match_user_dict.get('unmatched') is not None:\n unmatched = match_user_dict['unmatched']\n for indiv in unmatched:\n indiv_id = indiv[0]\n random.shuffle(non_platonic_users)\n for non_platonic_user in non_platonic_users:\n if indiv_id not in set(non_platonic_user[1]['active_chat_partners']) and indiv_id != non_platonic_user[0] :\n match_user_dict[indiv_id] = (non_platonic_user[0], str(min(indiv[0], non_platonic_user[0])) + '_' + str(max(indiv[0], non_platonic_user[0])))\n break\n if match_user_dict.get(indiv_id) is None:\n still_unmatched.append(indiv)\n else:\n break\n return match_user_dict, still_unmatched\n\ndef find_match_for_new_user(new_user_id, all_users_dict):\n match_user_dict = dict()\n still_unmatched = []\n platonic_users, non_platonic_users = form_groups(all_users_dict)\n # we are only working with platonic users for this version\n users_pool = platonic_users.copy()\n print('users_pool', users_pool)\n users_pool = sorted(users_pool, key=lambda tup: len(tup[1]['matched_count'])) # sort to ascending order of number of match_counts. The goal is to match new user with old users with low match counts\n for index, value in enumerate(users_pool): # swap new user to the front of the list. The user that was originally at the start of the list should either have zero or a really low match count\n if value[0] == new_user_id:\n users_pool[index], users_pool[0] = users_pool[0], users_pool[index]\n break\n index_to_be_removed = find_match_in_group(users_pool, match_user_dict) #the index here refers to the index of the unmatched_users list\n return match_user_dict, still_unmatched\n\n\nif __name__ == \"__main__\":\n # PYTHONHASHSEED=1833\n\n # random.seed(10)\n def create_all_users_dict(num_users):\n users_dict = dict()\n for i in range(num_users):\n users_dict[i] = {'want_match': True, 'want_platonic': False, 'questionnaire_scores': [random.randint(0, 5), random.randint(0, 5), random.randint(0, 5), random.randint(0, 5), random.randint(0, 5)], 'active_chat_partners':[]}\n return users_dict\n user_dict = create_all_users_dict(30)\n\n # print(user_dict)\n print(matching_algo(user_dict))\n \n\n\n\n","sub_path":"matching_algorithm.py","file_name":"matching_algorithm.py","file_ext":"py","file_size_in_byte":9084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"466596690","text":"import parser\nWEBTOON_ID = 651673\n'''\n네이버 웹툰 크롤러\n\n환경 세팅\n 1. alt + F12로 터미널 열기\n 2. 터미널에서 pyenv version입력해서 가상환경이 적용된 터미널인지 확인\n 3. pip 이용해서 BeautifulSoup4, requests설치\n pip install beautifulsoup4\n pip install requests\n pip install lxml\n'''\n\nresult = parser.get_webtoon_episode_list(WEBTOON_ID)\n# result = parser.get_episode_list_from_page(WEBTOON_ID)\n\nf = open('webtoon.html', 'w')\nf.write('')\nfor item in result:\n f.write('''
    \n {title}\n | {created}\n
    '''.format(\n href=item['link'],\n title=item['title'],\n created=item['created']\n ))\nf.write('')\nf.close()\n","sub_path":"Projects/python/crawling/crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"372720543","text":"from entropy import entropy\n\n\ndef informationgain(data, param, targetparam):\n freq = {}\n subentropy = 0.0\n\n for i in data:\n if (freq.has_key(i[param])):\n freq[i[param]] += 1.0\n else:\n freq[i[param]] = 1.0\n\n for val in freq.keys():\n val_prob = freq[val] / sum(freq.values())\n data_subset = [i for i in data if i[param] == val]\n subentropy += val_prob * entropy(data_subset, targetparam)\n\n return (entropy(data, targetparam) - subentropy)\n","sub_path":"Decision Tree/informationgain.py","file_name":"informationgain.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"645117987","text":"# To create sessions of 4 minutes from the specified beggining and end\ndef session(beg, en):\n tb = beg # tb is the time of beggining of the i-th session, the first session starts at the specified beggining\n te = 0 # te is the time of end of the session, it'll be 4 minutes after the tb\n ses = [];\n while (tb < en):\n te = tb + timedelta(minutes=4)\n if (te > en): # if the time exceed the specified end, te = te\n te = en\n microses = [tb, te] # 4 minutes session\n ses.append(\n microses) # list of all the sessions, it's possible to access to a particular session by accessing one of the indeces of the ses\n tb = te\n\n return ses","sub_path":"ShortSession.py","file_name":"ShortSession.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"343306017","text":"#!/usr/bin/env python\n'''\n Module contains information about health of the various targets\n'''\n\nfrom py.core.logging import log_info\n\nHEALTHY = 'healthy'\nEMPTY = 0\nONE = 1\n\ndef target_group_health_status(client, target_group):\n \"\"\"Helth check lookups for given target group.\"\"\"\n\n targets = client.describe_target_health(\n TargetGroupArn=target_group\n )\n\n log_info(\"Found `{}` targets.\".format(len(targets['TargetHealthDescriptions'])))\n result = {}\n for target in targets['TargetHealthDescriptions']:\n state = target['TargetHealth']['State']\n port = target['Target']['Port']\n if state == HEALTHY:\n log_info('State: `{}`. Port: `{}`.'.format(state, port))\n else:\n description = target['TargetHealth']['Description']\n log_info('State: `{}`. Port: `{}`. Description: `{}`'.format(state, port, description))\n result[state] = result.get(state, EMPTY) + ONE\n\n return result\n","sub_path":"aws/aws-py/py/elbv2/health_check.py","file_name":"health_check.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"180183706","text":"\"\"\"OpenID IdP Validation unit test package\n\nNERC DataGrid Project\n\"\"\"\n__author__ = \"P J Kershaw\"\n__date__ = \"16/07/09\"\n__copyright__ = \"(C) 2009 Science and Technology Facilities Council\"\n__license__ = \"BSD - see LICENSE file in top-level directory\"\n__contact__ = \"Philip.Kershaw@stfc.ac.uk\"\n__revision__ = '$Id$'\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\nimport os\nimport unittest\nfrom ndg.security.server.test.base import BaseTestCase, mk_data_dirpath\nfrom ndg.security.server.wsgi.openid.relyingparty.validation import (\n IdPValidator, IdPValidationDriver, IdPInvalidException, \n SSLIdPValidationDriver)\n \n \nclass ProviderWhitelistValidator(IdPValidator):\n \"\"\"Test stub for Whitelist validator\"\"\"\n def __init__(self):\n pass\n \n def initialize(self, **parameters):\n '''@raise ConfigException:''' \n assert('config-file' in parameters)\n \n def validate(self, idpEndpoint, idpIdentity):\n '''@raise IdPInvalidException:\n @raise ConfigException:''' \n pass\n\n\nclass ProviderIdentifierTestValidator(IdPValidator):\n \"\"\"Test stub for identifier validator - fixed to reject all IdPs\"\"\"\n def __init__(self):\n pass\n\n def initialize(self, **parameters):\n '''@raise ConfigException:''' \n assert('config-file' in parameters)\n \n def validate(self, idpEndpoint, idpIdentity):\n '''Test method hard wired to raise an invalid IdP exception\n @raise IdPInvalidException:\n @raise ConfigException:''' \n raise IdPInvalidException(\"%s is invalid\" % idpEndpoint)\n\n\nclass DiscoveryInfoPlaceHolder(object):\n getOPEndpoint = lambda self: 'https://localhost/openid/provider'\n\n \nclass IdentifierPlaceHolder(object):\n getIdentifier = lambda self: 'myid'\n\ntry:\n from M2Crypto import X509\n m2crypto_installed = True\n \n class X509StoreCtxPlaceHolder(object):\n x509CertFilePath = mk_data_dirpath(os.path.join('pki', 'localhost.crt'))\n \n def get1_chain(self):\n return [X509.load_cert(X509StoreCtxPlaceHolder.x509CertFilePath)]\n\nexcept ImportError:\n m2crypto_installed = False\n \n\nclass IdPValidationTestCase(BaseTestCase):\n thisDir = os.path.dirname(os.path.abspath(__file__))\n IDP_CONFIG_FILEPATH = os.path.join(thisDir, 'idpvalidator.xml')\n os.environ['NDGSEC_UNITTEST_IDPVALIDATION_DIR'] = thisDir\n \n \n def test01IdPConfigFileEnvVarNotSet(self):\n identifier = IdentifierPlaceHolder()\n discoveries = [DiscoveryInfoPlaceHolder()]\n \n idPValidationDriver = IdPValidationDriver()\n validDiscoveries = idPValidationDriver.performIdPValidation(identifier,\n discoveries)\n # Expect no discoveries returned because the IDP_CONFIG_FILE \n # environment variable is not set\n self.assert_(len(validDiscoveries) == 1)\n \n def test02WithIdPConfigFile(self):\n identifier = 'https://pjk.badc.rl.ac.uk'\n \n os.environ[IdPValidationDriver.IDP_CONFIG_FILEPATH_ENV_VARNAME\n ] = IdPValidationTestCase.IDP_CONFIG_FILEPATH\n \n idPValidationDriver = IdPValidationDriver()\n validDiscoveries = idPValidationDriver.performIdPValidation(identifier)\n self.assert_(len(validDiscoveries) == 2)\n \n @unittest.skipIf(not m2crypto_installed, \"Skipping IdPValidationTestCase \"\n \"M2Crypto is not installed.\")\n def test03SSLValidation(self):\n idpConfigFilePath = os.path.join(IdPValidationTestCase.thisDir, \n 'ssl-idp-validator.xml')\n idPValidationDriver = SSLIdPValidationDriver(\n idpConfigFilePath=idpConfigFilePath)\n \n # preVerifyOK set to 1 to indicate all is otherwise OK with \n # verification\n idPValidationDriver(1, X509StoreCtxPlaceHolder())\n \n \nif __name__ == \"__main__\":\n unittest.main() \n","sub_path":"ndg/security/server/test/unit/openid/relyingparty/validation/test_validation.py","file_name":"test_validation.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"304685428","text":"import task\n\nclass dec01_1(task.str_task):\n def run(self, data):\n sum = 0\n if len(data) > 1:\n for idx, d in enumerate(data):\n if data[idx - 1] == d:\n sum = sum + int(d)\n return sum\n\nclass dec01_2(task.str_task):\n def run(self, data):\n sum = 0\n half = int(len(data) / 2)\n for idx, d in enumerate(data[:half]):\n if d == data[half + idx]:\n sum = sum + int(d) * 2\n return sum\n\nif __name__ == \"__main__\":\n dec01_1().runtests()\n dec01_2().runtests()\n","sub_path":"2017/python/dec01.py","file_name":"dec01.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"564027102","text":"import subprocess as sub\n\n\nprint(\"\\n --- Program Start ---\\n\")\n\n#read file contents\nfile_to_read = \"ex.txt\"\nfile_object = open(file_to_read,\"r\")\nfile_contents = file_object.read()\nfile_object.close()\nprint (file_contents)\n\n#create a file that graphiz can look at.\ndot_file_name = file_to_read + \".dot\"\ndot_file_contents = \"digraph Test {\\n\"+file_contents+\"\\n}\"\nfile_object = open(dot_file_name,\"w\")\nfile_object.write(dot_file_contents)\nfile_object.close()\nsub.call([\"dot\",\"-Tpng\", \"-O\", \"ex.txt.dot\"])\n\n#remove the dot file\nsub.call([\"rm\",dot_file_name])\n\n#look at the graph\nsub.call([\"open\",dot_file_name+\".png\"])\n\n\nprint(\"\\n --- Program Finish ---\\n\")\n","sub_path":"trial/create_graph.py","file_name":"create_graph.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"330320149","text":"import time\n\ndef insertion_sort(list):\n for index in range(1, len(list)):\n position = index\n current_value = list[index]\n \n while(position>0 and list[position-1]>current_value):\n list[position] = list[position-1]\n position = position -1\n \n list[position] = current_value\n \n return list \n \nif __name__==\"__main__\":\n lst_des = [54,26,93,17,77,31,44,55,20]\n print(lst_des)\n antes = time.time()\n lst_ord = insertion_sort(lst_des)\n depois = time.time()\n print(lst_ord)\n print(\"Tempo de execução: \", depois - antes)","sub_path":"semana5/algoritimo_insertion_sort.py","file_name":"algoritimo_insertion_sort.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"247219947","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n主要测试内容:\n 模拟修改开服时间计划/项目下架计划/合服计划等\n web --> cmdb --> 运维管理机 --> cmdb\n使用方法:\n 1. 修改TEST_OPTION参数\n 2. 运行脚本 /data/code/cy_devops/bin/python3 /data/www/cmdb/ops/tests.py\n\"\"\"\nimport requests\nimport os\nimport django\nimport uuid\nimport sys\nimport json\nimport time\nimport random\nfrom cmdb.settings import PRODUCTION_ENV\n\npathname = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, pathname)\nsys.path.insert(0, os.path.abspath(os.path.join(pathname, '..')))\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"cmdb.settings\")\ndjango.setup()\n\nWEB_CMDB_URL = 'http://127.0.0.1:8000/api_web/'\nOPS_CMDB_URL = 'http://127.0.0.1:8000/api/'\nCMDB_URL = 'http://127.0.0.1:8000/api/'\nWEB_CMDB_TOKEN = '431b65c0a00dfa00399a8e36c47f54ad5d3686d5'\nOPS_CMDB_TOKEN = 'c6e7724396561cfd9004718330fc8a6dcbaf6409'\n\"\"\"\n1. 修改开服时间计划\n2. 项目下架计划\n3. 区服管理回调测试\n4. 单个区服迁服回调测试\n5. web新增cmdb合服计划\n6. web新增cmdb开服计划\n\"\"\"\nTEST_OPTION = [2]\n\nfrom ops.models import ModifyOpenSrvSchedule\nfrom ops.models import GameServerOff\n\n\ndef get_api(url, query_param, token):\n \"\"\"get请求\"\"\"\n msg = 'ok'\n success = True\n try:\n res = requests.get(url + query_param, headers={'Authorization': 'token {}'.format(token)})\n if res.status_code == 200:\n r = res.json()\n print(r)\n if r.get('resp', 1) != 1 or not r.get('success', True):\n raise Exception(r.get('reason', '') + r.get('msg', ''))\n else:\n raise Exception(res.status_code)\n except Exception as e:\n msg = str(e)\n success = False\n finally:\n return success, msg\n\n\ndef post_api(url, token, **kwargs):\n \"\"\"post请求\"\"\"\n msg = 'ok'\n success = True\n try:\n headers = {'Accept': 'application/json', 'Authorization': 'Token ' + token}\n data = kwargs.get('data', None)\n json = kwargs.get('json', None)\n if data:\n res = requests.post(url, data=data, headers=headers, timeout=60, verify=False)\n elif json:\n res = requests.post(url, json=json, headers=headers, timeout=60, verify=False)\n else:\n raise Exception('缺少post参数')\n if res.status_code == 200:\n r = res.json()\n print(r)\n if r.get('resp', 1) != 1 or not r.get('success', True):\n raise Exception(r.get('reason', '') + r.get('msg', ''))\n else:\n raise Exception(res.status_code)\n except Exception as e:\n msg = str(e)\n success = False\n finally:\n return success, msg\n\n\ndef test_modsrv_opentime():\n \"\"\"测试修改开服时间\"\"\"\n success = True\n msg = 'ok'\n try:\n \"\"\"web调用cmdb接口\"\"\"\n url = WEB_CMDB_URL + 'ModifySrvOpenTimeSchedule.Create/'\n token = WEB_CMDB_TOKEN\n post_data = {\n \"project\": \"cyh5s7\",\n \"area\": \"cn\",\n \"srv_id\": \"1600001\", # web区服id\n \"open_time\": \"1581419600\",\n }\n success, msg = post_api(url=url, token=token, data=post_data)\n if not success:\n raise Exception(msg)\n\n time.sleep(5)\n\n \"\"\"运维管理机回调cmdb\"\"\"\n url = OPS_CMDB_URL + 'ModSrvOpenTimeCallBack/'\n token = OPS_CMDB_TOKEN\n modify_schedule = ModifyOpenSrvSchedule.objects.last()\n # modify_schedule = ModifyOpenSrvSchedule.objects.get(uuid='455a7512-75fa-11e9-95e4-000c29bedb81')\n for task in modify_schedule.modifyopensrvscheduledetail_set.all():\n post_data = {\n \"uuid\": modify_schedule.uuid,\n \"sid\": task.game_server.sid,\n \"result\": True,\n \"msg\": \"修改开服时间成功\",\n }\n success, msg = post_api(url=url, token=token, json=post_data)\n except Exception as e:\n success = False\n msg = str(e)\n finally:\n return success, msg\n\n\ndef test_new_server_callback():\n \"\"\"测试新区服回调\"\"\"\n result = True\n srv_id = str(random.randint(10, 99)) + '_' + str(random.randint(100, 999))\n sid = str(random.randint(10000, 99999))\n api_name = '新区服回调-' + srv_id + '-'\n msg = api_name + '接口调用成功'\n try:\n url = CMDB_URL + 'newSrvCallBack?'\n query_param = 'project_type=1&game=snqxz&game_type=1&pf_name=37&srv_id=' + srv_id + '&srv_name=双线1服&ip=172.16.149.11&client_version=0001311&server_version=1937133&cdn_root_url=res.qxz.zhi-ming.com&cdn_dir=qq_s1&room=QQ云&host=snqxz_boke_210.61.161.63&open_time=1381419600&area_name=大陆&sid=' + sid\n success, reason = get_api(url, query_param, OPS_CMDB_TOKEN)\n if not success:\n raise Exception(reason)\n except Exception as e:\n msg = api_name + '接口调用失败:' + str(e)\n result = False\n finally:\n return result, msg, sid\n\n\ndef test_gameserver_off():\n \"\"\"测试项目下架计划\"\"\"\n success = True\n msg = 'ok'\n try:\n def create_and_send():\n \"\"\"创建新区服模拟区服下架\"\"\"\n print('创建新区服模拟区服下架')\n result, msg, sid = test_new_server_callback()\n srv_list = []\n srv_list.append(int(sid))\n srv_id = str(srv_list)\n \"\"\"web调用cmdb接口\"\"\"\n print('web调用cmdb接口')\n url = WEB_CMDB_URL + 'GameServerOff.Create/'\n token = WEB_CMDB_TOKEN\n post_data = {\n \"project\": \"snqxz\",\n \"area\": \"cn\",\n \"srv_id\": srv_id, # web区服id\n \"off_time\": \"1581419600\",\n \"web_callback_url\": \"https://xxxxxx/\",\n }\n success, msg = post_api(url=url, token=token, data=post_data)\n if not success:\n raise Exception(msg)\n\n create_and_send()\n create_and_send()\n\n time.sleep(3)\n\n \"\"\"运维管理机回调cmdb\"\"\"\n print('运维管理机回调cmdb')\n url = OPS_CMDB_URL + 'GameServerOffCallBack/'\n token = OPS_CMDB_TOKEN\n game_server_off = GameServerOff.objects.last()\n for task in game_server_off.gameserveroffdetail_set.all():\n post_data = {\n \"uuid\": game_server_off.uuid,\n \"srv_id\": task.game_server.sid,\n \"result\": False,\n \"msg\": \"原因:未知\",\n }\n success, msg = post_api(url=url, token=token, json=post_data)\n\n \"\"\"删除下架假话\"\"\"\n print('删除下架假话')\n url = WEB_CMDB_URL + 'GameServerOff.Delete/'\n token = WEB_CMDB_TOKEN\n game_server_off = GameServerOff.objects.last()\n for task in game_server_off.gameserveroffdetail_set.all():\n post_data = {\n \"project\": \"snqxz\",\n \"area\": \"cn\",\n \"srv_id\": json.dumps([task.game_server.sid]), # web区服id\n \"off_time\": \"1581419600\",\n \"web_callback_url\": \"https://xxxxxx/\",\n }\n success, msg = post_api(url=url, token=token, data=post_data)\n except Exception as e:\n success = False\n msg = str(e)\n finally:\n return success, msg\n\n\ndef test_game_server_action():\n \"\"\"测试区服管理回调操作\"\"\"\n success = True\n msg = 'ok'\n try:\n url = OPS_CMDB_URL + 'GameServerActionCallback/'\n token = OPS_CMDB_TOKEN\n post_data = {\n \"uuid\": \"54754358-8c2d-11e9-a3cb-000c292acc0b\",\n \"project\": \"jyjh\",\n \"srv_id\": \"cross_yy_4\",\n \"action_type\": \"start\",\n \"result\": 1,\n \"msg\": \"操作成功\"\n }\n success, msg = post_api(url=url, token=token, json=post_data)\n if not success:\n raise Exception(msg)\n except Exception as e:\n msg = str(e)\n success = False\n finally:\n return success, msg\n\n\ndef test_migration_callback():\n \"\"\"测试单个区服迁服回调\"\"\"\n success = True\n token = OPS_CMDB_TOKEN\n url = OPS_CMDB_URL + \"HostMigrationCallBack/\"\n sid = '500000000'\n post_data = {\n 'uuid': 'a3dfa844-8cc2-11e9-89d5-000c292acc0b-migrate',\n \"sid\": sid,\n \"result\": True,\n \"msg\": \"迁服成功\",\n }\n success, msg = post_api(url=url, token=token, json=post_data)\n if not success:\n raise Exception(msg)\n return success, '测试迁服回调'\n\n\ndef test_game_srv_merge_create():\n \"\"\"测试创建合服计划\"\"\"\n success = True\n msg = 'ok'\n try:\n url = WEB_CMDB_URL + 'GameServerMerge.Create/'\n token = WEB_CMDB_TOKEN\n post_data = {\n 'data': json.dumps([\n {\"main_srv\": \"2100001\", \"slave_srv\": \"300778\", \"group_id\": \"130\",\n \"merge_time\": 1568099875, \"project\": \"snqxz\"},\n ]),\n }\n success, msg = post_api(url=url, token=token, data=post_data)\n if not success:\n raise Exception(msg)\n except Exception as e:\n msg = str(e)\n success = False\n finally:\n return success, msg\n\n\ndef test_install_srv_create():\n \"\"\"测试装服计划\"\"\"\n success = True\n msg = 'ok'\n try:\n url = WEB_CMDB_URL + 'InstallGameServer.Create/'\n token = WEB_CMDB_TOKEN\n post_data = [\n {\n \"project\": \"ssss\", \"area\": \"大陆\", \"pf_id\": \"178\",\n \"pf_name\": \"178pop\", \"srv_num\": \"256\", \"srv_name\": \"双线一服\",\n \"server_version\": \"xxxx\", \"client_version\": \"xxxx\", \"client_dir\": \"xxxx\", \"open_time\": \"1531447135\",\n \"status\": \"0\", \"qq_srv_id\": \"100\", \"unique_srv_id\": \"132161841\", \"srv_type\": \"1\", \"srv_farm_id\": \"0\",\n \"srv_farm_name\": \"default\"\n },\n {\n \"project\": \"csxy\", \"area\": \"大陆\", \"pf_id\": \"70\",\n \"pf_name\": \"xinghuiorg\", \"srv_num\": \"1000\", \"srv_name\": \"测试一服\",\n \"server_version\": \"xxxx\", \"client_version\": \"xxxx\", \"client_dir\": \"xxxx\", \"open_time\": \"1531447135\",\n \"status\": \"0\", \"qq_srv_id\": \"100\", \"unique_srv_id\": \"984111364\", \"srv_type\": \"1\", \"srv_farm_id\": \"0\",\n \"srv_farm_name\": \"default2\"\n }\n ]\n success, msg = post_api(url=url, token=token, json=json.dumps(post_data))\n if not success:\n raise Exception(msg)\n except Exception as e:\n msg = str(e)\n success = False\n finally:\n return success, msg\n\n\nif __name__ == '__main__':\n if not PRODUCTION_ENV:\n for option in TEST_OPTION:\n if option == 1:\n print(test_modsrv_opentime())\n if option == 2:\n print(test_gameserver_off())\n if option == 3:\n print(test_game_server_action())\n if option == 4:\n print(test_migration_callback())\n if option == 5:\n print(test_game_srv_merge_create())\n if option == 6:\n print(test_install_srv_create())\n","sub_path":"ops/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":11208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"45968516","text":"from starlette.applications import Starlette\nfrom starlette.authentication import requires\nfrom starlette.middleware.authentication import AuthenticationMiddleware\nfrom starlette.middleware.sessions import SessionMiddleware\nfrom starlette.responses import JSONResponse\nfrom starlette.testclient import TestClient\n\nfrom starlette_auth import app as auth_app\nfrom starlette_auth.backends import ModelAuthBackend\nfrom starlette_auth.tables import Scope, User\n\n\n@requires([\"unauthenticated\"])\ndef unauthed(request):\n return JSONResponse({\"status\": \"ok\"})\n\n\n@requires([\"authenticated\"])\ndef authed(request):\n return JSONResponse({\"status\": \"ok\"})\n\n\n@requires([\"authenticated\", \"read\"])\ndef read(request):\n return JSONResponse({\"status\": \"ok\"})\n\n\n@requires([\"authenticated\", \"write\"])\ndef write(request):\n return JSONResponse({\"status\": \"ok\"})\n\n\ndef create_app():\n app = Starlette()\n app.mount(path=\"/auth\", app=auth_app, name=\"auth\")\n app.add_middleware(AuthenticationMiddleware, backend=ModelAuthBackend())\n app.add_middleware(SessionMiddleware, secret_key=\"secret\")\n app.add_route(\"/unauthed\", unauthed)\n app.add_route(\"/authed\", authed)\n app.add_route(\"/read\", read)\n app.add_route(\"/write\", write)\n return app\n\n\ndef test_scoped_endpoints(session):\n user = User(email=\"user@example.com\")\n user.set_password(\"password\")\n\n read_scope = Scope(code=\"read\")\n write_scope = Scope(code=\"write\")\n\n session.add_all([user, read_scope, write_scope])\n session.flush()\n\n app = create_app()\n\n with TestClient(app) as client:\n\n assert client.get(\"/unauthed\").status_code == 200\n assert client.get(\"/authed\").status_code == 403\n assert client.get(\"/read\").status_code == 403\n assert client.get(\"/write\").status_code == 403\n\n login = client.post(\n \"/auth/login\", data={\"email\": \"user@example.com\", \"password\": \"password\"}\n )\n\n assert login.status_code == 302\n\n assert client.get(\"/unauthed\").status_code == 403\n assert client.get(\"/authed\").status_code == 200\n assert client.get(\"/read\").status_code == 403\n assert client.get(\"/write\").status_code == 403\n\n user.scopes.append(read_scope)\n session.add(user)\n session.flush()\n\n assert client.get(\"/unauthed\").status_code == 403\n assert client.get(\"/authed\").status_code == 200\n assert client.get(\"/read\").status_code == 200\n assert client.get(\"/write\").status_code == 403\n\n user.scopes.append(write_scope)\n session.add(user)\n session.flush()\n\n assert client.get(\"/unauthed\").status_code == 403\n assert client.get(\"/authed\").status_code == 200\n assert client.get(\"/read\").status_code == 200\n assert client.get(\"/write\").status_code == 200\n","sub_path":"tests/test_scoped_endpoints.py","file_name":"test_scoped_endpoints.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"146822668","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Apr 21 19:32:39 2018\r\n\r\n@author: DELL\r\n\"\"\"\r\nfrom scrapy import Request\r\nfrom scrapy.spiders import Spider\r\nfrom mypy1.items import Mypy1Item\r\n\r\nimport json\r\nimport re\r\n\r\nclass DoubanActionSpider(Spider):\r\n name = 'douban_ajax'\r\n headers = {\r\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36', \r\n }\r\n count = 0\r\n \r\n def start_requests(self):\r\n url = 'https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&start=0&limit=20'\r\n yield Request(url, headers = self.headers)\r\n \r\n def parse(self,response):\r\n item = Mypy1Item()\r\n datas = json.loads(response.body.decode('utf-8'))\r\n \r\n if self.count<2:\r\n for data in datas:\r\n item['ranking'] = data['rank']\r\n item['score'] = data['score'] #rating?\r\n item['movie_name'] = data['title']\r\n item['score_num'] = data['vote_count']\r\n yield item\r\n \r\n page_num = re.search(r'start=(\\d+)', response.url).group(1) #group(1)?\r\n page_num = 'start=' + str(int(page_num)+20)\r\n next_url = re.sub(r'start=\\d+', page_num, response.url)\r\n yield Request(next_url, headers = self.headers)\r\n self.count += 1\r\n\r\n \r\n \r\n \r\n \r\n","sub_path":"douban_action_spider.py","file_name":"douban_action_spider.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"318350002","text":"from PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import (QGridLayout, QLabel, QPushButton, QWidget, QSlider,\n QScrollArea, QSpinBox, QTabWidget, QErrorMessage, QFileDialog)\nimport math\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport io\nimport ReportPDF\n\n# ---- Constant ----\nURL_GITHUB = 'https://raw.githubusercontent.com/dramco-iwast/docs/master/Power_Data.csv'\nDEBUG = False\nBATTERY = 500 # in mAh\nERROR_AVER_CUR_SLEEP = 1.26\nERROR_AVER_CUR_TX = 8000\nERROR_DATA_TX_TIME = [24.12, 35.05, 45.5, 126.15, 249.12, 495.61]\nERROR_DATA_TX_TIME_ACC = [30.06, 55.71, 107, 127.29, 332.24, 661.31]\n\n\nclass PowerReport(QWidget):\n \"\"\"Second window to manage the power report\"\"\"\n\n def __init__(self, data_acc,\n id_config_1=False, poll_interval_1=False, thresholds_1=False,\n id_config_2=False, poll_interval_2=False, thresholds_2=False,\n id_config_3=False, poll_interval_3=False, thresholds_3=False,\n id_config_4=False, poll_interval_4=False, thresholds_4=False,\n id_config_5=False, poll_interval_5=False, thresholds_5=False,\n id_config_6=False, poll_interval_6=False, thresholds_6=False,):\n super().__init__()\n\n self.resize(1000, 600)\n self.move(300, 150)\n\n # --------------------------------------------------------------------------------------------------------------\n # DECLARE ATTRIBUTES\n # --------------------------------------------------------------------------------------------------------------\n\n self.__data_acc = data_acc # Data accumulation ? (if 'False' -> No Data acc)\n self.__id = [] # ID(s) of the board(s) used\n self.__poll_interval = [] # Polling(s) Interval(s) (if 'False' -> No Polling)\n self.__thresholds = [] # Threshold(s) ? (if 'False' -> No Thresholds)\n self.__id_name = [] # ID(s) name(s) of the board(s) used\n self.__number_metrics = [] # Number(s) of metrics of each boards\n self.__lora_spread_factor = 11 # LoRa spreading factor (default -> 11)\n\n self.__id.append(id_config_1) # ID of the configuration 1\n self.__poll_interval.append(poll_interval_1) # Polling interval in min ? (if 'False' -> No Polling)\n self.__thresholds.append(thresholds_1) # Thresholds ? (if 'False' -> No Thresholds)\n\n self.__id.append(id_config_2) # ID of the configuration 2\n self.__poll_interval.append(poll_interval_2) # Polling interval in min ? (if 'False' -> No Polling)\n self.__thresholds.append(thresholds_2) # Thresholds ? (if 'False' -> No Thresholds)\n\n self.__id.append(id_config_3) # ID of the configuration 3\n self.__poll_interval.append(poll_interval_3) # Polling interval in min ? (if 'False' -> No Polling)\n self.__thresholds.append(thresholds_3) # Thresholds ? (if 'False' -> No Thresholds)\n\n self.__id.append(id_config_4) # ID of the configuration 4\n self.__poll_interval.append(poll_interval_4) # Polling interval in min ? (if 'False' -> No Polling)\n self.__thresholds.append(thresholds_4) # Thresholds ? (if 'False' -> No Thresholds)\n\n self.__id.append(id_config_5) # ID of the configuration 5\n self.__poll_interval.append(poll_interval_5) # Polling interval in min ? (if 'False' -> No Polling)\n self.__thresholds.append(thresholds_5) # Thresholds ? (if 'False' -> No Thresholds)\n\n self.__id.append(id_config_6) # ID of the configuration 6\n self.__poll_interval.append(poll_interval_6) # Polling interval in min ? (if 'False' -> No Polling)\n self.__thresholds.append(thresholds_6) # Thresholds ? (if 'False' -> No Thresholds)\n\n # Thresholds parameters (depends on the board -> we use an array for each parameters)\n self.__number_possible_thresh = [] # Nbr possible thresholds when there is a threshold interval\n self.__number_thresh_exceeded = [] # Nbr of excedeed thresholds (must be choose by the user !)\n self.__number_thresh_not_exceeded = [] # Nbr of non-exceeded thresholds\n self.__energy_thresh_exceeded = [] # Energy of an exceeded threshold event [uWh]\n self.__energy_thresh_not_exceeded = [] # Energy of a non-exceeded threshold event [uWh]\n self.__time_thresh_exceeded = [] # Time of an exceeded threshold event [ms]\n self.__time_thresh_not_exceeded = [] # Time of a non-exceeded threshold event [ms]\n self.__threshold_interval = [] # Time for the thresholds intervall (if it exists) [ms]\n\n # Polling parameters (depends on the board -> we use an array for each parameters)\n self.__number_polling_occurs = [] # Total number of pollings interrupts\n self.__time_polling_occurs = [] # Time for a polling event [ms]\n self.__energy_polling_occurs = [] # Energy for a polling event [uWh]\n\n # LoRa message parameters (depends on the board -> we use an array for each parameters)\n self.__time_wut_data = [] # Time for the \"Wake-Up Transceiver\" part [ms]\n self.__energy_wut_data = [] # Energy for the \"Wake-Up Transceiver\" part [uWh]\n self.__aver_cur_data_transmission = [] # Aver. Current for the transmission part [uA]\n self.__time_data_transmission = [] # Time for the transmission part [ms]\n self.__energy_data_transmission = [] # Energy for the transmission part [uWh]\n self.__time_data_reception = [] # Time for the receiving part [ms]\n self.__energy_data_reception = [] # Energy for the receiving part [uWh]\n self.__sending_castle_time = [] # Total time for a LoRa castle (=WUT+TX+RX) [ms]\n self.__sending_castle_energy = [] # Total energy for a LoRa castle (=WUT+TX+RX) [uWh]\n self.__sending_castle_energy_max = [] # Total energy for a LoRa castle (+Error on TX) [uWh]\n\n # Max Peak Value\n self.__max_peak_value = 0 # Maximum peak current depending on all data [mA]\n\n # Static Energy (depends on the board -> we use an array for parameters who depend on the board)\n self.__time_static_energy = [] # Time for the static energy of a specific board [ms]\n self.__power_static_energy = [] # Aver. Power for the static energy of a specific board [uW]\n self.__static_energy = 0 # Total static energy for the complete system [uWh]\n self.__static_energy_max = 0 # Total static energy for the complete system (with error max) [uWh]\n self.__static_energy_min = 0 # Total static energy for the complete system (with error min) [uWh]\n self.__static_time = 0 # Total static time for the complete system [ms]\n self.__percent_static_time = 100 # Percent of the static time [%]\n\n # Dynamic Energy (depends on the board -> we use an array for parameters who depend on the board)\n self.__time_dyn_data_energy = [] # Time for the \"dynamic-data\" energy of a specific board [ms]\n self.__dyn_data_energy = 0 # Energy for the \"dynamic-data\" energy of the complete system [uWh]\n self.__dyn_send_time = 0 # Time for the \"dynamic-send\" energy of the motherboard [ms]\n self.__dyn_send_energy = 0 # Energy for the \"dynamic-send\" energy of the motherboard [uWh]\n self.__dyn_send_energy_max = 0 # Energy for the \"dynamic-send\" energy of the motherboard (+Error TX) [uWh]\n\n # Total Aver. Consumption\n self.__total_aver_cons = 0 # Total aver. consumption for the complete system [uWh]\n self.__total_aver_cons_max = 0 # Total aver. consumption for the complete system (with error max) [uWh]\n self.__total_aver_cons_min = 0 # Total aver. consumption for the complete system (with error min) [uWh]\n\n # Status LoRa message parameters\n self.__wut_st_time = 0 # Time for the \"Wake-Up Transceiver\" part [ms]\n self.__wut_st_energy = 0 # Energy for the \"Wake-Up Transceiver\" part [uWh]\n self.__data_tx_st_aver_cur = 0 # Aver. Current for the transmission part [uA]\n self.__data_rx_st_time = 0 # Time for the transmission part [ms]\n self.__data_rx_st_energy = 0 # Energy for the transmission part [uWh]\n self.__time_st = 0 # Total time for the Status LoRa castle (=WUT+TX+RX) [ms]\n self.__energy_st = 0 # Total energy for the Status LoRa castle (=WUT+TX+RX) [uWh]\n self.__energy_st_max = 0 # Total energy for the Status LoRa castle (+Error on TX) [uWh]\n\n # Wake-Up motherboard event\n self.__time_wum = 0 # Time for a \"Wake-Up Motherboard\" event [ms]\n self.__number_wum = 5760 # This event occurs each with the new firmware\n self.__energy_wum = 0 # Energy for a \"Wake-Up Motherboard\" event [uWh]\n\n # Accumulation data parameters (depends on the board -> we use an array for parameters who depend on the board)\n self.__acc_data_send_nb = 0 # Number of accumulated message that are sent by the motherboard\n self.__lora_acc_thresholds = 30 # Limit of bytes for an accumulated message\n self.__time_store_data = [] # Time to store one metric in the motherboard for a specific board [ms]\n self.__energy_store_data = [] # Energy to store one metric in the motherboard for a specific board [uWh]\n self.__number_storing_msg = [] # Number of storing event for a specific board\n\n # Battery\n self.__life_estimation = 0 # Estimation of the lifetime for the complete system [ms]\n self.__life_estimation_min = 0 # Estimation of the lifetime for the complete system (min. life) [ms]\n\n # PDF report\n colonnes = 6\n lignes = 64\n self.data_pdf = [['/'] * colonnes for _ in range(lignes)]\n self.section_pdf = [0, 7, 14, 21, 28, 35, 42, 49, 56]\n self.pdf_data_date = \"\"\n\n # --------------------------------------------------------------------------------------------------------------\n # DESCRIPTION\n # --------------------------------------------------------------------------------------------------------------\n\n self.description_config_title = QLabel()\n self.description_config_title.setText(\"Configuration:\")\n\n self.description_config = QLabel()\n\n # --------------------------------------------------------------------------------------------------------------\n # POWER MEASUREMENT DATA\n # --------------------------------------------------------------------------------------------------------------\n self.tabs = QTabWidget()\n self.scrollDataWidget = self.config_data_widget()\n self.tabs.addTab(self.scrollDataWidget, \"Measurement Data\")\n\n # Collect number of pollings\n for id_c in range(len(self.__id)):\n if self.get_id(id_c) is not False:\n if self.get_poll_interval(id_c) is not False or self.get_poll_interval(id_c) != 0:\n self.append_number_polling_occurs(int(1440 / self.get_poll_interval(id_c)))\n else:\n self.append_number_polling_occurs(0)\n else:\n self.append_number_polling_occurs(0)\n\n # Collect number of thresholds not exceeded\n self.determine_number_thresh_not_exceeded()\n\n # Collect number of storing event (if data accumulation is enable)\n if self.get_data_acc() is True:\n self.determine_number_storing_msg()\n\n # --------------------------------------------------------------------------------------------------------------\n # EVENT WIDGET\n # --------------------------------------------------------------------------------------------------------------\n\n self.event_config_title = QLabel()\n self.event_config_title.setText(\"Events for a day:\")\n\n self.event_config = self.config_event_widget()\n self.event_config.setMaximumWidth(400)\n\n # Determine the number of message sending (if data accumulation is enabled)\n if self.get_data_acc() is True:\n self.determine_number_acc_send()\n\n # Determine an estimation of the total consumption of the system\n self.determine_total_average_cons()\n\n # --------------------------------------------------------------------------------------------------------------\n # GRAPHICS WIDGET\n # --------------------------------------------------------------------------------------------------------------\n\n self.graphics = self.config_graphic_widget()\n self.tabs.addTab(self.graphics, \"LoRa Castles\")\n\n # --------------------------------------------------------------------------------------------------------------\n # CONSUMPTION SUMMARY\n # --------------------------------------------------------------------------------------------------------------\n\n self.summary_consumption_title = QLabel()\n self.summary_consumption_title.setText(\"Consumption Summary:\")\n\n self.summary_consumption = QWidget()\n self.summary_consumption_layout = QGridLayout()\n\n # Determine Max Peak Value\n self.max_peak_value_label = QLabel(self.tr('Maximum peak current: '))\n max_peak_value_tr = self.get_max_peak_value()\n if max_peak_value_tr // 1000 >= 1.0:\n max_peak_value_tr /= 1000\n self.max_peak_value_n = QLabel(self.tr(str(max_peak_value_tr) + ' mA'))\n else:\n self.max_peak_value_n = QLabel(self.tr(str(max_peak_value_tr) + ' uA'))\n\n # Determine total time in static mode\n self.set_percent_static_time(round(self.get_static_time() / 864000, 3))\n self.sleep_time_label = QLabel(self.tr('Total sleep time: '))\n self.sleep_time_value_label = QLabel(\n self.tr(self.better_sleep_time(int(self.get_static_time() / 1000)) + ' (' + str(\n self.get_percent_static_time()) + ' %)'))\n\n # Determine total average consumption\n self.average_total_consumption_label = QLabel(self.tr('Average total consumption: '))\n self.average_total_consumption_max_label = QLabel(self.tr('Maximum: '))\n self.average_total_consumption_max_label.setAlignment(Qt.AlignRight)\n self.average_total_consumption_min_label = QLabel(self.tr('Minimum: '))\n self.average_total_consumption_min_label.setAlignment(Qt.AlignRight)\n self.average_total_consumption = QLabel(self.tr(str(round(self.get_total_aver_cons(), 2)) + ' uWh'))\n self.average_total_consumption.setStyleSheet(\"border-width: 1px; border-style: solid; border-radius: 0px;\")\n self.average_total_consumption_max = QLabel(self.tr(str(round(self.get_total_aver_cons_max(), 2)) + ' uWh'))\n self.average_total_consumption_min = QLabel(self.tr(str(round(self.get_total_aver_cons_min(), 2)) + ' uWh'))\n\n # Determine lifetime battery estimation\n self.determine_lifetime()\n self.lifetime_label = QLabel(self.tr('Estimated life time: '))\n self.lifetime_value_label = QLabel(self.tr(\n str(self.get_life_estimation())+' (min: '+str(self.get_life_estimation_min())+')'))\n\n self.summary_consumption_layout.addWidget(self.max_peak_value_label, 3, 0)\n self.summary_consumption_layout.addWidget(self.max_peak_value_n, 3, 1)\n self.summary_consumption_layout.addWidget(self.sleep_time_label, 4, 0)\n self.summary_consumption_layout.addWidget(self.sleep_time_value_label, 4, 1)\n self.summary_consumption_layout.addWidget(self.average_total_consumption_label, 0, 0)\n self.summary_consumption_layout.addWidget(self.average_total_consumption_max_label, 1, 0)\n self.summary_consumption_layout.addWidget(self.average_total_consumption_min_label, 2, 0)\n self.summary_consumption_layout.addWidget(self.average_total_consumption, 0, 1)\n self.summary_consumption_layout.addWidget(self.average_total_consumption_max, 1, 1)\n self.summary_consumption_layout.addWidget(self.average_total_consumption_min, 2, 1)\n self.summary_consumption_layout.addWidget(self.lifetime_label, 5, 0)\n self.summary_consumption_layout.addWidget(self.lifetime_value_label, 5, 1)\n\n self.summary_consumption.setLayout(self.summary_consumption_layout)\n\n # --------------------------------------------------------------------------------------------------------------\n # OTHERS\n # --------------------------------------------------------------------------------------------------------------\n\n link_template = '{1}'\n self.measurement_table_link = QLabel()\n self.measurement_table_link.setOpenExternalLinks(True)\n self.measurement_table_link.setText(link_template.format(URL_GITHUB, 'Access the table'))\n\n self.exit_button = QPushButton(self.tr('Exit'))\n self.exit_button.pressed.connect(self.on_exit_button)\n\n self.print_button = QPushButton(self.tr('Print PDF'))\n self.print_button.pressed.connect(self.on_print_button)\n\n self.debug()\n\n # --------------------------------------------------------------------------------------------------------------\n\n layout = QGridLayout()\n layout.addWidget(self.description_config_title, 0, 0)\n layout.addWidget(self.description_config, 1, 0)\n layout.addWidget(self.event_config_title, 4, 0)\n layout.addWidget(self.event_config, 5, 0, 9, 1)\n layout.addWidget(self.summary_consumption_title, 0, 1, 1, 4)\n layout.addWidget(self.summary_consumption, 1, 1, 3, 2)\n layout.addWidget(self.measurement_table_link, 15, 0)\n layout.addWidget(self.exit_button, 15, 4)\n layout.addWidget(self.print_button, 15, 3)\n layout.addWidget(self.tabs, 4, 1, 10, 4)\n self.setLayout(layout)\n\n def config_data_widget(self):\n \"\"\"Create the data widget table\"\"\"\n\n id_config = [0] # motherboard ID\n for idc in range(len(self.__id)):\n id_config.append(self.get_id(idc)) # sensor boards ID\n\n for idc in range(len(id_config)):\n if id_config[idc] is False:\n id_config[idc] = 1000 # if no sensor boards -> ID = 1000\n\n data_csv = self.collect_csv()\n\n # Collect date of the measurement of the motherboard\n date = data_csv.iat[0, 2]\n self.pdf_data_date = date\n\n # Collect Number of metrics per board\n for id_c in range(len(id_config)):\n if id_c != 0:\n if id_config[id_c] != 1000:\n self.append_number_metrics(int(data_csv.iat[id_config[id_c], 51]))\n else:\n self.append_number_metrics(0)\n\n # Collect LoRa Castles Characteristics\n if self.get_data_acc() is False:\n for id_c in range(len(id_config)):\n if id_c != 0:\n if id_config[id_c] != 1000:\n if data_csv.iat[id_config[id_c], 40] != 'No data':\n self.append_energy_wut_data(float(data_csv.iat[id_config[id_c], 40]))\n self.append_time_wut_data(float(data_csv.iat[id_config[id_c], 41]))\n self.append_aver_cur_data_transmission(float(data_csv.iat[id_config[id_c], 42]))\n self.append_energy_data_reception(float(data_csv.iat[id_config[id_c], 43]))\n self.append_time_data_reception(float(data_csv.iat[id_config[id_c], 44]))\n self.append_sending_castle_time(0)\n self.append_sending_castle_energy(0)\n self.append_sending_castle_energy_max(0)\n self.determine_sending_message(id_c - 1)\n else:\n self.append_energy_wut_data(0)\n self.append_time_wut_data(0)\n self.append_aver_cur_data_transmission(0)\n self.append_energy_data_reception(0)\n self.append_time_data_reception(0)\n self.append_sending_castle_time(0)\n self.append_sending_castle_energy(0)\n self.append_sending_castle_energy_max(0)\n else:\n self.append_energy_wut_data(0)\n self.append_time_wut_data(0)\n self.append_aver_cur_data_transmission(0)\n self.append_energy_data_reception(0)\n self.append_time_data_reception(0)\n self.append_sending_castle_time(0)\n self.append_sending_castle_energy(0)\n self.append_sending_castle_energy_max(0)\n else: # Data Acc is true\n self.append_energy_wut_data(float(data_csv.iat[5, 45]))\n self.append_time_wut_data(float(data_csv.iat[5, 46]))\n self.append_aver_cur_data_transmission(float(data_csv.iat[5, 47]))\n self.append_energy_data_reception(float(data_csv.iat[5, 48]))\n self.append_time_data_reception(float(data_csv.iat[5, 49]))\n self.append_sending_castle_time(0)\n self.append_sending_castle_energy(0)\n self.append_sending_castle_energy_max(0)\n self.determine_sending_message(0)\n\n # Collect Data storage informations\n if self.get_data_acc() is True:\n for id_c in range(len(id_config)):\n if id_c != 0:\n self.append_number_storing_msg(0)\n if id_config[id_c] != 1000:\n self.append_time_store_data(float(data_csv.iat[id_config[id_c], 34]))\n self.append_energy_store_data(float(data_csv.iat[id_config[id_c], 33]))\n else:\n self.append_time_store_data(0)\n self.append_energy_store_data(0)\n\n # Collect Static Power for all the system\n self.append_time_static_energy(0)\n self.append_time_dyn_data_energy(0)\n for id_c in range(len(id_config)):\n if id_config[id_c] != 1000:\n self.append_power_static_energy((float(data_csv.iat[id_config[id_c], 7]))*3.3) # in uW\n else:\n self.append_power_static_energy(0)\n\n self.append_time_static_energy(0)\n self.append_time_dyn_data_energy(0)\n\n # Determine Characteristics of the WUM event\n self.set_energy_wum(float(data_csv.iat[id_config[0], 13]))\n self.set_time_wum(float(data_csv.iat[id_config[0], 14]))\n\n # Collect boards name for the description\n Texte1 = str()\n for id_c in range(len(id_config)):\n if id_c != 0 and id_config[id_c] != 1000:\n self.append_id_name(str(data_csv.iat[id_config[id_c], 4]))\n Texte1 += 'Board ' + str(id_c) + ' -> ' + str(self.get_id_name(id_c - 1)) + '\\n'\n self.description_config.setText(Texte1)\n\n # Determine the status LoRa castle\n self.set_wut_st_time(float(data_csv.iat[id_config[0], 36]))\n self.set_wut_st_energy(float(data_csv.iat[id_config[0], 35]))\n self.set_data_tx_st_aver_cur(float(data_csv.iat[id_config[0], 37]))\n self.set_data_rx_st_time(float(data_csv.iat[id_config[0], 39]))\n self.set_data_rx_st_energy(float(data_csv.iat[id_config[0], 38]))\n\n self.determine_status_message()\n\n # Récupérer la période des thresholds en ms\n id_c = 1\n while id_c < len(id_config):\n if id_config[id_c] != 1000 and id_config[id_c] != 0 and self.get_thresholds(id_c - 1) is not False:\n self.append_threshold_interval(int(data_csv.iat[id_config[id_c], 50]))\n elif id_config[id_c] != 0:\n self.append_threshold_interval(0)\n id_c += 1\n\n # Collect all data and build the table\n data_label = []\n data_label_total = []\n data_header = [[], [], [], [], [], []]\n data_value = [[], [], [], [], [], []]\n data_value_nb = [[], [], [], [], [], []]\n data_total = [[], [], [], [], [], []]\n value_tempo = 0\n data_label_title = [' - Motherboard Wakes Up',\n ' - Threshold Not Exceeded',\n ' - Threshold Exceeded',\n ' - Polling Interrupt',\n ' - Saving data']\n\n data = QGridLayout()\n data.setSpacing(0)\n data.setVerticalSpacing(1)\n dataWidget = QWidget()\n dataWidget.setContentsMargins(0, 0, 0, 0)\n scrollDataWidget = QScrollArea()\n scrollDataWidget.setStyleSheet(\"border-width: 0px; border-radius: 0px;\")\n\n dataWidget.setLayout(data)\n scrollDataWidget.setWidgetResizable(True)\n scrollDataWidget.setWidget(dataWidget)\n\n column_dep = 5 # We begin at the column n°6\n section = 1 # 6 sections (without the data castle section)\n number_rows = 0 # 6 rows by sections\n\n while section <= 6:\n if section == 1:\n data_label.append(QLabel(self.tr('1. '))) # Item data_label (number_rows)\n data_label.append(QLabel(self.tr('Static Power/Sleep Mode'))) # Item data_label (number_rows+1)\n else:\n data_label.append(QLabel(self.tr(str(section) + '. '))) # Item data_label (number_rows)\n data_label.append(\n QLabel(self.tr('Dynamic Power ' + str(section - 2) + data_label_title[section-2]))) # Item data_label (number_rows+1)\n\n data_label.append(QLabel(self.tr('Average Current Value'))) # Item data_label (number_rows+2)\n data_label.append(QLabel(self.tr('Peak Current Value'))) # Item data_label (number_rows+3)\n data_label.append(QLabel(self.tr('Energy Value'))) # Item data_label (number_rows+4)\n data_label.append(QLabel(self.tr('Interval Time Value'))) # Item data_label (number_rows+5)\n\n data_label_total.append(QLabel(self.tr('Total')))\n data_total[section - 1].append(0)\n data_total[section - 1].append(0)\n data_total[section - 1].append(0)\n\n ligne_pdf = 0\n\n for id_c in range(len(id_config)):\n if id_config[id_c] == 1000:\n data_header[section - 1].append(QLabel(self.tr('Nothing')))\n elif id_config[id_c] == 0:\n data_header[section - 1].append(\n QLabel(self.tr('Motherboard\\nAlone'))) # Item data_header (id_c+section)\n else:\n data_header[section - 1].append(QLabel( # Item data_header (id_c+section)\n self.tr(str(data_csv.iat[id_config[id_c], 4]) + '\\nBoard')))\n\n if id_config[id_c] != 1000:\n # Aver. Current Value\n value_tempo = data_csv.iat[id_config[id_c], column_dep + 2 + ((section - 1) * 5)]\n if value_tempo == 'No data':\n data_value[section - 1].append(\n QLabel(self.tr(value_tempo))) # Item data_value[section-1][id_c*4]\n data_value_nb[section - 1].append(0) # Item data_value_nb[section-1][id_c*4]\n else:\n value_tempo = float(value_tempo)\n data_total[section - 1][0] += value_tempo\n data_value_nb[section - 1].append(value_tempo)\n self.data_pdf[self.section_pdf[section-1]+ligne_pdf][1] = str(round(value_tempo, 2))\n if value_tempo // 1000 >= 1.0:\n value_tempo /= 1000\n data_value[section - 1].append(QLabel(self.tr(str(round(value_tempo, 2)) + ' mA')))\n else:\n data_value[section - 1].append(QLabel(self.tr(str(round(value_tempo, 2)) + ' uA')))\n\n # Max. Current Value\n value_tempo = data_csv.iat[id_config[id_c], column_dep + ((section - 1) * 5)]\n if value_tempo == 'No data':\n data_value[section - 1].append(\n QLabel(self.tr(value_tempo))) # Item data_value[section-1][(id_c*4)+1]\n data_value_nb[section - 1].append(0) # Item data_value_nb[section-1][(id_c*4)+1]\n else:\n value_tempo = float(value_tempo)\n data_total[section - 1][1] += value_tempo\n data_value_nb[section - 1].append(value_tempo)\n if value_tempo > self.get_max_peak_value():\n self.set_max_peak_value(value_tempo)\n if value_tempo // 1000 >= 1.0:\n value_tempo /= 1000\n data_value[section - 1].append(QLabel(self.tr(str(round(value_tempo, 2)) + ' mA')))\n else:\n data_value[section - 1].append(QLabel(self.tr(str(round(value_tempo, 2)) + ' uA')))\n\n # Energy\n value_tempo = data_csv.iat[id_config[id_c], column_dep + 3 + ((section - 1) * 5)]\n if value_tempo == 'No data':\n data_value[section - 1].append(\n QLabel(self.tr(value_tempo))) # Item data_value[section-1][(id_c*4)+2]\n data_value_nb[section - 1].append(0) # Item data_value_nb[section-1][(id_c*4)+2]\n else:\n data_total[section - 1][2] += float(value_tempo)\n data_value[section - 1].append(QLabel(self.tr((str(round(float(value_tempo), 2))) + ' uWh')))\n data_value_nb[section - 1].append(float(value_tempo))\n self.data_pdf[self.section_pdf[section-1]+ligne_pdf][4] = str(round(float(value_tempo), 2))\n\n # Interval time\n value_tempo = data_csv.iat[id_config[id_c], column_dep + 4 + ((section - 1) * 5)]\n if value_tempo == 'No data':\n data_value[section - 1].append(\n QLabel(self.tr(value_tempo))) # Item data_value[section-1][(id_c*4)+3]\n data_value_nb[section - 1].append(0) # Item data_value_nb[section-1][(id_c*4)+3]\n else:\n value_tempo = float(value_tempo)\n data_value_nb[section - 1].append(float(value_tempo))\n self.data_pdf[self.section_pdf[section-1]+ligne_pdf][2] = str(round(value_tempo, 2))\n if value_tempo // 1000 >= 1.0:\n value_tempo /= 1000\n data_value[section - 1].append(QLabel(self.tr(str(round(value_tempo, 2)) + ' s')))\n else:\n data_value[section - 1].append(QLabel(self.tr(str(round(value_tempo, 2)) + ' ms')))\n\n data.addWidget(data_value[section - 1][id_c * 4], number_rows + 2, id_c + 2)\n data.addWidget(data_value[section - 1][(id_c * 4) + 1], number_rows + 3, id_c + 2)\n data.addWidget(data_value[section - 1][(id_c * 4) + 2], number_rows + 4, id_c + 2)\n data.addWidget(data_value[section - 1][(id_c * 4) + 3], number_rows + 5, id_c + 2)\n\n if id_config[id_c] != 1000:\n ligne_pdf += 1\n data.addWidget(data_header[section - 1][id_c], number_rows + 1, id_c + 2)\n\n data.addWidget(data_label_total[section - 1], number_rows + 1, id_c + 3)\n if data_total[section - 1][0] // 1000 >= 1.0:\n data_total[section - 1][0] /= 1000\n data.addWidget(QLabel(self.tr(str(round(data_total[section - 1][0], 1)) + ' mA')), number_rows + 2,\n id_c + 3)\n else:\n data.addWidget(QLabel(self.tr(str(round(data_total[section - 1][0], 1)) + ' uA')), number_rows + 2,\n id_c + 3)\n\n if data_total[section - 1][1] // 1000 >= 1.0:\n data_total[section - 1][1] /= 1000\n data.addWidget(QLabel(self.tr(str(round(data_total[section - 1][1], 1)) + ' mA')), number_rows + 3,\n id_c + 3)\n else:\n data.addWidget(QLabel(self.tr(str(round(data_total[section - 1][1], 1)) + ' uA')), number_rows + 3,\n id_c + 3)\n\n data.addWidget(QLabel(self.tr(str(round(data_total[section - 1][2], 1)) + ' uWh')), number_rows + 4,\n id_c + 3)\n\n data.addWidget(data_label[number_rows], number_rows, 0)\n data.addWidget(data_label[number_rows + 1], number_rows, 1, 1, 9)\n data_label[number_rows + 1].setStyleSheet(\n \"border-bottom-width: 1px; border-bottom-style: solid; border-radius: 0px;\"\n \"border-top-width: 1px; border-top-style: solid; border-radius: 0px;\")\n data.addWidget(data_label[number_rows + 2], number_rows + 2, 1)\n data.addWidget(data_label[number_rows + 3], number_rows + 3, 1)\n data.addWidget(data_label[number_rows + 4], number_rows + 4, 1)\n data.addWidget(data_label[number_rows + 5], number_rows + 5, 1)\n\n section += 1\n number_rows += 6\n\n for id_c in range(len(self.__id)):\n if self.get_poll_interval(id_c) is not False:\n self.append_energy_polling_occurs(nb=data_value_nb[4][((id_c + 1) * 4) + 2])\n self.append_time_polling_occurs(nb=data_value_nb[4][((id_c + 1) * 4) + 3])\n else:\n self.append_energy_polling_occurs(nb=0)\n self.append_time_polling_occurs(nb=0)\n\n if self.get_thresholds(id_c) is not False:\n self.append_energy_thresh_not_exceeded(nb=data_value_nb[2][((id_c + 1) * 4) + 2])\n self.append_time_thresh_not_exceeded(nb=data_value_nb[2][((id_c + 1) * 4) + 3])\n self.append_energy_thresh_exceeded(nb=data_value_nb[3][((id_c + 1) * 4) + 2])\n self.append_time_thresh_exceeded(nb=data_value_nb[3][((id_c + 1) * 4) + 3])\n elif self.get_id(id_c) == 1: # Exception for the buttons board...\n self.append_energy_thresh_not_exceeded(nb=0)\n self.append_time_thresh_not_exceeded(nb=0)\n self.append_energy_thresh_exceeded(nb=data_value_nb[3][((id_c + 1) * 4) + 2])\n self.append_time_thresh_exceeded(nb=data_value_nb[3][((id_c + 1) * 4) + 3])\n else:\n self.append_energy_thresh_not_exceeded(nb=0)\n self.append_time_thresh_not_exceeded(nb=0)\n self.append_energy_thresh_exceeded(nb=0)\n self.append_time_thresh_exceeded(nb=0)\n\n return scrollDataWidget\n\n # --------------------------------------------------------------------------------------------------------------\n\n def collect_csv(self):\n \"\"\"Upload the csv file stored in GitHub\"\"\"\n\n try:\n req = requests.get(URL_GITHUB)\n except requests.exceptions.ConnectionError:\n print(\"Error - No connection !\")\n error_window = QErrorMessage()\n error_window.setWindowTitle(\"Error\")\n error_window.showMessage(\"Hum... There is a problem with your Internet connection\")\n\n page = req.content\n soup = BeautifulSoup(page, 'html.parser')\n soup_str = soup.get_text()\n soup_str_io = io.StringIO(soup_str)\n data = pd.read_csv(soup_str_io, sep=\";\", skiprows=7)\n return data\n\n def config_graphic_widget(self):\n \"\"\"Build the LoRa castle widget\"\"\"\n\n graphics = QGridLayout()\n graphics.setSpacing(0)\n graphics.setVerticalSpacing(1)\n graphicsWidget = QWidget()\n graphicsWidget.setContentsMargins(0, 0, 0, 0)\n scrollGraphicsWidget = QScrollArea()\n scrollGraphicsWidget.setStyleSheet(\"border-width: 0px; border-radius: 0px;\")\n\n graphicsWidget.setLayout(graphics)\n # Scroll Area Properties\n scrollGraphicsWidget.setWidgetResizable(True)\n scrollGraphicsWidget.setWidget(graphicsWidget)\n\n # Status Message\n data_tx_time = self.determine_airtime_lora(payload_size=(7 + len(self.__id_name)), st=True) # in ms\n data_tx_energy = (((self.get_data_tx_st_aver_cur() / 1000000) * 3.3 * (\n data_tx_time / 1000)) / 3600) * 1000000 # in uWh\n\n title_status_message = QLabel(self.tr('Status Message'))\n title_status_message.setStyleSheet(\n \"border-bottom-width: 1px; border-bottom-style: solid; border-radius: 0px;\"\n \"border-top-width: 1px; border-top-style: solid; border-radius: 0px;\")\n title_energy_1 = QLabel(self.tr('Energy [uWh]'))\n title_time_1 = QLabel(self.tr('Time [ms]'))\n title_area_1 = QLabel(self.tr('Wake Up TX'))\n title_area_2 = QLabel(self.tr('Airtime TX'))\n title_area_3 = QLabel(self.tr('RX Area'))\n title_total_1 = QLabel(self.tr('Total'))\n value_energy_area_1 = QLabel(self.tr(str(round(self.get_wut_st_energy(),2))))\n self.value_energy_area_2 = QLabel(self.tr(str(round(data_tx_energy,2))))\n value_energy_area_3 = QLabel(self.tr(str(round(self.get_data_rx_st_energy(),2))))\n value_time_area_1 = QLabel(self.tr(str(round(self.get_wut_st_time(),2))))\n self.value_time_area_2 = QLabel(self.tr(str(round(data_tx_time,2))))\n value_time_area_3 = QLabel(self.tr(str(round(self.get_data_rx_st_time(),2))))\n self.value_total_energy_1 = QLabel(\n self.tr(str(round((self.get_wut_st_energy()+data_tx_energy+self.get_data_rx_st_energy()),2))))\n self.value_total_time_1 = QLabel(\n self.tr(str(round((self.get_wut_st_time() + data_tx_time + self.get_data_rx_st_time()),2))))\n\n graphics.addWidget(title_status_message, 0, 0, 1, 6)\n graphics.addWidget(title_energy_1, 1, 4)\n graphics.addWidget(title_time_1, 1, 5)\n graphics.addWidget(title_area_1, 2, 3)\n graphics.addWidget(title_area_2, 3, 3)\n graphics.addWidget(title_area_3, 4, 3)\n graphics.addWidget(title_total_1, 5, 3)\n graphics.addWidget(value_energy_area_1, 2, 4)\n graphics.addWidget(self.value_energy_area_2, 3, 4)\n graphics.addWidget(value_energy_area_3, 4, 4)\n graphics.addWidget(value_time_area_1, 2, 5)\n graphics.addWidget(self.value_time_area_2, 3, 5)\n graphics.addWidget(value_time_area_3, 4, 5)\n graphics.addWidget(self.value_total_energy_1, 5, 4)\n graphics.addWidget(self.value_total_time_1, 5, 5)\n\n if self.get_data_acc() is True: # Accumulated Message\n time_data_tx = self.determine_airtime_lora(payload_size=self.get_lora_acc_thresholds())\n energy_data_tx = (((time_data_tx / 1000) * 3.3 * (\n self.get_aver_cur_data_transmission(0) / 1000000)) / 3600) * 1000000\n\n title_acc_message = QLabel(self.tr('Accumulated Message'))\n title_acc_message.setStyleSheet(\n \"border-bottom-width: 1px; border-bottom-style: solid; border-radius: 0px;\"\n \"border-top-width: 1px; border-top-style: solid; border-radius: 0px;\")\n title_energy_2 = QLabel(self.tr('Energy [uWh]'))\n title_time_2 = QLabel(self.tr('Time [ms]'))\n title_area_21 = QLabel(self.tr('Wake Up TX'))\n title_area_22 = QLabel(self.tr('Airtime TX'))\n title_area_23 = QLabel(self.tr('RX Area'))\n title_total_2 = QLabel(self.tr('Total'))\n value_energy_area_21 = QLabel(self.tr(str(round(self.get_energy_wut_data(0),2))))\n self.value_energy_area_22 = QLabel(self.tr(str(round(energy_data_tx,2))))\n value_energy_area_23 = QLabel(self.tr(str(round(self.get_energy_data_reception(0),2))))\n value_time_area_21 = QLabel(self.tr(str(round(self.get_time_wut_data(0),2))))\n self.value_time_area_22 = QLabel(self.tr(str(round(time_data_tx,2))))\n value_time_area_23 = QLabel(self.tr(str(round(self.get_time_data_reception(0),2))))\n self.value_total_energy_2 = QLabel(\n self.tr(str(round((self.get_energy_wut_data(0) + energy_data_tx + self.get_energy_data_reception(0)),2))))\n self.value_total_time_2 = QLabel(\n self.tr(str(round((self.get_time_wut_data(0) + time_data_tx + self.get_time_data_reception(0)),2))))\n value_number_msg_title = QLabel(self.tr('Number of messages: '))\n self.value_number_msg = QLabel(self.tr(str(self.get_acc_data_send_nb())))\n\n graphics.addWidget(title_acc_message, 6, 0, 1, 6)\n graphics.addWidget(title_energy_2, 7, 4)\n graphics.addWidget(title_time_2, 7, 5)\n graphics.addWidget(title_area_21, 8, 3)\n graphics.addWidget(title_area_22, 9, 3)\n graphics.addWidget(title_area_23, 10, 3)\n graphics.addWidget(title_total_2, 11, 3)\n graphics.addWidget(value_energy_area_21, 8, 4)\n graphics.addWidget(self.value_energy_area_22, 9, 4)\n graphics.addWidget(value_energy_area_23, 10, 4)\n graphics.addWidget(value_time_area_21, 8, 5)\n graphics.addWidget(self.value_time_area_22, 9, 5)\n graphics.addWidget(value_time_area_23, 10, 5)\n graphics.addWidget(self.value_total_energy_2, 11, 4)\n graphics.addWidget(self.value_total_time_2, 11, 5)\n graphics.addWidget(value_number_msg_title, 12, 0)\n graphics.addWidget(self.value_number_msg, 12, 1)\n\n else: # Normal Message\n title_normal_message = []\n title_energy = []\n title_time = []\n title_area_21 = []\n title_area_22 = []\n title_area_23 = []\n title_total = []\n value_energy_area_21 = []\n self.value_energy_area_22 = []\n value_energy_area_23 = []\n value_time_area_21 = []\n self.value_time_area_22 = []\n value_time_area_23 = []\n self.value_total_energy = []\n self.value_total_time = []\n value_number_msg_title = []\n self.value_number_msg = []\n nb_rows = 6\n for board in range(len(self.__id_name)):\n time_data_tx = self.determine_airtime_lora(payload_size=(2 + (2 * (self.get_number_metrics(board)))))\n energy_data_tx = (((time_data_tx / 1000) * 3.3 * (\n self.get_aver_cur_data_transmission(board) / 1000000)) / 3600) * 1000000\n title_normal_message.append(QLabel(self.tr('Normal Message - '+self.get_id_name(board))))\n title_normal_message[board].setStyleSheet(\n \"border-bottom-width: 1px; border-bottom-style: solid; border-radius: 0px;\"\n \"border-top-width: 1px; border-top-style: solid; border-radius: 0px;\")\n title_energy.append(QLabel(self.tr('Energy [uWh]')))\n title_time.append(QLabel(self.tr('Time [ms]')))\n title_area_21.append(QLabel(self.tr('Wake Up TX')))\n title_area_22.append(QLabel(self.tr('Airtime TX')))\n title_area_23.append(QLabel(self.tr('RX Area')))\n title_total.append(QLabel(self.tr('Total')))\n value_energy_area_21.append(QLabel(self.tr(str(round(self.get_energy_wut_data(board), 2)))))\n self.value_energy_area_22.append(QLabel(self.tr(str(round(energy_data_tx, 2)))))\n value_energy_area_23.append(QLabel(self.tr(str(round(self.get_energy_data_reception(board), 2)))))\n value_time_area_21.append(QLabel(self.tr(str(round(self.get_time_wut_data(board), 2)))))\n self.value_time_area_22.append(QLabel(self.tr(str(round(time_data_tx, 2)))))\n value_time_area_23.append(QLabel(self.tr(str(round(self.get_time_data_reception(board), 2)))))\n self.value_total_energy.append(QLabel(\n self.tr(str(\n round((self.get_energy_wut_data(board) + energy_data_tx + self.get_energy_data_reception(board)), 2)))))\n self.value_total_time.append(QLabel(\n self.tr(\n str(round((self.get_time_wut_data(board) + time_data_tx + self.get_time_data_reception(board)), 2)))))\n value_number_msg_title.append(QLabel(self.tr('Number of messages: ')))\n self.value_number_msg.append(QLabel(self.tr(str(self.get_number_thresh_exceeded(board)+self.get_number_polling_occurs(board)))))\n\n graphics.addWidget(title_normal_message[board], 6+nb_rows, 0, 1, 6)\n graphics.addWidget(title_energy[board], 7+nb_rows, 4)\n graphics.addWidget(title_time[board], 7+nb_rows, 5)\n graphics.addWidget(title_area_21[board], 8+nb_rows, 3)\n graphics.addWidget(title_area_22[board], 9+nb_rows, 3)\n graphics.addWidget(title_area_23[board], 10+nb_rows, 3)\n graphics.addWidget(title_total[board], 11+nb_rows, 3)\n graphics.addWidget(value_energy_area_21[board], 8+nb_rows, 4)\n graphics.addWidget(self.value_energy_area_22[board], 9+nb_rows, 4)\n graphics.addWidget(value_energy_area_23[board], 10+nb_rows, 4)\n graphics.addWidget(value_time_area_21[board], 8+nb_rows, 5)\n graphics.addWidget(self.value_time_area_22[board], 9+nb_rows, 5)\n graphics.addWidget(value_time_area_23[board], 10+nb_rows, 5)\n graphics.addWidget(self.value_total_energy[board], 11+nb_rows, 4)\n graphics.addWidget(self.value_total_time[board], 11+nb_rows, 5)\n graphics.addWidget(value_number_msg_title[board], 12+nb_rows, 0)\n graphics.addWidget(self.value_number_msg[board], 12+nb_rows, 1)\n\n nb_rows += 7\n\n return scrollGraphicsWidget\n\n def config_event_widget(self):\n \"\"\"Build the event area to choose the parameters\"\"\"\n\n event_box = QGridLayout()\n event_widget = QWidget()\n scroll_event_widget = QScrollArea()\n\n for id_c in range(len(self.__id_name)):\n # For the buttons board\n if self.get_id_name(id_c) == 'Buttons':\n button_title = QLabel(self.tr('Events for the button board'))\n button_title.setStyleSheet(\"border-bottom-width: 1px; border-bottom-style: solid; border-radius: 0px;\")\n button_label = QLabel(self.tr('Number of times buttons are pressed: '))\n self.button_choice = QSpinBox()\n self.button_choice.setMaximum(100000)\n self.button_choice.valueChanged.connect(self.update_values)\n\n event_box.addWidget(button_title, 0, 0)\n event_box.addWidget(button_label, 1, 0)\n event_box.addWidget(self.button_choice, 1, 1)\n # For the power board\n elif self.get_id_name(id_c) == 'Power' or self.get_id_name(id_c) == 'Power (no thresh)':\n power_title = QLabel(self.tr('Events for the power board'))\n power_title.setStyleSheet(\"border-bottom-width: 1px; border-bottom-style: solid; border-radius: 0px;\")\n event_box.addWidget(power_title, 2, 0)\n if self.get_number_polling_occurs(id_c) != 0:\n power_label_pol = QLabel(self.tr('Number of polling interrupts: '))\n power_label_pol_nb = QLabel(self.tr(str(self.get_number_polling_occurs(id_c))))\n event_box.addWidget(power_label_pol, 3, 0)\n event_box.addWidget(power_label_pol_nb, 3, 1)\n if self.get_thresholds(id_c) is not False:\n power_label_th_ne = QLabel(self.tr('Number of non-exceeded thresholds: '))\n self.power_label_th_ne_nb = QLabel(self.tr(str(self.get_number_thresh_not_exceeded(id_c))))\n power_label_th_e = QLabel(self.tr('Number of exceeded thresholds:'))\n self.power_choice = QSpinBox()\n self.power_choice.setMaximum(self.get_number_thresh_not_exceeded(id_c))\n self.power_choice.valueChanged.connect(self.update_values)\n event_box.addWidget(power_label_th_ne, 4, 0)\n event_box.addWidget(self.power_label_th_ne_nb, 4, 1)\n event_box.addWidget(power_label_th_e, 5, 0)\n event_box.addWidget(self.power_choice, 5, 1)\n # For the sound board\n elif self.get_id_name(id_c) == 'Sound' or self.get_id_name(id_c) == 'Sound (no thresh)':\n sound_title = QLabel(self.tr('Events for the sound board'))\n sound_title.setStyleSheet(\"border-bottom-width: 1px; border-bottom-style: solid; border-radius: 0px;\")\n event_box.addWidget(sound_title, 6, 0)\n if self.get_number_polling_occurs(id_c) != 0:\n sound_label_pol = QLabel(self.tr('Number of polling interrupts: '))\n sound_label_pol_nb = QLabel(self.tr(str(self.get_number_polling_occurs(id_c))))\n event_box.addWidget(sound_label_pol, 7, 0)\n event_box.addWidget(sound_label_pol_nb, 7, 1)\n if self.get_thresholds(id_c) is not False:\n sound_label_th_ne = QLabel(self.tr('Number of non-exceeded thresholds: '))\n self.sound_choice_th_ne = QSpinBox()\n self.sound_choice_th_ne.setMaximum(100000)\n self.sound_choice_th_ne.valueChanged.connect(self.update_values)\n sound_label_th_e = QLabel(self.tr('Number of exceeded thresholds:'))\n self.sound_choice_th_e = QSpinBox()\n self.sound_choice_th_e.setMaximum(100000)\n self.sound_choice_th_e.valueChanged.connect(self.update_values)\n event_box.addWidget(sound_label_th_ne, 8, 0)\n event_box.addWidget(self.sound_choice_th_ne, 8, 1)\n event_box.addWidget(sound_label_th_e, 9, 0)\n event_box.addWidget(self.sound_choice_th_e, 9, 1)\n # For the environmental board\n elif self.get_id_name(id_c) == 'Environmental' or self.get_id_name(id_c) == 'Environmental (no thresh)':\n environmental_title = QLabel(self.tr('Events for the environmental board'))\n environmental_title.setStyleSheet(\"border-bottom-width: 1px; border-bottom-style: solid; border-radius: 0px;\")\n event_box.addWidget(environmental_title, 6, 0)\n if self.get_number_polling_occurs(id_c) != 0:\n environmental_label_pol = QLabel(self.tr('Number of polling interrupts: '))\n environmental_label_pol_nb = QLabel(self.tr(str(self.get_number_polling_occurs(id_c))))\n event_box.addWidget(environmental_label_pol, 7, 0)\n event_box.addWidget(environmental_label_pol_nb, 7, 1)\n if self.get_thresholds(id_c) is not False:\n environmental_label_th_ne = QLabel(self.tr('Number of non-exceeded thresholds: '))\n self.environmental_choice_th_ne = QSpinBox()\n self.environmental_choice_th_ne.setMaximum(100000)\n self.environmental_choice_th_ne.valueChanged.connect(self.update_values)\n environmental_label_th_e = QLabel(self.tr('Number of exceeded thresholds:'))\n self.environmental_choice_th_e = QSpinBox()\n self.environmental_choice_th_e.setMaximum(100000)\n self.environmental_choice_th_e.valueChanged.connect(self.update_values)\n event_box.addWidget(environmental_label_th_ne, 8, 0)\n event_box.addWidget(self.environmental_choice_th_ne, 8, 1)\n event_box.addWidget(environmental_label_th_e, 9, 0)\n event_box.addWidget(self.environmental_choice_th_e, 9, 1)\n # If you want to add a new board ...\n\n lora_label = QLabel(self.tr('LoRa settings'))\n lora_label.setStyleSheet(\"border-bottom-width: 1px; border-bottom-style: solid; border-radius: 0px;\")\n event_box.addWidget(lora_label, 10, 0)\n\n lora_spread_fact_label = QLabel(self.tr('Spreading factor: '))\n self.lora_spread_fact_nb_label = QLabel(self.tr(str(self.get_lora_spread_factor())))\n self.lora_spread_fact = QSlider(Qt.Horizontal, self)\n self.lora_spread_fact.setRange(7, 12)\n self.lora_spread_fact.setValue(11)\n self.lora_spread_fact.setFocusPolicy(Qt.NoFocus)\n self.lora_spread_fact.setPageStep(1)\n self.lora_spread_fact.valueChanged.connect(self.update_values)\n\n event_box.addWidget(lora_spread_fact_label, 11, 0)\n event_box.addWidget(self.lora_spread_fact, 12, 0)\n event_box.addWidget(self.lora_spread_fact_nb_label, 12, 1)\n\n event_widget.setLayout(event_box)\n scroll_event_widget.setWidgetResizable(True)\n scroll_event_widget.setWidget(event_widget)\n scroll_event_widget.setMinimumWidth(425)\n\n return scroll_event_widget\n\n def determine_airtime_lora(self, payload_size, st=False):\n \"\"\"Determine Air Time for the LoRa castle (TX time)\"\"\"\n # Inspired by code from GillesC\n # https://github.com/GillesC/LoRaEnergySim/blob/master/Framework/LoRaPacket.py\n n_pream = 8 # https://www.google.com/patents/EP2763321A1?cl=en\n t_sym = (2.0 ** self.get_lora_spread_factor()) / 125\n t_pream = (n_pream + 4.25) * t_sym\n if self.get_lora_spread_factor() >= 11:\n LDR_opt = 1 # Low Data Rate optimisation\n else:\n LDR_opt = 0\n\n payload_symb_n_b = 8 + max(\n math.ceil(\n (8.0 * payload_size - 4.0 * self.get_lora_spread_factor() + 28 + 16) / (4.0 * (\n self.get_lora_spread_factor() - 2 * LDR_opt))) * (1 + 4), 0)\n t_payload = payload_symb_n_b * t_sym\n\n if self.get_data_acc() is False:\n t_error = ERROR_DATA_TX_TIME[self.get_lora_spread_factor()-7]\n elif st is True:\n t_error = ERROR_DATA_TX_TIME[self.get_lora_spread_factor() - 7]\n else:\n t_error = ERROR_DATA_TX_TIME_ACC[self.get_lora_spread_factor()-7]\n\n return t_pream + t_payload + t_error\n\n def determine_status_message(self):\n \"\"\"Determine total energy and time for the status message\"\"\"\n\n data_tx_time = self.determine_airtime_lora(payload_size=(7 + len(self.__id_name)), st=True) # in ms\n data_tx_energy = (((self.get_data_tx_st_aver_cur() / 1000000) * 3.3 * (\n data_tx_time / 1000)) / 3600) * 1000000 # in uWh\n data_tx_energy_max = ((((self.get_data_tx_st_aver_cur()+ERROR_AVER_CUR_TX) / 1000000) * 3.3 * (\n data_tx_time / 1000)) / 3600) * 1000000 # in uWh\n\n total_time = self.get_wut_st_time() + data_tx_time + self.get_data_rx_st_time()\n total_energy = self.get_wut_st_energy() + data_tx_energy + self.get_data_rx_st_energy()\n total_energy_max = self.get_wut_st_energy() + data_tx_energy_max + self.get_data_rx_st_energy()\n\n self.set_time_st(total_time)\n self.set_energy_st(total_energy)\n self.set_energy_st_max(total_energy_max)\n\n def determine_sending_message(self, id):\n \"\"\"Determine normal LoRa message for a specific ID (or for the accumulated msg)\"\"\"\n\n if self.get_data_acc() is False:\n time_data_tx = self.determine_airtime_lora(payload_size=(2 + (2 * (self.get_number_metrics(id)))))\n else:\n time_data_tx = self.determine_airtime_lora(payload_size=self.get_lora_acc_thresholds())\n\n energy_data_tx = (((time_data_tx / 1000) * 3.3 * (\n self.get_aver_cur_data_transmission(id) / 1000000)) / 3600) * 1000000\n\n energy_data_tx_max = (((time_data_tx / 1000) * 3.3 * (\n (self.get_aver_cur_data_transmission(id)+ERROR_AVER_CUR_TX) / 1000000)) / 3600) * 1000000\n\n self.set_sending_castle_time(id,\n self.get_time_wut_data(id) + self.get_time_data_reception(id) + time_data_tx)\n self.set_sending_castle_energy(id,\n self.get_energy_wut_data(id) + self.get_energy_data_reception(id) + energy_data_tx)\n self.set_sending_castle_energy_max(id,\n self.get_energy_wut_data(id) + self.get_energy_data_reception(\n id) + energy_data_tx_max)\n\n def determine_static_energy(self):\n \"\"\"Determine the static energy for the entire system\"\"\"\n\n # ---- Determine Static Time ---- [ms]\n static_time = 86400000\n self.set_time_static_energy(0, 86400000-self.get_time_dyn_data_energy(0)-self.get_dyn_send_time())\n self.data_pdf[0][3] = round(86400000-self.get_time_dyn_data_energy(0)-self.get_dyn_send_time(), 2)\n static_time = static_time - self.get_time_dyn_data_energy(0) - self.get_dyn_send_time()\n for idc in range(len(self.__id)):\n self.set_time_static_energy(idc+1, 86400000-self.get_time_dyn_data_energy(idc+1))\n if self.__id[idc] is not False:\n self.data_pdf[idc+1][3] = round(86400000-self.get_time_dyn_data_energy(idc+1), 2)\n static_time -= self.get_time_dyn_data_energy(idc+1)\n\n # ---- Determine Static Energy ---- [uWh]\n static_energy = 0\n static_energy_max = 0\n static_energy_min = 0\n static_energy += self.get_power_static_energy(0)*self.get_time_static_energy(0)\n self.data_pdf[0][5] = round((self.get_power_static_energy(0)*self.get_time_static_energy(0)/3600000), 2)\n static_energy_max += (((self.get_power_static_energy(\n 0)/3.3)+ERROR_AVER_CUR_SLEEP)*3.3)*self.get_time_static_energy(0)\n static_energy_min += (((self.get_power_static_energy(\n 0)/3.3)-ERROR_AVER_CUR_SLEEP)*3.3)*self.get_time_static_energy(0)\n\n for idc in range(len(self.__id)):\n static_energy += self.get_power_static_energy(idc+1)*self.get_time_static_energy(idc+1)\n static_energy_max += (((self.get_power_static_energy(\n idc+1) / 3.3) + ERROR_AVER_CUR_SLEEP) * 3.3) * self.get_time_static_energy(idc+1)\n static_energy_min += (((self.get_power_static_energy(\n idc+1) / 3.3) - ERROR_AVER_CUR_SLEEP) * 3.3) * self.get_time_static_energy(idc+1)\n\n if self.get_id(idc) is not False:\n if self.get_id_name(idc) == 'Sound': # Disabling the microphone after an exceeded threshold\n static_energy -= ((21.6*3.3)*64000)*self.get_number_thresh_exceeded(idc)\n static_energy_max -= ((21.6*3.3)*64000)*self.get_number_thresh_exceeded(idc)\n static_energy_min -= ((21.6*3.3)*64000) * self.get_number_thresh_exceeded(idc)\n if self.get_id(idc) is not False:\n self.data_pdf[idc+1][5] = round((self.get_power_static_energy(idc+1) * self.get_time_static_energy(idc+1) / 3600000),\n 2)\n\n self.set_static_energy(static_energy/3600000)\n self.set_static_energy_max(static_energy_max/3600000)\n self.set_static_energy_min(static_energy_min/3600000)\n self.set_static_time(static_time)\n\n def determine_dynamic_data_energy(self):\n \"\"\"Determine the data dynamic energy for the entire system\"\"\"\n\n # ---- Determine Dynamic Data Time ---- [ms]\n # For Motherboard\n dynamic_time = 0\n dynamic_time += self.get_number_wum()*self.get_time_wum()\n if self.get_data_acc() is True:\n for idc in range(len(self.__id)):\n if self.get_id(idc) is not False:\n dynamic_time += self.get_number_storing_msg(idc)*self.get_time_store_data(idc)\n\n self.set_time_dyn_data_energy(0, dynamic_time)\n\n # For other boards\n for idc in range(len(self.__id)):\n dynamic_time = 0\n dynamic_time += self.get_number_polling_occurs(idc)*self.get_time_polling_occurs(idc)\n dynamic_time += self.get_number_thresh_not_exceeded(idc)*self.get_time_thresh_not_exceeded(idc)\n dynamic_time += self.get_number_thresh_exceeded(idc)*self.get_time_thresh_exceeded(idc)\n self.set_time_dyn_data_energy(idc+1, dynamic_time)\n\n # ---- Determine Dynamic Data Energy ---- [uWh]\n dynamic_energy = 0\n # For Motherboard\n dynamic_energy += self.get_number_wum()*self.get_energy_wum()\n if self.get_data_acc() is True:\n for idc in range(len(self.__id)):\n if self.get_id(idc) is not False:\n dynamic_energy += self.get_number_storing_msg(idc)*self.get_energy_store_data(idc)\n\n # For other boards\n for idc in range(len(self.__id)):\n dynamic_energy += self.get_number_polling_occurs(idc)*self.get_energy_polling_occurs(idc)\n dynamic_energy += self.get_number_thresh_not_exceeded(idc)*self.get_energy_thresh_not_exceeded(idc)\n dynamic_energy += self.get_number_thresh_exceeded(idc)*self.get_energy_thresh_exceeded(idc)\n\n self.set_dyn_data_energy(dynamic_energy)\n\n def determine_dynamic_send_energy(self):\n \"\"\"Determine the sending dynamic energy for the entire system\"\"\"\n\n # ---- Determine Dynamic Send Time ---- [ms]\n # For Motherboard\n dynamic_time = 0\n dynamic_time += self.get_time_st()\n if self.get_data_acc() is True:\n dynamic_time += self.get_acc_data_send_nb()*self.get_sending_castle_time(0)\n else:\n for idc in range(len(self.__id)):\n dynamic_time += self.get_number_thresh_exceeded(idc)*self.get_sending_castle_time(idc)\n dynamic_time += self.get_number_polling_occurs(idc)*self.get_sending_castle_time(idc)\n\n self.set_dyn_send_time(dynamic_time)\n\n # ---- Determine Dynamic Send Energy ---- [uWh]\n # For Motherboard\n dynamic_energy = 0\n dynamic_energy_max = 0\n dynamic_energy += self.get_energy_st()\n dynamic_energy_max += self.get_energy_st_max()\n\n if self.get_data_acc() is True:\n dynamic_energy += self.get_acc_data_send_nb()*self.get_sending_castle_energy(0)\n dynamic_energy_max += self.get_acc_data_send_nb() * self.get_sending_castle_energy_max(0)\n else:\n for idc in range(len(self.__id)):\n dynamic_energy += self.get_number_thresh_exceeded(idc)*self.get_sending_castle_energy(idc)\n dynamic_energy_max += self.get_number_thresh_exceeded(idc) * self.get_sending_castle_energy_max(idc)\n dynamic_energy += self.get_number_polling_occurs(idc)*self.get_sending_castle_energy(idc)\n dynamic_energy_max += self.get_number_polling_occurs(idc) * self.get_sending_castle_energy_max(idc)\n\n self.set_dyn_send_energy(dynamic_energy)\n self.set_dyn_send_energy_max(dynamic_energy_max)\n\n def determine_total_average_cons(self):\n \"\"\"Estimate the total average consumption\"\"\"\n\n self.determine_dynamic_data_energy()\n self.determine_dynamic_send_energy()\n self.determine_static_energy()\n\n self.set_total_aver_cons(self.get_static_energy()+self.get_dyn_data_energy()+self.get_dyn_send_energy())\n self.set_total_aver_cons_max(\n self.get_static_energy_max()+self.get_dyn_data_energy()+self.get_dyn_send_energy_max())\n self.set_total_aver_cons_min(\n self.get_static_energy_min() + self.get_dyn_data_energy() + self.get_dyn_send_energy())\n\n def on_exit_button(self):\n \"\"\"Close the window\"\"\"\n self.close()\n\n def on_print_button(self):\n \"\"\"Print a PDF report\"\"\"\n filepath, _ = QFileDialog.getSaveFileName(self, \"Save PDF\", \"\", \"PDF(*.pdf) \")\n if filepath == \"\":\n return\n self.pdf = ReportPDF.Report(filepath, \"IWAST Power Report\", )\n self.pdf.set_data_acc(self.get_data_acc())\n self.pdf.data_value = self.data_pdf\n self.pdf.data_date = self.pdf_data_date\n self.update_pdf()\n err = \"ok\"\n try:\n err = self.pdf.run()\n except:\n print(\"Error !\")\n error_window = QErrorMessage()\n error_window.setWindowTitle(\"Error\")\n error_window.showMessage(err)\n\n def update_values(self):\n \"\"\"Set the new values depending on the event choices\"\"\"\n # Update LoRa settings\n self.set_lora_spread_factor(self.lora_spread_fact.value())\n self.lora_spread_fact_nb_label.setText(self.tr(str(self.get_lora_spread_factor())))\n if self.get_data_acc() is False:\n for id_c in range(len(self.__id_name)):\n self.determine_sending_message(id_c)\n else:\n self.determine_sending_message(0)\n self.determine_status_message()\n\n # Update Thresholds numbers\n for id_c in range(len(self.__id_name)):\n if self.get_id_name(id_c) == 'Buttons':\n self.set_number_thresh_exceeded(idx=id_c, nb=self.button_choice.value())\n elif self.get_id_name(id_c) == 'Power':\n if self.get_thresholds(id_c) is not False:\n self.set_number_thresh_exceeded(idx=id_c, nb=self.power_choice.value())\n self.set_number_thresh_not_exceeded(idx=id_c, nb=(\n self.get_number_possible_thresh(id_c) - self.get_number_thresh_exceeded(id_c)))\n if self.get_number_thresh_not_exceeded(idx=id_c) < 0:\n self.set_number_thresh_not_exceeded(idx=id_c, nb=0)\n self.power_label_th_ne_nb.setText(str(self.get_number_thresh_not_exceeded(idx=id_c)))\n elif self.get_id_name(id_c) == 'Sound':\n if self.get_thresholds(id_c) is not False:\n self.set_number_thresh_exceeded(idx=id_c, nb=self.sound_choice_th_e.value())\n self.set_number_thresh_not_exceeded(idx=id_c, nb=self.sound_choice_th_ne.value())\n elif self.get_id_name(id_c) == 'Environmental':\n if self.get_thresholds(id_c) is not False:\n self.set_number_thresh_exceeded(idx=id_c, nb=self.environmental_choice_th_e.value())\n self.set_number_thresh_not_exceeded(idx=id_c, nb=self.environmental_choice_th_ne.value())\n\n if self.get_data_acc() is not False:\n self.determine_number_acc_send()\n self.determine_number_storing_msg()\n\n # Update total average consumption\n self.determine_total_average_cons()\n self.average_total_consumption.setText(self.tr(str(round(self.get_total_aver_cons(), 2)) + ' uWh'))\n self.average_total_consumption_max.setText(self.tr(str(round(self.get_total_aver_cons_max(), 2)) + ' uWh'))\n self.average_total_consumption_min.setText(self.tr(str(round(self.get_total_aver_cons_min(), 2)) + ' uWh'))\n\n # Update sleep time value\n self.set_percent_static_time(round(self.get_static_time() / 864000, 3))\n self.sleep_time_value_label.setText(\n self.tr(self.better_sleep_time(int(self.get_static_time() / 1000)) + ' (' + str(\n self.get_percent_static_time()) + ' %)'))\n\n # Update lifetime\n self.determine_lifetime()\n self.lifetime_value_label.setText(self.tr(\n str(self.get_life_estimation()) + ' (min: ' + str(self.get_life_estimation_min()) + ')'))\n\n # Update LoRa castles\n self.update_castles()\n\n self.debug()\n\n def update_castles(self):\n \"\"\"Update the LoRa castles characteristics\"\"\"\n # Status Message\n data_tx_time = self.determine_airtime_lora(payload_size=(7 + len(self.__id_name)), st=True) # in ms\n data_tx_energy = (((self.get_data_tx_st_aver_cur() / 1000000) * 3.3 * (\n data_tx_time / 1000)) / 3600) * 1000000 # in uWh\n\n self.value_energy_area_2.setText(self.tr(str(round(data_tx_energy, 2))))\n self.value_time_area_2.setText(self.tr(str(round(data_tx_time, 2))))\n self.value_total_energy_1.setText(\n self.tr(str(round((self.get_wut_st_energy() + data_tx_energy + self.get_data_rx_st_energy()), 2))))\n self.value_total_time_1.setText(\n self.tr(str(round((self.get_wut_st_time() + data_tx_time + self.get_data_rx_st_time()), 2))))\n\n if self.get_data_acc() is True:\n\n # Accumulated Message\n time_data_tx = self.determine_airtime_lora(payload_size=self.get_lora_acc_thresholds())\n energy_data_tx = (((time_data_tx / 1000) * 3.3 * (\n self.get_aver_cur_data_transmission(0) / 1000000)) / 3600) * 1000000\n\n self.value_energy_area_22.setText(self.tr(str(round(energy_data_tx, 2))))\n self.value_time_area_22.setText(self.tr(str(round(time_data_tx, 2))))\n self.value_total_energy_2.setText(\n self.tr(\n str(round((self.get_energy_wut_data(0) + energy_data_tx + self.get_energy_data_reception(0)), 2))))\n self.value_total_time_2.setText(\n self.tr(str(round((self.get_time_wut_data(0) + time_data_tx + self.get_time_data_reception(0)), 2))))\n self.value_number_msg.setText(self.tr(str(self.get_acc_data_send_nb())))\n\n else:\n nb_rows = 6\n for board in range(len(self.__id_name)):\n time_data_tx = self.determine_airtime_lora(payload_size=(2 + (2 * (self.get_number_metrics(board)))))\n energy_data_tx = (((time_data_tx / 1000) * 3.3 * (\n self.get_aver_cur_data_transmission(board) / 1000000)) / 3600) * 1000000\n\n self.value_energy_area_22[board].setText(self.tr(str(round(energy_data_tx, 2))))\n self.value_time_area_22[board].setText(self.tr(str(round(time_data_tx, 2))))\n self.value_total_energy[board].setText(\n self.tr(str(\n round(\n (self.get_energy_wut_data(board) + energy_data_tx + self.get_energy_data_reception(board)),\n 2))))\n self.value_total_time[board].setText(\n self.tr(\n str(round((self.get_time_wut_data(board) + time_data_tx + self.get_time_data_reception(board)),\n 2))))\n self.value_number_msg[board].setText(\n self.tr(str(self.get_number_thresh_exceeded(board) + self.get_number_polling_occurs(board))))\n nb_rows += 7\n\n def update_pdf(self):\n \"\"\"Update the PDF information\"\"\"\n for idc in range(len(self.__id_name)):\n self.pdf.add_board_name(idc+1, self.get_id_name(idc))\n\n self.pdf.add_spreading_factor(self.get_lora_spread_factor())\n self.pdf.add_data_value(self.section_pdf[1], 0, self.get_number_wum())\n self.pdf.add_data_value(self.section_pdf[1], 3, self.get_number_wum() * self.get_time_wum())\n self.pdf.add_data_value(self.section_pdf[1], 5, self.get_number_wum() * self.get_energy_wum())\n self.pdf.add_estimation_value(0, self.get_total_aver_cons())\n self.pdf.add_estimation_value(1, self.get_total_aver_cons_max())\n self.pdf.add_estimation_value(2, self.get_life_estimation())\n self.pdf.add_estimation_value(3, self.get_life_estimation_min())\n i = 0\n while i < 6:\n for idc in range(len(self.__id)):\n if self.get_id(idc) is not False:\n if i == 0:\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 0,\n self.get_number_thresh_not_exceeded(idc))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 3,\n round(self.get_number_thresh_not_exceeded(idc) *\n self.get_time_thresh_not_exceeded(idc), 2))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 5,\n round(self.get_number_thresh_not_exceeded(idc) *\n self.get_energy_thresh_not_exceeded(idc), 2))\n elif i == 1:\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 0,\n self.get_number_thresh_exceeded(idc))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 3,\n round(self.get_number_thresh_exceeded(idc) *\n self.get_time_thresh_exceeded(idc), 2))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 5,\n round(self.get_number_thresh_exceeded(idc) *\n self.get_energy_thresh_exceeded(idc), 2))\n elif i == 2:\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 0,\n self.get_number_polling_occurs(idc))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 3,\n round(self.get_number_polling_occurs(idc) *\n self.get_time_polling_occurs(idc), 2))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 5,\n round(self.get_number_polling_occurs(idc) *\n self.get_energy_polling_occurs(idc), 2))\n elif i == 3:\n if self.get_data_acc() is True:\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 0,\n self.get_number_storing_msg(idc))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 3,\n round(self.get_number_storing_msg(idc) *\n self.get_time_store_data(idc), 2))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 5,\n round(self.get_number_storing_msg(idc) *\n self.get_energy_store_data(idc), 2))\n elif i == 4:\n self.pdf.add_data_value(self.section_pdf[i + 2], 0, 1)\n self.pdf.add_data_value(self.section_pdf[i + 2], 1, '/')\n self.pdf.add_data_value(self.section_pdf[i + 2], 2, '/')\n self.pdf.add_data_value(self.section_pdf[i + 2], 3, round(self.get_time_st(), 2))\n self.pdf.add_data_value(self.section_pdf[i + 2], 4, '/')\n self.pdf.add_data_value(self.section_pdf[i + 2], 5, round(self.get_energy_st(), 2))\n elif i == 5:\n if self.get_data_acc() is True:\n self.pdf.add_data_value(self.section_pdf[i + 2], 0, round(self.get_acc_data_send_nb(),2))\n self.pdf.add_data_value(self.section_pdf[i + 2], 1, '/')\n self.pdf.add_data_value(self.section_pdf[i + 2], 2, round(self.get_sending_castle_time(0),2))\n self.pdf.add_data_value(self.section_pdf[i + 2], 3, round(self.get_acc_data_send_nb()*self.get_sending_castle_time(0),2))\n self.pdf.add_data_value(self.section_pdf[i + 2], 4, round(self.get_sending_castle_energy(0),2))\n self.pdf.add_data_value(self.section_pdf[i + 2], 5, round(self.get_acc_data_send_nb()*self.get_sending_castle_energy(0),2))\n else:\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 0,\n round(self.get_number_thresh_exceeded(idc) + self.get_number_polling_occurs(idc), 2))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 1, '/')\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 2,\n round(self.get_sending_castle_time(idc), 2))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 3,\n round(self.get_sending_castle_time(idc)*(self.get_number_thresh_exceeded(idc) + self.get_number_polling_occurs(idc)),\n 2))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 4,\n round(self.get_sending_castle_energy(idc), 2))\n self.pdf.add_data_value(self.section_pdf[i + 2] + idc + 1, 5, round(self.get_sending_castle_energy(idc)*(self.get_number_thresh_exceeded(idc) + self.get_number_polling_occurs(idc)), 2))\n\n i += 1\n\n def better_sleep_time(self, value_st):\n \"\"\"Convert sleep time in [s] into [hh:mm:ss]\"\"\"\n number_hours = str(value_st // 3600)\n number_min = str((value_st % 3600) // 60)\n number_sec = str((value_st % 3600) % 60)\n\n better_value = str('' + number_hours + 'h ' + number_min + 'm ' + number_sec + 's')\n return better_value\n\n def determine_number_thresh_not_exceeded(self):\n \"\"\"Determine the number of not-exceeded threshold for each board\"\"\"\n for id_c in range(len(self.__id)):\n if self.get_id(id_c) is not False:\n if self.get_thresholds(id_c) is True and self.get_id_name(id_c) != 'Sound':\n self.append_number_possible_thresh(int((86400000 / self.get_threshold_interval(id_c)\n - self.get_number_polling_occurs(id_c))))\n\n if self.get_number_possible_thresh(id_c) >= 0:\n self.append_number_thresh_not_exceeded(self.get_number_possible_thresh(id_c))\n self.append_number_thresh_exceeded(0)\n else:\n self.append_number_thresh_not_exceeded(0)\n self.append_number_thresh_exceeded(0)\n else:\n self.append_number_possible_thresh(0)\n self.append_number_thresh_not_exceeded(0)\n self.append_number_thresh_exceeded(0)\n else:\n self.append_number_possible_thresh(0)\n self.append_number_thresh_not_exceeded(0)\n self.append_number_thresh_exceeded(0)\n\n def determine_number_acc_send(self):\n \"\"\"Determine the number of accumulated message\"\"\"\n total_nb_metrics = 0\n for id_c in range(len(self.__id)):\n if self.get_id(id_c) is not False:\n total_nb_metrics += self.get_number_thresh_exceeded(id_c) * ((self.get_number_metrics(id_c)*2)+4)\n total_nb_metrics += self.get_number_polling_occurs(id_c) * ((self.get_number_metrics(id_c)*2)+4)\n\n self.set_acc_data_send_nb(int(total_nb_metrics / self.get_lora_acc_thresholds()))\n\n def determine_number_storing_msg(self):\n \"\"\"Determine the number of storing event for each boards\"\"\"\n for idc in range(len(self.__id)):\n if self.get_id(idc) is not False:\n total_number = 0\n total_number += self.get_number_thresh_exceeded(idc)*self.get_number_metrics(idc)\n if self.get_id_name(idc) == 'Sound' or self.get_id_name(idc) == 'Sound (no thresh)': # Sound board particularity\n total_number += 2*(self.get_number_polling_occurs(idc)*self.get_number_metrics(idc))\n else:\n total_number += self.get_number_polling_occurs(idc) * self.get_number_metrics(idc)\n self.set_number_storing_msg(idc, total_number)\n\n def determine_lifetime(self):\n \"\"\"Determine the lifetime of the entire system\"\"\"\n duration = (24/self.get_total_aver_cons())*((BATTERY*3.3)*1000) # in hours\n nb_jour = int(duration // 24)\n nb_heure = int(duration % 24)\n nb_minutes = int(((duration % 24) - int(duration % 24))*60)\n nb_seconds = int(\n ((((duration % 24) - int(duration % 24))*60) - int(((duration % 24) - int(duration % 24))*60))*60)\n self.set_life_estimation(str(nb_jour)+'d '+str(nb_heure)+'h '+str(nb_minutes)+'m '+str(nb_seconds)+'s')\n\n duration = (24 / self.get_total_aver_cons_max()) * ((BATTERY * 3.3) * 1000) # in hours\n nb_jour = int(duration // 24)\n nb_heure = int(duration % 24)\n nb_minutes = int(((duration % 24) - int(duration % 24)) * 60)\n nb_seconds = int(\n ((((duration % 24) - int(duration % 24)) * 60) - int(((duration % 24) - int(duration % 24)) * 60)) * 60)\n self.set_life_estimation_min(str(nb_jour)+'d '+str(nb_heure)+'h '+str(nb_minutes)+'m '+str(nb_seconds)+'s')\n\n def debug(self):\n if DEBUG is True:\n print('\\n--------------------GENERAL--------------------')\n print(' ID Config: ' + str(self.__id))\n print(' ID Name: ' + str(self.__id_name))\n print(' Thresholds ?: ' + str(self.__thresholds))\n print(' Number of metrics: ' + str(self.__number_metrics))\n print('\\n--------------------POLLING--------------------')\n print(' Polling Intervals: ' + str(self.__poll_interval))\n print(' Polling Numbers: ' + str(self.__number_polling_occurs))\n print(' Polling Times: ' + str(self.__time_polling_occurs))\n print(' Polling Energy: ' + str(self.__energy_polling_occurs))\n print('\\n------------------THRESHOLDS-------------------')\n print(' Possible Thresholds Numbers: ' + str(self.__number_possible_thresh))\n print(' Possible NE Thresholds Numbers: ' + str(self.__number_thresh_not_exceeded))\n print(' Possible E Thresholds Numbers: ' + str(self.__number_thresh_exceeded))\n print(' NE Thresholds Times: ' + str(self.__time_thresh_not_exceeded))\n print(' E Thresholds Times: ' + str(self.__time_thresh_exceeded))\n print(' NE Thresholds Energy: ' + str(self.__energy_thresh_not_exceeded))\n print(' E Thresholds Energy: ' + str(self.__energy_thresh_exceeded))\n print('\\n--------------WAKE UP MOTHERBOARD--------------')\n print(' WUM Numbers: ' + str(self.__number_wum))\n print(' WUM Times: ' + str(self.__time_wum))\n print(' WUM Energy: ' + str(self.__energy_wum))\n print('\\n--------------DATA SENDING CASTLE--------------')\n print(' WUT DATA Energy: ' + str(self.__energy_wut_data))\n print(' WUT DATA Time: ' + str(self.__time_wut_data))\n print(' DATA TX Aver. Current: ' + str(self.__aver_cur_data_transmission))\n print(' DATA RX Energy: ' + str(self.__energy_data_reception))\n print(' DATA RX Time: ' + str(self.__time_data_reception))\n print(' DATA Sending Castle Time: ' + str(self.__sending_castle_time))\n print(' DATA Sending Castle Energy: ' + str(self.__sending_castle_energy))\n print('DATA Sending Castle Energy (ERR): ' + str(self.__sending_castle_energy_max))\n print('\\n----------DATA SENDING CASTLE (STATUS)---------')\n print(' Sending Castle Time (status): ' + str(self.get_time_st()))\n print(' Sending Castle Energy (status): ' + str(self.get_energy_st()))\n print('Sending Castle Energy (status) E: ' + str(self.get_energy_st_max()))\n print('\\n-------------DATA ACCUMULATION-----------------')\n print(' (ACC) DATA Storage Energy: ' + str(self.__energy_store_data))\n print(' (ACC) DATA Storage Time: ' + str(self.__time_store_data))\n print(' (ACC) Number Data sending: ' + str(self.__acc_data_send_nb))\n print(' (ACC) Number Data Storing: ' + str(self.__number_storing_msg))\n print('\\n----------------STATIC ENERGY------------------')\n print(' Static Power: ' + str(self.__power_static_energy))\n print(' Static Times: ' + str(self.__time_static_energy))\n print(' Static Energy: ' + str(self.__static_energy))\n print('\\n----------- DYNAMIC ENERGY (DATA)--------------')\n print(' Dynamic Times: ' + str(self.__time_dyn_data_energy))\n print(' Dynamic Energy: ' + str(self.__dyn_data_energy))\n print('\\n----------- DYNAMIC ENERGY (SEND)--------------')\n print(' Dynamic Time: ' + str(self.__dyn_send_time))\n print(' Dynamic Energy: ' + str(self.__dyn_send_energy))\n\n # ------------------------------------------------------------------------------------------------------------------\n # ACCESSORS AND MUTATORS\n # ------------------------------------------------------------------------------------------------------------------\n\n def get_id(self, idx):\n return self.__id[idx]\n\n def get_poll_interval(self, idx):\n return self.__poll_interval[idx]\n\n def get_data_acc(self):\n return self.__data_acc\n\n def get_thresholds(self, idx):\n return self.__thresholds[idx]\n\n def get_energy_data_reception(self, idx):\n return self.__energy_data_reception[idx]\n\n def get_time_data_reception(self, idx):\n return self.__time_data_reception[idx]\n\n def get_energy_data_transmission(self, idx):\n return self.__energy_data_transmission[idx]\n\n def get_time_data_transmission(self, idx):\n return self.__time_data_transmission[idx]\n\n def get_aver_cur_data_transmission(self, idx):\n return self.__aver_cur_data_transmission[idx]\n\n def get_energy_wut_data(self, idx):\n return self.__energy_wut_data[idx]\n\n def get_time_wut_data(self, idx):\n return self.__time_wut_data[idx]\n\n def get_number_possible_thresh(self, idx):\n return self.__number_possible_thresh[idx]\n\n def get_number_thresh_exceeded(self, idx):\n return self.__number_thresh_exceeded[idx]\n\n def get_number_thresh_not_exceeded(self, idx):\n return self.__number_thresh_not_exceeded[idx]\n\n def get_energy_thresh_exceeded(self, idx):\n return self.__energy_thresh_exceeded[idx]\n\n def get_energy_thresh_not_exceeded(self, idx):\n return self.__energy_thresh_not_exceeded[idx]\n\n def get_time_thresh_exceeded(self, idx):\n return self.__time_thresh_exceeded[idx]\n\n def get_time_thresh_not_exceeded(self, idx):\n return self.__time_thresh_not_exceeded[idx]\n\n def get_threshold_interval(self, idx):\n return self.__threshold_interval[idx]\n\n def get_number_polling_occurs(self, idx):\n return self.__number_polling_occurs[idx]\n\n def get_time_polling_occurs(self, idx):\n return self.__time_polling_occurs[idx]\n\n def get_energy_polling_occurs(self, idx):\n return self.__energy_polling_occurs[idx]\n\n def get_id_name(self, idx):\n return self.__id_name[idx]\n\n def get_time_st(self):\n return self.__time_st\n\n def get_energy_st(self):\n return self.__energy_st\n\n def get_time_wum(self):\n return self.__time_wum\n\n def get_number_wum(self):\n return self.__number_wum\n\n def get_energy_wum(self):\n return self.__energy_wum\n\n def get_number_metrics(self, idx):\n return self.__number_metrics[idx]\n\n def get_sending_castle_time(self, idx):\n return self.__sending_castle_time[idx]\n\n def get_sending_castle_energy(self, idx):\n return self.__sending_castle_energy[idx]\n\n def get_percent_static_time(self):\n return self.__percent_static_time\n\n def get_total_aver_cons(self):\n return self.__total_aver_cons\n\n def get_lora_spread_factor(self):\n return self.__lora_spread_factor\n\n def get_wut_st_time(self):\n return self.__wut_st_time\n\n def get_wut_st_energy(self):\n return self.__wut_st_energy\n\n def get_data_tx_st_aver_cur(self):\n return self.__data_tx_st_aver_cur\n\n def get_data_rx_st_time(self):\n return self.__data_rx_st_time\n\n def get_data_rx_st_energy(self):\n return self.__data_rx_st_energy\n\n def get_acc_data_send_nb(self):\n return self.__acc_data_send_nb\n\n def get_lora_acc_thresholds(self):\n return self.__lora_acc_thresholds\n\n def get_time_store_data(self, idx):\n return self.__time_store_data[idx]\n\n def get_energy_store_data(self, idx):\n return self.__energy_store_data[idx]\n\n def get_total_aver_cons_max(self):\n return self.__total_aver_cons_max\n\n def get_total_aver_cons_min(self):\n return self.__total_aver_cons_min\n\n def get_life_estimation(self):\n return self.__life_estimation\n\n def get_life_estimation_min(self):\n return self.__life_estimation_min\n\n def get_time_static_energy(self, idx):\n return self.__time_static_energy[idx]\n\n def get_power_static_energy(self, idx):\n return self.__power_static_energy[idx]\n\n def get_static_energy(self):\n return self.__static_energy\n\n def get_static_energy_max(self):\n return self.__static_energy_max\n\n def get_static_energy_min(self):\n return self.__static_energy_min\n\n def get_static_time(self):\n return self.__static_time\n\n def get_time_dyn_data_energy(self, idx):\n return self.__time_dyn_data_energy[idx]\n\n def get_dyn_data_energy(self):\n return self.__dyn_data_energy\n\n def get_dyn_send_energy(self):\n return self.__dyn_send_energy\n\n def get_dyn_send_time(self):\n return self.__dyn_send_time\n\n def get_number_storing_msg(self, idx):\n return self.__number_storing_msg[idx]\n\n def get_energy_st_max(self):\n return self.__energy_st_max\n\n def get_sending_castle_energy_max(self, idx):\n return self.__sending_castle_energy_max[idx]\n\n def get_dyn_send_energy_max(self):\n return self.__dyn_send_energy_max\n\n # ------------------------------------------------------------------------------------------------------------------\n\n def set_energy_data_reception(self, idx, nb):\n self.__energy_data_reception[idx] = nb\n\n def set_time_data_reception(self, idx, nb):\n self.__time_data_reception[idx] = nb\n\n def set_energy_data_transmission(self, idx, nb):\n self.__energy_data_transmission[idx] = nb\n\n def set_time_data_transmission(self, idx, nb):\n self.__time_data_transmission[idx] = nb\n\n def set_aver_cur_data_transmission(self, idx, nb):\n self.__aver_cur_data_transmission[idx] = nb\n\n def set_energy_wut_data(self, idx, nb):\n self.__energy_wut_data[idx] = nb\n\n def set_time_wut_data(self, idx, nb):\n self.__time_wut_data[idx] = nb\n\n def set_number_possible_thresh(self, idx, nb):\n self.__number_possible_thresh[idx] = nb\n\n def set_number_thresh_exceeded(self, idx, nb):\n self.__number_thresh_exceeded[idx] = nb\n\n def set_number_thresh_not_exceeded(self, idx, nb):\n self.__number_thresh_not_exceeded[idx] = nb\n\n def set_energy_thresh_exceeded(self, idx, nb):\n self.__energy_thresh_exceeded[idx] = nb\n\n def set_energy_thresh_not_exceeded(self, idx, nb):\n self.__energy_thresh_not_exceeded[idx] = nb\n\n def set_time_thresh_exceeded(self, idx, nb):\n self.__time_thresh_exceeded[idx] = nb\n\n def set_time_thresh_not_exceeeded(self, idx, nb):\n self.__time_thresh_not_exceeeded[idx] = nb\n\n def set_threshold_interval(self, idx, nb):\n self.__threshold_interval[idx] = nb\n\n def set_number_polling_occurs(self, idx, nb):\n self.__number_polling_occurs[idx] = nb\n\n def set_time_polling_occurs(self, idx, nb):\n self.__time_polling_occurs[idx] = nb\n\n def set_energy_polling_occurs(self, idx, nb):\n self.__energy_polling_occurs[idx] = nb\n\n def set_id_name(self, idx, nb):\n self.__id_name[idx] = nb\n\n def set_time_st(self, nb):\n self.__time_st = nb\n\n def set_energy_st(self, nb):\n self.__energy_st = nb\n\n def set_time_wum(self, nb):\n self.__time_wum = nb\n\n def set_number_wum(self, nb):\n self.__number_wum = nb\n\n def set_energy_wum(self, nb):\n self.__energy_wum = nb\n\n def set_number_metrics(self, idx, nb):\n self.__number_metrics[idx] = nb\n\n def set_sending_castle_time(self, idx, nb):\n self.__sending_castle_time[idx] = nb\n\n def set_sending_castle_energy(self, idx, nb):\n self.__sending_castle_energy[idx] = nb\n\n def set_percent_static_time(self, nb):\n self.__percent_static_time = nb\n\n def set_total_aver_cons(self, nb):\n self.__total_aver_cons = nb\n\n def set_lora_spread_factor(self, nb):\n self.__lora_spread_factor = nb\n\n def set_wut_st_time(self, nb):\n self.__wut_st_time = nb\n\n def set_wut_st_energy(self, nb):\n self.__wut_st_energy = nb\n\n def set_data_tx_st_aver_cur(self, nb):\n self.__data_tx_st_aver_cur = nb\n\n def set_data_rx_st_time(self, nb):\n self.__data_rx_st_time = nb\n\n def set_data_rx_st_energy(self, nb):\n self.__data_rx_st_energy = nb\n\n def set_acc_data_send_nb(self, nb):\n self.__acc_data_send_nb = nb\n\n def set_lora_acc_thresholds(self, nb):\n self.__lora_acc_thresholds = nb\n\n def set_time_store_data(self, idx, nb):\n self.__time_store_data[idx] = nb\n\n def set_energy_store_data(self, idx, nb):\n self.__energy_store_data[idx] = nb\n\n def set_total_aver_cons_max(self, nb):\n self.__total_aver_cons_max = nb\n\n def set_total_aver_cons_min(self, nb):\n self.__total_aver_cons_min = nb\n\n def set_life_estimation(self, nb):\n self.__life_estimation = nb\n\n def set_life_estimation_min(self, nb):\n self.__life_estimation_min = nb\n\n def set_time_static_energy(self, idx, nb):\n self.__time_static_energy[idx] = nb\n\n def set_power_static_energy(self, idx, nb):\n self.__power_static_energy[idx] = nb\n\n def set_static_energy(self, nb):\n self.__static_energy = nb\n\n def set_static_time(self, nb):\n self.__static_time = nb\n\n def set_static_energy_max(self, nb):\n self.__static_energy_max = nb\n\n def set_static_energy_min(self, nb):\n self.__static_energy_min = nb\n\n def set_time_dyn_data_energy(self, idx, nb):\n self.__time_dyn_data_energy[idx] = nb\n\n def set_dyn_data_energy(self, nb):\n self.__dyn_data_energy = nb\n\n def set_dyn_send_energy(self, nb):\n self.__dyn_send_energy = nb\n\n def set_dyn_send_time(self, nb):\n self.__dyn_send_time = nb\n\n def set_number_storing_msg(self, idx, nb):\n self.__number_storing_msg[idx] = nb\n\n def set_energy_st_max(self, nb):\n self.__energy_st_max = nb\n\n def set_sending_castle_energy_max(self, idx, nb):\n self.__sending_castle_energy_max[idx] = nb\n\n def set_dyn_send_energy_max(self, nb):\n self.__dyn_send_energy_max = nb\n\n # ------------------------------------------------------------------------------------------------------------------\n\n def append_energy_data_reception(self, nb):\n self.__energy_data_reception.append(nb)\n\n def append_time_data_reception(self, nb):\n self.__time_data_reception.append(nb)\n\n def append_energy_data_transmission(self, nb):\n self.__energy_data_transmission.append(nb)\n\n def append_time_data_transmission(self, nb):\n self.__time_data_transmission.append(nb)\n\n def append_aver_cur_data_transmission(self, nb):\n self.__aver_cur_data_transmission.append(nb)\n\n def append_energy_wut_data(self, nb):\n self.__energy_wut_data.append(nb)\n\n def append_time_wut_data(self, nb):\n self.__time_wut_data.append(nb)\n\n def append_number_possible_thresh(self, nb):\n self.__number_possible_thresh.append(nb)\n\n def append_number_thresh_exceeded(self, nb):\n self.__number_thresh_exceeded.append(nb)\n\n def append_number_thresh_not_exceeded(self, nb):\n self.__number_thresh_not_exceeded.append(nb)\n\n def append_energy_thresh_exceeded(self, nb):\n self.__energy_thresh_exceeded.append(nb)\n\n def append_energy_thresh_not_exceeded(self, nb):\n self.__energy_thresh_not_exceeded.append(nb)\n\n def append_time_thresh_exceeded(self, nb):\n self.__time_thresh_exceeded.append(nb)\n\n def append_time_thresh_not_exceeded(self, nb):\n self.__time_thresh_not_exceeded.append(nb)\n\n def append_threshold_interval(self, nb):\n self.__threshold_interval.append(nb)\n\n def append_number_polling_occurs(self, nb):\n self.__number_polling_occurs.append(nb)\n\n def append_time_polling_occurs(self, nb):\n self.__time_polling_occurs.append(nb)\n\n def append_energy_polling_occurs(self, nb):\n self.__energy_polling_occurs.append(nb)\n\n def append_id_name(self, nb):\n self.__id_name.append(nb)\n\n def append_number_metrics(self, nb):\n self.__number_metrics.append(nb)\n\n def append_sending_castle_time(self, nb):\n self.__sending_castle_time.append(nb)\n\n def append_sending_castle_energy(self, nb):\n self.__sending_castle_energy.append(nb)\n\n def append_time_store_data(self, nb):\n self.__time_store_data.append(nb)\n\n def append_energy_store_data(self, nb):\n self.__energy_store_data.append(nb)\n\n def append_time_static_energy(self, nb):\n self.__time_static_energy.append(nb)\n\n def append_power_static_energy(self, nb):\n self.__power_static_energy.append(nb)\n\n def append_time_dyn_data_energy(self, nb):\n self.__time_dyn_data_energy.append(nb)\n\n def append_power_dyn_data_energy(self, nb):\n self.__power_dyn_data_energy.append(nb)\n\n def append_number_storing_msg(self, nb):\n self.__number_storing_msg.append(nb)\n\n def append_sending_castle_energy_max(self, nb):\n self.__sending_castle_energy_max.append(nb)\n # ------------------------------------------------------------------------------------------------------------------\n\n def get_max_peak_value(self):\n return self.__max_peak_value\n\n def get_time_evt(self, ind):\n return self.__time_evt[ind]\n\n def get_number_evt(self, ind):\n return self.__number_evt[ind]\n\n def get_energy_evt(self, ind):\n return self.__energy_evt[ind]\n\n def set_max_peak_value(self, nb):\n self.__max_peak_value = nb\n\n def set_number_evt(self, ind, nb):\n self.__number_evt[ind] = nb\n\n def set_time_evt(self, ind, nb):\n self.__time_evt[ind] = nb\n\n def set_energy_evt(self, ind, nb):\n self.__energy_evt[ind] = nb\n\n def append_time_evt(self, nb):\n self.__time_evt.append(nb)\n\n def append_number_evt(self, nb):\n self.__number_evt.append(nb)\n\n def append_energy_evt(self, nb):\n self.__energy_evt.append(nb)\n","sub_path":"src/main/python/PowerReport.py","file_name":"PowerReport.py","file_ext":"py","file_size_in_byte":101621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"391575376","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis module handles interfacing with feature databases for the purposes of\ncreating a search structure for searching a local (1km) area of a database\nin order to perform PnP-based navigation\n\"\"\"\n\nimport tables as tb\nimport numpy as np\nimport neogeodb.pytables_db as pdb\nfrom . import utils\n\n\nclass FeatureDatabase(object):\n\n \"\"\"\n This is an abstract base class for implementing a FeatureDatabase\n \"\"\"\n\n def load_features(self, bbox):\n \"\"\"\n Takes in a mercantile tile object and loads features from the\n data store into a local search object\n \"\"\"\n raise NotImplementedError\n\n def search_db(self, query_kp, query_descriptors):\n \"\"\"\n Takes in an NxM numpy.ndarray of N features with an M length\n descriptor. Returns 2D / 3D correspondences.\n \"\"\"\n raise NotImplementedError\n\n\nclass PyTablesDatabase(FeatureDatabase):\n\n \"\"\"\n This class implements a feature database that operates on and HDF5\n formatted store of database features, and uses pyflann to build a local\n search tree of features to be searched.\n \"\"\"\n\n def __init__(self, hdf_path):\n \"\"\"\n Load the HDF database into a pandas DataFrame\n \"\"\"\n self.zoom = 15 # Hard coded but you could check feat_geo\n self.matcher = None # Don't build the FLANN Index if we don't need to\n\n # HDF5 path names are coded for the moment. Sorry\n self.table_hdf = tb.open_file(hdf_path, mode='r')\n self.dbt = self.table_hdf.root.sift_db.sift_features_sorted\n self.uid = np.array(self.table_hdf.root.sift_db.unique_tiles)\n self.uid = self.uid.astype(np.uint32)\n\n # Set up the boundary info\n txmin = self.dbt.cols.x[self.dbt.colindexes['x'][0]]\n txmax = self.dbt.cols.x[self.dbt.colindexes['x'][-1]]\n tymin = self.dbt.cols.y[self.dbt.colindexes['y'][0]]\n tymax = self.dbt.cols.y[self.dbt.colindexes['y'][-1]]\n xbounds = (txmin, txmax)\n ybounds = (tymin, tymax)\n xb, yb = neoextent.pad_grid(xbounds, ybounds)\n self.xb = xb\n self.yb = yb\n\n # Load the aggregation by tile\n self.tid, self.tidcount = np.unique(self.dbt.cols.pair_id,\n return_counts=True)\n\n def load_features_by_extent(self, leaf, N):\n \"\"\"\n Called with a lon (deg), lat(deg), and radius (tiles) to return N \\\n feature descriptors from PyTablesDatabase. Uses the octave value \\\n to return the N largest features. If N > the number of features in \\\n that tile, then it returns all features. Returns None \\\n if nothing was found.\n \"\"\"\n rows = []\n for ii in np.arange(leaf.tiles.shape[0]):\n tileid = leaf.tiles[ii]\n if leaf.num_feat_per_tile[ii] > 0:\n rows.append(self.dbt.read_where('pair_id == tileid'))\n if len(rows) > 0:\n feat_in_tile = np.hstack(rows)\n ff = np.argsort(feat_in_tile['response'])\n best_feat = feat_in_tile[ff[-N:]]\n return best_feat\n","sub_path":"PFILT/neogeo/build/lib.linux-x86_64-2.7/neogeo/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"416677833","text":"#### GUI Screens #####\n\nimport pygame\nfrom pygame.locals import *\n\nclass GUI:\n\n def __init__(self, screen, width, height):\n \n self.screen = screen\n self.height = height\n self.width = width\n\n def TitleScreen(self):\n ''' display the title screen '''\n \n title = pygame.font.SysFont(\"Arial\", 50)\n subtitle = pygame.font.SysFont(\"Arial\", 30)\n string_list = \"G(A)SP Simulator\"\n pre_string = []\n \n for i in string_list:\n \"\"\" Title Screen animation \"\"\"\n self.screen.fill((0,0,0))\n pre_string.append(i)\n string = ''.join(pre_string)\n _title = title.render(str(string), True, (255,255,255))\n title_rect = _title.get_rect(centerx=self.width/2+110, centery=200)\n self.screen.blit(_title, title_rect)\n\n logo = pygame.sprite.Sprite()\n images = pygame.sprite.Group()\n logo.image = pygame.image.load(\"images/logo.png\")\n logo.rect = logo.image.get_rect()\n logo.rect.x, logo.rect.y = 75, (self.height/2)-154\n\n images.add(logo) # display the school logo\n \n images.draw(self.screen)\n \n pygame.display.update()\n pygame.time.delay(50)\n \n string_list = \"Andrew Wilkie Maddie Mackey\"\n pre_string = []\n\n for i in string_list:\n \"\"\" secondary title screen animation \"\"\"\n \n self.screen.fill((0,0,0))\n pre_string.append(i)\n string = ''.join(pre_string)\n _author = subtitle.render(str(string), True, (192,192,192))\n author_rect = _author.get_rect(centerx=self.width/2+110, centery=350)\n self.screen.blit(_author, author_rect)\n self.screen.blit(_title, title_rect)\n\n logo = pygame.sprite.Sprite()\n images = pygame.sprite.Group()\n logo.image = pygame.image.load(\"images/logo.png\")\n logo.rect = logo.image.get_rect()\n logo.rect.x, logo.rect.y = 75, (self.height/2)-154\n\n images.add(logo)\n \n images.draw(self.screen)\n\n pygame.display.update()\n pygame.time.delay(50)\n\n self.screen.blit(_title, title_rect)\n self.screen.blit(_author, author_rect)\n\n pygame.display.update()\n\n def Disconnected(self, label):\n \"\"\" object disconnected from serial \"\"\"\n\n font = pygame.font.SysFont(\"Arial\", 15)\n\n dis_con = font.render(\"DISCONNECTED\", True, (0,0,0))\n self.screen.blit(dis_con, (self.width/2, 0))\n\n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n return \"quit\"\n\n if event.type == pygame.KEYDOWN and event.key == K_ESCAPE:\n return \"quit\"\n\n \n return None\n\n def Variables(self, x_in, y_in, z_in, theta, direction, wind_speed, wind_direction):#, velocity):\n \"\"\" display all relevent variables of the object \"\"\"\n \n altitude = round(z_in/float(1000), 2)\n wind_speed = round(wind_speed/3.6, 2)\n \n font = pygame.font.SysFont(\"Arial\", 15)\n \n sprites = pygame.sprite.Group()\n altitude_group = pygame.sprite.Group()\n \n # variable sprites\n direction_sprite = pygame.sprite.Sprite()\n theta_sprite = pygame.sprite.Sprite()\n altitude_indicator = pygame.sprite.Sprite()\n altitude_level = pygame.sprite.Sprite()\n wind_direction_sprite = pygame.sprite.Sprite()\n scale = pygame.sprite.Sprite()\n compass = pygame.sprite.Sprite()\n\n # variable images\n direction_sprite.image = pygame.image.load(\"images/indicator.png\")\n theta_sprite.image = pygame.image.load(\"images/indicator.png\")\n altitude_level.image = pygame.image.load(\"images/altitude.png\")\n altitude_indicator.image = pygame.image.load(\"images/altitude_indicator.png\")\n wind_direction_sprite.image = pygame.image.load(\"images/indicator.png\")\n scale.image = pygame.image.load(\"images/scale_blank.png\")\n compass.image = pygame.image.load(\"images/compass.png\")\n \n # variable screen locations\n direction_sprite.rect = direction_sprite.image.get_rect(x=self.width-80, y=125)\n theta_sprite.rect = theta_sprite.image.get_rect(x=self.width-80, y=65)\n altitude_level.rect = altitude_indicator.image.get_rect(x=self.width-70, y=200)\n altitude_indicator.rect = altitude_indicator.image.get_rect(x=self.width-67, y=250-(altitude))\n wind_direction_sprite.rect = wind_direction_sprite.image.get_rect(x=self.width-80, y=275)\n scale.rect = scale.image.get_rect(x=self.width-125, y=self.height-50)\n compass.rect = scale.image.get_rect(x=self.width-82, y=5)\n \n sprites.add(direction_sprite, theta_sprite, altitude_level, wind_direction_sprite, scale, compass)\n altitude_group.add(altitude_indicator)\n\n direction_sprite.image = pygame.transform.rotate(direction_sprite.image, direction)\n theta_sprite.image = pygame.transform.rotate(theta_sprite.image, theta)\n wind_direction_sprite.image = pygame.transform.rotate(wind_direction_sprite.image, -90)\n\n # variable values to be displayed along side the variable images\n x = font.render(\"X \"+str(int(x_in)) , True, (0,0,0))\n y = font.render(\"Y \"+str(int(y_in)), True, (0,0,0))\n z = font.render(\"Z \"+str(int(z_in)), True, (0,0,0))\n\n theta = font.render(\"Theta \"+str(int(theta))+u\"\\u00b0\", True, (0,0,0))\n direction = font.render(\"Yaw \"+str(int(direction))+u\"\\u00b0\", True, (0,0,0))\n altitude = font.render(\"Altitude \"+str(altitude)+\" km\", True, (0,0,0))\n wind = font.render(\"Wind \"+str(wind_speed)+\" km/h\", True, (0,0,0))\n scale = font.render(\"100 m\", True, (0,0,0))\n #speed = font.render(\"Speed \"+str(velocity)+\" m/s\", True, (0,0,0))\n \n # display the variable\n self.screen.blit(x, ((self.width/3)/2, self.height-20))\n self.screen.blit(y, (((self.width/3)*3)/2 ,self.height-20))\n self.screen.blit(z, (((self.width/3)*5)/2 ,self.height-20))\n\n self.screen.blit(theta, ((self.width-100), 105))\n self.screen.blit(direction, ((self.width-100), 170))\n self.screen.blit(altitude, ((self.width-100), 255))\n self.screen.blit(wind, ((self.width-100), 315))\n #self.screen.blit(speed, ((self.width-100), 300))\n self.screen.blit(scale, (self.width-75, self.height-65))\n\n sprites.draw(self.screen)\n altitude_group.draw(self.screen)\n \n def Pause(self, x_in, y_in, z_in, theta, direction, wind_speed, wind_direction, sprites, pause_button):\n \"\"\" Pause the simulation \"\"\"\n \n self.screen.fill((200,200,200))\n pause_button_group = pygame.sprite.GroupSingle(pause_button) # pause button \n \n # restart simulation button\n restart_button = pygame.sprite.Sprite()\n restart_button.image = pygame.image.load('images/restart_button.png')\n restart_button.rect = restart_button.image.get_rect()\n restart_button_group = pygame.sprite.GroupSingle(restart_button)\n restart_button.rect.top = 40\n restart_button.rect.left = 5 \n \n self.Variables(x_in, y_in, z_in, theta, direction, wind_speed, wind_direction)\n\n finish = 'pause'\n \n font = pygame.font.SysFont(\"Arial\", 15)\n\n \n pause_title = font.render(\"PAUSED\", True, (0,0,0))\n\n self.screen.blit(pause_title, (self.width/2, 0))\n sprites.draw(self.screen)\n pause_button_group.draw(self.screen)\n restart_button_group.draw(self.screen)\n\n for event in pygame.event.get():\n \"\"\" event listeners \"\"\"\n\n if event.type == pygame.QUIT:\n return \"quit\"\n \n if event.type == pygame.KEYDOWN and event.key == K_ESCAPE:\n return \"quit\"\n\n if event.type == pygame.KEYDOWN and event.key == K_p:\n return \"\"\n if event.type == pygame.KEYDOWN and event.key == K_r:\n return \"restart\"\n\n if event.type == pygame.MOUSEBUTTONUP: # check if button clicked\n pos = pygame.mouse.get_pos()\n if pause_button.rect.collidepoint(pos): # pause\n return \"\"\n if restart_button.rect.collidepoint(pos):\n return \"restart\"\n \n pygame.display.update()\n\n\n return finish\n \n def Landed(self, x_in, y_in, z_in, theta, direction, wind_speed, wind_direction, sprites, pause_button):\n \"\"\" display the lasty know values, and say the object has hit the gound \"\"\"\n \n self.screen.fill((255,255,255))\n pause_button_group = pygame.sprite.GroupSingle(pause_button)\n \n restart_button = pygame.sprite.Sprite()\n restart_button.image = pygame.image.load('images/restart_button.png')\n restart_button.rect = restart_button.image.get_rect()\n restart_button_group = pygame.sprite.GroupSingle(restart_button)\n restart_button.rect.top = 40\n restart_button.rect.left = 5 \n \n self.Variables(x_in, y_in, z_in, theta, direction, wind_speed, wind_direction)\n\n finish = 'landed'\n \n font = pygame.font.SysFont(\"Arial\", 15)\n\n \n pause_title = font.render(\"Landed\", True, (0,0,0))\n\n self.screen.blit(pause_title, (self.width/2, 0))\n sprites.draw(self.screen)\n pause_button_group.draw(self.screen)\n restart_button_group.draw(self.screen)\n \n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n return \"quit\"\n\n if event.type == pygame.KEYDOWN and event.key == K_ESCAPE:\n return \"\"\n\n if event.type == pygame.MOUSEBUTTONUP: # check if button clicked\n pos = pygame.mouse.get_pos()\n if pause_button.rect.collidepoint(pos): # pause\n return \"\"\n if restart_button.rect.collidepoint(pos):\n return \"restart\"\n \n pygame.display.update()\n\n\n return finish\n \n\npygame.init()\nclock = pygame.time.Clock()\n","sub_path":"GASP_Balloon_Simulation/Backup/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":9371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"570505953","text":"import sys\n\ntest_cases = open(sys.argv[1], 'r')\n\nfor line in test_cases:\n if line == \"\\n\":\n continue\n\n line = line.rstrip(\"\\n\")\n splitline = line.split(\"|\")\n lnums = splitline[0].rstrip().split(\" \")\n rnums = splitline[1].lstrip().split(\" \")\n\n first = True\n for x in range(len(lnums)):\n if first == True:\n first = False\n else:\n sys.stdout.write(\" \")\n product = int(lnums[x]) * int(rnums[x])\n sys.stdout.write(repr(product))\n\n sys.stdout.write(\"\\n\")\n\ntest_cases.close()\n","sub_path":"multiply-lists/multiply-lists.py","file_name":"multiply-lists.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"45159439","text":"from django.conf.urls import url\n\nfrom wushu.Views import DashboardViews, AthleteViews, RefereeViews, ClubViews, CoachViews, DirectoryViews, UserViews, \\\n CompetitionViews, AdminViews, HelpViews, PageViews, PreRegistration, LogViews\n\napp_name = 'wushu'\n\nurlpatterns = [\n\n # Dashboard\n url(r'anasayfa/admin/$', DashboardViews.return_admin_dashboard, name='admin'),\n url(r'anasayfa/sehir-sporcu-sayisi/$', DashboardViews.City_athlete_cout, name='sehir-sporcu-sayisi'),\n url(r'anasayfa/sporcu/$', DashboardViews.return_athlete_dashboard, name='sporcu'),\n url(r'anasayfa/hakem/$', DashboardViews.return_referee_dashboard, name='hakem'),\n url(r'anasayfa/antrenor/$', DashboardViews.return_coach_dashboard, name='antrenor'),\n url(r'anasayfa/federasyon/$', DashboardViews.return_directory_dashboard, name='federasyon'),\n url(r'anasayfa/kulup-uyesi/$', DashboardViews.return_club_user_dashboard, name='kulup-uyesi'),\n\n # Sporcular\n url(r'sporcu/sporcu-ekle/$', AthleteViews.return_add_athlete, name='sporcu-ekle'),\n url(r'sporcu/sporcular/$', AthleteViews.return_athletes, name='sporcular'),\n\n # pagenation deneme\n url(r'page/$', PageViews.deneme, name='deneme'),\n url(r'sporcularajax/$', PageViews.return_athletesdeneme, name='sporculardeneme'),\n\n url(r'sporcu/sporcuKusakEkle/(?P\\d+)$', AthleteViews.sporcu_kusak_ekle, name='sporcu-kusak-ekle'),\n url(r'sporcu/sporcuKusakDuzenle/(?P\\d+)/(?P\\d+)$', AthleteViews.sporcu_kusak_duzenle,\n name='sporcu-kusak-duzenle'),\n url(r'sporcu/sporcuLisansEkle/(?P\\d+)$', AthleteViews.sporcu_lisans_ekle, name='sporcu-lisans-ekle'),\n url(r'sporcu/sporcuLisansDuzenle/(?P\\d+)/(?P\\d+)$', AthleteViews.sporcu_lisans_duzenle,\n name='sporcu-lisans-duzenle'),\n url(r'sporcu/sporcuLisansDuzenleMobil/lisans/(?P\\d+)$', AthleteViews.sporcu_lisans_duzenle_mobil,\n name='sporcu-lisans-duzenle-mobil'),\n url(r'sporcu/sporcuKusakDuzenleMobil/kusak/(?P\\d+)$', AthleteViews.sporcu_kusak_duzenle_mobil,\n name='sporcu-kusak-duzenle-mobil'),\n # ilk degeri verebilmek icin yönlendirme amaci ile kullanildi.\n url(r'sporcu/sporcuLisansDuzenleMobil/$', AthleteViews.sporcu_lisans_duzenle_mobil_ilet,\n name='sporcu-lisans-duzenle-mobil-ilet'),\n url(r'sporcu/sporcuKusakDuzenleMobil/$', AthleteViews.sporcu_kusak_duzenle_mobil_ilet,\n name='sporcu-kusak-duzenle-mobil-ilet'),\n\n url(r'sporcu/sporcuLisansDuzenle/onayla/(?P\\d+)/(?P\\d+)$',\n AthleteViews.sporcu_lisans_onayla, name='sporcu-lisans-onayla'),\n\n url(r'sporcu/sporcuLisansDuzenle/reddet/(?P\\d+)/(?P\\d+)$',\n AthleteViews.sporcu_lisans_reddet, name='sporcu-lisans-reddet'),\n url(r'sporcu/sporcuLisansDuzenle/lisanssil/(?P\\d+)/(?P\\d+)$', AthleteViews.sporcu_lisans_sil,\n name='sporcu-lisans-sil'),\n url(r'sporcu/sporcuLisansListesi/onayla/(?P\\d+)$',\n AthleteViews.sporcu_lisans_listesi_onayla, name='sporcu-lisans-listesi-onayla'),\n url(r'sporcu/sporcuLisansListesi/onaylaMobil/(?P\\d+)/(?P\\d+)$',\n AthleteViews.sporcu_lisans_listesi_onayla_mobil, name='sporcu-lisans-listesi-onayla-mobil'),\n\n url(r'sporcu/sporcuKusakListesi/onaylaMobil/(?P\\d+)/(?P\\d+)$',\n AthleteViews.sporcu_kusak_listesi_onayla_mobil, name='sporcu-kusak-listesi-onayla-mobil'),\n # lisans listesinin hepsini onaylama\n url(r'sporcu/sporcuLisansListesi/hepsinionayla/$', AthleteViews.sporcu_lisans_listesi_hepsionay,\n name='sporcu-lisans-hepsini-onayla'),\n # lisanslarin hepsini reddetme\n url(r'sporcu/sporcuLisansListesi/hepsiniReddet/$', AthleteViews.sporcu_lisans_listesi_hepsireddet,\n name='sporcu-lisans-hepsini-reddet'),\n\n # hepsini beklemeye al\n url(r'sporcu/sporcuLisansListesi/hepsinibekle/$', AthleteViews.sporcu_bekle,\n name='sporcu-lisans-hepsini-bekle'),\n\n url(r'sporcu/sporcuLisansListesi/reddet/(?P\\d+)$',\n AthleteViews.sporcu_lisans_listesi_reddet, name='sporcu-lisans-listesi-reddet'),\n url(r'sporcu/sporcuLisansListesiMobil/reddet/(?P\\d+)/(?P\\d+)$',\n AthleteViews.sporcu_lisans_listesi_reddet_mobil, name='sporcu-lisans-listesi-reddet-mobil'),\n url(r'sporcu/kusak/$', AthleteViews.return_belt, name='kusak'),\n url(r'sporcu/kusak/sil/(?P\\d+)$', AthleteViews.categoryItemDelete,\n name='categoryItem-delete'),\n url(r'sporcu/kusakDuzenle/(?P\\d+)$', AthleteViews.categoryItemUpdate,\n name='categoryItem-duzenle'),\n url(r'sporcu/sporcuKusakDuzenle/onayla/(?P\\d+)/(?P\\d+)$',\n AthleteViews.sporcu_kusak_onayla, name='sporcu-kusak-onayla'),\n url(r'sporcu/sporcuKusakReddet/(?P\\d+)/(?P\\d+)$',\n AthleteViews.sporcu_kusak_reddet, name='sporcu-kusak-reddet'),\n url(r'sporcu/sporcuKusakDuzenle/kusaksil/(?P\\d+)/(?P\\d+)$', AthleteViews.sporcu_kusak_sil,\n name='sporcu-kusak-sil'),\n\n # kuşaklarin hepsini beklemeye al\n url(r'sporcu/sporcuKusakbekle',\n AthleteViews.sporcu_kusak_bekle, name='sporcu-kusak-bekle'),\n # kuşak listesinin hepsini onayla\n url(r'sporcu/sporcuKusakListesi/hepsinionayla/$',\n AthleteViews.sporcu_kusak_listesi_hepsinionayla, name='sporcu-kusak-listesi-hepsinionayla'),\n\n # kuşak hepsini reddet\n url(r'sporcu/sporcuKusakDuzenle/reddet/$',\n AthleteViews.sporcu_kusak_hepsinireddet, name='sporcu-kusak-hepsinireddet'),\n\n # kusak listesi onay\n url(r'sporcu/sporcuKusakListesi/onayla/(?P\\d+)$',\n AthleteViews.sporcu_kusak_listesi_onayla, name='sporcu-kusak-listesi-onayla'),\n # kuşak listesi reddet\n url(r'sporcu/sporcuKusakListesi/reddet/(?P\\d+)$',\n AthleteViews.sporcu_kusak_listesi_reddet, name='sporcu-kusak-listesi-reddet'),\n\n url(r'sporcu/sporcuDuzenle/(?P\\d+)$', AthleteViews.updateathletes, name='update-athletes'),\n url(r'sporcu/sporcular/sil/(?P\\d+)$', AthleteViews.deleteAthletes,\n name='athlete-delete'),\n url(r'sporcu/sporcu-kusak-listesi/$', AthleteViews.sporcu_kusak_listesi, name='kusak-listesi'),\n url(r'sporcu/sporcu-lisans-listesi/$', AthleteViews.sporcu_lisans_listesi, name='lisans-listesi'),\n url(r'sporcu/sporcu-profil-guncelle/$', AthleteViews.updateAthleteProfile,\n name='sporcu-profil-guncelle'),\n\n # Hakemler\n url(r'hakem/hakem-ekle/$', RefereeViews.return_add_referee, name='hakem-ekle'),\n url(r'hakem/hakemler/$', RefereeViews.return_referees, name='hakemler'),\n url(r'hakem/seviye/$', RefereeViews.return_level, name='seviye'),\n url(r'hakem/seviye/sil/(?P\\d+)$', RefereeViews.categoryItemDelete,\n name='categoryItem-delete-seviye'),\n url(r'hakem/seviye/(?P\\d+)$', RefereeViews.categoryItemUpdate,\n name='categoryItem-duzenle-seviye'),\n url(r'hakem/hakemler/sil/(?P\\d+)$', RefereeViews.deleteReferee,\n name='referee-delete'),\n url(r'hakem/hakemDuzenle/(?P\\d+)$', RefereeViews.updateReferee,\n name='hakem-duzenle'),\n url(r'hakem/hakem-profil-guncelle/$', RefereeViews.updateRefereeProfile,\n name='hakem-profil-guncelle'),\n # /kademe\n url(r'hakem/Hakem-kademe-ekle/(?P\\d+)$', RefereeViews.hakem_kademe_ekle, name='hakem-kademe-ekle'),\n url(r'hakem/Kademe-Duzenle/onayla/(?P\\d+)/(?P\\d+)$', RefereeViews.kademe_onay,\n name='kademe-onayla-hakem'),\n url(r'hakem/Kademe-Duzenle/reddet/(?P\\d+)/(?P\\d+)$', RefereeViews.kademe_reddet,\n name='kademe-reddet-hakem'),\n url(r'hakem/Kademe-Duzenle/güncelle/(?P\\d+)/(?P\\d+)$', RefereeViews.kademe_update,\n name='kademe-güncelle-hakem'),\n url(r'hakem/Kademe-Duzenle/sil/(?P\\d+)/(?P\\d+)$', RefereeViews.kademe_delete,\n name='Kademe-sil-hakem'),\n # /vize\n url(r'hakem/hakem-vize-ekle/(?P\\d+)$', RefereeViews.vısa_ekle, name='hakem-vize-ekle'),\n url(r'hakem/Vize-Duzenle/onayla/(?P\\d+)/(?P\\d+)$', RefereeViews.visa_onay,\n name='hakem-vize-onayla'),\n url(r'hakem/Vize-Duzenle/reddet/(?P\\d+)/(?P\\d+)$', RefereeViews.visa_reddet,\n name='hakem-vize-reddet'),\n url(r'hakem/Vize-Duzenle/guncelle/(?P\\d+)/(?P\\d+)$', RefereeViews.vize_update,\n name='hakem-vize-güncelle'),\n url(r'hakem/Vize-Duzenle/sil/(?P\\d+)/(?P\\d+)$', RefereeViews.vize_delete,\n name='hakem-vize-sil'),\n\n # Kulüpler\n url(r'kulup/basvuru-listesi/$', PreRegistration.return_preRegistration, name='basvuru-listesi'),\n url(r'kulup/basvuru/onayla/(?P\\d+)$', PreRegistration.approve_preRegistration, name='basvuru-onayla'),\n url(r'kulup/basvuru/reddet/(?P\\d+)$', PreRegistration.rejected_preRegistration, name='basvuru-reddet'),\n url(r'sporcu/basvuru-incele/(?P\\d+)$', PreRegistration.update_preRegistration, name='update-basvuru'),\n\n url(r'kulup/kulup-ekle/$', ClubViews.return_add_club, name='kulup-ekle'),\n url(r'kulup/kulupler/$', ClubViews.return_clubs, name='kulupler'),\n url(r'kulup/kulup-uyesi-ekle/$', ClubViews.return_add_club_person, name='kulup-uyesi-ekle'),\n url(r'kulup/kulup-uyesi-guncelle/(?P\\d+)$', ClubViews.updateClubPersons, name='kulup-uyesi-guncelle'),\n url(r'kulup/kulup-uyeleri/$', ClubViews.return_club_person, name='kulup-uyeleri'),\n url(r'kulup/kulup-uye-rolu/$', ClubViews.return_club_role, name='kulup-uye-rolu'),\n url(r'kulup/kulup-uye-rolu/sil/(?P\\d+)$', ClubViews.deleteClubRole,\n name='ClubRole-delete'),\n url(r'kulup/kulup-uyeleri/sil/(?P\\d+)$', ClubViews.deleteClubUser,\n name='ClubUser-delete'),\n\n url(r'kulup/kulup-uyeleri/cikar/(?P\\d+)/(?P\\d+)/$', ClubViews.deleteClubUserFromClub,\n name='ClubUser-cikar'),\n url(r'kulup/kulup-antrenorleri/cikar/(?P\\d+)/(?P\\d+)/$', ClubViews.deleteCoachFromClub,\n name='ClubCoach-cikar'),\n\n url(r'kulup/kulupRolDuzenle/(?P\\d+)$', ClubViews.updateClubRole,\n name='updateClubRole'),\n url(r'kulup/kulupler/sil/(?P\\d+)$', ClubViews.clubDelete,\n name='delete-club'),\n url(r'kulup/kulupDuzenle/(?P\\d+)$', ClubViews.clubUpdate,\n name='update-club'),\n url(r'kulup/kusak-sinavlari/$', ClubViews.return_belt_exams, name='kusak-sinavlari'),\n url(r'kulup/kusak-sinav-detay/$', ClubViews.return_belt_exams_detail, name='kusak-sinav-detay'),\n url(r'kulup/kusak-sinavi-sporcu-sec/(?P\\d+)$', ClubViews.choose_athlete, name='kusak-sinavi-sporcu-sec'),\n #\n\n url(r'kulup/kusak-sinavi-ekle/$', ClubViews.add_belt_exam, name='kusak-sinavi-ekle'),\n url(r'kulup/kusak-sinavi-antroner-sec/(?P\\d+)$', ClubViews.choose_coach, name='kusak-sinavi-antroner-sec'),\n\n url(r'kulup/kusak-sinavi-antroner-sil/(?P\\d+)/(?P\\d+)$', ClubViews.choose_coach_remove,\n name='kulup-sinavi-antroner-sil'),\n url(r'kulup/kusak-sinavi-sporcu-sil/(?P\\d+)/(?P\\d+)$', ClubViews.choose_athlete_remove,\n name='kulup-sinavi-sporcu-sil'),\n\n url(r'kulup/kusak-sinavi-ekle/(?P\\S+?)$', ClubViews.add_belt_exam, name='kusak-sinavi-ekle'),\n url(r'kulup/kusak-sinavi-duzenle/(?P\\d+)$', ClubViews.update_belt_exam, name='kusak-sinavi-duzenle'),\n url(r'kulup/kusak-sinavlari/sil/(?P\\d+)$', ClubViews.delete_belt_exam, name='kusak-sinavi-sil'),\n url(r'kulup/kusak-sinavlari/incele/(?P\\d+)$', ClubViews.detail_belt_exam, name='kusak-sinavi-incele'),\n url(r'kulup/kusak-sinavlari/onayla/(?P\\d+)$', ClubViews.approve_belt_exam, name='kusak-sinavi-onayla'),\n url(r'kulup/kusak-sinavlari/reddet/(?P\\d+)$', ClubViews.denied_belt_exam, name='kusak-sinavi-reddet'),\n\n url(r'kulup/kulup-uyesi-profil-guncelle/$', ClubViews.updateClubPersonsProfile,\n name='kulup-uyesi-profil-guncelle'),\n\n url(r'kulup/kulup-uyesi-sec/(?P\\d+)$', ClubViews.choose_sport_club_user,\n name='choose-sport-club-user'),\n url(r'kulup/klupÜyesiSec/(?P\\d+)$', ClubViews.choose_sport_club_user,\n name='choose-sport-club-user'),\n\n # Antrenörler\n url(r'antrenor/antrenor-ekle/$', CoachViews.return_add_coach, name='antrenor-ekle'),\n url(r'antrenor/antrenorler/$', CoachViews.return_coachs, name='antrenorler'),\n url(r'antrenor/kademe/$', CoachViews.return_grade, name='kademe'),\n url(r'sporcu/yaskategori/$', AthleteViews.return_year, name='yas-katagori'),\n url(r'sporcu/yas/sil/(?P\\d+)$', AthleteViews.year_delete, name='yas-katagori-sil'),\n url(r'sporcu/yas/Duzenle/(?P\\d+)$', AthleteViews.yearUpdate, name='year-katagori-duzenle'),\n\n url(r'sporcu/taoluekle/$', AthleteViews.return_taolu, name='taolu-katagori'),\n url(r'sporcu/taolu/sil/(?P\\d+)$', AthleteViews.categoryTaoluDelete, name='taolu-katagori-sil'),\n url(r'sporcu/taolu/Duzenle/(?P\\d+)$', AthleteViews.categoryTaoluUpdate, name='taolu-katagori-duzenle'),\n # Halil Bozdağ Eklediği Taoulu yaş eklendisi\n url(r'sporcu/taoluekleyas/$', AthleteViews.return_taolu_years, name='yas-taolu-katagori'),\n url(r'sporcu/taoluekleyas/sil/(?P\\d+)$', AthleteViews.categoryTaoluyearsDelete, name='yas-taolu-katagori-sil'),\n url(r'sporcu/taoluekleyas/Duzenle/(?P\\d+)$', AthleteViews.categoryTaoluyearsUpdate,\n name='yas-taolu-katagori-duzenle'),\n\n # Sanda Yaş\n url(r'sporcu/sanda-ekleyas/$', AthleteViews.return_sanda_years, name='return_sanda_years'),\n url(r'sporcu/sanda-ekleyas/sil/(?P\\d+)$', AthleteViews.categorySandayearsDelete, name='yas-sanda-katagori-sil'),\n url(r'sporcu/sanda-ekleyas/Duzenle/(?P\\d+)$', AthleteViews.categorySandayearsUpdate,\n name='yas-sanda-katagori-duzenle'),\n\n url(r'antrenor/kademe/sil/(?P\\d+)$', CoachViews.categoryItemDelete,\n name='categoryItem-delete-kademe'),\n url(r'antrenor/kademeDuzenle/(?P\\d+)$', CoachViews.categoryItemUpdate,\n name='categoryItem-duzenle-kademe'),\n url(r'antrenor/antrenorler/sil/(?P\\d+)$', CoachViews.deleteCoach,\n name='delete-coach'),\n url(r'antrenor/antrenorDuzenle/(?P\\d+)$', CoachViews.coachUpdate,\n name='update-coach'),\n url(r'antrenor/antrenorSec/(?P\\d+)$', ClubViews.choose_coach,\n name='choose-coach'),\n url(r'antrenor/antrenor-profil-guncelle/$', CoachViews.updateCoachProfile,\n name='antrenor-profil-guncelle'),\n url(r'antrenor/antrenor-kademe-ekle/(?P\\d+)$', CoachViews.antrenor_kademe_ekle, name='antrenor-kademe-ekle'),\n # # vize ekle\n url(r'antrenor/antrenor-vize-ekle/(?P\\d+)$', CoachViews.antrenor_vısa_ekle, name='antrenor-vize-ekle'),\n\n # Kademe onay reddet sil güncelle liste\n url(r'antrenor/vize-Liste-Reddet/(?P\\d+)$', CoachViews.vize_reddet_liste,\n name='vize-list-reddet'),\n url(r'antrenor/vize-Liste-Onayla/(?P\\d+)$', CoachViews.vize_onayla_liste,\n name='vize-list-onay'),\n url(r'antrenor/Vize-Duzenle/sil/(?P\\d+)/(?P\\d+)$', CoachViews.vize_delete,\n name='vize-sil'),\n url(r'antrenor/Vize-Reddet/(?P\\d+)/(?P\\d+)$', CoachViews.vize_reddet, name='vize-reddet'),\n url(r'antrenor/Vize-Duzenle/onayla/(?P\\d+)/(?P\\d+)$', CoachViews.visa_onay, name='vize-onayla'),\n url(r'antrenor/Kademe-Duzenle/onayla/(?P\\d+)/(?P\\d+)$', CoachViews.kademe_onay,\n name='kademe-onayla'),\n url(r'antrenor/Kademe-Reddet/(?P\\d+)/(?P\\d+)$', CoachViews.kademe_reddet, name='kademe-reddet'),\n url(r'antrenor/Kademe-Duzenle/güncelle/(?P\\d+)/(?P\\d+)$', CoachViews.kademe_update,\n name='kademe-güncelle'),\n url(r'antrenor/Vize-Duzenle/guncelle/(?P\\d+)/(?P\\d+)$', CoachViews.vize_update,\n name='vize-güncelle'),\n url(r'antrenor/Kademe-Duzenle/sil/(?P\\d+)/(?P\\d+)$', CoachViews.kademe_delete,\n name='Kademe-sil'),\n url(r'antrenor/Kademe-listesi/', CoachViews.kademe_list, name='kademe-listesi'),\n url(r'antrenor/Vize-listesi/', CoachViews.vize_list, name='vize-listesi'),\n url(r'antrenor/kademe-Liste-Onayla/(?P\\d+)$', CoachViews.kademe_onayla,\n name='kademe-list-onay'),\n url(r'antrenor/kademe-Liste-reddet/(?P\\d+)$', CoachViews.kademe_reddet_liste,\n name='kademe-list-reddet'),\n url(r'antrenor/kademe-Liste-reddet-hepsi$', CoachViews.kademe_reddet_hepsi,\n name='kademe-list-reddet-hepsi'),\n url(r'antrenor/kademe-Liste-onay-hepsi$', CoachViews.kademe_onay_hepsi,\n name='kademe-list-onay-hepsi'),\n url(r'antrenor/kademe-Liste-bekle-hepsi$', CoachViews.kademe_bekle_hepsi, name='kademe-list-bekle-hepsi'),\n\n # visa seminar\n # Antrenör\n url(r'antrenor/visa-Seminar$', CoachViews.return_visaSeminar, name='visa-seminar'),\n url(r'antrenor/visa-Seminar-ekle$', CoachViews.visaSeminar_ekle, name='visa-seminar-ekle'),\n url(r'antrenor/visa-Seminar-duzenle/(?P\\d+)$', CoachViews.visaSeminar_duzenle, name='seminar-duzenle'),\n url(r'antrenor/visa-Seminar-Onayla/(?P\\d+)$', CoachViews.visaSeminar_onayla, name='seminar-onayla'),\n url(r'antrenor/visa-Seminar/Seminer-sil(?P\\d+)$', CoachViews.visaSeminar_sil, name='seminar-sil'),\n url(r'antrenor/visa-Seminar/antroner-sec/(?P\\d+)$', CoachViews.choose_coach, name='vize-semineri-antroner-sec'),\n url(r'antrenor/visa-Seminar/antroner-sil/(?P\\d+)/(?P\\d+)$', CoachViews.visaSeminar_Delete_Coach,\n name='visaSeminar-antrenör-sil'),\n # Hakem\n url(r'hakem/visa-Seminar$', RefereeViews.return_visaSeminar, name='hakem-visa-seminar'),\n url(r'hakem/visa-Seminar-ekle$', RefereeViews.visaSeminar_ekle, name='hakem-visa-seminar-ekle'),\n url(r'hakem/visa-Seminar-duzenle/(?P\\d+)$', RefereeViews.visaSeminar_duzenle, name='hakem-seminar-duzenle'),\n url(r'hakem/visa-Seminar/Seminer-sil(?P\\d+)$', RefereeViews.visaSeminar_sil, name='hakem-seminar-sil'),\n url(r'hakem/visa-Seminar/hakem-sec/(?P\\d+)$', RefereeViews.choose_referee, name='vize-semineri-hakem-sec'),\n url(r'hakem/visa-Seminar/hakem-sil/(?P\\d+)/(?P\\d+)$', RefereeViews.visaSeminar_Delete_Referee,\n name='visaSeminar-hakem-sil'),\n url(r'hakem/visa-Seminar-Onayla/(?P\\d+)$', RefereeViews.visaSeminar_onayla, name='hakem-seminar-onayla'),\n\n url(r'hakem/Kademe-listesi/', RefereeViews.kademe_list, name='hakem-kademe-listesi'),\n url(r'hakem/kademe-Liste-Onayla/(?P\\d+)$', RefereeViews.kademe_onayla,\n name='hakem-kademe-list-onay'),\n url(r'hakem/kademe-Liste-reddet/(?P\\d+)$', RefereeViews.kademe_reddet_liste,\n name='hakem-kademe-list-reddet'),\n url(r'hakem/vize-Liste-Reddet/(?P\\d+)$', RefereeViews.vize_reddet_liste,\n name='hakem-vize-list-reddet'),\n\n url(r'hakem/kademe-Liste-onay-hepsi$', RefereeViews.kademe_onay_hepsi,\n name='hakem-kademe-list-onay-hepsi'),\n url(r'hakem/kademe-Liste-reddet-hepsi$', RefereeViews.kademe_reddet_hepsi,\n name='hakem-kademe-list-reddet-hepsi'),\n url(r'hakem/Vize-listesi/', RefereeViews.vize_list, name='hakem-vize-listesi'),\n url(r'hakem/vize-Liste-Onayla/(?P\\d+)$', RefereeViews.vize_onayla_liste,\n name='hakem-vize-list-onay'),\n\n # Yönetim Kurulu\n url(r'yonetim/kurul-uyeleri/$', DirectoryViews.return_directory_members, name='kurul-uyeleri'),\n url(r'yonetim/kurul-uyesi-ekle/$', DirectoryViews.add_directory_member, name='kurul-uyesi-ekle'),\n url(r'yonetim/kurul-uyesi-duzenle/(?P\\d+)$', DirectoryViews.update_directory_member,\n name='kurul-uyesi-duzenle'),\n url(r'yonetim/kurul-uyeleri/sil/(?P\\d+)$', DirectoryViews.delete_directory_member,\n name='kurul-uyesi-sil'),\n url(r'yonetim/kurul-uye-rolleri/$', DirectoryViews.return_member_roles, name='kurul-uye-rolleri'),\n url(r'yonetim/kurul-uye-rolleri/sil/(?P\\d+)$', DirectoryViews.delete_member_role,\n name='kurul_uye_rol_sil'),\n url(r'yonetim/kurul-uye-rol-duzenle/(?P\\d+)$', DirectoryViews.update_member_role,\n name='kurul-uye-rol-duzenle'),\n url(r'yonetim/kurullar/$', DirectoryViews.return_commissions, name='kurullar'),\n url(r'yonetim/kurullar/sil/(?P\\d+)$', DirectoryViews.delete_commission,\n name='kurul_sil'),\n url(r'yonetim/kurul-duzenle/(?P\\d+)$', DirectoryViews.update_commission,\n name='kurul-duzenle'),\n url(r'yonetim/yonetim-kurul-profil-guncelle/$', DirectoryViews.updateDirectoryProfile,\n name='yonetim-kurul-profil-guncelle'),\n\n # Admin\n url(r'admin/admin-profil-guncelle/$', AdminViews.updateProfile,\n name='admin-profil-guncelle'),\n\n # Kullanıcılar/musabaka/musabakalar/\n url(r'kullanici/kullanicilar/$', UserViews.return_users, name='kullanicilar'),\n url(r'kullanici/kullanici-duzenle/(?P\\d+)$', UserViews.update_user, name='kullanici-duzenle'),\n url(r'kullanici/kullanicilar/aktifet/(?P\\d+)$', UserViews.active_user,\n name='kullanici-aktifet'),\n url(r'kullanici/kullanicilar/kullanici-bilgi-gonder/(?P\\d+)$', UserViews.send_information,\n name='kullanici-bilgi-gonder'),\n\n # Competition\n url(r'musabaka/musabakalar/$', CompetitionViews.return_competitions, name='musabakalar'),\n url(r'musabaka/musabaka-ekle/$', CompetitionViews.musabaka_ekle, name='musabaka-ekle'),\n url(r'musabaka/musabaka-duzenle/(?P\\d+)$', CompetitionViews.musabaka_duzenle, name='musabaka-duzenle'),\n\n url(r'musabaka/musabakalar/musabaka-sil(?P\\d+)$', CompetitionViews.musabaka_sil, name='musabaka-sil'),\n url(r'musabaka/Sanda/musabaka-sporcu-sec/(?P\\d+)$', CompetitionViews.musabaka_sporcu_sec,\n name='musabaka-sporcu-sec'),\n\n #\n # müsabaka sporcu seçme\n url(r'musabaka/musabaka-sanda-sporcu-kaydet/$', CompetitionViews.musabaka_sanda_sporcu_ekle,\n name='sanda-sporcu-kaydet'),\n url(r'musabaka/musabaka-taolu-sporcu-kaydet/$', CompetitionViews.musabaka_taolu_sporcu_ekle,\n name='taolu-sporcu-kaydet'),\n\n url(r'musabaka/musabaka-sanda-sporcu-sec/(?P\\d+)$', CompetitionViews.musabaka_sanda,\n name='musabaka-sanda-ekle'),\n url(r'musabaka/musabaka-taolu-sporcu-sec/(?P\\d+)/$', CompetitionViews.musabaka_taolu,\n name='musabaka-taolu-ekle'),\n\n url(r'musabaka/SporcuSecim/Sanda/$', CompetitionViews.return_sporcu_sec_sanda, name='sanda-sporcu-sec-ajax'),\n url(r'musabaka/SporcuSecim/Taolu/$', CompetitionViews.return_sporcu_sec_taolu, name='taolu-sporcu-sec-ajax'),\n\n url(r'musabaka/musabaka-duzenle/sanda-kaldir/(?P\\d+)/$', CompetitionViews.musabaka_sporcu_sil,\n name='musabaka-sporcu-kaldir'),\n url(r'musabaka/musabaka-duzenle/taolu-kaldir/(?P\\d+)/$', CompetitionViews.musabaka_sporcu_sil_taolu,\n name='musabaka-sporcu-kaldir_taolu'),\n\n # taolu\n\n url(r'musabaka/categori-sil/(?P\\d+)/(?P\\d+)$', CompetitionViews.musabaka_categori_sil,\n name='musabaka-categori-sil'),\n url(r'musabaka/KategorilerinSporculari/$', CompetitionViews.return_sporcu, name='Kategorilerin-Sporculari'),\n url(r'musabaka/SporcuSec/$', CompetitionViews.return_sporcu_sec, name='catagori-sporcu-sec-ajax'),\n\n url(r'musabaka/sporcu-sec/(?P\\d+)/(?P\\d+)$', CompetitionViews.choose_athlete,\n name='catagori-sporcu-sec'),\n url(r'musabaka/taoluSporcuSil/(?P\\d+)/(?P\\d+)$', CompetitionViews.taolu_sporcu_sil,\n name='taolu-sporcu-sil'),\n\n # Yardım ve destek\n\n url(r'yardim$', HelpViews.help, name='help'),\n url(r'sorular$', HelpViews.questions, name='sorular'),\n url(r'log/log-kayıtlari/$', LogViews.return_log, name='logs'),\n url(r'control/Lisanscontrol$', LogViews.control, name='control'),\n url(r'control/kusaksinav$', LogViews.controlkusak, name='control-kusak'),\n\n]\n","sub_path":"wushu/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":23984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"244744523","text":"#This is the application module for the flask project\nfrom flask import Flask, render_template, request, url_for\nfrom csvreader import csvreader\n\napp = Flask(__name__)\n\n@app.route('/')\n@app.route('/index')\ndef eventmap():\n return render_template(\"index.html\")\n\n@app.route('/map/', methods=['GET'])\ndef mapSetup():\n events = [] #this will be the list of events passed to the map\n #get the user input data\n restaurants=request.args['restaurants']\n bars=request.args['bars']\n concerts=request.args['concerts']\n parks=request.args['parks']\n volunteering=request.args['volunteering']\n family=request.args['family']\n date=request.args['date']\n #if the user checked restaurants, we add them from the csv\n if (restaurants=='yes'):\n for row in (csvreader('restaurants', date)):\n events.append(row)\n #we do the same for bars as we did for restaurants and so on\n if (bars=='yes'):\n for row in (csvreader('bars', date)):\n events.append(row)\n if (concerts=='yes'):\n for row in (csvreader('concerts', date)):\n events.append(row)\n if (parks=='yes'):\n for row in (csvreader('parks', date)):\n events.append(row)\n if (volunteering=='yes'):\n for row in (csvreader('volunteering', date)):\n events.append(row)\n if (family=='yes'):\n for row in (csvreader('family', date)):\n events.append(row)\n return render_template(\"map.html\", eventslist=events)\n\nif __name__ == '__main__':\n app.debug = True\n app.run()\n","sub_path":"eventmap.py","file_name":"eventmap.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"457785680","text":"import re\nimport requests\nimport telepot\nfrom time import sleep\nfrom bs4 import BeautifulSoup\nfrom yaml import load\nimport locale\nfrom IPython import embed\nimport sys\n\nlocale.setlocale(\n category=locale.LC_ALL,\n locale='de_DE.UTF-8',\n )\n\ntry:\n with open('/home/pi/Git/cryptobot/config.yaml') as f:\n config = load(f)\nexcept FileNotFoundError as e:\n # print(e)\n print('Config file in cryptobot directory not found, trying current directory.')\n try:\n with open('config.yaml') as f:\n config = load(f)\n except FileNotFoundError as e:\n # print(e)\n sys.exit('No config file found. Aborting ...')\n\ntoken = config['token']\nbot = telepot.Bot(token)\n\ncurrencies = [ # supported cryptocurrencies\n 'bitcoin',\n 'ethereum',\n 'iota'\n ]\ncommands = [ # implemented telegram commands\n '/start',\n '/bitcoin',\n '/bitcoin ',\n '/ethereum',\n '/ethereum ',\n '/iota',\n '/iota '\n ]\n\n# fallback answer if messages are not understood\nguide = 'Usage:\\n'\nfor command in commands:\n if command != commands[-1]:\n guide += \"- {}\\n\".format(command)\n else:\n guide += '- {}'.format(command)\n\n\ndef get_price(currency):\n '''Returns up-to-date price of currency.'''\n\n url = 'http://www.finanzen.net/devisen/{currency}-euro-kurs'.format(\n currency=currency)\n try:\n response = requests.get(url)\n except Exception as e:\n return 0 # there HAS TO BE a better way, but for now this needs to work\n\n soup = BeautifulSoup(response.text, 'html.parser')\n div = soup.find(\n \"div\", {\"class\": \"col-xs-5 col-sm-4 text-sm-right text-nowrap\"})\n\n x = r'[0-9]*\\.*[0-9]{1,3}\\,[0-9]{1,4}'\n price = re.findall(pattern=x, string=str(div))[0]\n\n #answer = '{curr} price is {price} EUR'.format(curr=currency, price=price)\n #return answer\n\n return locale.atof(price)\n\ndef get_value(currency, amount):\n price = get_price(currency)\n return amount*price\n\ndef answer(currency, amount=1):\n value = get_value(currency, amount)\n text_answer = 'Price for {amount} {curr} is {value} EUR'.format(curr=currency, amount=amount, value=value)\n return text_answer\n\ndef fallback(chat_id):\n '''Send fallback message if something is not quite right.'''\n bot.sendMessage(chat_id=chat_id, text=guide)\n\n\ndef handle(msg):\n\n content_type, chat_type, chat_id = telepot.glance(msg)\n\n if chat_id == 322086570:\n admin = True\n else:\n admin = False\n\n if content_type == 'text':\n command = msg['text']\n else:\n fallback(chat_id)\n return\n command = command[1:]\n command = command.split()\n if command[0] in currencies:\n if len(command) == 2:\n command[1] = command[1].replace(',', '.')\n bot.sendMessage(chat_id=chat_id, text=answer(command[0],float(command[1])))\n elif len(command) ==1:\n bot.sendMessage(chat_id=chat_id, text=answer(command[0]))\n else:\n bot.sendMessage(chat_id=chat_id, text='You have typed too many arguments.')\n fallback(chat_id)\n return\n else:\n fallback(chat_id)\n return\n return\n\n\n# Keep the bot listening and running\nprint('listening ...')\nbot.message_loop(handle)\n\nwhile True:\n sleep(10)\n # to send price information every `n` minutes check documentation of `telepot`\n # because there is a preimplemented function\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"584305758","text":"import numpy as npimg_i\nfrom commonlibs.analysis_tools.cocoeval_tools.coco_cls import COCO\nfrom commonlibs.analysis_tools.cocoeval_tools.cocoeval_cls import COCOeval\nfrom commonlibs.analysis_tools.cocoeval_tools.other_tools import split_cocos, split_resfiles\n\ndef eval_per_img(result_file, gt_ann_file, show_msg=False, img_ids=None):\n \"\"\"\n evaluate mAp, ... for every image\n :param result_file: result file\n :param gt_ann_file: gt coco annotation\n :return: {img_id: eval_results}\n \"\"\"\n # split coco and result for every image\n cocos = split_cocos(gt_ann_file, img_ids=img_ids)\n img_ids = cocos.keys()\n resfiles = split_resfiles(result_file, img_ids)\n eval_results = {}\n eval_results_str = {}\n # evaluate and get result\n for img_id, coco in cocos.items():\n result_file = resfiles[img_id]\n coco_dets = coco.loadRes(result_file)\n img_ids = coco.getImgIds()\n cocoEval = COCOeval(coco, coco_dets, 'bbox', show_msg=show_msg)\n cocoEval.params.imgIds = img_ids\n cocoEval.evaluate()\n cocoEval.accumulate()\n cocoEval.summarize()\n eval_results[img_id] = cocoEval.stats.tolist()\n eval_results_str[img_id] = cocoEval.stats_str\n\n return eval_results\n\nif __name__ == '__main__':\n res_file = '../../test_data/RESULT_retinanet_x101.bbox.json'\n ann_file = '../../test_data/instances_val2017.json'\n er = eval_per_img(res_file, ann_file, img_ids=[37777, 1000])\n print(er)\n\n\n","sub_path":"commonlibs/analysis_tools/coco_eval.py","file_name":"coco_eval.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"203469619","text":"\ndef digitos(n):\n while n != 0:\n r= n % 10\n n//=10\n print(r, end='')\n\ndef main():\n n = int(input('Digite su numero a acomodar verticalmente: '))\n print('')\n digitos(n)+1\nmain()","sub_path":"programas FNL/ciclo while 2.py","file_name":"ciclo while 2.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"600267595","text":"import os\nimport numpy as np\nfrom collections import OrderedDict as OD\n\n\n\n__all__ = ['get_lrt_cfg', 'get_cld_cfg', 'get_aer_cfg']\n\n\n\ndef get_lrt_cfg(\n lrt_fdir = os.environ['LIBRADTRAN_PY'],\n ssfr_fdir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'aux/ssfr'),\n spectral_resolution=0.1\n ):\n\n lrt_cfg = {\n 'executable_file' : '%s/bin/uvspec' % lrt_fdir,\n 'atmosphere_file' : '%s/data/atmmod/afglus.dat' % lrt_fdir,\n 'solar_file' : '%s/data/solar_flux/kurudz_%.1fnm.dat' % (lrt_fdir, spectral_resolution),\n 'data_files_path' : '%s/data' % lrt_fdir,\n 'rte_solver' : 'disort',\n 'number_of_streams' : 12,\n 'mol_abs_param' : 'LOWTRAN', # use 'reptran fine' for higher resolution\n 'slit_function_file_vis' : '%s/vis_%.1fnm_s.dat' % (ssfr_fdir, spectral_resolution),\n 'slit_function_file_nir' : '%s/nir_%.1fnm_s.dat' % (ssfr_fdir, spectral_resolution)\n }\n\n return lrt_cfg\n\n\n\ndef get_cld_cfg():\n\n cld_cfg = {\n 'cloud_file' : 'LRT_cloud_profile.txt',\n 'cloud_optical_thickness' : 20.0,\n 'cloud_effective_radius' : 10.0,\n 'liquid_water_content' : 0.02,\n 'cloud_type' : 'water', # or ice\n 'wc_properties' : 'mie',\n 'cloud_altitude' : np.arange(0.9, 1.31, 0.1)\n }\n\n return cld_cfg\n\n\n\ndef get_aer_cfg():\n\n aer_cfg = {\n 'aerosol_file': 'LRT_aerosol_profile.txt',\n 'aerosol_optical_depth' : 0.2,\n 'asymmetry_parameter' : 0.0,\n 'single_scattering_albedo' : 0.8,\n 'aerosol_altitude' : np.arange(3.0, 6.01, 0.2)\n }\n\n return aer_cfg\n\n\n\nif __name__ == '__main__':\n\n pass\n","sub_path":"lrt_util/cfg.py","file_name":"cfg.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"639010065","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 18 17:35:05 2019\n\n@author: Lycoris radiata\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 18 13:31:42 2019\n\n@author: Lycoris radiata\n\"\"\"\n#%%\nfrom PIL import Image, ImageDraw, ImageFont\nimport text_gen\nimport random\nimport numpy as np\nimport cv2 as cv2\nimport os\n#%% Paramters\n#row = 130\n#col = 130\nch = 1\n\n\nart = 'Library/Fonts/arial.ttf'\nwidth = 130\nheight_range = [35, 90, 120, 150, 180, 210]\n#scale = row/height\nfont_size = 28\nsteps = [-3, -2, -1, 0, 1, 2]\ny_compact = [-15, -10, -5, 0, 5, 10, 15]\n#steps = [-3]\ncaves = os.listdir('caves/')\nwith open ('annotation.txt', 'w'):\n pass\nwith open ('lexicon.txt', 'w'):\n pass\n#%%\nfor i in range(90000):\n height = random.choice(height_range)\n seed = random.randint(2,5)\n string = text_gen.gen(seed)\n # Special label a == \"/\", b = \"\\\"\n label = string\n string = string.replace(\"a\", \"/\").replace(\"b\", \"\\\\\")\n boxes = [0]*len(string)\n\n #%%\n cave = random.randint(0,3)\n im = Image.new(\"L\", (width, height), \"#fff\") \n flag = 0\n d = ImageDraw.Draw(im)\n x, y = 15, (height/2 - font_size/2) #The Anchor of the fucking text\n xx = 3\n flag_bar = 0\n falg_ul = 0\n\n #%% \n if falg_ul > 0.95:\n pirror = random.randint(1,len(string))\n last = random.randint( pirror,len(string))\n if random.random() > 0.95 and abs(pirror-last)>0 :\n # bar\n boxes[pirror:last] = [1]*abs(pirror-last)\n flag = 1\n elif abs(pirror-last)>0: \n #Lower\n boxes[pirror:last] = [-1]*abs(pirror-last)\n flag = -1\n #%% Draw\n y = (height/2 - font_size/2)\n for idx, val in enumerate(boxes):\n if val == 0:\n # Normal\n\n fill = '#000'\n font = ImageFont.truetype(art, font_size) # select the fucking art and size\n d.text((x, y), string[idx], font=font, fill = fill) # Draw labels and black color\n w = d.textsize(string[idx], font=font)[0] # Get fucking pirror of width\n x += w + random.choice(steps) # Anchor + width + Steps\n #y += font.getoffset(string[idx])[1] # Get fucking offset\n# else:\n# if idx <= 8:\n# y = 10\n# if cave == 0:\n# fill = '#fff'\n# else:\n# fill = '#000'\n# font = ImageFont.truetype(art, font_size) # select the fucking art and size\n# d.text((x, y), string[idx], font=font, fill = fill ) # Draw labels and black color\n# w = d.textsize(string[idx], font=font)[0] # Get fucking pirror of width\n# x += w + steps # Anchor + width + Steps\n# #y += font.getoffset(string[idx])[1] # Get fucking offset\n# else:\n# y = 25\n# if cave == 0:\n# fill = '#fff'\n# else:\n# fill = '#000'\n# font = ImageFont.truetype(art, font_size) # select the fucking art and size\n# d.text((xx, y), string[idx], font=font, fill = fill) # Draw labels and black color\n# w = d.textsize(string[idx], font=font)[0] # Get fucking pirror of width\n# xx += w + steps # Anchor + width + Steps\n# #y += font.getoffset(string[idx])[1] # Get fucking offset\n elif val == 1:\n # Upper\n y = height/2-font_size/2\n font = ImageFont.truetype(art, font_size)\n bars = '-'\n d.text((x, y), bars, font=font, fill=\"#000\") # Draw labels and black color\n w = d.textsize(bars, font=font)[0] # Get fucking pirror of width\n x += w + random.choice(steps) # Anchor + width + Steps\n #y += font.getoffset(string[idx])[1] # Get fucking offset\n elif val == -1:\n # Lower\n y = height/2-font_size/2\n font = ImageFont.truetype(art, int(font_size*0.8))\n h = d.textsize(string[idx], font=font)[1] # Get fucking pirror of height\n y += font_size/3.5\n d.text((x, y), string[idx], font=font, fill=\"#000\")\n w = d.textsize(string[idx], font=font)[0]\n x += w + random.choice(steps) # Anchor + width + Steps\n #%% - # \n if flag_bar > 0.95:\n font = ImageFont.truetype(art, font_size)\n counts = len(string)\n bars = '_'*(counts+1)\n h = d.textsize(bars, font=font)[1] # Get fucking pirror of height\n if flag == 0:\n ratio = 0.7\n elif flag == 1:\n ratio = 1\n elif flag == -1:\n ratio = 0.7\n x, y = 3, (height/2 - font_size*ratio - h)\n d.text((x, y), bars, font=font, fill=\"#000\")\n d.text((x, y+1), bars, font=font, fill=\"#000\")\n #%% Result\n if flag_bar > 0.95:\n label = label + 'b'\n #%%\n# im = cv2.resize(im, (31,31))\n# im = cv2.circle(im,(22, 22), 22, (0, 0, 0), 1)\n# im = cv2.resize(im, (200,31))\n# res = ''\n# for index, v in enumerate(boxes):\n# if v == 1:\n# res +='-'\n# else:\n# res += label[index]\n# res = res.replace('-', 'c')\n# cave = np.ones((row, col, ch))\n# cave *=255\n# anchor = int ((row - height)/2), int((col - width)/2)\n# y, x = anchor\n# cave[y:y+height, x:x+width, : ] = im\n# cave = cave.astype('uint8')\n #%%\n im = im.resize((130, 150),Image.ANTIALIAS)\n code = str(random.randint(0,10000))\n cv2.imwrite( './imgs/' + label + '_height' + str(height) + '_' + str(code) + '.png' , np.array(im))\n with open ('annotation.txt', 'a') as f:\n f.write('./imgs/' + label + '_height' + str(height) + '_' + str(code) + '.png' +' ' + str(i) + '\\n')\n with open ('lexicon.txt', 'a') as f:\n f.write(label + '\\n')\n\"\"\"\n原始碼\n\"\"\"\n #%% 上標\n #font = ImageFont.truetype(art, int(font_size*2/3))\n #h = d.textsize(\"T/M\", font=font)[1] # Get fucking pirror of height\n #y -= h / 2\n #d.text((x, y), \"T/M\", font=font, fill=\"#000\")\n #%% 下標\n #font = ImageFont.truetype(art, int(font_size*2/3))\n #h = d.textsize(\"T/M\", font=font)[1] # Get fucking pirror of height\n #y += h / 1.3\n #d.text((x, y), \"T/M\", font=font, fill=\"#000\")\n #%% 本體\n #font = ImageFont.truetype(art, font_size) # select the fucking art and size\n #d.text((x, y), string, font=font, fill=\"#000\") # Draw labels and black color\n #w = d.textsize(string, font=font)[0] # Get fucking pirror of width\n #x += w # Anchor + width\n #y += font.getoffset(string)[1] # Get fucking offset","sub_path":"sample3/gen-data/image-gen.py","file_name":"image-gen.py","file_ext":"py","file_size_in_byte":6650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"593534379","text":"''' Modul do obslugi kamery '''\nfrom PIL import Image, ImageTk\nimport cv2\n\nclass Cam(object):\n\n def __init__(self):\n self.zrzut = cv2.VideoCapture(0) # argument -> numer kamery w systemie\n def przechwytywanie(self, obroc_obraz=False):\n self.ret_val, self.ramka = self.zrzut.read()\n if obroc_obraz: self.ramka = cv2.flip(self.ramka, 1)\n self.cv2obraz = cv2.cvtColor(self.ramka, cv2.COLOR_BGR2RGBA)\n self.obraz = Image.fromarray(self.cv2obraz)\n def zapisz_zrzut(self, nazwa=\"Zrzut.jpg\"):\n ret_val, ramka = self.zrzut.read()\n cv2.imwrite(nazwa, ramka)\n\nclass Podglad(object):\n\n def __init__(self):\n\n self.okno = tk.Tk()\n self.okno.geometry('640x540')\n self.okno.title('Podgląd')\n self.kamera = Cam()\n self.monitor = tk.Label()\n self.monitor.grid(row=0, column=0)\n tk.Label().grid(row=1, column=0)\n tk.Button(text='Zrzut', width=50, command=\n self.kamera.zapisz_zrzut).grid(row=2, column=0)\n self.wyswietlanie()\n self.okno.mainloop()\n\n def wyswietlanie(self):\n\n self.kamera.przechwytywanie()\n self.obraz_tkinter = ImageTk.PhotoImage(image=self.kamera.obraz)\n self.monitor.config(image=self.obraz_tkinter)\n self.okno.after(40, self.wyswietlanie)\n\nif __name__ == '__main__':\n\n import tkinter as tk\n panel = Podglad()\n","sub_path":"kamera.py","file_name":"kamera.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"140868006","text":"#-------------------------------------------------------------------------------\n# Name: Uniform Cost Search\n# Purpose:\n#\n# Author: Michael Mullen\n#\n# Created: OCT 2013\n# Copyright: Open Source (c) Michael 2013\n# Licence: Open Source\n#-------------------------------------------------------------------------------\nimport bisect\nimport operator\nclass node:\n nValue = 0\n pNode = 0\n nCost = 0\n nDepth = 0\n def __init__(self, nodeValue,parentNode,nodeCost,nodeDepth):\n self.nValue = nodeValue\n self.pNode = parentNode\n self.nCost = nodeCost\n self.nDepth = nodeDepth\n\n def __lt__(self,other):\n return self.nCost < other.nCost\n def __gt__(self,other):\n return self.nCost > other.nCost\n\n def getChildren(self,pNode):\n \"\"\"get children of a node\"\"\"\n rNode = pNode.nValue*2\n lNode = pNode.nValue*2+1\n #rNodeCost = pNode.nCost+1\n #lNodeCost = pNode.nCost+10\n rNodeCost = pNode.nCost\n lNodeCost = pNode.nCost\n return[node(rNode,pNode.nValue,rNodeCost,(pNode.nDepth + 1)),node(lNode,pNode.nValue,lNodeCost,(pNode.nDepth + 1))]\n\n\nclass uniformCostSearch():\n \"\"\" Completes a best-first search\"\"\"\n \"\"\"NOTE providing '0' as a 'maxDepth' value allows an infinit search depth\"\"\"\n frontier = list() #sorted list\n explored = list()\n tested = list()\n goal = 0\n maxDepth = 0\n\n def __init__(self,firstNode,goalValue,maxDepth):\n self.frontier.append(firstNode)\n self.goal = goalValue\n self.maxDepth = maxDepth\n\n def explore(self):\n \"\"\"Explore for a solution\"\"\"\n curNode = node(0,0,0,0)\n solutionNode = (0,0,0,0)\n found = False\n self.frontierIsEmpty()\n\n #test child nodes\n while((not self.frontierIsEmpty()) and (not found)):\n\n \"\"\"print('-----------------new-----------------')#DEBUG\n print('current frontier:')#DEBUG\n self.printlist(self.frontier)#DEBUG\n print('current explored nodes:')#DEBUG\n self.printlist(self.explored)#DEBUG\"\"\"\n\n curNode = self.frontier.pop(0)\n if self.goalReached(curNode.nValue):\n self.addToExplored(curNode)\n found = True\n solutionNode = curNode\n break\n self.addToExplored(curNode)\n #print('current node is: %i' % curNode.nValue) #DEBUG\n if (curNode.nDepth < self.maxDepth or self.maxDepth == 0):\n children = curNode.getChildren(curNode)\n for child in children:\n #print (\"current child value: %i\" % child.nValue) #DEBUG\n if (not self.inExplored(child.nValue)) and (not self.inFrontier(child.nValue)):\n self.addToFrontier(child)\n else:\n childBetter(child)\n if(found):\n print(\"Uniform Cost Search FOUND A SOLUTION %i\" % solutionNode.nValue)\n print(\"here are the nodes visited:\")\n self.printlist(self.explored)\n elif not found and self.frontierIsEmpty():\n print(\"FAILURE, Uniform Cost Search did not find a solution\")\n print(\"here are the nodes visited:\")\n self.printlist(self.explored)\n\n def childBetter(child):\n x = 0\n max = len(self.frontier)\n while x < max:\n if (child.nValue == self.frontier[x].nValue and\n child.nCost < self.frontier[x].nCost):\n frontier[x] = child\n break\n\n\n\n def inExplored(self,curValue):\n \"\"\"check if node state is in explored list\"\"\"\n for x in self.explored:\n if( curValue == x.nValue):\n return True\n return False\n\n def addToExplored(self,curNode):\n self.explored.append(curNode)\n\n def inFrontier(self,curValue):\n \"\"\"check if node state is in frontier list\"\"\"\n for x in self.frontier:\n if( curValue == x.nValue):\n return True\n return False\n\n def frontierIsEmpty(self):\n \"\"\"check if frontier is empty\"\"\"\n if (len(self.frontier) > 0):\n return False\n return True\n\n def addToFrontier(self,curNode):\n \"\"\"add node to frontier\"\"\"\n if self.frontierIsEmpty():\n self.frontier.append(curNode)\n else:\n bisect.insort_right(self.frontier,curNode)\n\n\n def goalReached(self,nValue):\n \"\"\"YAY GOAL IS REACHED WE\"RE DONE\"\"\"\n if nValue == self.goal:\n return True\n return False\n\n def printlist(self,list):\n \"\"\"Utility for printing lists\"\"\"\n for item in list:\n print(item.nValue,end=', ')\n print('')\n def printListAndCost(self,list):\n for item in list:\n print(item.nValue,end=':')\n print(item.nCost,end=\", \")\n print('')\n\n\n\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n goalNode = 15\n maxDepth = 3\n\n startingNode = node(1,0,0,0)\n\n UCS = uniformCostSearch(startingNode,goalNode,maxDepth)\n UCS.explore()\n\nprint(\"DONE\")","sub_path":"Uniform Cost Search.py","file_name":"Uniform Cost Search.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"461045579","text":"\"\"\"dollar_word.py: Determines if words from a file are dollar words and writes the ones that are to a file.\"\"\"\n\nimport string\nimport os\n\nFROM_FILE = \"wordsEn.txt\"\nTO_FILE = \"dollarWords.txt\"\n\n\ndef word_value(word):\n if word.isalpha():\n return sum([string.ascii_lowercase.index(letter) + 1 for letter in word.lower()])\n return None\n\n\n# Main\ndef main():\n dictionary = None\n successful = None\n try:\n dictionary = open(\"{}/{}\".format(os.getcwd(), FROM_FILE))\n successful = open(\"{}/{}\".format(os.getcwd(), TO_FILE), \"w\")\n count = 0\n for word in dictionary:\n if word_value(word.rstrip()) == 100:\n successful.write(word)\n count += 1\n print(\"{!s} dollar words found!\".format(count))\n\n except Exception:\n print(\"*** Something bad happened!!! ***\")\n finally:\n if not dictionary == None:\n dictionary.close()\n if not successful == None:\n successful.close()\n input()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/dollar_word.py","file_name":"dollar_word.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"375529873","text":"# coding: utf-8\n\"\"\"A starter to start task.\nversion 2.0\n引入py文件后,在nds里面执行。\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import with_statement\nfrom ndscheduler import job\nimport yaml\nimport sys\nfrom importlib import import_module\nimport json\n\n'''configure the log'''\nimport logging\nimport logging.handlers\n\ninfile = 'mylogs/run_in_nds_job.log'\nhandler = logging.handlers.RotatingFileHandler(infile, mode='a', maxBytes=500 * 1024 * 1024, backupCount=3)\nfmt = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'\n\nformatter = logging.Formatter(fmt)\nhandler.setFormatter(formatter)\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(handler)\nlogger.setLevel(logging.INFO)\n\n\nclass RunInNdsJob(job.JobBase):\n\n @classmethod\n def meta_info(cls):\n return {\n 'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),\n 'notes': '配置任务信息',\n 'arguments': [\n # argument1\n {'type': 'dict', 'description': '在 tasks.yaml [任务列表配置文件] 中的任务名'}\n\n ],\n 'example_arguments': '[{\\\"task_name\\\": \\\"task1\\\"}]'\n }\n\n def run(self, kw_dict, *args, **kwargs):\n\n try:\n with open('tasks.yaml', 'r', encoding='utf-8') as f:\n tasks_dict = yaml.load(f.read())\n except Exception as e:\n with open('tasks.yaml', 'r') as f:\n tasks_dict = yaml.load(f.read())\n\n task_name = kw_dict.get('task_name')\n task_dict = tasks_dict[task_name]\n logger.info(task_dict)\n logger.info('Now is ready to run task %s' % task_dict['name'])\n\n # 即将启动的任务的输入参数\n task_params = task_dict.get('params')\n if task_params is None:\n task_params = {}\n\n # 即将启动的任务所在路径(到dir一层) --> 好像有缺陷!\n # 不用安装也可以了!! 直接引入\n sys.path.append(task_dict['env_path'])\n env_path = task_dict.get('path_dir')\n sys.path.append(env_path)\n\n # 模块名(文件名以.py结束)\n try:\n o = import_module(task_dict['file_name'].split('.py')[0])\n o.start_task(**task_params)\n\n logger.info(('Task %s has been finished.' % task_name))\n\n # 删掉刚刚引入的包,确保每次都是最新的\n sys.path.remove(env_path)\n sys.path.remove(task_dict['env_path'])\n del o\n\n except Exception as e:\n logger.error('Task %s failed. - %s' % (task_name, e))\n raise e\n\n return [json.dumps(task_dict)]\n\n\nif __name__ == \"__main__\":\n # You can easily test this job here\n job = RunInNdsJob.create_test_instance()\n job.run()\n","sub_path":"simple_scheduler/jobs/run_in_nds_job.py","file_name":"run_in_nds_job.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"379243045","text":"\n\nout = 0\n\ndef modexp(x,y,mod):\n if x==1 or y==0:\n return 1\n elif y==1:\n return x%mod\n else:\n z = modexp(x,int(y/2),mod)\n if y%2==1:\n return ((z%mod)*(z%mod)*(y%mod))%mod\n else:\n return ((z%mod)*(z%mod))%mod\n\n\nfor i in range(1,1001):\n num = modexp(i,i,10000000000)\n #num = pow(i,i,10000000000)\n out = (out + num)%10000000000\n\nprint(out)\n","sub_path":"q48.py","file_name":"q48.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"360110180","text":"from html.parser import HTMLParser\n\nfrom I10PY94 import out_by_keys\n\n__author__ = \"Ettore Forigo\"\n__license__ = \"GPL\"\n__date__ = \"22/03/2017\"\n__version__ = \"1\"\n__status__ = \"Development\"\n__doc__ = '''\nDato un file html, inserisce , se presenti e tramite la funzione contaTag, in un dizionario il numero di occorrenze dei\nseguenti tags [html,body,p,br,div,table,td,tr,ol,ul]\n'''\n\n\nclass Parser(HTMLParser):\n\tdef __init__(self, dict_):\n\t\tHTMLParser.__init__(self)\n\t\tself.dict_ = dict_\n\n\tdef handle_starttag(self, tag, attrs):\n\t\tself.dict_.update({tag: self.dict_.get(tag, 0) + 1})\n\n\tdef error(self, message):\n\t\tpass\n\n\ndef conta_tag(dict_, data):\n\tparser = Parser(dict_)\n\tparser.feed(data)\n\n\ndef main():\n\ttag_occurrences = {}\n\n\twith open(\"data.html\") as file:\n\t\tconta_tag(tag_occurrences, file.read())\n\n\tprint(out_by_keys(tag_occurrences))\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"2016-2017/Consegne/I10PY1_2.py","file_name":"I10PY1_2.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"345318151","text":"### 전처리 코드\n# https://omicro03.medium.com/%EC%9E%90%EC%97%B0%EC%96%B4%EC%B2%98%EB%A6%AC-nlp-15%EC%9D%BC%EC%B0%A8-fasttext-2b1aca6b3b56\n# https://github.com/nltk/nltk_data download nltk\n\nimport re\nimport timeit\n# from lxml import etree\n# import nltk\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nfrom konlpy.tag import Mecab\nfrom util.utilmanager import build_analyzer, to_jaso, tokenize_by_morpheme_char, tokenize_by_morpheme_jaso, get_one_edit_apart_words\nfrom ir.base import Tfidf\n\n# def g2tfidf(docs, q):\n# s = timeit.default_timer()\n# tfidf = Tfidf()\n# tfidf.fit(docs)\n# result, score = tfidf.query(str(q), return_scores=True)\n# ttime = timeit.default_timer() - s\n# print('g2tfidf ttime: %s' % ttime)\n# print(g2tfidf)\n# print(result[0])\n# print(result, score)\n# if not result:\n# return None\n# return result[0]\n\n\nmecab = Mecab()\nmorphs_l = mecab.morphs('영등포구청역에 있는 맛집 좀 알려주세요.')\nmorphs_txt = ' '.join(morphs_l)\n# print('morphs_txt')\n# print(morphs_txt)\n# targetXML = open('./ted_en-20160408.xml', 'r', encoding='UTF8')\n# target_text = etree.parse(targetXML)\n# parse_text = '\\n'.join(target_text.xpath('//content/text()'))\n# xml 파일로부터 사이의 내용만 가져온다.\n\nparse_text = '# 정규 표현식의 5g sub 모듈을 통해 content 중간에 등장하는 (Audio), (Laughter) 등의 배경음 부분을 제거. 휴대폰을 찾아줘'\n\ncontent_text = re.sub(r'\\([^)]*\\)', '', parse_text)\n# 정규 표현식의 sub 모듈을 통해 content 중간에 등장하는 (Audio), (Laughter) 등의 배경음 부분을 제거.\nsent_text = sent_tokenize(content_text)\n# 입력 코퍼스에 대해서 NLTK를 이용하여 문장 토큰화를 수행한다.\nnormalized_text = []\n\n# 글자단위 + nouns\nfor string in sent_text:\n # tokens = re.sub(r\"[^a-z0-9]+\", \" \", string.lower())\n tokens = re.sub(r\"[^a-z0-9|ㄱ-ㅎ|ㅏ-ㅣ|가-힣]+\", \" \", string.lower())\n print('tokens')\n print(tokens)\n\n nouns = mecab.nouns(tokens)\n nouns_txt = ' '.join(nouns)\n print('nouns_txt')\n print(nouns_txt)\n\n morphs_l = mecab.morphs(tokens)\n morphs_txt = ' '.join(morphs_l)\n print('morphs_txt')\n print(morphs_txt)\n\n # normalized_text.append(tokens)\n normalized_text.append(tokens + ' ' + nouns_txt)\n\n# # 글자단위 + 형태소 + nouns\n# for string in sent_text:\n# # tokens = re.sub(r\"[^a-z0-9]+\", \" \", string.lower())\n# tokens = re.sub(r\"[^a-z0-9|ㄱ-ㅎ|ㅏ-ㅣ|가-힣]+\", \" \", string.lower())\n# print('tokens')\n# print(tokens)\n#\n# nouns = mecab.nouns(tokens)\n# nouns_txt = ' '.join(nouns)\n# print('nouns_txt')\n# print(nouns_txt)\n#\n# morphs_l = mecab.morphs(tokens)\n# morphs_txt = ' '.join(morphs_l)\n# print('morphs_txt')\n# print(morphs_txt)\n#\n# # normalized_text.append(tokens)\n# normalized_text.append(tokens + ' ' + nouns_txt + ' ' + morphs_txt)\n\n\n\n# 글자+형태소+노멀라이즈 단위\n# for string in sent_text:\n# # tokens = re.sub(r\"[^a-z0-9]+\", \" \", string.lower())\n# tokens = re.sub(r\"[^a-z0-9|ㄱ-ㅎ|ㅏ-ㅣ|가-힣]+\", \" \", string.lower())\n# print('tokens')\n# print(tokens)\n# tokenize_morphem_char_l = tokenize_by_morpheme_char(tokens)\n#\n# print('tokenize_morphem_char_l')\n# print(tokenize_morphem_char_l)\n# morphs_txt = ' '.join(tokenize_morphem_char_l)\n# print('morphs_txt')\n# print(morphs_txt)\n# normalized_text.append(morphs_txt)\n\n# 자소단위\n# for string in sent_text:\n# tokenize_morphem_char_l = tokenize_by_morpheme_jaso(string)\n# print('tokenize_morphem_char_l')\n# print(tokenize_morphem_char_l)\n# tokens = ' '.join(tokenize_morphem_char_l)\n# morphs_txt = ' '.join(mecab.morphs(tokens))\n# print('morphs_txt')\n# print(morphs_txt)\n# normalized_text.append(morphs_txt)\n# print('normalized_text')\n# print(normalized_text)\n\n\ndocs = []\ndocs = [word_tokenize(sentence) for sentence in normalized_text]\nprint('docs')\nprint(docs)\n\n\n\n### FastText 학습\n# https://radimrehurek.com/gensim/models/fasttext.html\nfrom gensim.models import FastText, Word2Vec\n# ft_model = FastText(docs, size=100, window=5, min_count=1, workers=4, sg=1)\n# ft_model.save('ft.model')\n# fx = load_ft_model.wv\nprint('allllllllllllllll')\n# print(fx)\n\n\nload_ft_model = FastText.load('ft.model')\nfx = load_ft_model.wv.most_similar('5gg')\nprint(\"5gg\")\nprint(fx)\n\n\ns = timeit.default_timer()\nq = '후대폰'\nq_jaso = to_jaso(q)\nfx = load_ft_model.wv.most_similar(q)\nttime = timeit.default_timer() - s\nprint('q=%s' % q)\nprint('q_jaso=%s' % q_jaso)\nprint('ttime:%s' % ttime)\nprint(fx)\n\ns = timeit.default_timer()\nq = '배경'\nq_jaso = to_jaso(q)\nfx = load_ft_model.wv.most_similar(q)\nttime = timeit.default_timer() - s\nprint('q=%s' % q)\nprint('q_jaso=%s' % q_jaso)\nprint('ttime:%s' % ttime)\nprint(fx)\n\n\ns = timeit.default_timer()\nq = '5g 후대폰에 대해서 알려줘'\nmecab = Mecab()\nq_morph_l = mecab.morphs(q)\n\nq_jaso = to_jaso(q)\nfx = load_ft_model.wv.most_similar(positive=q_morph_l, topn=30)\n\nif fx:\n ls = list(map(lambda x: x[0], fx))\n\nttime = timeit.default_timer() - s\nprint('q=%s' % q)\nprint('q_jaso=%s' % q_jaso)\nprint('ttime:%s' % ttime)\nprint(fx)\n\nsimilar_l = get_one_edit_apart_words(ls, q)\n\n\n\n\n# w2v_model = Word2Vec(docs, size=100, window=5, min_count=1, workers=4, sg=1)\n# wx = w2v_model.wv.most_similar('5gg')\n# print(wx)\n","sub_path":"ztst/ztest/fasttext_test.py","file_name":"fasttext_test.py","file_ext":"py","file_size_in_byte":5428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"74678174","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport pymongo\nimport traceback\nfrom scrapy.loader.processors import TakeFirst\n\n\ndef contain_keyword(title):\n flag = 0\n back = title[-2:]\n up = title[:-2]\n back_keywords = u'指南,通知,公告'\n up_keywords = u'征集,申报,采购,项目,课题,专项,资金,招标,挂牌,出让'\n # 判断关键词是否存在后部\n for key in back_keywords.split(','):\n if back.find(key) != -1:\n flag = 1\n break\n # 判断关键词是否存在前部\n if flag == 1:\n for key in up_keywords.split(','):\n if up.find(key) != -1:\n return False\n other_keywords = u'结果公告、结果的公告、结果公示、' \\\n u'评审结果、中标公告、项目立项、' \\\n u'拟支持项目、项目实施、结题、' \\\n u'验收、监督、检查、入选、下达、' \\\n u'公示××项目、公布××的公告、公布××项目、' \\\n u'制度、管理办法、暂行办法、管理规定、目录、' \\\n u'需求、专家、预算、决算、概算、审计、' \\\n u'会计师事务所、召开、会议、汇报会、评审会、' \\\n u'评审工作、账户信息、严禁、有关问题、岗位、' \\\n u'培训工作、提供查询服务、落实、印发、征求、' \\\n u'意见、统计工作、任务书、任务完成情况、统计调查、' \\\n u'就业有关工作、方案公示、有关工作'\n for key in other_keywords.split(','):\n if title.find(key) != -1:\n return False\n return True\n\n\nclass MongoPipeline(object):\n \"\"\"保存爬取到的信息到数据\"\"\"\n\n def __init__(self, host, port, dbname, docname):\n self.host = host\n self.port = port\n self.dbname = dbname\n self.docname = docname\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(host=crawler.settings.get('MONGODB_HOST'),\n port=crawler.settings.get('MONGODB_PORT'),\n dbname=crawler.settings.get('MONGODB_DBNAME'),\n docname=crawler.settings.get('MONGODB_DOCNAME'))\n\n def open_spider(self, spider):\n try:\n server = pymongo.MongoClient(port=self.port, host=self.host)\n db = server[self.dbname]\n self.db = db[self.docname]\n except Exception as e:\n traceback.print_exc()\n else:\n spider.logger.info('Mongodb connections successfully!')\n\n def process_item(self, item, spider):\n item = dict(item)\n self.db.insert(item)\n return item\n\n\n","sub_path":"build/lib/generic/pipelines/mongodb.py","file_name":"mongodb.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"454950162","text":"\nimport cffi\nimport nose.tools\n\nimport cle\n\ndef test_cclemory():\n # This is a test case for C-backed Clemory.\n\n clemory = cle.Clemory(None, root=True)\n clemory.add_backer(0, \"\\x90\" * 1000)\n clemory.add_backer(2000, \"A\" * 1000)\n clemory.add_backer(3000, \"ABCDEFGH\")\n clemory._flatten_to_c()\n\n ffi = cffi.FFI()\n ffi.cdef(\"\"\"\n int memcmp(const void* s1, const void* s2, size_t n);\n \"\"\")\n c = ffi.verify(\"\"\"\n #include \n \"\"\")\n # pylint: disable=no-member\n byte_str = clemory.read_bytes_c(0)[0]\n out = c.memcmp(ffi.new(\"unsigned char []\", \"\\x90\" * 10), byte_str, 10)\n nose.tools.assert_equal(out, 0)\n\n byte_str = clemory.read_bytes_c(2000)[0]\n out = c.memcmp(ffi.new(\"unsigned char []\", \"B\" * 1000), byte_str, 1000)\n nose.tools.assert_not_equal(out, 0)\n out = c.memcmp(ffi.new(\"unsigned char []\", \"A\" * 1000), byte_str, 1000)\n nose.tools.assert_equal(out, 0)\n\n byte_str = clemory.read_bytes_c(3000)[0]\n out = c.memcmp(ffi.new(\"unsigned char []\", \"ABCDEFGH\"), byte_str, 8)\n nose.tools.assert_equal(out, 0)\n\ndef test_clemory():\n # directly write bytes to backers\n clemory = cle.Clemory(None, root=True)\n clemory.add_backer(0, \"A\" * 20)\n clemory.add_backer(20, \"A\" * 20)\n clemory.add_backer(50, \"A\" * 20)\n nose.tools.assert_equal(len(clemory._backers), 3)\n\n clemory.write_bytes_to_backer(10, \"B\" * 70)\n\n nose.tools.assert_equal(len(clemory._backers), 4)\n nose.tools.assert_equal(\"\".join(clemory.read_bytes(0, 80)), \"A\" * 10 + \"B\" * 70)\n\n\n clemory = cle.Clemory(None, root=True)\n clemory.add_backer(10, \"A\" * 20)\n clemory.add_backer(50, \"A\" * 20)\n nose.tools.assert_equal(len(clemory._backers), 2)\n clemory.write_bytes_to_backer(0, \"\") # Should not except out\n nose.tools.assert_equal(len(clemory._backers), 2)\n clemory.write_bytes_to_backer(0, \"B\" * 10)\n nose.tools.assert_equal(len(clemory._backers), 3)\n nose.tools.assert_equal(\"\".join(clemory.read_bytes(0, 25)), \"B\" * 10 + \"A\" * 15)\n\ndef main():\n g = globals()\n for func_name, func in g.iteritems():\n if func_name.startswith('test_') and hasattr(func, '__call__'):\n func()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tests/test_clemory.py","file_name":"test_clemory.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"219516168","text":"# coding:utf8\n\nimport os\nimport random\nimport re\nimport subprocess\nimport shutil\nfrom functools import reduce\nfrom os.path import abspath\nfrom io import open\nimport sys\n\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\n\ncurDir = os.path.split(os.path.abspath(sys.argv[0]))[0]\nprint(\"file dir \" + curDir)\noutDir = curDir + '/../out'\napktool = curDir + '/../tools/apktool_2.3.1.jar'\n# srcApk = '../com.csfo.omys___pie.apk'\n# targetApk = '../app-release.apk'\naapt = curDir + '/../tools/aapt.exe'\n\nkey = '{http://schemas.android.com/apk/res/android}name'\n\nkeystory_alias_password = \"123123\"\nkeystory_store_password = \"123123\"\n# keystory_store = \"../Everychange.key\"\n# keystory_alias = \"com.moe.omo\"\n\ntmpApk = \"tmp.apk\"\n\n\ndef unpack(src, dist):\n dist = os.path.join(dist, fileName(src))\n\n print(\"[+] unpack: \" + src)\n if os.path.exists(dist):\n shutil.rmtree(dist)\n\n cmd = ['java', '-jar', os.path.abspath(apktool), 'd', src, '-f', '-o', dist]\n try:\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n code = process.wait()\n if not code == 0:\n raise Exception(\"unpack failed:\" + str(stderr.decode(\"utf-8\")))\n else:\n pass\n # print(\"[+] \" + str(stdout, encoding=\"utf-8\"))\n except Exception as e:\n print('[-]' + str(e))\n raise e\n\n\ndef copytree(src, dst, symlinks=False):\n names = os.listdir(src)\n if not os.path.isdir(dst):\n os.makedirs(dst)\n errors = []\n for name in names:\n srcname = os.path.join(src, name)\n dstname = os.path.join(dst, name)\n try:\n if symlinks and os.path.islink(srcname):\n linkto = os.readlink(srcname)\n os.symlink(linkto, dstname)\n elif os.path.isdir(srcname):\n copytree(srcname, dstname, symlinks)\n else:\n if os.path.isdir(dstname):\n os.rmdir(dstname)\n elif os.path.isfile(dstname):\n os.remove(dstname)\n shutil.copy2(srcname, dstname)\n except (IOError, os.error) as why:\n errors.append((srcname, dstname, str(why)))\n except OSError as err:\n errors.extend(err.args[0])\n\n try:\n shutil.copystat(src, dst)\n except WindowsError:\n pass\n except OSError as why:\n errors.extend((src, dst, str(why)))\n if errors:\n raise shutil.Error(errors)\n\n\ndef fileName(f):\n return os.path.basename(f).split('.apk')[0]\n\n\ndef rePackage(src, dst):\n try:\n src = os.path.abspath(os.path.normpath(src))\n print(\"[+] repackage \", src, \" -> \", dst)\n cmd = ['java', '-jar', apktool, 'b', src, '-f', '-o', dst]\n p = subprocess.Popen(cmd)\n p.wait()\n except Exception as e:\n print(\"[-]\" + str(e))\n exit(-1)\n\n\ndef main():\n # process()\n mergeManifest(r\"E:\\PycharmProjects\\repacktool\\out\\app-release\", r\"E:\\PycharmProjects\\repacktool\\out\\com.bxdw.omzw___pie\"\n , r\"E:\\PycharmProjects\\repacktool\\out\\IMEI_Show\", \"\", True)\n pass\n\n\ndef process(src, dst, keyalias, keydir, rpackename, dynamic, gp):\n global servicePckName\n srcApk = src\n targetApk = dst\n dynamicApk = dynamic\n keystory_alias = keyalias\n out_src_dir = os.path.join(outDir, fileName(srcApk))\n out_dst_dir = os.path.join(outDir, fileName(targetApk))\n out_dyn_dir = os.path.join(outDir, fileName(dynamicApk))\n apks = [srcApk, targetApk]\n if gp:\n apks.append(dynamicApk)\n\n for apk in apks:\n unpack(os.path.abspath(apk), os.path.abspath(outDir))\n mergeApk(out_dst_dir, out_src_dir, out_dyn_dir, rpackename, gp)\n tmpApk_dir = os.path.join(outDir, tmpApk)\n signApk_dir = os.path.join(outDir, fileName(targetApk) + \".apk\")\n rePackage(out_dst_dir, abspath(tmpApk_dir))\n signApk(abspath(tmpApk_dir), abspath(signApk_dir), keystory_alias, abspath(keydir))\n\n removeTempFiles(tmpApk_dir)\n\n\ndef removeTempFiles(tmpApk_dir):\n print(\"[**] remove temporary files....\")\n try:\n os.remove(abspath(tmpApk_dir))\n for dir in os.listdir(abspath(outDir)):\n file = os.path.join(abspath(outDir), dir);\n if os.path.isdir(file):\n shutil.rmtree(file)\n except:\n pass\n\n print(\"[+] packed finish!!\")\n\n\ndef mergeApk(out_dst_dir, out_src_dir, out_dyn_dir, rePackageName, gp):\n copy_srcapk_file(out_dst_dir, out_src_dir)\n dst_activityList, dst_root, src_root = mergeManifest(out_src_dir, out_dst_dir, out_dyn_dir, rePackageName, gp)\n setStartService(dst_activityList, dst_root, out_dst_dir, src_root, gp)\n\n\ndef setStartService(dst_activityList, dst_root, out_dst_dir, src_root, gp):\n global servicePckName\n onCreateClass = dst_root.find(\"application\").attrib.get(key, None)\n servicePckName = getSourceServiceNameList(src_root)[0].replace(\".\", \"/\")\n print(\"[+] \" + servicePckName)\n if onCreateClass == None:\n for activity in dst_activityList:\n for i in activity.findall('intent-filter'):\n actions = i.findall('action')\n category = i.findall('category')\n l = [a.attrib.get(key) for a in actions]\n l += [a.attrib.get(key) for a in category]\n\n if 'android.intent.action.MAIN' in l and 'android.intent.category.LAUNCHER' in l:\n onCreateClass = activity.attrib.get(key)\n break\n\n if not onCreateClass:\n raise Exception(\"find onCreate fail!\")\n\n print(\"[+] \" + onCreateClass)\n classPath = os.path.join(out_dst_dir, \"smali\", onCreateClass.replace('.', '/') + \".smali\")\n wstr = \"\"\n with open(os.path.normpath(classPath), 'r', encoding='utf-8') as f:\n match = False\n inject = False\n for line in f:\n if re.search(\"^\\.method (protected|public) onCreate\\((Landroid/os/Bundle;)?\\)V$\", line):\n print(\"[+] %s find onCreate: %s\" % (onCreateClass, line))\n match = True\n\n if re.search(\"\\.end method\", line) and match:\n match = False\n inject = True\n\n if match:\n if re.search(\"return-void\", line):\n oldline = line\n line = ''\n if gp:\n pckname = servicePckName.split('/')\n line += '\\n\\tconst-string v0, \"%s\"\\n' % \".\".join(pckname[:-1])\n line += '\\n\\tinvoke-static {v0}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V\\n'\n\n line += '\\n\\tinvoke-virtual {p0}, L' + onCreateClass.replace('.',\n '/') + ';->getApplicationContext()Landroid/content/Context;\\n'\n\n line += '\\n\\tmove-result-object v0\\n'\n\n line += '\\n\\tconst/4 v1, 0x0\\n'\n\n line += '\\n\\tinvoke-static {v0, v1}, L' + servicePckName + ';->Activity' + ''.join(\n pckname[-2:-1]) + '_a(Landroid/content/Context;Landroid/content/Intent;)V\\n'\n\n line += \"\\n\\tnew-instance v0, Landroid/content/Intent;\\n\\n\" \\\n \"\\tconst-class v1, L\" + servicePckName + \";\\n\\n\" \\\n \"\\tinvoke-direct {v0, p0, v1}, Landroid/content/Intent;->(Landroid/content/Context;Ljava/lang/Class;)V\\n\\n\" \\\n \"\\tinvoke-virtual {p0, v0}, Landroid/content/Context;->startService(Landroid/content/Intent;)Landroid/content/ComponentName;\\n\\n\"\n if gp:\n # finish\n line += '\\n\\tinvoke-virtual{p0}, L%s;->finish()V\\n' % (onCreateClass.replace('.', '/'),)\n line += oldline\n\n if re.search(\"\\.locals (\\d)\", line):\n pattern = re.match(\"(\\s*\\.locals )(\\d)\", line)\n if int(pattern.group(2)) < 3:\n line = pattern.group(1) + \"3\\n\"\n\n wstr += line\n\n f.close()\n if not inject:\n raise Exception(\"set start service failed! \" + onCreateClass)\n with open(classPath, 'w') as f:\n if gp:\n wstr += addExitCode(onCreateClass)\n f.writelines(wstr)\n f.close()\n\ndef addExitCode(activity):\n line = '\\n\\n'\n line += '.method public onKeyDown(ILandroid/view/KeyEvent;)Z\\n'\n line += '\\t.locals 2\\n'\n line += '\\t.param p1, \"keyCode\" # I\\n'\n line += '\\t.param p2, \"event\" # Landroid/view/KeyEvent;\\n\\n'\n\n line += '\\t.prologue\\n'\n line += '\\tconst/4 v0, 0x0\\n\\n'\n\n line += '\\t.line 122\\n'\n line += '\\tconst/4 v1, 0x4\\n\\n'\n\n line += '\\tif-ne p1, v1,:cond_0\\n\\n'\n\n line += '\\t.line 123\\n\\n'\n line += '\\tinvoke-virtual {p0}, L%s;->finish()V\\n\\n' % activity.replace('.', '/')\n\n line += '\\t.line 124\\n'\n line += '\\tinvoke-static {v0}, Ljava/lang/System;->exit(I) V\\n\\n'\n\n line += '\\t.line 127\\n'\n line += '\\t:goto_0\\n'\n line += '\\treturn v0\\n\\n'\n\n line += '\\t:cond_0\\n'\n line += '\\tinvoke-super {p0, p1, p2}, Landroid/app/Activity;->onKeyDown(ILandroid/view/KeyEvent;)Z\\n\\n'\n\n line += '\\tmove-result v0\\n\\n'\n\n line += '\\tgoto:goto_0\\n\\n'\n\n line += '.end method'\n return line\n\ndef mergeManifest(out_src_dir, out_dst_dir, out_dyn_dir, rpackename, gp):\n srcManifestDir = os.path.join(out_src_dir, 'AndroidManifest.xml')\n dstManifestDir = os.path.join(out_dst_dir, 'AndroidManifest.xml')\n src_tree = parse_Manifest(srcManifestDir)\n src_root = src_tree.getroot()\n dst_tree = parse_Manifest(dstManifestDir)\n dst_root = dst_tree.getroot()\n src_perm = getSourcePermList(src_root)\n dst_perm = getSourcePermList(dst_root)\n # dst_perm = list(src_perm.union(dst_perm))\n # dst_perm = reduce(a, [[], ] + dst_perm)\n metaDataList = getSourceMetadataList(src_root)\n serviceList = getSourceServiceList(src_root)\n activityList = getSourceActList(src_root)\n receiverList = getSourceReceiverList(src_root)\n dst_metaDataList = getSourceMetadataList(dst_root)\n dst_serviceList = getSourceServiceList(dst_root)\n dst_activityList = getSourceActList(dst_root)\n dst_receiverList = getSourceReceiverList(dst_root)\n metaDataList = NameDifference(metaDataList, dst_metaDataList)\n serviceList = NameDifference(serviceList, dst_serviceList)\n receiverList = NameDifference(receiverList, dst_receiverList)\n\n isgp = gp\n # < activity\n # android:name = \"jp.wamo.amo.Activityamo\"\n # android:excludeFromRecents = \"true\"\n # android:theme = \"@android:style/Theme.Translucent\"\n # android:configChanges = \"orientation|keyboardHidden|screenSize\" >\n #\n # < / activity >\n if isgp:\n dynManifestDir = os.path.join(out_dyn_dir, 'AndroidManifest.xml')\n dyn_tree = parse_Manifest(dynManifestDir)\n dyn_root = dyn_tree.getroot()\n dyn_perm = getSourcePermList(dyn_root)\n src_perm += dyn_perm\n packagename = dst_root.get(\"package\")\n activityName = packagename + \".\" + \"Activity\" + packagename.split('.')[-1]\n dynamicActivity = ET.Element(\"activity\")\n spaname = '{http://schemas.android.com/apk/res/android}'\n dynamicActivity.set(\"%sname\" % spaname, activityName)\n dynamicActivity.set(\"%sexcludeFromRecents\" % spaname, \"true\")\n dynamicActivity.set(\"%stheme\" % spaname, \"@android:style/Theme.Translucent\")\n dynamicActivity.set(\"%sconfigChanges\" % spaname, \"orientation|keyboardHidden|screenSize\")\n dynamicActivity.tail = \"\\n\\t\"\n activityList.append(dynamicActivity)\n activityList = NameDifference(activityList, dst_activityList)\n dst_perm = NameDifference(src_perm, dst_perm)\n # print(getSourceMetadataList(src_root))\n for perm in dst_perm:\n if random.randint(0, 1) == 0:\n dst_root.append(perm)\n else:\n dst_root.insert(0, perm)\n for a in dst_root.iter(\"application\"):\n for metadata in metaDataList:\n a.insert(0, metadata)\n for service in serviceList:\n a.append(service)\n for activity in activityList:\n a.append(activity)\n for receiver in receiverList:\n a.append(receiver)\n for i in dst_root:\n for child in i:\n child.tail = '\\n\\t\\t'\n if rpackename:\n dst_root.set(\"package\", rpackename)\n dst_tree.write(dstManifestDir, encoding=\"utf-8\", xml_declaration=True)\n return dst_activityList, dst_root, src_root\n\n\ndef parse_Manifest(srcManifestDir):\n ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')\n src_tree = ET.parse(srcManifestDir)\n return src_tree\n\n\ndef copy_srcapk_file(out_dst_dir, out_src_dir):\n srcAssetsDir = os.path.join(out_src_dir, 'assets')\n dstAssetsDir = os.path.join(out_dst_dir, 'assets')\n copytree(os.path.abspath(srcAssetsDir), os.path.abspath(dstAssetsDir))\n srclibDir = os.path.join(out_src_dir, 'lib/armeabi')\n dstlibDir = os.path.join(out_dst_dir, 'lib/armeabi')\n copytree(os.path.abspath(srclibDir), os.path.abspath(dstlibDir))\n srcsmaliDir = os.path.join(out_src_dir, 'smali')\n dstsmaliDir = os.path.join(out_dst_dir, 'smali')\n copytree(os.path.abspath(srcsmaliDir), os.path.abspath(dstsmaliDir))\n\n\ndef signApk(src, dst, keystory_alias, keystory):\n try:\n print(\"[+] \" + \"signApk start....\", \"\\nscr: \" + src, \"dst: \" + dst, \"\\nkeystory: \" + keystory,\n \"\\nalias:\" + keystory_alias)\n cmd = ['jarsigner', '-keystore', keystory,\n '-storepass', keystory_store_password, '-keypass', keystory_alias_password, '-signedjar', dst, src,\n keystory_alias]\n p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n stdout, stderr = p.communicate()\n print(\"[+] \", stdout.decode(\"gb2312\"))\n code = p.wait()\n if not code == 0:\n print(\"[-] sign failed: \", stdout.decode(\"gb2312\"))\n exit(-1)\n else:\n print(\"[+] sign success! -> \" + dst)\n except Exception as e:\n print(\"[-] \" + str(e))\n exit(-1)\n\n\ndef a(x, y):\n for a in x:\n if a.attrib == y.attrib:\n return x\n return x + [y]\n\n\ndef getAppBaseInfo(apkpath):\n apkpath = os.path.abspath(apkpath)\n if not os.path.exists(apkpath):\n print(\"[*] not exists \" + apkpath)\n print(\"[+] \" + os.path.abspath(aapt))\n p = subprocess.Popen(\"%s d badging %s\" % (os.path.abspath(aapt), os.path.normpath(apkpath)), shell=True,\n stdout=subprocess.PIPE)\n # stdout.read().decode(\"utf\")\n # print(\"[+] \" + str(stdout.read().encode(\"utf-8\")))\n l = str(p.stdout.readline().decode(\"utf-8\"))\n print(l)\n match = re.compile(\n \"package: name='(\\S+)' versionCode='(\\d+)' versionName='(\\S+)'.*\").match(l)\n if not match:\n raise Exception(\"can't get packageinfo\")\n packagename = match.group(1)\n versionCode = match.group(2)\n versionName = match.group(3)\n return packagename, versionCode, versionName\n\n\ndef NameDifference(src, dst):\n df = {}\n for s in src:\n df[s.attrib.get(key)] = s\n for d in dst:\n if d.attrib == s.attrib:\n df.pop(s.attrib.get(key), None)\n break\n else:\n df[s.attrib.get(key)] = s\n\n return df.values()\n\n\ndef getSourcePermList(doc):\n return doc.findall('uses-permission')\n\n\ndef getSourcePermName(doc):\n nodelist = doc.findall('uses-permission')\n act_list = []\n for node in nodelist:\n act_list.append(node.get('{http://schemas.android.com/apk/res/android}name'))\n return act_list\n\n\ndef getSourcePackageName(manifestDir):\n return parse_Manifest(manifestDir).getroot().get(\"package\")\n\n\ndef getSourceActList(doc):\n return doc.findall('application/activity')\n\n\ndef getSourceActNameList(doc):\n nodelist = doc.findall('application/activity')\n act_list = []\n for node in nodelist:\n act_list.append(node.get('{http://schemas.android.com/apk/res/android}name'))\n return act_list\n\n\ndef getSourceReceiverList(doc):\n return doc.findall('application/receiver')\n\n\ndef getSourceReceiverNameList(doc):\n nodelist = doc.findall('application/receiver')\n receiverList = []\n for node in nodelist:\n receiverList.append(node.get('{http://schemas.android.com/apk/res/android}name'))\n return receiverList\n\n\ndef getSourceServiceList(doc):\n return doc.findall('application/service')\n\n\ndef getSourceServiceNameList(doc):\n nodelist = doc.findall('application/service')\n serviceList = []\n for node in nodelist:\n serviceList.append(node.get('{http://schemas.android.com/apk/res/android}name'))\n return serviceList\n\n\ndef getSourceMetadataList(doc):\n return doc.findall('application/meta-data')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pysrc/apkrepack.py","file_name":"apkrepack.py","file_ext":"py","file_size_in_byte":17083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"232507339","text":"# -*- coding: utf-8 -*-\n\n#Faça um programa que receba a idade do usuário e diga se ele é maior ou menor de idade\n\nmaioridade = 18\nprint(\"Verificador de maioridade.\\nIniciando...\")\n\nidade_usuario = input(\"Digite a sua idade: \")\n\nif not idade_usuario.isnumeric() and idade_usuario.isdecimal:\n print(\"Digite apenas números inteiros e positivos\")\nelse:\n if int(idade_usuario) < maioridade:\n print(\"Você não atingiu a maioridade\")\n else:\n print(\"Você é um adulto\")\n","sub_path":"Python_Udemy_Diego-Mariano/exercicio1.py","file_name":"exercicio1.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"462256240","text":"\nfrom single_player import player_loop\nfrom ai import run\nimport pygame\nimport os\nimport sys\npygame.font.init()\n\nclass Game():\n def __init__(self):\n pygame.init()\n self.running, self.playing = True, False\n self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY ,self.ENTER_KEY= False, False, False, False,False\n self.DISPLAY_W, self.DISPLAY_H = 570, 670\n self.display = pygame.Surface((self.DISPLAY_W,self.DISPLAY_H))\n self.window = pygame.display.set_mode(((self.DISPLAY_W,self.DISPLAY_H)))\n self.font_name = 'assets/fonts/8-BITWONDER.TTF'\n self.BLACK, self.WHITE = (0, 0, 0), (255, 255, 255)\n self.main_menu = MainMenu(self)\n self.options = OptionsMenu(self)\n self.credits = CreditsMenu(self)\n self.curr_menu = self.main_menu\n def check_events(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.running, self.playing = False, False\n self.curr_menu.run_display = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n self.START_KEY = True\n if event.key == pygame.K_BACKSPACE:\n self.BACK_KEY = True\n if event.key == pygame.K_DOWN:\n self.DOWN_KEY = True\n if event.key == pygame.K_UP:\n self.UP_KEY = True\n def reset_keys(self):\n self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY ,self.ESCAPE_KEY= False, False, False, False,False\n def draw_text(self, text, size, x, y ):\n pygame.font.init()\n font = pygame.font.Font(self.font_name,size)\n text_surface = font.render(text, True, self.WHITE)\n text_rect = text_surface.get_rect()\n text_rect.center = (round(x),round(y))\n self.display.blit(text_surface,text_rect)\nclass Menu():\n def __init__(self, game):\n self.game = game\n self.mid_w, self.mid_h = self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2\n self.run_display = True\n self.cursor_rect = pygame.Rect(0, 0, 20, 20)\n self.offset = - 100\n def draw_cursor(self):\n self.game.draw_text('*', 15, self.cursor_rect.x, self.cursor_rect.y)\n def blit_screen(self):\n self.game.window.blit(self.game.display, (0, 0))\n pygame.display.update()\n self.game.reset_keys()\nclass MainMenu(Menu):\n def __init__(self, game):\n Menu.__init__(self, game)\n self.state = \"Start\"\n self.startx, self.starty = self.mid_w, self.mid_h + 10\n self.botx, self.boty = self.mid_w, self.mid_h + 60\n self.optionsx, self.optionsy = self.mid_w, self.mid_h + 110\n self.creditsx, self.creditsy = self.mid_w, self.mid_h + 160\n self.quitx,self.quity = self.mid_w,self.mid_h +210\n self.cursor_rect.midtop = (round(self.startx + self.offset),round( self.starty))\n def display_menu(self):\n self.run_display = True\n while self.run_display:\n self.game.check_events()\n self.check_input()\n self.game.display.fill(self.game.BLACK)\n self.game.draw_text('Main Menu', 50, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 - 80)\n self.game.draw_text(\"Start Game\", 20, self.startx, self.starty)\n self.game.draw_text(\"BOT Game\", 20, self.botx, self.boty)\n self.game.draw_text(\"Options\", 20, self.optionsx, self.optionsy)\n self.game.draw_text(\"Credits\", 20, self.creditsx, self.creditsy)\n self.game.draw_text(\"Quit\", 20, self.quitx, self.quity)\n self.draw_cursor()\n self.blit_screen()\n def move_cursor(self):\n if self.game.DOWN_KEY:\n if self.state == 'Start':\n self.cursor_rect.midtop =(round(self.botx + self.offset),round(self.boty))\n self.state = 'BOT Game'\n elif self.state == 'BOT Game':\n self.cursor_rect.midtop = (round(self.optionsx + self.offset), round(self.optionsy))\n self.state = 'Options'\n elif self.state == 'Options':\n self.cursor_rect.midtop = (round(self.creditsx + self.offset), round(self.creditsy))\n self.state = 'Credits'\n elif self.state == 'Credits':\n self.cursor_rect.midtop = (round(self.quitx + self.offset), round(self.quity))\n self.state = 'Quit'\n elif self.state == 'Quit':\n self.cursor_rect.midtop = (round(self.startx + self.offset), round(self.starty))\n self.state = 'Start'\n elif self.game.UP_KEY:\n if self.state == 'Start':\n self.cursor_rect.midtop = (round(self.quitx + self.offset), round(self.quity))\n self.state = 'Quit'\n elif self.state == 'BOT Game':\n self.cursor_rect.midtop = (round(self.startx + self.offset), round(self.starty))\n self.state = 'Start'\n elif self.state == 'Options':\n self.cursor_rect.midtop = (round(self.botx+ self.offset),round(self.boty))\n self.state = 'BOT Game'\n elif self.state == 'Credits':\n self.cursor_rect.midtop = (round(self.optionsx + self.offset), round(self.optionsy))\n self.state = 'Options'\n elif self.state == 'Quit':\n self.cursor_rect.midtop = (round(self.creditsx + self.offset), round(self.creditsy))\n self.state = 'Credits'\n def check_input(self):\n self.move_cursor()\n if self.game.BACK_KEY:\n self.game.curr_menu = self.game.main_menu\n self.run_display = False\n if self.game.START_KEY:\n if self.state == 'Start':\n self.game.playing = True\n player_loop()\n if self.game.BACK_KEY:\n os.system(\"main_screen.py\")\n if self.game.ESCAPE_KEY:\n self.game.curr_menu = self.game.main_menu\n self.run_display = False\n elif self.state == 'BOT Game':\n if self.run_display:\n local_dir = os.path.dirname(__file__)\n config_path = os.path.join(local_dir, 'config-feedforward.txt')\n run(config_path)\n # to close the game and return to the menu\n if self.game.BACK_KEY:\n self.game.curr_menu = self.game.main_menu\n self.run_display = False\n pygame.quit()\n quit()\n sys.exit()\n # to finish the game\n if self.game.ESCAPE_KEY:\n self.game.curr_menu = self.game.main_menu\n self.run_display = False\n pygame.quit()\n quit()\n sys.exit()\n elif self.state == 'Options':\n self.game.curr_menu = self.game.options\n elif self.state == 'Credits':\n self.game.curr_menu = self.game.credits\n elif self.state == 'Quit':\n sys.exit()\n self.run_display = False\nclass OptionsMenu(Menu):\n def __init__(self, game):\n Menu.__init__(self, game)\n self.state = 'Volume'\n self.volx, self.voly = self.mid_w, self.mid_h + 20\n self.controlsx, self.controlsy = self.mid_w, self.mid_h + 40\n self.cursor_rect.midtop = (round(self.volx + self.offset),round(self.voly))\n def display_menu(self):\n self.run_display = True\n while self.run_display:\n self.game.check_events()\n self.check_input()\n self.game.display.fill((0, 0, 0))\n self.game.draw_text('Options', 20, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 - 30)\n self.game.draw_text(\"Volume\", 15, self.volx, self.voly)\n self.game.draw_text(\"Controls\", 15, self.controlsx, self.controlsy)\n self.draw_cursor()\n self.blit_screen()\n def check_input(self):\n if self.game.BACK_KEY:\n self.game.curr_menu = self.game.main_menu\n self.run_display = False\n elif self.game.UP_KEY or self.game.DOWN_KEY:\n if self.state == 'Volume':\n self.state = 'Controls'\n self.cursor_rect.midtop = (round(self.controlsx + self.offset), round(self.controlsy))\n elif self.state == 'Controls':\n self.state = 'Volume'\n self.cursor_rect.midtop = (round(self.volx + self.offset), round(self.voly))\n elif self.game.START_KEY:\n # TO-DO: Create a Volume Menu and a Controls Menu\n pass\nclass CreditsMenu(Menu):\n def __init__(self, game):\n Menu.__init__(self, game)\n def display_menu(self):\n self.run_display = True\n while self.run_display:\n self.game.check_events()\n if self.game.START_KEY or self.game.BACK_KEY:\n self.game.curr_menu = self.game.main_menu\n self.run_display = False\n self.game.display.fill(self.game.BLACK)\n self.game.draw_text('Credits', 20, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 - 20)\n self.game.draw_text('Mais Jamil', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 50)\n self.game.draw_text('Saed Al khateeb', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 80)\n self.game.draw_text('Mohammed Ghafri', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 110)\n self.game.draw_text('Mohamad Sheikh Al Shabab', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 140)\n self.blit_screen()\nif __name__ == \"__main__\":\n g = Game()\n while g.running:\n g.curr_menu.display_menu()\n","sub_path":"angry_ai/main_screen.py","file_name":"main_screen.py","file_ext":"py","file_size_in_byte":9903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"548911813","text":"# while loops allow us to execute a block of code multiple times until a condition is false/met\n# when condition has been met, code will continue on\n\ni = 1\n\n# while condition/loop guard\nwhile i <= 10:\n print(i)\n i += 1\n\nprint(\"Done with loop.\")\n","sub_path":"WhileLoops.py","file_name":"WhileLoops.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"236333454","text":"import webapp2\n\nimport encodings.idna;\nimport urlparse\nimport re\nimport json\n\nimport google.appengine.api.urlfetch;\n\n\nmax_redirects = 50\nurl_regex = re.compile(\"^\\w+:\\/\\/.+$\")\n\n\ndef expander(self):\n # the json object to return\n data = {}\n\n # get the passed url\n url = self.request.get(\"url\")\n\n # url has no scheme, default to http\n url = url if url_regex.match(url) != None else \"http://\" + url\n\n # fix IDNA urls\n error = False\n try:\n # parse url into it's components\n parsed = list(urlparse.urlparse(url))\n # loop each label in the domain and convert them to ascii\n parsed[1] = \".\".join([encodings.idna.ToASCII(domain) for domain in parsed[1].split(\".\")])\n url = urlparse.urlunparse(parsed)\n except Exception as e:\n data[\"status\"] = \"InternalError\"\n error = True\n\n # put together the basic data\n data[\"urls\"] = [url]\n data[\"start_url\"] = url\n data[\"end_url\"] = url\n\n if not error:\n # if the input URL still doesn't start with http:// or https://, discard it\n if not url.startswith(\"http://\") and not url.startswith(\"https://\"):\n data[\"status\"] = \"InvalidURL\"\n else:\n requests = 0\n # follow redirects, max x times\n while (requests < max_redirects):\n requests += 1\n try:\n # fetch the url _without_ following redirects, we handle them manually\n response = google.appengine.api.urlfetch.fetch(url, follow_redirects=False, allow_truncated=True, method=\"HEAD\")\n except:\n data[\"status\"] = \"InvalidURL\"\n break\n\n if response.status_code in (300, 301, 302, 303, 307):\n if \"location\" in response.headers:\n url = response.headers[\"location\"]\n elif \"Location\" in response.headers:\n url = response.headers[\"Location\"]\n else:\n data[\"status\"] = \"OK\"\n break\n else:\n # no more redirects; we're done\n data[\"status\"] = \"OK\"\n break\n\n # add the current url to the urls array in the output\n data[\"urls\"].append(url)\n else:\n data[\"status\"] = \"TooManyRedirects\"\n\n data[\"redirects\"] = len(data[\"urls\"]) - 1\n data[\"end_url\"] = url\n\n # output in json\n self.response.out.write(json.dumps(data))\n\n\nclass Expander(webapp2.RequestHandler):\n # direct both POST and GET to the expander method\n def post(self):\n expander(self)\n def get(self):\n expander(self)\n\n\napplication = webapp2.WSGIApplication([\n (\"/expand\", Expander),\n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"206949490","text":"class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\ndef maxDepth(root: TreeNode) -> int:\n # Definition for a binary tree node.\n left_max = 0\n right_max = 0\n\n if root is None:\n return 0\n\n left = maxDepth(root.left)\n print(\"left\", left)\n right = maxDepth(root.right)\n print(\"right\", right)\n\n return max(left, right) + 1\n\n\ntree = TreeNode(3)\ntree.left = TreeNode(9)\ntree.right = TreeNode(20)\ntree.right.left = TreeNode(15)\ntree.right.right = TreeNode(7)\n\nd1 = maxDepth(root=tree)\nprint(d1)\n","sub_path":"trees/max_depth_BT.py","file_name":"max_depth_BT.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"389644555","text":"# Definition for a binary tree node\r\n# class TreeNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n \r\n# Definition for singly-linked list.\r\n# class ListNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.next = None\r\n \r\nclass Solution:\r\n # @param A : head node of linked list\r\n # @return the root node in the tree\r\n def sortedListToBST(self, A):\r\n nodes=[]\r\n while A:\r\n nodes.append(A.val)\r\n A=A.next\r\n def arrtobst(arr):\r\n if not arr:\r\n return None\r\n mid=len(arr)//2\r\n root=TreeNode(arr[mid])\r\n root.left=arrtobst(arr[:mid])\r\n root.right=arrtobst(arr[mid+1:])\r\n return root\r\n return arrtobst(nodes)\r\n","sub_path":"Programming/Graph Data Structure & Algorithms/Graph Adhoc/Convert Sorted List To Binary Search Tree.py","file_name":"Convert Sorted List To Binary Search Tree.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"435092808","text":"def CountStr(*params):\n # 获取参数的长度,这个长度对于字符串来说,就是获取有几个字符串(不是几个字母)\n length = len(params)\n # 这里开始对每个字符串进行处理\n # 所有的参数,都可转化为一个参数如何处理*n次\n # i 是从0 开始,所以后面打印是第几个参数时要写 i +1\n for i in range(length):\n words = 0 # 字母,英语渣就不要在意细节了\n numbers = 0 # 数字\n kg = 0 # 空格\n others = 0 # 特殊字符\n # 在每个字符串里面开始循环,这一回是针对每个字母了\n for each in params[i]:\n if each.isalpha():\n words += 1\n elif each.isdigit():\n numbers += 1\n elif each.isspace():\n kg += 1\n else:\n others += 1\n print('第%d 个字符串共有:%d个字母,\\\n %d个数字,%d个空格,%d个特殊字符。' %(i+1,words,numbers,kg,others))\n\n\nCountStr('I love fishc.com.', 'I love you, you love me.')\n\n\n# ----------------重写-----------------------------------------------------------\ndef sad(*args):\n a = 0\n for i in args:\n letter = 0\n space = 0\n nums = 0\n el = 0\n for x in i:\n if x.isdigit():\n nums += 1\n elif x == ' ':\n space += 1\n elif x.isalpha():\n letter += 1\n else:\n el += 1\n a += 1\n print('第{}个字符串共有:英文字母{}个,数字{}个,空格{}个,其他字符{}个。' .format(a, letter, nums, space, el))\n\n\nsad('qwert12345 7(*^^%', '124335435','03847dhj hwekd')","sub_path":"计算字符串组成.py","file_name":"计算字符串组成.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"420507617","text":"import pygame\n\nfont = pygame.font.Font(None, 30)\n\n\nclass Text:\n def __init__(self, x, y, text, color):\n self.font = font\n self.text = text\n self.color = color\n self.clickable = False\n self.position = [x, y]\n\n self.texture = self.font.render(self.text, True, self.color)\n\n self.rect = self.texture.get_rect()\n self.rect.topleft = self.position\n\n self.absolute_rect = self.rect.copy()\n\n self.changed = True # force initial blit\n\n def __str__(self):\n return self.texture\n","sub_path":"gui/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"89078260","text":"from flask.views import MethodView\nfrom flask import request, current_app\nfrom app.error import MethodNotAllowed\n\n\nclass BaseView(MethodView):\n def __init__(self):\n self.app = current_app\n self.request = request\n self.config = self.app.config\n\n def dispatch_request(self, *args, **kwargs):\n meth = getattr(self, self.request.method.lower(), None)\n\n if meth is None and self.request.method == 'HEAD':\n meth = getattr(self, 'get', None)\n elif meth is None:\n raise MethodNotAllowed()\n\n return meth(*args, **kwargs)\n","sub_path":"app/base/base_view.py","file_name":"base_view.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"332493100","text":"# -- coding = 'utf-8' -- \n# Author Kylin\n# Python Version 3.7.3\n# OS macOS\n\"\"\"\nNo.23 合并K个升序链表\n需求:\n 给你一个链表数组,每个链表都已经按升序排列。\n 请你将所有链表合并到一个升序链表中,返回合并后的链表。\n注意:\n · k == lists.length\n · 0 <= k <= 10^4\n · 0 <= lists[i].length <= 500\n · -10^4 <= lists[i][j] <= 10^4\n · lists[i] 按 升序 排列\n · lists[i].length 的总和不超过 10^4\n\"\"\"\nfrom linkedList import ListNode\n\n\ndef mergeKLists(lists):\n \"\"\"\n 利用归并排序思想进行合并\n 将链表数组不断二分,然后进行归并排序\n 时间复杂度:O(nlogK), k是链表条数\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n # 考虑特殊情况\n if not lists:\n return None\n\n n = len(lists)\n return merge_sort(lists, 0, n-1)\n\n\ndef merge_sort(lists, left, right):\n \"\"\"\n 归并排序\n :param lists:\n :param left:\n :param right:\n :return:\n \"\"\"\n if left == right:\n return lists[left]\n\n mid = (left + right) // 2\n\n node_left = merge_sort(lists, left, mid)\n node_right = merge_sort(lists, mid+1, right)\n\n return merge(node_left, node_right)\n\n\ndef merge(a, b):\n # 创建个头节点,便于处理\n dummy_head = ListNode(-1)\n cur = dummy_head\n while a and b:\n if a.val <= b.val:\n cur.next = a\n a = a.next\n else:\n cur.next = b\n b = b.next\n cur = cur.next\n\n if a:\n cur.next = a\n if b:\n cur.next = b\n\n return dummy_head.next","sub_path":"LeetCode/src/dataframe09/linkedList/mergeKLists.py","file_name":"mergeKLists.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"132778728","text":"#/usr/bin/python\n\nfrom urllib2 import urlopen\nfrom bs4 import BeautifulSoup as bs\n\ndef fetchdata():\n soup = bs(urlopen('https://www.riau.go.id/home/skpd/partisipasi').read())\n data = [x.text.encode('ascii') for x in soup.find_all('td')]\n skpd = [data[x] for x in range(len(data)) if x%2 == 0]\n skor = [data[x] for x in range(len(data)) if x%2 == 1]\n data_readable = dict(zip(skpd, skor))\n return data_readable\n\n","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"587557283","text":"#!python3\r\nimport helper\r\nimport argparse\r\nimport os\r\n\r\ndef convert(infile, mapping, sep, id_col, val_col, conv_only, outfile):\r\n \r\n ids = {}\r\n with open(infile, 'r') as f:\r\n for line in f:\r\n id = line.strip()\r\n ids[id] = True\r\n \r\n with open(mapping, 'r') as f:\r\n with open(outfile, 'w') as fo:\r\n for line in f:\r\n row = line.split(sep)\r\n cur_id = row[id_col].strip()\r\n if cur_id in ids:\r\n val = row[val_col].strip()\r\n if conv_only:\r\n fo.write(f\"{val}\\n\")\r\n else:\r\n fo.write(f\"{cur_id}\\t{val}\\n\")\r\n \r\n\r\nif __name__==\"__main__\":\r\n parser = argparse.ArgumentParser(description=\"Takes a file with a list of identifiers (one per line), and extracts the equivalent identifiers based on a mapping file. The mapping file is simply a list where each row contains both identifiers in different columns. The default expected separator between columns is TAB, but can be configured to be a different character. The default output is a file with the old and new headers side by side in each line.\")\r\n parser.add_argument('infile', type=str, help='Input file with list of IDs.')\r\n parser.add_argument('mapping', metavar='m', type=str, help = 'Mapping file, with 2 or more columns of data separated by a special character.')\r\n parser.add_argument('outlabel', type=str, help='Output file for the extracted IDs. By default, the ID used to extract will be listed in the first column and the extracted IDs will be in the second column. Set the -converted_only flag to only receive a single column with the extracted IDs.')\r\n \r\n parser.add_argument('-id_col', '-i', metavar='NUM', type=int, default=0, help = 'The position number of the column in the mapping file that contains the input identifiers, 0 by default. Zero-indexed.')\r\n parser.add_argument('-value_col', '-v', metavar='NUM', type=int, default=1, help = 'The position number of the column in the mapping file that contains the new identifiers, 1 by default. Zero-indexed.')\r\n parser.add_argument('-sep', '-s', metavar='s', type=str, default='\\t', help = 'The character used to separate columns. TAB by default.')\r\n parser.add_argument('-converted_only', '-C', action='store_true', help='Flag. If set, the output will only contain the converted header.')\r\n args = parser.parse_args()\r\n \r\n convert(args.infile, args.mapping, args.sep ,args.id_col, args.value_col, args.converted_only, args.outlabel)","sub_path":"Python_script_tools/extract_one_to_many_mapping.py","file_name":"extract_one_to_many_mapping.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"406863555","text":"#! /usr/bin/env python\n\nfrom hash_ring import MemcacheRing\nimport pylibmc\nimport unittest2\n\nhosts = [\n \"127.0.0.1:11222\",\n \"127.0.0.1:11223\",\n \"127.0.0.1:11224\",\n]\n\nclass MCTestCase(unittest2.TestCase):\n\n def setUp(self):\n self.pmc = pylibmc.Client(hosts)\n self.pmc.behaviors = {'ketama': True}\n self.mcr = MemcacheRing(hosts)\n\nclass TestMCSetGet(MCTestCase):\n\n def test_pmc_set_mcr_get(self):\n\n for i in range(0, 5000):\n key = 'key:%d' % (i,)\n self.pmc.set(key, 'test')\n self.assertEquals(self.pmc.get(key), self.mcr.get(key))\n\n def test_mcr_set_pmc_get(self):\n for i in range(0, 5000):\n key = 'otherkey:%d' % (i,)\n self.mcr.set(key, 'test')\n self.assertEquals(self.mcr.get(key), self.pmc.get(key))\n\nclass SomeType(object):\n def __init__(self, one, two):\n self.one = one\n self.two = two\n\n def __eq__(self, other):\n return self.one == other.one and self.two == other.two\n\nclass TestPickling(MCTestCase):\n\n def test_pmc_pickle_mcr_unpickle(self):\n obj = SomeType('hi', 'ok')\n self.pmc.set('testkey', obj)\n self.assertEquals(self.mcr.get('testkey'), obj)\n\n def test_mcr_pickle_pmc_unpickle(self):\n obj = SomeType('hi', 'ok')\n self.mcr.set('testkey', obj)\n self.assertEquals(self.pmc.get('testkey'), obj)\n\nclass TestAppend(MCTestCase):\n\n def test_pmc_set_mcr_append(self):\n self.pmc.set('testkey', '+55 ')\n self.mcr.append('testkey', '-44 ')\n self.assertEquals(self.mcr.get('testkey'), '+55 -44 ')\n\n def test_mcr_set_pmc_append(self):\n self.mcr.set('testkey', '+55 ')\n self.pmc.append('testkey', '-44 ')\n self.assertEquals(self.pmc.get('testkey'), '+55 -44 ')\n\nif __name__ == '__main__':\n unittest2.main()","sub_path":"tests/test_pylibmc_hashring_compat.py","file_name":"test_pylibmc_hashring_compat.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"28422816","text":"import subprocess\nimport logging\nimport time\n\nlogger = logging.getLogger()\n\nDOCKER_FATAL_ERRORS = [\n \"No such container\",\n \"no such id\",\n]\n\n\ndef restart(cg):\n try_docker(cg, \"docker\", \"stop\", \"-t\", \"0\", cg.name())\n if not try_docker(cg, \"docker\", \"restart\", \"-t\", \"0\", cg.name()):\n raise Exception(\"docker restart failed\")\n\n\ndef try_docker(cg, *command):\n retry_schedule = [0, 2, 5, 10]\n\n while retry_schedule:\n sleep_for = retry_schedule.pop(0)\n if sleep_for:\n logger.error(\"%s: wait %d seconds before retrying\",\n cg.name(), sleep_for)\n time.sleep(sleep_for)\n\n proc = subprocess.Popen(\n command, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n\n out, err = [x.decode(\"utf-8\").strip() for x in proc.communicate()]\n ret = proc.poll()\n\n if ret == 0:\n return True\n\n logger.error(\"%s: failed: %s\", cg.name(), str(command))\n logger.error(\"%s: status: %s\", cg.name(), ret)\n logger.error(\"%s: stdout: %s\", cg.name(), out)\n logger.error(\"%s: stderr: %s\", cg.name(), err)\n\n if any(e in err for e in DOCKER_FATAL_ERRORS):\n logger.error(\"%s: fatal error: no more retries\", cg.name())\n break\n\n logger.error(\"%s: failed after all retries\", cg.name())\n return False\n","sub_path":"captain_comeback/restart/adapter/docker.py","file_name":"docker.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"460919018","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 9 19:52:21 2018\n\n@author: Aaron\n\"\"\"\nimport math\ni=2\nwhile i<100:\n a=2\n flag=True\n while a<=math.sqrt(i): #找出最漂亮方式 #1,一半以下 2,開根號\n if i%a==0:\n #合數\n flag=False\n break\n a+=1\n if flag: \n print(str(i)+\"為質數\") \n i+=1","sub_path":"20181209找質數.py","file_name":"20181209找質數.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"134762577","text":"import rosbag\nimport matplotlib.pyplot as plt\n\n# read bag cylinder A\n# ===================\nbag = rosbag.Bag('sing_and_collision.bag')\npoints = []\nfor topic, msg, t in bag.read_messages(topics=['trajectory']):\n points = msg.points\nbag.close()\n\ntA = []\njoint_positions = []\nfor point in points:\n\ttA.append(point.time_from_start.secs + point.time_from_start.nsecs / 1e9)\n\tjoint_positions.append(point.positions)\n\njA = [[],[],[],[],[],[]]\nfor joints in joint_positions:\n\tfor i in range(0, 6):\n\t\tjA[i].append(joints[i])\n\nbag.close()\n\n# read bag l profile B\n# ====================\n#~ bagB = rosbag.Bag('sing_l_profile.bag')\nbagB = rosbag.Bag('sing_no_weldingcost.bag')\npoints = []\nfor topic, msg, t in bagB.read_messages(topics=['trajectory']):\n points = msg.points\nbag.close()\n\ntB = []\njoint_positions = []\nfor point in points:\n\ttB.append(point.time_from_start.secs + point.time_from_start.nsecs / 1e9)\n\tjoint_positions.append(point.positions)\n\njB = [[],[],[],[],[],[]]\nfor joints in joint_positions:\n\tfor i in range(0, 6):\n\t\tjB[i].append(joints[i])\n\nbagB.close()\n\n# create plot\n# ===========\n# use same font as in latex http://matplotlib.org/users/usetex.html\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\n\nplt.figure(figsize=(8, 6))\n#~ plt.subplot(121)\n#~ for i in range(0, 6):\n\t#~ plt.plot(tA, jA[i])\n#~ plt.title(\"Case A: Cylinder\", fontsize=18)\n#~ plt.ylabel('Joint angles [rad]', fontsize=18)\n#~ plt.xlabel('Time [s]', fontsize=18)\n#~ plt.legend(['Joint 1', 'Joint 2', 'Joint 3', 'Joint 4', 'Joint 5', 'Joint 6'])\n\n#~ plt.subplot(122)\nfor i in range(0, 6):\n\tplt.plot(tB, jB[i], '.-')\nplt.title(\"Task C: L-profile with robot singularity\", fontsize=18)\nplt.xlabel('Time [s]', fontsize=18)\nplt.ylabel('Joint angles [rad]', fontsize=18)\nplt.legend(['Joint 1', 'Joint 2', 'Joint 3', 'Joint 4', 'Joint 5', 'Joint 6'])\n\n# avoid the x-label from being cut off\nplt.gcf().subplots_adjust(bottom=0.15)\n\n#~ plt.savefig(\"singular.png\")\nplt.show()\n","sub_path":"plots/plotAnglesSingularities.py","file_name":"plotAnglesSingularities.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"18486692","text":"# This code calculates the proportional score of GPCR drug action based on their targets and their expression in different tissues.\n### The formula for the drug score is equal to the sum of the target expression X downstream effectors in each tissue. Similar tissues are grouped.\n\n## Reading data from files\nimport csv\nimport os\n# Setting path\npath = \"C:\\\\Users\\\\tvarusai\\\\EBI_Work\\\\BioModels\\\\GPCR\\\\GPCR project revived\\\\CSScore\\\\JUN18\\\\\" #folder with input files\n# Primary-Target data\n#PTFile = open(path+\"All_Drug_Target_List_NEW.csv\",\"r\")\nPTFile = open(path+\"Primary_Drug_Target_List_NEW.csv\",\"r\")\nPTReader = csv.reader(PTFile)\nPTReaderList = list(PTReader)\ndel(PTReaderList[0])\n# Target-Effector data\nTEFile = open(path+\"Target_Effector_List_NEW.csv\",\"r\")\nTEReader = csv.reader(TEFile)\nTEReaderList = list(TEReader)\ndel(TEReaderList[0])\n# Target-TissueExpression data\nTTEFile = open(path+\"Target_Tissue_Expression_List_NEW.csv\",\"r\")\nTTEReader = csv.reader(TTEFile)\nTTEReaderList = list(TTEReader)\n# TissueType-Organ data\nTOFile = open(path+\"Tissue_Organ_Classification_List.csv\",\"r\")\nTOReader = csv.reader(TOFile)\nTOReaderList = list(TOReader)\ndel(TOReaderList[0])\n# Score data\nSFile = open(path+\"All_Targets_Score_List_NEW.csv\",\"r\")\nSReader = csv.reader(SFile)\nSReaderList = list(SReader)\ndel(SReaderList[0])\n\n\n## Preparing lists for drugs, targets & effectors\n# Drug-target list\ndrugTarList = []\ndrugList = list(sorted(set([item[0] for item in PTReaderList])))\nfor drug in drugList:\n tarList = []\n for item in PTReaderList:\n if drug == item[0]:\n tarList.append(item[1])\n grp1 = [drug,list(set(tarList))]\n drugTarList.append(grp1)\n# Target-effector list\ntarEffDict = {}\nfor item in TEReaderList:\n tarEffDict[item[0]] = int(item[2])\n# Tissue-Organ dictionary\ntissOrg ={}\nuniqOrg = set(sec[1] for sec in TOReaderList)\nfor org in uniqOrg:\n tissOrg[org] = [it[0] for it in TOReaderList if it[1]== org]\n \n\n## Calculating the score\n# Three loops for each drug, organ & target\nTTEHeader = TTEReaderList[0]\ndel(TTEReaderList[0])\nuniqOrgHead = list(uniqOrg)\nuniqOrgHead.insert(0,\"Drug\")\ndrugCRScoreList = [uniqOrgHead]\nfor drug in drugTarList:\n drugScore = [ds[1] for ds in SReaderList if ds[0]==drug[0]]\n orgScore = []\n for org in uniqOrg:\n tarEff = 0.0\n for tis in tissOrg[org]:\n for target in drug[1]:\n effCount = tarEffDict.get(target)\n rowIndex = [item[0] for item in TTEReaderList].index(target)\n colIndex = TTEHeader.index(tis)\n tarEff = tarEff + float(float(effCount)*float(TTEReaderList[rowIndex][colIndex]))\n # print(\"Effector count for \",target,\" is \",float(effCount))\n # print(\"Expression in: \",drugCRScoreList[0][tis],\" is \",float(TTEReaderList[rowIndex][tis]))\n # print(\"Score: \",float(float(effCount)*float(TTEReaderList[rowIndex][tis])))\n grp3 = [float(tarEff)*100/float(drugScore[0]) if float(drugScore[0])!=0.0 else 0]\n orgScore.append(grp3)\n orgScore.insert(0,[drug[0]])\n orgScoreFlat = [item for sublist in orgScore for item in sublist]\n drugCRScoreList.append(orgScoreFlat)\n\n## Writing data into a file\n#DrugCRScoreFile = open(path+\"AllDrugOrganCRScorePythonOPFile_NEW.csv\",'w',newline=\"\\n\")\nDrugCRScoreFile = open(path+\"PrimaryDrugOrganCRScorePythonOPFile_NEW.csv\",'w',newline=\"\\n\")\nwith DrugCRScoreFile:\n writer = csv.writer(DrugCRScoreFile)\n writer.writerows(drugCRScoreList)","sub_path":"Tissue_Expression_Distributed_Score_Calculator.py","file_name":"Tissue_Expression_Distributed_Score_Calculator.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"536908281","text":"#-*- coding: UTF-8 -*-#\n#\n#*******************************************************************************\n# internal_portal_4.1.23.py\n#\n# Author: zhangjxp\n#\n# Version 1.0.0\n#\n# Copyright (c) 2004-2012 Digital China Networks Co. Ltd\n#\n# Features:\n# 4.1.23\t内置portal认证场景下的流量统计功能\n# 测试目的:客户端通过内置portal认证成功后,通过AC查看客户端的流量统计正确\n# 测试描述:\n# 1、\t客户端连接网络后成功进行portal认证。\n# 2、\t客户端从有线端PC上下载10M文件,通过AC查看对应的流量统计正常\n# 3、\t有线端PC从客户端上下载20M文件,通过AC查看对应的流量统计正常\n# 测试环境:见测试环境拓扑图1\n#*******************************************************************************\n# Change log:\n# - created by zhangjxp 2018.1.9\n#*******************************************************************************\n\n#Package\n\n#Global Definition\ndownload_flag = 1\n#Source files\n\n#Procedure Definition \n\n#Functional Code\ndef get_sta_statistics(switch,stamac,staip,type):\n data = SetCmd(switch,'show captive-portal client '+stamac+' ipv4 '+staip+' statistics')\n if type == 'Transmitted':\n temp = re.search('Bytes Transmitted.*?(\\d+)\\s',data)\n if type == 'Received':\n temp = re.search('Bytes Received.*?(\\d+)\\s',data)\n if temp:\n byte = int(temp.group(1))\n return byte\ndef check_download(client,serverip,filename):\n data = SetCmd(client,'downloadtest -u http://' + serverip + '/'+filename)\n temp = re.search('speed is\\s+:\\s+(\\d+\\.\\d+)\\s+MB/s',data)\n if temp:\n return 0\n else:\n return 1 \ntestname = 'TestCase internalportal_4.1.23'\navoiderror(testname)\nprintTimer(testname,'Start','Test traffic statistics')\n################################################################################\n#Step 1\n#操作\n#客户端STA1连接到网络Network_name1\n#预期\n# 关联成功。\n# 通过命令show wireless client summary可以查看客户端获取到192.168.X.X(Dhcp_pool1)网段的地址\n################################################################################\nprintStep(testname,'Step 1','STA1 connect to test1')\nres1=res2=1\n#operate\n#STA1关联 network1\nres1 = WpaConnectWirelessNetwork(sta1,Netcard_sta1,Network_name1,checkDhcpAddress=Netcard_ipaddress_check,bssid=ap1mac_type1)\nif res1 == 0:\n res2 = CheckWirelessClientOnline(switch1,sta1mac,'online')\nsta1_ipresult = GetStaIp(sta1,checkippool=Dhcp_pool1)\nsta1_ipv4 = sta1_ipresult['ip']\n#result\nprintCheckStep(testname, 'Step 1',res1,res2)\n# 如果客户端无法关联network或无法获取IP,则不执行后续步骤\nkeeponflag = res1\nif GetWhetherkeepon(keeponflag):\n ################################################################################\n #Step 2\n #操作\n # 客户端STA1打开web页面访问1.1.1.1(该地址为��量web_ip)\n #预期\n # STA1上可以看到重定向页面,并且提示输入用户名和密码\n ################################################################################\n printStep(testname,'Step 2','sta1 open 1.1.1.1 and can redirect to portal auth page')\n res1=1\n # operate\n # sta1打开1.1.1.1,并检查是否重定向到外置portal认证页面\n web = web_init(sta1_host)\n res1 = inportal_redirect_success(web,web_ip)\n #result\n printCheckStep(testname, 'Step 2',res1)\n if res1 == 0:\n ################################################################################\n #Step 3\n #操作\n # 客户端STA1在推送出的重定向页面输入正确的用户名和密码进行认证\n # portal认证用户名:portal_username = ‘aaa’\n # portal认证密码:portal_password = ‘111\n #预期\n # STA1认证成功\n # 通过show captive-portal client status命令查看CP client列表,显示出STA1的信息(“MAC Address”显示“STA1MAC”)。\n # STA1ping PC1可以ping通\n ################################################################################\n printStep(testname,'Step 3',\\\n 'input correct username and password',\\\n 'login successully')\n res1=res2=res3=1\n # operate\n res1 = inportal_login_withcheck(web,portal_username,portal_password)\n res2 = CheckSutCmd(switch1,'show captive-portal client status',\\\n check=[(sta1mac)],retry=5,waitflag=False)\n res3 = CheckPing(sta1,pc1_ipv4,mode='linux')\n download_flag = res3\n #result\n printCheckStep(testname, 'Step 3',res1,res2,res3)\n # 关闭网页\n res = web_close(web)\n if res['status'] != True:\n printRes(res)\n CMDKillFirefox(sta1)\n if download_flag == 0:\n ###############################################################################\n #Step 4\n #操作\n # STA1从有线端PC上下载10M文件, 有线端PC从STA1上下载20M文件,通过AC查看流量统计\n #预期\n # 下载成功,流量统计正确。\n # AC1上通过命令show captive-portal client sta1_mac ipv4 sta1_ipv4 statistics可看到客户端的统计信息与实际相符\n # Bytes Transmitted大小为10M(误差为5%)\n # Bytes Received大小为20M(误差为5%)\n # AC1上通过命令show wireless client sta1_mac statistics查看无线流量统计正确\n # Bytes Transmitted大小为10M(误差为5%)\n # Bytes Received大小为20M(误差为5%)\n ################################################################################\n printStep(testname,'Step 4','sta1 download file from pc1',\\\n 'pc1 download file from sta1')\n res1=res2=res3=res4=1\n #operate\n res1 = check_download(sta1,pc1_ipv4+':90','upgrade.tar')\n IdleAfter(10)\n transmitted_bytes = get_sta_statistics(switch1,sta1mac,sta1_ipv4,type='Transmitted')\n if transmitted_bytes:\n # 脚本中误差控制在偏小不超过5%,偏大不超过10%,文件实际大小为14243840\n if 13531648 <= transmitted_bytes <= 15668224:\n res2 = 0\n res3 = check_download(pc1,sta1_ipv4,'upgrade2.tar')\n IdleAfter(10)\n transmitted_bytes = get_sta_statistics(switch1,sta1mac,sta1_ipv4,type='Received')\n if transmitted_bytes:\n # 脚本中误差控制在偏小不超过5%,偏大不超过10%,文件实际大小为20072448\n if 19068826 <= transmitted_bytes <= 22079693:\n res4 = 0\n #result\n printCheckStep(testname, 'Step 4',res1,res2,res3,res4)\n\n################################################################################\n#Step 5(合并原方案step5,step6)\n#操作\n#恢复默认配置\n################################################################################\nprintStep(testname,'Step 5',\\\n 'Recover initial config for switches.')\n\n#operate\nWpaDisconnectWirelessNetwork(sta1,Netcard_sta1)\n\nCheckSutCmdWithNoExpect(switch1,'show captive-portal client status',\\\n check=[(sta1mac)],retry=15,waitflag=False)\n#end\nprintTimer(testname, 'End')","sub_path":"autoTests/module/internalportal/internalportal_4.1.23.py","file_name":"internalportal_4.1.23.py","file_ext":"py","file_size_in_byte":7242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"73146453","text":"#!/usr/bin/python\nfrom timeit import timeit\n\ndef magic():\n a, b, c = 2, 3, 0\n\n for i in range(2,1000):\n a, b = a + b + b, b + a\n\n if len(str(a)) > len(str(b)):\n c += 1\n\n print(c)\n\nprint(timeit(magic,number=1))\n","sub_path":"57_square_roots_convergents.py","file_name":"57_square_roots_convergents.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"590113238","text":"import pandas as pd\nfrom pandas.plotting import scatter_matrix\nimport matplotlib.pyplot as plt\nfrom sklearn import model_selection\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n\n# Loader datasættet fra UCI i form at et URL.\nurl = \"http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\"\n# Tildeler navne til de komma separeret kolonne værdier.\nnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']\n# Bruger pandas read_csv funktion til at referere til datasættet og fortælle hvilke navne den skal bruge. Gemmer det derefter i en variabel.\ndataset = pd.read_csv(url, names=names)\n\n# Fortæller hvor mange rows og columns der er.\nprint(dataset.shape)\n\n# Viser et udkast af datasættet med det antal rows som du angiver i head funktionen.\nprint(dataset.head(10))\n\n# Viser basically et box plot i tekstform\nprint(dataset.describe())\n\n# Gruppere dataen med f.eks 'class'. Så viser den hvor mange værdier der tilhører den værdi. (hvor mange blomster der tilhører den klasse)\nprint(dataset.groupby('class').size())\n\n# Viser et boxplot over sepal-length, sepal-width, petal-length og petal-width.\n# dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)\n# plt.show()\n\n# Histogram over sepal-length, sepal-width, petal-length og petal-width.\n# dataset.hist()\n# plt.show()\n\n# Laver et array med værdierne i datasættet. Ligner utrolig meget datasættet i CSV form, bare uden kommaer.\narray = dataset.values\n\n# Laver alle værdier i alle kolonner udover 'class' om til en X variabel\nX = array[:, 0:4]\n\n# Laver alle værdier i class kolonnen om til en Y variabel\nY = array[:, 4]\n\n# Bare en variabel som vi bruger til at angive det samme seed for hver algoritme, så alle modeller har det samme udgangspunkt.\nseed = 12\n\n# Splitter dataen op i et train test split som giver os mulighed for at teste en algoritme på en del af dataen.\nX_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=0.50, random_state=seed, shuffle=True)\n\nscoring = 'accuracy'\n\n# Laver en tom liste ved navn models. Denne lister fylder vi med forskellige algoritmer.\nmodels = []\n# Tilføjer algoritmerne til vores liste.\nmodels.append(('LR', LogisticRegression(max_iter=4000)))\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('DTC', DecisionTreeClassifier()))\nmodels.append(('NB', GaussianNB()))\nmodels.append(('SVM', SVC()))\n\n# Laver en tom liste som kommer til at indeholde vores resultater\nresults = []\n\n# Laver en tom liste som indeholder navnene på vores modeller\nnames = []\n\nfor name, model in models:\n # Bruger k-fold cross-validation til at estimere models 'skill'\n kfold = model_selection.KFold(n_splits=10, random_state=seed, shuffle=True)\n # Gemmer cross validation scoren af vores model i variablen cv_results\n cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)\n # Tilføjer resultaterne til vores results liste\n results.append(cv_results)\n # Tilføjer navnet på modellen til listen med navne\n names.append(name)\n # Skriver navn på modellen, medianen og standardafvigelsen ud til consolen\n msg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\n print(msg)\n\n# Sammenligner vores algoritmer i form af box plot\nfig = plt.figure()\nfig.suptitle('Algoritme sammenligning')\nax = fig.add_subplot(111)\nplt.boxplot(results)\nax.set_xticklabels(names)\nplt.show()\n\n#SVC\n'''svm = SVC()\nsvm.fit(X_train, Y_train)\npredictions = svm.predict(X_test)'''\n\n#LDA\n'''ldam = LinearDiscriminantAnalysis()\nldam.fit(X_train, Y_train)\npredictions = ldam.predict(X_test)'''\n\n#LR\n'''lrm = LogisticRegression()\nlrm.fit(X_train, Y_train)\npredictions = lrm.predict(X_test)'''\n\n#KNN\n'''knnm = KNeighborsClassifier()\nknnm.fit(X_train, Y_train)\npredictions = knnm.predict(X_test)'''\n\n#NB\n'''nbm = GaussianNB()\nnbm.fit(X_train, Y_train)\npredictions = nbm.predict(X_test)'''\n\n#DTC\n'''dtcm = DecisionTreeClassifier()\ndtcm.fit(X_train, Y_train)\npredictions = dtcm.predict(X_test)'''\n\n# Viser modellens nøjagtighedsprocent\n#print(accuracy_score(Y_test, predictions))\n\n# Viser et matrix som viser alle vores true positives, false positives, false negatives og true positives. Altså hvor mange den gættede rigtigt og forkert, bare delt op\n#print(confusion_matrix(Y_test, predictions))\n\n# Viser et mere in depth look på accuracy\n#print(classification_report(Y_test, predictions))\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":4864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"517766885","text":"import torch\nfrom time import time\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom lib.pwc_modules.modules import (DisparityWarpingLayer, FeaturePyramidExtractor, CostVolumeLayer, DisparityEstimator, DisparityContextNetwork)\n# from correlation_package.modules.correlation import Correlation\n\n\nclass PWCDCNet(nn.Module):\n\n\n def __init__(self, device, lv_chs, search_range, batch_norm, corr_activation, residual, output_level):\n super(PWCDCNet, self).__init__()\n self.device = device\n self.lv_chs = lv_chs\n self.num_levels = len(lv_chs)\n self.search_range = search_range\n self.batch_norm = batch_norm\n self.corr_activation = corr_activation\n self.residual = residual\n self.output_level = output_level\n\n self.feature_pyramid_extractor = FeaturePyramidExtractor(lv_chs, batch_norm).to(device)\n \n self.warping_layer = DisparityWarpingLayer(device)\n\n # if args.corr == 'CostVolumeLayer':\n # self.corr = CostVolumeLayer(device, search_range)\n # else:\n # self.corr = Correlation(pad_size = search_range, kernel_size = 1, max_displacement = search_range, stride1 = 1, stride2 = 1, corr_multiply = 1).to(device)\n\n self.corr = CostVolumeLayer(device, search_range)\n \n self.disparity_estimators = []\n for l, ch in enumerate(lv_chs[::-1]):\n # layer = DisparityEstimator(ch + (search_range*2+1)**2 + 2, batch_norm).to(device)\n layer = DisparityEstimator(ch + (search_range*2+1)**2 + 1, batch_norm).to(device)\n self.add_module(f'DisparityEstimator(Lv{l})', layer)\n self.disparity_estimators.append(layer)\n\n self.dispchange_estimators = []\n for l, ch in enumerate(lv_chs[::-1]):\n # layer = DisparityEstimator(ch + (search_range*2+1)**2 + 2, batch_norm).to(device)\n layer = DisparityEstimator(ch + ((search_range*2+1)**2)*2 + 1*2, batch_norm).to(device)\n self.add_module(f'DispchangeEstimator(Lv{l})', layer)\n self.dispchange_estimators.append(layer)\n \n self.context_networks = []\n for l, ch in enumerate(lv_chs[::-1]):\n # layer = DisparityContextNetwork(ch + 2, batch_norm).to(device)\n layer = DisparityContextNetwork(ch + 1, batch_norm).to(device)\n self.add_module(f'ContextNetwork(Lv{l})', layer)\n self.context_networks.append(layer)\n\n self.dispchange_context_networks = []\n for l, ch in enumerate(lv_chs[::-1]):\n # layer = DisparityContextNetwork(ch + 2, batch_norm).to(device)\n layer = DisparityContextNetwork(ch*2 + 1, batch_norm).to(device)\n self.add_module(f'DispchangeContextNetwork(Lv{l})', layer)\n self.dispchange_context_networks.append(layer)\n\n # init\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n if m.bias is not None: nn.init.uniform_(m.bias)\n nn.init.xavier_uniform_(m.weight)\n\n if isinstance(m, nn.ConvTranspose2d):\n if m.bias is not None: nn.init.uniform_(m.bias)\n nn.init.xavier_uniform_(m.weight)\n\n def forward(self, x1_raw, x2_raw, x1_next_raw, x2_next_raw):\n\n # on the bottom level are original images\n x1_pyramid = self.feature_pyramid_extractor(x1_raw) + [x1_raw]\n x2_pyramid = self.feature_pyramid_extractor(x2_raw) + [x2_raw]\n x1_next_pyramid = self.feature_pyramid_extractor(x1_next_raw) + [x1_next_raw]\n x2_next_pyramid = self.feature_pyramid_extractor(x2_next_raw) + [x2_next_raw]\n\n\n for l, (x1, x2, x1_next, x2_next) in enumerate(zip(x1_pyramid, x2_pyramid, x1_next_pyramid, x2_next_pyramid)):\n # upsample flow and scale the displacement\n if l == 0:\n shape = list(x1.size()); shape[1] = 1\n dispchange = torch.zeros(shape).to(self.device)\n else:\n output_spatial_size = [x2.size(2), x2.size(3)]\n # flow = F.interpolate(flow, scale_factor = 2, mode = 'bilinear', align_corners=True) * 2\n dispchange = F.interpolate(dispchange, output_spatial_size, mode='bilinear', align_corners=True) * 2\n\n x2_warp = self.warping_layer(x2, disp)\n x2_next_warp = self.warping_layer(x2_next, disp_next)\n \n # correlation\n corr = self.corr(x1, x2_warp)\n if self.corr_activation: F.leaky_relu_(corr)\n corr_next = self.corr(x1_next, x2_next_warp)\n if self.corr_activation: F.leaky_relu_(corr_next)\n\n # concat and estimate flow\n # ATTENTION: `+ flow` makes flow estimator learn to estimate residual flow\n if self.residual:\n disp_coarse = self.disparity_estimators[l](torch.cat([x1, corr, disp], dim = 1)) + disp\n disp_next_coarse = self.disparity_estimators[l](torch.cat([x1_next, corr_next, disp_next], dim = 1)) + disp_next\n dispchange_coarse = self.dispchange_estimators[l](torch.cat([x1, disp, disp_next, corr, corr_next], dim = 1)) + dispchange\n else:\n disp_coarse = self.disparity_estimators[l](torch.cat([x1, corr, disp], dim = 1))\n disp_next_coarse = self.disparity_estimators[l](torch.cat([x1_next, corr_next, disp_next], dim = 1))\n dispchange_coarse = self.dispchange_estimators[l](torch.cat([x1, disp, disp_next, corr, corr_next], dim = 1))\n\n # print(disp_coarse.size())\n\n disp_fine = self.context_networks[l](torch.cat([x1, disp], dim = 1))\n disp_next_fine = self.context_networks[l](torch.cat([x1_next, disp_next], dim = 1))\n dispchange_fine = self.dispchange_context_networks[l](torch.cat([x1, x1_next, dispchange], dim = 1))\n\n disp = disp_coarse + disp_fine\n disp_next = disp_next_coarse + disp_next_fine\n dispchange = dispchange_coarse + dispchange_fine\n\n if l == self.output_level:\n dispchange = F.interpolate(dispchange, scale_factor = 2 ** (self.num_levels - self.output_level - 1), mode = 'bilinear', align_corners=True) * 2 ** (self.num_levels - self.output_level - 1)\n break\n\n return dispchange","sub_path":"src/model/nets/pwcnet_dispchange.py","file_name":"pwcnet_dispchange.py","file_ext":"py","file_size_in_byte":6335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"384495720","text":"import cv2\nimport os\nimport time\n\nimport numpy as np\nfrom imutils.video import FileVideoStream\n\nfrom rana_logger import add_log_entry, get_last_frame, setup, populate_video_table, \\\n get_processed_videos, add_processed_video\nfrom utils import get_video_list, manual_selection, get_filename, get_path_input, \\\n pollinator_setup, handle_pollinator, determine_site_preference\n\n\ndef handle_previous_frames(frame, previous_frames):\n \"\"\"\n Maintains and returns a list of up to the previous 200 frames\n which also includes the most recent/current frame.\n :param frame: Current frame.\n :param previous_frames: The current list of previous frames.\n :return: A list of at most 200 previous frames including the most\n recent/current frame.\n \"\"\"\n if len(previous_frames) >= 200:\n # Remove the oldest frame\n previous_frames.pop()\n\n # Add the current frame\n previous_frames.insert(0, frame)\n return previous_frames\n\n\ndef calculate_frame_number(labeled_frame, previous_frames, f_num):\n \"\"\"\n Calculates the frame number the user labeled.\n :param labeled_frame: The frame labeled by the user.\n :param previous_frames: The list of at most the 200 previous\n frames including the most recent/current frame.\n :param f_num: The current frame number from the video stream.\n :return calc_fnum: An integer value indicating the frame number\n that was labeled by the user.\n \"\"\"\n # Reverse the order of previous frames so recent frames are\n # located at the beginning of the list, allowing for list indexes\n # to be used to calculate the labeled frame number as an offset\n # of the current frame number.\n frame_idx = [np.array_equal(labeled_frame, frame) for frame in previous_frames].index(True)\n fnum_calc = f_num - frame_idx\n return fnum_calc\n\n\ndef process_video(arguments, vdir, video, site, plant):\n print(\"[*] Analyzing video {} from site {}, plant number {}.\".format(video, site, plant))\n last_log = get_last_frame(video)\n\n vs = FileVideoStream(os.path.join(vdir.directory, video)).start()\n\n # The current frame number and pollinator count\n f_num = 0\n count = 0\n\n # Allow the buffer some time to fill\n time.sleep(2.0)\n\n # Keep a list of previous frames\n previous_frames = []\n\n while vs.more():\n frame = vs.read()\n\n # If the frame is None, the video is done being processed and we can move to the next one\n if frame is None:\n break\n else:\n f_num += 1\n if last_log is not None and f_num <= last_log.frame:\n print(\"[*] Frame number {} has already been analyzed. Waiting for frame number {}...\"\n .format(f_num, last_log.frame + 1))\n # Continue to the next frame if the logs indicate we have analyzed frames later than this\n # one\n time.sleep(0.01) # Sleep here so we don't overtake the buffer\n continue\n\n \"\"\"\n Because previous frames are passed to manual selection,\n the pollinator selection may not have occurred on the\n current frame. Therefore, the frame number used for\n file names and logging will need to be calculated.\n \"\"\"\n previous_frames = handle_previous_frames(frame, previous_frames)\n pollinator, box, labeled_frame = manual_selection(f_num, previous_frames, site, plant, video)\n if pollinator is None and box is None and labeled_frame is None:\n continue\n\n fnum_calc = calculate_frame_number(labeled_frame, previous_frames, f_num)\n frame_fname = get_filename(fnum_calc, count, video, frame=True)\n if pollinator is not False and pollinator is not None:\n # Save the whole frame as a pollinator\n print(\"[*] Saving frame as an example of Pollinator.\")\n cv2.imwrite(os.path.join(arguments[\"write_path\"], \"Frames\", \"Pollinator\", frame_fname),\n labeled_frame)\n\n # And save the pollinator\n pol_fname = get_filename(fnum_calc, count, video)\n count = handle_pollinator(arguments, pol_fname, vdir, count, fnum_calc, pollinator, box, video,\n labeled_frame)\n\n elif pollinator is False and box is None:\n # Save the whole frame as an example of no pollinator\n print(\"[*] Saving frame as an example of Not_Pollinator.\")\n img_path = os.path.join(arguments[\"write_path\"], \"Frames\", \"Not_Pollinator\", frame_fname)\n cv2.imwrite(img_path, labeled_frame)\n w, h, _ = frame.shape\n size = w * h\n print(\"[*] Logging this frame as Not_Pollinator.\")\n add_log_entry(directory=vdir.directory,\n video=video,\n time=None,\n classification=\"Not_Pollinator\",\n pollinator_id=None,\n proba=None,\n genus=None,\n species=None,\n behavior=None,\n size=size,\n bbox=\"Whole\", # Entire frame\n size_class=None,\n frame_number=fnum_calc,\n manual=True,\n img_path=img_path,\n )\n\n # Video is done being processed\n add_processed_video(video, pollinator=True)\n vs.stop()\n\n\ncv2.destroyAllWindows()\n\n\ndef main(arguments):\n pollinator_setup(arguments)\n\n video_list = get_video_list(arguments[\"video_path\"])\n if not video_list:\n print(\"[!] No videos found in path: {}\".format(arguments[\"video_path\"]))\n\n site_pref = determine_site_preference(video_list)\n populate_video_table(video_list)\n\n processed_videos = get_processed_videos(pollinator=True)\n\n for vdir in video_list:\n split = vdir.directory.split(os.path.sep)[-2:] # Extract site and plant info from directory path\n site = split[0]\n if site_pref and site != site_pref:\n # If the user indicated a particular site, skip the others\n print(\"Skipping video from {} since you indicated you would like to work on site {}.\".format(site,\n site_pref))\n continue\n plant = split[1]\n for video in vdir.files:\n if video in processed_videos:\n print(\"[*] Video has been fully processed. Skipping...\")\n continue\n else:\n process_video(arguments, vdir, video, site, plant)\n\n\nif __name__ == \"__main__\":\n # Setup the database file\n setup()\n # Create a dictionary to store video and image path info\n args = get_path_input()\n main(args)\n","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":6875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"585799573","text":"# Aufgabe:\r\n# http://exercism.io/exercises/python/isbn-verifier/readme\r\n\r\n# Prüfe, ob isbn eine gültige ISBN-Nummer ist\r\nimport re\r\n\r\ndef verify(isbn):\r\n if len(isbn) < 10:\r\n return False\r\n\r\n check_digit = isbn[-1] # letzte Stelle der Eingabe\r\n if check_digit == \"X\":\r\n check_digit = 10\r\n elif check_digit.isdigit():\r\n check_digit = int(check_digit) # gültige Prüfziffer ist 0, 1, 2, ..., 9 oder X\r\n else:\r\n return False\r\n\r\n pre = isbn[:-1] # entferne die letzte Stelle der Eingabe\r\n pre = pre.replace(\"-\", \"\") # entferne Bindestriche\r\n if len(pre) != 9:\r\n return False\r\n\r\n pre = re.sub('[^0-9]', '', pre) # behalte nur Ziffern\r\n if len(pre) != 9:\r\n return False\r\n\r\n sum = 0\r\n for i in range(9):\r\n sum += int(pre[i]) * (10 - i)\r\n sum += check_digit\r\n\r\n return sum % 11 == 0","sub_path":"___Python/Torsten/Python-Kurs/p09_isbn/m01_isbn.py","file_name":"m01_isbn.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"76364197","text":"from PIL import Image, ImageDraw, ImageFont, ImageOps\nimport random\nimport sqlite3\nimport logging\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom optparse import OptionParser\n\nimport background_data_util\nimport font_data_util\n\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\nCHARACTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K']\nCOLORS = [\n (255, 255, 255), (255, 0, 0), (0, 255, 0),\n (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]\n\n\ndef load(font_size=48):\n images = background_data_util.load()\n images = [Image.open(path) for path in images]\n fonts = font_data_util.load()\n fonts = [ImageFont.truetype(path, font_size) for path in fonts]\n return images, fonts\n\n\ndef create_font_image(images, fonts, image_index, font_index,\n text='A', rotation=0, padding=12, output_size=64, color=(255, 0, 0)):\n assert image_index >= 0 and image_index < len(images)\n assert font_index >= 0 and font_index < len(fonts)\n\n img = images[image_index].copy()\n font = fonts[font_index]\n\n assert output_size < img.size[0] and output_size < img.size[1]\n\n txt = Image.new('L', (output_size, output_size))\n txt_draw = ImageDraw.Draw(txt)\n w, h = txt_draw.textsize(text, font=font)\n txt_draw.text(((output_size - w)/2, (output_size - h - padding)/2),\n text, font=font, fill=255)\n rotated = txt.rotate(rotation)\n\n x = random.randrange(0, img.size[0] - output_size)\n y = random.randrange(0, img.size[1] - output_size)\n img = img.crop((x, y, x + output_size, y + output_size))\n img.paste(ImageOps.colorize(rotated, (0, 0, 0), color), (0, 0),\n rotated)\n return img\n\n\ndef create_db(db_name, image_count, characters, colors, image_size=64):\n connection = sqlite3.connect(db_name)\n cursor = connection.cursor()\n cursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS characters(\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n data BLOB NOT NULL,\n width INTEGER,\n height INTEGER,\n rotation REAL,\n char TEXT\n );\"\"\")\n\n images, fonts = load()\n logger.info('inserting data into %s...' % (db_name))\n for i in range(image_count):\n image_index = random.randrange(0, len(images))\n font_index = random.randrange(0, len(fonts))\n rotation = random.randrange(0, 359)\n text = characters[random.randrange(0, len(characters))]\n color = colors[random.randrange(0, len(colors))]\n img = create_font_image(images, fonts, image_index, font_index, text=text,\n rotation=rotation, output_size=image_size, color=color)\n if rotation > 180:\n rotation -= 360\n cursor.execute(\"\"\"INSERT INTO characters(\n data, width, height, rotation, char) values (?, ?, ?, ?, ?);\"\"\",\n (buffer(np.array(img).tobytes()),\n image_size, image_size, rotation * math.pi / 180.0, text,))\n connection.commit()\n\n\ndef load_data(db_name, characters):\n connection = sqlite3.connect(db_name)\n cursor = connection.cursor()\n cursor.execute(\"\"\"SELECT * FROM characters;\"\"\")\n entries = cursor.fetchall()\n\n data = []\n label = []\n num_label = len(characters)\n logger.info('loading data from %s...' % (db_name))\n for entry in entries:\n w = entry[2]\n h = entry[3]\n data.append(np.array(entry[1]).reshape(h, w, 3))\n index = next(i for i, c in enumerate(characters) if c == entry[5])\n label.append([1 if l == index else 0 for l in range(num_label)] +\n [entry[4]])\n return np.array(data), np.array(label)\n\n\ndef main():\n parser = OptionParser()\n parser.add_option('-n', '--num_images', dest='num_images', default=10000,\n help='number of images to add to database')\n parser.add_option('-o', '--output', dest='output_db',\n default='characters_train.sqlite',\n help='output sqlite database path')\n option, args = parser.parse_args()\n\n create_db(option.output_db, int(option.num_images), CHARACTERS, COLORS)\n data, label = load_data(option.output_db, CHARACTERS)\n print('data shape: %s' % (str(data.shape)))\n\n index = random.randrange(len(data))\n plt.imshow(data[index])\n print(label[index, :])\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"rotational-invariance/data_util/rotational_invariance_data_util.py","file_name":"rotational_invariance_data_util.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"645308411","text":"# -*- coding: UTF-8 -*-\n#-----------------------------------------------------------------------------\n# project : Lisa server\n# module : plugins\n# file : PluginManager.py\n# description : Management of the plugins\n# author : G.Dumee\n#-----------------------------------------------------------------------------\n# copyright : Neotique\n#-----------------------------------------------------------------------------\n\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\nimport lisa.plugins, os, pip, shutil, inspect, json, datetime, uuid, importlib\nimport lisa.server.core\nfrom lisa.server.web.manageplugins.models import Plugin, Cron, Intent\nfrom twisted.python.reflect import namedAny\nfrom django.template.loader import render_to_string\nfrom pymongo import MongoClient\nfrom twisted.python import log\nfrom lisa.server.config_manager import ConfigManager\nfrom twisted.python.reflect import namedAny\n\n\n#-----------------------------------------------------------------------------\n# Globals\n#-----------------------------------------------------------------------------\n# Get server configuration\nconfiguration = ConfigManager.getConfiguration()\n\n# Get paths\nserver_path = configuration['path']\nplugins_path = os.path.dirname(lisa.plugins.__file__)\n\n\n#-----------------------------------------------------------------------------\n# PluginManager\n#-----------------------------------------------------------------------------\nclass PluginManager(object):\n \"\"\"\n Manage plugins\n \"\"\"\n # Plugins instances\n __PluginsInstances = {}\n\n #-----------------------------------------------------------------------------\n def __init__(self):\n # Not to be implemented\n raise\n\n #-----------------------------------------------------------------------------\n @classmethod\n def getEnabledPluginNames(cls):\n # List enabled plugins\n plugin_list = Plugin.objects(enabled = True, lang = configuration['lang_short'])\n\n # Fill plugins name list\n enabled_plugins_names = []\n for plugin in plugin_list:\n enabled_plugins_names.append(str(plugin['name']))\n\n return enabled_plugins_names\n\n #-----------------------------------------------------------------------------\n @classmethod\n def getEnabledPlugins(cls):\n # List enabled plugins\n return Plugin.objects(enabled = True, lang = configuration['lang_short'])\n\n #-----------------------------------------------------------------------------\n @classmethod\n def getEnabledIntents(cls):\n return Intent.objects(enabled = True)\n\n #-----------------------------------------------------------------------------\n @classmethod\n def getIntent(cls, intent_name):\n # TODO get these intents from a core function\n # Create the default core intents\n defaults_intent_list = {'name': \"core_i_can\",\n 'method_name': \"list_plugins\",\n 'plugin_name': \"Core\",\n 'enabled': True}\n intent_list, created = Intent.objects.get_or_create(name = 'core_i_can', defaults = defaults_intent_list)\n defaults_intent_list = {'name': \"core_i_can_plugin\",\n 'method_name': \"list_plugin_intents\",\n 'plugin_name': \"Core\",\n 'enabled': True}\n intent_list, created = Intent.objects.get_or_create(name = 'core_i_can_plugin', defaults = defaults_intent_list)\n\n # List enabled intents\n intent_list = Intent.objects(name = intent_name, enabled = True)\n\n # If not a unique enabled intent\n if intent_list is None or len(intent_list) != 1:\n return None\n\n return intent_list[0]\n\n #-----------------------------------------------------------------------------\n @classmethod\n def init(cls, global_context):\n # Instantiate Core plugin\n module = importlib.import_module(\"lisa.server.core.intents\")\n cls.__PluginsInstances[0] = getattr(module, \"Intents\")()\n cls.__PluginsInstances[0].uid = 0\n\n # Get enabled plugin lists\n plugin_list = cls.getEnabledPlugins()\n\n # Update plugin install\n for plugin in plugin_list:\n log.msg(\"Initiating plugin {name}\".format(name = plugin.name))\n cls._updatePlugin(plugin = plugin)\n\n try:\n # Create plugin instance\n cls.__PluginsInstances[plugin.pk] = namedAny(plugin.module)()\n cls.__PluginsInstances[plugin.pk].uid = plugin.pk\n except:\n log.err(\"Error while instantiating plugin {}\".format(plugin.name))\n if configuration['debug']['debug_plugin'] == True:\n raise\n\n # Init global context vars\n if hasattr(plugin, 'context') == True and plugin.context.has_key('global') == True:\n for var in plugin.context['global']:\n try:\n global_context.createGlobalVar(name = var, default = plugin.context['global'][var])\n except:\n log.err(\"Error while creating global context var {} for plugin {}\".format(var, plugin.name))\n if configuration['debug']['debug_plugin'] == True:\n raise\n\n #-----------------------------------------------------------------------------\n @classmethod\n def initContext(cls, context):\n # Get enabled plugin lists\n plugin_list = cls.getEnabledPlugins()\n\n # Update plugin install\n for plugin in plugin_list:\n if hasattr(plugin, 'context') == True and plugin.context.has_key('client') == True:\n for var in plugin.context['client']:\n try:\n context.createClientVar(name = var, default = plugin.context['client'][var])\n except:\n log.err(\"Error while creating client context var {} for plugin {}\".format(var, plugin['name']))\n if configuration['debug']['debug_plugin'] == True:\n raise\n\n #-----------------------------------------------------------------------------\n @classmethod\n def deinit(cls):\n # Get enabled plugin lists\n plugin_list = cls.getEnabledPlugins()\n\n # Delete plugin instances\n for pk in cls.__PluginsInstances:\n try:\n cls.__PluginsInstances[pk].clean()\n except:\n pass\n cls.__PluginsInstances = {}\n\n #-----------------------------------------------------------------------------\n @classmethod\n def getPlugin(cls, plugin_name = None, plugin_uid = None):\n # Return fake core plugin\n if (plugin_uid is not None and plugin_uid == 0) or (plugin_name is not None and plugin_name == \"Core\"):\n class FakePlugin():\n def __init__(self):\n self.name = \"Core\"\n self.pk = 0\n self.uid = 0\n self.steps = {'count': 0, 'first': None, 'last': None}\n return FakePlugin()\n\n # List enabled plugins\n plugin_list = Plugin.objects(enabled = True, lang = configuration['lang_short'])\n\n # Search plugin\n for plugin in plugin_list:\n # Search plugin by name\n if plugin_name is not None and plugin.name == plugin_name:\n return plugin\n\n # Search plugin by uid\n if plugin_uid is not None and plugin.pk == plugin_uid:\n return plugin\n\n # Not found\n return None\n\n #-----------------------------------------------------------------------------\n @classmethod\n def getPluginInstance(cls, plugin_name = None, plugin_uid = None):\n plugin = cls.getPlugin(plugin_name = plugin_name, plugin_uid = plugin_uid)\n if plugin is None:\n return None\n\n if cls.__PluginsInstances.has_key(plugin.pk) == False:\n return None\n\n return cls.__PluginsInstances[plugin.pk]\n\n #-----------------------------------------------------------------------------\n @classmethod\n def getPluginMethod(cls, plugin, method_name):\n # Core intents\n if plugin.name == \"Core\":\n return getattr(cls.__PluginsInstances[0], method_name)\n\n # Get method from instance\n try:\n return getattr(cls.__PluginsInstances[plugin.pk], method_name)\n except:\n if configuration['debug']['debug_plugin'] == True:\n raise\n\n return None\n\n #-----------------------------------------------------------------------------\n @classmethod\n def installPlugin(cls, plugin_name = None, test_mode = False, dev_mode = False):\n # If already installed\n if Plugin.objects(name = plugin_name):\n return {'status': 'fail', 'log': 'Plugin already installed'}\n\n # If not dev mode, download package\n if not dev_mode:\n if test_mode:\n pip.main(['install', '--quiet', '--install-option=--install-platlib=' + os.getcwd() + '/../',\n '--install-option=--install-purelib=' + os.getcwd() + '/../', 'lisa-plugin-' + plugin_name])\n else:\n pip.main(['install', 'lisa-plugin-' + plugin_name])\n\n # Create new plugin\n plugin = Plugin()\n setattr(plugin, 'name', plugin_name)\n\n # Update plugin in DB\n cls._updatePlugin(plugin = plugin)\n\n return {'status': 'success', 'log': 'Plugin installed'}\n\n #-----------------------------------------------------------------------------\n @classmethod\n def updatePlugin(cls, plugin_name = None, plugin_pk = None):\n # Get plugin by name or pk\n if plugin_pk:\n plugin_list = Plugin.objects(pk = plugin_pk)\n else:\n plugin_list = Plugin.objects(name = plugin_name)\n\n # Should be only one result\n if not plugin_list or len(plugin_list) != 1:\n return {'status': 'fail', 'log': 'Plugin not installed'}\n plugin = plugin_list[0]\n\n # Update plugin\n cls._updatePlugin(plugin = plugin)\n\n return {'status': 'success', 'log': 'Plugin updated'}\n\n #-----------------------------------------------------------------------------\n @classmethod\n def _updatePlugin(cls, plugin):\n # Load JSON\n plugin_path = os.path.normpath(plugins_path + '/' + plugin.name)\n jsonfile = os.path.normpath(plugin_path + '/' + plugin.name.lower() + '.json')\n try:\n metadata = json.load(open(jsonfile))\n except:\n log.err(\"Invalid JSON file for plugin {plugin} : {file}\".format(plugin = plugin.name, file = jsonfile))\n return\n\n # Parse file\n for item in metadata:\n if item == 'enabled':\n if metadata[item] == 0 or (type(metadata[item]) == str and metadata[item].lower() == 'false'):\n setattr(plugin, item, False)\n else:\n setattr(plugin, item, True)\n elif item != 'crons':\n setattr(plugin, item, metadata[item])\n\n # Delete older items\n d = plugin.__dict__.copy()\n for k in d:\n if k.startswith(\"_\") == False and k not in metadata and k != 'enabled':\n delattr(plugin, k)\n\n # TODO remove when uid are not useful\n setattr(plugin, 'uid', plugin.pk)\n\n #TODO\n setattr(plugin, 'steps', {'count': 0, 'first': None, 'last': None})\n\n # Add langages from directory search\n setattr(plugin, 'lang', [])\n localedir = os.path.normpath(plugin_path + '/lang')\n for x in os.listdir(localedir):\n try:\n if os.path.isfile(\"{localedir}/{lang}/LC_MESSAGES/{plugin}.po\".format(localedir = localedir, lang = x, plugin = plugin.name.lower())) == True:\n plugin.lang.append(x)\n except:\n pass\n\n # Add items\n setattr(plugin, 'path', plugin_path)\n setattr(plugin, 'module', '.'.join(['lisa.plugins', plugin.name, 'modules', plugin.name.lower(), plugin.name]))\n\n # Save updated plugin\n plugin.save()\n\n # Update crons\n remove_list = list(Cron.objects(plugin = plugin))\n if metadata.has_key('crons'):\n for cron_name, cron_item in metadata['crons'].iteritems():\n # Get cron from DB\n cron = None\n cron_list = Cron.objects(plugin = plugin, name = cron_name)\n if cron_list is not None and len(cron_list) == 1:\n cron = cron_list[0]\n\n # It's a new cron\n if cron is None:\n # Create a new cron\n cron = Cron()\n new_cron= True\n else:\n # Remove cron from list of crons to remove\n remove_list.remove(cron)\n new_cron = False\n\n # Update cron\n for parameter in cron_item:\n if parameter != 'enabled':\n setattr(cron, parameter, cron_item[parameter])\n\n # Delete older items\n d = cron.__dict__.copy()\n for k in d:\n if k.startswith(\"_\") == False and k not in cron_item and k != 'enabled':\n delattr(cron, k)\n\n # Set enabled only for new crons\n if new_cron == True:\n if cron_item.has_key('enabled') == True and (cron_item['enabled'] == 0 or (type(cron_item['enabled']) == str and cron_item['enabled'].lower() == 'false')):\n setattr(cron, 'enabled', False)\n else:\n setattr(cron, 'enabled', True)\n\n # Add items\n setattr(cron, 'name', cron_name)\n\n # Connect cron to plugin\n cron.plugin = plugin\n\n # Save cron\n cron.save()\n\n # Delete older crons for this plugin\n for i in remove_list:\n i.delete()\n\n # Update intents\n remove_list = list(Intent.objects(plugin = plugin))\n metadata_intents = None\n if metadata.has_key('configuration') and metadata['configuration'].has_key('intents'):\n metadata_intents = metadata['configuration']['intents']\n if metadata.has_key('intents'):\n metadata_intents = metadata['intents']\n if metadata_intents is not None:\n for wit_intent, intent_item in metadata_intents.iteritems():\n # Get intent from DB\n intent = None\n intent_list = Intent.objects(plugin = plugin, name = wit_intent)\n if intent_list is not None and len(intent_list) == 1:\n intent = intent_list[0]\n\n # It's a new intent\n if intent is None:\n # Create a new intent\n intent = Intent()\n new_intent= True\n else:\n # Remove intent from list of intents to remove\n remove_list.remove(intent)\n new_intent = False\n\n # Update intent\n for parameter in intent_item:\n if parameter == 'method':\n setattr(intent, 'method_name', intent_item[parameter])\n elif parameter == 'i_can':\n setattr(intent, parameter, intent_item[parameter])\n\n # Delete older items\n d = intent.__dict__.copy()\n for k in d:\n if k.startswith(\"_\") == False and k not in intent_item and k != 'enabled':\n delattr(intent, k)\n\n # Set enabled only for new intents\n if new_intent == True:\n setattr(intent, 'enabled', True)\n\n # Connect intent to plugin\n intent.plugin = plugin\n intent.plugin_name = plugin.name\n\n # Add items\n setattr(intent, 'name', wit_intent)\n\n # Save intent\n intent.save()\n\n # Delete older intents for this plugin\n for i in remove_list:\n i.delete()\n\n #-----------------------------------------------------------------------------\n @classmethod\n def enablePlugin(cls, plugin_name = None, plugin_pk = None):\n return cls._set_plugin_enabled(enabled = True, plugin_name = plugin_name, plugin_pk = plugin_pk)\n\n #-----------------------------------------------------------------------------\n @classmethod\n def disablePlugin(cls, plugin_name = None, plugin_pk = None):\n return cls._set_plugin_enabled(enabled = False, plugin_name = plugin_name, plugin_pk = plugin_pk)\n\n #-----------------------------------------------------------------------------\n @classmethod\n def _set_plugin_enabled(cls, enabled, plugin_name = None, plugin_pk = None):\n # Log string\n if enabled == True:\n astr = \"enabled\"\n else:\n astr = \"disabled\"\n\n # Get plugin by name or pk\n if plugin_pk:\n plugin_list = Plugin.objects(pk = plugin_pk)\n else:\n plugin_list = Plugin.objects(name = plugin_name)\n\n # Should be only one result\n if not plugin_list or len(plugin_list) != 1:\n return {'status': 'fail', 'log': 'Plugin not installed'}\n plugin = plugin_list[0]\n\n # If already done\n if enabled == True and plugin.enabled == enabled:\n return {'status': 'fail', 'log': 'Plugin already ' + astr}\n if enabled == False and plugin.enabled == enabled:\n return {'status': 'fail', 'log': 'Plugin already ' + astr}\n\n # Enable plugin\n plugin.enabled = enabled\n plugin.save()\n\n # Enable plugin crons\n for cron in Cron.objects(plugin = plugin):\n cron.enabled = enabled\n cron.save()\n\n # Enable plugin intents\n for intent in Intent.objects(plugin = plugin):\n intent.enabled = enabled\n intent.save()\n\n return {'status': 'success', 'log': 'Plugin ' + astr}\n\n #-----------------------------------------------------------------------------\n @classmethod\n def uninstallPlugin(cls, plugin_name = None, plugin_pk = None, dev_mode = False):\n # Get plugin by name or pk\n if plugin_pk:\n plugin_list = Plugin.objects(pk = plugin_pk)\n else:\n plugin_list = Plugin.objects(name = plugin_name)\n\n # Should be only one result\n if not plugin_list or len(plugin_list) != 1:\n return {'status': 'fail', 'log': 'Plugin not installed'}\n plugin = plugin_list[0]\n\n # Uninstall pip package\n if not dev_mode:\n pip.main(['uninstall', '--quiet', 'lisa-plugin-' + plugin_name])\n\n # Remove plugin crons\n for cron in Cron.objects(plugin = plugin):\n cron.delete()\n\n # Remove plugin intents\n for oIntent in Intent.objects(plugin = plugin):\n oIntent.delete()\n\n # Remove plugin\n plugin.delete()\n\n return {'status': 'success', 'log': 'Plugin uninstalled'}\n\n #-----------------------------------------------------------------------------\n @classmethod\n def getPluginMethods(cls, plugin_name = None):\n # Get plugin by name or pk\n if plugin_name:\n plugin_list = Plugin.objects(name = plugin_name)\n else:\n plugin_list = Plugin.objects\n\n # Parse plugins\n listallmethods = []\n for plugin in plugin_list:\n plugininstance = namedAny('.'.join(('lisa.plugins', str(plugin.name), 'modules', str(plugin.name).lower(), str(plugin.name))))()\n listpluginmethods = []\n for m in inspect.getmembers(plugininstance, predicate = inspect.ismethod):\n if not \"__init__\" in m and not m.startswith(\"_\"):\n listpluginmethods.append(m[0])\n listallmethods.append({'plugin': plugin.name, 'methods': listpluginmethods})\n\n # Parse core plugins\n for f in os.listdir(os.path.normpath(server_path + '/core')):\n fileName, fileExtension = os.path.splitext(f)\n if os.path.isfile(os.path.join(os.path.normpath(server_path + '/core'), f)) and not f.startswith('__init__') and fileExtension != '.pyc':\n coreinstance = namedAny('.'.join(('lisa.server.core', str(fileName).lower(), str(fileName).capitalize())))()\n listcoremethods = []\n for m in inspect.getmembers(coreinstance, predicate = inspect.ismethod):\n #init shouldn't be listed in methods and _ is for translation\n if not \"__init__\" in m and not m.startswith(\"_\"):\n listcoremethods.append(m[0])\n listallmethods.append({'core': fileName, 'methods': listcoremethods})\n\n log.msg(listallmethods)\n return listallmethods\n\n #-----------------------------------------------------------------------------\n @classmethod\n def _template_to_file(cls, filename, template, context):\n import codecs\n codecs.open(filename, 'w', 'utf-8').write(render_to_string(template, context))\n\n #-----------------------------------------------------------------------------\n @classmethod\n def createPlugin(cls, plugin_name, author_name, author_email):\n import requests\n import pytz\n\n metareq = requests.get('/'.join([configuration['plugin_store'], 'plugins.json']))\n if(metareq.ok):\n for item in json.loads(metareq.text or metareq.content):\n if item['name'].lower() == plugin_name.lower():\n return {'status': 'fail', 'log': 'Plugin already exist in the store'}\n context = {\n 'plugin_name': plugin_name,\n 'plugin_name_lower': plugin_name.lower(),\n 'author_name': author_name,\n 'author_email': author_email,\n 'creation_date': pytz.UTC.localize(datetime.datetime.now()).strftime(\"%Y-%m-%d %H:%M%z\")\n }\n\n # Create plugin dir\n os.mkdir(os.path.normpath(plugins_path + '/' + plugin_name))\n\n # Lang stuff\n os.mkdir(os.path.normpath(plugins_path + '/' + plugin_name + '/lang'))\n os.mkdir(os.path.normpath(plugins_path + '/' + plugin_name + '/lang/fr'))\n os.mkdir(os.path.normpath(plugins_path + '/' + plugin_name + '/lang/fr/LC_MESSAGES'))\n cls._template_to_file(filename = os.path.normpath(plugins_path + '/' + plugin_name + '/lang/fr/LC_MESSAGES/' + plugin_name.lower() + '.po'),\n template = 'plugin/lang/fr/LC_MESSAGES/module.po',\n context = context)\n\n # Module stuff\n os.mkdir(os.path.normpath(plugins_path + '/' + plugin_name + '/modules'))\n cls._template_to_file(filename = os.path.normpath(plugins_path + '/' + plugin_name + '/modules/' + plugin_name.lower() + '.py'),\n template = 'plugin/modules/module.tpl',\n context = context)\n open(os.path.normpath(plugins_path + '/' + plugin_name + '/modules/__init__.py'), \"a\")\n\n # Web stuff\n os.mkdir(os.path.normpath(plugins_path + '/' + plugin_name + '/web'))\n os.mkdir(os.path.normpath(plugins_path + '/' + plugin_name + '/web/templates'))\n shutil.copy(src = os.path.normpath(server_path + '/web/manageplugins/templates/plugin/web/templates/widget.html'),\n dst = os.path.normpath(plugins_path + '/' + plugin_name + '/web/templates/widget.html'))\n shutil.copy(src = os.path.normpath(server_path + '/web/manageplugins/templates/plugin/web/templates/index.html'),\n dst = os.path.normpath(plugins_path + '/' + plugin_name + '/web/templates/index.html'))\n open(os.path.normpath(plugins_path + '/' + plugin_name + '/web/__init__.py'), \"a\")\n cls._template_to_file(filename = os.path.normpath(plugins_path + '/' + plugin_name + '/web/api.py'),\n template = 'plugin/web/api.tpl',\n context = context)\n cls._template_to_file(filename = os.path.normpath(plugins_path + '/' + plugin_name + '/web/models.py'),\n template = 'plugin/web/models.tpl',\n context = context)\n cls._template_to_file(filename = os.path.normpath(plugins_path + '/' + plugin_name + '/web/tests.py'),\n template = 'plugin/web/tests.tpl',\n context = context)\n cls._template_to_file(filename = os.path.normpath(plugins_path + '/' + plugin_name + '/web/urls.py'),\n template = 'plugin/web/urls.tpl',\n context = context)\n cls._template_to_file(filename = os.path.normpath(plugins_path + '/' + plugin_name + '/web/views.py'),\n template = 'plugin/web/views.tpl',\n context = context)\n\n # Plugin stuff (metadata)\n cls._template_to_file(filename = os.path.normpath(plugins_path + '/' + plugin_name + '/__init__.py'),\n template = 'plugin/__init__.tpl',\n context = context)\n cls._template_to_file(filename = os.path.normpath(plugins_path + '/' + plugin_name + '/README.rst'),\n template = 'plugin/README.rst',\n context = context)\n cls._template_to_file(filename = os.path.normpath(plugins_path + '/' + plugin_name + '/' + plugin_name.lower() + '.json'),\n template = 'plugin/module.json',\n context = context)\n\n return {'status': 'success', 'log': 'Plugin created'}\n\n# --------------------- End of PluginManager.py ---------------------\n","sub_path":"lisa/server/plugins/PluginManager.py","file_name":"PluginManager.py","file_ext":"py","file_size_in_byte":26268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"144947090","text":"#======生成指定长度的随机字符串的函数==========\nfrom random import Random\ndef random_str(randomlength=8):\n str = ''\n chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'\n random = Random()\n for i in range(randomlength):\n str += chars[random.randint(0,len(chars)-1)]\n return str\n# print(random_str())\n\n#========发送邮箱验证==============\nfrom users.models import EmailVerifyRecord\nfrom django.core.mail import send_mail\nfrom mydjango.settings import EMAIL_FROM\ndef send_register_email(email,send_type='register'):\n email_record = EmailVerifyRecord()\n email_record.code = random_str(10)\n email_record.email = email\n email_record.send_type = send_type\n email_record.save()\n\n email_title = ''\n email_body = ''\n if send_type == 'register':\n email_title = '新用户账号激活'\n email_body = '请点击如下链接激活账号 http://127.0.0.1:8000/user/active/{0}'.format(email_record.code)\n # 使用django内部函数发送邮件\n send_status = send_mail(email_title,email_body,EMAIL_FROM,[email_record.email])\n if send_status:\n return send_status\n else:\n return False\n elif send_type == 'forget':\n email_title = '用户密码找回'\n email_body = '请点击如下链接重置用户密码 http://127.0.0.1:8000/user/resetpwd/{0}'.format(email_record.code)\n send_status = send_mail(email_title, email_body, EMAIL_FROM, [email_record.email])\n if send_status:\n return send_status\n else:\n return False\n\n","sub_path":"mydjango/apps/utils/email_send.py","file_name":"email_send.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"204032952","text":"import os\nimport numpy as np\nfrom PIL import Image\n\n'''\n参考:https://blog.csdn.net/weixin_44617502/article/details/113567148\n另一种方法:https://www.coder.work/article/1247090\n'''\n\npath = r'C:\\Users\\haidu\\Desktop\\YOLOP\\YoloP_data\\all_data_filter\\label'\nlane_path = r'C:\\Users\\haidu\\Desktop\\YOLOP\\YoloP_data\\all_data_filter\\lane_label'\nroad_path = r'C:\\Users\\haidu\\Desktop\\YOLOP\\YoloP_data\\all_data_filter\\road_label'\n\nfiles = os.listdir(path)\nfor fname in files:\n files = os.path.join(path, fname)\n img = Image.open(files)\n img_array = np.array(img) # 把图像转成数组格式\n shape = img_array.shape\n # print(img_array.shape)\n dst_road = np.zeros((shape[0], shape[1]))\n dst_lane = np.zeros((shape[0], shape[1]))\n # color =set()\n for i in range(0, shape[0]):\n for j in range(0, shape[1]):\n value = img_array[i, j]\n # if value not in color:\n # color.add(value)\n if img_array[i, j] == 1:\n dst_lane[i, j] = 255\n dst_road[i, j] = 255\n if img_array[i, j] == 2:\n dst_road[i, j] = 255\n img_road = Image.fromarray(np.uint8(dst_road))\n img_lane = Image.fromarray(np.uint8(dst_lane))\n # img_road = Image.fromarray(dst_road, mode='RGB')\n # img_lane = Image.fromarray(dst_lane, mode='RGB')\n # img_road = Image.open(img_road).convert('RGBA')\n # img_lane = Image.open(img_lane).convert('RGBA')\n file_name, file_extend = os.path.splitext(fname)\n dst_road = os.path.join(os.path.abspath(road_path), file_name + '.png')\n dst_lane = os.path.join(os.path.abspath(lane_path), file_name + '.png')\n img_road.save(dst_road)\n img_lane.save(dst_lane)\n","sub_path":"util_scripts/python_scripts/cov_8to32.py","file_name":"cov_8to32.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"533247096","text":"\"\"\"\nAuthor : Hoang Anh Nguyen\nEmail : n.h.a.1986@gmail.com\nLicence: BSD\n\"\"\"\n\nimport sys\nimport os\nimport numpy as np\nfrom time import time\nfrom utility import load_instances, load_labels, load_timestamps, convert_to_classlabels, write_results, plot_learning_curve\nfrom scipy.stats import randint as sp_randint\nfrom sklearn.svm import NuSVC\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import ExtraTreesClassifier, ExtraTreesRegressor\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.model_selection import RandomizedSearchCV, cross_val_score\nfrom sklearn.cross_validation import ShuffleSplit\nfrom sklearn.cross_validation import train_test_split\nimport matplotlib.pyplot as plt\n\n#------------------------------------------------------------\n#--------------------- Classfier Classes --------------------\n#------------------------------------------------------------\nclass Classifier:\n \n def __init__(self, X, y):\n self.y = y\n self.selectFeature(X) \n \n # Public methods\n def train(self, performTuning=False, showLearningCurve=False):\n \"\"\" train the model w.r.t input X and ground-truth label y\n return: optimal model\n \"\"\"\n print('======= Training model ========')\n \n # define cross validation method: Shuffle & Split\n if performTuning == False:\n self.model.fit(self.X, self.y)\n \n # show learning curve\n if showLearningCurve == True:\n title = 'Learning Curves'\n cv = ShuffleSplit(self.X.shape[0],\n n_iter=1,\n test_size=0.2,\n random_state=0)\n plot_learning_curve(self.model,\n title,\n self.X,\n self.y,\n cv=cv)\n plt.show()\n else:\n if not hasattr(self, 'param_rand'):\n print('This method does not support hyper-parameter tuning!')\n self.model.fit(self.X, self.y)\n return\n \n print('Start hyper-parameter tuning:')\n \n # we use random search grid for exploring hyperparameters space +\n # shuffle data input at each iteration\n n_iter_search = 20\n cv = ShuffleSplit(self.X.shape[0],\n n_iter=n_iter_search,\n test_size=0.2,\n random_state=0)\n random_search = RandomizedSearchCV(n_jobs=-1,\n estimator=self.model,\n cv=cv,\n param_distributions=self.param_rand,\n n_iter=n_iter_search)\n \n start = time()\n random_search.fit(self.X, self.y)\n print(\"RandomizedSearchCV took %.2f seconds for %d candidates\"\n \" parameter settings.\" % ((time() - start), n_iter_search))\n self._report(random_search.cv_results_)\n\n # use the best estimator\n self.model = random_search.best_estimator_\n \n print(\"Training accuracy: %.4f\" % self.model.score(self.X,\n self.y))\n \n def predict(self, X):\n \"\"\" predict label on the given input\n return: predicted label of each input\n \"\"\"\n return self.model.predict(X)\n \n ## Helpers\n def selectFeature(self, X):\n \"\"\" Compute feature importances by using ExtraTreesRegressor\n return: less dimensional features\n \"\"\"\n clf = ExtraTreesRegressor(n_jobs=-1)\n clf.fit(X, self.y)\n self.features = SelectFromModel(estimator=clf,\n threshold='0.24*mean',\n prefit=True)\n self.X = self.features.transform(X)\n print('New feature size: %.d' % self.X.shape[1])\n \n def _report(self, results, n_top=3):\n \"\"\" Display top 3 best models from random search for hyperparameters\n return: None\n \"\"\"\n for i in range(1, n_top + 1):\n candidates = np.flatnonzero(results['rank_test_score'] == i)\n for candidate in candidates:\n print(\"Model with rank: {0}\".format(i))\n print(\"Mean validation score: {0:.4f} (std: {1:.3f})\".format(\n results['mean_test_score'][candidate],\n results['std_test_score'][candidate]))\n print(\"Parameters: {0}\".format(results['params'][candidate]))\n print(\"\")\n\n##------------------------------------------\n# Class 1: Nu SVM\n# Similar to SVM but uses a parameter to control the number of support vectors\nclass SVM(Classifier):\n \n def __init__(self, X, y):\n Classifier.__init__(self, X, y)\n \n # All hyperparameters were fine-tuned from random search\n self.model = NuSVC(nu=0.4,\n kernel='rbf',\n degree=2,\n verbose=True)\n \n # For Nu SVM, we focus on tuning following 3 hyperparameters:\n # 1. nu: an upper bound on the fraction of training errors and\n # a lower bound of the fraction of support vectors.\n # 2. kernel: specifies the kernel type to be used in the algorithm\n # 3. degree: degree of the polynomial kernel function ('poly')\n self.param_rand = {\n \"nu\": [0.05, 0.2, 0.4, 0.5, 0.6, 0.8, 0.95],\n \"kernel\": ['poly', 'rbf', 'sigmoid'],\n \"degree\": sp_randint(2, 10)\n }\n\n##------------------------------------------\n# Class 2: Multi-layer Perceptron classifier\n# This model optimizes the log-loss function using LBFGS or stochastic \n# gradient descent.\nclass NeuralNetwork(Classifier):\n \n def __init__(self, X, y):\n Classifier.__init__(self, X, y)\n \n # All hyperparameters were fine-tuned from random search\n self.model = MLPClassifier(solver='adam',\n learning_rate='adaptive',\n alpha=0.005,\n hidden_layer_sizes=(116),\n random_state=1,\n learning_rate_init=1e-4,\n verbose=True)\n \n # For Neural Network, we focus on tuning following 3 hyperparameters:\n # 1. alpha: L2 penalty (regularization term)\n # 2. learning_rate_init: initial learning rate used\n # 3. hidden_layer_sizes: size of hidden layer\n self.param_rand = {\n \"alpha\": [1e-5, 5e-5, 1e-4, 5e-4, 1e-3, 5e-3, 1e-2, 1e-2, 1e-1],\n \"learning_rate_init\": [1e-5, 5e-5, 1e-4, 5e-4, 1e-3, 5e-3, 1e-2, \\\n 1e-1, 1, 10],\n \"hidden_layer_sizes\": sp_randint(4, 200)\n }\n \n##------------------------------------------\n# Class 3: Extremely Randomized Trees\n# This class implements a meta estimator that fits a number of randomized \n# decision trees (a.k.a. extra-trees) on various sub-samples of the dataset \n# and use averaging to improve the predictive accuracy and control over-fitting.\nclass ExtraTrees(Classifier):\n \n def __init__(self, X, y):\n Classifier.__init__(self, X, y)\n \n # All hyperparameters were fine-tuned from random search\n self.model = ExtraTreesClassifier(n_jobs=-1,\n max_features=18,\n min_samples_split=3,\n min_samples_leaf=1,\n n_estimators=127,\n verbose=True)\n \n # For Extra Trees, we focus on tuning following 4\n # hyperparameters:\n # 1. max_features: the number of features to consider when looking\n # for the best split.\n # 2. min_samples_split: the minimum number of samples required to \n # split an internal node.\n # 3. min_samples_leaf: the minimum number of samples required to be\n # at a leaf node.\n # 4. n_estimators: the number of trees in the forest.\n self.param_rand = {\n \"max_features\": sp_randint(3, 40),\n \"min_samples_split\": sp_randint(2, 20),\n \"min_samples_leaf\": sp_randint(1, 20),\n \"n_estimators\": sp_randint(50, 150)\n } \n\n##------------------------------------------\n# Class 4: Gaussian Naive Bayes (GaussianNB)\n# GaussianNB implements the Gaussian Naive Bayes algorithm for classification\nclass GaussianNaiveBayes(Classifier):\n \n def __init__(self, X, y):\n Classifier.__init__(self, X, y)\n \n self.model = GaussianNB()\n\n#------------------------------------------------------------\n#---------------------- Main function -----------------------\n#------------------------------------------------------------\ndef generate_features(instances):\n \"\"\" generate features\n param instances: a list of Instance class objects\n return: a feature matrix\n \"\"\"\n # feature set: [wave_data x y major minor pressure orientation]\n X = np.array([np.append(instance.audio.astype(float), \\\n [instance.touch['x'], \\\n instance.touch['y'], \\\n instance.touch['major'], \\\n instance.touch['minor'], \\\n instance.touch['pressure'], \\\n instance.touch['orientation']]) \\\n for instance in instances])\n return X\n\ndef calcul_precision(y_predicted, y_label):\n \"\"\" compare predicted label with ground_truth\n return: precision from 0->1\n \"\"\"\n return np.average(y_predicted==y_label)\n\ndef main(argv):\n \n # preprocessing: perform normalization and centralization on input data \n max_abs_scaler = StandardScaler()\n\n print('======= Preparing training dataset ========')\n train_instances = load_instances(\"data/train\")\n X_data = max_abs_scaler.fit_transform(generate_features(train_instances))\n y_data = load_labels(train_instances)\n \n # training & hyperparameter tuning will take 80% data, testing takes 20%\n X_train, X_test, y_train, y_test = train_test_split(X_data,\n y_data,\n test_size=0.2,\n random_state=0)\n \n print('Training samples : %.d' % X_train.shape[0])\n print('Feature size : %.d' % X_train.shape[1])\n print('Testing samples : %.d' % X_test.shape[0])\n \n # Pick one of the 4 following classifiers:\n# classifier = GaussianNaiveBayes(X_data, y_data)\n# classifier = SVM(X_train, y_train)\n# classifier = NeuralNetwork(X_train, y_train)\n classifier = ExtraTrees(X_train, y_train)\n\n # train with fine-tuned hyperparameters with/without\n # performing hyperparameter tuning (much longer to finish).\n classifier.train(performTuning=False,\n showLearningCurve=False)\n \n print('======= Validation on 20% training dataset ========')\n print('Testing score: %.4f' % \\\n classifier.model.score(classifier.features.transform(X_test),\n y_test))\n\n print('======= Classifying real test dataset ========')\n # Now prepare to run on real test dataset\n test_instances = load_instances(\"data/test\")\n X_real = max_abs_scaler.transform(generate_features(test_instances))\n timestamps = load_timestamps(test_instances)\n \n # predict\n y_pred = np.asarray(classifier.predict(classifier.features.transform(X_real)))\n classlabels = np.asarray(convert_to_classlabels(y_pred))\n \n # save results\n write_results(timestamps, classlabels, \"./fingersense-test-labels.csv\")\n print('Result saved to file fingersense-test-labels.csv')\n\nif __name__ == '__main__':\n exit(main(sys.argv[1:]))\n","sub_path":"src/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":12467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"314047373","text":"import logging\n\nlogging.basicConfig(level=logging.DEBUG,\n filename=\"app.log\",\n filemode=\"a\",\n format='%(asctime)s - %(levelname)s - %(message)s')\n\nlogging.debug('debug message')\nlogging.info('info message')\nlogging.warning('warn message')\nlogging.error('error message')\nlogging.critical('critical message')\nwhile True:\n file = input(\"Enter to open your file: \")\n if file == \"q\" or file == \"Q\":\n exit(0)\n try:\n with open(file, \"r\") as f:\n print(f\"{file} selected.\")\n print(f.read())\n break\n except FileNotFoundError:\n print(\"Wrong file or file path\")\n except UnicodeDecodeError:\n print(f\"Impossible open to file {file}\")\n\n\n","sub_path":"Python/Udemy/Log/Try_if_error.py","file_name":"Try_if_error.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"386674427","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nFile: stack.py\nAuthor: Hong-Wei Ng\nEmail: lightalchemist@gmail.com\nGithub: https://github.com/lightalchemist\nDescription: Implementation of standard stack using a linked list.\nIn addition, supports finding max element in O(1) time.\n\nThis implementation is merely for self-study and is\nnot necessarily a practical one.\nIn particular, this implementation is not thread-safe.\n\"\"\"\n\n\nfrom linked_list import LinkedList\n\n\nclass Stack(LinkedList):\n\n def __init__(self, items=None):\n super(Stack, self).__init__()\n if items is not None:\n self._insert_bulk(items)\n\n\n def _insert_bulk(self, items):\n current_max = -float(\"inf\") # Negative infinity\n for i in items:\n current_max = max(current_max, i)\n self.insert((i, current_max), 0)\n\n\n def top(self):\n if self.empty():\n raise IndexError(\"Cannot look at top of empty stack.\")\n\n return self._head.value[0]\n\n\n def pop(self):\n item, max_val = self[0].value\n del self[0]\n return item\n\n\n def push(self, item):\n if self.empty():\n self.insert((item, item), 0)\n else:\n max_val = max(item, self.head.value[1])\n self.insert((item, max_val), 0)\n\n\n def max(self):\n return self._head.value[1]\n\n\n def empty(self):\n return self._head is None\n\n\n def __str__(self):\n items = [node.value[0] for node in self]\n return str(list(items))\n\n\ndef test():\n s = Stack()\n assert s.empty()\n assert len(s) == 0\n\n\n s = Stack([1, 2, 3, 4])\n assert s.top() == 4\n assert s.max() == 4\n\n assert s.pop() == 4\n assert s.max() == 3\n s.push(1)\n assert s.max() == 3\n assert len(s) == 4\n assert s.pop() == 1\n assert not s.empty()\n\n s = Stack([1])\n assert not s.empty()\n assert s.top() == 1\n assert s.pop() == 1\n assert len(s) == 0\n assert s.empty()\n\n print(\"All tests pass.\")\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"algorithms/data_structures/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"480608168","text":"import cocos\nfrom cocos.director import director\nfrom cocos.menu import *\nfrom cocos.layer import *\nfrom cocos.scene import *\nfrom cocos.scenes.transitions import *\n\n\n\n\nclass MainMenuLayer(Layer):\n def __init__(self):\n super(MainMenuLayer, self).__init__()\n #self.add(MultiplexLayer(MainMenu()),z=1)\nclass MainMenu(Menu):\n def __init__(self):\n super(MainMenu, self).__init__(\"HearthStone\")\n self.font_title['font_size'] = 72\n self.font_title['color'] = (204,164,164,255)\n self.font_item['color'] = (255,255,255,255)\n self.font_item['font_size'] = 32\n self.font_item_selected['color'] = (255,255,255,255)\n self.font_item_selected['font_size'] = 46\n\n self.menu_anchor_y = CENTER\n self.menu_anchor_x = CENTER\n items = []\n items.append(MenuItem('StartGame',self.newGame))\n items.append(MenuItem('Quit',self.on_quit))\n self.create_menu( items, shake(), shake_back())\n def newGame(self):\n import gameview\n director.push(FlipAngular3DTransition(\n gameview.get_newgame(), 1.5))\n def on_quit(self):\n pyglet.app.exit()\n\n\n\nif __name__ == \"__main__\":\n pyglet.resource.path.append('data')\n pyglet.resource.reindex()\n\n director.init(width = 800, height=600)\n #scene\n scene = Scene()\n scene.add(MultiplexLayer(MainMenu(),),z=1)\n\n director.run(scene)\n","sub_path":"testcocos.py","file_name":"testcocos.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"264316826","text":"'''Print the First 3 multiples of the given number \"N\". \n(N is a positive integer)\nSample Input :\n2\nSample Output :\n2 4 6'''\nN = int(input())\nif N>0:\n for i in range(1,4):\n if i!=3:\n \tprint(i*N, end = \" \")\n else:\n print(i*N)\n","sub_path":"Python/Absolute Beginner/774.py","file_name":"774.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"96935597","text":"from django.urls import path,include\nfrom app.views import *\nurlpatterns = [\n\npath('',get,name=\"get\"),\npath('lead/',lead_mixins_detail.as_view(),name='lead'),\npath('lead//',lead_mixins_detail.as_view(),name='lead'),\npath('tr/',tr.as_view()),\npath('',Demo.as_view(),name='demo'),\npath('get/',get,name='get'),\npath('api-auth/', include('rest_framework.urls')),\n\n]\n\n ","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"158701259","text":"import pytest\n\n\ninvalid_users = [['root', '123'], ['test', 'test']]\n\n\ndef test_auth_check_valid_user(auth_prepare):\n valid_user = auth_prepare.connect.post('auth/check_user', data=['root', 'freenas'])\n\n assert valid_user.status_code == 200\n assert valid_user.json() is True\n\n\n@pytest.mark.parametrize('data_user', invalid_users)\ndef test_auth_check_invalid_user(auth_prepare, data_user):\n invalid_user = auth_prepare.connect.post('auth/check_user', data=data_user)\n\n assert invalid_user.status_code == 200\n assert invalid_user.json() is False\n\n\n@pytest.mark.parametrize('data_random', [[1000], [2000], [3000], [4000], [5000]])\ndef test_generate_token(auth_prepare, data_random):\n generate_token = auth_prepare.connect.post('auth/generate_token', data=data_random)\n\n assert generate_token.status_code == 200\n assert isinstance(generate_token.json(), str) is True\n","sub_path":"src/middlewared/middlewared/pytest/functional/test_0001_authentication.py","file_name":"test_0001_authentication.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"410408658","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport requests\nfrom data_response import DataResponse\n\n# --------------------------------\n# Connection\n# --------------------------------\n'''\nA classe Connection realiza conexão com servidor de serviço API\n'''\n\nclass Connection:\n\n # --------------------------------\n # __init__\n # --------------------------------\n def __init__(self, status):\n self.status = status\n\n # --------------------------------\n # load_config\n # --------------------------------\n '''\n Conecta o servidor de serviços API e recupera documentos\n '''\n def load_config(self, service_id):\n print ('SERVICE_ID =======>', service_id)\n url = 'http://localhost:9500/console/config'\n # url = 'http://10.1.0.90:9500/console/config'\n # url = 'http://console.unicoode.com:9500/console/config'\n params = dict(service=service_id)\n headers = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Accept': 'application/json',\n 'devdoo-api-key': '286c42a2b9dabb536c87b1a88a6842117bfb37ab',\n 'devdoo-app-id': '507f191e810c19729de860ea',\n 'devdoo-credentials': 'NTA3ZjE5MWU4MTBjMTk3MjlkZTg2MGVhOjhmNGY5ZjJkY2JhZjliZDhlZTllNGQxYTJjYjk3MWEwNDA4NDE1N2I='\n }\n data_response = requests.get(url, params=params, headers=headers, timeout=60)\n\n if type(data_response) == requests.models.Response:\n return DataResponse(data_response.json(), self.status)\n else:\n self.status.error(\"ERROR_CONNECTION\", None, [\"Falha na conexao com servidor de servicos API\", service_id])\n","sub_path":"devdoo/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"333046335","text":"\n\n\n\nimport pandas as pd\nimport io\nimport os\n\n\nVEP = 'pasan.vep'\n\n\n\nwith open(VEP, 'r') as f:\n lines = [l for l in f if not l.startswith('##')]\n vep = pd.read_table(io.StringIO(str.join(os.linesep, lines)), dtype={'#CHROM':str, 'POS':str}, low_memory=False)\n vep = vep.rename(columns={'#CHROM': 'CHROM'})\n vep = vep.set_index(['CHROM', 'POS'])\n\n\n\n\nvep = vep.reset_index()\nvep['ID_x'] = vep.CHROM + ':' + vep.POS +':'+vep.REF+':'+vep.ALT\nvep = vep.set_index(['CHROM', 'POS'])\nIDx = vep.ID_x.to_frame()\nvariant_info = vep.iloc[:,:6]\nvariant_info = variant_info.drop(axis = 1, labels = ['ID', 'QUAL', 'FILTER'])\nvariant_info['samtools'] = variant_info.INFO.str.split('|').str.get(0)\nvariant_info['VEP'] = variant_info.INFO.str.split(';').str.get(-1)\nvariant_info = variant_info.reset_index().set_index(['CHROM', 'POS'])\nVEP = variant_info.VEP.str.split(',', expand = True)\nVEP = VEP.dropna(axis = 1, how = 'all')\n\nstack = VEP.stack()\n\n\nstack = stack.to_frame()\n\n\nstack['Allele']= stack[0].str.split('|').str.get(0)\nstack['Consequence']= stack[0].str.split('|').str.get(1)\nstack['IMPACT']= stack[0].str.split('|').str.get(2)\nstack['SYMBOL']= stack[0].str.split('|').str.get(3)\nstack['Gene']= stack[0].str.split('|').str.get(4)\nstack['Feature_type']= stack[0].str.split('|').str.get(5)\nstack['Feature']= stack[0].str.split('|').str.get(6)\nstack['BIOTYPE']= stack[0].str.split('|').str.get(7)\nstack['EXON']= stack[0].str.split('|').str.get(8)\nstack['INTRON']= stack[0].str.split('|').str.get(9)\nstack['HGVSc']= stack[0].str.split('|').str.get(10)\nstack['HGVSp']= stack[0].str.split('|').str.get(11)\nstack['cDNA_position']= stack[0].str.split('|').str.get(12)\nstack['CDS_position']= stack[0].str.split('|').str.get(13)\nstack['Protein_position']= stack[0].str.split('|').str.get(14)\nstack['Amino_acids']= stack[0].str.split('|').str.get(15)\nstack['Codons']= stack[0].str.split('|').str.get(16)\nstack['Existing_variation']= stack[0].str.split('|').str.get(17)\nstack['DISTANCE']= stack[0].str.split('|').str.get(18)\nstack['STRAND']= stack[0].str.split('|').str.get(19)\nstack['FLAGS']= stack[0].str.split('|').str.get(20)\nstack['VARIANT_CLASS']= stack[0].str.split('|').str.get(21)\nstack['SYMBOL_SOURCE']= stack[0].str.split('|').str.get(22)\nstack['HGNC_ID']= stack[0].str.split('|').str.get(23)\nstack['CANONICAL']= stack[0].str.split('|').str.get(24)\nstack['MANE']= stack[0].str.split('|').str.get(25)\nstack['TSL']= stack[0].str.split('|').str.get(26)\nstack['APPRIS']= stack[0].str.split('|').str.get(27)\nstack['CCDS']= stack[0].str.split('|').str.get(28)\nstack['ENSP']= stack[0].str.split('|').str.get(29)\nstack['SWISSPROT']= stack[0].str.split('|').str.get(30)\nstack['TREMBL']= stack[0].str.split('|').str.get(31)\nstack['UNIPARC']= stack[0].str.split('|').str.get(32)\nstack['GENE_PHENO']= stack[0].str.split('|').str.get(33)\nstack['SIFT']= stack[0].str.split('|').str.get(34)\nstack['PolyPhen']= stack[0].str.split('|').str.get(35)\nstack['DOMAINS']= stack[0].str.split('|').str.get(36)\nstack['miRNA']= stack[0].str.split('|').str.get(37)\nstack['HGVS_OFFSET']= stack[0].str.split('|').str.get(38)\nstack['AF']= stack[0].str.split('|').str.get(39)\nstack['AFR_AF']= stack[0].str.split('|').str.get(40)\nstack['AMR_AF']= stack[0].str.split('|').str.get(41)\nstack['EAS_AF']= stack[0].str.split('|').str.get(42)\nstack['EUR_AF']= stack[0].str.split('|').str.get(43)\nstack['SAS_AF']= stack[0].str.split('|').str.get(44)\nstack['AA_AF']= stack[0].str.split('|').str.get(45)\nstack['EA_AF']= stack[0].str.split('|').str.get(46)\nstack['gnomAD_AF']= stack[0].str.split('|').str.get(47)\nstack['gnomAD_AFR_AF']= stack[0].str.split('|').str.get(48)\nstack['gnomAD_AMR_AF']= stack[0].str.split('|').str.get(49)\nstack['gnomAD_ASJ_AF']= stack[0].str.split('|').str.get(50)\nstack['gnomAD_EAS_AF']= stack[0].str.split('|').str.get(51)\nstack['gnomAD_FIN_AF']= stack[0].str.split('|').str.get(52)\nstack['gnomAD_NFE_AF']= stack[0].str.split('|').str.get(53)\nstack['gnomAD_OTH_AF']= stack[0].str.split('|').str.get(54)\nstack['gnomAD_SAS_AF']= stack[0].str.split('|').str.get(55)\nstack['MAX_AF']= stack[0].str.split('|').str.get(56)\nstack['MAX_AF_POPS']= stack[0].str.split('|').str.get(57)\nstack['CLIN_SIG']= stack[0].str.split('|').str.get(58)\nstack['SOMATIC']= stack[0].str.split('|').str.get(59)\nstack['PHENO']= stack[0].str.split('|').str.get(60)\nstack['PUBMED']= stack[0].str.split('|').str.get(61)\nstack['MOTIF_NAME']= stack[0].str.split('|').str.get(62)\nstack['MOTIF_POS']= stack[0].str.split('|').str.get(63)\nstack['HIGH_INF_POS']= stack[0].str.split('|').str.get(64)\nstack['MOTIF_SCORE_CHANGE']= stack[0].str.split('|').str.get(65)\n\n\nstack = stack.drop(axis = 1, labels = 0)\n\nstack = stack.reset_index()\n\nstack['SNP'] = stack.CHROM + ':' +stack.POS.astype(str)\n\nstack = stack.set_index('CHROM', 'POS')\nstack.to_csv('passvep_stack_vep.csv')\n\nstack = stack.reset_index()\nstack['BP'] = stack['POS']\n\nchr1 = stack[(stack['CHROM'] == 'chr1')]\nchr2 = stack[(stack['CHROM'] == 'chr2')]\nchr3 = stack[(stack['CHROM'] == 'chr3')]\nchr4 = stack[(stack['CHROM'] == 'chr4')]\nchr5 = stack[(stack['CHROM'] == 'chr5')]\nchr6 = stack[(stack['CHROM'] == 'chr6')]\nchr7 = stack[(stack['CHROM'] == 'chr7')]\nchr9 = stack[(stack['CHROM'] == 'chr9')]\nchr10 = stack[(stack['CHROM'] == 'chr10')]\nchr11 = stack[(stack['CHROM'] == 'chr11')]\nchr12 = stack[(stack['CHROM'] == 'chr12')]\nchr14 = stack[(stack['CHROM'] == 'chr14')]\nchr15 = stack[(stack['CHROM'] == 'chr15')]\nchr16 = stack[(stack['CHROM'] == 'chr16')]\nchr17 = stack[(stack['CHROM'] == 'chr17')]\nchr18 = stack[(stack['CHROM'] == 'chr18')]\nchr20 = stack[(stack['CHROM'] == 'chr20')]\nchr21 = stack[(stack['CHROM'] == 'chr21')]\nchr22 = stack[(stack['CHROM'] == 'chr22')]\nARNT = chr1[(chr1['BP'].astype(int) > 150754900) & (chr1['BP'].astype(int) < 151073108)].rename(columns={'POS':'chr1'})\nPARP1 = chr1[(chr1['BP'].astype(int) > 226258651) & (chr1['BP'].astype(int) < 226499883)].rename(columns={'POS':'chr1'})\nCASP8 = chr2[(chr2['BP'].astype(int) > 201047085) & (chr2['BP'].astype(int) < 201724509)].rename(columns={'POS':'chr2'})\nPAX3 = chr2[(chr2['BP'].astype(int) > 222095089) & (chr2['BP'].astype(int) < 222374945)].rename(columns={'POS':'chr2'})\nBAP1 = chr3[(chr3['BP'].astype(int) > 52289996) & (chr3['BP'].astype(int) < 52520048)].rename(columns={'POS':'chr3'})\nMITF = chr3[(chr3['BP'].astype(int) > 69636417) & (chr3['BP'].astype(int) < 70078609)].rename(columns={'POS':'chr3'})\nSOD3 = chr4[(chr4['BP'].astype(int) > 24692289) & (chr4['BP'].astype(int) < 25055958)].rename(columns={'POS':'chr4'})\nKIT = chr4[(chr4['BP'].astype(int) > 54548829) & (chr4['BP'].astype(int) < 54848706)].rename(columns={'POS':'chr4'})\nGC = chr4[(chr4['BP'].astype(int) > 71703635) & (chr4['BP'].astype(int) < 71867003)].rename(columns={'POS':'chr4'})\nNFKB1 = chr4[(chr4['BP'].astype(int) > 102394419) & (chr4['BP'].astype(int) < 102697771)].rename(columns={'POS':'chr4'})\nTERT = chr5[(chr5['BP'].astype(int) > 1142197) & (chr5['BP'].astype(int) < 1447788)].rename(columns={'POS':'chr5'})\nSLC45A2 = chr5[(chr5['BP'].astype(int) > 33840139) & (chr5['BP'].astype(int) < 34064027)].rename(columns={'POS':'chr5'})\nIRF4 = chr6[(chr6['BP'].astype(int) > 281588) & (chr6['BP'].astype(int) < 512178)].rename(columns={'POS':'chr6'})\nCYB5R4 = chr6[(chr6['BP'].astype(int) > 3948233) & (chr6['BP'].astype(int) < 84292890)].rename(columns={'POS':'chr6'})\nIL6 = chr7[(chr7['BP'].astype(int) > 22617257) & (chr7['BP'].astype(int) < 22833613)].rename(columns={'POS':'chr7'})\nMTAP = chr9[(chr9['BP'].astype(int) > 21665209) & (chr9['BP'].astype(int) < 22151817)].rename(columns={'POS':'chr9'})\nNFKB2 = chr10[(chr10['BP'].astype(int) > 102289907) & (chr10['BP'].astype(int) < 102513171)].rename(columns={'POS':'chr10'})\nCCND1 = chr11[(chr11['BP'].astype(int) > 69210414) & (chr11['BP'].astype(int) < 69803433)].rename(columns={'POS':'chr11'})\nTYR = chr11[(chr11['BP'].astype(int) > 89097917) & (chr11['BP'].astype(int) < 89675699)].rename(columns={'POS':'chr11'})\nATM = chr11[(chr11['BP'].astype(int) > 108136364) & (chr11['BP'].astype(int) < 108468324)].rename(columns={'POS':'chr11'})\nCYP27B1 = chr12[(chr12['BP'].astype(int) > 57666465 ) & (chr12['BP'].astype(int) < 57875869)].rename(columns={'POS':'chr12'})\nTEP1 = chr14[(chr14['BP'].astype(int) > 20399357) & (chr14['BP'].astype(int) < 20550325)].rename(columns={'POS':'chr14'})\nOCA2 = chr15[(chr15['BP'].astype(int) > 27670078) & (chr15['BP'].astype(int) < 28337214)].rename(columns={'POS':'chr15'})\nGRIN2A = chr16[(chr16['BP'].astype(int) > 9696254) & (chr16['BP'].astype(int) < 10280553)].rename(columns={'POS':'chr16'})\nSMG1 = chr16[(chr16['BP'].astype(int) >18749854 ) & (chr16['BP'].astype(int) < 19024774)].rename(columns={'POS':'chr16'})\nFTO = chr16[(chr16['BP'].astype(int) > 53363904 ) & (chr16['BP'].astype(int) < 54384452)].rename(columns={'POS':'chr16'})\nCDH1 = chr16[(chr16['BP'].astype(int) > 68528729) & (chr16['BP'].astype(int) < 68923897)].rename(columns={'POS':'chr16'})\nMC1R = chr16[(chr16['BP'].astype(int) > 89806464) & (chr16['BP'].astype(int) < 90031424)].rename(columns={'POS':'chr16'})\nCARD14 = chr17[(chr17['BP'].astype(int) > 80154433) & (chr17['BP'].astype(int) < 80508392)].rename(columns={'POS':'chr17'})\nBCL2 = chr18[(chr18['BP'].astype(int) > 63015199) & (chr18['BP'].astype(int) < 63421327)].rename(columns={'POS':'chr18'})\nASIP = chr20[(chr20['BP'].astype(int) > 33709976) & (chr20['BP'].astype(int) < 34374270)].rename(columns={'POS':'chr20'})\nTP53INP2 = chr20[(chr20['BP'].astype(int) > 34619476) & (chr20['BP'].astype(int) < 34933005)].rename(columns={'POS':'chr20'})\nMX2 = chr21[(chr21['BP'].astype(int) > 41194545) & (chr21['BP'].astype(int) < 41512249)].rename(columns={'POS':'chr21'})\nPLA2G6 = chr22[(chr22['BP'].astype(int) > 37870877) & (chr22['BP'].astype(int) < 38328731)].rename(columns={'POS':'chr22'})\n\nARNT.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/ARNT/ARNT_vep.csv')\nPARP1.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/PARP1/PARP1_vep.csv') \nCASP8.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/CASP8/CASP8_vep.csv') \nPAX3.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/PAX3/PAX3_vep.csv') \nBAP1.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/BAP1/BAP1_vep.csv') \nMITF.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/MITF/MITF_vep.csv') \nSOD3.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/SOD3/SOD3_vep.csv') \nKIT.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/KIT/KIT_vep.csv') \nGC.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/GC/GC_vep.csv') \nNFKB1.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/NFKB1/NFKB1_vep.csv') \nTERT.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/TERT/TERT_vep.csv') \nSLC45A2.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/SLC45A2/SLC45A2_vep.csv') \nIRF4.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/IRF4/IRF4_vep.csv') \nCYB5R4.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/CYB5R4/CYB5R4_vep.csv') \nIL6.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/IL6/IL6_vep.csv') \nMTAP.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/MTAP/MTAP_vep.csv') \nNFKB2.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/NFKB2/NFKB2_vep.csv') \nCCND1.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/CCND1/CCND1_vep.csv') \nTYR.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/TYR/TYR_vep.csv') \nATM.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/ATM/ATM_vep.csv') \nCYP27B1.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/CYP27B1/CYP27B1_vep.csv')\nTEP1.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/TEP1/TEP1_vep.csv') \nOCA2.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/OCA2/OCA2_vep.csv') \nGRIN2A.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/GRIN2A/GRIN2A_vep.csv') \nSMG1.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/SMG1/SMG1_vep.csv') \nFTO.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/FTO/FTO_vep.csv') \nCDH1.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/CDH1/CDH1_vep.csv') \nMC1R.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/MC1R/MC1R_vep.csv') \nCARD14.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/CARD14/CARD14_vep.csv') \nBCL2.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/BCL2/BCL2_vep.csv') \nASIP.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/ASIP/ASIP_vep.csv') \nTP53INP2.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/TP53INP2/TP53INP2_vep.csv') \nMX2.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/MX2/MX2_vep.csv') \nPLA2G6.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/PLA2G6/PLA2G6_vep.csv') \nTERT.to_csv('/mnt/Genoma/drobles/ccastaneda/gwas-reseq/regions/TERT/TERT_vep.csv')\n\n\n","sub_path":"scripts/python_scripts/vep_to_csv.py","file_name":"vep_to_csv.py","file_ext":"py","file_size_in_byte":12788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"135034919","text":"\"\"\"\r\nFor a given document, resolve co-refernce.\r\nTake n sentences at a time, create a sentence-sentence coreference\r\n\"\"\"\r\nfrom pycorenlp import StanfordCoreNLP\r\nimport time\r\nimport copy\r\nimport json\r\nnlp = StanfordCoreNLP('http://localhost:9000')\r\n\r\ndef co_reference(num_sentence,document):\r\n\r\n co_references=[]\r\n for i in range(len(document)):\r\n k1=i\r\n k2=k1+num_sentence\r\n sentence=' '.join(document[k1:k2] )# take a slice of document (multiple sentence)\r\n output = nlp.annotate(sentence, properties={\r\n 'annotators': 'tokenize, pos, parse, openie, ner, dcoref',\r\n 'outputFormat': 'json'\r\n })\r\n corefs=output['corefs']\r\n for k in corefs.keys():\r\n coref=corefs[k]\r\n if len(coref)>1: # if there are co-references (at least two terms)\r\n coref_temp=[]\r\n for c in coref:\r\n temp={}\r\n temp['sentNum']=c['sentNum']\r\n temp['text']=c['text']\r\n temp['type']=c['type']\r\n\r\n co_references.append(temp)\r\n\r\n return co_references\r\n\r\n","sub_path":"co_reference.py","file_name":"co_reference.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"205968841","text":"import argparse\nimport asyncio\nimport datetime\nimport functools\nimport json\nimport logging\nimport random\nimport re\nimport shlex\nimport socket\nimport string\nimport urllib\nimport zlib\n\nimport aiofiles\nimport websockets\nfrom quart import Quart, abort, jsonify, request\n\nimport sys\nsys.path.insert(1, '../ALttPEntranceRandomizer')\nimport Items\nimport MultiClient\nimport MultiServer\n\nimport multiprocessing\nimport multiprocessing.connection\nimport queue\nimport traceback\nmp_queue = [] \nmp_conn = None\ndef send_to_bot(o):\n global mp_queue\n global mp_conn\n mp_queue.append(o)\n logging.error('send_to_bot')\n try:\n if not mp_conn:\n mp_conn = multiprocessing.connection.Client('/tmp/nachobot', 'AF_UNIX')\n logging.error('maybe send?')\n while mp_queue:\n mp_conn.send(mp_queue[0])\n mp_queue = mp_queue[1:]\n except: \n mp_conn = None # probably this is bad \n logging.error('no connection to bot yet')\n logging.error(sys.exc_info()[0])\n # logging.error(str(serr))\n \n traceback.print_exc()\n\n# from config import Config as c\n\nAPP = Quart(__name__)\n\nMULTIWORLDS = {}\n\n@APP.route('/game', methods=['POST'])\nasync def create_game():\n global MULTIWORLDS\n\n data = await request.get_json()\n \n if not 'multidata_url' in data and not 'token' in data:\n abort(400, description=f'Missing multidata_url or token in data')\n\n port = int(data.get('port', random.randint(30000, 35000)))\n\n if port < 30000 or port > 35000:\n abort(400, description=f'Port {port} is out of bounds.')\n if is_port_in_use(port):\n abort(400, description=f'Port {port} is in use!')\n\n if 'token' in data:\n token = data['token']\n if token in MULTIWORLDS:\n abort(400, description=f'Game with token {token} already exists.')\n\n async with aiofiles.open(f\"data/{token}_multidata\", \"rb\") as multidata_file:\n binary = await multidata_file.read()\n else:\n req = urllib.request.Request(\n url=data['multidata_url'],\n headers={'User-Agent': 'SahasrahBot Multiworld Service'}\n )\n token = random_string(6)\n binary = urllib.request.urlopen(req).read()\n\n async with aiofiles.open(f\"data/{token}_multidata\", \"wb\") as multidata_file:\n await multidata_file.write(binary)\n\n multidata = json.loads(zlib.decompress(binary).decode(\"utf-8\"))\n\n ctx = await create_multiserver(port, f\"data/{token}_multidata\")\n\n MULTIWORLDS[token] = {\n 'token': token,\n 'server': ctx,\n 'port': port,\n 'admin': data.get('admin', None),\n 'date': datetime.datetime.now(),\n 'meta': data.get('meta', None),\n 'players': multidata['names'],\n }\n response = APP.response_class(\n response=json.dumps(MULTIWORLDS[token], default=multiworld_converter),\n status=200,\n mimetype='application/json'\n )\n return response\n\n@APP.route('/game', methods=['GET'])\nasync def get_all_games():\n global MULTIWORLDS\n response = APP.response_class(\n response=json.dumps(MULTIWORLDS, default=multiworld_converter),\n status=200,\n mimetype='application/json'\n )\n return response\n\n@APP.route('/game/', methods=['GET'])\nasync def get_game(token):\n global MULTIWORLDS\n\n if not token in MULTIWORLDS:\n abort(404, description=f'Game with token {token} was not found.')\n\n response = APP.response_class(\n response=json.dumps(MULTIWORLDS[token], default=multiworld_converter),\n status=200,\n mimetype='application/json'\n )\n return response\n\n@APP.route('/game//msg', methods=['PUT'])\nasync def update_game(token):\n data = await request.get_json()\n\n global MULTIWORLDS\n\n if not token in MULTIWORLDS:\n abort(404, description=f'Game with token {token} was not found.')\n\n if not 'msg' in data:\n abort(400)\n\n resp = await console_message(MULTIWORLDS[token]['server'], data['msg'])\n return jsonify(resp=resp, success=True)\n\n@APP.route('/game/', methods=['DELETE'])\nasync def delete_game(token):\n global MULTIWORLDS\n\n if not token in MULTIWORLDS:\n abort(404, description=f'Game with token {token} was not found.')\n\n close_game(token)\n return jsonify(success=True)\n\n@APP.route('/jobs/cleanup/', methods=['POST'])\nasync def cleanup(minutes):\n global MULTIWORLDS\n tokens_to_clean = []\n for token in MULTIWORLDS:\n if MULTIWORLDS[token]['date'] < datetime.datetime.now()-datetime.timedelta(minutes=minutes):\n tokens_to_clean.append(token)\n for token in tokens_to_clean:\n close_game(token)\n return jsonify(success=True, count=len(tokens_to_clean), cleaned_tokens=tokens_to_clean)\n\n@APP.errorhandler(400)\ndef bad_request(e):\n return jsonify(success=False, name=e.name, description=e.description, status_code=e.status_code)\n\n@APP.errorhandler(404)\ndef game_not_found(e):\n return jsonify(success=False, name=e.name, description=e.description, status_code=e.status_code)\n\n@APP.errorhandler(500)\ndef something_bad_happened(e):\n return jsonify(success=False, name=e.name, description=e.description, status_code=e.status_code)\n\ndef close_game(token):\n server = MULTIWORLDS[token]['server']\n server.server.ws_server.close()\n del MULTIWORLDS[token]\n\ndef is_port_in_use(port):\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n return s.connect_ex(('0.0.0.0', port)) == 0\n\ndef random_string(length=6):\n chars = string.ascii_lowercase + string.digits\n return ''.join(random.choice(chars) for i in range(length))\n\ndef multiworld_converter(o):\n if isinstance(o, MultiServer.Client):\n return {\n 'auth': o.auth,\n 'name': o.name,\n 'team': o.team,\n 'slot': o.slot,\n 'send_index': o.send_index\n }\n if isinstance(o, MultiServer.Context):\n return {\n 'data_filename': o.data_filename,\n 'save_filename': o.save_filename,\n 'clients': {\n 'count': len(o.clients),\n 'connected': o.clients\n }\n }\n if isinstance(o, tuple):\n return list([list(row) for row in o])\n if isinstance(o, datetime.datetime):\n return o.__str__()\n if isinstance(o, asyncio.subprocess.Process):\n return o.pid\n\n\ndef on_item_found(ctx, player_found, player_found_id, player_owned, player_owned_id, item, location_id, location):\n for mw in MULTIWORLDS.values():\n if mw['server'] == ctx:\n token = mw['token']\n break\n \n if token:\n send_to_bot({\"cmd\": \"found_item\", \"data\":{\"player_found\": player_found, \"player_found_id\": player_found_id, \"player_owned\": player_owned, \"player_owned_id\": player_owned_id, \"item\": item, \"location\": location, \"location_id\": location, \"token\": token}})\n else:\n logging.error(\"Couldn't find game\")\n\nasync def create_multiserver(port, multidatafile):\n args = argparse.Namespace(\n host='0.0.0.0',\n port=port,\n password=None,\n multidata=multidatafile,\n disable_save=False,\n loglevel=\"info\"\n )\n\n logging.basicConfig(format='[%(asctime)s] %(message)s', level=getattr(logging, args.loglevel.upper(), logging.INFO))\n\n ctx = MultiServer.Context(args.host, args.port, args.password, 1, 1000, False)\n\n ctx.data_filename = args.multidata\n ctx.item_found_cb = on_item_found\n\n try:\n with open(ctx.data_filename, 'rb') as f:\n jsonobj = json.loads(zlib.decompress(f.read()).decode(\"utf-8\"))\n for team, names in enumerate(jsonobj['names']):\n for player, name in enumerate(names, 1):\n ctx.player_names[(team, player)] = name\n ctx.rom_names = {tuple(rom): (team, slot) for slot, team, rom in jsonobj['roms']}\n ctx.remote_items = set(jsonobj['remote_items'])\n ctx.locations = {tuple(k): tuple(v) for k, v in jsonobj['locations']}\n except Exception as e:\n logging.error('Failed to read multiworld data (%s)' % e)\n return\n\n logging.info('Hosting game at %s:%d (%s)' % (ctx.host, ctx.port, 'No password' if not ctx.password else 'Password: %s' % ctx.password))\n\n ctx.disable_save = args.disable_save\n if not ctx.disable_save:\n if not ctx.save_filename:\n ctx.save_filename = (ctx.data_filename[:-9] if ctx.data_filename[-9:] == 'multidata' else (ctx.data_filename + '_')) + 'multisave'\n try:\n with open(ctx.save_filename, 'rb') as f:\n jsonobj = json.loads(zlib.decompress(f.read()).decode(\"utf-8\"))\n rom_names = jsonobj[0]\n received_items = {tuple(k): [MultiClient.ReceivedItem(**i) for i in v] for k, v in jsonobj[1]}\n if not all([ctx.rom_names[tuple(rom)] == (team, slot) for rom, (team, slot) in rom_names]):\n raise Exception('Save file mismatch, will start a new game')\n ctx.received_items = received_items\n logging.info('Loaded save file with %d received items for %d players' % (sum([len(p) for p in received_items.values()]), len(received_items)))\n except FileNotFoundError:\n logging.error('No save data found, starting a new game')\n except Exception as e:\n logging.info(e)\n\n ctx.server = websockets.serve(functools.partial(MultiServer.server, ctx=ctx), ctx.host, ctx.port, ping_timeout=None, ping_interval=None)\n await ctx.server\n return ctx\n\n# this is a modified version of MultiServer.console that can accept commands\nasync def console_message(ctx: MultiServer.Context, message):\n command = shlex.split(message)\n\n if command[0] == '/exit':\n ctx.server.ws_server.close()\n return\n\n if command[0] == '/players':\n return MultiServer.get_connected_players_string(ctx)\n if command[0] == '/password':\n MultiServer.set_password(ctx, command[1] if len(command) > 1 else None)\n if command[0] == '/kick' and len(command) > 1:\n team = int(command[2]) - 1 if len(command) > 2 and command[2].isdigit() else None\n for client in ctx.clients:\n if client.auth and client.name.lower() == command[1].lower() and (team is None or team == client.team):\n if client.socket and not client.socket.closed:\n await client.socket.close()\n\n if command[0] == '/forfeitslot' and len(command) > 1 and command[1].isdigit():\n if len(command) > 2 and command[2].isdigit():\n team = int(command[1]) - 1\n slot = int(command[2])\n else:\n team = 0\n slot = int(command[1])\n MultiServer.forfeit_player(ctx, team, slot)\n if command[0] == '/forfeitplayer' and len(command) > 1:\n team = int(command[2]) - 1 if len(command) > 2 and command[2].isdigit() else None\n for client in ctx.clients:\n if client.auth and client.name.lower() == command[1].lower() and (team is None or team == client.team):\n if client.socket and not client.socket.closed:\n MultiServer.forfeit_player(ctx, client.team, client.slot)\n if command[0] == '/senditem' and len(command) > 2:\n [(player, item)] = re.findall(r'\\S* (\\S*) (.*)', message)\n if item in Items.item_table:\n for client in ctx.clients:\n if client.auth and client.name.lower() == player.lower():\n new_item = MultiClient.ReceivedItem(Items.item_table[item][3], \"cheat console\", client.slot)\n MultiServer.get_received_items(ctx, client.team, client.slot).append(new_item)\n MultiServer.notify_all(ctx, 'Cheat console: sending \"' + item + '\" to ' + client.name)\n MultiServer.send_new_items(ctx)\n return f\"Item sent: {item}\"\n else:\n return f\"Unknown item: {item}\"\n\n if command[0][0] != '/':\n MultiServer.notify_all(ctx, '[Server]: ' + message)\n\nif __name__ == '__main__':\n APP.run(host='127.0.0.1', port=5000, use_reloader=False)\n","sub_path":"MultiworldHostService.py","file_name":"MultiworldHostService.py","file_ext":"py","file_size_in_byte":12145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"142412153","text":"\"\"\"\nCréez un algorithme pour afficher un triangle à l'écran comme indiqué ci-dessous.\nLa hauteur du triangle est donnée par l'utilisateur.\n\n*\n**\n***\n****\n*****\n******\n*******\n********\n*********\n**********\n\"\"\"\n\n\"\"\" algo: triangle\ndonées: n: int -> hauteur du triangle\nrésultat: affiche un triangle de hauter n à l'écran\n\"\"\"\n\n### déclaration et initialisation des variables\nn: int = None\n\n### séquence d'opérations\n\n# saisir la hauter du triangle\n# while n is None or n <= 1:\nn = int(input(\"Hauter du triangle ? (>= 2) \"))\n\n# afficher le triangle\nfor i in range(1, n+1):\t\t\t# traite les lignes\n for j in range(i):\t\t # traite les colonnes\n print(\"*\", end=\"\")\n print()","sub_path":"PROG/Partie II - Les structures de contrôle/S5 - Les boucles imbriquées/semaine_5_cor/exercice_1_better.py","file_name":"exercice_1_better.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"228288022","text":"import os\r\nimport csv\r\nimport glob\r\nimport ntpath\r\nfrom datetime import date\r\n\r\nimport location\r\nVillage = location.village\r\nHome = location.home\r\nNodes = location.nodes\r\nFlow = location.flow\r\n\r\n\r\ndef print_line_flow(line):\r\n print_line = line\r\n print(print_line)\r\n file_name = '/home/pi/pyserial-3.4/Flow_Data_Files/Flow_Data_{}_{}_{}.csv'.format(Village, Home, date.today())\r\n with open(file_name, 'a') as data_file:\r\n data_writer = csv.writer(data_file, delimiter=\",\", quoting=csv.QUOTE_NONE, escapechar=' ')\r\n data_writer.writerow([print_line])\r\n\r\n\r\ndef print_line_node(line):\r\n print_line = line\r\n print(print_line)\r\n file_name = '/home/pi/pyserial-3.4/Node_Data_Files/Node_Data_{}_{}_{}.csv'.format(Village, Home, date.today())\r\n with open(file_name, 'a') as data_file:\r\n data_writer = csv.writer(data_file, delimiter=\",\", quoting=csv.QUOTE_NONE, escapechar=' ')\r\n data_writer.writerow([print_line])\r\n\r\n\r\ndt = date.today()\r\n\r\nif not os.listdir('/home/pi/pyserial-3.4/Flow_Data_Files'):\r\n print_line_flow(Flow)\r\nelse:\r\n flow_name = ntpath.basename(sorted(glob.iglob('/home/pi/pyserial-3.4/Flow_Data_Files/*.csv'), key=os.path.getmtime)[-1])\r\n flow_month = flow_name[-9:-7]\r\n flow_day = flow_name[-6:-4]\r\n\r\n if int(flow_month) != dt.month or int(flow_day) != dt.day:\r\n print_line_flow(Flow)\r\n else:\r\n print(\"Flow File Already Created\")\r\n\r\nif not os.listdir('/home/pi/pyserial-3.4/Node_Data_Files'):\r\n print_line_node(Nodes)\r\nelse:\r\n node_name = ntpath.basename(sorted(glob.iglob('/home/pi/pyserial-3.4/Node_Data_Files/*.csv'), key=os.path.getmtime)[-1])\r\n node_month = node_name[-9:-7]\r\n node_day = node_name[-6:-4]\r\n\r\n if int(node_month) != dt.month or int(node_day) != dt.day:\r\n print_line_node(Nodes)\r\n else:\r\n print(\"Node File Already Created\")\r\n","sub_path":"create_data_files.py","file_name":"create_data_files.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"360342918","text":"\"\"\"\nLab 4 implementation starter\n\"\"\"\n\nfrom lab_4.main import WordStorage, encode_text, LikelihoodBasedTextGenerator, decode_text\nfrom lab_4.ngrams.ngram_trie import NGramTrie\n\nif __name__ == '__main__':\n corpus = ('i', 'have', 'a', 'cat', '',\n 'his', 'name', 'is', 'bruno', '',\n 'i', 'have', 'a', 'dog', 'too', '',\n 'his', 'name', 'is', 'rex', '',\n 'her', 'name', 'is', 'rex', 'too', '')\n\n storage = WordStorage()\n storage.update(corpus)\n encoded_text = encode_text(storage, corpus)\n\n n_gram_trie = NGramTrie(3, encoded_text)\n context = (storage.get_id('i'),\n storage.get_id('have'),)\n generator = LikelihoodBasedTextGenerator(storage, n_gram_trie)\n generated_text = generator.generate_text(context, 3)\n\n RESULT = decode_text(storage, generated_text)\n print(RESULT)\n\n # DO NOT REMOVE NEXT LINE - KEEP IT INTENTIONALLY LAST\n assert RESULT == ('I have a cat', 'His name is rex', 'Her name is rex'), 'Encoding not working'\n","sub_path":"lab_4/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"78260476","text":"from setuptools import setup, find_packages\nimport os\n\ndef read(*rnames):\n return open(os.path.join(os.path.dirname(__file__), *rnames)).read()\n\nversion = '0.1a'\nlong_description = (\n read('README.txt')\n + '\\n' +\n 'Change history\\n'\n '==============\\n'\n + '\\n' +\n read('CHANGES.txt')\n + '\\n' +\n 'Contributors\\n'\n '============\\n'\n + '\\n' +\n read('CONTRIBUTORS.txt')\n + '\\n' +\n 'Known Issues\\n'\n '============\\n'\n + '\\n' +\n read('KNOWN_ISSUES.txt')\n)\n\nsetup(name='collective.facetsupport',\n version=version,\n description=\"Tools for generating facets for content in Plone\",\n long_description=long_description,\n # Get more strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Framework :: Plone\",\n \"Programming Language :: Python\",\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: GNU General Public License (GPL)\",\n ],\n keywords='plone',\n author='Robin Harms Oredsson',\n author_email='robin@betahaus.net',\n url='https://svn.plone.org/svn/collective/collective.facetsupport',\n license='GPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['collective'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n )\n","sub_path":"pypi_install_script/collective.facetsupport-0.1a.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"48941372","text":"\"\"\"\n\n\"\"\"\n\nfrom django.core.management.base import BaseCommand\nfrom django.apps import apps\nfrom django.db.models import F\nfrom django.db import transaction\n\nfrom catalogues.models import Collection, Catalogue, Lot, Category\n\n\ndef range_string_to_list(range_string):\n begin, end = range_string.split('-', 1)\n return list(range(int(begin), int(end) + 1))\n\n\ndef ranges_string_to_list(ranges_string):\n parts = ranges_string.split(',')\n numbers = set()\n\n for part in parts:\n if '-' in part:\n numbers.update(range_string_to_list(part))\n elif part:\n numbers.update(int(part))\n return sorted(list(numbers))\n\n\nclass Command(BaseCommand):\n help = 'Split catalogue'\n\n def add_arguments(self, parser):\n # Optional\n parser.add_argument('-c', '--catalogue_id', type=str,\n help='UUID of catalogue to split')\n parser.add_argument('-n', '--new_catalogue_name', type=str,\n help='Name of the new catalogue')\n parser.add_argument('-i', '--index_in_catalogue', type=int,\n help='The index in the old catalogue of the first lot in the new catalogue')\n parser.add_argument('-e', '--exclude_index_in_catalogue', type=str,\n help='Lots with these indexes are not move to the new catalogue')\n\n def handle(self, *args, **kwargs):\n # Get the command line arguments\n catalogue = Catalogue.objects.get(uuid=kwargs.get('catalogue_id'))\n lot = Lot.objects.get(catalogue=catalogue, index_in_catalogue=kwargs.get('index_in_catalogue'))\n new_catalogue_name = kwargs.get('new_catalogue_name')\n exclude_indexes = ranges_string_to_list(kwargs.get('exclude_index_in_catalogue') or '')\n if not (catalogue and lot and new_catalogue_name):\n return\n\n with transaction.atomic():\n new_collection = Collection.objects.create(name=new_catalogue_name)\n new_catalogue = Catalogue.objects.create(short_title=new_catalogue_name, collection=new_collection)\n print(\"New catalogue URL:\", new_catalogue.get_absolute_url())\n lots_to_move = Lot.objects.filter(catalogue=catalogue, index_in_catalogue__gte=lot.index_in_catalogue)\\\n .exclude(index_in_catalogue__in=exclude_indexes)\n categories_to_move = Category.objects.filter(lot__in=lots_to_move).distinct()\n\n # Create new categories if necessary\n for category in categories_to_move.filter(lot__index_in_catalogue__lt=lot.index_in_catalogue):\n new_category = Category.objects.create(\n catalogue = category.catalogue,\n bookseller_category = category.bookseller_category,\n parisian_category = category.parisian_category\n )\n lots_to_move.filter(category=category).update(category=new_category)\n\n diff = lot.index_in_catalogue - 1\n lots_to_move.update(catalogue=new_catalogue, index_in_catalogue=F('index_in_catalogue') - diff)\n","sub_path":"catalogues/management/commands/splitcatalogue.py","file_name":"splitcatalogue.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"36590267","text":"__author__ = 'are'\n\nfrom ipywidgets import FloatProgress\nfrom IPython.display import display\n\nimport shapefile\n\ndef cont_to_shp(contour_set, levels, filename):\n\n # create shape instance and field\n w = shapefile.Writer()\n w.field(\"Head\", \"N\", decimal=2)\n\n # create shapes and records\n wdgt = FloatProgress(min=0, max=len(levels), description=\"collecting shapes ... \")\n display(wdgt)\n \n for collection, h in zip(contour_set.collections, levels):\n #sys.stdout.write(\" {:.1f}\".format(h))\n wdgt.value += 1\n for path in collection.get_paths():\n for polygon in path.to_polygons():\n #sys.stdout.write(\"|\")\n w.line(parts=[[list(p) for p in polygon ][:-1]])\n w.record(h)\n \n # save file\n print(\"\\nsaving \" + filename)\n w.save(filename)\n","sub_path":"gis/cont_to_shp.py","file_name":"cont_to_shp.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"200961619","text":"import itertools\nfrom typing import Generator\n\nfrom stemming.porter2 import stem\n\nfrom knock51 import extract_word\n\n\ndef word_stem(filename: str = './nlp.txt') -> Generator[str, None, None]:\n \"\"\"\n 単語と stem のペアを返す\n \"\"\"\n for word in extract_word(filename):\n s = stem(word)\n pair = f'{word}\\t{s}'\n yield pair\n\n\ndef main(stop):\n for pair in itertools.islice(word_stem(), stop):\n print(pair)\n\n\nif __name__ == '__main__':\n main(100)\n","sub_path":"hotate/chapter06/knock52.py","file_name":"knock52.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"1264748","text":"import sys\nfile_i = open('voorbeeld.invoer.txt')\nfile_o = open('mijn_uitvoer.txt', 'w')\nsys.stdin = file_i\nsys.stdout = file_o\n\ndef afstand(p, q):\n return abs(q[0] - p[0]) + abs(q[1] - p[1])\n\ndef verwerk_voetballer(aantal):\n d_tot = 0\n p = (0,0)\n for i in range(aantal):\n qx, qy = tuple(input().split())\n q = (int(qx), int(qy))\n d_tot += afstand(p, q)\n p = q\n return d_tot\n\naantal = int(input())\n\nfor i in range(1, aantal + 1):\n print(i, verwerk_voetballer(int(input())))\n","sub_path":"2018/Voetballer/Voetballer.py3","file_name":"Voetballer.py3","file_ext":"py3","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"358240997","text":"# encoding: utf-8\n\"\"\"\ntestSeralizationOfEval.py\n\nCreated by Chimezie Ogbuji on 2010-08-15.\nCopyright (c) 2010 __MyCompanyName__. All rights reserved.\n\"\"\"\n\nfrom rdflib import RDF, Literal, Variable\n\nfrom FuXi.Horn.HornRules import Clause, Rule\nfrom FuXi.Horn.PositiveConditions import Uniterm\nfrom FuXi.LP.BackwardFixpointProcedure import BFP_NS, BFP_RULE\n\n\ndef test_serialization_of_eval_pred():\n nsBindings = {\"bfp\": BFP_NS, \"rule\": BFP_RULE}\n evaluateTerm = Uniterm(\n BFP_NS.evaluate, [BFP_RULE[str(1)], Literal(1)], newNss=nsBindings\n )\n assert str(evaluateTerm) == \"bfp:evaluate(rule:1 1)\"\n xVar = Variable(\"X\")\n yVar = Variable(\"Y\")\n bodyTerm = Uniterm(RDF.rest, [xVar, yVar], newNss=nsBindings)\n rule = Rule(Clause(bodyTerm, evaluateTerm), declare=[xVar, yVar])\n assert str(rule) == \"Forall ?X ?Y ( bfp:evaluate(rule:1 1) :- rdf:rest(?X ?Y) )\"\n","sub_path":"test/test_horn/test_serialization_of_eval.py","file_name":"test_serialization_of_eval.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"223583355","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Import data\ndf = pd.read_csv('medical_examination.csv', index_col=0, sep=',')\n\n# Add 'overweight' column\ndf['overweight'] = df['weight'] / ((df['height'] / 100) ** 2)\ndf['overweight'] = np.where(df['overweight']>25, 1, 0) #if value over 25 return 1, else retun 0\n\n# Normalize data by making 0 always good and 1 always bad. If the value of 'cholestorol' or 'gluc' is 1, make the value 0. If the value is more than 1, make the value 1.\ndf['cholesterol'] = np.where(df['cholesterol']==1, 0, 1)\ndf['gluc'] = np.where(df['gluc']==1, 0, 1)\n\n# Draw Categorical Plot\ndef draw_cat_plot():\n # Create DataFrame for cat plot using `pd.melt` using just the values from 'cholesterol', 'gluc', 'smoke', 'alco', 'active', and 'overweight'.\n df_cat = pd.melt(df, id_vars=['cardio'], value_vars=['cholesterol','gluc','smoke','alco','active','overweight'])\n\n\n # Group and reformat the data to split it by 'cardio'. Show the counts of each feature. You will have to rename one of the collumns for the catplot to work correctly.\n df_cat['total'] = 0\n df_cat = df_cat.groupby(['cardio', 'variable', 'value'], as_index=False).count() #using groupby idea from: https://repl.it/@JooVictorVict33/fcc-medical-data-visualizer#medical_data_visualizer.py\n\n # Draw the catplot with 'sns.catplot()'\n g = sns.catplot(\n data=df_cat, \n x=\"variable\", \n y=\"total\", \n col=\"cardio\",\n hue=\"value\",\n kind=\"bar\",\n legend_out=True,\n )\n fig = g.fig #From https://forum.freecodecamp.org/t/fcc-medical-data-visualizer/408460/3\n\n # Do not modify the next two lines\n fig.savefig('catplot.png')\n return fig\n\n\n# Draw Heat Map\ndef draw_heat_map():\n # Clean the data\n heightCap = np.percentile(df['height'], 97.5)\n weightMin = np.percentile(df['weight'], 2.5)\n weightMax = np.percentile(df['weight'], 97.5)\n #print(heightCap, weightMin, weightMax)\n df_heat = df\n df_heat = df_heat[((df_heat['ap_lo'] <= df_heat['ap_hi']) & (df_heat['height'] >= df_heat['height'].quantile(0.025)))]\n df_heat = df_heat[(df_heat['height'] <= heightCap)]\n df_heat = df_heat[((df_heat['weight'] >= weightMin) & (df_heat['weight'] <= weightMax))]\n\n #no idea why, but fcc wants id to be included with heatmap, I can't make it work unless adding an id arr....\n df_heat['id'] = range(len(df_heat)) \n df_heat= df_heat[['id','age', 'gender', 'height', 'weight', 'ap_hi', 'ap_lo', 'cholesterol', 'gluc', 'smoke', 'alco', 'active', 'cardio', 'overweight']]\n df_heat = df_heat.astype('float')\n\n \n # Calculate the correlation matrix\n #corr = df_heat.corr(method=\"spearman\") -close but slightly wrong ansers, setting vmax and vmin fixed....instead of spearman method\n corr = df_heat.corr()\n # Generate a mask for the upper triangle\n #from documentation: https://seaborn.pydata.org/generated/seaborn.heatmap.html?highlight=heatmap#seaborn.heatmap\n mask = np.zeros_like(corr)\n mask[np.triu_indices_from(mask)] = True\n\n # Set up the matplotlib figure\n with sns.axes_style(\"white\"):\n fig, ax = plt.subplots(figsize=(12, 12))\n \n # Draw the heatmap with 'sns.heatmap()'\n ax = sns.heatmap(corr, square=True, \n mask=mask, annot=True, fmt='.1f', vmin='0.0', vmax='0.25')\n\n # Do not modify the next two lines\n fig.savefig('heatmap.png')\n return fig\n","sub_path":"fcc-medical-data-visualizer.py","file_name":"fcc-medical-data-visualizer.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"238895047","text":"\n# coding: utf-8\n\n# ## Importing required packages\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport random as rn\nimport warnings\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom bokeh.plotting import figure, show, output_file\nfrom bokeh.io import show, output_file\nfrom bokeh.models import ColumnDataSource\nfrom math import pi\nfrom bokeh.transform import cumsum\nfrom bokeh.palettes import Category20c\n\n\n# ## Setting the random seed so that the result for reproducibility\n\n# In[2]:\n\n\nnp.random.seed(42)\nrn.seed(42)\ntf.set_random_seed(42)\n\n\n# ## Initializing Variables\n\n# In[3]:\n\n\nle = preprocessing.LabelEncoder()\nenc = OneHotEncoder(handle_unknown='ignore')\n\n\n# ## Loading the Dataset\n\n# In[4]:\n\n\ndataset =pd.read_csv(\"Employee Attrition.csv\")\n\n\n# ## Encoding Categorical features\n\n# In[5]:\n\n\ndef transform(feature):\n dataset[feature]=le.fit_transform(dataset[feature])\n\n\n# ## Encoding all the columns\n\n# In[6]:\n\n\ncolumns =dataset.select_dtypes(include='object')\nfor col in columns.columns:\n transform(col)\n\n\n# ## Feature Scaling\n\n# In[7]:\n\n\nscaler=StandardScaler()\ndataset=dataset.astype(float)\nX=scaler.fit_transform(dataset.drop(['Attrition','EmployeeCount','EmployeeNumber','Over18','StandardHours'],axis=1))\nY=dataset['Attrition'].values\n\n\n# ## One Hot Encoding the target Variable\n\n# In[8]:\n\n\nY=to_categorical(Y)\n\n\n# ## Dividing it into train and test set\n\n# In[9]:\n\n\nx_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.25,random_state=42)\n\n\n# ## Building the Keras model\n\n# In[10]:\n\n\nmodel=Sequential()\nmodel.add(Dense(input_dim=30,units=8,activation='relu'))\nmodel.add(Dense(units=20,activation='relu'))\nmodel.add(Dense(units=2,activation='sigmoid'))\n\n\n# ## Defining loss and oprimizer \n\n# In[11]:\n\n\nmodel.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\n\n\n# ## Training the Model fit\n\n# In[12]:\n\n\nhistory= model.fit(x_train,y_train,validation_data=(x_test,y_test),epochs=50,verbose=1)\n\n\n# ## Evaluating the model\n\n# In[13]:\n\n\nmodel.evaluate(x_test,y_test)\n\n\n# ## Train Loss vs Test Loss\n\n# In[15]:\n\n\nimport matplotlib.pyplot as plt\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model Loss')\nplt.ylabel('Loss')\nplt.xlabel('Epochs')\nplt.legend(['train', 'test'])\nplt.show()\n\n\n# ## Train Accuracy vs Test Accuracy\n\n# In[16]:\n\n\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('Model Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epochs')\nplt.legend(['train', 'test'])\nplt.show()\n\n\n# ## Reading the dataset again for Plots\n\n# In[17]:\n\n\norignalDataset=pd.read_csv(\"Employee Attrition.csv\")\n\n\n# ## Defining colors for graphs\n\n# In[18]:\n\n\ndef getColors(number):\n colors = ['#5E759F','#C58A6A','#6D9C71','#AA6263','#837CA8','#8D7867']\n colors = colors[0:number]\n return colors\n\n\n# ## Function to plot Box Chart\n\n# In[19]:\n\n\ndef boxChart(group,xrange,yrange):\n cats = group\n yy = xrange\n g = yrange\n for i, l in enumerate(cats):\n yy[g == l] += i // 2\n df = pd.DataFrame(dict(score=yy, group=g))\n\n # find the quartiles and IQR for each category\n groups = df.groupby('group')\n q1 = groups.quantile(q=0.25)\n q2 = groups.quantile(q=0.5)\n q3 = groups.quantile(q=0.75)\n iqr = q3 - q1\n upper = q3 + 1.5*iqr\n lower = q1 - 1.5*iqr\n\n # find the outliers for each category\n def outliers(group):\n cat = group.name\n return group[(group.score > upper.loc[cat]['score']) | (group.score < lower.loc[cat]['score'])]['score']\n out = groups.apply(outliers).dropna()\n\n # prepare outlier data for plotting, we need coordinates for every outlier.\n if not out.empty:\n outx = []\n outy = []\n for keys in out.index:\n outx.append(keys[0])\n outy.append(out.loc[keys[0]].loc[keys[1]])\n\n p = figure(tools=\"\", background_fill_color=\"#efefef\", x_range=cats, toolbar_location=None)\n\n # if no outliers, shrink lengths of stems to be no longer than the minimums or maximums\n qmin = groups.quantile(q=0.00)\n qmax = groups.quantile(q=1.00)\n upper.score = [min([x,y]) for (x,y) in zip(list(qmax.loc[:,'score']),upper.score)]\n lower.score = [max([x,y]) for (x,y) in zip(list(qmin.loc[:,'score']),lower.score)]\n\n # stems\n p.segment(cats, upper.score, cats, q3.score, line_color=\"black\")\n p.segment(cats, lower.score, cats, q1.score, line_color=\"black\")\n\n # boxes\n p.vbar(cats, 0.3, q2.score, q3.score, fill_color=\"#E08E79\", line_color=\"black\")\n p.vbar(cats, 0.3, q1.score, q2.score, fill_color=\"#3B8686\", line_color=\"black\")\n\n # whiskers (almost-0 height rects simpler than segments)\n p.rect(cats, lower.score, 0.2, 0.01, line_color=\"black\")\n p.rect(cats, upper.score, 0.2, 0.01, line_color=\"black\")\n\n #outliers\n if not out.empty:\n p.circle(outx, outy, size=6, color=\"#F38630\", fill_alpha=0.6)\n\n p.xgrid.grid_line_color = None\n p.ygrid.grid_line_color = \"white\"\n p.grid.grid_line_width = 2\n p.xaxis.major_label_text_font_size=\"12pt\"\n output_file(\"age_attrition.html\", title=\"Attrition based on Age\")\n show(p)\n\n\n# ## Function to plot Bar Chart\n\n# In[20]:\n\n\ndef barChart(xrange,yrange,colors,title):\n output_file(\"total_attrition.html\")\n attrition = xrange\n counts = yrange\n source = ColumnDataSource(data=dict(attrition=attrition, counts=counts, color=colors))\n p = figure(x_range=attrition, y_range=(0,max(counts)+int(0.25*max(counts))), plot_height=350, title=title,\n toolbar_location=None, tools=\"\")\n p.vbar(x='attrition', top='counts', width=0.9, color='color', legend=\"attrition\", source=source)\n p.xgrid.grid_line_color = None\n p.legend.orientation = \"horizontal\"\n p.legend.location = \"top_left\"\n show(p)\n\n\n# ## Function to plot Line Chart\n\n# In[21]:\n\n\ndef lineChart(xrange,yrange):\n output_file(\"line.html\")\n p = figure(plot_width=400, plot_height=400)\n # add a line renderer\n p.line(xrange, yrange, line_width=2)\n show(p)\n\n\n# ## Function to plot Pie Chart¶\n\n# In[22]:\n\n\ndef pieChart(x,title):\n output_file(\"pie.html\")\n data = pd.Series(x).reset_index(name='value').rename(columns={'index':'item'})\n data['angle'] = data['value']/data['value'].sum() * 2*pi\n data['color'] = getColors(len(x))\n p = figure(plot_height=350, title=title, toolbar_location=None,\n tools=\"hover\", tooltips=\"@item: @value\", x_range=(-0.5, 1.0))\n p.wedge(x=0, y=1, radius=0.4,\n start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),\n line_color=\"white\", fill_color='color', legend='item', source=data)\n p.axis.axis_label=None\n p.axis.visible=False\n p.grid.grid_line_color = None\n show(p)\n\n\n# ## Calculating different metrics for Graph\n\n# In[23]:\n\n\nattritionGroup = orignalDataset['Attrition'].unique().tolist()\nattritionGroupReverse = attritionGroup[::-1]\nageList = orignalDataset['Age'].tolist()\nattritionList = orignalDataset['Attrition'].tolist()\n\nbusinessGroup = orignalDataset['BusinessTravel'].unique().tolist()\nbusinessList = orignalDataset['BusinessTravel'].tolist()\n\nattritionDeptList = orignalDataset[orignalDataset['Attrition'] == attritionGroup[0]]['Department'].tolist()\ndepartmentGroup = orignalDataset['Department'].unique().tolist()\n\nyesAttritionFrame = orignalDataset[orignalDataset['Attrition'] == attritionGroup[0]]\nwarnings.simplefilter(\"ignore\")\n\n\n# ## Charts analysed on entire organization\n\n# In[24]:\n\n\n#Bar Chart showing Total attrition\nbarChart(attritionGroup,[attritionList.count(attritionGroup[0]),attritionList.count(attritionGroup[1])],getColors(len(attritionGroup)),\"Total Attrition\")\n\n\n# In[25]:\n\n\n#Box Plot showing attrition based on Age\nboxChart(attritionGroupReverse,ageList,attritionList)\n\n\n# In[26]:\n\n\n#Creating Gender List and group\ngenderList= orignalDataset[orignalDataset['Attrition']==attritionGroup[0]]['Gender'].tolist()\ngenderGroup=list(set(genderList))\ngenderGroupCount = [genderList.count(genderGroup[0]),genderList.count(genderGroup[1])]\n#Bar Chart of Attrition based on Gender\nbarChart(genderGroup,genderGroupCount,getColors(len(genderGroup)),'Attrition based on Gender')\n\n\n# In[27]:\n\n\n#Pie Chart showing Attrition based on Department\nx = {}\nfor i in range(len(departmentGroup)):\n x[departmentGroup[i]] = attritionDeptList.count(departmentGroup[i])\npieChart(x,\"Attrition based on department\")\n\n\n# In[28]:\n\n\n#Creating marital Status List and group\nmaritalStatusList= orignalDataset[orignalDataset['Attrition']==attritionGroup[0]]['MaritalStatus'].tolist()\nmaritalStatusGroup=list(set(maritalStatusList))\nmaritalStatusGroupCount = [maritalStatusList.count(maritalStatusGroup[0]),maritalStatusList.count(maritalStatusGroup[1]),maritalStatusList.count(maritalStatusGroup[2])]\n#Bar Chart of Attrition based on Marital Status\nbarChart(maritalStatusGroup,maritalStatusGroupCount,getColors(len(maritalStatusGroup)),'Attrition based on Marital Status')\n\n\n# ## Charts analysed on Reserach and Development Department\n\n# In[29]:\n\n\n#Attrition in Reserach and development Department\nrdAttritionFrame = yesAttritionFrame[orignalDataset['Department'] == 'Research & Development']\n\n\n# In[30]:\n\n\n#Attrition in Research and Development based on amount of travel\ntravelList = rdAttritionFrame['BusinessTravel'].tolist()\ntravelGroup = orignalDataset['BusinessTravel'].unique().tolist()\nbarChart(travelGroup,[travelList.count(travelGroup[0]),travelList.count(travelGroup[1]),travelList.count(travelGroup[2])],getColors(len(travelGroup)),\"Attrition based on Business Travel\")\n\n\n# In[31]:\n\n\n#Creating OverTime List and group\noverTimeList= rdAttritionFrame['OverTime'].tolist()\noverTimeGroup=list(set(overTimeList))\noverTimeGroupCount = [overTimeList.count(overTimeGroup[0]),overTimeList.count(overTimeGroup[1])]\n#Bar Chart of Attrition based on Overtime\nbarChart(overTimeGroup,overTimeGroupCount,getColors(len(overTimeGroup)),\"Attrition based on overtime\")\n\n\n# In[32]:\n\n\n#Creating JobInvolvement List and Group\njobInvolvementList= rdAttritionFrame['JobInvolvement'].tolist()\njobInvolvementGroup=list(set(jobInvolvementList))\njobInvolvementGroupName = ['Low','Medium','High','Very High']\njobInvolvementGroupCount = [jobInvolvementList.count(jobInvolvementGroup[0]),jobInvolvementList.count(jobInvolvementGroup[1]),jobInvolvementList.count(jobInvolvementGroup[2]),jobInvolvementList.count(jobInvolvementGroup[3])]\n#Pie Chart of Attrition based on JobInvolvement\nx = {}\nfor i in range(len(jobInvolvementGroup)):\n x[jobInvolvementGroupName[i]] = jobInvolvementList.count(jobInvolvementGroup[i])\npieChart(x,\"Attrition based on Job Involvement\")\n\n\n# In[33]:\n\n\n#Grouping values based on PercentSalaryHike for Research and development\nbins = pd.cut(rdAttritionFrame['PercentSalaryHike'], [10, 15, 20, 25])\npercentHikeGroupList= rdAttritionFrame.groupby(bins)['PercentSalaryHike'].agg(['count'])['count'].tolist()\npercentageGroup = ['10-15%','15-20%','20-25%']\n#plotting pie chart based on PercentSalaryHike for Research and development\nx = {}\nfor i in range(len(percentageGroup)):\n x[percentageGroup[i]] = percentHikeGroupList[i]\npieChart(x,\"Attrition based on percentage Hike\")\n\n\n# In[34]:\n\n\n#Grouping values based on Performance Rating\nperformanceRatingList= rdAttritionFrame['PerformanceRating'].tolist()\nperformanceRatingGroup=[1,2,3,4]\nperformanceRatingGroupName = ['Low','Good','Excellent','Outstanding']\nperformanceRatingGroupCount = [performanceRatingList.count(performanceRatingGroup[0]),performanceRatingList.count(performanceRatingGroup[1]),performanceRatingList.count(performanceRatingGroup[2]),performanceRatingList.count(performanceRatingGroup[3])]\n#Bar Chart of Attrition based on Performance Rating\nbarChart(performanceRatingGroupName,performanceRatingGroupCount,getColors(len(performanceRatingGroup)),\"Attrition based on Performance Rating\")\n\n\n# ## Charts analysed on Sales Department\n\n# In[35]:\n\n\n#Attrition in Sales Department\nsalesAttritionFrame = yesAttritionFrame[orignalDataset['Department'] == 'Sales']\n\n\n# In[36]:\n\n\n#Attrition in Sales based on amount of travel\ntravelList = salesAttritionFrame['BusinessTravel'].tolist()\ntravelGroup = orignalDataset['BusinessTravel'].unique().tolist()\nbarChart(travelGroup,[travelList.count(travelGroup[0]),travelList.count(travelGroup[1]),travelList.count(travelGroup[2])],getColors(len(travelGroup)),\"Attrition based on Business Travel\")\n\n\n# In[37]:\n\n\n#Creating OverTime List and group\noverTimeList= salesAttritionFrame['OverTime'].tolist()\noverTimeGroup=list(set(overTimeList))\noverTimeGroupCount = [overTimeList.count(overTimeGroup[0]),overTimeList.count(overTimeGroup[1])]\n#Bar Chart of Attrition based on Overtime\nbarChart(overTimeGroup,overTimeGroupCount,getColors(len(overTimeGroup)),\"Attrition based on overtime\")\n\n\n# In[38]:\n\n\n#Creating JobInvolvement List and Group\njobInvolvementList= salesAttritionFrame['JobInvolvement'].tolist()\njobInvolvementGroup=list(set(jobInvolvementList))\njobInvolvementGroupName = ['Low','Medium','High','Very High']\njobInvolvementGroupCount = [jobInvolvementList.count(jobInvolvementGroup[0]),jobInvolvementList.count(jobInvolvementGroup[1]),jobInvolvementList.count(jobInvolvementGroup[2]),jobInvolvementList.count(jobInvolvementGroup[3])]\n#Pie Chart of Attrition based on JobInvolvement\nx = {}\nfor i in range(len(jobInvolvementGroup)):\n x[jobInvolvementGroupName[i]] = jobInvolvementList.count(jobInvolvementGroup[i])\npieChart(x,\"Attrition based on Job Involvement\")\n\n\n# In[39]:\n\n\n#Grouping values based on PercentSalaryHike\nbins = pd.cut(salesAttritionFrame['PercentSalaryHike'], [10, 15, 20, 25])\npercentHikeGroupList= salesAttritionFrame.groupby(bins)['PercentSalaryHike'].agg(['count'])['count'].tolist()\npercentageGroup = ['10-15%','15-20%','20-25%']\n#plotting pie chart based on PercentSalaryHike for Research and development\nx = {}\nfor i in range(len(percentageGroup)):\n x[percentageGroup[i]] = percentHikeGroupList[i]\npieChart(x,\"Attrition based on percentage Hike\")\n\n\n# In[40]:\n\n\n#Grouping values based on Performance Rating\nperformanceRatingList= salesAttritionFrame['PerformanceRating'].tolist()\nperformanceRatingGroup=[1,2,3,4]\nperformanceRatingGroupName = ['Low','Good','Excellent','Outstanding']\nperformanceRatingGroupCount = [performanceRatingList.count(performanceRatingGroup[0]),performanceRatingList.count(performanceRatingGroup[1]),performanceRatingList.count(performanceRatingGroup[2]),performanceRatingList.count(performanceRatingGroup[3])]\n#Bar Chart of Attrition based on Performance Rating\nbarChart(performanceRatingGroupName,performanceRatingGroupCount,getColors(len(performanceRatingGroup)),\"Attrition based on Performance Rating\")\n\n\n# ## Charts analysed on Human Resource Department\n\n# In[41]:\n\n\n#Attrition in Reserach and development Department\nhrAttritionFrame = yesAttritionFrame[orignalDataset['Department'] == 'Human Resources']\n\n\n# In[42]:\n\n\n#Attrition based on amount of travel\ntravelList = hrAttritionFrame['BusinessTravel'].tolist()\ntravelGroup = orignalDataset['BusinessTravel'].unique().tolist()\nbarChart(travelGroup,[travelList.count(travelGroup[0]),travelList.count(travelGroup[1]),travelList.count(travelGroup[2])],getColors(len(travelGroup)),\"Attrition based on Business Travel\")\n\n\n# In[43]:\n\n\n#Creating OverTime List and group\noverTimeList= hrAttritionFrame['OverTime'].tolist()\noverTimeGroup=list(set(overTimeList))\noverTimeGroupCount = [overTimeList.count(overTimeGroup[0]),overTimeList.count(overTimeGroup[1])]\n#Bar Chart of Attrition based on Overtime\nbarChart(overTimeGroup,overTimeGroupCount,getColors(len(overTimeGroup)),\"Attrition based on overtime\")\n\n\n# In[44]:\n\n\n#Creating JobInvolvement List and Group\njobInvolvementList= hrAttritionFrame['JobInvolvement'].tolist()\njobInvolvementGroup=list(set(jobInvolvementList))\njobInvolvementGroupName = ['Low','Medium','High','Very High']\njobInvolvementGroupCount = [jobInvolvementList.count(jobInvolvementGroup[0]),jobInvolvementList.count(jobInvolvementGroup[1]),jobInvolvementList.count(jobInvolvementGroup[2]),jobInvolvementList.count(jobInvolvementGroup[3])]\n#Pie Chart of Attrition based on JobInvolvement\nx = {}\nfor i in range(len(jobInvolvementGroup)):\n x[jobInvolvementGroupName[i]] = jobInvolvementList.count(jobInvolvementGroup[i])\npieChart(x,\"Attrition based on Job Involvement\")\n\n\n# In[45]:\n\n\n#Grouping values based on PercentSalaryHike\nbins = pd.cut(hrAttritionFrame['PercentSalaryHike'], [10, 15, 20, 25])\npercentHikeGroupList= hrAttritionFrame.groupby(bins)['PercentSalaryHike'].agg(['count'])['count'].tolist()\npercentageGroup = ['10-15%','15-20%','20-25%']\n#plotting pie chart based on PercentSalaryHike for Research and development\nx = {}\nfor i in range(len(percentageGroup)):\n x[percentageGroup[i]] = percentHikeGroupList[i]\npieChart(x,\"Attrition based on percentage Hike\")\n\n\n# In[46]:\n\n\n#Grouping values based on Performance Rating\nperformanceRatingList= hrAttritionFrame['PerformanceRating'].tolist()\nperformanceRatingGroup=[1,2,3,4]\nperformanceRatingGroupName = ['Low','Good','Excellent','Outstanding']\nperformanceRatingGroupCount = [performanceRatingList.count(performanceRatingGroup[0]),performanceRatingList.count(performanceRatingGroup[1]),performanceRatingList.count(performanceRatingGroup[2]),performanceRatingList.count(performanceRatingGroup[3])]\n#Bar Chart of Attrition based on Performance Rating\nbarChart(performanceRatingGroupName,performanceRatingGroupCount,getColors(len(performanceRatingGroup)),\"Attrition based on Performance Rating\")\n\n\n# ## Charts analysed on entire company\n\n# In[47]:\n\n\n#Grouping values based on YearsSinceLastPromotion\nlastPromotionYearList = yesAttritionFrame['YearsSinceLastPromotion'].tolist()\nlastPromotionYearGroup = list(set(lastPromotionYearList))\nlastPromotionYearGroupCount = []\nfor i in range(len(lastPromotionYearGroup)):\n lastPromotionYearGroupCount.append(lastPromotionYearList.count(lastPromotionYearGroup[i]))\n#lineChart showing attrition pattern with number of years since last promotion\nlineChart(lastPromotionYearGroup,lastPromotionYearGroupCount)\n\n\n# In[48]:\n\n\n#Grouping values based on Distance\nbins = pd.cut(yesAttritionFrame['DistanceFromHome'], [0, 10, 20, 30])\ndistanceGroupList= yesAttritionFrame.groupby(bins)['DistanceFromHome'].agg(['count'])['count'].tolist()\n#plotting bar chart based on distance for Research and evelopment\nbarChart(['0-10','10-20','20-30'],distanceGroupList,getColors(len(distanceGroupList)),\"Attrition based on Distance\")\n\n\n# In[49]:\n\n\n#Creating Education Group\neducationList = yesAttritionFrame['Education'].tolist()\neducationGroup= list(set(educationList))\neducationGroupName = ['Below College','College','Bachelor','Master','Doctor']\neducationGroupCount = [educationList.count(educationGroup[0]),educationList.count(educationGroup[1]),educationList.count(educationGroup[2]),educationList.count(educationGroup[3]),educationList.count(educationGroup[4])]\n#Pie chart showing Attrition based on Education for research and development\nx = {}\nfor i in range(len(educationGroup)):\n x[educationGroupName[i]] = educationList.count(educationGroup[i])\npieChart(x,\"Attrition based on Education\")\n\n\n# In[50]:\n\n\n#Creating EnvironmentSatisfaction Group\nenvSatList=yesAttritionFrame['EnvironmentSatisfaction'].tolist()\nenvSatGroup=list(set(envSatList))\nenvSatGroupName = ['Low','Medium','High','Very High']\nenvSatGroupCount = [envSatList.count(envSatGroup[0]),envSatList.count(envSatGroup[1]),envSatList.count(envSatGroup[2]),envSatList.count(envSatGroup[3])]\n#Bar Chart of Attrition based on EnvironmentSatisfaction\nbarChart(envSatGroupName,envSatGroupCount,getColors(len(envSatGroup)),\"Attrition based on Environment Satisfaction\")\n\n\n# In[51]:\n\n\n#Grouping values based on RelationshipSatisfaction\nrelationshipSatisfactionList= yesAttritionFrame['RelationshipSatisfaction'].tolist()\nrelationshipSatisfactionGroup= list(set(relationshipSatisfactionList))\nrelationshipSatisfactionGroupName = ['Low','Medium','High','Very High']\nrelationshipSatisfactionGroupCount = [relationshipSatisfactionList.count(relationshipSatisfactionGroup[0]),relationshipSatisfactionList.count(relationshipSatisfactionGroup[1]),relationshipSatisfactionList.count(relationshipSatisfactionGroup[2]),relationshipSatisfactionList.count(relationshipSatisfactionGroup[3])]\n#Bar Chart of Attrition based on Performance Rating\nbarChart(relationshipSatisfactionGroupName,relationshipSatisfactionGroupCount,getColors(len(relationshipSatisfactionGroup)),\"Attrition based on Relatinship Satisfaction\")\n\n\n# In[52]:\n\n\n#Grouping values based on StockOptions\nstockOptionList = yesAttritionFrame['StockOptionLevel'].tolist()\nstockOptionGroup = list(set(stockOptionList))\nstockOptionGroupName = ['Low','Medium','High','Very High']\nstockOptionGroupCount = [stockOptionList.count(stockOptionGroup[0]),stockOptionList.count(stockOptionGroup[1]),stockOptionList.count(stockOptionGroup[2]),stockOptionList.count(stockOptionGroup[3])]\n#Bar Chart of Attrition based on StockOptions\nbarChart(stockOptionGroupName,stockOptionGroupCount,getColors(len(stockOptionGroupName)),\"Attrition based on Stock Option\")\n\n\n# In[53]:\n\n\n#Grouping values based on WorkLifeBalance\nworkLifeBalanceList = yesAttritionFrame['WorkLifeBalance'].tolist()\nworkLifeBalanceGroup = list(set(workLifeBalanceList))\nworkLifeBalanceGroupName = ['Bad','Good','Better','Best']\nworkLifeBalanceGroupCount = [workLifeBalanceList.count(workLifeBalanceGroup[0]),workLifeBalanceList.count(workLifeBalanceGroup[1]),workLifeBalanceList.count(workLifeBalanceGroup[2]),workLifeBalanceList.count(workLifeBalanceGroup[3])]\n#Bar Chart of Attrition based on StockOptions\nbarChart(workLifeBalanceGroupName,workLifeBalanceGroupCount,getColors(len(workLifeBalanceGroup)),\"Attrition based on Work Life balance\")\n\n\n# In[54]:\n\n\n#Grouping values based on YearsInCurrentRole\nyearsInCurrentRoleList = yesAttritionFrame['YearsInCurrentRole'].tolist()\nyearsInCurrentRoleGroup = list(set(yearsInCurrentRoleList))\nyearsInCurrentRoleGroupCount = []\nfor i in range(len(yearsInCurrentRoleGroup)):\n yearsInCurrentRoleGroupCount.append(yearsInCurrentRoleList.count(yearsInCurrentRoleGroup[i]))\n#lineChart showing attrition pattern with number of years\nlineChart(yearsInCurrentRoleGroup,yearsInCurrentRoleGroupCount)\n\n\n# In[55]:\n\n\n#Grouping values based on YearsWithCurrManager\nyearsWithCurrManagerList = yesAttritionFrame['YearsWithCurrManager'].tolist()\nyearsWithCurrManagerGroup = list(set(yearsWithCurrManagerList))\nyearsWithCurrManagerGroupCount = []\nfor i in range(len(yearsWithCurrManagerGroup)):\n yearsWithCurrManagerGroupCount.append(yearsWithCurrManagerList.count(yearsWithCurrManagerGroup[i]))\n#lineChart showing attrition pattern with number of years\nlineChart(yearsWithCurrManagerGroup,yearsWithCurrManagerGroupCount)\n\n\n# In[56]:\n\n\n#Percentage of females leaving the company\nfemalePercenatge = genderGroupCount[0]/int(orignalDataset[orignalDataset['Gender'] == 'Female']['Gender'].count())\nprint(\"Percentage of Female attrition =\",int(femalePercenatge *100),\"%\")\n\n\n# In[57]:\n\n\n#Percentage of males leaving the company\nmalePercenatge = genderGroupCount[1]/int(orignalDataset[orignalDataset['Gender'] == 'Male']['Gender'].count())\nprint(\"Percentage of Male attrition =\",int(malePercenatge *100),\"%\")\n\n","sub_path":"Employee Attrition.py","file_name":"Employee Attrition.py","file_ext":"py","file_size_in_byte":23433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"423968617","text":"# Pedia overhaul by Toffer for Caveman2Cosmos.\n\nfrom CvPythonExtensions import *\n\nclass PediaImprovement:\n\n\tdef __init__(self, parent, H_BOT_ROW):\n\t\tself.main = parent\n\n\t\tH_PEDIA_PAGE = parent.H_PEDIA_PAGE\n\n\t\tself.Y_TOP_ROW = Y_TOP_ROW = parent.Y_PEDIA_PAGE\n\t\tself.Y_BOT_ROW = Y_TOP_ROW + H_PEDIA_PAGE - H_BOT_ROW\n\n\t\tself.H_TOP_ROW = H_TOP_ROW = (H_PEDIA_PAGE - H_BOT_ROW * 3) / 4\n\t\tself.H_BOT_ROW = H_BOT_ROW\n\n\t\tiSize = 64\n\t\tiRoom = H_BOT_ROW - 40\n\t\twhile True:\n\t\t\tif iSize < iRoom:\n\t\t\t\tself.S_BOT_ROW = iSize\n\t\t\t\tbreak\n\t\t\tiSize -= 4\n\n\t\tself.W_PEDIA_PAGE = W_PEDIA_PAGE = parent.W_PEDIA_PAGE\n\t\tself.W_3RD_PP = W_PEDIA_PAGE / 3\n\n\t\tself.X_COL_1 = X_COL_1 = parent.X_PEDIA_PAGE\n\n\t\tself.X_GRAPHIC = X_COL_1 + W_PEDIA_PAGE - H_TOP_ROW\n\n\t\tself.W_COL_1 = W_COL_1 = W_PEDIA_PAGE - H_TOP_ROW - 16\n\n\t\tself.S_ICON = S_ICON = H_TOP_ROW - 10\n\n\t\tself.W_STATS = W_COL_1 - S_ICON * 3\n\n\t\ti = H_TOP_ROW / 8\n\t\tself.X_MAIN = X_COL_1 + S_ICON - 8\n\t\tself.Y_MAIN = Y_TOP_ROW + i\n\t\tself.H_MAIN = H_TOP_ROW - i * 2\n\n\n\t\t#a = H_TOP_ROW / 12\n\t\t#self.X_STATS = X_COL_1 + S_ICON\n\t\t#self.Y_STATS = Y_TOP_ROW + a\n\t\t#self.H_STATS = H_TOP_ROW - a * 2 + 4\n\t\t#self.W_STATS = W_BASE - S_ICON\n\n\tdef interfaceScreen(self, iTheImprove):\n\t\tGC = CyGlobalContext()\n\t\tTRNSLTR = CyTranslator()\n\t\tCvTheImproveInfo = GC.getImprovementInfo(iTheImprove)\n\t\tscreen = self.main.screen()\n\t\taName = self.main.getNextWidgetName\n\n\t\teWidGen\t\t\t= WidgetTypes.WIDGET_GENERAL\n\t\teWidJuToBonus\t= WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS\n\t\teWidJuToBuild\t= WidgetTypes.WIDGET_PEDIA_JUMP_TO_BUILDING\n\t\teWidJuToCivic\t= WidgetTypes.WIDGET_PEDIA_JUMP_TO_CIVIC\n\t\teWidJuToFeature\t= WidgetTypes.WIDGET_PEDIA_JUMP_TO_FEATURE\n\t\teWidJuToRoute\t= WidgetTypes.WIDGET_PEDIA_JUMP_TO_ROUTE\n\t\teWidJuToTech\t= WidgetTypes.WIDGET_PEDIA_JUMP_TO_TECH\n\t\teWidJuToTerrain\t= WidgetTypes.WIDGET_PEDIA_JUMP_TO_TERRAIN\n\t\teWidJuToUnit\t= WidgetTypes.WIDGET_PEDIA_JUMP_TO_UNIT\n\t\tePnlBlue50\t\t= PanelStyles.PANEL_STYLE_BLUE50\n\t\tePnlEmpty\t\t= PanelStyles.PANEL_STYLE_EMPTY\n\t\teTblEmpty\t\t= TableStyles.TABLE_STYLE_EMPTY\n\t\teFontTitle\t\t= FontTypes.TITLE_FONT\n\t\teNumYieldTypes\t= YieldTypes.NUM_YIELD_TYPES\n\n\t\tenumGBS = self.main.enumGBS\n\t\tszfontEdge, szfont4b, szfont4, szfont3b, szfont3, szfont2b, szfont2 = self.main.aFontList\n\n\t\tW_PEDIA_PAGE = self.W_PEDIA_PAGE\n\t\tS_ICON = self.S_ICON\n\t\tX_COL_1 = self.X_COL_1\n\t\tW_COL_1 = self.W_COL_1\n\t\tH_BOT_ROW = self.H_BOT_ROW\n\t\tY_BOT_ROW_1 = self.Y_BOT_ROW\n\t\tH_TOP_ROW_1 = self.H_TOP_ROW\n\t\tY_TOP_ROW_1 = self.Y_TOP_ROW\n\t\tH_TOP_ROW_2 = H_BOT_ROW + H_BOT_ROW / 4\n\t\tY_TOP_ROW_2 = Y_TOP_ROW_1 + H_TOP_ROW_1\n\t\tY_MID_ROW = Y_TOP_ROW_2 + H_TOP_ROW_2\n\t\tH_MID_ROW = Y_BOT_ROW_1 - Y_MID_ROW\n\t\tW_STATS = self.W_STATS\n\t\tX_MAIN = self.X_MAIN\n\t\tY_MAIN = self.Y_MAIN\n\t\tH_MAIN = self.H_MAIN\n\t\tS_BOT_ROW = self.S_BOT_ROW\n\n\t\t# Graphic\n\t\tscreen.addImprovementGraphicGFC(\"Preview|Min\", iTheImprove, self.X_GRAPHIC, Y_TOP_ROW_1 + 8, H_TOP_ROW_1, H_TOP_ROW_1, eWidGen, iTheImprove, 0, -20, 30, 0.7, True)\n\t\tself.main.aWidgetBucket.append(\"Preview|Min\")\n\t\t# Main Panel\n\t\tscreen.setText(aName(), \"\", szfontEdge + CvTheImproveInfo.getDescription(), 1<<0, X_COL_1, 0, 0, FontTypes.TITLE_FONT, eWidGen, 0, 0)\n\t\tPnl = aName()\n\t\tscreen.addPanel(Pnl, \"\", \"\", False, False, X_COL_1 - 3, Y_TOP_ROW_1 + 2, W_COL_1 + 8, H_TOP_ROW_1 + 2, PanelStyles.PANEL_STYLE_MAIN)\n\t\tImg = \"ToolTip|IMP\" + str(iTheImprove)\n\t\tself.main.aWidgetBucket.append(Img)\n\t\tscreen.setImageButtonAt(Img, Pnl, CvTheImproveInfo.getButton(), 4, 6, S_ICON, S_ICON, eWidGen, 1, 1)\n\t\t# Stats\n\t\tszText = \"\"\n\t\tif CvTheImproveInfo.isOutsideBorders():\n\t\t\tszText += \" Can be built outside cultural borders.\\n\"\n\t\tszYieldReq = \" Min. \"\n\t\tbYieldReq = False\n\t\tszYield = \"\"\n\t\tfor k in range(YieldTypes.NUM_YIELD_TYPES):\n\t\t\tszChar = u'%c' % (GC.getYieldInfo(k).getChar())\n\t\t\tiYieldChange = CvTheImproveInfo.getYieldChange(k)\n\t\t\tif iYieldChange:\n\t\t\t\tif iYieldChange < 0:\n\t\t\t\t\tszYield += \" \"\n\t\t\t\telse:\n\t\t\t\t\tszYield += \" +\"\n\t\t\t\tszYield += str(iYieldChange) + szChar + \"\"\n\t\t\tiRiverYieldChange = CvTheImproveInfo.getRiverSideYieldChange(k)\n\t\t\tif iRiverYieldChange:\n\t\t\t\tif iRiverYieldChange < 0:\n\t\t\t\t\tszYield += \" (\"\n\t\t\t\telse:\n\t\t\t\t\tszYield += \" (+\"\n\t\t\t\tszYield += str(iRiverYieldChange) + szChar + \"River)\"\n\t\t\tiHillsYieldChange = CvTheImproveInfo.getHillsYieldChange(k)\n\t\t\tif iHillsYieldChange:\n\t\t\t\tif iHillsYieldChange < 0:\n\t\t\t\t\tszYield += \" (\"\n\t\t\t\telse:\n\t\t\t\t\tszYield += \" (+\"\n\t\t\t\tszYield += str(iHillsYieldChange) + szChar + \"Hill)\"\n\t\t\tiFreshwaterYieldChange = CvTheImproveInfo.getIrrigatedYieldChange(k)\n\t\t\tif iFreshwaterYieldChange:\n\t\t\t\tif iFreshwaterYieldChange < 0:\n\t\t\t\t\tszYield += \" (\"\n\t\t\t\telse:\n\t\t\t\t\tszYield += \" (+\"\n\t\t\t\tszYield += str(iFreshwaterYieldChange) + szChar + \"Freshwater)\"\n\t\t\tiPrereqNatureYield = CvTheImproveInfo.getPrereqNatureYield(k)\n\t\t\tif iPrereqNatureYield:\n\t\t\t\tbYieldReq = True\n\t\t\t\tszYieldReq += str(iPrereqNatureYield) + szChar\n\t\tif szYield:\n\t\t\tszText += szYield + \"\\n\"\n\t\tiDefenseMod = CvTheImproveInfo.getDefenseModifier()\n\t\tif iDefenseMod:\n\t\t\tszDefChar = unichr(8861)\n\t\t\tszText += szDefChar\n\t\t\tif iDefenseMod < 0:\n\t\t\t\tszText += \" \"\n\t\t\telse:\n\t\t\t\tszText += \" +\"\n\t\t\tszText += \"%d%%\" %iDefenseMod + unichr(8855) + szDefChar\n\t\tiAirDefense = CvTheImproveInfo.getAirBombDefense()\n\t\tif iAirDefense:\n\t\t\tif iAirDefense < 0:\n\t\t\t\tszText += \" \"\n\t\t\telse:\n\t\t\t\tszText += \" +\"\n\t\t\tszText += str(iAirDefense) + \" Air Defense\"\n\t\tif szText:\n\t\t\tlistBox = aName()\n\t\t\tscreen.addListBoxGFC(listBox, \"\", X_MAIN, Y_MAIN, W_STATS, H_MAIN, eTblEmpty)\n\t\t\tscreen.enableSelect(listBox, False)\n\t\t\tif szText:\n\t\t\t\tscreen.appendListBoxString(listBox, szfont3b + szText, eWidGen, 0, 0, 1<<0)\n\t\t# Builds\n\t\tPF = \"ToolTip|JumpTo|\"\n\t\taList0 = []\n\t\tfor i in range(GC.getNumBuildInfos()):\n\t\t\tCvBuildInfo = GC.getBuildInfo(i)\n\t\t\tif CvBuildInfo.getImprovement() == iTheImprove:\n\t\t\t\taList0.append((i, CvBuildInfo.getButton()))\n\n\t\tif aList0:\n\t\t\tszChild = PF + \"BUILD\"\n\t\t\tW_REQUIRES = W_COL_1 - W_STATS - S_ICON\n\t\t\tPnl = aName()\n\t\t\ty = Y_MAIN + (H_MAIN - H_BOT_ROW)/2\n\t\t\tscreen.addPanel(Pnl, \"\", \"\", False, True, X_MAIN + W_STATS, y, W_REQUIRES, H_BOT_ROW, ePnlBlue50)\n\t\t\tszText = szfont3b + \"Build:\"\n\t\t\tscreen.setLabelAt(aName(), Pnl, szText, 1<<0, 16, 2, 0, eFontTitle, eWidGen, 0, 0)\n\t\t\tPnl = aName()\n\t\t\tscreen.addScrollPanel(Pnl, \"\", X_MAIN + W_STATS - 2, y + 24, W_REQUIRES + 4, H_BOT_ROW - 50, ePnlBlue50)\n\t\t\tscreen.setStyle(Pnl, \"ScrollPanel_Alt_Style\")\n\t\t\tPF + \"CIVIC\"\n\t\t\tx = 4\n\t\t\tfor iType, BTN in aList0:\n\t\t\t\tscreen.setImageButtonAt(szChild + str(iType), Pnl, BTN, x, -2, S_BOT_ROW, S_BOT_ROW, eWidGen, 1, 1)\n\t\t\t\tx += S_BOT_ROW + 4\n\t\t\taList0 = []\n\n\t\t# Synergy\n\t\tszAnd = \"&\"\n\t\taValidList = []\n\t\taList1 = []\n\t\tfor iTech in range(GC.getNumTechInfos()):\n\t\t\tszYield = \"\"\n\t\t\tfor k in range(eNumYieldTypes):\n\t\t\t\tiYieldChange = CvTheImproveInfo.getTechYieldChanges(iTech, k)\n\t\t\t\tif iYieldChange:\n\t\t\t\t\tif iYieldChange < 0:\n\t\t\t\t\t\tszYield += \" \"\n\t\t\t\t\telse:\n\t\t\t\t\t\tszYield += \" \"\n\t\t\t\t\tszYield += str(iYieldChange) + u'%c' % (GC.getYieldInfo(k).getChar())\n\t\t\tif szYield:\n\t\t\t\taList1.append((iTech, szYield))\n\t\taList2 = []\n\t\tfor iCivic in range(GC.getNumCivicInfos()):\n\t\t\tszYield = \"\"\n\t\t\tfor k in range(eNumYieldTypes):\n\t\t\t\tiYieldChange = GC.getCivicInfo(iCivic).getImprovementYieldChanges(iTheImprove, k)\n\t\t\t\tif iYieldChange:\n\t\t\t\t\tif iYieldChange < 0:\n\t\t\t\t\t\tszYield += \" \"\n\t\t\t\t\telse:\n\t\t\t\t\t\tszYield += \" \"\n\t\t\t\t\tszYield += str(iYieldChange) + u'%c' % (GC.getYieldInfo(k).getChar())\n\t\t\tif szYield:\n\t\t\t\taList2.append((iCivic, szYield))\n\t\taList3 = []\n\t\tszChild = PF + \"BONUS\"\n\t\tn = 0\n\t\tfor iType in range(GC.getNumBonusInfos()):\n\t\t\tszYield = \"\"\n\t\t\tfor k in range(eNumYieldTypes):\n\t\t\t\tiYieldChange = CvTheImproveInfo.getImprovementBonusYield(iType, k)\n\t\t\t\tif iYieldChange:\n\t\t\t\t\tif iYieldChange < 0:\n\t\t\t\t\t\tszYield += \" \"\n\t\t\t\t\telse:\n\t\t\t\t\t\tszYield += \" \"\n\t\t\t\t\tszYield += str(iYieldChange) + u'%c' % (GC.getYieldInfo(k).getChar())\n\t\t\tif szYield:\n\t\t\t\taList3.append((iType, szYield))\n\t\t\tif CvTheImproveInfo.isImprovementBonusMakesValid(iType):\n\t\t\t\taValidList.append([szChild + str(iType) + \"|\" + str(n), GC.getBonusInfo(iType).getButton()])\n\t\t\t\tn += 1\n\t\taList4 = []\n\t\tfor iRoute in range(GC.getNumRouteInfos()):\n\t\t\tszYield = \"\"\n\t\t\tfor k in range(eNumYieldTypes):\n\t\t\t\tiYieldChange = CvTheImproveInfo.getRouteYieldChanges(iRoute, k)\n\t\t\t\tif iYieldChange:\n\t\t\t\t\tif iYieldChange < 0:\n\t\t\t\t\t\tszYield += \" \"\n\t\t\t\t\telse:\n\t\t\t\t\t\tszYield += \" \"\n\t\t\t\t\tszYield += str(iYieldChange) + u'%c' % (GC.getYieldInfo(k).getChar())\n\t\t\tif szYield:\n\t\t\t\taList4.append((iRoute, szYield))\n\t\tif aList1 or aList2 or aList3 or aList4:\n\t\t\tpanelName = aName()\n\t\t\tscreen.addPanel(panelName, \"Synergy:\", \"\", False, True, X_COL_1, Y_TOP_ROW_2, W_PEDIA_PAGE, H_TOP_ROW_2, ePnlBlue50)\n\t\t\tbAnd = False\n\t\t\tif aList1:\n\t\t\t\tbAnd = True\n\t\t\t\tfor i, szYield in aList1:\n\t\t\t\t\tchildPanelName = aName()\n\t\t\t\t\tscreen.attachPanel(panelName, childPanelName, \"\", \"\", True, True, ePnlEmpty)\n\t\t\t\t\tscreen.attachImageButton(childPanelName, \"\", GC.getTechInfo(i).getButton(), enumGBS, eWidJuToTech, i, 1, False)\n\t\t\t\t\tscreen.attachLabel(childPanelName, \"\", szfont3b + \" \" + szYield)\n\t\t\t\t\tscreen.attachLabel(panelName, \"\", \" \")\n\t\t\tif aList2:\n\t\t\t\tif bAnd:\n\t\t\t\t\tscreen.attachLabel(panelName, \"\", szAnd + \" \")\n\t\t\t\telse:\n\t\t\t\t\tbAnd = True\n\t\t\t\tfor i, szYield in aList2:\n\t\t\t\t\tchildPanelName = aName()\n\t\t\t\t\tscreen.attachPanel(panelName, childPanelName, \"\", \"\", True, True, ePnlEmpty)\n\t\t\t\t\tscreen.attachImageButton(childPanelName, \"\", GC.getCivicInfo(i).getButton(), enumGBS, eWidJuToCivic, i, 1, False)\n\t\t\t\t\tscreen.attachLabel(childPanelName, \"\", szfont3b + \" \" + szYield)\n\t\t\t\t\tscreen.attachLabel(panelName, \"\", \" \")\n\t\t\tif aList3:\n\t\t\t\tif bAnd:\n\t\t\t\t\tscreen.attachLabel(panelName, \"\", szAnd + \" \")\n\t\t\t\telse:\n\t\t\t\t\tbAnd = True\n\t\t\t\tfor i, szYield in aList3:\n\t\t\t\t\tchildPanelName = aName()\n\t\t\t\t\tscreen.attachPanel(panelName, childPanelName, \"\", \"\", True, True, ePnlEmpty)\n\t\t\t\t\tscreen.attachImageButton(childPanelName, \"\", GC.getBonusInfo(i).getButton(), enumGBS, eWidJuToBonus, i, 1, False)\n\t\t\t\t\tscreen.attachLabel(childPanelName, \"\", szfont3b + \" \" + szYield)\n\t\t\t\t\tscreen.attachLabel(panelName, \"\", \" \")\n\t\t\tif aList4:\n\t\t\t\tif bAnd:\n\t\t\t\t\tscreen.attachLabel(panelName, \"\", szAnd + \" \")\n\t\t\t\telse:\n\t\t\t\t\tbAnd = True\n\t\t\t\tfor i, szYield in aList4:\n\t\t\t\t\tchildPanelName = aName()\n\t\t\t\t\tscreen.attachPanel(panelName, childPanelName, \"\", \"\", True, True, ePnlEmpty)\n\t\t\t\t\tscreen.attachImageButton(childPanelName, \"\", GC.getRouteInfo(i).getButton(), enumGBS, eWidJuToRoute, i, 1, False)\n\t\t\t\t\tscreen.attachLabel(childPanelName, \"\", szfont3b + \" \" + szYield)\n\t\t\t\t\tscreen.attachLabel(panelName, \"\", \" \")\n\t\telse:\n\t\t\tY_MID_ROW -= H_TOP_ROW_2\n\t\t\tH_MID_ROW += H_TOP_ROW_2\n\t\t# Requires\n\t\tnTerrains = GC.getNumTerrainInfos()\n\t\tiType = CvTheImproveInfo.getPrereqTech()\n\t\tif iType != -1:\n\t\t\taList0.append([PF + \"TECH\" + str(iType), GC.getTechInfo(iType).getButton()])\n\n\t\t# bNotOnAnyBonus is not exposed to python.\n\n\t\tif CvTheImproveInfo.isWater():\n\t\t\taList0.append([PF + \"CONCEPT_NEW\" + str(GC.getInfoTypeForString(\"CONCEPT_WATER_TERRAINS\")), \"Art/Interface/Buttons/BaseTerrain/Ocean.dds\"])\n\n\t\tif CvTheImproveInfo.isRequiresPeak():\n\t\t\taList0.append([PF + \"TERRAIN\" + str(nTerrains - 2) + \"|\" + str(n), GC.getTerrainInfo(nTerrains - 2).getButton()])\n\t\t\tn += 1\n\t\telif not CvTheImproveInfo.isPeakMakesValid():\n\t\t\taList0.append([PF + \"TERRAIN\" + str(nTerrains - 2) + \"|\" + str(n), GC.getTerrainInfo(nTerrains - 2).getButton(), \"NOT\"])\n\t\t\tn += 1\n\n\t\tif CvTheImproveInfo.isRequiresFlatlands():\n\t\t\taList0.append([\"ToolTip|TxtTT|TXT_KEY_IMPROVEMENT_ONLY_BUILD_FLATLANDS1\", \"Art/Interface/Buttons/BaseTerrain/Grassland.dds\"])\n\n\t\tif CvTheImproveInfo.isRequiresRiverSide():\n\t\t\taList0.append([\"ToolTip|TxtTT|TXT_KEY_IMPROVEMENT_REQUIRES_RIVER1\", \"Art/Interface/Buttons/WorldBuilder/River_Placement.dds\"])\n\n\t\tif CvTheImproveInfo.isRequiresFeature():\n\t\t\taList0.append([\"ToolTip|TxtTT|Any_plot_feature1\", \"Art/bug/questionmark.dds\"])\n\n\t\tif CvTheImproveInfo.isRequiresIrrigation():\n\t\t\taList0.append([\"ToolTip|TxtTT|TXT_KEY_WB_IRRIGATION1\", \"Art/Interface/Buttons/Buildings/Irrigation.dds\"])\n\n\t\tif CvTheImproveInfo.isNoFreshWater():\n\t\t\taList0.append([\"ToolTip|TxtTT|TXT_KEY_IMPROVEMENT_NO_BUILD_FRESH_WATER1\", \"Art/bug/questionmark.dds\"])\n\n\t\tszChild = PF + \"TERRAIN\"\n\t\tfor i in range(nTerrains):\n\t\t\tif CvTheImproveInfo.getTerrainMakesValid(i):\n\t\t\t\taValidList.append((szChild + str(i) + \"|\" + str(n), GC.getTerrainInfo(i).getButton()))\n\t\t\t\tn += 1\n\t\tif CvTheImproveInfo.isHillsMakesValid():\n\t\t\taValidList.append((szChild + str(nTerrains - 1) + \"|\" + str(n), GC.getTerrainInfo(nTerrains - 1).getButton()))\n\t\t\tn += 1\n\n\t\tszChild = PF + \"FEATURE\"\n\t\tfor i in range(GC.getNumFeatureInfos()):\n\t\t\tif CvTheImproveInfo.getFeatureMakesValid(i):\n\t\t\t\taValidList.append((szChild + str(i) + \"|\" + str(n), GC.getFeatureInfo(i).getButton()))\n\t\t\t\tn += 1\n\n\t\tif aList0 or aValidList:\n\t\t\tszNot = \"{Not\"\n\t\t\tszOr = \"||\"\n\t\t\tszBracketL = \"{\"\n\t\t\tszBracketR = \"}\"\n\t\t\tH_SCROLL = H_BOT_ROW - 50\n\t\t\tPnl = aName()\n\t\t\tscreen.addPanel(Pnl, \"\", \"\", False, True, X_COL_1, Y_BOT_ROW_1, W_PEDIA_PAGE, H_BOT_ROW, ePnlBlue50)\n\t\t\tszText = szfont3b + TRNSLTR.getText(\"TXT_KEY_PEDIA_REQUIRES\", ())\n\t\t\tscreen.setLabelAt(aName(), Pnl, szText, 1<<2, W_PEDIA_PAGE / 2, 2, 0, eFontTitle, eWidGen, 0, 0)\n\t\t\tPnl = aName()\n\t\t\tscreen.addScrollPanel(Pnl, \"\", X_COL_1 - 2, Y_BOT_ROW_1 + 24, W_PEDIA_PAGE + 4, H_SCROLL, ePnlBlue50)\n\t\t\tscreen.setStyle(Pnl, \"ScrollPanel_Alt_Style\")\n\t\t\tscreen.hide(Pnl)\n\t\t\tx = 4\n\t\t\ty = H_SCROLL / 2 - 12\n\t\t\tbValidBracket = False\n\t\t\tfor entry in aList0:\n\t\t\t\tif entry[-1] == \"NOT\":\n\t\t\t\t\tif x != 4:\n\t\t\t\t\t\tx += 8\n\t\t\t\t\tscreen.setLabelAt(aName(), Pnl, szNot, 1<<0, x, y, 0, eFontTitle, eWidGen, 0, 0)\n\t\t\t\t\tx += 44\n\t\t\t\tscreen.setImageButtonAt(entry[0], Pnl, entry[1], x, -2, S_BOT_ROW, S_BOT_ROW, eWidGen, 1, 1)\n\t\t\t\tx += S_BOT_ROW + 4\n\t\t\t\tif entry[-1] == \"NOT\":\n\t\t\t\t\tx += 6\n\t\t\t\t\tscreen.setLabelAt(aName(), Pnl, szBracketR, 1<<0, x, y, 0, eFontTitle, eWidGen, 0, 0)\n\t\t\t\t\tx += 14\n\t\t\tif aList0 and len(aValidList):\n\t\t\t\tbValidBracket = True\n\t\t\t\tx += 8\n\t\t\t\tscreen.setLabelAt(aName(), Pnl, szBracketL, 1<<0, x, y, 0, eFontTitle, eWidGen, 0, 0)\n\t\t\t\tx += 16\n\t\t\ti = 0\n\t\t\tfor NAME, BTN in aValidList:\n\t\t\t\tif i == 0:\n\t\t\t\t\ti+= 1\n\t\t\t\telse:\n\t\t\t\t\tx += 6\n\t\t\t\t\tscreen.setLabelAt(aName(), Pnl, szOr, 1<<2, x, y, 0, eFontTitle, eWidGen, 0, 0)\n\t\t\t\t\tx += 10\n\t\t\t\tscreen.setImageButtonAt(NAME, Pnl, BTN, x, -2, S_BOT_ROW, S_BOT_ROW, eWidGen, 1, 1)\n\t\t\t\tx += S_BOT_ROW + 4\n\t\t\tif bValidBracket:\n\t\t\t\tscreen.setLabelAt(aName(), Pnl, szBracketR, 1<<0, x + 8, y, 0, eFontTitle, eWidGen, 0, 0)\n\t\t\tscreen.show(Pnl)\n\n\t\telse:\n\t\t\tH_MID_ROW += H_BOT_ROW\n\t\t# Effects and History\n\t\tszEffects = CyGameTextMgr().getImprovementHelp(iTheImprove, False)\n\t\ti = szEffects.find(\"\\n\") + 1\n\t\tif not i:\n\t\t\tszEffects = \"\"\n\t\tszHistory = CvTheImproveInfo.getCivilopedia()\n\t\tif szEffects or szHistory:\n\t\t\tif szEffects and szHistory:\n\t\t\t\tW_MID_COL_1 = self.W_3RD_PP\n\t\t\t\tW_MID_COL_2 = W_PEDIA_PAGE - W_MID_COL_1 - 8\n\t\t\t\tX_COL_2 = X_COL_1 + W_MID_COL_1 + 8\n\t\t\telif szEffects:\n\t\t\t\tW_MID_COL_1 = W_PEDIA_PAGE\n\t\t\telif szHistory:\n\t\t\t\tX_COL_2 = X_COL_1\n\t\t\t\tW_MID_COL_2 = W_PEDIA_PAGE\n\t\t\tif szEffects:\n\t\t\t\tszHeader = TRNSLTR.getText(\"TXT_KEY_PEDIA_EFFECTS\", ())\n\t\t\t\tscreen.addPanel(aName(), szHeader, \"\", True, False, X_COL_1, Y_MID_ROW, W_MID_COL_1, H_MID_ROW, ePnlBlue50)\n\t\t\t\tscreen.addMultilineText(aName(), szfont3 + szEffects[i:], X_COL_1 + 4, Y_MID_ROW + 32, W_MID_COL_1 - 8, H_MID_ROW - 40, eWidGen, 0, 0, 1<<0)\n\t\t\tif szHistory:\n\t\t\t\tszHeader = TRNSLTR.getText(\"TXT_KEY_PEDIA_HISTORY\", ())\n\t\t\t\tscreen.addPanel(aName(), szHeader, \"\", True, True, X_COL_2, Y_MID_ROW, W_MID_COL_2, H_MID_ROW, ePnlBlue50)\n\t\t\t\tscreen.addMultilineText(aName(), szfont2 + szHistory, X_COL_2 + 4, Y_MID_ROW + 32, W_MID_COL_2 - 8, H_MID_ROW - 40, eWidGen, 0, 0, 1<<0)\n","sub_path":"Assets/Python/Contrib/Pedia/PediaImprovement.py","file_name":"PediaImprovement.py","file_ext":"py","file_size_in_byte":16024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"21092478","text":"import csv\nimport random\nfrom typing import List\n\nimport kudu\nimport os\n\nimport time\n\nimport sys\nfrom kudu.client import Partitioning, PartialRow\nfrom kudu.schema import ColumnSpec\n\nCOL_NAMES_PLAIN_SET = [\"ts\" , \"value\"]\n\nCOL_NAMES_BLOB_SET = [\"ts\", \"amin_amax\", \"value\"]\n\ndef columns_builder_plain():\n builder = kudu.schema_builder()\n\n builder.add_column(\"ts\", kudu.int64, nullable=False, primary_key=True)\n builder.add_column(\"value\", kudu.float, nullable=False, primary_key=True)\n\n schema = builder.build()\n return schema\n\n\nclass KuduTimeAndSensorPart:\n def __init__(self):\n self.max_ts = 100000\n self.max_A = 1000\n\n self.ITEM_TO_WRITE_PER_FLUSH = 100000\n\n self.client = kudu.connect(\"192.168.13.133\", 7051)\n self.session = self.client.new_session(flush_mode='manual', timeout_ms=25000)\n\n self.table_name = \"kuduTSTimePart\"\n\n # kudu.Table\n self.table = None\n pass\n\n def _columns_builder(self):\n builder = kudu.schema_builder()\n builder.add_column('ts').type(kudu.int64).nullable(False)\n builder.add_column('sensor').type(kudu.int32).nullable(False)\n builder.add_column('value').type(kudu.float).nullable(False)\n builder.set_primary_keys(['ts', 'sensor'])\n schema = builder.build()\n return schema\n\n def _make_partitioning(self):\n # Create hash partitioning buckets\n # partitioning = Partitioning().add_hash_partitions('ts', 2)\n partitioning = Partitioning() \\\n .set_range_partition_columns(\"ts\") \\\n .add_range_partition(lower_bound=None,\n upper_bound=None,\n lower_bound_type='inclusive',\n upper_bound_type='exclusive')\n\n return partitioning\n\n def __open_or_create_table(self, name, partitioning, drop=False):\n \"\"\"Based on the default dstat column names create a new table indexed by a timstamp col\"\"\"\n exists = False\n hasBeenCreated = False\n schema = self._columns_builder()\n\n if self.client.table_exists(name):\n exists = True\n if drop:\n self.client.delete_table(name)\n exists = False\n else:\n tbl = self.client.table(name)\n if not tbl.schema.equals(schema):\n raise Exception(\"Table {} has other schema \"\n \"than this class implements and drop is False.\"\n \"Cannot continue\".format(self.table_name))\n\n if not exists:\n self.client.create_table(name, schema, partitioning, n_replicas=1)\n hasBeenCreated = True\n\n return (self.client.table(name), hasBeenCreated)\n\n def _generate_data(self, count):\n for ts in range(count):\n yield (ts, random.randint(0, 10), random.random() * self.max_A)\n\n def obtainTableForFillingWith(self, sequence: List, sensorIds: List[int]):\n if len(sequence) == 0:\n raise Exception(\"Sequence cannot be empty\")\n\n ts_min, value_min = sequence[0]\n ts_max, value_max = sequence[-1]\n ts_max += 1\n\n day_len = 60 * 24 * 60000\n week_len = day_len * 7\n month_len = day_len * 30\n year_len = day_len * 365\n\n part_interval_len = week_len\n\n parts_count = int((ts_max - ts_min) / part_interval_len)\n parts_count = parts_count if (ts_max - ts_min) % part_interval_len == 0 else parts_count + 1\n\n partitioning = Partitioning() \\\n .set_range_partition_columns(\"ts\")\n\n ts_start = ts_min\n ts_end = ts_start + part_interval_len\n\n\n partitioning = partitioning.add_range_partition(lower_bound={\"ts\": 0},\n upper_bound={\"ts\": ts_start},\n lower_bound_type='inclusive',\n upper_bound_type='exclusive')\n\n for wI in range(parts_count):\n partitioning = partitioning.add_range_partition(lower_bound={\"ts\": ts_start},\n upper_bound={\"ts\": ts_end},\n lower_bound_type='inclusive',\n upper_bound_type='exclusive')\n ts_start = ts_end\n ts_end = ts_end + part_interval_len\n\n partitioning = partitioning.add_range_partition(lower_bound={\"ts\": ts_end},\n upper_bound=None,\n lower_bound_type='inclusive',\n upper_bound_type='exclusive')\n\n\n if len(sensorIds) > 1:\n partitioning = partitioning.add_hash_partitions([\"sensor\"], num_buckets=len(sensorIds))\n\n self.table, hasBeenCreated = self.__open_or_create_table(self.table_name, partitioning, drop=True)\n\n if not hasBeenCreated:\n raise Exception(\"Table has not been created\")\n\n self.fill_table_from_seq(sequence, sensorIds)\n\n pass\n\n def obtainTable(self, recreate=False):\n partitioning = self._make_partitioning()\n self.table, hasBeenCreated = self.__open_or_create_table(self.table_name, partitioning, drop=recreate)\n\n def obtainAndFillTable(self):\n partitioning = self._make_partitioning()\n self.table, hasBeenCreated = self.__open_or_create_table(self.table_name, partitioning, drop=False)\n\n if hasBeenCreated:\n self.fill_table()\n\n def create_table(self):\n partitioning = self._make_partitioning()\n self.table, _ = self.__open_or_create_table(self.table_name, partitioning, drop=True)\n\n def remove_table(self):\n if self.client.table_exists(self.table_name):\n self.client.delete_table(self.table_name)\n self.table = None\n\n def fill_table(self):\n for ts, sensor, value in self._generate_data(self.max_ts):\n op = self.table.new_insert({\"ts\": ts, \"sensor\": sensor, \"value\": value})\n self.session.apply(op)\n pass\n\n self.session.flush()\n pass\n\n @staticmethod\n def sequence_from_file(filename: str) -> List:\n fpath = os.path.join(\"../resources/sample_data\", filename)\n\n lst = []\n with open(fpath, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n for i, (ts_str, value_str) in enumerate(csvreader):\n ts, value = int(ts_str), float(value_str)\n lst.append((ts, value))\n\n return lst\n\n def fill_table_from_seq(self, sequence: List, sensorIds: List[int]):\n self.session.set_flush_mode(flush_mode='manual')\n\n for j, sensorId in enumerate(sensorIds):\n for i, (ts, value) in enumerate(sequence):\n op = self.table.new_insert({\"ts\": ts, \"sensor\": sensorId, \"value\": value})\n self.session.apply(op)\n if i % self.ITEM_TO_WRITE_PER_FLUSH == 0:\n self.session.flush()\n currWrite = j * len(sequence) + i\n allToWrite = len(sensorIds) * len(sequence)\n print(\"Writing {}/{} records\".format(currWrite, allToWrite))\n\n self.session.flush()\n\n self.session.flush()\n\n def look_for_ampl_interval(self, amin, amax):\n sc = self.table.scanner()\n # sc.add_predicate(amin < self.table['ts'] < amax)\n sc.add_predicate(amin < self.table['ts'])\n sc.add_predicate(self.table['ts'] < amax)\n\n tupleResults = sc.open().read_all_tuples()\n\n return tupleResults\n\n def look_for_value(self, amin, amax):\n sc = self.table.scanner()\n # sc.add_predicate(amin < self.table['ts'] < amax)\n sc.add_predicate(amin < self.table['value'])\n sc.add_predicate(self.table['value'] < amax)\n\n tupleResults = sc.open().read_all_tuples()\n\n return tupleResults\n\n def get_all_data(self):\n sc = self.table.scanner()\n tupleResults = sc.open().read_all_tuples()\n return tupleResults\n\n pass\n\n\ndef checkInterval(kuduExample: KuduTimeAndSensorPart):\n kuduExample.obtainAndFillTable()\n\n ainterval = kuduExample.look_for_ampl_interval(-100, 500)\n\n print(\"Count of rows in the table '{}': {}\".format(kuduExample.table_name, len(ainterval)))\n\n for ts, sensor, value in ainterval[:10]:\n print(\"ts {} sensor {} - value {}\".format(ts, sensor, value))\n\n\ndef checkValue(kuduExample: KuduTimeAndSensorPart, lr=(-100, 500)):\n kuduExample.obtainAndFillTable()\n\n amin, amax = lr\n\n start = time.time()\n ainterval = list(kuduExample.look_for_value(amin, amax))\n end = time.time()\n\n print(\"Checking value time: {}\".format(end - start))\n\n print(\"Count of rows for defined values '{}': {}\".format(kuduExample.table_name, len(ainterval)))\n\n for ts, sensor, value in ainterval[:10]:\n print(\"ts {} sensor {} - value {}\".format(ts, sensor, value))\n\n\ndef getAllData(kuduExample: KuduTimeAndSensorPart):\n kuduExample.obtainAndFillTable()\n\n ainterval = kuduExample.get_all_data()\n\n print(\"Count of rows in the table '{}': {}\".format(kuduExample.table_name, len(ainterval)))\n\n for ts, sensor, value in ainterval[:10]:\n print(\"ts {} sensor {} - value {}\".format(ts, sensor, value))\n\n\ndef insertData(kuduExample: KuduTimeAndSensorPart):\n insertMultiData(kuduExample, sensorIds=[1])\n\n\ndef insertMultiData(kuduExample: KuduTimeAndSensorPart, sensorIds: List[int]):\n start = time.time()\n sequence = kuduExample.sequence_from_file(\"sensor-1-2007-2017.csv\")\n # sequence = kuduExample.sequence_from_file(\"tiny-sample-1-1kk.csv\")\n end = time.time()\n print(\"Reading raw data time: {}\".format(end - start))\n\n start = time.time()\n\n kuduExample.obtainTableForFillingWith(sequence, sensorIds=sensorIds)\n # kuduExample.obtainTable(recreate=True)\n # kuduExample.fill_table_from_seq(sequence, sensorId)\n\n end = time.time()\n\n print(\"Inserting time: {}\".format(end - start))\n\n\nif __name__ == \"__main__\":\n cmd = \"check\"\n if len(sys.argv) > 1:\n cmd = sys.argv[1]\n\n kuduExample = KuduTimeAndSensorPart()\n\n if cmd == \"insert\":\n insertMultiData(kuduExample, sensorIds=[i for i in range(1)])\n\n elif cmd == \"check\":\n checkValue(kuduExample, (265, 300))\n\n elif cmd == \"remove\":\n kuduExample.remove_table()\n else:\n print(\"Command is not recognized: {}\".format(cmd))\n sys.exit(-1)\n\n # getAllData(kuduExample)\n # checkInterval(kuduExample)\n pass","sub_path":"python/dstat-kudu/kudu_time_part.py","file_name":"kudu_time_part.py","file_ext":"py","file_size_in_byte":10748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"119308348","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 21 09:01:18 2020\n\n@author: labuser\n\nThis script will load the models and calculate the accuracy for each model\n\"\"\"\n\nimport os\nimport numpy as np\nimport DeepCluster\nfrom sklearn import preprocessing\n\nsignal_path = '/media/labuser/Data/nanopore/pUC19_nanopolish/numpy/'\nmodel_path = '/media/labuser/Data/nanopore/DESPERADO/models/'\nmodels = os.listdir(model_path)\n\nfile_out = '/media/labuser/Data/nanopore/DESPERADO/results/nanopolish_results'\nf = open(file_out, \"w\")\n\nfor model_ in models:\n # load numpy files\n mod_signal = np.load(signal_path+model_.split('.')[0]+'.npy')\n no_mod_signal = np.load(signal_path+'no_'+model_.split('.')[0]+'.npy')\n \n min_max_scaler = preprocessing.MinMaxScaler()\n mod_signal = min_max_scaler.fit_transform(mod_signal)\n no_mod_signal = min_max_scaler.fit_transform(no_mod_signal)\n \n # to load a saved model\n loaded_model = DeepCluster.DeepCluster(signal_shape=(60,1))\n trained_model = loaded_model.fit()\n trained_model.load_weights(model_path+model_)\n \n f.write('Model '+model_+'\\n')\n\n predictions_mod, _ = trained_model.predict(mod_signal[900:].reshape(100,60,1))\n acc = loaded_model.accuracy(np.zeros(100), predictions_mod.argmax(1))\n f.write('Accuracy test 100 modified reads : '+str(acc))\n\n f.write('\\n')\n predictions_mod, _ = trained_model.predict(no_mod_signal[900:].reshape(100,60,1))\n acc = loaded_model.accuracy(np.ones(100), predictions_mod.argmax(1))\n f.write('Accuracy test 100 non-modified reads :'+ str(acc))\n\n f.write('\\n')\n\nf.close()\n\n","sub_path":"scripts/benchmark_nanopolish.py","file_name":"benchmark_nanopolish.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"400125703","text":"import pandas as pd\nimport numpy as np\nimport os\nfrom model_lstm import lstm_mod\nimport datetime\nfrom datetime import datetime as dt\nfrom mk_dt_crard import mon_interval\nfrom scipy.stats.stats import pearsonr\n\n\ndef dt_category(df_in):\n col_list = ['category_1', 'category_4', 'most_recent_purchases_range', 'most_recent_sales_range']\n col_list_l = ['category_1_x', 'category_4', 'most_recent_purchases_range', 'most_recent_sales_range']\n cnt=len(col_list)\n df_in = df_in.astype(str)\n for i in range(cnt):\n col=col_list[i]\n col_l=col_list_l[i]\n fn_cat = 'category_merchant_' + col_list[i] + '.csv'\n df_cat = pd.read_csv(fn_cat, encoding=\"utf8\", sep=',', header=0)\n # df_cat=df_cat.astype(str)\n # print(col_l)\n df_m = pd.merge(df_in, df_cat, how='left', left_on=[col_l], right_on=[col])\n col_category=col+'_category'\n df_in[col_l]=df_m[col_category]\n col_list = ['authorized_flag', 'category_1', 'category_3']\n col_list_l = ['authorized_flag', 'category_1_y', 'category_3']\n cnt=len(col_list)\n for i in range(cnt):\n col=col_list[i]\n col_l=col_list_l[i]\n fn_cat = 'category_transactions_' + col_list[i] + '.csv'\n df_cat = pd.read_csv(fn_cat, encoding=\"utf8\", sep=',', header=0)\n df_m = pd.merge(df_in, df_cat, how='left', left_on=[col_l], right_on=[col])\n col_category=col+'_category'\n df_in[col_l]=df_m[col_category]\n df_in=df_in.fillna(-1)\n return df_in\ndef dt_coer(df_in):\n col_listx = ['category_1_x','category_2_x','state_id_x','city_id_x','subsector_id_x']\n col_listy = ['category_1_y','category_2_y','state_id_y','city_id_y','subsector_id_y']\n cnt=len(col_listx)\n coef=[]\n for i in range(cnt):\n if df_in.shape[0]==1:\n coef.append(0)\n continue\n # coef.append(pearsonr(df_in.loc[:,col_listx[i]], df_in.loc[:,col_listy[i]]))\n df_in.loc[0,col_listx[i]]=df_in.loc[0,col_listx[i]]+ 0.000000001\n df_in.loc[0,col_listy[i]]=df_in.loc[0,col_listy[i]]+ 0.000000002\n coef.append(np.corrcoef(df_in.loc[:,col_listx[i]], df_in.loc[:,col_listy[i]])[0, 1])\n return np.array(coef)\ndef absoluteFilePaths(directory):\n for dirpath,_,filenames in os.walk(directory):\n for f in filenames:\n yield os.path.abspath(os.path.join(dirpath, f))\ndef train():\n path = \"C:/01.work/01.python/998.data/011.rec\"\n os.chdir(path)\n img_train='train/'\n fn_card_list = \"card_id_list_train_f.csv\"\n mod_path = 'model/model_1212'\n #print pearsonr(a,b)\n\n # mod_path = 'mode_lstm_bidirection'\n # mod_path = 'mode_gru_bidirection'\n\n # img_train='train_test2/'\n # fn_card_list = \"card_id_list_train_f_test.csv\"\n\n # fn_train = 'train.csv'\n # df_train = pd.read_csv(fn_train, encoding=\"utf8\", sep=',', header=0)\n df_card_list=pd.read_csv(fn_card_list, encoding=\"utf8\", sep=',', header=0)\n # df_card_list=pd.merge(df_card_list_t,df_train,how='inner',on=['card_id'])\n # df_card_list=pd.merge(df_card_list_t,df_train,how='right',on=['card_id'])\n df_card_list=df_card_list.reset_index(drop=True)\n grp_key=['tans_cnt']\n df_card_grp=df_card_list.groupby(grp_key)\n cnt_grp=len(df_card_grp)\n i=0\n x_dim = 34\n class_num = 1\n lstm = lstm_mod(x_dim, class_num)\n checkpoint = 0\n if os.path.exists(mod_path + '/checkpoint'):\n checkpoint = lstm.restore(mod_path)\n checkpoint = int(checkpoint.split('-')[1])\n if not os.path.exists(mod_path):\n os.mkdir(mod_path)\n i = checkpoint\n # seq_size_last = 20\n cnt_tatal=0\n for dt_i in df_card_grp:\n cnt_tatal=cnt_tatal+1\n oldtime = datetime.datetime.now()\n for loopk in range(100):\n i_cur = 0\n for dt_i in df_card_grp:\n seq_size=dt_i[0]\n # if seq_size 1:\n n=n-1\n else:\n return (n)","sub_path":"backup/user_191/ch34_2020_04_07_18_54_33_925435.py","file_name":"ch34_2020_04_07_18_54_33_925435.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"9285074","text":"import numpy as np\nfrom collections import defaultdict\nimport itertools as it\n\n\n\nclass Featurer:\n def __init__(self, index):\n self.index = index\n self.features = {}\n self.nbFeatures = None\n\n def getFeatures(self, query):\n raise NotImplementedError\n\n def getDocFeatures(self, idDoc, query) -> np.array:\n raise NotImplementedError\n\nclass DocLengthFeaturer(Featurer):\n def __init__(self, index):\n super().__init__(index)\n self.nbFeatures = 1\n\n def getDocFeatures(self, idDoc, query):\n try:\n return self.features[idDoc]\n except KeyError:\n self.features[idDoc] = np.array([sum(self.index.getTfsForDoc(idDoc).values())])\n return self.features[idDoc]\n\nclass QueryLengthFeaturer(Featurer):\n def __init__(self, index, trep):\n super().__init__(index)\n self.nbFeatures = 1\n\n def getDocFeatures(self, idDoc, query):\n try:\n return self.features[query.id]\n except KeyError:\n self.features[query.id] = np.array([sum(query.trep.values())])\n return self.features[query.id]\n\nclass FeaturerModel(Featurer):\n def __init__(self, index, model, trep):\n super().__init__(index)\n self.model = model\n assert self.model.index == self.index\n self.nbFeatures = 1\n\n def getDocFeatures(self, idDoc, query):\n try:\n return np.array([self.model.getScore(idDoc, query)])\n except KeyError:\n return np.array([0])\n\n def getFeatures(self, query):\n if query.id in self.features:\n return self.features[query.id]\n else:\n self.features[query.id] = scores = {str(k): [v] for k, v in self.model.getScores(query).items()}\n return scores\n\nclass FeaturersList(Featurer):\n def __init__(self, index, featurers):\n super().__init__(index)\n self.featurers = featurers\n self.nbFeatures = sum(f.nbFeatures for f in featurers)\n\n def getDocFeatures(self, idDoc, query):\n f = np.hstack((f.getDocFeatures(idDoc, query) for f in self.featurers))\n return f/f.sum()\n\n def getFeatures(self, query):\n all_features = defaultdict(list)\n all_size = 0\n for featurer in self.featurers:\n try:\n features = featurer.getFeatures(query)\n except NotImplementedError:\n features = {idDoc:featurer.getDocFeatures(str(idDoc), query) for idDoc in all_features.keys()}\n size = featurer.nbFeatures\n for key in features.keys() & all_features.keys():\n all_features[key].extend(features[key])\n for key in all_features.keys() - features:\n all_features[key].extend([0] * size)\n for key in features.keys() - all_features.keys():\n all_features[key] = ([0] * all_size) + features[key]\n all_size += size\n return dict(all_features)\n\n\nclass IRmodel:\n def __init__(self, index):\n self.index = index\n\n def getScore(self, idDoc, query):\n raise NotImplementedError\n\n def getScores(self, query):\n raise NotImplementedError\n\n def getRanking(self, query):\n score = self.getScores(query)\n return sorted(score.items(), key=lambda x: (x[1], np.random.rand()), reverse=True)\n\nclass MetaModel(IRmodel):\n def __init__(self, index, featurers, trep, lr=0.05, lbda=0.1):\n super().__init__(index)\n self.featurers = FeaturersList(index, featurers)\n self.weights = None\n self.trep = trep\n self.lr = lr\n self.lbda = lbda\n\n def getDocScore(self, idDoc, query):\n features = np.array(self.featurers.getDocFeatures(idDoc, query))\n return (features/features.sum()) @ (self.weights)\n\n def getScores(self, query):\n features = self.featurers.getFeatures(query)\n data = np.vstack(features.values())\n scores = data @ (self.weights * (data.sum(axis=0)**-1))\n return {k: score for k, score in zip(features, scores)}\n\n def learn_weights(self, queries, niter):\n self.weights = np.ones(self.featurers.nbFeatures)/self.featurers.nbFeatures\n\n for i in range(niter):\n print(\"Iteration numéro \", i)\n\n query = np.random.choice(queries)\n # print(\"query n°\", query.id)\n # print(query.relevants)\n\n d_pert = str(int(np.random.choice(list(query.relevants))))\n d_npert = str(np.random.choice(len(self.index.docs)))\n while d_npert in query.relevants:\n d_npert = str(np.random.choice(len(self.index.docs)))\n # print(\"d_pert \", d_pert, \"d_npert\", d_npert)\n\n f_pert = self.getDocScore(d_pert, query)\n f_npert = self.getDocScore(d_npert, query)\n\n if 1 - f_pert > f_npert:\n # print(self.featurers.getDocFeatures(d_pert, query), self.featurers.getDocFeatures(d_npert, query))\n self.weights += self.lr * (self.featurers.getDocFeatures(d_pert, query) - self.featurers.getDocFeatures(d_npert, query))\n\n self.weights *= (1-2*self.lr*self.lbda)\n\n\nif __name__ == '__main__':\n from ParserCACM import ParserCACM\n from TextRepresenter import PorterStemmer\n from Index import Index\n from evaluationTest import QueryParserCACM, split_train_test\n\n corpus_file = 'cacm/cacm.txt'\n queries_file = 'cacm/cacm.qry'\n relations_file = 'cacm/cacm.rel'\n\n #Index loading\n trep = PorterStemmer()\n index = Index.from_file(\"index_cacm.pkl\", ParserCACM, corpus_file, PorterStemmer())\n\n #queries reading and processing\n queryParser = QueryParserCACM(queries_file, relations_file, trep=trep)\n synthetic_query = {'algebra': 1, 'sun': 2, 'cat': 1}\n\n queries = [q for q in iter(queryParser.nextQuery, None) if q.relevants]\n q = queries[0]\n q_train, q_test = split_train_test(queries, 0.8)\n\n from Okapi import Okapi\n #from RandomWalk import PageRank\n from weighter import Vectoriel, Weighter4\n\n model1 = Okapi(index)\n #model2 = PageRank(index, model1, nbLinksIn=3, nbSeeds=20)\n model3 = Vectoriel(normalised=True, weighter=Weighter4(index))\n\n f1 = DocLengthFeaturer(index)\n f2 = QueryLengthFeaturer(index, trep)\n fmodel1 = FeaturerModel(index, model1, trep)\n #fmodel2 = FeaturerModel(index, model2, trep)\n fmodel3 = FeaturerModel(index, model3, trep)\n\n metamodel = MetaModel(index, [fmodel1, fmodel3, f1, f2], trep=trep)\n metamodel.learn_weights(queries, 100)\n\n from evaluationTest import EvalIRModel, PrecisionMoyenne, PrecisionRappel\n ev = PrecisionRappel(nb_levels=10)\n evalmodel = EvalIRModel([metamodel], measures=[ev, PrecisionMoyenne()],trep=trep)\n # res1 = evalmodel.eval(q_train)\n # res2 = evalmodel.eval(q_test)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"555333245","text":"import sys\nimport pandas as pd\nfrom sqlalchemy import create_engine\nimport sqlite3\nimport nltk\nnltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger'])\n\nimport re\nimport numpy as np\nimport pandas as pd\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import WordNetLemmatizer\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.metrics import classification_report\n\ndef load_data(database_filepath):\n \"\"\"Load data from database file\n Input: database filepath\n Output: data split into X, Y and categories for training later.\n - X: training data with message column only\n - Y: 36 categories\n - category_names = column name of Y\"\"\"\n # load data from database\n con = sqlite3.connect(database_filepath)\n df = pd.read_sql(sql = 'select * from InsertTableName', con = con)\n df.dropna(axis = 0, inplace = True)\n X = df['message']\n Y = df.iloc[:, 4:]\n category_names = Y.columns\n return X, Y, category_names\n\n\ndef tokenize(text):\n \"\"\"Clean and tokenize the text in messages.\n Input:\n - Text in X\n Output:\n - Cleaned tokens\"\"\"\n url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n detected_urls = re.findall(url_regex, text)\n for url in detected_urls:\n text = text.replace(url, \"urlplaceholder\")\n\n tokens = word_tokenize(text)\n lemmatizer = WordNetLemmatizer()\n\n clean_tokens = []\n for tok in tokens:\n clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n clean_tokens.append(clean_tok)\n\n return clean_tokens\n\n\ndef build_model():\n \"\"\"Build model with pipeline and grid search.\n Input:\n None\n Content:\n - Model pipeline with 2 transformer and 1 classifier\n - parameters for grid search\n Output:\n grid search on pipeline\"\"\"\n pipeline = Pipeline([\n ('vect', CountVectorizer(tokenizer=tokenize)),\n ('tfidf', TfidfTransformer()),\n ('clf', MultiOutputClassifier(RandomForestClassifier()))\n ])\n\n parameters = {\n 'vect__ngram_range': ((1, 1), (1, 2)),\n 'vect__max_df': (0.5, 0.75, 1.0),\n 'vect__max_features': (None, 5000),\n 'tfidf__use_idf': (True, False)\n }\n\n cv = GridSearchCV(pipeline, param_grid=parameters)\n return cv\n\n\ndef evaluate_model(model, X_test, Y_test, category_names):\n \"\"\"Using classification_report to evalute the model\"\"\"\n y_pred = model.predict(X_test)\n reports = []\n for i in range(36):\n reports.append(classification_report(y_test.values[:, i], y_pred[:, i], target_names=Y.columns))\n return reports\n\n\ndef save_model(model, model_filepath):\n \"\"\"Output the model into pickle file\"\"\"\n pickle.dump(model, open(model_filepath, 'wb'))\n\n\ndef main():\n if len(sys.argv) == 3:\n database_filepath, model_filepath = sys.argv[1:]\n print('Loading data...\\n DATABASE: {}'.format(database_filepath))\n X, Y, category_names = load_data(database_filepath)\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)\n\n print('Building model...')\n model = build_model()\n\n print('Training model...')\n model.fit(X_train, Y_train)\n\n print('Evaluating model...')\n evaluate_model(model, X_test, Y_test, category_names)\n\n print('Saving model...\\n MODEL: {}'.format(model_filepath))\n save_model(model, model_filepath)\n\n print('Trained model saved!')\n\n else:\n print('Please provide the filepath of the disaster messages database '\\\n 'as the first argument and the filepath of the pickle file to '\\\n 'save the model to as the second argument. \\n\\nExample: python '\\\n 'train_classifier.py ../data/DisasterResponse.db classifier.pkl')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Testing_Files/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"36942656","text":"import os\nimport fresh_tomatoes\nimport media\n\n# find absolute path to csv\npath_to_file = os.path.join(os.path.dirname(__file__), 'my-favourite-movies.csv') # noqa\n\n# Create a list of dictionaries from the csv file containing my\n# favrouite movie data. The values in the top row of the csv\n# become the keys in each dict, in this case: 'title', 'year',\n# 'summary', 'yw-thoughts', 'poster', 'trailer'.\nmy_movies_data = media.csv_dict_list(path_to_file)\n\n\ndef create_list_of_movies(list_of_movies):\n \"\"\" Create a list of movie instances using the class `Movie`.\n\n Using a function and constructor from media.py, this function\n takes the list of dictionaries generated by `csv_dict_list`\n as its argument. It then loops through each dictionary and\n contructs instrances of the class `Movie` using the dict\n values of 'title', 'year', 'summary', 'yw-thoughts', 'poster',\n 'trailer' as the class arguments.\n\n Args:\n list_of_movies: A list of dictionaries containing\n data about movies. The keys in each dictionary are:\n 'title', 'year', 'summary', 'yw-thoughts',\n 'poster', 'trailer'.\n\n Returns:\n A list of instances of the class `Movie` where the\n arguments for each instance of `Movie` are set by\n the key value pairs in the list of dictionaries.\n For example:\n\n [\n movie1 = media.Movie(\"Jackie Brown\", \"1997\",\n \"A kick-ass lady outwits the dudes.\",\n \"Awesome movie, thumbs up!\",\n \"https://goo.gl/4yna4o\",\n \"https://youtu.be/J9Bd4ShuEAw\"),\n movie2 = media.Movie(\"Princess Mononoke\", \"1999\",\n \"A battle between several faction in magical\n woods.\",\n \"This movie is beautiful.\",\n \"https://goo.gl/sERJr1\",\n \"https://youtu.be/YOuG8m2RqOs\")\n ]\n \"\"\"\n movie_list = []\n\n # Loop through list of dictionaries\n for movie in list_of_movies:\n # Instantiate the class `Movie` using the dict values as\n # its arguments\n my_movie = media.Movie(\n (movie['title']),\n (movie['year']),\n (movie['summary']),\n (movie['yw-thoughts']),\n (movie['poster']),\n (movie['trailer'])\n )\n # Add the new `Movie` object to movie_list\n movie_list.append(my_movie)\n return movie_list\n\n# Create a list of instances of the class `Movie` using data\n# from csv file\nmovies = create_list_of_movies(my_movies_data)\n\n# Generate and open HTML webpage, using content from `Movie` objects\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"entertainment_centre.py","file_name":"entertainment_centre.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"472624757","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Apr 6 19:19:42 2019\r\n\r\n@author: yuichiro\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\ndef start():#盤の初期配置を返す\r\n board = np.zeros((6,6))\r\n board[2][2]=1\r\n board[3][3]=1\r\n board[2][3]=2\r\n board[3][2]=2\r\n return board\r\n\r\n\r\ndef move(num,myplace):\r\n lst=myplace\r\n if num==1:\r\n ls = [lst[0],lst[1]-1]\r\n elif num==2:\r\n ls = [lst[0]-1,lst[1]-1]\r\n elif num==3:\r\n ls = [lst[0]-1,lst[1]]\r\n elif num==4:\r\n ls = [lst[0]-1,lst[1]+1]\r\n elif num==5:\r\n ls = [lst[0],lst[1]+1]\r\n elif num==6:\r\n ls = [lst[0]+1,lst[1]+1]\r\n elif num==7:\r\n ls = [lst[0]+1,lst[1]]\r\n elif num==8:\r\n ls = [lst[0]+1,lst[1]-1]#lst[]を別の文字で置いてからやったほうがよかった\r\n \r\n \r\n if onboard(ls)==0:#盤から出るとき\r\n ls=[-1,-1]\r\n \r\n return ls\r\n##########################################################################\r\ndef onboard(ls):\r\n a=1\r\n if ls[0]<0 or ls[0]>5 or ls[1]<0 or ls[1]>5:#盤から出るとき\r\n a=0\r\n return a\r\n##########################################################################\r\ndef search(num,lst,board):\r\n a=list(range(1,9))#方向を定めるリスト\r\n myplace=lst#置いた石の座標\r\n lst=[]#返すリスト\r\n \r\n if num==1:#stone:置いた石と逆の色の石\r\n stone=2\r\n elif num==2:\r\n stone=1\r\n \r\n for i in a:#すべての方向において隣の石が何かを確認\r\n ls=move(i,myplace)\r\n if onboard(ls)==1:#移動方向が盤上\r\n a=ls[0]\r\n b=ls[1]\r\n if board[a][b]==stone:#隣の石が自分と違う色であるとき、その方向を返す\r\n lst.append(i)\r\n \r\n return lst#おいてはいけない場所の時は空になる\r\n#########################################################################\r\ndef search2(num,myplace,lst,board):\r\n if num==1:#stone:置いた石と逆の色の石\r\n stone=2\r\n elif num==2:\r\n stone=1\r\n ls=[]#返すリスト\r\n ls3=[]#移動先の座標を格納\r\n \r\n for i in lst:\r\n my=myplace\r\n num2=0\r\n ls2=[]#仮置きりスト(可能性のある座標を仮置きして、挟まれていたらlsに追加)\r\n while num2==0:#自分と同じ色の石が出てくるか、石がなくなるか、盤から出ない限りループ\r\n ls3=move(i,my)#移動先の座標\r\n if onboard(ls3)==1:\r\n if board[ls3[0]][ls3[1]]==stone:#移動先が自分と違う色の石\r\n ls2.append(ls3)\r\n elif board[ls3[0]][ls3[1]]==num:#移動先が自分と同じ色の石、searchより少なくとも一つの石はひっくり返せる\r\n ls.extend(ls2)\r\n num2=1\r\n elif board[ls3[0]][ls3[1]]==0:#移動した先に自分の石がなかった\r\n num2=1\r\n else:\r\n num2=1\r\n my=ls3\r\n return ls\r\n###################################################################################\r\ndef reverse(num,myplace,lst,board):\r\n ln=len(lst)#lstの要素数を調べる(len([[1,2],[3,4]])=2となる)\r\n \r\n for i in range(ln):\r\n y=lst[i][0]\r\n x=lst[i][1]\r\n \r\n board[y][x]=num#石をひっくり返す\r\n if i==0:\r\n board[myplace[0]][myplace[1]]=num\r\n return board\r\n####################################################################################\r\ndef testboard(board):\r\n for i in [1,2]:\r\n board[i][3]=1\r\n return board\r\n##################################################################################\r\ndef putstone(board):\r\n ok=0#置く場所が盤上:1 盤外:0\r\n while ok==0:\r\n a = input(\"石の座標を入力 x,y :\")#str型\r\n \r\n b=a.split(\",\")\r\n ytemp=b[1]\r\n xtemp=b[0]\r\n \r\n y=int(ytemp)\r\n x=int(xtemp)\r\n \r\n list=[y,x]\r\n \r\n if board[y][x]!=0:\r\n print(\"すでに石が置かれているのでその場所に置くことはできません\")\r\n continue\r\n \r\n if onboard(list)==1:\r\n ok=1\r\n elif onboard(list)==0:\r\n print(\"その場所に置くことはできません\")\r\n continue\r\n return list\r\n####################################################################################\r\ndef turn(num,board):\r\n startboard=board#初期盤面\r\n ok=1\r\n while ok==1:#ひっくり返せる石がなかった時に戻るためのループ\r\n place=putstone(startboard)#place:石を置いた場所\r\n maymove=search(num,place,startboard)\r\n turnplace=search2(num,place,maymove,startboard)\r\n if len(turnplace)==0:#ひっくり返す石がない\r\n print(\"その場所に置くことはできません\")\r\n continue\r\n newboard=reverse(num,place,turnplace,startboard)\r\n ok=2\r\n return newboard\r\n####################################################################################\r\n####################################################################################\r\n#def log():#待ったができるように、盤面の推移を記録する\r\n###################################################################################\r\ndef judge(num,board):\r\n a=2#a:1置く場所発見\r\n \r\n for i in range(6):\r\n for j in range(6):\r\n if board[i][j]==0:#いずれの石も置かれていないとき、その場所に石が置けるか判定\r\n place=[i,j]\r\n #print(place)\r\n maymove=search(num,place,board)\r\n turnplace=search2(num,place,maymove,board)\r\n if len(turnplace)!=0:#ひっくり返せる石があった\r\n a=1\r\n break\r\n if a==1:\r\n break\r\n return a\r\n####################################################################################\r\ndef Game():\r\n board = start()\r\n \r\n num=1\r\n play=1\r\n while play==1:\r\n print(board)\r\n print(num,\"の番です\")\r\n board=turn(num,board)\r\n \r\n if num==1:#nextnum:置いた石と逆の色の石\r\n nextnum=2\r\n elif num==2:\r\n nextnum=1\r\n \r\n if judge(nextnum,board)==1:\r\n num = nextnum\r\n continue\r\n elif judge(num,board)==1:\r\n continue\r\n else:\r\n play=0\r\n \r\n return board\r\n###############################################################################\r\ndef result(board):\r\n bnum=0\r\n wnum=0\r\n \r\n print(board)\r\n \r\n for i in range(6):\r\n for j in range(6):\r\n if board[i][j]==1:\r\n bnum+=1\r\n elif board[i][j]==2:\r\n wnum+=1\r\n \r\n print(\"黒:\",bnum,\"白:\",wnum)\r\n \r\n if bnum>wnum:\r\n print(\"黒の勝ち\")\r\n elif bnum= 1.0 and time <=150.0:\r\n return 100.0\r\n else:\r\n return 100.0\r\n\t\t\r\n\r\nmodel = ThermalModel()\r\n\r\n\r\n\r\nmodel.addNode(Node(1, m_Al*C_AL, 4, power_PHEATER, 'Placa 1'))\r\n\r\nmodel.addNode(Node(2, m_Al*C_AL, 4, lambda x: 0.0, 'Placa 2'))\r\n\r\nmodel.addNode(Node(3,mdisco*C_TFL,4,lambda x: 0.0, 'Disco'))\r\n\r\nmodel.addNode(Node(-4, 1.0, 4, lambda x: 0.0, 'Espacio'))\r\n\r\n\r\n#HEADER CONDUCTOR DATA\r\n\r\nmodel.addConductance(2, 3, 5.41)\r\n\r\nmodel.addAdmittance(1, 2, 650*F) #Placa 1 [cm^2] SIGMA = 5.67e-12 Stefan-Boltzmann constant in w/cm^2xK^4\r\nmodel.addAdmittance(1, -4, 650.0*(1-F)) #Placa 2[cm^2]\r\nmodel.addAdmittance(2, -4, (650.0-50)*(1-F)) #Espacio [cm^2]\r\n\r\n\r\nsolver = FDMExplicit(model,0.01)\r\nsolver.solve(t_start, t_end)\t\r\n\r\n#*******************************************************************************\r\n# Calculo del Tiempo \r\n\r\nfinal = datetime.datetime.now()\r\n\r\nDiferencia = final - inicio\r\nprint(\" \")\r\nprint(\"Tiempo de Procesamiento:\")\r\nprint (Diferencia.total_seconds())\r\n\r\n\r\n#------------------------------CREAR VENTANA---------------------------------\r\nroot = tkinter.Tk()\r\nroot.wm_title(\"Análisis y Diseño Térmico\")\r\n\r\n\r\n#------------------------------CREAR GRAFICA---------------------------------\r\nfig = Figure(figsize=(5, 5), dpi=100)\r\n\r\n\r\n\r\n\r\nfig.add_subplot(111).plot((solver.t)/3600,solver.T[0]-273, linestyle='--', color='blue', label=\"PLACA 1\")\r\nfig.add_subplot(111).plot((solver.t)/3600,solver.T[1]-273, linestyle='-', color='green', label=\"PLACA 2\")\r\n\r\nfig.add_subplot(111).plot((solver.t)/3600,solver.T[2]-273, linestyle='--', color='RED', label=\"DISCO\")\r\n\r\n\r\n\r\n# \r\n# #GRAFICA IMAGENES\r\n# \r\nfig.suptitle(\"PLACAS PARALELAS (Al) disco(TFL)=3mm\", fontsize=14)\r\nfig.add_subplot(111).set_xlabel('Tiempo [h]')\r\nfig.add_subplot(111).set_ylabel('Temperatura [C]')\r\nfig.add_subplot(111).grid(linestyle='--', linewidth=0.9, alpha=0.5)\r\nfig.add_subplot(111).legend(loc=6, bbox_to_anchor=(1.0,0.9))\r\n\r\n\r\ncanvas = FigureCanvasTkAgg(fig, master=root) # CREAR AREA DE DIBUJO DE TKINTER.\r\ncanvas.draw()\r\ncanvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)\r\n\r\n#-----------------------AÑADIR BARRA DE HERRAMIENTAS--------------------------\r\ntoolbar = NavigationToolbar2Tk(canvas, root)# barra de iconos\r\ntoolbar.update()\r\ncanvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)\r\n\r\n#-----------------------------BOTÓN \"cerrar\"----------------------------------\r\ndef cerrar():\r\n root.quit() \r\n root.destroy()\r\n\r\nbutton = tkinter.Button(master=root, text=\"cerrar\", command=cerrar)\r\nbutton.pack(side=tkinter.BOTTOM)\r\n\r\ntkinter.mainloop()\r\n\r\n\r\n\r\n","sub_path":"Dos placas paralelas con disco_ teflon.py","file_name":"Dos placas paralelas con disco_ teflon.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"507486245","text":"import pandas as pd\n\ntrainingSet = pd.read_csv(\"./data/train.csv\")\ntestingSet = pd.read_csv(\"./data/test.csv\")\n\nX_test = pd.merge(trainingSet, testingSet, left_on='Id', right_on='Id')\nprint(X_test.columns)\n\nX_test = X_test.drop(columns=['Score_x'])\nX_test = X_test.rename(columns={'Score_y': 'Score'})\n\nprint(X_test.columns)\nX_test.to_csv(\"./data/X_submission.csv\", index=False)\n\nX_train = trainingSet[trainingSet['Score'].notnull()]\nprint(trainingSet.shape)\nprint(X_train.shape)\nX_train.to_csv(\"./data/X_train.csv\", index=False)\n","sub_path":"08-midterm/starter-code/generate-Xtrain-Xsubmission.py","file_name":"generate-Xtrain-Xsubmission.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"380325575","text":"import pygame as pg\n\n\nclass Packet:\n def __init__(self, source, dest, vector, time):\n self.packet = dict()\n self.packet[\"source\"] = source\n self.packet[\"dest\"] = dest\n new_vector = vector.copy()\n\n # split horizon\n for i in range(len(source.hops)):\n if source.hops[i] == dest.id:\n new_vector[i] = 49 # Poison reverse\n\n self.packet[\"vector\"] = new_vector\n self.packet[\"query\"] = False\n\n self.source = source\n\n self.start_time = time\n\n self.time = source.links[dest]\n\n self.speed = [(dest.x - source.x) / self.time, (dest.y - source.y) / self.time]\n\n def draw(self, screen, time, size):\n pg.draw.circle(\n screen,\n self.source.color,\n (\n self.source.x + self.speed[0] * (time - self.start_time),\n self.source.y + self.speed[1] * (time - self.start_time),\n ),\n size,\n size,\n )\n pg.draw.circle(\n screen,\n (255, 255, 255),\n (\n self.source.x + self.speed[0] * (time - self.start_time),\n self.source.y + self.speed[1] * (time - self.start_time),\n ),\n size,\n size // 4,\n )\n","sub_path":"DUAL/Inactive/Packet.py","file_name":"Packet.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"433900540","text":"import cv2\nimport os\nimport dlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\nfrom skimage import io\n\nsubjects = [\"Elvina\", \"Mary\", \"Kostya\", \"Asie\", \"Alex Ch\", \"Kate\", \"Nastya\",\n \"Sergey\", \"Alina\", \"Alex P\", \"Alex B\", \"Riza\", \"Denis\", \"Vlad\", \"Daniil\"]\n\n# file = open('train.csv', 'w')\n# face_features = csv.writer(file)\n\n# files with models\nsp = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')\nfacerec = dlib.face_recognition_model_v1('dlib_face_recognition_resnet_model_v1.dat')\ndetector = dlib.get_frontal_face_detector()\n\n\ndef prepare_training_data(data_folder_path):\n\n # get the directories (one directory for each subject) in data folder\n dirs = os.listdir(data_folder_path)\n face_features = []\n cnt = 0\n # let's go through each directory and read images within it\n for dir_name in dirs:\n\n # our subject directories start with letter 's' so\n # ignore any non-relevant directories if any\n if not dir_name.startswith(\"s\"):\n continue\n\n # build path of directory containin images for current subject subject\n # sample subject_dir_path = \"training-data/s1\"\n subject_dir_path = data_folder_path + \"/\" + dir_name\n\n # get the images names that are inside the given subject directory\n subject_images_names = os.listdir(subject_dir_path)\n label = int(dir_name[1:len(dir_name)])\n # go through each image name, read image,\n # detect face and add face to list of faces\n for image_name in subject_images_names:\n # ignore system files like .DS_Store\n if image_name.startswith(\".\"):\n continue\n\n # build image path\n # sample image path = training-data/s1/1.pgm\n image_path = subject_dir_path + \"/\" + image_name\n\n # read image\n img = io.imread(image_path)\n face = detector(img, 2)\n\n # we will ignore faces that are not detected\n if face is not None:\n for d in face:\n print(\"Detection for {}: Left: {} Top: {} Right: {} Bottom: {}\".format(\n subjects[label], d.left(), d.top(), d.right(), d.bottom()))\n shape = sp(img, d)\n\n # take descriptor\n face_descriptor1 = facerec.compute_face_descriptor(img, shape)\n face_descriptor1 = np.array(face_descriptor1)\n\n face_features.append([])\n for j, val in enumerate(face_descriptor1):\n face_features[cnt].append(face_descriptor1[j])\n\n # last cell is for label\n face_features[cnt].append(label)\n print(face_features[cnt])\n cnt = cnt+1\n\n # break\n\n np.savetxt(\"train_full.csv\", face_features, delimiter=\",\")\n\n\nprint(\"Preparing data...\")\nprepare_training_data(\"train\")\nprint(\"Data prepared\")","sub_path":"faceDetection/dlib/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"300083197","text":"import boto3\nimport pandas as pd\nfrom src.utilities.redshift_access import make_rs_engine\n\ndb_user = 'rs_admin'\ncluster_id = 'mycluster'\ndb_name = 'test'\n\nrs_client = boto3.client('redshift')\n\nresponse = rs_client.describe_clusters(ClusterIdentifier=cluster_id)\nprint(response)\nclusters = response['Clusters']\n\none_cluster = next(item for item in clusters if (item['ClusterIdentifier'] == cluster_id and item['DBName']==db_name))\n\nendpoint = one_cluster['Endpoint']['Address']\nport = one_cluster['Endpoint']['Port']\n\nengine = make_rs_engine(username=db_user, db_name=db_name, db_host=endpoint, db_port=port, cluster_id=cluster_id)\n\nwith engine.connect() as conn, conn.begin():\n response = pd.read_sql('SELECT CURRENT_DATE', con=conn)\n print(response)","sub_path":"test_stuff.py","file_name":"test_stuff.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"77919175","text":"class Solution:\n # @param A : tuple of integers\n # @return an integer\n \n # O(M*N) time\n # - where N == len(nums)\n # - where M is the bit width of num in nums\n #\n # O(M) extra space\n def hammingDistance(self, nums):\n \n MOD = 1000000007\n BIT_WIDTH = 32\n \n \n num_zeros = [0]*BIT_WIDTH\n num_ones = [0]*BIT_WIDTH\n \n for num in nums:\n \n for i in range(BIT_WIDTH):\n \n mask = 1 << i\n \n bit_is_set_at_pos_i = (num & mask) > 0\n \n if bit_is_set_at_pos_i:\n num_ones[i] += 1\n else:\n num_zeros[i] += 1\n \n result = 0\n for i in range(BIT_WIDTH):\n result += (num_ones[i]*num_zeros[i] % MOD)\n \n return (result << 1) % MOD\n \n \n # O(M*N**2)\n # - where N == len(nums)\n # - where M == bitlength of num in nums\n def hammingDistance_slow(self, nums):\n \n MOD = 1000000007\n \n N = len(nums)\n \n sum_o_hamming_dists = 0\n \n for i in range(N):\n \n x = nums[i]\n \n for j in range(i+1, N):\n \n y = nums[j]\n \n sum_o_hamming_dists = (sum_o_hamming_dists + self.d(x,y)) % MOD\n \n return (sum_o_hamming_dists << 1) % MOD\n \n def d(self, x, y):\n \n diff = x^y\n \n return self.count_ones(diff)\n \n # O(answer)\n # worst case O(M) where M is the bitlength of diff\n def count_ones(self, diff):\n \n count = 0\n while diff:\n diff = (diff & (diff-1))\n count += 1\n return count\n\n# d(x,x) == 0\n# d(x,y) == d(y,x)","sub_path":"interviewbit.com/Math/sum_of_pairwise_hamming_distances.py","file_name":"sum_of_pairwise_hamming_distances.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"437363310","text":"import socket\nimport os\nimport signal\n\n'''\n使用信号处理僵尸进程\n'''\n\ndef signal_handler(num, frame):\n print(num, frame)\n while not (os.waitpid(-1, os.WNOHANG)):\n return\n\n# 注册僵尸进程信号处理\nsignal.signal(signal.SIGCHLD, signal_handler)\n\n# 某些会阻塞的系统调用会被在信号处理程序返回后被中断,这里处于各个平台的兼容性考虑,我们手动重启被中断的系统调用\nsignal.siginterrupt(signal.SIGCHLD, False)\n\n\nserSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserSock.bind((\"\", 8888))\nserSock.listen()\n\nwhile True:\n conn, addr = serSock.accept()\n pid = os.fork()\n if pid:\n conn.close()\n continue\n elif pid == 0:\n serSock.close()\n data = conn.recv(1024)\n conn.sendall(b\"echo: \" + data)\n conn.close()\n","sub_path":"python/media/处理僵尸进程.py","file_name":"处理僵尸进程.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"243457718","text":"class Solution:\n # @return a list of lists of integers\n def combine(self, n, k):\n if k > n or k == 0:\n return []\n return self.helper([i+1 for i in range(n)], k)\n\n def helper(self, N, k):\n if k == 0:\n return [[]]\n ret = []\n for i in range(len(N)-k+1):\n for c in self.helper(N[i+1:], k-1):\n ret.append([N[i]]+c)\n return ret\n","sub_path":"leetcode/combinations.py","file_name":"combinations.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"51920182","text":"'''\nFile name: juhuasuan.py\nPurpose: Crawl \"油烟机\" data from Taobao Juhuasuan. \nAuthor: Patrick Zhang(Patrick.zhang@bda.com)\nPython: Python 3.5\nHistory:\n 2015.09.19 Patrick Zhang write comments in this format\n'''\nfrom urllib.request import urlopen\nfrom datetime import date\nfrom lxml import html\nimport requests\nimport re\n\n# 聚划��品牌团URLmvURLMap\nHOME_URL = \"https://ju.taobao.com/tg/brand.htm\"\n# 需要抓取的品牌\nBRAND_SET = set([\"老板\", \"方太\", \"华帝\", \"西门子\", \"美的\"])\n# 首页“数码家电”AJAX_URL前缀\nFLOOR_AJAX_URL = (\"https://ju.taobao.com/json/tg/ajaxGetBrandsV2.json?page=1\"\n \"&_ksTS=1442828690619_396&page=1&btypes=1,2&showType=0&frontCatIds=\")\n# 商品详情页“已售”异步请求URL\nSOLD_URL = \"https://dskip.ju.taobao.com/detail/json/item_dynamic.htm?item_id={0}&id={1}\"\nTODAY = date.today()\n\ndef __open_url__(url):\n '''\n 私有方法\n '''\n try:\n response = requests.get(url)\n # print(\"结果串:\", requests.get(url).text)\n return response\n except Exception as ex:\n print(ex)\n\ndef get_home():\n '''\n 访问首页,获取sidebar中“数码家电”对应的AJAX_URL\n '''\n raw_html = __open_url__(HOME_URL).text\n tree = html.fromstring(raw_html)\n # existance = tree.xpath(\"//div[@id='J_FixedNav']/ul/li/a/span/text()='数码家电'\")\n floor_id = tree.xpath(\"//div[@id='J_FixedNav']/ul/li/a[span/text()='数码家电']/@href\")\n if floor_id:\n get_brand(floor_id[0][1:])\n else:\n print(\"{0} there is no '数码家电' Channel.\".format(TODAY))\n\ndef get_brand(floor_id):\n '''\n 找到每一个品牌对应的URL\n '''\n brand_json = __open_url__(FLOOR_AJAX_URL + floor_id).json()\n # 有可能一个品牌对应多个活动链接\n brand_dict = {}\n for brand in brand_json[\"brandList\"]:\n brand_name = brand[\"baseInfo\"][\"brandName\"]\n if \"/\" in brand_name:\n brand_name = brand_name.split(\"/\")[1]\n if brand_name in BRAND_SET:\n if brand_name in brand_dict:\n brand_dict[brand_name].add(\"https:\" + brand[\"baseInfo\"][\"activityUrl\"])\n else:\n brand_dict[brand_name] = set([\"https:\" + brand[\"baseInfo\"][\"activityUrl\"]])\n if brand_dict:\n for key, value in brand_dict.items():\n for activity_url in value:\n get_item_info(key, activity_url)\n else:\n print(\"{0} there is no required brands('老板', '方太', '华帝', '西门子', '美的')\".format(TODAY))\n\ndef get_item_info(brand, activity_url):\n tree = html.fromstring(__open_url__(activity_url).text)\n item_set = set()\n # category dict: item_url > category\n category_dict = {}\n # 商品楼层除了第一层,其他是异步加载的,所以需要一层一层的找\n # 第一层\n floor_1st_title = tree.xpath(\"//div[@id='content']//div[@id='floor1']//div[@class='l-f-tbox']/text()\")[0]\n floor_1st = tree.xpath(\"//div[@id='content']//div[@class='ju-itemlist']//li/a/@href\")\n for item_url in floor_1st:\n item_set.add(\"https:\" + item_url)\n category_dict[\"https:\" + item_url] = floor_1st_title\n # 从第二层开始,先找每一层url,再找每一层items\n floors = tree.xpath(\"//div[@id='content']//div[contains(@class, 'J_ItemList')]//@data-url\")\n for index, item_url in enumerate(floors):\n # 返回的json串是非规则的,不能直接解析\n json_str = __open_url__(\"https:\" + item_url).text\n prog = re.compile(\"a href=\\\"([^,]*?)\\\"\")\n match = prog.findall(json_str)\n floor_title = tree.xpath(\"//div[@id='floor\" + str(index + 2) \n + \"']//div[@class='l-f-tbox']/text()\")[0]\n for suffix in match:\n item_url = \"https:\" + suffix\n item_set.add(item_url)\n category_dict[item_url] = floor_title\n\n #######################ITEM ID收集完毕##########################\n with open(\"D:/juhuasuan_\" + str(TODAY) + \".txt\", \"a\", encoding=\"utf8\") as a_file:\n for item_url in item_set:\n print(item_url)\n product_tree = html.fromstring(__open_url__(item_url).text)\n properties = product_tree.xpath(\"//div[contains(@class, 'J_mainBox')]\")\n # title\n title = str(product_tree.xpath(\"//div[contains(@class, 'J_mainBox')]/h2/text()\")[0]).strip()\n # Tag\n tag = product_tree.xpath(\"//div[contains(@class, 'J_mainBox')]/div[@class='biztag ']/label/text()\")\n # 价格\n current_price = str(product_tree.xpath(\"//div[contains(@class, 'J_mainBox')]//div[@class='currentPrice']/small/following-sibling::text()\")[0]).strip()\n # 原价\n original_price = product_tree.xpath(\"//div[contains(@class, 'J_mainBox')]//*[@class='originPrice']/text()\")[0]\n # 店铺URL\n shop_url = \"https:\" + product_tree.xpath(\"//div[@id='detail-left']//a[@class='sellername']/@href\")[0]\n # 店铺名称\n shop_name = product_tree.xpath(\"//div[@id='detail-left']//a[@class='sellername']/text()\")[0]\n # 已售 - 异步加载的\n juId = product_tree.xpath(\"//input[@id='juId']/@value\")[0]\n # print(SOLD_URL.format(item_url.split(\"item_id=\")[1], juId))\n sold_json = __open_url__(SOLD_URL.format(item_url.split(\"item_id=\")[1], juId)).json()\n # print(sold_json)\n stock, sold_count = \"\", \"\"\n print(sold_json)\n if \"data\" in sold_json:\n if \"stock\" in sold_json:\n stock = sold_json[\"data\"][\"stock\"]\n if \"soldCount\" in sold_json:\n sold = sold_json[\"data\"][\"soldCount\"]\n row = u\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\t{6}\\t{7}\\t{8}\\t{9}\\t{10}\\t{11}\\n\".format(brand, \\\n title, item_url, category_dict[item_url], tag, current_price, original_price, \\\n stock, sold_count, shop_name, shop_url, TODAY)\n print(row)\n # Add to file\n a_file.write(row)\n\ndef main():\n get_home()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"spider/juhuasuan.py","file_name":"juhuasuan.py","file_ext":"py","file_size_in_byte":6122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"236688524","text":"# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2018, Dag Wieers (@dagwieers) \n# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)\n\nfrom copy import deepcopy\nfrom ansible.module_utils.basic import AnsibleModule, json\nfrom ansible.module_utils.six import PY3\nfrom ansible.module_utils.six.moves.urllib.parse import urlencode, urljoin\nfrom ansible.module_utils.urls import fetch_url\nfrom ansible.module_utils._text import to_bytes, to_native\n\n\nif PY3:\n def cmp(a, b):\n return (a > b) - (a < b)\n\n\ndef issubset(subset, superset):\n ''' Recurse through nested dictionary and compare entries '''\n\n # Both objects are the same object\n if subset is superset:\n return True\n\n # Both objects are identical\n if subset == superset:\n return True\n\n # Both objects have a different type\n if type(subset) != type(superset):\n return False\n\n for key, value in subset.items():\n # Ignore empty values\n if value is None:\n return True\n\n # Item from subset is missing from superset\n if key not in superset:\n return False\n\n # Item has different types in subset and superset\n if type(superset[key]) != type(value):\n return False\n\n # Compare if item values are subset\n if isinstance(value, dict):\n if not issubset(superset[key], value):\n return False\n elif isinstance(value, list):\n try:\n # NOTE: Fails for lists of dicts\n if not set(value) <= set(superset[key]):\n return False\n except TypeError:\n # Fall back to exact comparison for lists of dicts\n if not cmp(value, superset[key]):\n return False\n elif isinstance(value, set):\n if not value <= superset[key]:\n return False\n else:\n if not value == superset[key]:\n return False\n\n return True\n\n\ndef update_qs(params):\n ''' Append key-value pairs to self.filter_string '''\n accepted_params = dict((k, v) for (k, v) in params.items() if v is not None)\n return '?' + urlencode(accepted_params)\n\n\ndef mso_argument_spec():\n return dict(\n host=dict(type='str', required=True, aliases=['hostname']),\n port=dict(type='int', required=False),\n username=dict(type='str', default='admin'),\n password=dict(type='str', required=True, no_log=True),\n output_level=dict(type='str', default='normal', choices=['debug', 'info', 'normal']),\n timeout=dict(type='int', default=30),\n use_proxy=dict(type='bool', default=True),\n use_ssl=dict(type='bool', default=True),\n validate_certs=dict(type='bool', default=True),\n )\n\n\ndef mso_reference_spec():\n return dict(\n name=dict(type='str', required=True),\n schema=dict(type='str'),\n template=dict(type='str'),\n )\n\n\ndef mso_subnet_spec():\n return dict(\n subnet=dict(type='str', required=True, aliases=['ip']),\n description=dict(type='str'),\n scope=dict(type='str', choices=['private', 'public']),\n shared=dict(type='bool'),\n no_default_gateway=dict(type='bool'),\n )\n\n\ndef mso_contractref_spec():\n return dict(\n name=dict(type='str', required=True),\n schema=dict(type='str'),\n template=dict(type='str'),\n type=dict(type='str', required=True, choices=['consumer', 'provider']),\n )\n\n\nclass MSOModule(object):\n\n def __init__(self, module):\n self.module = module\n self.params = module.params\n self.result = dict(changed=False)\n self.headers = {'Content-Type': 'text/json'}\n\n # normal output\n self.existing = dict()\n\n # info output\n self.previous = dict()\n self.proposed = dict()\n self.sent = dict()\n\n # debug output\n self.has_modified = False\n self.filter_string = ''\n self.method = None\n self.path = None\n self.response = None\n self.status = None\n self.url = None\n\n # Ensure protocol is set\n self.params['protocol'] = 'https' if self.params.get('use_ssl', True) else 'http'\n\n # Set base_uri\n if 'port' in self.params and self.params['port'] is not None:\n self.baseuri = '{protocol}://{host}:{port}/api/v1/'.format(**self.params)\n else:\n self.baseuri = '{protocol}://{host}/api/v1/'.format(**self.params)\n\n if self.module._debug:\n self.module.warn('Enable debug output because ANSIBLE_DEBUG was set.')\n self.params['output_level'] = 'debug'\n\n if self.params['password']:\n # Perform password-based authentication, log on using password\n self.login()\n else:\n self.module.fail_json(msg=\"Parameter 'password' is required for authentication\")\n\n def login(self):\n ''' Log in to MSO '''\n\n # Perform login request\n self.url = urljoin(self.baseuri, 'auth/login')\n payload = {'username': self.params['username'], 'password': self.params['password']}\n resp, auth = fetch_url(self.module,\n self.url,\n data=json.dumps(payload),\n method='POST',\n headers=self.headers,\n timeout=self.params['timeout'],\n use_proxy=self.params['use_proxy'])\n\n # Handle MSO response\n if auth['status'] != 201:\n self.response = auth['msg']\n self.status = auth['status']\n self.fail_json(msg='Authentication failed: {msg}'.format(**auth))\n\n payload = json.loads(resp.read())\n\n self.headers['Authorization'] = 'Bearer {token}'.format(**payload)\n\n def request(self, path, method=None, data=None, qs=None):\n ''' Generic HTTP method for MSO requests. '''\n self.path = path\n\n if method is not None:\n self.method = method\n\n # If we PATCH with empty operations, return\n if method == 'PATCH' and not data:\n return {}\n\n self.url = urljoin(self.baseuri, path)\n\n if qs is not None:\n self.url = self.url + update_qs(qs)\n\n resp, info = fetch_url(self.module,\n self.url,\n headers=self.headers,\n data=json.dumps(data),\n method=self.method,\n timeout=self.params['timeout'],\n use_proxy=self.params['use_proxy'],\n )\n self.response = info['msg']\n self.status = info['status']\n\n # self.result['info'] = info\n\n # Get change status from HTTP headers\n if 'modified' in info:\n self.has_modified = True\n if info['modified'] == 'false':\n self.result['changed'] = False\n elif info['modified'] == 'true':\n self.result['changed'] = True\n\n # 200: OK, 201: Created, 202: Accepted, 204: No Content\n if self.status in (200, 201, 202, 204):\n output = resp.read()\n if output:\n return json.loads(output)\n\n # 404: Not Found\n elif self.method == 'DELETE' and self.status == 404:\n return {}\n\n # 400: Bad Request, 401: Unauthorized, 403: Forbidden,\n # 405: Method Not Allowed, 406: Not Acceptable\n # 500: Internal Server Error, 501: Not Implemented\n elif self.status >= 400:\n try:\n output = resp.read()\n payload = json.loads(output)\n except (ValueError, AttributeError):\n try:\n payload = json.loads(info['body'])\n except Exception:\n self.fail_json(msg='MSO Error:', data=data, info=info)\n if 'code' in payload:\n self.fail_json(msg='MSO Error {code}: {message}'.format(**payload), data=data, info=info, payload=payload)\n else:\n self.fail_json(msg='MSO Error:'.format(**payload), data=data, info=info, payload=payload)\n\n return {}\n\n def query_objs(self, path, key=None, **kwargs):\n ''' Query the MSO REST API for objects in a path '''\n found = []\n objs = self.request(path, method='GET')\n\n if objs == {}:\n return found\n\n if key is None:\n key = path\n\n if key not in objs:\n self.fail_json(msg=\"Key '%s' missing from data\", data=objs)\n\n for obj in objs[key]:\n for kw_key, kw_value in kwargs.items():\n if kw_value is None:\n continue\n if obj[kw_key] != kw_value:\n break\n else:\n found.append(obj)\n return found\n\n def get_obj(self, path, **kwargs):\n ''' Get a specific object from a set of MSO REST objects '''\n objs = self.query_objs(path, **kwargs)\n if len(objs) == 0:\n return {}\n if len(objs) > 1:\n self.fail_json(msg='More than one object matches unique filter: {0}'.format(kwargs))\n return objs[0]\n\n def lookup_schema(self, schema):\n ''' Look up schema and return its id '''\n if schema is None:\n return schema\n\n s = self.get_obj('schemas', displayName=schema)\n if not s:\n self.module.fail_json(msg=\"Schema '%s' is not a valid schema name.\" % schema)\n if 'id' not in s:\n self.module.fail_json(msg=\"Schema lookup failed for schema '%s': %s\" % (schema, s))\n return s['id']\n\n def lookup_domain(self, domain):\n ''' Look up a domain and return its id '''\n if domain is None:\n return domain\n\n d = self.get_obj('auth/domains', key='domains', name=domain)\n if not d:\n self.module.fail_json(msg=\"Domain '%s' is not a valid domain name.\" % domain)\n if 'id' not in d:\n self.module.fail_json(msg=\"Domain lookup failed for domain '%s': %s\" % (domain, d))\n return d['id']\n\n def lookup_roles(self, roles):\n ''' Look up roles and return their ids '''\n if roles is None:\n return roles\n\n ids = []\n for role in roles:\n r = self.get_obj('roles', name=role)\n if not r:\n self.module.fail_json(msg=\"Role '%s' is not a valid role name.\" % role)\n if 'id' not in r:\n self.module.fail_json(msg=\"Role lookup failed for role '%s': %s\" % (role, r))\n ids.append(dict(roleId=r['id']))\n return ids\n\n def lookup_site(self, site):\n ''' Look up a site and return its id '''\n if site is None:\n return site\n\n s = self.get_obj('sites', name=site)\n if not s:\n self.module.fail_json(msg=\"Site '%s' is not a valid site name.\" % site)\n if 'id' not in s:\n self.module.fail_json(msg=\"Site lookup failed for site '%s': %s\" % (site, s))\n return s['id']\n\n def lookup_sites(self, sites):\n ''' Look up sites and return their ids '''\n if sites is None:\n return sites\n\n ids = []\n for site in sites:\n s = self.get_obj('sites', name=site)\n if not s:\n self.module.fail_json(msg=\"Site '%s' is not a valid site name.\" % site)\n if 'id' not in s:\n self.module.fail_json(msg=\"Site lookup failed for site '%s': %s\" % (site, s))\n ids.append(dict(siteId=s['id'], securityDomains=[]))\n return ids\n\n def lookup_tenant(self, tenant):\n ''' Look up a tenant and return its id '''\n if tenant is None:\n return tenant\n\n t = self.get_obj('tenants', key='tenants', name=tenant)\n if not t:\n self.module.fail_json(msg=\"Tenant '%s' is not valid tenant name.\" % tenant)\n if 'id' not in t:\n self.module.fail_json(msg=\"Tenant lookup failed for tenant '%s': %s\" % (tenant, t))\n return t['id']\n\n def lookup_users(self, users):\n ''' Look up users and return their ids '''\n if users is None:\n return users\n\n ids = []\n for user in users:\n u = self.get_obj('users', username=user)\n if not u:\n self.module.fail_json(msg=\"User '%s' is not a valid user name.\" % user)\n if 'id' not in u:\n self.module.fail_json(msg=\"User lookup failed for user '%s': %s\" % (user, u))\n ids.append(dict(userId=u['id']))\n return ids\n\n def create_label(self, label, label_type):\n ''' Create a new label '''\n return self.request('labels', method='POST', data=dict(displayName=label, type=label_type))\n\n def lookup_labels(self, labels, label_type):\n ''' Look up labels and return their ids (create if necessary) '''\n if labels is None:\n return None\n\n ids = []\n for label in labels:\n l = self.get_obj('labels', displayName=label)\n if not l:\n l = self.create_label(label, label_type)\n if 'id' not in l:\n self.module.fail_json(msg=\"Label lookup failed for label '%s': %s\" % (label, l))\n ids.append(l['id'])\n return ids\n\n def anp_ref(self, **data):\n ''' Create anpRef string '''\n return '/schemas/{schema_id}/templates/{template}/anps/{anp}'.format(**data)\n\n def epg_ref(self, **data):\n ''' Create epgRef string '''\n return '/schemas/{schema_id}/templates/{template}/anps/{anp}/epgs/{epg}'.format(**data)\n\n def bd_ref(self, **data):\n ''' Create bdRef string '''\n return '/schemas/{schema_id}/templates/{template}/bds/{bd}'.format(**data)\n\n def contract_ref(self, **data):\n ''' Create contractRef string '''\n # Support the contract argspec\n if 'name' in data:\n data['contract'] = data['name']\n return '/schemas/{schema_id}/templates/{template}/contracts/{contract}'.format(**data)\n\n def filter_ref(self, **data):\n ''' Create a filterRef string '''\n return '/schemas/{schema_id}/templates/{template}/filters/{filter}'.format(**data)\n\n def vrf_ref(self, **data):\n ''' Create vrfRef string '''\n return '/schemas/{schema_id}/templates/{template}/vrfs/{vrf}'.format(**data)\n\n def make_reference(self, data, reftype, schema_id, template):\n ''' Create a reference from a dictionary '''\n # Removes entry from payload\n if data is None:\n return None\n\n if data.get('schema') is not None:\n schema_obj = self.get_obj('schemas', displayName=data['schema'])\n if not schema_obj:\n self.fail_json(msg=\"Referenced schema '{schema}' in {reftype}ref does not exist\".format(reftype=reftype, **data))\n schema_id = schema_obj['id']\n\n if data.get('template') is not None:\n template = data['template']\n\n refname = '%sName' % reftype\n\n return {\n refname: data['name'],\n 'schemaId': schema_id,\n 'templateName': template,\n }\n\n def make_subnets(self, data):\n ''' Create a subnets list from input '''\n if data is None:\n return None\n\n subnets = []\n for subnet in data:\n subnets.append(dict(\n ip=subnet['ip'],\n description=subnet.get('description', subnet['ip']),\n scope=subnet.get('scope', 'private'),\n shared=subnet.get('shared', False),\n noDefaultGateway=subnet.get('no_default_gateway', False),\n ))\n\n return subnets\n\n def sanitize(self, updates, collate=False, required=None, unwanted=None):\n ''' Clean up unset keys from a request payload '''\n if required is None:\n required = []\n if unwanted is None:\n unwanted = []\n self.proposed = deepcopy(self.existing)\n self.sent = deepcopy(self.existing)\n\n for key in self.existing:\n # Remove References\n if key.endswith('Ref'):\n del(self.proposed[key])\n del(self.sent[key])\n continue\n\n # Removed unwanted keys\n elif key in unwanted:\n del(self.proposed[key])\n del(self.sent[key])\n continue\n\n # Clean up self.sent\n for key in updates:\n # Always retain 'id'\n if key in required:\n pass\n\n # Remove unspecified values\n elif not collate and updates[key] is None:\n if key in self.existing:\n del(self.sent[key])\n continue\n\n # Remove identical values\n elif not collate and key in self.existing and updates[key] == self.existing[key]:\n del(self.sent[key])\n continue\n\n # Add everything else\n if updates[key] is not None:\n self.sent[key] = updates[key]\n\n # Update self.proposed\n self.proposed.update(self.sent)\n\n def exit_json(self, **kwargs):\n ''' Custom written method to exit from module. '''\n\n if self.params['state'] in ('absent', 'present'):\n if self.params['output_level'] in ('debug', 'info'):\n self.result['previous'] = self.previous\n # FIXME: Modified header only works for PATCH\n if not self.has_modified and self.previous != self.existing:\n self.result['changed'] = True\n\n # Return the gory details when we need it\n if self.params['output_level'] == 'debug':\n self.result['method'] = self.method\n self.result['response'] = self.response\n self.result['status'] = self.status\n self.result['url'] = self.url\n\n if self.params['state'] in ('absent', 'present'):\n self.result['sent'] = self.sent\n self.result['proposed'] = self.proposed\n\n self.result['current'] = self.existing\n\n if self.module._diff and self.result['changed'] is True:\n self.result['diff'] = dict(\n before=self.previous,\n after=self.existing,\n )\n\n self.result.update(**kwargs)\n self.module.exit_json(**self.result)\n\n def fail_json(self, msg, **kwargs):\n ''' Custom written method to return info on failure. '''\n\n if self.params['state'] in ('absent', 'present'):\n if self.params['output_level'] in ('debug', 'info'):\n self.result['previous'] = self.previous\n # FIXME: Modified header only works for PATCH\n if not self.has_modified and self.previous != self.existing:\n self.result['changed'] = True\n\n # Return the gory details when we need it\n if self.params['output_level'] == 'debug':\n if self.url is not None:\n self.result['method'] = self.method\n self.result['response'] = self.response\n self.result['status'] = self.status\n self.result['url'] = self.url\n\n if self.params['state'] in ('absent', 'present'):\n self.result['sent'] = self.sent\n self.result['proposed'] = self.proposed\n\n self.result['current'] = self.existing\n\n self.result.update(**kwargs)\n self.module.fail_json(msg=msg, **self.result)\n","sub_path":"env/lib/python3.9/site-packages/ansible/module_utils/network/aci/mso.py","file_name":"mso.py","file_ext":"py","file_size_in_byte":19674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"526261642","text":"# Училището получава отстъпка от крайната цена, в зависимост от броя на настанените в хотела ученици:\n# •\tАко броят на учениците е 50 или повече, училището получава 50% отстъпка\n# •\tАко броят на учениците е 20 или повече и в същото време по-малък от 50, училището получава 15% отстъпка\n# •\tАко броят на учениците е 10 или повече и в същото време по-малък от 20, училището получава 5% отстъпка\n# В таблицата по-долу са дадени спортовете, които ще се практикуват в зависимост от вида на ваканцията и групата\n# Да се напише програма, която пресмята цената, която ще заплати училището за нощувките и принтира спорта, който ще се практикува от учениците.\n# Изход\n# На конзолата се отпечатва 1 ред:\n# •\tСпортът, който са практикували учениците и цената за нощувките, която е заплатило училището, форматирана до втория знак след десетичната запетая, в следния формат:\n# \"{спортът} {цената} lv.“\n\nseason = input() #- “Winter”, “Spring” или “Summer”;\ngender = input()# - “boys”, “girls” или “mixed”;\npupils_count = int(input())#Брой на учениците – цяло число\nnights_count = int(input())# Брой на нощувките – цяло число\nprice_per_night = 0\nsport = 0\ndiscount = 1\nfinal_price = 0\nif season == \"Winter\":\n if gender == \"boys\":\n price_per_night = 9.6\n sport = \"Judo\"\n elif gender == \"girls\":\n price_per_night = 9.6\n sport = \"Gymnastics\"\n elif gender == \"mixed\":\n price_per_night = 10\n sport = \"Ski\"\nelif season == \"Spring\":\n if gender == \"boys\":\n price_per_night = 7.2\n sport = \"Tennis\"\n elif gender == \"girls\":\n price_per_night = 7.2\n sport = \"Athletics\"\n elif gender == \"mixed\":\n price_per_night = 9.5\n sport = \"Cycling\"\nelif season == \"Summer\":\n if gender == \"boys\":\n price_per_night = 15\n sport = \"Football\"\n elif gender == \"girls\":\n price_per_night = 15\n sport = \"Volleyball\"\n elif gender == \"mixed\":\n price_per_night = 20\n sport = \"Swimming\"\nif 10 <= pupils_count < 20:\n discount = 0.95\nelif 20 <= pupils_count < 50:\n discount = 0.85\nelif pupils_count >= 50:\n discount = 0.5\nfinal_price = (pupils_count * price_per_night * nights_count) * discount\nprint(f\"{sport} {final_price:.2f} lv.\")\n","sub_path":"Python Basics June 2020/3 conditional_statements_more_ex/3.3.7. school_camp.py","file_name":"3.3.7. school_camp.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"466312047","text":"# 1932. Merge BSTs to Create Single BST\n# vwc 249\n# 2021/09/23\n\n# Runtime: 2392 ms, faster than 80.62% of Python3 online submissions for Merge BSTs to Create Single BST.\n# Memory Usage: 63.7 MB, less than 71.32% of Python3 online submissions for Merge BSTs to Create Single BST.\n\n# 没啥思路,看了讨论区大佬的解答才写出来。此题是98. Validate Binary Search Tree.的升级题。\n# 观察1:如果这n棵树能够合并成一棵树,那么最终这棵树的要结点��值只会出现一次,其他树的根结点的值会出现两次,因为要合并\n# 因此用哈希表将所有结点的值的频数记录下来。最后看哪棵树的根结点只出现了一次。那棵树就是终极平衡树的根结点。\n# 观察2:终极平衡树中不可能有两个结点有相同的值,因此每个叶子至多会合并一次,并且能两两合并的树都是唯一确定的。\n# 用dfs来合并树,从终极要结点出发,遍历到它的每一片叶子上,根据叶子的值来寻找哈希表中是否有对应的子树,如果有的话合并即可,因为\n# 如果不合并的话,这棵树中就会有两个结点有相同的值,不符合要求。\n# 注:在dfs的过程中,同时检查平衡树的合理性,这点很是精妙。由min_val 和 max_val来进行判断。\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def canMerge(self, trees: List[TreeNode]) -> TreeNode:\n val2root, counts = {}, {}\n for t in trees:\n val2root[t.val] = t\n counts[t.val] = counts.get(t.val, 0) + 1\n if t.left:\n counts[t.left.val] = counts.get(t.left.val, 0) + 1\n if t.right:\n counts[t.right.val] = counts.get(t.right.val, 0) + 1\n root = None\n for t in trees:\n if counts[t.val] == 1:\n root = val2root[t.val]\n del val2root[t.val]\n break\n if not root: return None\n return root if self.dfs(root, val2root, 0, 60_000) and not val2root else None\n\n def dfs(self, root, val2root, min_val, max_val):\n if not root:\n return True\n if root.val <= min_val or root.val >= max_val:\n return False\n if not root.left and not root.right and root.val in val2root:\n new_root = val2root[root.val]\n root.left = new_root.left\n root.right = new_root.right\n del val2root[root.val]\n return self.dfs(root.left, val2root, min_val, root.val) and self.dfs(root.right, val2root, root.val, max_val)\n\n","sub_path":"1932. Merge BSTs to Create Single BST.py","file_name":"1932. Merge BSTs to Create Single BST.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"355524076","text":"# import numpy\nfrom copy import deepcopy\ngrids = []\nwith open('096.txt') as f:\n\tgrid = []\n\tfor line in [l.strip('\\n') for l in f.readlines()]:\n\t\tif 'Grid' in line:\n\t\t\tgrid = []\n\t\telse:\n\t\t\tgrid.append(list(map(int, line)))\n\t\tif len(grid) == 9:\n\t\t\tgrids.append(grid)\n\ndef check(grid, columns, squares):\n\tfor row in grid:\n\t\tif set(row) != set(range(1, 10)):\n\t\t\treturn False\n\n\tfor col in columns:\n\t\tif set(col) != set(range(1, 10)):\n\t\t\treturn False\n\n\tfor sq in squares:\n\t\tif set(sq) != set(range(1, 10)):\n\t\t\treturn False\n\n\treturn True\n\n\ndef eliminate(grid, poss):\n\tng = deepcopy(grid)\n\t# p = [list(map(len, row)) for row in poss]\n\tpcol = get_cols(poss)\n\tpsquares = get_squares(poss)\n\t# display((p, pcol, psquares))\n\n\t# Naked Cells\n\tfor i, row in enumerate(poss):\n\t\tfor j, col in enumerate(row):\n\t\t\tif len(col) == 1:\n\t\t\t\tng[i][j] = list(col)[0]\n\n\t#rows\n\tfor i, row in enumerate(poss):\n\t\tfor j, col in enumerate(row):\n\t\t\tfor l in col:\n\t\t\t\tindexes = [k for k, search in enumerate(row) if l in search]\n\t\t\t\tif len(indexes) == 1:\n\t\t\t\t\tng[i][j] = l\n\t\t\t\telif len(set(index//3 for index in indexes)) <= 1:\n\t\t\t\t\tfor a in range(3*(i//3), 3*(i//3 + 1)):\n\t\t\t\t\t\tfor b in range(3*(j//3), 3*(j//3 + 1)):\n\t\t\t\t\t\t\tif (a != i or b not in indexes) and l in poss[a][b]:\n\t\t\t\t\t\t\t\tposs[a][b].remove(l)\n\n\t# #cols\n\tfor j, col in enumerate(pcol):\n\t\tfor i, row in enumerate(col):\n\t\t\tfor l in row:\n\t\t\t\tindexes = [k for k, search in enumerate(col) if l in search]\n\t\t\t\tif len(indexes) == 1:\n\t\t\t\t\tng[i][j] = l\n\t\t\t\telif len(set(index//3 for index in indexes)) <= 1:\n\t\t\t\t\tfor a in range(3*(i//3), 3*(i//3 + 1)):\n\t\t\t\t\t\tfor b in range(3*(j//3), 3*(j//3 + 1)):\n\t\t\t\t\t\t\tif (a not in indexes or b != j) and l in poss[a][b]:\n\t\t\t\t\t\t\t\tposs[a][b].remove(l)\n\n\t#squares\n\tfor a, bsq in enumerate(psquares):\n\t\tfor b, lsq in enumerate(bsq):\n\t\t\tfor l in lsq:\n\t\t\t\tif sum(int(l in x) for x in bsq) == 1:\n\t\t\t\t\tng[3*(a//3)+b//3][3*(a%3)+b%3] = l\n\n\treturn ng\n\n\t\t\t\n\ndef solve(grid):\n\tg = deepcopy(grid)\n\tsteps = 0\n\twhile True:\n\t\tcols = get_cols(g)\n\t\tsquares = get_squares(g)\n\t\tpossibles = [[{}]*len(g) for _ in range(len(g))]\n\t\tfor i in range(len(g)):\n\t\t\tfor j in range(len(g)):\n\t\t\t\tsquare = 3*(i//3)+j//3\n\t\t\t\tif g[i][j] == 0:\n\t\t\t\t\tp = set(range(1, 10))\n\t\t\t\t\tfor l in g[i] + cols[j] + squares[square]:\n\t\t\t\t\t\tif l in p:\n\t\t\t\t\t\t\tp.remove(l)\n\t\t\t\t\tpossibles[i][j] = p\n\t\tnewG = eliminate(g, possibles)\n\t\t# display((g, newG, possibles))\n\t\tif newG == g:\n\t\t\tbreak\n\t\tg = newG\n\t\tsteps += 1\n\treturn newG, possibles, check(newG, cols, squares), steps\n\t\n\n\ndef get_cols(grid):\n\treturn list(map(list, zip(*grid)))\n\ndef get_squares(grid):\n\tsquares = []\n\tfor i in range(len(grid)):\n\t\tsq = []\n\t\tfor j in range(len(grid)):\n\t\t\tsq.append(grid[3*(i//3)+j//3][3*(i%3)+j%3])\n\t\tsquares.append(sq)\n\treturn squares\n\n\ndef display(grids):\n\tfor rows in zip(*grids):#numpy.array(grid):\n\t\tfor row in rows:\n\t\t\tprint(row, end= ' ')\n\t\tprint()\n\tprint()\n\ntotal = 0\nfor i, grid in enumerate(grids):\n\tnew_grid, possibles, solved, steps = solve(grid)\n\tprint(f'Grid {i} - {steps} steps', solved)\n\tif solved:\n\t\ttotal += 1\n\tif not solved:\n\t\tprint(grid)\n\t\t# break\n\t# print(steps, solved)\nprint(total)\n","sub_path":"096.py","file_name":"096.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"365015649","text":"# https://leetcode.com/problems/combination-sum/ Medium\n\nclass Solution:\n def recurse(self, curr_comb, curr_sum, j, T, C, sol):\n if curr_sum == T:\n sol.append(curr_comb.copy())\n elif curr_sum < T:\n for i in range(j, len(C)):\n curr_comb.append(C[i])\n self.recurse(curr_comb,curr_sum + C[i], i, T, C, sol)\n curr_comb.pop()\n\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n sol = []\n self.recurse([], 0, 0, target, candidates, sol)\n return sol\n","sub_path":"Tandon-LeetCode-Bootcamp/Week 4 Recursion DFS/combination-sum.py","file_name":"combination-sum.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"365257220","text":"# 合成数 N は 1 より大きく √N 以下の約数をもちます\n# https://excelmath.atelierkobato.com/composite/\n\nimport math\n\n\ndef gcd(m, n):\n if n == 0:\n return m\n\n return gcd(n, m % n)\n\n\ndef prime_factorize(N):\n \"\"\"素因数分解\n Return:\n [{prime1, exp_count2}, {prime2, exp_count2}]\n \n ex)\n 60 = 2**2 * 3 * 5\n -> [(2, 2), (3, 1), (5, 1)]\n \"\"\"\n res = []\n for i in range(2, int(math.sqrt(N)) + 1):\n if N % i != 0:\n continue\n\n exp_ct = 0\n while N % i == 0:\n exp_ct += 1\n N = N // i\n res.append((i, exp_ct))\n if N != 1:\n res.append((N, 1))\n\n return res\n\n\ndef get_factors(N, sort=True):\n # 約数のリストを返す\n # 12 -> 1, 2, 3, 4, 6, 12\n res = []\n for i in range(1, int(math.sqrt(N)) + 1):\n if N % i != 0:\n continue\n res.append(i) # 12 / 2 = 6\n res.append(N // i) # 12 / 6 = 2\n\n if sort:\n res.sort()\n\n return res\n\n\nif __name__ == \"__main__\":\n \"\"\"\n 10 : [(2, 1), (5, 1)]\n 16 : [(2, 4)]\n 60 : [(2, 2), (3, 1), (5, 1)]\n 1000000007 : [(1000000007, 1)]\n \"\"\"\n for v in [10, 16, 60, 1000000007]:\n print(v, ':', prime_factorize(v))\n","sub_path":"techs/factorize.py","file_name":"factorize.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"252231779","text":"import csv\nimport math\nimport os\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix, roc_curve, auc\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import GridSearchCV, LeaveOneOut\nfrom sklearn.preprocessing import StandardScaler, RobustScaler, Normalizer, MinMaxScaler\nimport numpy as np\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import StratifiedKFold,KFold\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom sklearn.metrics import roc_auc_score\n# from imblearn.over_sampling import SMOTE\n# from imblearn.combine import SMOTEENN \nfrom feature_selection.method.ANOVA import run1\nfrom feature_selection.method.MRMD import run2\n\ndef gettarget(dataset):\n classtarget=[]\n classtarget=[]\n if (dataset == 'Feng'):\n for i in range(0, 1552):\n classtarget.append(0)\n for i in range(0, 253):\n classtarget.append(1)\n if (dataset == 'ZhangTrain'):\n for i in range(0, 100):\n classtarget.append(0)\n for i in range(0, 100):\n classtarget.append(1)\n if (dataset == 'ZhangTest'):\n for i in range(0, 392):\n classtarget.append(0)\n for i in range(0, 74):\n classtarget.append(1)\n return classtarget\n\ndef getdata(filename,X):\n feature = []\n with open(filename + \".csv\") as fs:\n data = csv.reader(fs)\n for line in data:\n line = [float(x) for x in line]\n feature.append(line)\n feature = np.array(feature)\n if X == []:\n res = feature\n else:\n res = np.concatenate((X,feature),axis = 1)\n return res\n\ndef main(name,feature_extraction,feature_selection,standard,G,dimension,over_sampling):\n if name == 'Feng':\n x_train = []\n y_train=gettarget('Feng')\n y_train=np.array(y_train)\n if 'gram1' in feature_extraction:\n feature=getdata('./feature_data/Feng/Fenggram1',x_train)\n x_train=np.array(feature)\n if 'gram2' in feature_extraction:\n feature=getdata('./feature_data/Feng/Fenggram2',x_train)\n x_train=np.array(feature)\n if 'seqgram1' in feature_extraction:\n feature=getdata('./feature_data/Feng/Fengseqgram1',x_train)\n x_train=np.array(feature)\n if 'seqgram2' in feature_extraction:\n feature=getdata('./feature_data/Feng/Fengseqgram2',x_train)\n x_train=np.array(feature)\n if 'ACC' in feature_extraction:\n feature=getdata('./feature_data/Feng/'+str(G)+'Fengacc',x_train)\n x_train=np.array(feature)\n if '3gram1' in feature_extraction:\n feature=getdata('./feature_data/Feng/3Fenggram1',x_train)\n x_train=np.array(feature)\n print(x_train.shape)\n print(y_train.shape)\n elif name == 'Zhang':\n x_train = []\n x_test = []\n y_train=gettarget('ZhangTrain')\n y_train=np.array(y_train)\n y_test=gettarget('ZhangTest')\n y_test=np.array(y_test)\n if 'gram1' in feature_extraction:\n feature=getdata('./feature_data/ZhangTrain/ZhangTraingram1',x_train)\n x_train=np.array(feature)\n feature=getdata('./feature_data/ZhangTest/ZhangTestgram1',x_test)\n x_test=np.array(feature)\n if 'gram2' in feature_extraction:\n feature=getdata('./feature_data/ZhangTrain/ZhangTraingram2',x_train)\n x_train=np.array(feature)\n feature=getdata('./feature_data/ZhangTest/ZhangTestgram2',x_test)\n x_test=np.array(feature)\n if 'seqgram1' in feature_extraction:\n feature=getdata('./feature_data/ZhangTrain/ZhangTrainseqgram1',x_train)\n x_train=np.array(feature)\n feature=getdata('./feature_data/ZhangTest/ZhangTestseqgram1',x_test)\n x_test=np.array(feature)\n if 'seqgram2' in feature_extraction:\n feature=getdata('./feature_data/ZhangTrain/ZhangTrainseqgram2',x_train)\n x_train=np.array(feature)\n feature=getdata('./feature_data/ZhangTest/ZhangTestseqgram2',x_test)\n x_test=np.array(feature)\n if 'ACC' in feature_extraction:\n feature=getdata('./feature_data/ZhangTrain/'+str(G)+'ZhangTrainacc',x_train)\n x_train=np.array(feature)\n feature=getdata('./feature_data/ZhangTest/'+str(G)+'ZhangTestacc',x_test)\n x_test=np.array(feature)\n if '3gram1' in feature_extraction:\n feature=getdata('./feature_data/ZhangTrain/3ZhangTraingram1',x_train)\n x_train=np.array(feature)\n feature=getdata('./feature_data/ZhangTest/3ZhangTestgram1',x_test)\n x_test=np.array(feature)\n print(x_train.shape)\n print(x_test.shape)\n print(y_train.shape)\n print(y_test.shape)\n\n\n # if over_sampling != '':\n # if name == 'Feng':\n # if over_sampling == 'SMOTE':\n # smo = SMOTE(random_state=42)\n # x_train, y_train = smo.fit_sample(x_train, y_train)\n\n # elif over_sampling == 'SMOTEENN':\n # smo = SMOTEENN(random_state=42)\n # x_train, y_train = smo.fit_sample(x_train, y_train)\n # elif name == 'Zhang':\n # print(\"Balanced Before!\")\n # print('Over_sampling Successful!')\n # print(x_train.shape)\n # print(y_train.shape)\n if standard != '':\n if standard == 'Minmax':\n std = MinMaxScaler()\n elif standard == 'Robust':\n std = RobustScaler()\n elif standard == 'Standard':\n std = StandardScaler()\n x_train = std.fit_transform(x_train)\n if name == 'Zhang':\n x_test = std.fit_transform(x_test)\n print('standard Successful!')\n\n resultname = str(name)\n for i in range(len(feature_extraction)):\n if i != 0:\n resultname += '_'\n resultname += feature_extraction[i]\n else:\n resultname += feature_extraction[i]\n if feature_selection != '':\n resultname += '_'\n resultname += feature_selection\n\n if over_sampling != '':\n resultname += '_'\n resultname += over_sampling\n\n if feature_selection != '':\n path = './feature_selection/TempFile/'+resultname+'_result/'\n isExists=os.path.exists(path)\n if not isExists:\n os.makedirs(path) \n print('resultname:',resultname)\n\n if feature_selection != '':\n S1 = x_train.shape[0]\n S2 = x_train.shape[1]\n x_train_changed = np.zeros((S1+1, S2+1))\n x_train_changed[0][0] = 0\n for i in range(1,S2+1):\n x_train_changed[0][i] = i - 1\n for i in range(1,S1+1):\n x_train_changed[i][0] = y_train[i-1]\n for j in range(1,S2+1):\n x_train_changed[i][j] = x_train[i-1][j-1]\n\n file = open('./feature_selection/TempFile/'+resultname+'_result/'+name+'_x_train_changed.csv', 'w', newline='') \n content = csv.writer(file, dialect='excel')\n for i in range(len(x_train)+1):\n content.writerow(x_train_changed[i])\n file.close()\n\n feature_list = []\n if feature_selection == 'ANOVA':\n feature_list = run1('./feature_selection/TempFile/'+resultname+'_result/'+name+'_x_train_changed.csv')\n elif feature_selection == 'MRMD':\n path = './feature_selection/TempFile/'+resultname+'_result/'+name+'OrderList.csv'\n isExists=os.path.exists(path)\n if not isExists:\n feature_list = run2('./feature_selection/TempFile/'+resultname+'_result/'+name+'_x_train_changed.csv')\n else:\n file = open('./feature_selection/TempFile/'+resultname+'_result/'+name+'OrderList.csv', 'r') \n orderlist = csv.reader(file)\n for i in orderlist:\n feature_list = [int(float(x)) for x in i]\n file.close()\n\n for i in range(len(feature_list)):\n if feature_list[i] == '0.0.1':\n feature_list[i] = '0.0'\n print(feature_list)\n print(np.array(feature_list).shape)\n\n\n file = open('./feature_selection/TempFile/'+resultname+'_result/'+name+'OrderList.csv', 'w', newline='') \n content = csv.writer(file, dialect='excel') \n content.writerow(feature_list)\n file.close()\n\n k = dimension\n feature_list = [int(float(x)) for x in feature_list]\n xtrain = np.zeros((len(x_train), k))\n for i in range(0, k):\n index = feature_list[i]\n xtrain[:, i] = x_train[:, index]\n x_train = xtrain\n\n if name == 'Zhang':\n xtest = np.zeros((len(x_test), k))\n for i in range(0, k):\n index = feature_list[i]\n xtest[:, i] = x_test[:, index]\n x_test = xtest\n \n print('trainset_d:'+str(x_train.shape))\n\n path = './result/'+resultname+'_result/'\n isExists=os.path.exists(path)\n if not isExists:\n os.makedirs(path)\n best_score_all_dimension = []\n best_score_all_dimension1 = []\n best_score_all_dimension2 = []\n train_y = y_train\n KF = KFold(n_splits = 10,random_state = 7,shuffle=True)\n loo = LeaveOneOut()\n f1 = dimension\n if name == 'Feng':\n for k in range(f1,dimension+1,5):\n train_x=x_train[:,0:k]\n \n indexi = -1\n indexj = -1\n indexk = -1\n bestscore = -1\n\n file = open('./result/'+resultname+'_result/'+resultname+'_result.txt', 'a', newline='') \n\n for i in range(3, -15-1, -2):\n for j in range(-3, 15+1, 2):\n g = math.pow(2, i)\n c = math.pow(2, j)\n clf = SVC(C=c, gamma=g, kernel='rbf', probability=True, random_state=7)\n # score=cross_val_score(clf,train_x,train_y,cv=LeaveOneOut(),scoring='accuracy',n_jobs=-1).mean()\n score = cross_val_score(clf,train_x,train_y,cv=KF,scoring='accuracy',n_jobs=-1).mean()\n print(i,j,k,score)\n \n if score > bestscore:\n indexi = i\n indexj = j\n indexk = k\n bestscore = score\n \n print(k,bestscore)\n best_score_all_dimension.append(bestscore)\n file.writelines('std = '+str(standard)+'\\n')\n file.writelines('k = '+str(k)+'\\n')\n file.writelines('maxscore:'+str(bestscore)+'\\n')\n file.writelines('index:'+str([indexi,indexj,indexk,bestscore])+'\\n')\n file.close()\n\n\n if name == 'Zhang':\n test_y = y_test\n for k in range(f1,dimension+1,5):\n train_x = x_train[:,0:k]\n test_x = x_test[:,0:k]\n indexi = -1\n indexj = -1\n indexk = -1\n bestscore = -1\n bestscore1 = -1\n bestscore2 = -1\n file1 = open('./result/'+resultname+'_result/'+resultname+'_result_Train.txt', 'a', newline='') \n file2 = open('./result/'+resultname+'_result/'+resultname+'_result_Test.txt', 'a', newline='') \n\n for i in range(3, -15-1, -2):\n for j in range(-3, 15+1, 2):\n g = math.pow(2, i)\n c = math.pow(2, j)\n clf = SVC(C=c, gamma=g, kernel='rbf', probability=True, random_state=7)\n # train loo\n score1 = cross_val_score(clf,train_x,train_y,cv=loo,scoring='accuracy',n_jobs=-1).mean()\n # test\n clf.fit(train_x,train_y)\n predicted = clf.predict(test_x)\n score2 = accuracy_score(test_y,predicted)\n score = (score1 + score2)/2\n print(i,j,k,score1,score2,score)\n \n if score > bestscore:\n indexi = i\n indexj = j\n indexk = k\n bestscore = score\n bestscore1 = score1\n bestscore2 = score2\n \n print(k,bestscore1,bestscore2,bestscore)\n best_score_all_dimension.append(bestscore)\n best_score_all_dimension1.append(bestscore1)\n best_score_all_dimension2.append(bestscore2)\n file1.writelines('std = '+str(standard)+'\\n')\n file1.writelines('k = '+str(k)+'\\n')\n file1.writelines('maxscore:'+str(bestscore1)+'\\n')\n file1.writelines('index:'+str([indexi,indexj,indexk,bestscore1])+'\\n')\n file1.close()\n file2.writelines('std = '+str(standard)+'\\n')\n file2.writelines('k = '+str(k)+'\\n')\n file2.writelines('maxscore:'+str(bestscore2)+'\\n')\n file2.writelines('index:'+str([indexi,indexj,indexk,bestscore2])+'\\n')\n file2.close()\n if name == 'Feng':\n print('Feng_best_score_all:'+str(max(best_score_all_dimension)))\n if name == 'Zhang':\n index = best_score_all_dimension.index(max(best_score_all_dimension))\n print('ZhangTrain_best_score_all:'+str(best_score_all_dimension1[index]))\n print('ZhangTest_best_score_all:'+str(best_score_all_dimension2[index]))\n print('Average_best_score_all:'+str(max(best_score_all_dimension)))\n\n\nmain('Feng',['seqgram2'],'','Minmax',11,400,'')\nmain('Zhang',['seqgram2',],'','Minmax',11,400,'')","sub_path":"Seq_gram2.py","file_name":"Seq_gram2.py","file_ext":"py","file_size_in_byte":13649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"631189613","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport io\n\nDEBUG = True\nn_iterations = 0\nMAX_ITERATIONS = 10000 # Segmentation fault with 100000\nsys.setrecursionlimit(100000)\n\ndef readString(reader):\n return reader.readline().replace(\"\\n\",\"\")\n\ndef readInt(reader):\n line = reader.readline().replace(\"\\n\",\"\")\n if line==\"\":\n return None\n else:\n return int(line)\n\ndef readMatrix(reader, n_rows):\n matrix = []\n for i in range(n_rows):\n row = []\n line = reader.readline().replace(\"\\n\", \"\")\n for j in line:\n row.append(j)\n matrix.append(row)\n return matrix\n\n# https://stackoverflow.com/questions/24101524/finding-median-of-list-in-python\ndef median(list):\n n = len(list)\n if n<1:\n return None\n if n%2==1:\n return sorted(list)[n//2]\n else:\n return sum(sorted(list)[n//2-1:n//2+1])/2.0\n\ndef getMatrix(h, w, value):\n matrix = []\n for i in range(h):\n row = []\n for j in range(w):\n row.append(value)\n matrix.append(row)\n return matrix\n\n\"\"\"\nGreatest Common Divisor (GCD)\nhttp://en.wikipedia.org/wiki/Greatest_common_divisor\nThe GCD of k numbers say [n1,n2,n3… nk] is the \nlargest positive integer that divides all these numbers without any remainder. \n\nMinka has N (1 <= N <= 10^5) balls and there is a number \nV (1 <= V <= 10^4) written on every ball. \n\nNow Minka has to perform Q queries, \nand in each query he wants to know the number of possible ways \nhe can choose balls out of the N balls, \nso that GCD of the numbers written on the chosen balls equals to the number X of each query. \nAlthough he already knows the answer for each query, \nhe would still like you to check if you can also find answer to his queries. \nSince number of ways can be very large, your program should output the number of ways modulus 10^9+7. \nNotes: \n1) There can be at most 100 distinct numbers written on N balls. \n2) By definition, the GCD is only defined for 2 or more numbers. \nFor this problem, however, we will consider that the GCD of a single number \nmay also defined and in such case the GCD of a single number will be equal to the number itself \n(i.e. the GCD of 2 is 2. Please refer to the explanation of Sample Input 1 for more details).\n\"\"\"\n\ndef getV(reader):\n # Vi: number written on the ith ball.\n # 1 <= Vi <= 10^4\n V_aux = readString(reader).split(\" \")\n V_aux.pop() # Remove \"\\n\"\n # N = len(V)\n V = []\n for i in V_aux:\n V.append(int(i))\n return V\n\n\"\"\"\nv: V without repetitions\nw: number of repetitions\n\"\"\"\ndef getv(V):\n # Note 1: There can be at most 100 distinct numbers written on N balls.\n v = []\n w = {}\n for i in V:\n if i not in v:\n v.append(i)\n w[str(i)] = 1\n else:\n w[str(i)] += 1\n return v, w\n\ndef getGCDPairs(v):\n \"\"\"\n gcd(a, b) = X\n C(100, 2) = 4950 <- obligatorio (y es la cantidad de pares maxima posible)\n Pares que cumplen:\n (a1, b1) (a2, b2) ... (an, bn)\n\n 3 5 6 8 10\n 2 = gcd(6, 8) = gcd(6, 10) = gcd(8, 10) -> n = 3\n 15 20 25 47 90\n 5 = gcd(15, 20) = gcd(15, 25) -> n = 2\n \"\"\"\n\n pass\n\ndef main(argv):\n\n reader = io.open(sys.stdin.fileno())\n\n # N: number of balls.\n # 1 <= N <= 10^5\n N = readInt(reader)\n\n # Vi: number written on the ith ball.\n # 1 <= Vi <= 10^4\n V = getV(reader)\n print(V)\n\n # Note 1: There can be at most 100 distinct numbers written on N balls.\n v, w = getv(V)\n print(v)\n print(w)\n\n \"\"\"\n https://www.wyzant.com/resources/lessons/math/precalculus/factorials_permutations_and_combinations\n Combinations:\n Groups from 1 to 100 items.\n 1 <= n <= 100\n 1 <= r <= 100\n nCr = C(n,r)\n C(100,100) = 1\n C(100C,1) = 100\n C(100,50) = 100891344545564193334812497256\n Nop, no puedo andar calculando a mano las combinaciones.\n Ni tampoco tenerlas calculadas de prepo.\n C(100,2) = 4950\n Encuentro los pares y armo los grupos de 3 a 100.\n https://www.geeksforgeeks.org/gcd-two-array-numbers/\n https://www.sparknotes.com/math/prealgebra/wholenumbers/section4/\n \n \n\n \n gcd(a, b, c) = gcd(gcd(a, b), c) = gcd(X, c) = X\n C(100, 2) = 4950\n gcd(a, b, c, d) = gcd(gcd(a, b, c), d) = gcd(X, d) <- ya lo hice antes con gcd(X, c)\n Pares que cumplen:\n (X, c1) (X, c2) ... (X, cm)\n \n Armo:\n (a1, b1, c1) (a1, b1,c2) ... (a1, b1, cm)\n (a2, b2, c1) (a2, b2,c2) ... (a2, b2, cm)\n ...\n (an, bn, c1) (an, bn,c2) ... (an, bn, cm)\n \n d11 d12 ... d1m\n d21 d22 ... d2m\n ...\n dn1 dn2 ... dnm\n \n Luego:\n - (d11,c2) ... (d11, cm)\n (d12, c1) - ... (d21, cm)\n ...\n (d1m, c1)\n \n n pares gcd(a, b)\n m pares gcd(X, c)\n n * m grupos de 2\n \n \n 3 5 6 8 10\n 2 = gcd(6, 8) = gcd(6, 10) = gcd(8, 10) -> n = 3\n 2 = gcd(2, 6) = gcd(2, 8) = gcd(2, 10) -> m = n = 3 (no siempre)\n 6 8 10\n C(3, 2) = 3\n C(3, 3) = 1\n -> 4 posibilidades\n \n 15 20 25 30 47 90 100\n 5 = gcd(15, 20) = gcd(15, 25) = gcd(20, 25) = gcd(25, 30) -> n = 4\n 5 = gcd(5, 15) = gcd(5, 20) = gcd(5, 25) = gcd(5, 30) = gcd(5, 90) = gcd(5, 100) -> m = 6\n 90 100 (descartando a los de la otra lista)\n (15, 20)\n (15, 25)\n \n 1) Calculo el GCD para los 100 numeros\n 2) Armo el array de los que cumplen + sus repeticiones\n 3) Calculo la combinatoria\n \n Una vez que tengo los pares,\n (a, b) (c, d)\n armo los grupos\n C(4, 2) = 6 -> (a, b) (a, c) (a, d) (b, c) (b, d) (c, d)\n \n (a, b, c)\n (a, b, d)\n (b, c, d)\n \n \n \"\"\"\n\n # Q: number of GCD queries that will have to be performed.\n # 1 <= Q <= 10^4\n Q = readInt(reader)\n\n for i in range(Q):\n\n # X: GCD of each query\n # 1 <= X <= 10^4\n X = readInt(reader)\n print(X)\n\n \"\"\"\n Your program should output the number of ways modulus 10^9+7 that balls can be drawn from the set, so that their GCD equals the number X corresponding to each query. \nNote: There is a newline character at the end of the last line of the output.\n \"\"\"\nif __name__ == \"__main__\":\n main(sys.argv)","sub_path":"python/ieeextreme/n08/playwithgcd/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"251622967","text":"from flask import escape\n\n\ndef main(request):\n \"\"\"HTTP Cloud Function.\n Args:\n request (flask.Request): The request object.\n \n Returns:\n The response text, or any set of values that can be turned into a\n Response object using `make_response`\n .\n \"\"\"\n request_json: dict = request.get_json()\n\n if request_json and 'name' in request_json:\n name = request_json['name']\n else:\n name = 'World'\n return 'Ahoyhoy: {}!'.format(escape(name))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"244303459","text":"# coding: utf-8\n\"\"\"Abstract card input for NN.\n\nReturn stage.\n\nReturn board cards.\nReturn hole cards.\n\"\"\"\n\n\nclass Info:\n \"\"\"Abstract card information.\"\"\"\n\n def __init__(self, actions, board, hole_cards, position, stage):\n self.hole_cards = hole_cards\n self.position = position\n self.stage = stage\n self.get_accessible_board(board)\n self.process_actions(actions)\n\n def convert_cards_to_tensor(self):\n self.card_tensor = []\n for card in self.board_cards + self.hole_cards:\n if card:\n self.card_tensor.append(card.value)\n self.card_tensor.append(card.color)\n else:\n [self.card_tensor.append(0) for __ in range(2)]\n\n def get_accessible_board(self, board):\n \"\"\"Replace hidden card state.\"\"\"\n if 2 < self.stage:\n self.board_cards = board.cards[:self.stage] + \\\n (5 - self.stage) * [0]\n else:\n self.board_cards = 5 * [0]\n\n def get_input(self):\n \"\"\"Return 22 dimension tensor.\"\"\"\n self.convert_cards_to_tensor()\n return [self.position] + [self.stage] + self.card_tensor + \\\n self.abstract_betting_round\n\n def process_actions(self, actions):\n actions_length = len(actions)\n if actions_length < 6:\n actions = (6 - actions_length) * [0] + actions\n self.abstract_betting_round = []\n for action in actions[-6:]:\n if action:\n self.abstract_betting_round.append(action.bet)\n else:\n self.abstract_betting_round.append(-1)\n","sub_path":"poker_ai/blueprint/abstraction/information.py","file_name":"information.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"622465802","text":"import random\r\nimport time\r\nspeed_val={\r\n 1:0.4,\r\n 2:0.3,\r\n 3:0.2,\r\n 4:0.1,\r\n 5:0\r\n\r\n}\r\n\r\nclass Algorithms():\r\n def __init__(self, name,size=25,speed=1):\r\n self.array = random.sample(range(50, 450), size)\r\n self.name = name\r\n global speed_val\r\n self.speed=speed_val[speed]\r\n\r\n def update_screen(self, swap1=None, swap2=None, parse=None, mid=None, end=None, temp=None):\r\n import sorting_visualizer\r\n if self.name == \"Bubble Sort\":\r\n sorting_visualizer.update_bubblesort(self, swap1, swap2, parse)\r\n if self.name == \"Selection Sort\":\r\n sorting_visualizer.update_selectionsort(self, swap1, swap2, parse)\r\n if self.name == \"Insertion Sort\":\r\n sorting_visualizer.update_insertionsort(self, swap1, swap2, parse)\r\n if self.name == \"Merge Sort\":\r\n sorting_visualizer.update_mergesort(\r\n self, swap1, swap2, parse, mid, end, temp)\r\n if self.name == \"Quick Sort\":\r\n sorting_visualizer.update_quicksort(\r\n self, swap1, swap2, parse, mid, end)\r\n if self.name == \"Heap Sort\":\r\n sorting_visualizer.update_heapsort(self, swap1, swap2, parse, mid)\r\n\r\n def run(self):\r\n self.start_time = time.time()\r\n self.algorithm()\r\n self.end_time = time.time() - self.start_time\r\n return self.end_time\r\n\r\n\r\nclass BubbleSort(Algorithms):\r\n def __init__(self,size,speed):\r\n super().__init__(\"Bubble Sort\",size,speed)\r\n\r\n def algorithm(self):\r\n for i in range(len(self.array)+1):\r\n for j in range((len(self.array)-1-i)):\r\n if self.array[j] > self.array[j+1]:\r\n self.array[j], self.array[j + 1] = self.array[j+1], self.array[j]\r\n self.update_screen(self.array[j], self.array[j+1], i)\r\n time.sleep(self.speed)\r\n if i == len(self.array) or i == len(self.array)+1:\r\n self.update_screen(self.array[j], self.array[j + 1], i)\r\n\r\n\r\nclass SelectionSort(Algorithms):\r\n def __init__(self,size,speed):\r\n super().__init__(\"Selection Sort\",size,speed)\r\n\r\n def algorithm(self):\r\n for i in range(len(self.array)+1):\r\n\r\n smallest = i\r\n if i < len(self.array):\r\n for j in range(i, len(self.array)):\r\n if self.array[j] < self.array[smallest]:\r\n smallest = j\r\n self.update_screen(self.array[smallest], self.array[j], i)\r\n time.sleep(self.speed)\r\n self.array[smallest], self.array[i] = self.array[i], self.array[smallest]\r\n if i == len(self.array):\r\n self.update_screen(swap1=None, swap2=None, parse=i)\r\n\r\n\r\nclass InsertionSort(Algorithms):\r\n def __init__(self,size,speed):\r\n super().__init__(\"Insertion Sort\",size,speed)\r\n\r\n def algorithm(self):\r\n\r\n for i in range(1, len(self.array)):\r\n temp = self.array[i]\r\n j = i-1\r\n while j >= 0 and self.array[j] > temp:\r\n self.array[j+1] = self.array[j]\r\n j -= 1\r\n self.update_screen(i, j, temp)\r\n time.sleep(self.speed)\r\n self.array[j+1] = temp\r\n self.update_screen(i)\r\n time.sleep(self.speed)\r\n\r\n\r\nclass MergeSort(Algorithms):\r\n def __init__(self,size,speed):\r\n super().__init__(\"Merge Sort\",size,speed)\r\n\r\n def algorithm(self):\r\n self.merge_sort(0, len(self.array)-1)\r\n self.update_screen(None, None, None, None, None, [])\r\n\r\n def merge_sort(self, start, end):\r\n if start < end:\r\n mid = (start+end)//2\r\n self.merge_sort(start, mid)\r\n self.merge_sort(mid+1, end)\r\n self.merge(start, mid, end)\r\n\r\n def merge(self, start, mid, end):\r\n i = start\r\n j = mid+1\r\n temp = []\r\n while i <= mid and j <= end:\r\n self.update_screen(i, j, start, mid, end, temp)\r\n time.sleep(self.speed)\r\n if self.array[i] < self.array[j]:\r\n temp.append(self.array[i])\r\n i += 1\r\n else:\r\n temp.append(self.array[j])\r\n j += 1\r\n\r\n\r\n while i <= mid:\r\n self.update_screen(i, j, start, mid, end, temp)\r\n time.sleep(self.speed)\r\n temp.append(self.array[i])\r\n i += 1\r\n\r\n while j <= end:\r\n self.update_screen(i, j, start, mid, end, temp)\r\n time.sleep(self.speed)\r\n temp.append(self.array[j])\r\n j += 1\r\n\r\n self.array[start:end+1] = temp\r\n self.update_screen(None, None, start, mid, end, [])\r\n time.sleep(self.speed)\r\n\r\n\r\nclass QuickSort(Algorithms):\r\n def __init__(self,size,speed):\r\n super().__init__(\"Quick Sort\",size,speed)\r\n\r\n def algorithm(self):\r\n start = 0\r\n end = len(self.array)-1\r\n self.quick_sort(start, end)\r\n\r\n def sort(self, start, end):\r\n pivot = start\r\n i = start\r\n j = start+1\r\n\r\n while j <= end:\r\n if self.array[j] < self.array[pivot]:\r\n i += 1\r\n self.array[j], self.array[i] = self.array[i], self.array[j]\r\n self.update_screen(i, j, start, end)\r\n time.sleep(self.speed)\r\n\r\n j += 1\r\n\r\n self.array[i], self.array[pivot] = self.array[pivot], self.array[i]\r\n pivot = i\r\n self.update_screen(i, j, start, end, self.array[pivot])\r\n time.sleep(self.speed)\r\n return pivot\r\n\r\n def quick_sort(self, start, end):\r\n if start <= end:\r\n pivot = self.sort(start, end)\r\n self.quick_sort(start, pivot-1)\r\n self.quick_sort(pivot+1, end)\r\n\r\n\r\nclass HeapSort(Algorithms):\r\n def __init__(self,size,speed):\r\n super().__init__(\"Heap Sort\",size,speed)\r\n\r\n def algorithm(self):\r\n length = len(self.array)\r\n i = (length-2)//2\r\n while i >= 0:\r\n self.heapify(i, length-1, 0)\r\n i -= 1\r\n\r\n for i in range(len(self.array)):\r\n self.array[0], self.array[length -1] = self.array[length-1], self.array[0]\r\n length -= 1\r\n self.heapify(0, length-1, i)\r\n self.update_screen(-1,-1,-1, len(self.array)+1)\r\n\r\n def heapify(self, index, end, parse):\r\n largest = index\r\n right_child = (index*2)+2\r\n left_child = (index*2)+1\r\n if (right_child <= end) and self.array[right_child] > self.array[largest]:\r\n largest = right_child\r\n if (left_child <= end) and self.array[left_child] > self.array[largest]:\r\n largest = left_child\r\n self.update_screen(index, right_child, left_child, parse)\r\n time.sleep(self.speed)\r\n if(index != largest):\r\n\r\n self.array[index], self.array[largest] = self.array[largest], self.array[index]\r\n self.heapify(largest, end, parse)\r\n\r\n\r\n#\r\n# algo=HeapSort()\r\n# print(algo.array)\r\n# x=sorted(algo.array)\r\n# algo.run()\r\n# print(algo.array)\r\n# if x == algo.array:\r\n# print(True)\r\n","sub_path":"sorting_algorithm.py","file_name":"sorting_algorithm.py","file_ext":"py","file_size_in_byte":7140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"147080416","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\n#1 for spam 0 for ham\n#parameters\nfeatures_header = ['height','width','aspect_ratio','compression_ratio','file_size','image_area',\n 'entr_color','b_mean','g_mean','r_mean',\n 'r_skew','g_skew','b_skew',\n 'r_var','g_var','b_var',\n 'r_kurt','g_kurt','b_kurt',\n 'entr_hsv','h_mean','s_mean','v_mean',\n 'h_skew','s_skew','v_skew',\n 'h_var','s_var','v_var',\n 'h_kurt','s_kurt','v_kurt',\n 'lbp','entr_HOG','edges','avg_edge_len','snr','entr_noise']\n\n\nspam_dataset_path = \"Data/Image_Spam_Hunter/ImageHunter_Spam.csv\"\n# ham_dataset_path = \"Data/Image_Spam_Hunter/ImageSpamHunter_Ham.csv\"\n\n# spam_dataset_path = \"Data/Dredze/Dredze_Spam.csv\"\nham_dataset_path = \"Data/Image_Spam_Hunter/ImageSpamHunter_Ham.csv\"\n\n# spam_dataset_path = \"Data/Improved_Spam.csv\"\nimporved_spam_path = \"Data/Improved_Spam.csv\"\n\ntest_size_for_split = 0.2\n\n\ndef read_dataset(path,colmns):\n dataset = pd.read_csv(path,usecols=colmns)\n\n return dataset\n\ndef get_processed_dataset():\n # read dataset\n spam_dataset = read_dataset(spam_dataset_path, features_header)\n ham_dataset = read_dataset(ham_dataset_path, features_header)\n\n # remove duplicates to remove the same image features in dataset\n spam_dataset.drop_duplicates()\n ham_dataset.drop_duplicates()\n\n # add labels\n spam_dataset[\"label\"] = 1\n ham_dataset[\"label\"] = 0\n\n # join all dataset\n dataset = pd.concat([spam_dataset, ham_dataset])\n\n # X, Y features\n X = dataset.iloc[:, :38].values\n Y = dataset.iloc[:, 38].values\n\n # split the dataset\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=test_size_for_split, random_state=0)\n\n # scale the features\n sc = StandardScaler()\n X_train = sc.fit_transform(X_train)\n X_test = sc.transform(X_test)\n\n return X_train,X_test,Y_train,Y_test\n\ndef get_processed_improved_dataset():\n # read dataset\n spam_dataset = read_dataset(spam_dataset_path, features_header)\n ham_dataset = read_dataset(ham_dataset_path, features_header)\n improved_spam_dataset = read_dataset(imporved_spam_path,features_header)\n\n # remove duplicates to remove the same image features in dataset\n spam_dataset.drop_duplicates()\n ham_dataset.drop_duplicates()\n improved_spam_dataset.drop_duplicates() \n \n # add labels\n spam_dataset[\"label\"] = 1\n ham_dataset[\"label\"] = 0\n improved_spam_dataset[\"label\"] = 1\n \n # join all dataset\n dataset = pd.concat([spam_dataset, ham_dataset])\n\n # X, Y features\n X = dataset.iloc[:, :38].values\n Y = dataset.iloc[:, 38].values\n Improved_spam_features = improved_spam_dataset.iloc[:, :38].values\n Improved_spam_label = improved_spam_dataset.iloc[:, 38].values\n\n # split the dataset\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=test_size_for_split, random_state=0)\n\n # scale the features\n sc = StandardScaler()\n X_train = sc.fit_transform(X_train)\n X_test = sc.transform(X_test)\n Improved_spam_features = sc.transform(Improved_spam_features)\n\n return X_train,X_test,Y_train,Y_test,Improved_spam_features,Improved_spam_label\n","sub_path":"Model_preprocessing.py","file_name":"Model_preprocessing.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"145552814","text":"from apps.user.models import NavBar, EnNavBar\n\nfrom apps.user.constants import position_type\n\n\ndef get_all_navbar(context=dict()):\n \"\"\"\n 中文: 获取对应的nav导航\n \"\"\"\n nav_list = NavBar.objects.filter(is_published=True).order_by('nav_num')\n\n context.update({'navbar': nav_list})\n\n return context\n\n\ndef en_get_all_navbar(context=dict()):\n \"\"\"\n 英文: 获取对应的nav导航\n \"\"\"\n nav_list = EnNavBar.objects.filter(is_published=True).order_by('nav_num')\n context.update({'navbar': nav_list})\n return context\n\n\ndef get_next_news_not_position(news_obj):\n \"\"\" 下一篇文章防止是'招聘信息' \"\"\"\n if news_obj:\n if news_obj.types.typename == position_type:\n news_obj = news_obj.get_next_by_create_time()\n return get_next_news_not_position(news_obj)\n else:\n return news_obj\n\n\ndef get_pre_news_not_position(news_obj):\n \"\"\" 上一篇文章防止是'招聘信息' \"\"\"\n if news_obj:\n if news_obj.types.typename == position_type:\n news_obj = news_obj.get_previous_by_create_time()\n return get_pre_news_not_position(news_obj)\n else:\n return news_obj\n\n\ndef serializer_function(sf, objects, is_many=False):\n if is_many:\n serializer = sf.serializer_class(objects, many=is_many)\n else:\n serializer = sf.serializer_class(objects)\n\n return serializer.data\n","sub_path":"apps/user/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"378385087","text":"\nimport json\n\n\ndef parse_topology(p):\n filepath = p\n seen = set()\n\n with open(filepath) as fp:\n line = fp.readline()\n seen = set()\n dict = {'nodes': [], 'links': []}\n count = 0\n while line:\n count += 1\n if count == 1:\n line = fp.readline()\n continue\n pieces = line.strip().split(', ')\n to_node = pieces[0]\n from_node = pieces[1]\n capacity = pieces[2]\n prob_failure = pieces[3]\n\n if to_node not in seen:\n seen.add(to_node)\n dict['nodes'].append({\"id\": to_node})\n if from_node not in seen:\n seen.add(from_node)\n dict['nodes'].append({\"id\": from_node})\n\n dict['links'].append({'source': from_node, 'target': to_node, 'capacity': capacity, 'prob_failure': prob_failure})\n line = fp.readline()\n return dict\n\n\nparsed_json = parse_topology('./Custom.txt')\n\nwith open('./Custom.json', 'w') as fp:\n json.dump(parsed_json, fp)\n","sub_path":"www/frontend/src/force_graph/data/parse_topology.py","file_name":"parse_topology.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"524454581","text":"from .. import Availability, Class, Constant, Define, Method, Parameter, Type\n\ngx_class = Class('SAGAX',\n doc=\"Technical Services GX functions Header File for Sagax\")\n\ngx_defines = [\n]\n\n\ngx_methods = {\n 'Sagax IP': [\n\n Method('PlotXYZIP_SAGAX', module='geocssagax', version='6.3.0',\n availability=Availability.EXTENSION,\n doc=\"Create an IP plot from a RESINV2D XYZ file.\",\n return_type=Type.VOID,\n return_doc=\"Nothing\",\n parameters = [\n Parameter('param0', type=\"IP\",\n doc=\"IP handle\"),\n Parameter('param1', type=\"DB\",\n doc=\"DB handle\"),\n Parameter('param2', type=Type.STRING,\n doc=\"XYZ file name\"),\n Parameter('param3', type=Type.STRING,\n doc=\"map name\"),\n Parameter('param4', type=Type.STRING,\n doc=\"IP plot control file name (optional)\"),\n Parameter('param5', type=Type.INT32_T,\n doc=\"XYZ File Format 0:Original;1:RES2DINV XYZ file type\")\n ])\n ]\n}\n\n","sub_path":"spec/ps/SAGAX.py","file_name":"SAGAX.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"301986733","text":"import pandas as pd\nimport numpy as np\nimport pickle\nimport copy\nimport streamlit as st\nimport surprise\nfrom surprise import Reader, Dataset\nfrom surprise import SVD, NormalPredictor, BaselineOnly, KNNBasic, NMF\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n# Importing data\nproducts_df = pd.read_csv('resources/data/product.csv',sep = ',', index_col=0)\nratings_df = pd.read_csv('resources/data/ratings.csv',sep = ',', index_col=0)\n\nmin_rat = ratings_df['rating'].min()\nmax_rat = ratings_df['rating'].max()\n\nusers=ratings_df['userId'].unique()\n#import tensorflow as tf\n#model=tf.keras.models.load_model('resources/models/my_model.h5')\nmodel=pickle.load(open('resources/models/SVD.pkl', 'rb'))\n\ndef prediction_item(productId):\n \n # Data preprosessing\n reader = Reader(rating_scale = (min_rat,max_rat))\n load_df = Dataset.load_from_df(ratings_df[['userId', 'productId', 'rating']],reader)\n predictions = []\n for ui in users:\n predictions.append(model.predict(iid=productId,uid=ui, verbose = False))\n return predictions\n\ndef pred_products(product_list):\n \n # Store the id of users\n id_store=[]\n for i in product_list:\n predictions = prediction_item(productId = i)\n predictions.sort(key=lambda x: x.est, reverse=True)\n # Take the top 10 user id's from each product with highest rankings\n for pred in predictions[:10]:\n id_store.append(pred.uid)\n # Return a list of user id's\n return id_store\n \ndef collab_model(product_list,top_n=3):\n indices = pd.Series(products_df['productId'])\n product_ids = pred_products(product_list)\n df_init_users = ratings_df[ratings_df['userId']==product_ids[2]]\n\n \n #df_init_users=0\n for i in product_ids :\n df_init_users=df_init_users.append(ratings_df[ratings_df['userId']==i])\n\n # count_vec = CountVectorizer()\n # count_matrix = count_vec.fit_transform(df_init_users)\n #Getting the cosine similarity matrix\n cosine_sim = cosine_similarity(np.array(df_init_users), np.array(df_init_users))\n idx_1 = indices[indices == product_list[0]].index[0]\n idx_2 = indices[indices == product_list[1]].index[0]\n idx_3 = indices[indices == product_list[2]].index[0]\n # Creating a Series with the similarity scores in descending order\n rank_1 = cosine_sim[idx_1]\n rank_2 = cosine_sim[idx_2]\n rank_3 = cosine_sim[idx_3]\n # Calculating the scores\n score_series_1 = pd.Series(rank_1).sort_values(ascending = False)\n score_series_2 = pd.Series(rank_2).sort_values(ascending = False)\n score_series_3 = pd.Series(rank_3).sort_values(ascending = False)\n # Appending the names of products\n listings = score_series_1.append(score_series_1).append(score_series_3).sort_values(ascending = False)\n recommended_products = []\n # Choose top 50\n top_50_indexes = list(listings.iloc[1:50].index)\n # Removing chosen products\n top_indexes = np.setdiff1d(top_50_indexes,[idx_1,idx_2,idx_3])\n for i in top_indexes[:top_n]:\n recommended_products.append(list(products_df['title'])[i])\n return recommended_products","sub_path":"recommenders/collaborative_based.py","file_name":"collaborative_based.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"107037276","text":"import unittest\nfrom contextlib import redirect_stdout\nfrom io import StringIO\nfrom ukoly.kapitola3.concatenate import *\n\n\nclass MyTestCase(unittest.TestCase):\n def setUp(self):\n self.out = StringIO()\n\n def test_concatenate_with_percentage_operator(self):\n with redirect_stdout(self.out):\n concatenate_with_percentage_operator()\n self.assertEqual(self.out.getvalue(), \"Jmenuji se Boromir a jsem clovek. Moji oblibenou zbrani se stal mec \"\n \"a muj ukol je ochranit nositele prstenu moci.\\n\")\n\n def test_concatenate_with_format(self):\n with redirect_stdout(self.out):\n concatenate_with_format()\n self.assertEqual(self.out.getvalue(), \"Jmenuji se Boromir a jsem clovek. Moji oblibenou zbrani se stal mec \"\n \"a muj ukol je ochranit nositele prstenu moci.\\n\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"ukoly/kapitola3/test/concatenate_test.py","file_name":"concatenate_test.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"101266583","text":"\nimport threading as thr\nimport binance_trading.utils as ut\nimport get_price.get_binance_price as gbp\nimport shared.log as lg\nimport datetime as dt\nimport time as tm\nimport numpy as np\nfrom unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager\n\n\nclass Strategy:\n\n @classmethod\n def algo(cls, **kwargs):\n\n cls.ticker = kwargs['ticker']\n cls.interval = '1h'\n cls.client = ut.get_binanceUS_client()\n cls.log = lg.get_logger(file_identifier='binance_breakout', log_level='INFO')\n\n binance_websocket_api_manager = BinanceWebSocketApiManager(exchange=\"binance.us\")\n binance_websocket_api_manager.create_stream([\"depth20\"], {'ethusd'})\n\n ubwa = BinanceWebSocketApiManager(exchange=\"binance.us\")\n ubwa.create_stream(['trade', 'kline_1m'], ['btcusdt', 'bnbbtc', 'ethbtc'])\n\n while True:\n oldest_data_from_stream_buffer = ubwa.pop_stream_data_from_stream_buffer()\n if oldest_data_from_stream_buffer:\n print(oldest_data_from_stream_buffer)\n\n history_start_datetime = dt.datetime.now() + dt.timedelta(days=-19)\n cls.candle_history = gbp.get_klines(ticker=cls.ticker, interval=cls.interval,\n start_str=history_start_datetime.strftime('%m/%d/%y'), client=cls.client)\n\n cls.candle_history['ewm200'] = cls.candle_history['close'].ewm(span=200, adjust=True, min_periods=150).mean()\n cls.candle_history['ewm50'] = cls.candle_history['close'].ewm(span=50, adjust=True, min_periods=35).mean()\n cls.trend_status = 0\n\n cls.candle_history['hh'] = cls.candle_history['high'].rolling(10, min_periods=10).max()\n cls.candle_history['ll'] = cls.candle_history['low'].rolling(10, min_periods=10).min()\n\n cls.candle_history['percent_range'] = 100 * (cls.candle_history['hh'] - cls.candle_history['ll']) / cls.candle_history['ll']\n\n cls.percent_range_h = max(cls.candle_history['percent_range'].iloc[-169:-1])\n cls.percent_range_l = min(cls.candle_history['percent_range'].iloc[-169:-1])\n cls.percent_range_o = 100*(cls.candle_history['percent_range'].iloc[-2]-cls.percent_range_l)/(cls.percent_range_h-cls.percent_range_l)\n\n cls.price_location = 100*(cls.candle_history['close'].iloc[-2]-cls.candle_history['ewm200'].iloc[-2])/cls.candle_history['ewm200'].iloc[-2]\n\n cls.last_complete_candle_indx = -2\n cls.check_trend_status(reference_indx=cls.last_complete_candle_indx)\n cls.check_price_location()\n\n if cls.percent_range_o < 20:\n cls.price_compression_Q = True\n print('Price Compression: TRUE, percent_range_o: ' + str(round(cls.percent_range_o, 1)) +\n ', percent_range: ' + str(round(cls.candle_history['percent_range'].iloc[-2], 2)))\n else:\n cls.price_compression_Q = False\n print('Price Compression: FALSE, percent_range_o: ' + str(round(cls.percent_range_o, 1)) +\n ', percent_range: ' + str(round(cls.candle_history['percent_range'].iloc[-2], 2)))\n\n cls.candle_frame_needs_update_Q = True\n\n cls.periodic_call()\n\n @classmethod\n def periodic_call(cls):\n\n time_res = cls.client.get_server_time()\n cls.current_datetime = dt.datetime.fromtimestamp(time_res['serverTime']/1000, tz=dt.timezone.utc)\n\n if cls.current_datetime.minute < 2 and cls.candle_frame_needs_update_Q:\n data_start_datetime = cls.current_datetime + dt.timedelta(hours=-3)\n new_data = gbp.get_klines(ticker=cls.ticker, interval=cls.interval,\n start_str=data_start_datetime.strftime('%m/%d/%y, %H:%M:%S'), client=cls.client)\n\n new_data['ewm200'] = np.nan\n new_data['ewm50'] = np.nan\n new_data['hh'] = np.nan\n new_data['ll'] = np.nan\n new_data['percent_range'] = np.nan\n\n if new_data.iloc[-1]['openDatetime'].hour == cls.current_datetime.hour:\n if new_data.iloc[-2]['openTime'] == cls.candle_history.iloc[-1]['openTime']:\n\n cls.candle_history = cls.candle_history[:-1]\n cls.candle_history = cls.candle_history.append(new_data.iloc[-2])\n\n print('Successful candle replacement!')\n cls.update_indicators()\n\n elif new_data.iloc[-2]['openTime']-cls.candle_history.iloc[-1]['openTime'] == 3600000:\n\n cls.candle_history = cls.candle_history.append(new_data.iloc[-2])\n\n print('Successful candle attachment!')\n cls.update_indicators()\n\n elif cls.current_datetime.minute > 2:\n cls.candle_frame_needs_update_Q = True\n\n if (cls.trend_status > 0) and cls.price_compression_Q and cls.price_location_good_Q:\n market_depth = cls.client.get_order_book(symbol=cls.ticker)\n mid_price = (float(market_depth['bids'][0][0]) + float(market_depth['asks'][0][0]))/2\n\n if mid_price>cls.candle_history['hh'].iloc[cls.last_complete_candle_indx]:\n print(10*'-')\n print('BULLISH BREAKOUT: GO LONG')\n print(10*'-')\n\n thr.Timer(1, cls.periodic_call).start()\n\n @classmethod\n def update_ewma(cls, **kwargs):\n\n field_name = 'ewm' + str(kwargs['window_length'])\n alpha = 2/(kwargs['window_length']+1)\n\n cls.candle_history[field_name].iloc[-1] = alpha * cls.candle_history['close'].iloc[-1] +\\\n (1 - alpha) * cls.candle_history[field_name].iloc[-2]\n\n @classmethod\n def check_trend_status(cls, **kwargs):\n\n reference_indx = kwargs['reference_indx']\n\n if cls.candle_history['ewm50'].iloc[reference_indx] > cls.candle_history['ewm200'].iloc[reference_indx]:\n print('Trend Status: UP')\n cls.trend_status = 1\n elif cls.candle_history['ewm50'].iloc[reference_indx] < cls.candle_history['ewm200'].iloc[reference_indx]:\n print('Trend Status: DOWN')\n cls.trend_status = -1\n\n @classmethod\n def check_price_location(cls):\n if (cls.price_location > 1.96) and (cls.price_location < 7.46):\n cls.price_location_good_Q = True\n print('Price location: GOOD')\n else:\n cls.price_location_good_Q = False\n print('Price location: BAD')\n\n @classmethod\n def update_indicators(cls):\n\n cls.update_ewma(window_length=200)\n cls.update_ewma(window_length=50)\n\n cls.candle_history['hh'].iloc[-1] = max(cls.candle_history['high'].iloc[-10:])\n cls.candle_history['ll'].iloc[-1] = min(cls.candle_history['low'].iloc[-10:])\n\n cls.candle_history['percent_range'].iloc[-1] = 100 * (\n cls.candle_history['hh'].iloc[-1] - cls.candle_history['ll'].iloc[-1]) / \\\n cls.candle_history['ll'].iloc[-1]\n\n cls.percent_range_h = max(cls.candle_history['percent_range'].iloc[-168:])\n cls.percent_range_l = min(cls.candle_history['percent_range'].iloc[-168:])\n cls.percent_range_o = 100 * (cls.candle_history['percent_range'].iloc[-1] - cls.percent_range_l) / (\n cls.percent_range_h - cls.percent_range_l)\n\n cls.price_location = 100 * (cls.candle_history['close'].iloc[-1] - cls.candle_history['ewm200'].iloc[-1]) / \\\n cls.candle_history['ewm200'].iloc[-1]\n\n cls.check_price_location()\n cls.check_trend_status(reference_indx=-1)\n\n if cls.percent_range_o < 20:\n cls.price_compression_Q = True\n print('Price Compression: TRUE, percent_range_o: ' + str(round(cls.percent_range_o, 1)) +\n ', percent_range: ' + str(round(cls.candle_history['percent_range'].iloc[-1], 2)))\n else:\n cls.price_compression_Q = False\n print('Price Compression: FALSE, percent_range_o: ' + str(round(cls.percent_range_o, 1)) +\n ', percent_range: ' + str(round(cls.candle_history['percent_range'].iloc[-1], 2)))\n\n cls.last_complete_candle_indx = -1\n print(cls.current_datetime.strftime('%m/%d/%y, %H:%M:%S'))\n\n cls.candle_frame_needs_update_Q = False\n\n\ndef on_message(ws, message):\n print(message)\n\n\ndef on_close(ws):\n print('### closed ###')\n\n\n\nif __name__ == \"__main__\":\n\n Strategy.algo(ticker='ETHUSD')\n\n #fail_count = 0\n #run = True\n #while run:\n # try:\n # print('Running!')\n # Strategy.algo(ticker='ETHUSD')\n # except requests.exceptions.ConnectionError as e:\n # fail_count += 1\n # print('Caught exception: ', e)\n # tm.sleep(30)\n\n\n\n\n\n\n","sub_path":"PycharmProjects/binance_trading/binance_breakout_algo.py","file_name":"binance_breakout_algo.py","file_ext":"py","file_size_in_byte":8791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"358023354","text":"import os, datetime\nfrom PyQt5.QtCore import (\n QObject,\n pyqtSignal,\n pyqtSlot,\n QVariant,\n QDateTime,\n QFile,\n QFileInfo,\n QIODevice,\n QMessageLogger,\n QByteArray,\n QBuffer\n)\nfrom PyQt5.QtGui import (\n QImage,\n)\n\nfrom pymongo import MongoClient, ReadPreference\nfrom bson.objectid import ObjectId\nfrom bson.timestamp import Timestamp\nimport gridfs\n\nfrom qtwebapp.mime import MIMETYPE\nfrom qtwebapp.util import json_dumps, json_loads\nlogging = QMessageLogger()\n\nIMAGEFORMAT = {\n\t'image/bmp':'BMP',\n\t'image/gif':'GIF',\n\t'image/jpeg':'JPG',\n\t'image/png':'PNG',\n\t'image/x-portable-bitmap':'PBM',\n\t'image/x-portable-graymap':'PGM',\n\t'image/x-portable-pixmap':'PPM',\n\t'image/x-xbitmap':'XBM',\n\t'image/x-xpixmap':'XPM',\n\t'image/svg+xml':'SVG',\n}\ndef newId():\n return str(ObjectId())\nclass QtNonSqlMongoDatabaseError(Exception):\n pass\n\nclass QtNonSqlMongoDatabase(QObject):\n signalDocumentFind = pyqtSignal(str)\n def __init__(self, host = None, port = 27017, username=None, password=None, authMechanism='SCRAM-SHA-1', database=None, parent=None):\n super(QtNonSqlMongoDatabase, self).__init__(parent)\n self._parent = parent\n self._db = None\n\n if host is None or len(host) == 0:\n raise QtNonSqlMongoDatabaseError('host cannot be null')\n if port is None or port == 0:\n raise QtNonSqlMongoDatabaseError('port cannot be null or 0')\n if username and password:\n self._conn = MongoClient(host=host,\n port=port,\n username=username,\n password=password,\n authSource=database,\n authMechanism=authMechanism\n )\n else:\n self._conn = MongoClient(host=host, port=port)\n self._db = self._conn[database]\n\n def SwitchDB(self, database):\n if database and database in self._conn.database_names():\n self._db = self._conn[database]\n else:\n self._db = None\n\n\n\n def Close(self):\n self._conn.close()\n\n def IsTableExist(self, name):\n return self._db and name and name in self._db.collection_names()\n\n def CreateTables(self):\n pass\n\n def ResizeImage(self, imgs, size=0):\n global IMAGEFORMAT\n ret = imgs\n if size:\n ret = []\n for i in imgs:\n img = QImage.fromData(i['data'])\n w, h = img.width(), img.height()\n maxlen = max([w, h])\n img1 = None\n if maxlen == w:\n img1 = img.scaledToWidth(size)\n elif maxlen == h:\n img1 = img.scaledToHeight(size)\n if img1 and i['mimetype'] in IMAGEFORMAT:\n ba = QByteArray()\n buf = QBuffer(ba)\n buf.open(QIODevice.WriteOnly)\n img1.save(buf, IMAGEFORMAT[i['mimetype']])\n i['data'] = ba.data()\n ret.append(i)\n return ret\n\n def GridfsSave(self, cond={}, data=b'', is_overwrite=False, collection='fs', **kwargs):\n if not 'mimetype' in cond or len(cond['mimetype']) == 0:\n logging.critical('mongodb: mimetype cannot be null')\n return\n mimetype = cond['mimetype']\n\n if not 'filename' in cond or len(cond['filename']) == 0:\n logging.critical('mongodb: filename cannot be null')\n return\n filename = cond['filename']\n\n fs = gridfs.GridFS(self._db, collection=collection)\n if is_overwrite:\n try:\n for i in fs.find({'filename':cond['filename']}):\n fs.delete(i._id)\n fs.put(data, contentType=mimetype, filename=filename, **kwargs)\n except Exception as e:\n logging.critical('mongodb: gridfs put error:{}'.format(str(e)))\n else:\n try:\n fs.put(data, contentType=mimetype, filename=filename, **kwargs)\n except Exception as e:\n logging.critical('mongodb: gridfs put error:{}'.format(str(e)))\n\n def GridfsDelete(self, cond={}, collection='fs'):\n try:\n fs = gridfs.GridFS(self._db, collection=collection)\n if fs.exists(cond):\n l = []\n for i in fs.find(cond):\n l.append(i._id)\n for i in l:\n fs.delete(i)\n except Exception as e:\n logging.critical('mongodb: gridfs delete error:{}'.format(str(e)))\n\n def GetBinaryFile(self, cond={}, collection='fs'):\n ret = []\n fs = gridfs.GridFS(self._db, collection=collection)\n # now = QDateTime.currentDateTime().toString('yyyyMMddHHmmss')\n limit = 20\n skip = 0\n if 'limit' in cond:\n limit = cond['limit']\n del cond['limit']\n if 'skip' in cond:\n skip = cond['skip']\n del cond['skip']\n for i in fs.find(cond).limit(limit).skip(skip):\n ret.append({\n '_id': i._id,\n 'filename': i.filename,\n 'mimetype': i.contentType,\n 'data': i.read()\n })\n return ret\n\n\n def DeleteBinaryFile(self, cond={}, collection='fs'): #filename, uploadDate, length, contentType\n self.GridfsDelete(cond=cond, collection=collection)\n\n\n\n def SaveBinaryFile(self, cond={}, path=None, data=b'', is_overwrite=False):\n mimetype = 'application/octet-stream'\n filename = None\n if path :\n fi = QFileInfo(path)\n if fi.exists():\n filename = os.path.basename(path)\n cond['filename'] = filename\n ext = '.bin'\n if '.' in filename:\n ext = filename[filename.rindex('.'):]\n if ext in MIMETYPE:\n mimetype = MIMETYPE[ext]\n cond['mimetype'] = mimetype\n f = QFile(fi.absoluteFilePath())\n if f.open(QIODevice.ReadOnly):\n data = f.readAll().data()\n if f.isOpen():\n f.close()\n else:\n logging.critical('SaveBinaryFile:{} not exist'.format(path).encode('utf-8'))\n return\n if len(data) == 0:\n logging.critical('SaveBinaryFile:data cannot be null')\n return\n self.GridfsSave(cond=cond, data=data, is_overwrite=is_overwrite)\n\n\n\n\n\n\n def InsertDocuments(self, arr=[], table=None):\n if self.IsTableExist(table):\n if isinstance(arr, map):\n arr = list(arr)\n if len(arr):\n self._db[table].insert_many(self._convert2bson(arr))\n\n def InsertDocument(self, obj, table=None):\n ret = None\n if self.IsTableExist(table):\n ret = self._db[table].insert_one(self._convert2bson(obj))\n return ret\n\n\n def QueryCount(self, cond={}, table=None):\n count = 0\n if self.IsTableExist(table):\n cur = self._db[table].find(cond)\n count = cur.count()\n return count\n\n def _convert2dict(self, o):\n if isinstance(o, Timestamp):\n dt = o.as_datetime()\n o = dt.timestamp() #.strftime('%Y-%m-%d %H:%M:%S.%f')\n elif isinstance(o, datetime.datetime):\n o = o.timestamp()\n # elif isinstance(o, QDateTime):\n # o = o.toMSecsSinceEpoch()\n elif isinstance(o, ObjectId):\n o = str(o)\n elif isinstance(o, dict):\n for k in o:\n o[k] = self._convert2dict(o[k])\n elif isinstance(o, list):\n o = list(map(self._convert2dict, o))\n return o\n\n def _convert2bson(self, o, timekeys=['timestamp',]):\n if isinstance(o, QDateTime):\n o = o.toPyDateTime() # datetime.datetime.strptime(o.toString('yyyy-MM-dd HH:mm:ss'), '%Y-%m-%d %H:%M:%S')\n elif isinstance(o, str) :\n if len(o) == 24:\n try:\n id = ObjectId(o)\n gt = id.generation_time\n o = id\n return o\n except:\n pass\n d = None\n try:\n d = datetime.datetime.strptime(o, '%Y-%m-%d %H:%M:%S.%f')\n except:\n try:\n d = datetime.datetime.strptime(o, '%Y-%m-%d %H:%M:%S')\n except:\n try:\n d = datetime.datetime.strptime(o, '%Y-%m-%d')\n except:\n d = None\n if d:\n o = d\n elif isinstance(o, dict):\n for k in o:\n if k in timekeys and (isinstance(o[k], int) or isinstance(o[k], float)):\n o[k] = datetime.datetime.fromtimestamp(o[k])\n else:\n o[k] = self._convert2bson(o[k])\n elif isinstance(o, list):\n o = list(map(self._convert2bson, o))\n return o\n\n\n\n def QueryOne(self, cond={}, table=None):\n if self.IsTableExist(table):\n o = self._db[table].find_one(cond)\n if o:\n return self._convert2dict(o)\n else:\n return None\n else:\n return None\n\n\n def QueryDocuments(self, cond={}, table=None, limit=0, skip=0, is_emit=False):\n if self.IsTableExist(table):\n for i in self._db[table].find(cond).limit(limit).skip(skip):\n o = self._convert2dict(i)\n if is_emit:\n self.signalDocumentFind.emit(json_dumps(o))\n yield o\n else:\n return None\n\n\n def UpdateDocument(self, cond={}, table=None, update={}):\n if self.IsTableExist(table):\n self._db[table].find_one_and_update(cond, {'$set': update})\n\n def UpdateDocuments(self, cond={}, table=None, update={}):\n if self.IsTableExist(table):\n self._db[table].update_many(cond, {'$set': update})\n\n\n def DeleteDocument(self, cond={}, table=None):\n if self.IsTableExist(table):\n self._db[table].find_one_and_delete(cond)\n\n def DeleteDocuments(self, cond={}, table=None):\n if self.IsTableExist(table):\n self._db[table].delete_many(cond)\n\n","sub_path":"qtnonsqlmongo.py","file_name":"qtnonsqlmongo.py","file_ext":"py","file_size_in_byte":10481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"200617977","text":"# Copyright 2021 Sebastian Ahmed\n# This file, and derivatives thereof are licensed under the Apache License, Version 2.0 (the \"License\");\n# Use of this file means you agree to the terms and conditions of the license and are in full 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# Unless required by applicable law or agreed to in writing, software distributed under the License is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESSED OR IMPLIED.\n# See the License for the specific language governing permissions and limitations under the License.\n\nimport math\nfrom fifo_pkg.Fifo import Fifo\nfrom fifo_pkg.FifoSimulator import FifoSimulator\n\ndef init_level(pl_size:int,wrbw:int,rdbw:int)->int:\n # The required depth of the FIFO depends on whether the read or write rate is higher\n wdepth = pl_size * (1.0 - float(rdbw)/float(wrbw))\n rdepth = pl_size * (1.0 - float(wrbw)/float(rdbw))\n return math.ceil(max((wdepth),(rdepth)))\n\ndef test(depth:int,pl_size:int,wrbw:int,rdbw:int,il:int,simQuantum:int,tol=0.30):\n fifo = Fifo(depth=depth,verbose=False)\n sim = FifoSimulator(\n fifoHandle=fifo,\n pl_size=pl_size,\n writeBandwidth=wrbw,\n readBandwidth=rdbw,\n initLevel=il,\n simQuantum=simQuantum)\n\n sim.simulate()\n\n assert not fifo.error, f\"FIFO error ({fifo.errorType})\"\n assert fifo.level == 0, f\"FIFO not emptied (remaining entries={fifo.level})\"\n bw_ltol = float((1.0-tol) * wrbw/rdbw)\n bw_utol = float((1.0+tol) * wrbw/rdbw)\n assert fifo.bwratio > bw_ltol, f\"Simulated W:R bandwidth ratio out of lower-bound ({bw_ltol:.3f})\"\n assert fifo.bwratio < bw_utol, f\"Simulated W:R bandwidth ratio out of upper-bound ({bw_utol:.3f})\"\n\ndef main():\n for _ in range(5):\n test(depth=400,pl_size=200,wrbw=110,rdbw=100,il=40,simQuantum=1)\n il = init_level(200,100,110)\n test(depth=400,pl_size=200,wrbw=100,rdbw=110,il=math.ceil(il*3),simQuantum=1)\n\nif __name__ == '__main__':\n main()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"628961853","text":"\"\"\"\nThe dimod Response object allows dimod Samplers to respond consistently.\n\nThe Response is :class:`~collections.Iterable` (over the samples from lowest energy to highest) and\n:class:`~collections.Sized` (the number of samples in the response).\n\nExamples\n--------\n\n>>> response = dimod.ExactSolver().sample_ising({'a': -0.5}, {})\n>>> len(response)\n2\n>>> for sample in response:\n... print(sample)\n{'a': 1}\n{'a': -1}\n\n\"\"\"\nfrom collections import Mapping, Iterable, Sized, namedtuple\nimport itertools\nimport concurrent.futures\n\nimport numpy as np\nfrom six import itervalues, iteritems\n\nfrom dimod.decorators import vartype_argument\nfrom dimod.vartypes import Vartype\n\n__all__ = ['Response']\n\n\nclass Response(Iterable, Sized):\n \"\"\"A container for the samples and any other data returned by a dimod Sampler.\n\n Args:\n samples_matrix (:obj:`numpy.matrix`):\n A numpy matrix where each row is a sample.\n\n data_vectors (dict[field, :obj:`numpy.array`/list]):\n A dict containing additional per-sample data in vectors. Each vector should be the\n same length as samples_matrix. The key 'energy' and its vector are required.\n\n vartype (:class:`.Vartype`):\n The vartype of the samples.\n\n info (dict, optional, default=None):\n A dict containing information about the response as a whole.\n\n variable_labels (list, optional, default=None):\n Maps (by index) variable labels to the columns of the samples matrix.\n\n Attributes:\n vartype (:class:`.Vartype`): The vartype of the samples.\n\n info (dict): A dictionary containing information about the response as a whole.\n\n variable_labels (list/None): The variable labels. Each column in the samples matrix is the\n values assigned to one variable. If None then the column indices are the labels.\n\n label_to_idx (dict): A mapping from the variable labels to their columns in samples matrix.\n\n \"\"\"\n\n @vartype_argument('vartype')\n def __init__(self, samples_matrix, data_vectors, vartype, info=None, variable_labels=None):\n # Constructor is opinionated about the samples_matrix type, it should be a numpy matrix\n if not isinstance(samples_matrix, np.matrix):\n raise TypeError(\"expected 'samples_matrix' to be a numpy matrix\")\n elif samples_matrix.dtype != np.int8:\n # cast to int8\n samples_matrix = samples_matrix.astype(np.int8)\n\n self._samples_matrix = samples_matrix\n num_samples, num_variables = samples_matrix.shape\n\n if not isinstance(data_vectors, dict):\n raise TypeError(\"expected 'data_vectors' to be a dict\")\n if 'energy' not in data_vectors:\n raise ValueError(\"energy must be provided\")\n else:\n data_vectors = data_vectors.copy() # shallow copy\n data_vectors['energy'] = np.asarray(data_vectors['energy'])\n for vector in data_vectors.values():\n # todo - check that is a vector and that has the right length\n if isinstance(vector, (np.ndarray, list)):\n if len(vector) != num_samples:\n raise ValueError((\"expected data vector {} to be a vector of length {}\"\n \"\").format(vector, num_samples))\n else:\n raise TypeError(\"expected data vector {} to be a list of numpy array\".format(vector))\n self._data_vectors = data_vectors\n\n # vartype is checked by the decorator\n self.vartype = vartype\n\n if info is None:\n info = {}\n elif not isinstance(info, dict):\n raise TypeError(\"expected 'info' to be a dict.\")\n else:\n info = dict(info) # make a shallow copy\n self.info = info\n\n if variable_labels is None:\n self.variable_labels = None\n self.label_to_idx = None\n else:\n self.variable_labels = variable_labels = list(variable_labels)\n if len(variable_labels) != num_variables:\n msg = (\"variable_labels' length must match the number of columns in \"\n \"samples_matrix, {} labels, matrix has {} columns\".format(len(variable_labels), num_variables))\n raise ValueError(msg)\n\n self.label_to_idx = {v: idx for idx, v in enumerate(variable_labels)}\n\n # will store any pending Future objects and data about them\n self._futures = {}\n\n def __len__(self):\n \"\"\"The number of samples.\"\"\"\n num_samples, num_variables = self.samples_matrix.shape\n return num_samples\n\n def __iter__(self):\n \"\"\"Iterate over the samples, low energy to high.\"\"\"\n return self.samples(sorted_by='energy')\n\n def __str__(self):\n # developer note: it would be nice if the variable labels (if present could be printed)\n return self.samples_matrix.__str__()\n\n ##############################################################################################\n # Properties\n ##############################################################################################\n\n @property\n def samples_matrix(self):\n \"\"\":obj:`numpy.matrix`: The numpy int8 matrix containing the samples.\"\"\"\n if self._futures:\n self._resolve_futures(**self._futures)\n\n return self._samples_matrix\n\n @samples_matrix.setter\n def samples_matrix(self, mat):\n self._samples_matrix = mat\n\n @property\n def data_vectors(self):\n \"\"\"dict[field, :obj:`numpy.array`/list]: The per-sample data. The keys should be the\n data labels and the values should each be a vector of the same length as sample_matrix.\n \"\"\"\n if self._futures:\n self._resolve_futures(**self._futures)\n\n return self._data_vectors\n\n def done(self):\n \"\"\"True if all loaded futures are done or if there are no futures.\n\n Only relevant when the response is constructed with :meth:`Response.from_futures`.\n \"\"\"\n return all(future.done() for future in self._futures)\n\n ##############################################################################################\n # Construction and updates\n ##############################################################################################\n\n @classmethod\n def from_matrix(cls, samples, data_vectors, vartype=None, info=None, variable_labels=None):\n \"\"\"Build a Response from an array-like object.\n\n Args:\n samples (array_like/str):\n As for :class:`numpy.matrix`. See Notes.\n\n data_vectors (dict[field, :obj:`numpy.array`/list]):\n A dict containing additional per-sample data in vectors. Each vector should be the\n same length as samples_matrix. The key 'energy' and its vector are required.\n\n vartype (:class:`.Vartype`, optional, default=None):\n The vartype of the response. If not provided, the vartype will be inferred from the\n samples matrix if possible or a ValueError will be raised.\n\n info (dict, optional, default=None):\n A dict containing information about the response as a whole.\n\n variable_labels (list, optional, default=None):\n Maps (by index) variable labels to the columns of the samples matrix.\n\n Returns:\n :obj:`.Response`\n\n Raises:\n :exc:`ValueError`: If vartype is not provided and samples are either all 1s or have more\n than two unique values or if those values are not a know vartype.\n\n Examples:\n .. code-block:: python\n\n samples = np.matrix([[0, 1], [1, 0]])\n energies = [0.0, 1.0]\n response = Response.from_matrix(samples, {'energy': energies})\n\n .. code-block:: python\n\n samples = [[0, 1], [1, 0]]\n energies = [0.0, 1.0]\n response = Response.from_matrix(samples, {'energy': energies})\n\n Notes:\n SciPy defines array_like in the following way: \"In general, numerical data arranged in\n an array-like structure in Python can be converted to arrays through the use of the\n array() function. The most obvious examples are lists and tuples. See the documentation\n for array() for details for its use. Some objects may support the array-protocol and\n allow conversion to arrays this way. A simple way to find out if the object can be\n converted to a numpy array using array() is simply to try it interactively and see if it\n works! (The Python Way).\" [array_like]_\n\n References:\n .. [array_like] Docs.scipy.org. (2018). Array creation - NumPy v1.14 Manual. [online]\n Available at: https://docs.scipy.org/doc/numpy/user/basics.creation.html\n [Accessed 16 Feb. 2018].\n\n \"\"\"\n samples_matrix = np.matrix(samples, dtype=np.int8)\n\n if vartype is None:\n vartype = infer_vartype(samples_matrix)\n\n response = cls(samples_matrix, data_vectors=data_vectors,\n vartype=vartype, info=info, variable_labels=variable_labels)\n\n return response\n\n @classmethod\n def from_dicts(cls, samples, data_vectors, vartype=None, info=None):\n \"\"\"Build a Response from an iterable of dicts.\n\n Args:\n samples (iterable[dict]):\n An iterable of samples where each sample is a dictionary (or Mapping).\n\n data_vectors (dict[field, :obj:`numpy.array`/list]):\n A dict containing additional per-sample data in vectors. Each vector should be the\n same length as samples_matrix. The key 'energy' and its vector are required.\n\n vartype (:class:`.Vartype`, optional, default=None):\n The vartype of the response. If not provided, the vartype will be inferred from the\n samples matrix if possible or a ValueError will be raised.\n\n info (dict, optional, default=None):\n A dict containing information about the response as a whole.\n\n Returns:\n :obj:`.Response`\n\n Raises:\n :exc:`ValueError`: If vartype is not provided and samples are either all 1s or have more\n than two unique values or if those values are not a know vartype.\n\n Examples:\n .. code-block:: python\n\n samples = [{'a': -1, 'b': +1}, {'a': +1, 'b': -1}]\n energies = [-1.0, -1.0]\n response = Response.from_dicts(samples, {'energy': energies})\n\n \"\"\"\n samples = iter(samples)\n\n # get the first sample\n first_sample = next(samples)\n\n try:\n variable_labels = sorted(first_sample)\n except TypeError:\n # unlike types cannot be sorted in python3\n variable_labels = list(first_sample)\n num_variables = len(variable_labels)\n\n def _iter_samples():\n yield np.fromiter((first_sample[v] for v in variable_labels),\n count=num_variables, dtype=np.int8)\n\n try:\n for sample in samples:\n yield np.fromiter((sample[v] for v in variable_labels),\n count=num_variables, dtype=np.int8)\n except KeyError:\n msg = (\"Each dict in 'samples' must have the same keys.\")\n raise ValueError(msg)\n\n samples_matrix = np.matrix(np.stack(list(_iter_samples())))\n\n return cls.from_matrix(samples_matrix, data_vectors=data_vectors, vartype=vartype,\n info=info, variable_labels=variable_labels)\n\n @classmethod\n def from_pandas(cls, samples_df, data_vectors, vartype=None, info=None):\n \"\"\"Build a Response from a pandas DataFrame.\n\n Args:\n samples (:obj:`pandas.DataFrame`):\n A pandas DataFrame of samples where each row is a sample.\n\n data_vectors (dict[field, :obj:`numpy.array`/list]):\n A dict containing additional per-sample data in vectors. Each vector should be the\n same length as samples_matrix. The key 'energy' and its vector are required.\n\n vartype (:class:`.Vartype`, optional, default=None):\n The vartype of the response. If not provided, the vartype will be inferred from the\n samples matrix if possible or a ValueError will be raised.\n\n info (dict, optional, default=None):\n A dict containing information about the response as a whole.\n\n Returns:\n :obj:`.Response`\n\n Raises:\n :exc:`ValueError`: If vartype is not provided and samples are either all 1s or have more\n than two unique values or if those values are not a know vartype.\n\n Examples:\n .. code-block:: python\n\n import pandas as pd\n\n samples = pd.DataFrame([{'a': 1, 'b': 0}, {'a': 0, 'b': 0}], dtype='int8')\n response = Response.from_pandas(samples, {energy: [1, 0]})\n\n .. code-block:: python\n\n import pandas as pd\n\n samples = pd.DataFrame([[+1, -1]], dtype='int8', columns=['v1', 'v2'])\n response = Response.from_pandas(samples, {energy: [1]})\n\n \"\"\"\n import pandas as pd\n\n variable_labels = list(samples_df.columns)\n samples_matrix = samples_df.as_matrix(columns=variable_labels)\n\n if isinstance(data_vectors, pd.DataFrame):\n raise NotImplementedError(\"support for DataFrame data_vectors is forthcoming\")\n\n return cls.from_matrix(samples_matrix, data_vectors, vartype=vartype, info=info,\n variable_labels=variable_labels)\n\n @classmethod\n def from_futures(cls, futures, vartype, num_variables,\n samples_key='samples', data_vector_keys=None,\n info_keys=None, variable_labels=None, active_variables=None):\n \"\"\"Build a response from :obj:`~concurrent.futures.Future`-like objects.\n\n Args:\n futures (iterable):\n An iterable :obj:`~concurrent.futures.Future`-like objects. It is expected\n that :meth:`~concurrent.futures.Future.result` will return a dict.\n\n vartype (:class:`.Vartype`):\n The vartype of the response.\n\n num_variables (int):\n The number of variables each sample will have.\n\n samples_key (hashable, optional, default='samples'):\n The key of the result dict that contains the samples. The samples are expected\n to be array-like.\n\n data_vector_keys (iterable/mapping, optional, default=None):\n A mapping from the keys of the result dict to :attr:`Response.data_vectors`. If\n None, ['energy'] is assumed to be a key in the result dict and will map the the\n 'energy' data vector.\n\n info_keys (iterable/mapping, optional, default=None):\n A mapping from the keys of the result dict to :attr:`Response.info`.\n If None, info will be empty.\n\n variable_labels (list, optional, default=None):\n Maps (by index) variable labels to the columns of the samples matrix.\n\n active_variables (array-like, optional, default=None):\n Specify which columns of the result's samples should be used. If variable_labels is\n not provided then the variable_labels will be set to match active_variables\n\n Returns:\n :obj:`.Response`\n\n Examples:\n .. code-block:: python\n\n from concurrent.futures import Future\n\n future = Future()\n\n # load the future into response\n response = dimod.Response.from_futures((future,), dimod.BINARY, 3)\n\n future.set_result({'samples': [0, 1, 0], 'energy': [1]})\n\n # now read from the response\n matrix = response.samples_matrix\n\n .. code-block:: python\n\n from concurrent.futures import Future\n\n future = Future()\n\n # load the future into response\n response = dimod.Response.from_futures((future,), dimod.BINARY, 3,\n active_variables=[0, 1, 3])\n\n future.set_result({'samples': [0, 1, 3, 0], 'energy': [1]})\n\n # now read from the response, this matrix\n matrix = response.samples_matrix\n\n .. code-block:: python\n\n from concurrent.futures import Future\n\n future = Future()\n\n # load the future into response\n response = dimod.Response.from_futures((future,), dimod.BINARY, 3,\n data_vector_keys={'en': 'energy'})\n\n future.set_result({'samples': [0, 1, 0], 'en': [1]})\n\n # now read from the response\n matrix = response.samples_matrix\n\n Notes:\n The future objects are read on the first read of :attr:`.Response.samples_matrix` or\n :attr:`.Response.data_vectors`.\n\n \"\"\"\n\n if data_vector_keys is None:\n data_vector_keys = {'energy': 'energy'}\n elif isinstance(data_vector_keys, Mapping):\n data_vector_keys = dict(data_vector_keys)\n else:\n data_vector_keys = {key: key for key in data_vector_keys} # identity mapping\n\n if info_keys is None:\n info_keys = {}\n elif isinstance(info_keys, Mapping):\n info_keys = dict(info_keys)\n else:\n info_keys = {key: key for key in info_keys}\n\n # now initialize self with a 0 samples, but the correct number of variables/labels/etc\n empty_samples_matrix = np.matrix(np.empty((0, num_variables), dtype=np.int8))\n\n empty_data_vectors = {key: [] for key in itervalues(data_vector_keys)}\n\n if active_variables is not None:\n if variable_labels is None:\n variable_labels = active_variables\n elif len(variable_labels) != len(active_variables):\n raise ValueError(\"active_variables and variable_labels should have the same length\")\n\n\n # let Response parse vartype, variable_labels. We also want to start with an empty info\n response = Response(samples_matrix=empty_samples_matrix, data_vectors=empty_data_vectors,\n vartype=vartype, variable_labels=variable_labels)\n\n # now dump all of the remaining information into the _futures\n response._futures = {'futures': futures,\n 'samples_key': samples_key,\n 'data_vector_keys': data_vector_keys,\n 'info_keys': info_keys,\n 'variable_labels': variable_labels,\n 'active_variables': active_variables}\n\n return response\n\n def _resolve_futures(self, futures, samples_key, data_vector_keys, info_keys,\n variable_labels, active_variables):\n\n # first reset the futures to avoid recursion errors\n self._futures = {}\n\n # `dwave.cloud.qpu.computation.Future` is not yet interchangeable with\n # `concurrent.futures.Future`, so we need to detect the kind of future\n # we're dealing with.\n futures = list(futures) # if generator\n if hasattr(futures[0], 'as_completed'):\n as_completed = futures[0].as_completed\n else:\n as_completed = concurrent.futures.as_completed\n\n # combine all samples from all futures into a single response\n for future in as_completed(futures):\n result = future.result()\n\n # first get the samples matrix and filter out any inactive variables\n samples = np.matrix(result[samples_key], dtype=np.int8)\n if active_variables is not None:\n samples = samples[:, active_variables]\n\n # next get the data vectors\n data_vectors = {key: result[source_key] for source_key, key in iteritems(data_vector_keys)}\n\n # and the info\n info = {key: result[source_key] for source_key, key in iteritems(info_keys)}\n\n # now get the appropriate response\n response = self.__class__.from_matrix(samples, data_vectors=data_vectors, info=info,\n vartype=self.vartype, variable_labels=variable_labels)\n self.update(response)\n\n def update(self, *other_responses):\n \"\"\"Add other responses' values to the response.\n\n Args:\n *other_responses: (:obj:`.Response`):\n Any number of additional response objects. Must have matching sample_matrix\n dimensions, matching data_vector keys and identical variable labels.\n\n \"\"\"\n\n # make sure all of the other responses are the appropriate vartype. We could cast them but\n # that would effect the energies so it is best to happen outside of this function.\n vartype = self.vartype\n for response in other_responses:\n if vartype is not response.vartype:\n raise ValueError(\"can only update with responses of matching vartype\")\n\n # make sure that the variable labels are consistent\n variable_labels = self.variable_labels\n if variable_labels is None:\n __, num_variables = self.samples_matrix.shape\n variable_labels = list(range(num_variables))\n # in this case we need to allow for either None or variable_labels\n if not all(response.variable_labels is None or response.variable_labels == variable_labels\n for response in other_responses):\n raise ValueError(\"cannot update responses with unlike variable labels\")\n else:\n if not all(response.variable_labels == variable_labels for response in other_responses):\n raise ValueError(\"cannot update responses with unlike variable labels\")\n\n # concatenate all of the matrices\n matrices = [self.samples_matrix]\n matrices.extend([response.samples_matrix for response in other_responses])\n self.samples_matrix = np.concatenate(matrices)\n\n # group all of the data vectors\n for key in self.data_vectors:\n vectors = [self.data_vectors[key]]\n vectors.extend(response.data_vectors[key] for response in other_responses)\n self.data_vectors[key] = np.concatenate(vectors)\n\n # finally update the response info\n for response in other_responses:\n self.info.update(response.info)\n\n ###############################################################################################\n # Transformations and Copies\n ###############################################################################################\n\n def copy(self):\n \"\"\"Creates a shallow copy of the response.\"\"\"\n return self.from_matrix(self.samples_matrix, self.data_vectors,\n vartype=self.vartype, info=self.info,\n variable_labels=self.variable_labels)\n\n @vartype_argument('vartype')\n def change_vartype(self, vartype, data_vector_offsets=None, inplace=True):\n \"\"\"Creates a new response with the given vartype.\n\n Args:\n vartype (:class:`.Vartype`/str/set, optional):\n The variable type desired for the penalty model. Accepted input values:\n :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n inplace (bool, optional, default=True):\n If True, the response is updated in-place, otherwise a new response is returned.\n\n Returns:\n :obj:`.Response`. A new Response with vartype matching input 'vartype'.\n\n \"\"\"\n if not inplace:\n return self.copy().change_vartype(vartype, data_vector_offsets=data_vector_offsets, inplace=True)\n\n if data_vector_offsets is not None:\n for key in data_vector_offsets:\n self.data_vectors[key] += data_vector_offsets[key]\n\n if vartype is self.vartype:\n return self\n\n if vartype is Vartype.SPIN and self.vartype is Vartype.BINARY:\n self.samples_matrix = 2 * self.samples_matrix - 1\n self.vartype = vartype\n elif vartype is Vartype.BINARY and self.vartype is Vartype.SPIN:\n self.samples_matrix = (self.samples_matrix + 1) // 2\n self.vartype = vartype\n else:\n raise ValueError(\"Cannot convert from {} to {}\".format(self.vartype, vartype))\n\n return self\n\n def relabel_variables(self, mapping, inplace=True):\n \"\"\"Relabel the variables according to the given mapping.\n\n Args:\n mapping (dict):\n A dict mapping the current variable labels to new ones. If an incomplete mapping is\n provided unmapped variables will keep their labels\n\n inplace (bool, optional, default=True):\n If True, the response is updated in-place, otherwise a new response is returned.\n\n Returns:\n :class:`.Response`: A response with the variables relabeled. If inplace=True, returns\n itself.\n\n Examples:\n .. code-block:: python\n\n response = dimod.Response.from_dicts([{'a': -1}, {'a': +1}], {'energy': [-1, 1]})\n response.relabel_variables({'a': 0})\n\n .. code-block:: python\n\n response = dimod.Response.from_dicts([{'a': -1}, {'a': +1}], {'energy': [-1, 1]})\n new_response = response.relabel_variables({'a': 0}, inplace=False)\n\n \"\"\"\n if not inplace:\n return self.copy().relabel_variables(mapping, inplace=True)\n\n # we need labels\n if self.variable_labels is None:\n __, num_variables = self.samples_matrix.shape\n self.variable_labels = list(range(num_variables))\n\n try:\n old_labels = set(mapping)\n new_labels = set(itervalues(mapping))\n except TypeError:\n raise ValueError(\"mapping targets must be hashable objects\")\n\n for v in new_labels:\n if v in self.variable_labels and v not in old_labels:\n raise ValueError(('A variable cannot be relabeled \"{}\" without also relabeling '\n \"the existing variable of the same name\").format(v))\n\n shared = old_labels & new_labels\n if shared:\n old_to_intermediate, intermediate_to_new = resolve_label_conflict(mapping, old_labels, new_labels)\n\n self.relabel_variables(old_to_intermediate, inplace=True)\n self.relabel_variables(intermediate_to_new, inplace=True)\n return self\n\n self.variable_labels = variable_labels = [mapping.get(v, v) for v in self.variable_labels]\n self.label_to_idx = {v: idx for idx, v in enumerate(variable_labels)}\n return self\n\n ###############################################################################################\n # Viewing a Response\n ###############################################################################################\n\n def samples(self, sorted_by='energy'):\n \"\"\"Iterate over the samples in the response.\n\n Args:\n sorted_by (str/None, optional, default='energy'):\n Over what data_vector to sort the samples. If None, the samples are yielded in\n the order given by the samples matrix.\n\n Yields:\n :obj:`.SampleView`: A view object mapping the variable labels to their values. Acts like\n a read-only dict.\n\n Examples:\n >>> response = dimod.ExactSolver().sample_ising({'a': -0.5, 'b': 1.0}, {('a', 'b'): -1})\n >>> response.samples_matrix\n matrix([[-1, -1],\n [ 1, -1],\n [ 1, 1],\n [-1, 1]])\n >>> for sample in response.samples(sorted_by=None):\n ... print(sample)\n {'a': -1, 'b': -1}\n {'a': 1, 'b': -1}\n {'a': 1, 'b': 1}\n {'a': -1, 'b': 1}\n >>> for sample in response.samples(): # sorted_by='energy'\n ... print(sample)\n {'a': -1, 'b': -1}\n {'a': 1, 'b': -1}\n {'a': 1, 'b': 1}\n {'a': -1, 'b': 1}\n\n \"\"\"\n if sorted_by is None:\n order = np.arange(len(self))\n else:\n order = np.argsort(self.data_vectors[sorted_by])\n\n samples = self.samples_matrix\n label_mapping = self.label_to_idx\n for idx in order:\n yield SampleView(idx, samples, label_mapping)\n\n def data(self, fields=None, sorted_by='energy', name='Sample'):\n \"\"\"Iterate over the data in the response.\n\n Args:\n fields (list, optional, default=None):\n If specified, the yielded tuples will only include the values in fields.\n A special field name 'sample' can be used to view the samples.\n\n sorted_by (str/None, optional, default='energy'):\n Over what data_vector to sort the samples. If None, the samples are yielded in\n the order given by the samples matrix.\n\n name (str/None, optional, default='Sample'):\n The name of the yielded namedtuples or None to yield regular tuples.\n\n Yields:\n namedtuple/tuple: The data in the response, in the order specified by the input\n 'fields'.\n\n Examples:\n >>> response = dimod.ExactSolver().sample_ising({'a': -0.5, 'b': 1.0}, {('a', 'b'): -1})\n >>> for datum in response.data():\n ... print(datum)\n Sample(sample={'a': -1, 'b': -1}, energy=0.0)\n Sample(sample={'a': 1, 'b': -1}, energy=1.0)\n Sample(sample={'a': 1, 'b': 1}, energy=1.0)\n Sample(sample={'a': -1, 'b': 1}, energy=4.0)\n >>> for sample, energy in response.data():\n ... print(energy)\n 0.0\n 1.0\n 1.0\n 4.0\n >>> for energy, in response.data(['energy']):\n ... print(energy)\n 0.0\n 1.0\n 1.0\n 4.0\n\n \"\"\"\n if fields is None:\n fields = ['sample']\n fields.extend(self.data_vectors)\n\n if sorted_by is None:\n order = np.arange(len(self))\n else:\n order = np.argsort(self.data_vectors[sorted_by])\n\n if name is None:\n # yielding a tuple\n def _pack(values):\n return tuple(values)\n else:\n # yielding a named tuple\n SampleTuple = namedtuple(name, fields)\n\n def _pack(values):\n return SampleTuple(*values)\n\n samples = self.samples_matrix\n label_mapping = self.label_to_idx\n data_vectors = self.data_vectors\n\n def _values(idx):\n for field in fields:\n if field == 'sample':\n yield SampleView(idx, samples, label_mapping)\n else:\n yield data_vectors[field][idx]\n\n for idx in order:\n yield _pack(_values(idx))\n\n\nclass SampleView(Mapping):\n \"\"\"View each row of the samples matrix as if it was a dict.\"\"\"\n def __init__(self, idx, samples, label_mapping=None):\n self.label_mapping = label_mapping\n self.idx = idx\n self.samples = samples\n\n def __getitem__(self, key):\n if self.label_mapping is not None:\n key = self.label_mapping[key]\n\n return int(self.samples[self.idx, key])\n\n def __iter__(self):\n # iterate over the variables\n return self.label_mapping.__iter__()\n\n def __len__(self):\n num_samples, num_variables = self.samples.shape\n return num_variables\n\n def __repr__(self):\n \"\"\"Represents itself as as a dictionary\"\"\"\n return dict(self).__repr__()\n\n\ndef infer_vartype(samples_matrix):\n \"\"\"Try to determine the Vartype of the samples matrix based on its values.\n\n Args:\n samples_matrix (:object:`numpy.ndarray`):\n An array or matrix of samples.\n\n Returns:\n :class:`.Vartype`\n\n Raises:\n ValueError: If the matrix is all ones, contains values other than -1, 1, 0 or contains more\n than two unique values.\n\n \"\"\"\n ones_matrix = samples_matrix == 1\n\n if np.all(ones_matrix):\n msg = (\"ambiguous vartype - an empty samples_matrix or one where all the values \"\n \"are all 1 must have the vartype specified by setting vartype=dimod.SPIN or \"\n \"vartype=dimod.BINARY.\")\n raise ValueError(msg)\n\n if np.all(ones_matrix + (samples_matrix == 0)):\n return Vartype.BINARY\n elif np.all(ones_matrix + (samples_matrix == -1)):\n return Vartype.SPIN\n else:\n sample_vals = set(int(v) for v in np.nditer(samples_matrix)) - {-1, 1, 0}\n if sample_vals:\n msg = (\"samples_matrix includes unknown values {}\").format(sample_vals)\n else:\n msg = (\"samples_matrix includes both -1 and 0 values\")\n raise ValueError(msg)\n","sub_path":"dimod/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":33673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"197829710","text":"\"\"\"\nPip.Services Prometheus\n--------------------\n\nPip.Services is an open-source library of basic microservices.\npip_services3_prometheus contains components for working with meters in the Prometheus service.\n\nLinks\n`````\n\n* `website `\n* `development version `\n\n\"\"\"\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\ntry:\n readme = open('readme.md').read()\nexcept:\n readme = __doc__\n\nsetup(\n name='pip_services3_prometheus',\n version='3.1.2',\n url='http://github.com/pip-services3-python/pip-services3-prometheus-python',\n license='MIT',\n description='Prometheus components for Pip.Services in Python',\n author='Conceptual Vision Consulting LLC',\n author_email='seroukhov@gmail.com',\n long_description=readme,\n long_description_content_type=\"text/markdown\",\n packages=find_packages(exclude=['config', 'data', 'test']),\n include_package_data=True,\n zip_safe=True,\n platforms='any',\n install_requires=[\n 'pytest',\n\n 'pip-services3-commons >= 3.3.9, < 4.0',\n 'pip-services3-components >= 3.5.0, < 4.0',\n 'pip-services3-rpc >= 3.2.12, < 4.0'\n ],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Topic :: Software Development :: Libraries :: Python Modules'\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"40027280","text":"\"\"\"singular value decomposition\"\"\"\nimport numpy as np\n\ndef singular_values(dataset):\n \"\"\"applies svd to the dataset to obtain singular values\n\n :type dataset: numpy.array (mxn) | numpy.matrix (mxn)\n :return: singular values obtained from applying svd on the dataset\n \"\"\"\n U, sigma, Vt = np.linalg.svd(dataset)\n return sigma\n\ndef compress_dataset(dataset):\n \"\"\"uses svd to compress the dataset into a new one with fewer feature but that still conserves 90% of the energy\n\n :type dataset: numpy.matrix (mxn)\n :return: compressed dataset\n \"\"\"\n U, sigma, Vt = np.linalg.svd(dataset)\n energy_threshold = sum(sigma ** 2) * 0.9\n\n # find minimum number of features that contain 90% of the energy\n num_single_values = 0\n for i in range(1, len(sigma)):\n energy = sum(sigma[:i] ** 2)\n if energy >= energy_threshold:\n num_single_values = i\n\n # reconstruct the dataset with less features\n sigma_matrix = np.mat(np.eye(num_single_values) * sigma[:num_single_values])\n # transform dataset into lower dimensional space\n compressed_dataset = dataset.T * U[:, :num_single_values] * sigma_matrix.I\n return compressed_dataset\n","sub_path":"dimensionality_reduction/singular_value_decomposition/svd.py","file_name":"svd.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"335339467","text":"import numpy\r\n\r\nclass Solution(object):\r\n def matrixReshape(self, nums, r, c):\r\n \"\"\"\r\n :type nums: List[List[int]]\r\n :type r: int\r\n :type c: int\r\n :rtype: List[List[int]]\r\n \"\"\"\r\n shape = numpy.array(nums).shape\r\n \r\n if r*c != shape[0]*shape[1]:\r\n return nums\r\n \r\n else:\r\n return numpy.reshape(nums, (r, c)).tolist()\r\n\r\nif __name__ =='__main__':\r\n test = Solution()\r\n print(test.matrixReshape([[1,2],[3,4]],r=1,c=4))\r\n","sub_path":"No566_reshape_the_matrix.py","file_name":"No566_reshape_the_matrix.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"287566111","text":"#!usr/bin/env python\n# -*- coding:utf-8 _*-\n\"\"\"\n@author:jerry\n@file: student_insecure_server.py\n@time: 2019/06/18\n\"\"\"\nimport time\nimport logging\nimport grpc\nimport student_pb2_grpc\nfrom concurrent.futures import ThreadPoolExecutor\nfrom student_servicer_imp import StudentServiceImp\n\n_ONE_DAY_IN_SECONDS = 60 * 60 * 24\n\n\ndef serve():\n logging.info(\"rpc服务启动\")\n server = grpc.server(ThreadPoolExecutor(max_workers=3))\n student_pb2_grpc.add_StudentServiceServicer_to_server(servicer=StudentServiceImp(), server=server)\n server.add_insecure_port(\"localhost:8080\")\n server.start()\n try:\n while True:\n time.sleep(_ONE_DAY_IN_SECONDS)\n except KeyboardInterrupt:\n server.stop(0)\n logging.info(\"rpc服务停止\")\n\n\nif __name__ == '__main__':\n logging.basicConfig(filename='./server.log', level=10)\n serve()\n","sub_path":"insecure-demo/student_insecure_server.py","file_name":"student_insecure_server.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"565937649","text":"import tensorflow as tf\nimport numpy as np\nimport random\nimport os\nimport cv2\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(os.path.dirname(os.path.realpath(__file__))+\"/../data/MNIST_data/\", one_hot=True)\n\nx = tf.placeholder(\"float\", [None, 784])\ny = tf.placeholder(\"float\", [None, 10])\n\nW = tf.Variable(tf.zeros([784, 10]))\nb = tf.Variable(tf.zeros([10]))\n\nlearning_rate = 0.01\ntraining_epochs = 1\nbatch_size = 100\ndisplay_step = 1\n\n### modeling ###\n\nactivation = tf.nn.softmax(tf.matmul(x, W) + b)\n\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(activation), reduction_indices=1))\n\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)\n\ninit = tf.global_variables_initializer()\n\nsess = tf.Session()\nsess.run(init)\n\n### training ###\n\nfor epoch in range(training_epochs) :\n\n avg_cost = 0\n total_batch = int(mnist.train.num_examples/batch_size)\n\n for i in range(total_batch) :\n\n batch_xs, batch_ys =mnist.train.next_batch(batch_size)\n sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})\n avg_cost += sess.run(cross_entropy, feed_dict = {x: batch_xs, y: batch_ys}) / total_batch\n\n if epoch % display_step == 0 :\n print(\"Epoch : \", \"%04d\" % (epoch+1), \"cost=\", \"{:.9f}\".format(avg_cost))\n\nprint(\"Optimization Finished\")\n\n### predict number ###\n\nr = random.randint(0, mnist.test.num_examples - 1)\nprint(\"Prediction: \", sess.run(tf.argmax(activation,1), {x: mnist.test.images[r:r+1]}))\nprint(\"Correct Answer: \", sess.run(tf.argmax(mnist.test.labels[r:r+1], 1)))\n\nimage = np.zeros((1,784))\nsess.run(tf.argmax(activation,1), {x: image})","sub_path":"SFData/ICSE2020/s39032277_ground_truth.py","file_name":"s39032277_ground_truth.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"405289957","text":"# Copyright 2017 IBM Corp.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nfrom zvmsdk import config\nfrom zvmsdk import constants as const\nfrom zvmsdk import exception\nfrom zvmsdk import log\nfrom zvmsdk import smtclient\nfrom zvmsdk import utils as zvmutils\n\n\n_HOSTOPS = None\nCONF = config.CONF\nLOG = log.LOG\n\n\ndef get_hostops():\n global _HOSTOPS\n if _HOSTOPS is None:\n _HOSTOPS = HOSTOps()\n return _HOSTOPS\n\n\nclass HOSTOps(object):\n\n def __init__(self):\n self._smtclient = smtclient.get_smtclient()\n\n def get_info(self):\n inv_info = self._smtclient.get_host_info()\n host_info = {}\n\n with zvmutils.expect_invalid_resp_data(inv_info):\n host_info['zcc_userid'] = inv_info['zcc_userid']\n host_info['zvm_host'] = inv_info['zvm_host']\n host_info['vcpus'] = int(inv_info['lpar_cpu_total'])\n host_info['vcpus_used'] = int(inv_info['lpar_cpu_used'])\n host_info['cpu_info'] = {}\n host_info['cpu_info'] = {'architecture': const.ARCHITECTURE,\n 'cec_model': inv_info['cec_model'], }\n mem_mb = zvmutils.convert_to_mb(inv_info['lpar_memory_total'])\n host_info['memory_mb'] = mem_mb\n mem_mb_used = zvmutils.convert_to_mb(inv_info['lpar_memory_used'])\n host_info['memory_mb_used'] = mem_mb_used\n host_info['hypervisor_type'] = const.HYPERVISOR_TYPE\n verl = inv_info['hypervisor_os'].split()[1].split('.')\n version = int(''.join(verl))\n host_info['hypervisor_version'] = version\n host_info['hypervisor_hostname'] = inv_info['hypervisor_name']\n host_info['ipl_time'] = inv_info['ipl_time']\n diskpool_name = CONF.zvm.disk_pool.split(':')[1]\n dp_info = self.diskpool_get_info(diskpool_name)\n host_info.update(dp_info)\n\n return host_info\n\n def guest_list(self):\n guest_list = self._smtclient.get_all_user_direct()\n with zvmutils.expect_invalid_resp_data(guest_list):\n return guest_list\n\n def diskpool_get_info(self, pool):\n dp_info = self._smtclient.get_diskpool_info(pool)\n with zvmutils.expect_invalid_resp_data(dp_info):\n for k in list(dp_info.keys()):\n s = dp_info[k].strip().upper()\n if s.endswith('G'):\n sl = s[:-1].split('.')\n n1, n2 = int(sl[0]), int(sl[1])\n if n2 >= 5:\n n1 += 1\n dp_info[k] = n1\n elif s.endswith('M'):\n n_mb = int(s[:-3])\n n_gb, n_ad = n_mb // 1024, n_mb % 1024\n if n_ad >= 512:\n n_gb += 1\n dp_info[k] = n_gb\n else:\n exp = \"ending with a 'G' or 'M'\"\n errmsg = (\"Invalid diskpool size format: %(invalid)s; \"\n \"Expected: %(exp)s\") % {'invalid': s, 'exp': exp}\n LOG.error(errmsg)\n raise exception.SDKInternalError(msg=errmsg)\n\n return dp_info\n","sub_path":"zvmsdk/hostops.py","file_name":"hostops.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"465593849","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.feature_selection import VarianceThreshold\ndef dataDesc(data): #数据的基础信息展示\n var_types= pd.DataFrame(data.dtypes,columns=['v_types'])\n var_types['flag']=var_types['v_types'].apply(lambda x:('float' in str(x)) or ('int' in str(x)) or ('ouble' in str(x))) \n obj_features=data[var_types[var_types['flag']==False].index]\n num_desc=data.describe().T\n num_features=list(var_types[var_types['flag']==True].index)\n for num in num_features:\n st=data[num].value_counts()\n num_desc.at[num,'unique']=st.shape[0]\n if st.shape[0]>0:\n num_desc.at[num,'top']=st.index[0]\n num_desc.at[num,'freq']=st.values[0] \n if obj_features.shape[1]>0 : \n obj_desc=obj_features.describe().T\n rs=pd.concat([obj_desc,num_desc])\n else:\n rs=num_desc\n rs=rs[['min','25%','50%','75%','max','mean','std','count','unique','top','freq' ]] \n rs['missing']=1-rs['count']/data.shape[0]\n print(\"===================各个变量的基本情况==================\")\n print(rs.round())\n #cov = np.corrcoef(data[num_features].T)\n cov=data[num_features].corr().round(2)\n print(\"===================各数量变量的相关系数矩阵==================\")\n print(cov)\n plt.figure(figsize=(8,8))\n img = plt.matshow(cov,cmap=plt.cm.winter,fignum=0)# plt.cm.winter\n plt.title('corr of variable')\n plt.colorbar(img, ticks=[-1,0,1])\n plt.show()\n plt.close()\n print(\"===================变量分布统计图==================\")\n data.hist(figsize=(13,4*(data.shape[1]//3+1)),bins=30) #各个变量分布\n plt.show()\n plt.close()\n if len(num_features)<11:\n print(\"===================各数值变量间的散点关系图==================\")\n pd.scatter_matrix(data[num_features],figsize=(18,12))\n plt.show()\n plt.close()\n else:\n print(\"数值变量超过10个,不统计各个变量间的散点关系图\")\n num_features.remove('Target')\n rows=len(num_features)//3+1\n plt.figure(figsize=(13,4*rows))\n i=1\n for v in num_features:\n plt.subplot(rows,3,i)\n plt.plot( data['Target'],data[v],'or')\n plt.title(v+\" vs Target scatter\")\n i=i+1\n print(\"===================自变量与目标变量的散点图==================\")\n plt.show()\n plt.close()\n return rs,cov\nif __name__ == '__main__':\n# data=loadDataSet()\n data=pd.read_table('D:\\model_data\\diabetes.txt')\n data.rename(columns={'Y':'Target'}, inplace = True)#设立目标变量 因变量\n #desc=dataDesc(std_data) #数据初步探索\n y=np.array(data['Target'])\n x_df=data.drop(['Target'],axis=1)\n feature_names=list(x_df.columns)\n X=StandardScaler().fit_transform(X=x_df,y=y) # 标准化 也可以归一化,但是标准化多\n st=VarianceThreshold(threshold=3).fit_transform(X=data,y=y)\n #pca = PCA(n_components='mle') \n #pca.fit(data[['AGE', 'SEX', 'BMI', 'BP', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6']])\n #gui_data=(data - data.min()) / (data.max() - data.min()) #归一化\n \n #data.hist(figsize=(15,15),bins=30) #各个变量分布\n #pd.scatter_matrix(data,figsize=(18,12))","sub_path":"model/diabetes.py","file_name":"diabetes.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"56649721","text":"\nimport os\nimport re\nimport math\nimport os.path as op\n\nfrom pyrocko import config, util\nfrom pyrocko.topo import srtmgl3, etopo1, dataset, tile\n\npositive_region = tile.positive_region\n\nearthradius = 6371000.0\nr2d = 180./math.pi\nd2r = 1./r2d\nkm = 1000.\nd2m = d2r*earthradius\nm2d = 1./d2m\n\ntopo_data_dir = config.config().topo_dir\n\nsrtmgl3 = srtmgl3.SRTMGL3(\n name='SRTMGL3',\n data_dir=op.join(topo_data_dir, 'SRTMGL3'))\n\nsrtmgl3_d2 = dataset.DecimatedTiledGlobalDataset(\n name='SRTMGL3_D2',\n base=srtmgl3,\n ndeci=2,\n data_dir=op.join(topo_data_dir, 'SRTMGL3_D2'))\n\nsrtmgl3_d4 = dataset.DecimatedTiledGlobalDataset(\n name='SRTMGL3_D4',\n base=srtmgl3_d2,\n ndeci=2,\n data_dir=op.join(topo_data_dir, 'SRTMGL3_D4'))\n\nsrtmgl3_d8 = dataset.DecimatedTiledGlobalDataset(\n name='SRTMGL3_D8',\n base=srtmgl3_d4,\n ndeci=2,\n ntx=1001,\n nty=1001,\n data_dir=op.join(topo_data_dir, 'SRTMGL3_D8'))\n\netopo1 = etopo1.ETOPO1(\n name='ETOPO1',\n data_dir=op.join(topo_data_dir, 'ETOPO1'))\n\netopo1_d2 = dataset.DecimatedTiledGlobalDataset(\n name='ETOPO1_D2',\n base=etopo1,\n ndeci=2,\n data_dir=op.join(topo_data_dir, 'ETOPO1_D2'))\n\netopo1_d4 = dataset.DecimatedTiledGlobalDataset(\n name='ETOPO1_D4',\n base=etopo1_d2,\n ndeci=2,\n data_dir=op.join(topo_data_dir, 'ETOPO1_D4'))\n\netopo1_d8 = dataset.DecimatedTiledGlobalDataset(\n name='ETOPO1_D8',\n base=etopo1_d4,\n ndeci=2,\n data_dir=op.join(topo_data_dir, 'ETOPO1_D8'))\n\nsrtmgl3_all = [\n srtmgl3,\n srtmgl3_d2,\n srtmgl3_d4,\n srtmgl3_d8]\n\netopo1_all = [\n etopo1,\n etopo1_d2,\n etopo1_d4,\n etopo1_d8]\n\ndems = srtmgl3_all + etopo1_all\n\n\ndef make_all_missing_decimated():\n for dem in dems:\n if isinstance(dem, dataset.DecimatedTiledGlobalDataset):\n dem.make_all_missing()\n\n\ndef cpt(name):\n if os.path.exists(name):\n return name\n\n if not re.match(r'[A-Za-z0-9_]+', name):\n raise Exception('invalid cpt name')\n\n fn = util.data_file(os.path.join('colortables', '%s.cpt' % name))\n if not os.path.exists(fn):\n raise Exception('cpt file does not exist: %s' % fn)\n\n return fn\n\n\ndef comparison(region, dems=dems):\n import matplotlib.pyplot as plt\n\n east, west, south, north = tile.positive_region(region)\n\n fig = plt.gcf()\n\n for idem, dem_ in enumerate(dems):\n fig.add_subplot(len(dems), 1, idem+1)\n t = dem_.get(region)\n if t:\n plt.pcolormesh(t.x(), t.y(), t.data)\n plt.title(dem_.name)\n plt.xlim(east, west)\n plt.ylim(south, north)\n\n plt.show()\n\n\nclass UnknownDEM(Exception):\n pass\n\n\ndef dem_names():\n return [dem.name for dem in dems]\n\n\ndef dem(dem_name):\n for dem in dems:\n if dem.name == dem_name:\n return dem\n\n raise UnknownDEM(dem_name)\n\n\ndef get(dem_name, region):\n return dem(dem_name).get(region)\n\n\ndef select_dem_names(kind, dmin, dmax, region):\n assert kind in ('land', 'ocean')\n ok = []\n if kind == 'land':\n for dem in srtmgl3_all:\n if dem.is_suitable(region, dmin, dmax):\n ok.append(dem.name)\n break\n\n for dem in etopo1_all:\n if dem.is_suitable(region, dmin, dmax):\n ok.append(dem.name)\n break\n\n return ok\n\nif __name__ == '__main__':\n #comparison((-180., 180., -90, 90), dems=[etopo1_d8])\n util.setup_logging('topo', 'info')\n comparison((30, 31, 30, 31), dems=[srtmgl3, srtmgl3_d2])\n","sub_path":"src/topo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"223345506","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport codecs\nimport os\nimport io\nimport glob\nimport random\n\ndef feed(reduceby):\n #Parent.SendStreamMessage(\"Beginning Overheat\")\n global timerActive\n voteDir = 'D:/Program Files/Streamlabs Chatbot/Services/Twitch/Votes/'\n campfireDir = 'D:/Program Files/Streamlabs Chatbot/Services/Twitch/flame.txt'\n retVal = ''\n threshold = 800\n interval = 100 # for every 100 past 1000, increase the multiplier by 1\n payoutBase = 2\n payoutInterval = 1000\n \n timerActive = False\n choices = os.listdir(voteDir)\n \n # add multiple copies of choices with higher values\n for file in os.listdir(voteDir):\n \n with io.open(voteDir + file, 'r', encoding = 'utf-8-sig') as f:\n campfire = int(f.read().decode('utf-8-sig'))\n \n if campfire >= (threshold+interval):\n multiplier = (campfire-1000)/100\n \n for i in range(multiplier):\n choices.append(file)\n \n choice = random.choice(choices)\n name = choice # choose a random file from within the directory\n \n #for each in choices:\n # Parent.SendStreamMessage(each)\n \n with open(voteDir + name, 'r') as file: # open the random file\n filedata = int(file.read().decode('utf-8-sig'))\n \n #Parent.SendStreamMessage('Opened name: ' + name)\n\n if reduceby > filedata: # make sure it has enough logs to reduce by that much\n retVal += 'The questing tendrils of salamander flame pass up ' + name.split('.')[0] + '; It is too small to sate it\\'s appetite.'\n \n #Parent.SendStreamMessage('Too small')\n else: # feed\n filedata = filedata - reduceby\n retVal += 'The salamander flame gorges itself on '+ name.split('.')[0] + '\\'s log pile, consuming ' + str(reduceby) + ' logs. It is sated for now.'\n \n #Parent.SendStreamMessage('The right size.')\n \n # Write the reduced log count to the file.\n with open(voteDir + name, 'w+') as file:\n file.write(str(filedata))\n \n print('The right size, but smaller')\n \n # read in the campfire\n with open(campfireDir, 'r') as file:\n campfire = int(file.read().decode('utf-8-sig'))\n print(str(campfire))\n campfire = campfire + reduceby\n \n #Parent.SendStreamMessage('Payout interval: ' + payoutInterval)\n #payout = int(payoutBase) + int(campfire / payoutInterval)\n #Parent.SendStreamMessage(payout)\n payout = 2\n print(\"The growing forest rewards users with \" + str(payout))\n \n # write the new campfire value in\n with open(campfireDir, 'w+') as file:\n file.write(str(campfire))\n \n myDict = {}\n #for viewers in Parent.GetViewerList():\n # this controls how much chatters get payed\n # myDict[viewers] = payout\n\n #Parent.AddPointsAll(myDict)\n #Parent.SendStreamMessage(\"The growing forest rewards users with \" + payout)\n \n print(retVal)\n \nfeed(10)","sub_path":"Overheat/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"182022103","text":"import requests\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport json\n\nurl = \"https://bloomberg-market-and-financial-news.p.rapidapi.com/market/get-full\"\n\nquerystring = {\"id\":\"adsmi:ind,aex:ind,co1:com,gc1:com\"}\n\nheaders = {\n 'x-rapidapi-key': \"a9164563cbmshbb0d9669c26e1e6p1c432bjsn477e1068516e\",\n 'x-rapidapi-host': \"bloomberg-market-and-financial-news.p.rapidapi.com\"\n }\n\nresponse = requests.request(\"GET\", url, headers=headers, params=querystring)\n\nprint(response.text)\n\nrow_data = response.text\n\nwith open (\"data_log_original_version.txt\", \"w\") as plik:\n\tprint(row_data, file=plik)\n\nd = json.loads(row_data)\n\nwith open (\"data_log_original_version_json.json\", \"w\") as plik:\n\tprint(d, file=plik)\n\ndf = pd.json_normalize(d['result'])\ndf_t = df.T\n\ndf_t.to_excel(\"structured_data_original_version.xlsx\")","sub_path":"data_download/data_download_BLOOMBERG/MARKET/get-full/data_fetch.py","file_name":"data_fetch.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"203749767","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nimport random\n\n# 이 코드는 agent의 수와 target의 수가 고정된 상황에서 움직이는 target을 찾는 문제를 위해 만든 코드임\nclass Drones(object):\n def __init__(self, pos, view_range):\n self.pos = pos\n self.view_range = view_range\n\nclass Human(object): \n #사람 위치도 random하게 설정할 수 있음. 나중에 constant velocity 모델을 고려한다고 하면 더 다양한 움직임을 가지는 target을 생성 가능함\n def __init__(self, pos):\n self.pos = pos\n\nclass EnvDrones(object):\n def __init__(self, map_size, drone_num, view_range, tree_num, human_num):\n self.map_size = map_size\n self.drone_num = drone_num\n self.tree_num = tree_num # tree가 사람의 움직임을 방해하는가?\n self.human_num = human_num\n self.view_range = view_range\n \n # initialize blocks \n self.land_mark_map = np.zeros((self.map_size, self.map_size))\n for i in range(self.map_size):\n for j in range(self.map_size):\n if random.random() < 0.000001:\n # self.land_mark_map[i, j] = 0.0 # Block을 random하게 생성하는 코드\n self.land_mark_map[i, j] = 1 # Block을 random하게 생성하는 코드\n\n # intialize tree\n for i in range(self.tree_num):\n temp_pos = [random.randint(0, self.map_size-1), random.randint(0, self.map_size-1)]\n while self.land_mark_map[temp_pos[0], temp_pos[1]] != 0:\n temp_pos = [random.randint(0, self.map_size-1), random.randint(0, self.map_size-1)]\n self.land_mark_map[temp_pos[0], temp_pos[1]] = 2\n\n # initialize humans\n self.human_list = []\n for i in range(self.human_num): \n temp_pos = [random.randint(0, self.map_size-1), random.randint(0, self.map_size-1)]\n while self.land_mark_map[temp_pos[0], temp_pos[1]] != 0:\n temp_pos = [random.randint(0, self.map_size-1), random.randint(0, self.map_size-1)]\n temp_human = Human(temp_pos)\n self.human_list.append(temp_human)\n\n \"\"\"\n 블록과 나무 그리고 사람을 초기화 할 때는 서로 겹치지 않도록 0이 아닌 부분을 제외하는 방식으로 위치 할당\n \"\"\"\n # initialize drones\n self.start_pos = [self.map_size-1, self.map_size-1] # 드론의 초기 위치를 동일하게 할당하고 아래쪽에 random 한 위치로 할당 시켜버린다.\n self.drone_list = []\n for i in range(drone_num):\n temp_drone = Drones(self.start_pos, view_range)\n self.drone_list.append(temp_drone) \n\n def get_full_obs(self):\n obs = np.ones((self.map_size, self.map_size, 3))\n for i in range(self.map_size):\n for j in range(self.map_size):\n if self.land_mark_map[i, j] == 1: # block\n obs[i, j, 0] = 0\n obs[i, j, 1] = 0\n obs[i, j, 2] = 0\n if self.land_mark_map[i, j] == 2: # tree\n obs[i, j, 0] = 0\n obs[i, j, 1] = 1\n obs[i, j, 2] = 0\n\n for i in range(self.human_num):\n obs[self.human_list[i].pos[0], self.human_list[i].pos[1], 0] = 1\n obs[self.human_list[i].pos[0], self.human_list[i].pos[1], 1] = 0\n obs[self.human_list[i].pos[0], self.human_list[i].pos[1], 2] = 0\n return obs\n\n def get_drone_obs(self, drone):\n obs_size = 2 * drone.view_range - 1\n # obs = np.ones((self.map_size, self.map_size, 3)) # global observation size 와 local observation size 를 모두 통일\n obs = np.ones((obs_size, obs_size, 3))\n\n for i in range(obs_size):\n for j in range(obs_size):\n x = i + drone.pos[0] - drone.view_range + 1\n y = j + drone.pos[1] - drone.view_range + 1\n\n for k in range(self.human_num):\n if self.human_list[k].pos[0] == x and self.human_list[k].pos[1] == y:\n obs[i, j, 0] = 1\n obs[i, j, 1] = 0\n obs[i, j, 2] = 0\n\n if x>=0 and x<=self.map_size-1 and y>=0 and y<=self.map_size-1:\n if self.land_mark_map[x, y] == 1:\n obs[i, j, 0] = 0\n obs[i, j, 1] = 0\n obs[i, j, 2] = 0\n if self.land_mark_map[x, y] == 2:\n obs[i, j, 0] = 0\n obs[i, j, 1] = 1\n obs[i, j, 2] = 0\n else:\n obs[i, j, 0] = 0.5\n obs[i, j, 1] = 0.5\n obs[i, j, 2] = 0.5\n\n if (drone.view_range - 1 - i)*(drone.view_range - 1 - i)+(drone.view_range - 1 - j)*(drone.view_range - 1 - j) > drone.view_range*drone.view_range:\n obs[i, j, 0] = 0.5\n obs[i, j, 1] = 0.5\n obs[i, j, 2] = 0.5\n return obs\n\n def get_joint_obs(self):\n obs = np.ones((self.map_size, self.map_size, 3))\n for i in range(self.map_size):\n for j in range(self.map_size):\n obs[i, j, 0] = 0.5\n obs[i, j, 1] = 0.5\n obs[i, j, 2] = 0.5\n for k in range(self.drone_num):\n temp = self.get_drone_obs(self.drone_list[k])\n size = temp.shape[0] \n for i in range(size):\n for j in range(size):\n x = i + self.drone_list[k].pos[0] - self.drone_list[k].view_range + 1\n y = j + self.drone_list[k].pos[1] - self.drone_list[k].view_range + 1\n if_obs = True\n if temp[i, j, 0] == 0.5 and temp[i, j, 1] == 0.5 and temp[i, j, 2] == 0.5:\n if_obs = False\n if if_obs == True: \n obs[x, y, 0] = temp[i, j, 0]\n obs[x, y, 1] = temp[i, j, 1]\n obs[x, y, 2] = temp[i, j, 2]\n return obs\n\n def get_local_obs(self, drone_index):\n obs = np.ones((self.map_size, self.map_size, 3))\n for i in range(self.map_size):\n for j in range(self.map_size):\n obs[i, j, 0] = 0.5\n obs[i, j, 1] = 0.5\n obs[i, j, 2] = 0.5\n temp = self.get_drone_obs(self.drone_list[drone_index])\n size = temp.shape[0]\n for i in range(size):\n for j in range(size):\n x = i + self.drone_list[drone_index].pos[0] - self.drone_list[drone_index].view_range + 1\n y = j + self.drone_list[drone_index].pos[1] - self.drone_list[drone_index].view_range + 1\n if_obs = True\n if temp[i, j, 0] == 0.5 and temp[i, j, 1] == 0.5 and temp[i, j, 2] == 0.5:\n if_obs = False\n if if_obs == True: \n obs[x, y, 0] = temp[i, j, 0]\n obs[x, y, 1] = temp[i, j, 1]\n obs[x, y, 2] = temp[i, j, 2]\n return obs\n \n def rand_reset_drone_pos(self): \n for k in range(self.drone_num): \n self.drone_list[k].pos = [random.randint(0, self.map_size-1), random.randint(0, self.map_size-1)] \n\n def drone_step(self, drone_act_list):\n # Action에 맞춰서 drone의 position을 grid 상에서 옮겨버림\n if len(drone_act_list) != self.drone_num:\n print(\"Not enough number of actions for the agents\")\n return 0\n bad_actions = []\n self.bad_action = False \n for k in range(self.drone_num):\n if drone_act_list[k] == 0: # go up\n if self.drone_list[k].pos[0] > 0:\n self.drone_list[k].pos[0] = self.drone_list[k].pos[0] - 1\n if self.drone_list[k].pos[0] == 0:\n self.bad_action = True\n elif drone_act_list[k] == 1: # go down\n if self.drone_list[k].pos[0] < self.map_size - 1:\n self.drone_list[k].pos[0] = self.drone_list[k].pos[0] + 1\n if self.drone_list[k].pos[0] == self.map_size:\n self.bad_action = True\n elif drone_act_list[k] == 2: # go left\n if self.drone_list[k].pos[1] > 0:\n self.drone_list[k].pos[1] = self.drone_list[k].pos[1] - 1\n if self.drone_list[k].pos[1] == 0:\n self.bad_action = True\n elif drone_act_list[k] == 3: # go right\n if self.drone_list[k].pos[1] < self.map_size - 1:\n self.drone_list[k].pos[1] = self.drone_list[k].pos[1] + 1\n if self.drone_list[k].pos[1] == self.map_size:\n self.bad_action = True\n elif drone_act_list[k] == 4: # stop\n self.drone_list[k].pos[0] = self.drone_list[k].pos[0]\n self.drone_list[k].pos[1] = self.drone_list[k].pos[1]\n \n if self.drone_list[k].pos[0] == self.map_size or self.drone_list[k].pos[1] == self.map_size:\n self.bad_action = True\n bad_actions.append(self.bad_action)\n\n return bad_actions\n \"\"\"\n ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ> y\n |\n |\n | x축, y축을 잘 보고 판단!\n |\n |\n |\n x\n \"\"\"\n def human_step(self, human_act_list):\n if len(human_act_list) != self.human_num:\n return\n for k in range(self.human_num):\n if human_act_list[k] == 0:\n if self.human_list[k].pos[0] > 0:\n free_space = self.land_mark_map[self.human_list[k].pos[0] - 1, self.human_list[k].pos[1]]\n if free_space == 0:\n self.human_list[k].pos[0] = self.human_list[k].pos[0] - 1\n elif human_act_list[k] == 1:\n if self.human_list[k].pos[0] < self.map_size - 1:\n free_space = self.land_mark_map[self.human_list[k].pos[0] + 1, self.human_list[k].pos[1]]\n if free_space == 0:\n self.human_list[k].pos[0] = self.human_list[k].pos[0] + 1\n elif human_act_list[k] == 2:\n if self.human_list[k].pos[1] > 0:\n free_space = self.land_mark_map[self.human_list[k].pos[0], self.human_list[k].pos[1] - 1]\n if free_space == 0:\n self.human_list[k].pos[1] = self.human_list[k].pos[1] - 1\n elif human_act_list[k] == 3:\n if self.human_list[k].pos[1] < self.map_size - 1:\n free_space = self.land_mark_map[self.human_list[k].pos[0], self.human_list[k].pos[1] + 1]\n if free_space == 0:\n self.human_list[k].pos[1] = self.human_list[k].pos[1] + 1\n elif human_act_list[k] == 4:\n self.human_list[k].pos[0] = self.human_list[k].pos[0]\n self.human_list[k].pos[1] = self.human_list[k].pos[1]\n\n def step(self, human_act_list, drone_act_list): \n self.drone_step(drone_act_list)\n self.human_step(human_act_list) \n\n def cal_distance(self, ref_x, ref_y, target_x, target_y):\n return np.sqrt(pow(ref_x -target_x, 2) + pow(ref_y - target_y, 2))\n\n def get_reward(self, observations, min_distance):\n obs_size = 2 * self.view_range - 1\n communication_bound = 2*obs_size\n total_reward = []\n distance_matrix = []\n # calculate the center position of the drone\n self.x_center = int(obs_size / 2)\n self.y_center = int(obs_size / 2)\n self.ref_x = self.drone_list[0].pos[0]\n self.ref_y = self.drone_list[0].pos[1]\n\n for k in range(self.drone_num): \n current_x = self.drone_list[k].pos[0]\n current_y = self.drone_list[k].pos[1]\n r = 0.1\n target_count = 0 \n temp_count = 0\n # target이 local observation 내부에 있는지 여부를 파악하여 reward를 줌\n for i in range(obs_size):\n for j in range(obs_size):\n if observations[k][i,j,0]==1 and observations[k][i,j,1] == 0 and observations[k][i,j,2] == 0:\n temp_count += 1\n target_count +=1\n \n if temp_count != 0: \n distance = self.cal_distance(self.x_center, self.y_center, i, j) \n r = (self.view_range*2 - distance + 1) * 0.1 \n temp_count = 0\n\n # # commnuication bound\n if min_distance[k] >= communication_bound:\n r = r + 0.3 \n\n # if target_count == 0 and (current_x <= 0 or current_y <=0 or current_x >= self.map_size - 1 or current_y >= self.map_size -1): \n # r = r - 1 \n\n total_reward.append(r) \n \n return total_reward\n\n def communication(self, agent_index):\n # get current drone position\n current_x = self.drone_list[agent_index].pos[0]\n current_y = self.drone_list[agent_index].pos[1]\n \n # calculate the distance between agents\n distance = np.zeros([self.drone_num,1])\n index = 0 \n for k in range(self.drone_num):\n if k is not agent_index:\n target_x = self.drone_list[k].pos[0]\n target_y = self.drone_list[k].pos[1]\n distance[k] = self.cal_distance(current_x, current_y, target_x, target_y)\n elif k == agent_index:\n distance[k] = 1000\n \n # get the closest agent index and position\n min_distance = np.min(distance)\n closest_agent_index = np.argmin(distance) \n closest_position = [self.drone_list[closest_agent_index].pos[0], self.drone_list[closest_agent_index].pos[0]] \n \n vector_pos = [current_x / self.map_size, \n current_y / self.map_size, \n self.drone_list[closest_agent_index].pos[0] / self.map_size, \n self.drone_list[closest_agent_index].pos[0]/ self.map_size] \n closest_info = vector_pos \n \n return [closest_info, min_distance]\n","sub_path":"VDN/env_Drones.py","file_name":"env_Drones.py","file_ext":"py","file_size_in_byte":14833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"488769921","text":"from typing import List\nfrom Leetcode.utils import perf\n\n\nclass Solution:\n\n serialize = {\n None: 'null',\n True: 'true',\n False: 'false'\n }\n\n @perf\n def run(self, actions, inputs, word_dictionary):\n ans = [None]\n wd = word_dictionary\n\n for j, action in enumerate(actions[1:], 1):\n if action == 'addWord':\n word = inputs[j][0]\n wd.addWord(word)\n ans.append(None)\n elif action == 'search':\n word = inputs[j][0]\n res = wd.search(word)\n ans.append(res)\n\n ans = [ self.serialize[entry] for entry in ans ]\n ans = '[' + ','.join(ans) + ']'\n return ans\n","sub_path":"Leetcode/add_and_search_word/run_solution.py","file_name":"run_solution.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"402936997","text":"#coding: utf-8\n\nimport datetime\nfrom django.contrib.auth import logout, authenticate, login\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response\nfrom django.core.validators import validate_email\nfrom django.contrib import messages\nfrom django.shortcuts import redirect\nfrom django.utils.safestring import mark_safe\nfrom .models import Perfil, TipoUsuario, Organizacion, Rol, Agenda\nfrom multimodelo.settings import LOGIN_URL\nfrom userdj.calendario import CalendarioAgenda\nfrom .forms import OrganizacionForm\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.http import HttpResponseForbidden\n\n\ndef login_user(request):\n logout(request)\n username = password = ''\n error = False\n if request.POST:\n username = request.POST['username']\n password = request.POST['password']\n next = request.GET.get('next', '/')\n user = authenticate(username=username, password=password)\n\n if user is not None:\n if user.is_active:\n login(request, user)\n return HttpResponseRedirect(next)\n else:\n error = True\n\n return render_to_response('userdj/login.html', {'error': error}, context_instance=RequestContext(request))\n\n\ndef salir(request):\n logout(request)\n return HttpResponseRedirect('/acceder/')\n\n\ndef asignar_cuestionario(request):\n idUsuario = request.GET['idUsuario']\n cuestionario = request.GET['cuestionario']\n valor = int(request.GET['valor'])\n \n usuario = User.objects.get(id=idUsuario)\n perfil = Perfil.objects.get(usuario=usuario)\n \n if cuestionario == 'entorno':\n perfil.cuestionario_entorno = valor\n else: \n perfil.cuestionario_extraccion = valor\n \n perfil.save()\n return HttpResponse(\"OK\")\n\n\ndef modificar_usuario(request, id_usuario):\n user = User.objects.get(id=id_usuario)\n perfil = Perfil.objects.get(usuario=user)\n\n tipos_usuarios = TipoUsuario.objects.all()\n organizaciones = Organizacion.objects.all()\n roles = Rol.objects.all()\n\n username = user.username\n nombre = user.first_name\n apellidos = user.last_name\n correo = user.email\n\n representante = perfil.principal\n tipo_usuario = perfil.tipo_usuario\n organizacion = perfil.organizacion\n rol = perfil.rol\n\n if request.method == 'POST':\n\n username = request.POST.get('username')\n nombre = request.POST.get('nombre')\n apellidos = request.POST.get('apellidos')\n correo = request.POST.get('correo')\n password = User.objects.make_random_password()\n\n representante = request.POST.get('representante', None)\n tipo_usuario = request.POST.get('tipo_usuario')\n organizacion = request.POST.get('organizacion', None)\n rol = request.POST.get('rol')\n\n try:\n validate_email(correo)\n try:\n from django.contrib.auth import authenticate\n\n user = User.objects.get(id=id_usuario)\n user.first_name = nombre\n user.last_name = apellidos\n\n if int(tipo_usuario) == 7:\n if request.user.is_superuser:\n user.is_staff = True\n user.is_superuser = True\n else:\n tipo_usuario = 1\n\n user.save()\n\n perfil = Perfil.objects.get(usuario=user)\n\n if organizacion:\n perfil.organizacion = Organizacion.objects.get(id=organizacion)\n else:\n perfil.organizacion = request.user.perfil.all()[:1].get().organizacion\n\n perfil.tipo_usuario = TipoUsuario.objects.get(id=tipo_usuario)\n perfil.rol = Rol.objects.get(id=rol)\n perfil.principal = False\n\n if representante:\n perfil.principal = True\n\n perfil.save()\n\n #email = EmailMultiAlternatives('Nueva cuenta', u\"Nombre de usuario: \" + username + u\"\\nContraseña: \" + password + u\"Agregar cita: http://mm.edgaruribe.mx/citas/agregar/\\n\", \"administrador@edgaruribe.mx\", [correo])\n #email.attach_alternative(u\"Nombre de usuario: \" + username + u\"
    Contraseña: \" + password + u'
    Agregar cita: http://mm.edgaruribe.mx/citas/agregar/
    ', \"text/html\")\n #email.send()\n\n # authenticate(username, password=password)\n\n messages.success(request, 'Usuario modificado correctamente.' + tipo_usuario)\n\n return redirect('usuarios')\n except Exception as e:\n messages.error(request, 'El nombre de usuario ya existe. ' + str(e) + ' - ' + tipo_usuario)\n except:\n messages.error(request, 'El correo es invalido.')\n\n return render_to_response('userdj/registro.html',\n {'username': username,\n 'nombre': nombre,\n 'apellidos': apellidos,\n 'correo': correo,\n 't_u': tipo_usuario,\n 'o': organizacion,\n 'r': rol,\n 'tipos_usuarios': tipos_usuarios,\n 'organizaciones': organizaciones,\n 'roles': roles,\n 'accion': \"Modificar\"},\n context_instance=RequestContext(request))\n\n\ndef agregar_usuario(request):\n tipos_usuarios = TipoUsuario.objects.all()\n organizaciones = Organizacion.objects.all()\n roles = Rol.objects.all()\n\n if request.method == 'POST':\n\n username = request.POST.get('username')\n nombre = request.POST.get('nombre')\n apellidos = request.POST.get('apellidos')\n correo = request.POST.get('correo')\n password = User.objects.make_random_password()\n\n representante = request.POST.get('representante', None)\n tipo_usuario = request.POST.get('tipo_usuario')\n organizacion = request.POST.get('organizacion', None)\n rol = request.POST.get('rol')\n\n existe = User.objects.filter(email=correo).exists()\n\n if not existe:\n try:\n validate_email(correo)\n try:\n from django.contrib.auth import authenticate\n\n user = User.objects.create_user(username, correo, password)\n user.first_name = nombre\n user.last_name = apellidos\n\n if int(tipo_usuario) == 7:\n if request.user.is_superuser:\n user.is_staff = True\n user.is_superuser = True\n else:\n tipo_usuario = 1\n\n user.save()\n\n perfil = Perfil()\n\n if organizacion:\n perfil.organizacion = Organizacion.objects.get(id=organizacion)\n else:\n perfil.organizacion = request.user.perfil.all()[:1].get().organizacion\n\n perfil.usuario = user\n perfil.tipo_usuario = TipoUsuario.objects.get(id=tipo_usuario)\n perfil.rol = Rol.objects.get(id=rol)\n perfil.principal = False\n\n if representante:\n perfil.principal = True\n\n perfil.save()\n\n if perfil.principal:\n asunto = u\"Registro como representante de organización\"\n mensaje = u\"Qué tal, el motivo del presente es que has sido registrado como representante de tu organización en el sistema para la extracción del conocimiento tácito de la organización para realizar el proyecto de formalización del conocimiento sobre los procesos para desarrolo de software que se llevan a cabo en tu organización, adjunto en este mensaje se envían el usuario y contraseña para acceso al sistema así como el link para acceder al sistema.\"\n mensaje_fin = u\"El siguiente paso es que entres al sistema, revises los datos de tu organización y agregues a los entrevistados de tu organización gracias.\"\n else:\n asunto = u\"Registro como entrevistado de organización\"\n mensaje = u\"Qué tal, el motivo del presente es que has sido registrado como entrevistado de tu organización, en el sistema para la extracción del conocimiento tácito de la organización para realizar el proyecto de formalización del conocimiento sobre los procesos para desarrolo de software que se llevan a cabo en tu organización, adjunto en este mensaje se envían el usuario y contraseña para acceso al sistema así como el link para acceder al sistema.\"\n mensaje_fin = u\"El siguiente paso es que accedas al sistema y selecciones el día y hora de tu entrevista gracias.\"\n\n email = EmailMultiAlternatives(asunto,\n mensaje + u\"\\n\\nNombre de usuario: \" + username + u\"\\nContraseña: \" + password + u\"Agregar cita: http://mm.edgaruribe.mx/citas/agregar/\\n\\n\" + mensaje_fin + u\"\\n\",\n \"administrador@edgaruribe.mx\", [correo])\n email.attach_alternative(\n \"

    \" + mensaje + u\"



    Nombre de usuario: \" + username + u\"
    Contraseña: \" + password + u'
    Agregar cita: http://mm.edgaruribe.mx/citas/agregar/

    ' + mensaje_fin + u\"


    \",\n \"text/html\")\n email.send()\n\n # authenticate(username, password=password)\n\n messages.success(request, 'Usuario agregado correctamente.' + tipo_usuario)\n\n return redirect('usuarios')\n except Exception as e:\n messages.error(request, 'El nombre de usuario ya existe. ' + str(e) + ' - ' + tipo_usuario)\n except:\n messages.error(request, 'El correo es invalido.')\n else:\n messages.error(request, 'El correo ya existe.')\n\n return render_to_response('userdj/registro.html',\n {'username': username,\n 'nombre': nombre,\n 'apellidos': apellidos,\n 'correo': correo,\n 't_u': tipo_usuario,\n 'o': organizacion,\n 'r': rol,\n 'tipos_usuarios': tipos_usuarios,\n 'organizaciones': organizaciones,\n 'roles': roles},\n context_instance=RequestContext(request))\n else:\n return render_to_response('userdj/registro.html',\n {'tipos_usuarios': tipos_usuarios,\n 'organizaciones': organizaciones,\n 'roles': roles},\n context_instance=RequestContext(request))\n\n\ndef usuarios(request):\n organizacion = int(request.GET.get(\"organizacion\", 0))\n organizaciones = Organizacion.objects.all()\n tipos_usuarios = TipoUsuario.objects.all()\n roles = Rol.objects.all()\n\n page = request.GET.get('page')\n\n if request.user.is_superuser:\n if not organizacion == 0:\n usuarios = User.objects.filter(perfil__organizacion_id=organizacion)\n else:\n usuarios = User.objects.all().order_by(\"-id\")\n else:\n usuarios = User.objects.filter(perfil__organizacion=request.user.perfil.all()[:1].get().organizacion).order_by(\n \"-id\")\n\n paginator = Paginator(usuarios, 10)\n\n try:\n usuarios = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n usuarios = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n usuarios = paginator.page(paginator.num_pages)\n\n return render_to_response('userdj/usuarios.html',\n {'usuarios': usuarios,\n 'organizacion': organizacion,\n 'organizaciones': organizaciones,\n 'tipos_usuarios': tipos_usuarios,\n 'roles': roles},\n context_instance=RequestContext(request))\n\n\ndef agenda(request, mes, ano):\n organizacion = int(request.GET.get('organizacion', 0))\n citas = Agenda.objects.filter(fecha__year=ano, fecha__month=int(mes)).order_by('fecha')\n\n if not organizacion == 0:\n citas = Agenda.objects.filter(usuario__perfil__organizacion_id=organizacion, fecha__year=ano,\n fecha__month=int(mes)).order_by('fecha')\n\n calendario = CalendarioAgenda(citas).formatmonth(int(ano), int(mes))\n\n organizaciones = Organizacion.objects.all()\n return render_to_response('userdj/calendario.html', {'calendario': mark_safe(calendario),\n 'citas': citas,\n 'mes': mes,\n 'ano': ano,\n 'organizaciones': organizaciones,\n 'organizacion': organizacion},\n context_instance=RequestContext(request))\n\n\ndef organizaciones(request):\n if request.user.is_superuser:\n organizaciones = Organizacion.objects.all().order_by(\"-id\")\n else:\n organizaciones = Organizacion.objects.filter(perfil__usuario=request.user)\n\n paginator = Paginator(organizaciones, 10)\n page = request.GET.get('page')\n\n try:\n organizaciones = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n organizaciones = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n organizaciones = paginator.page(paginator.num_pages)\n\n form = OrganizacionForm()\n\n return render_to_response('userdj/organizaciones.html', {'organizaciones': organizaciones,\n 'form': form},\n context_instance=RequestContext(request))\n\n\ndef agregar_organizacion(request):\n if request.method == 'POST':\n form = OrganizacionForm(request.POST)\n\n if form.is_valid():\n form.save()\n messages.success(request, 'Organización agregada correctamente.')\n return redirect('organizaciones')\n else:\n messages.error(request, 'Error al agregar el formulario.')\n\n else:\n form = OrganizacionForm()\n return render_to_response('userdj/agregar_organizacion.html', {'form': form},\n context_instance=RequestContext(request))\n\n\ndef modificar_organizacion(request, id_organizacion):\n organizacion = Organizacion.objects.get(id=id_organizacion)\n\n if request.method == 'POST':\n form = OrganizacionForm(request.POST, instance=organizacion)\n\n if form.is_valid():\n form.save()\n messages.success(request, 'Organización modificada correctamente.')\n return redirect('organizaciones')\n else:\n messages.error(request, 'Error al modificar el formulario.')\n\n else:\n form = OrganizacionForm(instance=organizacion)\n return render_to_response('userdj/agregar_organizacion.html', {'form': form, 'modificar': True},\n context_instance=RequestContext(request))\n\n\n@login_required(login_url=LOGIN_URL)\ndef agregar_cita(request):\n cita = None\n\n if request.method == 'POST':\n fecha = request.POST.get('fecha')\n hora = request.POST.get('hora') + \":00\"\n fecha_hora = datetime.datetime.strptime(fecha + \" \" + hora, '%d/%m/%Y %H:%M:%S')\n\n try:\n cita = Agenda.objects.get(usuario=request.user, fecha=fecha_hora)\n messages.error(request, 'La cita ya existe, para camibiarla selecciona otra fecha y/u hora.')\n except Agenda.DoesNotExist:\n try:\n cita = Agenda.objects.get(usuario=request.user)\n cita.cancelada = True\n cita.save()\n\n agenda = Agenda()\n agenda.fecha = fecha_hora\n agenda.usuario = request.user\n agenda.modificada = True\n agenda.save()\n messages.success(request, 'Cita modificada correctamente.')\n\n except:\n agenda = Agenda()\n agenda.fecha = fecha_hora\n agenda.usuario = request.user\n agenda.save()\n messages.success(request, 'Cita agregada correctamente.')\n else:\n try:\n cita = Agenda.objects.filter(usuario=request.user)[:1].get()\n except Agenda.DoesNotExist:\n cita = None\n\n return render_to_response('userdj/agregar_cita.html', {'cita': cita},\n context_instance=RequestContext(request))\n\n\ndef enviar_recordatorio(request):\n today = datetime.date.today()\n citas = Agenda.objects.filter(fecha__year=today.year, fecha__month=today.month, fecha__day=today.day)\n correos = \"\"\n for cita in citas:\n correos += cita.usuario.email + \"
    \"\n email = EmailMultiAlternatives('Recordatorio cita',\n \"Recuerda que tu cita es hoy a las \" + str(cita.fecha.hour) + \":\" + str(\n cita.fecha.minute) + \".\", \"administrador@edgaruribe.mx\",\n [cita.usuario.email])\n email.attach_alternative(\n \"Recuerda que tu cita es hoy a las \" + str(cita.fecha.hour) + \":\" + str(cita.fecha.minute) + \".\",\n \"text/html\")\n try:\n email.send()\n except:\n pass\n\n return HttpResponse(\"Ok!
    \" + correos)\n\n\ndef eliminar_usuario(request, id_usuario):\n borrar = bool(request.POST.get('borrar', False))\n usuario = User.objects.get(id=id_usuario)\n\n if borrar:\n usuario.delete()\n messages.success(request, 'Usuario eliminado correctamente.')\n return redirect(\"usuarios\")\n\n return render_to_response('userdj/borrar.html',\n {'mensaje': u\" al usuario %s %s\" % (usuario.first_name, usuario.last_name ),\n 'link': reverse('usuarios')},\n context_instance=RequestContext(request))\n\n\ndef eliminar_organizacion(request, id_organizacion):\n borrar = bool(request.POST.get('borrar', False))\n\n organizacion = Organizacion.objects.get(id=id_organizacion)\n\n if borrar:\n organizacion.delete()\n messages.success(request, 'Organización eliminado correctamente.')\n return redirect(\"organizaciones\")\n\n return render_to_response('userdj/borrar.html', {'mensaje': u\" la organización %s \" % organizacion.nombre,\n 'link': reverse('organizaciones')},\n context_instance=RequestContext(request))\n","sub_path":"multimodelo/userdj/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"536367475","text":"# Copyright 2010 New Relic, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pytest\nimport threading\n\nfrom newrelic.core.config import global_settings\nfrom testing_support.fixtures import override_generic_settings\n\nfrom newrelic.core.application import Application\nfrom newrelic.core.agent_streaming import StreamingRpc\nfrom newrelic.core.infinite_tracing_pb2 import Span, AttributeValue\nfrom testing_support.validators.validate_metric_payload import (\n validate_metric_payload)\n\nsettings = global_settings()\n\nCONDITION_CLS = type(threading.Condition())\n\n\n@pytest.fixture()\ndef app():\n app = Application('Python Agent Test (Infinite Tracing)')\n yield app\n # Calling internal_agent_shutdown on an application that is already closed\n # will raise an exception.\n active_session = app._active_session\n try:\n app.internal_agent_shutdown(restart=False)\n except:\n pass\n if active_session:\n assert not active_session._rpc.response_processing_thread.is_alive()\n assert not active_session._rpc.channel\n\n\n@pytest.mark.parametrize(\n 'status_code, metrics', (\n ('UNIMPLEMENTED', [\n ('Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED', 1),\n ('Supportability/InfiniteTracing/Span/Response/Error', 1)]),\n ('INTERNAL', [\n ('Supportability/InfiniteTracing/Span/gRPC/INTERNAL', 1),\n ('Supportability/InfiniteTracing/Span/Response/Error', 1)]),\n ))\ndef test_infinite_tracing_span_streaming(mock_grpc_server,\n status_code, metrics, monkeypatch, app):\n event = threading.Event()\n\n class TerminateOnWait(CONDITION_CLS):\n def notify_all(self, *args, **kwargs):\n event.set()\n return super(TerminateOnWait, self).notify_all(*args, **kwargs)\n\n def wait(self, *args, **kwargs):\n event.set()\n return super(TerminateOnWait, self).wait(*args, **kwargs)\n\n @staticmethod\n def condition(*args, **kwargs):\n return TerminateOnWait(*args, **kwargs)\n\n monkeypatch.setattr(StreamingRpc, 'condition', condition)\n\n span = Span(\n intrinsics={'status_code': AttributeValue(string_value=status_code)},\n agent_attributes={},\n user_attributes={})\n\n @override_generic_settings(settings, {\n 'distributed_tracing.enabled': True,\n 'span_events.enabled': True,\n 'infinite_tracing.trace_observer_host': 'localhost',\n 'infinite_tracing.trace_observer_port': mock_grpc_server,\n 'infinite_tracing.ssl': False,\n })\n @validate_metric_payload(metrics=metrics)\n def _test():\n app.connect_to_data_collector(None)\n\n app._stats_engine.span_stream.put(span)\n\n assert event.wait(timeout=5)\n\n app.harvest(shutdown=True)\n\n _test()\n\n\ndef test_reconnect_on_failure(monkeypatch, mock_grpc_server,\n buffer_empty_event, app):\n\n status_code = \"INTERNAL\"\n wait_event = threading.Event()\n continue_event = threading.Event()\n\n class WaitOnWait(CONDITION_CLS):\n def wait(self, *args, **kwargs):\n wait_event.set()\n continue_event.wait()\n return True\n\n @staticmethod\n def condition(*args, **kwargs):\n return WaitOnWait(*args, **kwargs)\n\n monkeypatch.setattr(StreamingRpc, 'condition', condition)\n\n terminating_span = Span(\n intrinsics={'status_code': AttributeValue(string_value=status_code)},\n agent_attributes={},\n user_attributes={})\n\n span = Span(\n intrinsics={},\n agent_attributes={},\n user_attributes={})\n\n @override_generic_settings(settings, {\n 'distributed_tracing.enabled': True,\n 'span_events.enabled': True,\n 'infinite_tracing.trace_observer_host': 'localhost',\n 'infinite_tracing.trace_observer_port': mock_grpc_server,\n 'infinite_tracing.ssl': False,\n })\n def _test():\n app.connect_to_data_collector(None)\n\n # Send a span that will trigger a failure\n app._stats_engine.span_stream.put(terminating_span)\n\n assert wait_event.wait(timeout=5)\n\n # Send a normal span afterwards\n app._stats_engine.span_stream.put(span)\n\n buffer_empty_event.clear()\n\n # Trigger the event so that a reconnect will occur\n continue_event.set()\n\n # Wait for the stream buffer to empty meaning all spans have been sent.\n assert buffer_empty_event.wait(10)\n app.internal_agent_shutdown(restart=False)\n\n _test()\n\n\ndef test_agent_restart(app):\n # Get the application connected to the actual 8T endpoint\n app.connect_to_data_collector(None)\n rpc = app._active_session._rpc\n\n # Store references to the original rpc and threads\n original_rpc = rpc.rpc\n original_thread = rpc.response_processing_thread\n original_span_stream = app._stats_engine.span_stream\n assert original_rpc\n assert rpc.response_processing_thread.is_alive()\n\n # Force an agent restart\n app.internal_agent_shutdown(restart=True)\n\n # Wait for connect to complete\n app._connected_event.wait()\n rpc = app._active_session._rpc\n\n assert not original_thread.is_alive()\n assert rpc.rpc is not original_rpc\n assert app._stats_engine.span_stream is not original_span_stream\n assert rpc.response_processing_thread.is_alive()\n\n\ndef test_disconnect_on_UNIMPLEMENTED(mock_grpc_server, monkeypatch, app):\n event = threading.Event()\n\n class WaitOnNotify(CONDITION_CLS):\n def notify_all(self, *args, **kwargs):\n event.set()\n return super(WaitOnNotify, self).notify_all(*args, **kwargs)\n\n @staticmethod\n def condition(*args, **kwargs):\n return WaitOnNotify(*args, **kwargs)\n\n monkeypatch.setattr(StreamingRpc, 'condition', condition)\n\n terminating_span = Span(\n intrinsics={'status_code': AttributeValue(\n string_value='UNIMPLEMENTED')},\n agent_attributes={},\n user_attributes={})\n\n @override_generic_settings(settings, {\n 'distributed_tracing.enabled': True,\n 'span_events.enabled': True,\n 'infinite_tracing.trace_observer_host': 'localhost',\n 'infinite_tracing.trace_observer_port': mock_grpc_server,\n 'infinite_tracing.ssl': False,\n })\n def _test():\n app.connect_to_data_collector(None)\n\n # Send a span that will trigger disconnect\n app._stats_engine.span_stream.put(terminating_span)\n\n # Wait for the notify event in close to be called\n assert event.wait(timeout=5)\n\n # Verify the rpc management thread is killed\n rpc_thread = app._active_session._rpc.response_processing_thread\n rpc_thread.join(timeout=5)\n assert not rpc_thread.is_alive()\n\n _test()\n\n\ndef test_agent_shutdown():\n # Get the application connected to the actual 8T endpoint\n app = Application('Python Agent Test (Infinite Tracing)')\n app.connect_to_data_collector(None)\n rpc = app._active_session._rpc\n # Store references to the original rpc and threads\n assert rpc.response_processing_thread.is_alive()\n app.internal_agent_shutdown(restart=False)\n assert not rpc.response_processing_thread.is_alive()\n assert not rpc.channel\n\n\n@pytest.mark.xfail(reason=\"This test is flaky\", strict=False)\ndef test_no_delay_on_ok(mock_grpc_server, monkeypatch, app):\n wait_event = threading.Event()\n connect_event = threading.Event()\n\n metrics = [('Supportability/InfiniteTracing/Span/gRPC/OK', 1),\n ('Supportability/InfiniteTracing/Span/Response/Error', None)]\n\n class SetFlagOnWait(CONDITION_CLS):\n def wait(self, *args, **kwargs):\n wait_event.set()\n return super(SetFlagOnWait, self).wait(*args, **kwargs)\n\n @staticmethod\n def condition(*args, **kwargs):\n return SetFlagOnWait(*args, **kwargs)\n\n monkeypatch.setattr(StreamingRpc, 'condition', condition)\n span = Span(\n intrinsics={\"status_code\": AttributeValue(string_value=\"OK\")},\n agent_attributes={},\n user_attributes={},\n )\n\n @override_generic_settings(settings, {\n 'distributed_tracing.enabled': True,\n 'span_events.enabled': True,\n 'infinite_tracing.trace_observer_host': 'localhost',\n 'infinite_tracing.trace_observer_port': mock_grpc_server,\n 'infinite_tracing.ssl': False,\n })\n @validate_metric_payload(metrics=metrics)\n def _test():\n\n def connect_complete():\n connect_event.set()\n\n app.connect_to_data_collector(connect_complete)\n\n assert connect_event.wait(timeout=5)\n connect_event.clear()\n\n # Send a span that will trigger disconnect\n stream_buffer = app._stats_engine.span_stream\n rpc = app._active_session._rpc\n\n _rpc = rpc.rpc\n\n def patched_rpc(*args, **kwargs):\n connect_event.set()\n return _rpc(*args, **kwargs)\n\n rpc.rpc = patched_rpc\n\n\n # Put a span that will trigger an OK status code and wait for an attempted\n # reconnect.\n stream_buffer.put(span)\n assert connect_event.wait(timeout=5)\n rpc.close()\n assert not wait_event.is_set()\n app.harvest()\n\n _test()\n","sub_path":"tests/agent_streaming/test_infinite_tracing.py","file_name":"test_infinite_tracing.py","file_ext":"py","file_size_in_byte":9683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"60394880","text":"#-*-coding:utf8 -*-\n'''\n 缓存配置,缓存服务挂掉时,程序里的数据,以及elasticsearch的搜索点\n'''\nimport ConfigParser\nimport os\nimport pdb\nimport json\nfrom Clogdata import Clogdata\nfrom EShelplog import getlogInst\nimport os\ng_loginst=getlogInst()\ncf = ConfigParser.ConfigParser()\ncf.read('config/ess.conf')\nclass ESconfig:\n def __init__(self):\n global cf\n secs = cf.sections()\n self.Scalesize=0\n def setsize(self,size):\n self.Scalesize=size\n ret=cf.set(\"elasticsearchpara\",\"scalsize\",size)\n with open(\"config/ess.conf\", \"w+\") as f:\n cf.write(f)\n\n def getsize(self):\n temp = cf.get(\"elasticsearchpara\", \"scalsize\")\n self.Scalesize =cf.get(\"elasticsearchpara\", \"scalsize\")\n return self.Scalesize\n\nclass Dictcache:\n def __init__(self):\n self.dict={}\n def Getdict(self):\n global cf\n secs = cf.sections()\n str = cf.get(\"dictdata\", \"g_dict\")\n self.dict = self.deserialize(str)\n return self.dict\n def Setdict(self,tempdict):\n self.dict = tempdict\n ret = cf.set(\"dictdata\", \"g_dict\", self.serialize())\n with open(\"config/ess.conf\", \"w+\") as f:\n cf.write(f)\n def serialize(self):\n strdict=\"\"\n for (key,value) in self.dict.items():\n strdict+=key\n strdict+=\"@@@\"\n valuedata=json.dumps(value.Data2Json())\n strdict+=str(valuedata)\n strdict+=\"&&\"\n strdict=strdict[:-2] #去掉最后一个”&&“\n return strdict\n\n def deserialize(self,strdata):\n tempdict={}\n strdata=strdata.encode('utf-8')\n filedlist = strdata.split('&&')\n for item in filedlist:\n keyvalue=item.split(\"@@@\",1)\n strobj=keyvalue[1]\n jsonobj=json.loads(strobj.encode('utf-8'))\n logobj=Clogdata()\n logobj.copyAttr(jsonobj)\n tempdict[keyvalue[0]]=logobj\n self.dict=tempdict\n return self.dict\n pass\n def Createconf(self):# 不存在就创建一个\n global g_loginst\n flag=os.path.exists('config/ess.conf')\n if flag==True:\n pass\n g_loginst.logger.info(\"配置文件存在,不需要创建\")\n else:\n g_loginst.logger.info(\"配置文件不存在,创建文件\")\n cf.add_section('elasticsearchpara')\n cf.set('elasticsearchpara','scalsize',0)\n cf.add_section('dictdata')\n cf.set('dictdata','g_dict',{})\n pdb.set_trace()\n with open('config/ess.conf', 'w') as configfile:\n cf.write(configfile)\nif __name__ =='__main__':\n pass\n t=Dictcache()\n pdb.set_trace()\n t.Createconf()\n","sub_path":"ESconfig.py","file_name":"ESconfig.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"66909575","text":"import xml.etree.ElementTree as ET \r\nimport json\r\n\r\ndatasource= open('FindBugsCompileTime.xml')\r\ntree = ET.parse('FindBugsCompileTime.xml') \r\nroot = tree.getroot()\r\nprint (root.get('version'))\r\n# one specific item attribute\r\nprint(root[1].attrib)\r\nvulnTag= \"BugInstance\"\r\nappName=\"\"\r\n#Count total number of vulnerabilities\r\nfor element in root:\r\n if (element.tag=='FindBugsSummary'):\r\n total_vuln= element.get('total_bugs')\r\nprint (total_vuln)\r\nif (root[1].get('projectName')!=None):\r\n appName = root[1].get('projectName')\r\nelse:\r\n appName = \"ProjectNameNotDefined\"\r\nprint (appName)\r\nmydict= {}\r\nmydict [vulnTag]=[]\r\nfor element in root:\r\n if (element.tag==vulnTag):\r\n mydict[vulnTag].append({ \r\n 'findingName': element.get('category'),\r\n 'severity': element.get('priority'),\r\n 'description': element[0][0].get('sourcepath')\r\n })\r\nwith open('findbugs-json-output.json', 'w') as outfile: \r\n json.dump(mydict, outfile)\r\n\r\n\r\n\r\n","sub_path":"findbugs-python.py","file_name":"findbugs-python.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"46636818","text":"from rest_framework import serializers\nfrom authentication.models import User\nfrom social.models import Followers, Request, Tags, TagContains\nfrom utils import paginator\n\nclass TagSearchSerializer(serializers.ModelSerializer):\n count = serializers.SerializerMethodField()\n results = serializers.SerializerMethodField()\n total_pages = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n fields = ('count', 'total_pages', 'results')\n\n def get_count(self, obj):\n count = len(self.context.get(\"data\"))\n return count\n\n def get_total_pages(self, obj):\n all = self.context.get(\"data\")\n p = paginator(all, limit=15)\n return p.get('total_page')\n\n def get_results(self, obj):\n\n page = self.context.get(\"page\")\n url = self.context.get(\"url\")\n all = self.context.get(\"data\")\n requset_user = self.context.get('request_user')\n p = paginator(all, page=page, limit=15)\n\n result = p.get('result')\n result_list = []\n for tag in result:\n\n all_pic = TagContains.objects.filter(tag=tag).order_by('-id')\n if len(all_pic) == 0:\n continue\n picture = url + str(all_pic[0].post.picture)\n\n item = {\n 'tag_id': tag.id,\n 'tag_name': tag.name,\n 'picture': picture\n }\n result_list.append(item)\n\n return result_list\n\n\n\n","sub_path":"social/serializers/tag_search_serializer.py","file_name":"tag_search_serializer.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"264894079","text":"import numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torchvision.models as models\r\nimport math\r\n\r\nimport os,inspect,sys\r\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\r\nsys.path.insert(0,currentdir)\r\n\r\n\"\"\"\r\nImplementation of CNN+LSTM.\r\n\"\"\"\r\n\"\"\"\r\nImplementation of Resnet+LSTM\r\n\"\"\"\r\nclass ResCRNN(nn.Module):\r\n def __init__(self, sample_size=256, sample_duration=16, num_classes=100,\r\n lstm_hidden_size=512, lstm_num_layers=1, arch=\"resnet18\",\r\n attention=False):\r\n super(ResCRNN, self).__init__()\r\n self.sample_size = sample_size\r\n self.sample_duration = sample_duration\r\n self.num_classes = num_classes\r\n\r\n # network params\r\n self.lstm_hidden_size = lstm_hidden_size\r\n self.lstm_num_layers = lstm_num_layers\r\n self.attention = attention\r\n\r\n # network architecture\r\n if arch == \"resnet18\":\r\n resnet = models.resnet18(pretrained=False)\r\n elif arch == \"resnet34\":\r\n resnet = models.resnet34(pretrained=False)\r\n elif arch == \"resnet50\":\r\n resnet = models.resnet50(pretrained=False)\r\n elif arch == \"resnet101\":\r\n resnet = models.resnet101(pretrained=False)\r\n elif arch == \"resnet152\":\r\n resnet = models.resnet152(pretrained=False)\r\n # delete the last fc layer\r\n modules = list(resnet.children())[:-1]\r\n self.resnet = nn.Sequential(*modules)\r\n self.lstm = nn.LSTM(\r\n input_size=resnet.fc.in_features,\r\n hidden_size=self.lstm_hidden_size,\r\n num_layers=self.lstm_num_layers,\r\n batch_first=True,\r\n )\r\n self.fc1 = nn.Linear(self.lstm_hidden_size, self.num_classes)\r\n\r\n def forward(self, x):\r\n # CNN\r\n cnn_embed_seq = []\r\n # x: (batch_size, channel, t, h, w)\r\n for t in range(x.size(2)):\r\n # with torch.no_grad():\r\n out = self.resnet(x[:, :, t, :, :])\r\n # print(out.shape)\r\n out = out.view(out.size(0), -1)\r\n cnn_embed_seq.append(out)\r\n\r\n cnn_embed_seq = torch.stack(cnn_embed_seq, dim=0)\r\n # print(cnn_embed_seq.shape)\r\n # batch first\r\n cnn_embed_seq = cnn_embed_seq.transpose_(0, 1)\r\n\r\n # LSTM\r\n # use faster code paths\r\n self.lstm.flatten_parameters()\r\n out, (h_n, c_n) = self.lstm(cnn_embed_seq, None)\r\n # MLP\r\n if self.attention:\r\n out = self.fc1(self.attn_block(out))\r\n else:\r\n # out: (batch, seq, feature), choose the last time step\r\n out = self.fc1(out[:, -1, :])\r\n\r\n return out\r\n\r\n\r\n# Test\r\nif __name__ == '__main__':\r\n import sys\r\n sys.path.append(\"..\")\r\n import torchvision.transforms as transforms\r\n sample_size = 128\r\n sample_duration = 16\r\n num_classes = 100\r\n # crnn = CRNN()\r\n data=torch.randn(1,3,16,128,128).cuda()\r\n crnn = ResCRNN(sample_size=sample_size, sample_duration=sample_duration, num_classes=num_classes, arch=\"resnet18\").cuda()\r\n print(crnn(data).size())","sub_path":"models/resnet2dlstm.py","file_name":"resnet2dlstm.py","file_ext":"py","file_size_in_byte":3162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"241236709","text":"import numpy as np\nimport tensorflow as tf\nfrom tqdm import tqdm\n\nimport os\nimport matplotlib.pyplot as plt\n\npath_upwards = '../../'\nimport sys\nsys.path.extend([path_upwards + '../TailingDamDetection/'])\n\nimport config\nfrom nn_architecture.aka_lenet import cnn_adjust_lr\nfrom utils.ml_functions import softmax\n\nrseed = 1000\nnp.random.seed(rseed)\ntf.random.set_random_seed(rseed)\n\nexperiment_name = 'two_classes_images_v3'\n\npath_to_data = path_upwards + config.data_path + config.experiment_data + experiment_name + '/'\npath_to_results = path_upwards + config.result_path + config.experiment_data + experiment_name + '/'\nif not os.path.exists(path_to_results):\n os.makedirs(path_to_results)\n\nn_epoch = 40\nbatch_size = 32\n\ndata = np.load(path_to_data + 'train_test_data.npz')\n\ntrain_images = data['train_images']\ntrain_labels = data['train_labels']\n\ncnn = cnn_adjust_lr(n_classes=train_labels.shape[1], input_shape=train_images[0].shape, lr=1e-4)\n\ntrain_accuracy = np.zeros((n_epoch,), dtype=np.float64)\n\nfor epoch in range(n_epoch):\n print('\\tepoch %d...' % epoch)\n\n cnn.fit(train_images, train_labels, epochs=1, shuffle=True, batch_size=batch_size, verbose=0)\n\n train_prediction = cnn.predict(train_images)\n train_accuracy[epoch] = np.mean(np.argmax(train_prediction, axis=1) == np.argmax(train_labels, axis=1))\n print('\\ttrain accuracy {}'.format(train_accuracy[epoch]))\n\n\ntrain_predicted_probs = softmax(train_prediction, axis=1)\n\nplt.plot(range(n_epoch), train_accuracy, 'r--', label='train')\nplt.title('Accuracy')\n#plt.savefig(path_to_results + 'accuracy_results_{}.pdf'.format(cv_run))\nplt.show()\n\nif not os.path.exists(path_to_results + 'trained_model/'):\n os.makedirs(path_to_results + 'trained_model/')\ncnn.save(path_to_results + 'trained_model/weights.ckpt')\n\nnp.savez(path_to_results + 'results',\n train_accuracy=train_accuracy,\n train_predicted_probs=train_predicted_probs)\n","sub_path":"dam_recognition/two_classes_images_v3/train_cnn_from_scratch.py","file_name":"train_cnn_from_scratch.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"615581078","text":"# -*- coding: utf-8 -*-\nfrom main.Database.base import Base\nfrom sqlalchemy import Column, String, Integer, Table, ForeignKey\nfrom sqlalchemy.orm import relationship, backref\n\nroles_users = Table(\n 'roles_users',\n Base.metadata,\n Column('user_id', Integer(), ForeignKey('user.id')),\n Column('role_id', Integer(), ForeignKey('permission.id'))\n)\n\nclass User(Base):\n __tablename__ = 'user'\n id = Column(Integer, primary_key=True)\n username = Column(String(32))\n psk = Column(String)\n permission = relationship(\n 'Permission',\n secondary=roles_users,\n backref=backref('user', lazy='dynamic')\n )\n\n\n def __init__(self, username, psk, permission):\n self.username = username\n self.psk = psk\n self.permission = permission\n\n def __str__(self):\n return \"id: {}, username: {}, psk: {}, permission: {}\".format(self.id, self.username, self.psk, self.permission)\n","sub_path":"software/django project/main/Database/User.py","file_name":"User.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"309597654","text":"from company import CompanyManager\nfrom IO import IO\n\n\ndef main():\n io = IO()\n io.options['test']()\n \"\"\" OLD SCHOOL\n manager = CompanyManager('database.db')\n manager.create_tables()\n\n while True:\n command = input(\"command>\")\n if command == \"add_employee\":\n name = input(\"name\")\n monthly_salary = input(\"monthly_salary\")\n yearly_bonus = input(\"yearly_bonus\")\n position = input(\"position\")\n manager.add_employee(name, monthly_salary, yearly_bonus, position)\n\n if command == \"list_employess\":\n return manager.cursor.execute(\"SELECT name FROM users\")\n \"\"\"\nif __name__ == '__main__':\n main()\n","sub_path":"week6/2-nd/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"296521761","text":"# -*- coding: utf-8 -*-\nimport re\n\ndef fixed_width(input_str, fixed_w=0, input_str_codec='utf-8'):\n\t\"\"\"\n\t把一个字符串裁剪为不长于fixed_w的版本,考虑“中文字符在屏幕中占两个显示位”的因素。\n\t\"\"\"\n\tif not isinstance(input_str, basestring):\n\t\treturn input_str\n\telif isinstance(input_str, basestring) and not isinstance(input_str, unicode):\n\t\tinput_str = unicode(input_str, input_str_codec)\n\n\tpat = re.compile(r'[\\x00-\\xFF]')\n\n\twidth_got = 0\n\tshorted_str = ''\n\tori_len = len(input_str)\n\tstop_poz = ori_len if ori_len > fixed_w else fixed_w\t#取长的,循环到取够长度为止\n\n\tc_list = list(input_str)\n\n\tfor i in range(0, stop_poz):\n\t\tif i < ori_len:\n\t\t\tnew_c = c_list[i]\n\t\telse:\n\t\t\tnew_c = ' '\n\n\t\tif pat.match(new_c):\n\t\t\twidth_got += 1\n\t\telse:\n\t\t\twidth_got += 2\n\n\t\tshorted_str += new_c\n\n\t\tif width_got == fixed_w:\n\t\t\treturn shorted_str\n\t\telif width_got == fixed_w + 1:\n\t\t\treturn shorted_str[0:i] + ' '\n\n","sub_path":"haotuWeixinEnterprise/haotu/utils/string.py","file_name":"string.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"138609440","text":"resource = [400, 540, 120, 9, 550]\nespresso = [250, 0, 16, 1, 4]\nlatte = [350, 75, 20, 1, 7]\ncappuccino = [200, 100, 12, 1, 6]\nnew_resource = [[], [], [], [], []]\n\n\ndef result(resource):\n print('The coffee machine has:')\n print(str(resource[0]) + ' of water')\n print(str(resource[1]) + ' of milk')\n print(str(resource[2]) + ' of coffee beans')\n print(str(resource[3]) + ' of disposable cups')\n if resource[4] == 0:\n print(str(resource[4]) + ' of money')\n else:\n print('$' + str(resource[4]) + ' of money')\n\n\ndef write_action():\n action = str(input('\\n' + 'Write action (buy, fill, take, remaining, exit):' + '\\n'))\n if action == 'exit':\n quit()\n elif action == 'remaining':\n print()\n result(resource)\n write_action()\n elif action == 'take':\n action_take()\n elif action == 'fill':\n action_fill()\n elif action == 'buy':\n action_buy()\n\n\ndef action_take():\n print()\n print('I gave you $' + str(resource[4]))\n resource[4] = 0\n write_action()\n\n\ndef action_fill():\n print()\n resource[0] += int(input('Write how many ml of water do you want to add:' + '\\n'))\n resource[1] += int(input('Write how many ml of milk do you want to add:' + '\\n'))\n resource[2] += int(input('Write how many grams of coffee beans do you want to add:' + '\\n'))\n resource[3] += int(input('Write how many disposable cups of coffee do you want to add:' + '\\n'))\n write_action()\n\n\ndef check_resource(coffee):\n for i in range(len(resource) - 1):\n if resource[i] - coffee[i] < 0:\n print('Sorry, not enough resource!')\n write_action()\n else:\n print('I have enough resources, making you a coffee!')\n resource_calculation(coffee)\n\n\ndef resource_calculation(coffee):\n global resource\n for i in range(len(resource) - 1):\n new_resource[i] = resource[i] - coffee[i]\n new_resource[4] = resource[4] + coffee[4]\n resource = new_resource\n write_action()\n\n\ndef action_buy():\n print()\n coffee = str(input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:' + '\\n'))\n if coffee == 'back':\n write_action()\n elif coffee == '1':\n check_resource(espresso)\n elif coffee == '2':\n check_resource(latte)\n elif coffee == '3':\n check_resource(cappuccino)\n\n\nwrite_action()\n","sub_path":"Coffee Machine/task/machine/coffee_machine.py","file_name":"coffee_machine.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"49730651","text":"# Copyright 2020 Sonatype 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.\nimport json\nfrom fpdf import FPDF\nimport datetime\nimport time\nimport plotly.graph_objects as go\nimport argparse\nimport statistics\n\nparser = argparse.ArgumentParser(description='generate insights report')\nparser.add_argument('-all','--insightsAll', help='generates insights report for all violations', action='store_true', required=False)\nparser.add_argument('-s','--insightsSec', help='generates insights report only for Security violations', action='store_true', required=False)\nparser.add_argument('-l','--insightsLic', help='generates insights report only for Licensing violations', action='store_true', required=False)\nparser.add_argument('-before','--beforeFile', help='enter the path to the earlier json file to compare',dest='jsonBefore', action='store', required=True)\nparser.add_argument('-after','--afterFile', help='enter the path to the later json file to compare',dest='jsonAfter', action='store', required=True)\n\nargs = vars(parser.parse_args())\n\nxtitle = [\"Date\", \"Applications\", \"Organisations\"]\nfilenameBefore = args['jsonBefore']\nfilenameAfter = args['jsonAfter']\nsonatype_colours = ['rgb(0,106,197)','rgb(253,198,22)','rgb(246,128,4)','rgb(205,0,40)']\ndisfixwai_colours = ['rgb(245,69,44)','rgb(0,209,146)','rgb(101,104,255)']\nfrom datetime import date\ntoday = datetime.datetime.today()\ntoday = today.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n\nwith open(filenameBefore, 'r') as f1:\n report1 = json.load(f1)\n summary1 = report1[\"summary\"]\n apps1 = report1[\"apps\"]\n licences1 = report1[\"licences\"]\n Security1 = report1[\"security\"]\n appCount1 = len(apps1)\n\nwith open(filenameAfter, 'r') as f2:\n report2 = json.load(f2)\n summary2 = report2[\"summary\"]\n apps2 = report2[\"apps\"]\n licences2 = report2[\"licences\"]\n Security2 = report2[\"security\"]\n appCount2 = len(apps2)\n\n#print(str(appCount1)+\" , \"+str(appCount2))\n\n# Print iterations progress\ndef printProgressBar (\n iteration, \n total, \n prefix = 'Progress:', \n suffix = 'Complete', \n decimals = 1, \n length = 50, \n fill = '█'):\n\n time.sleep(0.1)\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\n filledLength = int(length * iteration // total)\n bar = fill * filledLength + '-' * (length - filledLength)\n print('\\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\\r')\n # Print New Line on Complete\n if iteration == total: \n print()\n\n#---------------------------------\n# Chart/pdf functions\n\ndef make_chart(period, data, filename, title, xtitle):\n fig = go.Figure(\n data=[ go.Bar(x=period, y=data, textposition='auto') ], \n layout_title_text=title\n )\n\n fig.update_layout(autosize=False, width=864, height=528, xaxis=go.layout.XAxis(title_text=xtitle))\n fig.update_xaxes(tickvals=period,automargin=True)\n\n fig.write_image(filename)\n\ndef make_stacked_chart(period, data, legend, filename, title, xtitle,colours):\n traces = []\n for i in range(0, len(data)):\n trace = go.Bar(\n name = legend[i],\n x = period,\n y = data[i],\n textposition = 'auto',\n marker = dict(color=colours[i])\n )\n traces.append(trace)\n\n fig = go.Figure(data=traces, layout_title_text=title)\n fig.update_layout(\n barmode='stack',\n autosize=False,\n width=840,\n height=528,\n xaxis=go.layout.XAxis(\n title_text=xtitle\n )\n )\n fig.update_xaxes(tickvals=period,automargin=True)\n fig.write_image(filename)\n\ndef make_group_chart(period, data, legend, filename, title, xtitle,colours):\n traces = []\n for i in range(0, len(data)):\n trace = go.Bar(\n name = legend[i],\n x = period,\n y = data[i],\n textposition = 'auto',\n marker = dict(color=colours[i])\n )\n traces.append(trace)\n\n fig = go.Figure(data=traces, layout_title_text=title)\n fig.update_layout(\n barmode='group',\n autosize=False,\n width=840,\n height=528,\n xaxis=go.layout.XAxis(\n title_text=xtitle\n )\n )\n fig.update_xaxes(tickvals=period,automargin=True)\n fig.write_image(filename)\n\n\n\n#---------------------------------\n\nclass PDF(FPDF):\n def header(self):\n # Logo\n self.image('sonatype_logo.png', 10, 8, 33)\n # Times bold 15\n self.set_font('Times', 'B', 15)\n # Move to the right\n self.cell(80)\n # Title\n self.cell(100, 10, 'Success Metrics report', 1, 0, 'C')\n # Line break\n self.ln(20)\n\n # Page footer\n def footer(self):\n # Position at 1.5 cm from bottom\n self.set_y(-15)\n # Arial italic 8\n self.set_font('Times', 'I', 8)\n # Page number\n self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')\n\n #Chapter title\n def chapter_title(self, title):\n # Arial 12\n self.set_font('Times', 'B', 12)\n # Background color\n self.set_fill_color(200, 220, 255)\n # Title\n self.cell(0, 6, '%s' % (title), 0, 1, 'L', 1)\n # Line break\n self.ln(0)\n\n #Chapter body\n def chapter_body(self, content_dict):\n # Times 12\n self.set_font('Times', '', 12)\n # Output justified text\n #self.multi_cell(0, 5, content)\n for field in content_dict:\n self.cell(0, 5, field+\": \"+content_dict[field], 1, 1)\n # Line break\n self.ln()\n\n #Print chapter\n def print_chapter(self, title, content):\n self.add_page('L')\n self.chapter_title(title)\n self.chapter_body(content)\n\n def print_list(self,data):\n self.cell()\n\n def fancy_table(this,header,data):\n #Colors, line width and bold font\n this.set_fill_color(255,0,0)\n this.set_text_color(255)\n this.set_draw_color(128,0,0)\n this.set_line_width(.3)\n this.set_font('Times','B')\n #Header\n w=[]\n column_no = len(header)\n page_width = 277 #magic number for A4 in mm\n column_width = page_width/column_no\n for i in range(0,column_no):\n w.append(column_width)\n for i in range(0,column_no):\n this.cell(w[i],7,header[i],1,0,'C',1)\n this.ln()\n #Color and font restoration\n this.set_fill_color(224,235,255)\n this.set_text_color(0)\n this.set_font('Times')\n #Data\n fill=0\n #print(\"This data: \")\n #print(len(data))\n #print(len(w))\n #print(column_no)\n for row in data:\n for i in range(0,column_no):\n this.cell(w[i],6,row[i],'LR',0,'C',fill)\n #print(row[i])\n this.ln()\n fill=not fill\n this.cell(sum(w),0,'','T')\n\n\n#---------------------------------\n\ndef output_pdf(pages, filename):\n\tpdf = FPDF()\n\tpdf.set_font('Times','B',12)\n\tfor image in pages:\n\t\tpdf.add_page('L')\n\t\tpdf.set_xy(0,0)\n\t\tpdf.image(image, x = None, y = None, w = 0, h = 0, type = '', link = '')\n\tpdf.output(filename, 'F')\n\n\n#---------------------------------\n\ndef nonzeroAvg(metric,percentage,integer):\n nonzero = 0\n aux = 0\n for i in range(0,len(metric)):\n if metric[i] != 0:\n aux += metric[i]\n nonzero += 1\n if nonzero == 0:\n nonzero = 1\n if percentage == True:\n output = round((aux / nonzero) * 100,1)\n elif integer == True:\n output = int(aux / nonzero)\n else:\n output = round(aux / nonzero,1)\n return(output)\n\n#---------------------------------\n\ndef average(numerator,denominator,percentage,integer):\n if denominator == 0:\n denominator = 1\n if percentage == True:\n output = round((numerator / denominator) * 100,1)\n elif integer == True:\n output = int(numerator / denominator)\n else:\n output = round(numerator / denominator,1)\n return(output)\n#---------------------------------\n\ndef weeksWithData(scope):\n aux = 0\n stop = 0\n for week in range(0,len(scope)):\n if scope[week] == 0 and stop == 0:\n aux += 1\n elif scope[week] != 0:\n stop = 1\n output = len(scope) - aux \n return(output)\n\n#---------------------------------\n\ndef getScope(scope1,scope2):\n S1 = set(scope1)\n S2 = set(scope2)\n inter = S1.intersection(S2)\n #print(inter)\n if inter != {}:\n if scope2[-1] >= scope1[-1]:\n index = scope2.index(scope1[-1])\n scope = scope2[index+1:]\n elif scope1[-1] > scope2[-1]:\n print(\"The date ranges for before and after json files are swapped. Please, run the command again but swapping the files for before and after. \\nExiting...\")\n raise SystemExit\n if scope == []:\n print(\"The date ranges for before and after json files are identical. There is no delta to analyse. \\nExiting...\")\n raise SystemExit\n #print(\"scope1: \"+str(scope1))\n #print(\"scope2: \"+str(scope2))\n #print(\"index: \"+str(index))\n #print(\"scope1[-1]: \"+str(scope1[-1]))\n #print(\"length of scope1: \"+str(len(scope1)))\n #print(\"length of scope2: \"+str(len(scope2)))\n #print(\"scope: \"+str(scope))\n else:\n print(\"The date ranges for before and after json files do not intersect. There is a gap in the data. \\nPlease generate new json files extending the date ranges so that both json files intersect. \\nExiting...\")\n raise SystemExit\n return(scope)\n\n#---------------------------------\n\n#INSIGHTS: Insights report (comparison between two different json files)\ndef insights(apps1,apps2,summary1,summary2,report):\n\n pages, t, graphNo = [], 0, 2\n appName, orgName, OpeLow, OpeMod, OpeSev, OpeCri, mttrLow, mttrMod, mttrSev, mttrCri = [],[],[],[],[],[],[],[],[],[]\n printProgressBar(t,graphNo)\n \n pdf = PDF()\n pdf.alias_nb_pages()\n\n if report == 'summary':\n selector = 'TOTAL'\n if report == 'security':\n selector = 'SECURITY'\n if report == 'licences':\n selector = 'LICENSE'\n\n ################################\n #Loading data for json1 (before)\n ################################\n header_Open_App1 = ['Application', 'Critical','Severe','Moderate','Low']\n data_Open_App1= []\n for app in apps1:\n critical1 = app[report]['openCountsAtTimePeriodEnd'][selector]['CRITICAL']['rng'][-1]\n severe1 = app[report]['openCountsAtTimePeriodEnd'][selector]['SEVERE']['rng'][-1]\n moderate1 = app[report]['openCountsAtTimePeriodEnd'][selector]['MODERATE']['rng'][-1]\n low1 = app[report]['openCountsAtTimePeriodEnd'][selector]['LOW']['rng'][-1]\n aux1 = [critical1,severe1,moderate1,low1]\n data_Open_App1.append([app['applicationName']] + aux1)\n data_Open_App1.sort(key = lambda data_Open_App1: data_Open_App1[1], reverse = True)\n aux1=[]\n if len(data_Open_App1) <= 100:\n for i in range(0,len(data_Open_App1)):\n aux1.append([data_Open_App1[i][0],str(data_Open_App1[i][1]),str(data_Open_App1[i][2]),str(data_Open_App1[i][3]),str(data_Open_App1[i][4])])\n else:\n for i in range(0,100):\n aux1.append([data_Open_App1[i][0],str(data_Open_App1[i][1]),str(data_Open_App1[i][2]),str(data_Open_App1[i][3]),str(data_Open_App1[i][4])])\n data_Open_App1 = aux1\n ###########################\n\n ################################\n #Loading data for json2 (after)\n ################################\n header_Open_App2 = ['Application', 'Critical','Severe','Moderate','Low']\n data_Open_App2= []\n for app in apps2:\n critical2 = app[report]['openCountsAtTimePeriodEnd'][selector]['CRITICAL']['rng'][-1]\n severe2 = app[report]['openCountsAtTimePeriodEnd'][selector]['SEVERE']['rng'][-1]\n moderate2 = app[report]['openCountsAtTimePeriodEnd'][selector]['MODERATE']['rng'][-1]\n low2 = app[report]['openCountsAtTimePeriodEnd'][selector]['LOW']['rng'][-1]\n aux2 = [critical2,severe2,moderate2,low2]\n data_Open_App2.append([app['applicationName']] + aux2)\n data_Open_App2.sort(key = lambda data_Open_App2: data_Open_App2[1], reverse = True)\n aux2=[]\n if len(data_Open_App2) <= 100:\n for i in range(0,len(data_Open_App2)):\n aux2.append([data_Open_App2[i][0],str(data_Open_App2[i][1]),str(data_Open_App2[i][2]),str(data_Open_App2[i][3]),str(data_Open_App2[i][4])])\n else:\n for i in range(0,100):\n aux2.append([data_Open_App2[i][0],str(data_Open_App2[i][1]),str(data_Open_App2[i][2]),str(data_Open_App2[i][3]),str(data_Open_App2[i][4])])\n data_Open_App2 = aux2\n ###########################\n\n scope = getScope(summary1[\"dates\"],summary2[\"dates\"]) \n weeks = len(scope)\n weeks1 = weeksWithData(summary1[\"weeks\"])\n weeks2 = weeksWithData(summary2[\"weeks\"])\n\n onboarded = summary2[\"appOnboard\"][-1] - summary1[\"appOnboard\"][-1]\n onboarded1 = summary1[\"appOnboard\"][-1]\n onboarded2 = summary2[\"appOnboard\"][-1]\n weeklyOnboard = average(onboarded,weeks,0,0)\n weeklyOnboard1 = average(onboarded1,weeks1,0,0)\n weeklyOnboard2 = average(onboarded2,weeks2,0,0)\n\n scanned1 = sum(summary1[\"appNumberScan\"])\n scanned2 = sum(summary2[\"appNumberScan\"])\n scanned = summary2[\"appNumberScan\"][-weeks:]\n #print(\"scanned: \"+str(scanned))\n weeklyScanned = average(sum(scanned),weeks,0,0)\n weeklyScanned1 = average(scanned1,weeks1,0,0)\n\n scans = sum(summary2[\"weeklyScans\"]) - sum(summary1[\"weeklyScans\"])\n scans1 = sum(summary1[\"weeklyScans\"])\n scans2 = sum(summary2[\"weeklyScans\"])\n if scans < 0:\n scans = scans2\n weeklyScans = average(scans,weeks,0,0)\n weeklyScans1 = average(scans1,weeks1,0,0)\n weeklyScans2 = average(scans2,weeks2,0,0)\n\n discovered = sum(summary2[\"discoveredCounts\"][\"TOTAL\"]) - sum(summary1[\"discoveredCounts\"][\"TOTAL\"])\n discovered1 = sum(summary1[\"discoveredCounts\"][\"TOTAL\"])\n discovered2 = sum(summary2[\"discoveredCounts\"][\"TOTAL\"])\n if discovered < 0:\n discovered = discovered2\n weeklyDiscovered = average(discovered,weeks,0,0)\n weeklyDiscovered1 = average(discovered1,weeks1,0,0)\n weeklyDiscovered2 = average(discovered2,weeks2,0,0)\n \n disCri = sum(summary2[\"discoveredCounts\"][\"CRITICAL\"]) - sum(summary1[\"discoveredCounts\"][\"CRITICAL\"])\n disCri1 = sum(summary1[\"discoveredCounts\"][\"CRITICAL\"])\n disCri2 = sum(summary2[\"discoveredCounts\"][\"CRITICAL\"])\n\n if disCri < 0:\n disCri = disCri2\n weeklyDisCri = average(disCri,weeks,0,0)\n weeklyDisCri1 = average(disCri1,weeks1,0,0)\n weeklyDisCri2 = average(disCri2,weeks2,0,0)\n\n \n if len(data_Open_App1) > 0:\n mostCri = data_Open_App2[0][0]\n mostCriVal = data_Open_App2[0][1]\n else:\n mostCri = \"Error: No applications found!\"\n mostCriVal = 0\n if len(data_Open_App2) > 0:\n leastCri = data_Open_App2[-1][0]\n leastCriVal = data_Open_App2[-1][1]\n else:\n leastCri = \"Error: No applications found!\"\n leastCriVal = 0\n\n fixed = sum(summary2[\"fixedCounts\"][\"TOTAL\"]) - sum(summary1[\"fixedCounts\"][\"TOTAL\"])\n fixed1 = sum(summary1[\"fixedCounts\"][\"TOTAL\"])\n fixed2 = sum(summary2[\"fixedCounts\"][\"TOTAL\"])\n if fixed < 0:\n fixed = fixed2\n weeklyFixed = average(fixed,weeks,0,0)\n weeklyFixed1 = average(fixed1,weeks1,0,0)\n weeklyFixed2 = average(fixed2,weeks2,0,0)\n \n fixedCri = sum(summary2[\"fixedCounts\"][\"CRITICAL\"]) - sum(summary1[\"fixedCounts\"][\"CRITICAL\"])\n fixedCri1 = sum(summary1[\"fixedCounts\"][\"CRITICAL\"])\n fixedCri2 = sum(summary2[\"fixedCounts\"][\"CRITICAL\"])\n\n if fixedCri < 0:\n fixedCri = fixedCri2\n weeklyFixedCri = average(fixedCri,weeks,0,0)\n weeklyFixedCri1 = average(fixedCri1,weeks1,0,0)\n weeklyFixedCri2 = average(fixedCri2,weeks2,0,0)\n\n\n waived = sum(summary2[\"waivedCounts\"][\"TOTAL\"]) - sum(summary1[\"waivedCounts\"][\"TOTAL\"])\n waived1 = sum(summary1[\"waivedCounts\"][\"TOTAL\"])\n waived2 = sum(summary2[\"waivedCounts\"][\"TOTAL\"])\n if waived < 0:\n waived = waived2\n weeklyWaived = average(waived,weeks,0,0)\n weeklyWaived1 = average(waived1,weeks1,0,0)\n weeklyWaived2 = average(waived2,weeks2,0,0)\n waivedCri = sum(summary2[\"waivedCounts\"][\"CRITICAL\"]) - sum(summary1[\"waivedCounts\"][\"CRITICAL\"])\n waivedCri1 = sum(summary1[\"waivedCounts\"][\"CRITICAL\"])\n waivedCri2 = sum(summary2[\"waivedCounts\"][\"CRITICAL\"])\n\n if waivedCri < 0:\n waivedCri = waivedCri2\n weeklyWaivedCri = average(waivedCri,weeks,0,0)\n weeklyWaivedCri1 = average(waivedCri1,weeks1,0,0)\n weeklyWaivedCri2 = average(waivedCri2,weeks2,0,0)\n\n\n opened1 = summary1[\"openCountsAtTimePeriodEnd\"][\"TOTAL\"][-1]\n opened2 = summary2[\"openCountsAtTimePeriodEnd\"][\"TOTAL\"][-1]\n openedCri1 = summary1[\"openCountsAtTimePeriodEnd\"][\"CRITICAL\"][-1]\n openedCri2 = summary2[\"openCountsAtTimePeriodEnd\"][\"CRITICAL\"][-1]\n \n dealt = fixed + waived\n if discovered > 0:\n dealtRate = round((dealt / discovered) * 100,1)\n else:\n dealtRate = 0\n dealt1 = fixed1 + waived1\n if discovered1 > 0:\n dealtRate1 = round((dealt1 / discovered1) * 100,1)\n else:\n dealtRate1 = 0\n \n riskRatio = [float(i) for i in summary2[\"riskRatioCritical\"]]\n riskRatio = riskRatio[-weeks:]\n riskRatioAvg = average(sum(riskRatio),weeks,0,0)\n riskRatio1 = [float(i) for i in summary1[\"riskRatioCritical\"]]\n riskRatioAvg1 = average(sum(riskRatio1),weeks1,0,0)\n\n sigma = round(statistics.stdev(riskRatio),1)\n sigma1 = round(statistics.stdev(riskRatio1),1)\n \n mttr = summary2[\"mttrCriticalThreat\"][-weeks:]\n mttrAvg = nonzeroAvg(mttr,0,0)\n mttr1 = summary1[\"mttrCriticalThreat\"]\n mttrAvg1 = nonzeroAvg(mttr1,0,0)\n\n\n if report == 'summary':\n pdf.print_chapter('Insights Summary (all violations)',\"\")\n elif report == 'security':\n pdf.print_chapter('Insights Summary (only security violations)',\"\")\n elif report =='licences':\n pdf.print_chapter('Insights Summary (only licensing violations)',\"\")\n \n content0 = \"Report run on: \"+str(today)+\" comparing \"+str(filenameBefore)+\" with \"+str(filenameAfter)+\" from w/c \"+str(scope[0])+\" to w/c \"+str(scope[-1])\n pdf.multi_cell(0,5,content0,0)\n pdf.ln(10)\n \n content1 = \"During the \"+str(weeks)+\" weeks in scope, your organisation:\"\n pdf.set_font('Times', 'B', 24)\n pdf.cell(0,0,content1,0)\n pdf.ln(10)\n pdf.set_font('Times', 'B', 18)\n \n content2 = \"Onboarded \"+str(onboarded)+\" applications (going from \"+str(onboarded1)+\" to \"+str(onboarded2)+\" apps), at an average of \"+str(weeklyOnboard)+\" per week (previously \"+str(weeklyOnboard1)+\" apps onboarded per week).\"\n pdf.multi_cell(0,7,content2,0)\n pdf.ln(1)\n if weeklyOnboard > weeklyOnboard1:\n content21 = \"This represents a \"+str(round(average(weeklyOnboard,weeklyOnboard1,1,0) - 100,1))+\"% increase in the onboarding rate.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content21,0)\n elif weeklyOnboard < weeklyOnboard1:\n content21 = \"This represents a \"+str(round(100 - average(weeklyOnboard,weeklyOnboard1,1,0),1))+\"% reduction in the onboarding rate. Have all apps been onboarded yet?\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content21,0)\n elif onboarded1 == onboarded2:\n content21 = \"No new applications have been onboarded during this time period. Have all apps been onboarded yet?\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content21,0)\n else:\n content21 = \"This represents a stable onboarding pattern.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content21,0)\n pdf.ln(10)\n pdf.set_text_color(0, 0, 0)\n\n content3 = \"Scanned applications at an average of \"+str(weeklyScanned)+\" apps scanned per week (previously \"+str(weeklyScanned1)+\" apps scanned per week). Scanning coverage is \"+str(round(average(weeklyScanned,onboarded2,1,0),1))+\"% (percentage of total apps scanned).\"\n pdf.multi_cell(0,7,content3,0)\n pdf.ln(1)\n if weeklyScanned > weeklyScanned1:\n content31 = \"This represents a \"+str(round(average(weeklyScanned,weeklyScanned1,1,0) - 100,1))+\"% increase in the scanning coverage rate.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content31,0)\n elif weeklyScanned < weeklyScanned1:\n content31 = \"This represents a \"+str(round(100 - average(weeklyScanned,weeklyScanned1,1,0),1))+\"% reduction in the scanning coverage rate.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content31,0)\n elif scanned == 0:\n content31 = \"No applications have been scanned during this time period. Is there a problem with the CI integration or with the uptake of IQ within the development teams?\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content31,0)\n else:\n content31 = \"This represents a stable app scanning pattern.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content31,0)\n pdf.ln(10)\n pdf.set_text_color(0, 0, 0)\n \n content4 = \"Performed \"+str(scans)+\" scans (previously \"+str(scans1)+\" scans) at an average of \"+str(weeklyScans)+\" scans per week (previously \"+str(weeklyScans1)+\" scans per week).\"\n pdf.multi_cell(0,7,content4,0)\n pdf.ln(1)\n if weeklyScans > weeklyScans1:\n content41 = \"This represents a \"+str(round(average(weeklyScans,weeklyScans1,1,0) - 100,1))+\"% increase in the scanning rate.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content41,0)\n elif weeklyScans < weeklyScans1:\n content41 = \"This represents a \"+str(round(100 - average(weeklyScans,weeklyScans1,1,0),1))+\"% reduction in the scanning rate.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content41,0)\n elif scans == 0:\n content41 = \"No scans have been performed during this time period. Is there a problem with the CI integration or with the uptake of IQ within the development teams?\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content41,0)\n else:\n content41 = \"This represents a stable scanning pattern.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content41,0)\n pdf.ln(10)\n pdf.set_text_color(0, 0, 0)\n\n\n content5 = \"Discovered \"+str(discovered)+\" new violations at an average of \"+str(weeklyDiscovered)+\" discovered per week (previously \"+str(weeklyDiscovered1)+\" discovered per week). \\nOf these, \"+str(disCri)+\" were Critical at an average of \"+str(weeklyDisCri)+\" discovered Criticals per week (previously \"+str(weeklyDisCri1)+\" discovered Criticals per week).\"\n\n pdf.multi_cell(0,7,content5,0)\n pdf.ln(1)\n if weeklyDiscovered > weeklyDiscovered1:\n content51 = \"This represents a \"+str(round(average(weeklyDiscovered,weeklyDiscovered1,1,0) - 100,1))+\"% increase in the discovery rate. This could indicate that development teams are not selecting safer OSS components. Have you integrated the IDE plugins and Chrome extension?\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content51,0)\n elif weeklyDiscovered < weeklyDiscovered1:\n content51 = \"This represents a \"+str(round(100 - average(weeklyDiscovered,weeklyDiscovered1,1,0),1))+\"% reduction in the discovery rate. This could indicate that development teams are selecting safer OSS components, hence shifting left.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content51,0)\n elif discovered == 0 and scans != 0:\n content51 = \"No new discovered violations during this time period. This could indicate that development teams are selecting safer OSS components, hence shifting left.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content51,0)\n else:\n content51 = \"This represents a stable discovery rate.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content51,0)\n pdf.ln(1)\n pdf.set_text_color(0, 0, 0)\n if (weeklyDisCri > weeklyDisCri1) and (weeklyDiscovered >= weeklyDiscovered1):\n content52 = \"This also represents a \"+str(round(average(weeklyDisCri,weeklyDisCri1,1,0) - 100,1))+\"% increase in the discovery rate for Critical violations.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content52,0)\n elif (weeklyDisCri > weeklyDisCri1) and (weeklyDiscovered < weeklyDiscovered1):\n content52 = \"However, there is a \"+str(round(average(weeklyDisCri,weeklyDisCri1,1,0) - 100,1))+\"% increase in the discovery rate for Critical violations.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content52,0)\n elif (weeklyDisCri < weeklyDisCri1) and (weeklyDiscovered >= weeklyDiscovered1):\n content52 = \"However, there is a \"+str(round(100 - average(weeklyDisCri,weeklyDisCri1,1,0),1))+\"% reduction in the discovery rate for Critical violations.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content52,0)\n\n elif (weeklyDisCri < weeklyDisCri1) and (weeklyDiscovered < weeklyDiscovered1):\n content52 = \"This also represents a \"+str(round(100 - average(weeklyDisCri,weeklyDisCri1,1,0),1))+\"% reduction in the discovery rate for Critical violations.\"\n\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content52,0) \n else:\n content52 = \"This represents a stable discovery rate for Critical violations.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content52,0)\n pdf.ln(10)\n pdf.set_text_color(0, 0, 0)\n\n\n content6 = \"Fixed \"+str(fixed)+\" violations from your open backlog at an average of \"+str(weeklyFixed)+\" fixed per week (previously \"+str(weeklyFixed1)+\" fixed per week). \\nOf these, \"+str(fixedCri)+\" were Critical at an average of \"+str(weeklyFixedCri)+\" fixed Criticals per week (previously \"+str(weeklyFixedCri1)+\" fixed Criticals per week).\"\n\n pdf.multi_cell(0,7,content6,0)\n pdf.ln(1)\n if weeklyFixed > weeklyFixed1:\n content61 = \"This represents a \"+str(round(average(weeklyFixed,weeklyFixed1,1,0) - 100,1))+\"% increase in the fixing rate.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content61,0)\n elif weeklyFixed < weeklyFixed1:\n content61 = \"This represents a \"+str(round(100 - average(weeklyFixed,weeklyFixed1,1,0),1))+\"% reduction in the fixing rate.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content61,0)\n else:\n content61 = \"This represents a stable fixing rate.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content61,0)\n pdf.ln(1)\n pdf.set_text_color(0, 0, 0)\n if (weeklyFixedCri > weeklyFixedCri1) and (weeklyFixed >= weeklyFixed1):\n content62 = \"This also represents a \"+str(round(average(weeklyFixedCri,weeklyFixedCri1,1,0) - 100,1))+\"% increase in the fixing rate for Critical violations.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content62,0)\n elif (weeklyFixedCri > weeklyFixedCri1) and (weeklyFixed < weeklyFixed1):\n content62 = \"However, there is a \"+str(round(average(weeklyFixedCri,weeklyFixedCri1,1,0) - 100,1))+\"% increase in the fixing rate for Critical violations.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content62,0)\n elif (weeklyFixedCri < weeklyFixedCri1) and (weeklyFixed >= weeklyFixed1):\n content62 = \"However, there is a \"+str(round(100 - average(weeklyFixedCri,weeklyFixedCri1,1,0),1))+\"% reduction in the fixing rate for Critical violations.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content62,0)\n\n elif (weeklyFixedCri < weeklyFixedCri1) and (weeklyFixed < weeklyFixed1):\n content62 = \"This also represents a \"+str(round(100 - average(weeklyFixedCri,weeklyFixedCri1,1,0),1))+\"% reduction in the fixing rate for Critical violations.\"\n\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content62,0) \n else:\n content62 = \"This represents a stable fixing rate for Critical violations.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content62,0)\n pdf.ln(10)\n pdf.set_text_color(0, 0, 0)\n\n content7 = \"Waived \"+str(waived)+\" violations at an average of \"+str(weeklyWaived)+\" waived per week (previously \"+str(weeklyWaived1)+\" waived per week).\\nOf these, \"+str(waivedCri)+\" were Critical at an average of \"+str(weeklyWaivedCri)+\" waived Criticals per week (previously \"+str(weeklyWaivedCri1)+\" waived Criticals per week).\"\n pdf.multi_cell(0,7,content7,0)\n pdf.ln(1)\n if weeklyWaived > weeklyWaived1:\n content71 = \"This represents a \"+str(round(average(weeklyWaived,weeklyWaived1,1,0) - 100,1))+\"% increase in the waiving rate.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content71,0)\n elif weeklyWaived < weeklyWaived1:\n content71 = \"This represents a \"+str(round(100 - average(weeklyWaived,weeklyWaived1,1,0),1))+\"% reduction in the waiving rate.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content71,0)\n elif waived == 0:\n content71 = \"This means that waivers are not being used.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content71,0)\n else:\n content71 = \"This represents a stable waiving rate.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content71,0)\n pdf.ln(1)\n pdf.set_text_color(0, 0, 0)\n if (weeklyWaivedCri > weeklyWaivedCri1) and (weeklyWaived >= weeklyWaived1):\n content72 = \"This also represents a \"+str(round(average(weeklyWaivedCri,weeklyWaivedCri1,1,0) - 100,1))+\"% increase in the waiving rate for Critical violations.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content72,0)\n elif (weeklyWaivedCri > weeklyWaivedCri1) and (weeklyWaived < weeklyWaived1):\n content72 = \"However, there is a \"+str(round(average(weeklyWaivedCri,weeklyWaivedCri1,1,0) - 100,1))+\"% increase in the waiving rate for Critical violations.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content72,0)\n elif (weeklyWaivedCri < weeklyWaivedCri1) and (weeklyWaived >= weeklyWaived1):\n content72 = \"However, there is a \"+str(round(100 - average(weeklyWaivedCri,weeklyWaivedCri1,1,0),1))+\"% reduction in the waiving rate for Critical violations.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content72,0)\n\n elif (weeklyWaivedCri < weeklyWaivedCri1) and (weeklyWaived < weeklyWaived1):\n content72 = \"This also represents a \"+str(round(100 - average(weeklyWaivedCri,weeklyWaivedCri1,1,0),1))+\"% reduction in the waiving rate for Critical violations.\"\n\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content72,0) \n elif waivedCri == 0:\n content72 = \"This means that waivers are not used for Critical violations.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content72,0)\n else:\n content72 = \"This represents a stable waiving rate for Critical violations.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content72,0)\n pdf.ln(10)\n pdf.set_text_color(0, 0, 0)\n \n content8 = \"Your organisation currently has \"+str(opened2)+\" open violations in their backlog (previously \"+str(opened1)+\" violations). Of these, \"+str(openedCri2)+\" were Critical (previously \"+str(openedCri1)+\" were Critical).\"\n pdf.multi_cell(0,7,content8,0)\n pdf.ln(1)\n if opened2 > opened1:\n content81 = \"This represents a \"+str(round(average(opened2,opened1,1,0) - 100,1))+\"% increase in violations in the backlog.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content81,0)\n elif opened2 < opened1:\n content81 = \"This represents a \"+str(round(100 - average(opened2,opened1,1,0),1))+\"% reduction in violations in the backlog.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content81,0)\n else:\n content81 = \"There were the same number of violations in the open backlog at the beginning and at the end of the period in scope.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content81,0)\n pdf.ln(1)\n pdf.set_text_color(0, 0, 0)\n if (openedCri2 > openedCri1) and (opened2 >= opened1):\n content82 = \"This also represents a \"+str(round(average(openedCri2,openedCri1,1,0) - 100,1))+\"% increase in Critical violations in the backlog.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content82,0)\n elif (openedCri2 > openedCri1) and (opened2 < opened1):\n content82 = \"However, there is a \"+str(round(average(openedCri2,openedCri1,1,0) - 100,1))+\"% increase in Critical violations in the backlog.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content82,0)\n elif (openedCri2 < openedCri1) and (opened2 >= opened1):\n content82 = \"However, there is a \"+str(round(100 - average(openedCri2,openedCri1,1,0),1))+\"% reduction in Critical violations in the backlog.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content82,0)\n elif (openedCri2 < openedCri1) and (opened2 < opened1):\n content82 = \"This also represents a \"+str(round(100 - average(openedCri2,openedCri1,1,0),1))+\"% reduction in Critical violations in the backlog.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content82,0) \n else:\n content82 = \"There were the same number of Critical violations in the open backlog at the beginning and at the end of the period in scope.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content82,0)\n pdf.ln(10)\n pdf.set_text_color(0, 0, 0)\n \n content9 = \"Your organisation currently has a Backlog Dealing rate ((Fixed + Waived) / Discovered) of \"+str(dealtRate)+\"% (previously it was \"+str(dealtRate1)+\"%).\"\n pdf.multi_cell(0,7,content9,0)\n pdf.ln(1)\n if dealtRate > dealtRate1:\n content91 = \"This represents a \"+str(round(average(dealtRate,dealtRate1,1,0) - 100,1))+\"% increase in the Backlog Dealing rate, which means that the backlog is reducing.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content91,0)\n elif dealtRate < dealtRate1:\n content91 = \"This represents a \"+str(round(100 - average(dealtRate,dealtRate1,1,0),1))+\"% reduction in the Backlog Dealing rate, which means that the backlog is increasing.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content91,0)\n else:\n content91 = \"The Backlog Dealing rate was the same at the beginning and at the end of the period in scope.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content91,0)\n pdf.ln(10)\n pdf.set_text_color(0, 0, 0)\n \n content10 = \"On average, each application had \"+str(round(riskRatioAvg,1))+\" open Critical violations (previously \"+str(round(riskRatioAvg1,1))+\" open Critical violations).\"\n pdf.multi_cell(0,7,content10,0)\n pdf.ln(1)\n if riskRatioAvg > riskRatioAvg1:\n content101 = \"This represents a \"+str(round(average(riskRatioAvg,riskRatioAvg1,1,0) - 100,1))+\"% increase in the risk ratio.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content101,0)\n elif riskRatioAvg < riskRatioAvg1:\n content101 = \"This represents a \"+str(round(100 - average(riskRatioAvg,riskRatioAvg1,1,0),1))+\"% reduction in the risk ratio.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content101,0)\n else:\n content101 = \"The risk ratio was the same at the beginning and at the end of the period in scope.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content101,0)\n pdf.ln(10)\n pdf.set_text_color(0, 0, 0)\n\n content11 = \"The standard deviation was \"+str(sigma)+\" open Critical violations (previously \"+str(sigma1)+\" open Critical violations).\"\n pdf.multi_cell(0,7,content11,0)\n pdf.ln(1)\n if sigma > sigma1:\n content111 = \"This represents a \"+str(round(average(sigma,sigma1,1,0) - 100,1))+\"% increase in the spread of Critical violations.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content111,0)\n elif sigma < sigma1:\n content111 = \"This represents a \"+str(round(100 - average(sigma,sigma1,1,0),1))+\"% reduction in the spread of Critical violations.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content111,0)\n else:\n content111 = \"The standard deviation was the same at the beginning and at the end of the period in scope.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content111,0)\n pdf.ln(10)\n pdf.set_text_color(0, 0, 0)\n\n #-------------------------------------------------------------------------\n ################################\n #Loading data for json2 (after)\n ################################\n header_Open_App = ['Application', 'Critical','Severe','Moderate','Low']\n data_Open_App= []\n for app in apps2:\n critical2 = app[report]['openCountsAtTimePeriodEnd'][selector]['CRITICAL']['rng'][-1]\n severe2 = app[report]['openCountsAtTimePeriodEnd'][selector]['SEVERE']['rng'][-1]\n moderate2 = app[report]['openCountsAtTimePeriodEnd'][selector]['MODERATE']['rng'][-1]\n low2 = app[report]['openCountsAtTimePeriodEnd'][selector]['LOW']['rng'][-1]\n aux2 = [critical2,severe2,moderate2,low2]\n data_Open_App.append([app['applicationName']] + aux2)\n data_Open_App.sort(key = lambda data_Open_App: data_Open_App[1], reverse = True)\n aux2=[]\n if len(data_Open_App) <= 100:\n for i in range(0,len(data_Open_App)):\n aux2.append([data_Open_App[i][0],str(data_Open_App[i][1]),str(data_Open_App[i][2]),str(data_Open_App[i][3]),str(data_Open_App[i][4])])\n else:\n for i in range(0,100):\n aux2.append([data_Open_App[i][0],str(data_Open_App[i][1]),str(data_Open_App[i][2]),str(data_Open_App[i][3]),str(data_Open_App[i][4])])\n \n for app in range(0,len(aux2)):\n if float(aux2[app][1]) >= riskRatioAvg+sigma:\n low_index = app\n data_Open_App = aux2[:low_index+1]\n\n if low_index > 0: \n content12 = \"Based on the current average and standard deviation, below is a table with the applications to be prioritised for remediation (all apps with more than \"+str(round(riskRatioAvg+sigma,1))+\" open Critical violations):\"\n pdf.multi_cell(0,7,content12,0)\n pdf.ln(5)\n\n pdf.fancy_table(header_Open_App, data_Open_App)\n pdf.ln(15)\n t +=1\n printProgressBar(t,graphNo)\n\n #---------------------------------------------------------------------\n\n pdf.set_font('Times', 'B', 18)\n content13 = \"It took an average of \"+str(mttrAvg)+\" days to fix Critical violations (previously \"+str(mttrAvg1)+\" days to fix Critical violations).\"\n\n pdf.cell(0,0,content13,0)\n pdf.ln(5)\n if mttrAvg > mttrAvg1:\n content131 = \"This represents a \"+str(round(average(mttrAvg,mttrAvg1,1,0) - 100,1))+\"% increase in the MTTR for Critical violations.\"\n pdf.set_text_color(255, 0, 0)\n pdf.multi_cell(0,7,content131,0)\n elif mttrAvg < mttrAvg1:\n content131 = \"This represents a \"+str(round(100 - average(mttrAvg,mttrAvg1,1,0),1))+\"% reduction in the MTTR for Critical violations.\"\n pdf.set_text_color(0, 153, 0)\n pdf.multi_cell(0,7,content131,0)\n else:\n content131 = \"The MTTR for Critical violations was the same at the beginning and at the end of the period in scope.\"\n pdf.set_text_color(0, 0, 255)\n pdf.multi_cell(0,7,content131,0)\n pdf.ln(10)\n pdf.set_text_color(0, 0, 0)\n\n\n t +=1\n printProgressBar(t,graphNo)\n\n ###########################\n\n \n #-------------------------------------------------------------------------\n return pdf\n\n\n#-------------------------------------------------------------------------\ndef insightsAll():\n pdf = insights(apps1,apps2,summary1,summary2,'summary')\n pdf.output('./output/insights_report_all.pdf', 'F')\n\n\n#-------------------------------------------------------------------------\ndef insightsSec():\n pdf = insights(apps1,apps2,Security1,Security2,'security')\n pdf.output('./output/insights_report_security.pdf', 'F')\n #print(\"Report not yet implemented\")\n#-------------------------------------------------------------------------\ndef insightsLic():\n pdf = insights(apps1,apps2,licences1,licences2,'licences')\n pdf.output('./output/insights_report_licences.pdf', 'F')\n #print(\"Report not yet implemented\")\n#-------------------------------------------------------------------------\n#-------------------------------------------------------------------------\n\n\ndef main():\n \n for report in args:\n if args[report] == True:\n exec(report+\"()\")\n \n\nif __name__ == \"__main__\":\n main()\n#raise SystemExit\n\n","sub_path":"insights.py","file_name":"insights.py","file_ext":"py","file_size_in_byte":41425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"645025453","text":"# Created byMartin.cz\n# Copyright (c) Martin Strohalm. All rights reserved.\n\nimport weakref\n\n\nclass Proxy(object):\n \"\"\"\n This class encapsulates given callback function to enable weak references\n to instance methods as well as functions.\n \"\"\"\n \n \n def __init__(self, callback):\n \"\"\"\n Initializes a new instance of Proxy.\n \n Args:\n callback: callable\n Callback function or method to be encapsulated.\n \"\"\"\n \n # instance methods\n if hasattr(callback, '__self__'):\n self.obj = weakref.ref(callback.__self__)\n self.func = weakref.ref(callback.__func__)\n \n # direct function\n else:\n self.obj = None\n self.func = weakref.ref(callback)\n \n \n def __repr__(self):\n \"\"\"Gets debug string representation.\"\"\"\n \n return \"Proxy(%s)\" % self.callback\n \n \n def __call__(self, *args, **kwargs):\n \"\"\"Calls defined callback.\"\"\"\n \n self.callback(*args, **kwargs)\n \n \n def __eq__(self, other):\n \"\"\"Compares two proxies for equality.\"\"\"\n \n if not isinstance(other, Proxy):\n other = Proxy(other)\n \n if self.obj is other.obj:\n return self.func is other.func\n \n if self.obj is None or other.obj is None:\n return False\n \n return self.obj() is other.obj() and self.func() is other.func()\n \n \n def __ne__(self, other):\n \"\"\"Compares two proxies for non-equality.\"\"\"\n \n return not self.__eq__(other)\n \n \n @property\n def callback(self):\n \"\"\"Gets the callback.\"\"\"\n \n # direct function\n if self.obj is None:\n return self.func()\n \n # instance method\n obj = self.obj()\n if obj is not None:\n return getattr(obj, self.func().__name__)\n","sub_path":"pero/events/proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"101593518","text":"#\n# LSST Data Management System\n# Copyright 2014 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\"\"\"\nTests for lsst.afw.geom.XYTransform and xyTransformRegistry\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\nimport math\nimport unittest\n\nfrom builtins import range\nfrom builtins import object\n\nimport lsst.utils.tests\nimport lsst.pex.exceptions\nfrom lsst.afw.geom import Extent2D, Point2D, xyTransformRegistry, OneXYTransformConfig, \\\n IdentityXYTransform, AffineXYTransform, RadialXYTransform\n\n\nclass RefMultiAffineTransform(object):\n\n def __init__(self, affineTransformList):\n self.affineTransformList = affineTransformList\n\n def __call__(self, point):\n for tr in self.affineTransformList:\n point = tr(point)\n return point\n\n\nclass RefMultiXYTransform(object):\n\n def __init__(self, transformList):\n self.transformList = transformList\n\n def forwardTransform(self, point):\n for tr in self.transformList:\n point = tr.forwardTransform(point)\n return point\n\n def reverseTransform(self, point):\n for tr in reversed(self.transformList):\n point = tr.reverseTransform(point)\n return point\n\n def linearizeForwardTransform(self, point):\n affineTransformList = [tr.linearizeForwardTransform(point) for\n tr in self.transformList]\n return RefMultiAffineTransform(affineTransformList)\n\n def linearizeReverseTransform(self, point):\n affineTransformList = [tr.linearizeReverseTransform(point) for\n tr in reversed(self.transformList)]\n return RefMultiAffineTransform(affineTransformList)\n\n\nclass XYTransformTestCase(unittest.TestCase):\n\n def fromIter(self):\n for x in (-1.1, 0, 2.2):\n for y in (3.1, 0, 2.1):\n yield Point2D(x, y)\n\n def checkBasics(self, transform):\n \"\"\"Check round trip and linearization of transform\n \"\"\"\n for fromPoint in self.fromIter():\n toPoint = transform.forwardTransform(fromPoint)\n roundTripPoint = transform.reverseTransform(toPoint)\n for i in range(2):\n self.assertAlmostEqual(fromPoint[i], roundTripPoint[i])\n\n for deltaFrom in (\n Extent2D(0),\n Extent2D(0.1, -0.1),\n Extent2D(-0.15, 0.1),\n ):\n tweakedFromPoint = fromPoint + deltaFrom\n tweakedToPoint = transform.forwardTransform(tweakedFromPoint)\n linToPoint = transform.linearizeForwardTransform(\n fromPoint)(tweakedFromPoint)\n linRoundTripPoint = transform.linearizeReverseTransform(\n toPoint)(tweakedToPoint)\n for i in range(2):\n self.assertAlmostEqual(\n tweakedToPoint[i], linToPoint[i], places=2)\n self.assertAlmostEqual(\n tweakedFromPoint[i], linRoundTripPoint[i], places=2)\n\n def checkConfig(self, tClass, tConfig, filePath):\n \"\"\"Check round trip of config\n \"\"\"\n tConfig.save(filePath)\n loadConfig = tConfig.__class__()\n loadConfig.load(filePath)\n transform = tClass(loadConfig)\n self.checkBasics(transform)\n\n def testIdentity(self):\n \"\"\"Test identity = IdentityXYTransform\n \"\"\"\n identClass = xyTransformRegistry[\"identity\"]\n with lsst.utils.tests.getTempFilePath(\".py\") as filePath:\n self.checkConfig(identClass, identClass.ConfigClass(), filePath)\n ident = identClass(identClass.ConfigClass())\n self.assertEqual(type(ident), IdentityXYTransform)\n self.checkBasics(ident)\n for fromPoint in self.fromIter():\n toPoint = ident.forwardTransform(fromPoint)\n for i in range(2):\n self.assertAlmostEqual(fromPoint[i], toPoint[i])\n\n def testInverted(self):\n \"\"\"Test inverted = InvertedXYTransform\n \"\"\"\n invertedClass = xyTransformRegistry[\"inverted\"]\n invertedConfig = invertedClass.ConfigClass()\n affineClass = xyTransformRegistry[\"affine\"]\n invertedConfig.transform.retarget(affineClass)\n affineConfig = invertedConfig.transform\n affineConfig.translation = (1.2, -3.4)\n with lsst.utils.tests.getTempFilePath(\".py\") as filePath:\n self.checkConfig(invertedClass, invertedConfig, filePath)\n inverted = invertedClass(invertedConfig)\n self.checkBasics(inverted)\n for fromPoint in self.fromIter():\n toPoint = inverted.forwardTransform(fromPoint)\n predToPoint = fromPoint - \\\n Extent2D(*invertedConfig.transform.translation)\n for i in range(2):\n self.assertAlmostEqual(toPoint[i], predToPoint[i])\n\n def testDefaultAffine(self):\n \"\"\"Test affine = AffineXYTransform with default coeffs (identity transform)\n \"\"\"\n affineClass = xyTransformRegistry[\"affine\"]\n affineConfig = affineClass.ConfigClass()\n with lsst.utils.tests.getTempFilePath(\".py\") as filePath:\n self.checkConfig(affineClass, affineConfig, filePath)\n affine = affineClass(affineConfig)\n self.assertEqual(type(affine), AffineXYTransform)\n self.checkBasics(affine)\n for fromPoint in self.fromIter():\n toPoint = affine.forwardTransform(fromPoint)\n for i in range(2):\n self.assertAlmostEqual(fromPoint[i], toPoint[i])\n\n def testTranslateAffine(self):\n \"\"\"Test affine = AffineXYTransform with just translation coefficients\n \"\"\"\n affineClass = xyTransformRegistry[\"affine\"]\n affineConfig = affineClass.ConfigClass()\n affineConfig.translation = (1.2, -3.4)\n with lsst.utils.tests.getTempFilePath(\".py\") as filePath:\n self.checkConfig(affineClass, affineConfig, filePath)\n affine = affineClass(affineConfig)\n for fromPoint in self.fromIter():\n toPoint = affine.forwardTransform(fromPoint)\n predToPoint = fromPoint + Extent2D(*affineConfig.translation)\n for i in range(2):\n self.assertAlmostEqual(toPoint[i], predToPoint[i])\n\n def testLinearAffine(self):\n \"\"\"Test affine = AffineXYTransform with just linear coefficients\n \"\"\"\n affineClass = xyTransformRegistry[\"affine\"]\n affineConfig = affineClass.ConfigClass()\n rotAng = 0.25 # radians\n xScale = 1.2\n yScale = 0.8\n affineConfig.linear = (\n math.cos(rotAng) * xScale, math.sin(rotAng) * yScale,\n -math.sin(rotAng) * xScale, math.cos(rotAng) * yScale,\n )\n with lsst.utils.tests.getTempFilePath(\".py\") as filePath:\n self.checkConfig(affineClass, affineConfig, filePath)\n affine = affineClass(affineConfig)\n for fromPoint in self.fromIter():\n toPoint = affine.forwardTransform(fromPoint)\n predToPoint = Point2D(\n affineConfig.linear[0] * fromPoint[0] +\n affineConfig.linear[1] * fromPoint[1],\n affineConfig.linear[2] * fromPoint[0] +\n affineConfig.linear[3] * fromPoint[1],\n )\n for i in range(2):\n self.assertAlmostEqual(toPoint[i], predToPoint[i])\n\n def testFullAffine(self):\n \"\"\"Test affine = AffineXYTransform with just linear coefficients\n \"\"\"\n affineClass = xyTransformRegistry[\"affine\"]\n affineConfig = affineClass.ConfigClass()\n affineConfig.translation = (-2.1, 3.4)\n rotAng = 0.832 # radians\n xScale = 3.7\n yScale = 45.3\n affineConfig.linear = (\n math.cos(rotAng) * xScale, math.sin(rotAng) * yScale,\n -math.sin(rotAng) * xScale, math.cos(rotAng) * yScale,\n )\n with lsst.utils.tests.getTempFilePath(\".py\") as filePath:\n self.checkConfig(affineClass, affineConfig, filePath)\n affine = affineClass(affineConfig)\n for fromPoint in self.fromIter():\n toPoint = affine.forwardTransform(fromPoint)\n predToPoint = Point2D(\n affineConfig.linear[0] * fromPoint[0] +\n affineConfig.linear[1] * fromPoint[1],\n affineConfig.linear[2] * fromPoint[0] +\n affineConfig.linear[3] * fromPoint[1],\n )\n predToPoint = predToPoint + Extent2D(*affineConfig.translation)\n for i in range(2):\n self.assertAlmostEqual(toPoint[i], predToPoint[i])\n\n def testRadial(self):\n \"\"\"Test radial = RadialXYTransform\n \"\"\"\n radialClass = xyTransformRegistry[\"radial\"]\n radialConfig = radialClass.ConfigClass()\n radialConfig.coeffs = (0, 1.05, 0.1)\n with lsst.utils.tests.getTempFilePath(\".py\") as filePath:\n self.checkConfig(radialClass, radialConfig, filePath)\n radial = radialClass(radialConfig)\n self.assertEqual(type(radial), RadialXYTransform)\n self.assertEqual(len(radial.getCoeffs()), len(radialConfig.coeffs))\n for coeff, predCoeff in zip(radial.getCoeffs(), radialConfig.coeffs):\n self.assertAlmostEqual(coeff, predCoeff)\n self.checkBasics(radial)\n for fromPoint in self.fromIter():\n fromRadius = math.hypot(fromPoint[0], fromPoint[1])\n fromAngle = math.atan2(fromPoint[1], fromPoint[0])\n predToRadius = fromRadius * \\\n (radialConfig.coeffs[2] *\n fromRadius + radialConfig.coeffs[1])\n predToPoint = Point2D(\n predToRadius * math.cos(fromAngle),\n predToRadius * math.sin(fromAngle))\n toPoint = radial.forwardTransform(fromPoint)\n for i in range(2):\n self.assertAlmostEqual(toPoint[i], predToPoint[i])\n\n def testBadRadial(self):\n \"\"\"Test radial with invalid coefficients\n \"\"\"\n for badCoeffs in (\n (0.1,), # len(coeffs) must be > 1\n (0.1, 1.0), # coeffs[0] must be zero\n (0.0, 0.0), # coeffs[1] must be nonzero\n (0.0, 0.0, 0.1), # coeffs[1] must be nonzero\n ):\n with self.assertRaises(lsst.pex.exceptions.Exception):\n RadialXYTransform(badCoeffs)\n\n radialClass = xyTransformRegistry[\"radial\"]\n radialConfig = radialClass.ConfigClass()\n radialConfig.coeffs = badCoeffs\n with self.assertRaises(Exception):\n radialConfig.validate()\n\n def testMulti(self):\n \"\"\"Test multi = MultiXYTransform\n \"\"\"\n affineClass = xyTransformRegistry[\"affine\"]\n wrapper0 = OneXYTransformConfig()\n wrapper0.transform.retarget(affineClass)\n affineConfig0 = wrapper0.transform\n affineConfig0.translation = (-2.1, 3.4)\n rotAng = 0.832 # radians\n xScale = 3.7\n yScale = 45.3\n affineConfig0.linear = (\n math.cos(rotAng) * xScale, math.sin(rotAng) * yScale,\n -math.sin(rotAng) * xScale, math.cos(rotAng) * yScale,\n )\n\n wrapper1 = OneXYTransformConfig()\n wrapper1.transform.retarget(affineClass)\n affineConfig1 = wrapper1.transform\n affineConfig1.translation = (26.5, -35.1)\n rotAng = -0.25 # radians\n xScale = 1.45\n yScale = 0.9\n affineConfig1.linear = (\n math.cos(rotAng) * xScale, math.sin(rotAng) * yScale,\n -math.sin(rotAng) * xScale, math.cos(rotAng) * yScale,\n )\n\n multiClass = xyTransformRegistry[\"multi\"]\n multiConfig = multiClass.ConfigClass()\n multiConfig.transformDict = {\n 0: wrapper0,\n 1: wrapper1,\n }\n with lsst.utils.tests.getTempFilePath(\".py\") as filePath:\n self.checkConfig(multiClass, multiConfig, filePath)\n multiXYTransform = multiClass(multiConfig)\n\n affine0 = affineClass(affineConfig0)\n affine1 = affineClass(affineConfig1)\n transformList = (affine0, affine1)\n refMultiXYTransform = RefMultiXYTransform(transformList)\n\n self.checkBasics(refMultiXYTransform)\n\n for fromPoint in self.fromIter():\n toPoint = multiXYTransform.forwardTransform(fromPoint)\n predToPoint = refMultiXYTransform.forwardTransform(fromPoint)\n for i in range(2):\n self.assertAlmostEqual(toPoint[i], predToPoint[i])\n\n\nclass MemoryTester(lsst.utils.tests.MemoryTestCase):\n pass\n\n\ndef setup_module(module):\n lsst.utils.tests.init()\n\n\nif __name__ == \"__main__\":\n lsst.utils.tests.init()\n unittest.main()\n","sub_path":"tests/test_xyTransform.py","file_name":"test_xyTransform.py","file_ext":"py","file_size_in_byte":13789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"135507915","text":"import math\n\n\nclass SimpleDistanceCalculation:\n\n def __init__(self, known_cone_width, known_cone_height, focal_length, image_width, image_height):\n self.known_cone_width = known_cone_width\n self.known_cone_height = known_cone_height\n self.focal_length = focal_length\n self.image_width = image_width\n self.image_width_half = image_width / 2.\n self.image_height = image_height\n\n def calculate_focal_length(self, known_distance, cone_w, cone_h):\n focal_width = (cone_w * known_distance) / self.known_cone_width\n focal_height = (cone_h * known_distance) / self.known_cone_height\n return (focal_width + focal_height) / 2\n\n def calculate_distance(self, cone_w, cone_h):\n distance_width = (self.known_cone_width * self.focal_length) / cone_w\n distance_height = (self.known_cone_height * self.focal_length) / cone_h\n return (distance_width + distance_height) / 2\n\n def calculate_relative_angle(self, cone_x, cone_y):\n if cone_x >= self.image_width_half:\n opposite = cone_x - self.image_width / 2.\n else:\n opposite = self.image_width / 2. - cone_x\n adjacent = self.image_height - cone_y\n return math.tan(opposite / adjacent)\n","sub_path":"SimpleDistanceCalculation.py","file_name":"SimpleDistanceCalculation.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"389798077","text":"import os\nfrom datetime import datetime\nfrom flask import (\n render_template,\n url_for,\n flash,\n redirect,\n request,\n Blueprint,\n current_app,\n send_file,\n)\nfrom P2MT_App.fetTools.forms import UploadFetDataForm\nfrom P2MT_App.fetTools.generateFetOutputFiles import ripFetFiles\nfrom P2MT_App.main.utilityfunctions import printLogEntry\n\nfetTools_bp = Blueprint(\"fetTools_bp\", __name__)\n\n\ndef save_csvFile(form_csvFetFile, filename):\n output_file_path = \"/tmp\"\n file_path = os.path.join(output_file_path, filename)\n # file_path = os.path.join(current_app.root_path, \"static/fet_data_files\", filename)\n form_csvFetFile.save(file_path)\n # file1 = open(file_path, \"w\")\n # file1.write(form_csvFetFile.data)\n # file1.close()\n return file_path\n\n\n@fetTools_bp.route(\"/fettools\", methods=[\"GET\", \"POST\"])\ndef displayFetTools():\n form = UploadFetDataForm()\n if form.validate_on_submit():\n if form.csvFetStudentInputFile.data:\n FetStudentInputFile = save_csvFile(\n form.csvFetStudentInputFile.data, \"FET_Student_Input_File.csv\"\n )\n if form.csvFetClassTeacherInputFile.data:\n FetClassTeacherInputFile = save_csvFile(\n form.csvFetClassTeacherInputFile.data,\n \"FET_Class_Teacher_Input_File.csv\",\n )\n if form.csvFetTimetableInputFile.data:\n FetTimeTableFile = save_csvFile(\n form.csvFetTimetableInputFile.data, \"FET_Timetable_File.csv\"\n )\n flash(\"Your account has been updated!\", \"success\")\n # output_file_path = os.path.join(current_app.root_path, \"static/fet_data_files\")\n output_file_path = \"/tmp\"\n ripFetFiles(\n form.yearOfGraduation.data,\n form.schoolYear.data,\n form.semester.data,\n FetStudentInputFile,\n FetClassTeacherInputFile,\n FetTimeTableFile,\n output_file_path,\n )\n print(\n \"=== Completed ripFetFiles. Redirecting to fetOutputFiles ===\",\n datetime.now(),\n \" ===\",\n )\n return redirect(url_for(\"fetTools_bp.fetOutputFiles\"))\n elif request.method == \"GET\":\n return render_template(\n \"fettools.html\", title=\"FET Tools\", UploadFetDataForm=form\n )\n print(form.errors)\n\n\n@fetTools_bp.route(\"/fetoutputfiles\", methods=[\"GET\"])\ndef fetOutputFiles():\n print(\"=== Arriving at fetOutputFiles ===\", datetime.now(), \" ===\")\n return render_template(\"fetoutputfiles.html\", title=\"FET Output Files\")\n\n\n@fetTools_bp.route(\"/fetoutputfiles/downloadcsv\")\ndef download_FetCsvFile():\n printLogEntry(\"download_FetCsvFile() function called\")\n csvFilename = \"/tmp/FetOutputFile.csv\"\n return send_file(csvFilename, as_attachment=True, cache_timeout=0)\n\n\n@fetTools_bp.route(\"/fetoutputfiles/downloadjson\")\ndef download_FetJsonFile():\n printLogEntry(\"download_FetJsonFile() function called\")\n csvFilename = \"/tmp/FetOutputFile.json\"\n return send_file(csvFilename, as_attachment=True, cache_timeout=0)\n","sub_path":"P2MT_App/fetTools/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"333622935","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /users/garrigaf/Documents/git/darfix/build/lib/darfix/__init__.py\n# Compiled at: 2020-03-03 08:28:12\n# Size of source mod 2**32: 1824 bytes\n\"\"\"The darfix package contains the following main sub-packages:\n\n- silx.core: Core classes and functions\n- silx.gui: Qt widgets for data visualization and data file browsing\n- silx.image: Some processing functions for 2D images\n- silx.io: Functions for input/output operations\n- silx.utils: Miscellaneous convenient functions\n\"\"\"\n__authors__ = [\n 'J. Garriga']\n__license__ = 'MIT'\n__date__ = '16/12/2019'\nfrom ._config import Config as _Config\nconfig = _Config()","sub_path":"pycfiles/darfix-0.3.0-py3-none-any/__init__.cpython-37.py","file_name":"__init__.cpython-37.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"70729248","text":"# !/usr/bin/env python\n# coding: utf-8\n\"\"\"\n# file : WSGIServer.py\n# author : shao\n# date: 2017/10/30 0030\n\"\"\"\nimport socket\nimport sys\n\n\nclass WSGIServer(object):\n\taddress_family=socket.AF_INET\n\tsocket_type=socket.SOCK_STREAM\n\trequest_queue_size=1\n\t\n\tdef __init__(self,server_address):\n\t\tself.listen_socket=listen_socket=socket.socket(\n\t\t\tself.address_family,\n\t\t\tself.socket_type\n\t\t)\n\t\t\n\t\tlisten_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\n\t\t# 绑定服务器地址\n\t\tlisten_socket.bind(server_address)\n\t\t# 监听\n\t\tlisten_socket.listen(self.request_queue_size)\n\t\t# 得到服务器的主机名和端口\n\t\thost,port=self.listen_socket.getsockname()[:2]\n\t\tself.server_name=socket.getfqdn(host)\n\t\tself.server_port=port\n\t\t\n\t\t# 返回网络应用的头部信息\n\t\tself.headers_set=[]\n\t\n\tdef set_app(self,application):\n\t\tself.application=application\n\t\n\tdef server_forever(self):\n\t\tlisten_socket=self.listen_socket\n\t\twhile True:\n\t\t\t# 监听客户端连接\n\t\t\tself.client_connection,client_address=listen_socket.accept()\n\t\t\t# 处理请求,关闭连接,循环等待\n\t\t\tself.handle_one_request()\n\t\n\tdef handle_one_request(self):\n\t\tself.request_data=request_data=self.client_connection.recv(2048)\n\t\t# 输出格式化的请求数据\n\t\tprint(''.join(\n\t\t\t'< {line}\\n'.format(line=line)\n\t\t\tfor line in request_data.splitlines()\n\t\t))\n\t\t\n\t\tself.parse_request(request_data)\n\t\t\n\t\t# 使用请求数据构建环境目录\n\t\tenv=self.get_environ()\n\t\t\n\t\tresult=self.application(env,self.start_response)\n\t\t\n\t\tself.finish_response(result)\n\t\n\tdef parse_request(self,text):\n\t\trequest_line=str(text.splitlines()[0])\n\t\t# print(request_line)\n\t\t# request_line=bytes(request_line,encoding='UTF-8')\n\t\trequest_line=request_line.rstrip('\\r\\n')\n\t\t(self.request_method,# GET\n\t\t self.path,# /hello\n\t\t self.request_version, # HTTP /1.1\n\t\t )=request_line.split()\n\t\n\tdef get_environ(self):\n\t\tenv={}\n\t\tenv['wsgi.version']=(1,0)\n\t\tenv['wsgi.url_scheme']='http'\n\t\tenv['wsgi.input']=str(self.request_data)\n\t\tenv['wsgi.errors']=sys.stderr\n\t\tenv['wsgi.mutithread']=True\n\t\tenv['wsgi.mutiprocess']=True\n\t\tenv['wsgi.run_once']=False\n\t\t\n\t\tenv['REQUEST_METHOD']=self.request_method\n\t\tenv['PATH_INFO']=self.path\n\t\tenv['SERVER_NAME']=self.server_name\n\t\tenv['SERVER_PORT']=str(self.server_port)\n\t\treturn env\n\t\n\tdef start_response(self,status,response_headers,exc_info=None):\n\t\tserver_headers=[\n\t\t\t('Data','Tue, 31 Mar 2015 12:54:46 GMT'),\n\t\t\t('Server','WSGIServer 0.2'),\n\t\t]\n\t\tself.headers_set=[status,response_headers+server_headers]\n\t\n\t# return self.finish_response\n\t\n\tdef finish_response(self,result):\n\t\ttry:\n\t\t\tstatus,response_headers=self.headers_set\n\t\t\tresponse='HTTP/1.1 {status}\\r\\n'.format(status=status)\n\t\t\tfor header in response_headers:\n\t\t\t\tresponse+='{0}: {1}\\r\\n'.format(*header)\n\t\t\tresponse+='\\r\\n'\n\t\t\tresponse=str(response)\n\t\t\t\n\t\t\tfor data in result:\n\t\t\t\tresponse+=str(data)\n\t\t\t\n\t\t\tprint(''.join(\n\t\t\t\t'> {line}\\n'.format(line=line)\n\t\t\t\tfor line in response.splitlines()\n\t\t\t))\n\t\t\tresponse=bytes(response,encoding='UTF-8')\n\t\t\tself.client_connection.sendall(response)\n\t\t\n\t\tfinally:\n\t\t\tself.client_connection.close()\n\n\nSERVER_ADDRESS=(HOST,PORT)='',8888\n\n\ndef make_server(server_address,application):\n\tserver=WSGIServer(server_address)\n\tserver.set_app(application)\n\treturn server\n\n\nif __name__=='__main__':\n\tif len(sys.argv)<2:\n\t\tsys.exit('Provide a WSGI application object as module:callable')\n\tapp_path=sys.argv[1]\n\tmodule,application=app_path.split(':')\n\tmodule=__import__(module)\n\tapplication=getattr(module,application)\n\thttpd=make_server(SERVER_ADDRESS,application)\n\tprint('WSGIServer:Server HTTP on port {port}...\\n'.format(port=PORT))\n\thttpd.server_forever()\n","sub_path":"server/serverproject/WSGIServer.py","file_name":"WSGIServer.py","file_ext":"py","file_size_in_byte":3641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"579197186","text":"from bs4 import BeautifulSoup\nimport requests\nimport html5lib\nmy_url=\"https://www.vocabulary.com/lists/141245\"\nraw_cont=requests.get(my_url)\nsoup= BeautifulSoup(raw_cont.text, 'html5lib')\nword_list={}\nword_list_unfil=soup.find('ol', attrs = {'id':'wordlist'})\nfor obj in word_list_unfil.findAll('li',attrs={'class':'entry learnable'}):\n word=(obj.find('a',attrs={'class':'word dynamictext'})).text\n word_def=(obj.find('div',attrs={'class':'definition'})).text\n word_list[word]=word_def\nwith open('WordList.txt','w') as f:\n for w,w_d in word_list.items():\n f.write(w+\" : \"+w_d+\"\\n\")\n\n \n","sub_path":"C++/Hangman Project/scripts/scrapper_script.py","file_name":"scrapper_script.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"97147101","text":"def merge_attached_event(mpack_event, data):\n '\\n Merges an event payload attached in the ``__sentry-event`` attachment.\\n '\n size = mpack_event.size\n if ((size == 0) or (size > MAX_MSGPACK_EVENT_SIZE_BYTES)):\n return\n try:\n event = unpack(mpack_event)\n except (ValueError, UnpackException, ExtraData) as e:\n minidumps_logger.exception(e)\n return\n for key in event:\n value = event.get(key)\n if (value is not None):\n data[key] = value","sub_path":"Data Set/bug-fixing-5/00f97172d2c459ee2f3e2cd37d5035d17749e393--bug.py","file_name":"00f97172d2c459ee2f3e2cd37d5035d17749e393--bug.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"591094646","text":"import sys\nsys.setrecursionlimit(10000)\n\ninput = sys.stdin.readline\n\n\nt = int(input())\n\n\ndx = [0, 0, 1, -1]\ndy = [-1, 1, 0, 0]\n\ndef dfs(y, x):\n visited[y][x] = 1\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if 0 <= nx < m and 0 <= ny < n:\n if visited[ny][nx] == 0 and matrix[ny][nx] == 1:\n dfs(ny, nx)\n\nfor _ in range(t):\n m, n, k = map(int, input().split())\n matrix = [[0]*m for _ in range(n)]\n for _ in range(k):\n a, b = map(int, input().split())\n matrix[b][a] = 1\n visited = [[0]*m for _ in range(n)]\n inum = 0\n for i in range(n):\n for j in range(m):\n if visited[i][j] == 0 and matrix[i][j] == 1:\n dfs(i, j)\n inum += 1\n print(inum)","sub_path":"boj/boj_1012.py","file_name":"boj_1012.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"638098553","text":"import json\nimport boto3\nfrom botocore.exceptions import ClientError\nimport sys\n\ndef pp(obj):\n print(json.dumps(obj, sort_keys=True,indent=3, separators=(',', ': ')))\n\ndef lambda_handler(event, context):\n pp(event)\n region_map = {\n \"tokyo\": \"ap-northeast-1\",\n \"singapore\": \"ap-southeast-1\",\n \"frankfurt\": \"eu-central-1\",\n \"ireland\": \"eu-west-1\",\n \"london\": \"eu-west-2\",\n \"sydney\": \"ap-southeast-2\",\n \"oregon\": \"us-west-2\",\n \"ohio\": \"us-east-2\",\n \"canada\": \"ca-central-1\"\n }\n resp = {}\n resp[\"sessionAttributes\"] = { \"foo\": \"bar\" }\n resp[\"dialogAction\"] = {\n \"type\" : \"Close\",\n \"fulfillmentState\": \"Fulfilled\",\n \"message\": {\n \"contentType\": \"PlainText\",\n \"content\": \"Awesome! Your stack is launching now!\"\n }\n }\n # validate the fulfillment\n if event[\"bot\"][\"name\"] != \"BookTrip\" or event[\"currentIntent\"][\"name\"] != \"LaunchStack\" or event[\"currentIntent\"][\"confirmationStatus\"] != \"Confirmed\":\n # invalid \n print(\"ERROR - invalid event\")\n return \"\"\n instance_number = event[\"currentIntent\"][\"slots\"][\"slotNumber\"]\n instance_os = event[\"currentIntent\"][\"slots\"][\"slotOS\"]\n instance_region = event[\"currentIntent\"][\"slots\"][\"slotRegion\"]\n if int(instance_number) not in range(1,11):\n resp[\"dialogAction\"][\"message\"][\"content\"] = \"invalid instance count\"\n return resp\n elif instance_os.lower() not in ['linux', 'windows']:\n resp[\"dialogAction\"][\"message\"][\"content\"] = \"invalid OS\"\n return resp\n elif instance_region.lower() not in region_map.keys():\n resp[\"dialogAction\"][\"message\"][\"content\"] = \"invalid region\"\n return resp\n \n region_code = region_map[instance_region.lower()]\n instance_os = instance_os.lower()\n instance_number = int(instance_number)\n #cfn_stack_url = 'https://s3-us-west-2.amazonaws.com/pahud-cfn-us-west-2/ecs-cfn-refarch/cloudformation/codepipeline.yml'\n cfn_stack_url = {\n 'linux': 'https://s3-us-west-2.amazonaws.com/pahud-cfn-us-west-2/ecs-cfn-refarch/cloudformation/service.yml',\n 'windows': 'https://s3-us-west-2.amazonaws.com/pahud-cfn-us-west-2/ecs-cfn-refarch/cloudformation/service-windows.yml'\n }\n\n session = boto3.session.Session()\n cfn = boto3.client('cloudformation', region_name=region_code)\n try:\n print('creating stack now')\n cfn_resp = cfn.create_stack(\n StackName='summit-lex-{0}'.format(instance_os),\n TemplateURL=cfn_stack_url[instance_os],\n Parameters=[\n {\n 'ParameterKey': 'ASGDesiredCapacity',\n 'ParameterValue': str(instance_number),\n 'UsePreviousValue': True\n },\n {\n 'ParameterKey': 'ASGMaxSize',\n 'ParameterValue': str(int(instance_number) + 5),\n 'UsePreviousValue': True\n },\n {\n 'ParameterKey': 'ASGMinSize',\n 'ParameterValue': '0',\n 'UsePreviousValue': True\n },\n {\n 'ParameterKey': 'Repository',\n 'ParameterValue': '',\n 'UsePreviousValue': True\n }\n ],\n Capabilities=['CAPABILITY_IAM']\n\n )\n print(cfn_resp)\n resp[\"dialogAction\"][\"message\"][\"content\"] = \"Awesome! Your stack is launching in {0} now!\".format(instance_region)\n except ClientError as ex:\n print(ex)\n resp[\"dialogAction\"][\"message\"][\"content\"] = 'failed to create - resource already exists'\n \n \n return resp\n","sub_path":"Lambda/LexLaunchStack/venv/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"289317164","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom pathlib import Path\nimport warnings\nimport covid19dh\nimport pandas as pd\nfrom covsirphy.util.term import Term\nfrom covsirphy.cleaning.cbase import CleaningBase\nfrom covsirphy.cleaning.jhu_data import JHUData\nfrom covsirphy.cleaning.oxcgrt import OxCGRTData\nfrom covsirphy.cleaning.population import PopulationData\nfrom covsirphy.cleaning.pcr_data import PCRData\n\n\nclass COVID19DataHub(Term):\n \"\"\"\n Load datasets retrieved from COVID-19 Data Hub.\n https://covid19datahub.io/\n\n Args:\n filename (str): CSV filename to save records\n \"\"\"\n # Citation\n CITATION = '(Secondary source)' \\\n ' Guidotti, E., Ardia, D., (2020), \"COVID-19 Data Hub\",' \\\n ' Journal of Open Source Software 5(51):2376, doi: 10.21105/joss.02376.'\n # Name conversion list of columns\n _OXCGRT_COLS_RAW = [\n \"school_closing\",\n \"workplace_closing\",\n \"cancel_events\",\n \"gatherings_restrictions\",\n \"transport_closing\",\n \"stay_home_restrictions\",\n \"internal_movement_restrictions\",\n \"international_movement_restrictions\",\n \"information_campaigns\",\n \"testing_policy\",\n \"contact_tracing\",\n \"stringency_index\"\n ]\n _COL_DICT = {\n \"date\": Term.DATE,\n \"administrative_area_level_1\": Term.COUNTRY,\n \"administrative_area_level_2\": Term.PROVINCE,\n \"tests\": Term.TESTS,\n \"confirmed\": Term.C,\n \"deaths\": Term.F,\n \"recovered\": Term.R,\n \"population\": Term.N,\n \"iso_alpha_3\": Term.ISO3,\n **{v: v.capitalize() for v in _OXCGRT_COLS_RAW}\n }\n # Class objects of datasets\n OBJ_DICT = {\n \"jhu\": JHUData,\n \"population\": PopulationData,\n \"oxcgrt\": OxCGRTData,\n \"pcr\": PCRData,\n }\n\n def __init__(self, filename):\n try:\n self.filepath = Path(filename)\n except TypeError:\n raise TypeError(f\"@filename should be a path-like object, but {filename} was applied.\")\n self.filepath.parent.mkdir(exist_ok=True, parents=True)\n self.primary_list = None\n self._loaded_df = None\n\n def load(self, name=\"jhu\", force=True, verbose=1):\n \"\"\"\n Load the datasets of COVID-19 Data Hub and create dataset object.\n\n Args:\n name (str): name of dataset, \"jhu\", \"population\", \"oxcgrt\" or \"pcr\"\n force (bool): if True, always download the dataset from the server\n verbose (int): level of verbosity\n\n Returns:\n covsirphy.CleaningBase: the dataset\n\n Note:\n If @verbose is 2, detailed citation list will be shown when downloading.\n If @verbose is 1, how to show the list will be explained.\n Citation of COVID-19 Data Hub will be set as JHUData.citation etc.\n \"\"\"\n if name not in self.OBJ_DICT:\n raise KeyError(\n f\"@name must be {', '.join(list(self.OBJ_DICT.keys()))}, but {name} was applied.\")\n # Get all data\n if self._loaded_df is None:\n self._loaded_df = self._load(force=force, verbose=verbose)\n return self.OBJ_DICT[name](data=self._loaded_df, citation=self.CITATION)\n\n def _load(self, force, verbose):\n \"\"\"\n Load the datasets of COVID-19 Data Hub.\n\n Args:\n force (bool): if True, always download the dataset from the server\n verbose (int): level of verbosity\n\n Returns:\n pandas.DataFrame: as the same as COVID19DataHub._preprocessing()\n\n Note:\n If @verbose is 2, detailed citation list will be shown when downloading.\n If @verbose is 1, how to show the list will be explained.\n \"\"\"\n # Use local CSV file\n if not force and self.filepath.exists():\n df = CleaningBase.load(\n self.filepath,\n dtype={\n self.PROVINCE: \"object\", \"Province/State\": \"object\",\n \"key\": \"object\", \"key_alpha_2\": \"object\",\n })\n if set(self._COL_DICT.values()).issubset(df.columns):\n return df\n # Download dataset from server\n raw_df = self._retrieve(verbose=verbose)\n raw_df.to_csv(self.filepath, index=False)\n return raw_df\n\n def _retrieve(self, verbose=1):\n \"\"\"\n Retrieve datasets from COVID-19 Data Hub.\n Level 1 (country) and level2 (province) will be used and combined to a dataframe.\n\n Args:\n verbose (int): level of verbosity\n\n Note:\n If @verbose is 2, detailed citation list will be shown when downloading.\n If @verbose is 1, how to show the list will be explained.\n \"\"\"\n # Download datasets\n if verbose:\n print(\"Retrieving datasets from COVID-19 Data Hub https://covid19datahub.io/\")\n c_df, p_df, self.primary_list = self._download()\n # Merge the datasets\n df = pd.concat([c_df, p_df], axis=0, ignore_index=True)\n # Perform pre-processing\n df = self._preprocessing(df)\n # Show citation list\n if verbose:\n if isinstance(verbose, int) and verbose >= 2:\n print(\"\\nDetailed citaition list:\")\n print(self.primary_list)\n else:\n print(\"\\tPlease set verbose=2 to see the detailed citation list.\")\n return df\n\n def _download(self):\n \"\"\"\n Retrieve dataset and citation list from COVID-19 Data Hub.\n\n Returns:\n tuple:\n pandas.DataFrame: dataset at country level\n pandas.DataFrame: dataset at province level\n str: the list of primary sources\n\n Note:\n For some countries, province-level data is included.\n \"\"\"\n warnings.simplefilter(\"ignore\", ResourceWarning)\n levels = [f\"administrative_area_level_{i}\" for i in range(1, 4)]\n # Level 1 (country/region)\n c_raw, c_cite = covid19dh.covid19(country=None, level=1, verbose=False, raw=True)\n c_df = c_raw.groupby(levels[0]).ffill().fillna(0)\n for num in range(3):\n c_df.loc[:, levels[num]] = c_raw[levels[num]]\n # Level 2 (province/state)\n p_raw, p_cite = covid19dh.covid19(country=None, level=2, verbose=False, raw=True)\n p_df = p_raw.groupby(levels[:2]).ffill().fillna(0)\n for num in range(3):\n p_df.loc[:, levels[num]] = p_raw[levels[num]]\n # Citation\n cite = pd.concat([c_cite, p_cite], axis=0, ignore_index=True)\n cite = cite.loc[:, [\"title\", \"year\", \"url\"]]\n cite = cite.sort_values([\"year\", \"url\"], ascending=[False, True])\n cite.drop_duplicates(subset=\"title\", inplace=True)\n series = cite.apply(lambda x: f\"{x[0]} ({x[1]}), {x[2]}\", axis=1)\n return (c_df, p_df, \"\\n\".join(series.tolist()))\n\n def _preprocessing(self, raw):\n \"\"\"\n Perform pre-processing with the raw dataset.\n\n Args:\n raw (pandas.DataFrame):\n Index\n reset index\n Columns\n Refer to COVID-19 Data Hub homepage.\n https://covid19datahub.io/articles/doc/data.html\n\n Returns:\n pandas.DataFrame:\n Index\n reset index\n Columns\n - Date: observation date\n - Country: country/region name\n - Province: province/prefecture/state name\n - Confirmed: the number of confirmed cases\n - Infected: the number of currently infected cases\n - Fatal: the number of fatal cases\n - Recovered: the number of recovered cases\n - School_closing\n - Workplace_closing\n - Cancel_events\n - Gatherings_restrictions\n - Transport_closing\n - Stay_home_restrictions\n - Internal_movement_restrictions\n - International_movement_restrictions\n - Information_campaigns\n - Testing_policy\n - Contact_tracing\n - Stringency_index\n\n Note:\n Data types are not confirmed.\n \"\"\"\n df = raw.copy()\n # Replace column names\n df = df.rename(columns=self._COL_DICT)\n self._ensure_dataframe(df, columns=list(self._COL_DICT.values()))\n # Country\n df[self.COUNTRY] = df[self.COUNTRY].replace(\n {\n # COD\n \"Congo, the Democratic Republic of the\": \"Democratic Republic of the Congo\",\n # COG\n \"Congo\": \"Republic of the Congo\",\n # KOR\n \"Korea, South\": \"South Korea\",\n }\n )\n # Set 'Others' as the country name of cruise ships\n ships = [\"Diamond Princess\", \"Costa Atlantica\", \"Grand Princess\", \"MS Zaandam\"]\n for ship in ships:\n df.loc[df[self.COUNTRY] == ship, [self.COUNTRY, self.PROVINCE]] = [self.OTHERS, ship]\n return df\n\n @property\n def primary(self):\n \"\"\"\n str: the list of primary sources.\n \"\"\"\n return self.primary_list or self._download()[-1]\n","sub_path":"covsirphy/cleaning/covid19datahub.py","file_name":"covid19datahub.py","file_ext":"py","file_size_in_byte":9374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"99672373","text":"from django.db import models\n\nfrom api.managers.ComplianceReportStatusManager import \\\n ComplianceReportStatusManager\nfrom api.managers.TheTypeManager import TheTypeManager\nfrom api.models.CompliancePeriod import CompliancePeriod\nfrom api.models.ComplianceReportSchedules import ScheduleC, ScheduleB, ScheduleA\nfrom api.models.Organization import Organization\nfrom api.models.mixins.DisplayOrder import DisplayOrder\nfrom api.models.mixins.EffectiveDates import EffectiveDates\nfrom auditable.models import Auditable\n\n\nclass ComplianceReportStatus(Auditable, DisplayOrder, EffectiveDates):\n \"\"\"\n List of Possible statuses for compliance reports.\n \"\"\"\n status = models.CharField(\n max_length=25,\n blank=True,\n null=True,\n unique=True,\n db_comment=\"Contains an enumerated value to describe the compliance \"\n \"report status. This is a unique natural key.\"\n )\n\n objects = ComplianceReportStatusManager()\n\n def natural_key(self):\n \"\"\"\n Allows type 'status' to be used to identify\n a row in the table\n \"\"\"\n return (self.status,)\n\n class Meta:\n db_table = 'compliance_report_status'\n\n db_table_comment = \"List of possible statuses.\" \\\n \"(Draft, Submitted, Received, etc.)\"\n\n\nclass ComplianceReportType(DisplayOrder):\n \"\"\"\n List of Possible statuses for compliance reports.\n \"\"\"\n the_type = models.CharField(\n max_length=100,\n blank=False,\n null=False,\n unique=True,\n db_comment=\"Short descriptive name of the compliance report type.\"\n )\n\n description = models.CharField(\n max_length=1000, blank=True, null=False,\n db_comment=\"Description of the compliance report type. This is the \"\n \"displayed name.\"\n )\n\n objects = TheTypeManager()\n\n def natural_key(self):\n \"\"\"\n Allows type 'status' to be used to identify\n a row in the table\n \"\"\"\n return (self.the_type,)\n\n class Meta:\n db_table = 'compliance_report_type'\n\n db_table_comment = \"List of possible compliance report types.\"\n\n\nclass ComplianceReport(Auditable):\n \"\"\"\n List of Possible statuses for compliance reports.\n \"\"\"\n status = models.ForeignKey(\n ComplianceReportStatus,\n on_delete=models.PROTECT,\n null=False\n )\n\n type = models.ForeignKey(\n ComplianceReportType,\n on_delete=models.PROTECT,\n null=False\n )\n\n organization = models.ForeignKey(\n Organization,\n on_delete=models.CASCADE,\n null=False\n )\n\n compliance_period = models.ForeignKey(\n CompliancePeriod,\n on_delete=models.DO_NOTHING,\n null=False\n )\n\n schedule_a = models.OneToOneField(\n ScheduleA,\n related_name='compliance_report',\n on_delete=models.CASCADE,\n null=True\n )\n\n schedule_b = models.OneToOneField(\n ScheduleB,\n related_name='compliance_report',\n on_delete=models.CASCADE,\n null=True\n )\n\n schedule_c = models.OneToOneField(\n ScheduleC,\n related_name='compliance_report',\n on_delete=models.CASCADE,\n null=True\n )\n\n class Meta:\n db_table = 'compliance_report'\n\n db_table_comment = \"Contains annual compliance report records\"\n","sub_path":"backend/api/models/ComplianceReport.py","file_name":"ComplianceReport.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"120369538","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nfrom typing import List, Optional\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n # 全部取出,再拼接\n import heapq\n dummy = ListNode(0)\n p = dummy\n h = []\n for i in range(len(lists)):\n if lists[i]:\n heapq.heappush(h, (lists[i].val, i))\n lists[i] = lists[i].next\n\n while h:\n val, idx = heapq.heappop(h)\n p.next = ListNode(val)\n p = p.next\n if lists[idx]:\n heapq.heappush(h, (lists[idx].val, idx))\n lists[idx] = lists[idx].next\n return dummy.next\n\n\nif __name__ == '__main__':\n sn = Solution()\n\n from gen_node import gen_node\n\n lists = [gen_node([1, 4, 5]), gen_node([1, 3, 4]), gen_node([2, 6])]\n\n print(sn.mergeKLists(lists))\n","sub_path":"字节/23.py","file_name":"23.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"581659518","text":"# import hashlib\nimport base58\nfrom urllib.parse import urlparse\n\nimport dateutil.parser\nimport multihash\nfrom goose import Goose\n# from lxml import etree\nfrom scrapy.linkextractors import LinkExtractor\n\n\nclass WebsiteParser(object):\n \"\"\"\n Receive response from scrapy\n Return the list of items to save:\n * HTML content to save to S3\n * parsed dict with information to send to SQS\n \"\"\"\n\n def __init__(self, response, allowed_domains=[]):\n self.response = response\n self.allowed_domains = allowed_domains\n self.my_le = LinkExtractor(allow=('', ))\n\n def get_body(self):\n return self.response.body\n\n def get_content_multihash(self):\n return base58.b58encode(\n bytes(multihash.encode(self.response.body, multihash.SHA1))\n )\n\n def get_s3_filename(self):\n # return hashlib.sha256(self.response.url.encode('utf-8')).hexdigest()\n return self.get_content_multihash()\n\n def get_result(self):\n \"\"\"\n Return parse results\n https://github.com/difchain/rmaas/blob/master/docs/WebCrawler_Client.md\n \"\"\"\n gs = Goose()\n parsed_article = gs.extract(raw_html=self.get_body())\n\n owner = urlparse(self.response.url).netloc\n identifier = self.response.url # .replace('https://', '').replace('http://', '')\n result = {\n # RecordName area\n 'identifier': identifier,\n 'owner': owner,\n # RecordVersion area\n 'Hash': self.get_content_multihash(),\n 'RecordsAuthority': 'naa.gov.au:gda21',\n 'Title': parsed_article.title,\n 'Description': parsed_article.cleaned_text[:300],\n 'Author': self._get_version_author(),\n 'DateCreated': self._get_date_created(),\n 'Classification': 'UNCLASSIFIED',\n 'Language': self._get_language(),\n # object\n 'size': len(self.response.body),\n 'MIMEType': self._get_mimetype(),\n # etc\n 's3_filename': self.get_s3_filename(),\n 'external_domains': self._get_external_domains(),\n 'links': self._get_links(),\n }\n return result\n\n # def _get_version_title(self):\n # return self.response.selector.xpath('//title/text()').extract_first() or '?'\n\n # def _get_version_description(self):\n # tree = etree.HTML(self.response.body)\n # etree.strip_tags(tree)\n # text_spaced = etree.tounicode(tree, method='text').replace('\\n', ' ').strip()\n # text = ' '.join(x for x in text_spaced.split() if x)\n # return text[:300] if text else '?'\n\n def _get_version_author(self):\n return 'John the Dropbear'\n\n def _get_mimetype(self):\n result = self.response.headers.get('Content-Type')\n if result:\n result = result.decode('utf-8')\n return result or 'text/html'\n\n def _get_date_created(self):\n lm = self.response.headers.get('Last-Modified')\n if lm:\n lm = dateutil.parser.parse(lm)\n if lm:\n lm = lm.isoformat()\n return lm\n\n def _get_language(self):\n return 'en-us'\n\n def _get_external_domains(self):\n # get the list of external domain names linked from this page\n external_domains = set()\n for link in self.my_le.extract_links(self.response):\n parsed_link = urlparse(link.url)\n if parsed_link.netloc not in self.allowed_domains:\n external_domains.add(parsed_link.netloc)\n return sorted(list(external_domains))\n\n def _get_links(self):\n links = set()\n for link in self.my_le.extract_links(self.response):\n links.add(link.url)\n return sorted(list(links))\n","sub_path":"crawler-node/src/my_parser.py","file_name":"my_parser.py","file_ext":"py","file_size_in_byte":3775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"514100670","text":"import requests \nimport numpy as np\nimport csv\nimport os\nimport pandas as pd\nfrom textblob import TextBlob\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom api_cred import Credentials\n\n\n\nfrom google.cloud import language\nfrom google.cloud.language import enums\nfrom google.cloud.language import types\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"/path/to/credientials.json\"\n\ndef run_azure(input_array):\n creds = Credentials().get('azure')\n headers = { 'Ocp-Apim-Subscription-Key' : creds['subscription_key'] }\n sentiment_api_url = creds['endpoint'] + \"sentiment\"\n docs = []\n assert(len(input_array.flatten()) <= 1000)\n for i, input_text in enumerate(input_array.flatten()):\n docs.append({'id' : str(i+1), 'language' : 'en', 'text' : input_text})\n documents = { 'documents' : docs }\n response = requests.post(sentiment_api_url, headers=headers, json=documents)\n sentiments = response.json()\n print(sentiments)\n scores = [x['score'] for x in sentiments['documents']]\n scores = np.array(scores)\n return scores.reshape(input_array.shape[0], 1)\n\n\ndef run_textblob(input_array): \n result_arr = []\n for r in input_array: \n blob = TextBlob(r)\n result_arr.append([blob.sentiment.polarity, blob.sentiment.subjectivity])\n return result_arr\n\ndef api_chunks(twt_list, n=1000):\n for i in range(0, len(twt_list), n): \n yield twt_list[i:i+n]\n\ndef write_results(tweet_list, label_list, sensitive_attr, api_func, save_file, score_label): \n with open(save_file, 'w') as f: \n csv_writer = csv.writer(f)\n if len(score_label) == 1: \n csv_writer.writerow([\"text X\", \"Z\", \"label Y\", score_label])\n else: \n print([\"text X\", \"Z\", \"label Y\"] + score_label)\n csv_writer.writerow([\"text X\", \"Z\", \"label Y\"] + score_label)\n sentiment = [] \n review_iter = api_chunks(tweet_list, 50)\n for sub_list in review_iter: \n sentiment += list(api_func(np.array(sub_list)))\n\n for i, twt in enumerate(tweet_list): \n if len(sentiment[i]) == 1: \n csv_writer.writerow([twt, sensitive_attr[i], label_list[i], sentiment[i][0]])\n else: \n csv_writer.writerow([twt, sensitive_attr[i], label_list[i]] + sentiment[i])\n\ndef run_google_sentiment(input_array): \n # Instantiates a client\n client = language.LanguageServiceClient()\n\n result_arr = [] \n # The text to analyze\n for twt in input_array: \n document = types.Document(\n content=twt,\n type=enums.Document.Type.PLAIN_TEXT)\n\n # Detects the sentiment of the text\n try: \n sentiment = client.analyze_sentiment(document=document).document_sentiment\n print('Text: {}'.format(twt))\n print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))\n result_arr.append([sentiment.score, sentiment.magnitude])\n except: \n print(twt)\n result_arr.append([0, 0])\n\n return result_arr\n\n\ndef run_custom_sentiment(input_array): \n df = pd.read_csv('datasets/amazon_sentiment.csv')\n texts = df['text'].tolist() \n labels = df['label'].tolist()\n vectorizer = CountVectorizer(stop_words='english', max_features=10000)\n train_features = vectorizer.fit_transform(texts[1000:9000])\n nb_model = MultinomialNB()\n nb_model.fit(train_features, labels[1000:9000])\n\n vocab = vectorizer.vocabulary_\n\n vectorizer = CountVectorizer(stop_words='english', vocabulary=vocab)\n test_features = vectorizer.fit_transform(input_array)\n predictions = nb_model.predict(test_features)\n prob = nb_model.predict_proba(test_features)\n predictions = nb_model.predict(test_features)\n\n class_prob = [[p[1]] for p in prob]\n return class_prob\n\n\n\n\nif __name__ == \"__main__\": \n\n reviews = [] \n sensitive_attr = [] \n labels = [] \n dataset_str = 'movies'\n with open('datasets/' + dataset_str + '1000.csv', 'r') as f: \n csv_reader = csv.reader(f)\n row = next(csv_reader)\n for row in csv_reader: \n reviews.append(row[0])\n sensitive_attr.append(row[1])\n labels.append(row[2])\n\n #write_results(reviews, labels, sensitive_attr, run_azure, 'results/'+ dataset_str + '_azure_results.csv', ['sentiment'])\n \n #write_results(reviews, labels, sensitive_attr, run_textblob, 'results/'+ dataset_str + '_tb_results.csv', ['sentiment'])\n\n #write_results(reviews, labels, sensitive_attr, run_google_sentiment, 'results/'+ dataset_str + '_google_results.csv', ['sentiment', 'magnitude'])\n","sub_path":"tasks/nlp/get_sentiment.py","file_name":"get_sentiment.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"374907688","text":"import cv2\nimport matplotlib.pylab as plt\nimport numpy as np\nimport math\nimport pylab as pl\nimport scipy.signal as signal\n\nCAMERA={\n 'FX_C':1081.3720703125,\n 'FY_C':-1081.3720703125,\n 'CX_C':960.5,\n 'CY_C':539.5,\n 'FX_D':366.864685058594,\n 'FY_D':-366.864685058594,\n 'CX_D':263.148010253906, \n 'CY_D':200.292007446289}\n\ndef RGBtoD(p, frame):\n if frame<=30:\n c=3.5\n elif frame>=130:\n c=4.5\n else:\n c=4\n x_c=p[0]\n y_c=p[1]\n x_d=round((x_c-CAMERA['CX_C'])/CAMERA['FX_C']*CAMERA['FX_D']+CAMERA['CX_D']+c)\n y_d=round((y_c-CAMERA['CY_C'])/CAMERA['FY_C']*CAMERA['FY_D']+CAMERA['CY_D'])\n #print(x_d)\n #print(y_d)\n #print(type(im[y_d][x_d][0]))\n #print(im[y_d+424][x_d][0])\n \n return (x_d, y_d)\n\ndef filter(p, im, size):\n s=(size-1)/2\n (x_d, y_d)=RGBtoD(p)\n win=[im[i,j] for i in range(y_d-s, y_d+s+1) for j in range(x_d-s, x_d+s+1)]\n for k in win:\n if (k>=0 and k<=23) or k>175:\n win.remove(k)\n win=np.array(win)\n return np.median(win)\n\ndef RGBto3D(p, im, frame, filter=False, size=0):\n \n x_c=p[0]\n y_c=p[1]\n if frame<=30:\n c=3.5\n elif frame>=130:\n c=4.5\n else:\n c=4\n x_d=round((x_c-CAMERA['CX_C'])/CAMERA['FX_C']*CAMERA['FX_D']+CAMERA['CX_D']+c)\n y_d=round((y_c-CAMERA['CY_C'])/CAMERA['FY_C']*CAMERA['FY_D']+CAMERA['CY_D'])\n #print(x_d)\n #print(y_d)\n #print(type(im[y_d][x_d][0]))\n #print(im[y_d+424][x_d][0])\n if len(p)==2:\n if filter:\n z=his_image(im, size, p, frame)[0]\n else:\n #print(im[round(y_d)][round(x_d)][0])\n z=im[round(y_d)][round(x_d)][0]*256/6+im[round(y_d+424)][round(x_d)][0]\n '''\n if(z==0):\n z1=max([im[y_d+i][x_d+j][0] for i in range(-2,3) for j in range(-2,3)])\n z0=min([im[y_d+i][x_d+j][0] for i in range(-2,3) for j in range(-2,3)])\n \n z=z1*256+z0 \n '''\n x=(x_d-CAMERA['CX_D'])*z/CAMERA['FX_D']\n y=(y_d-CAMERA['CY_D'])*(z)/CAMERA['FY_D']\n else:\n z=p[2]\n x=(x_d-CAMERA['CX_D'])*z/CAMERA['FX_D']\n y=(y_d-CAMERA['CY_D'])*(z)/CAMERA['FY_D']\n \n return (x, y, z)\n\ndef angle(p1,p2,p3,alwaysPositive=True):\n n=len(p1)\n # vectors\n v1=[(p1[i]-p2[i]) for i in range(n)]\n v2=[(p3[i]-p2[i]) for i in range(n)]\n # angle = acos( dot(v1,v2) / (len(v1)*len(v2)) )\n dot=sum([(v1[i]*v2[i]) for i in range(n)])\n len_v1=math.sqrt(sum([(v1[i]**2) for i in range(n)]))\n len_v2=math.sqrt(sum([(v2[i]**2) for i in range(n)]))\n if(len_v1!=0 and len_v2!=0):\n if not alwaysPositive and n==3 and (v1[2]<0 and v2[2]<=0):\n return 360-math.degrees(math.acos(dot/(len_v1*len_v2)))\n else:\n return math.degrees(math.acos(dot/(len_v1*len_v2)))\n else:\n return 180\n\ndef v2i(cap, frame, save=False): \n cap.set(cv2.CAP_PROP_POS_FRAMES, frame) # 设置帧数标记\n ret, im = cap.read() # read方法返回一个布尔值和一个视频帧\n if ret: \n if save:\n cv2.imwrite(\"test1/img/\" + str(frame) + \"C.jpg\", im)\n return im\n else:\n return 'No image!!'\n \ndef his_image(im, size, p, frame):\n\n # médian\n #img_m=cv2.medianBlur(im,5)\n #font=cv2.FONT_HERSHEY_SIMPLEX\n img_m=im[0:828, 0:512]\n '''\n img_m_h=img_m[0:424, 0:512]\n img_m_b=img_m[424:828, 0:512]\n for i in range(424):\n for j in range(512):\n img_m[i,j]=img_m_h[i,j]*256/6+img_m_b[i,j]\n '''\n \n x=p[0]\n y=p[1]\n (x_d, y_d)=RGBtoD((x, y),frame)\n ndg_h1=img_m[y_d, x_d][0]# Original Depth_high\n ndg_b1=img_m[y_d+424, x_d][0]# Depth Original_low\n print(ndg_h1, ndg_b1)\n #print(img_m[(y_d-int((size-1)/2)):(y_d+int((size-1)/2)),(x_d-int((size-1)/2)):(x_d+int((size-1)/2))] )\n ng=[]\n #print(img_m[(y_d-int((size-1)/2)):(y_d+int((size-1)/2)),(x_d-int((size-1)/2)):(x_d+int((size-1)/2))] )\n for i in range(y_d-int((size-1)/2), y_d+int((size-1)/2)+1):\n for j in range(x_d-int((size-1)/2), x_d+int((size-1)/2)+1):\n z0=(img_m[i,j]*256/6+img_m[i+424,j])[0]/10\n if z0>120 and z0<850:\n ng.append(int(round(z0)))\n \n print(len(ng))\n ngh=[0]*851\n for h in set(ng):\n ngh[h]=ng.count(h)\n\n zm=ngh.index(max(ngh))*10\n print(zm)\n\n return (zm, ndg_h1*256/6+ndg_b1)\n\ndef compt(t1, vd, t2, gt, dt, show=False):\n gt_r=[]\n t=[]\n t1=[j-dt for j in t1]\n for i in t1:\n \n if i<=0:\n continue\n elif i\n \n \n \n Форма добавления\n \n \n \n \n \n
    \n

    Форма добавления

    \n
    \n \n \n \n
    \n
    \n \"\"\")\n # В этой части из таблицы regions берутся все строки и помещаются в выпадающий список\n select = \"\"\"\n Регион \"\n print(select)\n print(\"\"\"\n Город \n
    \n
    \n Телефон: +7\n
    \n
    \n E-mail\n
    \n \n \n
    \n \n \n \"\"\")\nelif 'exportExcelButton' in form: # Если нажата кнопка \"Экспортировать таблицу в Excel\"\n tablePeoples = {\"Surname\": [], # Собирается таблица для записи в файл (пока есть только шапка)\n \"Name\": [],\n \"Patronymic\": [],\n \"Region\": [],\n \"City\": [],\n \"Telephone\": [],\n \"E-mail\": []}\n cursor = db.cursor()\n cursor.execute('''\n SELECT p.surname, p.name, p.patronymic, r.region, c.city, p.telephone, p.email FROM peoples p\n JOIN regions r ON p.regionId = r.id\n JOIN cities c ON (p.cityId=c.id AND p.regionId = c.regionId) \n ''')\n peoples = cursor.fetchall() # Из таблицы peoples забираются все строки и постепенно наполняют tablePeoples\n for surname, name, patronymic, region, city, telephone, email in peoples:\n tablePeoples[\"Surname\"].append(surname)\n tablePeoples[\"Name\"].append(name)\n tablePeoples[\"Patronymic\"].append(patronymic)\n tablePeoples[\"Region\"].append(region)\n tablePeoples[\"City\"].append(city)\n tablePeoples[\"Telephone\"].append(telephone)\n tablePeoples[\"E-mail\"].append(email)\n dataFrame = pd.DataFrame(tablePeoples)\n dataFrame.to_excel(\"Peoples.xlsx\") # Записываем таблицу в файл с именем Peoples.xlsx в директорию проекта\n print('''\n \n \n \n \n ''') # Уведомляем пользователя о том, что таблица peoples была экспортрована\nelif 'importPdfButton' in form: # Если нажата кнопка \"Импорт данных из PDF\"\n pdf = workPDF.openPDF() # Открываем PDF\n text = workPDF.getText(pdf) # Получаем текст из файла (с сохранененной структурой)\n text = text.split('\\n') # Получаем список строк из файла\n data = {} # Данные из резюме (пока пустой)\n\n fio = text[0].split(' ') # Первой строчкой в резюме является ФИО, которое разделено пробелами. Считываем его.\n data[\"Surname\"] = fio[0]\n data[\"Name\"] = fio[1]\n data[\"Patronymic\"] = '-'\n if len(fio) > 2:\n data[\"Patronymic\"] = ' '.join(fio[1:]) # В случае, если в резюме есть и отчество, получаем и его (иначе, значение по умолчанию = \"-\")\n\n city = text[4].split(' ') # Получаем строку про место проживания (известен только город)\n city = city[len(city) - 1]\n cursor = db.cursor()\n cursor.execute(\"SELECT id, regionId FROM cities WHERE city='{}'\".format(city))\n location = cursor.fetchall()\n data[\"City\"] = location[0][0] # Получаем ИД города и региона из таблицы, исходя из названия города\n data[\"Region\"] = location[0][1]\n\n telephone = text[2] # Получаем строку с телефоном\n data[\"Telephone\"] = re.sub(\n '[- ]*',\n '',\n re.findall(r'[(][0-9]{3,}[)]\\s*[0-9]+[-\\s]*[0-9]+[-\\s]*[0-9]', telephone)[0]\n ) # Получаем сам номер телефона поиском в строке по шаблону номера телефона\n\n email = text[3] # Получаем строку с почтой\n data[\"E-mail\"] = re.findall(r'\\w+@[A-Z0-9]+\\.[A-Z]{2,4}', email, flags=re.IGNORECASE)[0] # Получаем саму почту поиском в строке по шаблону почты\n cursor = db.cursor()\n request = \"INSERT INTO peoples VALUES({},{},{},{},{},{},{})\".format(\n \"\\'{}\\'\".format(data[\"Surname\"]),\n \"\\'{}\\'\".format(data[\"Name\"]),\n \"\\'{}\\'\".format(data[\"Patronymic\"]),\n int(data[\"Region\"]),\n int(data[\"City\"]),\n \"\\'{}\\'\".format(data[\"Telephone\"]),\n \"\\'{}\\'\".format(data[\"E-mail\"])\n ) # Вставляем в таблицу полученные с резюме данные\n cursor.execute(request)\n db.commit() # Фиксируем изменения\n print('''\n \n \n \n \n \n ''') # Уведомляем пользователя о том, что данные уже добавлены и возвращаемя обратно к таблице\nelif 'exportPdfButton' in form: # Если нажата кнопка \"Экспортировать таблицу в PDF\"\n newPdf = FPDF() # Создаем pdf и добавляем шрифт для записи русских символов\n newPdf.add_font('Athena', '', 'font/new_athena_unicode.ttf', uni=True)\n cursor = db.cursor() # Создаем курсор перед выполением запроса\n cursor.execute('''\n SELECT p.surname, p.name, p.patronymic, r.region, c.city, p.telephone, p.email FROM peoples p\n JOIN regions r ON p.regionId = r.id\n JOIN cities c ON (p.cityId=c.id AND p.regionId = c.regionId)\n ''') # Получаем все данные с таблицы\n peoples = cursor.fetchall() # Забираем все найденные данные\n for i, person in enumerate(peoples): # Постепенно заполняем файл\n newPdf.add_page() # Создаем новую страницу в файле (для резюме следующего человека из списка)\n newPdf.set_font(family=\"Athena\", size=30) # Устанавливаем шрифт\n newPdf.cell(0, 10, txt=\"Резюме {}\".format(i+1), ln=1, align=\"C\") # Заголовок\n newPdf.cell(0, 10, txt=\"\", ln=1, align=\"C\") # Новая строчка\n fio = ' '.join([person[0], person[1]]) # Имя и Фамилия соединятются через пробел\n if person[2] != '-':\n fio = ' '.join([fio, person[2]]) # Если указано и отчество, то присоединяем и отчество\n newPdf.cell(0, 10, txt=fio, ln=1, align=\"C\") # Вставляем строчку с ФИО\n newPdf.set_font(family=\"Athena\", size=20) # Устанавливаем шрифт (уменьшаем размер)\n location = ''\n if person[3] != '-' and person[4] == '-':\n location = person[3]\n elif person[3] == '-' and person[4] != '-':\n location = person[4]\n else:\n location = ', '.join([person[3], person[4]])\n newPdf.cell(0, 10, txt=\"Проживает в {}\".format(location), ln=1, align=\"C\") # Вставляем строку с местом проживанием (если что-то не указано, то пропускаем его)\n if person[5] != '-':\n newPdf.cell(0, 10, txt=\"Телефон +7{}\".format(person[5]), ln=1, align=\"C\") # Если указан телефон, то добавляем в резюме\n if person[6] != '-':\n newPdf.cell(0, 10, txt=\"Почта {}\".format(person[6]), ln=1, align=\"C\") # Если указана почта, то добавляем в резюме\n newPdf.output(\"Peoples.pdf\") # Сохраняем все сформированные данные в файле pdf\n print('''\n \n \n \n \n \n ''') # Уведомляем пользователя о том, что данные уже экспортированы в Peoples.pdf и возвращаемя обратно к таблице\n","sub_path":"cgi-bin/formTableListener.py","file_name":"formTableListener.py","file_ext":"py","file_size_in_byte":12851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"340787037","text":"import logging\nimport time\nimport sys\n\nimport smpplib.gsm\nimport smpplib.client\nimport smpplib.consts\nimport config\n\n# if you want to know what's happening\nlogging.basicConfig(level='DEBUG')\n\nclient = smpplib.client.Client(config.host, config.port, allow_unknown_opt_params=True)\n\ndef handle_receive_sms(pdu):\n logging.debug('Sample dict log: %s', pdu)\n return 0 # cmd status for deliver_sm_resp\n\ndef send_message(part):\n pdu = client.send_message(\n source_addr_ton=smpplib.consts.SMPP_TON_INTL,\n source_addr=config.source_addr,\n dest_addr_ton=smpplib.consts.SMPP_TON_INTL,\n destination_addr=config.default_receiver,\n short_message=part,\n data_coding=encoding_flag,\n esm_class=msg_type_flag,\n registered_delivery=True,\n )\n\ndef listen(client):\n client.listen()\n\n# Print when obtain message_id\nclient.set_message_sent_handler(\n lambda pdu: sys.stdout.write('sent {} {}\\n'.format(pdu.sequence, pdu.message_id)))\nclient.set_message_received_handler(lambda pdu: handle_receive_sms(pdu))\n\nclient.connect()\nclient.bind_transceiver(system_id=config.system_id, password=config.password)\n\ntry:\n\tlisten(client)\nexcept:\n\ttime.sleep(600)\n\tlisten(client)\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"557091029","text":"from django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom main.models import Place\n\n\nclass CommentManager(models.Manager):\n def filter_by_instance(self, instance):\n content_type = ContentType.objects.get_for_model(instance)\n obj_id = instance.id\n qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id)\n return qs\n\n\nclass Comment(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True)\n object_id = models.PositiveIntegerField(null=True)\n content_object = GenericForeignKey('content_type', 'object_id')\n content = models.TextField()\n timestamp = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return str(self.user.username)\n\n objects = CommentManager()\n","sub_path":"mainproject/comments/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"652282885","text":"import psycopg2\nimport base64\nimport os\nfrom python.Utils import get_images_label\nfrom psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT\nfrom psycopg2.sql import Identifier, SQL\n\ncursor = \"\"\n\n\ndef create_filled_tables():\n for image_label in get_images_label():\n cursor.execute(SQL(\"CREATE TABLE {} (id SERIAL, data BYTEA)\").format(Identifier(image_label)))\n files = next(os.walk(os.getcwd() + \"\\\\assets\\\\img\\\\\" + image_label))[2]\n location = \"assets/img/\" + image_label + \"/\"\n for file in files:\n with open(location + file, \"rb\") as img:\n data = base64.b64encode(img.read())\n cursor.execute(SQL(\"INSERT INTO {} (data) VALUES (%s)\").format(Identifier(image_label)), [data])\n\n\ndef get_data_from_db(label):\n cursor.execute(SQL(\"SELECT data FROM {} ORDER BY random() limit 30\").format(Identifier(label)))\n return cursor.fetchall()\n\n\ndef connect():\n global cursor\n con = psycopg2.connect(database=\"\", user=\"\",\n password=\"\",\n host=\"\", port=\"5432\")\n con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n cursor = con.cursor()\n","sub_path":"python/Database.py","file_name":"Database.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"38613604","text":"# Copyright (c) 2013, 2018 National Technology and Engineering Solutions of Sandia, LLC . Under the terms of Contract\n# DE-NA0003525 with National Technology and Engineering Solutions of Sandia, LLC, the U.S. Government\n# retains certain rights in this software.\n\n#!/usr/bin/env python\n\nimport os\nimport subprocess\n\nenabled_plugins = \"/etc/munin/plugins\"\nplugin_storage = \"/usr/share/munin/plugins\"\nconf_storage = \"/etc/munin/plugin-conf.d\"\ncontext = \"system_u:object_r:munin_unconfined_plugin_exec_t:s0\"\n\nfor plugin in [\"couchdb-availability\", \"couchdb-request-times\", \"slycat-availability\", \"slycat-files\", \"slycat-memory\", \"slycat-threads\", \"slycat-requests\"]:\n subprocess.check_call([\"cp\", plugin, plugin_storage])\n subprocess.check_call([\"chown\", \"root:root\", os.path.join(plugin_storage, plugin)])\n subprocess.check_call([\"chmod\", \"755\", os.path.join(plugin_storage, plugin)])\n subprocess.check_call([\"chcon\", context, os.path.join(plugin_storage, plugin)])\n subprocess.check_call([\"ln\", \"-sf\", os.path.join(plugin_storage, plugin), os.path.join(enabled_plugins, plugin)])\n\nfor conf in [\"slycat.conf\", \"slycat-files.conf\", \"slycat-requests.conf\"]:\n subprocess.check_call([\"cp\", conf, conf_storage])\n\nsubprocess.check_call([\"/etc/init.d/munin-node\", \"restart\"])\n","sub_path":"munin-plugins/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"525260055","text":"# Copyright CERFACS (http://cerfacs.fr/)\n# Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n#\n# Author: Natalia Tatarinova\n\nfrom datetime import datetime\n\n\n# set the global attributs \"title\", \"history\", \"reference\", \"institution\" and \"comment\" in output meta data\n# (the minimum set of global attributes recomended by CF: http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.4/cf-conventions.html)\n\n\ndef title(out_nc, indice_name):\n '''\n Set the global attribute \"title\" in output meta data\n \n :param out_nc: out NetCDF dataset\n :type out_nc: netCDF4.Dataset\n :param indice_name: name of indice \n :type indice_name: str\n \n '''\n \n if indice_name in ['TG', 'TX', 'TN', 'DTR', 'ETR', 'vDTR']:\n indice_group = 'temperature'\n elif indice_name in ['SU', 'TR', 'CSU', 'TXx', 'TNx', 'TG90p', 'TX90p', 'TN90p', 'WSDI']:\n indice_group = 'heat'\n elif indice_name in ['GD4', 'GSL', 'FD', 'CFD', 'HD17','ID', 'TXn', 'TNn', 'TG10p', 'TX10p', 'TN10p', 'CSDI']:\n indice_group = 'cold'\n elif indice_name in ['CDD']:\n indice_group = 'drought' \n elif indice_name in ['PRCPTOT', 'RR1', 'SDII', 'CWD', 'R10mm', 'R20mm', 'RX1day', 'RX5day', 'R75p', 'R95p', 'R99p', 'R75pTOT', 'R95pTOT', 'R99pTOT']:\n indice_group = 'rain'\n elif indice_name in ['SD','SD1', 'SD5cm', 'SD50cm']:\n indice_group = 'snow'\n elif indice_name in ['CD','CW', 'WD', 'WW']:\n indice_group = 'compound'\n \n # example: title: ECA heat indice SU\n title_str = 'ECA {0} indice {1}'.format(indice_group, indice_name)\n\n out_nc.setncattr('title', title_str)\n \ndef history(out_nc, calc_grouping, indice_name, time_range):\n '''\n Set the global attribute \"title\" in output meta data\n \n :param out_nc: out NetCDF dataset\n :type out_nc: netCDF4.Dataset\n :param calc_grouping: temporal grouping to apply for calculations\n :type calc_grouping: list of str or int\n :param indice_name: name of indice \n :type indice_name: str\n :param time_range: upper and lower bounds for time dimension subsetting\n :type time_range:[datetime.datetime, datetime.datetime]\n \n \n '''\n\n current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n dt1 = time_range[0]\n dt2 = time_range[1]\n \n dt1_str = '{0}-{1}-{2}'.format(dt1.year, dt1.month, dt1.day)\n dt2_str = '{0}-{1}-{2}'.format(dt2.year, dt2.month, dt2.day)\n\n # make an attempt to select the mode from a seasonal grouping object\n try:\n mode = calc_grouping.icclim_mode\n # if this attribute does not exist, attempt to identify the grouping through other comparisons methods\n except AttributeError:\n ## use sets to allow different orderings\n if set(calc_grouping) == set(['year','month']):\n mode = 'monthly time series'\n ## always convert to list before comparison in case a tuple is passed\n elif list(calc_grouping) == ['year']:\n mode = 'annual'\n elif list(calc_grouping) == ['month']:\n mode = 'monthly climatology'\n else:\n mode = str(calc_grouping)\n # etc ...\n \n # example of history_str: 2012-10-02 15:30:20 Calculation of SU indice (monthly) from 1960-01-01 to 1990-12-31.\n history_str = '{0} Calculation of {1} indice ({2}) from {3} to {4}.'.format(current_time, indice_name, mode, dt1_str, dt2_str)\n\n out_nc.setncattr('history', getattr(out_nc,'history') + ' \\n' + history_str)\n \ndef history2(out_nc, calc_grouping, indice_name, time_range):\n '''\n Set the global attribute \"title\" in output meta data\n \n :param out_nc: out NetCDF dataset\n :type out_nc: netCDF4.Dataset\n :param calc_grouping: temporal grouping to apply for calculations\n :type calc_grouping: list of str or int\n :param indice_name: name of indice \n :type indice_name: str\n :param time_range: upper and lower bounds for time dimension subsetting\n :type time_range:[datetime.datetime, datetime.datetime]\n \n \n '''\n\n current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n dt1 = time_range[0]\n dt2 = time_range[1]\n \n dt1_str = '{0}-{1}-{2}'.format(dt1.year, dt1.month, dt1.day)\n dt2_str = '{0}-{1}-{2}'.format(dt2.year, dt2.month, dt2.day)\n \n if calc_grouping == 'year':\n mode = 'annual time series'\n elif calc_grouping == 'month':\n mode = 'monthly time series'\n elif calc_grouping == 'DJF':\n mode = 'winter time series'\n elif calc_grouping == 'MAM':\n mode = 'spring time series'\n elif calc_grouping == 'JJA':\n mode = 'summer time series'\n elif calc_grouping == 'SON':\n mode = 'autumn time series'\n elif calc_grouping == 'ONDJFM':\n mode = 'winter half-year time series'\n elif calc_grouping == 'AMJJAS':\n mode = 'summer half-year time series'\n elif type(calc_grouping) is list:\n if calc_grouping[0]=='month':\n months = calc_grouping[1]\n mode = 'monthly time series (months: ' + str(months) + ')' \n elif calc_grouping[0]=='season':\n months_season = calc_grouping[1]\n if type(months_season) is list: \n season = months_season\n elif type(months_season) is tuple:\n season = months_season[0]+months_season[1]\n mode = 'seasonal time series (season: ' + str(season) + ')' \n \n else:\n raise(NotImplementedError(calc_grouping))\n # etc ...\n \n # example of history_str: 2012-10-02 15:30:20 Calculation of SU indice (monthly) from 1960-01-01 to 1990-12-31.\n history_str = '{0} Calculation of {1} indice ({2}) from {3} to {4}.'.format(current_time, indice_name, mode, dt1_str, dt2_str)\n\n out_nc.setncattr('history', getattr(out_nc,'history') + ' \\n' + history_str) # ? \n\n\ndef references(out_nc):\n '''\n Set the global attribute \"references\" in output meta data\n \n :param out_nc: out NetCDF dataset\n :type out_nc: netCDF4.Dataset\n \n '''\n \n references_str = 'ATBD of the ECA indices calculation (http://eca.knmi.nl/documents/atbd.pdf)'\n out_nc.setncattr('references', references_str)\n\n\ndef institution(out_nc, institution_str):\n '''\n Set the global attribute \"institution\" in output meta data\n \n :param out_nc: out NetCDF dataset\n :type out_nc: netCDF4.Dataset\n :param institution_str: institution which uses this library\n :type institution_str: str\n \n '''\n \n #institution_str = 'Climate impact portal (http://climate4impact.eu)'\n \n out_nc.setncattr('institution', institution_str)\n \n \ndef comment(out_nc, indice_name):\n '''\n Set the global attribute \"comment\" in output meta data\n \n :param out_nc: out NetCDF dataset\n :type out_nc: netCDF4.Dataset\n \n Note: will be defined for several indices, else will be empty\n \n '''\n \n if indice_name == 'GSL':\n comment_str = 'This indice is defined only for the northern hemisphere'\n \n # elif ...\n \n # elif ...\n \n # etc\n \n else:\n comment_str = ' '\n \n out_nc.setncattr('comment', comment_str)\n","sub_path":"icclim/set_globattr.py","file_name":"set_globattr.py","file_ext":"py","file_size_in_byte":7137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"459074431","text":"# Pyrogram - Telegram MTProto API Client Library for Python\n# Copyright (C) 2017-2018 Dan Tès \n#\n# This file is part of Pyrogram.\n#\n# Pyrogram is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser 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# Pyrogram is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with Pyrogram. If not, see .\n\nfrom pyrogram.api.core import Object\n\n\nclass PhotoSize(Object):\n \"\"\"This object represents one size of a photo or a file / sticker thumbnail.\n\n Args:\n file_id (``str``):\n Unique identifier for this file.\n\n width (``int``):\n Photo width.\n\n height (``int``):\n Photo height.\n\n file_size (``int``, *optional*):\n File size.\n\n date (``int``, *optional*):\n Date the photo was sent in Unix time\n \"\"\"\n\n ID = 0xb0700005\n\n def __init__(self, file_id, width, height, file_size=None, date=None):\n self.file_id = file_id # string\n self.width = width # int\n self.height = height # int\n self.file_size = file_size # flags.0?int\n self.date = date\n","sub_path":"ENV/lib/python3.5/site-packages/pyrogram/client/types/photo_size.py","file_name":"photo_size.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"325179916","text":"from django.http import HttpResponseForbidden\nfrom django.shortcuts import get_object_or_404\nfrom django.urls import resolve\n\nimport waffle\nfrom project.models import ProjectTeam, Issue, Project\nfrom re import compile\n\nPROJECT_URLS = [compile(r'^project/.+')]\nISSUE_ORDER = compile(r'^project/issue_order/$')\n\n\nclass CheckProjectRelation(object):\n def __init__(self, get_response):\n self.get_response = get_response\n\n def is_user_attached_to_project(self, user_id, project_id):\n user_project_team = ProjectTeam.objects.filter(project_id=project_id, employees=user_id)\n if user_project_team:\n return True\n else:\n get_object_or_404(Project, pk=project_id)\n return False\n\n def __call__(self, request):\n path = request.path_info.lstrip('/')\n if request.user.is_staff or \\\n not any(m.match(path) for m in PROJECT_URLS):\n response = self.get_response(request)\n return response\n\n if waffle.flag_is_active(request, 'create_team') and path == 'project/create/':\n return self.get_response(request)\n\n resolved = resolve(request.path)\n if resolved.kwargs.get('project_id', False):\n if self.is_user_attached_to_project(request.user.id,\n resolved.kwargs['project_id']):\n response = self.get_response(request)\n return response\n\n if request.method == 'POST':\n response = self.get_response(request)\n return response\n\n return HttpResponseForbidden()\n","sub_path":"Jiller/middleware/CheckProjectRelationMiddleware.py","file_name":"CheckProjectRelationMiddleware.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"438134608","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport time\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nfrom openpyxl import Workbook, load_workbook\nfrom os.path import exists\nfrom datetime import datetime\nimport re\nimport string\nfrom openpyxl.styles import PatternFill, Color\n\ndef is_digit(str):\n try:\n tmp = float(str)\n return True\n except ValueError:\n return False\n\ntoday = datetime.now()\ntodayDate = today.strftime('%Y-%m-%d')\nMonthDate = today.strftime('%Y-%m')\ntodayCnt = int(today.strftime('%d'))\n\n#work_path = 'C:/study/python/chubb/'\nwork_path = 'D:/dev/python/chubb/'\n\ntoday_file_name = 'TaskToClose_' + MonthDate + '.xlsx'\nfile_path = work_path + today_file_name\n\nif exists(file_path):\n result_xlsx = load_workbook(file_path)\n worksheet = result_xlsx.active\n\nelse:\n result_xlsx = Workbook()\n worksheet = result_xlsx.active\n worksheet.append(['중분류', '소분류', 'ServiceNow', '등록일', '예상작업기간', '상태', '실제작업기간', '진행율', 'MM', '담당팀', '담당자', '요청자','datetime'])\n\n\n\nchg_file_name = 'ChangeToClose_' + MonthDate + '.xlsx'\nchg_file_path = work_path + chg_file_name\n\nif exists(chg_file_path):\n chg_xlsx = load_workbook(chg_file_path)\n chg_sheet = chg_xlsx.active\n\nelse:\n chg_xlsx = Workbook()\n chg_sheet = chg_xlsx.active\n chg_sheet.append(['중분류', '소분류', 'ServiceNow', '등록일', '예상작업기간', '상태', '실제작업기간', '진행율', 'MM', '담당팀', '담당자', '요청자','datetime'])\n\n# driver = webdriver.Chrome('D:\\dev\\python\\chromedriver')\ndriver = webdriver.Chrome(work_path + 'chromedriver')\n\ninput_sdesc = '' # 제목\ncno_text = '' # 콜번호\nopened_t = '' # 요청일시\ncaller_t = '' # 요청자\nworkguy = '' # 담당자\nrequestNo = '' # Request번호\nisApproved = ''\ndoneYN = ''\ntransferDate = ''\netc = '' # 오류 내용\noriDesc = '' # 요청내용\nCALL_URL = ''\nREQ_URL = ''\nIT_worker = ''\ntitleM = '' #중분류\ndoneDate = '' # 처리일\nclickLabel = 'ChangeToClose'\n#clickLabel = 'TaskToCloseAll'\n\ntry:\n driver.get('https://chubb.service-now.com')\n\n elem = driver.find_element_by_id('username')\n elem.send_keys('jsmoon')\n\n elem = driver.find_element_by_id('password')\n elem.send_keys('Niceday77')\n # elem.send_keys(open('password').read().strip())\n elem.send_keys(Keys.RETURN)\n\n elem = driver.find_element_by_name('securityCode')\n inputKey = input()\n elem.send_keys(inputKey)\n elem.send_keys(Keys.RETURN)\n\n # 아이프레임이 로딩 끝나기를 ��다린다.\n iframe = driver.find_element_by_id('gsft_main')\n driver.switch_to.frame(iframe)\n\n WebDriverWait(driver, 60).until(\n # By.ID 는 ID로 검색, By.CSS_SELECTOR 는 CSS Selector 로 검색\n EC.presence_of_element_located((By.ID, \"sysparm_page_num\"))\n )\n\n waitingTime = 0\n\n # 여기서 부터 반복~~~\n while 1:\n time.sleep(waitingTime)\n\n # favorites tab 클릭\n driver.switch_to.default_content()\n WebDriverWait(driver, 60).until(\n EC.element_to_be_clickable((By.ID, \"favorites_tab\"))\n )\n\n driver.find_element_by_xpath('//a[@id=\"favorites_tab\"]').click()\n\n wait = WebDriverWait(driver, 60)\n cond = EC.element_to_be_clickable((By.LINK_TEXT, clickLabel))\n btn = wait.until(cond)\n btn.click()\n\n iframe = driver.find_element_by_id('gsft_main')\n driver.switch_to.frame(iframe)\n\n list_body = driver.find_element_by_class_name('list2_body')\n elems = list_body.find_elements_by_xpath('//tr[contains(@id,\"row_\")]')\n\n # 처리할 대상\n cno_t = ''\n cno_text = ''\n tag_t = ''\n caller_t = ''\n desc_t = ''\n doneYN = 'N'\n workguy = ''\n doneDate = ''\n taskType = ''\n isDB = ''\n isApp = ''\n isClose = ''\n state = ''\n\n for elem in elems:\n\n taskType = ''\n isDB = ''\n isApp = ''\n isClose = ''\n titleM = ''\n cno_text = ''\n state = ''\n cno_t = ''\n\n cno = elem.find_element_by_xpath('.//a[@class=\"linked formlink\"]')\n\n clink = cno.get_attribute('href')\n desc = elem.find_element_by_xpath('./td[4]')\n desc_chk = desc.text\n desc_chk = desc_chk.lower()\n cno_text = cno.text\n\n workguy = elem.find_element_by_xpath('./td[5]/a').text # 담당자\n caller_t = elem.find_element_by_xpath('./td[6]/a').text # 요청자\n state = elem.find_element_by_xpath('./td[7]').text # 상태\n #print('workguy:'+workguy)\n #print('caller_t:' + caller_t)\n #print('desc_chk:' + desc_chk)\n\n if cno_text.startswith('SCTASK'):\n taskType = 'SCTASK'\n if cno_text.startswith('CTASK'):\n taskType = 'CTASK'\n if cno_text.startswith('CHG'):\n taskType = 'CHG'\n if cno_text.startswith('INC'):\n taskType = 'INC'\n\n # 반영건 종료 대상 판단\n if (taskType == 'CTASK' and state == 'In Progress' and 'app완' in desc_chk and workguy in ['In-Moo Lee', 'Jin-Sung Moon']):\n print(\"111 taskNo:\" + cno_text)\n isClose = 'Y'\n isApp = 'Y'\n titleM = '소스반영'\n elif (taskType == 'CTASK' and state == 'In Progress' and 'db완' in desc_chk and 'app완' in desc_chk and workguy in ['Yong-Keum Kim']):\n print(\"222 taskNo:\" + cno_text)\n isClose = 'Y'\n isDB = 'Y'\n titleM = 'DB반영'\n elif '(선처리)' in desc_chk or '(완료)' in desc_chk or '[완료]' in desc_chk or '[완]' in desc_chk or '(완)' in desc_chk or '[처리완료]' in desc_chk:\n print(\"333 taskNo:\" + cno_text)\n isClose = 'Y'\n elif taskType == 'CHG' and (state == 'Review' or state == 'Scheduled') :\n print(\"CHG 처리대상:\" + cno_text)\n isClose = 'Y'\n\n # 중분류\n if taskType == 'CTASK' and 'app완' in desc_chk :\n isApp = 'Y'\n titleM = '소스반영'\n if taskType == 'CTASK' and 'db완' in desc_chk:\n isDB = 'Y'\n titleM = 'DB반영'\n\n\n\n if isClose:\n cno_t = cno\n # caller_t = caller.text\n desc_t = desc.text\n CALL_URL = clink\n # opened_t = opened.text\n print(\"taskNo:\" + cno.text)\n #print(CALL_URL)\n break\n\n\n # 담당자 지정건 없으면 종료\n if not isClose:\n #waitingTime = 60\n\n if clickLabel == 'ChangeToClose':\n\n clickLabel = 'TaskToCloseAll'\n else:\n clickLabel = 'ChangeToClose'\n\n print('------ 대상없음 '+clickLabel+'로 전환!! ------')\n\n continue\n\n\n waitingTime = 0\n\n # 하단 페이지 타이밍 로딩 기다리기\n WebDriverWait(driver, 60).until(\n EC.element_to_be_clickable((By.ID, \"page_timing_div\"))\n )\n\n # 요청서 번호 클릭\n cno_t.click()\n\n # Work notes 입력란 표시까지 대기\n WebDriverWait(driver, 60).until(\n EC.presence_of_element_located((By.ID, \"activity-stream-textarea\"))\n )\n\n if taskType == 'SCTASK':\n print('-------------SCTASK--------------')\n\n RequestedFor = driver.find_element_by_xpath(\"//input[@id='sys_display.sc_task.request_item.request.requested_for']\")\n AssignedTo = driver.find_element_by_xpath(\"//*[@id='sys_display.sc_task.assigned_to']\")\n ExpectedStart = driver.find_element_by_xpath(\"//*[@id='sc_task.expected_start']\")\n ChangedDate = driver.find_element_by_xpath(\"//*[@id='sn_form_inline_stream_entries']/ul/li[1]/div[2]/span/div[1]\")\n ShortDesc = driver.find_element_by_xpath(\"//input[@id='sc_task.short_description']\")\n Description = driver.find_element_by_xpath(\"//*[@id='sc_task.description']\")\n\n input_sdesc = ShortDesc.get_attribute('value')\n #opened_t = ExpectedStart.get_attribute('value')\n changedDate_t = ChangedDate.text\n IT_worker = AssignedTo.get_attribute('value')\n caller_t = RequestedFor.get_attribute('value')\n oriDesc = Description.get_attribute('value')\n\n #print(input_sdesc)\n #print(opened_t)\n #print(changedDate_t)\n #print(IT_worker)\n #print(caller_t)\n #print(oriDesc)\n\n tmpDesc = oriDesc.lower()\n\n for s_word in ['이용건수','수급권','한도초과','한도 초과','배서불가','담보삭제','강제배서', '강제 배서', '계약상태', '계약 상태','피보험자 오류','피보험자 수','고객번호','고객 번호','pos','cpc','보험시작일 변경','피보험자업로드','계좌 변경','webfax','피보험자 수정','단체 피보험자','출력물','피보험자 이름변경']:\n if s_word in tmpDesc:\n titleM = '계속계약'\n break\n for s_word in ['dc code', 'producer code', '머리디안', 'meridian','pacpl']:\n if s_word in tmpDesc:\n titleM = '머리디안'\n break\n for s_word in ['지연일수','보험금','응급실','지급일','claim','보상','출재']:\n if s_word in tmpDesc:\n titleM = '보상'\n break\n for s_word in ['상품복사','상품개정','개정상품','판매제한','판매플랜','마케팅플랜','상품복사','상품 복사','plan 복사','plan복사','pve','플랜코드','담보 명칭 변경']:\n if s_word in tmpDesc:\n titleM = '상품'\n break\n for s_word in ['수당']:\n if s_word in tmpDesc:\n titleM = '수당'\n break\n for s_word in ['즉시이체','환급목록','거래자료','거래 자료','가상계좌','캠페인 소급','시책','수수료','결제','입출금','환급금','가마감']:\n if s_word in tmpDesc:\n titleM = '입출금'\n break\n for s_word in ['입사자','수수료 정산 종료일','권한 부여','권한부여','id등록','id 등록','발령','전배','사용자명','맥 추가','mac 추가','수신인','겸직','개명','권한삭제','권한 삭제','권한','해촉','퇴사','조직']:\n if s_word in tmpDesc:\n titleM = '조직'\n break\n for s_word in ['청약','갱신','단체','포괄번호']:\n if s_word in tmpDesc:\n titleM = '청약'\n break\n\n if not titleM:\n titleM = '기타'\n\n if opened_t:\n opened_t = opened_t[:10]\n\n if not opened_t:\n opened_t = changedDate_t[:10]\n\n opened_t = opened_t.replace(\"-\", \".\")\n # 완료일자\n items = re.findall('처리일자\\s\\s:\\s([^\\n]+)', tmpDesc)\n if len(items) > 0:\n doneDate = items[0]\n #work_period = datetime.now().strftime('%m.%d') + '~' + datetime.now().strftime('%m.%d')\n\n print('titleM:'+titleM)\n print('doneDate:(' + doneDate+')')\n\n if doneDate:\n work_period = doneDate + '~' + doneDate\n\n # 처리일자를 기재하지 않으면 요청일자를 처리일로 셋팅\n if not doneDate:\n work_period = opened_t[5:] + '~' + opened_t[5:]\n\n print(work_period)\n\n # 요청일자\n reqDate = ''\n items = re.findall('요청일자\\s\\s:\\s([^\\n]+)', tmpDesc)\n if len(items) > 0:\n reqDate = items[0]\n reqDate = reqDate.replace('-','.')\n\n print('reqDate:(' + reqDate + ')')\n\n if reqDate:\n opened_t = reqDate\n\n # 엑셀쓰기\n worksheet.append([titleM, input_sdesc, cno_text, opened_t, work_period, '완료', work_period, '100', '-', 'OPR', IT_worker, caller_t, datetime.now()])\n #worksheet.cell(5, (12 + todayCnt), '○')\n #ca2 = worksheet['R6']\n #ca2.fill = PatternFill(patternType='solid', fgColor=Color('00B0F0'))\n result_xlsx.save(file_path)\n\n # Work notes 입력란 표시까지 대기\n WebDriverWait(driver, 60).until(\n EC.visibility_of_element_located((By.ID, \"activity-stream-textarea\"))\n )\n # Work notes 입력\n driver.find_element_by_xpath(\"//textarea[@id='activity-stream-textarea']\").send_keys('Completed')\n\n # Close 버튼 클릭\n driver.find_element_by_xpath(\"//*[@id='close_sc_task']\").click()\n\n if taskType == 'CTASK':\n print('-------반영건-------CTASK----------------')\n\n AssignedTo = driver.find_element_by_xpath(\"//*[@id='sys_display.change_task.assigned_to']\")\n IT_worker = AssignedTo.get_attribute('value')\n ShortDesc = driver.find_element_by_xpath(\"//input[@id='change_task.short_description']\")\n input_sdesc = ShortDesc.get_attribute('value')\n\n planned_start_date = driver.find_element_by_xpath(\"//input[@id='change_task.planned_start_date']\")\n planned_end_date = driver.find_element_by_xpath(\"//input[@id='change_task.planned_end_date']\")\n planStartDate = planned_start_date.get_attribute('value')\n planEndDate = planned_end_date.get_attribute('value')\n print('planStartDate:'+planStartDate)\n print('planEndDate:' + planEndDate)\n\n ori_start_date = driver.find_element_by_xpath(\"//input[@id='sys_original.change_task.change_request.start_date']\")\n ori_end_date = driver.find_element_by_xpath(\"//input[@id='sys_original.change_task.change_request.end_date']\")\n oriStartDate = ori_start_date.get_attribute('value')\n oriEndDate = ori_end_date.get_attribute('value')\n print('oriStartDate:'+oriStartDate)\n print('oriEndDate:' + oriEndDate)\n\n if not planStartDate:\n planned_start_date.send_keys(oriStartDate)\n if not planEndDate:\n planned_end_date.send_keys(oriEndDate)\n\n if not titleM:\n titleM = 'DB작업'\n\n\n elems = driver.find_elements_by_xpath('//*[@class=\"h-card h-card_md h-card_comments\"]')\n i = 1\n max_e = len(elems)\n print('elems len: ' + str(max_e))\n for elem in elems:\n\n e_createdby = elem.find_element_by_xpath('.//*[@class=\"sn-card-component-createdby\"]')\n print('e_createdby:'+e_createdby.text)\n e_date = elem.find_element_by_xpath('.//*[@class=\"date-calendar\"]')\n print('e_date:'+e_date.text)\n '''\n if i == 1: # 완료일도 그냥 최초 작성일로 설정.\n doneDate = e_date.text\n doneDate = doneDate[5:10]\n doneDate = doneDate.replace(\"-\", \".\")\n '''\n if i == max_e: #최초작성일\n opened_t = e_date.text\n opened_t = opened_t[:10]\n opened_t = opened_t.replace(\"-\", \".\")\n\n doneDate = e_date.text\n doneDate = doneDate[5:10]\n doneDate = doneDate.replace(\"-\", \".\")\n\n caller_t = e_createdby.text\n i = i + 1\n\n\n # short desc에 종료일자 있으면 검사 ex) [완료][6.17]\n if input_sdesc:\n print('shortDesc:' + input_sdesc)\n\n # 완료일자\n items = re.findall('\\[([^]]+)', input_sdesc)\n\n for itm in items:\n itm = itm.replace('/', '.')\n\n if is_digit(itm) and len(itm) <= 5:\n doneDate = itm\n print('doneDate:' + doneDate)\n break\n\n\n print('opened_t:' + opened_t)\n print('doneDate:' + doneDate)\n work_period = doneDate + '~' + doneDate\n\n print('work_period:' + work_period)\n print('input_sdesc:' + input_sdesc)\n print('IT_worker:' + IT_worker)\n print('caller_t:' + caller_t)\n\n # 엑셀쓰기\n if isApp and isDB:\n worksheet.append(\n ['소스반영', input_sdesc, cno_text, opened_t, work_period, '완료', work_period, '100', '-', 'OPR',\n IT_worker, caller_t, datetime.now()])\n worksheet.append(\n ['DB반영', desc_t, cno_text, opened_t, work_period, '완료', work_period, '100', '-', 'OPR',\n 'Yong-Keum Kim',\n caller_t, datetime.now()])\n result_xlsx.save(file_path)\n else:\n worksheet.append(\n [titleM, input_sdesc, cno_text, opened_t, work_period, '완료', work_period, '100', '-', 'OPR',\n IT_worker,\n caller_t, datetime.now()])\n result_xlsx.save(file_path)\n\n\n # Close notes 입력란 표시까지 대기\n WebDriverWait(driver, 60).until(\n EC.visibility_of_element_located((By.ID, \"change_task.close_notes\"))\n )\n # Close code 선택\n driver.find_element_by_xpath(\"//option[@value='successful']\").click()\n # Close notes 입력\n close_notes = driver.find_element_by_xpath(\"//textarea[@id='change_task.close_notes']\")\n if not close_notes.text:\n close_notes.send_keys('Completed')\n\n # Close 버튼 클릭\n butts = driver.find_elements_by_xpath(\"//button[@id='change_task_to_closed']\")\n butt = butts[1]\n # print(butt.text)\n butt.click()\n #input()\n if taskType == 'CHG':\n # Close notes 입력란 표시까지 대기\n WebDriverWait(driver, 60).until(\n EC.visibility_of_element_located((By.ID, \"change_request.close_notes\"))\n )\n\n print('state:'+state)\n\n # 종료처리\n if state == 'Review':\n # Actual start end 입력\n planned_start_date = driver.find_element_by_xpath(\"//input[@id='change_request.work_start']\")\n planned_end_date = driver.find_element_by_xpath(\"//input[@id='change_request.work_end']\")\n planStartDate = planned_start_date.get_attribute('value')\n planEndDate = planned_end_date.get_attribute('value')\n print('Actual start date:' + planStartDate)\n print('Actual end date:' + planEndDate)\n\n ori_start_date = driver.find_element_by_xpath(\"//input[@id='change_request.start_date']\")\n ori_end_date = driver.find_element_by_xpath(\"//input[@id='change_request.end_date']\")\n oriStartDate = ori_start_date.get_attribute('value')\n oriEndDate = ori_end_date.get_attribute('value')\n print('oriStartDate:' + oriStartDate)\n print('oriEndDate:' + oriEndDate)\n\n if not planStartDate:\n planned_start_date.send_keys(oriStartDate)\n if not planEndDate:\n planned_end_date.send_keys(oriEndDate)\n\n AssignedTo = driver.find_element_by_xpath(\"//*[@id='sys_display.change_request.assigned_to']\")\n IT_worker = AssignedTo.get_attribute('value')\n ShortDesc = driver.find_element_by_xpath(\"//input[@id='change_request.short_description']\")\n input_sdesc = ShortDesc.get_attribute('value')\n RequestedBy = driver.find_element_by_xpath(\"//input[@id='sys_display.change_request.requested_by']\")\n caller_t = RequestedBy.get_attribute('value')\n\n # 활동이력\n elems = driver.find_elements_by_xpath('//*[@class=\"h-card h-card_md h-card_comments\"]')\n i = 1\n max_e = len(elems)\n print('elems len: ' + str(max_e))\n for elem in elems:\n\n e_createdby = elem.find_element_by_xpath('.//*[@class=\"sn-card-component-createdby\"]')\n #print('e_createdby:' + e_createdby.text)\n e_date = elem.find_element_by_xpath('.//*[@class=\"date-calendar\"]')\n #print('e_date:' + e_date.text)\n\n if i == 1: # 완료일\n doneDate = e_date.text\n doneDate = doneDate[5:10]\n doneDate = doneDate.replace(\"-\", \".\")\n\n if i == max_e: # 최초작성일\n opened_t = e_date.text\n opened_t = opened_t[:10]\n opened_t = opened_t.replace(\"-\", \".\")\n #caller_t = e_createdby.text\n i = i + 1\n work_period = doneDate + '~' + doneDate\n\n if not titleM:\n titleM = '종료처리'\n\n chg_sheet.append(\n [titleM, input_sdesc, cno_text, opened_t, work_period, '완료', work_period, '100', '-', 'OPR',\n IT_worker,\n caller_t, datetime.now()])\n chg_xlsx.save(chg_file_path)\n\n # Close code 선택\n driver.find_element_by_xpath(\"//option[@value='successful']\").click()\n # Close notes 입력\n driver.find_element_by_xpath(\"//textarea[@id='change_request.close_notes']\").send_keys('Completed')\n # Close 버튼 클릭\n butts = driver.find_elements_by_xpath(\"//button[@id='state_model_move_to_closed']\")\n butt = butts[1]\n # print(butt.text)\n\n #input() #################### test\n\n\n butt.click()\n # close 버튼이 사라질때까지 기다린다.\n WebDriverWait(driver, 60).until(\n EC.invisibility_of_element_located((By.XPATH, \"//button[@id='state_model_move_to_closed']\"))\n )\n # implement 처리\n if state == 'Scheduled':\n # implement 버튼 클릭\n butts = driver.find_elements_by_xpath(\"//button[@id='state_model_move_to_implement']\")\n butt = butts[1]\n butt.click()\n # close 버튼이 사라질때까지 기다린다.\n WebDriverWait(driver, 60).until(\n EC.invisibility_of_element_located((By.XPATH, \"//button[@id='state_model_move_to_implement']\"))\n )\n\n\nexcept Exception as e:\n print('----------- Main Error -------------')\n print(e)\n etc = str(e)\n worksheet.append(\n [input_sdesc, cno_text, oriDesc, opened_t, caller_t, workguy, requestNo, datetime.now(), etc, CALL_URL,\n REQ_URL])\n result_xlsx.save(file_path)\nfinally:\n print('~~~~~~~~~~ Main END ~~~~~~~~~~~~!')\n input()\n driver.quit()\n","sub_path":"TaskToClose.py","file_name":"TaskToClose.py","file_ext":"py","file_size_in_byte":23863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"78080622","text":"from typing import List\nimport collections\n\nclass Solution:\n def canCross(self, stones: List[int]) -> bool:\n pastJumps = {x: set() for x in stones}\n pastJumps[0].add(0)\n \n for i in stones:\n for k in pastJumps[i]:\n for s in [k - 1, k, k + 1]:\n if s > 0 and i + s in pastJumps:\n pastJumps[i + s].add(s)\n \n return bool(pastJumps[stones[-1]])\n \n def canCross1(self, stones: List[int]) -> bool:\n pastJumps = collections.defaultdict(set)\n pastJumps[0] = {0}\n \n for i in range(1, len(stones)):\n newJumps = collections.defaultdict(set)\n for last, jumps in pastJumps.items():\n j = stones[i] - last\n \n if j in jumps or j + 1 in jumps or j - 1 in jumps:\n newJumps[stones[i]].add(j)\n \n pastJumps.update(newJumps)\n \n return len(pastJumps[stones[-1]]) != 0","sub_path":"leetcode/403-Frog-Jump.py","file_name":"403-Frog-Jump.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"351296938","text":"import re\nimport string\nimport collections as cll\nfrom scipy.stats import kendalltau\nimport math\nimport subprocess\n\n\nclass Bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n @classmethod\n def postprocess(cls, input_str):\n input_str = input_str.replace(\"\", cls.HEADER)\n input_str = input_str.replace(\"\", cls.OKBLUE)\n input_str = input_str.replace(\"\", cls.OKGREEN)\n input_str = input_str.replace(\"\", cls.WARNING)\n input_str = input_str.replace(\"\", cls.FAIL)\n input_str = input_str.replace(\"\", cls.ENDC)\n input_str = input_str.replace(\"\", cls.BOLD)\n input_str = input_str.replace(\"\", cls.UNDERLINE)\n return input_str\n\n\ndef print_counter(counts, prefix=\"\"):\n keys = list(counts.keys())\n keys.sort()\n for key in keys:\n print(\"{}{} = {:d} / {:d} ({:.2f}%)\".format(prefix, key, counts[key], sum(counts.values()), counts[key] * 100 / sum(counts.values())))\n\ndef get_bucket(x, thresholds):\n bucket = -1\n for flt in thresholds:\n if x >= flt:\n bucket += 1\n else:\n break\n return bucket\n\n\ndef get_kendall_tau(x1, x2):\n x1 = normalize_answer(x1)\n x2 = normalize_answer(x2)\n\n x1_tokens = x1.split()\n x2_tokens = x2.split()\n\n for x1_index, tok in enumerate(x1_tokens):\n try:\n x2_index = x2_tokens.index(tok)\n x1_tokens[x1_index] = \"-{:d}\".format(x1_index + 1)\n x2_tokens[x2_index] = \"-{:d}\".format(x1_index + 1)\n except ValueError:\n pass\n\n common_seq_x1 = [int(x1_tok_flag.split(\"-\")[-1]) for x1_tok_flag in x1_tokens if x1_tok_flag.startswith(\"\")]\n common_seq_x2 = [int(x2_tok_flag.split(\"-\")[-1]) for x2_tok_flag in x2_tokens if x2_tok_flag.startswith(\"\")]\n\n assert len(common_seq_x1) == len(common_seq_x2)\n\n ktd = kendalltau(common_seq_x1, common_seq_x2).correlation\n anomaly = False\n\n if math.isnan(ktd):\n ktd = -1.0\n anomaly = True\n\n return ktd, anomaly\n\n\ndef normalize_answer(s):\n \"\"\"Lower text and remove punctuation, articles and extra whitespace.\"\"\"\n\n def remove_articles(text):\n return re.sub(r'\\b(a|an|the)\\b', ' ', text)\n\n def white_space_fix(text):\n return ' '.join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return ''.join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\n\ndef f1_score(prediction, ground_truth):\n \"\"\"Calculate word level F1 score.\"\"\"\n prediction_tokens = normalize_answer(prediction).split()\n ground_truth_tokens = normalize_answer(ground_truth).split()\n if not prediction_tokens and not ground_truth_tokens:\n return 1.0, 1.0, 1.0\n common = cll.Counter(prediction_tokens) & cll.Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return 0, 0, 0\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return precision, recall, f1\n\n\ndef export_server(output, filename, server_folder, server=\"azkaban\"):\n with open(\"{}.txt\".format(filename), \"w\") as f:\n f.write(Bcolors.postprocess(output) + \"\\n\")\n print(\"Exporting {} to {}...\".format(filename, server))\n subprocess.check_output(\"cat {0}.txt | ansi2html.sh --palette=linux --bg=dark > {0}.html\".format(filename), shell=True)\n subprocess.check_output(\"scp {}.html {}:/scratch/kalpesh/style_transfer_overlap/data_logs/{}\".format(filename, server, server_folder), shell=True)\n\n\nhp_feature_sets = [\n (\"original\", \"input0\", \"save_62\", \"author_data/authors_1M_tokens_37_classes_srl_arg0_arg1\"),\n (\"punctuation\", \"punctuation_input0\", \"save_98\", \"author_data/authors_1M_tokens_37_classes_srl_arg0_arg1_punctuation\"),\n (\"pos_tags\", \"pos_tags_input0\", \"save_45\", \"author_data/authors_1M_tokens_37_classes_srl_arg0_arg1_pos_tag\"),\n (\"shuffle\", \"shuffle_input0\", \"save_60\", \"author_data/authors_1M_tokens_37_classes_srl_arg0_arg1_shuffle\"),\n (\"top_100\", \"top_100_input0\", \"save_89\", \"author_data/authors_1M_tokens_37_classes_srl_arg0_arg1_top_100\"),\n (\"top_10\", \"top_10_input0\", \"save_88\", \"author_data/authors_1M_tokens_37_classes_srl_arg0_arg1_top_10\"),\n]\nshakespeare_feature_sets = [\n (\"original\", \"input0\", \"save_110\", \"shakespeare/unsupervised_filtered\"),\n]\nshakespeare_prior_feature_sets = [\n (\"original\", \"input0\", \"save_151\", \"shakespeare/unsupervised_prior\")\n]\nshakespeare_prior_detokenized_feature_sets = [\n (\"original\", \"input0\", \"save_149\", \"shakespeare/unsupervised_prior_detokenize\")\n]\nformality_prior_feature_sets = [\n (\"original\", \"input0\", \"save_159\", \"formality/formality_prior\")\n]\nformality_prior_detokenized_feature_sets = [\n (\"original\", \"input0\", \"save_157\", \"formality/formality_prior_detokenize\")\n]\nshakespeare_aae_tweets_feature_sets = [\n (\"original\", \"input0\", \"save_112\", \"dataset_pools/shakespeare_aae_tweets\"),\n]\nseven_styles_feature_sets = [\n (\"original\", \"input0\", \"save_116\", \"dataset_pools/shakespeare_aae_tweets_bible_romantic-poetry_joyce_congress-bills\"),\n]\nsix_styles_feature_sets = [\n (\"original\", \"input0\", \"save_123\", \"dataset_pools/shakespeare_aae_tweets_bible_romantic-poetry_switchboard\"),\n]\npoliteness_feature_sets = [\n (\"original\", \"input0\", \"save_147\", \"politeness/politeness\"),\n]\ngender_feature_sets = [\n (\"original\", \"input0\", \"save_139\", \"gender/gender\"),\n]\nformality_feature_sets = [\n (\"original\", \"input0\", \"save_143\", \"formality/formality\"),\n]\npolitical_feature_sets = [\n (\"original\", \"input0\", \"save_145\", \"political-slant/political-slant\"),\n]\nten_styles_feature_sets = [\n (\"original\", \"input0\", \"save_133\", \"dataset_pools/shakespeare_aae_tweets_bible_romantic-poetry_switchboard_coha_3_bins_lyrics_full\"),\n]\ntwelve_styles_feature_sets = [\n (\"original\", \"input0\", \"save_161\", \"dataset_pools/shakespeare_aae_tweets_bible_romantic-poetry_congress-bills_joyce_switchboard_coha_3_bins_lyrics_full\"),\n]\neleven_styles_feature_sets = [\n (\"original\", \"input0\", \"save_170\", \"dataset_pools/shakespeare_aae_tweets_bible_romantic-poetry_joyce_switchboard_coha_3_bins_lyrics_full\"),\n]\n\nall_ft_sets = [\n hp_feature_sets, shakespeare_feature_sets, shakespeare_aae_tweets_feature_sets, seven_styles_feature_sets,\n six_styles_feature_sets, politeness_feature_sets, gender_feature_sets, formality_feature_sets,\n political_feature_sets, ten_styles_feature_sets, shakespeare_prior_detokenized_feature_sets, shakespeare_prior_feature_sets,\n formality_prior_feature_sets, formality_prior_detokenized_feature_sets, twelve_styles_feature_sets, eleven_styles_feature_sets\n]\n\n\ndef choose_classifier_feat_sets_from_dir(data_dir):\n stripped_data_dir = data_dir.replace(\"/mnt/nfs/work1/miyyer/kalpesh/projects/style-embeddings\", \"\").strip(\"/\")\n for ft_set in all_ft_sets:\n if ft_set[0][-1] == stripped_data_dir:\n return ft_set\n raise ValueError(\"ft_set not found\")\n\ndef choose_classifier_feat_sets(ft_set):\n if ft_set == \"shakespeare\":\n feature_sets = shakespeare_feature_sets\n elif ft_set == \"shakespeare_aae_tweets\":\n feature_sets = shakespeare_aae_tweets_feature_sets\n elif ft_set == \"seven_styles_feature_sets\":\n feature_sets = seven_styles_feature_sets\n elif ft_set == \"six_styles_feature_sets\":\n feature_sets = six_styles_feature_sets\n elif ft_set == \"politeness_feature_sets\":\n feature_sets = politeness_feature_sets\n elif ft_set == \"ten_styles_feature_sets\":\n feature_sets = ten_styles_feature_sets\n elif ft_set == \"twelve_styles_feature_sets\":\n feature_sets = twelve_styles_feature_sets\n elif ft_set == \"eleven_styles_feature_sets\":\n feature_sets = eleven_styles_feature_sets\n elif ft_set == \"formality_feature_sets\":\n feature_sets = formality_feature_sets\n elif ft_set == \"gender_feature_sets\":\n feature_sets = gender_feature_sets\n elif ft_set == \"political_feature_sets\":\n feature_sets = political_feature_sets\n elif ft_set == \"harry_potter\":\n feature_sets = hp_feature_sets\n elif ft_set == \"shakespeare_prior\":\n feature_sets = shakespeare_prior_feature_sets\n elif ft_set == \"shakespeare_prior_detokenize\":\n feature_sets = shakespeare_prior_detokenized_feature_sets\n elif ft_set == \"formality_prior\":\n feature_sets = formality_prior_feature_sets\n elif ft_set == \"formality_prior_detokenize\":\n feature_sets = formality_prior_detokenized_feature_sets\n else:\n raise ValueError(\"Invalid value for --ft_set\")\n\n return feature_sets\n","sub_path":"datasets/preprocess_utils.py","file_name":"preprocess_utils.py","file_ext":"py","file_size_in_byte":8947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"190651205","text":"#!/usr/bin/env python\n#coding:utf-8\n\"\"\"\n Author: iJasonLee (kingmax_res@163.com | 184327932@qq.com)\n Purpose: \n Created: 2017/8/13\n\"\"\"\n\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\n\n########################################################################\nclass Communicate(QObject):\n \"\"\"\"\"\"\n updateBW = pyqtSignal(int)\n \n########################################################################\nclass BurningWidget(QWidget):\n \"\"\"\"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self):\n \"\"\"Constructor\"\"\"\n \n super(BurningWidget, self).__init__()\n self.initUI()\n \n #----------------------------------------------------------------------\n def initUI(self):\n \"\"\"\"\"\"\n self.setMinimumSize(1, 30)\n self.value = 75\n self.num = [75, 150, 225, 300, 375, 450, 525, 600, 675]\n \n #----------------------------------------------------------------------\n def setValue(self, val):\n \"\"\"\"\"\"\n self.value = val\n \n #----------------------------------------------------------------------\n def paintEvent(self, e):\n \"\"\"\"\"\"\n pt = QPainter()\n pt.begin(self)\n self.drawWidget(pt)\n pt.end()\n \n #----------------------------------------------------------------------\n def drawWidget(self, pt):\n \"\"\"\"\"\"\n MAX_CAPACITY = 700\n OVER_CAPACITY = 750\n \n font = QFont('Serif', 7, QFont.Light)\n pt.setFont(font)\n \n size = self.size()\n w = size.width()\n h = size.height()\n step = int(round(w/10))\n till = int((w / OVER_CAPACITY) * self.value)\n full = int((w / OVER_CAPACITY) * MAX_CAPACITY)\n \n pt.setPen(Qt.white)\n pt.setBrush(QColor(255, 255, 184)) \n if self.value >= MAX_CAPACITY:\n pt.drawRect(0, 0, full, h)\n c = QColor(255, 175, 175)\n pt.setPen(c)\n pt.setBrush(c)\n pt.drawRect(full, 0, till-full, h)\n else:\n pt.drawRect(0, 0, till, h)\n \n pen = QPen(QColor(20, 20, 20), 1, Qt.SolidLine)\n pt.setPen(pen)\n pt.setBrush(Qt.NoBrush)\n pt.drawRect(0, 0, w-1, h-1)\n \n j = 0\n for i in range(step, 10*step, step):\n pt.drawLine(i, 0, i, 5)\n metrics = pt.fontMetrics()\n txt = str(self.num[j])\n fw = metrics.width(txt)\n pt.drawText(i-fw/2, h/2, txt)\n j += 1\n \n\n########################################################################\nclass Window(QWidget):\n \"\"\"\"\"\"\n \n #----------------------------------------------------------------------\n def __init__(self):\n \"\"\"Constructor\"\"\"\n super(Window, self).__init__()\n self.initUI()\n\n #----------------------------------------------------------------------\n def initUI(self):\n \"\"\"\"\"\"\n OVER_CAPACITY = 750\n \n sld = QSlider(Qt.Horizontal, self)\n sld.setFocusPolicy(Qt.NoFocus)\n sld.setRange(1, OVER_CAPACITY)\n sld.setValue(75)\n sld.setGeometry(30, 40, 300, 30)\n \n self.c = Communicate()\n self.bwWidget = BurningWidget()\n self.c.updateBW[int].connect(self.bwWidget.setValue)\n \n sld.valueChanged[int].connect(self.changeValue)\n \n hbox = QHBoxLayout()\n hbox.addWidget(self.bwWidget)\n vbox = QVBoxLayout()\n vbox.addStretch(1)\n vbox.addLayout(hbox)\n self.setLayout(vbox)\n\n self.setGeometry(300, 300, 390, 210)\n self.setWindowTitle('Customize Burning Widget')\n self.show()\n \n #----------------------------------------------------------------------\n def changeValue(self, val):\n \"\"\"\"\"\"\n self.c.updateBW.emit(val)\n self.bwWidget.repaint()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n win = Window()\n sys.exit(app.exec_())","sub_path":"customWidget/customWidget.py","file_name":"customWidget.py","file_ext":"py","file_size_in_byte":4064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"39539781","text":"import numpy\nfrom scipy.special import gammaln\n\ndef _gammaln(x):\n \"\"\"Vectorized calculation of ln(abs(gamma(array))) across a Numpy array.\n\n Numpy does not have a native implementation of gammaln.\n U{Scipy does },\n but that would introduce a dependency.\n \"\"\"\n \n array = numpy.asarray(x)\n gammaln_cof = [76.18009173, -86.50532033, 24.01409822, -1.231739516e0, 0.120858003e-2, -0.536382e-5]\n gammaln_stp = 2.50662827465\n x = numpy.array(array - 1.0)\n tmp = x + 5.5\n tmp = ((x + 0.5)*numpy.log(tmp)) - tmp\n ser = numpy.ones(array.shape[0], dtype=numpy.dtype(float))\n for cof in gammaln_cof:\n x += 1.0\n ser += cof/x\n return (tmp + numpy.log(gammaln_stp*ser))\n\ndef logfactorial(n):\n \n return gammaln( n + 1)\n","sub_path":"threeML/plugins/gammaln.py","file_name":"gammaln.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"226739881","text":"\"\"\"\nExtract Edges\n~~~~~~~~~~~~~~~~~\n\nExtracts edges from a surface.\n\"\"\"\n\n# sphinx_gallery_thumbnail_number = 2\nimport pyvista as pv\nfrom pyvista import examples\n\n###############################################################################\n# From vtk documentation, the edges are one of the following:\n#\n# 1. boundary (used by one polygon) or a line cell\n# 2. non-manifold (used by three or more polygons)\n# 3. feature edges (edges used by two triangles and whose dihedral angle > feature_angle)\n# 4. manifold edges (edges used by exactly two polygons).\n#\n# This filter will extract those edges given a feature angle and return a datset\n# with lines that represent the edges of the original mesh.\n# To demonstrate, we will first extract the edges around Queen Nefertiti's eyes:\n\n# Load Queen Nefertiti mesh\nmesh = examples.download_nefertiti()\n\n# Extract the edges above a 12 degree feature angle\nedges = mesh.extract_edges(12)\n\n# Render the edge lines ontop of the original mesh\np = pv.Plotter()\np.add_mesh(mesh, color=True)\np.add_mesh(edges, color=\"red\", line_width=5)\n# Define a camera position that will zoom to her eye\np.camera_position = [(96.0, -197.0, 45.0), (7.0, -109.0, 22.0), (0, 0, 1)]\np.show()\n\n###############################################################################\n# We can do this anaylsis for any :class:`pyvista.PolyData` object. Let's try\n# the cow mesh example:\n\nmesh = examples.download_cow()\n\nedges = mesh.extract_edges(20)\n\np = pv.Plotter()\np.add_mesh(mesh, color=True)\np.add_mesh(edges, color=\"red\", line_width=5)\np.camera_position = [(9.5, 3.0, 5.5), (2.5, 1, 0), (0, 1, 0)]\np.show()\n","sub_path":"examples/01-filter/extract-edges.py","file_name":"extract-edges.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"411814415","text":"#Write a function writeNumbers() that takes a file name as parameter, write to the file each on a different line,\n# the numbers from 100 to 1000 (inclusive) incremented by 100.\n#so the file will contain 100 200 300 .... 1000 each on a separate line.\n\n\ndef writeNumbers(filename):\n with open(filename,'a') as harun:\n for i in range(100,10001,100):\n k=str(i)\n k+=\" \\n\"\n harun.writelines(k)\n k=\"\"\n\n\n\n\n\nwriteNumbers(\"harun.text\")\n\n\n","sub_path":"FinalExercises/files/writeNumbers.py","file_name":"writeNumbers.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"373382044","text":"\nimport math\nimport operator\n\nimport cadquery as cq\n\nimport paramak\n\n\nclass BallReactor(paramak.Reactor):\n \"\"\"Creates geometry for a simple ball reactor including a plasma,\n cylindical center column shielding, square toroidal field coils.\n There is no inboard breeder blanket on this ball reactor like\n most spherical reactors.\n\n :param inner_bore_radial_thickness: the radial thickness of \n the inner bore (cm)\n :type inner_bore_radial_thickness: float\n :inboard_tf_leg_radial_thickness: the radial thickness of the\n inner leg of the toroidal field coils (cm)\n :type inboard_tf_leg_radial_thickness: float\n :center_column_shield_radial_thickness: the radial thickness\n of the center column shield (cm)\n :type center_column_shield_radial_thickness: float\n :divertor_radial_thickness: the radial thickness of the divertor\n (cm), this fills the gap between the center column shield and blanket\n :type divertor_radial_thickness: float\n :inner_plasma_gap_radial_thickness: the radial thickness of the\n inboard gap between the plasma and the center column shield (cm)\n :type inner_plasma_gap_radial_thickness: float\n :plasma_radial_thickness: the radial thickness of the plasma (cm),\n this is double the minor radius\n :type plasma_radial_thickness: float\n :outer_plasma_gap_radial_thickness: the radial thickness of the\n outboard gap between the plasma and the firstwall (cm)\n :type outer_plasma_gap_radial_thickness: float\n :firstwall_radial_thickness: the radial thickness of the first wall (cm)\n :type firstwall_radial_thickness: float\n :blanket_radial_thickness: the radial thickness of the blanket (cm)\n :type blanket_radial_thickness: float\n :blanket_rear_wall_radial_thickness: the radial thickness of the rear wall\n of the blanket (cm)\n :type blanket_rear_wall_radial_thickness: float\n :elongation: the elongation of the plasma\n :type elongation: float\n :triangularity: the triangularity of the plasma\n :type triangularity: float\n :number_of_tf_coils: the number of tf coils\n :type number_of_tf_coils: int\n :pf_coil_to_rear_blanket_radial_gap: the radial distance between the rear\n blanket and the closest poloidal field coil (optional)\n :type pf_coil_to_rear_blanket_radial_gap: float\n :pf_coil_radial_thicknesses: the radial thickness of each poloidal field\n coil (optional)\n :type pf_coil_radial_thicknesses: list of floats\n :pf_coil_vertical_thicknesses: the vertical thickness of each poloidal\n field coil (optional)\n :type pf_coil_vertical_thicknesses: list of floats\n :pf_coil_to_tf_coil_radial_gap: the radial distance between the rear of\n the poloidal field coil and the toroidal field coil (optional)\n :type pf_coil_to_tf_coil_radial_gap: float\n :tf_coil_radial_thickness: the radial thickness of the toroidal field\n coil (optional)\n :type tf_coil_radial_thickness: float\n :tf_coil_poloidal_thickness: the poloidal thickness of the toroidal field\n coil (optional)\n :type tf_coil_poloidal_thickness: float\n :rotation_angle: the angle of the sector that is desired\n :type rotation_angle: int\n\n :return: a Reactor object that has generic functionality\n :rtype: paramak shape object\n \"\"\"\n\n def __init__(\n self,\n inner_bore_radial_thickness,\n inboard_tf_leg_radial_thickness,\n center_column_shield_radial_thickness,\n divertor_radial_thickness,\n inner_plasma_gap_radial_thickness,\n plasma_radial_thickness,\n outer_plasma_gap_radial_thickness,\n firstwall_radial_thickness,\n blanket_radial_thickness,\n blanket_rear_wall_radial_thickness,\n elongation,\n triangularity,\n number_of_tf_coils,\n pf_coil_to_rear_blanket_radial_gap = None,\n pf_coil_radial_thicknesses = None,\n pf_coil_vertical_thicknesses = None,\n pf_coil_to_tf_coil_radial_gap = None,\n tf_coil_radial_thickness = None,\n tf_coil_poloidal_thickness = None,\n rotation_angle = 360,\n ):\n\n super().__init__([])\n\n self.inner_bore_radial_thickness = inner_bore_radial_thickness\n self.inboard_tf_leg_radial_thickness = inboard_tf_leg_radial_thickness\n self.center_column_shield_radial_thickness = center_column_shield_radial_thickness\n self.divertor_radial_thickness = divertor_radial_thickness\n self.inner_plasma_gap_radial_thickness = inner_plasma_gap_radial_thickness\n self.plasma_radial_thickness = plasma_radial_thickness\n self.outer_plasma_gap_radial_thickness = outer_plasma_gap_radial_thickness\n self.firstwall_radial_thickness = firstwall_radial_thickness\n self.blanket_radial_thickness = blanket_radial_thickness\n self.blanket_rear_wall_radial_thickness = blanket_rear_wall_radial_thickness\n self.pf_coil_to_rear_blanket_radial_gap = pf_coil_to_rear_blanket_radial_gap\n self.pf_coil_radial_thicknesses = pf_coil_radial_thicknesses\n self.pf_coil_vertical_thicknesses = pf_coil_vertical_thicknesses\n self.pf_coil_to_tf_coil_radial_gap = pf_coil_to_tf_coil_radial_gap\n self.tf_coil_radial_thickness = tf_coil_radial_thickness\n self.tf_coil_poloidal_thickness = tf_coil_poloidal_thickness\n\n # sets major raduis and minor radius from equatorial_points to allow a radial build\n # this helps avoid the plasma overlapping the center column and such things\n inner_equatorial_point = inner_bore_radial_thickness + inboard_tf_leg_radial_thickness + center_column_shield_radial_thickness + inner_plasma_gap_radial_thickness\n outer_equatorial_point = inner_equatorial_point + plasma_radial_thickness\n self.major_radius = (inner_equatorial_point + plasma_radial_thickness + inner_equatorial_point) /2\n self.minor_radius = ((outer_equatorial_point + inner_equatorial_point) /2 )-inner_equatorial_point\n\n self.elongation = elongation\n self.triangularity = triangularity\n\n self.number_of_tf_coils = number_of_tf_coils\n self.rotation_angle = rotation_angle\n\n self.create_components()\n\n\n def create_components(self):\n\n shapes_or_components = []\n\n plasma = paramak.Plasma(major_radius=self.major_radius,\n minor_radius=self.minor_radius,\n elongation=self.elongation,\n triangularity=self.triangularity,\n rotation_angle=self.rotation_angle)\n plasma.create_solid()\n\n shapes_or_components.append(plasma)\n\n\n # this is the radial build sequence, where one componet stops and another starts\n inner_bore_start_radius = 0\n inner_bore_end_radius = inner_bore_start_radius + self.inner_bore_radial_thickness\n\n inboard_tf_coils_start_radius = inner_bore_end_radius\n inboard_tf_coils_end_radius = inboard_tf_coils_start_radius + self.inboard_tf_leg_radial_thickness\n\n center_column_shield_start_radius = inboard_tf_coils_end_radius\n center_column_shield_end_radius = center_column_shield_start_radius + self.center_column_shield_radial_thickness\n\n divertor_start_radius = center_column_shield_end_radius\n divertor_end_radius = center_column_shield_end_radius + self.divertor_radial_thickness\n\n firstwall_start_radius = center_column_shield_end_radius \\\n + self.inner_plasma_gap_radial_thickness \\\n + self.plasma_radial_thickness \\\n + self.outer_plasma_gap_radial_thickness \n firstwall_end_radius = firstwall_start_radius + self.firstwall_radial_thickness\n\n blanket_start_radius = firstwall_end_radius\n blanket_end_radius = blanket_start_radius + self.blanket_radial_thickness\n\n blanket_read_wall_start_radius = blanket_end_radius \n blanket_read_wall_end_radius = blanket_read_wall_start_radius + self.blanket_rear_wall_radial_thickness \n\n #this is the vertical build sequence, componets build on each other in a similar manner to the radial build\n\n divertor_start_height = plasma.high_point[1]+ self.outer_plasma_gap_radial_thickness\n # make it the same hight as fw, blanket, rw\n divertor_end_height = divertor_start_height + self.firstwall_radial_thickness + self.blanket_radial_thickness + self.blanket_rear_wall_radial_thickness\n\n firstwall_start_height = divertor_start_height\n firstwall_end_height = firstwall_start_height + self.firstwall_radial_thickness\n\n blanket_start_height = firstwall_end_height\n blanket_end_height = blanket_start_height + self.blanket_radial_thickness\n\n blanket_rear_wall_start_height = blanket_end_height\n blanket_rear_wall_end_height = blanket_rear_wall_start_height + self.blanket_rear_wall_radial_thickness\n\n tf_coil_height = blanket_rear_wall_end_height\n center_column_shield_height = blanket_rear_wall_end_height * 2\n\n if self.pf_coil_vertical_thicknesses!=None and self.pf_coil_radial_thicknesses !=None and self.pf_coil_to_rear_blanket_radial_gap !=None:\n number_of_pf_coils = len(self.pf_coil_vertical_thicknesses)\n\n y_position_step = (2*(blanket_rear_wall_end_height + self.pf_coil_to_rear_blanket_radial_gap))/(number_of_pf_coils+1)\n\n pf_coils_y_values = []\n pf_coils_x_values = []\n # adds in coils with equal spacing strategy, should be updated to allow user positions\n for i in range(number_of_pf_coils):\n y_value =blanket_rear_wall_end_height + self.pf_coil_to_rear_blanket_radial_gap - y_position_step*(i+1)\n x_value = blanket_read_wall_end_radius + self.pf_coil_to_rear_blanket_radial_gap + \\\n 0.5*self.pf_coil_radial_thicknesses[i]\n pf_coils_y_values.append(y_value)\n pf_coils_x_values.append(x_value)\n\n pf_coil_start_radius = blanket_read_wall_end_radius + self.pf_coil_to_rear_blanket_radial_gap\n pf_coil_end_radius = pf_coil_start_radius + max(self.pf_coil_radial_thicknesses)\n \n if self.pf_coil_to_tf_coil_radial_gap !=None and self.tf_coil_radial_thickness !=None:\n tf_coil_start_radius = pf_coil_end_radius + self.pf_coil_to_rear_blanket_radial_gap \n tf_coil_end_radius = tf_coil_start_radius + self.tf_coil_radial_thickness\n\n\n if self.rotation_angle < 360:\n max_high = 3 * center_column_shield_height\n max_width = 3 * blanket_read_wall_end_radius\n cutting_slice = paramak.RotateStraightShape(points=[\n (0,max_high),\n (max_width, max_high),\n (max_width, -max_high),\n (0, -max_high),\n ],\n rotation_angle=360-self.rotation_angle,\n azimuth_placement_angle=360-self.rotation_angle\n )\n else:\n cutting_slice=None\n\n # shapes_or_components.append(inboard_tf_coils)\n inboard_tf_coils = paramak.CenterColumnShieldCylinder(\n height=tf_coil_height * 2,\n inner_radius=inboard_tf_coils_start_radius,\n outer_radius=inboard_tf_coils_end_radius,\n rotation_angle=self.rotation_angle,\n # color=centre_column_color,\n stp_filename=\"inboard_tf_coils.stp\",\n name=\"inboard_tf_coils\",\n material_tag=\"inboard_tf_coils_mat\",\n )\n shapes_or_components.append(inboard_tf_coils)\n\n center_column_shield = paramak.CenterColumnShieldCylinder(\n height=center_column_shield_height,\n inner_radius=center_column_shield_start_radius,\n outer_radius=center_column_shield_end_radius,\n rotation_angle=self.rotation_angle,\n # color=centre_column_color,\n stp_filename=\"center_column_shield.stp\",\n name=\"center_column_shield\",\n material_tag=\"center_column_shield_mat\",\n )\n shapes_or_components.append(center_column_shield)\n\n space_for_divertor = plasma.high_point[0] - center_column_shield_end_radius\n\n #add blanket if the divertor doesn't take up all the space\n if space_for_divertor > self.divertor_radial_thickness:\n print('making extra blanket as there is space between the divertor and existing blanket')\n extra_blanket_upper = paramak.RotateStraightShape(points=[\n (divertor_end_radius, blanket_start_height),\n (divertor_end_radius, blanket_end_height),\n (plasma.high_point[0], blanket_end_height),\n (plasma.high_point[0], blanket_start_height),\n ],\n rotation_angle=self.rotation_angle,\n stp_filename='extra_blanket_upper.stp',\n name='extra_blanket_upper',\n material_tag='blanket_mat')\n shapes_or_components.append(extra_blanket_upper)\n\n extra_firstwall_upper = paramak.RotateStraightShape(points=[\n (divertor_end_radius, firstwall_start_height),\n (divertor_end_radius, firstwall_end_height),\n (plasma.high_point[0], firstwall_end_height),\n (plasma.high_point[0], firstwall_start_height),\n ],\n rotation_angle=self.rotation_angle,\n stp_filename='extra_firstwall_upper.stp',\n name='extra_firstwall_upper',\n material_tag='firstwall_mat')\n shapes_or_components.append(extra_firstwall_upper)\n\n extra_blanket_rear_wall_upper = paramak.RotateStraightShape(points=[\n (divertor_end_radius, blanket_rear_wall_start_height),\n (divertor_end_radius, blanket_rear_wall_end_height),\n (plasma.high_point[0], blanket_rear_wall_end_height),\n (plasma.high_point[0], blanket_rear_wall_start_height),\n ],\n rotation_angle=self.rotation_angle,\n stp_filename='extra_blanket_rear_wall_upper.stp',\n name='extra_blanket_rear_wall_upper',\n material_tag='blanket_rear_wall_mat')\n shapes_or_components.append(extra_blanket_rear_wall_upper)\n\n extra_blanket_lower = paramak.RotateStraightShape(points=[\n (divertor_end_radius, -blanket_start_height),\n (divertor_end_radius, -blanket_end_height),\n (plasma.high_point[0], -blanket_end_height),\n (plasma.high_point[0], -blanket_start_height),\n ],\n rotation_angle=self.rotation_angle,\n stp_filename='extra_blanket_lower.stp',\n name='extra_blanket_lower',\n material_tag='blanket_mat')\n shapes_or_components.append(extra_blanket_lower)\n\n extra_firstwall_lower = paramak.RotateStraightShape(points=[\n (divertor_end_radius, -firstwall_start_height),\n (divertor_end_radius, -firstwall_end_height),\n (plasma.high_point[0], -firstwall_end_height),\n (plasma.high_point[0], -firstwall_start_height),\n ],\n rotation_angle=self.rotation_angle,\n stp_filename='extra_firstwall_lower.stp',\n name='extra_firstwall_lower',\n material_tag='firstwall_mat')\n shapes_or_components.append(extra_firstwall_lower)\n\n extra_blanket_rear_wall_lower = paramak.RotateStraightShape(points=[\n (divertor_end_radius, -blanket_rear_wall_start_height),\n (divertor_end_radius, -blanket_rear_wall_end_height),\n (plasma.high_point[0], -blanket_rear_wall_end_height),\n (plasma.high_point[0], -blanket_rear_wall_start_height),\n ],\n rotation_angle=self.rotation_angle,\n stp_filename='extra_blanket_rear_wall_lower.stp',\n name='extra_blanket_rear_wall_lower',\n material_tag='blanket_rear_wall_mat')\n shapes_or_components.append(extra_blanket_rear_wall_lower)\n\n divertor_upper_part = paramak.RotateStraightShape(points=[\n (divertor_start_radius, divertor_end_height),\n (divertor_start_radius, divertor_start_height),\n (divertor_end_radius, divertor_start_height),\n (divertor_end_radius, divertor_end_height),\n ],\n stp_filename='divertor_upper.stp',\n name='divertor_upper',\n rotation_angle=self.rotation_angle,\n material_tag='divertor_mat'\n )\n shapes_or_components.append(divertor_upper_part)\n\n # negative signs used as this is in the negative side of the Z axis \n divertor_lower_part = paramak.RotateStraightShape(points=[\n (divertor_start_radius, -divertor_end_height),\n (divertor_start_radius, -divertor_start_height),\n (divertor_end_radius, -divertor_start_height),\n (divertor_end_radius, -divertor_end_height),\n ],\n stp_filename='divertor_lower.stp',\n name='divertor_lower',\n rotation_angle=self.rotation_angle,\n material_tag='divertor_mat'\n )\n shapes_or_components.append(divertor_lower_part)\n\n # curve divertor arround if it is larger than the horitonal space provided\n elif self.divertor_radial_thickness > space_for_divertor:\n\n length_of_curved_section = self.divertor_radial_thickness - space_for_divertor\n\n center_point, radius = paramak.utils.find_center_point_of_circle(point1=(firstwall_start_radius, 0),\n point2=(plasma.high_point[0], firstwall_start_height),\n point3=(plasma.low_point[0], -firstwall_start_height))\n\n circumference = 2.*math.pi*radius\n\n rotation_angle = (length_of_curved_section * 2 * math.pi) / circumference\n\n new_point_x1, new_point_y1 = paramak.utils.rotate(center_point, (plasma.high_point[0], firstwall_start_height), -rotation_angle/2.)\n new_point_x2, new_point_y2 = paramak.utils.rotate(center_point, (plasma.high_point[0], firstwall_start_height), -rotation_angle)\n new_point_x3, new_point_y3 = paramak.utils.rotate(center_point, (plasma.high_point[0], blanket_rear_wall_end_height), -rotation_angle)\n new_point_x4, new_point_y4 = paramak.utils.rotate(center_point, (plasma.high_point[0], blanket_rear_wall_end_height), -rotation_angle/2.)\n\n divertor_upper_part = paramak.RotateMixedShape(points=[\n (divertor_start_radius, divertor_end_height, 'straight'),\n (divertor_start_radius, divertor_start_height, 'straight'),\n (divertor_start_radius+space_for_divertor, divertor_start_height, 'circle'),\n (new_point_x1, new_point_y1, 'circle'),\n (new_point_x2, new_point_y2, 'straight'),\n (new_point_x3, new_point_y3, 'circle'),\n (new_point_x4, new_point_y4, 'circle'),\n (divertor_start_radius+space_for_divertor, divertor_end_height, 'straight'),\n ],\n stp_filename='divertor_upper.stp',\n name='divertor_upper',\n rotation_angle=self.rotation_angle,\n material_tag='divertor_mat'\n )\n shapes_or_components.append(divertor_upper_part)\n\n # negative signs used as this is in the negative side of the Z axis \n divertor_lower_part = paramak.RotateMixedShape(points=[\n (divertor_start_radius, -divertor_end_height, 'straight'),\n (divertor_start_radius, -divertor_start_height, 'straight'),\n (divertor_start_radius+space_for_divertor, -divertor_start_height, 'circle'),\n (new_point_x1, -new_point_y1, 'circle'),\n (new_point_x2, -new_point_y2, 'straight'),\n (new_point_x3, -new_point_y3, 'circle'),\n (new_point_x4, -new_point_y4, 'circle'),\n (divertor_start_radius+space_for_divertor, -divertor_end_height, 'straight'),\n ],\n stp_filename='divertor_lower.stp',\n name='divertor_lower',\n rotation_angle=self.rotation_angle,\n material_tag='divertor_mat'\n )\n shapes_or_components.append(divertor_lower_part)\n\n elif self.divertor_radial_thickness == space_for_divertor:\n\n divertor_upper_part = paramak.RotateMixedShape(points=[\n (divertor_start_radius, divertor_end_height, 'straight'),\n (divertor_start_radius, divertor_start_height, 'straight'),\n (divertor_start_radius+space_for_divertor, divertor_start_height, 'straight'),\n (divertor_start_radius+space_for_divertor, divertor_end_height, 'straight'),\n ],\n stp_filename='divertor_upper.stp',\n name='divertor_upper',\n rotation_angle=self.rotation_angle,\n material_tag='divertor_mat'\n )\n shapes_or_components.append(divertor_upper_part)\n\n # negative signs used as this is in the negative side of the Z axis \n divertor_lower_part = paramak.RotateMixedShape(points=[\n (divertor_start_radius, -divertor_end_height, 'straight'),\n (divertor_start_radius, -divertor_start_height, 'straight'),\n (divertor_start_radius+space_for_divertor, -divertor_start_height, 'straight'),\n (divertor_start_radius+space_for_divertor, -divertor_end_height, 'straight'),\n ],\n stp_filename='divertor_lower.stp',\n name='divertor_lower',\n rotation_angle=self.rotation_angle,\n material_tag='divertor_mat'\n )\n shapes_or_components.append(divertor_lower_part)\n\n firstwall = paramak.BlanketConstantThicknessArcV(\n inner_mid_point=(firstwall_start_radius, 0),\n inner_upper_point=(plasma.high_point[0], firstwall_start_height),\n inner_lower_point=(plasma.low_point[0], -firstwall_start_height),\n thickness=self.firstwall_radial_thickness,\n rotation_angle=self.rotation_angle,\n stp_filename='firstwall.stp',\n name='firstwall',\n material_tag='firstwall_mat',\n cut=[divertor_lower_part, divertor_upper_part]\n )\n shapes_or_components.append(firstwall)\n\n blanket = paramak.BlanketConstantThicknessArcV(\n inner_mid_point=(blanket_start_radius, 0),\n inner_upper_point=(plasma.high_point[0], blanket_start_height),\n inner_lower_point=(plasma.low_point[0], -blanket_start_height),\n thickness=self.blanket_radial_thickness,\n rotation_angle=self.rotation_angle,\n stp_filename='blanket.stp',\n name='blanket',\n material_tag='blanket_mat',\n cut=[divertor_lower_part, divertor_upper_part]\n )\n shapes_or_components.append(blanket)\n\n blanket_rear_casing = paramak.BlanketConstantThicknessArcV(\n inner_mid_point=(blanket_read_wall_start_radius, 0),\n inner_upper_point=(plasma.high_point[0], blanket_rear_wall_start_height),\n inner_lower_point=(plasma.low_point[0], -blanket_rear_wall_start_height),\n thickness=self.blanket_rear_wall_radial_thickness,\n rotation_angle=self.rotation_angle,\n stp_filename='blanket_rear_wall.stp',\n name='blanket_rear_wall',\n material_tag='blanket_rear_wall_mat',\n cut=[divertor_lower_part, divertor_upper_part]\n )\n shapes_or_components.append(blanket_rear_casing)\n\n if self.pf_coil_vertical_thicknesses!=None and self.pf_coil_radial_thicknesses !=None and self.pf_coil_to_rear_blanket_radial_gap !=None:\n \n for i, (rt, vt, y_value, x_value) in enumerate(zip(self.pf_coil_radial_thicknesses,\n self.pf_coil_vertical_thicknesses,\n pf_coils_y_values,\n pf_coils_x_values,\n )\n ):\n\n\n pf_coil = paramak.PoloidalFieldCoil(width=rt, \n height=vt,\n center_point=(x_value,y_value),\n rotation_angle=self.rotation_angle,\n stp_filename='pf_coil_'+str(i)+'.stp',\n name='pf_coil',\n material_tag='pf_coil_mat')\n shapes_or_components.append(pf_coil)\n \n if self.pf_coil_to_tf_coil_radial_gap !=None and self.tf_coil_radial_thickness !=None:\n tf_coil = paramak.ToroidalFieldCoilRectangle(inner_upper_point=(inboard_tf_coils_start_radius, tf_coil_height),\n inner_lower_point=(inboard_tf_coils_start_radius, -tf_coil_height),\n inner_mid_point=(tf_coil_start_radius, 0),\n thickness= self.tf_coil_radial_thickness,\n number_of_coils=self.number_of_tf_coils,\n distance=self.tf_coil_poloidal_thickness,\n cut=cutting_slice)\n\n shapes_or_components.append(tf_coil)\n \n self.shapes_and_components = shapes_or_components","sub_path":"paramak/parametric_reactors/ball_reactor.py","file_name":"ball_reactor.py","file_ext":"py","file_size_in_byte":26301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"429600621","text":"# Databricks notebook source\nfrom tweepy import OAuthHandler\nfrom tweepy import API\nfrom tweepy import Cursor\nfrom textblob import TextBlob\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nimport tweepy as tw\nimport pandas as pd\nimport re\nimport numpy as np\nimport csv\n\nconsumer_key = '' #twitter app’s API Key\nconsumer_secret = '' #twitter app’s API secret Key\naccess_token = '' #twitter app’s Access token\naccess_token_secret = '' #twitter app’s access token secret\n\nauth = OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\nauth_api = API(auth)\n\nIBMacess_tweets = auth_api.user_timeline(screen_name = \"IBMAccess\", q=\"#a11y\",count = 1000, include_rts = False, tweet_mode = \"extended\", lang=\"en\", since=\"2018-11-16\")\nfinal_tweets = [each_tweet.full_text for each_tweet in IBMacess_tweets]\n\ndef cleanTxt(text):\n text = re.sub('@[A-Za-z0–9]+', '', text) # Removing @mentions\n text = re.sub('https?:\\/\\/\\S+', '', text) # Removing hyperlink\n\n return text\n\n\ndf = pd.DataFrame([tweet.full_text for tweet in IBMacess_tweets], columns=['Tweets'])\ndf['Tweets']= df['Tweets'].apply(cleanTxt)\n\n\ndef getSubjectivity(text):\n return TextBlob(text).sentiment.subjectivity\n\n\n# Create a function to get the polarity\ndef getPolarity(text):\n return TextBlob(text).sentiment.polarity\n\n\n# Create two new columns 'Subjectivity' & 'Polarity'\ndf['Subjectivity'] = df['Tweets'].apply(getSubjectivity)\ndf['Polarity'] = df['Tweets'].apply(getPolarity)\n\n\n#Creating a worldcloud to check what words appear the most\nallWords = ' '.join([twts for twts in df['Tweets']])\nwordCloud = WordCloud(width=500, height=300, random_state=21, max_font_size=110).generate(allWords)\n\n\nplt.imshow(wordCloud, interpolation=\"bilinear\")\nplt.axis('off')\n\n#Analysis of sentiment score\ndef getAnalysis(score):\n if score < 0:\n return 'Negative'\n elif score == 0:\n return 'Neutral'\n else:\n return 'Positive'\n\n\ndf['Analysis'] = df['Polarity'].apply(getAnalysis)\n\n\n# Printing positive tweets\nprint('Printing positive tweets:\\n')\nj=1\nsortedDF = df.sort_values(by=['Polarity']) #Sort the tweets\nfor i in range(0, sortedDF.shape[0] ):\n if( sortedDF['Analysis'][i] == 'Positive'):\n print(str(j) + ') '+ sortedDF['Tweets'][i])\n print()\n j= j+1\n\n\n# Printing negative tweets\nprint('Printing negative tweets:\\n')\nj=1\nsortedDF = df.sort_values(by=['Polarity'],ascending=False)\nfor i in range(0, sortedDF.shape[0] ):\n if( sortedDF['Analysis'][i] == 'Negative'):\n print(str(j) + ') '+sortedDF['Tweets'][i])\n print()\n j=j+1\n\n#plot polarity and subjectivity\nplt.figure(figsize=(8, 6))\nfor i in range(0, df.shape[0]):\n plt.scatter(df[\"Polarity\"][i], df[\"Subjectivity\"][i], color='Blue')\n\nplt.title('Sentiment Analysis')\nplt.xlabel('Polarity')\nplt.ylabel('Subjectivity')\nplt.show()","sub_path":"tweet_analysis.py","file_name":"tweet_analysis.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"469978834","text":"import cv2\nimport numpy as np\nimport common\nimport global_values\n\nclass Box:\n def __init__(self, robot):\n self.robot = robot\n self.color = None\n self.points = None\n self.center_x = 0\n self.center_y = 0\n self.image_half_width = 500 ##### TO EDIT: get the width from a global variable #####\n self.center_accuracy = 100 # is used when checking the box is in the center or not\n self.variance = global_values.square_variance# Variance for right-square\n self.thresh_frame = None\n def is_box_totally_visible(self):\n self.points = None\n if self.color is None:\n masked = common.apply_mask(self.robot.current_frame)\n else:\n masked = common.apply_mask(self.robot.current_frame,self.color)\n gray_img = cv2.cvtColor(masked,cv2.COLOR_BGR2GRAY)\n thresh = common.get_otsu_gaussian_threshold(gray_img)\n self.thresh_frame = cv2.cvtColor(thresh,cv2.COLOR_GRAY2BGR)\n contours = common.get_contours(thresh)\n return self.look_for_box(contours,self.variance)\n\n\n\n def look_for_box(self,contours,var):\n for c in contours:\n moments = cv2.moments(c)\n if moments[\"m00\"] > 10000: #make 1000 if it didnt work\n r = cv2.minAreaRect(c)\n r = ((r[0][0], r[0][1]), (r[1][0], r[1][1]), r[2])\n (width,height)=(r[1][0], r[1][1])\n box = cv2.boxPoints(r)\n\n box = np.int0(box)\n if (height > (1 - var) * width and height < (1 + var) * width):\n self.points = box\n #print box\n #self.center_x = int(box[:, 0].mean())\n self.center_x = int((min(box[:,0]) + max(box[:,0]))/2)\n self.center_y = int((min(box[:,1]) + max(box[:,1]))/2)\n\n return True\n return False\n\n def is_box_seen(self):\n ########### is box partially visible code goes here ###############\n\n\n\n pass\n\n\n\n\n##############3 debugging code ##############################\n def show(self): # For testing\n frame = self.thresh_frame\n\n if self.is_box_totally_visible():\n cv2.drawContours(frame, [self.points], -1, (0, 0, 255), 2)\n cv2.circle(frame, (self.center_x, self.center_y), 7, (0, 0, 255), 2)\n\n ls = self.left_shifting()\n rs = self.right_shifting()\n if ls > 0:\n cv2.putText(frame, \"LEFT SHIFT \" + str(ls), (self.image_half_width - 200, 100), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.8, (0, 255, 255))\n elif rs > 0:\n cv2.putText(frame, \"RIGHT SHIFT \" + str(rs), (self.image_half_width + 200, 100), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.8, (0, 255, 255))\n else:\n cv2.putText(frame, \"CENTERED\", (self.image_half_width, 100), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.8, (0, 255, 0))\n\n return frame\n\n def is_centered(self): # Check wheather the box is centered or not\n return abs(self.image_half_width - self.center_x) <= self.center_accuracy\n\n def left_shifting(self): # Distance to the left from the center\n shifting = (self.image_half_width - self.center_accuracy) - self.center_x\n return shifting if shifting > 0 else 0\n\n def right_shifting(self): # Distance to the right from the center\n shifting = self.center_x - (self.image_half_width + self.center_accuracy)\n return shifting if shifting > 0 else 0\n","sub_path":"SLIIT Robofest 2016/robofest_pi/v1/box_logic.py","file_name":"box_logic.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"322253976","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n\t#/code/\n url(r'^$', views.codebeta, name='codebeta'),\n url(r'^ot/$', views.ot, name='ot'),\n #/code/projects\n url(r'^projects/$', views.projects, name='projects'),\n #/code/share\n url(r'^share/$', views.share, name='share'),\n #/code/projects/new\n url(r'^newproject/$', views.newproject, name='newproject'),\n #/code/projects/projectname\n\turl(r'^projects/(?P[0-9]+)/$', views.whichproject, name='whichproject'),\n\t#/code/projects/projectname/filename\n\turl(r'^projects/(?P[0-9]+)/(?P[a-zA-Z0-9]+)/$', views.file, name='code'),\n\t#/code/share/sharehash\n\turl(r'^share/(?P[0-9a-zA-Z]+)/$', views.share, name='share'),\n#test email thing\n\turl(r'^testemail/$', views.notifyUser2, name='notifyUser2'),\n\n# AJAX FUNCTIONS\n # PROJECT\n #ajax call /code/newProjectAjax/\n url(r'^newProjectAjax/$', views.newProjectAjax, name='newProjectAjax'),\n #ajax call /code/ajax_check_addmember_username/\n url(r'^ajax_check_addmember_username/$', views.ajax_check_addmember_username, name='ajax_check_addmember_username'),\n #ajax call /code/ajax_addNewTeamMember/\n url(r'^ajax_addNewTeamMember/$', views.ajax_addNewTeamMember, name='ajax_addNewTeamMember'),\n # FILE\n #ajax call /code/newFileAjax/\n url(r'^newFileAjax/$', views.newFileAjax, name='newFileAjax'),\n #ajax call /code/newFileAjax/\n url(r'^newDirAjax/$', views.newDirAjax, name='newDirAjax'),\n #ajax call /code/newFileAjax/\n url(r'^saveCodeContent/$', views.saveCodeContent, name='saveCodeContent'),\n url(r'^saveCodeContentFromNode/$', views.saveCodeContentFromNode, name='saveCodeContentFromNode'),\n #ajax call /code/loadInitialFile/\n url(r'^loadInitialFile/$', views.loadInitialFile, name='loadInitialFile'),\n #ajax call /code/loadSharedFile/\n url(r'^loadSharedFile/$', views.loadSharedFile, name='loadSharedFile'),\n #ajax call /code/deleteFileAjax/\n url(r'^deleteFileAjax/$', views.deleteFileAjax, name='deleteFileAjax'),\n #ajax call /code/deleteFideleteProjectleAjax/\n url(r'^deleteProject/$', views.deleteProject, name='deleteProject'),\n\n]\n\n\n\n'''\nsamples\n'''\n # url(r'^createStory/$', views.createStory, name='createStory'),\n # url(r'^editStory/$', views.editStory, name='editStory'),\n # url(r'^deleteStory/$', views.deleteStory, name='deleteStory'),\n # # /projectname/\n\t# url(r'^(?P[0-9]+)/$', views.project, name='project'),\n\t# # url(r'^(?P[0-9]+)/iteration/$', views.iteration, name='iteration'),\n\t# # url(r'^(?P[0-9]+)/iteration/new/$', views.newIteration, name='newIteration'),\n\t# # url(r'^(?P[0-9]+)/iteration/(?P[0-9]+)/$', views.iteration, name='iteration'),\n\t# url(r'^(?P[a-zA-Z]+)/iteration/new/$', views.newIteration, name='newIteration'),\n\t# url(r'^(?P[a-zA-Z]+)/iteration/(?P[0-9]+)/$', views.iteration, name='iteration'),\n\n","sub_path":"codeapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"173749810","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 1 15:31:47 2021\n\n@author: Daniel Souza - PC\n\"\"\"\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nfrom pandas.api.types import is_numeric_dtype\n\ndef plot_histograms(df, title, n_columns = 4):\n fig_columns = n_columns\n fig_rows = int(np.ceil(len(df.columns) / fig_columns))\n \n fig, axes = plt.subplots(fig_rows, fig_columns, figsize=(18, 4 * fig_rows))\n fig.suptitle(title, size='xx-large')\n\n for i, column in enumerate(df.columns):\n ax = axes[i//fig_columns][i%fig_columns]\n \n sns.histplot(data = df, x = column, ax=ax, kde = True)\n \n if(is_numeric_dtype(df[column])):\n ax.axvline(x=np.mean(df[column]), linestyle='dashed', label='Mean')\n ax.legend()\n \n\n ax.set_title(column.title().replace(\"_\", \" \"))\n \n\n plt.tight_layout()\n \n return fig\n\ndef plot_high_correlation_variables(df, correlation, correl_threshold, title, n_columns = 4):\n fig_columns = 4\n\n high_corr_pair_list = []\n \n # Add high correlation variables pairs to list\n for i, line in enumerate(correlation.columns):\n for column in correlation.columns[i+1:]:\n cor_abs_val = np.abs(correlation.loc[line, column])\n \n if cor_abs_val >= correl_threshold:\n high_corr_pair_list.append([line, column, cor_abs_val])\n \n # Sort list according to absolute correlation\n high_corr_pair_list.sort(reverse = True, key = lambda x: x[2])\n # Set amount of rows \n fig_rows = int(np.ceil(len(high_corr_pair_list) / fig_columns))\n \n # Plot charts\n fig, axes = plt.subplots(fig_rows, fig_columns, figsize=(18, 4*fig_rows))\n fig.suptitle(title, size='xx-large')\n \n for i, pair in enumerate(high_corr_pair_list):\n if fig_rows > 1:\n ax = axes[i//fig_columns][i%fig_columns]\n else:\n ax = axes[i]\n \n cor_i = correlation.loc[pair[0], pair[1]]\n \n sns.scatterplot(data = df, x = pair[1], y = pair[0], ax = ax, alpha = 0.8)\n ax.set_title(str(pair[0]).title().replace(\"_\", \" \") + \" x \" + str(pair[1]).title().replace(\"_\", \" \") \\\n + \", corr = {:.2f}\".format(cor_i) )\n \n plt.tight_layout()\n plt.subplots_adjust(top=0.95)\n return fig","sub_path":"exploratory_analysis.py","file_name":"exploratory_analysis.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"329985263","text":"__author__ = 'Guillaume'\n# from https://www.interviewbit.com/courses/programming/topics/math/problems/factors/\n\nimport math\n\n\nclass Solution:\n # @param A : integer\n # @return a list of integers\n def allFactors(self, A):\n res1 = []\n res2 = []\n for i in range(1, int(math.ceil(math.sqrt(A)) + 1)):\n if A % i == 0:\n res1.append(i)\n if i != math.sqrt(A):\n res2.append(int(A/i))\n return res1 + res2[::-1]\n\n\nsl = Solution()\nprint(sl.allFactors(12))\n","sub_path":"Python/IB_all_factors.py","file_name":"IB_all_factors.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"402069404","text":"# {@tested@}\nfrom sys import version_info\n\nis_string = None; is_string\ndef _define_is_string_by_version(v):\n global is_string\n if v == 2:\n is_string = eval('''lambda o: isinstance(o, basestring)''')\n elif 3 <= v:\n is_string = lambda o: isinstance(o, (bytes, str))\n else:\n raise AssertionError(v)\n_define_is_string_by_version(version_info[0])\n\ndef is_regex(o):\n if not atom(o):\n return False\n if is_string(o):\n return True\n try:\n o.match\n except AttributeError:\n return False\n return True\n\ndef atom(o):\n return is_string(o) or not _is_iterable(o)\n\ndef is_iterable(o):\n return not is_string(o) and _is_iterable(o)\n\ndef _is_iterable(o):\n try:\n o.__iter__\n except AttributeError:\n return False\n return True\n","sub_path":"gnuinst/lib/atom.py","file_name":"atom.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"84068326","text":"from PyQt5.QtCore import *\r\nfrom InStkForm_handler import *\r\nfrom GlobalAPI_handler import *\r\nfrom Chart_handler import *\r\nfrom RcvSckt_handler import *\r\nfrom SndSckt_handler import *\r\nfrom TFQttn_handler import *\r\nfrom TestQttn_Sender import *\r\nfrom PyQt5 import uic\r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\r\n\r\nui_path = os.path.dirname(os.path.abspath(__file__))\r\nMainFormClass = uic.loadUiType(os.path.join(ui_path, \"MainForm.ui\"))[0]\r\n\r\n# 메인 폼 핸들러\r\nclass MainForm_handler(QMainWindow, MainFormClass):\r\n\r\n def __init__(self, isUnite=\"None\"):\r\n super().__init__()\r\n\r\n # 폼 설정\r\n self.setupUi(self)\r\n\r\n # 객체변수 설정\r\n self.DBH = None # DB 핸들러\r\n self.APIH = None # API 핸들러\r\n self.CrtH = None # 차트 핸들러\r\n self.QttnSctkT = None # 시세수신소켓쓰레드\r\n self.TfRcvSctkT = None # 딥러닝수신소켓쓰레드\r\n self.TfSndSctkT = None # 딥러닝송신소켓\r\n self.ProcStkList = [] # 처리대상 종목리스트\r\n self.TestQttnSnd = None # 테스트 시세 전송 쓰레드\r\n\r\n # 수신소켓 동작여부\r\n self.NowRcvIdxQttn = False\r\n self.NowRcvGlobalQttn = False\r\n self.NowTensorFlow = False\r\n self.NowRcvGlobalSavedQttn = False\r\n\r\n # 버튼이벤트 핸들러 설정\r\n self.btnInStkCd.clicked.connect (self.ClickInStkCd ) # 처리종목 입력\r\n self.btnDelStkCd.clicked.connect (self.ClickDelStkCd ) # 처리종목 삭제\r\n self.btnInitMnQttn.clicked.connect (self.ClickInitMnQttn ) # 처리종목 분봉시세 초기화\r\n self.btnRcvIdxQttn.clicked.connect (self.ClickRcvIdxQttn ) # 지수 실시간 시세 받기/종료\r\n self.btnRcvGlobalQttn.clicked.connect (self.ClickRcvGlobalQttn ) # 글로벌 실시간 시세 받기/종료\r\n self.btnTensorFlow.clicked.connect (self.ClickTensorFlow ) # 딥러닝 송수신 동작/중지\r\n self.btnRcvGlobalSavedQttn.clicked.connect(self.ClickRcvGlobalSavedQttn) # 저장된 글로벌 시세 받기/종료\r\n\r\n self.btnMnQttnOrd.clicked.connect (self.ClickMnQttnOrd ) # 빈분봉처리\r\n self.btnSetFstQttn.clicked.connect (self.ClickSetFstQttn ) # 첫시세 설정\r\n self.btnMnQttnOrd.setVisible(False)\r\n self.btnSetFstQttn.setVisible(False)\r\n\r\n # DB 핸들러 초기화\r\n try:\r\n self.DBH = DB_handler() # DB 핸들러\r\n except Exception as e:\r\n print(\"DB 핸들러 오류:\",e)\r\n\r\n # API 핸들러 초기화\r\n try:\r\n self.APIH = GlobalAPI_handler()\r\n self.APIH.initAPI(False, self) # 전송모드일 경우 True, 메인폼 수신 False\r\n print(\"GLOBAL end \")\r\n except Exception as e:\r\n print(\"API초기화오류:\",e)\r\n\r\n # 차트 초기화\r\n self.fig = plt.Figure()\r\n self.canvas = FigureCanvas(self.fig)\r\n self.vbChart.addWidget(self.canvas)\r\n self.CrtH = Chart_handler()\r\n self.CrtH.SetHandler(self.fig, self.canvas)\r\n\r\n # 처리대상 종목 초기화\r\n self.ShowProcStkList()\r\n\r\n # 딥러닝 시세 핸들러 초기화\r\n self.TFH = TFQttn_handler(self)\r\n\r\n # 통합실행의 경우 수신준비\r\n if (isUnite == \"TRUE\"):\r\n #3초 딜레이후 실행\r\n time.sleep(3)\r\n # 지수시세 실시간\r\n self.ClickRcvIdxQttn()\r\n # 텐서플로 실시간\r\n self.ClickTensorFlow()\r\n\r\n return None\r\n\r\n def __del__(self):\r\n self.APIH.CloseAPI()\r\n return None\r\n\r\n # 처리대상종목 입력\r\n def ClickInStkCd(self):\r\n if (self.NowRcvGlobalQttn):\r\n ctypes.windll.user32.MessageBoxW(0, \"글로번 시세 수신중으로 추가 불가\", \"알림\", 0)\r\n return None\r\n inStkForm = InStkForm_handler()\r\n inStkForm.exec_()\r\n self.ShowProcStkList()\r\n return None\r\n\r\n # 처리대상종목 삭제\r\n def ClickDelStkCd(self):\r\n if (self.NowRcvGlobalQttn):\r\n ctypes.windll.user32.MessageBoxW(0, \"글로번 시세 수신중으로 추가 불가\", \"알림\", 0)\r\n return None\r\n sItem = self.tblProcStkList.selectedItems()\r\n sMktTpCd = sItem[CodeDef.PROC_STK_COL_MKT_TP_CD].text() # 시장구분코드\r\n sStkCd = sItem[CodeDef.PROC_STK_COL_STK_CD].text() # 종목코드\r\n self.DBH.deleteProcStk(sMktTpCd, sStkCd)\r\n self.ShowProcStkList()\r\n return None\r\n\r\n # 처리대상 종목 표시\r\n def ShowProcStkList(self):\r\n StkList = self.DBH.queryProcStkList()\r\n RowCnt = len(StkList.index)\r\n ColCnt = len(StkList.columns)\r\n self.tblProcStkList.setRowCount(RowCnt)\r\n self.tblProcStkList.setColumnCount(ColCnt)\r\n self.tblProcStkList.setHorizontalHeaderLabels(list(StkList))\r\n # 처리대상 종목리스트\r\n self.ProcStkList.clear()\r\n self.ProcStkList = list(StkList[\"STK_CD\"])\r\n\r\n for iRow in range(RowCnt):\r\n for iCol in range(ColCnt):\r\n item = QTableWidgetItem(StkList.iat[iRow,iCol])\r\n item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)\r\n self.tblProcStkList.setItem(iRow, iCol, item)\r\n\r\n self.tblProcStkList.resizeColumnsToContents()\r\n self.tblProcStkList.resizeRowsToContents()\r\n return None\r\n\r\n # 처리대상 종목 리스트 가져오기\r\n def GetProcStkList(self):\r\n return self.ProcStkList[:]\r\n\r\n # 처리종목 분봉시세 초기화\r\n def ClickInitMnQttn(self):\r\n Chk = ctypes.windll.user32.MessageBoxW(0, \"초기화 시작합니다.\", \"알림\", 1)\r\n if(Chk == 2):\r\n return None\r\n # 초기화 대상 종목 리스트 조회\r\n StkList = self.DBH.queryProcStkList()\r\n RowCnt = len(StkList.index)\r\n for iRow in range(RowCnt):\r\n\r\n # 티레이더 글로벌 초기화 확인\r\n if(StkList.iat[iRow, CodeDef.PROC_STK_COL_RCV_TP] != \"GLOBAL\"):\r\n continue\r\n\r\n MktTpCd = StkList.iat[iRow, CodeDef.PROC_STK_COL_MKT_TP_CD]\r\n StkCd = StkList.iat[iRow, CodeDef.PROC_STK_COL_STK_CD]\r\n LastDtMn = StkList.iat[iRow, CodeDef.PROC_STK_COL_LAST_DT_MN]\r\n LastDt = LastDtMn[:8]\r\n LastMn = LastDtMn[-4:]\r\n # 데이터가 없는 경우는 기본값 이용\r\n if (LastDt is None or len(LastDt.strip()) == 0):\r\n LastDt = CodeDef.INIT_STR_DT_DEFAULT\r\n if (LastMn is None or len(LastMn.strip()) == 0):\r\n LastMn = CodeDef.INIT_STR_MN_DEFAULT\r\n\r\n inEndDt = CodeDef.INIT_END_DT_DEFAULT\r\n inEndMn = CodeDef.INIT_END_MN_DEFAULT\r\n\r\n # 동기화보다 뒤면 패스\r\n if(int(LastDt + LastMn) >= int(CodeDef.INIT_END_DT_DEFAULT + CodeDef.INIT_END_MN_DEFAULT)):\r\n continue\r\n\r\n print(\"초기화 시작:\",StkCd,(LastDt + LastMn) ,(inEndDt + inEndMn))\r\n try:\r\n # 기존 시세삭제\r\n self.DBH.deleteMnQttn(MktTpCd, StkCd, LastDt, LastMn, inEndDt, inEndMn)\r\n\r\n # 시세 분봉 초기입력\r\n self.APIH.InitMnQttn(MktTpCd, StkCd, LastDt, LastMn, inEndDt, inEndMn)\r\n print(\"초기 분송 수신입력 종료:\", StkCd)\r\n\r\n # 빈분봉 처리시작\r\n print(\"빈분봉처리 시작!!:\", StkCd)\r\n\r\n # 빈분봉처리 대상 구간 조회\r\n print(\"조회:\", MktTpCd, StkCd, LastDt, LastMn, CodeDef.INIT_END_DT_DEFAULT, CodeDef.INIT_END_MN_DEFAULT)\r\n Qttn = self.DBH.queryMnQttn(MktTpCd,StkCd,LastDt,LastMn,CodeDef.INIT_END_DT_DEFAULT, CodeDef.INIT_END_MN_DEFAULT)\r\n\r\n ProcDt = datetime(year=int(LastDt[:4]), month=int(LastDt[4:6]), day=int(LastDt[6:]),hour=int(LastMn[:2]), minute=int(LastMn[2:]))\r\n if (CodeDef.isQttnBlnk(self, ProcDt)):\r\n ProcDt = CodeDef.getMon07AM(self,ProcDt)\r\n\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n QttnCnt = len(Qttn.index)\r\n FtPrc = 0.0\r\n HgPrc = 0.0\r\n LoPrc = 0.0\r\n ClPrc = 0.0\r\n UpdnPrc = 0.0\r\n Vlum = 0.0\r\n PreQttn = []\r\n Dt = None\r\n Mn = None\r\n for qIdx in range(QttnCnt):\r\n Dt = Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_DT]\r\n Mn = Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_MN]\r\n FtPrc = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_FTPRC])\r\n HgPrc = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_HGPRC])\r\n LoPrc = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_LOPRC])\r\n ClPrc = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_CLPRC])\r\n UpdnPrc = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_UPDN_PRC])\r\n Vlum = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_VLUM])\r\n\r\n if((Dt+Mn) == (ProcDt.strftime(\"%Y%m%d%H%M\"))):\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n # 이전시세 백업\r\n PreQttn = [FtPrc, HgPrc, LoPrc, ClPrc, UpdnPrc, Vlum]\r\n continue\r\n else:\r\n # 이전시세가 없으면 넘긴다\r\n if(len(PreQttn)==0):\r\n ProcDt = datetime(year=int(Dt[:4]), month=int(Dt[4:6]), day=int(Dt[6:]),\r\n hour=int(Mn[:2]), minute=int(Mn[2:4]))\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n PreQttn = [FtPrc, HgPrc, LoPrc, ClPrc, UpdnPrc, Vlum]\r\n continue\r\n\r\n EndDt = datetime(year=int(Dt[:4]), month=int(Dt[4:6]), day=int(Dt[6:]),hour=int(Mn[:2]), minute=int(Mn[2:4]))\r\n MnCnt = (EndDt - ProcDt).total_seconds()/60.0\r\n\r\n for eIdx in range(int(MnCnt)):\r\n # 비는 시세 확인\r\n if(CodeDef.isQttnBlnk(self, ProcDt)):\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n continue\r\n if(ProcDt == EndDt):\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n break\r\n\r\n self.DBH.insertMnQttn(MktTpCd, StkCd, ProcDt.strftime(\"%Y%m%d\"), ProcDt.strftime(\"%H%M\"), PreQttn[0], PreQttn[1], PreQttn[2], PreQttn[3], PreQttn[4], PreQttn[5])\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n\r\n # 이전시세 백업\r\n PreQttn = [FtPrc, HgPrc, LoPrc, ClPrc, UpdnPrc, Vlum]\r\n \r\n # 빈분봉 채우기 if 끝\r\n # 종목 시세 정리 for qIdx in range(QttnCnt): 끝\r\n\r\n # 마지막 시세가 초기화 종료일까지 못갔을 경우 마지막을 채운다.\r\n if(int(ProcDt.strftime(\"%Y%m%d%H%M\")) < int(CodeDef.INIT_END_DT_DEFAULT+CodeDef.INIT_END_MN_DEFAULT)):\r\n\r\n EndDt = datetime(year=int(CodeDef.INIT_END_DT_DEFAULT[:4]), month=int(CodeDef.INIT_END_DT_DEFAULT[4:6]), day=int(CodeDef.INIT_END_DT_DEFAULT[6:]), hour=int(CodeDef.INIT_END_MN_DEFAULT[:2]),minute=int(CodeDef.INIT_END_MN_DEFAULT[2:4]))\r\n MnCnt = (EndDt - ProcDt).total_seconds() / 60.0\r\n\r\n for eIdx in range(int(MnCnt)+1):\r\n # 비는 시세 확인\r\n if (CodeDef.isQttnBlnk(self, ProcDt)):\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n continue\r\n if (int(ProcDt.strftime(\"%H%M\")) > int(EndDt.strftime(\"%H%M\"))):\r\n #print(\"ProcDt:\",ProcDt,\"EndDt:\",EndDt)\r\n break\r\n\r\n self.DBH.insertMnQttn(MktTpCd, StkCd, ProcDt.strftime(\"%Y%m%d\"), ProcDt.strftime(\"%H%M\"),\r\n PreQttn[0], PreQttn[1], PreQttn[2], PreQttn[3], PreQttn[4], PreQttn[5])\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n\r\n except Exception as e:\r\n print(\"빈분봉처리에러:\",e,StkCd)\r\n return None\r\n\r\n # 최종 초기화 일자시각 입력\r\n self.DBH.updateProcStkLastDtMn(MktTpCd, StkCd, (inEndDt+inEndMn))\r\n\r\n # 처리종목별 처리 for iRow in range(RowCnt): 끝\r\n\r\n ctypes.windll.user32.MessageBoxW(0, \"초기화 완료되었습니다.\", \"알림\", 0)\r\n self.ShowProcStkList()\r\n return None\r\n\r\n # 지수시세 실시간 받기/종료\r\n def ClickRcvIdxQttn(self):\r\n # 중지실행\r\n if(self.NowRcvIdxQttn):\r\n if (self.QttnSctkT is not None):\r\n print(\"지수시세 쓰레드 중지 시작\")\r\n try:\r\n self.QttnSctkT.DoStop()\r\n self.QttnSctkT.join()\r\n except Exception as e:\r\n print(\"지수시세 받기 쓰레드 중지 에러:\", e)\r\n return None\r\n print(\"지수시세 Loop 종료됨.\")\r\n self.btnRcvIdxQttn.setText(\"지수시세수신\")\r\n self.NowRcvIdxQttn = False\r\n self.btnRcvIdxQttn.setStyleSheet(\"background-color:None\")\r\n # 받기시작\r\n else:\r\n try:\r\n self.QttnSctkT = RcvSckt_handler(self,CodeDef.PORT_INDEX_QTTN)\r\n self.QttnSctkT.start()\r\n except Exception as e:\r\n print(\"지수시세 받기 쓰레드 시작 에러:\", e)\r\n return None\r\n print(\"지수시세 Loop 시작됨.\")\r\n self.btnRcvIdxQttn.setText(\"지수시세중지\")\r\n self.NowRcvIdxQttn = True\r\n self.btnRcvIdxQttn.setStyleSheet(\"background-color:rgb(255,020,147)\")\r\n return None\r\n\r\n # 글로벌 실시간 시세 받기/종료\r\n def ClickRcvGlobalQttn(self):\r\n # 중지실행\r\n if (self.NowRcvGlobalQttn):\r\n #for idx in range(len(self.ProcStkList)):\r\n # self.APIH.StopRealRcv(None, self.ProcStkList[idx])\r\n self.APIH.StopAllRealRcv()\r\n self.btnRcvGlobalQttn.setText(\"글로벌시세수신\")\r\n self.NowRcvGlobalQttn = False\r\n self.btnRcvGlobalQttn.setStyleSheet(\"background-color:None\")\r\n print(\"Global 시세받기 종료됨.\")\r\n # 받기시작\r\n else:\r\n self.btnRcvGlobalQttn.setText(\"글로벌시세중지\")\r\n self.NowRcvGlobalQttn = True\r\n self.btnRcvGlobalQttn.setStyleSheet(\"background-color:rgb(255,020,147)\")\r\n print(\"Global 시세받기 시작됨.\")\r\n for idx in range(len(self.ProcStkList)):\r\n self.APIH.OnRequest(\"REAL_QTTN\", \"61\", self.ProcStkList[idx])\r\n #self.APIH.waitSrvrRspn()\r\n return None\r\n\r\n # 글로벌 저장된 시세 받기/종료\r\n def ClickRcvGlobalSavedQttn(self):\r\n # 중지실행\r\n if (self.NowRcvGlobalSavedQttn):\r\n try:\r\n self.TestQttnSnd.DoStop()\r\n #self.TestQttnSnd.join()\r\n except Exception as e:\r\n print(\"저장된 글로벌 시세받기 쓰레드 중지 에러:\", e)\r\n return None\r\n self.btnRcvGlobalSavedQttn.setText(\"저장된시세수신\")\r\n self.NowRcvGlobalSavedQttn = False\r\n self.btnRcvGlobalSavedQttn.setStyleSheet(\"background-color:None\")\r\n print(\"저장된 Global 시세받기 종료됨.\")\r\n # 받기시작\r\n else:\r\n try:\r\n if(self.TestQttnSnd is None):\r\n # 차트 X축 변경(0900에 시작으로 변경)\r\n self.CrtH.SetTestQttnXList()\r\n\r\n self.TestQttnSnd = TestQttn_Sender(self)\r\n self.TestQttnSnd.start()\r\n else:\r\n self.TestQttnSnd.DoRestart()\r\n except Exception as e:\r\n print(\"저장된 글로벌 시세받기 쓰레드 시작 에러:\", e)\r\n return None\r\n self.btnRcvGlobalSavedQttn.setText(\"저장된시세수신중지\")\r\n self.NowRcvGlobalSavedQttn = True\r\n self.btnRcvGlobalSavedQttn.setStyleSheet(\"background-color:rgb(255,020,147)\")\r\n print(\"저장된 Global 시세받기 시작됨.\")\r\n\r\n return None\r\n\r\n # 실시간 수신시세 처리\r\n # inProcTp : 처리구분\r\n # inQttn : 시세문자열\r\n def ProcRcvRealQttn(self,inProcTp,inRcvQttn):\r\n # 다중수신여부 확인\r\n inQttn = inRcvQttn.split(\"|\")\r\n InfoCnt = len(inQttn)\r\n QttnList = [] # 시세열\r\n Tmplist = [] # 임시 시세열\r\n # 시세 파싱\r\n for i in range(InfoCnt):\r\n if(len(inQttn[i]) == 0):\r\n continue\r\n # 시세넣기\r\n if (inQttn[i] == \"E\"):\r\n QttnList.append(Tmplist)\r\n Tmplist = []\r\n else:\r\n Tmplist.append(inQttn[i])\r\n\r\n # 시세차트설정\r\n if(inProcTp == \"KOSPI_INDEX\"):\r\n self.CrtH.UpdateRealQttn(QttnList, \"CurrentPrice\")\r\n #print(\"QttnList:\",QttnList)\r\n self.TFH.UpdateQttn(QttnList)\r\n elif(inProcTp == \"GLOBAL_QTTN\"):\r\n #self.CrtH.UpdateRealQttn(QttnList, \"Prediction\") # 테스트용\r\n # 딥러닝 시세 업데이트 및 시세 저장\r\n self.TFH.UpdateQttn(QttnList)\r\n elif (inProcTp == \"TF_RSLT\"):\r\n self.dispText(\"결과수신!!:\" + inRcvQttn)\r\n self.CrtH.UpdateRealQttn(QttnList, \"Prediction\") # 테스트용\r\n else:\r\n print(\"inProcTp 확인\")\r\n\r\n return None\r\n\r\n # 딥러닝 동작/중지\r\n def ClickTensorFlow(self):\r\n # 실행중지\r\n if (self.NowTensorFlow):\r\n # 송신 소켓은 따로 처리하지 않는다.\r\n # 수신 쓰레드 중지\r\n if (self.TfRcvSctkT is not None):\r\n print(\"딥러닝 쓰레드 중지 시작\")\r\n try:\r\n self.TfRcvSctkT.DoStop()\r\n self.TfRcvSctkT.join()\r\n except Exception as e:\r\n print(\"딥러닝 쓰레드 중지에러\")\r\n print(\"에러:\",e)\r\n return None\r\n print(\"딥러닝 Loop 종료됨.\")\r\n self.btnTensorFlow.setText(\"딥러닝연결\")\r\n self.btnTensorFlow.setStyleSheet(\"background-color:None\")\r\n self.NowTensorFlow = False\r\n # 동작실행\r\n else:\r\n # 수신소켓 쓰레드 시작\r\n try:\r\n self.TfRcvSctkT = RcvSckt_handler(self, CodeDef.PORT_TF_RCV_RSLT)\r\n self.TfRcvSctkT.start()\r\n except Exception as e:\r\n print(\"딥러닝 쓰레드 시작에러:\", e)\r\n return None\r\n\r\n # 송신소켓 접속\r\n try:\r\n if(self.TfSndSctkT is None):\r\n self.TfSndSctkT = SndSckt_handler()\r\n if (self.TfSndSctkT.GetOnSock() == False):\r\n self.TfSndSctkT.CnntSckt(CodeDef.PORT_TF_DATA)\r\n except Exception as e:\r\n print(\"송신소켓 접속 시작에러:\", e)\r\n return None\r\n print(\"딥러닝 Loop 시작됨.\")\r\n self.btnTensorFlow.setStyleSheet(\"background-color:rgb(255,020,147)\")\r\n self.btnTensorFlow.setText(\"딥러닝중지\")\r\n self.NowTensorFlow = True\r\n\r\n return None\r\n\r\n\r\n # 딥러닝 프로그램에 데이터 전송\r\n # TFQttn_handler에서 사용\r\n # inSndData : 전송데이터\r\n def SendTensorFlow(self,inSndData):\r\n #self.dispText(\"시세전송!!:\"+inSndData)\r\n # 데이터 전송\r\n try:\r\n if (self.TfSndSctkT is not None and self.TfSndSctkT.GetOnSock()):\r\n self.TfSndSctkT.SendData(inSndData)\r\n except Exception as e:\r\n print(\"딥러닝 데이터 전송 에러:\", e)\r\n\r\n return None\r\n\r\n\r\n # 비어있는 분봉시세 초기화만 처리\r\n def ClickMnQttnOrd(self):\r\n # 처리대상\r\n #StkList = ['NQU18','HGU18','ADU18']\r\n #StkList = ['ADU18']\r\n StkList = [\"USDCNH\"]\r\n RowCnt = len(StkList)\r\n for iRow in range(RowCnt):\r\n StkCd = StkList[iRow]\r\n print(\"처리시작:\",StkCd)\r\n try:\r\n # 분봉조회\r\n #Qttn = self.DBH.queryMnQttn(\"DERV\",StkCd,CodeDef.INIT_STR_DT_DEFAULT, CodeDef.INIT_STR_MN_DEFAULT, CodeDef.INIT_END_DT_DEFAULT, CodeDef.INIT_END_MN_DEFAULT)\r\n Qttn = self.DBH.queryMnQttn(\"DERV\", StkCd, \"20180604\", \"0900\",\"20181102\", \"0859\")\r\n\r\n ProcDt = datetime(year=int(CodeDef.INIT_STR_DT_DEFAULT[:4]), month=int(CodeDef.INIT_STR_DT_DEFAULT[4:6]), day=int(CodeDef.INIT_STR_DT_DEFAULT[6:]),hour=int(CodeDef.INIT_STR_MN_DEFAULT[:2]), minute=int(CodeDef.INIT_STR_MN_DEFAULT[2:]))\r\n if (CodeDef.isQttnBlnk(self, ProcDt)):\r\n ProcDt = CodeDef.getMon07AM(self,ProcDt)\r\n\r\n QttnCnt = len(Qttn.index)\r\n FtPrc = 0.0\r\n HgPrc = 0.0\r\n LoPrc = 0.0\r\n ClPrc = 0.0\r\n UpdnPrc = 0.0\r\n Vlum = 0.0\r\n PreQttn = []\r\n for qIdx in range(QttnCnt):\r\n Dt = Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_DT]\r\n Mn = Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_MN]\r\n FtPrc = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_FTPRC])\r\n HgPrc = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_HGPRC])\r\n LoPrc = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_LOPRC])\r\n ClPrc = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_CLPRC])\r\n UpdnPrc = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_UPDN_PRC])\r\n Vlum = float(Qttn.iat[qIdx, CodeDef.QTTN_MN_DATA_COL_VLUM])\r\n\r\n if( qIdx in [0,1,2,3,4]):\r\n print(\"(Dt+Mn) == (ProcDt.strftime(%Y%m%d%H%M)):\", (Dt + Mn), (ProcDt.strftime(\"%Y%m%d%H%M\")))\r\n\r\n if((Dt+Mn) == (ProcDt.strftime(\"%Y%m%d%H%M\"))):\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n # 이전시세 백업\r\n PreQttn = [FtPrc, HgPrc, LoPrc, ClPrc, UpdnPrc, Vlum]\r\n continue\r\n else:\r\n # 이전시세가 없으면 조회 첫번째로 세팅후 넘긴다\r\n if(len(PreQttn)==0):\r\n ProcDt = datetime(year=int(Dt[:4]), month=int(Dt[4:6]), day=int(Dt[6:]), hour=int(Mn[:2]),minute=int(Mn[2:4]))\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n PreQttn = [FtPrc, HgPrc, LoPrc, ClPrc, UpdnPrc, Vlum]\r\n continue\r\n\r\n #print(\"(Dt+Mn) == (ProcDt.strftime(%Y%m%d%H%M)):\", (Dt + Mn), (ProcDt.strftime(\"%Y%m%d%H%M\")))\r\n\r\n EndDt = datetime(year=int(Dt[:4]), month=int(Dt[4:6]), day=int(Dt[6:]),hour=int(Mn[:2]), minute=int(Mn[2:4]))\r\n MnCnt = (EndDt - ProcDt).total_seconds()/60.0\r\n\r\n for eIdx in range(int(MnCnt)):\r\n # 비는 시세 확인\r\n if(CodeDef.isQttnBlnk(self, ProcDt)):\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n continue\r\n if(ProcDt == EndDt):\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n break\r\n\r\n self.DBH.insertMnQttn(\"DERV\"\r\n , StkCd, ProcDt.strftime(\"%Y%m%d\"), ProcDt.strftime(\"%H%M\"), PreQttn[0], PreQttn[1], PreQttn[2], PreQttn[3], PreQttn[4], PreQttn[5])\r\n ProcDt = ProcDt + CodeDef.ONE_MINUTE\r\n\r\n # 이전시세 백업\r\n PreQttn = [FtPrc, HgPrc, LoPrc, ClPrc, UpdnPrc, Vlum]\r\n\r\n # -- 빈분봉 채워넣기 for문 종료 -----\r\n\r\n # ------- 조회된 시세 main for문 종료 ------\r\n except Exception as e:\r\n print(e)\r\n print(\"처리끝:\",StkCd)\r\n # --------- 빈분봉처리 종료 ---------\r\n ctypes.windll.user32.MessageBoxW(0, \"초기화 완료되었습니다.\", \"알림\", 0)\r\n return None\r\n\r\n # 출력 표시\r\n def dispText(self,inText):\r\n self.edtChk.append(inText) ## 임시확인\r\n return None\r\n\r\n # 첫시세 설정\r\n # 장중 마지막 시세를 가져와 설정함.\r\n def ClickSetFstQttn(self):\r\n\r\n print(\"첫시세 설정!!\")\r\n\r\n mn = int(datetime.today().strftime(\"%H%M\"))\r\n\r\n if(mn > 1500 or mn < 900):\r\n ctypes.windll.user32.MessageBoxW(0, \"장중에만 사용가능\", \"알림\", 0)\r\n return None\r\n\r\n FstQttn = self.DBH.queryFstTFQttn()\r\n\r\n RowCnt = len(FstQttn)\r\n for idx in range(RowCnt):\r\n FstQttn[idx] = str(FstQttn[idx])\r\n\r\n print(\"FstQttn:\", FstQttn)\r\n\r\n self.TFH.SetFstQttn(FstQttn)\r\n\r\n return None\r\n\r\n # 분봉 시세 저장\r\n # inProcTp : 처리구분\r\n # inStkCd : 종목코드\r\n # inDt : 일자\r\n # inTime : 시간(HHMM)\r\n # inFtPrc : 시가\r\n # inHgPrc : 고가\r\n # inLoPrc : 저가\r\n # inClPrc : 종가\r\n # inUpDnPrc : 등락가\r\n # inVlum : 거래량\r\n def insertMnQttn(self, inProcTp, inStkCd, inDt, inMn, inFtPrc, inHgPrc, inLoPrc, inClPrc, inUpDnPrc, inVlum):\r\n\r\n self.DBH.insertMnQttn(inProcTp, inStkCd, inDt,inMn, inFtPrc, inHgPrc, inLoPrc, inClPrc, inUpDnPrc, inVlum)\r\n\r\n return None","sub_path":"YT_Prediction/MainForm_handler.py","file_name":"MainForm_handler.py","file_ext":"py","file_size_in_byte":26752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"406594986","text":"import cv2\nimport os\nimport glob\nimport tf_calib\nimport numpy as np\n\ntry:\n import python.modules.tf_calib\nexcept ImportError:\n pass\n\n\ndef calibrate(path: str, filter: str, nrows: int, ncols: int):\n calibrator = tf_calib.TFCalib()\n objp = np.zeros((nrows * ncols, 3), np.float32)\n objp[:, :2] = np.mgrid[0:nrows, 0:ncols].T.reshape(-1, 2)\n for imname in glob.glob(os.path.join(path, filter)):\n image = cv2.imread(imname, cv2.IMREAD_GRAYSCALE)\n f, corners = cv2.findChessboardCorners(image, (nrows, ncols), None)\n cv2.cornerSubPix(image, corners, (11, 11), (-1, -1),\n (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001))\n calibrator.train(np.squeeze(corners.astype(np.float64)), objp)\n\n\ndef test_solve():\n def f1(x, y):\n return x ** 2 + x * y\n\n def f2(x, y):\n return y ** 2 + 2 * y\n\n x_sol = 2\n y_sol = 3\n\n constants = [f1(x_sol, y_sol), f2(x_sol, y_sol)]\n X = np.ndarray((2,), dtype=np.float32)\n tf_calib.solve([f1, f2], constants, np.array([[0., 3.], [2., 4.]]), X, 100)\n\n\nif __name__ == '__main__':\n # test_solve()\n calibrate('/data/stereo_images/left', 'left*.png', 8, 13)\n","sub_path":"python/modules/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"486115885","text":"from abc import ABCMeta, abstractmethod\n\nclass CourseException(Exception):\n\tdef __init__(self, message):\n\t\tsuper().__init__(message)\n\nclass Course():\n\tdef __init__(self, name):\n\t\tself.name = name\n\t\tself.teachers = set()\n\t\tself.students = set()\n\t\n\tdef __repr__(self):\n\t\treturn self.name\n\t\n\tdef add_teacher(self, teacher):\n\t\tif not isinstance(teacher, Teacher):\n\t\t\traise CourseException(\n\t\t\t\t'Class \"{}\" is not Teacher!'.format(teacher)\n\t\t\t)\n\t\t\t\n\t\tif teacher not in self.teachers:\n\t\t\tself.teachers.add(teacher)\n\t\tif not teacher.hasCource(self):\n\t\t\tteacher.add_cource(self)\n\t\t\n\tdef remove_teacher(self, teacher):\n\t\tif not isinstance(teacher, Teacher):\n\t\t\traise CourseException(\n\t\t\t\t'Class \"{}\" is not Teacher!'.format(teacher)\n\t\t\t)\n\t\t\n\t\tif teacher in self.teachers:\n\t\t\tself.teachers.remove(teacher)\n\t\tif teacher.hasCource(self):\n\t\t\tteacher.remove_cource(self)\n\t\t\t\n\tdef hasTeacher(self, teacher):\n\t\tif not isinstance(teacher, Teacher):\n\t\t\traise CourseException(\n\t\t\t\t'Class \"{}\" is not Teacher!'.format(teacher)\n\t\t\t)\n\t\t\t\n\t\treturn teacher in self.teachers\n\t\t\n\tdef get_list_all_teachers(self):\n\t\treturn list(self.teachers)\n\t\t\n\tdef add_student(self, student):\n\t\tif not isinstance(student, Student):\n\t\t\traise CourseException(\n\t\t\t\t'Class \"{}\" is not Student!'.format(student)\n\t\t\t)\n\t\t\t\n\t\tif student not in self.students:\n\t\t\tself.students.add(student)\n\t\tif not student.hasCource(self):\n\t\t\tstudent.add_cource(self)\n\t\t\n\tdef remove_student(self, student):\n\t\tif not isinstance(student, Student):\n\t\t\traise CourseException(\n\t\t\t\t'Class \"{}\" is not Student!'.format(student)\n\t\t\t)\n\t\t\n\t\tif student in self.students:\n\t\t\tself.students.remove(student)\n\t\tif student.hasCource(self):\n\t\t\tstudent.remove_cource(self)\n\t\n\tdef hasStudent(self, student):\n\t\tif not isinstance(student, Student):\n\t\t\traise CourseException(\n\t\t\t\t'Class \"{}\" is not Student!'.format(student)\n\t\t\t)\n\t\t\t\n\t\treturn student in self.students\n\t\t\n\tdef get_list_all_students(self):\n\t\treturn list(self.students)\n\t\n\tdef getInfoAboutCources(self):\n\t\treturn 'Курс \"{}\". \\nПреподаватели: {} \\nСтуденты: {}\\n'.format(self.name, \\\n\t\t\t\"\".join(str(i) for i in list(self.teachers)), \"\".join(str(i) for i in list(self.students)))\n\t\n\t\t\n\t\t\nclass RoleInItmoCourceException(Exception):\n\tdef __init__(self, message):\n\t\tsuper().__init__(message)\n\t\t\t\nclass RoleInItmoCource(metaclass=ABCMeta):\n\tdef __init__(self, firstname, lastname):\n\t\tself.firstname = firstname\n\t\tself.lastname = lastname\n\t\tself.cources = set()\n\t\n\t@abstractmethod\n\tdef __repr__(self):\n\t\tpass\n\t\n\tdef add_cource(self, cource):\n\t\tif not isinstance(cource, Course):\n\t\t\traise RoleInItmoCourceException(\n\t\t\t\t'Class \"{}\" is not Course!'.format(cource)\n\t\t\t)\n\t\tself.cources.add(cource)\n\t\t\n\tdef remove_cource(self, cource):\n\t\tif not isinstance(cource, Course):\n\t\t\traise RoleInItmoCourceException(\n\t\t\t\t'Class \"{}\" is not Course!'.format(cource)\n\t\t\t)\n\t\tif cource in self.cources:\n\t\t\tself.cources.remove(cource)\n\t\t\n\tdef getInfoAboutCources(self):\n\t\treturn ''.join(str(i) for i in list(self.cources))\n\t\t\n\tdef hasCource(self, cource):\n\t\tif not isinstance(cource, Course):\n\t\t\traise RoleInItmoCourceException(\n\t\t\t\t'Class \"{}\" is not Course!'.format(cource)\n\t\t\t)\n\t\treturn cource in self.cources\n\t\t\n\tdef get_list_all_cources(self):\n\t\treturn list(self.cources)\n\nclass Student(RoleInItmoCource):\n\tdef __init__(self, firstname, lastname):\n\t\tsuper().__init__(firstname, lastname)\n\t\n\tdef __repr__(self):\n\t\treturn '\"{} {}\"'.format(self.firstname, self.lastname)\n\t\n\tdef getInfoAboutCources(self):\n\t\treturn 'Я учусь на следующих курсах: \"{}\"'.format(super().getInfoAboutCources())\n\t\t\n\tdef remove_cource(self, cource):\n\t\tsuper().remove_cource(cource)\n\t\tif cource.hasStudent(self):\n\t\t\tcource.remove_student(self)\n\t\t\t\n\tdef add_cource(self, cource):\n\t\tsuper().add_cource(cource)\n\t\tif not cource.hasStudent(self):\n\t\t\tcource.add_student(self)\n\t\t\nclass Teacher(RoleInItmoCource):\n\tdef __init__(self, firstname, lastname, skills):\n\t\tsuper().__init__(firstname, lastname)\n\t\tself.skills = skills\n\t\n\tdef __repr__(self):\n\t\treturn '\"{} {}\" Умения: \"{}\".'.format(self.firstname, self.lastname, \\\n\t\t\t\", \".join(self.skills))\n\t\n\tdef getInfoAboutCources(self):\n\t\treturn 'Я преподаю на следующих курсах: \"{}\"'.format(super().getInfoAboutCources())\n\t\t\n\tdef remove_cource(self, cource):\n\t\tsuper().remove_cource(cource)\n\t\tif cource.hasTeacher(self):\n\t\t\tcource.remove_teacher(self)\n\t\t\t\n\tdef add_cource(self, cource):\n\t\tsuper().add_cource(cource)\n\t\tif not cource.hasTeacher(self):\n\t\t\tcource.add_teacher(self)\n\t\t\t\npython_cource = Course(\"Python\")\nteacher = Teacher(\"Кирилл\", \"Версетти\", ['Python', 'PHP', 'JS', 'HTML', 'CSS', 'Docker'])\nstudent = Student(\"Александр\", \"Разыграев\")\npython_cource.add_teacher(teacher)\npython_cource.add_student(student)\n\nprint(student.getInfoAboutCources())\nprint(teacher.getInfoAboutCources())\nprint(python_cource.getInfoAboutCources())\n\npython_cource.remove_teacher(teacher)\npython_cource.remove_student(student)\n\nprint(student.getInfoAboutCources())\nprint(teacher.getInfoAboutCources())\nprint(python_cource.getInfoAboutCources())\n\npython_cource.add_teacher(teacher)\npython_cource.add_student(student)\nstudent2 = Student(\"Иванов\", \"Иван\")\npython_cource.add_student(student2)\n\nprint(student.getInfoAboutCources())\nprint(teacher.getInfoAboutCources())\nprint(python_cource.getInfoAboutCources())\n\nteacher.remove_cource(python_cource)\nstudent2.remove_cource(python_cource)\n\nprint(student.getInfoAboutCources())\nprint(teacher.getInfoAboutCources())\nprint(python_cource.getInfoAboutCources())\n\nstudent2.add_cource(python_cource)\n\nprint(student.getInfoAboutCources())\nprint(teacher.getInfoAboutCources())\nprint(python_cource.getInfoAboutCources())\n\nprint(python_cource.get_list_all_students())\nprint(python_cource.get_list_all_teachers())\nprint(student2.get_list_all_cources())","sub_path":"task_training_center.py","file_name":"task_training_center.py","file_ext":"py","file_size_in_byte":5859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"380658606","text":"import math\nfrom display import *\n\ndef magnitude(vector):\n return math.sqrt(math.pow(vector[0],2)+math.pow(vector[1],2)+math.pow(vector[2],2))\n\n#vector functions\n#normalize vector, should modify the parameter\ndef normalize(vector):\n print(vector)\n length = magnitude(vector)\n if length==0:\n return vector\n else:\n vector[0]/=length\n vector[1]/=length\n vector[2]/=length\n return vector\n#Return the dot porduct of a . b\ndef dot_product(a, b):\n return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]\n\n#Calculate the surface normal for the triangle whose first\n#point is located at index i in polygons\ndef calculate_normal(polygons, i):\n p0=polygons[i]\n p1=polygons[i+1]\n p2=polygons[i+2]\n a=[p1[0]-p0[0],p1[1]-p0[1],p1[2]-p0[2]]\n b=[p2[0]-p0[0],p2[1]-p0[1],p2[2]-p0[2]]\n n=[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]]\n return n\n","sub_path":"gmath.py","file_name":"gmath.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"575735525","text":"#encoding=utf-8\r\nimport os\r\nimport json\r\nfrom apyori import apriori # Frequent Pattern 分析用\r\nimport jieba # 中文斷詞用\r\nfrom langconv import* # 繁體轉簡體用,為了讓 結巴 的中文斷詞表現更好\r\nfrom wordcloud import WordCloud\r\n\r\n# 有些字我們不在乎,只要一碰到就可以去掉它...\r\nstop_word_list = [', ', ',', '...', '的', '\\xa0', ' ', '「', '」', '。', ',', '、', '(', ')', ':', '.', '...', '】', '【', '....', '”',\r\n 'a', 'is', 'of', 'the', 'an', 'to', 'as', 'at', 'by', 'in', 'on', 'with', 'for', 'and', 'are', 'that', 'have', 'has', 'had', 'we',\r\n '-', '—', 'your', 'its', '', '“', '/', ';', '》', '《', '“', 'he', 'they', 'was', 'or', 'be', 'this', 'how', 'his', 'per',\r\n 'it\\'s', 'so', 'who', 'were', 'their', 'it', 'what', 'you', 'our', 'she', 'my', 'say', 10, 20]\r\n\r\n# 讀取 英文 版本JSON檔,並將所有檔案整合成一份 txt 檔並輸出,接著再做資料處理 (老實說,模組化寫得不好... 較無彈性...)\r\n# 因為中文版處理方式較麻煩 (需斷詞),故分成兩種版本\r\ndef read_json_en(keywords_of_title_en, keywords_of_text_en):\r\n # 將所有爬到的 English新聞 們整合成一份 txt 檔案,以便將來討論某個特定關鍵字的成因\r\n def aggregate_news_en(json_file):\r\n with open('aggregated_news_en.txt', 'w') as f:\r\n for data in json_file:\r\n f.write('news_title: ')\r\n f.write(str(data['news_title'].encode(encoding=\"utf-8\")))\r\n f.write('\\n')\r\n f.write('news_text: ')\r\n f.write(str(data['news_text'].encode(encoding=\"utf-8\")))\r\n f.write('\\n')\r\n f.write('news_link: ')\r\n f.write(str(data['news_link'].encode(encoding=\"utf-8\")))\r\n f.write('\\n\\n')\r\n\r\n\r\n # 我們要一次處理多個 json 檔案,這邊要 ***手動*** 設定資料夾名稱,並放在project的同一個資料夾內 (或者用絕對路徑)\r\n file_name = ['Anti+Extradition+Law_0622', 'Hong+Kong_0622', 'Tiananmen_0622']\r\n # 把所有讀進來的JSON檔案存進一個list內\r\n json_data_list = list()\r\n for name in file_name:\r\n if os.path.exists(name):\r\n print(name + '/' + name[:-5] + '.json')\r\n with open(name + '/' + name[:-5] + '.json', 'r') as input_file:\r\n tmp_json_data = json.load(input_file)\r\n json_data_list.extend(tmp_json_data)\r\n else:\r\n print('資料夾名稱: %s 應該有誤,請檢查' % (name))\r\n # print(json_data_list)\r\n # print(len(json_data_list)) # 看一下讀進了幾條新聞\r\n aggregate_news_en(json_data_list) # 將所有讀進來的 英文 新聞整合成一份txt檔\r\n\r\n # 開始把句子中的單字拆出來,順便去除stop_word,未來要做資料分析用\r\n for news in json_data_list:\r\n # 處理標題\r\n tmp = []\r\n for char in news['news_title'].lower().split(): # 記得要一律轉成小寫,不然之後會分析不出frequent pattern\r\n if char not in stop_word_list:\r\n tmp.append(char)\r\n keywords_of_title_en.append(tmp)\r\n\r\n # 處理內文\r\n tmp = []\r\n for char in news['news_text'].lower().split(): # 記得要一律轉成小寫,不然之後會分析不出frequent pattern\r\n if char not in stop_word_list:\r\n tmp.append(char)\r\n keywords_of_text_en.append(tmp)\r\n\r\n\r\n# 讀取 中文 版本JSON檔,並將所有檔案整合成一份 txt 檔並輸出,接著再做資料處理 (老實說,模組化寫得不好... 較無彈性...)\r\n# 因為中文版處理方式較麻煩 (需斷詞),故分成兩種版本\r\ndef read_json_ch(keywords_of_title_ch, keywords_of_text_ch):\r\n # 將所有爬到的新聞們整合成一份 txt 檔案,中文版需處理編碼問題,比較麻煩\r\n def aggregate_news_ch(json_file):\r\n with open('aggregated_news_ch.txt', 'wb') as f: # 這邊要記得用wb\r\n for data in json_file:\r\n f.write('news_title: '.encode('utf8'))\r\n f.write(data['news_title'].encode('utf8'))\r\n f.write('\\n'.encode('utf8'))\r\n f.write('news_text: '.encode('utf8'))\r\n f.write(data['news_text'].encode(encoding=\"utf-8\"))\r\n f.write('\\n'.encode('utf8'))\r\n f.write('news_link: '.encode('utf8'))\r\n f.write(data['news_link'].encode(encoding=\"utf-8\"))\r\n f.write('\\n\\n'.encode('utf8'))\r\n\r\n\r\n # 我們要一次處理多個 json 檔案,這邊要 ***手動*** 設定資料夾名稱,並放在project的同一個資料夾內 (或者用絕對路徑)\r\n file_name = ['六四_0622', '香港_0622', '反送中_0622']\r\n json_data_list = list()\r\n for name in file_name:\r\n if os.path.exists(name):\r\n with open(name + '/' + name[:-5] + '.json', 'r') as input_file:\r\n tmp_json_data = json.load(input_file)\r\n json_data_list.extend(tmp_json_data)\r\n else:\r\n print('檔案名稱: %s 應該有誤,請檢查' % (name))\r\n # print(json_data_list)\r\n # print(len(json_data_list)) # 看一下讀進了幾條新聞\r\n aggregate_news_ch(json_data_list) # 將所有讀進來的 中文 新聞整合成一份txt檔\r\n\r\n # 開始把句子中的字拆出來 (中文斷詞),順便去除stop_word,未來要做資料分析用\r\n for news in json_data_list:\r\n # 處理標題\r\n title = news['news_title'] # 中文比較麻煩,沒辦法用split來切。 需使用 結巴 函式庫\r\n title = Converter('zh-hans').convert(title) # 繁體中文轉換成簡體中文,這樣斷詞的效果比較好\r\n # print(title)\r\n seg_list = jieba.cut(title, cut_all=False, HMM=True) # 預設精準模式\r\n # seg_list = jieba.cut_for_search(title, HMM=True) # 搜尋引擎模式,好像沒有比較厲害?\r\n split_word = \"/\".join(seg_list)\r\n # print(split_word)\r\n keywords_of_title_ch.append(split_word)\r\n\r\n # 處理內文\r\n text = news['news_text'] # 中文比較麻煩,沒辦法用split來切。 需使用 結巴 函式庫\r\n text = Converter('zh-hans').convert(text) # 繁體中文轉換成簡體中文,這樣斷詞的效果比較好\r\n # print(text)\r\n seg_list = jieba.cut(text, cut_all=False, HMM=True) # 預設精準模式\r\n # seg_list = jieba.cut_for_search(text, HMM=True) # 搜尋引擎模式,不知道有沒有比較厲害?\r\n split_word = \"/\".join(seg_list)\r\n # print(split_word)\r\n keywords_of_text_ch.append(split_word)\r\n\r\n # 將斷詞過後的中文 標題 弄成適合作Apriori的資料格式 (list),故使用到tmp, tmp2 (外層list包一堆內層list)\r\n tmp = []\r\n for sentence in keywords_of_title_ch:\r\n words = sentence.split('/')\r\n tmp2 = []\r\n for word in words:\r\n if word not in stop_word_list:\r\n word = Converter('zh-hant').convert(word) # 最後轉換回繁體中文\r\n tmp2.append(word)\r\n tmp.append(tmp2)\r\n keywords_of_title_ch[:] = tmp # 這麼做超級重要!! 因為 keywords_of_text_ch[] = tmp 只是改變local的指標,當函數結束就被回收了 (所以不會真的變動到...)\r\n\r\n # 將斷詞過後的中文 內文 弄成適合作Apriori的資料格式 (list),故使用到tmp, tmp2 (外層list包一堆內層list)\r\n tmp = []\r\n for sentence in keywords_of_text_ch:\r\n words = sentence.split('/')\r\n tmp2 = []\r\n for word in words:\r\n if word not in stop_word_list:\r\n word = Converter('zh-hant').convert(word) # 最後轉換回繁體中文\r\n tmp2.append(word)\r\n tmp.append(tmp2)\r\n keywords_of_text_ch[:] = tmp # 這麼做超級重要!! 因為 keywords_of_text_ch[] = tmp 只是改變local的指標,當函數結束就被回收了 (所以不會真的變動到...)\r\n\r\n\r\n# 回傳frequent pattern分析後的結果 (frozen set)\r\ndef frequent_pattern_analyze(data):\r\n print('----- 開始Frequent Pattern分析... (Apriori) -----')\r\n # print(data)\r\n association_rules = apriori(data)\r\n association_results = list(association_rules)\r\n frequent_pattern_result = []\r\n for i in association_results:\r\n frequent_pattern_result.append(i)\r\n print('----- Frequent Pattern分析完成! -----')\r\n return frequent_pattern_result\r\n\r\n\r\n# 由於Frequent Pattern效果不好,故嘗試關鍵字頻率分析\r\ndef frequency_statistics(data):\r\n frequency_count = {}\r\n for news_title in data:\r\n for word in news_title:\r\n if word not in frequency_count and word not in stop_word_list:\r\n frequency_count[word] = 1\r\n elif word in frequency_count and word not in stop_word_list:\r\n frequency_count[word] += 1\r\n\r\n # 依照出現頻率由大到小排序\r\n sorted_frequency_count = sorted(frequency_count.items(), key=lambda x: x[1], reverse=True)\r\n # 這邊再進一步處理,把一些 單一字 或 頻率太低的字過濾掉 (e.g., '我': 14)\r\n freq_count_result = []\r\n for i in sorted_frequency_count:\r\n if len(i[0]) >= 2 and i[1] >= 15: # len(i[0]) 是中文詞長度、len(i[1]) 是出現頻率 (原則上我們對單一中文字沒興趣,故過濾)\r\n freq_count_result.append( (i[0], i[1]) )\r\n return freq_count_result\r\n\r\n\r\n# 方便 print list用的\r\ndef print_data(data):\r\n print(' --- print data... ---')\r\n for i in data:\r\n print(i)\r\n print(' --- print finished! ---')\r\n\r\n# 將分析出來的 頻率統計 輸出成4個txt檔案,以供將來做成文字雲\r\ndef output_frequency_count(word_count_title_en, word_count_text_en,\r\n word_count_title_ch, word_count_text_ch):\r\n with open('word_count_title_en.txt', 'w') as f:\r\n for tuple in word_count_title_en:\r\n for i in range(tuple[1]):\r\n f.write(tuple[0] + ' ')\r\n f.write('\\n')\r\n with open('word_count_text_en.txt', 'w') as f:\r\n for tuple in word_count_text_en:\r\n for i in range(tuple[1]):\r\n f.write(tuple[0] + ' ')\r\n f.write('\\n')\r\n with open('word_count_title_ch.txt', 'w') as f:\r\n for tuple in word_count_title_ch:\r\n for i in range(tuple[1]):\r\n f.write(tuple[0] + ' ')\r\n f.write('\\n')\r\n with open('word_count_text_ch.txt', 'w') as f:\r\n for tuple in word_count_text_ch:\r\n for i in range(tuple[1]):\r\n f.write(tuple[0] + ' ')\r\n f.write('\\n')\r\n\r\n\r\n# 將統計出來的資料視覺化成文字雲 共4張圖片,不輸出frequent pattern (沒有找到明顯的pattern, 且格式比較難處理)\r\ndef output_word_cloud():\r\n # 這邊要 ***手動*** 設定txt檔案名稱,並放在project的同一個資料夾內 (或者用絕對路徑)\r\n for file_name in ['word_count_title_en', 'word_count_text_en', 'word_count_title_ch', 'word_count_text_ch']:\r\n text = open( file_name + \".txt\", 'r').read()\r\n wc = WordCloud(background_color=\"white\",\r\n width=1000,\r\n height=860,\r\n margin=2,\r\n font_path='msyh.ttf', # 引入一個支援中文的字型,建議字型放在同一個資料夾內\r\n collocations=False, # 這行超重要!!!,不然字體會重複出現多次\r\n max_words=100,\r\n max_font_size=150,\r\n min_font_size=32)\r\n wc.generate(text)\r\n wc.to_file(file_name + '.png')\r\n\r\n\r\nif __name__ == '__main__':\r\n # 首先宣告list,未來要存新聞 標題&內文 關鍵詞用的\r\n keywords_of_title_en, keywords_of_text_en = list(), list()\r\n keywords_of_title_ch, keywords_of_text_ch = list(), list()\r\n\r\n # 讀取 English JSON檔案,並存進 keywords_of_title_en, keywords_of_text_en 兩個list\r\n read_json_en(keywords_of_title_en, keywords_of_text_en)\r\n print_data(keywords_of_title_en)\r\n print_data(keywords_of_text_en)\r\n\r\n # 讀取 中文 JSON檔案,並存進 keywords_of_title_ch, keywords_of_text_ch 兩個list\r\n read_json_ch(keywords_of_title_ch, keywords_of_text_ch)\r\n print_data(keywords_of_title_ch)\r\n print_data(keywords_of_text_ch)\r\n\r\n # 開始做 英文版 Frequent Pattern 分析\r\n frequent_pattern_of_title_en = frequent_pattern_analyze(keywords_of_title_en)\r\n print_data(frequent_pattern_of_title_en)\r\n frequent_pattern_of_text_en = frequent_pattern_analyze(keywords_of_text_en)\r\n print_data(frequent_pattern_of_text_en)\r\n\r\n # 開始做 中文版 Frequent Pattern 分析\r\n frequent_pattern_of_title_ch = frequent_pattern_analyze(keywords_of_title_ch)\r\n print_data(frequent_pattern_of_title_ch)\r\n frequent_pattern_of_text_ch = frequent_pattern_analyze(keywords_of_text_ch)\r\n print_data(frequent_pattern_of_text_ch)\r\n\r\n # 開始做 English版 字彙頻率 分析\r\n frequency_count_of_title_en = frequency_statistics(keywords_of_title_en)\r\n print_data(frequency_count_of_title_en)\r\n frequency_count_of_text_en = frequency_statistics(keywords_of_text_en)\r\n print_data(frequency_count_of_text_en)\r\n\r\n # 開始做 中文版 字彙頻率 分析\r\n frequency_count_of_title_ch = frequency_statistics(keywords_of_title_ch)\r\n print_data(frequency_count_of_title_ch)\r\n frequency_count_of_text_ch = frequency_statistics(keywords_of_text_ch)\r\n print_data(frequency_count_of_text_ch)\r\n\r\n # 開始輸出 字母頻率 統計,共4個txt檔案\r\n output_frequency_count(frequency_count_of_title_en, frequency_count_of_text_en, frequency_count_of_title_ch, frequency_count_of_text_ch)\r\n # 開始輸出 文字雲 ,會讀取上一步驟之4個txt檔案 (或者你自己準備其他txt檔案也可以啦...)\r\n output_word_cloud()","sub_path":"DataScience_Final/show_data.py","file_name":"show_data.py","file_ext":"py","file_size_in_byte":14112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"3869032","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\n\n\ndef write_helpfile(obj):\n \"\"\"\n Function to write help(obj) to file in current working directory.\n \"\"\"\n filename = obj.__class__.__name__ + '_help.txt'\n try:\n with open(filename, 'w') as f:\n t = sys.stdout\n sys.stdout = f\n help(obj)\n sys.stdout = t\n if not os.path.isfile(filename):\n raise Exception('No file written')\n except Exception as e:\n print('Error in helpfilewriter: ', e)\n else:\n print(f'Class {obj.__class__.__name__} help file {filename} saved to working directory.')\n","sub_path":"OpenSeries/helpfilewriter.py","file_name":"helpfilewriter.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"165899912","text":"#coding=utf-8\n\n\"\"\"\nCreated on 2020/11/18\n@author: lianxiujuan\n@desc: 标签-托盘\n\"\"\"\n\nimport pytest\nimport sys\nfrom DataApp.LabelmgData import *\nfrom src.public.common.Close_current_tab import Close_current_tab\nfrom src.public.common.Login import *\nfrom src.pageobjectAPP.pageLabel import *\nfrom src.public.common.Select_Item import *\nfrom src.public.common.Search_Item import *\nimport random,string\n\nlabeldata = ''.join(random.sample(string.ascii_letters + string.digits, 4))\n\n\nclass Test_palletlabel:\n def test_palletlabel_login(self):\n login_label()\n new_click(pallet)\n time.sleep(2)\n label_add(labeldata, labeldata, labeldata, labeldata)\n time.sleep(2)\n assert new_page_source(labeldata)\n\n # 新增 标签-托盘\n def test_add_palletlabel(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n label_add(palletcode, palletname, palletdesc, palletzpl)\n time.sleep(2)\n assert new_page_source(palletcode)\n\n # 搜索 标签-托盘\n def test_search_palletlabel(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n search_item(\"编码\", palletcode)\n time.sleep(2)\n ele = new_find_elements(searchresult)\n text = new_get_text_ele(ele[0])\n time.sleep(2)\n assert palletcode in text\n search_item(\"编码\", ' ')\n time.sleep(2)\n\n # 编辑 标签-托盘\n def test_edit_palletlabel(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n select_item(palletcode)\n label_edit(editname, editdesc, editzpl)\n time.sleep(2)\n assert new_page_source(editname)\n\n # 设置标准模板\n def test_setdefault_palletlabel(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n label_setdefault()\n time.sleep(2)\n select_item(labeldata)\n label_setdefault()\n time.sleep(2)\n\n # 删除 标签-托盘\n def test_delete_palletlabel(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n select_item(palletcode)\n label_delete()\n time.sleep(2)\n assert new_page_source(palletcode) == False\n sleep(1)\n Close_current_tab()\n\n\nif __name__ == '__main__':\n pytest.main(['-s','test_palletlabelcase.py'])\n","sub_path":"TestcaseApp/Label/test_palletlabel.py","file_name":"test_palletlabel.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"19755451","text":"import datetime\n\nimport pymysql\n\nconnection = pymysql.connect(user='root', db='data', unix_socket='/var/lib/mysql/mysql.sock')\n\nfor table in ['detail_user_reg']:\n total = 0\n day = datetime.date(2017, 1, 1)\n\n start_time = datetime.datetime.now()\n while day < datetime.date(2017, 12, 31):\n print(table, day)\n for batch_commit in range(1):\n for execute in range(100):\n with connection.cursor() as cursor:\n values_str = '(%s,\"%s\")' % (total, day.strftime('%Y-%m-%d'))\n total += 1\n for i in range(999):\n values_str += ',(%s,\"%s\")' % (total, day.strftime('%Y-%m-%d'))\n total += 1\n sql = \"INSERT INTO `\" + table + \"` (`uid`, `date`) VALUES \" + values_str\n cursor.execute(sql)\n connection.commit()\n day += datetime.timedelta(days=1)\n print('Insert complete! Time used: ', datetime.datetime.now() - start_time)\n","sub_path":"insert_huge_data.py","file_name":"insert_huge_data.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"171700375","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport pronouncing as pr\nfrom collections import Counter\nimport re\nimport json\n\ndef nl_split(text, char):\n\n # split the given text into a list of its sentences, split by every newline\n sentences_nl_split = [sentence.split() for sentence in text.split(char)]\n\n # for each word in every sentence, remove any special characters from it and lowercase it\n words = [[re.sub('[^A-Za-z0-9]+', '', word).lower() for word in sentence] for sentence in sentences_nl_split]\n\n # create one single list of all the words separated by a space\n word_list = []\n for line in words:\n if len(line) == 0:\n continue\n else:\n for word in line:\n word_list.append(word)\n word_list.append(' ')\n\n return word_list\n\ndef sounds(words):\n\n # for each word in a sentence, find its arpabet translation, append them into a single list, assume first phone\n sound_list = []\n for word in words:\n if word == ' ':\n sound_list.append(word)\n continue\n else:\n sound = pr.phones_for_word(word)\n # if len of sound == 0, it was not recognized as a word in the cmu dictionary\n if len(sound) == 0:\n sound_list.append('*')\n else:\n sound_list.append(sound[0])\n return sound_list\n\ndef stresses(sounds):\n # for each sound of every word, find the syllable stress pattern\n stress_list = []\n for sound in sounds:\n if sound == ' ':\n stress_list.append(sound)\n elif sound == '*':\n stress_list.append(sound)\n else:\n stress_list.append(pr.stresses(sound))\n return stress_list\n\n\ndef word_count(words):\n c = dict(Counter(words))\n del c[\" \"]\n counts = [{\"word\":key, \"count\":value} for key, value in c.items()]\n return counts\n\ndef phones_count(sounds):\n # count individual sounds in it arpabet word\n individual_sounds = []\n for word in sounds:\n phone = str(word).split()\n for sound in phone:\n individual_sounds.append(sound)\n c = dict(Counter(individual_sounds))\n #convert counter object c into a Json object with a key, value\n sound_json = [{\"phone\":key, \"count\":value} for key, value in c.items()]\n\n\n return sound_json\n\ndef stress_csv(stresses):\n\n # create csv of stresses\n f = open(\"stresses.csv\", \"w\")\n for stress in stresses:\n if stress == ' ':\n f.write('\\n')\n else:\n f.write(stress + ' ')\n f.close()\n\ndef create_json(dict, filename):\n\n #create a json file of the phones counter\n f = open(filename, \"w\")\n json.dump(dict, f, sort_keys = True, indent = 4)\n f.close()\n\n\n\n","sub_path":"poetryparser.py","file_name":"poetryparser.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"55007732","text":"# Sacado de https://scipy.github.io/old-wiki/pages/Cookbook/Matplotlib/LaTeX_Examples.html\n\nimport matplotlib.pyplot as plt\nimport pylab\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n#import numarray\nfrom pylab import arange,pi,sin,cos,sqrt,savefig\n\n\ngolden_mean = (math.sqrt(5)-1.0)/2.0 # Aesthetic ratio\nfig_width = 3+3/8 \t\t\t # width in inches\nfig_height = fig_width*golden_mean # height in inches\nfig_size = [fig_width,fig_height]\n\nparams = {'backend': 'ps',\n 'axes.titlesize': 8,\n 'axes.labelsize': 9,\n 'axes.linewidth': 0.5, \n 'axes.grid': True,\n 'axes.labelweight': 'normal', \n 'font.family': 'serif',\n 'font.size': 8.0,\n 'font.weight': 'normal',\n 'text.color': 'black',\n 'xtick.labelsize': 8,\n 'ytick.labelsize': 8,\n 'text.usetex': True,\n 'legend.fontsize': 8,\n 'figure.dpi': 300,\n 'figure.figsize': fig_size,\n 'savefig.dpi': 300,\n }\n\npylab.rcParams.update(params)\n\n### DATA\n\ndata = np.genfromtxt('out_distbc_225p_1.2m.txt', delimiter = ' ')\n\nvd = data[:,0]\ndistance = data[:,1]\nerror = data[:,2]\n\n### PLOT\n\npylab.figure(1)\npylab.clf()\n\n\nplt.plot(vd,distance,'wo',zorder=3) \nplt.plot(vd,distance,'k',lw=1.0,zorder=2) \nplt.errorbar(vd,distance,error,linestyle='-',fmt='.',color='w',ecolor='k',label='N=225',zorder=1) \n\n\n#pylab.xticks(np.arange(0,8,2))\n#pylab.yticks(np.arange(20,100,20))\npylab.xlabel('$v_d$~(m/s)')\npylab.ylabel('Distance~(m)')\npylab.legend()\n#pylab.ylim(20, 80)\n#pylab.xlim(0, 6)\nlgd=plt.legend() \nlgd.set_visible(False)\n \npylab.savefig('distancebc_225p_1.2m.eps', format='eps', dpi=300, bbox_inches='tight')\n\n\n\n'''\n\n####################OLD STUFF#########################\n\n#plt.legend(loc=4)\n#pylab.grid(True)\n\n#plt.scatter(gap1,te1,marker='o',s=50, color='w', zorder=0)\n#plt.axhline(y=31, xmin=0, xmax=8, linewidth=1, color = 'black',ls='dashed')\n\nplt.figure(1)\nplt.errorbar(gap1,te1,yerr1,linestyle='',marker='o',color='red',label='vd= 4 m/s ')\nplt.errorbar(gap2,te2,yerr2,linestyle='',marker='o',label='vd= 8 m/s')\nplt.errorbar(gap3,te3,yerr3,linestyle='',marker='o',color='green',label='N= 961')\n#plt.axhline(y=40, xmin=0, xmax=21, linewidth=2, color = 'green') #linea horizontal\n#plt.axvline(1.2,linewidth=2, color='k', linestyle='-')\nplt.legend(loc=4)\nplt.xlabel('Gap size (m)',fontsize=22)\nplt.ylabel('Evacuation Time (s)', fontsize=22)\n'''\n\n","sub_path":"bc2/d_medio/plot_dmed.py","file_name":"plot_dmed.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"157007732","text":"import numpy as np\nimport pandas as pd\nfrom scipy.spatial import distance\nimport scipy, argparse, os, sys, csv, io, time\n\nimport torch\nimport torch.nn as nn\nimport torch.functional as F\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, Dataset\n\nclass log_manager_heracles():\n def __init__(self, args):\n self.G = np.zeros((2,))\n self.D = np.zeros((2,))\n self.total_tp = np.zeros((2,))\n self.total_len = np.zeros((2,))\n self.Dx = np.zeros((2,))\n self.Dx_score = np.zeros((2,))\n self.D_Gz1 = np.zeros((2,))\n self.D_Gz1_score = np.zeros((2,))\n self.D_Gz2 = np.zeros((2,))\n self.D_Gz2_score = np.zeros((2,))\n self.loss_Dx = np.zeros((2,))\n self.loss_D_Gz1 = np.zeros((2,))\n self.loss_D_Gz2 = np.zeros((2,))\n self.recall = np.zeros((2,))\n self.tr_total_loss_Dx = []\n self.tr_total_loss_D_Gz1 = []\n self.tr_total_loss_D_Gz2 = []\n self.te_total_loss_Dx = []\n self.te_total_loss_D_Gz1 = []\n self.te_total_loss_D_Gz2 = []\n self.tr_recall = []\n self.te_recall = []\n def accumlate_D(self, Dx, Dx_score, D_Gz1, D_Gz1_score, train=True):\n mode = 0 if train else 1\n self.D[mode] += 1\n self.Dx[mode] += Dx\n self.Dx_score[mode] += Dx_score\n self.D_Gz1[mode] += D_Gz1\n self.D_Gz1_score[mode] += D_Gz1_score\n self.loss_Dx[mode] += (2 * self.Dx[mode] + 3 * self.Dx_score[mode])\n self.loss_D_Gz1[mode] += (2 * self.D_Gz1[mode] + 3 * self.D_Gz1_score[mode])\n def accumlate_G(self, D_Gz2, D_Gz2_score, train=True):\n mode = 0 if train else 1\n self.G[mode] += 1\n self.D_Gz2[mode] += D_Gz2\n self.D_Gz2_score[mode] += D_Gz2_score\n self.loss_D_Gz2[mode] += (2 * self.D_Gz2[mode] + 3 * self.D_Gz2_score[mode])\n def accumlate_R(self, tp, total_l, train=True):\n mode = 0 if train else 1\n self.total_tp[mode] += tp\n self.total_len[mode] += total_l\n self.recall[mode] = self.total_tp[mode] / self.total_len[mode] *100\n def display(self, train=True):\n mode = 0 if train else 1\n return (self.Dx[mode]/self.D[mode], self.D_Gz1[mode]/self.D[mode],\n self.D_Gz2[mode]/self.G[mode], self.recall[mode])\n def record_log(self):\n self.tr_total_loss_Dx.append(self.Dx[0]/self.D[0])\n self.tr_total_loss_D_Gz1.append(self.D_Gz1[0]/self.D[0])\n self.tr_total_loss_D_Gz2.append(self.D_Gz2[0]/self.G[0])\n self.te_total_loss_Dx.append(self.Dx[1]/self.D[1])\n self.te_total_loss_D_Gz1.append(self.D_Gz1[1]/self.D[1])\n self.te_total_loss_D_Gz2.append(self.D_Gz2[1]/self.G[1])\n self.tr_recall.append(self.recall[0])\n self.te_recall.append(self.recall[1])\n np.savez(os.path.join('log', 'log_{}.npz'.format('heracles')),\n train_Dx= self.tr_total_loss_Dx,\n train_D_Gz1 = self.tr_total_loss_D_Gz1,\n train_D_Gz2 = self.tr_total_loss_D_Gz2,\n train_recall = self.tr_recall,\n test_Dx = self.te_total_loss_Dx,\n test_D_Gz1 = self.te_total_loss_D_Gz1,\n test_D_Gz2 = self.te_total_loss_D_Gz2,\n test_recall = self.te_recall)\n self.clean_record()\n def clean_record(self):\n self.G = np.zeros((2,))\n self.D = np.zeros((2,))\n self.total_tp = np.zeros((2,))\n self.total_len = np.zeros((2,))\n self.Dx = np.zeros((2,))\n self.Dx_score = np.zeros((2,))\n self.D_Gz1 = np.zeros((2,))\n self.D_Gz1_score = np.zeros((2,))\n self.D_Gz2 = np.zeros((2,))\n self.D_Gz2_score = np.zeros((2,))\n self.loss_Dx = np.zeros((2,))\n self.loss_D_Gz1 = np.zeros((2,))\n self.loss_D_Gz2 = np.zeros((2,))\n self.recall = np.zeros((2,))\n def plot_log(self):\n import matplotlib\n import matplotlib.pyplot as plt\n matplotlib.use('Agg')\n plt.figure(figsize=(16,12))\n plt.clf()\n plt.subplot(2, 1, 1)\n l1 = np.array(self.tr_recall).flatten()\n l2 = np.array(self.te_recall).flatten()\n plt.xlabel('Epochs')\n plt.plot(l1, label='train')\n plt.plot(l2, label='test')\n plt.legend(loc='lower right')\n plt.title('{}_recall'.format('heracles'))\n plt.subplot(2, 3, 4)\n l1 = np.array(self.tr_total_loss_Dx).flatten()\n l2 = np.array(self.te_total_loss_Dx).flatten()\n plt.xlabel('Epochs')\n plt.plot(l1, label='train')\n plt.plot(l2, label='test')\n plt.legend(loc='upper right')\n plt.title('{}_D(x)'.format('heracles'))\n plt.subplot(2, 3, 5)\n l1 = np.array(self.tr_total_loss_D_Gz1).flatten()\n l2 = np.array(self.te_total_loss_D_Gz1).flatten()\n plt.xlabel('Epochs')\n plt.plot(l1, label='train')\n plt.plot(l2, label='test')\n plt.legend(loc='upper right')\n plt.title('{}_D(G(z1))'.format('heracles'))\n plt.subplot(2, 3, 6)\n l1 = np.array(self.tr_total_loss_D_Gz2).flatten()\n l2 = np.array(self.te_total_loss_D_Gz2).flatten()\n plt.xlabel('Epochs')\n plt.plot(l1, label='train')\n plt.plot(l2, label='test')\n plt.legend(loc='upper right')\n plt.title('{}_D(G(z2))'.format('heracles'))\n plt.tight_layout()\n plt.savefig(os.path.join('plot', 'heracles'))\n plt.close()\n\nclass log_manager():\n def __init__(self, args):\n self.model = args.mt\n self.end2end = \"End-to-End\" if args.end2end == \"True\" else \"Non-End-to-End\"\n self.count = np.zeros((2,))\n self.total_loss = np.zeros((2,))\n self.total_tp = np.zeros((2,))\n self.total_len = np.zeros((2,))\n self.recall = np.zeros((2,))\n self.loss = np.zeros((2,))\n\n self.tr_loss = []\n self.te_loss = []\n self.tr_recall = []\n self.te_recall = []\n def accumulate(self, loss, tp, total, train=True):\n mode = 0 if train else 1\n self.count[mode] += 1\n self.total_loss[mode] += loss\n self.total_tp[mode] += tp\n self.total_len[mode] += total\n self.recall[mode] = self.total_tp[mode] / self.total_len[mode] *100\n self.loss[mode] = self.total_loss[mode]/ self.count[mode]\n def record_log(self):\n self.tr_loss.append(self.loss[0])\n self.tr_recall.append(self.recall[0])\n self.te_loss.append(self.loss[1])\n self.te_recall.append(self.recall[1])\n np.savez(os.path.join('log', 'log_{}_{}.npz'.format(self.model, self.end2end)),\n train_loss= self.tr_loss,\n train_recall = self.tr_recall,\n test_loss = self.te_loss,\n test_recall = self.te_recall)\n self.clean_record()\n def clean_record(self):\n self.count = np.zeros((2,))\n self.total_loss = np.zeros((2,))\n self.total_tp = np.zeros((2,))\n self.total_len = np.zeros((2,))\n self.recall = np.zeros((2,))\n self.loss = np.zeros((2,))\n def plot_log(self):\n import matplotlib\n import matplotlib.pyplot as plt\n matplotlib.use('Agg')\n plt.figure(figsize=(16,12))\n plt.clf()\n plt.subplot(2, 1, 1)\n l1 = np.array(self.tr_loss).flatten()\n l2 = np.array(self.te_loss).flatten()\n plt.xlabel('Epochs')\n plt.plot(l1, label='train')\n plt.plot(l2, label='test')\n plt.legend(loc='upper right')\n plt.title('{}_{}_loss'.format(self.end2end, self.model))\n plt.subplot(2,1,2)\n l1 = np.array(self.tr_recall).flatten()\n l2 = np.array(self.te_recall).flatten()\n plt.xlabel('Epochs')\n plt.plot(l1, label='train')\n plt.plot(l2, label='test')\n plt.legend(loc='lower right')\n plt.title('{}_{}_recall'.format(self.end2end, self.model))\n plt.tight_layout()\n plt.savefig(os.path.join('plot', self.end2end+'_'+self.model))\n plt.close()\n\ndef cos_cdist(y_pred, vec_matrix):\n return scipy.spatial.distance.cdist(y_pred, vec_matrix, 'euclidean')\n\ndef top_k(y_pred, vec_matrix, k):\n tmp = cos_cdist(y_pred, vec_matrix)\n total_top_k = np.argsort(tmp)[:, :k]\n return total_top_k\n\ndef f1_score(top_k_result, hashtag_y, idx2word):\n # string compare to string\n gt_hashtag, to_word = [], []\n tp, total_l = 0, 0\n for ele in hashtag_y:\n ele = ele.strip().split()\n gt_hashtag.append(ele)\n for row in range(len(top_k_result)):\n tmp = []\n for ele in top_k_result[row]:\n tmp += [idx2word[ele]]\n to_word.append(tmp)\n for row_idx in range(len(to_word)):\n tp += len(set(to_word[row_idx])&set(gt_hashtag[row_idx]))\n total_l += len(gt_hashtag[row_idx])\n return tp, total_l\n\n\nif __name__ == \"__main__\":\n a = np.array([[1,0,0], [0,1,0]])\n b = np.array([[1,0,0],[0,1,1]])\n c = np.array([[0,1,0]])\n print(a, b, c)\n print(cos_cdist(a,b))\n print(cos_cdist(a,c))\n print(np.argsort(cos_cdist(a,b)))\n print(\"this is evalution pyfile\")\n","sub_path":"hades_model/utils/evalution.py","file_name":"evalution.py","file_ext":"py","file_size_in_byte":9179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"625722639","text":"#!/usr/bin/python\n# This file is part of Ansible\n#\n# Ansible 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# Ansible 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 Ansible. If not, see .\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\n\nDOCUMENTATION = \"\"\"\n---\nmodule: elasticache_parameter_group\nshort_description: Manage cache security groups in Amazon Elasticache.\ndescription:\n - Manage cache security groups in Amazon Elasticache.\n - Returns information about the specified cache cluster.\nversion_added: \"2.3\"\nauthor: \"Sloane Hertel (@s-hertel)\"\nextends_documentation_fragment:\n - aws\n - ec2\nrequirements: [ boto3, botocore ]\noptions:\n group_family:\n description:\n - The name of the cache parameter group family that the cache parameter group can be used with.\n Required when creating a cache parameter group.\n choices: ['memcached1.4', 'memcached1.5', 'redis2.6', 'redis2.8', 'redis3.2', 'redis4.0', 'redis5.0']\n name:\n description:\n - A user-specified name for the cache parameter group.\n required: yes\n description:\n description:\n - A user-specified description for the cache parameter group.\n state:\n description:\n - Idempotent actions that will create/modify, destroy, or reset a cache parameter group as needed.\n choices: ['present', 'absent', 'reset']\n required: true\n values:\n description:\n - A user-specified dictionary of parameters to reset or modify for the cache parameter group.\n\"\"\"\n\nEXAMPLES = \"\"\"\n# Note: None of these examples set aws_access_key, aws_secret_key, or region.\n# It is assumed that their matching environment variables are set.\n---\n- hosts: localhost\n connection: local\n tasks:\n - name: 'Create a test parameter group'\n elasticache_parameter_group:\n name: 'test-param-group'\n group_family: 'redis3.2'\n description: 'This is a cache parameter group'\n state: 'present'\n - name: 'Modify a test parameter group'\n elasticache_parameter_group:\n name: 'test-param-group'\n values:\n activerehashing: yes\n client-output-buffer-limit-normal-hard-limit: 4\n state: 'present'\n - name: 'Reset all modifiable parameters for the test parameter group'\n elasticache_parameter_group:\n name: 'test-param-group'\n state: reset\n - name: 'Delete a test parameter group'\n elasticache_parameter_group:\n name: 'test-param-group'\n state: 'absent'\n\"\"\"\n\nRETURN = \"\"\"\nelasticache:\n description: cache parameter group information and response metadata\n returned: always\n type: dict\n sample:\n cache_parameter_group:\n cache_parameter_group_family: redis3.2\n cache_parameter_group_name: test-please-delete\n description: \"initial description\"\n response_metadata:\n http_headers:\n content-length: \"562\"\n content-type: text/xml\n date: \"Mon, 06 Feb 2017 22:14:08 GMT\"\n x-amzn-requestid: 947291f9-ecb9-11e6-85bd-3baa4eca2cc1\n http_status_code: 200\n request_id: 947291f9-ecb9-11e6-85bd-3baa4eca2cc1\n retry_attempts: 0\nchanged:\n description: if the cache parameter group has changed\n returned: always\n type: bool\n sample:\n changed: true\n\"\"\"\n\n# import module snippets\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.ec2 import boto3_conn, get_aws_connection_info, ec2_argument_spec, camel_dict_to_snake_dict\nfrom ansible.module_utils._text import to_text\nfrom ansible.module_utils.six import string_types\nimport traceback\n\ntry:\n import boto3\n import botocore\n HAS_BOTO3 = True\nexcept ImportError:\n HAS_BOTO3 = False\n\n\ndef create(module, conn, name, group_family, description):\n \"\"\" Create ElastiCache parameter group. \"\"\"\n try:\n response = conn.create_cache_parameter_group(CacheParameterGroupName=name, CacheParameterGroupFamily=group_family, Description=description)\n changed = True\n except botocore.exceptions.ClientError as e:\n module.fail_json(msg=\"Unable to create cache parameter group.\", exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))\n return response, changed\n\n\ndef delete(module, conn, name):\n \"\"\" Delete ElastiCache parameter group. \"\"\"\n try:\n conn.delete_cache_parameter_group(CacheParameterGroupName=name)\n response = {}\n changed = True\n except botocore.exceptions.ClientError as e:\n module.fail_json(msg=\"Unable to delete cache parameter group.\", exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))\n return response, changed\n\n\ndef make_current_modifiable_param_dict(module, conn, name):\n \"\"\" Gets the current state of the cache parameter group and creates a dict with the format: {ParameterName: [Allowed_Values, DataType, ParameterValue]}\"\"\"\n current_info = get_info(conn, name)\n if current_info is False:\n module.fail_json(msg=\"Could not connect to the cache parameter group %s.\" % name)\n\n parameters = current_info[\"Parameters\"]\n modifiable_params = {}\n\n for param in parameters:\n if param[\"IsModifiable\"]:\n modifiable_params[param[\"ParameterName\"]] = [param.get(\"AllowedValues\")]\n modifiable_params[param[\"ParameterName\"]].append(param[\"DataType\"])\n modifiable_params[param[\"ParameterName\"]].append(param.get(\"ParameterValue\"))\n return modifiable_params\n\n\ndef check_valid_modification(module, values, modifiable_params):\n \"\"\" Check if the parameters and values in values are valid. \"\"\"\n changed_with_update = False\n\n for parameter in values:\n new_value = values[parameter]\n\n # check valid modifiable parameters\n if parameter not in modifiable_params:\n module.fail_json(msg=\"%s is not a modifiable parameter. Valid parameters to modify are: %s.\" % (parameter, modifiable_params.keys()))\n\n # check allowed datatype for modified parameters\n str_to_type = {\"integer\": int, \"string\": string_types}\n expected_type = str_to_type[modifiable_params[parameter][1]]\n if not isinstance(new_value, expected_type):\n if expected_type == str:\n if isinstance(new_value, bool):\n values[parameter] = \"yes\" if new_value else \"no\"\n else:\n values[parameter] = to_text(new_value)\n elif expected_type == int:\n if isinstance(new_value, bool):\n values[parameter] = 1 if new_value else 0\n else:\n module.fail_json(msg=\"%s (type %s) is not an allowed value for the parameter %s. Expected a type %s.\" %\n (new_value, type(new_value), parameter, modifiable_params[parameter][1]))\n else:\n module.fail_json(msg=\"%s (type %s) is not an allowed value for the parameter %s. Expected a type %s.\" %\n (new_value, type(new_value), parameter, modifiable_params[parameter][1]))\n\n # check allowed values for modifiable parameters\n choices = modifiable_params[parameter][0]\n if choices:\n if not (to_text(new_value) in choices or isinstance(new_value, int)):\n module.fail_json(msg=\"%s is not an allowed value for the parameter %s. Valid parameters are: %s.\" %\n (new_value, parameter, choices))\n\n # check if a new value is different from current value\n if to_text(values[parameter]) != modifiable_params[parameter][2]:\n changed_with_update = True\n\n return changed_with_update, values\n\n\ndef check_changed_parameter_values(values, old_parameters, new_parameters):\n \"\"\" Checking if the new values are different than the old values. \"\"\"\n changed_with_update = False\n\n # if the user specified parameters to reset, only check those for change\n if values:\n for parameter in values:\n if old_parameters[parameter] != new_parameters[parameter]:\n changed_with_update = True\n break\n # otherwise check all to find a change\n else:\n for parameter in old_parameters:\n if old_parameters[parameter] != new_parameters[parameter]:\n changed_with_update = True\n break\n\n return changed_with_update\n\n\ndef modify(module, conn, name, values):\n \"\"\" Modify ElastiCache parameter group to reflect the new information if it differs from the current. \"\"\"\n # compares current group parameters with the parameters we've specified to to a value to see if this will change the group\n format_parameters = []\n for key in values:\n value = to_text(values[key])\n format_parameters.append({'ParameterName': key, 'ParameterValue': value})\n try:\n response = conn.modify_cache_parameter_group(CacheParameterGroupName=name, ParameterNameValues=format_parameters)\n except botocore.exceptions.ClientError as e:\n module.fail_json(msg=\"Unable to modify cache parameter group.\", exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))\n return response\n\n\ndef reset(module, conn, name, values):\n \"\"\" Reset ElastiCache parameter group if the current information is different from the new information. \"\"\"\n # used to compare with the reset parameters' dict to see if there have been changes\n old_parameters_dict = make_current_modifiable_param_dict(module, conn, name)\n\n format_parameters = []\n\n # determine whether to reset all or specific parameters\n if values:\n all_parameters = False\n format_parameters = []\n for key in values:\n value = to_text(values[key])\n format_parameters.append({'ParameterName': key, 'ParameterValue': value})\n else:\n all_parameters = True\n\n try:\n response = conn.reset_cache_parameter_group(CacheParameterGroupName=name, ParameterNameValues=format_parameters, ResetAllParameters=all_parameters)\n except botocore.exceptions.ClientError as e:\n module.fail_json(msg=\"Unable to reset cache parameter group.\", exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))\n\n # determine changed\n new_parameters_dict = make_current_modifiable_param_dict(module, conn, name)\n changed = check_changed_parameter_values(values, old_parameters_dict, new_parameters_dict)\n\n return response, changed\n\n\ndef get_info(conn, name):\n \"\"\" Gets info about the ElastiCache parameter group. Returns false if it doesn't exist or we don't have access. \"\"\"\n try:\n data = conn.describe_cache_parameters(CacheParameterGroupName=name)\n return data\n except botocore.exceptions.ClientError as e:\n return False\n\n\ndef main():\n argument_spec = ec2_argument_spec()\n argument_spec.update(\n dict(\n group_family=dict(type='str', choices=['memcached1.4', 'memcached1.5', 'redis2.6', 'redis2.8', 'redis3.2', 'redis4.0', 'redis5.0']),\n name=dict(required=True, type='str'),\n description=dict(default='', type='str'),\n state=dict(required=True),\n values=dict(type='dict'),\n )\n )\n module = AnsibleModule(argument_spec=argument_spec)\n\n if not HAS_BOTO3:\n module.fail_json(msg='boto required for this module')\n\n parameter_group_family = module.params.get('group_family')\n parameter_group_name = module.params.get('name')\n group_description = module.params.get('description')\n state = module.params.get('state')\n values = module.params.get('values')\n\n # Retrieve any AWS settings from the environment.\n region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)\n if not region:\n module.fail_json(msg=\"Either region or AWS_REGION or EC2_REGION environment variable or boto config aws_region or ec2_region must be set.\")\n\n connection = boto3_conn(module, conn_type='client',\n resource='elasticache', region=region,\n endpoint=ec2_url, **aws_connect_kwargs)\n\n exists = get_info(connection, parameter_group_name)\n\n # check that the needed requirements are available\n if state == 'present' and not (exists or parameter_group_family):\n module.fail_json(msg=\"Creating a group requires a family group.\")\n elif state == 'reset' and not exists:\n module.fail_json(msg=\"No group %s to reset. Please create the group before using the state 'reset'.\" % parameter_group_name)\n\n # Taking action\n changed = False\n if state == 'present':\n if exists:\n # confirm that the group exists without any actions\n if not values:\n response = exists\n changed = False\n # modify existing group\n else:\n modifiable_params = make_current_modifiable_param_dict(module, connection, parameter_group_name)\n changed, values = check_valid_modification(module, values, modifiable_params)\n response = modify(module, connection, parameter_group_name, values)\n # create group\n else:\n response, changed = create(module, connection, parameter_group_name, parameter_group_family, group_description)\n if values:\n modifiable_params = make_current_modifiable_param_dict(module, connection, parameter_group_name)\n changed, values = check_valid_modification(module, values, modifiable_params)\n response = modify(module, connection, parameter_group_name, values)\n elif state == 'absent':\n if exists:\n # delete group\n response, changed = delete(module, connection, parameter_group_name)\n else:\n response = {}\n changed = False\n elif state == 'reset':\n response, changed = reset(module, connection, parameter_group_name, values)\n\n facts_result = dict(changed=changed, elasticache=camel_dict_to_snake_dict(response))\n\n module.exit_json(**facts_result)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"env/lib/python3.9/site-packages/ansible/modules/cloud/amazon/elasticache_parameter_group.py","file_name":"elasticache_parameter_group.py","file_ext":"py","file_size_in_byte":14590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"239034193","text":"# Copyright 2018 Spotify AB. 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\"\"\"Utilities and Mocked Data for tests\"\"\"\n\nfrom comet_core.app import EventContainer\n\n\ndef get_all_test_messages(parsed=False):\n \"\"\"Get all test messages and their filenames as an iterator.\n\n Args:\n parsed (bool): returns Event objects if true otherwise strings\n Yields:\n EventContainer: some test event\n \"\"\"\n event = EventContainer('test', {})\n event.set_owner('test@acme.org')\n event.set_fingerprint('test')\n return [event]\n","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"223931895","text":"import sys\nimport logging\nimport sqlite3\nimport hashlib\nimport csv\nfrom pathlib import Path\n\nlogger = logging.getLogger(\"sqlitedb\")\n\n\nclass LocalDB():\n def __init__(self, dbLoc=None):\n \"\"\"init the sqlite database class\n\n Args:\n dbLoc ([string], optional): database filename. Defaults to :memory:\n \"\"\"\n self.conn = None\n if dbLoc == None:\n dbLoc = \":memory:\"\n\n logger.debug(f\"attempt open db {dbLoc}\")\n try:\n self.conn = sqlite3.connect(\n dbLoc, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)\n except sqlite3.Error as errID:\n logger.critical(\n f\"Database connection failure. \", exc_info=True)\n sys.exit(1)\n except Exception as err:\n logger.critical(f\"Error: {err}\", exc_info=True)\n sys.exit(1)\n\n logger.debug(f\"successful connection to {dbLoc}\")\n\n c = self.conn.cursor()\n c.execute(\"PRAGMA foreign_keys = ON\")\n c.execute(\"PRAGMA database_list;\")\n xtmp = c.fetchall()\n logger.debug(f\"PRAGMA database_list: {xtmp}\")\n\n def _exeScriptFile(self, scriptFileName):\n \"\"\"Executes a Script file. (internal use only)\n\n Args:\n scriptFileName (string): SQL script file to run\n \"\"\"\n\n logger.debug(f\"loading script: {scriptFileName} to memory\")\n scriptFile = open(scriptFileName, 'r')\n script = scriptFile.read()\n scriptFile.close()\n logger.debug(f\"executing script: {scriptFileName}\")\n try:\n c = self.conn.cursor()\n c.executescript(script)\n except Exception as e:\n logger.critical(\n f\"Unexpected Error running script: {scriptFileName}. Exception {e}\", exc_info=True)\n sys.exit(1)\n\n self.conn.commit()\n logger.debug(f\"script: {scriptFileName} commited successfully\")\n\n def _exeSQLInsert(self, sql, theVals):\n \"\"\"Submit insert type sql. (internal use only)\n\n Args:\n sql (string): The insert Sql, this will include INSERT\n theVals : The value parms passed into the sql.\n theVals type depends on the sql, i.e. list or dict.\n\n Returns:\n [list]: [int,string]\n Samples:\n [0, \"Commit successful\"]\n [2, f\"sqlite integrity error: {e.args[0]}\"]\n Unexpected error will exit app\n \"\"\"\n logger.debug(f\"Sql: {sql}\")\n logger.debug(f\"Values: {theVals}\")\n try:\n c = self.conn.cursor()\n c.execute(sql, theVals)\n self.conn.commit()\n\n except sqlite3.IntegrityError as e:\n logger.warning(f\"sqlite integrity error: {e.args[0]}\")\n return [2, f\"sqlite integrity error: {e.args[0]}\"]\n except Exception as e:\n logger.critical(\n f\"Unexpected error executing sql: {sql}. Values are {theVals} Exception: {e}\", exc_info=True)\n sys.exit(1)\n\n logger.debug(\"successful commit of sql\")\n return [0, \"Commit successful\"]\n\n def initDB(self, scriptPath):\n \"\"\"Create tables, views, indexes for the database\n\n ASSUMPTION database is new, and tables do not exist.\n Args:\n scriptPath (string): Path to script(s). Defaults to None.\n \"\"\"\n logger.info(f\"scriptPath={scriptPath}\")\n gtScripts = Path(scriptPath)\n logger.info(f\"Executing scripts to create database\")\n\n scriptFile = gtScripts / \"createtables.sql\"\n logger.debug(f\"Executing {scriptFile}\")\n self._exeScriptFile(scriptFileName=f'{scriptFile}')\n\n def addLibKeyRec(self, srcRec):\n \"\"\"Add a record to the Library Key table\n\n Args:\n srcRec ([class srcRec]): Source record to add\n\n Returns:\n [int]: The primary key id for the added source record\n \"\"\"\n sql = \"INSERT INTO t_libkeys (server, library, filePath, skey, uKey) VALUES (:server, :libName, :uFilePath, :sKey, :uKey)\"\n theVals = {'server': srcRec.svrName,\n 'libName': srcRec.libName, 'uFilePath': srcRec.uFilePath, 'sKey': srcRec.sKey, 'uKey': srcRec.uKey}\n r = self._exeSQLInsert(sql, theVals)\n\n # Getting the rowID for the record just added.\n try:\n c = self.conn.cursor()\n c.execute(\"select last_insert_rowid()\")\n row = c.fetchone()\n except Exception as e:\n logger.critical(\n f\"Unexpected error executing sql: {sql}. Exception: {e}\", exc_info=True)\n sys.exit(1)\n\n return row[0]\n\n def addLibValRec(self, keyRec):\n sql = \"INSERT INTO t_libvals (srcKey_id, s_value) VALUES (:srcKey, :sValue)\"\n theVals = {'srcKey': keyRec.srckey_id, 'sValue': keyRec.sValue}\n logger.debug(f\"adding movie library value record\")\n return self._exeSQLInsert(sql, theVals)\n\n def exportLibDiff(self, oFile):\n \"\"\"Export the Library diff query to a csv file\n\n Args:\n oFile (string): File name for the csv file\n \"\"\"\n logger.debug(f\"oFile={oFile}\")\n\n sql = \"SELECT library, filePath, skey, server1_val, server2_val, isDiff FROM v_lib_DiffResults\"\n\n try:\n logger.debug(f\"executing sql: {sql}\")\n localc = self.conn.cursor()\n localc.execute(sql)\n\n except Exception as e:\n logger.critical(\n f\"Unexpected error executing sql: {sql}. Values are {theVals} Exception: {e}\", exc_info=True)\n sys.exit(1)\n\n logger.debug(f\"Writing sql results to: {oFile}\")\n with open(oFile, \"w\", newline='') as csv_file:\n csv_writer = csv.writer(csv_file, dialect='excel')\n csv_writer.writerow([i[0] for i in localc.description])\n csv_writer.writerows(localc)\n\n def exportColDiff(self, oFile):\n logger.debug(f\"oFile={oFile}\")\n sql = \"select libname as library, colname, skey, server1_val, server2_val, isdiff FROM v_col_DiffResults\"\n try:\n logger.debug(f\"executing sql: {sql}\")\n localc = self.conn.cursor()\n localc.execute(sql)\n except Exception as e:\n logger.critical(\n f\"Unexpected error executing sql: {sql}. Values are {theVals} Exception: {e}\", exc_info=True)\n sys.exit(1)\n\n logger.debug(f\"Writing sql results to: {oFile}\")\n with open(oFile, \"w\", newline='') as csv_file:\n csv_writer = csv.writer(csv_file, dialect='excel')\n csv_writer.writerow([i[0] for i in localc.description])\n csv_writer.writerows(localc)\n\n def addColKeyRec(self, keyRec):\n \"\"\"Add a record to the Collection keys table\n\n Args:\n keyRec (Class ColKey): Collection Key's object with values to write\n\n Returns:\n [int]: The primary key id for the added key record\n \"\"\"\n pass\n sql = \"INSERT INTO t_colkeys (svrName, libName, colName, sKey, uKey) VALUES (:svrName, :libName, :colName, :sKey, :uKey)\"\n theVals = {'svrName': keyRec.svrName, 'libName': keyRec.libName,\n 'colName': keyRec.colName, \"sKey\": keyRec.sKey, \"uKey\": keyRec.uKey}\n\n logger.debug(f\"adding collection key record : {theVals}, \")\n r = self._exeSQLInsert(sql, theVals)\n # Getting the rowID for the record just added.\n try:\n xcursor = self.conn.cursor()\n xcursor.execute(\"select last_insert_rowid()\")\n row = xcursor.fetchone()\n except Exception as e:\n logger.critical(\n f\"Unexpected error executing sql: {sql}. Exception: {e}\", exc_info=True)\n sys.exit(1)\n\n return row[0]\n\n def addColValRec(self, valRec):\n sql = \"INSERT INTO t_colvals (colkey_id, s_value) VALUES (:ColKey, :sValue)\"\n theVals = {'ColKey': valRec.srckey_id, 'sValue': valRec.sValue}\n\n logger.debug(f\"adding collection value record {valRec.srckey_id}\")\n\n return self._exeSQLInsert(sql, theVals)\n\n\nclass LibSrcKey():\n def __init__(self):\n self.svrName = \"\"\n self.libName = \"\"\n self.uFilePath = \"\"\n self.sKey = \"\"\n\n @property\n def uKey(self):\n # Returns unique key created by\n # returning md5 hexdigest of the combined:\n # - Library Name (libname)\n # - Universal File Path (uFilePath)\n # - Key (sKey)\n str2hash = self.libName + self.uFilePath + self.sKey\n return hashlib.md5(str2hash.encode()).hexdigest()\n\n\nclass LibKeyVal():\n def __init__(self):\n self.srckey_id = \"\"\n self.sValue = \"\"\n\n def __repr__(self):\n return f\"srckey_id={self.srckey_id}, svalue={self.sValue}\"\n\n\nclass ColKey():\n def __init__(self):\n self.svrName = \"\"\n self.libName = \"\"\n self.colName = \"\"\n self.sKey = \"\"\n\n @property\n def uKey(self):\n # Returns unique key created by\n # returning md5 hexdigest of the combined:\n # - Library Name (libname)\n # - Collection Name (colName)\n # - Key (sKey)\n str2hash = self.libName + self.colName + self.sKey\n return hashlib.md5(str2hash.encode()).hexdigest()\n\n\nclass ColKeyVal():\n def __init__(self):\n self.srckey_id = \"\"\n self.sValue = \"\"\n\n def __repr__(self):\n return f\"srckey_id={self.srckey_id}, svalue={self.sValue}\"\n","sub_path":"plexinfo/sqlitedb.py","file_name":"sqlitedb.py","file_ext":"py","file_size_in_byte":9488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"291973120","text":"# -*- coding: utf-8 -*-\n# This file is a personal adaptation the SPORCO package. Details of the\n# copyright for the toolbox and user license can be found in the 'LICENSE.txt'\n# file distributed with the package.\n\n\"\"\"Classes for ADMM algorithm for the Convolutional BPDN problem specific to the\"\n Object project. Adaptation from SPORCO.\"\"\"\n\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom builtins import range\nfrom builtins import object\n\nimport copy\nfrom types import MethodType\nimport collections\n\nimport numpy as np\nimport scipy\nfrom scipy import linalg\nimport tensorly as tl\n\nfrom sporco import cdict\nfrom sporco import util\nfrom sporco import common\nfrom sporco.admm import admm\nfrom sporco.admm import cbpdn\n\nimport sporco.cnvrep as cr\nimport sporco.linalg as sl\nimport sporco.prox as sp\nfrom sporco.util import u\n\n\n__author__ = \"\"\"David Reixach \"\"\"\n\nclass IterStatsConfig(object):\n \"\"\"Configuration object for Alternated Kruscal ConvBPDN learning algorithm\n iteration statistics.\n\n Adaptation from Sporco ditclearn::IterStatsConfig\n\n \"\"\"\n\n fwiter = 4\n \"\"\"Field width for iteration count display column\"\"\"\n fpothr = 2\n \"\"\"Field precision for other display columns\"\"\"\n\n\n def __init__(self, isfld, isxmap, evlmap, hdrtxt, hdrmap,\n fmtmap=None):\n \"\"\"\n Parameters\n ----------\n isfld : list\n List of field names for iteration statistics namedtuple\n isxmap : dict\n Dictionary mapping iteration statistics namedtuple field names\n to field names in corresponding X step object iteration\n statistics namedtuple\n evlmap : dict\n Dictionary mapping iteration statistics namedtuple field names\n to labels in the dict returned by :meth:`DictLearn.evaluate`\n hdrtxt : list\n List of column header titles for verbose iteration statistics\n display\n hdrmap : dict\n Dictionary mapping column header titles to IterationStats entries\n fmtmap : dict, optional (default None)\n A dict providing a mapping from field header strings to print\n format strings, providing a mechanism for fields with print\n formats that depart from the standard format\n \"\"\"\n\n self.IterationStats = collections.namedtuple('IterationStats', isfld)\n self.isxmap = isxmap\n self.evlmap = evlmap\n self.hdrtxt = hdrtxt\n self.hdrmap = hdrmap\n\n # Call utility function to construct status display formatting\n self.hdrstr, self.fmtstr, self.nsep = common.solve_status_str(\n hdrtxt, fmtmap=fmtmap, fwdth0=type(self).fwiter,\n fprec=type(self).fpothr)\n\n\n\n def iterstats(self, j, t, isx, evl):\n \"\"\"Construct IterationStats namedtuple from X step list\n IterationStats namedtuples.\n\n Parameters\n ----------\n j : int\n Iteration number\n t : float\n Iteration time\n isx : namedtuple\n IterationStats namedtuple from X step object\n evl : dict\n Dict associating result labels with values computed by\n :meth:`DictLearn.evaluate`\n \"\"\"\n\n vlst = []\n # Iterate over the fields of the IterationStats namedtuple\n # to be populated with values. If a field name occurs as a\n # key in the isxmap dictionary, use the corresponding key\n # value as a field name in the isx namedtuple for the X\n # step object and append the value of that field as the\n # next value in the IterationStats namedtuple under\n # construction. There are also two reserved field\n # names, 'Iter' and 'Time', referring respectively to the\n # iteration number and run time of the dictionary learning\n # algorithm.\n for fnm in self.IterationStats._fields:\n if fnm in self.isxmap:\n vlst.append(getattr(isx, self.isxmap[fnm]))\n elif fnm in self.evlmap:\n vlst.append(evl[fnm])\n elif fnm == 'Iter':\n vlst.append(j)\n elif fnm == 'Time':\n vlst.append(t)\n else:\n vlst.append(None)\n\n return self.IterationStats._make(vlst)\n\n\n\n def printheader(self):\n \"\"\"Print status display header and separator strings.\"\"\"\n\n print(self.hdrstr)\n self.printseparator()\n\n\n\n def printseparator(self):\n \"Print status display separator string.\"\"\"\n\n print(\"-\" * self.nsep)\n\n\n\n def printiterstats(self, itst):\n \"\"\"Print iteration statistics.\n\n Parameters\n ----------\n itst : namedtuple\n IterationStats namedtuple as returned by :meth:`iterstats`\n \"\"\"\n\n itdsp = tuple([getattr(itst, self.hdrmap[col]) for col in self.hdrtxt])\n print(self.fmtstr % itdsp)\n\n\nclass KCSC_ConvRepIndexing(object):\n \"\"\"Array dimensions and indexing for Kruskal CSC problems.\n\n Manage the inference of problem dimensions and the roles of\n :class:`numpy.ndarray` indices for convolutional representations in\n convolutional sparse coding problems (e.g.\n :class:`.admm.cbpdn.ConvBPDN` and related classes).\n \"\"\"\n\n def __init__(self, cri_AK, Rank, l):\n \"\"\"Initialise a ConvRepIndexing object.\n\n Initialise a ConvRepIndexing object representing dimensions\n of S (input signal), D (dictionary), and X (coefficient array)\n in a convolutional representation. These dimensions are\n inferred from the input `D` and `S` as well as from parameters\n `dimN` and `dimK`. Management and inferrence of these problem\n dimensions is not entirely straightforward because\n :class:`.admm.cbpdn.ConvBPDN` and related classes make use\n *internally* of S, D, and X arrays with a standard layout\n (described below), but *input* `S` and `D` are allowed to\n deviate from this layout for the convenience of the user.\n\n The most fundamental parameter is `dimN`, which specifies the\n dimensionality of the spatial/temporal samples being\n represented (e.g. `dimN` = 2 for representations of 2D\n images). This should be common to *input* S and D, and is\n also common to *internal* S, D, and X. The remaining\n dimensions of input `S` can correspond to multiple channels\n (e.g. for RGB images) and/or multiple signals (e.g. the array\n contains multiple independent images). If input `S` contains\n two additional dimensions (in addition to the `dimN` spatial\n dimensions), then those are considered to correspond, in\n order, to channel and signal indices. If there is only a\n single additional dimension, then determination whether it\n represents a channel or signal index is more complicated. The\n rule for making this determination is as follows:\n\n * if `dimK` is set to 0 or 1 instead of the default ``None``,\n then that value is taken as the number of signal indices in\n input `S` and any remaining indices are taken as channel\n indices (i.e. if `dimK` = 0 then dimC = 1 and if `dimK` = 1\n then dimC = 0).\n * if `dimK` is ``None`` then the number of channel dimensions is\n determined from the number of dimensions in the input\n dictionary `D`. Input `D` should have at least `dimN` + 1\n dimensions, with the final dimension indexing dictionary\n filters. If it has exactly `dimN` + 1 dimensions then it is a\n single-channel dictionary, and input `S` is also assumed to be\n single-channel, with the additional index in `S` assigned as a\n signal index (i.e. dimK = 1). Conversely, if input `D` has\n `dimN` + 2 dimensions it is a multi-channel dictionary, and\n the additional index in `S` is assigned as a channel index\n (i.e. dimC = 1).\n\n Note that it is an error to specify `dimK` = 1 if input `S`\n has `dimN` + 1 dimensions and input `D` has `dimN` + 2\n dimensions since a multi-channel dictionary requires a\n multi-channel signal. (The converse is not true: a\n multi-channel signal can be decomposed using a single-channel\n dictionary.)\n\n The *internal* data layout for S (signal), D (dictionary), and\n X (coefficient array) is (multi-channel dictionary)\n ::\n\n sptl. chn sig flt\n S(N0, N1, ..., C, K, 1)\n D(N0, N1, ..., C, 1, M)\n X(N0, N1, ..., 1, K, M)\n\n or (single-channel dictionary)\n\n ::\n\n sptl. chn sig flt\n S(N0, N1, ..., C, K, 1)\n D(N0, N1, ..., 1, 1, M)\n X(N0, N1, ..., C, K, M)\n\n where\n\n * Nv = [N0, N1, ...] and N = N0 x N1 x ... are the vector of sizes\n of the spatial/temporal indices and the total number of\n spatial/temporal samples respectively\n * C is the number of channels in S\n * K is the number of signals in S\n * M is the number of filters in D\n\n It should be emphasised that dimC and `dimK` may take on values\n 0 or 1, and represent the number of channel and signal\n dimensions respectively *in input S*. In the internal layout\n of S there is always a dimension allocated for channels and\n signals. The number of channel dimensions in input `D` and the\n corresponding size of that index are represented by dimCd\n and Cd respectively.\n\n Parameters\n ----------\n D : array_like\n Input dictionary\n S : array_like\n Input signal\n dimK : 0, 1, or None, optional (default None)\n Number of dimensions in input signal corresponding to multiple\n independent signals\n dimN : int, optional (default 2)\n Number of spatial/temporal dimensions of signal samples\n \"\"\"\n\n # # Determine whether dictionary is single- or multi-channel\n # self.dimCd = D.ndim - (dimN + 2)\n # if self.dimCd == 0:\n # self.Cd = 1\n # else:\n # self.Cd = D.shape[-2]\n #\n # # Numbers of spatial, channel, and signal dimensions in\n # # external S are dimN, dimC, and dimK respectively. These need\n # # to be calculated since inputs D and S do not already have\n # # the standard data layout above, i.e. singleton dimensions\n # # will not be present\n # if dimK is None:\n # rdim = S.ndim - dimN\n # if rdim == 0:\n # (dimC, dimK) = (0, 0)\n # elif rdim == 1:\n # dimC = self.dimCd # Assume S has same number of channels as D\n # dimK = S.ndim - dimN - dimC # Assign remaining channels to K\n # else:\n # (dimC, dimK) = (1, 1)\n # else:\n # dimC = S.ndim - dimN - dimK # Assign remaining channels to C\n #\n # self.dimN = dimN # Number of spatial dimensions\n # self.dimC = dimC # Number of channel dimensions in S\n # self.dimK = dimK # Number of signal dimensions in S\n #\n # # Number of channels in S\n # if self.dimC == 1:\n # self.C = S.shape[dimN]\n # else:\n # self.C = 1\n # Cx = self.C - self.Cd + 1\n #\n # # Ensure that multi-channel dictionaries used with a signal with a\n # # matching number of channels\n # if self.Cd > 1 and self.C != self.Cd:\n # raise ValueError(\"Multi-channel dictionary with signal with \"\n # \"mismatched number of channels (Cd=%d, C=%d)\" %\n # (self.Cd, self.C))\n #\n # # Number of signals in S\n # if self.dimK == 1:\n # self.K = S.shape[self.dimN + self.dimC]\n # else:\n # self.K = 1\n #\n # # Number of filters\n # self.M = D.shape[1] # KCSC std layout D(n',M,n,C)\n #\n # # Shape of spatial indices and number of spatial samples\n # self.Nv = S.shape[0:dimN]\n # self.N = np.prod(np.array(self.Nv))\n #\n # self.N_ = D.shape[0]\n #\n # self.nv = tuple(np.array(np.array(self.Nv)/self.N_,dtype=int))\n #\n # # Axis indices for each component of X and internal S and D\n # self.axisN = tuple(range(2, dimN+2))\n # self.axisC = dimN + 2\n # self.axisK = dimN + 3\n # self.axisM = 1\n #\n # # Shapes of internal S, D, and X (TO BE DONE, maybe not needed)\n # self.shpD = (self.N_,) + (self.M,) + self.nv + (self.Cd,) + (1,)\n # self.shpS = (1,) + (1,) + self.Nv + (self.C,) + (self.K,)\n # self.shpX = (1,) + (self.M,) + self.nv + (Cx,) + (self.K,)\n #\n # # Number of independent Linear systems\n # self.dimL = np.prod(self.nv)*self.Cd\n\n # Shape of spatial indices and number of spatial samples\n self.n = cri_AK.Nv[l]\n self.NC = int(cri_AK.N*cri_AK.Cd/self.n)\n self.MR = int(np.sum(Rank))\n\n # Axis indices for each component of X and internal S and D\n self.axisNC = [0]\n self.axisMR = [1]\n self.axisn = [2]\n\n # Shapes of internal S, D, and X\n self.shpD = (self.NC,self.MR,self.n)\n self.shpS = (self.NC,1,self.n)\n self.shpX = (self.MR,1,self.n)\n\n\n\n def __str__(self):\n \"\"\"Return string representation of object.\"\"\"\n\n return pprint.pformat(vars(self))\n\n\n\ndef Kl1Wshape(W, cri):\n r\"\"\"Get internal shape for an :math:`\\ell_1` norm weight array.\n\n Get appropriate internal shape (see\n :class:`CSC_ConvRepIndexing`) for an :math:`\\ell_1` norm weight\n array `W`, as in option ``L1Weight`` in\n :class:`.admm.cbpdn.ConvBPDN.Options` and related options classes.\n The external shape of `W` depends on the external shape of input\n data array `S` and the size of the final axis (i.e. the number of\n filters) in dictionary array `D`. The internal shape of the\n weight array `W` is required to be compatible for multiplication\n with the internal sparse representation array `X`. The simplest\n criterion for ensuring that the external `W` is compatible with\n `S` is to ensure that `W` has shape ``S.shape + D.shape[-1:]``,\n except that non-singleton dimensions may be replaced with\n singleton dimensions. If `W` has a single additional axis that is\n neither a spatial axis nor a filter axis, it is assigned as a\n channel or multi-signal axis depending on the corresponding\n assignement in `S`.\n\n Parameters\n ----------\n W : array_like\n Weight array\n cri : :class:`CSC_ConvRepIndexing` object\n Object specifying convolutional representation dimensions\n\n Returns\n -------\n shp : tuple\n Appropriate internal weight array shape\n \"\"\"\n\n # Number of dimensions in input array `S`\n sdim = len(cri.shpX) # + cri.dimC + cri.dimK\n\n if W.ndim < sdim:\n if W.size == 1:\n # Weight array is a scalar\n shpW = (1,) * 3\n else:\n # Invalid weight array shape\n raise ValueError('weight array must be scalar or have at least '\n 'the same number of dimensions as input array')\n elif W.ndim == sdim:\n # Weight array has the same number of dimensions as the input array\n shpW = W.shape\n else:\n # # Weight array has more dimensions than the input array\n # if W.ndim == cri.dimN + 4:\n # # Weight array is already of the appropriate shape\n # shpW = W.shape\n # else:\n # # # Assume that the final axis in the input array is the filter\n # # # index\n # # shpW = (1,) + W.shape[-1:] + W.shape[0:-1] + (1,) * (2 - cri.dimC - \\\n # # cri.dimK)\n\n # Invalid weight array shape\n raise ValueError('Internal shape of weight array should match shpX'\n 'w(MR, 1, n)')\n\n return shpW\n\n\n\nclass KConvBPDN(cbpdn.GenericConvBPDN):\n r\"\"\"\n ADMM algorithm for the Convolutional BPDN (CBPDN)\n :cite:`wohlberg-2014-efficient` :cite:`wohlberg-2016-efficient`\n :cite:`wohlberg-2016-convolutional` problem.\n\n |\n\n .. inheritance-diagram:: ConvBPDN\n :parts: 2\n\n |\n\n Solve the optimisation problem\n\n .. math::\n \\mathrm{argmin}_\\mathbf{x} \\;\n (1/2) \\left\\| \\sum_m \\mathbf{d}_m * \\mathbf{x}_m -\n \\mathbf{s} \\right\\|_2^2 + \\lambda \\sum_m \\| \\mathbf{x}_m \\|_1\n\n for input image :math:`\\mathbf{s}`, dictionary filters\n :math:`\\mathbf{d}_m`, and coefficient maps :math:`\\mathbf{x}_m`,\n via the ADMM problem\n\n .. math::\n \\mathrm{argmin}_{\\mathbf{x}, \\mathbf{y}} \\;\n (1/2) \\left\\| \\sum_m \\mathbf{d}_m * \\mathbf{x}_m -\n \\mathbf{s} \\right\\|_2^2 + \\lambda \\sum_m \\| \\mathbf{y}_m \\|_1\n \\quad \\text{such that} \\quad \\mathbf{x}_m = \\mathbf{y}_m \\;\\;.\n\n Multi-image and multi-channel problems are also supported. The\n multi-image problem is\n\n .. math::\n \\mathrm{argmin}_\\mathbf{x} \\;\n (1/2) \\sum_k \\left\\| \\sum_m \\mathbf{d}_m * \\mathbf{x}_{k,m} -\n \\mathbf{s}_k \\right\\|_2^2 + \\lambda \\sum_k \\sum_m\n \\| \\mathbf{x}_{k,m} \\|_1\n\n with input images :math:`\\mathbf{s}_k` and coefficient maps\n :math:`\\mathbf{x}_{k,m}`, and the multi-channel problem with input\n image channels :math:`\\mathbf{s}_c` is either\n\n .. math::\n \\mathrm{argmin}_\\mathbf{x} \\;\n (1/2) \\sum_c \\left\\| \\sum_m \\mathbf{d}_m * \\mathbf{x}_{c,m} -\n \\mathbf{s}_c \\right\\|_2^2 +\n \\lambda \\sum_c \\sum_m \\| \\mathbf{x}_{c,m} \\|_1\n\n with single-channel dictionary filters :math:`\\mathbf{d}_m` and\n multi-channel coefficient maps :math:`\\mathbf{x}_{c,m}`, or\n\n .. math::\n \\mathrm{argmin}_\\mathbf{x} \\;\n (1/2) \\sum_c \\left\\| \\sum_m \\mathbf{d}_{c,m} * \\mathbf{x}_m -\n \\mathbf{s}_c \\right\\|_2^2 + \\lambda \\sum_m \\| \\mathbf{x}_m \\|_1\n\n with multi-channel dictionary filters :math:`\\mathbf{d}_{c,m}` and\n single-channel coefficient maps :math:`\\mathbf{x}_m`.\n\n After termination of the :meth:`solve` method, attribute :attr:`itstat`\n is a list of tuples representing statistics of each iteration. The\n fields of the named tuple ``IterationStats`` are:\n\n ``Iter`` : Iteration number\n\n ``ObjFun`` : Objective function value\n\n ``DFid`` : Value of data fidelity term :math:`(1/2) \\| \\sum_m\n \\mathbf{d}_m * \\mathbf{x}_m - \\mathbf{s} \\|_2^2`\n\n ``RegL1`` : Value of regularisation term :math:`\\sum_m \\|\n \\mathbf{x}_m \\|_1`\n\n ``PrimalRsdl`` : Norm of primal residual\n\n ``DualRsdl`` : Norm of dual residual\n\n ``EpsPrimal`` : Primal residual stopping tolerance\n :math:`\\epsilon_{\\mathrm{pri}}`\n\n ``EpsDual`` : Dual residual stopping tolerance\n :math:`\\epsilon_{\\mathrm{dua}}`\n\n ``Rho`` : Penalty parameter\n\n ``XSlvRelRes`` : Relative residual of X step solver\n\n ``Time`` : Cumulative run time\n \"\"\"\n\n\n class Options(cbpdn.GenericConvBPDN.Options):\n r\"\"\"ConvBPDN algorithm options\n\n Options include all of those defined in\n :class:`.admm.ADMMEqual.Options`, together with additional options:\n\n ``L1Weight`` : An array of weights for the :math:`\\ell_1`\n norm. The array shape must be such that the array is\n compatible for multiplication with the `X`/`Y` variables (see\n :func:`.cnvrep.l1Wshape` for more details). If this\n option is defined, the regularization term is :math:`\\lambda\n \\sum_m \\| \\mathbf{w}_m \\odot \\mathbf{x}_m \\|_1` where\n :math:`\\mathbf{w}_m` denotes slices of the weighting array on\n the filter index axis.\n \"\"\"\n\n defaults = copy.deepcopy(cbpdn.GenericConvBPDN.Options.defaults)\n defaults.update({'L1Weight': 1.0})\n\n\n def __init__(self, opt=None):\n \"\"\"\n Parameters\n ----------\n opt : dict or None, optional (default None)\n ConvBPDN algorithm options\n \"\"\"\n\n if opt is None:\n opt = {}\n cbpdn.GenericConvBPDN.Options.__init__(self, opt)\n\n\n\n itstat_fields_objfn = ('ObjFun', 'DFid', 'RegL1', 'RegL2')\n hdrtxt_objfn = ('Fnc', 'DFid', u('Regℓ1'), u('Regℓ2'))\n hdrval_objfun = {'Fnc': 'ObjFun', 'DFid': 'DFid',\n u('Regℓ1'): 'RegL1', u('Regℓ2'): 'RegL2'}\n\n\n def __init__(self, Wf, Sf, cri_K, dtype, lmbda=None, mu=0.0, opt=None):\n \"\"\"\n This class supports an arbitrary number of spatial dimensions,\n `dimN`, with a default of 2. The input dictionary `D` is either\n `dimN` + 1 dimensional, in which case each spatial component\n (image in the default case) is assumed to consist of a single\n channel, or `dimN` + 2 dimensional, in which case the final\n dimension is assumed to contain the channels (e.g. colour\n channels in the case of images). The input signal set `S` is\n either `dimN` dimensional (no channels, only one signal), `dimN`\n + 1 dimensional (either multiple channels or multiple signals),\n or `dimN` + 2 dimensional (multiple channels and multiple\n signals). Determination of problem dimensions is handled by\n :class:`.cnvrep.CSC_ConvRepIndexing`.\n\n\n |\n\n **Call graph**\n\n .. image:: ../_static/jonga/cbpdn_init.svg\n :width: 20%\n :target: ../_static/jonga/cbpdn_init.svg\n\n |\n\n\n Parameters\n ----------\n D : array_like\n Dictionary array\n S : array_like\n Signal array\n lmbda : float\n Regularisation parameter\n opt : :class:`ConvBPDN.Options` object\n Algorithm options\n dimK : 0, 1, or None, optional (default None)\n Number of dimensions in input signal corresponding to multiple\n independent signals\n dimN : int, optional (default 2)\n Number of spatial/temporal dimensions\n \"\"\"\n\n # Set default options if none specified\n if opt is None:\n opt = KConvBPDN.Options()\n\n # Set dtype attribute based on S.dtype and opt['DataType']\n self.set_dtype(opt, dtype)\n\n # problem dimensions\n self.cri = cri_K\n\n # Reshape D and S to standard layout (NOT NEEDED in AKConvBPDN)\n self.Wf = np.asarray(Wf.reshape(self.cri.shpD), dtype=self.dtype)\n self.Sf = np.asarray(Sf.reshape(self.cri.shpS), dtype=self.dtype)\n # self.Sf_ = np.moveaxis(Sf.reshape([self.cri.nv[0],self.cri.N_,1]),[0,1,2],[2,0,1])\n\n # Set default lambda value if not specified\n if lmbda is None:\n b = np.conj(Df) * Sf\n lmbda = 0.1 * abs(b).max()\n\n # Set l1 term scaling\n self.lmbda = self.dtype.type(lmbda)\n\n # Set l2 term scaling\n self.mu = self.dtype.type(mu)\n\n # Set penalty parameter\n self.set_attr('rho', opt['rho'], dval=(50.0 * self.lmbda + 1.0),\n dtype=self.dtype)\n\n # Set rho_xi attribute (see Sec. VI.C of wohlberg-2015-adaptive)\n if self.lmbda != 0.0:\n rho_xi = float((1.0 + (18.3)**(np.log10(self.lmbda) + 1.0)))\n else:\n rho_xi = 1.0\n self.set_attr('rho_xi', opt['AutoRho', 'RsdlTarget'], dval=rho_xi,\n dtype=self.dtype)\n\n # Call parent class __init__ (not ConvBPDN bc FFT domain data)\n super(cbpdn.GenericConvBPDN, self).__init__(self.cri.shpX, Sf.dtype, opt)\n\n # Initialise byte-aligned arrays for pyfftw\n self.YU = sl.pyfftw_empty_aligned(self.Y.shape, dtype=self.dtype)\n self.Xf = sl.pyfftw_empty_aligned(self.Y.shape, self.dtype)\n\n\n self.c = [None] * self.cri.n # to be filled with cho_factor\n\n self.setdictf()\n\n\n # Set l1 term weight array\n self.wl1 = np.asarray(opt['L1Weight'], dtype=self.dtype)\n self.wl1 = self.wl1.reshape(Kl1Wshape(self.wl1, self.cri))\n\n print('L1Weight %s \\n' % (self.wl1,))\n\n\n def setdictf(self, Wf=None):\n \"\"\"Set dictionary array.\"\"\"\n\n if Wf is not None:\n self.Wf = Wf;\n # Compute D^H S\n print('Df shape %s \\n' % (self.Wf.shape,))\n print('Sf shape %s \\n' % (self.Sf.shape,))\n\n self.WSf = (np.sum(np.conj(self.Wf) * self.Sf, axis=0)).squeeze()\n # if self.cri.Cd > 1:\n # self.WSf = np.sum(self.WSf, axis=self.cri.axisC, keepdims=True)\n\n # Df_full = self.Wf.reshape([self.cri.shpD[0],self.cri.shpD[1],self.cri.n])\n for s in range(self.cri.n):\n Df_ = self.Wf[:,:,s]\n Df_H = np.conj(Df_.transpose())\n self.c[s] = linalg.cho_factor(np.dot(Df_H,Df_) + (self.mu + self.rho) * \\\n np.identity(self.cri.MR,dtype=self.dtype),lower=False,check_finite=True)\n\n\n def uinit(self, ushape):\n \"\"\"Return initialiser for working variable U\"\"\"\n\n if self.opt['Y0'] is None:\n return np.zeros(ushape, dtype=self.dtype)\n else:\n # If initial Y is non-zero, initial U is chosen so that\n # the relevant dual optimality criterion (see (3.10) in\n # boyd-2010-distributed) is satisfied.\n return (self.lmbda/self.rho)*np.sign(self.Y)\n\n\n def xstep(self):\n r\"\"\"Minimise Augmented Lagrangian with respect to\n :math:`\\mathbf{x}`.\n \"\"\"\n\n self.YU[:] = self.Y - self.U\n\n print('YU dtype %s \\n' % (self.YU.dtype,))\n\n b = (self.WSf + self.rho*sl.fftn(self.YU, None, self.cri.axisn).squeeze())\n\n # print('b shape %s \\n' % (b.shape,))\n\n # if self.cri.Cd == 1:\n for s in range(self.cri.n):\n self.Xf[:,0,s] = linalg.cho_solve(self.c[s],b[:,s],check_finite=True)\n # else:\n # raise ValueError(\"Multi-channel dictionary not implemented\")\n # self.Xf[:] = sl.solvemdbi_ism(self.Wf, self.mu + self.rho, b,\n # self.cri.axisM, self.cri.axisC)\n\n self.X = sl.irfftn(self.Xf, [self.cri.n], self.cri.axisn)\n\n # if self.opt['LinSolveCheck']:\n # Dop = lambda x: sl.inner(self.Wf, x, axis=self.cri.axisM)\n # if self.cri.Cd == 1:\n # DHop = lambda x: np.conj(self.Wf) * x\n # else:\n # DHop = lambda x: sl.inner(np.conj(self.Wf), x,\n # axis=self.cri.axisC)\n # ax = DHop(Dop(self.Xf)) + (self.mu + self.rho)*self.Xf\n # self.xrrs = sl.rrs(ax, b)\n # else:\n # self.xrrs = None\n\n\n def ystep(self):\n r\"\"\"Minimise Augmented Lagrangian with respect to\n :math:`\\mathbf{y}`.\"\"\"\n\n scalar_factor = (self.lmbda / self.rho) * self.wl1\n print('AX dtype %s \\n' % (self.AX.dtype,))\n print('U dtype %s \\n' % (self.U.dtype,))\n print('sc_factor shape %s \\n' % (scalar_factor.shape,))\n\n self.Y = sp.prox_l1(self.AX + self.U,(self.lmbda / self.rho) * self.wl1)\n super(KConvBPDN, self).ystep()\n\n\n def obfn_reg(self):\n \"\"\"Compute regularisation term and contribution to objective\n function. (ConvElasticNet)\n \"\"\"\n\n rl1 = np.linalg.norm((self.wl1 * self.obfn_gvar()).ravel(), 1)\n rl2 = 0.5*np.linalg.norm(self.obfn_gvar())**2\n return (self.lmbda*rl1 + self.mu*rl2, rl1, rl2)\n\n\n def setdict(self):\n \"\"\"Set dictionary array.\n\n Overriding this method is required.\n \"\"\"\n\n raise NotImplementedError()\n\n\n def reconstruct(self):\n \"\"\"Reconstruct representation.\n\n Overriding this method is required.\n \"\"\"\n\n raise NotImplementedError()\n\n\nclass AKConvBPDN(object):\n \"\"\"Boundary masking for convolutional representations using the\n Alternated Kruscal ConvBPDN technique described in\n :cite:`humbert-2019`. Implemented as a wrapper about a\n ConvBPDN or derived object (or any other object with\n sufficiently similar interface and internals). The wrapper is largely\n transparent, but must be taken into account when setting some of the\n options for the inner object, e.g. the shape of the ``L1Weight``\n option array must take into account the extra dictionary atom appended\n by the wrapper.\n \"\"\"\n\n class Options(cdict.ConstrainedDict):\n \"\"\"AKConvBPDN options.\n\n Options:\n\n ``Verbose`` : Flag determining whether iteration status is\n displayed.\n\n ``StatusHeader`` : Flag determining whether status header and\n separator are displayed.\n\n ``IterTimer`` : Label of the timer to use for iteration times.\n\n ``MaxMainIter`` : Maximum main iterations.\n\n ``Callback`` : Callback function to be called at the end of\n every iteration.\n \"\"\"\n\n defaults = {'Verbose': False, 'StatusHeader': True,\n 'IterTimer': 'solve', 'MaxMainIter': 50,\n 'Callback': None}\n\n\n def __init__(self, opt=None):\n \"\"\"\n Parameters\n ----------\n opt : dict or None, optional (default None)\n DictLearn algorithm options\n \"\"\"\n\n if opt is None:\n opt = {}\n cdict.ConstrainedDict.__init__(self, opt)\n\n\n def __new__(cls, *args, **kwargs):\n \"\"\"Create an AKConvBPDN object and start its\n initialisation timer.\"\"\"\n\n instance = super(AKConvBPDN, cls).__new__(cls)\n instance.timer = util.Timer(['init', 'solve', 'solve_wo_eval'])\n instance.timer.start('init')\n return instance\n\n\n def __init__(self, D, S, R, opt=None, lmbda=None, optx=None,\n dimK=None, dimN=2,*args, **kwargs):\n \"\"\"\n Parameters\n ----------\n xstep : internal xstep object (e.g. xstep.ConvBPDN)\n D : array_like\n Dictionary array\n S : array_like\n Signal array\n R : array_like\n Rank array\n lmbda : list of float\n Regularisation parameter\n opt : list containing :class:`ConvBPDN.Options` object\n Algorithm options for each individual solver\n dimK : 0, 1, or None, optional (default None)\n Number of dimensions in input signal corresponding to multiple\n independent signals\n dimN : int, optional (default 2)\n Number of spatial/temporal dimensions\n *args\n Variable length list of arguments for constructor of internal\n xstep object (e.g. mu)\n **kwargs\n Keyword arguments for constructor of internal xstep object\n \"\"\"\n\n if opt is None:\n opt = AKConvBPDN.Options()\n self.opt = opt\n\n # Infer outer problem dimensions\n self.cri = cr.CSC_ConvRepIndexing(D, S, dimK=dimK, dimN=dimN)\n\n # Parse mu\n if 'mu' in kwargs:\n mu = kwargs['mu']\n else:\n mu = [0] * self.cri.dimN\n\n # Parse lmbda and optx\n if lmbda is None: lmbda = [None] * self.cri.dimN\n if optx is None: optx = [None] * self.cri.dimN\n\n # Parse isc\n if 'isc' in kwargs:\n isc = kwargs['isc']\n else:\n isc = None\n\n # Store parameters\n self.lmbda = lmbda\n self.optx = optx\n self.mu = mu\n self.R = R\n\n # Reshape D and S to standard layout\n self.D = np.asarray(D.reshape(self.cri.shpD), dtype=S.dtype)\n self.S = np.asarray(S.reshape(self.cri.shpS), dtype=S.dtype)\n\n # Compute signal in DFT domain\n self.Sf = sl.fftn(self.S, None, self.cri.axisN)\n # print('Sf shape %s \\n' % (self.Sf.shape,))\n # print('S shape %s \\n' % (self.S.shape,))\n # print('shpS %s \\n' % (self.cri.shpS,))\n\n # Signal uni-dim (kruskal)\n # self.Skf = np.reshape(self.Sf,[np.prod(np.array(self.Sf.shape)),1],order='F')\n\n # Decomposed Kruskal Initialization\n self.K = []\n self.Kf = []\n Nvf = []\n for i,Nvi in enumerate(self.cri.Nv): # Ui\n Ki = np.random.randn(Nvi,np.sum(self.R))\n Kfi = sl.pyfftw_empty_aligned(Ki.shape, self.Sf.dtype)\n Kfi[:] = sl.fftn(Ki,None,[0])\n self.K.append(Ki)\n self.Kf.append(Kfi)\n Nvf.append(Kfi.shape[0])\n\n self.Nvf = tuple(Nvf)\n\n # Fourier dimensions\n self.NC = int(np.prod(self.Nvf)*self.cri.Cd)\n\n # dict FFT\n self.setdict()\n\n # Init KCSC solver (Needs to be initiated inside AKConvBPDN because requires convolvedict() and reshapesignal())\n self.xstep = []\n for l in range(self.cri.dimN):\n\n Wl = self.convolvedict(l) # convolvedict\n cri_l = KCSC_ConvRepIndexing(self.cri,self.R,l) # cri KCSC\n\n self.xstep.append(KConvBPDN(Wl, np.reshape(self.Sf,cri_l.shpS,order='C'), cri_l,\\\n self.S.dtype, self.lmbda[l], self.mu[l], self.optx[l]))\n\n # Init isc\n if isc is None:\n\n isc_lst = [] # itStats from block-solver\n isc_fields = []\n for i in range(self.cri.dimN):\n str_i = '_{0!s}'.format(i)\n\n isc_i = IterStatsConfig(\n isfld=['ObjFun'+str_i, 'PrimalRsdl'+str_i,'DualRsdl'+str_i,\n 'Rho'+str_i],\n isxmap={'ObjFun'+str_i: 'ObjFun', 'PrimalRsdl'+str_i: 'PrimalRsdl',\n 'DualRsdl'+str_i: 'DualRsdl', 'Rho'+str_i: 'Rho'},\n evlmap={},\n hdrtxt=['Fnc'+str_i, 'r'+str_i, 's'+str_i, u('ρ'+str_i)],\n hdrmap={'Fnc'+str_i: 'ObjFun'+str_i, 'r'+str_i: 'PrimalRsdl'+str_i,\n 's'+str_i: 'DualRsdl'+str_i, u('ρ'+str_i): 'Rho'+str_i}\n )\n isc_fields += isc_i.IterationStats._fields\n\n isc_lst.append(isc_i)\n\n # isc_it = IterStatsConfig( # global itStats -> No, to be managed in dictlearn\n # isfld=['Iter','Time'],\n # isxmap={},\n # evlmap={},\n # hdrtxt=['Itn'],\n # hdrmap={'Itn': 'Iter'}\n # )\n #\n # isc_fields += isc_it._fields\n\n self.isc_lst = isc_lst\n # self.isc_it = isc_it\n self.isc = collections.namedtuple('IterationStats', isc_fields)\n\n # Required because dictlrn.DictLearn assumes that all valid\n # xstep objects have an IterationStats attribute\n # self.IterationStats = self.xstep.IterationStats\n\n self.itstat = []\n self.j = 0\n\n\n def solve(self):\n \"\"\"Call the solve method of the inner KConvBPDN object and return the\n result.\n \"\"\"\n\n itst = []\n\n # Main optimisation iterations\n for self.j in range(self.j, self.j + self.opt['MaxMainIter']):\n\n for l in range(self.cri.dimN):\n\n # Pre x-step\n Wl = self.convolvedict(l) # convolvedict\n self.xstep[l].setdictf(Wl) # setdictf\n\n # Solve KCSC\n self.xstep[l].solve()\n\n # Post x-step\n Kl = np.moveaxis(self.xstep[l].getcoef().squeeze(),[0,1],[1,0])\n self.Kf[l] = sl.fftn(Kl, None, [0]) # Update Kruskal\n\n # IterationStats\n xitstat = self.xstep.itstat[-1] if self.xstep.itstat else \\\n self.xstep.IterationStats(\n *([0.0,] * len(self.xstep.IterationStats._fields)))\n\n itst += self.isc_lst[l].iterstats(self.j, 0, xitstat, 0) # Accumulate\n\n self.itstat.append(self.isc(*itst)) # Cast to global itstats and store\n\n # Decomposed ifftn\n for l in range(self.cri.dimN):\n self.K[l] = sl.irfftn(self.Kf[l], self.cri.Nv[l], [0]) # ifft transform\n\n self.j += 1\n\n\n def setdict(self, D=None):\n \"\"\"Set dictionary array.\"\"\"\n\n if D is not None:\n self.D = np.asarray(D, dtype=self.dtype)\n # self.Df = sl.fftn(self.D, self.cri.Nv, self.cri.axisN)\n\n print('D shape %s \\n' % (self.D.shape,))\n print('axisN %s \\n' % (self.cri.axisN,))\n print('dimN %s \\n' % (self.cri.dimN,))\n\n # Df = self.D\n # for l in range(self.cri.dimN):\n # Df = sl.fftn(Df, [self.cri.Nv[l]], [self.cri.axisN[l]])\n # self.Df = Df\n\n self.Df = sl.fftn(self.D, self.Nvf, self.cri.axisN)\n\n print('Df shape %s \\n' % (self.Df.shape,))\n print('self.cri.Cd %s \\n' % (self.cri.Cd,))\n print('self.NC %s \\n' % (self.NC,))\n print('self.Nvf %s \\n' % (self.Nvf,))\n\n # if not hasattr(self, 'cri_f'):\n # # At first call: Infer outer problem dimensions for fourier domain\n # self.cri_f = cr.CSC_ConvRepIndexing(self.Df, self.Sf, dimK=self.cri.dimK, dimN=self.cri.dimN)\n\n NC = self.NC\n M = self.cri.M\n\n self.Df_mat = np.dot(np.reshape(self.Df,[NC,M],order='F'),self.getweights().transpose()) # Df_mat(NC,R*M)\n\n\n def convolvedict(self,l=None):\n \"\"\"W: Convolve D w/.\"\"\"\n\n Df_mat = self.Df_mat\n Kf = self.Kf\n\n NC = self.NC\n\n Nl = self.Nvf[l] if l is not None else 1\n\n print('Kf shape %s \\n' % (Kf[l].shape,))\n print('Nl %s \\n' % (Nl,))\n\n Df_ = np.moveaxis(np.reshape(Df_mat,[Nl,int(NC/Nl),sum(self.R)],order='F'),\\\n [0,1,2],[2,0,1]).squeeze()\n Q = np.reshape(tl.tenalg.khatri_rao(Kf,skip_matrix=l,reverse=True),\\\n [int(NC/Nl),sum(self.R),1])\n return Df_*Q\n\n\n def getweights(self):\n \"\"\"Linear map from [NxR*K] to [NxK] array.\"\"\"\n\n weightsArray = []\n for k,Rk in enumerate(self.R):\n weightsArray.append(np.ones([Rk,1]))\n\n return linalg.block_diag(*weightsArray) # map from R*M to M\n\n\n def getcoef(self):\n \"\"\"Get result of inner xstep object and expand Kruskal.\"\"\"\n\n Nz = self.cri.Nv\n Nz.append(self.cri.M)\n\n Z = np.dot(tl.tenalg.khatri_rao(self.K,reverse=True),self.getweights())\n\n return tl.base.vec_to_tensor(Z,Nz) # as array Z(N0,N1,...,M)\n\n\n def getKruskal(self):\n \"\"\"Get decomposed Krukal Z.\"\"\"\n\n return self.K()\n\n\n def reconstruct(self, X=None):\n \"\"\"Reconstruct representation.\"\"\"\n\n Df = self.Df\n Nz = self.Nvf\n Nz.append(self.cri.M)\n\n # # Stupid Option\n # Tz = self.getcoef()\n # Xf = sl.rfftn(Tz,None,self.cri.axisN)\n\n #Smart Option\n Zf = np.dot(tl.tenalg.khatri_rao(self.Kf,reverse=True),self.getweights())\n Xf = tl.base.vec_to_tensor(Z,Nz)\n\n Sf = np.sum(Df*Xf, axis=self.cri.axisM)\n\n return sl.ifftn(Sf, self.cri.Nv, self.cri.axisN)\n\n\n def getitstat(self):\n \"\"\"Get iteration stats.\"\"\"\n\n return self.itstat\n","sub_path":"sporco/admm/object.py","file_name":"object.py","file_ext":"py","file_size_in_byte":39170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"63632675","text":"#!/usr/bin/env python\nimport torch\nimport numpy as np\nfrom numpy import random\nimport socket\n\nfrom models.experimental import attempt_load\nfrom utils.general import non_max_suppression\n\nimport cv2\nimport sys\nimport time\n\nfrom socket_funcs import *\n\ndef letterbox(\n img,\n new_shape=(640, 640),\n color=(114, 114, 114),\n auto=True,\n scaleFill=False,\n scaleup=True,\n):\n # Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232\n shape = img.shape[:2] # current shape [height, width]\n if isinstance(new_shape, int):\n new_shape = (new_shape, new_shape)\n # Scale ratio (new / old)\n r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n if not scaleup: # only scale down, do not scale up (for better test mAP)\n r = min(r, 1.0)\n # Compute padding\n ratio = r, r # width, height ratios\n new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding\n if auto: # minimum rectangle\n dw, dh = np.mod(dw, 32), np.mod(dh, 32) # wh padding\n elif scaleFill: # stretch\n dw, dh = 0.0, 0.0\n new_unpad = (new_shape[1], new_shape[0])\n ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios\n dw /= 2 # divide padding into 2 sides\n dh /= 2\n if shape[::-1] != new_unpad: # resize\n img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)\n top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n img = cv2.copyMakeBorder(\n img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color\n ) # add border\n return img, ratio, (dw, dh)\n\ndef preprocessing(img):\n img = letterbox(img, new_shape=(640, 640))[0]\n # Convert\n img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416\n img = np.ascontiguousarray(img)\n img = torch.from_numpy(img).to(\"cuda:0\")\n img = img.half() # if half else img.float() # uint8 to fp16/32\n img /= 255.0 # 0 - 255 to 0.0 - 1.0\n img = img.unsqueeze(0)\n return img\n\n\nmodel_path = \"./weights/churo.pt\"\n\n\nwith open('AWS_IP.txt', 'r') as f:\n TCP_IP = f.readline()\nTCP_PORT = 6666\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((TCP_IP, TCP_PORT))\ns.listen(True)\n \nTCP_PORT = 5555\nss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nss.bind((TCP_IP, TCP_PORT))\nss.listen(True)\n\nprint('listening...')\ncam_client, addr = s.accept()\nprint('image node connected')\nmsg_client, addr = ss.accept()\nprint('message node connected')\nprint(\"start\")\n\nif __name__ == \"__main__\":\n model = attempt_load(model_path, map_location=\"cuda\")\n model = model.autoshape() # for autoshaping of PIL/cv2/np inputs and NMS\n model.half()\n names = model.module.names if hasattr(model, \"module\") else model.names\n print(\"classes : \",names)\n colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]\n while True:\n t = time.time()\n im0 = recv_img_from(cam_client)\n h,w=im0.shape[:2]\n \n img = preprocessing(im0)\n h_,w_=640,640\n \n # Inference\n prediction = model(img)[0]\n prediction = non_max_suppression(prediction)\n prediction = prediction[0].cpu().numpy()\n bboxes = []\n for pred in prediction:\n if pred is not None:\n x1 = min(1,max(0,float(pred[0]/w_)))\n y1 = min(1,max(0,float(pred[1]/h_)))\n x2 = min(1,max(0,float(pred[2]/w_)))\n y2 = min(1,max(0,float(pred[3]/h_)))\n cls = int(pred[-1])\n bboxes.append([x1, y1, x2, y2, cls])\n\n msgs=''\n if len(bboxes) != 0:\n for box in bboxes:\n msg=\"{0:0.4f},{1:0.4f},{2:0.4f},{3:0.4f},{4}\".format(box[0],box[1],box[2],box[3],box[4])\n msgs=msgs+msg+'!'\n # print(\"bboxes :\",bboxes)\n # print(\"msgs :\",msgs)\n # print(\"msgs length:\",len(msgs))\n # send_image_to(im0,cam_client,dsize=(480, 320))\n send_msg_to(msgs,msg_client)\n dt = time.time()-t\n print(\"fps :{0:0.3f}\".format(1/dt))","sub_path":"yolov5_simple.py","file_name":"yolov5_simple.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"388167043","text":"\n\n#calss header\nclass _DETRITUS():\n\tdef __init__(self,): \n\t\tself.name = \"DETRITUS\"\n\t\tself.definitions = [u'waste material or rubbish, especially left after a particular event: ', u'a loose mass of decaying material']\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/_detritus.py","file_name":"_detritus.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"101767818","text":"def get_answers_tree(project, snapshot=None):\n\n values = {}\n valuesets = {}\n\n # first we loop over all values of this snapshot\n # the values are gathered in one nested dict {attribute_id: set_index: collection_index: value}\n # additionally all values with an attribute labeled 'id' are collected in a dict {attribute.parent.id: value.text}\n\n for value in project.values.filter(snapshot=snapshot):\n if value.attribute:\n # put values in a dict labled by the values attibute id, the set_index and the collection_index\n if value.attribute.id not in values:\n values[value.attribute.id] = {}\n if value.set_index not in values[value.attribute.id]:\n values[value.attribute.id][value.set_index] = {}\n if value.collection_index not in values[value.attribute.id][value.set_index]:\n values[value.attribute.id][value.set_index][value.collection_index] = {}\n\n values[value.attribute.id][value.set_index][value.collection_index] = value\n\n # put all values with an attribute labeled 'id' in a valuesets dict labeled by the parent attribute entities id\n if value.attribute.key == 'id':\n if value.attribute.parent.id not in valuesets:\n valuesets[value.attribute.parent.id] = {}\n\n valuesets[value.attribute.parent.id][value.set_index] = value.text\n\n # then we loop over sections, subsections and entities to collect questions and answers\n\n sections = []\n for catalog_section in project.catalog.sections.order_by('order'):\n subsections = []\n for catalog_subsection in catalog_section.subsections.order_by('order'):\n entities = []\n for catalog_entity in catalog_subsection.entities.filter(question__parent=None).order_by('order'):\n\n if catalog_entity.attribute_entity:\n\n if catalog_entity.is_set:\n\n attribute_entity = catalog_entity.attribute_entity\n\n if attribute_entity.parent_collection or attribute_entity.is_collection:\n\n if attribute_entity.parent_collection:\n collection = attribute_entity.parent_collection\n else:\n collection = attribute_entity\n\n questions = []\n for catalog_question in catalog_entity.questions.order_by('order'):\n\n # for a questionset collection loop over valuesets\n if collection.id in valuesets:\n\n sets = []\n for set_index in valuesets[collection.id]:\n valueset = valuesets[collection.id][set_index]\n\n # try to get the values for this question's attribute_entity and set_index\n answers = get_answers(values, catalog_question.attribute_entity.id, set_index)\n\n if answers:\n sets.append({\n 'id': valueset,\n 'answers': answers\n })\n\n if sets:\n questions.append({\n 'sets': sets,\n 'text': catalog_question.text,\n 'attribute': catalog_question.attribute_entity.attribute,\n 'is_collection': catalog_question.attribute_entity.is_collection or catalog_question.widget_type == 'checkbox'\n })\n\n if questions:\n entities.append({\n 'questions': questions,\n 'attribute': catalog_entity.attribute_entity,\n 'is_set': True,\n 'is_collection': True,\n })\n\n else:\n # # for a questionset loop over questions\n questions = []\n for catalog_question in catalog_entity.questions.order_by('order'):\n\n # try to get the values for this question's attribute_entity\n answers = get_answers(values, catalog_question.attribute_entity.id)\n\n if answers:\n questions.append({\n 'text': catalog_question.text,\n 'attribute': catalog_question.attribute_entity.attribute,\n 'answers': answers,\n 'is_collection': catalog_question.attribute_entity.is_collection or catalog_question.widget_type == 'checkbox'\n })\n\n if questions:\n entities.append({\n 'questions': questions,\n 'attribute': catalog_entity.attribute_entity,\n 'is_set': True,\n 'is_collection': False\n })\n\n else:\n # for a question just collect the answer\n\n # try to get the values for this question's attribute_entity\n answers = get_answers(values, catalog_entity.attribute_entity.id)\n\n if answers:\n entities.append({\n 'text': catalog_entity.question.text,\n 'attribute': catalog_entity.attribute_entity.attribute,\n 'answers': answers,\n 'is_set': False,\n 'is_collection': catalog_entity.attribute_entity.is_collection or catalog_entity.question.widget_type == 'checkbox'\n })\n\n if entities:\n subsections.append({\n 'title': catalog_subsection.title,\n 'entities': entities\n })\n\n if subsections:\n sections.append({\n 'title': catalog_section.title,\n 'subsections': subsections\n })\n\n return {'sections': sections}\n\n\ndef get_answers(values, attribute_id, set_index=0):\n answers = []\n\n try:\n for collection_index, value in sorted(values[attribute_id][set_index].items()):\n answers.append(value.value_and_unit)\n except KeyError:\n pass\n\n return answers\n","sub_path":"rdmo/projects/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"142758141","text":"import cv2\n\nimage = cv2.imread('image.jpg')\ngrayscale = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\ncv2.imshow('grayscale', grayscale)\ncv2.waitKey(0)\n# aplicar limiarização\nret, threshhold = cv2.threshold(grayscale, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\ncv2.imshow('threshhold', threshhold)\ncv2.waitKey(0)\nkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 10))\nfor i in range(10):\n erosao = cv2.erode(threshhold, kernel, iterations=i)\n cv2.imshow('erosao', erosao)\n cv2.waitKey(1000)\n","sub_path":"40/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"467991258","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\n\n\"\"\"\n一级级路由\n\n\"\"\"\n# alt + 回车\nurlpatterns = [\n url('admin/', admin.site.urls),\n url('1/', include('model01.urls')),\n url('2/', include('model02.urls')),\n]\n","sub_path":"Django02/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"622348550","text":"from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest\nfrom django.shortcuts import render, get_object_or_404\nfrom django.core.urlresolvers import reverse\nfrom turnos.models import Person, Department, Role, Calendar, Event\nfrom .forms import DepartmentForm, RoleForm, FormRole, FormPersonNew, CalendarForm\nfrom django.template import RequestContext, loader\nfrom django.shortcuts import redirect\nfrom django.forms.formsets import formset_factory\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.views.generic import TemplateView\nimport json\nfrom django.views.decorators.csrf import csrf_exempt\n\n\"\"\"\n\nclass NewTurn(TemplateView):\n template_name = 'admin/department_turn.html'\n form = CalendarForm()\n\n def get_context_data(self, *args, **kwargs):\n context = super(NewTurn, self).get_context_data(**kwargs)\n\n pk = self.kwargs.get('pk', None)\n new_month = self.kwargs.get('month', None)\n\n persons = Person.objects.filter(department__id=pk).values('name', 'first_surname').order_by('name')\n calendars = Calendar.objects.filter(department__id=pk).order_by('month')\n department = Department.objects.get(pk=pk)\n context.update(form=CalendarForm())\n\n extra_context = {'person_list': persons,\n 'group':department,\n 'calendars': calendars}\n\n for key, value in extra_context.items():\n if callable(value):\n context[key] = value()\n else:\n context[key] = value\n\n return context\n\n @csrf_exempt\n def dispatch(self, *args, **kwargs):\n return super(NewTurn, self).dispatch(*args, **kwargs)\n\n\n def post(self, request, *args, **kwargs):\n if not request.is_ajax():\n return HttpResponseBadRequest('Expected an XMLHttpRequest')\n\n in_data = json.loads(request.body)\n form = CheckoutForm(data={'subject': in_data.get('subject')})\n\n if form.is_valid():\n new_calendar = form.save(commit=False)\n department = Department.objects.get(pk=pk)\n new_calendar.department = department\n new_calendar.save()\n\n return HttpResponseRedirect(reverse('audiovisual.views.DepartmentTurn',\n args=(pk, new_calendar.id)))\n\n\"\"\"\n\n@login_required(login_url='/admin/login')\ndef controls(request):\n users = User.objects.all()\n context = {'user_list':users}\n return render(request, 'admin/panel_de_control.html', context)\n\n@login_required(login_url='/admin/login')\ndef DepartmentIndex(request):\n department_list = Department.objects.order_by('title')\n RoleFormset = formset_factory(RoleForm, extra=3)\n form = DepartmentForm()\n formset = RoleFormset()\n\n if request.method == \"POST\":\n # save button pressed\n if 'save' in request.POST:\n print('save button pressed')\n form = DepartmentForm(request.POST)\n formset = RoleFormset(request.POST, request.FILES)\n\n if form.is_valid() and formset.is_valid():\n title = form.cleaned_data['title']\n\n # create a new department\n new_department = Department.objects.create(title = title)\n\n for form in formset:\n data = form.cleaned_data\n title = data.get('title')\n\n # if not empty\n if title:\n Role.objects.create(department=new_department, title=title)\n\n\n form = DepartmentForm()\n formset = RoleFormset()\n pass\n\n # Cancel button pressed\n elif 'cancel' in request.POST:\n form = DepartmentForm()\n formset = RoleFormset()\n print('cancel button pressed')\n\n # method = GET\n else:\n form = DepartmentForm()\n formset = RoleFormset()\n\n context= {'department_list' : department_list, 'form':form, 'formset':formset}\n return render(request, 'admin/department_index.html', context)\n\n# Page for roles in a particular department with id = pk\n@login_required(login_url='/admin/login')\ndef DepartmentRole(request, pk):\n department = get_object_or_404(Department, pk=pk)\n\n if request.method == \"POST\":\n # save button pressed\n if 'save' in request.POST:\n print('save button pressed')\n form = FormRole(request.POST)\n\n if form.is_valid():\n title = form.cleaned_data['title']\n\n # create a new Role\n Role.objects.create(department=department, title=title)\n\n # generate a new form for redirection\n form = FormRole()\n\n # Get all Roles belonging to the Department with id = pk\n roles = Role.objects.filter(department = department)\n\n # Cancel button pressed\n elif 'cancel' in request.POST:\n form = FormRole()\n\n # Get all Roles belonging to the Department with id = pk\n roles = department.role_set.all()\n print('cancel button pressed')\n\n # method = GET\n else:\n form = FormRole()\n\n # Get all Roles belonging to the Department with id = pk\n roles = Role.objects.filter(department = department)\n\n # Display the roles page with empty role\n context= {'role_list':roles, 'department':department, 'form':form}\n return render(request, 'admin/department_rol.html', context)\n\n@login_required(login_url='/admin/login')\ndef DepartmentPerson(request, pk):\n person_list = Person.objects.filter(department__id=pk)\n department = get_object_or_404(Department, pk=pk)\n context= {'person_list' : person_list, 'department':department}\n return render(request, 'admin/department_members.html', context)\n\n@login_required(login_url='/admin/login')\ndef DepartmentTurn(request, pk, month=0, new_month=True, new_event=False):\n persons = Person.objects.filter(department__id=pk).values('name', 'first_surname').order_by('name')\n calendars = Calendar.objects.filter(department__id=pk).order_by('month')\n department = Department.objects.get(pk=pk)\n #events = Event.objects.filter(calendar__month=month).order_by('date')\n form = CalendarForm()\n\n if request.method == \"POST\":\n # save button pressed\n if 'save' in request.POST:\n print('save button pressed')\n form = CalendarForm(request.POST)\n\n if form.is_valid():\n new_calendar = form.save(commit=False)\n department = Department.objects.get(pk=pk)\n new_calendar.department = department\n new_calendar.save()\n\n return HttpResponseRedirect(reverse('audiovisual.views.DepartmentTurn',\n args=(pk, new_calendar.id)))\n elif 'cancel' in request.POST:\n new_month = False\n\n context= { 'person_list': persons,\n 'form':form,\n 'group':department,\n 'calendars': calendars,\n 'new_month': new_month,\n 'new_event': new_event}\n return render(request, 'admin/department_turn.html', context)\n\n\n# Page for all persons\n@login_required(login_url='/admin/login')\ndef PersonIndex(request):\n person_list = Person.objects.all()[:15]\n context= {'person_list' : person_list}\n return render(request, 'admin/personas.html', context)\n\n# Page for a particular person\n@login_required(login_url='/admin/login')\ndef PersonDetail(request, pk):\n person = get_object_or_404(Person, pk=pk)\n context = {'person':person}\n return render(request, 'admin/person_detail.html', context)\n\n# Page to edit a person\n@login_required(login_url='/admin/login')\ndef PersonEdit(request, pk):\n person = get_object_or_404(Person, pk=pk)\n form = FormPersonNew(instance=person)\n\n if request.method == \"POST\":\n # save button pressed\n if 'save' in request.POST:\n form = FormPersonNew(request.POST, instance=person)\n\n if form.is_valid():\n form.save()\n\n\n return HttpResponseRedirect(reverse('audiovisual.views.PersonDetail', args=(pk,)))\n\n # Display the edit person page\n context= {'form':form}\n return render(request, 'admin/person_edit.html', context)\n\n\n# Page to edit a person\n@login_required(login_url='/admin/login')\ndef PersonClear(request, pk):\n return render(request, 'admin/detalle.html')\n\n\n\n@login_required(login_url='/admin/login')\ndef PersonNew(request):\n form = FormPersonNew()\n\n if request.method == \"POST\":\n # save button pressed\n if 'save' in request.POST or 'save_new' in request.POST:\n print('save button pressed')\n form = FormPersonNew(request.POST)\n\n if form.is_valid():\n form.save()\n\n # generate a new form for redirection\n form = FormPersonNew()\n\n if 'save_new' in request.POST:\n # return to the create page\n return HttpResponseRedirect(reverse('audiovisual.views.PersonNew'))\n\n elif 'cancel' in request.POST:\n # return to the list of persons\n return HttpResponseRedirect(reverse('audiovisual.views.PersonIndex'))\n\n # Display the roles page with empty or error filled form\n context= {'form':form}\n return render(request, 'admin/person_create.html', context)\n\n\n@login_required(login_url='/admin/login')\ndef details(request):\n return render(request, 'admin/detalle.html')\n\n@login_required(login_url='/admin/login')\ndef turns(request):\n return render(request, 'admin/detalle.html')\n\n# Page for all roles in all department\n@login_required(login_url='/admin/login')\ndef RoleIndex(request):\n role_list = Role.objects.all()[:15]\n context= {'role_list' : role_list}\n return render(request, 'admin/roles_index.html', context)\n","sub_path":"audiovisual/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"460891638","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n#\n# Complete the 'birthdayCakeCandles' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts INTEGER_ARRAY candles as parameter.\n#\n\ndef birthdayCakeCandles(candles):\n count1 = {}\n count2 = 0\n candles.sort()\n for num in candles:\n if num in count1:\n count1[num] += 1\n else:\n count1[num] = 1\n\n k = list(count1.keys())[-1]\n print(count1[k])\n\n # Write your code here\n\n\nif __name__ == '__main__':\n\n\n candles_count = int(input().strip())\n\n candles = list(map(int, input().rstrip().split()))\n n = len(candles)\n\n result = birthdayCakeCandles(candles)\n\n\n\n\n","sub_path":"Mix Questions/candle_plm.py","file_name":"candle_plm.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"32191822","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, api, _\n\n\nclass SaleAdvancePaymentInv(models.TransientModel):\n _inherit = \"sale.advance.payment.inv\"\n\n @api.multi\n def _create_invoice(self, order, so_line, amount):\n invoice = super(SaleAdvancePaymentInv, self)._create_invoice(order, so_line, amount)\n if invoice:\n invoice.action_invoice_open()\n","sub_path":"bi_automatic_invoice_validate/models/sale_advance_payment_inv.py","file_name":"sale_advance_payment_inv.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"623041082","text":"import json\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nfrom time import sleep\nfrom modules.caps_client import CapsClient\n\nfrom credentials import cookies\nfrom config import Config\n\n\nclass EmailChecker:\n\n def __init__(self):\n\n self.cap = CapsClient()\n self.cred = self._get_cookies()\n options = webdriver.ChromeOptions()\n options.add_argument(\"--start-maximized\")\n options.add_argument(\"--disable-infobars\")\n # options.add_argument(\"--incognito\")\n # options.add_argument('--proxy-server=socks://' + self.cred['proxy_host'] + ':' + self.cred['proxy_port'])\n options.add_argument(\"--proxy-server={}\".format(self._get_proxy()))\n\n print(\"proxy: {}\".format(self._get_proxy()))\n\n self.Cookies = json.loads(self.cred['cookies'])\n\n # chrome webdriver\n # self.driver = webdriver.Chrome(options=options)\n\n # remote webdriver\n self.driver = webdriver.Remote(\n command_executor=Config.SELENIUM_URI,\n desired_capabilities=options.to_capabilities(),\n )\n\n # self.EMAILFIELD = (By.ID, \"identifierId\")\n # self.PASSWORDFIELD = (By.NAME, \"password\")\n # self.NEXTBUTTON = (By.ID, \"identifierNext\")\n # self.PNEXTBUTTON = (By.ID, \"passwordNext\")\n self.SEARCHFIELD = (By.NAME, \"q\")\n self.SUBMIT = (By.CLASS_NAME, \"gbqfb\")\n\n # random proxy based on chosen filters\n def _get_proxy(self):\n\n try:\n random_proxy = self.cap.get_proxy_random(type='socks5')\n return \"socks5://{}:{}\".format(random_proxy['host'], random_proxy['port'])\n\n except:\n return 'socks5://5.39.20.153:25567'\n\n def _get_cookies(self):\n credential = self.cap.get_credential_random('google')\n return {'cookies': cookies['cookies']}\n\n def checker(self, emailId):\n\n url = \"https://gmail.com/\"\n self.driver.get(\"https://google.com\")\n\n for cookie in self.Cookies:\n cookie_dict = {'domain': cookie['domain'], 'secure': cookie['secure'], 'value': cookie['value'],\n 'name': cookie['name'], 'httpOnly': cookie['httpOnly'], 'storeId': cookie['storeId'],\n 'path': cookie['path'], 'session': cookie['session'], 'hostOnly': cookie['hostOnly'],\n 'sameSite': cookie['sameSite'], 'id': cookie['id']}\n try:\n if cookie['expirationDate']:\n cookie_dict['expirationDate'] = cookie['expirationDate']\n # print(cookie['expirationDate'])\n except:\n pass\n # print(cookie_dict)\n self.driver.add_cookie(cookie_dict)\n sleep(0.5)\n self.driver.get('https://gmail.com')\n\n # print(emailId)\n #\n WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable(self.SEARCHFIELD)).send_keys(emailId)\n # WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable(self.SUBMIT)).click()\n self.driver.find_element_by_name('q').send_keys(Keys.ENTER)\n # WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable(self.PASSWORDFIELD)).send_keys(passd)\n # WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable(self.PNEXTBUTTON)).click()\n # # print(\"%s seconds\" % (time.time() - start_time))\n sleep(3)\n try:\n\n # # googleplusid\n try:\n mailid1 = self.driver.find_element_by_xpath('//*[@id=\":2\"]/div/div[2]/div[4]/div[1]/div[2]/div[1]/div[1]')\n except NoSuchElementException:\n mailid1 = self.driver.find_element_by_xpath('//*[@id=\":1\"]/div/div[2]/div[4]/div[1]/div[2]/div[1]/div[1]')\n # # sleep(0.5)\n # print(mailid1)\n # e = mailid1.get_attribute('href')\n # image on google account\n try:\n image = self.driver.find_element_by_xpath('//*[@id=\":2\"]/div/div[2]/div[4]/div[1]/div[1]/img')\n except NoSuchElementException:\n image = self.driver.find_element_by_xpath('//*[@id=\":1\"]/div/div[2]/div[4]/div[1]/div[1]/img')\n img = image.get_attribute('src')\n # print(e)\n # name of the user\n name = mailid1.text\n self.driver.quit()\n\n return {'email': True,\n 'email_id': emailId,\n # 'googlePlusId': e[24:],\n 'name': name,\n 'image': img}\n except:\n self.driver.quit()\n return {'email': False}\n\n # # try:\n # mailid1 = self.driver.find_element_by_xpath('//*[@id=\"app__container\"]/div[2]/header')\n # sleep(0.5)\n # print(mailid1.text)\n # self.driver.quit()\n #\n # return {'mailid': False}\n # except:\n # mailid = self.driver.find_element_by_xpath('//*[@id=\"signup_magiclink\"]/div[1]/div/h1/p')\n # sleep(2)\n # print(mailid.text)\n # self.driver.quit()\n #\n # return {'mailid': True}\n\n\nif __name__ == '__main__':\n obj = EmailChecker()\n # print(obj.checker('veronikascott27@gmail.com'))\n print(obj.checker('justinmat1994@gmail.com'))\n # print(obj.checker('justinmat199@gmail.com'))\n\n","sub_path":"google-api/modules/emailChecker.py","file_name":"emailChecker.py","file_ext":"py","file_size_in_byte":5560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"589459548","text":"import cv2, time\n\nvideo=cv2.VideoCapture(0)\n\na=0\n\n#while loop -> ctr c to stop (or z if ctr c doesn't work)\n#while loop bc you want to have string of pics.\nwhile True:\n a=a+1\n check, frame = video.read()\n\n print(check)\n print(frame)\n\n gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n #time.sleep(3) -> if you use cv2.waitKey for a specific time (not 0 to stop with the button as before) you don't need this command anymore\n cv2.imshow(\"Capturing\", gray)\n\n key=cv2.waitKey(1)\n\n if key==ord('q'):\n break\nprint(a)\n#it's to check how many iterations you have \n\nvideo.release()\ncv2.destroyAllWindows()\n","sub_path":"MotionDetector/video_creation.py","file_name":"video_creation.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"160432691","text":"from datetime import datetime\nfrom ftw.testing import freeze\nfrom opengever.testing import IntegrationTestCase\nfrom opengever.testing.helpers import index_data_for\nfrom opengever.trash.trash import ITrasher\nfrom plone import api\n\n\nclass TestCatalog(IntegrationTestCase):\n\n def test_trashed_index_registered(self):\n self.assertIn('trashed', api.portal.get_tool('portal_catalog').indexes())\n\n def test_modified_index_gets_updated_when_trashing(self):\n self.login(self.regular_user)\n\n with freeze(datetime(2014, 5, 7, 12, 30)) as clock:\n ITrasher(self.subsubdocument).trash()\n clock.forward(minutes=5)\n\n ITrasher(self.taskdocument).trash()\n clock.forward(minutes=5)\n\n ITrasher(self.document).trash()\n clock.forward(minutes=5)\n\n ITrasher(self.subdocument).trash()\n\n catalog = api.portal.get_tool('portal_catalog')\n modified_idx = catalog._catalog.indexes['modified']\n\n def modified_idx_value(obj):\n return index_data_for(obj)['modified']\n\n def to_idx_value(value):\n return modified_idx._convert(value)\n\n self.assertEqual(\n to_idx_value(datetime(2014, 5, 7, 12, 30)),\n modified_idx_value(self.subsubdocument))\n\n self.assertEqual(\n to_idx_value(datetime(2014, 5, 7, 12, 35)),\n modified_idx_value(self.taskdocument))\n\n self.assertEqual(\n to_idx_value(datetime(2014, 5, 7, 12, 40)),\n modified_idx_value(self.document))\n\n self.assertEqual(\n to_idx_value(datetime(2014, 5, 7, 12, 45)),\n modified_idx_value(self.subdocument))\n","sub_path":"opengever/trash/tests/test_catalog.py","file_name":"test_catalog.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"240340995","text":"# Singly-linked lists are already defined with this interface:\n# class ListNode(object):\n# def __init__(self, x):\n# self.value = x\n# self.next = None\n#\ndef isListPalindrome(l):\n a = []\n while l != None:\n a.append(l.value)\n l = l.next\n return a == a[::-1]","sub_path":"Interview_Practice/LinkedList/isListPalindrome.py","file_name":"isListPalindrome.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"115129685","text":"# List Comprehension\n# ls = [i for i in range(100) if i%3 == 0]\n# print(ls)\n#\n# ls = [i for i in range(0,100,3) ]\n# print(ls)\n#\n# # Print dictionary 0:item0, 1:item1..\n# dict = { i:f\"item{i}\" for i in range(5) }\n# print(dict)\n#\n# # Reverse of above dict\n# dict1 = {value:key for key,value in dict.items()}\n# print(dict1)\n\n# Generator Comprehension\n# evens = (i for i in range(40) if i%2==0)\n# print(evens)\n# print(type(evens))\n# print(evens.__next__())\n# print(evens.__next__())\n# print(evens.__next__())\n\n#Q Take numbers in input as a list, ask for which type of comprehension want ??\n# ..convert them to that comprehension.\n\nlst = input(\"Enter the number\")\nlst = lst.split(' ')\n# print(type(lst))\n# print(lst)\n# lst=[i for i in input(\"enter element\").split(' ')]\n\nchoice = int(input(\"Enter -\\n 1 for List comprehension \\n 2 for Set comprehension \\n 3 for Dictionary comprehension\"))\nif choice ==1:\n lst1 = [i for i in lst]\n print(lst1)\nelif choice == 2:\n sett = { i for i in lst}\n print(sett)\nelse:\n dict_user = {l: f\"You are awesome programmer\" for l in lst}\n print(dict_user)\n\n","sub_path":"Comprehension-file.py","file_name":"Comprehension-file.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"474824280","text":"import copy\n\nfrom game.player import Player\nimport game.constants as const\n\n\nclass MisterX(Player):\n def __init__(self, game, name, blackCards=2, doubleMoveCards=2):\n super().__init__(game, name, busCard=3, taxiCard=4, undergroundCard=3)\n\n # Black cards hide used transportation method from the detectives\n # 2x cards can be used to move twice in one turn\n self.cards.update({\n 'black': blackCards,\n 'double': doubleMoveCards,\n })\n self.originalCards = copy.deepcopy(self.cards)\n\n self.doubleMoves = []\n \n @property\n def lastKnownPosition(self):\n try:\n idx = max([i - 1 for i in const.MRX_OPEN_TURNS if i - 1 < len(self.history)])\n except ValueError:\n # max from an empty sequence\n return None\n return self.history[idx][-1]\n\n def __str__(self):\n \"Overwite the string method of base class Player for consistency\"\n return \"Mr. X\"\n\n def cloneFrom(self, old):\n super().cloneFrom(old)\n self.doubleMoves = [m for m in old.doubleMoves]\n\n def clone(self, game=None):\n if game is None:\n game = self.game\n new = type(self)(game, self.name)\n new.cloneFrom(self)\n return new\n\n def reset(self):\n super().reset()\n self.doubleMoves = []\n","sub_path":"game/misterx.py","file_name":"misterx.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"313041048","text":"import sys\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport glob\r\n\r\ntimeout = 600\r\nlength = 500\r\nmin_points = 1\r\nnpop = 25\r\ndef getData(files):\r\n\tavg = []\r\n\tdata = []\r\n\tN = 0\r\n\tfor i in range(0,len(files)):\r\n\t\ttry:\r\n\t\t\tfiledata = np.loadtxt(files[i])\r\n\t\t\tif isinstance(filedata,np.ndarray) and len(filedata.shape) == 1 and filedata.shape[0] >= min_points:\r\n\t\t\t\tdata.append(filedata)\r\n\t\t\telse:\r\n\t\t\t\tprint(\"Warning - Bad input: \" + files[i])\r\n\t\texcept ValueError:\r\n\t\t\tprint(\"Bad data in \" + str(files[i]))\r\n\t\t\r\n\t\tif len(data) > 0:\r\n\t\t\tN = max(N,len(data[-1]))\r\n\tN =min(N,npop)\r\n\tfor i in range(N):\r\n\t\tfor j in range(len(data)):\r\n\t\t\tif i < len(data[j]):\r\n\t\t\t\tif data[j][i] >= timeout and data[j][i] < timeout + 30:\r\n\t\t\t\t\tdata[j][i] = timeout\r\n\t\t\t\t\t#assert len(data[j]) == i + 1 , \"wtf\"\r\n\t\t\t\t\twhile len(data[j]) < npop:\r\n\t\t\t\t\t\t#data[j].append(timeout)\r\n\t\t\t\t\t\tdata[j] = np.append(data[j],timeout)\r\n\t\t\t\t\tbreak\r\n\t\t\telif i == len(data[j]):\r\n\t\t\t\tdata[j] = np.append(data[j],data[j][-1])\r\n\t\tx = 0.0\r\n\t\tm=0.0\r\n\t\tfor j in range(len(data)):\r\n\t\t\tif i < len(data[j]):\r\n\t\t\t\tx += data[j][i]\r\n\t\t\t\tm += 1.0\r\n\t\t\t\tif data[j][i] > 605:\r\n\t\t\t\t\tprint(x,files[j])\r\n\t\t\t\t\tprint(data[j])\r\n\t\t\t\t\tsys.exit(1)\r\n\t\tavg.append(x/m)\r\n\treturn avg\r\n\r\ndir = \"../data/7_28_test_mathvz3/\"\t\r\n\t\r\nscores = []\r\nscores.append(getData(glob.glob(dir + \"run*random*.txt\")))\r\nscores.append(getData(glob.glob(dir + \"run*Eps*.txt\")))\t\t\r\nscores.append(getData(glob.glob(dir + \"run*Thomp*.txt\")))\r\nscores.append(getData(glob.glob(dir + \"run*UCB*.txt\")))\r\nplt.plot(scores[0],label = \"Random\")\r\nplt.plot(scores[1],label = \"Epsilon\")\r\nplt.plot(scores[2],label = \"Thompson\")\r\nplt.plot(scores[3],label = \"UCB\")\r\nplt.legend()\r\nplt.show()\r\n","sub_path":"plots/parse_dump_exp2.py","file_name":"parse_dump_exp2.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"512530820","text":"import threading\r\n\r\n\r\nclass HeadPhone(threading.Thread):\r\n def run(self):\r\n for _ in xrange(10):\r\n print(threading.current_thread().getName())\r\n\r\nx = HeadPhone(name='send')\r\ny = HeadPhone(name='recv')\r\nx.start()\r\ny.start()\r\n","sub_path":"HeadPhone/sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"386387866","text":"import dill\n\nname = 'cart69'\n\nwith open('./'+name+'.dill', 'rb') as f:\n out = dill.load(f)\n\n\n# for set in range(0, 10):\ndata = out['problem_data']\nsol = out['solution'][-1][-1]\n\nsol.prepare(data)\n\nwriteList = []\n\nfor state in data['state_list']:\n x = sol.evaluate(state)\n writeList.append(x)\n # print(x)\n\n# print(sol.evaluate('xb'))\n# print(sol.evaluate('yb'))\n\nu = sol.evaluate('w')\nwriteList.append(u)\n\nt = sol.evaluate('t')\nwriteList.append(t)\n# print(t)\n\n# print(writeList)\n\nwith open(name+\".txt\", \"w\") as my_file:\n for set in writeList:\n for element in set:\n my_file.write(str(element) + ' ')\n my_file.write('\\n\\n')\n","sub_path":"examples/Nolan/AFRL/Carts/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"555559367","text":"from kivy.app import App\nfrom kivy.properties import ObjectProperty, StringProperty, BooleanProperty\nfrom kivy.uix.gridlayout import GridLayout\n\nfrom generalcommands import to_bool\nfrom generalconstants import containers_friendly, video_codecs_friendly, audio_codecs_friendly\nfrom generalElements.buttons.MenuButton import MenuButton\nfrom generalElements.dropDowns.NormalDropDown import NormalDropDown\n\nfrom kivy.lang.builder import Builder\n\nBuilder.load_string(\"\"\"\n:\n padding: 0, 0, int(app.button_scale / 2), 0\n cols: 1\n size_hint: 1, None\n height: self.minimum_height\n BoxLayout:\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n WideButton:\n text: 'Convert'\n on_release: root.encode()\n WideButton:\n text: 'Cancel Edit'\n warn: True\n on_release: root.owner.set_edit_panel('main')\n MediumBufferY:\n NormalLabel:\n text: 'Convert Video:'\n MenuStarterButtonWide:\n text: 'Presets'\n size_hint_x: 1\n on_release: root.preset_drop.open(self)\n GridLayout:\n canvas.before:\n Color:\n rgba: app.theme.area_background\n BorderImage:\n pos: self.pos\n size: self.size\n source: 'data/buttonflat.png'\n padding: app.padding\n cols: 1\n size_hint: 1, None\n height: self.minimum_height\n BoxLayout:\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n LeftNormalLabel:\n text: 'Container:'\n MenuStarterButtonWide:\n size_hint_x: 1\n text: root.file_format\n on_release: root.container_drop.open(self)\n SmallBufferY:\n NormalToggle:\n id: resize\n size_hint_x: 1\n state: 'down' if root.resize else 'normal'\n text: 'Resize' if self.state == 'down' else 'No Resize'\n on_release: root.update_resize(self.state)\n BoxLayout:\n disabled: not root.resize\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n ShortLabel:\n text: 'Size:'\n NormalInput:\n id: widthInput\n hint_text: '1920'\n multiline: False\n text: root.resize_width\n on_text: root.set_resize_width(self)\n ShortLabel:\n text: 'x'\n NormalInput:\n id: heightInput\n hint_text: '1080'\n multiline: False\n text: root.resize_height\n on_text: root.set_resize_height(self)\n SmallBufferY:\n NormalToggle:\n id: deinterlace\n size_hint_x: 1\n state: 'down' if root.deinterlace else 'normal'\n text: 'Deinterlace' if self.state == 'down' else 'No Deinterlace'\n on_release: root.update_deinterlace(self.state)\n SmallBufferY:\n BoxLayout:\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n LeftNormalLabel:\n text: 'Video Codec:'\n MenuStarterButtonWide:\n size_hint_x: 1\n text: root.video_codec\n on_release: root.video_codec_drop.open(self)\n id: videoCodecDrop\n #BoxLayout:\n # orientation: 'horizontal'\n # size_hint_y: None\n # height: app.button_scale\n # LeftNormalLabel:\n # text: 'Video Quality:'\n # MenuStarterButtonWide:\n # size_hint_x: 1\n # text: root.video_quality\n # on_release: root.video_quality_drop.open(self)\n # id: videoQualityDrop\n BoxLayout:\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n LeftNormalLabel:\n text: 'Encoding Speed:'\n MenuStarterButtonWide:\n size_hint_x: 1\n text: root.encoding_speed\n on_release: root.encoding_speed_drop.open(self)\n id: encodingSpeedDrop\n BoxLayout:\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n LeftNormalLabel:\n text: 'Video Bitrate:'\n FloatInput:\n id: videoBitrateInput\n text: root.video_bitrate\n\n SmallBufferY:\n BoxLayout:\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n LeftNormalLabel:\n text: 'Audio Codec:'\n MenuStarterButtonWide:\n size_hint_x: 1\n text: root.audio_codec\n on_release: root.audio_codec_drop.open(self)\n id: audioCodecDrop\n BoxLayout:\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n LeftNormalLabel:\n text: 'Audio Bitrate:'\n FloatInput:\n id: audioBitrateInput\n text: root.audio_bitrate\n SmallBufferY:\n GridLayout:\n canvas.before:\n Color:\n rgba: app.theme.area_background\n BorderImage:\n pos: self.pos\n size: self.size\n source: 'data/buttonflat.png'\n padding: app.padding\n cols: 1\n size_hint: 1, None\n height: self.minimum_height\n BoxLayout:\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n LeftNormalLabel:\n text: \"Manual command line:\"\n BoxLayout:\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n LeftNormalLabel:\n text: \"This will override all other settings.\"\n SmallBufferY:\n BoxLayout:\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n ShortLabel:\n text: 'ffmpeg.exe '\n NormalInput:\n id: commandInput\n hint_text: '-sn %c %v %a %f %p %b %d'\n multiline: False\n text: root.command_line\n on_text: root.set_command_line(self)\n BoxLayout:\n orientation: 'horizontal'\n size_hint_y: None\n height: app.button_scale\n LeftNormalLabel:\n text: \"String Replacements:\"\n GridLayout:\n cols: 3\n size_hint: 1, None\n height: int(app.button_scale * 9)\n\n ShortLabel:\n text: '%i'\n ShortLabel:\n text: ' - '\n LeftNormalLabel:\n text: 'Input File (Required)'\n\n ShortLabel:\n text: '%c'\n ShortLabel:\n text: ' - '\n LeftNormalLabel:\n text: 'Container Setting'\n\n ShortLabel:\n text: '%v'\n ShortLabel:\n text: ' - '\n LeftNormalLabel:\n text: 'Video Codec Setting'\n\n ShortLabel:\n text: '%a'\n ShortLabel:\n text: ' - '\n LeftNormalLabel:\n text: 'Audio Codec Setting'\n\n ShortLabel:\n text: '%f'\n ShortLabel:\n text: ' - '\n LeftNormalLabel:\n text: 'Framerate (From Original File)'\n\n ShortLabel:\n text: '%p'\n ShortLabel:\n text: ' - '\n LeftNormalLabel:\n text: 'Pixel Format (From Original File)'\n\n ShortLabel:\n text: '%b'\n ShortLabel:\n text: ' - '\n LeftNormalLabel:\n text: 'Video Bitrate Setting'\n\n ShortLabel:\n text: '%d'\n ShortLabel:\n text: ' - '\n LeftNormalLabel:\n text: 'Audio Bitrate Setting'\n\n ShortLabel:\n text: '%%'\n ShortLabel:\n text: ' - '\n LeftNormalLabel:\n text: 'Single Percent Sign (%)'\n\"\"\")\n\nclass EditConvertVideo(GridLayout):\n \"\"\"Convert a video file to another format using ffmpeg.\"\"\"\n\n owner = ObjectProperty()\n\n #Encoding settings\n video_codec = StringProperty()\n audio_codec = StringProperty()\n video_quality = StringProperty()\n encoding_speed = StringProperty()\n file_format = StringProperty()\n input_file = StringProperty()\n video_bitrate = StringProperty('8000')\n audio_bitrate = StringProperty('192')\n command_line = StringProperty()\n deinterlace = BooleanProperty(False)\n resize = BooleanProperty(False)\n resize_width = StringProperty('1920')\n resize_height = StringProperty('1080')\n\n #Dropdown menus\n preset_drop = ObjectProperty()\n container_drop = ObjectProperty()\n video_codec_drop = ObjectProperty()\n video_quality_drop = ObjectProperty()\n encoding_speed_drop = ObjectProperty()\n audio_codec_drop = ObjectProperty()\n\n def __init__(self, **kwargs):\n self.setup_dropdowns()\n app = App.get_running_app()\n encoding_preset = app.config.get('Presets', 'encoding')\n if encoding_preset:\n encoding_settings = encoding_preset.split(',', 10)\n if len(encoding_settings) == 11:\n self.file_format = encoding_settings[0]\n self.video_codec = encoding_settings[1]\n self.audio_codec = encoding_settings[2]\n self.resize = to_bool(encoding_settings[3])\n self.resize_width = encoding_settings[4]\n self.resize_height = encoding_settings[5]\n self.video_bitrate = encoding_settings[6]\n self.audio_bitrate = encoding_settings[7]\n self.encoding_speed = encoding_settings[8]\n self.deinterlace = to_bool(encoding_settings[9])\n self.command_line = encoding_settings[10]\n super(EditConvertVideo, self).__init__(**kwargs)\n\n def refresh_buttons(self):\n pass\n\n def save_last(self):\n pass\n\n def load_last(self):\n pass\n\n def store_settings(self):\n encoding_preset = self.file_format+','+self.video_codec+','+self.audio_codec+','+str(self.resize)+','+self.resize_width+','+self.resize_height+','+self.video_bitrate+','+self.audio_bitrate+','+self.encoding_speed+','+str(self.deinterlace)+','+self.command_line\n app = App.get_running_app()\n app.config.set('Presets', 'encoding', encoding_preset)\n\n def setup_dropdowns(self):\n \"\"\"Creates and populates the various drop-down menus used by this dialog.\"\"\"\n\n self.preset_drop = NormalDropDown()\n app = App.get_running_app()\n for index, preset in enumerate(app.encoding_presets):\n menu_button = MenuButton(text=preset['name'])\n menu_button.bind(on_release=self.set_preset)\n self.preset_drop.add_widget(menu_button)\n\n self.file_format = containers_friendly[0]\n self.container_drop = NormalDropDown()\n for container in containers_friendly:\n menu_button = MenuButton(text=container)\n menu_button.bind(on_release=self.change_container_to)\n self.container_drop.add_widget(menu_button)\n\n self.video_codec = video_codecs_friendly[0]\n self.video_codec_drop = NormalDropDown()\n for codec in video_codecs_friendly:\n menu_button = MenuButton(text=codec)\n menu_button.bind(on_release=self.change_video_codec_to)\n self.video_codec_drop.add_widget(menu_button)\n\n #self.video_quality = 'Constant Bitrate'\n #video_qualities = ['Constant Bitrate', 'High', 'Medium', 'Low', 'Very Low']\n #self.video_quality_drop = NormalDropDown()\n #for quality in video_qualities:\n # menu_button = MenuButton(text=quality)\n # menu_button.bind(on_release=self.change_video_quality_to)\n # self.video_quality_drop.add_widget(menu_button)\n\n self.encoding_speed = 'Fast'\n encoding_speeds = ['Very Fast', 'Fast', 'Medium', 'Slow', 'Very Slow']\n self.encoding_speed_drop = NormalDropDown()\n for speed in encoding_speeds:\n menu_button = MenuButton(text=speed)\n menu_button.bind(on_release=self.change_encoding_speed_to)\n self.encoding_speed_drop.add_widget(menu_button)\n\n self.audio_codec = audio_codecs_friendly[0]\n self.audio_codec_drop = NormalDropDown()\n for codec in audio_codecs_friendly:\n menu_button = MenuButton(text=codec)\n menu_button.bind(on_release=self.change_audio_codec_to)\n self.audio_codec_drop.add_widget(menu_button)\n\n def update_deinterlace(self, state):\n if state == 'down':\n self.deinterlace = True\n else:\n self.deinterlace = False\n\n def update_resize(self, state):\n if state == 'down':\n self.resize = True\n else:\n self.resize = False\n\n def set_resize_width(self, instance):\n self.resize_width = instance.text\n self.store_settings()\n\n def set_resize_height(self, instance):\n self.resize_height = instance.text\n self.store_settings()\n\n def set_preset(self, instance):\n \"\"\"Sets the current dialog preset settings to one of the presets stored in the app.\n Argument:\n index: Integer, the index of the preset to set.\n \"\"\"\n\n self.preset_drop.dismiss()\n app = App.get_running_app()\n for preset in app.encoding_presets:\n if preset['name'] == instance.text:\n if preset['file_format'] in containers_friendly:\n self.file_format = preset['file_format']\n else:\n self.file_format = containers_friendly[0]\n if preset['video_codec'] in video_codecs_friendly:\n self.video_codec = preset['video_codec']\n else:\n self.video_codec = video_codecs_friendly[0]\n if preset['audio_codec'] in audio_codecs_friendly:\n self.audio_codec = preset['audio_codec']\n else:\n self.audio_codec = audio_codecs_friendly[0]\n self.resize = preset['resize']\n self.resize_width = preset['width']\n self.resize_height = preset['height']\n self.video_bitrate = preset['video_bitrate']\n self.audio_bitrate = preset['audio_bitrate']\n self.encoding_speed = preset['encoding_speed']\n self.deinterlace = preset['deinterlace']\n self.command_line = preset['command_line']\n self.store_settings()\n return\n\n def on_video_bitrate(self, *_):\n self.store_settings()\n\n def on_audio_bitrate(self, *_):\n self.store_settings()\n\n def set_command_line(self, instance):\n self.command_line = instance.text\n self.store_settings()\n\n def change_video_quality_to(self, instance):\n \"\"\"Sets the self.video_quality value.\"\"\"\n\n self.video_quality_drop.dismiss()\n self.video_quality = instance.text\n self.store_settings()\n\n def change_encoding_speed_to(self, instance):\n \"\"\"Sets the self.encoding_speed value.\"\"\"\n\n self.encoding_speed_drop.dismiss()\n self.encoding_speed = instance.text\n self.store_settings()\n\n def change_audio_codec_to(self, instance):\n \"\"\"Sets the self.audio_codec value.\"\"\"\n\n self.audio_codec_drop.dismiss()\n self.audio_codec = instance.text\n self.store_settings()\n\n def change_video_codec_to(self, instance):\n \"\"\"Sets the self.video_codec value.\"\"\"\n\n self.video_codec_drop.dismiss()\n self.video_codec = instance.text\n self.store_settings()\n\n def change_container_to(self, instance):\n \"\"\"Sets the self.file_format value.\"\"\"\n\n self.container_drop.dismiss()\n self.file_format = instance.text\n self.store_settings()\n\n def encode(self):\n \"\"\"Pass encoding settings to owner album screen and tell it to begin encoding process.\"\"\"\n\n #file_format = containers[containers_friendly.index(self.file_format)]\n #video_codec = video_codecs[video_codecs_friendly.index(self.video_codec)]\n #audio_codec = audio_codecs[audio_codecs_friendly.index(self.audio_codec)]\n encoding_settings = {'file_format': self.file_format,\n 'video_codec': self.video_codec,\n 'audio_codec': self.audio_codec,\n 'resize': self.resize,\n 'width': self.resize_width,\n 'height': self.resize_height,\n 'video_bitrate': self.video_bitrate,\n 'audio_bitrate': self.audio_bitrate,\n 'encoding_speed': self.encoding_speed,\n 'deinterlace': self.deinterlace,\n 'command_line': self.command_line}\n self.owner.encoding_settings = encoding_settings\n print(encoding_settings)\n self.store_settings()\n self.owner.begin_encode()","sub_path":"screenAlbum/EditConvertVideo.py","file_name":"EditConvertVideo.py","file_ext":"py","file_size_in_byte":17673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"272067233","text":"import logging\nimport logging.handlers\nimport os\nimport traceback\nimport json\nimport time\nfrom enum import Enum\nfrom pathlib import Path\nfrom time import sleep\n\n\nfrom typing import Callable, Sequence\n\nimport pika\nimport re\nfrom pika.adapters.blocking_connection import BlockingChannel\n\nfrom innovapos.shared.data import utils\nfrom innovapos.shared.data.abstractions import AbstractDataAdapter, BaseDataAdapterParameters\nfrom innovapos.shared.data.adapters import TCPDataAdapterParameters, TCPDataAdapter, SerialDataAdapterParameters#,SerialDataAdapter\nfrom innovapos.shared.data.exceptions import NotUnderstoodException\nfrom innovapos.shared.data.utils import Singleton\nfrom innovapos.worker.clients import HardwareClient, BlockingAMQPClient\nimport datetime\nimport os\n\nclass HardwareWorkerSettings:\n def __init__(self):\n \"\"\"\n Reflects the configuration file that is read from the drive.\n By default targets the simulator and a local RabbitMQ instance\n \"\"\"\n self.machine_id = None\n self.restart_on_fail_seconds: str = None\n self.include_stacktrace: bool = False\n self.rabbitmq_incoming_connection_string: str = None\n self.rabbitmq_incoming_queue_name: str = None\n self.rabbitmq_outgoing_connection_string: str = None\n self.rabbitmq_outgoing_queue_name: str = None\n self.rabbitmq_app_gate_connection_string: str = None\n self.rabbitmq_app_gate_queue_name: str = None\n self.logging_logger_name: str = None\n self.logging_level: int = None\n self.logging_filename: str = None\n self.logging_format: str = None\n self.ccm_adapter_type: str = None\n self.ccm_connection_string: str = None\n self.mon_adapter_type: str = None\n self.mon_connection_string: str = None\n self.general_adapter = BaseDataAdapterParameters()\n self.general_adapter.send_msg_end = \"\\n\"\n self.general_adapter.recv_msg_end = \"\\n\"\n self.general_adapter.timeout = 1\n self.general_adapter.answer_delay = 1\n\n\n @staticmethod\n def parse_config_to_settings(path: str):\n \"\"\"\n Parses a settings file with its configuration. \n\n :param path: path to load configuration from\n :type path: str\n :return: loaded settings object\n :rtype: HardwareWorkerSettings\n \"\"\"\n # check that file exists. if it does not - raise\n if not path:\n raise ValueError(\"Path to config file is None\")\n else:\n from pathlib import Path\n print(f'Path {path}')\n my_file = Path(path)\n if not my_file.is_file():\n raise FileNotFoundError(\"Could not find config file at provided path\")\n from configparser import ConfigParser\n parser = ConfigParser()\n parser.read(path)\n config = HardwareWorkerSettings()\n\n # uuid from getnode is the mac address of the current machine in the case that we don't have one defined\n import uuid\n config.machine_id = utils.get_with_default(parser, \"worker\", \"machine_id\", uuid.getnode())\n config.include_stacktrace = utils.get_with_default(parser, \"worker\", \"include_stacktrace\", False)\n config.restart_on_fail_seconds = int(utils.get_with_default(parser, \"worker\", \"restart_on_fail_seconds\", 3))\n\n config.logging_level = utils.get_with_default(parser, \"logging\", \"level\", \"DEBUG\")\n config.logging_filename = utils.get_with_default(parser, \"logging\", \"filename\", 'innovapos_no_config.log')\n config.logging_format = utils.get_with_default(parser, \"logging\", \"format\",\n \"%%(asctime)s %%(name)s %%(levelname)s %%(message)s\")\n config.ccm_adapter_type = utils.get_with_default(parser, \"ccm_adapter\", \"type\", None)\n config.ccm_connection_string = utils.get_with_default(parser, \"ccm_adapter\", \"connection_string\", None)\n config.mon_adapter_type = utils.get_with_default(parser, \"mon_adapter\", \"type\", None)\n config.mon_connection_string = utils.get_with_default(parser, \"mon_adapter\", \"connection_string\", None)\n # config.general_adapter.send_msg_end = utils.get_with_default(parser, \"general_adapters\", \"send_end_char\",\n # config.general_adapter.send_msg_end)\n # config.general_adapter.recv_msg_end = utils.get_with_default(parser, \"general_adapters\", \"receive_end_char\",\n # config.general_adapter.recv_msg_end)\n # TODO: fix ini file \\n auto escape\n config.general_adapter.send_msg_end = '\\n'\n config.general_adapter.recv_msg_end = '\\n'\n\n timeout_int = int(utils.get_with_default(parser, \"general_adapters\", \"timeout\", \"2\"))\n config.general_adapter.timeout = timeout_int\n answer_delay_int = int(utils.get_with_default(parser, \"general_adapters\", \"answer_delay\", \"2\"))\n config.general_adapter.answer_delay = answer_delay_int\n conn = parser.get(\"rabbitmq_incoming\", \"connection_string\")\n print(f'conexcion: {conn}')\n config.rabbitmq_incoming_connection_string = parser.get(\"rabbitmq_incoming\", \"connection_string\")\n config.rabbitmq_incoming_queue_name = f'{parser.get(\"rabbitmq_incoming\", \"queue_name\")}{config.machine_id}'\n config.rabbitmq_outgoing_connection_string = parser.get(\"rabbitmq_outgoing\", \"connection_string\")\n config.rabbitmq_outgoing_queue_name = f'{parser.get(\"rabbitmq_outgoing\", \"queue_name\")}{config.machine_id}'\n #gateway\n config.rabbitmq_app_gate_connection_string = parser.get(\"rabbitmq_local\", \"connection_string\")\n config.rabbitmq_app_gate_queue_name = f'{parser.get(\"rabbitmq_local\", \"queue_name\")}-{config.machine_id}'\n\n\n\n return config\n\n\n\nclass WorkerStates(Enum):\n NONE = \"NONE\" # --si\n DEBUGGING = \"DEBUGGING\"\n ANY = \"ANY\" # --si\n BOOTING = \"BOOTING\"\n IDLE = \"IDLE\"\n BUYING_CASH = \"BUYING_CASH\"\n BUYING_CASH_NO_APP = \"BUYING_CASH_NO_APP\"\n WAITING_CASH = \"WAITING_CASH\"\n RETURN_CASH = \"RETURN_CASH\"\n DISPENSING = \"DISPENSING\"\n WAIT_COLLECTION = \"WAIT_COLLECTION\"\n MANUAL = \"MANUAL\" # --si\n APP = \"APP\" # --si\n WAIT_PRODUCT_OUT=\"WAIT_PRODUCT_OUT\" #--si\n WAIT_PRODUCT_OUT_LOCAL=\"WAIT_PRODUCT_OUT_LOCAL\"\n LOCAL=\"LOCAL\"\n\nclass MessageJson():\n Accion=''\n Phone=''\n Success='true'\n Status=''\n Mensaje=''\n TimeBloq=''\n\nclass ErrorProcess():\n DESCONOCIDO = \"ERR-1000: ERROR DESCONOCIDO\" # --si\n CONEXION_USO= \"ERR-1001: La conexion esta en uso\"\n USO_APP = \"ERR-1002: Maquina usada por APP\"\n CCM_STATUS = \"ERR-2001: Maquina No disponible\"\n CCM_SELECT = \"ERR-2002: No se puede Seleccionar el producto\"\n CCM_OUT_PRODUC=\"ERR-2003: Existe un Producto en el Dispensador, Retirelo para continuar\"\n CCM_WRITE = \"ERR-2004: No se puede Despachar el producto\"\n TIME_OUT=\"ERR-2004: Su compra ha exedido el tiempo Establecido.\"\n PRICE_LACK=\"ERR-3001: Precio Insuficente \"\n\n SET_STOCK=\"ERR-3002: no se puede Actualizar el Stock\"\n SET_STOCK_FULL=\"ERR-3003: No se puede actualizar el Stock Full\"\n GET_STOCK=\"ERR-3004: No se puede obtener el Stock\"\n GET_STOCK_FULL=\"ERR-3005: No se puede obtener el Stock Full\"\n SET_PRICE=\"ERR-3006: Error Actualizando el Precio\"\n\nclass SussesProcess():\n START='Proceso Iniciado con Exito'\n PREPARE='Equipo Preparado Para Compra'\n CANCEL='Operaciones Canceladas'\n CCM_STATUS = \"Maquina disponible\"\n CCM_SELECT = \"Producto Seleccionado\"\n CCM_WRITE = \"Producto Despachado\"\n\n SET_STOCK = \"Stock Agregado con Exito\"\n SET_STOCK_FULL = \"Stock Agregado con Exito\"\n SET_PRICE = \"Actiualizacion de Precio Correcto\"\n ADD_TIME = \"Tiempo extra Asignado\"\n\nclass ConstantesProcess():\n TimeMessageExpire:str='60000'\n QueueServer:str='SERVER'\n TimeMessageExpireMovil:str='120000'\n QueueServerCompra:str='OUT_ServerREAD'\n\n\n\n\n@Singleton\nclass HardwareWorker:\n _instance_ = None\n\n def __init__(self):\n \"\"\"\n Main coordinator of the interaction with the dispenser\n Uses innovapos.dispenser.adapters.HardwareClient in order to interact with the data; \\\n the pika library is used in order to be able to read and write from RabbitMQ\n\n \"\"\"\n self._ws_handlers_ = {}\n self._gateway_handlers_ = {}\n self._app_handlers_ = {}\n self.settings: HardwareWorkerSettings = None\n self.hardware_client: HardwareClient = None\n self.ws_client: BlockingAMQPClient = None\n self.gateway_client: BlockingAMQPClient = None\n self.cur_app_user_client: BlockingAMQPClient = None\n self.machine_id = None\n self.current_state = WorkerStates.BOOTING\n # TODO: Variables de Uso local\n self.importeIngresado = 0\n self.precioProducto = 0\n self.KeyApi:str=None\n self.KeyTime:int=0\n self.new_inc_queue:str=None\n self.new_out_queue:str=None\n self.Fecha:datetime=None\n self.isFinish:bool=False\n\n def restart(self):\n self.current_state = WorkerStates.IDLE\n self.KeyApi: str = None\n self.KeyTime: int = 0\n self.new_inc_queue: str = None\n self.new_out_queue: str = None\n self.Fecha: datetime = None\n self.current_state=WorkerStates.IDLE\n\n @staticmethod\n def _shared_decorator_(fn, handlers_dict, rule, valid_states):\n if valid_states is None or len(valid_states) == 0:\n raise RuntimeError(\"Valid states for a handler cannot be None or empty. Use WorkerStates.NONE if needed\")\n if rule in handlers_dict:\n raise RuntimeError(f\"rule {rule} is being set twice, existing handler is {handlers_dict[rule]}\")\n handlers_dict[rule] = {\"valid_states\": valid_states, \"function\": fn}\n return fn\n\n def ws_message_handler(self, rule, valid_states: Sequence[WorkerStates]) -> \\\n Callable[[BlockingAMQPClient, pika.BasicProperties, str], None]:\n \"\"\"\n Message handler decorator. Registers a function in the handlers dictionary so that when a new message arrives\n from the SERVER message queue it gets handled.\n :param rule: \n :type rule: \n :param valid_states: \n :type valid_states: \n :return: \n :rtype: \n \"\"\"\n\n def decorator(fn):\n self._shared_decorator_(fn, self._ws_handlers_, rule, valid_states)\n return fn\n\n return decorator\n\n def gateway_message_handler(self, rule, valid_states: Sequence[WorkerStates] = None) -> \\\n Callable[[BlockingAMQPClient, pika.BasicProperties, str], None]:\n \"\"\"\n Message handler decorator. Registers a function in the handlers dictionary so that when a new message arrives\n from the GATEWAY message queue it gets handled.\n :param rule: \n :type rule: \n :return: \n :rtype: \n \"\"\"\n\n def decorator(fn):\n self._shared_decorator_(fn, self._gateway_handlers_, rule, valid_states)\n return fn\n\n return decorator\n\n def app_message_handler(self, rule, valid_states: Sequence[WorkerStates] = None) -> \\\n Callable[[BlockingAMQPClient, pika.BasicProperties, str], None]:\n \"\"\"\n Message handler decorator. Registers a function in the handlers dictionary so that when a new message arrives\n from the APP message queue it gets handled.\n :param rule: \n :type rule: \n :return: \n :rtype: \n \"\"\"\n\n def decorator(fn):\n self._shared_decorator_(fn, self._app_handlers_, rule, valid_states)\n return fn\n\n return decorator\n\n def _setup_logging_(self) -> None:\n self.logger = logging.getLogger(self.settings.logging_logger_name)\n self.logger.setLevel(self.settings.logging_level)\n log_stream_handler = logging.StreamHandler()\n log_stream_handler.setLevel(self.settings.logging_level)\n log_stream_formatter = logging.Formatter(self.settings.logging_format)\n log_stream_handler.setFormatter(log_stream_formatter)\n\n if self.settings.logging_filename.startswith(\"~\"):\n self.settings.logging_filename = self.settings.logging_filename.replace(\"~\", os.path.expanduser(\"~\"))\n dir_path = Path(self.settings.logging_filename).parent\n os.makedirs(dir_path, exist_ok=True)\n log_file_handler = logging.handlers.TimedRotatingFileHandler(filename=self.settings.logging_filename,\n when='D', interval=1, backupCount=0)\n log_file_formatter = logging.Formatter(self.settings.logging_format)\n log_file_handler.setFormatter(log_file_formatter)\n self.logger.addHandler(log_stream_handler)\n self.logger.addHandler(log_file_handler)\n self.logger.info(\" = = = = = = Bootstrapper logging setup = = = = = = \")\n self.logger.debug(\"Bootstrapper config complete\")\n\n def configure_from_config_file(self, config_path: str):\n self.settings = HardwareWorkerSettings.parse_config_to_settings(config_path)\n self._setup_logging_()\n self.machine_id = self.settings.machine_id\n self.logger.info(f\"Machine configured as {self.machine_id} from config file {config_path}\")\n\n def _create_and_configure_adapter_(self, adapter_type: str, connection_string: str) -> AbstractDataAdapter:\n \"\"\"\n Configures a data adapter based on the the configuration loaded\n\n :param connection_string: configuration string for the needed adapter\n :type connection_string: configuration\n :return: \n :rtype: \n \"\"\"\n adapter: AbstractDataAdapter = None\n if adapter_type == \"tcp\":\n con_str_split = connection_string.split(\":\")\n hostname = con_str_split[0]\n port = int(con_str_split[1])\n adapter_params = TCPDataAdapterParameters(hostname=hostname, port=port,\n send_end_char=self.settings.general_adapter.send_msg_end,\n recv_end_char=self.settings.general_adapter.recv_msg_end,\n timeout=self.settings.general_adapter.timeout,\n answer_delay=self.settings.general_adapter.answer_delay)\n adapter = TCPDataAdapter(adapter_params)\n elif adapter_type == \"serial\":\n adapter_params = SerialDataAdapterParameters(serial_port=connection_string,\n send_end_char=self.settings.general_adapter.send_msg_end,\n recv_end_char=self.settings.general_adapter.recv_msg_end,\n timeout=self.settings.general_adapter.timeout,\n answer_delay=self.settings.general_adapter.answer_delay)\n adapter = SerialDataAdapter(adapter_params)\n return adapter\n\n def _setup_hw_client_(self):\n ccm_adapter = self._create_and_configure_adapter_(self.settings.ccm_adapter_type,\n self.settings.ccm_connection_string)\n mon_adapter = self._create_and_configure_adapter_(self.settings.mon_adapter_type,\n self.settings.mon_connection_string)\n self.hardware_client: HardwareClient = HardwareClient(ccm_adapter=ccm_adapter, mon_adapter=mon_adapter)\n\n self.hardware_client.set_monedero_callback(self._monedero_message_received_callback_)\n self.hardware_client.open_connections()\n\n\n def _setup_ws_amqp_client_(self):\n #TODO: agregado para phone\n self.ws_client = BlockingAMQPClient(\n incoming_mq_params=pika.URLParameters(self.settings.rabbitmq_incoming_connection_string),\n incoming_queue_name=self.settings.rabbitmq_incoming_queue_name,\n outgoing_mq_params=pika.URLParameters(self.settings.rabbitmq_outgoing_connection_string),\n outgoing_queue_name=self.settings.rabbitmq_outgoing_queue_name,\n message_handler=self._ws_message_received_callback_)\n self.ws_client.begin_consuming()\n self.logger.info(\"WS AMQP setup done\")\n\n def _setup_app_gateway_amqp_client_(self):\n #todo Agregado para phone\n print(f'innova: {self.settings.rabbitmq_app_gate_connection_string}')\n self.gateway_client = BlockingAMQPClient(\n incoming_mq_params=pika.URLParameters(self.settings.rabbitmq_app_gate_connection_string),\n incoming_queue_name=self.settings.rabbitmq_app_gate_queue_name,\n outgoing_mq_params=pika.URLParameters(self.settings.rabbitmq_app_gate_connection_string),\n outgoing_queue_name=self.settings.rabbitmq_app_gate_queue_name + \"-default\",\n message_handler=self._gateway_message_received_callback_)\n self.gateway_client.begin_consuming()\n self.logger.debug(\"App Gate AMQP setup done\")\n\n def _setup_cur_app_user_client_(self, incoming_queue_name: str, outgoing_queue_name: str,\n message_handler: Callable[[BlockingChannel, pika.spec.Basic.Deliver,\n pika.spec.BasicProperties, bytes], None]):\n self.cur_app_user_client = BlockingAMQPClient(\n incoming_mq_params=pika.URLParameters(self.settings.rabbitmq_app_gate_connection_string),\n incoming_queue_name=incoming_queue_name,\n outgoing_mq_params=pika.URLParameters(self.settings.rabbitmq_app_gate_connection_string),\n outgoing_queue_name=outgoing_queue_name,\n message_handler=message_handler)\n self.cur_app_user_client.begin_consuming()\n\n def _shared_message_handler_(self, client: BlockingAMQPClient, handlers_dict: dict,\n channel: BlockingChannel, method: pika.spec.Basic.Deliver,\n props: pika.spec.BasicProperties, body: bytes):\n try:\n self.logger.info(f\"Reciviendo mensaje de AMQP. MSG ID: {props.message_id}\")\n _props = pika.spec.BasicProperties()\n _props.expiration = '20000'\n\n if props.type not in handlers_dict: # no existe handler para este tipo\n print('no existe handler para este tipo')\n self.logger.error('no existe handler para este tipo')\n raise NotUnderstoodException(f\"Tipo de Mensaje '{props.type}' No es Soportado por el handler\")\n handler_info = handlers_dict[props.type] # handler existe, lo sacamos\n valid_states = handler_info['valid_states']\n if self.current_state not in valid_states and WorkerStates.ANY not in valid_states:\n # si el estado no es valido o si el comando no soporta \"ANY\" -> mandamos error\n # TODO: definir como controlar errores de este tipo\n if WorkerStates.NONE in valid_states:\n self.logger.warning(f\"Handler function {handler_info['function']} has a NONE identifier. \" +\n f\"Is this intentional?\")\n self.logger.debug(f\"Could not handle command {props.message_id}. \" +\n f\"Estado Actual {self.current_state}, Enviado: {valid_states}\")\n\n\n client.send_message(f\"Estado Actual {self.current_state}, Esperado: {valid_states}\",props=_props)\n return\n handler = handler_info[\"function\"]\n self.logger.info(f\"Handling msg #{props.message_id}, type '{props.type}' with {handler}\")\n message = body.decode()\n handler(client, props, message)\n\n except Exception as exc:\n stack_trace = traceback.format_exc()\n self.logger.error(f\"An exception occured while handling MQ message #{props.message_id}\\n{stack_trace}\")\n client.send_message(stack_trace,props=_props)\n self.logger.debug(f\"Error from message #{props.message_id} sent to queue.\")\n\n def _monedero_message_received_callback_(self, message: str) -> str:\n\n #TODO: hugo monedero callback\n '''\n print('')\n print('')\n print('>>>>>>>>>>>>>< LECTURA MONEDERO >>>>>>>>>>>>>>>>>>>>><')\n print('')\n print('')\n print('')\n '''\n # self.logger.debug(f\" Message from Monedero {message}\")\n '''\n 1.- Verificcamos el comando del monedero\n :param message: \n :return: \n '''\n\n #fecha=str(time.strftime(\"%H:%M:%S\"))\n if 'PING' in message:\n return ''\n self.logger.info(f\"Monedero message received: {message}\")\n\n #print(f'Precio Producto:>>>>>>> {self.precioProducto}')\n print(f'====================================')\n print(f'Mensaje monedero: {message}')\n print(f'Status: {self.current_state}')\n print(f'====================================')\n if('CCM_Valor_Introducido' in message and (self.current_state==WorkerStates.APP or self.current_state==WorkerStates.LOCAL)):\n matches = re.search(\"CCM_Valor_Introducido_(\\d+\\.\\d+)CCM_Valor_Restante_(\\d+\\.\\d+)\", message)\n self.importeIngresado = self.importeIngresado + float(matches.groups()[0])\n print('**************************************')\n print('Lectura comandos ')\n print(f'Importe Introducido: {self.importeIngresado}')\n print(f'Mensaje Machine: {message}')\n print('**************************************')\n return 'Status: APP'\n if((self.current_state==WorkerStates.WAIT_PRODUCT_OUT or self.current_state==WorkerStates.WAIT_PRODUCT_OUT_LOCAL) and (('CCM_Producto_OUT' in message)or ('CCM_Producto_Out' in message ))):\n print('Producto retirado OK')\n print('Valida CCM_Producto_OUT Y WAIT_PRODUCT_OUT_LOCAL')\n print(f'Estado Machine:{self.current_state}')\n print(f'isFinish:{self.isFinish}')\n\n if(self.current_state==WorkerStates.WAIT_PRODUCT_OUT):\n if (self.isFinish==True):\n self.current_state==WorkerStates.IDLE\n else:\n self.current_state=WorkerStates.APP\n print(f'Cambiado Estado:{self.current_state}')\n else:\n if (self.isFinish == True):\n self.current_state == WorkerStates.IDLE\n else:\n self.current_state = WorkerStates.LOCAL\n\n\n self.importeIngresado=0\n self.precioProducto=0\n\n return 'OK'\n\n if ('CCM_OK_DEVOLUCION' in message and (self.current_state==WorkerStates.APP or self.current_state==WorkerStates.LOCAL)):\n self.importeIngresado = 0\n return 'Status: APP'\n\n print(f'Estatus machine: {self.current_state}')\n #elif ('CCM_DESPEDIDA_OK' in message or 'CCM_OK_DEVOLUCION' in message or 'CCM_Producto_Out' in message or 'CCM_COMMAND_PRODUCTOTAMBOR' in message or 'CCM_Recarga_Stop' in message):\n #\n # self.current_state=WorkerStates.IDLE\n # self.importeIngresado=0\n # self.precioProducto=0\n #else:\n # print(f'Mensaje: {message}')\n # self.importeIngresado = 0\n # self.precioProducto = 0\n\n return 'Operando'\n\n def changeStatus(self, Estatus):\n if Estatus.upper() == 'NOR':\n self.current_state = WorkerStates.MANUAL\n elif Estatus.upper() == 'APP':\n self.current_state = WorkerStates.APP\n else:\n self.current_state = WorkerStates.IDLE\n\n def messageJsonOutput(self, Mensaje: MessageJson,MultiDat:str=None):\n return self.messageJsonOutput_Encoding(Mensaje.Accion, Mensaje.Phone, Mensaje.Success, Mensaje.Status, Mensaje.Mensaje,Mensaje.TimeBloq,MultiDat)\n\n ''\n def messageJsonOutput_Encoding(self, Accion, Phone, Success, Status, Mensaje,TimeBloq,MultiDat):\n\n jsonData = '{\"Accion\":\"'+str(Accion)+'\",\"Phone\":\"'+str(Phone)+'\",\"Success\":'+str(Success)+',\"Status\":\"'+str(Status)+'\",\"Mensaje\":\"'+str(Mensaje)+'\",\"TimeBloq\":\"'+str(TimeBloq)+'\"}'\n if MultiDat!=None:\n jsonData = '{\"Accion\":\"' + str(Accion) + '\",\"Phone\":\"' + str(Phone) + '\",\"Success\":' + str(\n Success) + ',\"Status\":\"' + str(Status) + '\",\"Mensaje\":' + str(Mensaje) + '}'\n jsonToPython =jsonData# json.loads(jsonData)\n print(f'Mensaje >>>> : {jsonToPython}')\n return jsonToPython\n\n def _ws_message_received_callback_(self, channel: BlockingChannel, method: pika.spec.Basic.Deliver,\n props: pika.spec.BasicProperties, body: bytes):\n self._shared_message_handler_(self.ws_client, self._ws_handlers_, channel, method, props, body)\n\n def _gateway_message_received_callback_(self, channel: BlockingChannel, method: pika.spec.Basic.Deliver,\n props: pika.spec.BasicProperties, body: bytes):\n self._shared_message_handler_(self.gateway_client, self._gateway_handlers_, channel, method, props, body)\n\n def _app_message_received_callback_(self, channel: BlockingChannel, method: pika.spec.Basic.Deliver,\n props: pika.spec.BasicProperties, body: bytes):\n self._shared_message_handler_(self.cur_app_user_client, self._app_handlers_, channel, method, props, body)\n\n def run_with_autorecover(self):\n \"\"\"\n Runs the worker\n \"\"\"\n self.logger.info(\"Starting up dispenser main loop\")\n self.logger.info(f\"Following command handlers were registered:\\n {', '.join(self._ws_handlers_.keys())}\")\n TimeReboot=0\n while True:\n try:\n self.logger.info(f\"Ejecutando Autorecover.Inicio el worker de conexiones\")\n print('HMS: configurando hw_client_')\n #TODO: TV\n self.logger.info(f\"Configurando conexiones con los Soket\")\n self._setup_hw_client_()\n print('HMS: configurando amqp_client_')\n self._setup_ws_amqp_client_()\n #TODO: desactivamos la parte del gateway\n print('HMS: configurando gateway')\n # HMS: gateway\n #self._setup_app_gateway_amqp_client_()\n self.logger.info(f\"Conexion Iniciada con Exito. Inicio de Loop de eventos.\")\n self.current_state = WorkerStates.IDLE\n\n #import threading\n #import sys\n #from innovapos.worker.tasks.Api import API\n #Service=API()\n #Service.Run()\n\n #t=threading.Thread(target=Service.Run())\n #t.start()\n #t.join()\n #Service.Run()\n\n while True:\n self.ws_client.process_data_events()\n #HMS: gateway\n #self.gateway_client.process_data_events()\n if self.cur_app_user_client is not None:\n self.cur_app_user_client.process_data_events()\n sleep(0.1)\n except Exception as e:\n TimeReboot = TimeReboot + 1\n # TODO: LINUX\n print(f'HMS Reboot: {TimeReboot}')\n if (TimeReboot == 3):\n os.system('sudo reboot now')\n\n\n self.logger.exception(f\"An error has occurred during worker execution.\")\n self.logger.info(\"Recovering from error. Restarting in \" +\n f\"{self.settings.restart_on_fail_seconds} seconds...\")\n sleep(self.settings.restart_on_fail_seconds)\n\n\n","sub_path":"src/innovapos/worker/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":27987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"107077104","text":"import data\nfrom menu import await_input\ndef search_tool(will_print=False):\n \"\"\"If will_print is true will search for and print entries in the phonebook. If false it will return a list with those entries instead.\"\"\"\n search_term = input(\"Search for: \").lower()\n is_item_found = False\n list_out = []\n\n for entry in data.container_phonebook: #Search for each dictionary in the list.\n for key in entry: #Search for each key in the dictionary.\n if entry[key].lower() == search_term: #Search each value in the dictionary.\n if will_print == True:\n print(\"{first_name} {last_name}: {number}\".format(**entry)) #** is an operator that unpacks a dictionary.\n is_item_found = True\n else:\n list_out.append(entry) \n if (\"{first_name} {last_name}\".format(**entry)).lower() == search_term:\n print(\"{first_name} {last_name}: {number}\".format(**entry)) #** is an operator that unpacks a dictionary.\n is_item_found = True\n\n if is_item_found == False:\n print(\"No Entries Found\")\n await_input()\n return list_out\n \n \n\n","sub_path":"02-week/2-wednesday/labs/henderson-ephriam/project-phone-book/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"538431967","text":"import unittest\nimport numpy as np\nimport numpy.testing as npt\nimport lbm_bgk as lbm\n\n\ndims, q = 2, 9\ne = np.array([(0, 0), (1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (-1, 1),\n (-1, -1), (1, -1)])\nw = np.array([4./9., 1./9., 1./9., 1./9., 1./9., 1./36., 1./36., 1./36.,\n 1./36.])\nc = 1./np.sqrt(3) # Speed of sound\n\n\nclass TestFunctions(unittest.TestCase):\n\n def test_viscosity(self):\n self.assertEqual(lbm.viscosity(10, 10, 100), 1)\n\n def test_RelaxationTime(self):\n self.assertAlmostEqual(lbm.RelaxationTime(c, 10, 10, 300), 1.5)\n\n def test_density(self):\n self.assertEqual(lbm.density(np.array([1, 2, 3])), 6)\n\n def test_geometry(self):\n self.assertTrue(lbm.geometry(1, 0, 4, 1, 4).all())\n self.assertFalse(lbm.geometry(0, 0, 3, 1, 4).all())\n npt.assert_array_equal(lbm.geometry(1, 1, 1, 3, 3)[1],\n [False, True, False])\n\n def test_vel_init(self):\n self.assertAlmostEqual(lbm.vel_init(0.1, 1, 1, 2)[0], 0.1)\n self.assertAlmostEqual(lbm.vel_init(0.1, 1, 1, 2)[1], 0.0)\n\n def test_solve(self):\n self.assertAlmostEqual(lbm.solve(Nx=2, Ny=4, max_v=0.1, x_c=0, y_c=3,\n side=0, iterations=10)[1][1,0,3], 0.0)\n\n self.assertAlmostEqual(lbm.solve(Nx=2, Ny=4, max_v=0.1, x_c=0, y_c=3,\n side=0, iterations=10)[1][1,1,3], 0.0)\n\n self.assertAlmostEqual(lbm.solve(Nx=2, Ny=4, max_v=0.1, x_c=0, y_c=3,\n side=0, iterations=10)[1][1, 1, 3], 0)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_lbm.py","file_name":"test_lbm.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"565729443","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def reverseList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if head is None:\n return None\n\n if head.next is None:\n return head\n\n # divide and conquer\n # 1. find the last node of current iteration\n # 2. put the last node in the first place\n # 3. recursively reverse the rest of nodes, \n # and connect the first (last previously) node to the reversed nodes\n head_copy = head\n \n while head.next.next:\n head = head.next\n \n last_node = head.next\n head.next = None\n\n last_node.next = self.reverseList(head_copy)\n\n return last_node\n\n def reverseBetween(self, head, m, n):\n \"\"\"\n :type head: ListNode\n :type m: int\n :type n: int\n :rtype: ListNode\n \"\"\"\n\n if head is None:\n return None\n \n # add a header before any non-trivial node\n header = ListNode(-999)\n header.next = head\n head = header\n\n index = 0\n while head:\n if index == m - 1:\n before_reverse = head\n start = head.next\n if index == n:\n end = head\n after_reverse = head.next\n break\n \n index += 1\n head = head.next\n\n end.next = None\n reversed_linked_list = self.reverseList(start)\n before_reverse.next = reversed_linked_list\n\n head = header\n while head.next:\n head = head.next\n \n head.next = after_reverse\n\n return header.next\n","sub_path":"codes/MartinMa28/python3/0092_reverse_linked_list_2.py","file_name":"0092_reverse_linked_list_2.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"617198204","text":"from collections import deque\nimport sys\nN = int(sys.stdin.readline())\nqueue = deque()\nfor _ in range(N):\n cmd = list(sys.stdin.readline().split())\n if cmd[0] == 'push_back':\n queue.append(cmd[1])\n\n elif cmd[0] == 'push_front':\n queue.appendleft(cmd[1])\n\n elif cmd[0] == 'pop_front':\n if len(queue) == 0:\n print('-1')\n else:\n print(queue.popleft())\n\n elif cmd[0] == 'pop_back':\n if len(queue) == 0:\n print('-1')\n else:\n print(queue.pop())\n\n elif cmd[0] == 'size':\n print(str(len(queue)))\n\n elif cmd[0] == 'empty':\n if len(queue) == 0:\n print('1')\n else:\n print('0')\n\n elif cmd[0] == 'front':\n if len(queue) == 0:\n print('-1')\n else:\n print(queue[0])\n\n elif cmd[0] == 'back':\n if len(queue) == 0:\n print('-1')\n else:\n print(queue[-1])","sub_path":"알고리즘 기초/10866.py","file_name":"10866.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"326614446","text":"import sys\nsys.stdin = open(\"파리퇴치.txt\", 'r')\n\nT = int(input())\nfor tc in range(T):\n N, M = map(int, input().split()) #N 영역크기, M 파리채크기\n arr = [list(map(int,input().split())) for _ in range(N)]\n maxi = 0\n\n\n for i in range(N-M+1):\n for j in range(N-M+1):\n dye = 0\n for k in range(M):\n for l in range(M):\n\n dye += arr[i+k][j+l]\n\n if maxi < dye:\n maxi = dye\n print(maxi)\n\n\n\n\n\n","sub_path":"08_algorithm/05_algorithm2019.08.19/파리퇴치.py","file_name":"파리퇴치.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"173999370","text":"nums = [3,4,5,1,2] \n\n# binary search - o(logn) runtime, o(1) space\nif not nums:\n return -1\n\nl = 0\nr = len(nums) - 1\nwhile l < r:\n mid = l + (r-l)//2\n if nums[mid] > nums[r]:\n l = mid + 1\n else:\n r = mid\n\nreturn nums[l]","sub_path":"medium/153.py","file_name":"153.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"31184401","text":"import os\nfrom flask import Flask, flash, render_template, request, redirect, \\\n url_for, send_from_directory\nfrom werkzeug import secure_filename\nimport cloudinary\nfrom cloudinary.uploader import upload\nfrom cloudinary.utils import cloudinary_url\nimport requests\n\nfrom label import label_leaf\n\nALLOWED_EXTENSIONS = set(['jpg', 'jpeg'])\nUPLOAD_FOLDER = './pictures'\n\napp = Flask(__name__)\napp.secret_key = '@3xffxbex9b5x06:x8f=xc0x04x15Bxe6xc2'\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\ncloudinary.config( \n cloud_name = \"toni-not-oak\",\n api_key = \"866339269462168\",\n api_secret = \"TwmBPqSIbsuwWcG2w3-SrkokM2Q\"\n)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n # Check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file_to_upload = request.files['file']\n # If user does not select file, browser also\n # submit an empty part without filename\n if file_to_upload.filename == '':\n flash('No selected file')\n return redirect(request.url)\n # Check if filetype is okay\n if not allowed_file(file_to_upload.filename):\n flash('File-type not allowed. Use .png, .jpg or .jpeg.')\n print('File-type not allowed. Use .png, .jpg or .jpeg.')\n return redirect(request.url)\n # Upload file\n upload_result = upload(file_to_upload, folder = 'uploads')\n thumbnail_for_model, options = cloudinary_url(\n upload_result['public_id'], format=\"jpg\", crop=\"scale\", width=299,\n height=299)\n thumbnail_for_user, options = cloudinary_url(\n upload_result['public_id'], format=\"jpg\", crop=\"fit\", width=600,\n height=600, secure=True)\n # Analysis\n image = requests.get(thumbnail_for_model, allow_redirects=True)\n open('image/image.jpg', 'wb').write(image.content)\n leaf_result = label_leaf('image/image.jpg')\n return render_template('analysis.html',\n leaf=leaf_result['labels'][0],\n certainty=leaf_result['results'][0], time=leaf_result['time'],\n thumbnail_for_user=thumbnail_for_user)\n\n # Upload form via GET request\n return render_template('index.html')\n\n\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n\n@app.route('/analysis_example', methods=['GET', 'POST'])\ndef examples():\n if request.method == 'POST':\n thumbnail_for_user = request.form.get('postImage')\n # Resize for model via Cloudinary URL\n thumbnail_for_model = thumbnail_for_user.replace(\"w_600\",\"w_299,h_299\")\n # Analysis\n image = requests.get(thumbnail_for_model, allow_redirects=True)\n open('image/image.jpg', 'wb').write(image.content)\n leaf_result = label_leaf('image/image.jpg')\n return render_template('analysis.html',\n leaf=leaf_result['labels'][0],\n certainty=leaf_result['results'][0], time=leaf_result['time'],\n thumbnail_for_user=thumbnail_for_user)\n\n return render_template('index.html')\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"121512003","text":"#!/usr/bin/env python\n\nimport sys\nimport yaml\nimport subprocess\n\nignore_attribs = ['CameraName',\n 'DeviceEthAddress',\n 'HostEthAddress',\n 'HostIPAddress',\n 'SerialNumber',\n 'UniqueId',\n 'WhitebalMode',\n 'ExposureMode',\n 'GainMode',\n 'FrameStartTriggerMode',\n 'StreamBytesPerSecond',\n 'Height',\n 'Width',\n 'ExposureValue',\n 'GainValue',\n 'WhitebalValueRed',\n 'WhitebalValueBlue',\n 'RegionX',\n 'RegionY',\n 'PacketSize',\n 'FrameRate',\n 'SyncInLevels',\n 'StatFrameRate',\n 'StatFramesCompleted',\n 'StatFramesDropped',\n 'StatPacketsErroneous',\n 'StatPacketsMissed',\n 'StatPacketsReceived',\n 'StatPacketsRequested',\n 'StatPacketsResent']\n\n\ndef write_attributes(output):\n attribs = {}\n for ln in output.split('\\n'):\n vals = ln.split()\n \n if len(vals) < 3:\n continue\n\n if vals[-2] != '=':\n continue\n\n if ignore_attribs.count(vals[0]) == 0:\n attribs[vals[0]] = vals[-1]\n \n stream = file('prosilica_attribs.yaml', 'w')\n yaml.dump(attribs, stream)\n \n\n\nif __name__ == '__main__':\n IP = '10.68.0.20'\n \n cmd = 'rosrun prosilica_gige_sdk ListAttributes %s' % IP\n \n p = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n stderr = subprocess.PIPE, shell=True)\n o, e = p.communicate()\n \n if p.returncode != 0:\n print >> sys.stderr, \"Unable to get Attributes from prosilica\"\n\n write_attributes(o)\n","sub_path":"root/usr/share/checkprosilica/get_prosilica_attribs.py","file_name":"get_prosilica_attribs.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"521898303","text":"\"\"\"\nGiven a sorted array, convert it into a height-balanced binary search tree.\n--\nstart from the middle,\nrecurse on the left and right\n\"\"\"\n\n\nclass Node:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n\ndef high_balanced_bst(arr):\n def helper(start, end, arr):\n if start > end:\n return None\n elif start == end:\n return Node(arr[start])\n else:\n mid = start + (end - start) // 2\n n = Node(arr[mid])\n n.left = helper(start, mid - 1, arr)\n n.right = helper(mid + 1, end, arr)\n return n\n\n return helper(0, len(arr) - 1, arr)\n\n\nif __name__ == \"__main__\":\n res = high_balanced_bst([1, 2, 3, 4, 5])\n","sub_path":"old/dcp_series/dcp_296.py","file_name":"dcp_296.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"424089698","text":"import spacy\n\n# Matcherをインポート\nfrom spacy.matcher import Matcher\n\nnlp = spacy.load(\"en_core_web_sm\")\ndoc = nlp(\"Upcoming iPhone X release date leaked as Apple reveals pre-orders\")\n\n# 共有語彙データを用いてMatcherを初期化\nmatcher = Matcher(nlp.vocab)\n\n# 「iPhone」と「X」にマッチするパターンを作成\npattern = [{\"TEXT\": \"iPhone\"}, {\"TEXT\": \"X\"}]\n\n# matcherにパターンを追加\nmatcher.add(\"IPHONE_X_PATTERN\", None, pattern)\n\n# docに対してmatcherを用いる\nmatches = matcher(doc)\nprint(\"Matches:\", [doc[start:end].text for match_id, start, end in matches])\n","sub_path":"exercises/ja/solution_01_11.py","file_name":"solution_01_11.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"278171338","text":"def ChkPrime(no):\n\tif no > 1:\n\t\tfor i in range(2, no):\n\t\t\tif no % i == 0:\n\t\t\t\tbreak\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\telse:\n\t\treturn False\n\ndef main():\n\tno = int(input(\"Enter a number: \"))\n\tif no > 0:\n\t\tArr = list()\n\t\tfor i in range(0, no):\n\t\t\tprint(\"Enter no {}: \".format(i+1), end=\"\")\n\t\t\tArr.append(int(input()))\n\t\tprint(\"Accepted List: {}\".format(Arr))\n\t\tFilteredList = list(filter(ChkPrime, Arr))\n\t\tif len(FilteredList) > 0:\n\t\t\tprint(\"Filtered List: {}\".format(FilteredList))\n\t\t\tMappedList = list(map(lambda no : no * 2, FilteredList))\n\t\t\tprint(\"Mapped list: {}\".format(MappedList))\n\t\t\tprint(\"Maximum number from mapped list is: {}\".format(max(MappedList)))\n\t\telse:\n\t\t\tprint(\"There is no filtered data for further operations\")\n\telse:\n\t\tprint(\"Please enter a valid number\")\nif __name__ == \"__main__\":\n\tmain()","sub_path":"Assignment4/Assignment4_5.py","file_name":"Assignment4_5.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"636600036","text":"import torch\nfrom eod.utils.general.registry_factory import RUNNER_REGISTRY\nfrom eod.utils.general.global_flag import FP16_FLAG\n\nfrom .base_runner import BaseRunner\n\n\n__all__ = ['FP16Runner']\n\n\n@RUNNER_REGISTRY.register('fp16')\nclass FP16Runner(BaseRunner):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.scaler = torch.cuda.amp.GradScaler(enabled=True)\n self.fp16 = True\n FP16_FLAG.fp16 = True\n\n def forward(self, batch, return_output=False):\n with torch.cuda.amp.autocast(enabled=True):\n output = self.forward_model(batch)\n self._temporaries['last_output'] = output\n losses = [val for name, val in output.items() if name.find('loss') >= 0]\n loss = sum(losses)\n if return_output:\n return loss, output\n else:\n return loss\n\n def backward(self, loss):\n self.model.zero_grad()\n self.scaler.scale(loss).backward()\n self._hooks('after_backward', self.cur_iter, loss)\n return loss\n\n def update(self):\n self.scaler.step(self.optimizer)\n self.scaler.update()\n self._hooks('after_update', self.cur_iter)\n\n def resume_fp16(self, ckpt):\n self.scaler.load_state_dict(ckpt['scaler'])\n\n def get_fp16_dump_dict(self):\n return {'scaler': self.scaler.state_dict()}\n","sub_path":"eod/runner/fp16_runner.py","file_name":"fp16_runner.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"389144211","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 ('database', '0005_kviz_uganka'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user',\n name='tocke',\n field=models.IntegerField(verbose_name='tocke', default=0),\n ),\n ]\n","sub_path":"database/migrations/0006_user_tocke.py","file_name":"0006_user_tocke.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"572201869","text":"import os\nimport json\nfrom flask import Flask, render_template, request\nfrom flask_bootstrap import Bootstrap\nfrom steamapi import core, user\nimport requests as reqGet\n\napp = Flask(\"whatcanweplay\")\nBootstrap(app)\nSTEAM_KEY = os.environ.get('STEAM_KEY')\ncore.APIConnection(api_key=STEAM_KEY)\n\n\ndef getUserID(nickname):\n session = reqGet.Session()\n session.mount(\"http://\", reqGet.adapters.HTTPAdapter(max_retries=10))\n print(\"Retrieving user and game data for \" + nickname + \"...\")\n id_response_json = json.loads(session.get(\n url='http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=' + STEAM_KEY + '&vanityurl=' + nickname).text)\n # If user is found\n if id_response_json and id_response_json['response']['success'] == 1:\n return str(id_response_json['response']['steamid'])\n else:\n print(\"cry\")\n\n\ndef make_string_of_games(games):\n all_games = \"\"\n for game in games:\n all_games += game.name + \"\\n\"\n return all_games\n\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\ndef make_list_of_shared_games(friends):\n games = []\n for friend in friends:\n games.append(friend.games)\n result = set(games[0])\n for game in games[1:]:\n result.intersection_update(game)\n return sorted(result, key=lambda x: x.name)\n\n\n# Friend.state\n# 0 - Offline\n# 1 - Online\n# 3 - Away\n\n\ndef sort_friends_by_status(steam_user):\n friends = sorted(steam_user.friends, key=lambda x: x.name)\n online_friends = []\n for friend in friends:\n if friend.state != 0:\n online_friends.append(friend)\n friends.remove(friend)\n return online_friends + friends\n\n\n@app.route('/user')\ndef page_with_loaded_user():\n name = request.args.get('search')\n if \" \" in name:\n names = name.split(\" \")\n friends = []\n for name in names:\n try:\n friends.append(user.SteamUser(userid=int(name)))\n except ValueError:\n friends.append(user.SteamUser(userurl=name))\n return render_template('index.html', main_user=friends[0], friends=sort_friends_by_status(friends[0]),\n games=make_list_of_shared_games(friends))\n\n try:\n try:\n steam_user = user.SteamUser(userid=int(name))\n except ValueError: # Not an ID, but a vanity URL.\n steam_user = user.SteamUser(userurl=name)\n name = steam_user.name\n img = steam_user.avatar\n friends = sort_friends_by_status(steam_user)\n return render_template('index.html', main_user=steam_user, friends=friends)\n # return render_template('hello.html', name=name, content=content, img=img, games=make_string_of_games(steam_user.games))\n except Exception as ex:\n # We might not have permission to the user's friends list or games, so just carry on with a blank message.\n return render_template('index.html', user=name)\n # return render_template('hello.html', name=name)\n\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"224599461","text":"from typing import Optional, Union, Sequence\n\nfrom webdnn.graph.operator import Operator\nfrom webdnn.graph.operators.attributes.inplace import Inplace\nfrom webdnn.graph.order import Order\nfrom webdnn.graph.placeholder import Placeholder\nfrom webdnn.graph.variable import Variable\nfrom webdnn.graph.variables.constant_variable import ConstantVariable\nfrom webdnn.util.misc import mul\n\n\nclass Reshape(Operator):\n \"\"\"Reshape(name, in_order, out_order, out_shape)\n\n Reshape array assuming it is C-order.\n Removing / inserting axis with length 1\n\n When in_order: NHWC, out_order: NTC, out_shape: (2, 6, 10) and input variable is (2, 3, 4, 5), the semantic procedure is as follows.\n 1. Interpret input variable as NTHWC (2, 1, 3, 4, 5) with inserting axis with length 1\n 2. Reshape it with assuming C-order and length of axis being removed is 1; NTHWC (2, 6, 1, 1, 10)\n 3. Remove axes; NTC (2, 6, 10)\n\n Swapping axes is prohibited because it is ambiguous.\n If in_order and out_order match the actual input / output variable order, kernel does not have to do anything.\n\n Args:\n name (str): Operator name.\n in_order (:class:`~webdnn.graph.order.Order`): input order\n out_order (:class:`~webdnn.graph.order.Order`): output order\n out_shape (list of int or :class:`~webdnn.graph.placeholder.Placeholder`): output shape\n\n Signature\n .. code::\n\n y, = op(x)\n\n - **x** - Input variable.\n - **y** - Output variable.\n \"\"\"\n\n def __init__(self, name: Optional[str], in_order: Order, out_order: Order, out_shape: Sequence[Union[int, Placeholder]]):\n super().__init__(name)\n\n assert -1 not in out_shape, \"-1 (wildcard) in reshape output shape is currently not supported\"\n\n self.parameters[\"in_order\"] = in_order\n self.parameters[\"out_order\"] = out_order\n self.parameters[\"out_shape\"] = out_shape\n\n self.attributes.add(Inplace(self, \"x\", \"y\"))\n\n def __call__(self, x: Variable):\n in_shape = x.shape\n in_order = self.parameters[\"in_order\"]\n out_shape = self.parameters[\"out_shape\"]\n out_order = self.parameters[\"out_order\"]\n assert x.order == in_order\n assert x.size == mul(out_shape), f\"Reshape operator must not change variable size: \" \\\n f\"(x.shape)={in_shape}, (x.size)={mul(in_shape)}, \" \\\n f\"(y.shape)={out_shape}, (y.size)={mul(out_shape)}\"\n\n y = Variable(out_shape, out_order)\n self.append_input(\"x\", x)\n self.append_output(\"y\", y)\n\n return y,\n\n def fold_constance(self):\n in_order = self.parameters[\"in_order\"]\n out_shape = self.parameters[\"out_shape\"]\n out_order = self.parameters[\"out_order\"]\n\n x = self.inputs[\"x\"]\n y = self.outputs[\"y\"]\n y.replace(ConstantVariable(x.copy().change_order(in_order).data.reshape(out_shape), out_order))\n self.remove_all()\n","sub_path":"src/graph_transpiler/webdnn/graph/operators/reshape.py","file_name":"reshape.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"501336549","text":"contents = [line.rstrip('\\n') for line in open('input')]\n\nseen = set()\ntotal = 0\nindex = 0\n\nwhile True:\n total += int(contents[index])\n if total in seen:\n print(total)\n break\n seen.add(total)\n index += 1\n if index >= len(contents):\n index = 0\n","sub_path":"python/1/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"275901812","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\nimport os, sys, subprocess, math\nfrom time import sleep\nimport scipy.stats as stats\n\n#\n# Tiempo de simulacion (en segundos)\n#\nTS=7200\n\n#\n# Lee cuáles son las paradas existentes\n#\nPARADAS=[]\nf=open(\"paradas.txt\",\"r\")\nfor l in f:\n p=int(l)\n PARADAS.append(p)\nf.close()\n\n#\n# Lee cuáles son las líneas existentes\n#\nLINEAS=[]\nf=open(\"lineas.txt\",\"r\")\nfor l in f:\n li=int(l)\n LINEAS.append(li)\nf.close()\n\n#\n# Lee para cada parada cuál es el lambda de arribo de personas\n#\nLAMBDAS_PARADAS={}\ns=subprocess.Popen([ 'bash','./calcula_lambdas_paradas' ], stdout=subprocess.PIPE)\nfor l in s.stdout:\n s=l.split(',')\n p=int(s[0]) # parada\n l=float(s[1]) # lambda\n LAMBDAS_PARADAS[p]=l\n \n#\n# Lee para cada linea cuál es el lambda de arribo a su primer parada\n#\nLAMBDAS_LINEAS={}\ns=subprocess.Popen([ 'bash','./calcula_lambdas_lineas' ], stdout=subprocess.PIPE)\nfor l in s.stdout:\n s=l.split(',')\n li=int(s[0]) # linea\n la=float(s[1]) # lambda\n LAMBDAS_LINEAS[li]=la\n\n#\n# Lee para cada combinación de parada y linea el lambda de gente que sube\n#\nLAMBDAS_PARADAS_LINEAS={}\ns=subprocess.Popen([ 'bash','./calcula_lambdas_paradas_lineas' ], stdout=subprocess.PIPE)\nfor l in s.stdout:\n s=l.split(',')\n pa=int(s[0]) # parada\n li=int(s[1]) # linea\n la=float(s[2]) # lambda\n LAMBDAS_PARADAS_LINEAS[pa,li]=la\n \n#\n# Lee lambda de tiempo que demora una persona en subir\n#\ns=subprocess.Popen( ['bash','./lambda_tiempo_subir'],stdout=subprocess.PIPE)\nfor l in s.stdout:\n LAMBDA_TIEMPO_SUBIR=float(l)\n\n#\n# Lee cuáles son las primeras paradas de cada linea\n#\nPRIMER_PARADA={}\ns=subprocess.Popen( ['bash','./calcula_primeras_paradas'],stdout=subprocess.PIPE)\nfor l in s.stdout:\n s=l.split(',')\n l=int(s[0]) # linea\n p=int(s[1]) # primer parada\n PRIMER_PARADA[l]=p\n\n#\n# Lee valores para la distribución normal que se usará para\n# calcular la cantidad inicial de personas en cada parada\n#\nMU={}\nS2={}\nMAX={}\ns=subprocess.Popen( ['bash','./calcula_s2'],stdout=subprocess.PIPE)\nfor l in s.stdout:\n s=l.split(',')\n p=int(s[0]) # parada\n mu=float(s[1]) # mu\n s2=float(s[2]) # s^2\n mx=int(s[3]) # cantidad máxima de personas observada\n MU[p]=mu\n S2[p]=s2\n MAX[p]=mx\n\n#\n# Calcula array AP\n#\nAP={}\nfor p in PARADAS:\n remanente=0\n for seg in range (1,TS):\n va=stats.expon.rvs(scale=LAMBDAS_PARADAS[p])\n llegan,r=divmod(va+remanente,1)\n remanente=va+remanente-llegan\n AP[p,seg]=llegan\n\n#\n# Ciclo principal\n#\n\nPP={}\nTANT={}\nTULT={}\nDELTA=[]\nTPANT={}\nTPULT={}\nDELTAP=[]\nPROXIMO={}\n\nfor p in PARADAS:\n PP[p]=int(round(stats.norm.rvs()*math.sqrt(S2[p])+MU[p],0))\n if PP[p] < 0:\n PP[p]=0\n if PP[p] > MAX[p]:\n PP[p]=MAX[p]\n\nfor l in LINEAS:\n va=stats.expon.rvs(scale=LAMBDAS_LINEAS[l])\n PROXIMO[l]=int(va)\n\nfor seg in range (1,TS):\n for p in PARADAS:\n PP[p]+=AP[p,seg]\n \n # Ve si hay que inyectar un nuevo colectivo\n # -----------------------------------------\n for l in LINEAS:\n\n # Partida de un colectivo\n # -----------------------\n if seg==PROXIMO[l]:\n # 1) inyecta colectivo\n # 2) calcula el próximo\n va=stats.expon.rvs(scale=LAMBDAS_LINEAS[l])\n PROXIMO[l]=int(va)+seg\n # 3) cálculos para determinar factor de contracción\n if l not in TANT:\n TANT[l]=seg\n else:\n DELTA.append(seg-TANT[l])\n TANT[l]=seg\n\n # Llegada de colectivos a parada\n # ------------------------------\n if True==True:\n p=1 # OJO, acá hay que ver a qué parada llegó el colectivo\n l=17 # OJO, acá hay que ver a qué linea corresponde el colectivo\n\n if (p,l) not in TULT: # Es la primer llegada de la linea a la parada\n TULT[p,l]=0\n\n # tt significa tiempo transcurrido\n tt=seg-TULT[p,l]\n\n suben=round(stats.expon.rvs(scale=LAMBDAS_PARADAS_LINEAS[p,l]*tt),0)\n tdet=round(stats.expon.rvs(scale=LAMBDA_TIEMPO_SUBIR*tt),0)\n\n # Cálculos para determinar factor de contracción\n if p==PRIMER_PARADA[l]:\n if l not in TPANT:\n TPANT[l]=seg\n else:\n DELTAP.append(seg-TPANT[l])\n TPANT[l]=seg\n\n # Establecer detención\n\n if PP[p] < suben:\n PP[p]=0\n else:\n PP[p]-=suben\n","sub_path":"mediciones/simulacion.py","file_name":"simulacion.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"460564042","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\ndic = {\n \"植物\":\n {\"草本植物\":\n [\"牵牛花\",\"瓜叶草\",\"葫芦\",\"翠菊\",\"冬小麦\"],\n \"木本植物\":\n [\"乔木\",\"灌木\",\"如松\",\"杉\",\"樟\"],\n \"水生植物\":\n [\"菊花\",\"干厨菜\",\"菖蒲\",\"水葱\",\"再力花\",\"梭鱼草\"]},\n \"动物\":\n {\"两栖动物\":\n [\"山龟\",\"山鳌\",\"石蛙\",\"娃娃鱼\",\"蟾蜍\",\"龟\",\"鳄鱼\",\"蜥蜴\",\"蛇\"],\n \"禽类\":\n [\"雏鸡\",\"原鸡\",\"长鸣鸡\",\"昌国鸡\",\"斗鸡\",\"长尾鸡\",\"乌骨鸡\"],\n \"哺乳类动物\":\n [\"虎\",\"狼\",\"鼠\",\"貂\",\"猴\",\"树懒\",\"斑马\",\"狗\"]}}\nli = []\ngo = True\nwhile go:\n for i,v in enumerate(dic,1):\n print(i,v)\n li.append(v)\n u_c = input(\">>>\")\n if u_c == \"b\":\n li.clear()\n break\n elif u_c == \"q\":\n go = False\n break\n else:\n u_c = int(u_c)\n u_c = int(u_c)\n li1 = []\n while go:\n for i,v in enumerate(dic[li[u_c-1]],1):\n print(i,v)\n li1.append(v)\n u_c1 = input(\">>>>\")\n if u_c1 == \"b\":\n li1.clear()\n break\n elif u_c1 == \"q\":\n go = False\n break\n else:\n u_c1 = int(u_c1)\n\n while go:\n for i in dic[li[u_c-1]][li1[u_c1-1]]:\n print(i)\n u_c2 = str(input(\">>>>>\"))\n u_c2 = u_c2.lower()\n if u_c2 == \"b\":\n li1.clear()\n break\n elif u_c2 == \"q\":\n go = False\n break\n","sub_path":"python_scripts/Three_mem.py","file_name":"Three_mem.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"131566735","text":"import logging\n\ndef logger(module, level='info'):\n \"\"\"\n\n :param module: module name\n :param level: logging level , check LEVELS variable for available options\n :return: logger object\n \"\"\"\n formatter = \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n\n LEVELS = {'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL}\n level_name = LEVELS.get(level, logging.NOTSET)\n logging.basicConfig(format=formatter, level=level_name)\n log = logging.getLogger(module)\n return log","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"100022954","text":"from __future__ import print_function\nimport csv\nimport sys\nimport re\nfrom utils import Utils\nfrom filereader import FileReader\n\nclass Join:\n def __init__(self):\n self.utils = Utils()\n self.filereader = FileReader()\n\n def join(self, dictionary, tableNames, const_conditions, join_conditions):\n database = {}\n visited = {}\n for t in tableNames:\n visited[t] = False\n database[t] = []\n self.filereader.readFile(t + \".csv\", database[t])\n # print database\n Jc = self.get_join_conditions(dictionary, join_conditions)\n remove_attribs = []\n i = 1\n for t in tableNames:\n self.utils.spaces_rem(t)\n if i == 1:\n resultant_data = database[t]\n visited[t] = True\n schema = dictionary[t]\n i = 0\n else:\n for key, value in visited.items():\n if visited[key]:\n try:\n join_attribs = Jc[(t, key)]\n except:\n join_attribs = None\n if join_attribs:\n remove_attribs.append(t + '.' + join_attribs[0])\n resultant_data, schema = self.join_tables(resultant_data, database[t], key, t, schema,\n join_attribs[1], join_attribs[0], dictionary)\n else:\n resultant_data, schema = self.join_tables(resultant_data, database[t], key, t, schema, None,\n None,\n dictionary)\n\n if const_conditions:\n if \"=\" in const_conditions:\n if len(const_conditions):\n resultant_data, schema = self.utils.rem_via_constants(resultant_data, const_conditions, schema,\n dictionary,\n tableNames)\n\n for r in remove_attribs:\n try:\n schema.remove(r)\n except:\n print(\"No such attribute present\")\n\n return resultant_data, schema\n\n def get_join_conditions(self, dictionary, join_conditions):\n Jc = {}\n if join_conditions:\n for j in join_conditions:\n j = self.utils.spaces_rem(j)\n c = self.utils.parse_condition(j)\n if c:\n Jc[(c[0], c[1])] = (c[2], c[3])\n Jc[(c[1], c[0])] = (c[3], c[2])\n return Jc\n\n def join_tables(self, resultant_data, table_data, table1, table2, schema, r_att, t_att, dictionary):\n if schema:\n if r_att and t_att:\n h = {}\n new = []\n old = []\n i = schema.index(table1 + \".\" + r_att)\n\n for idx, row in enumerate(resultant_data):\n h[row[i]] = idx\n if t_att:\n i = dictionary[table2].index(table2 + \".\" + t_att)\n if resultant_data:\n for row in table_data:\n if h.has_key(row[i]):\n new.append(resultant_data[h[row[i]]] + row)\n resultant_data = new\n\n else:\n new = []\n if resultant_data:\n for r in resultant_data:\n for t in table_data:\n new.append(r + t)\n resultant_data = new\n schema += dictionary[table2]\n\n return (resultant_data, schema)\n","sub_path":"join.py","file_name":"join.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"9289567","text":"\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: David Bestue\n\"\"\"\n\nimport numpy as np\nimport random\nimport pandas as pd\n\n\n### rgb in psychopy goes from -1 (0) to 1 (255)\n\nno_stim = [0,0,0] # grey\nc1=[-1,-1,1] ### dark blue\nc2=[-1,1,-1] ### green\nc3=[-1,1,1] ####cyan\nc4=[1,-1,-1] #red\nc5=[1,-1,1] #pink\nc6=[1,1,-1] #yellow\nc7=[1,1,1] #white\n\n\npos_colors = [c1,c2,c3,c4,c5,c6,c7]\npos_locs = np.arange(1,9,1)\n\ndelay_short=1\ndelay_inter=4\ndelay_long=7\n\nlow_load = 3\nhigh_load = 7\n\ntrials_each = 8# 6-7min aprox 16 ##12-15 min aprox\n\n\n##file 1: short version\n# outputs_short=[]\n\n# for delay in [delay_short, delay_long]:\n# outputs_ = []\n# for loads in [low_load, high_load]:\n# for t in range(trials_each):\n# number_grey_pos = 8-loads\n# list_grey = [no_stim for i in range(number_grey_pos)]\n# list_colors = random.sample(pos_colors,loads) \n# list_trial = list_grey + list_colors \n# #\n# random.shuffle(list_trial) \n# #\n# pos_locs = np.arange(0,8,1)\n# candidate_targets = pos_locs[np.array([list_trial[i] !=[0,0,0] for i in range(8)]) ] ##locations with color\n# target_ = random.choice(list(candidate_targets))\n# response_cue = list_trial[target_]\n# #\n# target_angle = np.arange(0,360,45)[target_]\n# #\n# output = list_trial + [response_cue] + [target_angle] + [loads] + [delay] + [t]\n# outputs_.append(output)\n# ###\n# trials = pd.DataFrame(outputs_)\n# trials.columns=['Color0', 'Color45', 'Color90', 'Color135', 'Color180', 'Color225', 'Color270', 'Color315', 'Cueresp', 'target_angle', 'load', 'delay', 'trial']\n# if delay==delay_short:\n# trials.to_excel('trials_short_delay.xlsx')\n# else:\n# trials.to_excel('trials_long_delay.xlsx')\n\n\n\n\n##file 2: long version\noutputs_short=[]\n\nfor delay in [delay_short, delay_inter, delay_long]:\n outputs_ = []\n for loads in [low_load, high_load]:\n for t in range(trials_each):\n number_grey_pos = 8-loads\n list_grey = [no_stim for i in range(number_grey_pos)]\n list_colors = random.sample(pos_colors,loads) \n list_trial = list_grey + list_colors \n #\n random.shuffle(list_trial) \n #\n pos_locs = np.arange(0,8,1)\n candidate_targets = pos_locs[np.array([list_trial[i] !=[0,0,0] for i in range(8)]) ] ##locations with color\n target_ = random.choice(list(candidate_targets))\n response_cue = list_trial[target_]\n #\n target_angle = np.arange(0,360,45)[target_]\n #\n indiv_colors = list(np.concatenate(list_trial))\n output = indiv_colors + [response_cue[0]] + [response_cue[1]] + [response_cue[2]] + [target_angle] + [loads] + [delay] + [t]\n outputs_.append(output)\n ###\n trials = pd.DataFrame(outputs_)\n colors_columns = [['Color'+a+'_r', 'Color'+a+'_g', 'Color'+a+'_b'] for a in ['0', '45', '90', '135', '180', '225', '270', '315'] ]\n colors_columns = list(np.concatenate(colors_columns)) \n Column_names = colors_columns + ['Cueresp_r', 'Cueresp_g', 'Cueresp_b', 'target_angle', 'load', 'delay', 'trial']\n trials.columns=Column_names\n if delay==delay_short:\n trials.to_excel('trials_short_delay3.xlsx')\n elif delay==delay_inter:\n trials.to_excel('trials_inter_delay3.xlsx')\n else:\n trials.to_excel('trials_long_delay3.xlsx')\n\n\n\n","sub_path":"task/stims_generator2.py","file_name":"stims_generator2.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"417114282","text":"import random\n\n# 점수 알고리즘을 위한 random 모듈 import\n\n\nclass bowling_board(): # OOP 5대 원칙중 단일 책임 원칙(SRP)에 따라 board 만 분리\n def __init__(self):\n self.history = []\n\n def add_score(self, name, score):\n self.history.append(name + \" : \" + score)\n\n def get_history(self):\n return self.history\n\n\nclass bowling_game(): # OOP 5대 원칙중 단일 책임 원칙(SRP)에 따라 game 코드만 분리\n def __init__(self, num_of_players, names_of_players):\n self.num_of_players = num_of_players\n self.names = names_of_players\n self.board = bowling_board() # 점수판\n\n # bowling 클래스의 num_of_players 초기화 될 때 각각 인자로 받은 값으로 정의\n def __make_score(self, user_input):\n rand = random.randrange(0, 10)\n user_input += rand # 입력 받은 값의 1부터 10까지의 임의의 수를 더함\n if user_input > 10:\n user_input -= 10\n return str(user_input) # 문자열 연산에 필요한 값이기 때문에 str로 형 변환을 해주어야 함\n\n def shoot(self, user_input):\n score = self.__make_score(user_input)\n self.board.add_score(self.names[len(self.board.get_history()) - 1],\n score)\n\n def get_board(self):\n return self.board\n\n\nclass bowling_informations():\n @staticmethod\n def print_rules():\n print(\"\"\"\n 반갑습니다.\\n\n 이 볼링 게임에 대해서 설명 드리도록 하겠습니다.\\n\n 1부터 10 사이의 수를 입력해주세요.\\n\n 저는 여기에 1부터 10까지의 임의의 수를 더하겠습니다.\\n\n 이 값이 10보다 작다면 여러분의 점수이고,\\n\n 그렇지 않다면 그 값에 10을 뺀 값이 여러분의 점수입니다.\n \"\"\")\n\n @staticmethod\n def print_greeting(num_of_players):\n if (num_of_players is 1): # 플레이어\n print(\"안녕하세요. 혼자 플레이 하시는군요!\")\n else:\n print(\"%d분 안녕하세요!\" % num_of_players)\n\n\ndef main():\n bowling_informations.print_rules()\n\n num_of_players = int(input(\"플레이어 수를 입력해주세요: \")) # 정수형 값으로 플레이어수를 입력 받음\n names = []\n\n if num_of_players is 0:\n print(\"게임을 종료합니다.\")\n exit()\n\n bowling_informations.print_greeting(num_of_players)\n\n for i in range(0, num_of_players):\n name = input(\"%d번째 플레이어의 이름을 입력해주세요: \" %\n (i + 1)) # 사용자에게는 1부터 시작하는 셈이 익숙함으로 1부터 시작\n names.append(name)\n\n game = bowling_game(num_of_players, names)\n\n print(\"\\n\")\n\n for i in range(0, num_of_players):\n user_input = -1\n while user_input < 0 or user_input > 10:\n user_input = int(\n input(\"숫자를 입력해주세요: \")) # 숫자를 입력받아야 함으로 정수 int로 형 변환\n game.shoot(user_input)\n\n print(\"\\n\\n-----게임종료-----\\n\\n\")\n\n for history in game.get_board().get_history():\n print(history)\n\n\nmain()\n","sub_path":"OOP/bowling.py","file_name":"bowling.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"567724206","text":"import csv\nimport statistics\n\n#Abrir arquivo base para calcular as medianas\nf = open('C:/Users/marco.junior/Desktop/TabelaDelphi.csv', encoding='UTF-8')\n\n#Criar lists a partir do arquivo aberto.\nSkuMedian = []\nPriceToMedian = []\n\nreader = csv.reader(f, delimiter = ',')\nfor row in reader:\n SkuMedian.append(row[0])\n PriceToMedian.append(row[4])\nf.close()\n\n#Excluir Cabeçalho das listas criadas e remover as duplicatas\ndel SkuMedian[0]\ndel PriceToMedian[0]\n\nPriceToMedian = [float(x) for x in PriceToMedian]\nSkuClean = list(set(SkuMedian))\n\n#Calcular a Mediana da Base\nMedian = []\ni = 0\nk = 0\nwhile k in range(len(SkuClean)):\n c = []\n c.append(SkuClean[k])\n PriceListToMedian = []\n for index, item in enumerate(SkuMedian):\n if item == c[0]:\n j = index\n PriceListToMedian.append(float(PriceToMedian[j]))\n PriceListToMedian = [x for x in PriceListToMedian if x != 0]\n if PriceListToMedian == []:\n Median.append(0)\n else:\n MedianToappend = statistics.median(PriceListToMedian)\n Median.append(MedianToappend)\n k += 1\nMedian = [int(x) for x in Median]\n\n#Abrir CSV Lojista e criar lists com as informações\nseller = open('C:/Users/marco.junior/Desktop/PricePartner53.csv', encoding='UTF-8')\n\nSellersSKU = []\nSellersPrice = []\nreader = csv.reader(seller, delimiter = ',')\nfor row in reader:\n SellersSKU.append(row[0])\n SellersPrice.append(row[1])\nseller.close()\ndel SellersSKU[0]\ndel SellersPrice[0]\nSellersPrice = [float(x) for x in SellersPrice]\n\n#Escrever o Cabeçalho no arquivo gerado no Output\nheader = [\"SKU\", \"Preço enviado\", \"Mediana\", \"Porcentagem\"]\nwith open('DelphiPrecos2.csv', 'w',newline='') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter=',',\n quotechar='|', quoting=csv.QUOTE_MINIMAL)\n spamwriter.writerow(header)\n\n#Comparar CSV Lojista com Mediana Calculada e printar no arquivo gerado caso o preço seja desproporcional à mediana\ni = 0\nwhile i in range(len(SellersSKU)):\n for index, item in enumerate(SkuClean):\n if item == SellersSKU[i]:\n j = index\n if(SellersPrice[i] != 0):\n if (SellersPrice[i] <= Median[j]* 0.6) or (SellersPrice[i] >= Median[j]* 3.0):\n Percentage = int((SellersPrice[i] * 100)/Median[j])\n print(SellersSKU[i], SellersPrice[i], Median[j], Percentage)\n Row = [SellersSKU[i],SellersPrice[i],Median[j], Percentage]\n with open('DelphiPrecos2.csv', 'a', newline='') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter=',',\n quoting=csv.QUOTE_MINIMAL)\n spamwriter.writerow(Row)\n\n i += 1","sub_path":"untitled/venv/LendoCSV/CódigoCompleto.py","file_name":"CódigoCompleto.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"308371482","text":"\"\"\"\nThis spider is a SalesStaff spider created on top of the ATSSpider\nscrapy crawl salesstaff -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.sales-staff.de/kandidaten/#stellenangebote\"\n\nsample url:\nhttp://www.sales-staff.de/kandidaten/#stellenangebote\n\"\"\"\n\nfrom re import compile\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix\n\n\nclass SalesStaff(ATSSpider):\n\n name = \"salesstaff\"\n ref_re = compile(r\"(\\d+)$\")\n\n def parse(self, response):\n sel = Selector(response)\n if not hasattr(self, \"logo_url\"):\n logo_url = sel.xpath('//img[@class=\"logo\"]/@src').extract()\n if logo_url:\n self.logo_url = logo_url\n\n iframe_url = sel.xpath(\n '//iframe[@name=\"Stellenangebote\"]/@src').extract()\n if iframe_url:\n yield Request(iframe_url[0], callback=self.parse_jobs_list)\n\n def parse_jobs_list(self, response):\n sel = Selector(response)\n if not self.expected_job_count_set:\n job_count = sel.xpath('//div[@class=\"left\"]/text()').extract()\n if job_count:\n self.expected_job_count = job_count\n\n jobs = sel.xpath('//table[@class=\"recordList\"]//tr')\n for job in jobs:\n job_url = job.xpath('./td/a/@href').extract()\n if job_url:\n job_url = urljoin(response.url, job_url[0])\n meta = {\n 'title': job.xpath('./td/a/text()').extract(),\n 'cat': job.xpath(\n './td[@class=\"category\"]/text()').extract(),\n 'loc': job.xpath('./td[@class=\"region\"]/text()').extract(),\n }\n yield Request(\n job_url, callback=self.parse_job_callback(), meta=meta\n )\n\n next_url = sel.xpath('//a[@class=\"button next\"]/@href').extract()\n if next_url:\n next_url = urljoin(response.url, next_url[0])\n yield Request(next_url, callback=self.parse_jobs_list)\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n\n loader.add_value('url', response.url)\n loader.add_value('logo_url', self.logo_url)\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('location', response.meta.get('loc'))\n loader.add_value('jobcategory', response.meta.get('cat'))\n loader.add_value(\n 'referencenumber', response.url,\n Prefix('%s-' % self.name), re=self.ref_re\n )\n\n loader.add_xpath(\n 'description',\n '//div[@id=\"jobBody\"]/following-sibling::node()'\n )\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/salesstaff.py","file_name":"salesstaff.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"172794886","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom camparing_epsilon import run_experiment as eps_exp\n\n\nclass Bandit:\n def __init__(self,m,upper_limit):\n self.m = m\n self.mean = upper_limit\n self.N = 1\n\n def pull(self):\n return np.random.randn() + self.m\n\n def update(self,x):\n self.N += 1\n self.mean = (1 - 1.0/self.N)*self.mean + 1.0/self.N*x\n\n\ndef run_experiment(m1,m2,m3,upper_limit,N):\n bandits = [Bandit(m1,upper_limit), Bandit(m2,upper_limit), Bandit(m3,upper_limit)]\n\n data = np.empty(N)\n for i in range(N):\n #optimistic initial\n j = np.argmax([b.mean for b in bandits])\n x = bandits[j].pull()\n bandits[j].update(x)\n\n #for the plot\n data[i] = x\n cumulative_average =np.cumsum(data)/(np.arange(N)+1)\n\n #plot moving average ctr\n\n plt.plot(cumulative_average)\n plt.plot(np.ones(N)*m1)\n plt.plot(np.ones(N)*m2)\n plt.plot(np.ones(N)*m3)\n plt.xscale('log')\n plt.show()\n\n for bandit in bandits:\n print(bandit.mean)\n\n return cumulative_average\n\n\nif __name__ == '__main__':\n c_1 = run_experiment(1.0,2.0,3.0,10,100000)\n c_05 = run_experiment(1.0,2.0,3.0,0.05,100000)\n c_e= eps_exp(1.0,2.0,3.0,0.1,100000)\n\n\n #log scale plot\n plt.title(label=\"log_scale\")\n plt.plot(c_1,label= 'optimistic = 10')\n plt.plot(c_e,label= 'eps = 0.1')\n plt.legend()\n plt.xscale('log')\n plt.show()\n\n # linear plot\n plt.title(label=\"linear plot\")\n plt.plot(c_1,label= 'optimistic = 10')\n plt.plot(c_e, label='eps = 0.1')\n\n plt.legend()\n plt.show()","sub_path":"Machine Learning/optimistic_initial_values.py","file_name":"optimistic_initial_values.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"328561059","text":"class Solution(object):\r\n def numberOfArithmeticSlices(self, A):\r\n \"\"\"\r\n :type A: List[int]\r\n :rtype: int\r\n \"\"\"\r\n count = sum = 0\r\n \r\n for i in range(1,len(A)-1):\r\n if A[i]-A[i-1] == A[i+1]-A[i]:\r\n \r\n count += 1 # every time move forward one means a new array itself, and one new combine with previous one\r\n sum += count\r\n else:\r\n count = 0\r\n \r\n return sum\r\n\r\nif __name__ == '__main__':\r\n\r\n test = Solution()\r\n print(test.numberOfArithmeticSlices([1,3,5,6,7,9,11,13]))\r\n","sub_path":"numberOfArithmeticSlices.py","file_name":"numberOfArithmeticSlices.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"134107191","text":"#!/usr/bin/python\n\nimport os, sys, shutil\nimport numpy as np\nimport pyrap.tables as tb\n\nimport logging\nlogger = logging.getLogger('PiLL')\n\ndef merge_parmdb(parmdb_p, parmdb_a, parmdb_out, clobber=False):\n \"\"\"\n Merges facet selfcal parmdbs into a parmdb for a single band\n\n Parameters\n ----------\n parmdb_p : str\n Filename of CommonScalarPhase and TEC parmdb\n parmdb_a : str\n Filename of Gain parmdb. The nearset match in frequency to that of the\n input band will be used\n parmdb_out : str\n Filename of output file\n clobber : bool, optional\n If True, overwrite existing output file\n\n \"\"\"\n import lofar.parmdb as parmdb\n if type(clobber) is str:\n if clobber.lower() == 'true':\n clobber = True\n else:\n clobber = False\n\n if os.path.exists(parmdb_out):\n if clobber:\n shutil.rmtree(parmdb_out)\n else:\n return\n pdb_out = parmdb.parmdb(parmdb_out, create=True)\n\n # Copy over the CommonScalar phases and TEC\n pdb_p = parmdb.parmdb(parmdb_p)\n for parmname in pdb_p.getNames():\n parms = pdb_p.getValuesGrid(parmname)\n pdb_out.addValues(parms)\n\n # Copy over the Gains\n pdb_a = parmdb.parmdb(parmdb_a)\n for parmname in pdb_a.getNames():\n parms = pdb_a.getValuesGrid(parmname)\n pdb_out.addValues(parms)\n\n # Write values\n pdb_out.flush()\n \n\ndef find_nchan(ms):\n \"\"\"\n Find number of channel in this ms\n \"\"\"\n with tb.table(ms+'/SPECTRAL_WINDOW', ack=False) as t:\n nchan = t.getcol('NUM_CHAN')\n assert (nchan[0] == nchan).all() # all spw have same channels?\n logger.debug('Channel in '+ms+': '+str(nchan[0]))\n return nchan[0]\n\n\ndef find_chanband(ms):\n \"\"\"\n Find bandwidth of a channel\n \"\"\"\n with tb.table(ms+'/SPECTRAL_WINDOW', ack=False) as t:\n chan_w = t.getcol('CHAN_WIDTH')[0]\n assert all(x==chan_w[0] for x in chan_w) # all chans have same width\n logger.debug('Channel width in '+ms+': '+str(chan_w[0]/1e6)+' MHz')\n return chan_w[0]\n\n\ndef find_timeint(ms):\n \"\"\"\n Get time interval in seconds\n \"\"\"\n with tb.table(ms, ack=False) as t:\n Ntimes = len(set(t.getcol('TIME')))\n with tb.table(ms+'/OBSERVATION', ack=False) as t:\n deltat = (t.getcol('TIME_RANGE')[0][1]-t.getcol('TIME_RANGE')[0][0])/Ntimes\n logger.debug('Time interval for '+ms+': '+str(deltat))\n return deltat\n\n\ndef get_phase_centre(ms):\n \"\"\"\n Get the phase centre of the first source (is it a problem?) of an MS\n \"\"\"\n field_no = 0\n ant_no = 0\n with tb.table(ms + '/FIELD', ack=False) as field_table:\n direction = field_table.getcol('PHASE_DIR')\n ra = direction[ ant_no, field_no, 0 ]\n dec = direction[ ant_no, field_no, 1 ]\n return (ra*180/np.pi, dec*180/np.pi)\n\n","sub_path":"autocal/lib_pipeline_ms.py","file_name":"lib_pipeline_ms.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"384567388","text":"from django.shortcuts import render\nfrom rest_framework import generics, status # generic.ListAPIVIEW allowed us to create a class inherits from a generic API view # status for access to http status code when we use Response\nfrom .serializers import RoomSerializer, CreateRoomSerializer\nfrom api.models import Room\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response # get response from our view\n\n# Create your views here.\n\n\nclass RoomView(generics.ListAPIView): # Is a already set up to return to us all of difference room \n queryset = Room.objects.all() \n serializer_class = RoomSerializer\n\n\nclass CreateRoomView(APIView): # APIView allowed us to overwrite default ( get and post )method \n serializer_class = CreateRoomSerializer\n\n def post(self, request, format=None): \n if not self.request.session.exists(self.request.session.session_key): # For at identify host we should use session-key.# Session is a temporary connection between to computer or devices\n self.request.session.create() # if there is no session so makes a session\n\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid(): # if there are those data, that should to be like 'guest_can_pause', 'votes_to_skip'\n guest_can_pause = serializer.data.get('guest_can_pause') # get they data\n votes_to_skip = serializer.data.get('votes_to_skip')\n host = self.request.session.session_key\n queryset = Room.objects.filter(host=host) \n if queryset.exists(): # If there is any room with the same host code\n room = queryset[0] # get det first room\n room.guest_can_pause = guest_can_pause\n room.votes_to_skip = votes_to_skip\n room.save(update_fields=['guest_can_pause', 'votes_to_skip'])\n return Response(RoomSerializer(room).data, status=status.HTTP_200_OK)\n else: # If there is any room so makes a room \n room = Room(host=host, guest_can_pause=guest_can_pause,\n votes_to_skip=votes_to_skip)\n room.save()\n return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED) # serilize the room\n\n return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST)","sub_path":"music_controller/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"182132811","text":"import networkx as nx\nimport xlsxwriter\nimport operator\nimport os\n\n\n\n\ntime_index = 0\ndataset_percentage = 0\n\n\n\n# Start from the first cell below the headers.\nmanifest = 15\n\n# Candidate tested functions\nfunction_lists = [nx.resource_allocation_index,\n nx.jaccard_coefficient,\n nx.adamic_adar_index,\n nx.preferential_attachment]\n\nprecentage_conatainer = [0.1, 0.3, 0.5, 0.7, 0.9]\n\ndef test_predictions(datasetPath, threshold, percentage, prediction_function, worksheet, row, col):\n # Creating a graph\n Ga = nx.Graph()\n Gb = nx.Graph()\n\n\n total_lines = 0\n currentIndex = 0\n bList = []\n\n\n # Loop the Dataset to calculate the total lines, and put all the data into graph A\n with open(datasetPath) as f:\n for line in f:\n total_lines = total_lines + 1\n inner_list = [int(elt.strip()) for elt in line.split()]\n Ga.add_node(inner_list[0])\n Ga.add_node(inner_list[1])\n\n\n\n # Populate the graph with half data\n with open(datasetPath) as f:\n\n for line in f:\n currentIndex += 1\n inner_list = [int(elt.strip()) for elt in line.split()]\n\n if currentIndex <= total_lines * percentage:\n Ga.add_edge(inner_list[0], inner_list[1])\n else:\n if currentIndex >= total_lines:\n break\n bList.append((inner_list[0], inner_list[1]))\n\n\n no_edge_pairs = nx.non_edges(Ga)\n\n preds = prediction_function(Ga, list(no_edge_pairs))\n mylist = (list(preds))\n mylist.sort(key=operator.itemgetter(2), reverse=True)\n\n number_of_top_percent = int(threshold * (len(mylist) / 100))\n\n cList = []\n topPercentList = mylist[0:number_of_top_percent]\n for item in topPercentList:\n cList.append((item[0], item[1]))\n\n dList = list(set(bList + cList))\n repeatedNumber = len(bList) + len(cList) - len(dList)\n\n worksheet.write(row, col, round(repeatedNumber / len(bList),3) )\n worksheet.write(row, col + manifest, round(repeatedNumber / len(topPercentList), 3) )\n\n\n\ndef start_test():\n\n for current_dataset_percentage in precentage_conatainer:\n print('%f ' % (current_dataset_percentage))\n\n result_output_path = \"Results/results\" + str(current_dataset_percentage*10) + \".xlsx\"\n # Create a workbook and add a worksheet.\n workbook = xlsxwriter.Workbook(result_output_path)\n\n # Add a bold format to use to highlight cells.\n bold = workbook.add_format({'bold': True})\n\n for current_function in function_lists:\n print(current_function.__name__)\n worksheet = workbook.add_worksheet(current_function.__name__)\n row = 1\n col = 1\n\n for current_threshold in range(10, 91, 20):\n print(' %d ' %(current_threshold))\n # AUC y-axis\n worksheet.write(row, 0, current_threshold, bold)\n worksheet.write(row+1, 0, \"Average\", bold)\n\n # precision y-axis\n worksheet.write(row, manifest, current_threshold, bold)\n\n col = 1\n datasetfiles = os.listdir(\"NewDatasets/\")\n for current_dataset in datasetfiles:\n print(\" {}\" + (current_dataset))\n # AUC x-axis\n worksheet.write(0, col, current_dataset, bold)\n\n # precision x-axis\n worksheet.write(0, col + manifest, current_dataset, bold)\n\n current_dataset_name = \"NewDatasets/\" + current_dataset\n\n\n test_predictions(current_dataset_name, current_threshold, current_dataset_percentage, current_function, worksheet, row, col)\n\n col += 1\n\n row += 1\n # average\n worksheet.write(row, 1, '=AVERAGE(B2:B6)')\n\n\n workbook.close()\n\ndef main():\n start_test()\n\n print(\"end\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Week10xls.py","file_name":"Week10xls.py","file_ext":"py","file_size_in_byte":4010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"54034017","text":"from django.shortcuts import render, redirect\nfrom .models import Article, Comment\nfrom .forms import ArticleForm, CommentForm\n\n# Create your views here.\ndef index(request):\n articles = Article.objects.all()\n context = {\n 'articles': articles,\n }\n return render(request, 'articles/index.html', context)\n\ndef new(request):\n if request.method == \"POST\":\n form = ArticleForm(request.POST)\n form.save()\n return redirect('articles:index')\n else:\n form = ArticleForm()\n context = {\n 'form': form,\n }\n print(form)\n return render(request, 'articles/new.html', context)\n\ndef detail(request, article_pk):\n article = Article.objects.get(pk=article_pk)\n comments = article.comment_set.all()\n commentform = CommentForm()\n context = {\n 'article': article,\n 'commentform': commentform,\n 'comments': comments,\n }\n return render(request, 'articles/detail.html', context)\n\ndef edit(request, article_pk):\n article = Article.objects.get(pk=article_pk) \n if request.method == \"POST\":\n form = ArticleForm(request.POST, instance=article)\n form.save()\n return redirect('articles:detail', article_pk)\n else:\n form = ArticleForm(instance=article)\n context = {\n 'form': form,\n }\n return render(request, 'articles/new.html', context)\n\ndef delete(request, article_pk):\n article = Article.objects.get(pk=article_pk)\n article.delete()\n return redirect('articles:index')\n\ndef comment_create(request, article_pk):\n if request.method == \"POST\":\n comment_form = CommentForm(request.POST)\n comment = comment_form.save(commit=False)\n comment.article_id = article_pk\n comment.save()\n\n return redirect('articles:detail', article_pk)\n\ndef comment_delete(request, article_pk, comment_pk):\n comment = Comment.objects.get(pk=comment_pk)\n comment.delete()\n return redirect('articles:detail', article_pk)\n \n \n\n \n","sub_path":"03_Django/pair-programmig2/articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"48063272","text":"from django.db import models\nfrom django.urls import reverse\nfrom django.core import validators\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom ticketflix.spectacle.models import Spectacle\nfrom ticketflix.room.models import Room\n\nclass Session(models.Model):\n\n date = models.DateField(\n auto_now=False,\n auto_now_add=False\n )\n\n time = models.TimeField(\n auto_now=False,\n auto_now_add=False\n )\n\n place = models.CharField(\n max_length=50\n )\n\n available_ticket_number = models.IntegerField()\n\n total_ticket_number = models.IntegerField()\n\n spectacle = models.ForeignKey(\n Spectacle,\n related_name='sessions',\n related_query_name='session',\n on_delete=models.CASCADE,\n null=True\n )\n\n price = models.FloatField(\n verbose_name=_(\"Preço\"),\n help_text=_(\"Preço\"),\n validators=[validators.MinValueValidator(0)],\n blank=False,\n default=0\n )\n\n room = models.ForeignKey(\n Room,\n related_name='sessions',\n related_query_name='sessions',\n on_delete=models.CASCADE,\n blank=False,\n default=None\n )\n\n def __str__(self):\n return ('Session ' + str(self.id))\n\n class Meta:\n verbose_name = (\"Sessão\")\n verbose_name_plural = (\"Sessões\")\n","sub_path":"ticketflix/session/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"426122712","text":"from collections import OrderedDict\nfrom urllib.parse import urljoin\n\nfrom django.template.loader import render_to_string\nfrom rest_framework import exceptions\nfrom rest_framework.compat import coreapi\nfrom rest_framework.schemas import SchemaGenerator\n\n\ndef make_plain_schema(nested_schema) -> OrderedDict:\n \"\"\"Makes plain ordered schema from nested schema recursively.\"\"\"\n plain_schema = OrderedDict()\n\n def _unpack(schema, path=''):\n if hasattr(schema, 'data') and schema.data:\n for name, node in schema.data.items():\n new_path = '{} {}'.format(path, name) if path else name\n if hasattr(node, 'links') and node.links:\n plain_schema[new_path] = node\n else:\n _unpack(node, path=new_path)\n\n _unpack(nested_schema)\n return plain_schema\n\n\nclass CustomSchemaGenerator(SchemaGenerator):\n def get_link(self, path, method, view):\n methods = [\n 'get_path_fields',\n 'get_serializer_fields',\n 'get_pagination_fields',\n 'get_filter_fields'\n ]\n\n fields = []\n for method_name in methods:\n try:\n fields += getattr(self, method_name)(path, method, view)\n except (AttributeError, AssertionError):\n # it suppresses any exceptions caused by some custom serializers, methods etc.\n pass\n\n if fields and any([field.location in ('form', 'body') for field in fields]):\n encoding = self.get_encoding(path, method, view)\n else:\n encoding = None\n\n description = self.get_description(path, method, view)\n\n if self.url and path.startswith('/'):\n path = path[1:]\n\n return coreapi.Link(\n url=urljoin(self.url, path),\n action=method.lower(),\n encoding=encoding,\n fields=fields,\n description=description\n )\n\n\nclass ApiDocsHandler(object):\n template = 'api_docs/template.md'\n\n def __init__(self, project_name: [str, None]=None, template: [str, None]=None):\n self.project_name = project_name or ''\n self.template = template or self.template\n\n def render(self) -> str:\n generator = CustomSchemaGenerator(\n title=self.project_name,\n )\n schema = generator.get_schema()\n\n if not schema:\n raise exceptions.ValidationError(\n 'The schema generator did not return a schema Document'\n )\n\n return render_to_string(self.template, {\n 'project_name': self.project_name,\n 'api': make_plain_schema(schema)\n })\n","sub_path":"drf_api_docs/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"576883745","text":"from discord.ext import commands, tasks\r\nfrom contextlib import redirect_stdout\r\r\nimport os\r\nimport subprocess\r\nimport traceback\r\nimport discord\r\nimport traceback\r\nimport io\r\nimport textwrap\r\n\r\n\r\n\r\nclass Admin(commands.Cog, command_attrs=dict(hidden=True)):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n self._last_result = None\r\n\r\n\r\n def cleanup_code(self, content):\r\n \"\"\"Automatically removes code blocks from the code.\"\"\"\r\n # remove ```py\\n```\r\n if content.startswith('```') and content.endswith('```'):\r\n return '\\n'.join(content.split('\\n')[1:-1])\r\n\r\n # remove `foo`\r\n return content.strip('` \\n')\r\n\r\n async def cog_check(self, ctx):\r\n return await self.bot.is_owner(ctx.author)\r\n\r\n\r\n @commands.command()\r\n async def discord_py(self, ctx):\r\n await ctx.send(discord.__version__)\r\n\r\n @commands.command()\r\n async def load(self, ctx, module:str, opt:str = None):\r\n module = f'cogs.{module}'\r\n if opt is None:\r\n self.bot.load_extension(module)\r\n\r\n elif opt == 'un':\r\n self.bot.unload_extension(module)\r\n\r\n elif opt == 're':\r\n self.bot.reload_extension(module)\r\n\r\n else:\r\n return await ctx.message.add_reaction('\\N{BLACK QUESTION MARK ORNAMENT}')\r\n \r\n await ctx.message.add_reaction('\\N{WHITE HEAVY CHECK MARK}')\r\n\r\n \r\n @commands.command()\r\n async def restart(self, ctx):\r\n os.system('cals')\r\n subprocess.run(\"launc.py\", shell=True)\n \n @commands.command()\n async def shutdown(self, ctx):\n await bot.logout()\n \r\n\r\n \r\n \r\n\r\n async def say_permissions(self, ctx, member):\r\n permissions = member.guild_permissions\r\n e = discord.Embed(colour=member.colour)\r\n avatar = member.avatar_url_as(static_format='png')\r\n e.set_author(name=str(member), url=avatar)\r\n allowed, denied = [], []\r\n for name, value in permissions:\r\n name = name.replace('_', ' ').replace('guild', 'server').title()\r\n if value:\r\n allowed.append(name)\r\n else:\r\n denied.append(name)\r\n\r\n e.add_field(name='Allowed', value='\\n'.join(allowed))\r\n e.add_field(name='Denied', value='\\n'.join(denied))\r\n await ctx.send(embed=e)\r\n\r\n @commands.command()\r\n async def cp(self, ctx):\r\n \"\"\"Shows a member's permissions in a specific channel.\r\n If no channel is given then it uses the current one.\r\n You cannot use this in private messages. If no member is given then\r\n the info returned will be yours.\r\n \"\"\"\r\n guild = self.bot.get_guild(619926767821652000)\r\n channel = self.bot.get_channel(650399901284565023)\r\n member = ctx.guild.me\r\n\r\n await self.say_permissions(ctx, member)\r\n\r\n @cp.error\r\n async def load_error(self, ctx, error):\r\n await ctx.send(f'```py\\n{traceback.format_exc()}\\n```')\r\n\r\n @commands.command(aliases = ['role_list'])\r\n async def _list(self, ctx):\r\n guild = self.bot.get_guild(619926767821652000)\r\n desc = '\\n'.join(f'{role.name} - {role.id}' for role in reversed(guild.roles))\r\n embed = discord.Embed(title = '役職一覧', colour = ctx.author.colour, description = desc)\r\n await ctx.send(embed = embed)\r\n\r\n \r\n @commands.command(name='eval')\r\n async def _eval(self, ctx, *, body: str = None):\r\n \"\"\"Evaluates a code\"\"\"\r\n if body is None:\r\n return await ctx.send('w')\r\n\r\n env = {\r\n 'bot': self.bot,\r\n 'ctx': ctx,\r\n 'channel': ctx.channel,\r\n 'author': ctx.author,\r\n 'guild': ctx.guild,\r\n 'message': ctx.message,\r\n '_': self._last_result\r\n }\r\n\r\n env.update(globals())\r\n \r\n body = self.cleanup_code(body)\r\n stdout = io.StringIO()\r\n try:\r\n to_compile = f'async def func():\\n{textwrap.indent(body, \" \")}'\r\n exec(to_compile, env)\r\n except Exception as e:\r\n return await ctx.send(f'```py\\n{e.__class__.__name__}: {e}\\n```')\r\n func = env['func']\r\n \r\n try:\r\n with redirect_stdout(stdout):\r\n ret = await func()\r\n except Exception as e:\r\n value = stdout.getvalue()\r\n await ctx.send(f'```py\\n{value}{traceback.format_exc()}\\n```')\r\n else:\r\n value = stdout.getvalue()\r\n if ret is None:\r\n if value:\r\n await ctx.send(f'```py\\n{value}\\n```')\r\n else:\r\n self._last_result = ret\r\n await ctx.send(f'```py\\n{value}{ret}\\n```')\r\n\r\n @commands.command()\r\n async def tes_(self, ctx, member):\r\n await ctx.send(type(member))\r\ndef setup(bot):\r\n bot.add_cog(Admin(bot))","sub_path":"cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"358463805","text":"import csv\nfrom re import sub\nfrom decimal import Decimal\nimport glob, os\n\nGREEN = '\\033[32m'\nRED = '\\033[31m'\nBLUE = '\\033[36m'\nENDC = '\\033[0m'\n\ndef moneyToFloat( money_string ):\n\t\n\tif money_string[0] != '-':\n\t\tmoney_float = Decimal( sub(r'[^\\d.]', '', money_string) ) \n\telse:\n\t\tmoney_float = Decimal( sub(r'[^\\d.]', '', money_string) )\n\t\tmoney_float = 0 - money_float\n\n\treturn money_float\n\ndef moneyToString( money_float ):\n\t\n\tif money_float >= 0:\n\t\treturn \"$\" + str(money_float)\n\telif money_float < 0:\n\t\treturn \"-$\" + str(money_float * -1)\n\ndef compare( date, reg_or_adtnl ):\n\n\tfilename1 = 'Payment' + '/' + date + '.csv'\n\twith open(filename1, 'r') as csvfile:\n\n\t\tpayment_activity = csv.DictReader(csvfile)\n\t\tresult = {}\n\n\t\tfor row_a in payment_activity:\n\t\n\t\t\tamount_paid \t\t= moneyToFloat( row_a['Amount'] )\n\t\t\tamount_discrepency \t= moneyToFloat( row_a['Amount'] )\n\n\t\t\tfilename2 = reg_or_adtnl + '/' + date + '.csv'\n\t\t\twith open(filename2, 'r') as csvfile2:\n\t\t\t\tactivity_2 = csv.DictReader(csvfile2)\n\n\t\t\t\tfor row_b in activity_2:\n\t\t\t\t\tif row_a['Order Number'] == row_b['Order Number']:\n\t\t\t\t\t\tamount_discrepency = amount_discrepency - moneyToFloat( row_b['Purchase amount'] )\n\n\t\t\tresult[row_a['Order Number']] = amount_discrepency\n\n\t\treturn result\n\ndef dict_reconcile( payment_dict, date, style ):\n\n\tresult = {}\n\n\tfor key in payment_dict:\n\n\t\tamount_paid \t\t= payment_dict[key]\n\t\tamount_discrepency \t= payment_dict[key]\t\n\n\t\tfilename1 = style + '/' + date + '.csv'\n\t\twith open(filename1, 'r') as csvfile:\n\n\t\t\tadditional_activity = csv.DictReader(csvfile)\n\t\t\t\n\t\t\tfor row_a in additional_activity:\n\n\t\t\t\tif row_a['Order Number'] == key:\n\t\t\t\t\tif style != 'Payment':\n\t\t\t\t\t\tamount_discrepency = amount_discrepency - moneyToFloat( row_a['Purchase amount'] )\n\t\t\t\t\telif style == 'Payment':\n\t\t\t\t\t\tamount_discrepency = amount_discrepency - moneyToFloat( row_a['Amount'] )\n\n\t\tresult[key] = amount_discrepency\n\n\treturn result\n\ndef getDates( directory ):\n\t\n\tdates = []\n\tos.chdir( directory )\n\tfor file in glob.glob( \"*.csv\" ):\n\t\tdates.append( file.split('.')[0] )\n\n\tos.chdir( '../' )\n\n\treturn dates\n\ndef class_breakdown( date ):\n\n\tnumbers = {}\n\tmoney \t= {}\n\n\tfilename1 = 'Registration' + '/' + date + '.csv'\n\tfilename2 = 'Additional' + '/' + date + '.csv'\n\twith open(filename1, 'r') as csvfile:\n\t\treg_activity = csv.DictReader(csvfile)\n\t\tfor row_a in reg_activity:\n\t\t\tsession_name = row_a['Session']\n\t\t\tprint()\n\t\t\tprint( \"Session : \" + session_name )\n\t\t\tsession_name = session_name[:session_name.find(\"(\")]\n\t\t\tprint( \"Session : \" + session_name )\n\t\t\t\n\t\t\tnumbers.setdefault(session_name, 0)\n\t\t\tmoney.setdefault(session_name, 0)\n\t\t\t\n\t\t\tprint( \"for \" + str(row_a['Participant']) + \" on \" + str(date) );\n\t\t\tnumbers[session_name] = numbers[session_name] + 1\n\t\t\tmoney[session_name] = money[session_name] + moneyToFloat(row_a['Purchase amount'])\n\t\t\tprint( \"adding \" + str(moneyToFloat(row_a['Purchase amount'])) + \" to \" + str(money[session_name]) )\n\n\twith open(filename2, 'r') as csvfile:\n\t\tadditional_activity = csv.DictReader(csvfile)\n\t\tfor row_b in additional_activity:\n\t\t\tearly_drop_off = 'Early Drop Off'\n\t\t\tlate_pick_up = 'Late Pick Up'\n\n\t\t\tsession_name = row_b['Session']\n\t\t\tsession_name = session_name[:session_name.find(\"(\")]\n\n\t\t\tmoney.setdefault( early_drop_off, 0)\n\t\t\tmoney.setdefault( late_pick_up, 0)\n\t\t\tif \"Early\" in row_b['Item Name']:\n\t\t\t\tmoney[early_drop_off] = money[early_drop_off] + moneyToFloat(row_b['Purchase amount'])\n\t\t\tif \"Late\" in row_b['Item Name']:\n\t\t\t\tmoney[late_pick_up] = money[late_pick_up] + moneyToFloat(row_b['Purchase amount'])\n\t\t\tmoney[session_name] = money[session_name] + moneyToFloat(row_b['Purchase amount'])\n\n\n\treturn_tuple = (numbers, money)\n\treturn return_tuple\n\n\n","sub_path":"ActRecon.py","file_name":"ActRecon.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"134898519","text":"# Visualize the topics\nimport pyLDAvis\nimport pyLDAvis.gensim\nimport gensim\nimport pickle\n\nwith open('./pickle/bow_corpus.pkl', 'rb') as f:\n bow_corpus = pickle.load(f)\n\nwith open('./pickle/corpus_tfidf.pkl', 'rb') as f:\n corpus_tfidf = pickle.load(f)\n\nwith open('./pickle/dictionary.pkl', 'rb') as f:\n dictionary = pickle.load(f)\n\nlda_model = gensim.models.LdaModel.load('./pickle/lda_model')\nvis_10topics = pyLDAvis.gensim.prepare(lda_model, bow_corpus, dictionary)\npyLDAvis.save_html(vis_10topics, './DataViz/Viz10Topics.html')\n\nlda_model_tfidf = gensim.models.LdaModel.load('./pickle/lda_model_tfidf')\nvis_10topics_tfidf = pyLDAvis.gensim.prepare(lda_model_tfidf, corpus_tfidf, dictionary)\npyLDAvis.save_html(vis_10topics_tfidf, './DataViz/Viz10TopicsTFIDF.html')\n\nlda_model_mallet_tfidf = gensim.models.wrappers.LdaMallet.load('./pickle/lda_model_mallet_tfidf')\nlda_mallet2gensim = gensim.models.wrappers.ldamallet.malletmodel2ldamodel(lda_model_mallet_tfidf, iterations=1000)\nvis_mallet_tfidf = pyLDAvis.gensim.prepare(lda_mallet2gensim, corpus_tfidf, dictionary)\npyLDAvis.save_html(vis_mallet_tfidf, './DataViz/Viz10TopicsMalletTFIDF.html')","sub_path":"15-Visualize10TopicsModels.py","file_name":"15-Visualize10TopicsModels.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"414543389","text":"class tool(object):#tool成为类对象\n num=0#类属性\n def __init__(self,name):#\n self.name=name#实例属性\n tool.num+=1#调用类属性的方法,类名.类属性。即可\n #类属性每个实例的对象都可以在类中的方法中调用\n #类的属性,但是方法与方法之间的之间的属性不可以直接调用\n #类属性是可以被更改的,再次创建对象的时候类属性会被改变\n print(tool.num)\ntool1=tool('铁铲')#tool1为实例对象\ntool2=tool('铁铲1')\ntool3=tool('铁铲2')\n\n","sub_path":"01-python基础/62-类属性和实例属性,类对象和实例对象.py","file_name":"62-类属性和实例属性,类对象和实例对象.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"589785819","text":"import csv\nfrom django.core.management.base import BaseCommand\nfrom project_app.models import Station, Route\n\n\nclass Command(BaseCommand):\n help = 'importing stations from file to DB'\n\n def add_arguments(self, parser):\n pass\n\n # def handle(self, *args, **options):\n # with open('moscow_bus_stations.csv', 'rt', encoding='cp1251') as csv_file:\n # table_reader = csv.reader(csv_file, delimiter=';')\n # next(table_reader)\n # for line in table_reader:\n # # for obj in list(Station.objects.all()):\n # # print(obj.routes.all())\n # # break\n # # print(line)\n # routes_obj = []\n # routes_list = line[7].split('; ')\n # for route in routes_list:\n # if Route.objects.filter(name=route):\n # route_obj = Route.objects.get(name=route)\n # # print(route_obj)\n # print(f'маршрут {route} уже есть')\n # routes_obj.append(route_obj)\n # else:\n # Route.objects.create(name=route)\n # route_obj = Route.objects.get(name=route)\n # print(f'создание маршрута {route}')\n # routes_obj.append(route_obj)\n # print(routes_obj)\n # station = Station.objects.create(latitude=line[3], longitude=line[2], name=line[1])\n # station.save()\n # print(station.routes.set(routes_obj))\n # station.save()\n # print(station.routes.all())\n # print(route_obj.stations.last())\n # # if len(Station.objects.all()) == 10:\n # # break\n #\n # routes_obj.clear()\n\n def handle(self, *args, **options):\n with open('moscow_bus_stations.csv', newline='', encoding='cp1251') as csv_file:\n reader = csv.DictReader(csv_file, delimiter=';')\n for row in reader:\n station = Station()\n station.id = row['ID']\n station.name = row['Name']\n station.latitude = row['Latitude_WGS84']\n station.longitude = row['Longitude_WGS84']\n station.save()\n for route in row['RouteNumbers'].split('; '):\n obj, routes = Route.objects.get_or_create(name=route)\n station.routes.add(obj)\n print('Строка обработана - {}'.format(row))\n print('Загрузка завершена')\n\n\n\n # print(Station.routes.first())\n\n\n","sub_path":"project_app/management/commands/import_stations.py","file_name":"import_stations.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"29878788","text":"#!/usr/bin/env python\n\"\"\"\n This is a script for finding all json parameter files located in a directiory tree. This script is most powerful\n when used in the cluster experiments. It allows me to make changes to branches of the experiment directory structure.\n \n The script will then attempt to open these json files, make an edit before saving the changes.\n \n BE AWARE: USE WITH CAUTION\n\"\"\"\n\nimport os\nimport sys\n\nfrom Directory_tree_searching import load_json_data, save_json_data, find_file_paths_in_sub_directories\n\n\ndef print_help():\n print(\"\\nThis script can sensitive so handle with care.\\n\\n\"\n \"The parameter inputs for this script are:\\n\"\n \" - sys.arg[1] = Base directory path (preferably from root) that we will be finding parameter files from.\\n\"\n \" - sys.arg[2] = The filename of the parameter files.\\n\"\n \" - sys.arg[3] = The file path filters to be applied, separated by (,). \\n\"\n \" - sys.arg[4] = the Key of the variable you wish to alter.\\n\"\n \" - sys.arg[5] = The value (i.e. int, str, or bool) that you wish to replace.\\n\"\n \" - sys.arg[6] = *OPTIONAL* Override all user inputs in the script (enter True/False)\\n\\n\"\n \"To print the locations of all parameter files to be altered - do NOT provide a key or value\\n\")\n\n\ndef make_backup_json(file_path, parameter_file_data):\n # make backup\n if file_path.endswith('.json'):\n backup_file_path = file_path[:-5]\n backup_file_path = backup_file_path + \"_backup.json\"\n save_json_data(parameter_file_data, backup_file_path)\n else:\n raise Exception(\"Cannot figure out backup because parameter file does not end with .json\")\n\n\ndef convert_string_to_logical_type_var(arg):\n # Check for int\n\n if arg == \"del\":\n return \"del\"\n\n for var_type in [int, float]:\n try:\n test_type = var_type(arg)\n if str(test_type) == arg:\n print(\"\\nValue '{0}' has been found to cleanly convert to an {1}.\".format(arg, var_type))\n return test_type\n except:\n pass\n\n if arg == \"True\" or arg == \"true\":\n print(\"\\nValue '{0}' has been found to cleanly convert to an {1}.\".format(arg, type(True)))\n return True\n elif arg == \"False\" or arg == \"false\":\n print(\"\\nValue '{0}' has been found to cleanly convert to an {1}.\".format(arg, type(True)))\n return False\n elif arg == \"none\" or arg == \"None\":\n return None\n\n print(\"Cannot convert the string '{0}' to int, float, or bool. Will treat as a string\".format(arg))\n return arg\n\n\ndef check_recognised_key(parameter_file_data, key):\n if key in parameter_file_data.keys():\n return True\n else:\n return False\n\n\ndef user_check_add_key(file_path, key, user_approve_add_key_all, overide_user_inputs, value):\n approved = False\n if user_approve_add_key_all or overide_user_inputs:\n approved = True\n else:\n print(\"{0} was not found in {1}.\".format(key, file_path))\n user_approve_add_key = input(\n \"Would you like me to add '{0}' with value {1} to this data? y/n: \".format(key, value))\n if user_approve_add_key == \"y\":\n approved = True\n if user_approve_add_key_all != \"n\":\n user_approve_add_key_all = input(\"Would you like me to add this key to all files found? y/n: \")\n if user_approve_add_key_all == \"y\":\n user_approve_add_key_all = True\n else:\n user_approve_add_key_all = False\n\n return approved, user_approve_add_key_all\n\n\ndef update_parameter_files(parameter_file_paths, key, value, overide_user_inputs):\n print(\"\\nATTEMPTING TO UPDATE PARAMETERS!\\n\")\n\n user_approve_add_key_all = None\n\n for file_path in parameter_file_paths:\n parameter_file_data = load_json_data(file_path)\n\n # Check approve criteria\n update_approved = False\n if overide_user_inputs:\n update_approved = True\n elif user_approve_add_key_all:\n update_approved = True\n elif check_recognised_key(parameter_file_data, key):\n update_approved = True\n else:\n update_approved, user_approve_add_key_all = user_check_add_key(file_path, key, user_approve_add_key_all,\n overide_user_inputs, value)\n\n if update_approved or overide_user_inputs:\n print(\"Modifying {0}\".format(file_path))\n make_backup_json(file_path, parameter_file_data)\n parameter_file_data[key] = value\n save_json_data(parameter_file_data, file_path)\n\n\ndef delete_key_from_files(parameter_file_paths, key, value, overide_user_inputs):\n print(\"\\nATTEMPTING TO UPDATE PARAMETERS!\\n\")\n\n user_approve_add_key_all = None\n\n for file_path in parameter_file_paths:\n parameter_file_data = load_json_data(file_path)\n\n # Check approve criteria\n update_approved = False\n if overide_user_inputs:\n update_approved = True\n elif user_approve_add_key_all:\n update_approved = True\n elif check_recognised_key(parameter_file_data, key):\n update_approved = True\n else:\n print(\"{0} not found in {1}\".format(key, file_path))\n continue\n\n if update_approved or overide_user_inputs:\n print(\"Deleting {0} from {1}\".format(key, file_path))\n make_backup_json(file_path, parameter_file_data)\n parameter_file_data.pop(key)\n save_json_data(parameter_file_data, file_path)\n\n\ndef unpack_sys_arguments(args):\n base_dir_path = None\n filename = None\n key = None\n value = None\n override_user_inputs = False\n filters = None\n\n if len(args) >= 3:\n base_dir_path = sys.argv[1]\n if base_dir_path == \".\":\n base_dir_path = os.getcwd()\n filename = sys.argv[2]\n\n if len(sys.argv) >= 4:\n filters = sys.argv[3].split(\",\")\n\n if len(args) >= 5:\n key = args[4]\n\n if len(args) >= 6:\n value = args[5]\n\n if len(sys.argv) >= 7:\n if sys.argv[6] == \"1\" or sys.argv[6] == \"True\":\n override_user_inputs = True\n print(\"\\n OVERRIDE USER INPUTS = {0}\".format(override_user_inputs))\n\n return base_dir_path, filename, key, value, filters, override_user_inputs\n\n\ndef display_file_path_list(parameter_file_paths, base_dir_path, key):\n string = \"\\nI found [{0}] files with that name in [ {1} ] \\n\\n\".format(len(parameter_file_paths), base_dir_path)\n print(\"=\" * len(string))\n print(string)\n print(\"=\" * len(string))\n if key is None:\n for file_path in parameter_file_paths:\n print(file_path[len(base_dir_path):])\n else:\n # Open each file\n for file_path in parameter_file_paths:\n parameter_file_data = load_json_data(file_path)\n if key in parameter_file_data.keys():\n print(file_path[len(base_dir_path):], \"*** with VALUE:\", parameter_file_data[key],\n type(parameter_file_data[key]), \"***\")\n else:\n print(file_path[len(base_dir_path):], \"*** Key NOT present. ***\")\n print(string)\n print(\"=\" * len(string))\n print(\"\\n\")\n\n\ndef user_check(key, value, overide_user_inputs):\n if value != \"del\":\n print(\"\\n=================================================\"\n \"\\nBased upon the script args, you would like the key:\\n-- {0} \\nto have value: \\n-- {1} {2}\"\n \"\\n\\nVERY CAREFULLY CHECK: ARE THESE DETAILS CORRECT?\"\n \"\\n=================================================\".format(key, value, type(value)))\n elif value == \"del\":\n print(\"\\n===========================================================\"\n \"\\nBased upon the script args, you would like to *DELETE* key\\n-- {0}\"\n \"\\nVERY CAREFULLY CHECK: ARE THESE DETAILS CORRECT?\"\n \"\\n===========================================================\".format(key, value, type(value)))\n\n if not overide_user_inputs:\n y = \"y\"\n user_checked = input(\"Input 'y' to continue:\")\n if user_checked == \"n\":\n raise Exception(\"ABORTING because user input {0}\".format(user_checked))\n elif user_checked != \"y\":\n raise Exception(\"Unrecognised input '{0}'. Exiting\".format(user_checked))\n elif user_checked == \"y\":\n return True\n else:\n raise Exception(\"UNRECOGNISED ERROR IN USER CHECK!\")\n else:\n print(\"OVERRIDE USER INPUTS APPLIED!\")\n return True\n\n\ndef filtered_file_paths(parameter_file_paths, filters):\n if filters is None:\n return parameter_file_paths\n filtered_file_paths = []\n for path in parameter_file_paths:\n my_bool = True\n for f in filters:\n if f not in path:\n my_bool = False\n\n if my_bool:\n filtered_file_paths.append(path)\n\n if len(filtered_file_paths) == 0:\n print(\"ERROR - Filtering paths lead to no acceptable paths.\")\n exit()\n\n return filtered_file_paths\n\n\ndef main():\n print(\"\\n\\nWelcome to the change parameter file detail script.\\n\")\n\n if len(sys.argv) == 1:\n print_help()\n exit()\n print(\"\\nYour system arguments are:\")\n for arg in sys.argv[1:]:\n print(arg)\n\n base_dir_path, filename, key, value, filters, override_user_inputs = unpack_sys_arguments(sys.argv)\n\n parameter_file_paths = None\n if base_dir_path is not None and filename is not None:\n parameter_file_paths = find_file_paths_in_sub_directories(base_dir_path, filename)\n parameter_file_paths = filtered_file_paths(parameter_file_paths, filters)\n display_file_path_list(parameter_file_paths, base_dir_path, key)\n else:\n exit()\n\n if key is not None and value is not None:\n value = convert_string_to_logical_type_var(value)\n if user_check(key, value, override_user_inputs):\n if value == \"del\":\n delete_key_from_files(parameter_file_paths, key, value, override_user_inputs)\n else:\n update_parameter_files(parameter_file_paths, key, value, override_user_inputs)\n print(\"\\nScript complete! All files have been updated.\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bin/change_directory_tree_par_detail.py","file_name":"change_directory_tree_par_detail.py","file_ext":"py","file_size_in_byte":10400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"402439623","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\nbl_info = {\n \"name\": \"Useless Tools\",\n \"description\": \"Just a little collection of scripts and tools I use daily\",\n \"author\": \"Greg Zaal\",\n \"version\": (1, 2),\n \"blender\": (2, 75, 0),\n \"location\": \"Mostly 3D view toolshelf\",\n \"warning\": \"\",\n \"wiki_url\": \"\",\n \"tracker_url\": \"\",\n \"category\": \"Tools\"}\n\n\nimport bpy\nimport os\n\nglobal obtypes\nobtypes = ['MESH', 'CURVE', 'SURFACE', 'META', 'FONT', 'ARMATURE', 'LATTICE', 'EMPTY', 'CAMERA', 'LAMP']\n\n\nclass UTSetSelectable(bpy.types.Operator):\n\n 'Sets selectability for the selected objects'\n bl_idname = 'ut.set_selectable'\n bl_label = 'set selectable'\n selectable = bpy.props.BoolProperty()\n\n def execute(self, context,):\n for obj in bpy.context.selected_objects:\n if self.selectable == True:\n obj.hide_select = False\n else:\n obj.hide_select = True\n return {'FINISHED'}\n\n\nclass UTSetRenderable(bpy.types.Operator):\n\n 'Sets renderability for the selected objects'\n bl_idname = 'ut.set_renderable'\n bl_label = 'set renderable'\n renderable = bpy.props.BoolProperty()\n\n def execute(self, context,):\n for obj in bpy.context.selected_objects:\n if self.renderable == True:\n obj.hide_render = False\n else:\n obj.hide_render = True\n return {'FINISHED'}\n\n\nclass UTAllSelectable(bpy.types.Operator):\n\n 'Allows all objects to be selected'\n bl_idname = 'ut.all_selectable'\n bl_label = 'all selectable'\n\n def execute(self, context,):\n for obj in bpy.data.objects:\n obj.hide_select = False\n return {'FINISHED'}\n\n\nclass UTAllRenderable(bpy.types.Operator):\n\n 'Allows all objects to be rendered'\n bl_idname = 'ut.all_renderable'\n bl_label = 'all renderable'\n\n def execute(self, context,):\n for obj in bpy.data.objects:\n obj.hide_render = False\n return {'FINISHED'}\n\n\nclass UTSelNGon(bpy.types.Operator):\n\n 'Selects faces with more than 4 vertices'\n bl_idname = 'ut.select_ngons'\n bl_label = 'Select NGons'\n\n @classmethod\n def poll(cls, context):\n if not context.active_object or context.mode != 'EDIT_MESH':\n return False\n else:\n return True\n\n def execute(self, context):\n context.tool_settings.mesh_select_mode = (False, False, True)\n bpy.ops.mesh.select_face_by_sides(number=4, type='GREATER', extend=True)\n return {'FINISHED'}\n\n\nclass UTWireHideSel(bpy.types.Operator):\n\n 'Hides the wire overlay of all objects in the selection'\n bl_idname = 'ut.wirehidesel'\n bl_label = 'Hide Wire'\n show = bpy.props.BoolProperty(default=False)\n\n def execute(self, context):\n for e in bpy.context.selected_objects:\n try:\n e.show_wire = self.show\n except KeyError:\n print(\"Error on \" + e.name)\n return {'FINISHED'}\n\n\nclass UTWireHideAll(bpy.types.Operator):\n\n 'Hides the wire overlay of all objects'\n bl_idname = 'ut.wirehideall'\n bl_label = 'Hide Wire (All)'\n show = bpy.props.BoolProperty(default=False)\n\n def execute(self, context):\n for e in bpy.data.objects:\n try:\n e.show_wire = self.show\n except KeyError:\n print(\"Error on \" + e.name)\n return {'FINISHED'}\n\n\nclass UTSubsurfHideSel(bpy.types.Operator):\n\n 'Sets the Subsurf modifier of all objects in selection to be invisible in the viewport'\n bl_idname = 'ut.subsurfhidesel'\n bl_label = 'Subsurf Hide'\n show = bpy.props.BoolProperty(default=False)\n\n def execute(self, context):\n for e in bpy.context.selected_objects:\n try:\n e.modifiers['Subsurf'].show_viewport = self.show\n except KeyError:\n print(\"No subsurf on \" + e.name + \" or it is not named Subsurf\")\n return {'FINISHED'}\n\n\nclass UTSubsurfHideAll(bpy.types.Operator):\n\n 'Sets the Subsurf modifier of all objects to be invisible in the viewport'\n bl_idname = 'ut.subsurfhideall'\n bl_label = 'Subsurf Hide (All)'\n show = bpy.props.BoolProperty(default=False)\n\n def execute(self, context):\n for e in bpy.data.objects:\n try:\n e.modifiers['Subsurf'].show_viewport = self.show\n except KeyError:\n print(\"No subsurf on \" + e.name + \" or it is not named Subsurf\")\n return {'FINISHED'}\n\n\nclass UTOptimalDisplaySel(bpy.types.Operator):\n\n 'Disables Optimal Display for all Subsurf modifiers on selected objects'\n bl_idname = 'ut.optimaldisplaysel'\n bl_label = 'Optimal Display'\n on = bpy.props.BoolProperty(default=False)\n\n def execute(self, context):\n for e in bpy.context.selected_objects:\n try:\n e.modifiers['Subsurf'].show_only_control_edges = self.on\n except KeyError:\n print(\"No subsurf on \" + e.name + \" or it is not named Subsurf\")\n return {'FINISHED'}\n\n\nclass UTOptimalDisplayAll(bpy.types.Operator):\n\n 'Disables Optimal Display for all Subsurf modifiers'\n bl_idname = 'ut.optimaldisplayall'\n bl_label = 'Optimal Display Off (All)'\n on = bpy.props.BoolProperty(default=False)\n\n def execute(self, context):\n for e in bpy.data.objects:\n try:\n e.modifiers['Subsurf'].show_only_control_edges = self.on\n except KeyError:\n print(\"No subsurf on \" + e.name + \" or it is not named Subsurf\")\n return {'FINISHED'}\n\n\nclass UTAllEdges(bpy.types.Operator):\n\n 'Enables All Edges for all objects'\n bl_idname = 'ut.all_edges'\n bl_label = 'All Edges'\n on = bpy.props.BoolProperty(default=False)\n\n def execute(self, context):\n for e in bpy.data.objects:\n e.show_all_edges = self.on\n return {'FINISHED'}\n\n\nclass UTDoubleSided(bpy.types.Operator):\n\n 'Disables Double Sided Normals for all objects'\n bl_idname = 'ut.double_sided'\n bl_label = 'Double Sided Normals'\n on = bpy.props.BoolProperty(default=False)\n\n def execute(self, context):\n for e in bpy.data.meshes:\n try:\n e.show_double_sided = self.on\n except KeyError:\n print(\"Error setting double sided on \" + e.name)\n return {'FINISHED'}\n\n\nclass UTClearAnim(bpy.types.Operator):\n\n 'Deletes animation for the selected objects'\n bl_idname = 'ut.clearanim'\n bl_label = 'Delete Animation'\n selected_only = bpy.props.BoolProperty(default=False)\n\n def execute(self, context):\n if self.selected_only:\n objs = bpy.context.selected_objects\n else:\n objs = bpy.data.objects\n\n for obj in objs:\n obj.animation_data_clear()\n\n self.report({'INFO'}, \"Animation deleted\")\n return {'FINISHED'}\n\n\nclass UTKillSubsurfs(bpy.types.Operator):\n\n 'Deletes all Subsurf modifiers in the scene'\n bl_idname = 'ut.remove_all_subsurfs'\n bl_label = 'Kill All Subsurfs'\n\n def execute(self, context,):\n counter = 0\n for obj in bpy.data.objects:\n bpy.context.scene.objects.active = obj\n for mod in bpy.context.object.modifiers:\n if mod.type == 'SUBSURF':\n if context.mode == \"EDIT_MESH\":\n bpy.ops.object.editmode_toggle()\n bpy.ops.object.modifier_remove(modifier=mod.name)\n bpy.ops.object.editmode_toggle()\n else:\n bpy.ops.object.modifier_remove(modifier=mod.name)\n counter = counter + 1\n self.report({'INFO'}, str(counter) + \" subsurfs removed!\")\n return {'FINISHED'}\n\n\nclass UTDrawTypeOp(bpy.types.Operator):\n\n 'Sets draw type for the selected objects'\n bl_idname = 'ut.set_draw_type'\n bl_label = 'Draw Type'\n prop = bpy.props.StringProperty()\n\n def execute(self, context,):\n for obj in bpy.context.selected_objects:\n obj.draw_type = self.prop\n return {'FINISHED'}\n\n\nclass UTDrawTypeMenu(bpy.types.Menu):\n bl_idname = 'OBJECT_MT_DrawTypeMenu'\n bl_label = \"Draw Type\"\n\n def draw(self, context):\n layout = self.layout\n layout.operator(\"ut.set_draw_type\", text=\"Textured\").prop = \"TEXTURED\"\n layout.operator(\"ut.set_draw_type\", text=\"Solid\").prop = \"SOLID\"\n layout.operator(\"ut.set_draw_type\", text=\"Wire\").prop = \"WIRE\"\n layout.operator(\"ut.set_draw_type\", text=\"Bounds\").prop = \"BOUNDS\"\n\n\nclass UTSetLens(bpy.types.Operator):\n\n 'Sets viewport lense to 100mm'\n bl_idname = 'ut.set_lens'\n bl_label = 'Set Lens'\n prop = bpy.props.IntProperty(default=35)\n\n def execute(self, context,):\n bpy.context.space_data.lens = self.prop\n return {'FINISHED'}\n\n\nclass UTOriginToSel(bpy.types.Operator):\n\n 'Moves object origin to selection (Edit mode only, cannot undo)'\n bl_idname = 'ut.origin_to_selected'\n bl_label = 'Origin to Selected'\n\n @classmethod\n def poll(cls, context):\n return context.active_object and (bpy.context.mode == 'EDIT_MESH' or bpy.context.mode == 'EDIT_CURVE')\n\n def execute(self, context,):\n curloc = bpy.context.scene.cursor_location\n curx = curloc.x\n cury = curloc.y\n curz = curloc.z\n\n bpy.ops.view3d.snap_cursor_to_selected()\n bpy.ops.object.editmode_toggle()\n bpy.ops.object.origin_set(type='ORIGIN_CURSOR', center='MEDIAN')\n bpy.ops.object.editmode_toggle()\n bpy.context.scene.cursor_location.x = curx\n bpy.context.scene.cursor_location.y = cury\n bpy.context.scene.cursor_location.z = curz\n return {'FINISHED'}\n\n\nclass UTRecalcNormalsObjects(bpy.types.Operator):\n\n 'Recalculate normals of all selected objects'\n bl_idname = 'ut.recalculate_normals'\n bl_label = 'Recalculate Normals'\n\n @classmethod\n def poll(cls, context):\n return bpy.context.mode == 'OBJECT' and bpy.context.selected_objects\n\n def execute(self, context,):\n objs = context.selected_objects\n oldactive = context.active_object\n\n for obj in objs:\n context.scene.objects.active = obj\n bpy.ops.object.editmode_toggle()\n bpy.ops.mesh.select_all(action='SELECT')\n bpy.ops.mesh.normals_make_consistent(inside=False)\n bpy.ops.object.editmode_toggle()\n self.report({'INFO'}, \"Recalculated normals of \" + obj.name)\n return {'FINISHED'}\n\n\nclass UTSaveFile(bpy.types.Operator):\n\n 'Saves the File, or Save As if not saved already'\n bl_idname = 'ut.save_file'\n bl_label = 'Save File'\n\n @classmethod\n def poll(cls, context):\n return bpy.data.filepath != \"\" and not bpy.data.filepath.endswith(\"untitled.blend\")\n\n def execute(self, context,):\n if bpy.data.filepath != \"\":\n bpy.ops.wm.save_mainfile(filepath=bpy.data.filepath)\n else:\n bpy.ops.wm.save_as_mainfile()\n return {'FINISHED'}\n\n\nclass UTSaveFileIncrement(bpy.types.Operator):\n\n 'Increments the file name and then saves it'\n bl_idname = 'ut.save_file_increment'\n bl_label = 'Save File Increment'\n\n @classmethod\n def poll(cls, context):\n return bpy.data.filepath[-7:-6].isnumeric()\n\n def execute(self, context,):\n if bpy.data.filepath != \"\":\n fp = bpy.data.filepath\n enddigit = fp[-7:-6]\n end2digit = fp[-8:-7]\n end3digit = fp[-9:-8]\n if enddigit.isnumeric():\n if int(enddigit) == 9 and not end2digit.isnumeric():\n endint = int(enddigit) + 1\n fp = fp[:-7] + str(endint) + fp[-6:]\n if int(enddigit) != 9:\n endint = int(enddigit) + 1\n fp = fp[:-7] + str(endint) + fp[-6:]\n if end2digit.isnumeric() and int(enddigit) == 9:\n endint = 0\n end2int = int(end2digit) + 1\n fp = fp[:-8] + str(end2int) + str(endint) + fp[-6:]\n if end3digit.isnumeric() and int(end2digit) == 9 and int(enddigit) == 9:\n endint = 0\n end2int = 0\n end3int = int(end3digit) + 1\n fp = fp[:-10] + str(end3int) + str(end2int) + str(endint) + fp[-6:]\n splitsep = fp.split(os.sep)\n self.report({'INFO'}, \"Saved as \" + splitsep[len(splitsep) - 1])\n bpy.ops.wm.save_as_mainfile(filepath=fp)\n else:\n print(\"saving as...\")\n bpy.ops.wm.save_as_mainfile()\n return {'FINISHED'}\n\n\nclass UTClippingToggle(bpy.types.Operator):\n\n 'Toggles mirror modifiers clipping property'\n bl_idname = 'ut.mirror_clipping'\n bl_label = 'Toggle Clipping'\n\n @classmethod\n def poll(cls, context):\n hasmirror = False\n for obj in bpy.context.selected_objects:\n for mod in obj.modifiers:\n if mod.type == 'MIRROR':\n hasmirror = True\n return hasmirror\n\n def execute(self, context):\n for e in bpy.context.selected_objects:\n try:\n if e.modifiers['Mirror'].use_clip == True:\n e.modifiers['Mirror'].use_clip = False\n elif e.modifiers['Mirror'].use_clip == False:\n e.modifiers['Mirror'].use_clip = True\n except KeyError:\n print(\"No mirror modifier on \" + e.name + \" or it is not named Mirror\")\n return {'FINISHED'}\n\n\nclass UTEmptyAlign(bpy.types.Operator):\n\n 'Sets the offset of the image'\n bl_idname = 'ut.align_empty'\n bl_label = 'Align'\n pos = bpy.props.StringProperty()\n\n @classmethod\n def poll(cls, context):\n isimage = False\n if context.active_object.empty_draw_type == 'IMAGE':\n isimage = True\n return isimage\n\n def execute(self, context,):\n pos = self.pos\n px = 0\n py = 0\n\n if pos == \"U_L\":\n px = 0\n py = -1\n if pos == \"U_M\":\n px = -0.5\n py = -1\n if pos == \"U_R\":\n px = -1\n py = -1\n if pos == \"M_L\":\n px = 0\n py = -0.5\n if pos == \"M_M\":\n px = -0.5\n py = -0.5\n if pos == \"M_R\":\n px = -1\n py = -0.5\n if pos == \"D_L\":\n px = 0\n py = 0\n if pos == \"D_M\":\n px = -0.5\n py = 0\n if pos == \"D_R\":\n px = -1\n py = 0\n\n obj = bpy.context.active_object\n if not context.scene.UTEmptySlide:\n obj.empty_image_offset[0] = px\n obj.empty_image_offset[1] = py\n else:\n dx = obj.empty_image_offset[0] - px\n dy = obj.empty_image_offset[1] - py\n obj.empty_image_offset[0] = px\n obj.empty_image_offset[1] = py\n obj.location.x = obj.location.x + (dx * obj.empty_draw_size * obj.scale.x)\n obj.location.y = obj.location.y + (dy * obj.empty_draw_size * obj.scale.y)\n\n goodrot = True\n if obj.rotation_euler.x != 0 or obj.rotation_euler.y != 0 or obj.rotation_euler.z != 0 or obj.rotation_quaternion.w != 1 or obj.rotation_quaternion.x != 0 or obj.rotation_quaternion.y != 0 or obj.rotation_quaternion.z != 0 or obj.rotation_axis_angle[0] != 0 or obj.rotation_axis_angle[1] != 0 or obj.rotation_axis_angle[2] != 1 or obj.rotation_axis_angle[3] != 0:\n goodrot = False\n if goodrot == False and context.scene.UTEmptySlide == True:\n self.report({'WARNING'}, \"CAUTION! Aligning images with 'Slide Origin' on and a non-default rotation may have unexpected results\")\n return {'FINISHED'}\n\n\nclass UTAddPositionedSuzanne(bpy.types.Operator):\n\n 'Add a monkey that sits on the ground'\n bl_idname = 'ut.positioned_suz'\n bl_label = 'Positioned Suzanne'\n\n @classmethod\n def poll(cls, context):\n return (context.mode == 'OBJECT')\n\n def execute(self, context):\n cloc = context.scene.cursor_location\n bpy.ops.mesh.primitive_monkey_add(radius=1, view_align=False, enter_editmode=False, location=(cloc.x, cloc.y, cloc.z + 0.4955), layers=(True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False))\n bpy.ops.object.shade_smooth()\n bpy.ops.object.subdivision_set(level=3)\n bpy.context.object.modifiers[\"Subsurf\"].render_levels = 3\n bpy.context.object.rotation_euler.x = -0.6254132986068726\n\n return {'FINISHED'}\n\n\nclass UTDeleteNodeGroups(bpy.types.Operator):\n\n 'Disables Fake User and reloads the file. Click this several times until there are no unused groups left'\n bl_idname = 'ut.delete_node_groups'\n bl_label = 'Delete Unused Node Groups'\n\n @classmethod\n def poll(cls, context):\n return bpy.data.filepath != \"\" and not bpy.data.filepath.endswith(\"untitled.blend\")\n\n def execute(self, context):\n groups = bpy.data.node_groups\n\n num_groups = len(groups)\n num_affected = 0\n for g in groups:\n if g.use_fake_user:\n g.use_fake_user = False\n num_affected += 1\n\n bpy.ops.wm.save_reload()\n\n self.report({'INFO'}, (\"Affected \" + str(num_affected) + \" of \" + str(num_groups)))\n\n return {'FINISHED'}\n\n\n","sub_path":"scripts/addons_extern/AF_display_tools/useless_tools.py","file_name":"useless_tools.py","file_ext":"py","file_size_in_byte":18285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"451214890","text":"from itertools import chain\nfrom operator import attrgetter\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\n\nfrom feed.models import Tweet, Retweet, DummyUser\n\n\n@login_required\ndef home(request):\n if request.method == \"POST\":\n t = Tweet(text=request.POST[\"text\"])\n t.user = request.user\n t.save()\n return HttpResponseRedirect(reverse(\"feed:home\"))\n\n tweets = Tweet.objects.all()\n retweets = Retweet.objects.all()\n tweets_n_retweets = sorted(chain(tweets, retweets), key=attrgetter('pub_date'), reverse=True)\n\n return render(request, \"feed/home.html\", {\"items\": tweets_n_retweets,\n \"s\": \"1234\"})\n\n\ndef list_tweets(request, username):\n # tweets = Tweet.objects.filter(user__username=username).order_by(\"-pub_date\")\n\n tweets = User.objects.get(username=username).tweet_set.order_by(\"-pub_date\")\n return render(request, \"feed/list_tweets.html\", {\"tweets\": tweets})\n\n\n@login_required\ndef cite(request):\n if request.method != \"POST\":\n return HttpResponse(\"Not supported\")\n t = Tweet(user=request.user)\n origin = Tweet.objects.get(id=request.POST[\"tweet_id\"])\n t.text = 'RT @%s: \"%s\" on %s' % (origin.user.username,\n origin.text,\n origin.pub_date)\n t.save()\n return HttpResponseRedirect(reverse(\"feed:home\"))\n\n\ndef retweet(request):\n if request.method != \"POST\":\n return HttpResponse(\"Not supported\")\n rt = Retweet(\n user=request.user,\n tweet_id=request.POST[\"tweet_id\"]\n )\n rt.save()\n return HttpResponseRedirect(reverse(\"feed:home\"))\n\n\ndef dummy(request):\n return render(request, \"feed/dummy01.html\")\n","sub_path":"07 app with tags&filters and static/feed/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"519709212","text":"arr1 = [9, 20, 28, 18, 11]\narr2 = [30, 1, 21, 17, 28]\ndef solution(n, arr1, arr2):\n answer = []\n for a1, a2 in zip(arr1, arr2):\n a12 = str(bin(a1 | a2))[2:]\n print(a12)\n a12 = '0' * (n-len(a12)) +a12\n a12.replace('1','#')\n a12.replace('0',' ')\n return answer\n\n\nresult = solution(5,arr1,arr2)\n\nprint(result)\n","sub_path":"python/kakao2018/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"617846074","text":"import time\n\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nimport flask\nfrom flask import request, jsonify\n\n# initialize firebase application\nfirebase_admin.initialize_app()\n\n# connect to db\ndb = firestore.client()\n\nrecdata = {\n \"type_of_followup\": \"val\",\n \"details\": \"val\",\n \"doc_id\": \"val\",\n \"doer_docid\": \"val\",\n \"follow_up_id\": \"val\",\n \"edate\": \"val\"\n}\n\n\ndef hello_world(request):\n recdata = flask.request.json\n\n type_of_followup = recdata['type_of_followup']\n details = recdata['details']\n doc_id = recdata['doc_id']\n doer_docid = recdata['doer_docid']\n follow_up_id = recdata['follow_up_id']\n edate = int(time.time())\n\n docs = db.collection(\"Profile\").document(doc_id).collection(\"FollowUps\").document(follow_up_id)\n\n flag = 0\n\n for doc in docs:\n flag = 1\n\n if flag == 0:\n response = {\n \"status\": \"False\",\n \"message\": \"FollowUp does not exists!\"\n }\n return jsonify(response)\n\n ref = db.collection(\"Profile\").document(doc_id).collection(\"FollowUps\").document(follow_up_id).collection(\"FollowUpDetails\").document()\n\n data = {\n \"type_of_followup\": type_of_followup,\n \"details\": details,\n \"doer_docid\": doer_docid,\n \"doc_id\": doc_id,\n \"follow_up_id\": follow_up_id,\n \"edate\": edate\n }\n\n ref.set(data)\n\n response = {\n \"status\": \"True\",\n \"message\": \"FollowUpDetails added successfully!\"\n }\n\n return jsonify(response)\n","sub_path":"testing/addFollowUpDetails.py","file_name":"addFollowUpDetails.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"12179640","text":"#!/usr/bin/python3\n\n# traj2moments.py\n# calculates moments of segment length distribution from state populations (loaded from trajectory file)\n\nfrom matplotlib import rc\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.matlib as npm\nimport sys\n\nrc('font', **{'family': 'serif', 'serif': ['Computer Modern']})\nrc('text', usetex=True)\n\ntry:\n data = np.loadtxt(sys.argv[1])\nexcept:\n print('Syntax: traj2moments.py input_filename')\n sys.exit()\n\nvtx_loc = data[0:2,1:] # vertex locations on graph\ntraj = data[2:,1:] # trajectory (i.e. p(vertex) over time)\nt = data[2:,0] # time\nntstep = np.size(t) # number of timesteps\n\nL = np.max(vtx_loc) # number of monomer units in the system\n\nvtx_nbound = vtx_loc[0,] # number of bound monomers in config at each vertex\nvtx_nbonds = vtx_loc[1,] # number of bonds in config at each vertex\nvtx_nmon = L - vtx_nbound # number of monomers in config at each vertex\nvtx_nseg = L - vtx_nbonds # number of segments in config at each vertex\nvtx_lbar = np.divide(L, vtx_nseg) # average segment length in config at each vertex\n\nmoments = np.empty([ntstep,0])\nmoment0 = np.transpose(np.sum(np.multiply(traj,npm.repmat(np.ones(np.size(vtx_lbar)),ntstep,1)),axis=1))\nmoment1 = np.sum(np.multiply(traj,npm.repmat(np.power(vtx_lbar,1.0),ntstep,1)),axis=1)\nmoment2 = np.sum(np.multiply(traj,npm.repmat(np.power(vtx_lbar,2.0),ntstep,1)),axis=1)\nmoment3 = np.sum(np.multiply(traj,npm.repmat(np.power(vtx_lbar,3.0),ntstep,1)),axis=1)\nmoments = np.concatenate((t[:,None],moment0[:,None],moment1[:,None],moment2[:,None],moment3[:,None]),axis=1)\nprint('\\n'.join(' '.join(str(cell) for cell in row) for row in moments))\n","sub_path":"analytic/full/traj2moments.py","file_name":"traj2moments.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"214459063","text":"#-*- coding: utf-8 -*-\nfrom socket import *\nfrom time import ctime\nfrom time import localtime\nimport time\n\nHOST=''\nPORT=2222 #设置侦听端口\nBUFSIZ=1024\nADDR=(HOST, PORT)\nsock=socket(AF_INET, SOCK_STREAM)\n\nsock.bind(ADDR)\n\nsock.listen(5)\n#设置退出条件\nSTOP_CHAT=False\nwhile not STOP_CHAT:\n print('Waiting for connection, on port:%d' % (PORT))\n tcpClientSock, addr=sock.accept()\n print('Connected by address:',addr)\n while True:\n try:\n data=tcpClientSock.recv(BUFSIZ)\n except:\n #print(e)\n tcpClientSock.close()\n break\n if not data:\n break\n #python3使用bytes,所以要进行编码\n #s='%s发送给我的信息是:[%s] %s' %(addr[0],ctime(), data.decode('utf8'))\n #对日期进行一下格式化\n ISOTIMEFORMAT='%Y-%m-%d %X'\n stime=time.strftime(ISOTIMEFORMAT, localtime())\n #s='%sReceived message:%s' %(addr[0],data)\n #tcpClientSock.send(s.encode('utf8'))\n print([stime],':',data.decode('utf8'))\n #如果输入quit(忽略大小写),则程序退出\n STOP_CHAT=(data.upper()==\"QUIT\")\n if STOP_CHAT:\n break\ntcpClientSock.close()\nsock.close()\n","sub_path":"Demo/s2.py","file_name":"s2.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"353640479","text":"#\n# @lc app=leetcode id=156 lang=python3\n#\n# [156] Binary Tree Upside Down\n#\n# https://leetcode.com/problems/binary-tree-upside-down/description/\n#\n# algorithms\n# Medium (56.19%)\n# Likes: 330\n# Dislikes: 1024\n# Total Accepted: 66.1K\n# Total Submissions: 117.5K\n# Testcase Example: '[1,2,3,4,5]'\n#\n# Given the root of a binary tree, turn the tree upside down and return the new\n# root.\n# \n# You can turn a binary tree upside down with the following steps:\n# \n# \n# The original left child becomes the new root.\n# The original root becomes the new right child.\n# The original right child becomes the new left child.\n# \n# \n# \n# \n# The mentioned steps are done level by level, it is guaranteed that every node\n# in the given tree has either 0 or 2 children.\n# \n# \n# Example 1:\n# \n# \n# Input: root = [1,2,3,4,5]\n# Output: [4,5,2,null,null,3,1]\n# \n# \n# Example 2:\n# \n# \n# Input: root = []\n# Output: []\n# \n# \n# Example 3:\n# \n# \n# Input: root = [1]\n# Output: [1]\n# \n# \n# \n# Constraints:\n# \n# \n# The number of nodes in the tree will be in the range [0, 10].\n# 1 <= Node.val <= 10\n# Every node has either 0 or 2 children.\n# \n# \n#\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n '''\n 145/145 cases passed (36 ms)\n Your runtime beats 45.14 % of python3 submissions\n Your memory usage beats 52.78 % of python3 submissions (14.3 MB)\n '''\n def upsideDownBinaryTree(self, root: TreeNode) -> TreeNode:\n if not root:\n return root\n \n return self.helper(root, None)\n \n def helper(self, node, parent):\n if not node:\n return parent\n \n newRoot = self.helper(node.left, node)\n node.left = parent.right if parent else None\n node.right = parent\n\n return newRoot\n\n\n \n# @lc code=end\n\n","sub_path":"Python/156.binary-tree-upside-down.py","file_name":"156.binary-tree-upside-down.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"114909685","text":"#首先创建一个list\nL = [x * x for x in range(10)]\n#然后 把这个list写成generator\ng = (x * x for x in range(10))\n#打印出每一个元素\nfor n in g:\n print(n)\n\n#斐波拉契数列\ndef fib(max):\n a,b,c=0,0,1\n while a 0:\n model_lst = []\n for i in range(10):\n model = models.resnet18()\n model_lst.append(model)\n model = EnsembleModel(model_lst, 5)\n # model = models.resnet18(pretrained=False)\n # model.conv1 = nn.Conv2d(4, 64, kernel_size=7, stride=2, padding=3, bias=False)\n # model.fc = nn.Linear(512, 5, bias=True)\n if model_ckpt:\n state_dict = torch.load(model_ckpt)\n state_dict = {m.replace('module.', '') : i for m, i in state_dict.items()}\n model.load_state_dict(state_dict)\n\n transform = transforms.Compose([ToTensor()])\n\n \n with torch.no_grad():\n model.eval()\n model = model.cuda()\n num_input = len(input_fnames)\n dataset_val = CustomDataset(input_images, output_labels, transform=transform)\n loader_val = DataLoader(dataset_val, batch_size=num_input, shuffle=False, collate_fn=dataset_val.custom_collate_fn, num_workers=8)\n\n for batch, data in enumerate(loader_val, 1):\n val_label = data['label'].to(device)\n val_input = data['input'].to(device)\n pred_label = model(val_input)\n \n result_y = (max_values - min_values) * pred_label.cpu().numpy() + min_values\n result_x = (max_values - min_values) * val_label.cpu().numpy() + min_values\n\n for y in result_y:\n for a in range(len(y)):\n if y[a] < 0:\n y[a] = 0\n if answer:\n final_output = np.concatenate([result_x, result_y], axis=1)\n final_output = pd.DataFrame(final_output, index=img_idx, columns=[f'label_{_}' for _ in target_df.columns] + [f'pred_{_}' for _ in target_df.columns])\n\n squared_error = np.zeros(5)\n squared_target = np.zeros(5)\n\n for n, cname in enumerate(target_df.columns):\n squared_error[n] += np.sum(np.power(final_output['label_{}'.format(cname)] - final_output['pred_{}'.format(cname)], 2))\n squared_target[n] += np.sum(np.power(final_output['label_{}'.format(cname)], 2))\n\n nmse = squared_error / squared_target\n\n # print(nmse)\n # print(\"NMSE: {:.4f}\".format(np.sum(nmse)))\n\n final_output.to_csv(result_path)\n \n if write_json:\n columns = [\"FreshWeightShoot\", \"DryWeightShoot\", \"Height\", \"Diameter\", \"LeafArea\"]\n columns_output = [\"RGBImage\", \"DebthInformation\"]\n columns_output.extend(columns)\n final_output = pd.DataFrame(result_y, index=img_idx, columns=[f'{_}' for _ in columns])\n final_output['RGBImage'] = input_fnames\n depth_input_fnames = [fname.replace('RGB', 'Debth') for fname in input_fnames]\n final_output['DebthInformation'] = depth_input_fnames\n final_output = final_output[columns_output]\n result = final_output.to_json(orient=\"index\")\n parsed = json.loads(result)\n parsed = {'Measurements': parsed}\n json.dumps(parsed, indent='\\t')\n file_path = os.path.join('./evaluation', (model_name + '.json'))\n with open(file_path, 'w') as outfile:\n json.dump(parsed, outfile, indent=4)\n\n return np.sum(nmse)\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"AGIC-PART A\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"--model_name\", default='best', type=str, dest=\"model_name\") \n parser.add_argument(\"--answer\", default=1, type=int, dest=\"answer\")\n parser.add_argument(\"--verbose\", default=1, type=int, dest='verbose')\n parser.add_argument(\"--write_json\", default=1, type=int, dest='write_json')\n\n return parser.parse_args()\n\ndef main():\n args = parse_args()\n evaluate(args)\n\nif __name__ == '__main__':\n main()","sub_path":"evaluate_ensemble.py","file_name":"evaluate_ensemble.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"564980175","text":"# Copyright (c) 2011 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport datetime\n\nfrom iso8601 import iso8601\nfrom oslo_utils import timeutils\nimport webob.exc\n\nfrom cinder.api.contrib import hosts as os_hosts\nfrom cinder import context\nfrom cinder import exception\nfrom cinder import test\n\n\ncreated_time = datetime.datetime(2012, 11, 14, 1, 20, 41, 95099)\ncurr_time = datetime.datetime(2013, 7, 3, 0, 0, 1)\n\nSERVICE_LIST = [\n {'created_at': created_time, 'updated_at': curr_time,\n 'host': 'test.host.1', 'topic': 'cinder-volume', 'disabled': 0,\n 'availability_zone': 'cinder'},\n {'created_at': created_time, 'updated_at': curr_time,\n 'host': 'test.host.1', 'topic': 'cinder-volume', 'disabled': 0,\n 'availability_zone': 'cinder'},\n {'created_at': created_time, 'updated_at': curr_time,\n 'host': 'test.host.1', 'topic': 'cinder-volume', 'disabled': 0,\n 'availability_zone': 'cinder'},\n {'created_at': created_time, 'updated_at': curr_time,\n 'host': 'test.host.1', 'topic': 'cinder-volume', 'disabled': 0,\n 'availability_zone': 'cinder'},\n {'created_at': created_time, 'updated_at': None,\n 'host': 'test.host.1', 'topic': 'cinder-volume', 'disabled': 0,\n 'availability_zone': 'cinder'},\n]\n\nLIST_RESPONSE = [{'service-status': 'available', 'service': 'cinder-volume',\n 'zone': 'cinder', 'service-state': 'enabled',\n 'host_name': 'test.host.1', 'last-update': curr_time},\n {'service-status': 'available', 'service': 'cinder-volume',\n 'zone': 'cinder', 'service-state': 'enabled',\n 'host_name': 'test.host.1', 'last-update': curr_time},\n {'service-status': 'available', 'service': 'cinder-volume',\n 'zone': 'cinder', 'service-state': 'enabled',\n 'host_name': 'test.host.1', 'last-update': curr_time},\n {'service-status': 'available', 'service': 'cinder-volume',\n 'zone': 'cinder', 'service-state': 'enabled',\n 'host_name': 'test.host.1', 'last-update': curr_time},\n {'service-status': 'unavailable', 'service': 'cinder-volume',\n 'zone': 'cinder', 'service-state': 'enabled',\n 'host_name': 'test.host.1', 'last-update': None},\n ]\n\n\ndef stub_utcnow(with_timezone=False):\n tzinfo = iso8601.Utc() if with_timezone else None\n return datetime.datetime(2013, 7, 3, 0, 0, 2, tzinfo=tzinfo)\n\n\nclass FakeRequest(object):\n environ = {'cinder.context': context.get_admin_context()}\n GET = {}\n\n\nclass FakeRequestWithcinderZone(object):\n environ = {'cinder.context': context.get_admin_context()}\n GET = {'zone': 'cinder'}\n\n\nclass HostTestCase(test.TestCase):\n \"\"\"Test Case for hosts.\"\"\"\n\n def setUp(self):\n super(HostTestCase, self).setUp()\n self.controller = os_hosts.HostController()\n self.req = FakeRequest()\n self.patch('cinder.db.service_get_all', autospec=True,\n return_value=SERVICE_LIST)\n self.mock_object(timeutils, 'utcnow', stub_utcnow)\n\n def _test_host_update(self, host, key, val, expected_value):\n body = {key: val}\n result = self.controller.update(self.req, host, body=body)\n self.assertEqual(expected_value, result[key])\n\n def test_list_hosts(self):\n \"\"\"Verify that the volume hosts are returned.\"\"\"\n hosts = os_hosts._list_hosts(self.req)\n self.assertEqual(LIST_RESPONSE, hosts)\n\n cinder_hosts = os_hosts._list_hosts(self.req, 'cinder-volume')\n expected = [host for host in LIST_RESPONSE\n if host['service'] == 'cinder-volume']\n self.assertEqual(expected, cinder_hosts)\n\n def test_list_hosts_with_zone(self):\n req = FakeRequestWithcinderZone()\n hosts = os_hosts._list_hosts(req)\n self.assertEqual(LIST_RESPONSE, hosts)\n\n def test_bad_status_value(self):\n self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,\n self.req, 'test.host.1', body={'status': 'bad'})\n self.assertRaises(webob.exc.HTTPBadRequest,\n self.controller.update,\n self.req,\n 'test.host.1',\n body={'status': 'disablabc'})\n\n def test_bad_update_key(self):\n bad_body = {'crazy': 'bad'}\n self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,\n self.req, 'test.host.1', body=bad_body)\n\n def test_bad_update_key_and_correct_udpate_key(self):\n bad_body = {'status': 'disable', 'crazy': 'bad'}\n self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,\n self.req, 'test.host.1', body=bad_body)\n\n def test_good_udpate_keys(self):\n body = {'status': 'disable'}\n self.assertRaises(NotImplementedError, self.controller.update,\n self.req, 'test.host.1', body=body)\n\n def test_bad_host(self):\n self.assertRaises(exception.HostNotFound,\n self.controller.update,\n self.req,\n 'bogus_host_name',\n body={'disabled': 0})\n\n def test_show_forbidden(self):\n self.req.environ['cinder.context'].is_admin = False\n dest = 'dummydest'\n self.assertRaises(webob.exc.HTTPForbidden,\n self.controller.show,\n self.req, dest)\n self.req.environ['cinder.context'].is_admin = True\n\n def test_show_host_not_exist(self):\n \"\"\"A host given as an argument does not exists.\"\"\"\n self.req.environ['cinder.context'].is_admin = True\n dest = 'dummydest'\n self.assertRaises(exception.ServiceNotFound,\n self.controller.show,\n self.req, dest)\n","sub_path":"cinder/tests/unit/api/contrib/test_hosts.py","file_name":"test_hosts.py","file_ext":"py","file_size_in_byte":6502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"534503521","text":"\n# 参数\n# multiprocessing.Process(group=None, target=None, name=None, args=(), kwargs={})\n\n# - group: 分组,实际上很少使用,\n# - target: 表示调用对象,你可以传入方法的名字,或者函数名称\n# - name: 别名,相当于给这个进程取一个名字\n# - args: 表示调用对象的位置参数元祖,比如target是函数a,他有两个参数m,n,那么args就传入(m,n)即可\n# - kwargs:表示调用对象的字典\n\nfrom multiprocessing import Process\n\n\ndef f(name):\n print(f'hello {name}')\n\nif __name__ == '__main__':\n p = Process(target=f, args=('john',))\n p.start()\n p.join() # 等待子进程结束,父进程才能结束\n\n# join(timeout) # 超过多少秒 子进程不结束,则父进程也会立即结束\n# 如果可选参数 timeout 是None(默认值),则该方法将阻塞\n# 知道调用join() 方法的进程终止。如果timeout是一个正数,它最多会阻塞 timeout 秒。\n# 请注意,如果进程终止或方法超时,则该方法返回 None。\n# 检查进程的exitcode以确定它是否终止\n# 一个进程可以合并多次\n# 进程无法并入自身,因为这会导致死锁。\n# 尝试在启动进程之前合并进程是错误的","sub_path":"week03/p_multiprocessing.py","file_name":"p_multiprocessing.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"461048079","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom .store_read_settings_py3 import StoreReadSettings\n\n\nclass HttpReadSettings(StoreReadSettings):\n \"\"\"Sftp read settings.\n\n All required parameters must be populated in order to send to Azure.\n\n :param additional_properties: Unmatched properties from the message are\n deserialized this collection\n :type additional_properties: dict[str, object]\n :param type: Required. The read setting type.\n :type type: str\n :param max_concurrent_connections: The maximum concurrent connection count\n for the source data store. Type: integer (or Expression with resultType\n integer).\n :type max_concurrent_connections: object\n :param request_method: The HTTP method used to call the RESTful API. The\n default is GET. Type: string (or Expression with resultType string).\n :type request_method: object\n :param request_body: The HTTP request body to the RESTful API if\n requestMethod is POST. Type: string (or Expression with resultType\n string).\n :type request_body: object\n :param additional_headers: The additional HTTP headers in the request to\n the RESTful API. Type: string (or Expression with resultType string).\n :type additional_headers: object\n :param request_timeout: Specifies the timeout for a HTTP client to get\n HTTP response from HTTP server.\n :type request_timeout: object\n \"\"\"\n\n _validation = {\n 'type': {'required': True},\n }\n\n _attribute_map = {\n 'additional_properties': {'key': '', 'type': '{object}'},\n 'type': {'key': 'type', 'type': 'str'},\n 'max_concurrent_connections': {'key': 'maxConcurrentConnections', 'type': 'object'},\n 'request_method': {'key': 'requestMethod', 'type': 'object'},\n 'request_body': {'key': 'requestBody', 'type': 'object'},\n 'additional_headers': {'key': 'additionalHeaders', 'type': 'object'},\n 'request_timeout': {'key': 'requestTimeout', 'type': 'object'},\n }\n\n def __init__(self, *, type: str, additional_properties=None, max_concurrent_connections=None, request_method=None, request_body=None, additional_headers=None, request_timeout=None, **kwargs) -> None:\n super(HttpReadSettings, self).__init__(additional_properties=additional_properties, type=type, max_concurrent_connections=max_concurrent_connections, **kwargs)\n self.request_method = request_method\n self.request_body = request_body\n self.additional_headers = additional_headers\n self.request_timeout = request_timeout\n","sub_path":"sdk/datafactory/azure-mgmt-datafactory/azure/mgmt/datafactory/models/http_read_settings_py3.py","file_name":"http_read_settings_py3.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"178878147","text":"from django.db import models\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\"\"\"This file is used to assign a oitive value for each Course\nThis takes that if not positive Integer is already associated to the model \nThen it allots one to it bu uing uery Set\n\"\"\"\n\n\nclass OrderField(models.PositiveIntegerField):\n\n\tdef __init__(self,for_fields=None,*args,**kwargs):\n\t\tself.for_fields=for_fields\n\t\tsuper (OrderField,self).__init__(*args,**kwargs)\n\n\tdef pre_save(self, model_instance,add):\n\t\tif getattr(model_instance,self.attname) is None:\n\t\t\ttry:\n\t\t\t\tqs=self.model.objects.all()\n\n\t\t\t\tif self.for_fields:\n\t\t\t\t\t# filter by objects with the same field values\n\t\t\t\t\t# for the fields in \"for_fields\"\n\t\t\t\t\tquery={fields:getattr(model_instance,fields) for fields in self.for_fields}\n\t\t\t\t\tqs=qs.filter(**query)\n\t\t\t\t# get the order of the last item\n\t\t\t\tlast_value=qs.latest(self.attname)\n\t\t\t\tvalue=last_value.order+1\n\t\t\texcept ObjectDoesNotExist:\n\t\t\t\tvalue=0\n\n\t\t\tsetattr(model_instance,self.attname,value)\n\t\t\treturn value\n\n\t\telse:\n\t\t\treturn super(OrderField,self).pre_save(model_instance,add)","sub_path":"elearn/courses/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"475988397","text":"#使用range()使for循环执行相应次数,同时创建相对应的外星人\n#罗旭阳,2019/01/29\n#创建一个存储外星人的空列表\naliens = []\n\n# 创建30个外星人\nfor alien_num in range(30):\n\tnew_alien = {\"color\" : \"green\", \"point\" : 5, \"speed\" : \"slow\"}\n\taliens.append(new_alien)\n\n#显示前五个外星人\nfor alien in aliens[:5]:\n\tprint(alien)\n\nprint(\"... ...\")\n\n#显示到底创建多少个外星人\nprint(\"Total number of aliens : \" + str(len(aliens)))\n","sub_path":"auto_create_aliens.py","file_name":"auto_create_aliens.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"228478861","text":"from app.global_data.global_data import g\nfrom app.domain.message import Message\nfrom app.utils.pageable import gen_pageable\n\n\ndef create_message(message):\n sql = '''\n INSERT INTO message (\n sender,\n receiver,\n subject,\n content,\n url,\n urgent,\n viewed,\n deleted,\n created_date,\n modified_date\n ) VALUES (\"{}\", \"{}\", \"{}\", \"{}\", \"{}\", {}, {}, {}, \"{}\", \"{}\")\n '''.format(\n message.sender,\n message.receiver,\n message.subject,\n message.content,\n message.url if hasattr(message, 'url') else '',\n 1 if hasattr(message, 'urgent') and message.urgent else 0,\n 1 if message.viewed else 0,\n 1 if message.deleted else 0,\n message.createdDate,\n message.modifiedDate\n )\n\n conn = g.db.pool.connection()\n with conn.cursor() as cursor:\n cursor.execute(sql)\n conn.commit()\n cursor.execute('SELECT last_insert_id() FROM message limit 1')\n id = cursor.fetchone()[0]\n conn.close()\n\n return id\n\n\ndef get_messages(where, pageable):\n pageable = gen_pageable(pageable)\n sql = 'SELECT * FROM message {} {}'.format(where, pageable)\n sql_total_count = 'SELECT COUNT(*) FROM message {}'.format(where)\n\n conn = g.db.pool.connection()\n with conn.cursor() as cursor:\n cursor.execute(sql)\n records = cursor.fetchall()\n message_list = []\n for record in records:\n message = Message()\n message.from_record(record)\n message_list.append(message.__dict__)\n\n cursor.execute(sql_total_count)\n total_count = cursor.fetchone()\n conn.close()\n\n return total_count[0], message_list\n\n\ndef find_one_by_id(id):\n sql = 'SELECT * FROM message WHERE id = \"{}\" limit 1'.format(id)\n\n conn = g.db.pool.connection()\n with conn.cursor() as cursor:\n cursor.execute(sql)\n records = cursor.fetchall()\n conn.close()\n\n message_list = []\n for record in records:\n message = Message()\n message.from_record(record)\n message_list.append(message)\n\n return message_list[0] if len(message_list) > 0 else None\n\n\ndef delete_message(id):\n sql = 'DELETE FROM message WHERE id = \"{}\"'.format(id)\n\n conn = g.db.pool.connection()\n with conn.cursor() as cursor:\n cursor.execute(sql)\n conn.commit()\n conn.close()\n\n\ndef update_message_viewed(id, viewed):\n sql = '''\n UPDATE message SET \n viewed = {}\n WHERE id = {}\n '''.format(\n 1 if viewed else 0,\n id\n )\n\n conn = g.db.pool.connection()\n with conn.cursor() as cursor:\n cursor.execute(sql)\n conn.commit()\n conn.close()\n\n\ndef update_message_deleted(id, deleted):\n sql = '''\n UPDATE message SET \n deleted = {}\n WHERE id = {}\n '''.format(\n 1 if deleted else 0,\n id\n )\n\n conn = g.db.pool.connection()\n with conn.cursor() as cursor:\n cursor.execute(sql)\n conn.commit()\n conn.close()\n\n\ndef get_unread_count(receiver, deleted):\n sql = 'SELECT COUNT(*) FROM message WHERE receiver = \"{}\" and deleted = {} and viewed = 0'.format(\n receiver,\n 1 if deleted else 0\n )\n\n conn = g.db.pool.connection()\n with conn.cursor() as cursor:\n cursor.execute(sql)\n count = cursor.fetchone()\n conn.close()\n\n return count[0]\n","sub_path":"uaa-python/app/database/message_db.py","file_name":"message_db.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"392930895","text":"from abc import ABC, abstractmethod\nimport torch, torchtext\nimport gensim\nimport os\nimport numpy as np\n\n\nclass KeyedVectors:\n\n def __init__(self, word2index, weights):\n assert len(word2index)==weights.shape[0], 'wrong number of dimensions'\n index2word = {i:w for w,i in word2index.items()}\n assert len([i for i in range(len(index2word)) if i not in index2word])==0, 'gaps in indexing not allowed'\n self.word2index = word2index\n self.index2word = index2word\n self.weights = weights\n\n def extract(self, words):\n dim = self.weights.shape[1]\n v_size = len(words)\n\n source_idx, target_idx = [], []\n for i,word in enumerate(words):\n if word not in self.word2index: continue\n j = self.word2index[word]\n source_idx.append(i)\n target_idx.append(j)\n\n extraction = np.zeros((v_size, dim))\n extraction[np.asarray(source_idx)] = self.weights[np.asarray(target_idx)]\n\n return extraction\n\n\n\nclass PretrainedEmbeddings(ABC):\n\n def __init__(self):\n super().__init__()\n\n @abstractmethod\n def vocabulary(self): pass\n\n @abstractmethod\n def dim(self): pass\n\n @classmethod\n def reindex(cls, words, word2index):\n source_idx, target_idx = [], []\n for i, word in enumerate(words):\n if word not in word2index: continue\n j = word2index[word]\n source_idx.append(i)\n target_idx.append(j)\n source_idx = np.asarray(source_idx)\n target_idx = np.asarray(target_idx)\n return source_idx, target_idx\n\n\nclass GloVe(PretrainedEmbeddings):\n\n def __init__(self, setname='840B'):\n super().__init__()\n print(f'Loading GloVe pretrained vectors from torchtext')\n self.embed = torchtext.vocab.GloVe(setname)\n print('Done')\n\n def vocabulary(self):\n return set(self.embed.stoi.keys())\n\n def dim(self):\n return self.embed.dim\n\n def extract(self, words):\n source_idx, target_idx = PretrainedEmbeddings.reindex(words, self.embed.stoi)\n extraction = torch.zeros((len(words), self.dim()))\n extraction[source_idx] = self.embed.vectors[target_idx]\n return extraction\n\n\nclass Word2Vec(PretrainedEmbeddings):\n\n def __init__(self, path, limit=None):\n super().__init__()\n print(f'Loading word2vec pretrained vectors from {path}')\n assert os.path.exists(path), print(f'pre-trained keyed vectors not found in {path}')\n self.embed = gensim.models.KeyedVectors.load_word2vec_format(path, binary=True, limit=limit)\n self.word2index={w:i for i,w in enumerate(self.embed.index2word)}\n print('Done')\n\n def vocabulary(self):\n return set(self.word2index.keys())\n\n def dim(self):\n return self.embed.vector_size\n\n def extract(self, words):\n source_idx, target_idx = PretrainedEmbeddings.reindex(words, self.word2index)\n extraction = np.zeros((len(words), self.dim()))\n extraction[source_idx] = self.embed.vectors[target_idx]\n extraction = torch.from_numpy(extraction).float()\n return extraction\n\n","sub_path":"src/embedding/pretrained.py","file_name":"pretrained.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"414764284","text":"##############\n# Exercise 2.5\n##############\n\n# You can use the supplied test cases for your own testing. Good luck!\n\nimport re\n\nstart = \"ATG\"\nstop = [\"TAA\", \"TAG\", \"TGA\"]\n\n\ncodon_dict = dict()\n\ndef complementary(input):\n m = dict({\n 'A': 'T',\n 'T': 'A',\n 'G': 'C',\n 'C': 'G'\n })\n\n return \"\".join([m[letter] for letter in input.upper()])\n\n\n\ndef initDict():\n all = ['G', 'T', 'A', 'C']\n\n # G\n codon_dict.update({'GG'+c: 'G' for c in all})\n codon_dict.update({'GC'+c: 'A' for c in all})\n codon_dict.update({'GT'+c: 'V' for c in all})\n codon_dict.update({'GA'+c: 'E' for c in ['G', 'A']})\n codon_dict.update({'GA'+c: 'D' for c in ['C', 'T']})\n\n # C\n codon_dict.update({'CT'+c: 'L' for c in all})\n codon_dict.update({'CC'+c: 'P' for c in all})\n codon_dict.update({'CG'+c: 'R' for c in all})\n codon_dict.update({'CA'+c: 'Q' for c in ['G', 'A']})\n codon_dict.update({'CA'+c: 'H' for c in ['C', 'T']})\n\n # A\n codon_dict.update({'AC'+c: 'T' for c in all})\n codon_dict.update({'AT'+c: 'I' for c in ['A', 'C', 'T']})\n codon_dict.update({'ATG': 'M'})\n codon_dict.update({'AA'+c: 'K' for c in ['G', 'A']})\n codon_dict.update({'AA'+c: 'N' for c in ['C', 'T']})\n codon_dict.update({'AG'+c: 'R' for c in ['G', 'A']})\n codon_dict.update({'AG'+c: 'S' for c in ['C', 'T']})\n\n # T\n codon_dict.update({'TC'+c: 'S' for c in all})\n codon_dict.update({'TT'+c: 'L' for c in ['G', 'A']})\n codon_dict.update({'TT'+c: 'F' for c in ['C', 'T']})\n codon_dict.update({'TA'+c: 'Y' for c in ['C', 'T']})\n codon_dict.update({'TA'+c: 'STOP' for c in ['G', 'A']})\n codon_dict.update({'TG'+c: 'C' for c in ['C', 'T']})\n codon_dict.update({'TGA': 'STOP'})\n codon_dict.update({'TGG': 'W'})\n\ndef triplet_to_aa(t):\n if len(t) != 3:\n return None\n\n return codon_dict.get(t)\n\n\ndef validate(genome):\n if len(re.sub(\"[^TAGC]+\", '', genome)) < len(genome):\n raise TypeError\n\ndef get_next(genome, start_index):\n if start_index + 3 < len(genome):\n return (genome[start_index:start_index+3], start_index+3)\n elif start_index + 3 == len(genome):\n return (genome[start_index:start_index+3], 0)\n elif start_index + 3 > len(genome) and start_index + 3 < len(genome) + 3:\n res = genome[start_index:len(genome)]\n next_index = start_index - len(genome) + 3\n res = res + genome[0:next_index]\n return (res, next_index)\n else:\n raise RuntimeError\n\ndef read(genome, start_index, reversed):\n validate(genome)\n current_index = start_index\n first_sequence_index = None\n reading_sequence = False\n done = False\n\n first_stop = None\n\n sequences = dict()\n\n aa_sequence = \"\"\n while not done:\n triplet, next_index = get_next(genome, current_index)\n if not reading_sequence and triplet == start:\n first_sequence_index = current_index\n reading_sequence = True\n\n if reading_sequence and triplet in stop:\n reading_sequence = False\n\n if first_stop is None:\n first_stop = current_index\n else:\n if current_index == first_stop:\n done = True\n\n if len(aa_sequence) > 33:\n from_index = first_sequence_index\n to_index = next_index - 1 if next_index > 0 else len(genome)-1\n\n if reversed:\n from_index = len(genome) - from_index - 1\n to_index = len(genome) - to_index - 1\n\n new = (from_index, to_index, aa_sequence, reversed)\n old = sequences.get(to_index)\n\n if old is None:\n sequences[to_index] = new\n else:\n _, _, seq, _ = sequences[to_index]\n if len(seq) > len(aa_sequence):\n sequences[to_index] = new\n\n aa_sequence = \"\"\n\n if reading_sequence:\n aa_sequence += (triplet_to_aa(triplet))\n\n current_index = next_index\n\n return sequences\n\ndef get_orfs(genome):\n initDict()\n l = []\n\n res = read(genome, 0, False)\n for last_index, orf in read(genome, 1, False).items():\n if res.get(last_index) is not None:\n _, _, old_seq, _ = res.get(last_index)\n _, _, new_seq, _ = orf\n if len(new_seq) > len(old_seq):\n res[last_index] = orf\n for last_index, orf in read(genome, 2, False).items():\n if res.get(last_index) is not None:\n _, _, old_seq, _ = res.get(last_index)\n _, _, new_seq, _ = orf\n if len(new_seq) > len(old_seq):\n res[last_index] = orf\n\n l = list(res.values())\n\n res = read(complementary(genome)[::-1], 0, True)\n for last_index, orf in read(complementary(genome)[::-1], 1, True).items():\n if res.get(last_index) is not None:\n _, _, old_seq, _ = res.get(last_index)\n _, _, new_seq, _ = orf\n if len(new_seq) > len(old_seq):\n res[last_index] = orf\n for last_index, orf in read(complementary(genome)[::-1], 2, True).items():\n if res.get(last_index) is not None:\n _, _, old_seq, _ = res.get(last_index)\n _, _, new_seq, _ = orf\n if len(new_seq) > len(old_seq):\n res[last_index] = orf\n\n l += list(res.values())\n\n return l","sub_path":"codechecker/repos/1/collected_files/orffinder/ga58luw.py","file_name":"ga58luw.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"287493651","text":"from datetime import datetime\nfrom textwrap import dedent\nfrom os.path import join, dirname\n\nfrom django.db import connection, reset_queries\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.sites.models import Site\nfrom django.conf import settings\nfrom django.test import TestCase as DjangoTestCase, override_settings\n\nfrom django_comments_tree.models import (TreeComment, CommentAssociation,\n MaxThreadLevelExceededException)\nfrom django_comments_tree.tests.models import Article, Diary\n\nfrom django_comments_tree.models import (LIKEDIT_FLAG, DISLIKEDIT_FLAG,\n TreeCommentFlag)\nfrom django_comments_tree.tests.factories import (ArticleFactory,\n UserFactory,\n TreeCommentFactory,\n TreeCommentFlagFactory)\n\n\nclass ManagerTestBase(DjangoTestCase):\n\n @classmethod\n def setUpTestData(cls):\n cls.article_1 = ArticleFactory.create()\n cls.article_2 = ArticleFactory.create()\n cls.user1 = UserFactory.create()\n cls.user2 = UserFactory.create()\n cls.site = Site.objects.get(pk=1)\n cls.root_1 = TreeComment.objects.get_or_create_root(cls.article_1)\n cls.root_2 = TreeComment.objects.get_or_create_root(cls.article_2)\n\n cls.c1list = []\n cls.c2list = []\n for x in range(10):\n cls.c1list.append(cls.root_1.add_child(comment=f\"Comment Root1 {x}\"))\n cls.c2list.append(cls.root_2.add_child(comment=f\"Comment Root2 {x}\"))\n\n TreeCommentFlagFactory.create(user=cls.user1,\n comment=cls.c1list[0],\n flag=LIKEDIT_FLAG)\n TreeCommentFlagFactory.create(user=cls.user1,\n comment=cls.c1list[1],\n flag=DISLIKEDIT_FLAG)\n TreeCommentFlagFactory.create(user=cls.user1,\n comment=cls.c1list[2],\n flag=LIKEDIT_FLAG)\n TreeCommentFlagFactory.create(user=cls.user1,\n comment=cls.c1list[3],\n flag=DISLIKEDIT_FLAG)\n TreeCommentFlagFactory.create(user=cls.user1,\n comment=cls.c1list[7],\n flag=LIKEDIT_FLAG)\n TreeCommentFlagFactory.create(user=cls.user1,\n comment=cls.c1list[7],\n flag=TreeCommentFlag.SUGGEST_REMOVAL)\n\n\n\nclass TestModelManager(ManagerTestBase):\n\n def test_user_likes(self):\n\n result = TreeComment.objects.user_flags_for_model(self.user1,\n self.article_1)\n\n self.assertIsNotNone(result)\n\n self.assertIn('user', result)\n likes = result['liked']\n dislikes = result['disliked']\n reported = result['reported']\n self.assertEqual(len(likes), 3)\n self.assertEqual(len(dislikes), 2)\n self.assertEqual(len(reported), 1)\n self.assertEqual(likes, [self.c1list[0].id, self.c1list[2].id, self.c1list[7].id])\n","sub_path":"django_comments_tree/tests/test_model_manager.py","file_name":"test_model_manager.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"194936174","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.views.generic import ListView\nfrom django.views.generic.edit import UpdateView, CreateView, FormView\nfrom django.core.urlresolvers import reverse\nfrom django.template import RequestContext\nfrom django.db.models import Q\n\n#from haystack.views import SearchView\n#from haystack.forms import SearchForm\n#from haystack.query import SearchQuerySet\n\nfrom profiles.models import Profile\nfrom geonames.models import Locality\nfrom models import Cartera, Practica, Ubicacion, Registro, Borrador, Definitiva, Otro_agente, Informacion_financiera\n\nfrom django import forms\nfrom gmapi import maps\nfrom gmapi.forms.widgets import GoogleMap\n\nfrom django.conf import settings\nimport elasticsearch\n\nes_host = settings.ELASTICSEARCH_HOST\n\nclass MapForm(forms.Form):\n \"\"\"Widget con google map grande\"\"\"\n map = forms.Field(widget=GoogleMap(attrs={'width':750, 'height':400}))\n\nclass MMapForm(forms.Form):\n \"\"\"Widget con google map chico\"\"\"\n map = forms.Field(widget=GoogleMap(attrs={'width':500, 'height':270}))\n\ndef mapea_busquedas(geo_names=[], googles=[]):\n \"\"\"Inserta los marcadores de dos listas de las busquedas de geocodificacion\"\"\"\n color = {1 : 'ffdf00', 2 : '0005ff'}\n gmap = maps.Map(opts = {\n 'mapTypeId': maps.MapTypeId.ROADMAP,\n 'mapTypeControlOptions': {\n 'style': maps.MapTypeControlStyle.DROPDOWN_MENU }, })\n if geo_names == None : geo_names = [] \n for location in geo_names :\n marker = maps.Marker(opts = {\n 'map': gmap,\n 'position': maps.LatLng(location.latitude,location.longitude),\n 'icon': u'http://gmapsmarkergenerator.eu01.aws.af.cm/getmarker?scale=1&color=%s' %color[2] })\n #'icon' : u'/static/markers/2.png' })\n maps.event.addListener(marker, 'mouseover', 'myobj.markerOver')\n maps.event.addListener(marker, 'mouseout', 'myobj.markerOut')\n info = maps.InfoWindow({\n 'content': location.address ,\n 'disableAutoPan': True })\n info.open(gmap, marker)\n if googles == None : googles = [] \n for location in googles :\n marker = maps.Marker(opts = {\n 'map': gmap,\n 'position': maps.LatLng(location.latitude,location.longitude),\n 'icon': u'http://gmapsmarkergenerator.eu01.aws.af.cm/getmarker?scale=1&color=%s' %color[1] })\n #'icon' : u'/static/markers/1.png' })\n maps.event.addListener(marker, 'mouseover', 'myobj.markerOver')\n maps.event.addListener(marker, 'mouseout', 'myobj.markerOut')\n info = maps.InfoWindow({\n 'content': location.address ,\n 'disableAutoPan': True })\n info.open(gmap, marker)\n return gmap\n\ndef mapea_practicas(practicas):\n \"\"\"Inserta marcadores coloreados en base al numero de la cartera a que pertenecen las practicas\"\"\"\n color = {1 : 'ffcf00', 2 : '0030ff', 3 : '30ff00', 0 : 'ff00cf', 4: '00b099', 5 : '9940ff'} \n #color = {}\n #for n in range(1,15) :\n # color.update({n: '%d.png' %n})\n gmap = maps.Map(opts = {\n 'mapTypeId': maps.MapTypeId.ROADMAP,\n 'mapTypeControlOptions': {\n 'style': maps.MapTypeControlStyle.DROPDOWN_MENU }, })\n for practica in practicas: #[ubicacion for borradores in practica.borrador_set.all() for ubicacion in borradores.ubicaciones.all()]:\n for u in practica.ubicaciones.all() :\n if u.point :\n location = u.point\n marker = maps.Marker(opts = {\n 'map': gmap,\n 'position': maps.LatLng(location.y,location.x),\n 'icon': u'http://gmapsmarkergenerator.eu01.aws.af.cm/getmarker?scale=1&color=%s' %color[practica.registro.cartera.pk%6]\n #'icon' : u'/static/markers/%s' % color[practica.registro.cartera.pk%14]\n })\n maps.event.addListener(marker, 'mouseover', 'myobj.markerOver')\n maps.event.addListener(marker, 'mouseout', 'myobj.markerOut')\n info = maps.InfoWindow({\n 'content': practica.registro.cartera.name+'
    '+practica.name+'
    '+u.address ,\n 'disableAutoPan': True })\n info.open(gmap, marker)\n return gmap\n\ndef practicando(user) :\n \"\"\"Genera la lista de objetos a listar para cada grupo de usuarios\"\"\"\n if user.groups.filter(name__in=['Codificadores',]) or user.is_superuser :\n lista = user.borrador_set.filter(estado=1)\n elif user.groups.filter(name__in=['Arbitros',]) :\n lista = user.definitiva_set.order_by('estado') # .exclude(estado=4)\n elif user.groups.filter(name__in=['Gerentes',]) :\n lista = Cartera.objects.filter(gerente=user) # .exclude(practicas__definitiva__estado=4)\n else :\n lista = Cartera.objects.all()\n return lista\n\ndef display(obj, field):\n field_obj = obj._meta.get_field(field)\n if getattr(obj,field) : return dict(field_obj.choices)[getattr(obj,field)]\n else : return '----'\n\n@login_required\ndef home(request):\n \"\"\"Vista inicial con la lista de elementos a administrar\n\n **Context**\n\n ``practicas``\n Instancia de :model:`observatorio.Practica`.\n\n ``carteras``\n Instancia de :model:`observatorio.Cartera`.\n\n **Template:**\n\n :template:`admin/home.html`\n \"\"\"\n if 'observacoop' in request.get_host() :\n practicas = practicando(request.user)\n else :\n return redirect(reverse('profile_logout'))\n\n context = RequestContext(request) \n if request.user.groups.filter(name__in=['Gerentes','Administradores']) :\n context['title'] = \"Carteras\"\n context['carteras'] = practicas\n practicas = set([practica for cartera in practicas for practica in cartera.practicas.all()])\n\n else:\n context['title'] = \"Practicas\"\n\n context['objects'] = practicas\n \n return render(request, 'admin/home.html', context )\n\n@login_required\ndef map(request, opt, pk):\n \"\"\"Despliega en un mapa los marcadores segun las\n\n **opciones**\n\n ``apa`` restinge las ubicaciones geocodificadas a las de la cartera(pk)\n\n ``bus`` busca en Geonames y google el termino de busqueda\n\n ``pnt`` busqueda inversa del codigo de geonames\n\n ``---`` las ubicaciones de las practicas asociadas al usuario \n \"\"\"\n context = RequestContext(request) \n if request.user.groups.filter(name='Arbitros') :\n practicas = Borrador.objects.filter(registro__definitiva__arbitro=request.user)\n elif request.user.groups.filter(name='Gerentes') :\n practicas = Borrador.objects.filter(registro__cartera__gerente=request.user)\n elif request.user.groups.filter(name='Administradores') :\n practicas = Borrador.objects.all()\n else :\n practicas = practicando(request.user)\n context['is_popup'] = True\n context['pk'] = pk\n\n if 'apa' == opt :\n practicas = practicas.filter(registro__cartera__id=pk) # [practica for practica in practicas if practica.registro.cartera.id == pk ]\n context['title'] = 'Cartera: %s' %practicas[0].registro.cartera.name\n\n if 'pnt' == opt :\n import requests\n import json\n gmap = maps.Map(opts = {'mapTypeId': maps.MapTypeId.ROADMAP, 'zoom': 8,\n 'mapTypeControlOptions': {\n 'style': maps.MapTypeControlStyle.DROPDOWN_MENU }, })\n ubicacion = Ubicacion.objects.get(pk=pk)\n base_url = 'http://api.geonames.org/getJSON?geonameId=%s&username=observacoop' %ubicacion.geonameId\n url_info = requests.get(base_url)\n geoinfo = json.loads(url_info.text)\n conts=''\n for line in [''+key+': '+geoinfo[key].__repr__()+'
    ' for key in geoinfo.viewkeys() if geoinfo[key] and key not in ['timezone','bbox']]: #alternateNames\n conts += line\n marker = maps.Marker(opts = {\n 'map': gmap,\n 'position': maps.LatLng(ubicacion.point.y,ubicacion.point.x),\n 'icon': u'http://gmapsmarkergenerator.eu01.aws.af.cm/getmarker?scale=1&color=%s' %\"00FFFF\"\n #'icon' : u'/static/markers/%d.png' % 8\n })\n maps.event.addListener(marker, 'mouseover', 'myobj.markerOver')\n info = maps.InfoWindow({\n 'content': conts,\n 'disableAutoPan': True })\n info.open(gmap, marker)\n context['form'] = MMapForm(initial={'map': gmap})\n context['title'] = 'geonameId: %d' % ubicacion.geonameId\n\n elif len(request.GET) or 'bus' == opt :\n data = request.GET\n context['is_popup'] = False\n query = data.get('q')\n if query :\n from geopy.geocoders import GeoNames, GoogleV3\n GNlocator = GeoNames(country_bias='MX', username='observacoop', timeout=40, proxies=None)\n Golocator = GoogleV3(api_key='AIzaSyDsI5Yh2XdPIRkbF-_Z1AP17vcXF_tYp-I', domain='maps.googleapis.com', \n scheme='https', client_id=None, secret_key=None, timeout=40, proxies=None)\n geo_names = GNlocator.geocode(query,False)\n googles = Golocator.geocode(query,False)\n if geo_names != None or googles != None :\n gmap = mapea_busquedas(geo_names, googles)\n context['form'] = MapForm(initial={'map': gmap})\n context['geo_names'] = geo_names\n context['googles'] = googles\n context['title'] = 'encontradas'\n else:\n context['error'] = 'No hay respuesta, favor de hacer una nueva busqueda'\n\n else :\n gmap = mapea_practicas(practicas)\n context['form'] = MapForm(initial={'map': gmap})\n\n return render(request, 'admin/map.html', context )\n\nclass UpdateUbicacionView(FormView):\n \"\"\"Asigna a la ubicacion el codigo de GeoNames seleccionado del resultado de la busqueda\"\"\"\n model = Ubicacion\n\n def get(self, request, **kwargs):\n return redirect(reverse('admin:observatorio_ubicacion_change', args=(self.kwargs['pk'],)))\n\n def post(self, request, **kwargs):\n \"\"\"Asigna los atributos de la respuesta de GeoNames\"\"\"\n from django.contrib.gis.geos import Point\n ubicacion_id = int(self.kwargs['pk'])\n ubicacion = Ubicacion.objects.get(pk=ubicacion_id)\n ubicacion.adminName1 = request.POST.get('adminName1')\n ubicacion.address = request.POST.get('address')\n ubicacion.geonameId = int(request.POST.get('geonameId'))\n ubicacion.point = Point(float(request.POST.get('point_longitude')), float(request.POST.get('point_latitude')))\n ubicacion.save()\n\n return redirect(reverse('admin:observatorio_ubicacion_change', args=(self.kwargs['pk'],)))\n \n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super(UpdateUbicacionView, self).dispatch(*args, **kwargs)\n\n@login_required\ndef pendientes(request, pk):\n \"\"\"Genera la lista de las ubicaciones que no estan geocodificados al cambiar el estado del borrador\"\"\"\n practicas = practicando(request.user).filter(ubicaciones__estado=1).filter(pk=pk)\n ubicaciones = [ ubicacion for practica in practicas for ubicacion in practica.ubicaciones.all() ]\n context = RequestContext(request) \n context['title'] = \"Ubicaciones pendientes por geocodificar\"\n context['objects'] = set(ubicaciones)\n \n return render(request, 'admin/pendientes.html', context )\n\nclass UpdatePracticaView(FormView):\n \"\"\"Actualizacion de estados\n **Definitiva**\n\n ``Geocodificada`` Cuando ambos borradores estan geocodificados, se llena con los datos que tienen ambos en comun junto con los que tiene solo uno o el otro, mismos que se borran si alguno es rechazado.\n \n ``En proceso`` Cuando ambos borradores son rechazados.\n\n ``Indexada`` Cuando ambos borradores estan aceptados y se han rectificado los datos definitivos. \n \"\"\"\n model = Practica\n\n def get(self, request, **kwargs):\n context = RequestContext(request)\n template = 'admin/error.html'\n context['practica'] = Borrador.objects.get(pk=int(self.kwargs['pk']))\n return render(request, template, context) \n\n def post(self, request, **kwargs):\n practica_id = int(self.kwargs['pk'])\n if self.kwargs['opt'] == 'idx' :\n practica = Definitiva.objects.get(pk=practica_id)\n else :\n practica = Borrador.objects.get(pk=practica_id)\n if practica.ubicaciones.filter(estado=1) :\n return redirect(reverse('observatorio_pendientes', kwargs={'pk' : practica.pk}))\n if self.kwargs['opt'] == 'gcd' : \n practica.estado = 2\n practica.error = None\n practica.save()\n if not practica.registro.borrador_set.filter(estado=1) :\n definitiva = practica.registro.definitiva_set.all().first()\n borradores = practica.registro.borrador_set.all()\n for field in practica.practica_ptr._meta.fields :\n if getattr(borradores[0],field.name) == getattr(borradores[1],field.name) :\n setattr(definitiva,field.name,getattr(borradores[0],field.name))\n if not getattr(borradores[0],field.name) and getattr(borradores[1],field.name) :\n setattr(definitiva,field.name,getattr(borradores[1],field.name))\n if not getattr(borradores[1],field.name) and getattr(borradores[0],field.name) :\n setattr(definitiva,field.name,getattr(borradores[0],field.name))\n for ubicacion in borradores[0].practica_ptr.ubicaciones.filter(geonameId__in=[u.geonameId for u in borradores[1].practica_ptr.ubicaciones.all()]) :\n ub = Ubicacion.objects.create(practicas=definitiva.practica_ptr)\n otra = borradores[1].practica_ptr.ubicaciones.get(geonameId=ubicacion.geonameId)\n for field, val, display_val in ubicacion : \n if getattr(ubicacion,field.name) == getattr(otra,field.name) : setattr(ub, field.name, val)\n ub.save()\n for ubicacion in borradores[0].practica_ptr.ubicaciones.exclude(geonameId__in=[u.geonameId for u in borradores[1].practica_ptr.ubicaciones.all()]) :\n ub = Ubicacion.objects.create(practicas=definitiva.practica_ptr)\n for field, val, display_val in ubicacion : \n if field.name not in ('id', 'actividades', 'actividad', 'practicas') : setattr(ub, field.name, val)\n if field.name == 'actividad' : \n ub.actividad.add(val)\n ub.save()\n for ubicacion in borradores[1].practica_ptr.ubicaciones.exclude(geonameId__in=[u.geonameId for u in borradores[0].practica_ptr.ubicaciones.all()]) :\n ub = Ubicacion.objects.create(practicas=definitiva.practica_ptr)\n for field, val, display_val in ubicacion : \n if field.name not in ('id', 'actividades', 'actividad', 'practicas') : setattr(ub, field.name, val)\n if field.name == 'actividad' : \n ub.actividad.add(val)\n ub.save()\n for agente in borradores[0].practica_ptr.otros_agentes.filter(nombre__in=[a.nombre for a in borradores[1].practica_ptr.otros_agentes.all()]) :\n ag = Otro_agente.objects.create(practica=definitiva.practica_ptr)\n otra = borradores[1].practica_ptr.otros_agentes.get(nombre=ubicacion.geonameId)\n for field, val, display_val in agente : \n if getattr(agente,field.name) == getattr(otra,field.name) : setattr(ag, field.name, val)\n ag.save()\n for agente in borradores[0].practica_ptr.otros_agentes.exclude(nombre__in=[a.nombre for a in borradores[1].practica_ptr.otros_agentes.all()]) :\n ag = Otro_agente.objects.create(practica=definitiva.practica_ptr)\n for field, val, display_val in agente : \n if field.name not in ('id', 'otros_agentes', 'practica') : setattr(ag, field.name, val)\n ag.save()\n for agente in borradores[1].practica_ptr.otros_agentes.exclude(nombre__in=[a.nombre for a in borradores[0].practica_ptr.otros_agentes.all()]) :\n ag = Otro_agente.objects.create(practica=definitiva.practica_ptr)\n for field, val, display_val in agente : \n if field.name not in ('id', 'otros_agentes', 'practica') : setattr(ag, field.name, val)\n ag.save()\n for info in [ informacion for borrador in borradores for informacion in borrador.practica_ptr.financieros.all() ] :\n fi = Informacion_financiera.objects.create(practica=definitiva.practica_ptr)\n for field, val, display_val in info :\n if field.name not in ('id', 'practica', 'ministraciones') : setattr(fi, field.name, val)\n if field.name == 'ministraciones' :\n for ministracion in val.all(): fi.ministraciones.add(ministracion)\n fi.save()\n definitiva.estado = 2\n definitiva.save()\n if self.kwargs['opt'] == 'gdc' : \n if not request.POST.get('error') :\n context = RequestContext(request)\n template = 'admin/error.html'\n context['practica'] = Borrador.objects.get(pk=int(self.kwargs['pk']))\n context['error'] = 'Favor de dar un motivo'\n return render(request, template, context) \n else :\n practica.error = self.request.POST['error']\n practica.estado = 1\n practica.save()\n definitiva = practica.registro.definitiva_set.all().first()\n new=Definitiva.objects.create(arbitro_id=definitiva.arbitro_id,registro_id=definitiva.registro_id)\n definitiva.delete()\n if practica.registro.borrador_set.filter(estado=2) :\n new.estado = 2\n new.save()\n if self.kwargs['opt'] == 'fin' : \n practica.estado = 3\n practica.save()\n if not practica.registro.borrador_set.filter(estado__in=[1, 2]) :\n definitiva = practica.registro.definitiva_set.all().first()\n definitiva.estado = 3\n definitiva.save()\n if self.kwargs['opt'] == 'idx' : \n practica.estado = 4\n practica.save()\n return redirect(reverse('observatorio_home'))\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super(UpdatePracticaView, self).dispatch(*args, **kwargs)\n\n@login_required\ndef arbitra(request, pk, opt):\n \"\"\"Despliegue y cambio de estado de borradores y edicion de definitiva para el arbitro\"\"\"\n context = RequestContext(request)\n if opt == 'b' :\n objeto = Borrador.objects.get(pk=pk)\n elif opt == 'd' :\n objeto = Definitiva.objects.get(pk=pk)\n if opt == 'r' :\n context['title'] = \"Revisión de practicas\"\n context['definitiva'] = Definitiva.objects.get(pk=pk)\n template = 'admin/arbitra.html'\n else :\n template = 'admin/skel_arbitra.html'\n fieldset = (\n ('Información General', {'d_fields': ('practica_tipo',), 'fields': ('pais_receptor', 'pais_oferente', 'pais_socio',),\n 'd_fields2': ('poblacion_objetivo',), 'fields2': ( 'agencia_implementadora',), 'd_fields3': ( 'tipo_agente_implementador',), \n 'fields3': ( 'agencia_financiadora',), 'd_fields4': ('tipo_agente_financiador', 'modalidad_de_cooperacion', \n 'tipo_de_cooperacion', 'estatus',), 'fields4': ( 'descripcion_corta',\n 'descripcion_larga',), 'l_fields': ('documento_extra', 'url_referencia',)}),)\n fieldsets = (\n ('Inicio de operaciones', {'fields': ('inicio_dia','inicio_mes','inicio_ano')}),\n ('Final de operaciones', {'fields': ('final_dia','final_mes','final_ano')}),\n ('Vigencia', {'fields': ('vigencia_meses','vigencia_anos',)}),\n )\n sections = []\n for section in fieldset :\n fields = []\n for field in section[1]['d_fields'] :\n fields.append({'name': objeto._meta.get_field(field).verbose_name.capitalize() , 'value': display(objeto,field)})\n for field in section[1]['fields'] :\n fields.append({'name': objeto._meta.get_field(field).verbose_name.capitalize() , 'value': getattr(objeto,field) })\n for field in section[1]['d_fields2'] :\n fields.append({'name': objeto._meta.get_field(field).verbose_name.capitalize() , 'value': display(objeto,field)})\n for field in section[1]['fields2'] :\n fields.append({'name': objeto._meta.get_field(field).verbose_name.capitalize() , 'value': getattr(objeto,field) })\n for field in section[1]['d_fields3'] :\n fields.append({'name': objeto._meta.get_field(field).verbose_name.capitalize() , 'value': display(objeto,field)})\n for field in section[1]['fields3'] :\n fields.append({'name': objeto._meta.get_field(field).verbose_name.capitalize() , 'value': getattr(objeto,field) })\n for field in section[1]['d_fields4'] :\n fields.append({'name': objeto._meta.get_field(field).verbose_name.capitalize() , 'value': display(objeto,field)})\n for field in section[1]['fields4'] :\n fields.append({'name': objeto._meta.get_field(field).verbose_name.capitalize() , 'value': getattr(objeto,field) })\n sections.append({'name': section[0], 'fields': fields})\n for section in fieldsets :\n fields = []\n for field in section[1]['fields'] :\n if getattr(objeto,field) :\n fields.append({'name': objeto._meta.get_field(field).verbose_name.capitalize() , 'value': getattr(objeto,field) })\n sections.append({'name': section[0], 'fields': fields})\n links = []\n fields = []\n if objeto.documento_extra :\n fields.append({'name': objeto._meta.get_field('documento_extra').verbose_name.capitalize() , 'url': objeto.documento_extra.url, 'value': objeto.documento_extra.name.strip('./') })\n fields.append({'name': objeto._meta.get_field('url_referencia').verbose_name.capitalize() , 'url': objeto.url_referencia, 'value': objeto.url_referencia })\n links.append({'name': 'Referencias', 'fields': fields})\n related = []\n fields = []\n for agente in objeto.otros_agentes.all() :\n subfields = []\n for field, val, display_val in agente :\n subfields.append({'name': field.verbose_name.capitalize(), 'value': display_val})\n fields.append({'name': agente.nombre, 'value': subfields })\n related.append({'name': 'Otros Agentes', 'fields': fields})\n fields = []\n for financiera in objeto.financieros.all() :\n subfields = []\n subfields.append({'name': 'Ministrado', 'value': financiera.ministrado()})\n for field, val, display_val in financiera :\n subfields.append({'name': field.name.capitalize(), 'value': display_val})\n fields.append({'name': financiera.id_financiadora, 'value': subfields }) \n related.append({'name': 'Información Fianciera', 'fields': fields})\n fields = []\n for ubicacion in objeto.ubicaciones.all() :\n subfields = []\n for field, val, display_val in ubicacion :\n subfields.append({'name': field.verbose_name.capitalize(), 'value': display_val})\n fields.append({'id': ubicacion.id, 'name': ubicacion.geo_codigo, 'value': subfields })\n related.append({'name': 'Ubicaciones', 'fields': fields})\n context['sections'] = sections\n context['related'] = related\n context['links'] = links\n context['objeto'] = objeto\n \n return render(request, template, context)\n\nclass CreateCarteraView(CreateView):\n model = Cartera\n template_name = 'observatorio/cartera_form.html'\n #class_form = CarteraForm\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super(CreateCarteraView, self).dispatch(*args, **kwargs)\n","sub_path":"observatorio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":24575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"196073942","text":"#!/usr/bin/python3\n\"\"\"Function to print a square\n with the character #. size must be\n 0 or a positive integer, otherwise raise a\n ValueError or TypeError.\n\"\"\"\n\n\ndef print_square(size):\n \"\"\"Print a square with # character and size 0 or\n a positive integer, otherwise raise exceptions.\n \"\"\"\n if type(size) is not int:\n raise TypeError(\"size must be an integer\")\n if size < 0:\n raise ValueError(\"size must be >= 0\")\n for i in range(size):\n print(\"#\" * size)\n","sub_path":"0x07-python-test_driven_development/4-print_square.py","file_name":"4-print_square.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"493744834","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom tornado.web import RequestHandler\n\nimport os\nimport codecs\nimport json\nimport hashlib\nimport functools\nimport urlparse # py2\nfrom urllib import urlencode # py2\n\nfrom libs_gl import xlog\nfrom libs_gl import xhttp\n\nimport base_handler\n\nimport dao\nimport config\nimport time\nimport datetime\nimport requests\nimport recharge_handler\n\nbrand_info = {\n\n\t\"uu\": {\n\t\t\"name\": u\"UU电话\",\n\t},\n\n\t\"efl\": {\n\t\t\"name\": u\"易聊电话\",\n\t},\n\t\"3g\": {\n\t\t\"name\": u\"3G电话\",\n\t},\n\n\t\"kc\": {\n\t\t\"name\": u\"KC电话\",\n\t},\n\n\t\"sky\": {\n\t\t\"name\": u\"Sky电话\",\n\t},\n\n\t\"feiin\": {\n\t\t\"name\": u\"免费Wifi电话\",\n\t},\n\t\"4g\": {\n\t\t\"name\": u\"4G电话\",\n\t},\n}\n\n\nclass IndexHandler(RequestHandler):\n\tdef get(self, bid):\n\t\tpc_flag = self.get_argument(\"pc_flag\", \"\")\n\t\tuid = self.get_argument(\"uid\", \"\")\n\t\tkeys = brand_info.keys()\n\t\tif bid not in keys:\n\t\t\tkwargs = {\n\t\t\t\t\"reason\": u\"非法请求,品牌不正确\",\n\t\t\t}\n\t\t\tself.render(\"activities/double_dan/error.html\", **kwargs)\n\t\t\treturn\n\n\t\tis_iphone = False\n\t\tuser_agent = self.request.headers[\"User-Agent\"]\n\t\t\"\"\":type :str\"\"\"\n\t\tif user_agent.lower().find('iphone') != -1:\n\t\t\tis_iphone = True\n\n\t\tis_act_start = recharge_handler.check_activity_time_range()\n\t\tif is_act_start < 0:\n\t\t\tis_act_start = False\n\t\telse:\n\t\t\tis_act_start = True\n\n\n\t\tkwargs = {\n\t\t\t\"bid\": bid,\n\t\t\t\"uid\": uid,\n\t\t\t\"is_iphone\": is_iphone,\n\t\t\t\"pc_flag\": pc_flag,\n\t\t\t\"is_act_start\":is_act_start,\n\t\t}\n\t\tself.render(\"activities/double_dan/index.html\", **kwargs)\n\n\nclass LotterHandler(RequestHandler):\n\tdef get(self, bid):\n\t\tuid = self.get_argument(\"uid\", \"\")\n\t\tdata = recharge_handler.startLottery(bid, uid)\n\t\tself.write(json.dumps(data))\n\n\nclass LotteryDemoHandler(RequestHandler):\n\tdef get(self, bid):\n\t\tpc_flag = self.get_argument(\"pc_flag\", \"\")\n\t\tuid = self.get_argument(\"uid\", \"\")\n\t\tis_iphone = False\n\t\tuser_agent = self.request.headers[\"User-Agent\"]\n\t\t\"\"\":type :str\"\"\"\n\t\tif user_agent.lower().find('iphone') != -1:\n\t\t\tis_iphone = True\n\n\t\tkwargs = {\n\t\t\t\"bid\": bid,\n\t\t\t\"uid\": uid,\n\t\t\t\"is_iphone\": is_iphone,\n\t\t\t\"pc_flag\": pc_flag,\n\t\t}\n\t\tself.render(\"activities/double_dan/demo.html\", **kwargs)\n\n\nclass LoginHandler(RequestHandler):\n\tdef get(self, bid):\n\t\tuid = self.get_argument(\"uid\", \"\")\n\t\tpwd = self.get_argument(\"password\", \"\")\n\t\tif (len(uid) > 10):\n\t\t\tdata = recharge_handler.checkUserInfo(bid, uid, \"mobile\", pwd)\n\t\t\tif data.get(\"result\") == -1:\n\t\t\t\tdata = recharge_handler.checkUserInfo(bid, uid, \"uid\", pwd)\n\t\telse:\n\t\t\tdata = recharge_handler.checkUserInfo(bid, uid, \"uid\", pwd)\n\t\tself.write(json.dumps(data))\n\n\nclass QueryLotteryHandler(RequestHandler):\n\tdef get(self, bid, **kwargs):\n\t\tuid = self.get_argument(\"uid\", \"\")\n\t\tdata = recharge_handler.queryLottery(bid, uid)\n\t\t\"\"\":type :dict\"\"\"\n\t\tkwargs = {\n\t\t\t'list': data\n\t\t}\n\t\tself.render(\"activities/double_dan/lottery_log.html\", **kwargs)\n","sub_path":"src/main/act_double_dan.py","file_name":"act_double_dan.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"277246181","text":"from flask import abort, redirect, render_template, request, url_for,abort,flash\nfrom flask_login import current_user, login_required, login_user, logout_user, login_manager\n\nfrom app.request import get_quote\n\nfrom .. import db\nfrom ..user import Blog, Comment, User\nfrom . import main\nfrom .forms import BlogForm, CommentForm, UpdateProfile,UpForm\n\n\n\n\n@main.route('/', methods=['GET', 'POST'])\ndef index():\n '''\n View root page function that returns the index page and its data\n '''\n title = 'my blogquote'\n quote = get_quote()\n blogs = Blog.query.all()\n return render_template('index.html', title=title, quote=quote, blogs=blogs)\n\n\n@main.route('/blog/new', methods=['GET', 'POST'])\n@login_required\ndef blogs():\n \"\"\"\n view blog function to create a new blog\n \"\"\"\n blog_form = BlogForm()\n\n if blog_form.validate_on_submit():\n title = blog_form.title.data\n content = blog_form.content.data\n print(current_user._get_current_object().id)\n blog = Blog(user_id=current_user._get_current_object().id,\n title=title, content=content)\n\n db.session.add(blog)\n db.session.commit()\n\n return redirect(url_for('main.index'))\n\n return render_template('new_blog.html', blog_form=blog_form)\n\n@main.route(\"/post/\")\n@login_required\ndef mypost(post_id):\n comments = Comment.query.filter_by(post_id=post_id).all()\n print(comments)\n heading = 'comments'\n blog = blog.query.get_or_404(post_id)\n return render_template('posts.html', title=blog.title, blog=blog, comments=comments, heading=heading)\n\n@main.route('/delete/blog,', methods=['GET', 'POST'])\n@login_required\ndef delete_blog(id):\n blog = Blog.query.filter_by(id=id).first()\n if blog is not None:\n blog.delete_blog()\n \n return redirect(url_for('main.index',))\n\n@main.route(\"/blog/update/\", methods=['GET', 'POST'])\n@login_required\ndef update_blog(id):\n blog = Blog.query.filter_by(id = id).first()\n if blog is None:\n abort(404)\n form = UpForm()\n if form.validate_on_submit():\n title = form.title.data\n content = form.content.data\n print(current_user._get_current_object().id)\n blog = Blog(user_id=current_user._get_current_object().id,\n title=title, content=content)\n \n db.session.add(blog)\n db.session.commit()\n \n return redirect(url_for('main.index', blog_id=blog.id))\n elif request.method == 'GET':\n title = form.title.data\n content = form.content.data\n return render_template('blog.html',form=form)\n\n\n@main.route('/user/')\n@login_required\ndef profile(uname):\n user = User.query.filter_by(username=uname).first()\n\n if user is None:\n abort(404)\n\n return render_template(\"profile/profile.html\", user=user)\n\n\n@main.route('/user//update', methods=['GET', 'POST'])\n@login_required\ndef update_profile(uname):\n user = User.query.filter_by(username=uname).first()\n if user is None:\n abort(404)\n\n form = UpdateProfile()\n\n if form.validate_on_submit():\n user.bio = form.bio.data\n\n db.session.add(user)\n db.session.commit()\n\n return redirect(url_for('.profile', uname=user.username))\n\n return render_template('profile/update.html', form=form)\n\n\n@main.route('/comment/new/', methods=['GET', 'POST'])\n@login_required\ndef new_comment(blog_id):\n form = CommentForm()\n blog = Blog.query.get(blog_id)\n if form.validate_on_submit():\n content = form.content.data\n\n new_comment = Comment(\n content=content, user_id=current_user._get_current_object().id, blog_id=blog_id)\n db.session.add(new_comment)\n db.session.commit()\n\n return redirect(url_for('.new_comment', blog_id=blog_id))\n\n comments = Comment.query.filter_by(blog_id=blog_id).all()\n print(comments)\n return render_template('comments.html', form=form, blog=blog, comments=comments)\n\n\n@main.route('/delete/new/', methods=['GET', 'POST'])\n@login_required\ndef delete_comment(id):\n comment = Comment.query.filter_by(id=id).first()\n form = CommentForm()\n if comment is not None:\n comment.delete_comment()\n return redirect(url_for('main.index'))\n\n return render_template('comments.html', form=form)","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"499051433","text":"from datetime import datetime\n\n# 0 -> Empty cells\nboard = [\n [3, 0, 0, 0, 0, 9, 4, 0, 7],\n [0, 0, 0, 0, 0, 0, 8, 6, 0],\n [0, 0, 8, 1, 0, 4, 3, 0, 0],\n [0, 3, 1, 7, 0, 0, 0, 0, 0],\n [0, 9, 4, 0, 0, 0, 7, 8, 0],\n [0, 0, 0, 0, 0, 5, 1, 3, 0],\n [0, 0, 9, 5, 0, 3, 2, 0, 0],\n [0, 8, 5, 0, 0, 0, 0, 0, 0],\n [1, 0, 3, 6, 0, 0, 0, 0, 4],\n]\nempty_cell_list = []\n\n\ndef is_board_valid(row: int, column: int, value: int) -> bool:\n \"\"\"\n Check if board is valid given row, column and particular value for that row x column\n \"\"\"\n if value == 0:\n return False\n\n # Row and column control\n for i in range(9):\n if (i != column and board[row][i] == value) or (i != row and board[i][column] == value):\n return False\n\n # Sub-box control\n sub_box_i = 3 * (row // 3)\n sub_box_j = 3 * (column // 3)\n for i in range(sub_box_i, sub_box_i + 3):\n for j in range(sub_box_j, sub_box_j + 3):\n if i != row and j != column and board[i][j] == value:\n return False\n\n return True\n\n\ndef extract_empty_cells() -> None:\n \"\"\"\n Extract initial empty cells and populate empty_cells list\n \"\"\"\n for i in range(9):\n for j in range(9):\n if board[i][j] == 0:\n empty_cell_list.append((i, j))\n\n\ndef print_board() -> None:\n \"\"\"\n Print board (Empty cells (0: int) will be replaced with space)\n \"\"\"\n for i in range(9):\n line_str = \"|\"\n for j in range(9):\n line_str += \" {} |\".format(\" \" if board[i][j] == 0 else board[i][j])\n print(line_str)\n\n\ndef main() -> None:\n \"\"\"\n Start solving process\n \"\"\"\n start = datetime.utcnow()\n\n extract_empty_cells()\n print(\"Empty cell count: {}\".format(len(empty_cell_list)))\n\n empty_cell_index = 0\n while True:\n row, column = empty_cell_list[empty_cell_index]\n value = board[row][column]\n\n while True:\n if value > 9:\n # Backtrack\n board[row][column] = 0\n empty_cell_index -= 1\n row, column = empty_cell_list[empty_cell_index]\n board[row][column] += 1\n break\n elif is_board_valid(row, column, value):\n # Continue\n board[row][column] = value\n empty_cell_index += 1\n break\n else:\n # Value is not appropriate for board, continue\n value += 1\n\n if empty_cell_index < 0:\n print(\"Invalid!\")\n break\n elif empty_cell_index == len(empty_cell_list):\n print(\"Solved!\")\n break\n\n print_board()\n\n # Calculate time interval\n end = datetime.utcnow()\n seconds = (end-start).total_seconds()\n print(\"Passed time: {:.3f} seconds\".format(seconds))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"594715075","text":"#!/usr/bin/env python\r\n# -*- coding: UTF-8 -*-\r\n\r\nimport os\r\nfrom chimera import *\r\nfrom chimera import runCommand as rc\r\nfrom chimera.tkgui import saveReplyLog as rl\r\n\r\npath=\"C:/Users/pukma/Desktop/DOCKING/3A_cox2_a/0_RMSD\"\r\nref='1cx2'\r\nmodel='pose4'\r\nligand='S58'\r\n\r\n\r\nos.chdir(path+'/')\r\ncurrentPose=0\r\n\r\nreplyobj.status(\"Processing \"+model+\".pdb\") \r\nrc(\"open #0 \" + ref + \".pdb\")\r\nrc(\"open #1 \" + model + \".pdb\")\r\nrc(\"matchmaker #0 #1 \")\r\nRMSD = rc(\"rmsd #1:\"+ligand+ \" #0:\"+ligand) \r\nrl('I.txt')\r\n\r\n\r\n\r\n","sub_path":"AD_wyniki/3A_cox2_a/0_RMSD/RMSD.py","file_name":"RMSD.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"107548100","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nx = []\ny = []\n\nfigure, ax = plt.subplots(figsize=(4, 3))\nline, = ax.plot(x, y)\nplt.axis([0, 4 * np.pi, -1, 1])\n\n\ndef func_animate(i):\n x = np.linspace(0, 4 * np.pi, 1000)\n y = np.sin(2 * (x - 0.1 * i))\n\n line.set_data(x, y)\n\n return line,\n\n\nani = FuncAnimation(figure,\n func_animate,\n frames=10,\n interval=50)\n\nani.save(r'animation.gif', fps=10)\n\nplt.show()\n","sub_path":"plot_realtime_graph.py","file_name":"plot_realtime_graph.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"119342343","text":"import ftputil\nimport os\n\n#FTPHost instances can be created with the following call:\n#ftp_host = ftputil.FTPHost(server, user, password, account,\n# session_factory=ftplib.FTP)\nftpHost = ftputil.FTPHost(\"92.120.196.100\", \"nxa16738\", \"Welcome@123\")\n\nlocalFile = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.md')\n\n#Copies a local source file (given by a filename, i. e. a string) to the remote host under the name target\n#upload(source, target, callback=None)\nftpHost.upload(localFile , \"/README.md\")\n\n#Performs a download from the remote source file to a local target file\n#download(source, target, callback=None)\nftpHost.download(\"/README.md\", localFile)\n\n#Makes the given directory on the remote host. \n#This does not construct \"intermediate\" directories that don't already exist.\n#mkdir(path, [mode])\nftpHost.mkdir(\"/b\")\n\n#Makes the given directory on the remote host. \n#but also makes intermediate directories\n#makedirs(path, [mode])\nftpHost.makedirs(\"/a/b/c\")\n\n#Removes the given remote directory.\n#rmdir(path)\nftpHost.rmdir(\"/b/a\")\n\n#Removes the given remote directory\n#rmtree(path)\nftpHost.rmtree(\"/a/b\")\n\n#Removes a file or link on the remote host\n#remove(path)\nftpHost.remove(\"/README.md\") ","sub_path":"useftputil.py","file_name":"useftputil.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"314913389","text":"import keys\nfrom data_source import DataSource\nfrom location import Location\nfrom population import PopulationSource\nimport requests\nimport pandas as pd\n\n# Staff cost per establishment\nclass StaffCostSource(DataSource):\n def __init__(self, loc):\n super().__init__(loc)\n\n def _fetch(self):\n pop = PopulationSource(self._loc)\n url = 'https://api.census.gov/data/2016/cbp'\n params = {\n 'get': 'ESTAB,EMP,PAYANN',\n # 'for': 'place:'+loc.place_id, # city\n 'for': 'county:*',#+self._loc.county_id, # county\n 'in': 'state:'+self._loc.state_id,\n 'key': keys.CENSUS_API_KEY\n }\n\n try:\n result = requests.get(url, params=params)\n except requests.ConnectionError:\n print('failed to connect')\n self._current = None\n return\n\n data = result.json()\n if len(data) > 1:\n # self._current = int(data[1][0]) / pop.current\n df = pd.DataFrame(data[1:], columns=data[0])\n df['ESTAB'] = df['ESTAB'].apply(int)\n df['EMP'] = df['EMP'].apply(int)\n df['PAYANN'] = df['PAYANN'].apply(int)\n df = df.assign(geo=lambda x: x.state + x.county)\n df = df.set_index('geo')\n df = df.join(pop.df['POP'], how='inner')\n df = df.assign(calc=lambda x: x.PAYANN / x.ESTAB * 1000)\n self._current = df[df['county'] == self._loc.county_id].iloc[0]['calc']\n self._min = df['calc'].min()\n self._max = df['calc'].max()\n self._min_std = df['calc'].mean() - df['calc'].std() * 2\n self._max_std = df['calc'].mean() + df['calc'].std() * 2\n\n @property\n def star_rating(self):\n if self.current != None:\n if round(10 - super().star_rating, 1) < 1:\n return 1\n else:\n return round(10 - super().star_rating, 1)\n else:\n return None\n\nif __name__ == '__main__':\n loc = Location('CO', 'Grand Junction')\n restaurants = StaffCostSource(loc)\n print(restaurants.current)\n #print(restaurants.min)\n #print(restaurants.max)\n print(restaurants.min_std)\n print(restaurants.max_std)\n print(restaurants.star_rating)\n","sub_path":"Backend/staff_cost.py","file_name":"staff_cost.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"219970351","text":"#!/usr/bin/python\nimport numpy as np\nimport sys\n#import ipdb\n\n'''\n Interpolation step of Algorithm 3.6 in Nocedal and Wright. Uses equation\n 3.58 from the book.\n\n phi -- Function phi(alpha) defined in Algorithm 3.6\n phi_prime -- Derivative phi'(alpha)\n alpha_lo -- Lower bound for astar\n alpha_hi-- Upper bound for astar\n method -- Interpolation method to use. Must be in `methods` (default 'quadratic')\n'''\ndef interpolate(phi, phi_prime, alpha_lo, alpha_hi, method='quadratic'):\n\n methods = ['quadratic', 'bisection']\n\n if method == 'quadratic':\n denominator = phi(alpha_hi) - phi(alpha_lo) - phi_prime(alpha_lo) * (alpha_hi - alpha_lo)\n\n if np.abs(denominator) < 1e-10:\n # numerical underflow issues, so avoid\n return interpolate(phi, phi_prime, alpha_lo, alpha_hi, 'bisection')\n\n alpha_j = alpha_lo + phi_prime(alpha_lo) * (alpha_hi - alpha_lo) * (alpha_hi - alpha_lo) / denominator / 2\n\n if alpha_j <= min([alpha_lo, alpha_hi]) or alpha_j >= max([alpha_lo, alpha_hi]):\n return interpolate(phi, phi_prime, alpha_lo, alpha_hi, 'bisection')\n \n return alpha_j\n \n elif method == 'bisection':\n return (alpha_lo + alpha_hi) / 2.0\n \n else:\n raise ValueError('Invalid method. Valid methods are {}'.format(methods))\n\n'''\n Algorithm 3.6 in Nocedal and Wright.\n\n phi -- Function phi(alpha) defined in Algorithm 3.6\n phi_prime -- Derivative phi'(alpha)\n alpha_lo -- Lower bound for alpha_star\n alpha_hi -- Upper bound for alpha_star\n c1 -- Scaling factor for the first Wolfe condition (default 1e-4)\n c2 -- Scaling factor for the second Wolfe condition (default 0.9)\n Returns alpha_star, the acceptable alpha step size\n'''\ndef zoom(phi, phi_prime, phi_0, phi_prime_0, alpha_lo, alpha_hi, c1=1e-4, c2=0.1):\n\n while True:\n\n alpha_j = interpolate(phi, phi_prime, alpha_lo, alpha_hi, 'quadratic')\n\n phi_j = phi(alpha_j)\n\n if (phi_j > phi_0 + c1 * alpha_j * phi_prime_0) or \\\n (phi_j >= phi(alpha_lo)):\n alpha_hi = alpha_j\n\n else:\n phi_prime_j = phi_prime(alpha_j)\n if abs(phi_prime_j) <= abs(c2 * phi_prime_0):\n alpha_star = alpha_j\n return alpha_star\n elif phi_prime_j * (alpha_hi - alpha_lo) >= 0:\n alpha_hi = alpha_lo\n\n alpha_lo = alpha_j\n\n\n return alpha_j\n\n\n'''\n Algorithm 3.5 in Nocedal and Wright.\n\n phi -- Function phi(alpha) defined in Algorithm 3.5\n phi_prime -- Derivative phi'(alpha)\n c1 -- Scaling factor for the first Wolfe condition (default 1e-4)\n c2 -- Scaling factor for the second Wolfe condition (default 0.9)\n alpha_max -- Maximum step size allowed\n step_sz -- Step size to increment alpha by (default 1)\n\n Returns alpha_star, the acceptable step size which satisfies the strong\n Wolfe conditions.\n'''\ndef line_search(phi, phi_prime, c1=1e-4, c2=0.1, alpha_scale=4):\n\n # phi_alpha_prev is not actually used for first iteration, so don't bother\n # computing phi(alpha_prev)\n alphas = [0] # alpha_0 is set to 0\n\n # store these for repeated use in our loop\n phi_0 = phi(0)\n phi_prime_0 = phi_prime(0)\n\n if phi_prime_0 > 0:\n # This should not happen in general. However, for simple momentum\n # this may happen. So, just reverse direction.\n print(\"ERROR: phi_prime_0 > 0 in line search.\")\n alphas.append(-1)\n elif phi_prime_0 == 0:\n print(\"WARNING: phi_prime == 0 ??\")\n return 0\n else:\n # alpha_1 is set between 0 and alpha_max\n alphas.append(1)\n\n # Set alpha_0 and phi_0 to start with\n alpha_i = 0\n phi_i = phi_0\n\n i = 1\n # During this loop, our invariant is that alphas[-1] is alpha_i, and\n # alphas[-2] is alpha_{i-1}\n while True:\n alpha_i_minus_1 = alpha_i\n alpha_i = alphas[-1]\n\n phi_i_minus_1 = phi_i\n phi_i = phi(alpha_i)\n\n phi_prime_i = phi_prime(alpha_i)\n\n # if our new alpha estimate alpha_i violates the first Wolfe condition,\n # then use zoom() to return an alpha between our prior alpha and\n # alpha_i\n if (phi_i > phi_0 + c1 * alpha_i * phi_prime_0) or \\\n (phi_i >= phi_i_minus_1 and i > 1):\n alpha_star = zoom(phi, phi_prime, phi_0, phi_prime_0, alpha_i_minus_1, alpha_i, c1, c2)\n return alpha_star\n\n # if our new alpha estimate alpha_i satisfies both the first and second\n # Wolfe conditions, then we're done so return it\n elif np.abs(phi_prime_i) <= -c2 * phi_prime_0:\n alpha_star = alpha_i\n return alpha_star\n\n # if alpha_i satisfied the first Wolfe condition but not the second,\n # and the slope at alpha_i is positive, then we're heading up away from\n # a local minimum, so backtrack with zoom\n elif phi_prime_i >= 0:\n alpha_star = zoom(phi, phi_prime, phi_0, phi_prime_0, alpha_i, alpha_i_minus_1, c1, c2)\n return alpha_star\n\n # if alpha_i satisfied the first Wolfe condition but not the second,\n # yet the slope at alpha_i is negative, then we can still decreate phi\n # by continuing forward, so move alpha_i forward by step_size\n else:\n # increment i by appending to our list, and set alpha_{i+1} in between alpha_i and alpha_max\n alphas.append(alpha_i * alpha_scale)\n i += 1\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Lbfgs and BFGS/chapter_3_algorithms.py","file_name":"chapter_3_algorithms.py","file_ext":"py","file_size_in_byte":5535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"356310725","text":"# Bungeni Parliamentary Information System - http://www.bungeni.org/\n# Copyright (C) 2010 - Africa i-Parliaments - http://www.parliaments.info/\n# Licensed under GNU GPL v2 - http://www.gnu.org/licenses/gpl-2.0.txt\n\n\"\"\"Custom fields for some content attributes\n\n$Id: fields.py 9920 2012-10-04 14:29:25Z mario.ruggier $\n$URL: https://bungeni-portal.googlecode.com/svn/bungeni.main/trunk/bungeni/ui/fields.py $\n\"\"\"\n\nfrom zope.schema import Text\nfrom zope.schema.interfaces import IVocabularyFactory\nfrom zope.interface import implements \nfrom zope.component import getUtility\nfrom zope.schema.interfaces import ValidationError\nfrom bungeni.ui.interfaces import IVocabularyTextField\nfrom bungeni.ui.i18n import _\n\nclass InvalidVocabularySelection(ValidationError):\n __doc__ = _(\"\"\"Choose items from provided vocabulary\"\"\")\n\nclass VocabularyTextField(Text):\n \"\"\"Field for selection of controlled heirarchical (ITreeVocabulary) \n vocabulary terms.\n \"\"\"\n implements(IVocabularyTextField)\n \n @property\n def vocabulary(self):\n return getUtility(IVocabularyFactory, self.vocabulary_name)\n \n def __init__(self, vocabulary, **kw):\n self.vocabulary_name = vocabulary\n super(VocabularyTextField, self).__init__(**kw)\n \n def _validate(self, values):\n super(VocabularyTextField, self)._validate(values)\n if values:\n try:\n self.vocabulary.validateTerms(values.split(\"\\n\"))\n except LookupError:\n raise InvalidVocabularySelection(values, ())\n \n\n","sub_path":"bungeni.main/bungeni/ui/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"325133759","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Created By : Dick Tsai\n# Created Date : Mon May 27 2019\n# Description : Set up device before running monkey test\n\nimport sys\nimport time\nfrom uiautomator import Device\n\nd = Device(sys.argv[1])\nd.screen.on()\n\nd(resourceId=\"com.yandex.setupwizard:id/btn_language\").click.wait()\nd(text=\"English (United States)\").click.wait()\n\nd(text=\"Get started\").wait.exists(timeout=30)\n\n# language\nd(text=\"Get started\").click.wait()\n\n# connect to mobile network\nd(text=\"SKIP\").click.wait()\n\n# connect to wi-fi\nd(text=\"SKIP\").click.wait()\nd(text=\"CONTINUE\").click.wait()\n\n# date & time\nd(text=\"NEXT\").click.wait()\n\n# fingerprint\nd(text=\"SKIP\").click.wait()\n\n# protect your phone\nd(text=\"Not now\").click.wait()\nd(text=\"SKIP ANYWAY\").click.wait()\n\n# google services\nd(text=\"MORE\").click.wait()\nd(text=\"ACCEPT\").click.wait()\n\n# accelerated location\nd(text=\"Next\").click.wait()\n\n# open settings\nd(resourceId=\"com.google.android.googlequicksearchbox:id/search_widget_google_logo\").wait.exists(timeout=30)\nd.open.quick_settings()\nd(resourceId=\"com.android.systemui:id/settings_button\").click.wait()\n\n# turn off WiFi\nd(scrollable=True).scroll.to(text=\"Network & internet\")\nd(text=\"Network & internet\").click.wait()\nif d(text=\"ON\", className=\"android.widget.Switch\").exists:\n d(text=\"ON\", className=\"android.widget.Switch\").click.wait()\nd.press(\"back\")\n\n# turn off bt\nd(scrollable=True).scroll.to(text=\"Connected devices\")\nd(text=\"Connected devices\").click.wait()\nd(text=\"Connection preferences\").click.wait()\nd(text=\"Bluetooth\").click.wait()\nif d(text=\"ON\", className=\"android.widget.Switch\").exists:\n d(text=\"ON\", className=\"android.widget.Switch\").click.wait()\nd.press(\"back\")\nd.press(\"back\")\nd.press(\"back\")\n\n# Display -> Choose \"Never\"\nd(scrollable=True).scroll.to(text=\"Display\")\nd(text=\"Display\").click.wait()\nd(text=\"Advanced\").click.wait()\nd(text=\"Sleep\").click.wait()\nd(text=\"30 minutes\").click.wait()\nd.press(\"back\")\n\n# Security -> Choose Screen lock \"None\"\nd(scrollable=True).scroll.to(text=\"Security & location\")\nd(text=\"Security & location\").click.wait()\nd(text=\"Screen lock\").click.wait()\nd(text=\"None\").click.wait()\nd.press(\"back\")\n\n# Stay Awake > On\nd(scrollable=True).scroll.to(text=\"System\")\nd(text=\"About phone\").click.wait()\nd(scrollable=True).scroll.to(text=\"Build number\")\nd(text=\"Build number\").click()\nd(text=\"Build number\").click()\nd(text=\"Build number\").click()\nd(text=\"Build number\").click()\nd(text=\"Build number\").click()\nd(text=\"Build number\").click()\nd(text=\"Build number\").click()\nd.press(\"back\")\nd(text=\"System\").click.wait()\nd(text=\"Advanced\").click.wait()\nd(text=\"Developer options\").click.wait()\nd(scrollable=True).scroll.to(text=\"Stay awake\")\nd(text=\"Stay awake\").right(text=\"OFF\", className=\"android.widget.Switch\").click.wait()\nd.press(\"home\")\n","sub_path":"autotest/tradefed/config/8710_monkey_config.py","file_name":"8710_monkey_config.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"607589330","text":"import random\nimport math\nimport copy\n\n#####################################################\n#####################################################\n# Please enter the number of hours you spent on this\n# assignment here\nnum_hours_i_spent_on_this_assignment = 0\n#####################################################\n#####################################################\n\n#####################################################\n#####################################################\n# Give one short piece of feedback about the course so far. What\n# have you found most interesting? Is there a topic that you had trouble\n# understanding? Are there any changes that could improve the value of the\n# course to you? (We will anonymize these before reading them.)\n# \n#####################################################\n#####################################################\n\n\n\n# Outputs a random integer, according to a multinomial\n# distribution specified by probs.\ndef rand_multinomial(probs):\n # Make sure probs sum to 1\n assert(abs(sum(probs) - 1.0) < 1e-5)\n rand = random.random()\n for index, prob in enumerate(probs):\n if rand < prob:\n return index\n else:\n rand -= prob\n return 0\n\n# Outputs a random key, according to a (key,prob)\n# iterator. For a probability dictionary\n# d = {\"A\": 0.9, \"C\": 0.1}\n# call using rand_multinomial_iter(d.items())\ndef rand_multinomial_iter(iterator):\n rand = random.random()\n for key, prob in iterator:\n if rand < prob:\n return key\n else:\n rand -= prob\n return 0\n\nclass HMM():\n #0.5*0.169*0.01*0.169\n def __init__(self):\n self.num_states = 2\n self.prior = [0.5, 0.5]\n self.transition = [[0.999, 0.001], [0.01, 0.99]]\n self.emission = [{\"A\": 0.291, \"T\": 0.291, \"C\": 0.209, \"G\": 0.209},\n {\"A\": 0.169, \"T\": 0.169, \"C\": 0.331, \"G\": 0.331}]\n self.path=[]\n # Generates a sequence of states and characters from\n # the HMM model.\n # - length: Length of output sequence\n def sample(self, length):\n sequence = []\n states = []\n rand = random.random()\n cur_state = rand_multinomial(self.prior)\n for i in range(length):\n states.append(cur_state)\n char = rand_multinomial_iter(self.emission[cur_state].items())\n sequence.append(char)\n cur_state = rand_multinomial(self.transition[cur_state])\n return sequence, states\n\n # Generates a emission sequence given a sequence of states\n def generate_sequence(self, states):\n sequence = []\n for state in states:\n char = rand_multinomial_iter(self.emission[state].items())\n sequence.append(char)\n return sequence\n\n # Computes the (natural) log probability of sequence given a sequence of states.\n def logprob(self, sequence, states):\n ###########################################\n probability =[]\n current_state = states[0]\n current_obs = sequence[0]\n probability = math.log(self.prior[current_state]) + math.log(self.emission[current_state][current_obs])\n for index in range(1,len(sequence)):\n\n current_obs = sequence[index]\n current_state = states[index]\n prev_state = states[index -1]\n trans_prob = math.log(self.transition[prev_state][current_state])\n #trans_prob = self.prob_of_path((prev_state,current_state),probability[index-1],current_obs)\n emission_prob = math.log(self.emission[current_state][current_obs])\n probability = trans_prob + emission_prob + probability\n\n return probability\n # End your code\n ###########################################\n\n\n # Outputs the most likely sequence of states given an emission sequence\n # - sequence: String with characters [A,C,T,G]\n # return: list of state indices, e.g. [0,0,0,1,1,0,0,...]\n def viterbi(self, sequence):\n ###########################################\n # Start your cod\n steps = [[0 for x in range(2)] for y in range(len(sequence))]\n prev_table= [[0 for x in range(2)] for y in range(len(sequence))]\n prev_table[0][0] = -1\n prev_table[0][1] = -1\n\n steps[0][0]= math.log(self.prior[0]) + math.log(self.emission[0][sequence[0]])\n steps[0][1] = math.log(self.prior[1]) + math.log(self.emission[1][sequence[0]])\n #print(steps)\n\n for sym in range(1,len(sequence)):\n # 1= move, 0 = stay\n #probability of emitting T under state 0 or 1\n emission_H = math.log(self.emission[1][sequence[sym]])\n emission_L = math.log(self.emission[0][sequence[sym]])\n\n #L_to_L = math.log(steps[sym-1][0],2) + math.log(self.transition[0][1],2) + math.log(self.emission[0][sequence[sym]],2)\n #probability of staying in state 0 + log of previous state\n L_to_L = self.prob_of_path((0,0),\n steps[sym-1][0],\n sequence[sym]\n )\n # H_to_L = steps[sym-1][1] * self.transition[1][1] *self.emission[0][sequence[sym]]\n #probability of going to state 0 from 1 + log(previous char)\n H_to_L = self.prob_of_path((1,0),\n steps[sym-1][1],\n sequence[sym])\n # H_to_H = steps[sym-1][1] * self.transition[1][0] *self.emission[1][sequence[sym]]\n H_to_H = self.prob_of_path((1,1),\n steps[sym-1][1],\n sequence[sym])\n # L_to_H = steps[sym-1][0] * self.transition[0][1] *self.emission[1][sequence[sym]]\n L_to_H = self.prob_of_path((0,1),\n steps[sym-1][0],\n sequence[sym])\n\n steps[sym][0] = emission_L + max(L_to_L , H_to_L)\n steps[sym][1] = emission_H + max(L_to_H , H_to_H)\n #came from L\n prev_table[sym][0] = 0 if max(L_to_L, H_to_L) == L_to_L else 1\n #came from H\n\n prev_table[sym][1] = 0 if max(L_to_H , H_to_H) == L_to_H else 1\n print(steps)\n print(prev_table)\n return self.back_track(steps,prev_table)\n\n # need to consider transition probabilities\n\n def back_track(self,prob_table,prev_table):\n path = []\n #find max for last element of sewuence\n last_sym = prob_table[len(prob_table)-1]\n #print(last_sym)\n start_index = 0\n if(max(last_sym[0],last_sym[1])) == last_sym[0]:\n start_index = 0\n path.append(0)\n else:\n start_index = 1\n path.append(1)\n #prev_table.reverse()\n for index in range(len(prev_table)-1,0,-1):\n\n prev_node = prev_table[index][start_index]\n path.append( prev_node)\n start_index = prev_node\n path.reverse()\n #print(path)\n return path\n\n def prob_of_path(self,path,prev_probablity,sym):\n start = path[0]\n end = path[1]\n return prev_probablity + math.log(self.transition[start][end])\n\n def getSequence(self,path):\n outputsequence=\"\"\n for tup in path:\n outputsequence = outputsequence + tup[0]\n print(outputsequence)\n return outputsequence\n def obtain_max(self,probL, probR):\n if max(probL, probR) == probL:\n return ('0', probL)\n else:\n return ('1', probR)\n\ndef read_sequence(filename):\n with open(filename, \"r\") as f:\n return f.read().strip()\n\ndef write_sequence(filename, sequence):\n with open(filename, \"w\") as f:\n f.write(\"\".join(sequence))\n\ndef write_output(filename, logprob, states):\n with open(filename, \"w\") as f:\n f.write(str(logprob))\n f.write(\"\\n\")\n for state in range(2):\n f.write(str(states.count(state)))\n f.write(\"\\n\")\n f.write(\"\".join(map(str, states)))\n f.write(\"\\n\")\n\nhmm = HMM()\n\nsequence = read_sequence(\"small.txt\")\nviterbi = hmm.viterbi(sequence)\nlogprob = hmm.logprob(sequence, viterbi)\n\nwrite_output(\"test_op.txt\",logprob, viterbi)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"553402972","text":"# -*- coding: utf-8 -*-\n# @Author: Vincent Xu\n# @E-mail: wenhong0815@qq.com\n# For my Graduation Design about RS\n# import sqlite3\n# conn = sqlite3.connect('temporary.db')\n# c = conn.cursor()\n# c.execute('''CREATE TABLE id2token\n# (ID CHAR(100) PRIMARY KEY NOT NULL,\n# TOKEN char(100) NOT NULL UNIQUE)''')\n# conn.commit()\n# conn.close()\nimport sqlite3\nfrom pybloom_live import ScalableBloomFilter\n\nclass easyRelation():\n '''\n 顾名思义,简单的关系数据库,使用sqlite数据库,仅仅适用于“简单的关系”\n 主要是因为对于大量数据而言,使用python的列表或者队列都很耗内存,且查询低效\n 故有此类,多为二元表+状态标识\n 但是因为比较easy,也没有更多功能\n '''\n\n def __init__(self):\n self.conn = sqlite3.connect('temporary.db')\n self.c = self.conn.cursor()\n print(__name__+' need to end')\n \n\n def getCursor(self):\n '''\n 返回游标和数据库连接\n 可以用于执行其他的sql语句\n '''\n return (self.c,self.conn)\n\n def insertID_TOKEN(self, uid, url_token):\n '''\n 插入一个id和token的对应关系\n '''\n try:\n self.c.execute(\n 'INSERT INTO id2token (ID,TOKEN) VALUES (\\'{0}\\',\\'{1}\\')'.format(uid, url_token))\n self.conn.commit()\n except:\n self.conn.close()\n self.conn = sqlite3.connect('temporary.db')\n self.c = self.conn.cursor()\n\n def insert(self,dic):\n '''\n 与insertID_TOKEN的区别只是接收一个字典为参数\n 字典键包括 id url_token\n '''\n uid = dic['id']\n url_token = dic['url_token']\n try:\n self.c.execute(\n 'INSERT INTO id2token (ID,TOKEN,ISPROCESS) VALUES (\\'{0}\\',\\'{1}\\',0)'.format(uid, url_token))\n self.conn.commit()\n except:\n self.conn.close()\n self.conn = sqlite3.connect('temporary.db')\n self.c = self.conn.cursor()\n def delone(self,token):\n '''\n 按照token删除一条记录\n '''\n self.c.execute('DELETE FROM id2token where TOKEN=\\''+token+'\\'')\n self.conn.commit()\n\n def createindex(self):\n '''\n 创建索引\n '''\n self.c.execute('create index if not exists idindex on id2token(ID);')\n self.conn.commit()\n self.c.execute('create index if not exists tokenindex on id2token(TOKEN);')\n self.conn.commit()\n self.c.execute('create index if not exists isindex on id2token(ISPROCESS);')\n self.conn.commit()\n def getone(self):\n '''\n 在未处理的数据中取一条来处理\n '''\n cur = self.c.execute(\n 'SELECT TOKEN from id2token WHERE ISPROCESS=0 LIMIT 1')\n c=None\n for row in cur:\n c=row[0]\n break\n return c\n\n def okone(self,token):\n '''\n 标识该记录已经被处理过\n '''\n self.c.execute('update id2token set ISPROCESS=1 where TOKEN = \\'' + token + '\\'')\n self.conn.commit()\n\n\n def getResult(self, key, mood='VIA_TOKEN'):\n '''\n 查询\n '''\n if mood == 'VIA_TOKEN':\n cur = self.c.execute(\n 'SELECT ID from id2token WHERE TOKEN=\\'' + str(key)+ '\\'')\n for row in cur:\n return row[0]\n elif mood == 'VIA_ID':\n cur = self.c.execute(\n 'SELECT TOKEN from id2token WHERE ID=\\'' + str(key) + '\\'')\n for row in cur:\n return row[0]\n\n def __del__(self):\n pass\n\n def end(self):\n '''\n 应该被显式的关闭\n '''\n self.conn.close()\n self.__del__()\n def total(self):\n '''\n 返回目前数据库中的记录总数\n '''\n cc = self.c.execute('''SELECT * FROM id2token''')\n r = cc.fetchall()\n return len(r)\n def fiktergenerator(self,mode):\n '''\n 从数据库某一字段读取生成过滤器\n '''\n if 'token' in mode:\n mode = 'TOKEN'\n if 'id' in mode:\n mode = 'ID'\n cc = self.c.execute('SELECT '+mode+' FROM id2token')\n r = cc.fetchall()\n bloom = ScalableBloomFilter(100000000,0.001)\n for i in r:\n bloom.add(i[0])\n return bloom\n\n\n\n\nif __name__ == '__main__':\n ea = easyRelation()\n # # ea.insertID_TOKEN('aaaaaaaaaaa','aaaaaaaaaaaaaa')\n # print(ea.getResult('aaaaaaaaaaa', mood='VIA_ID'))\n ea.fiktergenerator('url_token')\n","sub_path":"functiontool/easyRelation.py","file_name":"easyRelation.py","file_ext":"py","file_size_in_byte":4658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"348179599","text":"from socketIO_client import SocketIO\nimport sys\n\n\nport = 8080\nhost = \"localhost\"\ninterval = 1\n\n\n#read port from commandline python wind_managment.py host 8080\nif len(sys.argv) >= 3:\n try:\n port = int(sys.argv[2])\n host = sys.argv[1]\n except:\n print(\"Argument error, Usage: python wind_managment.py host port\")\n\n\ndef logACK(data):\n print(\"Acknoledgement received for %s\"%data['original'])\n\nif __name__ == \"__main__\":\n socketIO = SocketIO(host, port)\n socketIO.on(\"ack\", logACK)\n\n while True:\n try:\n socketIO.emit('windSpeedUpdate', {'value': 200})\n socketIO.emit('windDirectionUpdate', {'value': 45})\n socketIO.wait(interval)\n except:\n break\n\n\n\n","sub_path":"NodePythonConnection/SocketTestPy/wind_management.py","file_name":"wind_management.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"69572998","text":"import numpy as np\r\nfrom math import log\r\nimport random\r\nfrom operator import itemgetter\r\nfrom matplotlib import pyplot as plt\r\nimport PyInquirer as inquirer\r\nfrom os import system\r\n\r\ndef random_arribo():\r\n t_arribo = random.uniform(0,1)\r\n return - (1 / lamda_arribo) * log(t_arribo)\r\n\r\ndef random_partida():\r\n t_partida = random.uniform(0,1)\r\n return - (1 / lamda_partida) * log(t_partida)\r\n\r\ndef random_prioridad():\r\n paramet_poisson = 0.5\r\n return np.random.poisson(paramet_poisson)\r\n\r\ndef Inicializar():\r\n global Time\r\n global tProxArribo \r\n global tProxPartida \r\n global ProxEventoEsArribo\r\n global AreaQ \r\n global AreaB \r\n global AreaS \r\n global NroClientesEnCola \r\n global TimeUltimoEvento \r\n global ServidorOcupado \r\n global ListaArribos\r\n global ClientesDemorados \r\n global NroCliCompDemora \r\n global DemoraTotal \r\n global NroClientesEnCola \r\n global infinito \r\n global NroClientesEnSistema\r\n global NroClientesDenegados\r\n global DemoraSistema\r\n\r\n Time = 0\r\n tProxArribo = 0\r\n tProxPartida = 0\r\n ProxEventoEsArribo = True\r\n AreaQ = 0\r\n AreaB = 0\r\n AreaS = 0\r\n NroClientesEnCola = 0\r\n TimeUltimoEvento = 0\r\n ServidorOcupado = False\r\n ListaArribos = []\r\n ClientesDemorados = 0\r\n NroCliCompDemora = 0\r\n DemoraTotal = 0\r\n NroClientesEnCola = 0\r\n infinito = 999999999999999999999999\r\n NroClientesEnSistema = 0\r\n NroClientesDenegados = 0\r\n DemoraSistema = 0\r\n tProxPartida = infinito\r\n tProxArribo = round(Time + random_arribo(), 4)\r\n \r\ndef DeterminarEvento():\r\n global Time\r\n global ProxEventoEsArribo\r\n\r\n if tProxArribo <= tProxPartida:\r\n Time = tProxArribo\r\n ProxEventoEsArribo = True\r\n else:\r\n Time = tProxPartida\r\n ProxEventoEsArribo = False\r\n\r\ndef ActualizarEstadisticos():\r\n global AreaQ\r\n global AreaB\r\n global AreaS\r\n global TimeUltimoEvento\r\n\r\n TDesdeUltimoEvento = round(Time - TimeUltimoEvento, 4)\r\n TimeUltimoEvento = Time\r\n\r\n AreaQ += NroClientesEnCola * TDesdeUltimoEvento\r\n AreaB += ServidorOcupado * TDesdeUltimoEvento\r\n AreaS += NroClientesEnSistema * TDesdeUltimoEvento\r\n\r\n AreaQ = round(AreaQ,4)\r\n AreaB = round(AreaB,4)\r\n AreaS = round(AreaS,4)\r\n\r\ndef Arribo():\r\n global ListaArribos\r\n global NroCliCompDemora\r\n global ServidorOcupado\r\n global NroClientesEnCola\r\n global tProxPartida\r\n global tProxArribo\r\n global NroClientesEnSistema\r\n global DemoraSistema\r\n\r\n NroClientesEnSistema += 1\r\n tProxArribo = round(Time + random_arribo(),4)\r\n\r\n if ServidorOcupado:\r\n NroClientesEnCola += 1\r\n # Simulacion con prioridad\r\n if Prioridad: \r\n prioridad = random_prioridad()\r\n ListaArribos.append([Time,prioridad])\r\n\r\n # Ordeno por prioridad y luego por tiempo\r\n ListaArribos = sorted(ListaArribos, key=itemgetter(0))\r\n ListaArribos = sorted(ListaArribos, key=itemgetter(1), reverse = True) \r\n else:\r\n ListaArribos.append(Time)\r\n \r\n else:\r\n # Servidor desocupado, no hizo fila\r\n NroCliCompDemora += 1\r\n ServidorOcupado = True\r\n\r\n # Genera su propio evento partida\r\n tProxPartida = round(Time + random_partida(),4)\r\n # 0 porque no hizo cola + el tiempo en atenderlo\r\n DemoraSistema += (0 + (tProxPartida - Time))\r\n \r\ndef Partida():\r\n global DemoraTotal\r\n global NroCliCompDemora \r\n global NroClientesEnCola\r\n global NroClientesEnSistema\r\n global tProxPartida\r\n global ListaArribos\r\n global ServidorOcupado\r\n global DemoraSistema\r\n\r\n NroClientesEnSistema -= 1\r\n\r\n if NroClientesEnCola == 0:\r\n # Cola vacia\r\n ServidorOcupado = False\r\n tProxPartida = infinito\r\n else:\r\n # Paso un cliente al servidor, fila - 1\r\n NroClientesEnCola -= 1\r\n if Prioridad:\r\n Demora = Time - ListaArribos[0][0]\r\n else:\r\n Demora = Time - ListaArribos[0]\r\n\r\n NroCliCompDemora += 1\r\n tProxPartida = round(Time + random_partida(),4)\r\n\r\n DemoraTotal += round(Demora, 4)\r\n DemoraSistema += (round(Demora, 4) + (tProxPartida - Time))\r\n \r\n ListaArribos.pop(0)\r\n\r\ndef DenegarServicio():\r\n global NroClientesDenegados\r\n global tProxArribo\r\n\r\n tProxArribo = round(Time + random_arribo(),4)\r\n NroClientesDenegados += 1\r\n\r\ndef input_medida_graficar(): \r\n opciones = [\r\n {\r\n 'type': 'list',\r\n 'name': 'medida_seleccionada',\r\n 'message': \"Seleccione una medida de rendimiento\",\r\n 'choices': ['Promedio de clientes en cola', \r\n 'Numero de clientes en cola real', \r\n 'Promedio de clientes en el sistema', \r\n 'Promedio de tiempo en cola', \r\n 'Promedio de tiempo en el sistema', \r\n 'Utilizacion del servidor', \r\n 'Probabilidad de n clientes en cola', \r\n 'Denegacion de servicio'\r\n ]\r\n }\r\n ]\r\n\r\n system(\"cls\")\r\n print(chr(27)+\"[1;33m\") \r\n print('---------------------------------------------')\r\n print(' ¿QUE DESEA GRAFICAR? ')\r\n print('---------------------------------------------')\r\n print(chr(27)+\"[;37m\")\r\n respuesta = inquirer.prompt(opciones)\r\n selec = respuesta['medida_seleccionada']\r\n system(\"cls\")\r\n \r\n return selec\r\n\r\ndef input_parametros():\r\n global lamda_arribo\r\n global lamda_partida\r\n global LimiteDenegacion\r\n global max_simulaciones\r\n global max_iteracion\r\n global Prioridad\r\n\r\n system(\"cls\")\r\n # Parametros de entrada -----------\r\n print(chr(27)+\"[1;33m\") \r\n print(' * Ingrese los parametros de entrada. * ')\r\n print()\r\n print(chr(27)+\"[;37m\")\r\n lamda_arribo = float(input('Lamda de arribo : ')) \r\n lamda_partida = float(input('Lamda de servicio : '))\r\n LimiteDenegacion = int(input('Limite de denegacion : '))\r\n max_simulaciones = int(input('Cant. Simulaciones : '))\r\n max_iteracion = int(input('Cant. Iteraciones : '))\r\n\r\n opciones = [\r\n {\r\n 'type': 'list',\r\n 'name': 'prioridad',\r\n 'message': \"¿Desea una disciplina de cola con prioridad?\",\r\n 'choices': ['Si', 'No']\r\n }\r\n ]\r\n\r\n respuesta = inquirer.prompt(opciones)\r\n selec = respuesta['prioridad']\r\n if selec == 'Si':\r\n Prioridad = True\r\n else:\r\n Prioridad = False\r\n\r\n system(\"cls\")\r\n\r\n # # Parametros de entrada Default -----------\r\n # lamda_arribo = 0.5 # 1.428571429\r\n # lamda_partida = 1 # 1.5151515151\r\n # Prioridad = False\r\n # LimiteDenegacion = 50\r\n # # ---------------------------------\r\n # max_simulaciones = 10\r\n # max_iteracion = 20000\r\n # ---------------------------------\r\n # Se puede evaluar la cantidad de clientes que fueron denegados.\r\n # Tambien se puede evaluar la probabilidad\r\n # ---------------------------------\r\n\r\n\r\ninfinito = 999999999999999999999999\r\n\r\n# =====================================\r\n# El programa tambien funciona para cuando existe una cola con prioridad.\r\n# =====================================\r\n\r\ninput_parametros()\r\nwhile True:\r\n opcion = input_medida_graficar()\r\n\r\n list_t_prom_en_cola = []\r\n list_prom_nro_cli_cola = []\r\n list_utilizac_servidor = []\r\n list_tiempos = []\r\n list_nro_cli_cola = []\r\n list_t_prom_en_sistema = []\r\n list_prom_nro_cli_sist = []\r\n list_nro_cli_cola = []\r\n list_nro_cli_denegados = []\r\n list_prom_nro_cli_denegados = []\r\n barras_prom_nro_cli_cola = []\r\n barras_prom_cli_denegados = []\r\n\r\n #============================= VARIAS SIMULACIONES\r\n for j in range(max_simulaciones):\r\n prom_nro_cli_cola = []\r\n t_prom_en_cola = []\r\n utilizac_servidor = []\r\n tiempos = []\r\n nro_cli_cola = []\r\n t_prom_en_sistema = []\r\n prom_nro_cli_sist = []\r\n nro_cli_denegados = []\r\n prom_nro_cli_denegados = []\r\n\r\n #======================== UNA SIMULACION\r\n Inicializar()\r\n for i in range(1, max_iteracion):\r\n DeterminarEvento()\r\n ActualizarEstadisticos()\r\n\r\n if ProxEventoEsArribo:\r\n if (ServidorOcupado + NroClientesEnCola) < LimiteDenegacion:\r\n Arribo()\r\n else:\r\n DenegarServicio()\r\n else:\r\n Partida() \r\n\r\n nro_cli_cola .append(NroClientesEnCola)\r\n tiempos .append(Time)\r\n t_prom_en_cola .append(round(DemoraTotal / NroCliCompDemora,4))\r\n prom_nro_cli_cola .append(round(AreaQ / Time, 4))\r\n utilizac_servidor .append(round(AreaB / Time, 4))\r\n t_prom_en_sistema .append(round(DemoraSistema / NroCliCompDemora, 4))\r\n prom_nro_cli_sist .append(round(AreaS / Time, 4))\r\n nro_cli_denegados .append(NroClientesDenegados)\r\n\r\n prom_nro_cli_denegados.append(NroClientesDenegados / (NroCliCompDemora + NroClientesDenegados))\r\n \r\n\r\n if j == 0:\r\n print('------------ Medidas de desempeño ------')\r\n print(f'd(n) = SUM(Di) / n = {round(DemoraTotal / NroCliCompDemora,4)}') # Tiempo promedio en cola\r\n print(f'q(n) = integral(Q(t)) / T(n) = {round(AreaQ / Time, 4)}') # Nro promedio de clientes en cola\r\n print(f'mu(n) = integral(B(t) / T(n) = {round(AreaB / Time, 4)}') # Utilizacion del servidor\r\n print()\r\n print(f'Demora en el sistema = {round(DemoraSistema/ NroCliCompDemora,4)}') # Tiempo promedio en el sistema\r\n print(f'Nro clientes en el sistema = {round(AreaS / Time, 4)}')\r\n print()\r\n print(f'Prom nro clientes denegados = {NroClientesDenegados / (NroCliCompDemora + NroClientesDenegados)}')\r\n print(f'Nro clientes denegados = {NroClientesDenegados}')\r\n print(f'Nro clientes fueron atendidos = {NroCliCompDemora}')\r\n cli_denegados = NroClientesDenegados / (NroCliCompDemora + NroClientesDenegados)\r\n\r\n\r\n # Listas de medidas de desempeño\r\n list_prom_nro_cli_cola.append(prom_nro_cli_cola)\r\n list_t_prom_en_cola .append(t_prom_en_cola)\r\n list_utilizac_servidor.append(utilizac_servidor)\r\n list_tiempos .append(tiempos)\r\n list_t_prom_en_sistema.append(t_prom_en_sistema)\r\n list_prom_nro_cli_sist.append(prom_nro_cli_sist)\r\n list_nro_cli_cola .append(nro_cli_cola)\r\n\r\n list_nro_cli_denegados.append(nro_cli_denegados)\r\n list_prom_nro_cli_denegados.append(prom_nro_cli_denegados)\r\n\r\n #======================== Listas para el diagrama de barras\r\n barras_nro_cli_cola = []\r\n barras_cli_denegados = []\r\n\r\n for i in range(9):#max(nro_cli_cola)):\r\n barras_nro_cli_cola.append(nro_cli_cola.count(i) / len(nro_cli_cola))\r\n barras_prom_nro_cli_cola.append(barras_nro_cli_cola)\r\n\r\n #======================== Promedio de las medidas de desempeño\r\n prom_list_prom_nro_cli_cola = []\r\n prom_list_t_prom_en_cola = []\r\n prom_list_utilizac_servidor = []\r\n prom_list_t_prom_en_sistema = []\r\n prom_list_prom_nro_cli_sist = []\r\n prom_barras_prom_nro_cli_cola = []\r\n prom_barras_prom_cli_denegados = []\r\n\r\n for i in range(max_iteracion - 1) :\r\n prom_list_prom_nro_cli_cola .append(np.mean([x[i] for x in list_prom_nro_cli_cola]))\r\n prom_list_t_prom_en_cola .append(np.mean([x[i] for x in list_t_prom_en_cola ]))\r\n prom_list_utilizac_servidor .append(np.mean([x[i] for x in list_utilizac_servidor]))\r\n prom_list_t_prom_en_sistema .append(np.mean([x[i] for x in list_t_prom_en_sistema]))\r\n prom_list_prom_nro_cli_sist .append(np.mean([x[i] for x in list_prom_nro_cli_sist]))\r\n\r\n for i in range(9) :\r\n prom_barras_prom_nro_cli_cola.append(np.mean([x[i] for x in barras_prom_nro_cli_cola]))\r\n\r\n def poner_fondo_color():\r\n ax = plt.gca()\r\n ax.set_facecolor('#f5f5f5')\r\n\r\n\r\n #====================================================================================================\r\n # TODAS LAS GRAFICAS ================================================================================\r\n #====================================================================================================\r\n\r\n #=======================GRAFICOS PROMEDIO CLIENTES EN COLA ============================\r\n if opcion == 'Promedio de clientes en cola':\r\n valor_calculadora = 0.5\r\n for i in range(max_simulaciones):\r\n plt.plot(list_tiempos[i], list_prom_nro_cli_cola[i], c = '#c6a664', alpha = 0.8)\r\n\r\n # plt.axhline(y = valor_calculadora, color = '#1766e2', label = \"Valor calculadora online\", linewidth=3)\r\n #plt.plot([0, 10000], [0, 10000], color = '#1766e2', label = \"Valor calculadora online\", linewidth=3)\r\n plt.plot(list_tiempos[i], prom_list_prom_nro_cli_cola, label = 'Promedio del promedio', c = '#b32428', linewidth=3)\r\n #plt.xlim(0,10000)\r\n plt.title ('Promedio de clientes en cola q(n)')\r\n plt.xlabel('Tiempo')\r\n plt.ylabel('Promedio de clientes en cola q(n)')\r\n plt.legend()\r\n poner_fondo_color()\r\n plt.show()\r\n\r\n #=============================== Clientes en cola reales. SCATTER ====================================\r\n if opcion == 'Numero de clientes en cola real':\r\n\r\n for i in range(max_simulaciones):\r\n plt.scatter(list_tiempos[i], list_nro_cli_cola[i], s = 5, alpha=0.3, c='#c03997')\r\n\r\n plt.title('Numero de clientes en cola N(t)')\r\n plt.xlabel('Tiempo (t)')\r\n plt.ylabel('Numero de clientes en cola N(t)')\r\n plt.legend()\r\n poner_fondo_color()\r\n plt.show()\r\n\r\n #=============================== Clientes en cola reales. LINEAS =====================================\r\n\r\n for i in range(max_simulaciones):\r\n plt.plot(list_tiempos[i], list_nro_cli_cola[i], c='#49b07d')\r\n #plt.plot(list_tiempos[i], prom_list_prom_nro_cli_cola, label = 'Promedio del promedio', c = 'k')\r\n plt.title('Numero de clientes en cola N(t)')\r\n plt.xlabel('Tiempo (t)')\r\n plt.ylabel('Numero de clientes en cola N(t)')\r\n plt.show()\r\n\r\n #=============================== PROM CLIENTES EN EL SISTEMA ==========================================\r\n if opcion == 'Promedio de clientes en el sistema':\r\n\r\n plt.hist(list_nro_cli_cola[0], color = '#ffd900', bins = 15, edgecolor = '#ffd900', linewidth=1)\r\n plt.xlabel('Numero de clientes en el sistema')\r\n plt.ylabel('Frecuencia absoluta de Ns(t)')\r\n poner_fondo_color()\r\n plt.grid(linestyle = '--')\r\n plt.show()\r\n\r\n for i in range(max_simulaciones):\r\n plt.plot(list_tiempos[i], list_prom_nro_cli_sist[i], c = '#c6d8a5')\r\n plt.plot(list_tiempos[i], prom_list_prom_nro_cli_sist, label = 'Promedio del promedio', c = '#0071bc')\r\n plt.title('Promedio de clientes en el sistema')\r\n plt.xlabel('Tiempo (t)')\r\n plt.ylabel('Numero de clientes en cola Ns(t)')\r\n plt.legend()\r\n poner_fondo_color()\r\n plt.show()\r\n\r\n #================================ PROM TIEMPO EN LA COLA =============================================================\r\n if opcion == 'Promedio de tiempo en cola': \r\n\r\n for i in range(max_simulaciones):\r\n plt.plot(list_tiempos[i], list_t_prom_en_cola[i], c='#ff7203', alpha = 0.5)\r\n plt.plot(list_tiempos[i], list_t_prom_en_sistema[i], c='#e63244', alpha = 0.5) #T.Sistema\r\n\r\n plt.plot(list_tiempos[i], prom_list_t_prom_en_cola, label = 'Promedio del promedio Wq', c = '#641c34', linewidth = 2)\r\n plt.plot(list_tiempos[i], prom_list_t_prom_en_sistema, label = 'Promedio del promedio Ws', c = '#641c34',linewidth = 2) #T.sistema\r\n plt.title('Promedio de demora en cola (Wq) / sistema (Ws)')\r\n poner_fondo_color()\r\n plt.grid(linestyle = '--')\r\n plt.legend()\r\n plt.show()\r\n\r\n #=============================== PROM TIEMPO EN EL SISTEMA ==========================================\r\n if opcion == 'Promedio de tiempo en el sistema':\r\n\r\n for i in range(max_simulaciones):\r\n plt.plot(list_tiempos[i], list_t_prom_en_sistema[i])\r\n plt.plot(list_tiempos[i], prom_list_t_prom_en_sistema, label = 'Promedio del promedio', c = 'k')\r\n plt.title('Promedio de tiempo en el sistema')\r\n plt.legend()\r\n plt.show()\r\n\r\n #=============================== PROM UTILIZACION SERVIDOR ==========================================\r\n if opcion == 'Utilizacion del servidor':\r\n\r\n for i in range(max_simulaciones):\r\n plt.plot(list_tiempos[i], list_utilizac_servidor[i], c= '#03baff', alpha = 0.5)\r\n \r\n plt.title('Promedio de utilizacion del servidor p')\r\n plt.plot(list_tiempos[i], prom_list_utilizac_servidor, label = 'Promedio del promedio', c = '#032cff', linewidth = 2)\r\n poner_fondo_color()\r\n plt.grid(linestyle = '--')\r\n plt.xlabel('Tiempo (t)')\r\n plt.ylabel('Promedio de utilizacion del servidor (p)')\r\n plt.legend()\r\n plt.show()\r\n\r\n\r\n mu = AreaB / Time\r\n veces_mu = [mu, 1 - mu]\r\n nombres = [\"Porcentaje que se utilizó el servidor\",\"Porcentaje que no se utilizó el servidor\"]\r\n plt.pie(veces_mu, labels=nombres, autopct=\"%0.1f %%\")\r\n plt.title(\"Porcentaje factor de utilizacion del servidor\")\r\n plt.show()\r\n #=============================== UTILIZACIÓN DEL SERVIDOR scatter ====================================\r\n for i in range(max_simulaciones):\r\n list_utilizac_servidor[i].sort()\r\n list_prom_nro_cli_sist[i].sort()\r\n #plt.plot(list_utilizac_servidor[i], list_prom_nro_cli_sist[i])\r\n plt.scatter(list_utilizac_servidor[i], list_prom_nro_cli_sist[i], s = 10, alpha=0.5, c= '#baff03')\r\n\r\n poner_fondo_color()\r\n plt.grid(linestyle = '--')\r\n plt.xlabel('Promedio utilizacion del servidor (p)')\r\n plt.ylabel('Promedio nro de clientes en cola (Nq)')\r\n plt.show()\r\n\r\n #==================== PROB. n CLIENTS EN COLA (UTILIZACIÓN DEL SERVIDOR) ======================\r\n if opcion == 'Probabilidad de n clientes en cola':\r\n\r\n x = np.arange(len(prom_barras_prom_nro_cli_cola))\r\n y = prom_barras_prom_nro_cli_cola\r\n\r\n plt.stem(x, y, use_line_collection = True, basefmt = 'None', linefmt = 'm')\r\n plt.grid(linestyle = '--')\r\n poner_fondo_color()\r\n plt.xlim(-0.1, 9)\r\n #plt.ylim(0,1)\r\n plt.xlabel('Cllientes en cola')\r\n plt.ylabel('Probabilidad de n clientes en cola')\r\n plt.show()\r\n\r\n #================================ DENEGACION DE SERVICIO ========================================\r\n # Hacer tender la denegacion a un nro muy alto de corridas.\r\n\r\n if opcion == 'Denegacion de servicio':\r\n #================================ Clintes denegados en promedio\r\n for i in range(max_simulaciones):\r\n plt.plot(list_tiempos[i], list_prom_nro_cli_denegados[i])\r\n plt.xlabel('Tiempo (t)')\r\n plt.ylabel('Promedio clientes denegados.')\r\n poner_fondo_color()\r\n plt.grid(linestyle = '--')\r\n plt.show()\r\n\r\n #================================ Clintes denegados reales\r\n for i in range(max_simulaciones):\r\n plt.plot(list_tiempos[i], list_nro_cli_denegados[i])\r\n plt.xlabel('Tiempo (t)')\r\n plt.ylabel('Clientes denegados.')\r\n poner_fondo_color()\r\n plt.grid(linestyle = '--')\r\n plt.show()\r\n\r\n\r\n # x = np.arange(len(prom_barras_prom_cli_denegados))\r\n # y = prom_barras_prom_cli_denegados\r\n\r\n # plt.stem(x, y, use_line_collection = True, basefmt = 'None', linefmt = 'm')\r\n # plt.grid(linestyle = '--')\r\n # poner_fondo_color()\r\n # #plt.xlim(-0.1, 9)\r\n # #plt.ylim(0,1)\r\n # plt.xlabel('Cllientes denegados')\r\n # plt.ylabel('Probabilidad de n clientes denegados')\r\n # plt.show()\r\n\r\n\r\n # plt.hist(list_nro_cli_denegados[0], color = '#fdd900', bins = 10, edgecolor = '#fdd900', linewidth=1)\r\n # plt.show()\r\n #=============================================================================================\r\n\r\n\r\n","sub_path":"TP 3.1 - MM1/Codigo/TP3-Codigo-Fernandez-Avila.py","file_name":"TP3-Codigo-Fernandez-Avila.py","file_ext":"py","file_size_in_byte":21206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"247996006","text":"# coding=utf-8\n\nimport re\n\nfrom marshmallow import (\n Schema as BaseSchema,\n pre_load,\n post_load\n)\n\n\ndef _snake_case_to_camel_case(name):\n def _camel(match):\n return match.group(1) + match.group(2).upper()\n\n return re.sub(r\"(.*?)_([a-zA-Z])\", _camel, name, 0)\n\n\nclass Schema(BaseSchema):\n def on_bind_field(self, name, obj):\n obj.data_key = _snake_case_to_camel_case(obj.data_key or name)\n\n @pre_load\n def strip(self, data, **kwargs):\n \"\"\"strip text data from request.json\n data: Union[str, list, int, float, dict]\n\n :param data:\n \"\"\"\n if isinstance(data, str):\n return data.strip()\n if isinstance(data, list):\n return [self.strip(val) for val in data]\n if isinstance(data, dict):\n return {key: self.strip(val) for key, val in data.items()}\n return data\n\n @post_load\n def remove_extra_field(self, data, **kwargs):\n \"\"\"remove_extra_field\n\n :param data:\n \"\"\"\n if data is not None:\n ret = {}\n for key, _ in self.fields.items():\n if key in data:\n ret[key] = data[key]\n return ret\n return None\n","sub_path":"app/extends/marshmallow.py","file_name":"marshmallow.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"270364849","text":"import os, time\nif(os.path.exists(\"_conda.exe\")):\n path = os.getcwd()\n path_1 = path + ';'\n path_2 = path + '\\\\Scripts;'\n path_3 = path + '\\\\Library\\\\bin;'\n path_add = '\"%Path%;' + path_1 + path_2 + path_3 + '\" /m'\n command = \"setx path \" + path_add\n if os.system(command) == 0:\n os.system(\"color 2F\")\n print(\"\\n\\n\\n\\n\\n 执行成功\")\n time.sleep(5)\nelse:\n os.system(\"color 4F\")\n print(\"\\n\\n\\n\\n\\n 请将此文件放置在Miniconda目录下运行\")\n time.sleep(5)","sub_path":"test/set_os_environ_path/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"334557633","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/ztfy/scheduler/events.py\n# Compiled at: 2013-06-04 02:31:26\n__docformat__ = 'restructuredtext'\nimport atexit, logging\nlogger = logging.getLogger('ztfy.scheduler')\nimport time, transaction, zmq\nfrom transaction.interfaces import ITransactionManager\nfrom zope.catalog.interfaces import ICatalog\nfrom zope.component.interfaces import ISite, IRegistered, IUnregistered, IComponentRegistry\nfrom zope.intid.interfaces import IIntIds\nfrom zope.lifecycleevent.interfaces import IObjectRemovedEvent\nfrom zope.processlifetime import IDatabaseOpenedWithRoot\nfrom ztfy.scheduler.interfaces import ISchedulerHandler, IScheduler, ISchedulerTask\nfrom ztfy.security.interfaces import ILocalRoleIndexer\nfrom ztfy.utils.interfaces import INewSiteManagerEvent\nfrom zc.catalog.catalogindex import SetIndex\nfrom zope.app.publication.zopepublication import ZopePublication\nfrom zope.catalog.catalog import Catalog\nfrom zope.component import hooks, getUtilitiesFor, queryUtility, adapter\nfrom zope.intid import IntIds\nfrom zope.location.location import locate\nfrom zope.traversing import api as traversing_api\nfrom ztfy.scheduler.process import SchedulerProcess, SchedulerMessageHandler\nfrom ztfy.utils.site import locateAndRegister\nfrom ztfy.zmq.process import processExitFunc\n_schedulers = {}\n\ndef updateDatabaseIfNeeded(context):\n \"\"\"Check for missing utilities at application startup\"\"\"\n try:\n sm = context.getSiteManager()\n except:\n return\n\n default = sm['default']\n intids = queryUtility(IIntIds)\n if intids is None:\n intids = default.get('IntIds')\n if intids is None:\n intids = IntIds()\n locate(intids, default)\n IComponentRegistry(sm).registerUtility(intids, IIntIds, '')\n default['IntIds'] = intids\n catalog = default.get('SecurityCatalog')\n if catalog is None:\n catalog = Catalog()\n locateAndRegister(catalog, default, 'SecurityCatalog', intids)\n IComponentRegistry(sm).registerUtility(catalog, ICatalog, 'SecurityCatalog')\n if catalog is not None:\n if 'ztfy.SchedulerManager' not in catalog:\n index = SetIndex('ztfy.SchedulerManager', ILocalRoleIndexer, False)\n locateAndRegister(index, catalog, 'ztfy.SchedulerManager', intids)\n if 'ztfy.SchedulerOperator' not in catalog:\n index = SetIndex('ztfy.SchedulerOperator', ILocalRoleIndexer, False)\n locateAndRegister(index, catalog, 'ztfy.SchedulerOperator', intids)\n return\n\n\n@adapter(IDatabaseOpenedWithRoot)\ndef handleOpenedDatabase(event):\n \"\"\"Launch scheduler process\"\"\"\n handler = queryUtility(ISchedulerHandler)\n if handler is None:\n return\n else:\n db = event.database\n connection = db.open()\n root = connection.root()\n root_folder = root.get(ZopePublication.root_name, {})\n for site in root_folder.values():\n if ISite(site, None) is not None:\n hooks.setSite(site)\n manager = ITransactionManager(site)\n for attempt in manager.attempts():\n with attempt as (t):\n updateDatabaseIfNeeded(site)\n if t.status == 'Committed':\n break\n\n for _name, utility in getUtilitiesFor(IScheduler):\n if utility.zmq_address:\n try:\n try:\n path = traversing_api.getPath(utility)\n except:\n continue\n\n if _schedulers.get(path) is None:\n process = SchedulerProcess(utility, SchedulerMessageHandler)\n process.start()\n time.sleep(2)\n if process.is_alive():\n _schedulers[path] = process\n atexit.register(processExitFunc, process=process)\n logger.info('Starting ZMQ process %s listening on %s with PID %d for handler %s' % (\n process.name, utility.zmq_address,\n process.pid, str(process.handler)))\n except zmq.ZMQError as e:\n logger.warning(\"Can't start scheduler process: \" + e.message)\n\n return\n\n\n@adapter(INewSiteManagerEvent)\ndef handleNewSiteManager(event):\n updateDatabaseIfNeeded(event.object)\n\n\n@adapter(IScheduler, IRegistered)\ndef handleRegisteredSchedulerUtility(utility, event):\n if utility.zmq_address:\n path = traversing_api.getPath(utility)\n if _schedulers.get(path) is None:\n process = SchedulerProcess(utility, SchedulerMessageHandler)\n process.start()\n time.sleep(2)\n if process.is_alive():\n _schedulers[path] = process\n atexit.register(processExitFunc, process=process)\n logger.info('Starting ZMQ process %s listening on %s with PID %d for handler %s' % (\n process.name, utility.zmq_address,\n process.pid, str(process.handler)))\n return\n\n\n@adapter(IScheduler, IUnregistered)\ndef handleUnregisteredSchedulerUtility(utility, event):\n try:\n path = traversing_api.getPath(utility)\n except:\n return\n\n process = _schedulers.get(path)\n if process is not None:\n process.terminate()\n process.join()\n logger.info('Stopped unregistered scheduler process %s with PID %d' % (process.name, process.pid))\n del _schedulers[path]\n return\n\n\ndef _deleteSchedulerHook(*args, **kw):\n \"\"\"After commit hook for scheduler deletion\"\"\"\n path = kw.get('scheduler_path')\n if path is not None:\n process = _schedulers.get(path)\n if process is not None:\n process.terminate()\n process.join()\n logger.info('Stopped deleted scheduler process %s with PID %d' % (process.name, process.pid))\n del _schedulers[path]\n return\n\n\n@adapter(IScheduler, IObjectRemovedEvent)\ndef handleDeletedScheduler(utility, event):\n transaction.get().addAfterCommitHook(_deleteSchedulerHook, kws={'scheduler_path': traversing_api.getPath(utility)})\n\n\n@adapter(ISchedulerTask, IObjectRemovedEvent)\ndef handleDeletedTask(task, event):\n \"\"\"Reset deleted tasks...\"\"\"\n task.reset()","sub_path":"pycfiles/ztfy.scheduler-0.5.2-py2.7/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":6625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"583429490","text":"class Difference:\n def __init__(self, a):\n self.__elements = a\n self.maximum=[]\n self.maximumDifference=0\n\n # Add your code here\n\n def computeDifference(self):\n for y in range(len(self.__elements)):\n for x in range(len(self.__elements)):\n b=self.__elements[y]-self.__elements[x]\n self.maximum.append(abs(b))\n self.maximumDifference=max(self.maximum)\n\n# End of Difference class\n\n_ = input()\na = [int(e) for e in input().split(' ')]\n\nd = Difference(a)\nd.computeDifference()\n\nprint(d.maximumDifference)","sub_path":"Day_14_Scope.py","file_name":"Day_14_Scope.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"437115023","text":"from .base import base_model\n\nclass moving_average_model(base_model):\n\t\n\tdef forecast(self, parameters, training_set, forecast_horison):\n\t\tlookback = parameters['lookback']\n\t\tlag = parameters['lag']\n\t\tforecasted_values = {}\n\t\tfor col in training_set:\n\t\t\tdata = list(training_set[col])\n\t\t\t\n\t\t\tbasic_arr = data[-lookback-lag:]\n\t\t\tfor x in range(0, forecast_horison):\n\t\t\t\tnext_val = sum(basic_arr[x-lookback-lag:x-lag])/lookback\n\t\t\t\tbasic_arr.append(next_val)\n\n\t\t\tforecasted_values[col] = basic_arr[lookback+ lag:]\n\n\t\treturn forecasted_values\n\n\tdef get_name(self):\n\t\treturn 'Moving average model'","sub_path":"framework/forecasting/moving_average_model.py","file_name":"moving_average_model.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"353994459","text":"import os\nimport requests\nimport json\nimport errno\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\n\nchrome_options = Options()\nchrome_options.add_argument(\"--headless\")\nchrome_options.binary_location = '/usr/bin/google-chrome'\n\ndef make_sure_path_exists(path):\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n\ndef request(driver):\n s = requests.Session()\n cookies = driver.get_cookies()\n for cookie in cookies:\n s.cookies.set(cookie['name'].encode(\"utf-8\").replace('\"', ''), cookie['value'].encode(\"utf-8\").replace('\"', ''))\n return s\n\ndef login(driver):\n login_url = \"https://www.familysearch.org/auth/familysearch/login?fhf=true&returnUrl=%2F&ldsauth=false\"\n driver.get(login_url)\n user_name = driver.find_element_by_name(\"userName\").send_keys('ing.pereira')\n password = driver.find_element_by_name(\"password\").send_keys('movilnet')\n driver.find_element_by_tag_name(\"form\").submit()\n\ndef get_image_id(list, index):\n return list[index].split('/')[-2]\n\ndef get_record_payload(list, index_image, catalog, folder):\n ark_image_id = get_image_id(list, index_image)\n return {\n \"type\": \"image-data\",\n \"args\": {\n \"imageURL\": \"https://www.familysearch.org/dz/v1/\" + ark_image_id,\n \"state\": {\n \"i\": str(index_image),\n \"cat\": catalog,\n \"imageOrFilmUrl\": \"/ark:/\" + folder + \"/\" + ark_image_id,\n \"catalogContext\": catalog,\n \"viewMode\": \"i\",\n \"selectedImageIndex\": index_image\n },\n \"locale\": \"en\"\n }\n }\n\ndef get_images_list(req, authToken, dgsNum, catalog):\n json_params = {\n \"type\": \"film-data\",\n \"args\": {\n \"dgsNum\": dgsNum,\n \"state\": {\n \"cat\": catalog,\n \"catalogContext\": catalog,\n \"viewMode\": \"i\",\n \"selectedImageIndex\": -1\n },\n \"locale\": \"en\",\n \"sessionId\": authToken,\n \"loggedIn\": True\n }\n }\n results = req.post(\n \"https://www.familysearch.org/search/filmdatainfo\",\n json = json_params,\n headers = {\n \"referer\": temp_url,\n \"authorization\": \"Bearer \" + authToken,\n \"origin\": \"https://www.familysearch.org\",\n \"accept\": \"application/json, application/json\",\n \"content-type\": \"application/json\"\n }\n )\n response = json.loads(results.content)\n list = response['images']\n return list\n\ndriver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', chrome_options=chrome_options)\ntemp_url = \"https://www.familysearch.org/ark:/61903/3:1:3Q9M-CSDK-YSS2-K\"\n\nlogin(driver)\n\ndriver.get(temp_url)\n\nwaitForRecordToLoad = WebDriverWait(driver, 10)\nwaitForRecordToLoad.until(expected_conditions.visibility_of_element_located((By.XPATH, \"//canvas\")))\n\nauthToken = driver.get_cookie(\"fssessionid\")[\"value\"]\nreq = request(driver)\n\ncatalog = \"990690\"\ndgsNum = \"007979779\"\nfolder = \"61903\"\nrecords_download_folder = os.getcwd() + '/' + dgsNum + \"_\" + catalog + \"_\" + folder\n\nmake_sure_path_exists(records_download_folder)\n\nlist = get_images_list(req, authToken, dgsNum, catalog)\n\nfor i in range(1036, 1182):\n print(\"Downloading record \" + str(i) + \" ...\")\n record_payload = get_record_payload(list, i-1, catalog, folder)\n record_results = req.post(\n \"https://www.familysearch.org/search/filmdatainfo\",\n json = record_payload,\n headers = {\n \"referer\": temp_url,\n \"authorization\": \"Bearer \" + authToken,\n \"origin\": \"https://www.familysearch.org\",\n \"accept\": \"application/json, application/json\",\n \"content-type\": \"application/json\"\n }\n )\n\n record = json.loads(record_results.content)\n\n url = record['meta']['links']['image-stream-image-dist']['href']\n download_file = records_download_folder + \"/\" + str(i) + \"_\" + get_image_id(list, i-1) + \".jpg\"\n image = req.get(url)\n\n with open(download_file, 'wb') as f:\n f.write(image.content)\n\ndriver.close()\n","sub_path":"family_search_records_downloader.py","file_name":"family_search_records_downloader.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"216076669","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Budget_window',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created', models.DateTimeField(editable=False)),\n ('modified', models.DateTimeField()),\n ('name', models.TextField()),\n ('open_date', models.DateTimeField()),\n ('close_date', models.DateTimeField()),\n ('current_year', models.DateTimeField()),\n ('prediction_year', models.DateTimeField()),\n ('by', models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"SchBerg/budget/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"83901499","text":"import numpy as np\nimport csv\nimport pandas\nimport json\n\n# Sean Delargy\n# TODO: track freethrows\n# TODO: handle dirty data - clean up\n\ndef intializeLineupInfo(lineup_df, teamToPlayer, playerToTeam, gameLineups):\n for (_, game, period, player, team, status) in lineup_df.itertuples():\n if team not in teamToPlayer:\n teamToPlayer[team] = set()\n teamToPlayer[team].add(player)\n \n if player not in playerToTeam:\n playerToTeam[player] = team\n\n if period != 0: \n game_period = game + \"_\" + str(period)\n else:\n game_period = game \n\n if game_period not in gameLineups:\n gameLineups[game_period] = set()\n gameLineups[game_period].add(player)\n convertSetToArray(teamToPlayer) \n convertSetToArray(gameLineups)\n lineupsSetUpCorrectly(lineup_df, teamToPlayer, playerToTeam, gameLineups)\n\n\ndef convertSetToArray(map):\n for curr in map:\n copy = map[curr]\n map[curr] = list(copy)\n\n\ndef lineupsSetUpCorrectly(lineup_df, teamToPlayer, playerToTeam, gameLineups):\n # 82 Games\n # 16 teams\n teams = lineup_df.Team_id.unique()\n players = lineup_df.Person_id.unique()\n assert len(players) == 15 * len(teams)\n assert len(players) == len(playerToTeam.keys()) \n assert len(teams) == len(teamToPlayer.keys())\n \n for team in teamToPlayer:\n assert len(teamToPlayer[team]) == 15\n for game in gameLineups.keys():\n assert len(gameLineups[game]) == 30 or len(gameLineups[game]) == 10 # 30 if for game, 10 if for period\n\n\ndef gameSetUpCorrectly(currentGame, teamOneLineup, teamTwoLineup, teamOne, teamTwo, playerToOffensiveRating, playerToDefensiveRating):\n # assert that the lengths are correct\n assert len(teamOneLineup) == 5\n assert len(teamTwoLineup) == 5\n for i in range(5):\n assert playerToTeam[teamOneLineup[i]] == teamOne\n assert playerToTeam[teamTwoLineup[i]] == teamTwo\n #assert len(playerToOffensiveRating.keys()) == 15\n #assert len(playerToDefensiveRating.keys()) == 15\n\n\ndef setLineups(currentGame, teamOne, period):\n teamOneLineup = []\n teamTwoLineup = []\n for player in gameLineups[currentGame + \"_\" + str(period)]:\n if playerToTeam[player] == teamOne:\n teamOneLineup.append(player)\n else:\n teamTwoLineup.append(player) \n assert len(teamOneLineup) == 5\n assert len(teamTwoLineup) == 5 \n return teamOneLineup, teamTwoLineup\n\n\ndef assignPoints(scoringTeam, scoredAgainstTeam, point_value, playerToOffensiveRating, playerDefensiveRating):\n for player in scoringTeam:\n stats = playerToOffensiveRating[player]\n updated = (stats[0] + point_value, stats[1] + 1)\n playerToOffensiveRating[player] = updated\n for player in scoredAgainstTeam:\n stats = playerToDefensiveRating[player]\n updated = (stats[0] + point_value, stats[1] + 1)\n playerToDefensiveRating[player] = updated\n\n\ndef initializeRatings(currentGame, gameLineups):\n playerToOffensiveRating = {}\n playerToDefensiveRating = {}\n for player in gameLineups[currentGame]:\n playerToOffensiveRating[player] = (0, 0) # points, possessions\n playerToDefensiveRating[player] = (0, 0)\n return playerToOffensiveRating, playerToDefensiveRating\n\n\n# Setup\ndf = pandas.read_csv('Play_by_Play.txt', sep=\"\\t\")\nplaybyplay_df = df.sort_values(by=['Game_id', 'Period', 'PC_Time', 'WC_Time', 'Event_Num'], ascending=[True, True, False, True, True])\nlineup_df = pandas.read_csv(\"Game_Lineup.txt\", sep=\"\\t\")\nevents_df = pandas.read_csv(\"Event_Codes.txt\", sep=\"\\t\")\n\n# intialize needed variables on game level\ncsvData = []\neventCounter = 0 # current event of game\ncurrentGame = 0\nteamOneLineup = [] \nteamTwoLineup = [] \ngameLineups = {} # map game_period --> players in game at start of period\nteamToPlayer = {} # map of teams to all players on team\nplayerToTeam = {} # map of player to its team\nskippedEvents = 0 # used to keep track of irregularities\nintializeLineupInfo(lineup_df, teamToPlayer, playerToTeam, gameLineups)\n# these will be used to keep track of the correct players to assign foul points to\nlastPlayLineupOne = []\nlastPlayLineupTwo = []\npointsUnassigned = False \n\nwhile eventCounter < playbyplay_df.shape[0]: # go through all events\n\n # intialize game information\n if currentGame != playbyplay_df[\"Game_id\"][eventCounter]:\n currentGame = playbyplay_df[\"Game_id\"][eventCounter]\n firstPlayer = gameLineups[currentGame][0]\n teamOne = playerToTeam[firstPlayer]\n teamOneLineup, teamTwoLineup = setLineups(currentGame, teamOne, 1)\n teamTwoPlayer = teamTwoLineup[0] \n teamTwo = playerToTeam[teamTwoPlayer]\n\n playerToOffensiveRating = {} # all players in game to their offensive rating\n playerToDefensiveRating = {} # all players in game to their defensive rating\n playerToOffensiveRating, playerToDefensiveRating = initializeRatings(currentGame, gameLineups)\n teamOnePossession = True\n currentPeriod = 1 \n eventCounter += 1 # no longer need start game event\n \n gameSetUpCorrectly(currentGame, teamOneLineup, teamTwoLineup, teamOne, teamTwo, playerToOffensiveRating, playerToDefensiveRating)\n\n # process all the events in current game \n while eventCounter < playbyplay_df.shape[0] and playbyplay_df[\"Game_id\"][eventCounter] == currentGame:\n if currentPeriod != playbyplay_df[\"Period\"][eventCounter]:\n currentPeriod = playbyplay_df[\"Period\"][eventCounter]\n teamOneLineup, teamTwoLineup = setLineups(currentGame, teamOne, currentPeriod) \n\n eventMessageType = playbyplay_df[\"Event_Msg_Type\"][eventCounter]\n # TODO: Implement fouls\n # My plan to ensure that foul shots are assigned to the correct players is to save the current lineups\n # on fouls (includine technicals) that will lead to foul shots. In addition to this there will be a boolean\n # indicating that the points from foul shots should go to the past saved lineups. A counter will be kept of how many \n # foul shots are expected to be assigned to the past lineup, that way if there is a technical after foul shots\n # there will be a way to know what should be assigned to the past lineup and when the program should go back\n # to using the current lineup. \n # TODO: analyze possession edge cases in play by play data \n if eventMessageType == 1: # made basket\n point_value = playbyplay_df[\"Option1\"][eventCounter] \n if teamOnePossession:\n assignPoints(teamOneLineup,teamTwoLineup, point_value, playerToOffensiveRating, playerToDefensiveRating)\n else:\n assignPoints(teamTwoLineup, teamOneLineup, point_value, playerToOffensiveRating, playerToDefensiveRating)\n teamOnePossession = not teamOnePossession \n elif eventMessageType == 4: # rebound\n teamRebound = playbyplay_df[\"Team_id\"][eventCounter] \n if teamRebound == teamOne and not teamOnePossession:\n assignPoints(teamTwoLineup, teamOneLineup, 0, playerToOffensiveRating, playerToDefensiveRating)\n teamOnePossession = not teamOnePossession\n elif teamRebound != teamOne and teamOnePossession:\n assignPoints(teamOneLineup, teamTwoLineup, 0, playerToOffensiveRating, playerToDefensiveRating)\n teamOnePossession = not teamOnePossession \n elif eventMessageType == 5 or eventMessageType == 13: # turnover / end of period\n if teamOnePossession:\n assignPoints(teamOneLineup, teamTwoLineup, 0, playerToOffensiveRating, playerToDefensiveRating)\n else:\n assignPoints(teamTwoLineup, teamOneLineup, 0, playerToOffensiveRating, playerToDefensiveRating)\n teamOnePossession = not teamOnePossession \n elif eventMessageType == 8: # substitution\n player1 = playbyplay_df[\"Person1\"][eventCounter] \n player2 = playbyplay_df[\"Person2\"][eventCounter]\n if pointsUnassigned:\n lastPlayLineupOne = teamOneLineup.copy()\n lastPlayLineupTwo = teamTwoLineup.copy()\n assert playerToTeam[player1] == playerToTeam[player2]\n team = playerToTeam[player1]\n if team == teamOne:\n if player1 not in teamOneLineup: # player can't be subbed out if not on court\n skippedEvents += 1 # keep track of this irregularity (or bug - need to look into)\n else:\n teamOneLineup.remove(player1)\n teamOneLineup.append(player2)\n else:\n if player1 not in teamTwoLineup: # player can't be subbed out if not on court\n skippedEvents += 1\n else:\n teamTwoLineup.remove(player1)\n teamTwoLineup.append(player2)\n assert len(teamOneLineup) == 5\n assert len(teamTwoLineup) == 5 \n eventCounter += 1\n\n # game finished -> process data into CSV\n for player in gameLineups[currentGame]:\n # need to get game, player, offensive, defensive\n offense = 0\n if playerToOffensiveRating[player][1] != 0:\n possessions = playerToOffensiveRating[player][1] \n points = playerToOffensiveRating[player][0]\n offense = points * 100 / possessions\n defense = 0\n if playerToDefensiveRating[player][1] != 0:\n possessions = playerToDefensiveRating[player][1] \n points = playerToDefensiveRating[player][0]\n defense = points * 100 / possessions\n newRow = [currentGame, player, offense, defense]\n csvData.append(newRow)\n\n\nwith open('SEATTLE_SUPERSONICS_Q1_BBALL.csv', 'w') as csvFile:\n writer = csv.writer(csvFile)\n writer.writerows(csvData)\ncsvFile.close()\n\n","sub_path":"calculateRatings.py","file_name":"calculateRatings.py","file_ext":"py","file_size_in_byte":10064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"583668851","text":"import pyPdf\n\ndef main():\n\tcontent = ''\n\tpath = r'c:\\Users\\Hao\\Downloads\\PayrollTimesheetProcedures.pdf'\n\tpdf = pyPdf.PdfFileReader(open(path, 'rb'))\n\tfor k in range(pdf.getNumPages()):\n\t\tcontent += pdf.getPage(k).extractText() + '\\n'\n\t#content = ' '.join(content.replace(u'\\xa0', ' ').strip().split())\n\topen(r'c:\\Users\\Hao\\Downloads\\Extracted_text.txt', 'w').writelines(content)\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"ScrapingPDF.py","file_name":"ScrapingPDF.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"518264819","text":"'''\n validation.py, an extension to validictory made to specifically deal\n with more python types and formats.\n'''\n\nfrom validator import SchemaValidator, validate\nfrom extended import ExtendedSchemaValidator\nfrom coercer import SchemaCoercer, ExtendedSchemaCoercer\n\n\ndef Either(*types, **kw):\n '''\n Example:\n Object(\n properties=dict(\n something=Either(\n Boolean(),\n Null,\n required=True\n )\n )\n )\n '''\n return dict(\n type=types,\n **kw\n )\n\n\nclass MetaSchemaElement(type):\n\n def __new__(cls, name, bases, dct):\n\n attrs = dct.get('attrs', [])\n\n def makeattr(attr):\n methodname = attr[0]\n realname = attr[0]\n default = None\n\n if len(attr) == 2:\n default = attr[1]\n\n if len(attr) == 3:\n default = attr[2]\n realname = attr[1]\n\n def method(self, val=default):\n res = self.copy()\n res[realname] = val\n return res\n\n method.__name__ = methodname\n return method\n\n for attr in attrs:\n dct[attr[0]] = makeattr(attr)\n\n return super(MetaSchemaElement, cls).__new__(cls, name, bases, dct)\n\n\nclass SchemaElement(dict):\n type = ''\n\n attrs = [\n ('dependencies', []),\n ('default',)\n ]\n\n __metaclass__ = MetaSchemaElement\n\n def __init__(self):\n self['type'] = self.type\n\n def __call__(self, *a, **kw):\n newobj = self.__class__(*a, **kw)\n\n for k, v in self.items():\n if not k in newobj:\n newobj[k] = v\n\n return newobj\n\n def copy(self):\n newobj = self.__class__()\n for k, v in self.items():\n newobj[k] = v\n return newobj\n\n @property\n def required(self):\n cp = self.copy()\n cp['required'] = True\n return cp\n\n @property\n def not_required(self):\n cp = self.copy()\n cp['required'] = False\n return cp\n\n @property\n def nullable(self):\n ''' Should be the last one to be called '''\n return dict(\n type=[self, {'type': 'null'}]\n )\n\n def _validate(self, data, validator_cls=SchemaValidator,\n format_validators=None, required_by_default=False,\n blank_by_default=False, ignore_required=False):\n return validate(\n data,\n self,\n validator_cls=validator_cls,\n format_validators=format_validators,\n required_by_default=required_by_default,\n blank_by_default=blank_by_default,\n ignore_required=ignore_required\n )\n\n def validate(self, data, **kw):\n return self._validate(data, **kw)\n\n def coerce(self, data, validator_cls=SchemaCoercer, **kw):\n return self._validate(data, validator_cls=validator_cls, **kw)\n\n\nclass _Object(SchemaElement):\n type = 'object'\n\n attrs = [\n ('properties', {}),\n ('patterns', 'patternProperties', {}),\n ('additionalProperties', 'additionalProperties', True),\n ('min_props', 'minProperties', 0),\n ('max_props', 'maxProperties', 0),\n ]\n\n def __init__(self, *propdicts, **kw):\n super(_Object, self).__init__()\n self['properties'] = {}\n for propdict in propdicts:\n self['properties'].update(propdict)\n self['properties'].update(kw)\n\n def pattern(self, regexp, type):\n if not 'patternProperties' in self:\n self['patternProperties'] = {}\n self['patternProperties'][regexp] = type\n return self\n\n def require_either(self, *a):\n self['requireEither'] = a\n return self\n\n def merge(self, other):\n for k, v in other.get('properties', {}).items():\n self['properties'][k] = v\n\n if other.get('patternProperties', None) and not 'patternProperties' in self:\n self['patternProperties'] = {}\n for k, v in other.get('patternProperties', {}).items():\n self['patternProperties'][k] = v\n return self\n\n\nclass _StrictObject(_Object):\n ''' A variant of Object that disallows additional properties.\n '''\n\n def __init__(self, **kw):\n super(_StrictObject, self).__init__(**kw)\n self['additionalProperties'] = False\n\n\nclass _Array(SchemaElement):\n type = 'array'\n\n attrs = (\n ('min_items', 'minItems', 0),\n ('max_items', 'maxItems', 0),\n ('additional_items', 'additionalItems', True),\n ('unique_items', 'uniqueItems', True)\n )\n\n def __init__(self, items=None):\n self['type'] = 'array'\n if items:\n self['items'] = items\n\n\nclass _Number(SchemaElement):\n type = 'number'\n\n attrs = (\n ('min', 'minimum'),\n ('max', 'maximum'),\n ('divisible_by',),\n ('excl_min', 'exclusiveMinimum'),\n ('excl_max', 'exclusiveMaximum'),\n )\n\n\nclass _Integer(_Number):\n type = 'integer'\n\n\nclass _Boolean(SchemaElement):\n type = 'boolean'\n\n\nclass _Datetime(SchemaElement):\n type = 'datetime'\n\n\nclass _String(SchemaElement):\n type = 'string'\n\n attrs = (\n ('min_length', 'minLength', 0),\n ('max_length', 'maxLength', 0),\n ('format',),\n ('pattern',),\n )\n\n def enum(self, *args):\n cp = self.copy()\n enum = []\n for a in args:\n if isinstance(a, (tuple, list)):\n enum += a\n else:\n enum.append(a)\n cp['enum'] = enum\n return cp\n\n @property\n def allow_blank(self):\n cp = self.copy()\n cp['blank'] = True\n return cp\n\n\nclass _Any(SchemaElement):\n type = 'any'\n\n# Any is meant to be used as is, without instanciating it.\nAny = _Any()\nObject = _Object()\nStrictObject = _StrictObject()\nArray = _Array()\nNumber = _Number()\nInteger = _Integer()\nBoolean = _Boolean()\nString = _String()\nDatetime = _Datetime()\n","sub_path":"validictory/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":6053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"635424904","text":"# complexity O(len(coins)^ amount) if coins have 1 in it -> horrible\n# space Complexity : O(amount) if coins have 1 in it\n\n\nclass Solution:\n\n def minCoins(self, coins, amount):\n if(amount < 0):\n return -1\n if(amount == 0):\n return 0\n min_value = 9999999\n for coin in coins:\n minSubCoins = self.minCoins(coins, amount - coin)\n if(minSubCoins != -1):\n min_value = min(min_value, minSubCoins)\n\n if(min_value == 9999999):\n return -1\n else:\n return min_value + 1\n\n def coinChange(self, coins: List[int], amount: int) -> int:\n return self.minCoins(coins, amount)\n\n# since this problem have optimal SubStructures and have operlapping subproblems as well\n# Hence we can use extra space ior say memCache to store some results\n# DP Approach: TOP-DOWN APPROACH\n# Time Complexity = O(amount*len(coins))\n# space complexity = O(amount) + recusion stack space\n\n\nclass Solution:\n def minCoins(self, coins, amount, dp):\n if(amount < 0):\n return -1\n\n if(amount == 0):\n return 0\n\n if(dp[amount] != -2):\n return dp[amount]\n\n min_value = 9999999\n for coin in coins:\n minSubCoins = self.minCoins(coins, amount - coin, dp)\n if(minSubCoins != -1):\n min_value = min(min_value, minSubCoins)\n if(min_value == 9999999):\n dp[amount] = -1\n return dp[amount]\n else:\n dp[amount] = min_value + 1\n return dp[amount]\n\n def coinChange(self, coins: List[int], amount: int) -> int:\n dp = [-2] * (amount + 1)\n dp[0] = 0\n self.minCoins(coins, amount, dp)\n return dp[amount]\n\n\n# DP Approach: Bottom-UP APPROACH\n# Space O(amount)\n# Time O(amount*len(coins))\n\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n dp = [-1] * (amount + 1)\n dp[0] = 0\n\n for i in range(1, amount+1):\n min_value = 999999\n for coin in coins:\n if(i - coin >= 0 and dp[i - coin] != -1):\n min_value = min(min_value, dp[i - coin])\n\n if(min_value == 999999):\n dp[i] = -1\n else:\n dp[i] = min_value + 1\n return dp[amount]\n","sub_path":"leetcode/practise/322.coinChange.py","file_name":"322.coinChange.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"87129088","text":"# SPDX-FileCopyrightText: 2021 Niko Rodriguez\n#\n# SPDX-License-Identifier: Unlicense\nfrom utime import sleep\nfrom machine import I2C\nfrom i2c import BNO08X_I2C\nfrom BNO080 import (\n BNO_REPORT_ACCELEROMETER,\n BNO_REPORT_GYROSCOPE,\n BNO_REPORT_MAGNETOMETER,\n BNO_REPORT_ROTATION_VECTOR,\n)\n\n\ni2c_obj = I2C(1, freq=400000)\n#bno = BNO08X_I2C(i2c_obj, debug=True)\nbno = BNO08X_I2C(i2c_obj)\n\n\nbno.enable_feature(BNO_REPORT_ACCELEROMETER)\nbno.enable_feature(BNO_REPORT_GYROSCOPE)\nbno.enable_feature(BNO_REPORT_MAGNETOMETER)\nbno.enable_feature(BNO_REPORT_ROTATION_VECTOR)\n\nwhile True:\n \n sleep(1)\n print(\"Acceleration:\")\n accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member\n print(\"X: %0.6f Y: %0.6f Z: %0.6f m/s^2\" % (accel_x, accel_y, accel_z))\n print(\"\")\n\n print(\"Gyro:\")\n gyro_x, gyro_y, gyro_z = bno.gyro # pylint:disable=no-member\n print(\"X: %0.6f Y: %0.6f Z: %0.6f rads/s\" % (gyro_x, gyro_y, gyro_z))\n print(\"\")\n\n print(\"Magnetometer:\")\n mag_x, mag_y, mag_z = bno.magnetic # pylint:disable=no-member\n print(\"X: %0.6f Y: %0.6f Z: %0.6f uT\" % (mag_x, mag_y, mag_z))\n print(\"\")\n \n sleep(1)\n #print(\"Rotation Vector Quaternion:\")\n quat_i, quat_j, quat_k, quat_real = bno.quaternion # pylint:disable=no-member\n print(\n \"%0.2f,%0.2f,%0.2f,%0.2f\" % (quat_real,quat_i, quat_j, quat_k)\n )","sub_path":"examples/bno08x_simpletest.py","file_name":"bno08x_simpletest.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"103915003","text":"#!/usr/bin/env python\n# encoding: utf-8\nimport re\nfrom lxml import etree\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\nfrom scrapy.utils.project import get_project_settings\nfrom scrapy_redis.spiders import RedisSpider\nfrom sina.items import SearchPageItem\nfrom sina.spiders.utils import time_fix, extract_weibo_content, extract_comment_content\nimport time\nfrom datetime import datetime as dt\nfrom sina.spiders.utils import get_random_proxy\n\n\nclass WeiboSpider(RedisSpider):\n name = \"weibo_search_timeline_spider\"\n redis_key = \"weibo_search_timeline_spider:start_urls\"\n all_page_num = 0\n current_page = 0\n weibo_baseurl = \"https://weibo.cn\"\n\n def __init__(self, *a, **kw):\n super(WeiboSpider, self).__init__(*a, **kw)\n settings=get_project_settings()\n time_start_str = settings.get('TIME_START')\n self.time_start_from = dt.strptime(time_start_str, \"%Y-%m-%d %H:%M\")\n self.use_proxy = settings.get('PROXY_BASEURL')\n\n def time_flag_compare(self, timeString):\n print(\"[DEBUG] Created Time String: \"+timeString)\n time = dt.strptime(timeString,'%Y-%m-%d %H:%M')\n if self.time_start_from > time:\n print(\"[INFO] Hit Start Time Criteria\")\n return 1\n else:\n return 0\n\n def get_base_url(self):\n if self.use_proxy:\n return get_random_proxy()\n else:\n return \"https://weibo.cn\"\n\n # Default Start\n def parse(self, response):\n current_page = response.url.split(\"&\")[-1].split(\"=\")[-1]\n current_page = int(current_page)\n #print(\"[DEBUG] current_page:\" + str(current_page))\n print(\"[DEBUG] response.url:\" + str(response.url))\n\n selector = Selector(response)\n searchpage_item = SearchPageItem()\n searchpage_item['page_url'] = re.sub(\"https://.*?/fireprox\",self.weibo_baseurl,response.url)\n searchpage_item['page_raw'] = selector.extract() # get raw page content \n searchpage_item['search_key'] = searchpage_item['page_url'].split(\"&\")[0].split(\"=\")[-1]\n searchpage_item['sort_setting'] = searchpage_item['page_url'].split(\"&\")[1].split(\"=\")[-1]\n searchpage_item['filter_setting'] = searchpage_item['page_url'].split(\"&\")[2].split(\"=\")[-1]\n searchpage_item['crawl_time_utc'] = dt.utcnow()\n yield searchpage_item\n\n # print(\"[DEBUG] page content:\" + searchpage_item['page_raw'])\n # print(\"[DEBUG] original url:\" + searchpage_item['page_url'])\n\n tree_node = etree.HTML(response.body)\n tweet_nodes = tree_node.xpath('//div[@class=\"c\" and @id]')\n if len(tweet_nodes) == 0 and current_page != 1:\n if response.meta[\"empty_page_count\"] > 0:\n empty_page_count = response.meta[\"empty_page_count\"] + 1\n else:\n empty_page_count = 1\n else:\n empty_page_count = 0\n\n \n if empty_page_count != 3:\n next_page = current_page + 1\n page_url = re.sub(\"https://.*?/fireprox\",self.get_base_url(),response.url)\n page_url = page_url.replace('page='+str(current_page), 'page={}'.format(next_page))\n yield Request(page_url, self.parse, dont_filter=True, meta={'empty_page_count': empty_page_count},priority=1)\n \n\nif __name__ == \"__main__\":\n process = CrawlerProcess(get_project_settings())\n process.crawl('weibo_search_timeline_spider')\n process.start()\n print(\"[INFO] Parser Started\")","sub_path":"crawl_search/sina/spiders/weibo_spider.py","file_name":"weibo_spider.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"310214034","text":"# https://medium.com/@devnag/generative-adversarial-networks-gans-in-50-lines-of-code-pytorch-e81b79659e3f\n# https://github.com/devnag/pytorch-generative-adversarial-networks/blob/master/gan_pytorch.py\n# (cuda) https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/\n# 02-intermediate/convolutional_neural_network/main-gpu.py\n# https://github.com/eriklindernoren/PyTorch-GAN/blob/master/implementations/gan/gan.py\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom tqdm import tqdm\nimport pandas as pd\nfrom preprocessing import plot\nfrom preprocessing import preprocessing as pre\n\n\ndef plot_gan_result(data, gen_data):\n origin_data = pd.DataFrame(data.data.numpy())\n origin_data['class'] = 1\n generated_data = pd.DataFrame(np.asarray(gen_data.data))\n generated_data['class'] = 0\n combined_data = origin_data.append(generated_data)\n plt.scatter(combined_data.iloc[:, 0], combined_data.iloc[:, 1], s=100, marker='*', c=combined_data['class'])\n # plt.show()\n\n\ndef generator(layers_):\n legos = []\n for idx in range(len(layers_) - 1):\n in_n = layers_[idx]\n out_n = layers_[idx + 1]\n\n # linear sum\n legos.append(nn.Linear(in_n, out_n))\n\n if idx != (len(layers_) - 2): # range: -1 & in_n: -1, therefore: -2\n # act. func.\n legos.append(nn.Dropout(p=0.5))\n legos.append(nn.BatchNorm1d(out_n))\n legos.append(nn.LeakyReLU(0.2))\n\n # output layer\n # legos.append(nn.Tanh())\n\n _model = nn.Sequential(*legos)\n return _model\n\n\ndef discriminator(layers_):\n legos = []\n for idx in range(len(layers_) - 1):\n in_n = layers_[idx]\n out_n = layers_[idx + 1]\n\n # linear sum\n legos.append(nn.Linear(in_n, out_n))\n\n if idx != (len(layers_) - 2): # range: -1 & in_n: -1, therefore: -2\n # act. func.\n legos.append(nn.Dropout(p=0))\n legos.append(nn.BatchNorm1d(out_n))\n legos.append(nn.LeakyReLU(0.2))\n\n # output layer\n legos.append(nn.Sigmoid())\n\n _model = nn.Sequential(*legos)\n return _model\n\n\ndef print_metric(d_model, real_data_, gen_data_):\n print(\"\\n\\nD prob (on real data): \", round(torch.mean(d_model(real_data_).data), 3))\n print(\"D prob (on gen data): \", round(torch.mean(d_model(gen_data_).data), 3))\n\n\nif __name__ == \"__main__\":\n # --- data --- #\n # 1) normal: unimodal\n n_row = 3000\n dim = 2\n # data = torch.randn([n_row, dim])\n # data = Variable(data, requires_grad=False).type(torch.FloatTensor)\n\n data = pre.get_normal_data(mu_=0, sigma_=0.5, n_=int(n_row), dim_=dim)\n data, scaler = pre.scale_minus1_to_1(data_=data)\n data = Variable(torch.from_numpy(data), requires_grad=False).type(torch.FloatTensor)\n # todo: scale data\n\n # --- generator & discriminator --- #\n g_input_size = 2\n G = generator([g_input_size, 10, 10, 2])\n D = discriminator([2, 10, 10, 1])\n\n # --- optimizer --- #\n learning_rate = 0.0003\n d_optimizer = optim.Adam(D.parameters(), lr=learning_rate, weight_decay=0.001)\n g_optimizer = optim.Adam(G.parameters(), lr=learning_rate)\n\n # --- parameters --- #\n epochs, d_epochs, g_epochs = 100, 10, 1\n n_row = data.size()[0]\n total_batch = 10\n batch_size = int(n_row / total_batch)\n\n if torch.cuda.is_available():\n D.cuda()\n G.cuda()\n\n d_probs = [None for _ in range(epochs)]\n g_probs = [None for _ in range(epochs)]\n\n for epoch in tqdm(range(epochs)):\n data = data[np.random.choice(n_row, size=n_row, replace=False), :] # shuffle\n\n for d_epoch in range(d_epochs):\n for batch_idx in range(total_batch):\n # make generated data\n z_noise = torch.randn([batch_size, dim])\n z_noise = Variable(z_noise, requires_grad=False).type(torch.FloatTensor).cuda()\n gen_data = G(z_noise)\n real_data = data[(batch_size * batch_idx):(batch_size * (batch_idx+1)), :]\n real_data = real_data.cuda()\n\n d_error = (1/2)*((D(real_data)-1)**2) + (1/2)*((D(gen_data)-0)**2)\n d_error = torch.mean(d_error)\n\n D.zero_grad()\n d_error.backward()\n d_optimizer.step()\n\n for g_epoch in range(g_epochs):\n for batch_idx in range(total_batch):\n # make generated data\n z_noise = torch.randn([batch_size, dim])\n z_noise = Variable(z_noise, requires_grad=False).type(torch.FloatTensor).cuda()\n gen_data = G(z_noise)\n\n g_error_tmp = (1/2)*((D(gen_data)-1)**2)\n g_error = torch.mean(g_error_tmp)\n\n G.zero_grad()\n D.zero_grad()\n g_error.backward()\n g_optimizer.step()\n\n if epoch % 10 == 0:\n print_metric(D, real_data, gen_data)\n print(\"\\n\\nD prob: \", round(torch.mean(D(real_data).data), 3))\n print(\"G prob: \", round(torch.mean(D(gen_data).data), 3))\n\n d_probs[epoch] = round(torch.mean(D(real_data).data), 3)\n g_probs[epoch] = round(torch.mean(D(gen_data).data), 3)\n\n\n# --- plot --- #\nplt.plot(d_probs, 'r')\nplt.plot(g_probs, 'b')\nplt.show()\n\nplot_gan_result(data, gen_data)\nplt.show()\n\nplot.plot_gan_d_boundary(D, n=10000, min_=-10, max_=10, is_prob=True)\nz_noise = torch.randn([n_row, dim])\nz_noise = Variable(z_noise, requires_grad=False).type(torch.FloatTensor).cuda()\ngen_data = G(z_noise)\nplot.plot_gan_result(data, gen_data)\nplt.show()\n\n","sub_path":"GAN/LSGAN_test_gaussian.py","file_name":"LSGAN_test_gaussian.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"149474528","text":"from rest_test_generation import rest_types\n\nMAX_STRING_LENGTH = 10**9\n\ndef make_test_vals(node):\n \"\"\"\n Makes test values for leaves, tests the range limits\n \"\"\"\n n_type = rest_types(node.type)\n vals = []\n set_default(node, vals)\n if n_type == 'string':\n set_length_vals(node, vals)\n elif n_type == 'int':\n set_range_vals(node, vals)\n elif n_type == 'bool':\n vals.extend([False, True])\n elif n_type == 'enum':\n vals.extend( node.enumeration_list )\n\n return vals\n\ndef make_test_vals_fail(node):\n \"\"\"\n Makes failing test values for leaves, tests the range limits\n \"\"\"\n n_type = rest_types(node.type)\n vals = []\n if n_type == 'string':\n set_length_vals_fail(node, vals)\n elif n_type == 'int':\n set_range_vals_fail(node, vals)\n elif n_type == 'bool':\n pass\n elif n_type == 'enum':\n set_range_vals_fail(node, vals)\n\n return vals\n\ndef make_test_vals_field(node):\n \"\"\"\n Makes test values for fields, tests the range limits\n \"\"\"\n vals = []\n if node.leaf_type == 'leaf_list':\n vals = make_test_vals_list(node)\n elif node.leaf_type == 'leaf':\n vals = make_test_vals(node)\n\n return vals\n\ndef make_test_vals_fail_field(node):\n \"\"\"\n Makes failing test values for fields, tests the range limits\n \"\"\"\n vals = []\n if node.leaf_type == 'leaf_list':\n vals = make_test_vals_fail_list(node)\n elif node.leaf_type == 'leaf':\n vals = make_test_vals_fail(node)\n\n return vals\n\ndef make_test_vals_list(node):\n \"\"\"\n Makes test values for leaf lists, tests the range limits\n \"\"\"\n vals = []\n for el in xrange(2):\n vals.append(make_test_vals(node))\n return vals\n\ndef make_test_vals_fail_list(node):\n \"\"\"\n Makes failing test values for leaf lists, tests the range limits\n \"\"\"\n vals = []\n for el in xrange(2):\n vals.append(make_test_vals_fail(node))\n return vals\n\ndef set_default(node, vals):\n \"\"\"\n Adds the default value to field. Do not use on failing values\n \"\"\"\n if node.default != None and rest_types(node.type) != 'bool':\n vals.append( node.default )\n\ndef set_range_vals(node, vals):\n \"\"\"\n Sets values to test ranges for nodes using attribute range\n \"\"\"\n for l_bound, u_bound in get_limits(node.range.getRangeList()):\n vals.extend([l_bound, u_bound])\n\ndef set_range_vals_fail(node, vals):\n \"\"\"\n Sets failing values to test ranges for nodes using attribute range\n \"\"\"\n for l_bound, u_bound in get_limits(node.range.getRangeList()):\n vals.extend([l_bound-1, u_bound+1])\n\ndef set_length_vals(node, vals):\n \"\"\"\n Sets values to test ranges for nodes using attribute length\n \"\"\"\n if node.length:\n lim_list = node.length.getRangeList()\n for l_bound, u_bound in get_limits(node.length.getRangeList()):\n vals.append(\"l\" * l_bound)\n if u_bound < MAX_STRING_LENGTH:\n vals.append(\"u\" * u_bound)\n else:\n vals.append(\"teststring\")\n else:\n vals.append(\"teststring\")\n\ndef set_length_vals_fail(node, vals):\n \"\"\"\n Sets failing values to test ranges for nodes using attribute length\n \"\"\"\n if node.length:\n lim_list = node.length.getRangeList()\n\n for l_bound, u_bound in get_limits(node.length.getRangeList()):\n if l_bound > 0:\n vals.append(\"l\" * (l_bound - 1))\n if u_bound < MAX_STRING_LENGTH:\n vals.append(\"u\" * (u_bound + 1))\n\ndef get_limits(limit_list):\n \"\"\"\n Returns a list of range restrictions in reduced format\n \"\"\"\n def make_bounds(range_set):\n \"\"\"This function turns ranges of 1 element into two\"\"\"\n if len(range_set) == 1:\n return range_set ++ range_set\n return range_set\n\n reduced = reduce_lim_list(limit_list)\n return map(make_bounds, reduced)\n\ndef is_in_range(val, range_list):\n for range_set in range_list:\n l_lim = range_set[0]\n u_lim = range_set[-1]\n if val == l_lim or val == u_lim or val in range(l_lim, u_lim):\n return True\n return False\n\ndef reduce_lim_list(lim_list):\n \"\"\"\n This function reduces the limit list to a normalized state so we can make assumptions\n Essentially it reduces this behaviour to simplest form:\n range: 0 | 1..100; -> range: 0..100;\n In this way, we can assume that the range edges are 1 away from being invalid\n \"\"\"\n def recurse_sort_reduce(lim_list):\n s_list = sorted(lim_list, key=lambda el: el[0])\n return recurse_reduce(s_list)\n\n def recurse_reduce(lim_list):\n new_el = None\n for a, b in zip(lim_list, lim_list[1:]):\n if a[0] == b[0] or a[0] + 1 == b[0]:\n new_el = (a[0], max(a[-1], b[-1]))\n elif b[0] <= a[-1]:\n new_el = (a[0], max(b[-1], a[-1]))\n\n if new_el:\n lim_list.remove(a)\n lim_list.remove(b)\n lim_list.append(new_el)\n return recurse_sort_reduce(lim_list)\n\n return lim_list\n\n lim_list = map(list, lim_list)\n return recurse_sort_reduce( lim_list )\n\n","sub_path":"env/lib/python2.7/site-packages/rest_test/make_test_values.py","file_name":"make_test_values.py","file_ext":"py","file_size_in_byte":5215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"638045130","text":"T = int(input())\nfor t in range(T):\n N = int(input())\n if N % 9 == 2 or N % 9 == 3:\n print('Sailaja')\n else:\n print('Supraja')\n \n'''\nInput:\n5\n\nOutput:\nSupraja\n\n\nSample - 2\n\nInput:\n3\n\nOutput:\nSailaja\n\n'''\n","sub_path":"Contests/Others/COUT-2K18/p6.py","file_name":"p6.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"455774947","text":"import cpu\nimport preprocess\nraml=cpu.raml #nly here for db show up in VAriables pane purposes keep it tho\nAcc=cpu.Acc\nPRGMC=cpu.PRGMC\nrom=preprocess.rom\nstack=cpu.stack\n\n\n\nwhile PRGMC255:\n f.writelines(\"Illegal Immediate Value \"+\"at line \"+str(count)+\"\\n\")\n exit()\n\n f.writelines(instructions[input_arr[0]][\"opcode\"]+register[input_arr[1]]+'{0:08b}'.format(int(input_arr[2][1:]))+\"\\n\")\n \n elif instructions[input_arr[0]][\"type\"] == \"C\":\n if len(input_arr)!=3:\n f.writelines(\"Wrong Syntax for this type of instruction \"+\"at line \"+str(count)+\"\\n\")\n exit()\n if input_arr[1] or input_arr[2] not in register:\n f.writelines(\"Typo in Register Name \"+\"at line\"+str(count)+\"\\n\")\n exit()\n\n f.writelines(instructions[input_arr[0]][\"opcode\"]+\"00000\"+register[input_arr[1]]+register[input_arr[2]]+\"\\n\")\n elif instructions[input_arr[0]][\"type\"] == \"D\":\n if len(input_arr)!=3:\n f.writelines(\"Wrong Syntax for this type of instruction \"+\"at line \"+str(count)+\"\\n\")\n exit()\n if input_arr[2] not in variables:\n f.writelines(\"Use of Undefined Variable \"+\"at line \"+count+\"\\n\")\n exit()\n if input_arr[1] not in register:\n f.writelines(\"Typo in Register Name \"+\"at line \"+count+\"\\n\")\n exit()\n f.writelines(instructions[input_arr[0]][\"opcode\"]+register[input_arr[1]]+'{0:08b}'.format((finalcount-len(variables))+variables[input_arr[2]])+\"\\n\")\n elif instructions[input_arr[0]][\"type\"] == \"E\":\n if len(input_arr)!=2:\n f.writelines(\"Wrong Syntax for this type of instruction \"+\"at line \"+str(count)+\"\\n\")\n exit()\n if input_arr[2] not in variables:\n f.writelines(\"Use of Undefined Variable \"+\"at line \"+str(count)+\"\\n\")\n exit()\n if input_arr[2] not in labels:\n f.writelines(\"Use of Undefined Labels \"+\"at line \"+str(count)+\"\\n\")\n exit()\n f.writelines(instructions[input_arr[0]][\"opcode\"]+\"000\"+input_arr[1]+\"\\n\")\n\n elif instructions[input_arr[0]][\"type\"] == \"F\":\n \n if len(input_arr)!=1:\n f.writelines(\"Wrong Syntax for this type of instruction \"+\"at line \"+str(count)+\"\\n\")\n exit()\n\n if count != finalcount:\n f.writelines(\"hlt not being used as last instruction \"+\"at line \"+str(count)+\"\\n\")\n exit()\n\n f.writelines(instructions[input_arr[0]][\"opcode\"]+\"0\"*11+\"\\n\")\n \n \n else:\n f.writelines(\"Typos in Instruction name \"+\"at line \"+str(count)+\"\\n\")\n exit()\n \n \n if input_arr[0] not in instructions and input_arr[0] != \"var\" and input_arr[0][:-1]!=\":\" :\n f.writelines(\"General Syntax Error \"+\"at line \"+str(count)+\"\\n\")\n exit()\n\n \n \n\n# Assembler's function\n\n# Code to read file from EOD Line wise.\ndef main():\n finalcount = 0 #Size of File Line Wise\n count = 0\n with open('Simple-Assembler/stdin.txt' , 'r') as f1:\n for line in f1:\n finalcount += 1\n flag1 = False\n flag2 = False \n with open('Simple-Assembler/stdin.txt', 'r') as f1:\n for line in f1:\n if line == '': # If empty string is read then stop the loop\n break\n count+=1\n assembler(line,count,finalcount,flag1,flag2) # perform some operation(s) on given string\n\nif __name__ == '__main__':\n\tmain()\n\n\n\n\n ","sub_path":"Simple-Assembler/assembler.py","file_name":"assembler.py","file_ext":"py","file_size_in_byte":7777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"143379205","text":"import json\n\nimport requests\nfrom braces.views import CsrfExemptMixin\nfrom django.http import HttpResponse\n\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.views import APIView\nimport pymongo\nimport datetime\n\nimport pandas as pd\nimport datetime\nfrom sklearn.ensemble import RandomForestClassifier\n\ndb_address = \"Your MongoDB Address\"\nFCM_Key= 'Your FCM_key'\n\n\nclass SensorView(CsrfExemptMixin, APIView):\n authentication_classes = []\n permission_classes = [AllowAny]\n\n def post(self, request):\n client = pymongo.MongoClient(db_address)\n db = client.IoT_DB\n save_Sensor_DB = db.Sensor\n ML_DB = db.ML_DB\n test = json.loads(request.data)\n\n datetime_convert = datetime.datetime.strptime(test['cur_time'], '%Y-%m-%d %H:%M:%S')\n test['cur_time'] = datetime_convert.replace(microsecond=0)\n\n # 온도저장\n save_Sensor_DB.insert_one(test)\n\n new_dict = dict()\n\n #머신러닝 데이터 저장\n finding_ML_data = ML_DB.find_one({'HW_ID': str(test['serial'])})\n if bool(finding_ML_data):\n\n print(\"not empty\")\n finding_ML_data['count'] = (finding_ML_data['count'] +1) % 3\n test.pop('_id')\n finding_ML_data['data'].append(test)\n if finding_ML_data['count'] == 0:\n call_ML(finding_ML_data)\n new_list = list()\n finding_ML_data['data'] = new_list\n ML_DB.update({\"HW_ID\": finding_ML_data['HW_ID']},\n {\n '$set': {\n 'data' : finding_ML_data['data'],\n 'count' : finding_ML_data['count'],\n }\n }\n ,upsert = False, multi = False)\n\n else:\n print(\"empty\")\n new_list = list()\n test.pop('_id')\n new_list.append(test)\n\n new_dict['HW_ID'] = str(test['serial'])\n new_dict['count'] = 1\n new_dict['data'] = new_list\n ML_DB.insert_one(new_dict)\n\n #IoT 온습도 변화정보 라즈베리파이 전송\n matching = db.IoT_Device\n finding = matching.find_one({\"HW_ID\" : str(test['serial'])})\n response = {'temp' : float(finding['SET_TEMP']), 'hum' : float(finding['SET_HUM']), 'connect' : 1}\n json_response = json.dumps(response)\n\n client.close()\n return HttpResponse(json_response, status=200)\n\n\ndef call_ML(ML_data):\n client = pymongo.MongoClient(db_address)\n db = client.IoT_DB\n USER_matching = db.User_Room_Matching\n FCM_key_matching = db.FCM_key\n\n train = pd.read_csv('./train_nt6.csv')\n test0 = pd.DataFrame(ML_data['data'][0], index = [0])\n test1 = pd.DataFrame(ML_data['data'][1], index = [1])\n test2 = pd.DataFrame(ML_data['data'][2], index = [2])\n resutl1 = test0.append(test1)\n test = resutl1.append(test2)\n test_time = test.sort_values(by=['cur_time'], axis=0)\n\n idx1 = test_time[(test_time['temp_max'] > 50) | (test_time['temp_min'] < -20)].index\n test_time = test_time.drop(idx1)\n idx2 = test_time[(test_time['hum_max'] > 100) | (test_time['hum_min'] < 0)].index\n test_time = test_time.drop(idx2)\n\n num = test_time.shape[0]\n test_time = test_time.reindex(range(num), method='ffill')\n\n f = open(\"test14p.csv\", \"w\")\n f.write('temp_avg_gap')\n f.write(\",\")\n f.write('hum_avg_gap')\n f.write(\",\")\n f.write('temp_max_min')\n f.write(\",\")\n f.write('temp_min_max')\n f.write(\",\")\n f.write('hum_max_min')\n f.write(\",\")\n f.write('hum_min_max')\n f.write(\",\")\n f.write('status')\n f.write(\"\\n\")\n for i in range(test_time.shape[0] - 1):\n if test_time['status'][i] != 22:\n if test_time['status'][i + 1] == test_time['status'][i] and test_time['serial'][i + 1] == test_time['serial'][i]:\n data = test_time['cur_time'][i + 1] - test_time['cur_time'][i]\n res = round(data.seconds + data.days * 24 * 3600)\n print(\"res = \",res)\n if res < 100:\n print(\"4\")\n f.write(str(round(test_time['temp_avg'][i + 1] - test_time['temp_avg'][i], 2)))\n f.write(\",\")\n f.write(str(round(test_time['hum_avg'][i + 1] - test_time['hum_avg'][i], 2)))\n f.write(\",\")\n f.write(str(round(test_time['temp_max'][i + 1] - test_time['temp_min'][i], 2)))\n f.write(\",\")\n f.write(str(round(test_time['temp_min'][i + 1] - test_time['temp_max'][i], 2)))\n f.write(\",\")\n f.write(str(round(test_time['hum_max'][i + 1] - test_time['hum_min'][i], 2)))\n f.write(\",\")\n f.write(str(round(test_time['hum_min'][i + 1] - test_time['hum_max'][i], 2)))\n f.write(\",\")\n f.write(str(test_time['status'][i]))\n f.write(\"\\n\")\n f.close()\n\n test = pd.read_csv('./test14p.csv')\n\n train_data = train.drop('work', axis=1)\n target = train[\"work\"]\n clf = RandomForestClassifier(n_estimators=7)\n clf.fit(train_data, target)\n\n\n test_data = test.copy()\n\n if (test_data.shape[0] < 2):\n return 0\n\n predict = clf.predict(test_data)\n result = pd.DataFrame({\n 'status': test['status'],\n 'work': predict\n })\n print(result)\n result.to_csv('result_RF_14.csv', index=False)\n result_RF = pd.read_csv('result_RF_14.csv')\n print(result_RF)\n\n for i in range(0, result_RF.shape[0] - 1, 2):\n if result_RF['status'][i] == result_RF['status'][i + 1]:\n if (result_RF['work'][i] | result_RF['work'][i + 1]) == 0:\n print(\"ERROR OCCUR in status \", result_RF['status'][i])\n print(result_RF['work'][i])\n print(result_RF['work'][i + 1])\n print(i)\n #DB에서 HW_ID를 바탕으로 user id 를 검색\n #DB 의 FCM_key에는 USER_ID와 key 값만있으므로 search 할 때 USER_ID 중요\n userid = USER_matching.find_one({'HW_ID': str(ML_data['data'][0]['serial'])})\n FCM = FCM_key_matching.find_one({'USER_ID' : userid['USER_ID']})\n\n send_form_FCM(FCM['Key'], result_RF['status'][i])\n\n\ndef send_form_FCM(ids, status):\n\n temp_st = int(status / 10)\n hum_st = int(status) % 10\n print(\"status = \",status,type(status))\n print(\"temp_st = \",temp_st)\n print(\"hum_st = \",hum_st)\n\n title = ''\n body = ''\n print(\"making message body\")\n\n #해당 모델에서는 온도를 올리고 습도를 낮추는 기능으로 백열구가 연결되어 있으므로 문제점이 됨\n #따라서 온도를 올려야되고 습도를 낮춰야 되는 경우룰 분리시켜서 if checking\n if temp_st == 1 :\n title += '팬 '\n body += '팬 연결 상태와 동작 상태를 확인해주세요\\n'\n if temp_st == 3 and hum_st == 1:\n title += '백열구 '\n body += '백열구 연결 상태와 동작 상태를 확인해 주세요\\n'\n elif temp_st == 3:\n title += '백열구 '\n body += '백열구 연결 상태와 동작 상태를 확인해 주세요\\n'\n elif hum_st == 1:\n title += '백열구 '\n body += '백열구 연결 상태와 동작 상태를 확인해 주세요\\n'\n if hum_st == 3:\n title += '가습기 '\n body += '가습기 연결 상태와 동작 상태를 확인해 주세요\\n'\n\n title += \"에러\"\n\n # fcm 푸시 메세지 요청 주소\n url = 'https://fcm.googleapis.com/fcm/send'\n\n # 인증 정보(서버 키)를 헤더에 담아 전달\n #header 의 정보로 FCM_key, 즉 Firebase 에 등록된 앱의 key를 사용\n headers = {\n 'Authorization': 'key='+FCM_Key,\n 'Content-Type': 'application/json; UTF-8',\n }\n\n\n #ids 에는 기기별로 고유하게 가지는 Token 값을 사용\n # 보낼 내용을 작성\n content = {\n 'to': ids,\n 'notification': {\n 'title': title,\n 'body': body\n }\n }\n print(\"send request message to FCM\")\n\n r = requests.post(url, data=json.dumps(content), headers=headers)\n","sub_path":"sensor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"256555873","text":"\"\"\"added orientation column to pi model\n\nRevision ID: 2711340c6d9d\nRevises: 490d49497045\nCreate Date: 2015-09-25 09:43:33.202018\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '2711340c6d9d'\ndown_revision = '490d49497045'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('PiUrl', sa.Column('orientation', sa.Integer(), nullable=True))\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('PiUrl', 'orientation')\n ### end Alembic commands ###\n","sub_path":"alembic/versions/2711340c6d9d_added_orientation_column_to_pi_model.py","file_name":"2711340c6d9d_added_orientation_column_to_pi_model.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"502139948","text":"# Definition for an interval.\n# class Interval(object):\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[Interval]\n :type newInterval: Interval\n :rtype: List[Interval]\n \"\"\"\n def overlap(i, n):\n if i.start > n.start:\n i, n = n, i\n return i.end >= n.start\n\n def merge2(i, n):\n return Interval(min(i.start, n.start), max(i.end, n.end))\n\n ans = []\n for i in intervals:\n if overlap(i, newInterval):\n newInterval = merge2(i, newInterval)\n else:\n if i.start > newInterval.start:\n i, newInterval = newInterval, i\n ans.append(i)\n ans.append(newInterval)\n return ans\n","sub_path":"Insert Interval.py","file_name":"Insert Interval.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"510024483","text":"# -*- coding: utf-8 -*-\r\nfrom __future__ import print_function, division\r\nimport numpy as np\r\nimport torch\r\nimport pdb\r\nimport Filter\r\nimport Model as Model\r\nimport matplotlib.pyplot as plt\r\nimport copy\r\nimport os\r\n#import Optimizer_predictive_Adams as Optimizer\r\nimport Optimizer_SGD as Optimizer\r\nimport visdom\r\n\r\n'''\r\n这个new的分解方法是针对新的数据,mvc, open, close, rest 都是一大推的\r\n加入predictive adams,特别适合优化这种鞍点saddle point问题\r\n'''\r\nSAVE_DIR = './saveDecomposition_mvc'\r\n\r\nRESTORE_PREVIOUS_MODEL = True\r\nDEVICE = torch.device('cuda')\r\nDTYPE = torch.float\r\n\r\nVIS = visdom.Visdom(env='MVC')\r\nNB_PLOTS = 3 # 在visdom中plot的MUAPs的数目\r\n\r\nDATA_DIMS = 512\r\nGEN_SEARCH_NUM = 3\r\nNOISE_DIMS = 100\r\nNGF = 64\r\nNDF = 64 \r\n\r\nLEARNING_RATE_z = 0.01\r\nLEARNING_RATE_A = 0.001\r\nLAMBDA = 1\r\nLAMBDA_1 = 0.1 # 用来控制到底是产生的数据真实和拟合的权重\r\nLAMBDA_2 = 0 # penalty for A\r\n\r\nEPOCHS = 50000\r\nSAVE_EVERY = 1000\r\nPLOT_EVERY = 100\r\n\r\nDECREASE_LR = 100\r\nUPDATE_A_EVERY = 20 #20\r\nUPDATE_z_EVERY = 1 #1\r\n\r\nGAUSSIAN_NOISE = False\r\n\r\n# FIR滤波器\r\ncoeff_matrix_np = Filter.fir_filter_matrix(DATA_DIMS, 100, 1000)\r\ncoeff_matrix = torch.from_numpy(coeff_matrix_np)\r\ncoeff_matrix = coeff_matrix.to(DEVICE, DTYPE)\r\n\r\n# 读取数据\r\n'''\r\nEMG = np.load('./EMG_for_decomposition/trial2_data_dict.npy') # 需要分解的肌肉电信号\r\nEMG = EMG.item()\r\nEMG_mvc = copy.copy(EMG['mvc'])\r\nEMG_mvc = EMG_mvc[:10] # 减小一点EMG_mvc的数目\r\n'''\r\n\r\nEMG = np.load('./EMG_for_decomposition/S002/S00201_resample.npy')\r\nEMG = np.squeeze(EMG)\r\n#EMG = EMG[0:5120]\r\n#EMG_mvc = np.reshape(EMG, (10, DATA_DIMS))\r\nEMG = EMG[0:512 * 1]\r\nEMG_mvc = np.reshape(EMG, (1, DATA_DIMS))\r\n\r\n# 归一化 [-1,1]\r\nEMG_mvc_max = np.max(EMG_mvc.flatten())\r\nEMG_mvc_min = np.min(EMG_mvc.flatten())\r\nEMG_mvc = (EMG_mvc - EMG_mvc_min) / (EMG_mvc_max - EMG_mvc_min) # [0, 1]\r\nEMG_mvc = (EMG_mvc - 0.5) * 2\r\n\r\nEMG_mvc = np.matmul(EMG_mvc, coeff_matrix_np)\r\n\r\nEMG_mvc = torch.from_numpy(EMG_mvc)\r\nEMG_mvc = EMG_mvc.to(DEVICE, DTYPE)\r\nbatch_size = EMG_mvc.shape[0]\r\n\r\n\r\n# variable 输入噪声z,混合矩阵A, 考虑梯度\r\nif RESTORE_PREVIOUS_MODEL:\r\n #checkpoint = torch.load(os.path.join(SAVE_DIR, 'checkpoints','checkpoint.tar'))\r\n checkpoint = torch.load(os.path.join(SAVE_DIR, 'checkpoint.tar'))\r\n z = checkpoint['z']\r\n A = checkpoint['A']\r\nelse:\r\n if GAUSSIAN_NOISE:\r\n z = torch.randn(GEN_SEARCH_NUM, NOISE_DIMS, 1, device=DEVICE, dtype=DTYPE, requires_grad=True)\r\n else:\r\n z = np.random.uniform(-1, 1, (GEN_SEARCH_NUM, NOISE_DIMS, 1))\r\n z = torch.tensor(z, requires_grad=True, device=DEVICE, dtype=DTYPE)\r\n \r\n A = torch.randn(batch_size, GEN_SEARCH_NUM, device=DEVICE, dtype=DTYPE, requires_grad=True)\r\n #A = torch.ones(batch_size, GEN_SEARCH_NUM, device=DEVICE, dtype=DTYPE, requires_grad=True)\r\n\r\nG_DC = Model.build_dc_generator(ngf=NGF, noise_dims=NOISE_DIMS)\r\nG_DC.load_state_dict(torch.load('./saveTorch/G_DC_46_0.pth', map_location='cuda'))\r\nG_DC = G_DC.to(DEVICE, DTYPE)\r\nG_DC.eval()\r\n\r\nD_DC = Model.build_dc_classifier(ndf=NDF)\r\nD_DC.load_state_dict(torch.load('./saveTorch/D_DC_46_0.pth', map_location='cuda'))\r\nD_DC = D_DC.to(DEVICE, DTYPE)\r\nD_DC.eval()\r\n\r\n# 关闭对G_DC的梯度计算\r\nfor p in G_DC.parameters():\r\n p.requires_grad = False\r\n\r\nfor p in D_DC.parameters():\r\n p.requires_grad = False \r\n\r\n\r\nmseloss = torch.nn.MSELoss(size_average=False)\r\nl1loss = torch.nn.L1Loss(size_average=False)\r\n\r\nz_vel = torch.zeros_like(z)\r\nA_vel = torch.zeros_like(A)\r\n\r\nfor epoch in range(EPOCHS):\r\n \r\n MUAPs = G_DC(z)\r\n MUAPs = torch.matmul(MUAPs, coeff_matrix) # 对每个MUAPs进行100Hz的高通滤波\r\n MUAPs_logits = D_DC(MUAPs)\r\n\r\n MUAPs = torch.squeeze(MUAPs)\r\n if GEN_SEARCH_NUM == 1:\r\n MUAPs = torch.unsqueeze(MUAPs, 0)\r\n\r\n reconstruct_EMG = torch.matmul(A, MUAPs) #debug torch.abs\r\n\r\n if batch_size > 1:\r\n penalty_A = torch.mean(torch.std(A, dim=0)) - torch.mean(torch.abs(A)) # 第一项希望A尽可能相同,第二项希望A的值不要是零\r\n #loss = LAMBDA * mseloss(reconstruct_EMG, EMG_mvc) - LAMBDA_1 * torch.mean(MUAPs_logits) + LAMBDA_2 * penalty_A\r\n loss = LAMBDA * l1loss(reconstruct_EMG, EMG_mvc) - LAMBDA_1 * torch.mean(MUAPs_logits) + LAMBDA_2 * penalty_A\r\n else:\r\n penalty_A = - torch.mean(torch.abs(A)) # 希望A的值越大越好\r\n #loss = LAMBDA * mseloss(reconstruct_EMG, EMG_mvc) - LAMBDA_1 * torch.mean(MUAPs_logits) + LAMBDA_2 * penalty_A\r\n loss = LAMBDA * l1loss(reconstruct_EMG, EMG_mvc) - LAMBDA_1 * torch.mean(MUAPs_logits) + LAMBDA_2 * penalty_A\r\n\r\n loss.backward()\r\n epsilon = 0.0001\r\n\r\n with torch.no_grad():\r\n\r\n if epoch % UPDATE_z_EVERY == 0:\r\n z_grad = LEARNING_RATE_z * z.grad / (z.grad.data.norm(2) + epsilon)\r\n z -= z_grad + 0.5 * z_vel\r\n z_vel.data = z_grad.data\r\n if not GAUSSIAN_NOISE:\r\n z_np = z.data.cpu().numpy()\r\n z_np = np.clip(z_np, -1, 1)\r\n z_tensor = torch.tensor(z_np, device=DEVICE, dtype=DTYPE)\r\n z.data = z_tensor\r\n\r\n if epoch % UPDATE_A_EVERY == 0:\r\n A_grad = LEARNING_RATE_A * A.grad / (A.grad.data.norm(2) + epsilon)\r\n #A -= A_grad + 0.5 * A_vel\r\n A_vel.data = A_grad.data\r\n\r\n z.grad.zero_()\r\n A.grad.zero_()\r\n if (epoch + 1) % PLOT_EVERY == 0:\r\n print('Epoch: ', epoch, 'Loss: ', loss.item())\r\n \r\n # 输出 orignal 和 reconstruct来看\r\n VIS.line(X=np.arange(batch_size * DATA_DIMS), Y=EMG_mvc.view(-1), win='EMG', name='original')\r\n VIS.line(X=np.arange(batch_size * DATA_DIMS), Y=reconstruct_EMG.view(-1), win='EMG', name='reconstruct', update='append')\r\n\r\n # 输出 MUAPTs来看\r\n assert GEN_SEARCH_NUM >= NB_PLOTS, \"Note that replace=False, GEN_SEARCH_NUM >= NB_PLOTS\"\r\n random_choice = np.random.choice(GEN_SEARCH_NUM, NB_PLOTS, replace=False)\r\n average_A = torch.mean(A, dim=0)\r\n for i, index in enumerate(random_choice):\r\n VIS.line(X=np.arange(DATA_DIMS), Y=MUAPs[index] * average_A[index], win='MUAPT' + str(i), name='MUAPs' + str(i))\r\n\r\n if epoch % SAVE_EVERY == 0:\r\n np.save(os.path.join(SAVE_DIR, 'original_EMG.npy'), EMG_mvc.cpu().data.numpy())\r\n np.save(os.path.join(SAVE_DIR, 'reconstruct_EMG.npy'), reconstruct_EMG.cpu().data.numpy())\r\n np.save(os.path.join(SAVE_DIR, 'MUAPs.npy'), MUAPs.cpu().data.numpy())\r\n np.save(os.path.join(SAVE_DIR, 'z.npy'), z.cpu().data.numpy())\r\n np.save(os.path.join(SAVE_DIR, 'A.npy'), A.cpu().data.numpy())\r\n\r\n # 保存结果\r\n results = {'z':z, 'A':A}\r\n torch.save(results, os.path.join(SAVE_DIR, 'checkpoint.tar'))\r\n\r\n","sub_path":"decomposition_mvc_with_filter.py","file_name":"decomposition_mvc_with_filter.py","file_ext":"py","file_size_in_byte":6828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"335911324","text":"from datetime import datetime, timedelta\n\nfrom django.contrib.auth.models import User\nfrom django.http import JsonResponse, HttpRequest\n\nfrom polls.api.presenters.user_dish import UserDishPresenter\nfrom polls.errors import EntityNotFoundException\nfrom polls.models import Dish, UserDishes\n\n\ndef apply_dish(request: HttpRequest, user_id: int, dish_id: int):\n link = UserDishes()\n\n user = User.objects.get(pk=user_id)\n dish = Dish.objects.get(pk=dish_id)\n\n if not user or not dish:\n raise EntityNotFoundException()\n\n link.user = user\n link.dish = dish\n link.save()\n\n return JsonResponse({\n \"data\": UserDishPresenter(link).to_json()\n })\n\n\ndef calorie_analyze(request: HttpRequest, user_id: int):\n date_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)\n date_end = date_start + timedelta(days=1)\n\n sql = \"\"\"\n SELECT \n *, SUM(d.calorie_total) as calorie_analyze \n FROM polls_dish d\n LEFT JOIN polls_userdishes ud ON ud.dish_id = d.id\n WHERE ud.user_id = {user_id} AND ud.date_create BETWEEN \"{date_start}\" AND \"{date_end}\" \n \"\"\".format(**{\n \"user_id\": user_id,\n \"date_start\": date_start,\n \"date_end\": date_end\n })\n dish: Dish = Dish.objects.raw(sql)\n\n calorie = 0\n if dish[0].calorie_analyze is not None:\n calorie = int(dish[0].calorie_analyze)\n\n return JsonResponse({\n \"data\": {\n \"calorie\": calorie\n }\n })\n","sub_path":"src/polls/api/actions/users_action.py","file_name":"users_action.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"584548660","text":"#!/usr/bin/env python3\nimport asyncio\nimport types, time\nimport random, struct\nimport argparse, logging\nimport dns.resolver\nimport dns.message\nimport socket\nimport threading\nimport multiprocessing as mp\nimport aioprocessing as aiomp\nimport multiprocessing.managers\n\n# Attempt to use uvloop if installed for extra performance\n# try:\n# \timport uvloop\n# \tasyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n# except ImportError:\n# \tpass\n\n\n# Handle command line arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('-a', '--listen-address', default='localhost',\n\t\t\t\t\thelp='address to listen on for DNS over HTTPS requests (default: %(default)s)')\nparser.add_argument('-p', '--listen-port', type=int, default=53,\n\t\t\t\t\thelp='port to listen on for DNS over HTTPS requests (default: %(default)s)')\nparser.add_argument('-u', '--upstreams', nargs='+', default=['1.1.1.1', '1.0.0.1'],\n\t\t\t\t\thelp='upstream servers to forward DNS queries and requests to (default: %(default)s)')\nparser.add_argument('-t', '--tcp', action='store_true', default=False,\n\t\t\t\t\thelp='serve TCP based queries and requests along with UDP (default: %(default)s)')\nparser.add_argument('-m', '--max-cache-size', type=int, default=10000,\n\t\t\t\t\thelp='maximum size of the cache in dns records (default: %(default)s)')\nparser.add_argument('--active', action='store_true', default=False,\n\t\t\t\t\thelp='actively replace expired cache entries by performing upstream requests (default: %(default)s)')\nparser.add_argument('--timeout', type=float, default=5.0,\n\t\t\t\t\thelp='time to wait before giving up on a request (default: %(default)s seconds)')\nargs = parser.parse_args()\n\nhost = args.listen_address\nport = args.listen_port\nupstreams = args.upstreams\ncache_size = args.max_cache_size\nactive = args.active\ntimeout = args.timeout\n\n# Basic diagram\n# Q Q\n# listener -> cache {} -> forwarder\n# Q Q\n\n# Queue for listener to post requests and get responses\ncache_request = aiomp.AioQueue()\ncache_response = aiomp.AioQueue()\nforwarder_request = aiomp.AioQueue()\nforwarder_response = aiomp.AioQueue()\n\n\ndef main():\n\t# Setup logging\n\tlogging.basicConfig(level='INFO', format='[%(levelname)s] %(message)s')\n\n\t# Setup resolver cache\n\tworkers = []\n\tcache = DnsLruCache(cache_size)\n\twait_table = DnsWaitTable()\n\t# p4 = mp.Process(target=echo_worker, args=(forwarder_request, forwarder_response), daemon=True)\n\t# workers.append(p4)\n\tp = mp.Process(target=cache_worker, args=(cache, wait_table, cache_request, cache_response, forwarder_request, forwarder_response), daemon=True)\n\tworkers.append(p)\n\tp = mp.Process(target=forwarder_worker, args=((upstreams[0], 53), timeout, forwarder_request, forwarder_response), daemon=True)\n\tworkers.append(p)\n\n\t# Setup event loop\n\tloop = asyncio.get_event_loop()\n\n\t# Setup UDP server\n\tlogging.info('Starting UDP server listening on: %s#%d' % (host, port))\n\tudp_listen = loop.create_datagram_endpoint(lambda: UdpDnsListen(cache_response, cache_request), local_addr = (host, port))\n\tudp, protocol = loop.run_until_complete(udp_listen)\n\n\t# Setup TCP server\n\tif args.tcp:\n\t\tlogging.info('Starting TCP server listening on %s#%d' % (host, port))\n\t\ttcp_listen = loop.create_server(TcpDnsListen, host, port)\n\t\ttcp = loop.run_until_complete(tcp_listen)\n\n\t# Serve forever\n\ttry:\n\t\tfor worker in workers:\n\t\t\tworker.start()\n\n\t\tloop.run_forever()\n\texcept (KeyboardInterrupt, SystemExit):\n\t\tpass\n\n\t# Close listening servers and event loop\n\tudp.close()\n\tif args.tcp:\n\t\ttcp.close()\n\n\tloop.close()\n\n\nclass UdpDnsListen(asyncio.DatagramProtocol):\n\t\"\"\"\n\tDNS over UDP listener.\n\t\"\"\"\n\n\tdef __init__(self, in_queue, out_queue, **kwargs):\n\t\tself.in_queue = in_queue\n\t\tself.out_queue = out_queue\n\t\tsuper().__init__(**kwargs)\n\n\tdef connection_made(self, transport):\n\t\tself.transport = transport\n\n\tdef datagram_received(self, data, addr):\n\t\tasyncio.ensure_future(self.process_packet(data, addr))\n\n\tdef error_received(self, exc):\n\t\tlogging.warning('Minor transport error')\n\n\tasync def process_packet(self, query, addr):\n\t\t# Post query to cache -> (query, addr)\n\t\tlogging.debug('LISTENER: Cache POST %s' % (addr[0]))\n\t\tself.out_queue.put((query, addr))\n\n\t\t# Get response from cache <- (answer, addr)\n\t\tanswer, addr = await self.in_queue.coro_get()\n\t\tlogging.debug('LISTENER: Cache GET %s' % (addr[0]))\n\n\t\t# Send DNS packet to client\n\t\tself.transport.sendto(answer, addr)\n\nclass TcpDnsListen(asyncio.Protocol):\n\t\"\"\"\n\tDNS over TCP listener.\n\t\"\"\"\n\n\tdef connection_made(self, transport):\n\t\tself.transport = transport\n\n\tdef data_received(self, data):\n\t\tasyncio.ensure_future(self.process_packet(data))\n\n\tdef eof_received(self):\n\t\tif self.transport.can_write_eof():\n\t\t\tself.transport.write_eof()\n\n\tdef connection_lost(self, exc):\n\t\tself.transport.close()\n\n\tasync def process_packet(self, data):\n\t\tpass\n\n\nclass DnsRequest:\n\t\"\"\"\n\tDNS request object used for associating responses.\n\t\"\"\"\n\n\tdef __init__(self, qname, qtype, qclass):\n\t\tself.qname = qname\n\t\tself.qtype = qtype\n\t\tself.qclass = qclass\n\nclass DnsWaitTableEntry:\n\t\"\"\"\n\tDNS waiting table entry.\n\t\"\"\"\n\n\tdef __init__(self, start, wait_list=None):\n\t\tself.start = start\n\t\tself.wait_list = wait_list\n\n\t\tif self.wait_list is None:\n\t\t\tself.wait_list = []\n\nclass DnsWaitTable:\n\t\"\"\"\n\tDNS waiting table to store clients waiting on DNS requests.\n\t\"\"\"\n\n\tdef __init__(self, lock=None):\n\t\tself.table = {}\n\t\tself.lock = lock\n\n\t\tif self.lock is None:\n\t\t\tself.lock = threading.Lock()\n\n\tdef get(self, key):\n\t\treturn self.table.get(key)\n\n\tdef set(self, key, value):\n\t\tself.table[key] = value\n\n\tdef delete(self, key):\n\t\ttry:\n\t\t\tdel self.table[key]\n\t\texcept KeyError:\n\t\t\tpass\n\nclass DnsLruCacheNode:\n\t\"\"\"\n\tDNS LRU cache entry.\n\t\"\"\"\n\n\tdef __init__(self, key, value):\n\t\tself.key = key\n\t\tself.value = value\n\t\tself.prev = self\n\t\tself.next = self\n\n\tdef link_before(self, node):\n\t\tself.prev = node.prev\n\t\tself.next = node\n\t\tnode.prev.next = self\n\t\tnode.prev = self\n\n\tdef link_after(self, node):\n\t\tself.prev = node\n\t\tself.next = node.next\n\t\tnode.next.prev = self\n\t\tnode.next = self\n\n\tdef unlink(self):\n\t\tself.next.prev = self.prev\n\t\tself.prev.next = self.next\n\n\nclass DnsLruCache:\n\t\"\"\"\n\tDNS LRU cache to store recently processes lookups.\n\t\"\"\"\n\n\tdef __init__(self, size=100000):\n\t\tself.data = {}\n\t\tself.sentinel = DnsLruCacheNode(None, None)\n\t\tself.hits = 0\n\t\tself.misses = 0\n\t\tself.size = size\n\n\t\tif self.size < 1:\n\t\t\tself.size = 1\n\n\tdef get(self, key):\n\t\t\"\"\"\n\t\tReturns value associated with key.\n\t\t\"\"\"\n\n\t\t# Attempt to lookup data\n\t\tnode = self.data.get(key)\n\n\t\tif node is None:\n\t\t\tself.misses += 1\n\t\t\treturn None\n\n\t\t# Unlink because we're either going to move the node to the front\n\t\t# of the LRU list or we're going to free it.\n\t\tnode.unlink()\n\n\t\t# Check if data is expired\n\t\tif node.value.expiration <= time.time():\n\t\t\tdel self.data[node.key]\n\t\t\treturn None\n\n\t\tnode.link_after(self.sentinel)\n\n\t\t# Return data with updated ttl\n\t\tresponse = node.value.response\n\t\tttl = int(node.value.expiration - time.time())\n\t\tfor section in (response.answer, response.authority, response.additional):\n\t\t\tfor rr in section:\n\t\t\t\trr.ttl = ttl\n\n\t\tself.hits += 1\n\t\treturn node.value\n\n\tdef put(self, key, value):\n\t\t\"\"\"\n\t\tAssociate key and value in the cache.\n\t\t\"\"\"\n\n\t\tnode = self.data.get(key)\n\n\t\t# Remove previous entry in this position\n\t\tif node is not None:\n\t\t\tnode.unlink()\n\t\t\tdel self.data[node.key]\n\n\t\t# Clean out least used entries if necessary\n\t\twhile len(self.data) >= self.size:\n\t\t\tnode = self.sentinel.prev\n\t\t\tnode.unlink()\n\t\t\tdel self.data[node.key]\n\n\t\t# Add entry to cache\n\t\tnode = DnsLruCacheNode(key, value)\n\t\tnode.link_after(self.sentinel)\n\t\tself.data[key] = node\n\n\tdef flush(self, key=None):\n\t\t\"\"\"\n\t\tFlush the cache of entries.\n\t\t\"\"\"\n\n\t\t# Flush only key if given\n\t\tif key is not None:\n\t\t\tnode = self.data.get(key)\n\n\t\t\tif node is not None:\n\t\t\t\tnode.unlink()\n\t\t\t\tdel self.data[node.key]\n\t\telse:\n\t\t\tnode = self.sentinel.next\n\n\t\t\t# Remove references to all entry nodes\n\t\t\twhile node != self.sentinel:\n\t\t\t\tnext = node.next\n\t\t\t\tnode.prev = None\n\t\t\t\tnode.next = None\n\t\t\t\tnode = next\n\n\t\t\t# Reset cache\n\t\t\tself.data = {}\n\t\t\tself.hits = 0\n\t\t\tself.misses = 0\n\n\tdef ratio(self):\n\t\t\"\"\"\n\t\tReturn cache hit ratio since creation or last full flush.\n\t\t\"\"\"\n\n\t\tif (self.hits + self.misses) > 0:\n\t\t\treturn self.hits / (self.hits + self.misses)\n\t\telse:\n\t\t\treturn 0\n\n\tdef expired(self, timeout):\n\t\t\"\"\"\n\t\tReturns list of expired or almost expired cache entries.\n\t\t\"\"\"\n\n\t\texpired = []\n\n\t\tfor k, v in self.data.items():\n\t\t\tif v.value.expiration <= time.time() + timeout:\n\t\t\t\texpired.append(k)\n\n\t\treturn expired\n\n\n################################################################################\ndef cache_worker(cache, wait_table, in_queue, out_queue, next_in, next_out):\n\tloop = asyncio.new_event_loop()\n\tasyncio.set_event_loop(loop)\n\tasyncio.ensure_future(cache_async_read(cache, wait_table, in_queue, out_queue, next_in))\n\tasyncio.ensure_future(cache_async_write(cache, wait_table, out_queue, next_out))\n\tif active:\n\t\t# threading.Thread(target=active_cache, args=(cache, 10, next_in), daemon=True).start()\n\t\tasyncio.ensure_future(active_cache_async(cache, 10, next_in))\n\tloop.run_forever()\n\nasync def cache_async_read(cache, wait_table, in_queue, out_queue, next_in):\n\twhile True:\n\t\t# Get query from client <- (query, addr)\n\t\tquery, addr = await in_queue.coro_get()\n\t\trequest = dns.message.from_wire(query)\n\t\tid = request.id\n\t\trequest = request.question[0]\n\t\trequest = DnsRequest(request.name, request.rdtype, request.rdclass)\n\t\tlogging.debug('CACHE: Client GET %s' % (request.qname))\n\n\t\t# Answer query from cache if possible\n\t\tresponse = cache.get((request.qname, request.qtype, request.qclass))\n\t\tif response is not None:\n\t\t\tresponse.response.id = id\n\t\t\tanswer = response.response.to_wire()\n\n\t\t\t# Post response to client -> (answer, addr)\n\t\t\tlogging.debug('CACHE: Client POST %s' % (request.qname))\n\t\t\tout_queue.put((answer, addr))\n\t\t\tcontinue\n\n\t\t# Add client to wait list for this query\n\t\tentry = wait_table.get((request.qname, request.qtype, request.qclass))\n\n\t\t# Create new wait list for this query and submit request\n\t\tif entry is None:\n\t\t\tentry = DnsWaitTableEntry(time.time(), [(addr, id)])\n\t\t\twait_table.set((request.qname, request.qtype, request.qclass), entry)\n\n\t\t\t# Post query to forwarder -> (request)\n\t\t\tlogging.debug('CACHE: Forwarder POST %s' % (request.qname))\n\t\t\tnext_in.put(request)\n\n\t\t# Request is pending so add client to wait list\n\t\telse:\n\t\t\t# # Query has expired so reset wait list\n\t\t\t# if (entry.start + timeout) <= time.time():\n\t\t\t# \traise KeyError\n\n\t\t\t# Check if client is already waiting\n\t\t\twait_list = entry.wait_list\n\t\t\tfor i, entry in enumerate(wait_list):\n\t\t\t\t# Use ID of latest request\n\t\t\t\tif entry[0] == addr:\n\t\t\t\t\twait_list[i] = (addr, id)\n\t\t\t\t\tcontinue\n\n\t\t\t# Add client to wait list\n\t\t\twait_list.append((addr, id))\n\nasync def cache_async_write(cache, wait_table, out_queue, next_out):\n\twhile True:\n\t\t# Get response from the forwarder <- (request, response)\n\t\trequest, response = await next_out.coro_get()\n\t\tlogging.debug('CACHE: Forwarder GET %s' % (request.qname))\n\n\t\t# Add entry to cache\n\t\tcache.put((request.qname, request.qtype, request.qclass), response)\n\n\t\t# Reply to clients waiting for this query\n\t\tentry = wait_table.get((request.qname, request.qtype, request.qclass))\n\n\t\t# No clients are waiting on this query\n\t\tif entry is None:\n\t\t\tcontinue\n\n\t\t# Clients are waiting so create and send replies\n\t\treply_list = entry.wait_list\n\t\tfor (addr, id) in reply_list:\n\t\t\t# Prepare answer to query\n\t\t\tresponse.response.id = id\n\t\t\tanswer = response.response.to_wire()\n\n\t\t\t# Post response to client -> (answer, addr)\n\t\t\tout_queue.put((answer, addr))\n\t\t\tlogging.debug('CACHE: Client POST %s' % (request.qname))\n\n\t\t# Remove wait list for this query\n\t\twait_table.delete((request.qname, request.qtype, request.qclass))\n\nasync def active_cache_async(cache, period, out_queue):\n\t\"\"\"\n\tWorker to process cache entries and preemptively replace expired or almost expired entries.\n\n\tParams:\n\t\tcache - cache object to store data in for quick retrieval (synchronized)\n\t\tperiod - time to wait between cache scans (in seconds)\n\t\tout_queue - queue object to send requests for further processing (synchronized)\n\t\"\"\"\n\n\twhile True:\n\t\texpired = cache.expired(period)\n\n\t\tfor key in expired:\n\t\t\trequest = DnsRequest(*key)\n\t\t\tout_queue.put(request)\n\n\t\tif len(expired) > 0:\n\t\t\tlogging.info('CACHE: Updated %d/%d entries' % (len(expired), len(cache.data)))\n\t\t\tlogging.info('CACHE: Hits %d, Misses %d, Ratio %.2f' % (cache.hits, cache.misses, cache.ratio()))\n\n\t\tawait asyncio.sleep(period)\n################################################################################\n\n\n################################################################################\nclass UdpDnsForward(asyncio.DatagramProtocol):\n\t\"\"\"\n\tDNS over UDP forwarder.\n\t\"\"\"\n\n\tdef __init__(self, out_queue):\n\t\tself.out_queue = out_queue\n\t\tsuper().__init__()\n\n\tdef connection_made(self, transport):\n\t\tself.transport = transport\n\n\tdef datagram_received(self, data, addr):\n\t\tasyncio.ensure_future(self.process_packet(data))\n\n\tasync def process_packet(self, answer):\n\t\tanswer = dns.message.from_wire(answer)\n\t\trequest = DnsRequest(answer.question[0].name, answer.question[0].rdtype, answer.question[0].rdclass)\n\t\tresponse = dns.resolver.Answer(request.qname, request.qtype, request.qclass, answer, False)\n\n\t\tlogging.debug('FORWARDER: Cache POST %s' % (request.qname))\n\t\tself.out_queue.put((request, response))\n\ndef forwarder_worker(upstream, timeout, in_queue, out_queue):\n\tloop = asyncio.new_event_loop()\n\tasyncio.set_event_loop(loop)\n\n\t# Connect to remote server\n\tudp_forward = loop.create_datagram_endpoint(lambda: UdpDnsForward(out_queue), remote_addr=upstream)\n\ttransport, protocol = loop.run_until_complete(udp_forward)\n\n\tasyncio.ensure_future(forwarder_async(transport, in_queue))\n\tloop.run_forever()\n\nasync def forwarder_async(transport, in_queue):\n\twhile True:\n\t\trequest = await in_queue.coro_get()\n\t\tlogging.debug('FORWARDER: Cache GET %s' % (request.qname))\n\n\t\tquery = dns.message.make_query(request.qname, request.qtype, request.qclass)\n\t\tquery = query.to_wire()\n\n\t\ttransport.sendto(query)\n################################################################################\n\nasync def forwarder_async2(sock, timeout, in_queue, out_queue):\n\twhile True:\n\t\trequest = await in_queue.coro_get()\n\t\tlogging.debug('forwarder: Cache GET %s' % (request.qname))\n\n\t\tquery = dns.message.make_query(request.qname, request.qtype, request.qclass)\n\t\tquery = query.to_wire()\n\n\t\tanswer, rtt = await udp_request(sock, query, timeout)\n\n\t\tif answer == b'':\n\t\t\tresponse = None\n\t\telse:\n\t\t\tanswer = dns.message.from_wire(answer)\n\t\t\tresponse = dns.resolver.Answer(request.qname, request.qtype, request.qclass, answer, False)\n\n\t\tawait out_queue.coro_put((request, response))\n\t\tlogging.debug('forwarder: Cache POST %s' % (request.qname))\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"concepts/doh-cache-fork.py","file_name":"doh-cache-fork.py","file_ext":"py","file_size_in_byte":14817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"258862797","text":"from numpy import*\nfrom numpy.linalg import inv, det, norm\nimport time\n\ndef Coordinate(N, l_ref, dir):\n\t\"\"\" Function to compute the coordinate values along the Span and Chord wise direction\n\tInput Arguments:\n\t\tN = Number of nodes in the given direction (int)\n\t\tl_ref = Physical Length in the given direction (float)\n\t\tdir = Coordinate direction, \"x\" or \"z\" (string)\n\tOutput:\n\t\tpos = 1D array containing nodes in the direction (numpy array)\n\t\"\"\"\n\tif dir == \"x\":\n\t\tc = 1;\n\telif dir == \"z\":\n\t\tc = -1;\n\tpos = zeros((1, N))[0];\n\tfor i in range(1, N + 2):\n\t\ttheta_i = (i - 1)*pi/N;\n\t\ttheta_j = i*pi/N;\n\t\tif i != N + 1:\n\t\t\tpos[i - 1] = c*0.5*(l_ref/2*(1 - cos(theta_i)) + l_ref/2*(1 - cos(theta_j)));\n\treturn pos;\n\n## Radial Basis Function Interpolation\ndef RBF(r):\n\t\"\"\" Function to define Radial Basis Function\n\tInput Arguments:\n\t\tr = distance between two nodes (float or numpy array)\n\tOutput:\n\t\tbasis = Value of basis function\n\t\"\"\"\n\te = 260;\n\tbasis = sqrt(1 + (e*r)**2);\n\t#basis = exp(-(800*r)**2)\n\treturn basis;\n\ndef RBF_Matrix(nodes):\n\t\"\"\" Function to Generate Matrix for RBF interpolation\n\tInput Arguments:\n\t\tnodes = N by 2 array containing interpolation nodes, in the form [x, y] in each row (numpy array)\n\tOutput:\n\t\tA = Matrix A\n\t\"\"\"\n\tprint(\"Generating Matrix for RBF interpolation\");\n\tts = time.time();\n\tNorm = lambda x, y: sqrt(x**2 + y**2);\n\tX, Y = meshgrid(nodes[:, 0], nodes[:, 1]);\n\tdX = X.T - X;\n\tdY = Y - Y.T;\n\tA = RBF(Norm(dX, dY));\n\tprint(\"That took: \", time.time() - ts, \"s\");\n\treturn A;\n\ndef Inter(a, x, y, nodes):\n\t\"\"\" Function to evaluate RBF at desired location\n\tInput Arguments:\n\t\ta = Coefficient of each basis function (numpy array)\n\t\tx = x coordinate (numpy array)\n\t\ty = y coordinate (numpy array)\n\t\tnodes = Interpolation nodes\n\tOutput:\n\t\tfi = Value of RBF at all x, y 's\n\t\"\"\"\n\tif shape(x) != (len(x),):\n\t\tx = x[0, :];\n\t\ty = y[:, 0];\n\tNorm = lambda x, y: sqrt(x**2 + y**2);\n\tts = time.time();\n\tfi = zeros((len(x), len(y)));\n\tfor i in range(len(x)):\n\t\tfor j in range(len(y)):\n\t\t\tr = norm(array([x[i], y[j]]) - nodes, axis = 1);\n\t\t\tfi[i, j] = a.dot(RBF(r));\n\treturn fi.T;\n\ndef InerpolationError(a, A):\n\t\"\"\" Function to evaluate the interpolation error using the formula\n\t\tfrom litrature : e_i = a_i/inv(A_{i, i})\n\tInput Arguments:\n\t\ta = array of coefficients of each RBF (numpy array or list)\n\t\tA = Interpolation matrix (N X N matrix, numpy array)\n\tOutput:\n\t\te = error (numpy array)\n\t\"\"\"\n\te = a/diagonal(inv(A));\n\t#print(\"Interpolation residuals =\", e);\n\tprint(\"Interpolation error =\", amax(e));\n\treturn e;","sub_path":"MainCode/AeroLoadInterpolation.py","file_name":"AeroLoadInterpolation.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"183563724","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nmercadolibre.py\n===============\n\nSee http://mercadolibre-py.readthedocs.org/ for documentation.\n\n\"\"\"\n\n__title__ = 'mercadolibre.py'\n__author__ = 'Santiago Basulto'\n__version__ = '0.1.7'\n__build__ = 0x000101\n__license__ = 'MIT'\n__copyright__ = ''\n\n__version_info__ = tuple(int(i) for i in __version__.split('.'))\n\nfrom .api import MercadoLibre\n","sub_path":"mercadolibre/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"113640204","text":"import os\nimport shutil\nfrom os.path import abspath\nfrom unittest import mock\n\nfrom . import OriginTest\nfrom .. import assert_logging\nfrom ... import call_pkg_config, test_stage_dir\n\nfrom mopack.path import Path\nfrom mopack.origins import Package\nfrom mopack.origins.apt import AptPackage\nfrom mopack.origins.system import SystemPackage\nfrom mopack.types import dependency_string, FieldKeyError\n\n\nclass TestSystemPackage(OriginTest):\n pkg_type = SystemPackage\n pkgdir = os.path.join(test_stage_dir, 'origins')\n pkgconfdir = os.path.join(pkgdir, 'pkgconfig')\n\n def setUp(self):\n super().setUp()\n self.clear_pkgdir()\n\n def clear_pkgdir(self):\n if os.path.exists(self.pkgdir):\n shutil.rmtree(self.pkgdir)\n\n def check_get_linkage(self, pkg, submodules, expected=None, *,\n find_pkg_config=False):\n def mock_isfile(p, variables={}):\n p = os.path.normcase(p.string(**variables))\n return p.startswith(os.path.normcase(abspath('/mock')) + os.sep)\n\n if expected is None:\n depname = dependency_string(pkg.name, submodules)\n expected = {'name': depname, 'type': 'system', 'generated': True,\n 'auto_link': False, 'pcnames': [depname],\n 'pkg_config_path': [self.pkgconfdir]}\n\n self.clear_pkgdir()\n side_effect = None if find_pkg_config else OSError()\n with mock.patch('subprocess.run', side_effect=side_effect), \\\n mock.patch('mopack.linkages.path_system.file_outdated',\n return_value=True), \\\n mock.patch('mopack.linkages.path_system._system_include_path',\n return_value=[Path('/mock/include')]), \\\n mock.patch('mopack.linkages.path_system._system_lib_path',\n return_value=[Path('/mock/lib')]), \\\n mock.patch('mopack.linkages.path_system._system_lib_names',\n return_value=['lib{}.so']), \\\n mock.patch('mopack.linkages.path_system.isfile',\n mock_isfile):\n self.assertEqual(pkg.get_linkage(self.metadata, submodules),\n expected)\n\n def check_pkg_config(self, name, submodules, expected={}):\n pcname = dependency_string(name, submodules)\n self.assertCountEqual(\n call_pkg_config(pcname, ['--cflags'], path=self.pkgconfdir),\n expected.get('cflags', [])\n )\n self.assertCountEqual(\n call_pkg_config(pcname, ['--libs'], path=self.pkgconfdir),\n expected.get('libs', ['-L' + abspath('/mock/lib'), '-l' + name])\n )\n\n def test_resolve_path(self):\n pkg = self.make_package('foo')\n with assert_logging([('resolve', 'foo from system')]):\n pkg.resolve(self.metadata)\n self.assertEqual(pkg.version(self.metadata), None)\n self.check_get_linkage(pkg, None)\n self.check_pkg_config('foo', None)\n\n def test_resolve_pkg_config(self):\n pkg = self.make_package('foo')\n with assert_logging([('resolve', 'foo from system')]):\n pkg.resolve(self.metadata)\n self.check_get_linkage(pkg, None, {\n 'name': 'foo', 'type': 'system', 'pcnames': ['foo'],\n 'pkg_config_path': [],\n }, find_pkg_config=True)\n\n def test_explicit_version(self):\n pkg = self.make_package('foo', version='2.0')\n with assert_logging([('resolve', 'foo from system')]):\n pkg.resolve(self.metadata)\n self.assertEqual(pkg.version(self.metadata), '2.0')\n self.check_get_linkage(pkg, None)\n self.check_pkg_config('foo', None)\n\n def test_auto_link(self):\n pkg = self.make_package('foo', auto_link=True)\n with assert_logging([('resolve', 'foo from system')]):\n pkg.resolve(self.metadata)\n self.check_get_linkage(pkg, None, {\n 'name': 'foo', 'type': 'system', 'generated': True,\n 'auto_link': True, 'pcnames': ['foo'],\n 'pkg_config_path': [self.pkgconfdir],\n })\n self.check_pkg_config('foo', None, {\n 'libs': ['-L' + abspath('/mock/lib')],\n })\n\n def test_include_path(self):\n incdir = abspath('/mock/path/to/include')\n pkg = self.make_package('foo', include_path='/mock/path/to/include',\n headers=['foo.hpp'])\n with assert_logging([('resolve', 'foo from system')]):\n pkg.resolve(self.metadata)\n self.check_get_linkage(pkg, None)\n self.check_pkg_config('foo', None, {'cflags': ['-I' + incdir]})\n\n def test_library_path(self):\n libdir = abspath('/mock/path/to/lib')\n pkg = self.make_package('foo', library_path='/mock/path/to/lib')\n with assert_logging([('resolve', 'foo from system')]):\n pkg.resolve(self.metadata)\n self.check_get_linkage(pkg, None)\n self.check_pkg_config('foo', None, {'libs': ['-L' + libdir, '-lfoo']})\n\n def test_headers(self):\n pkg = self.make_package('foo', headers='foo.hpp')\n with assert_logging([('resolve', 'foo from system')]):\n pkg.resolve(self.metadata)\n self.check_get_linkage(pkg, None)\n self.check_pkg_config('foo', None, {\n 'cflags': ['-I' + abspath('/mock/include')],\n })\n\n pkg = self.make_package('foo', headers=['foo.hpp'])\n with assert_logging([('resolve', 'foo from system')]):\n pkg.resolve(self.metadata)\n self.check_get_linkage(pkg, None)\n self.check_pkg_config('foo', None, {\n 'cflags': ['-I' + abspath('/mock/include')],\n })\n\n def test_libraries(self):\n pkg = self.make_package('foo', libraries='bar')\n with assert_logging([('resolve', 'foo from system')]):\n pkg.resolve(self.metadata)\n self.check_get_linkage(pkg, None)\n self.check_pkg_config('foo', None, {\n 'libs': ['-L' + abspath('/mock/lib'), '-lbar'],\n })\n\n pkg = self.make_package('foo', libraries=['foo', 'bar'])\n with assert_logging([('resolve', 'foo from system')]):\n pkg.resolve(self.metadata)\n self.check_get_linkage(pkg, None)\n self.check_pkg_config('foo', None, {\n 'libs': ['-L' + abspath('/mock/lib'), '-lfoo', '-lbar'],\n })\n\n pkg = self.make_package('foo', libraries=None)\n with assert_logging([('resolve', 'foo from system')]):\n pkg.resolve(self.metadata)\n self.check_get_linkage(pkg, None)\n self.check_pkg_config('foo', None, {'libs': []})\n\n def test_submodules(self):\n submodules_required = {'names': '*', 'required': True}\n submodules_optional = {'names': '*', 'required': False}\n\n pkg = self.make_package('foo', submodules=submodules_required)\n self.check_get_linkage(pkg, ['sub'])\n self.check_pkg_config('foo', ['sub'], {\n 'libs': ['-L' + abspath('/mock/lib'), '-lfoo_sub'],\n })\n\n pkg = self.make_package('foo', libraries='bar',\n submodules=submodules_required)\n self.check_get_linkage(pkg, ['sub'])\n self.check_pkg_config('foo', ['sub'], {\n 'libs': ['-L' + abspath('/mock/lib'), '-lbar', '-lfoo_sub'],\n })\n\n pkg = self.make_package('foo', submodules=submodules_optional)\n self.check_get_linkage(pkg, ['sub'])\n self.check_pkg_config('foo', ['sub'], {\n 'libs': ['-L' + abspath('/mock/lib'), '-lfoo', '-lfoo_sub'],\n })\n\n pkg = self.make_package('foo', libraries='bar',\n submodules=submodules_optional)\n self.check_get_linkage(pkg, ['sub'])\n self.check_pkg_config('foo', ['sub'], {\n 'libs': ['-L' + abspath('/mock/lib'), '-lbar', '-lfoo_sub'],\n })\n\n def test_invalid_submodule(self):\n pkg = self.make_package('foo', submodules={\n 'names': ['sub'], 'required': True\n })\n with self.assertRaises(ValueError):\n pkg.get_linkage(self.metadata, ['invalid'])\n\n def test_invalid_linkage(self):\n with self.assertRaises(FieldKeyError):\n self.make_package('foo', linkage={'type': 'system'})\n\n def test_deploy(self):\n pkg = self.make_package('foo')\n # This is a no-op; just make sure it executes ok.\n pkg.deploy(self.metadata)\n\n def test_clean_pre(self):\n oldpkg = self.make_package('foo')\n newpkg = self.make_package(AptPackage, 'foo')\n\n # System -> Apt\n self.assertEqual(oldpkg.clean_pre(self.metadata, newpkg), False)\n\n # Apt -> nothing\n self.assertEqual(oldpkg.clean_pre(self.metadata, None), False)\n\n def test_clean_post(self):\n oldpkg = self.make_package('foo')\n newpkg = self.make_package(AptPackage, 'foo')\n\n # System -> Apt\n self.assertEqual(oldpkg.clean_post(self.metadata, newpkg), False)\n\n # Apt -> nothing\n self.assertEqual(oldpkg.clean_post(self.metadata, None), False)\n\n def test_clean_all(self):\n oldpkg = self.make_package('foo')\n newpkg = self.make_package(AptPackage, 'foo')\n\n # System -> Apt\n self.assertEqual(oldpkg.clean_all(self.metadata, newpkg),\n (False, False))\n\n # Apt -> nothing\n self.assertEqual(oldpkg.clean_all(self.metadata, None), (False, False))\n\n def test_equality(self):\n pkg = self.make_package('foo')\n\n self.assertEqual(pkg, self.make_package('foo'))\n self.assertEqual(pkg, self.make_package(\n 'foo', config_file='/path/to/mopack2.yml'\n ))\n\n self.assertNotEqual(pkg, self.make_package('bar'))\n\n def test_rehydrate(self):\n opts = self.make_options()\n pkg = SystemPackage('foo', _options=opts, config_file=self.config_file)\n data = pkg.dehydrate()\n self.assertEqual(pkg, Package.rehydrate(data, _options=opts))\n\n def test_upgrade(self):\n opts = self.make_options()\n data = {'origin': 'system', '_version': 0, 'name': 'foo',\n 'linkage': {'type': 'system', '_version': 0}}\n with mock.patch.object(SystemPackage, 'upgrade',\n side_effect=SystemPackage.upgrade) as m:\n pkg = Package.rehydrate(data, _options=opts)\n self.assertIsInstance(pkg, SystemPackage)\n m.assert_called_once()\n","sub_path":"test/unit/origins/test_system.py","file_name":"test_system.py","file_ext":"py","file_size_in_byte":10452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"612406265","text":"import logging\n\nfrom .base_service import BaseService\nfrom application.models.order_model import OrderModel\nfrom application.services.k_service import KService\nfrom application.common.foundation import db\nfrom sqlalchemy import between,func\nfrom application.common.dict import thunder_service_ID\nimport time\n\n\nclass OrderService(BaseService):\n @staticmethod\n def add_order(order_id,user_id,thunderservice_id,placeOrderTime,coupon,amount,emailNotification,description):\n print (user_id,thunderservice_id,placeOrderTime,coupon,amount,emailNotification,description)\n order = OrderModel(\n order_id = order_id,\n user_id = user_id,\n thunderservice_id = thunderservice_id,\n placeOrderTime = placeOrderTime,\n coupon = coupon,\n amount = amount,\n emailNotification = emailNotification,\n description = description,\n orderStatus = '1'\n )\n db.session.add(order)\n\n\n @staticmethod\n def delete_order(order_id):\n OrderModel.query.filter(OrderModel.id == order_id).delete()\n\n\n @staticmethod\n def cancel_order(order_id):\n order = OrderModel.query.filter(OrderModel.id == order_id).first()\n if order.orderStatus == None or order.orderStatus == '1' :\n order.orderStatus = '3'\n db.session.commit()\n return True\n else:\n return False\n\n @staticmethod\n def mark_paid_order(order_id):\n order = OrderModel.query.filter(OrderModel.id == order_id).first()\n # mark order as paid\n order.orderStatus = '2'\n db.session.commit()\n\n @staticmethod\n def make_fulfill(order_id):\n from application.services.user_service import UserService\n order = OrderModel.query.filter(OrderModel.id == order_id).first()\n user = UserService.get_user(order.user_id)\n if user:\n from application.models.thunderservice_model import ThunderserviceModel\n if user.thunderservice_id == order.thunderservice_id:\n\n # 相同的thunderservice,只修改到期时间\n thunderservice = ThunderserviceModel.query.filter(ThunderserviceModel.id == order.thunderservice_id).first()\n duration = thunderservice.duration*86400\n user.thunderservice_endtime = max(user.thunderservice_endtime, int(time.time())) + duration\n\n # 标记本order已经完成了\n order.thunderserviceStatus = '1'\n db.session.commit()\n\n # 增加记录到K线图\n KService_action = '201'\n KService.add_record(action=KService_action,parameter1=order.amount,parameter2='Paid',timestamp=int(time.time()))\n\n return True\n else:\n #取user当前的thunderservice是否是付费service,如果是,记录还剩多少时间。\n timeLeft = 0\n if str(user.thunderservice_id) in thunder_service_ID['FUFEI']:\n timeLeft = user.thunderservice_endtime - int(time.time())\n if timeLeft < 0:\n timeLeft = 0\n\n thunderservice = ThunderserviceModel.query.filter(ThunderserviceModel.id == order.thunderservice_id).first()\n user_updatedata={\n \"thunderservice_id\":order.thunderservice_id,\n \"thunderservice_client_amount\":thunderservice.defaultClientAmount,\n \"thunderservice_traffic_amount\":thunderservice.defaultTrafficAmount,\n }\n thunderservice_starttime = time.time()\n thunderservice_endtime = time.time()\n if thunderservice.id != 1:\n thunderservice_endtime = thunderservice_endtime + thunderservice.duration*86400 + timeLeft\n\n UserService.modify_user_by_id(order.user_id,update_data=user_updatedata)\n db.session.commit()\n\n UserService.active_thunderservice(order.user_id,order.thunderservice_id,thunderservice_starttime,thunderservice_endtime)\n db.session.commit()\n\n order.thunderserviceStatus = '1'\n db.session.commit()\n\n # 增加记录到K线图\n KService_action = '201'\n KService.add_record(action=KService_action,parameter1=order.amount,parameter2='Paid',timestamp=int(time.time()))\n return True\n else:\n return False\n\n\n @staticmethod\n def get_order_amount():\n orderAmount = OrderModel.query.filter().count()\n return orderAmount if orderAmount else 0\n\n @staticmethod\n def get_orders(pageNum,pageSize):\n orders = OrderModel.query.filter().limit(pageSize).offset((pageNum-1)*pageSize)\n return orders\n\n @staticmethod\n def get_order(order_id):\n order = OrderModel.query.filter(OrderModel.id == order_id).first()\n return order if order else None\n\n @staticmethod\n def get_expressorder(expressorder_id):\n order = OrderModel.query.filter(OrderModel.order_id == expressorder_id).first()\n return order if order else None\n\n @staticmethod\n def modify_order_by_id(order_id,update_data):\n update = OrderModel.query.filter(OrderModel.id == order_id).first()\n for key in update_data:\n setattr(update,key,update_data[key])\n\n @staticmethod\n def get_order_sum(start,end):\n orderSum = OrderModel.query(func.sum(OrderModel.amount)).filter(between(OrderModel.placeOrderTime,start,end)).all()\n return orderSum if orderSum else 0\n\n @staticmethod\n def get_paidOrder_sum(start,end):\n # paidOrderSum = OrderModel.query(func.sum(OrderModel.amount)).filter(between(OrderModel.placeOrderTime,start,end)).scalar()\n\n sql = \"SELECT SUM(amount) as amount from orders \\\n WHERE orderStatus = '2' AND \\\n placeOrderTime between {} and {}\" \\\n .format(start,end)\n list = db.session.execute(sql).fetchall()\n paidOrderSum =float('%.2f' % list[0][0])\n return paidOrderSum if paidOrderSum else 0","sub_path":"application/services/order_service.py","file_name":"order_service.py","file_ext":"py","file_size_in_byte":6162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"163328516","text":"import argparse\nimport pickle\nimport os\nimport json\nimport torch\nimport random\nimport numpy as np\nimport zipfile\n\nfrom tatk.nlu.bert.dataloader import Dataloader\nfrom tatk.nlu.bert.model import BertNLU\nfrom tatk.util.file_util import cached_path\n\n\ntorch.manual_seed(9102)\nrandom.seed(9102)\nnp.random.seed(9102)\n\n\nparser = argparse.ArgumentParser(description=\"Test a model.\")\nparser.add_argument('--config_path',\n help='path to config file')\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n config = json.load(open(args.config_path))\n data_dir = config['data_dir']\n output_dir = config['output_dir']\n log_dir = config['log_dir']\n DEVICE = config['DEVICE']\n\n data = pickle.load(open(os.path.join(data_dir,'data.pkl'),'rb'))\n intent_vocab = pickle.load(open(os.path.join(data_dir,'intent_vocab.pkl'),'rb'))\n tag_vocab = pickle.load(open(os.path.join(data_dir,'tag_vocab.pkl'),'rb'))\n for key in data:\n print('{} set size: {}'.format(key,len(data[key])))\n print('intent num:', len(intent_vocab))\n print('tag num:', len(tag_vocab))\n\n dataloader = Dataloader(data, intent_vocab, tag_vocab, config['model'][\"pre-trained\"])\n\n best_model_path = best_model_path = os.path.join(output_dir, 'bestcheckpoint.tar')\n if not os.path.exists(best_model_path):\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n print('Load from zipped_model_path param')\n archive_file = cached_path(config['zipped_model_path'])\n archive = zipfile.ZipFile(archive_file, 'r')\n archive.extractall()\n archive.close()\n print('Load from',best_model_path)\n checkpoint = torch.load(best_model_path, map_location=DEVICE)\n print('best_intent_step', checkpoint['best_intent_step'])\n print('best_tag_step', checkpoint['best_tag_step'])\n\n model = BertNLU(config['model'], dataloader.intent_dim, dataloader.tag_dim,\n DEVICE=DEVICE,\n intent_weight=dataloader.intent_weight)\n model_dict = model.state_dict()\n state_dict = {k: v for k, v in checkpoint['model_state_dict'].items() if k in model_dict.keys()}\n model_dict.update(state_dict)\n model.load_state_dict(model_dict)\n model.to(DEVICE)\n\n batch_size = config['batch_size']\n\n test_loss = 0\n test_intent_loss = 0\n test_tag_loss = 0\n for batched_data, real_batch_size in dataloader.yield_batches(batch_size, data_key='test'):\n intent_loss, tag_loss, total_loss, intent_logits, tag_logits = model.eval_batch(*batched_data)\n test_intent_loss += intent_loss * real_batch_size\n test_tag_loss += tag_loss * real_batch_size\n test_loss += total_loss * real_batch_size\n total = len(dataloader.data['test'])\n test_loss /= total\n test_intent_loss /= total\n test_tag_loss /= total\n print('%d samples test loss: %f' % (total, test_loss))\n print('\\t intent loss:', test_intent_loss)\n print('\\t tag loss:', test_tag_loss)\n print('Load from', best_model_path)\n print('best_intent_step', checkpoint['best_intent_step'])\n print('best_tag_step', checkpoint['best_tag_step'])\n","sub_path":"tatk/nlu/bert/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"67880721","text":"from datetime import date\nprint('{}Vamos ver sua situação quanto ao alistamento militar!!{}'.format('\\033[1:31m', '\\033[m'))\nanoNascimento = int(input('Digite o seu ano de nascimento: '))\nidadeAtual = date.today().year - anoNascimento\nif idadeAtual < 18:\n tempoParaAlistamento = 18 - idadeAtual\n print('Você {}ainda vai se alistar ao serviço militar{} e isso será daqui a {}{}{} anos.'.format('\\033[36m', '\\033[m', '\\033[36m', tempoParaAlistamento, '\\033[m', ))\nelif idadeAtual == 18:\n print('{}Já é hora{} de se alistar!!!'.format('\\033[33m', '\\033[m'))\nelse:\n tempoParaAlistamento = idadeAtual - 18\n print('O seu {}período para alistamento ja encerrou{} a {}{}{} anos.'.format('\\033[34m', '\\033[m', '\\033[34m', tempoParaAlistamento, '\\033[m'))\n\n\n\n\n","sub_path":"Exerciciospython/Condicoes Aninhadas/e039.py","file_name":"e039.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"319404634","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nclass PieChartContainer():\n def __init__(self, pc_data_arr):\n self.pc_data_arr = pc_data_arr\n def show(self):\n # fig = plt.figure(figsize = (4,4))\n # for i in range (1,len(self.pc_data_arr)+1):\n # fig.add_subplot(4,4,i)\n # plt.pie(self.value_key,self.pc_data_arr[i-1],autopct='%1.1f%%', labels = self.pc_data_arr[i-1])\n # plt.show()\n for i in range (len(self.pc_data_arr)):\n plt.pie(self.pc_data_arr[i],labels=self.pc_data_arr[i])\n plt.show()\n\nclass PieChartData():\n def __init__(self,csv_filename, name_key, value_key):\n self.csv_filename = csv_filename\n self.name_key = name_key\n self.value_key = value_key\n def get_name(self):\n r = pd.read_csv(self.csv_filename)\n name = r[self.name_key]\n values = r[self.value_key]\n print (name)\n print (values)\n\n\n # def show(self):\n # df = plt.read_csv(self.csv_filename)\n # def save(self,filename):\n\n\nCD1 = PieChartData(\"random_data.csv\",\"names\",\"values\")\nCD2 = PieChartData(\"courses_data.csv\",\"courses\",\"values\")\nCD3 = PieChartData(\"courses_data.csv\",\"courses\",\"values\")\nCD4 = PieChartData(\"random_data.csv\",\"names\",\"values\")\n\npc_array = [CD1, CD2, CD3, CD4]\npc_container = PieChartContainer(pc_array)\npc_container.show()\n# pc_container.save(\"random_courses.png\")","sub_path":"Mathplotlib/e21_pie.py","file_name":"e21_pie.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"546032686","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom carbuisness.items import YouxinpaiPicItem\nimport time\nfrom scrapy.conf import settings\nfrom scrapy.mail import MailSender\nimport logging\nimport json\nimport random\nimport re\nimport pymongo\nimport urllib2\nfrom selenium import webdriver\nfrom scrapy.xlib.pydispatch import dispatcher\nfrom scrapy import signals\nimport urllib\nimport os\nfrom carbuisness.items import TTPaiItem\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nwebsite = 'ttpai'\n\nclass TtpaiSpider(scrapy.Spider):\n name = \"ttpai\"\n allowed_domains = [\"ttpai.cn\"]\n start_urls = (\n 'http://pai.ttpai.cn/',\n )\n def __init__(self, **kwargs):\n super(TtpaiSpider, self).__init__(**kwargs)\n self.mailer = MailSender.from_settings(settings)\n self.counts = 0\n self.carnum = 3000000\n self.page = 1\n # Mongo\n settings.set('CrawlCar_Num', self.carnum, priority='cmdline')\n settings.set('MONGODB_DB', 'carbusiness', priority='cmdline')\n settings.set('MONGODB_COLLECTION', website, priority='cmdline')\n\n # self.browser = webdriver.PhantomJS(executable_path=\"D:/phantomjs.exe\")\n # # self.browser = webdriver.PhantomJS(executable_path=\"/usr/local/phantomjs/bin/phantomjs\")\n # # self.browser = webdriver.PhantomJS(executable_path=\"/root/home/phantomjs\")\n # super(TtpaiSpider, self).__init__()\n # dispatcher.connect(self.spider_closed, signals.spider_closed)\n\n # def spider_closed(self):\n # self.browser.quit()\n\n def parse(self, response):\n\n # print(response.body)\n\n lis = response.xpath(\"//*[@id='filter-form']/div[2]/div[2]/ul/li\")\n print(lis)\n for li in lis:\n href = \"http://pai.ttpai.cn\" + li.xpath('./div[1]/a/@href').extract_first()\n yield scrapy.Request(href, callback=self.parse_detail)\n if self.page < 201:\n self.page = self.page + 1\n yield scrapy.Request('http://pai.ttpai.cn/', callback=self.parse, meta={'page': str(self.page)}, dont_filter=True)\n\n\n def parse_detail(self, response):\n div_num = 1\n if not response.xpath(\"//*[@id='car-info-nav']/div[1]/div[1]/div[1]/table/tr[7]/td[2]/text()\"):\n div_num = 2\n item = TTPaiItem()\n item['title'] = response.xpath(\"//div[@class='car-title']/h1/span/text()\").extract_first()\n item['car_type'] = response.xpath(\"//*[@id='car-info-nav']/div[\"+str(div_num)+\"]/div[1]/div[1]/table/tr[7]/td[2]/text()\").extract_first()\n item['location'] = \"\"\n item['regi_location'] = \"\"\n item['first_regi'] = response.xpath(\"//*[@id='car-info-nav']/div[\"+str(div_num)+\"]/div[1]/div[1]/table/tr[4]/td[2]/text()\").extract_first()\n item['miles'] = response.xpath(\"//*[@id='car-info-nav']/div[\"+str(div_num)+\"]/div[1]/div[1]/table/tr[1]/td[2]/text()\").extract_first()\n item['color'] = response.xpath(\"//*[@id='car-info-nav']/div[\"+str(div_num)+\"]/div[1]/div[1]/table/tr[2]/td[2]/text()\").extract_first()\n item['ex_times'] = response.xpath(\"//*[@id='car-info-nav']/div[\"+str(div_num)+\"]/div[1]/div[1]/table/tr[10]/td[2]/text()\").extract_first()\n item['use_type'] = response.xpath(\"//*[@id='car-info-nav']/div[\"+str(div_num)+\"]/div[1]/div[1]/table/tr[6]/td[2]/span/text()\").extract_first()\n item['car_level_main'] = response.xpath(\"//div[@class='section-degree']/span[1]/text()\").extract_first()\n item['car_level_device'] = response.xpath(\"//div[@class='section-degree']/span[2]/text()\").extract_first()\n item['car_level_outer'] = response.xpath(\"//div[@class='section-degree']/span[3]/text()\").extract_first()\n item['car_level_inner'] = response.xpath(\"//div[@class='section-degree']/span[4]/text()\").extract_first()\n item['report_url'] = response.url\n item['price'] = response.xpath(\"//div[@class='section-km clearfix']/ul/li[4]/span/text()\").extract_first()\n item['grabtime'] = time.strftime('%Y-%m-%d %X', time.localtime())\n item['desc'] = response.xpath(\"//div[@class='section-info']/p/text()\").extract_first()\n item['status'] = response.url\n item['url'] = response.url\n yield item","sub_path":"cagey/carbuisness/carbuisness/spiders/ttpai.py","file_name":"ttpai.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"277214916","text":"from __future__ import absolute_import, division\n\nimport torch\nfrom torch.autograd import Variable\n\nimport numpy as np\nfrom scipy.ndimage.interpolation import map_coordinates as sp_map_coordinates\n\n\ndef th_flatten(a):\n \"\"\"Flatten tensor\"\"\"\n return a.contiguous().view(a.nelement())\n\n\ndef th_repeat(a, repeats, axis=0):\n \"\"\"Torch version of np.repeat for 1D\"\"\"\n assert len(a.size()) == 1\n return th_flatten(torch.transpose(a.repeat(repeats, 1), 0, 1))\n\n\ndef np_repeat_2d(a, repeats):\n \"\"\"TensorFlow version of np.repeat for 2D\"\"\"\n assert len(a.shape) == 2\n a = np.expand_dims(a, 0)\n a = np.tile(a, [repeats, 1, 1])\n return a\n\n\ndef th_gather_2d(inputs, coords):\n index = coords[:, 0] * inputs.size(1) + coords[:, 1]\n x = torch.index_select(th_flatten(inputs), 0, index)\n return x.view(coords.size(0))\n\n\ndef th_map_coordinates(inputs, coords, order=1):\n \"\"\"Tensorflow verion of scipy.ndimage.map_coordinates\n Note that coords is transposed and only 2D is supported\n Parameters\n ----------\n inputs: tf.Tensor. shape = (s, s)\n coords: tf.Tensor. shape = (n_points, 2)\n order:\n \"\"\"\n\n assert order == 1\n input_size = inputs.size(0)\n\n coords = torch.clamp(coords, 0, input_size - 1)\n coords_lt = coords.floor().long()\n coords_rb = coords.ceil().long()\n coords_lb = torch.stack([coords_lt[:, 0], coords_rb[:, 1]], 1)\n coords_rt = torch.stack([coords_rb[:, 0], coords_lt[:, 1]], 1)\n\n vals_lt = th_gather_2d(inputs, coords_lt.detach())\n vals_rb = th_gather_2d(inputs, coords_rb.detach())\n vals_lb = th_gather_2d(inputs, coords_lb.detach())\n vals_rt = th_gather_2d(inputs, coords_rt.detach())\n\n coords_offset_lt = coords - coords_lt.type(coords.data.type())\n\n vals_t = vals_lt + (vals_rt - vals_lt) * coords_offset_lt[:, 0]\n vals_b = vals_lb + (vals_rb - vals_lb) * coords_offset_lt[:, 0]\n mapped_vals = vals_t + (vals_b - vals_t) * coords_offset_lt[:, 1]\n return mapped_vals\n\n\ndef sp_batch_map_coordinates(inputs, coords):\n \"\"\"Reference implementation for batch_map_coordinates\"\"\"\n # coords = coords.clip(0, inputs.shape[1] - 1)\n\n assert (coords.shape[2] == 2)\n height = coords[:, :, 0].clip(0, inputs.shape[1] - 1)\n width = coords[:, :, 1].clip(0, inputs.shape[2] - 1)\n np.concatenate((np.expand_dims(height, axis=2), np.expand_dims(width, axis=2)), 2)\n\n mapped_vals = np.array([\n sp_map_coordinates(one_input, coord.T, mode='nearest', order=1)\n for one_input, coord in zip(inputs, coords)\n ])\n return mapped_vals\n\n\ndef th_batch_map_coordinates(inputs, coords, order=1):\n \"\"\"Batch version of th_map_coordinates\n Only supports 2D feature maps\n Parameters\n ----------\n inputs: tf.Tensor. shape = (b, s, s)\n coords: tf.Tensor. shape = (b, n_points, 2)\n order:\n Returns\n -------\n tf.Tensor. shape = (b, s, s)\n \"\"\"\n\n batch_size = inputs.size(0)\n input_height = inputs.size(1)\n input_width = inputs.size(2)\n\n n_coords = coords.size(1)\n\n # coords = torch.clamp(coords, 0, input_size - 1)\n\n coords = torch.cat((torch.clamp(coords.narrow(2, 0, 1), 0, input_height - 1), torch.clamp(coords.narrow(2, 1, 1), 0, input_width - 1)), 2)\n\n assert (coords.size(1) == n_coords)\n\n coords_lt = coords.floor().long()\n coords_rb = coords.ceil().long()\n coords_lb = torch.stack([coords_lt[..., 0], coords_rb[..., 1]], 2)\n coords_rt = torch.stack([coords_rb[..., 0], coords_lt[..., 1]], 2)\n idx = th_repeat(torch.arange(0, batch_size), n_coords).long()\n idx = Variable(idx, requires_grad=False)\n if inputs.is_cuda:\n idx = idx.cuda()\n\n def _get_vals_by_coords(tensor, tensor_coords):\n indices = torch.stack([\n idx, th_flatten(tensor_coords[..., 0]), th_flatten(tensor_coords[..., 1])\n ], 1)\n index = indices[:, 0] * tensor.size(1) * tensor.size(2) + indices[:, 1] * tensor.size(2) + indices[:, 2]\n vals = th_flatten(tensor).index_select(0, index)\n vals = vals.view(batch_size, n_coords)\n return vals\n\n vals_lt = _get_vals_by_coords(inputs, coords_lt.detach())\n vals_rb = _get_vals_by_coords(inputs, coords_rb.detach())\n vals_lb = _get_vals_by_coords(inputs, coords_lb.detach())\n vals_rt = _get_vals_by_coords(inputs, coords_rt.detach())\n\n coords_offset_lt = coords - coords_lt.type(coords.data.type())\n vals_t = coords_offset_lt[..., 0]*(vals_rt - vals_lt) + vals_lt\n vals_b = coords_offset_lt[..., 0]*(vals_rb - vals_lb) + vals_lb\n mapped_vals = coords_offset_lt[..., 1]* (vals_b - vals_t) + vals_t\n return mapped_vals\n\n\ndef sp_batch_map_offsets(inputs, offsets):\n \"\"\"Reference implementation for tf_batch_map_offsets\"\"\"\n batch_size = inputs.shape[0]\n input_height = inputs.shape[1]\n input_width = inputs.shape[2]\n\n offsets = offsets.reshape(batch_size, -1, 2)\n grid = np.stack(np.mgrid[:input_height, :input_width], -1).reshape(-1, 2)\n grid = np.repeat([grid], batch_size, axis=0)\n coords = offsets + grid\n # coords = coords.clip(0, input_size - 1)\n\n mapped_vals = sp_batch_map_coordinates(inputs, coords)\n return mapped_vals\n\n\ndef th_generate_grid(batch_size, input_height, input_width, data_type, cuda):\n grid = np.meshgrid(\n range(input_height), range(input_width), indexing='ij'\n )\n grid = np.stack(grid, axis=-1)\n grid = grid.reshape(-1, 2)\n\n grid = np_repeat_2d(grid, batch_size)\n grid = torch.from_numpy(grid).type(data_type)\n if cuda:\n grid = grid.cuda()\n return Variable(grid, requires_grad=False)\n\n\ndef th_batch_map_offsets(inputs, offsets, grid=None, order=1):\n \"\"\"Batch map offsets into input\n Parameters\n ---------\n inputs: torch.Tensor. shape = (b, s, s)\n grid:\n offsets: torch.Tensor. shape = (b, s, s, 2)\n Returns\n -------\n torch.Tensor. shape = (b, s, s)\n \"\"\"\n batch_size = inputs.size(0)\n input_height = inputs.size(1)\n input_width = inputs.size(2)\n\n offsets = offsets.view(batch_size, -1, 2)\n if grid is None:\n grid = th_generate_grid(batch_size, input_height, input_width, offsets.data.type(), offsets.data.is_cuda)\n\n coords = offsets + grid\n\n mapped_vals = th_batch_map_coordinates(inputs, coords)\n return mapped_vals\n","sub_path":"blackbox-deep-graph-matching/hades_painting/models/deform.py","file_name":"deform.py","file_ext":"py","file_size_in_byte":6255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"116153238","text":"# uncompyle6 version 2.10.1\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.8 (default, Apr 20 2019, 23:18:21) \n# [GCC 8.2.0]\n# Embedded file name: google3/third_party/py/defusedxml/common.py\n# Compiled at: 2019-06-18 16:41:38\n\"\"\"Common constants, exceptions and helpe functions\n\"\"\"\nimport sys\nPY3 = sys.version_info[0] == 3\n\nclass DefusedXmlException(ValueError):\n \"\"\"Base exception\n \"\"\"\n\n def __repr__(self):\n return str(self)\n\n\nclass DTDForbidden(DefusedXmlException):\n \"\"\"Document type definition is forbidden\n \"\"\"\n\n def __init__(self, name, sysid, pubid):\n super(DTDForbidden, self).__init__()\n self.name = name\n self.sysid = sysid\n self.pubid = pubid\n\n def __str__(self):\n tpl = \"DTDForbidden(name='{}', system_id={!r}, public_id={!r})\"\n return tpl.format(self.name, self.sysid, self.pubid)\n\n\nclass EntitiesForbidden(DefusedXmlException):\n \"\"\"Entity definition is forbidden\n \"\"\"\n\n def __init__(self, name, value, base, sysid, pubid, notation_name):\n super(EntitiesForbidden, self).__init__()\n self.name = name\n self.value = value\n self.base = base\n self.sysid = sysid\n self.pubid = pubid\n self.notation_name = notation_name\n\n def __str__(self):\n tpl = \"EntitiesForbidden(name='{}', system_id={!r}, public_id={!r})\"\n return tpl.format(self.name, self.sysid, self.pubid)\n\n\nclass ExternalReferenceForbidden(DefusedXmlException):\n \"\"\"Resolving an external reference is forbidden\n \"\"\"\n\n def __init__(self, context, base, sysid, pubid):\n super(ExternalReferenceForbidden, self).__init__()\n self.context = context\n self.base = base\n self.sysid = sysid\n self.pubid = pubid\n\n def __str__(self):\n tpl = \"ExternalReferenceForbidden(system_id='{}', public_id={})\"\n return tpl.format(self.sysid, self.pubid)\n\n\nclass NotSupportedError(DefusedXmlException):\n \"\"\"The operation is not supported\n \"\"\"\n pass\n\n\ndef _apply_defusing(defused_mod):\n assert defused_mod is sys.modules[defused_mod.__name__]\n stdlib_name = defused_mod.__origin__\n __import__(stdlib_name, {}, {}, ['*'])\n stdlib_mod = sys.modules[stdlib_name]\n stdlib_names = set(dir(stdlib_mod))\n for name, obj in vars(defused_mod).items():\n if name.startswith('_') or name not in stdlib_names:\n continue\n setattr(stdlib_mod, name, obj)\n\n return stdlib_mod\n\n\ndef _generate_etree_functions(DefusedXMLParser, _TreeBuilder, _parse, _iterparse):\n \"\"\"Factory for functions needed by etree, dependent on whether\n cElementTree or ElementTree is used.\"\"\"\n\n def parse(source, parser=None, forbid_dtd=False, forbid_entities=True, forbid_external=True):\n if parser is None:\n parser = DefusedXMLParser(target=_TreeBuilder(), forbid_dtd=forbid_dtd, forbid_entities=forbid_entities, forbid_external=forbid_external)\n return _parse(source, parser)\n\n def iterparse(source, events=None, parser=None, forbid_dtd=False, forbid_entities=True, forbid_external=True):\n if parser is None:\n parser = DefusedXMLParser(target=_TreeBuilder(), forbid_dtd=forbid_dtd, forbid_entities=forbid_entities, forbid_external=forbid_external)\n return _iterparse(source, events, parser)\n\n def fromstring(text, forbid_dtd=False, forbid_entities=True, forbid_external=True):\n parser = DefusedXMLParser(target=_TreeBuilder(), forbid_dtd=forbid_dtd, forbid_entities=forbid_entities, forbid_external=forbid_external)\n parser.feed(text)\n return parser.close()\n\n return (\n parse, iterparse, fromstring)\n# okay decompiling ./google3/third_party/py/defusedxml/common.pyc\n","sub_path":"pars/setup.uncompyle/google3/third_party/py/defusedxml/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"601706243","text":"# The following code is needed for us to check your answer, do not modify it, please.\nstudents = json.loads(input())\nBelov = students['Belov']\nSmith = students['Smith']\nSarada = students['Sarada']\n\n# Your code here. Work with the vriables 'Belov', 'Smith', and 'Sarada'\nmaterias = set()\nmaterias.update(Belov)\nmaterias.update(Smith)\nmaterias.update(Sarada)\nprint(len(materias))\n","sub_path":"Topics (1)/Set/Counting unique/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"91227131","text":"# Hint: You may not need all of these. Remove the unused functions.\nfrom hashtables import (HashTable,\n hash_table_insert,\n hash_table_retrieve\n)\n\n\nclass Ticket:\n def __init__(self, source, destination):\n self.source = source\n self.destination = destination\n\n\ndef reconstruct_trip(tickets, length):\n hashtable = HashTable(length)\n route = [None] * length\n\n \"\"\"\n YOUR CODE HERE\n \"\"\"\n for ticket in tickets:\n hash_table_insert(hashtable, ticket.source, ticket.destination)\n if ticket.source == \"NONE\":\n route[0] = ticket.destination\n \n curr_ticket = route[0]\n pointer = 1\n while route[-1] is None:\n route[pointer] = hash_table_retrieve(hashtable, curr_ticket)\n curr_ticket = route[pointer]\n pointer += 1\n return route\n","sub_path":"hashtables/ex2/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"431082358","text":"import pandas as pd\nimport json\nimport requests\nimport numpy as np\n\nsheets_cards = pd.read_excel('../training dataset - medical.xlsx', sheet_name='Cardiology and Infectious Disea')\ndata_ans = pd.DataFrame(sheets_cards)\nn = len(data_ans.index)\n\nmcq = ['A', 'B', 'C', 'D', 'E']\n\n\n\n\nanswers = data_ans['Answer.answer' + 'A']\nquestions = data_ans['Answer.question']\n\nlabels_ans = data_ans['Answer.image.label']\n\nfor i in range(n):\n print(answers[i])\n print(answers.iloc[i])\n","sub_path":"test/test-datasetIII.py","file_name":"test-datasetIII.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"154862114","text":"from dash import callback_context\nfrom dash.dependencies import Input, Output, State\nfrom dash.exceptions import PreventUpdate\nimport dash_table\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport pandas as pd\nfrom itertools import compress\n\nfrom utils.load_df import siseri_quarter_df\nfrom utils.anomaly_utils import get_iqr_enveloppes\nfrom config import cfg\n\n\ndef get_worker_df(worker_id):\n if worker_id is None:\n return pd.DataFrame()\n else:\n worker_df = siseri_quarter_df[siseri_quarter_df['worker_id'] == worker_id]\n return worker_df\n\n\ndef get_worker_measures_data(worker_df):\n if worker_df.empty:\n return None\n else:\n data_df = worker_df.copy()\n data_df = data_df.sort_values('measure_quarter', ascending=False)\n data_df = data_df[cfg.WORKER_TABLE_COLUMNS]\n\n if 'measure_quarter' in data_df.columns:\n data_df['measure_quarter_ts'] = data_df['measure_quarter'].dt.to_timestamp()\n data_df['measure_quarter'] = data_df['measure_quarter'].astype(str)\n\n return data_df.to_dict('records')\n\n\ndef get_worker_measures_hist(worker_df):\n if worker_df.empty:\n return {}\n\n fig = px.histogram(worker_df, x=\"measure_value\")\n\n if all(worker_df['measure_value'] == 0):\n fig.update_xaxes(range=[0, 1])\n\n fig.update_xaxes(title_text='Dosi [mSv]', title_font=dict(size=16))\n fig.update_yaxes(title_text='Number of measures', title_font=dict(size=16))\n\n return fig\n\n\ndef get_envelop_df(envelop_method, envelop_level):\n envelop_df = get_iqr_enveloppes(\n siseri_quarter_df,\n context='domain',\n level=envelop_level\n )\n return envelop_df\n\n\ndef add_worker_measures_on_fig(worker_df, fig):\n for worker_firm_id in worker_df['worker_firm_id'].unique():\n subplot_df = worker_df[worker_df['worker_firm_id'] == worker_firm_id]\n fig.add_trace(\n go.Scatter(\n x=subplot_df['measure_quarter_ts'],\n y=subplot_df['measure_value'],\n mode='markers',\n name=worker_firm_id,\n legendgroup=\"firm_id_group\"\n )\n )\n\n\ndef add_worker_envelop_on_fig(worker_df, envelop_df, fig, context='domain'):\n if context not in ['domain', 'sector']:\n raise AttributeError\n context_column = f\"{context}_type\"\n context_upper_bound = f\"{context}_upper_bound\"\n context_group = f\"{context}_group\"\n \n plot_df = pd.merge(\n worker_df[['worker_firm_id', 'measure_quarter_ts', 'domain_type','sector_type', 'measure_value']], \n envelop_df[[context_column, 'measure_quarter_ts', 'upper_bound']], \n on=[context_column, 'measure_quarter_ts'],\n how='left'\n ).rename(columns={'upper_bound': context_upper_bound})\n \n for context_type in plot_df[context_column].unique():\n subplot_df = plot_df[plot_df[context_column] == context_type]\n fig.add_trace(\n go.Scatter(\n x=subplot_df['measure_quarter_ts'],\n y=subplot_df[context_upper_bound],\n mode='lines',\n name=context_type,\n legendgroup=context_group\n )\n )\n\n\ndef get_worker_measures_scatter(worker_df, envelop_checklist, envelop_level):\n if worker_df.empty:\n return {}\n\n worker_plot_df = worker_df.copy()\n worker_plot_df['measure_quarter_ts'] = worker_plot_df['measure_quarter'].dt.to_timestamp()\n worker_plot_df['worker_firm_id'] = worker_plot_df['worker_firm_id'].astype(str)\n\n fig = go.Figure()\n add_worker_measures_on_fig(worker_plot_df, fig)\n\n if envelop_checklist:\n if 'domain' in envelop_checklist:\n domain_envelop_df = get_iqr_enveloppes(siseri_quarter_df, context='domain', level=envelop_level)\n domain_envelop_df['measure_quarter_ts'] = domain_envelop_df['measure_quarter'].dt.to_timestamp()\n add_worker_envelop_on_fig(worker_plot_df, domain_envelop_df, fig, context='domain')\n if 'sector' in envelop_checklist:\n sector_envelop_df = get_iqr_enveloppes(siseri_quarter_df, context='sector', level=envelop_level)\n sector_envelop_df['measure_quarter_ts'] = sector_envelop_df['measure_quarter'].dt.to_timestamp()\n add_worker_envelop_on_fig(worker_plot_df, sector_envelop_df, fig, context='sector')\n\n fig.update_layout(legend_title_text='worker_firm_id')\n\n return fig\n\n\ndef register_callbacks(app):\n @app.callback(\n Output('worker-store', 'data'),\n [Input('worker-id-input', 'value'), \n Input('worker-envelop-checklist', 'value')],\n [State('worker-store', 'data')]\n )\n def store_worker_id(worker_id, envelop_checklist, data):\n if worker_id is None:\n raise PreventUpdate\n \n if not data:\n data = {'worker_id': worker_id, 'envelop_checklist': envelop_checklist}\n else:\n data['worker_id'] = worker_id\n data['envelop_checklist'] = envelop_checklist\n return data\n\n @app.callback(\n Output('worker-measures-table', 'data'),\n [Input('worker-measures-scatter', 'selectedData'), \n Input('worker-data-store', 'modified_timestamp')], \n [State('worker-store', 'data'),\n State('worker-data-store', 'data')]\n )\n def set_worker_table(selected_data, ts, ctrl_data, data):\n\n # determine which input has fired\n ctx = callback_context\n if ctx.triggered:\n if ctx.triggered[0]['prop_id'] == 'worker-data-store.modified_timestamp':\n selected_data = None\n\n if selected_data is None:\n # to deal with first render\n if data['worker_data'] is None:\n worker_id = ctrl_data['worker_id']\n worker_df = get_worker_df(worker_id)\n worker_data = get_worker_measures_data(worker_df)\n else:\n worker_data = data['worker_data']\n return worker_data\n \n # render only selected points\n selected_points_list = selected_data['points']\n selected_points_list = [(point['x'], point['y']) for point in selected_points_list]\n \n table_points_list = [(point['measure_quarter_ts'].split('T')[0] , point['measure_value']) for point in data['worker_data']]\n table_bool_list = [point in selected_points_list for point in table_points_list]\n\n return list(compress(data['worker_data'], table_bool_list))\n\n @app.callback(\n [Output('worker-id-input', 'value'),\n Output('worker-envelop-checklist', 'value'),\n Output('worker-measures-scatter', 'figure'),\n Output('worker-measures-hist', 'figure'), \n Output('worker-data-store', 'data')],\n [Input('worker-ctrl-button', 'n_clicks')],\n [State('worker-store', 'data'), \n State('worker-data-store', 'data'), \n State('domains-ctrl-store-envelop', 'data')]\n )\n def set_worker_table_scatter(n_clicks, ctrl_data, data, ctrl_domains_data):\n worker_id = ctrl_data['worker_id']\n envelop_level=ctrl_domains_data[\"envelop_level_ctrl\"]\n envelop_checklist = ctrl_data['envelop_checklist']\n if envelop_checklist is None:\n envelop_checklist = []\n\n worker_df = get_worker_df(worker_id)\n\n worker_data = get_worker_measures_data(worker_df)\n data['worker_data'] = worker_data\n\n return worker_id, envelop_checklist, get_worker_measures_scatter(worker_df, envelop_checklist, envelop_level), get_worker_measures_hist(worker_df), data\n ","sub_path":"dash-app/modules/worker/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":7577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"319396128","text":"Import('env')\n\nfrom os.path import dirname\n\n_INCLUDES = [Dir('../lib').abspath, Dir('../src').abspath]\n\n_SOURCES = ['../src/syphonClient.mm', '../src/syphonServer.mm',\n\t\t'../src/syphonServerDirectory.mm', '../lib/SyphonNameboundClient.m']\n_SOURCES = [Dir(dirname(s)).abspath + '/' + s for s in _SOURCES]\n\nenv.Append(CPPPATH = _INCLUDES)\nenv.Append(APP_SOURCES = _SOURCES)\nenv.Append(FRAMEWORKS = ['Syphon'])\nenv.Append(FRAMEWORKPATH = [Dir('../lib').abspath])\n\n# copy Syphon.framework to app\nif 'APP_TARGET' in env:\n\tfout = env['APP_TARGET'] + '.app/Contents/Frameworks/Syphon.framework'\n\tfin = Dir('../lib/Syphon.framework').abspath\n\tCommand('#' + fout, fin, Copy(fout, fin))\n\nReturn('env')\n","sub_path":"scons/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"172934629","text":"from modules.aligner.aligner import aligner\nfrom modules.caller.caller import caller\nfrom modules.bamtools.bamer import bamer\nfrom config import caller_tool,align_tool\n\ndef fastq2vcf(fq1,fq2,prefix,bed):\n #1 align fastq2bam\n\n aln = aligner(fq1,fq2,prefix)\n bam = aln.alignBy(align_tool)\n\n #2 bam tools\n bamtool = bamer(bam,prefix)\n bamtool.dedups()\n bamtool.sorts()\n bamtool.index()\n bam = bamtool.bam\n\n #3call bam2vcf\n vc = caller(bam,prefix,bed)\n vc.callBy(caller_tool)\n vcf = vc.vcf\n\n return vcf\n\n\n#if __name__ == \"__main__\":\n# fastq2vcf(fq1,fq2,prefix,bed)\n","sub_path":"seq-service/fastq2vcf/fastq2vcf.py","file_name":"fastq2vcf.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"341975776","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport random\n\nfrom matplotlib import rc\nfrom matplotlib import rcParams\n\n__author__ = 'ernesto'\n\n# if use latex or mathtext\nrc('text', usetex=True)\nrcParams['text.latex.preamble'] = [r\"\\usepackage{amsmath}\"]\n\n\ndef sequential_lse(x, A0, var_A0, r):\n # numero de muestras de los datos\n N = x.shape[0]\n # inicialización de vectores con las estimaciones, ganancias\n # y varianzas del LS secuencial\n A_est = np.zeros((N, ))\n gains = np.zeros((N, ))\n vars = np.zeros((N, ))\n A_est[0] = A0\n vars[0] = var_A0\n for n in np.arange(1, N):\n gains[n] = vars[n - 1] / (vars[n - 1] + r ** n)\n A_est[n] = A_est[n - 1] + gains[n] * (x[n] - A_est[n - 1])\n vars[n] = (1 - gains[n]) * vars[n - 1]\n return gains, A_est, vars\n\n\n# Parámetros\nA = 10\nrs = [0.95, 1, 1.05]\nN = 100\n\n# Generación de los datos\nn_seq = len(rs)\nxs = np.zeros((N, n_seq))\nfor j in np.arange(n_seq):\n random.seed(35)\n #random.seed(40)\n #random.seed(65)\n r = rs[j]\n for i in np.arange(N):\n xs[i, j] = random.normalvariate(A, math.sqrt(r ** i))\n\ngains = np.zeros((N, n_seq))\nA_est = np.zeros((N, n_seq))\nvars = np.zeros((N, n_seq))\n\nfor j in np.arange(n_seq):\n r = rs[j]\n gains[:, j], A_est[:, j], vars[:, j] = sequential_lse(xs[:, j], xs[0, j], 1, rs[j])\n\nn = np.arange(N)\nprint(A_est[0, 0])\n\nydata_max = 20\nydata_min = 0\nest_max = 10.5\nest_min = 9.9\nvar_max = 1\nvar_min = 0\ngain_max = gains[1, 0]\ngain_min = 0\n\nfontsize = 13\n\nfig = plt.figure(0, figsize=(10, 7), frameon=False)\nj = 0\nax = plt.subplot2grid((12, 9), (0, 0), rowspan=3, colspan=3)\nplt.plot(n, xs[:, j], 'k')\nplt.ylim(ydata_min, ydata_max)\nplt.xlim(0, N-1)\nax.set_xticklabels([])\nplt.title('$r={:.2f}$'.format(rs[j]), fontsize=fontsize)\nplt.ylabel('$x[n]$', fontsize=fontsize)\nax = plt.subplot2grid((12, 9), (3, 0), rowspan=3, colspan=3)\nplt.plot(n, A_est[:, j], 'k')\nplt.ylim(est_min, est_max)\nplt.xlim(0, N-1)\nplt.plot([0, N-1], [A, A], 'k--', lw=1)\nax.set_xticklabels([])\nplt.ylabel('$\\hat{A}[n]$', fontsize=fontsize)\nax = plt.subplot2grid((12, 9), (6, 0), rowspan=3, colspan=3)\nplt.plot(n, vars[:, j], 'k')\nplt.ylim(var_min, var_max)\nplt.xlim(0, N-1)\nax.set_xticklabels([])\nplt.ylabel('$\\mathrm{var}(\\hat{A}[n])$', fontsize=fontsize)\nax = plt.subplot2grid((12, 9), (9, 0), rowspan=3, colspan=3)\nplt.plot(n[1:], gains[1:, j], 'k')\nplt.ylim(gain_min, gain_max)\nplt.xlim(0, N-1)\nplt.ylabel('$K[n]$', fontsize=fontsize)\nplt.xlabel('$n$', fontsize=fontsize)\ngain_lim = 1 - rs[j]\nplt.plot([0, N-1], [gain_lim, gain_lim], 'k--', lw=1)\n\nj += 1\nax = plt.subplot2grid((12, 9), (0, 3), rowspan=3, colspan=3)\nplt.plot(n, xs[:, j], 'k')\nplt.ylim(ydata_min, ydata_max)\nplt.xlim(0, N-1)\nplt.title('$r={:.2f}$'.format(rs[j]))\nax.set_xticklabels([])\nax.set_yticklabels([])\nax = plt.subplot2grid((12, 9), (3, 3), rowspan=3, colspan=3)\nplt.plot(n, A_est[:, j], 'k')\nplt.ylim(est_min, est_max)\nplt.xlim(0, N-1)\nax.set_xticklabels([])\nax.set_yticklabels([])\nplt.plot([0, N-1], [A, A], 'k--', lw=1)\nax = plt.subplot2grid((12, 9), (6, 3), rowspan=3, colspan=3)\nplt.plot(n, vars[:, j], 'k')\nplt.ylim(var_min, var_max)\nplt.xlim(0, N-1)\nax.set_xticklabels([])\nax.set_yticklabels([])\nax = plt.subplot2grid((12, 9), (9, 3), rowspan=3, colspan=3)\nplt.plot(n[1:], gains[1:, j], 'k')\nplt.ylim(gain_min, gain_max)\nplt.xlim(0, N-1)\nax.set_yticklabels([])\nplt.xlabel('$n$', fontsize=fontsize)\n\nj += 1\nax = plt.subplot2grid((12, 9), (0, 6), rowspan=3, colspan=3)\nplt.plot(n, xs[:, j], 'k')\nplt.ylim(ydata_min, ydata_max)\nplt.xlim(0, N-1)\nax.set_xticklabels([])\nax.set_yticklabels([])\nplt.title('$r={:.2f}$'.format(rs[j]))\nax = plt.subplot2grid((12, 9), (3, 6), rowspan=3, colspan=3)\nplt.plot(n, A_est[:, j], 'k')\nplt.ylim(est_min, est_max)\nplt.xlim(0, N-1)\nax.set_xticklabels([])\nax.set_yticklabels([])\nplt.plot([0, N-1], [A, A], 'k--', lw=1)\nax = plt.subplot2grid((12, 9), (6, 6), rowspan=3, colspan=3)\nplt.plot(n, vars[:, j], 'k')\nplt.ylim(var_min, var_max)\nplt.xlim(0, N-1)\nax.set_xticklabels([])\nax.set_yticklabels([])\nvar_lim = (rs[j]-1)/rs[j]\nplt.plot([0, N-1], [var_lim, var_lim], 'k--', lw=1)\nax = plt.subplot2grid((12, 9), (9, 6), rowspan=3, colspan=3)\nplt.plot(n[1:], gains[1:, j], 'k')\nplt.ylim(gain_min, gain_max)\nplt.xlim(0, N-1)\nax.set_yticklabels([])\nplt.xlabel('$n$', fontsize=fontsize)\n\nplt.savefig('problem_8_22.pdf', bbox_inches='tight')\n\nplt.show()","sub_path":"figuras/PycharmKayStatisticalReport/problem_8_22.py","file_name":"problem_8_22.py","file_ext":"py","file_size_in_byte":4400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"389672297","text":"#!/usr/bin/env python3\n\nimport subprocess\nimport threading\nimport socket\nimport time\nimport sys\n\nsubprocess.call('clear',shell=True)\n\nclass ThisThread(threading.Thread):\n #\n def __init__(self,threadName,host,begin,end):\n #\n threading.Thread.__init__(self)\n #\n self.threadName = threadName\n #\n self.host = host\n #\n self.begin = begin\n #\n self.end = end\n #\n def run(self):\n #\n ScanHost(self.threadName,self.host,self.begin,self.end)\n\ndef ScanHost(threadName,host,start,end):\n #\n try:\n #\n for port in range(int(start),int(end)):\n #\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n #\n socket.setdefaulttimeout(1)\n #\n response = s.connect_ex((host,port))\n #\n if(response == 0):\n #\n print(\"[*] %s : %i \" % (host,port))\n #\n except socket.error:\n #\n print(\"[!] Socket Error \")\n\nprint(\"[*] Threaded TCP Port Scanner [*]\")\n#\nhost = input(\"[+] Enter the subject host IP-> \")\n#\nstart = int(input(\"[+] Enter the first port-> \"))\n#\nend = int(input(\"[+] Enter the last port-> \"))\n#\ntotal_ports = end-start\n#\nports_per_thread = 30\n#\ntotal_number = total_ports / ports_per_thread\n\nif(total_ports % ports_per_thread != 0):\n #\n total_number = total_number+1\n #\nif(total_number > 300):\n #\n ports_per_thread = total_ports / 300\n #\n ports_per_thread = ports_per_thread + 1\n #\n if(total_ports%ports_per_thread != 0):\n #\n total_number = total_number+1\n #\nthreads = []\n#\nfor i in range(int(total_number)):\n #\n k = i\n #\n end_two = start+ports_per_thread\n #\n thread = ThisThread(\"T1\",host,start,end_two)\n #\n thread.start()\n #\nthreads.append(thread)\n#\nend = end_two\n#\nfor t in threads:\n #\n t.join()\n","sub_path":"Python-Penetration-Testing/ThreadedPortScanner.py","file_name":"ThreadedPortScanner.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"178706752","text":"import os\r\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_race.settings')\r\n\r\nimport django\r\ndjango.setup()\r\n\r\nimport re\r\nimport pandas \r\nfrom django.contrib.auth.models import User\r\nfrom django.db import transaction\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nfrom datetime import datetime\r\nfrom app_race.models import * #Vishnupriya\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport pandas \r\nfrom app_race.models import * #Vishnupriya\r\n\r\nurl = \"https://www.indiarace.com/Home/racingCenterEvent?venueId=3&event_date=2020-03-06&race_type=RESULTS\"\r\npage = requests.get(url)\r\npage_data = BeautifulSoup(page.content,\"html.parser\")\r\n\r\n\r\ntotal = page_data.find_all(\"div\",class_ = \"row winner_row\")\r\ntotal_race = len(total)\r\n\r\n\r\nwith transaction.atomic():\r\n for i in range(1,total_race+1):\r\n race_id = 'race-'+str((i))\r\n datas = []\r\n\r\n items = page_data.find_all(\"div\",id = race_id)\r\n\r\n table = items[0].find_all('table', attrs={'class':'result-table-new1'})\r\n table_len = len(table)\r\n for i in range(0,table_len): \r\n thead = table[0].find_all('thead')\r\n tbody = table[0].find_all('tbody')\r\n rows1 = thead[0].find_all('tr')\r\n rows2 = tbody[0].find_all('tr')\r\n\r\n\r\n\r\n for row in rows2:\r\n cols = row.find_all('td')\r\n cols = [ele.text.strip() for ele in cols]\r\n datas.append(cols) # Get rid of empty values\r\n data_len = len(datas)\r\n\r\n\r\n for data in datas:\r\n #race number\r\n raceno_data = items[0].find('div',class_ ='side_num')\r\n raceno = raceno_data.find('h1').text\r\n race_primarykey = raceno_data.find('h5').text\r\n\r\n #race heading datas\r\n racehead_data = items[0].find('div',class_ ='center_heading')\r\n main_head = racehead_data.find('h2').text\r\n main_subhead = racehead_data.find('h3').text\r\n\r\n #race distance\r\n racetime_data = items[0].find('div',class_ ='archive_time') \r\n race_distance = racetime_data.find('h4').text\r\n\r\n\r\n # main_head = main_head.strip()\r\n # main_head = main_head.replace(\" \", \"\")\r\n # main_head = \" \".join(main_head.split())\r\n\r\n\r\n #table Data\r\n Pl = data[0]\r\n h_no = data[1]\r\n horse_pedigree = data[2]\r\n desc = data[3]\r\n trainer = data[4]\r\n jockey = data[5]\r\n wt = data[6]\r\n al = data[7]\r\n dr = data[8]\r\n sh = data[9]\r\n won_by = data[10]\r\n dist_win = data[11]\r\n rtg = data[12]\r\n odds = data[13]\r\n time = data[14]\r\n\r\n result = Result(\r\n Pl = Pl,\r\n h_no = h_no,\r\n horse_pedigree = horse_pedigree,\r\n desc = desc,\r\n trainer = trainer,\r\n jockey = jockey,\r\n wt = wt,\r\n al = al,\r\n dr = dr,\r\n sh = sh,\r\n won_by = won_by,\r\n dist_win = dist_win,\r\n rtg = rtg,\r\n odds = odds,\r\n time = time,\r\n raceno = raceno,\r\n race_primarykey = race_primarykey,\r\n main_head = main_head,\r\n main_subhead = main_subhead,\r\n race_distance = race_distance,\r\n )\r\n result.full_clean()\r\n result.save()\r\n\r\n print(\"sucess\")\r\n\r\n","sub_path":"indiarace_resultdata.py","file_name":"indiarace_resultdata.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"524964552","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport requests, json, codecs, random, time\r\nimport logging\r\nfrom matplotlib import pyplot as plt\r\n\r\nlogging.basicConfig(level=logging.INFO)\r\n\r\n# get the response\r\nuserfile = open('user.txt')\r\nusers = userfile.readlines()\r\nuserfile.close()\r\n# cookiefile = open('cookie.txt')\r\n# cookie = cookiefile.read().strip()\r\n\r\nwf = codecs.open('info.txt', 'w', 'utf-8')\r\nmissing_file = open('info_missing_list.txt', 'w')\r\n\r\nfor userid in users:\r\n userid = userid.strip()\r\n logging.info('user ID:' + userid)\r\n\r\n headers = {\r\n 'Accept': 'application/json, text/plain, */*',\r\n 'Accept-Encoding': 'gzip, deflate, sdch, br',\r\n 'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',\r\n 'Connection': 'keep-alive',\r\n 'Host': 'm.weibo.cn',\r\n 'Referer': 'http://m.weibo.cn/u/%s?uid=%s&luicode=20000174&featurecode=20000180' % (userid, userid),\r\n 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) '\r\n 'AppleWebKit/601.1.46 (KHTML, like Gecko) '\r\n 'Version/9.0 Mobile/13B143 Safari/601.1',\r\n 'X-Requested-With': 'XMLHttpRequest'\r\n }\r\n\r\n URL = 'http://m.weibo.cn/api/container/getIndex?uid=%s&luicode=20000174&' \\\r\n 'featurecode=20000180&type=uid&value=%s&containerid=100505%s' % (userid, userid, userid)\r\n\r\n try:\r\n time.sleep(random.random() * 2 + 1)\r\n h = requests.get(url=URL, headers=headers)\r\n if h.text:\r\n logging.info('First Connection Succeeded')\r\n else:\r\n logging.warning('First Connection Failed')\r\n\r\n # get info\r\n text = json.loads(h.text)\r\n print(text)\r\n user_info = text['userInfo']\r\n # print(user_info.keys())\r\n # print(user_info)\r\n json.dump(user_info, wf, ensure_ascii=False)\r\n wf.write('\\n')\r\n logging.info('Scratch Succeeded!')\r\n\r\n\r\n except:\r\n logging.warning('Scratch Failed!')\r\n missing_file.write(userid + '\\n')\r\n time.sleep(random.random() * 2 + 2)\r\n\r\nwf.close()\r\nmissing_file.close()\r\n","sub_path":"scratch_info.py","file_name":"scratch_info.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"412369629","text":"from blob import *\nimport cv2 as cv\nimport param as pm\nimport numpy as np\n\nWHITE = 1.0\nBLACK = 0.0\nROTULATED = 0.99 # value of rotulated pixel\n\nALTURA_MIN = 7\nLARGURA_MIN = 7\nN_PIXELS_MIN = 15\n\n# funcao recursiva para rotular pixels e blob\ndef rotula(img, blob, y0, x0):\n img[y0, x0] = ROTULATED\n blob.addPixel(y0, x0)\n pixels = list()\n pixels.append((y0, x0))\n while(len(pixels) > 0):\n y0, x0 = pixels[0] \n del pixels[0] \n # vizinhança de 8\n for y in range(y0-1, y0+2):\n if(y < len(img) and y >= 0):\n for x in range(x0-1, x0+2):\n if (x >= 0 and x < len(img[y])):\n if(img[y, x] == WHITE):\n img[y, x] = ROTULATED\n blob.addPixel(y, x)\n pixels.append((y, x)) \n\n# get list of blobs in image\ndef getBlobs(img):\n blobs = []\n for y in range(0, len(img)):\n for x in range(0, len(img[y])):\n if(img[y, x] == WHITE):\n blobs.append(Blob())\n rotula(img, blobs[-1], y, x)\n return blobs\n\n# funcao para validar o blob\ndef validaBlobs(blobs):\n valBlobs = []\n for blob in blobs:\n if (blob.nPixel < N_PIXELS_MIN):\n continue\n if((blob.xmax - blob.xmin) < LARGURA_MIN):\n continue\n if((blob.ymax - blob.ymin) < ALTURA_MIN):\n continue\n valBlobs.append(blob)\n return valBlobs\n\n\ndef checkDiscontinuity(blob, imgBin):\n disc = [0, 0]\n # check vertical discontinuities\n for x in range(blob.xmin, blob.xmax+1):\n val = imgBin[blob.ymin, x]\n change = 0\n for y in range(blob.ymin+1, blob.ymax+1):\n if imgBin[y, x] != val:\n val = imgBin[y, x]\n change += 1\n if change > 2:\n disc[0] += 1\n break\n # check horizontal discontinuities\n for y in range(blob.ymin, blob.ymax+1):\n val = imgBin[y, blob.xmin]\n change = 0\n for x in range(blob.xmin+1, blob.xmax+1):\n if imgBin[y, x] != val:\n val = imgBin[y, x]\n change += 1\n if change > 2:\n disc[1] += 1\n break\n return disc\n\n\ndef erodeBlob(blob, imgBin):\n kernel = np.ones((pm.KERNEL_SIZE, pm.KERNEL_SIZE), np.uint8)\n imgErode = cv.erode(imgBin, kernel, iterations=1)\n # update blob pixels to pixels from eroded image\n for y, x in blob.pixels:\n imgBin[y, x] = imgErode[y, x]\n\n\ndef updateBlob(blobs, blobUpdate, imgBin):\n # \"unrotulate\" all non black pixels in blob\n for y, x in blobUpdate.pixels:\n if(imgBin[y, x] > BLACK):\n imgBin[y, x] = WHITE\n newBlobs = []\n\n # rotulate blob area again\n for y, x in blobUpdate.pixels:\n if(imgBin[y, x] == WHITE):\n newBlobs.append(Blob())\n rotula(imgBin, newBlobs[-1], y, x)\n return newBlobs\n\n\ndef treatBlobs(blobs, imgBin):\n newBlobs = []\n treatedBlobs = []\n for blob in blobs:\n disc = checkDiscontinuity(blob, imgBin)\n # if the blobs has at least two discontinuities\n if(sum(disc) >= 2):\n erodeBlob(blob, imgBin)\n resBlobs = updateBlob(blobs, blob, imgBin)\n # if the blob was destroyed, consider the old one as a new blob\n if len(resBlobs) == 0:\n newBlobs.append(blob)\n else:\n treatedBlobs.append(blob)\n # add blobs created to new Blobs\n for resBlob in resBlobs:\n newBlobs.append(resBlob)\n \n # remove treated blobs\n for blob in treatedBlobs:\n blobs.remove(blob)\n # add new blobs\n for blob in newBlobs:\n blobs.append(blob)\n \n return (treatedBlobs, newBlobs)","sub_path":"Implementacoes/04 - Arroz/funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"58247030","text":"from collections import Counter\nclass Solution(object):\n def canMakePaliQueries(self, s, queries):\n \"\"\"\n :type s: str\n :type queries: List[List[int]]\n :rtype: List[bool]\n \"\"\"\n# straightforward method, TLE\n# res = []\n \n# for start, end, replace in queries:\n# substring = s[start:end+1]\n# count = self.makePalindrome(substring)\n# count = count//2\n# if count<=replace:\n# res.append(True)\n# else:\n# res.append(False)\n# return res\n \n# def makePalindrome(self, substring):\n# hmap = Counter(substring)\n# count = 0\n# for key in hmap:\n# if hmap[key]%2 == 1:\n# count+=1\n# return count\n\n res = []\n pre = [[True]*26]\n for idx, val in enumerate(s):\n tmp = pre[-1][:]\n tmp[ord(val)-ord('a')]^=True\n pre.append(tmp)\n for l, r, replace in queries:\n res.append( replace>=sum((pre[r+1][i]-pre[l][i])%2 == 1 for i in range(26))//2 )\n return res","sub_path":"1177-CanMakePalindromeFromSubstring.py","file_name":"1177-CanMakePalindromeFromSubstring.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"357724909","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def levelOrderBottom(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root:\n return []\n res = []\n queue = [root]\n while queue:\n cur = []\n nxt = []\n for q in queue:\n cur.append(q.val)\n if q.left:\n nxt.append(q.left)\n if q.right:\n nxt.append(q.right)\n # res.insert(0, cur)\n res.append(cur)\n queue = nxt\n return res[::-1]\n # return res\n","sub_path":"0107_Binary_Tree_Level_Order_Traversal_II.py","file_name":"0107_Binary_Tree_Level_Order_Traversal_II.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"223536412","text":"import os\nimport shutil\n\n\ndef makefolders(folder_name):\n image_classes={}\n for image_name in sorted(os.listdir(folder_name)):\n class_name=image_name.split('_')[0]\n if class_name in image_classes:\n image_classes[class_name].append(image_name)\n else:\n image_classes[class_name]=[image_name]\n if not os.path.isdir('foldered_data'):\n os.makedirs('foldered_data')\n class_list = sorted(list(image_classes.keys()))\n for c_name in class_list:\n os.makedirs('foldered_data/'+c_name)\n images_in_class = image_classes[c_name]\n for i_name in images_in_class:\n shutil.copyfile(folder_name+'/'+i_name,'foldered_data/'+c_name+'/'+i_name)\n\nmakefolders('TEST')","sub_path":"make_foldered_data.py","file_name":"make_foldered_data.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"12576414","text":"# NO IMPORTS!\n\n# def setup_trie(words = None):\n# # build an empty tree\n# trie = Trie()\n\n# # insert words from corpus or from supplied list\n# if words == 'jules_verne':\n# with open(os.path.join(TEST_DIRECTORY, 'testing_data', 'words.json')) as f:\n# words = json.load(f)\n# # pre-compute frequency to avoid a zillion\n# # separate inserts for each word in corpus\n# for w in set(words):\n# trie.insert(w, words.count(w))\n# else:\n# for w in words:\n# trie.insert(w)\n\n# # okay, our work here is done...\n# return trie\n\n# def dictify(trie,prefix=''):\n# if trie is None: return None\n# result = {\"frequency\": trie.frequency, \"children\": {}}\n# for ch,child in trie.children.items():\n# result[\"children\"][ch] = dictify(child,prefix + ch)\n# return result\n\n\n\nclass Trie:\n ##################################################\n ## basic methods\n ##################################################\n\n def __init__(self, freq=0):\n self.frequency = freq #Number of times the word occurs\n self.children = {} #dictionary of children\n\n def insert(self, word, frequency=0):\n \"\"\" add word with given frequency to the trie. \"\"\"\n pointer = self\n for i in range(len(word)): \n letter = word[i]\n if letter in pointer.children:\n pointer = pointer.children[letter]\n \n else:\n pointer.children[letter] = Trie(0)\n pointer = pointer.children[letter]\n \n if i == len(word)-1:\n if frequency != 0:\n pointer.frequency = frequency\n else:\n pointer.frequency += 1\n\n def find(self,prefix):\n \"\"\" return trie node for specified prefix, None if not in trie. \"\"\"\n if len(prefix) == 0:\n return self\n else:\n next_letter = prefix[0]\n if next_letter in self.children:\n return self.children[next_letter].find(prefix[1:])\n else: \n return None\n\n def __contains__(self, word):\n \"\"\" is word in trie? return True or False. \"\"\"\n node = self.find(word)\n if node is None:\n return False\n elif node.frequency == 0:\n return False\n return True\n\n\n def __iter__(self):\n \"\"\" generate list of (word,freq) pairs for all words in\n this trie and its children. Must be a generator! \"\"\"\n\n if self.frequency > 0:\n yield (\"\", self.frequency)\n for letter, child in self.children.items():\n for word, freq in child:\n yield (letter + word, freq)\n\n ##################################################\n ## additional methods\n ##################################################\n\n def sort_list_by_freq(self, l):\n l.sort(key = lambda tup: -tup[1])\n return l\n\n def autocomplete(self, prefix, N, index=0):\n \"\"\" return the list of N most-frequently occurring words\n that start with prefix. \"\"\"\n possibilities = []\n prefix_node = self.find(prefix)\n if prefix_node is None:\n return []\n # elif prefix_node.frequency > 0:\n # possibilities.append((prefix, prefix_node.frequency))\n\n for word, freq in prefix_node:\n possibilities.append((prefix + word, freq))\n # print(possibilities)\n possibilities = self.sort_list_by_freq(possibilities)\n # if len(possibilities) <= N:\n # return possibilities\n return [i[0] for i in possibilities[:N]]\n \n def update_result(self, result, potential):\n node = self.find(potential)\n if node is not None and node.frequency > 0:\n result.append((potential, node.frequency))\n # print(result)\n return result\n\n def inserted_check(self, prefix, i):\n letters = [chr(i) for i in range(ord('a'), ord('z')+1)]\n result = []\n for letter in letters:\n inserted_option = prefix[:i] + letter + prefix[i:]\n result = self.update_result(result, inserted_option)\n return result\n\n def repleacement_check(self, prefix, i):\n letters = [chr(i) for i in range(ord('a'), ord('z')+1)]\n result = []\n for letter in letters:\n replace_option = prefix[:i] + letter + prefix[i+1:]\n # print(replace_option)\n result = self.update_result(result, replace_option)\n return result\n\n def deletion_check(self, prefix, i):\n deleted_option = prefix[:i] + prefix[i+1:]\n result = self.update_result([], deleted_option)\n return result\n\n def transpose_check(self, prefix, i):\n transpose_option = prefix[:i] + prefix[i+1] + prefix[i] + prefix[i+2:]\n result = self.update_result([], transpose_option)\n return result\n\n def corrections(self, prefix, count):\n \"\"\" \n Create a list of count words with the \n \"\"\"\n corrections = []\n for i in range(len(prefix)):\n corrections += self.inserted_check(prefix, i) #return a list of (word, freq)\n corrections += self.repleacement_check(prefix, i)\n if i < len(prefix)-1:\n corrections += self.deletion_check(prefix, i) \n corrections += self.transpose_check(prefix, i)\n # print(\"corrections\",corrections)\n corrections = list(set(corrections))\n corrections = self.sort_list_by_freq(corrections)\n return [i[0] for i in corrections[:count]]\n\n def autocorrect(self, prefix, N):\n \"\"\" return the list of N most-frequent words that start with\n prefix or that are valid words that differ from prefix\n by a small edit. \"\"\"\n completions = self.autocomplete(prefix, N)\n if len(completions) > N:\n return completions\n corrections = self.corrections(prefix, N-len(completions)) #return top N-len freq words with that prefix\n final = completions + corrections\n return final\n\n\n def matches_pattern(self, word_obj, pattern):\n word, freq = word_obj\n i_w, i_p = 0, 0\n # print(word_obj)\n # print(pattern)\n\n if i_w < len(word) and i_p < len(pattern):\n if word[i_w] == pattern[i_p]:\n i_w += 1\n i_p += 1\n is_done = self.matches_pattern((word[i_w:], freq), pattern[i_p:])\n if is_done:\n return True\n elif pattern[i_p] == \"?\":\n i_w += 1\n i_p += 1 \n is_done = self.matches_pattern((word[i_w:], freq), pattern[i_p:])\n if is_done:\n return True\n elif pattern[i_p] == \"*\":\n if i_p == len(pattern)-1: #final letter or only letter\n return True\n\n is_done_1 = self.matches_pattern((word[1:], freq), pattern[1:])\n is_done_2 = self.matches_pattern((word[1:], freq), pattern)\n if is_done_1 or is_done_2:\n return True\n return False\n return False\n if word == \"\" and pattern not in (\"\", \"*\"):\n return False\n\n elif pattern == \"\" and word != \"\":\n return False\n\n return True\n\n def filter(self,pattern):\n \"\"\" return list of (word, freq) for all words in trie that match\n pattern. pattern is a string, interpreted as explained below:\n * matches any sequence of zero or more characters,\n ? matches any single character,\n otherwise char in pattern char must equal char in word. \"\"\"\n result = []\n for word_obj in self:\n match = self.matches_pattern(word_obj, pattern)\n # print(word_obj, pattern, match)\n if match:\n result.append(word_obj)\n return result\n\n# handy stand-alone testing setup\nif __name__ == '__main__':\n # read in words\n import json # this import allowed as part of testing...\n with open('testing_data/words.json') as f:\n words = json.load(f)\n\n\n trie = Trie() \n result = trie.matches_pattern((\"mattress\", 3), '*???')\n # print(result)\n \"\"\"\n # small corpus: insert words one-by-one\n trie = Trie()\n for w in words[:50]: trie.insert(w)\n \"\"\"\n\n # large corpus: precompute count for each word\n trie = Trie()\n for w in set(words):\n trie.insert(w,words.count(w))\n\n # your test here!\n # Example: 5- or more letter words beginning in \"a\" and ending in \"ing\"\n #print(trie.filter('a?*ing'))\n","sub_path":"lab6/bb.py","file_name":"bb.py","file_ext":"py","file_size_in_byte":8765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"579527932","text":"def STORY():\r\n\t\"\"\"\r\n\tThis is the 'STORY MODE'.\r\n\tThe goal is to get to floor 1, beat the behemoth\r\n\tand just DON'T DIE. \r\n\tZork, this was made by Alastar S.\r\n\tThis game is- free-ware.. Free to distribute,\r\n\tbut please don't change and say it is your own?\r\n\tI will be making changes in the future, just contact\r\n\tme for the next versions (until' I stop development).\r\n\t\"\"\"\r\n\r\n\tfrom os import system\r\n\t#Important classes\r\n\tfrom tools import Player, Zombie, Chest\r\n\t#Important functions\r\n\tfrom tools import character_setup, mov_user, draw_room, clear, mov_direction\r\n\tfrom tools import draw_dialog, enemy_attack, pause\r\n\t#For tests\r\n\tfrom tools import user_pos_setup, mk_room, Getch\r\n\t#SO we can tell the user how long they played for\r\n\t#from datetime import datetime\r\n\timport time\r\n\tfrom time import sleep #To make program wait\r\n\r\n\t#This is for crediting people (like playtesters)\r\n\t# in the Special Thanks section of the credits\r\n\tdef credit_in_special_thanks(msg):\r\n\t\tprint(\"\\t - {}\".format(msg))\r\n\t\tsleep(1)\r\n\r\n\t#This is the player\r\n\tuser = Player(input(\"What is your name?: \"))\r\n\r\n\tstartTime = time.time() #The start time\r\n\r\n\t#Makes the room, and sets up stuff for player\r\n\troom, user.pos = character_setup()\r\n\r\n\t#Draws character for first time\r\n\troom[user.pos[1]][user.pos[0]] = \"@\"\r\n\r\n\tskip = False #Skip movement of AI\r\n\tfloor = 90 #128 #The floor that the player is on\r\n\t#For the final message, says \"Damn {number} floors- they were tired\"\r\n\tstarting_floor_number = floor\r\n\r\n\tchange_floor = -1 #Subtract 1\r\n\r\n\tmobs = {} #This dictionary contains every enemy\r\n\tobjects = {} #All of the objects (like chests)\r\n\r\n\tdialog = [] #Stuff to be printed\r\n\texit = False #If the user wants to exit\r\n\r\n\tmob_number = 0 #Number of mobs\r\n\r\n\tclear() #Clear screen at start\r\n\tprint(\"FLOOR: {}\".format(floor)) #Prints floor number\r\n\tprint(\"HP: {}\".format(user.hp)) #Prints health of player\r\n\tprint(\"Hint: press 'h' for help\") #Tell user where help is\r\n\tdraw_room(room) #Draw room at start\r\n\r\n\twhile True: #Keep going until user presses escape\r\n\t\t#For the user moving\r\n\t\tuser.pos,room,floor,mobs,objects,dialog,skip,exit,addOnTime = mov_user('story',user,room,floor,user.char,mobs,objects, change_floor, startTime,0)\r\n\r\n\t\t#If we are exiting the menu\r\n\t\tif exit == True: break\r\n\r\n\t\t#This is the end of the game\r\n\t\tif floor == 0:\r\n\t\t\tclear()\r\n\t\t\tend = int((time.time() - startTime)/60)\r\n\r\n\t\t\tprint(\"{} stood upon the body of the mighty beast.\".format(user.name))\r\n\t\t\tsleep(2)\r\n\t\t\tprint(\"{} looked at the Behemoth- surprised they killed that thing.\".format(user.name))\r\n\t\t\tsleep(3)\r\n\t\t\tprint(\"{} was really tired. I mean- damn, {} floors.\".format(user.name, starting_floor_number))\r\n\t\t\tsleep(3)\r\n\t\t\tprint(\"Covered in blood, {} gets off of the beast and walks\".format(user.name))\r\n\t\t\tprint(\"over to the corner of the room. There, a mighty chest lies.\")\r\n\t\t\tsleep(4)\r\n\t\t\tprint(\"Putting down {} {} pries open the chest.\".format(user.inventory['primary'][1], user.name))\r\n\t\t\tsleep(3)\r\n\t\t\tprint(\"Inside is a small blue vial containing an unknown fluid.\")\r\n\t\t\tprint(\"The color of the vial's contents slowly changes in hue.\")\r\n\t\t\tsleep(4)\r\n\t\t\tprint(\"This is why {} came here. For this mysterious vile.\".format(user.name))\r\n\t\t\tprint(\"If {}'s lover was to keep living, they would need this.\".format(user.name))\r\n\t\t\tsleep(4)\r\n\t\t\tprint(\"{} stuffed the vile into their pocket, and proceeded to the stairs.\".format(user.name))\r\n\t\t\tsleep(3)\r\n\t\t\tprint(\"It was going to be a long climb up, but it was worth it.\")\r\n\t\t\tsleep(3)\r\n\t\t\tprint(\"{} left, leaving the Behemoth behind, leaving this place behind.\".format(user.name))\r\n\t\t\tsleep(3)\r\n\t\t\tprint(\"{} went home.\".format(user.name))\r\n\t\t\tsleep(3)\r\n\t\t\tprint(\"_____________________________________________________\")\r\n\t\t\tprint(\"_____________________________________________________\")\r\n\t\t\tprint(\"\\n\\t\\t\\tThe End.\")\r\n\t\t\tprint(\"\\t\\t Play time: {} mins\".format(end))\r\n\t\t\tsleep(3) #Wait for credits\r\n\t\t\t\r\n\t\t\tprint(\"\\n\\n\\nPress anything to proceed..\")\r\n\t\t\tpause()\r\n\t\t\tclear()\r\n\r\n\t\t\tprint(\"CREDITS:\")\r\n\t\t\tprint(\"_____________\\n\")\r\n\r\n\t\t\tprint(\"Lead advisor: Kieran Slater\\n\")\r\n\t\t\tsleep(2)\r\n\t\t\tprint(\"Co-writer: Jacob Conrad\\n\")\r\n\t\t\tsleep(2)\r\n\t\t\tprint(\"Lead programmer: Alastar's fingers\\n\")\r\n\t\t\tsleep(2)\r\n\r\n\t\t\t#Special thanks section\r\n\t\t\tprint(\"Special thanks to:\")\r\n\t\t\tprint(\"_____________________\")\r\n\t\t\tsleep(1.5)\r\n\t\t\t#Thank my dad\r\n\t\t\tcredit_in_special_thanks(\"Dan S. [parental unit], [play tester]\")\r\n\t\t\t#Credit my brother\r\n\t\t\tcredit_in_special_thanks(\"Kieran S. [play tester], [lead advisor]\")\r\n\t\t\t#Credit Noah T.\r\n\t\t\tcredit_in_special_thanks(\"Noah T. [play tester]\")\r\n\t\t\t#Thank Susie S.\r\n\t\t\tcredit_in_special_thanks(\"Susie S. [play tester]\")\r\n\t\t\t#Thank Alex F.\r\n\t\t\tcredit_in_special_thanks(\"Alex F. [play tester]\")\r\n\t\t\t#Thank Rowan P.\r\n\t\t\tcredit_in_special_thanks(\"Rowan P. [play tester]\")\r\n\t\t\t#Thank Paris D.\r\n\t\t\tcredit_in_special_thanks(\"Paris D. [play tester]\")\r\n\t\t\t#Thank Jacob C.\r\n\t\t\tcredit_in_special_thanks(\"Jacob C. [play tester], [co-writer]\")\r\n\t\t\t#Thank Mark Z.\r\n\t\t\tcredit_in_special_thanks(\"Mark Z. [play tester]\")\r\n\r\n\t\t\t#Wait for next section\r\n\t\t\tsleep(2)\r\n\r\n\t\t\tprint(\"\\nEnd message:\")\r\n\t\t\tprint(\"_____________________\")\r\n\t\t\tsleep(1.5)\r\n\t\t\tprint(\"\\nI hoped you enjoyed! This has been a fun\")\r\n\t\t\tsleep(1.5)\r\n\t\t\tprint(\"little project of mine (mainly to see if I\")\r\n\t\t\tsleep(1.5)\r\n\t\t\tprint(\"could even do graphics like this!) and it \")\r\n\t\t\tsleep(1.5)\r\n\t\t\tprint(\"has been.. interesting. This is formally\")\r\n\t\t\tsleep(1.5)\r\n\t\t\tprint(\"'my first game', and it was fun! The making\")\r\n\t\t\tsleep(1.5)\r\n\t\t\tprint(\"of Rouge-like's is interesting (and I actually\")\r\n\t\t\tsleep(1.5)\r\n\t\t\tprint(\"think I may make more if my brother pushes\")\r\n\t\t\tsleep(1.5)\r\n\t\t\tprint(\"me enough for it).\")\r\n\t\t\tsleep(1.5)\r\n\t\t\tprint(\"Thanks for all of the fish.\")\r\n\t\t\tprint(\"- Alastar\")\r\n\t\t\tsleep(2)\r\n\r\n\t\t\tprint(\"\\n\\nPress anything to win..\")\r\n\t\t\tpause()\r\n\t\t\tbreak #Stop story mode\r\n\r\n\t\t#If there are any mobs\r\n\t\tif skip == False and len(mobs) > 0:\r\n\t\t\t#Go through every mob\r\n\t\t\tfor index in mobs:\r\n\t\t\t\t#Gets the movement of the monster\r\n\t\t\t\tmov = mov_direction(user.pos, mobs[index].pos, room)\r\n\t\t\t\t#Moves monster\r\n\t\t\t\tmobs[index].pos,room,floor,mobs,objects,X,Y,skip,W = mov_user('story',mobs[index],room,floor,mobs[index].char,mobs,objects,change_floor,startTime,0,mov)\r\n\r\n\t\t\t#Allow any mobs that can, attack, attack\r\n\t\t\tuser, dialog = enemy_attack(user, dialog, room, mobs)\r\n\r\n\t\t\t#If the user is dead now.\r\n\t\t\tif user.hp <= 0:\r\n\t\t\t\tdeath_time = int((time.time() - startTime)/60) #Time they died\r\n\t\t\t\tclear()\r\n\t\t\t\t#The total play-time of the player (in minutes)\r\n\t\t\t\t#time_of_death_minutes = abs(death_time.minute - startTime.minute)\r\n\t\t\t\t#The total play-time of the player (in hour)\r\n\t\t\t\t#time_of_death_hours = abs(death_time.hour - startTime.hour)\r\n\t\t\t\t#Rest in piece \r\n\t\t\t\tdeath_message = \"Rest in piece {}\".format(user.name)\r\n\t\t\t\t#Bumper to center the gravestone\r\n\t\t\t\tbumper = (len(death_message)//2-1)*' '\r\n\r\n\t\t\t\t#Shows death screen\r\n\t\t\t\tprint(bumper+\" ______\")\r\n\t\t\t\tprint(bumper+\" / \\\\\")\r\n\t\t\t\tprint(bumper+\"| |\")\r\n\t\t\t\tprint(bumper+\"| R.I.P. |\")\r\n\t\t\t\tprint(bumper+\"| |\")\r\n\t\t\t\tprint(bumper+\"|________|\")\r\n\t\t\t\tprint(death_message)\r\n\t\t\t\t#Prints out play time in hours and minutes\r\n\t\t\t\tprint(\" Play time: {} mins\".format(death_time))\r\n\t\t\t\tpause()\r\n\t\t\t\tbreak #Stop game\r\n\r\n\t\tclear() #Clear previous frame of game\r\n\t\tprint(\"FLOOR: {}\".format(floor)) #Prints floor number\r\n\t\tprint(\"HP: {}\".format(user.hp)) #Prints health of player\r\n\r\n\t\t#Print hp of the boss if we are on floor 1\r\n\t\tif floor == 1 and len(mobs)>0: print(\"BEHEMOTH: {}\".format(mobs[0].hp))\r\n\t\t\r\n\t\tdraw_room(room) #draw current frame\r\n\t\tdraw_dialog(dialog) #Draws response dialog\r\n","sub_path":"Story_mode.py","file_name":"Story_mode.py","file_ext":"py","file_size_in_byte":7654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"326788940","text":"#Leia 3 (três) números (cada número corresponde a um lado do triângulo), \r\n#verifique e escreva se os 3 (três) números formam um triângulo \r\n#(a soma de dois lados não pode ser menor que o terceiro lado). \r\n#Se formam, verifique se formam um triângulo equilátero (3 lados iguais), isósceles (2 lados iguais) ou\r\n#escaleno (3 lados diferentes). Não existe lado com tamanho 0 (zero).\r\n\r\na = int(input('Qual o primeiro lado? '))\r\nb = int(input('Qual o segundo lado? '))\r\nc = int(input('Qual o terceiro lado? '))\r\n\r\nif a + b < c or a + c < b or b + c < a:\r\n print('Não é um triângulo')\r\n\r\nif a == b == c:\r\n print('É um triângulo equilátero')\r\n\r\nelif a == b and a == c or b == c and b == a or c == a and c == b:\r\n print('É um triângulo isósceles')\r\n\r\nelif a != b and b != c:\r\n print('É um triângulo escaleno')","sub_path":"Fabio02_P01/F2_P1_Q7_LADOSTRIANGULO.py","file_name":"F2_P1_Q7_LADOSTRIANGULO.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"35388977","text":"from django.test import TestCase\nfrom django.contrib.auth.models import User\nfrom .models import RawMaterial, MeasurementType, Supplier, Currency\n\n\nclass MaterialTests(TestCase):\n @classmethod\n def setUpTestData(cls):\n testuser1 = User.objects.create_user(\n username='testuser1', password='deneme123'\n )\n measurement_type = MeasurementType.objects.create(code='KG', name='Kilogram')\n supplier = Supplier.objects.create(\n name='Tesla', phone=123, email='tesla@tesla.com',\n address='San Francisco-California-USA'\n )\n currency = Currency.objects.create(code='USD', name='United States Dollar')\n test_material = RawMaterial.objects.create(\n accountant=testuser1, material_name='tesla model 3', measurement_type=measurement_type,\n total_amount=1, price=50.00, currency=currency, supplier=supplier\n )\n\n def test_material(self):\n material = RawMaterial.objects.get(id=1)\n accountant = f\"{material.accountant}\"\n name = f\"{material.material_name}\"\n measurement_type = f\"{material.measurement_type}\"\n total_amount = f\"{material.total_amount}\"\n price = f\"{material.price}\"\n currency = f\"{material.currency}\"\n supplier = f\"{material.supplier}\"\n \n self.assertEqual(accountant, 'testuser1')\n self.assertEqual(name, 'tesla model 3')\n self.assertEqual(measurement_type, 'KG')\n self.assertEqual(total_amount, '1.00')\n self.assertEqual(price, '50.00')\n self.assertEqual(currency, 'USD')\n self.assertEqual(supplier, 'Tesla')\n","sub_path":"api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"72235554","text":"\"\"\"https://leetcode.com/problems/n-queens-ii/\"\"\"\n\n\nclass Solution:\n def totalNQueens(self, n: int) -> int:\n ret = [0]\n self.dfs(n, [], [], [], ret)\n return ret[0]\n\n def dfs(self, n, queens, xy_dif, xy_sum, ret):\n p = len(queens)\n if p == n:\n print(queens)\n ret[0] += 1\n else:\n for q in range(n):\n if q not in queens and (p - q) not in xy_dif and (p + q) not in xy_sum:\n self.dfs(n, queens + [q], xy_dif + [p - q], xy_sum + [p + q], ret)\n","sub_path":"leetcode/1-100/52-N-Queens II/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"469404985","text":"#!/usr/bin/env python\nimport webapp2\nimport urllib\n\n\nclass HomeHandler(webapp2.RequestHandler):\n\tdef get(self):\n\t\tself.response.write(\"welcome to the home page\")\n\nclass SearchHandler(webapp2.RequestHandler):\n\tdef get(self):\n\t\tsearch_tag = self.request.get('tag_string')\n\t\tif (search_tag):\n\t\t\tquery_params = urllib.urlencode({'tag_string':search_tag})\n\t\t\tself.redirect('/post/render?' + query_params)\n\t\telse:\n\t\t\tquery_params = urllib.urlencode({'error_message':\"You must enter a value\"})\n\t\t\tself.redirect('/?' + query_params)\n\n\napp = webapp2.WSGIApplication([\n\t('/home', HomeHandler),\n\t('/home/search?', SearchHandler)\n], debug=True)","sub_path":"home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"119546501","text":"import flask\nfrom tenacity import app\n\nfrom tenacity.command import question as command_question\n\n\n@app.route('/question', methods=['GET', 'POST'])\ndef question():\n data = {}\n for key in flask.request.args.keys():\n # import pdb;pdb.set_trace()\n try:\n data[key] = getattr(command_question, key)(flask.request.args[key])\n except AttributeError:\n data = {\"error\": \"'{}' does not exist.\".format(key)}\n break\n\n return flask.jsonify(data)\n","sub_path":"tenacity/route/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"287918141","text":"from __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nfrom datetime import datetime, date, timedelta\n\nimport backtrader as bt\nimport backtrader.analyzers as btanalyzers\n\nfrom AnalysisPackage.Indicators import CombinedIndicator, MomentumIndicator, BollingerIndicator, RsiIndicator\nfrom MarketData import MarketDataSource, MarketData\nfrom PredictionModel import PredictionModelFactory\n\ndaysOffset = 10\nlast_date = date.today()\n# last_date = date.today() - + timedelta(days=daysOffset)\nseq_len = 21\n\n\nclass MySimpleStrategy(bt.Strategy):\n\n params = (\n ('security', ''),\n )\n\n def __init__(self):\n self.model = PredictionModelFactory.create_default(seq_len)\n self.all_prices = MarketDataSource().get_stock_data_basic(self.params.security)\n weight_file = self.params.security + '_trained_reg.h5'\n self.model.model.load_weights(weight_file)\n\n def log(self, txt, dt=None):\n ''' Logging function for this strategy'''\n dt = dt or self.datas[0].datetime.date(0)\n print('%s, %s' % (dt.isoformat(), txt))\n\n def notify_trade(self, trade):\n if not trade.isclosed:\n return\n\n self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm))\n\n def notify_order(self, order):\n if order.status in [order.Submitted, order.Accepted]:\n # Buy/Sell order submitted/accepted to/by broker - Nothing to do\n return\n\n # Check if an order has been completed\n # Attention: broker could reject order if not enougth cash\n if order.status in [order.Completed]:\n if order.isbuy():\n self.log('BUY EXECUTED, %.2f' % order.executed.price)\n elif order.issell():\n self.log('SELL EXECUTED, %.2f' % order.executed.price)\n\n self.bar_executed = len(self)\n\n elif order.status in [order.Canceled, order.Margin, order.Rejected]:\n self.log('Order Canceled/Margin/Rejected')\n\n # Write down: no pending order\n self.order = None\n\n def next(self):\n # Simply log the closing price of the series from the reference\n # self.log('Close, %.2f' % self.dataclose[0])\n # self.sell()\n position = self.getpositionbyname(self.params.security)\n date = self.datas[0].datetime.date(0)\n date = datetime.combine(date, datetime.min.time())\n filtered = self.all_prices[self.all_prices.index <= date].copy()\n indicators = CombinedIndicator((MomentumIndicator(), BollingerIndicator(), RsiIndicator()))\n market_data = MarketData(self.params.security, filtered, ma=[50, 100, 200], indicator=indicators)\n total_days = 5\n prices = self.model.predict_days(market_data, total_days)\n last_price = prices[-1]\n\n if last_price > (self.data.close[0] * 1.01) and position.size == 0:\n self.log('BUY CREATE, %.2f' % self.data.close[0])\n self.buy(price=self.data.close[0], size=800)\n elif (last_price * 1.01) <= self.data.close[0] and position.size > 0:\n self.log('SELL CREATE, %.2f' % self.data.close[0])\n self.sell(price=self.data.close[0], size=position.size)\n\n\nif __name__ == '__main__':\n cerebro = bt.Cerebro()\n\n stock = \"TSLA\"\n # Add a strategy\n cerebro.addstrategy(MySimpleStrategy, security=stock)\n\n cerebro.broker.setcash(10000.0)\n print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())\n cerebro.broker.setcommission(commission=0.001)\n\n data = bt.feeds.Quandl(\n dataname=stock,\n apikey='XH28RzhxDVHKWwnaN1Hv',\n fromdate=datetime(2017, 1, 1),\n todate=last_date)\n cerebro.adddata(data)\n\n cerebro.addwriter(bt.WriterFile, csv=True, out='your_strategy_results.csv')\n\n # Analyzer\n cerebro.addanalyzer(btanalyzers.SharpeRatio, _name='mysharpe')\n\n thestrats = cerebro.run()\n print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())\n\n thestrat = thestrats[0]\n print('Sharpe Ratio:', thestrat.analyzers.mysharpe.get_analysis())\n\n cerebro.plot()\n\n","sub_path":"Trader.py","file_name":"Trader.py","file_ext":"py","file_size_in_byte":4118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"96005885","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import fields, models, api, _\nfrom odoo.tools import float_is_zero\nfrom collections import defaultdict\nfrom odoo.exceptions import UserError\n\n\nclass BlanketOrderWizard(models.TransientModel):\n _name = 'sale.blanket.order.wizard'\n _description = 'Blanket order wizard'\n\n @api.model\n def _default_order(self):\n self.env['sale.blanket.order'].expire_the_orders()\n if not self.env.context.get('active_id'):\n return False\n blanket_order = self.env['sale.blanket.order'].search(\n [('id', '=', self.env.context['active_id'])], limit=1)\n if blanket_order.state == 'expired':\n raise UserError(_('You can\\'t create a sale order from '\n 'an expired blanket order!'))\n return blanket_order\n\n @api.model\n def _check_valid_blanket_order_line(self, bo_lines):\n precision = self.env['decimal.precision'].precision_get(\n 'Product Unit of Measure')\n company_id = False\n\n if all(float_is_zero(\n line.remaining_uom_qty, precision_digits=precision)\n for line in bo_lines):\n raise UserError(\n _('The sale has already been completed.'))\n\n for line in bo_lines:\n if line.order_id.state != 'open':\n raise UserError(\n _('Sale Blanket Order %s is not open') %\n line.order_id.name)\n line_company_id = line.company_id and line.company_id.id or False\n if company_id is not False \\\n and line_company_id != company_id:\n raise UserError(\n _('You have to select lines '\n 'from the same company.'))\n else:\n company_id = line_company_id\n\n @api.model\n def _default_lines(self):\n blanket_order_line_obj = self.env['sale.blanket.order.line']\n blanket_order_line_ids = self.env.context.get('active_ids', False)\n active_model = self.env.context.get('active_model', False)\n\n if active_model == 'sale.blanket.order':\n bo_lines = self._default_order().order_line\n else:\n bo_lines = blanket_order_line_obj.browse(blanket_order_line_ids)\n\n self._check_valid_blanket_order_line(bo_lines)\n\n lines = [(0, 0, {\n 'blanket_line_id': l.id,\n 'product_id': l.product_id.id,\n 'date_scheduled': l.date_scheduled,\n 'remaining_uom_qty': l.remaining_uom_qty,\n 'price_unit': l.price_unit,\n 'product_uom': l.product_uom,\n 'qty': l.remaining_uom_qty,\n 'partner_id': l.partner_id,\n }) for l in bo_lines.filtered(lambda l: l.remaining_uom_qty != 0.0)]\n return lines\n\n blanket_order_id = fields.Many2one(\n 'sale.blanket.order', readonly=True)\n sale_order_id = fields.Many2one(\n 'sale.order',\n string='Purchase Order',\n domain=[('state', '=', 'draft')])\n line_ids = fields.One2many(\n 'sale.blanket.order.wizard.line', 'wizard_id',\n string='Lines', default=_default_lines)\n\n def create_sale_order(self):\n order_lines_by_customer = defaultdict(list)\n currency_id = 0\n pricelist_id = 0\n user_id = 0\n payment_term_id = 0\n for line in self.line_ids.filtered(lambda l: l.qty != 0.0):\n if line.qty > line.remaining_uom_qty:\n raise UserError(\n _('You can\\'t order more than the remaining quantities'))\n vals = {'product_id': line.product_id.id,\n 'name': line.product_id.name,\n 'product_uom': line.product_uom.id,\n 'sequence': line.blanket_line_id.sequence,\n 'price_unit': line.blanket_line_id.price_unit,\n 'blanket_order_line': line.blanket_line_id.id,\n 'product_uom_qty': line.qty,\n 'tax_id': [(6, 0, line.taxes_id.ids)]}\n order_lines_by_customer[line.partner_id.id].append((0, 0, vals))\n\n if currency_id == 0:\n currency_id = line.blanket_line_id.order_id.currency_id.id\n elif currency_id != line.blanket_line_id.order_id.currency_id.id:\n currency_id = False\n\n if pricelist_id == 0:\n pricelist_id = line.blanket_line_id.pricelist_id.id\n elif pricelist_id != line.blanket_line_id.pricelist_id.id:\n pricelist_id = False\n\n if user_id == 0:\n user_id = line.blanket_line_id.salesman_id.id\n elif user_id != line.blanket_line_id.salesman_id.id:\n user_id = False\n\n if payment_term_id == 0:\n payment_term_id = line.blanket_line_id.payment_term_id.id\n elif payment_term_id != line.blanket_line_id.payment_term_id.id:\n payment_term_id = False\n\n if not order_lines_by_customer:\n raise UserError(_('An order can\\'t be empty'))\n\n if not currency_id:\n raise UserError(_('Can not create Sale Order from Blanket '\n 'Order lines with different currencies'))\n\n res = []\n for customer in order_lines_by_customer:\n order_vals = {\n 'partner_id': customer,\n 'origin': self.blanket_order_id.name,\n 'user_id': user_id,\n 'currency_id': currency_id,\n 'pricelist_id': pricelist_id,\n 'payment_term_id': payment_term_id,\n 'order_line': order_lines_by_customer[customer],\n }\n sale_order = self.env['sale.order'].create(order_vals)\n res.append(sale_order.id)\n return {\n 'domain': [('id', 'in', res)],\n 'name': _('Sales Orders'),\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'res_model': 'sale.order',\n 'context': {'from_sale_order': True},\n 'type': 'ir.actions.act_window'\n }\n\n\nclass BlanketOrderWizardLine(models.TransientModel):\n _name = 'sale.blanket.order.wizard.line'\n _description = 'Blanket order wizard line'\n\n wizard_id = fields.Many2one('sale.blanket.order.wizard')\n blanket_line_id = fields.Many2one(\n 'sale.blanket.order.line')\n product_id = fields.Many2one(\n 'product.product',\n related='blanket_line_id.product_id',\n string='Product')\n product_uom = fields.Many2one(\n 'uom.uom',\n related='blanket_line_id.product_uom',\n string='Unit of Measure')\n date_scheduled = fields.Date(\n related='blanket_line_id.date_scheduled')\n remaining_uom_qty = fields.Float(\n related='blanket_line_id.remaining_uom_qty')\n qty = fields.Float(string='Quantity to Order', required=True)\n price_unit = fields.Float(\n related='blanket_line_id.price_unit')\n currency_id = fields.Many2one(\n 'res.currency', related='blanket_line_id.currency_id')\n partner_id = fields.Many2one(\n 'res.partner',\n related='blanket_line_id.partner_id',\n string='Vendor')\n taxes_id = fields.Many2many(\n 'account.tax', related=\"blanket_line_id.tax_id\")\n","sub_path":"clientes/sales_blanket_order/wizard/create_sale_orders.py","file_name":"create_sale_orders.py","file_ext":"py","file_size_in_byte":7292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"383172200","text":"'''\nPrimes\n\n11408 - Count DePrimes\n\nInput\nEach line contains a and b in the format ‘a b’. 2 ≤ a ≤ 5000000. a ≤ b ≤ 5000000. Input is terminated by a line containing ‘0’.\n\nOutput\nEach line should contain the number of DePrimes for the corresponding test case. Explanation: In Test Case 2, take 10. Its Prime Factors are 2 and 5. Sum of Prime Factors is 7, which is a prime. So, 10 is a DePrime.\n\n1. a < i < b; 2. i = prime * prime; 3. prime + prime = prime\n'''\nimport math\n# only go through prime numbers smaller then n^1/2:\n# go through prime numbers under 1000000^1/2 to bulid a list, and cross out multiples of prime numbers one by one. Those not crossed out are prime numbers\n# primes within (1000000^1/2)\n\ndef prime():\n isPrime = [True for _ in range(5000000)] # 2 * i + 1= n\n isPrime[0], isPrime[1] = False, False\n buff = set()\n for i in range(len(isPrime)):\n if isPrime[i]:\n buff.add(i)\n for j in range(i * i, len(isPrime), i):\n isPrime[j] = False\n return buff\n\nif __name__ == '__main__':\n primes = prime()\n sortedPrimes = sorted(primes)\n while True:\n try:\n n = input()\n if n == '0':\n break\n a, b = list(map(int, n.split()))\n dePrimes = []\n for i in range(a, b + 1):\n factors = []\n for p1 in sortedPrimes:\n if p1 < b + 1:\n p2 = i / p1\n if p2 % 1 == 0:\n factors.append(p1)\n if sum(factors)in primes:\n dePrimes.append(i)\n print(len(dePrimes))\n except(EOFError):\n break\n","sub_path":"11408.py","file_name":"11408.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"536304018","text":"\"\"\"\nInput validators to use in the mock query API.\n\"\"\"\n\nimport cgi\nimport io\nimport uuid\nfrom typing import Any, Callable, Dict, Tuple\n\nimport wrapt\nfrom requests import codes\nfrom requests_mock.request import _RequestObjectProxy\nfrom requests_mock.response import _Context\n\nfrom mock_vws.database import VuforiaDatabase\nfrom mock_vws.states import States\n\nfrom .._constants import ResultCodes\nfrom .._database_matchers import get_database_matching_client_keys\nfrom .._mock_common import parse_multipart\n\n\n@wrapt.decorator\ndef validate_project_state(\n wrapped: Callable[..., str],\n instance: Any,\n args: Tuple[_RequestObjectProxy, _Context],\n kwargs: Dict,\n) -> str:\n \"\"\"\n Validate the state of the project.\n\n Args:\n wrapped: An endpoint function for `requests_mock`.\n instance: The class that the endpoint function is in.\n args: The arguments given to the endpoint function.\n kwargs: The keyword arguments given to the endpoint function.\n\n Returns:\n The result of calling the endpoint.\n A `FORBIDDEN` response with an InactiveProject result code if the\n project is inactive.\n \"\"\"\n request, context = args\n\n database = get_database_matching_client_keys(\n request_headers=request.headers,\n request_body=request.body,\n request_method=request.method,\n request_path=request.path,\n databases=instance.databases,\n )\n\n assert isinstance(database, VuforiaDatabase)\n if database.state != States.PROJECT_INACTIVE:\n return wrapped(*args, **kwargs)\n\n context.status_code = codes.FORBIDDEN\n transaction_id = uuid.uuid4().hex\n result_code = ResultCodes.INACTIVE_PROJECT.value\n\n # The response has an unusual format of separators, so we construct it\n # manually.\n return (\n '{\"transaction_id\": '\n f'\"{transaction_id}\",'\n f'\"result_code\":\"{result_code}\"'\n '}'\n )\n\n\n@wrapt.decorator\ndef validate_max_num_results(\n wrapped: Callable[..., str],\n instance: Any, # pylint: disable=unused-argument\n args: Tuple[_RequestObjectProxy, _Context],\n kwargs: Dict,\n) -> str:\n \"\"\"\n Validate the ``max_num_results`` field is either an integer within range or\n not given.\n\n Args:\n wrapped: An endpoint function for `requests_mock`.\n instance: The class that the endpoint function is in.\n args: The arguments given to the endpoint function.\n kwargs: The keyword arguments given to the endpoint function.\n\n Returns:\n The result of calling the endpoint.\n A `BAD_REQUEST` response if the ``max_num_results`` field is either not\n an integer, or an integer out of range.\n \"\"\"\n request, context = args\n body_file = io.BytesIO(request.body)\n\n _, pdict = cgi.parse_header(request.headers['Content-Type'])\n parsed = parse_multipart(\n fp=body_file,\n pdict={\n 'boundary': pdict['boundary'].encode(),\n },\n )\n [max_num_results] = parsed.get('max_num_results', ['1'])\n assert isinstance(max_num_results, str)\n invalid_type_error = (\n f\"Invalid value '{max_num_results}' in form data part \"\n \"'max_result'. \"\n 'Expecting integer value in range from 1 to 50 (inclusive).'\n )\n\n try:\n max_num_results_int = int(max_num_results)\n except ValueError:\n context.status_code = codes.BAD_REQUEST\n return invalid_type_error\n\n java_max_int = 2147483647\n if max_num_results_int > java_max_int:\n context.status_code = codes.BAD_REQUEST\n return invalid_type_error\n\n if max_num_results_int < 1 or max_num_results_int > 50:\n context.status_code = codes.BAD_REQUEST\n out_of_range_error = (\n f'Integer out of range ({max_num_results_int}) in form data part '\n \"'max_result'. Accepted range is from 1 to 50 (inclusive).\"\n )\n return out_of_range_error\n\n return wrapped(*args, **kwargs)\n\n\n@wrapt.decorator\ndef validate_include_target_data(\n wrapped: Callable[..., str],\n instance: Any, # pylint: disable=unused-argument\n args: Tuple[_RequestObjectProxy, _Context],\n kwargs: Dict,\n) -> str:\n \"\"\"\n Validate the ``include_target_data`` field is either an accepted value or\n not given.\n\n Args:\n wrapped: An endpoint function for `requests_mock`.\n instance: The class that the endpoint function is in.\n args: The arguments given to the endpoint function.\n kwargs: The keyword arguments given to the endpoint function.\n\n Returns:\n The result of calling the endpoint.\n A `BAD_REQUEST` response if the ``include_target_data`` field is not an\n accepted value.\n \"\"\"\n request, context = args\n body_file = io.BytesIO(request.body)\n\n _, pdict = cgi.parse_header(request.headers['Content-Type'])\n parsed = parse_multipart(\n fp=body_file,\n pdict={\n 'boundary': pdict['boundary'].encode(),\n },\n )\n\n [include_target_data] = parsed.get('include_target_data', ['top'])\n lower_include_target_data = include_target_data.lower()\n allowed_included_target_data = {'top', 'all', 'none'}\n if lower_include_target_data in allowed_included_target_data:\n return wrapped(*args, **kwargs)\n\n assert isinstance(include_target_data, str)\n unexpected_target_data_message = (\n f\"Invalid value '{include_target_data}' in form data part \"\n \"'include_target_data'. \"\n \"Expecting one of the (unquoted) string values 'all', 'none' or 'top'.\"\n )\n context.status_code = codes.BAD_REQUEST\n return unexpected_target_data_message\n\n\n@wrapt.decorator\ndef validate_content_type_header(\n wrapped: Callable[..., str],\n instance: Any, # pylint: disable=unused-argument\n args: Tuple[_RequestObjectProxy, _Context],\n kwargs: Dict,\n) -> str:\n \"\"\"\n Validate the ``Content-Type`` header.\n\n Args:\n wrapped: An endpoint function for `requests_mock`.\n instance: The class that the endpoint function is in.\n args: The arguments given to the endpoint function.\n kwargs: The keyword arguments given to the endpoint function.\n\n Returns:\n The result of calling the endpoint.\n An ``UNSUPPORTED_MEDIA_TYPE`` response if the ``Content-Type`` header\n main part is not 'multipart/form-data'.\n A ``BAD_REQUEST`` response if the ``Content-Type`` header does not\n contain a boundary which is in the request body.\n \"\"\"\n request, context = args\n\n main_value, pdict = cgi.parse_header(request.headers['Content-Type'])\n if main_value != 'multipart/form-data':\n context.status_code = codes.UNSUPPORTED_MEDIA_TYPE\n context.headers.pop('Content-Type')\n return ''\n\n if 'boundary' not in pdict:\n context.status_code = codes.BAD_REQUEST\n context.headers['Content-Type'] = 'text/html;charset=UTF-8'\n return (\n 'java.io.IOException: RESTEASY007550: '\n 'Unable to get boundary for multipart'\n )\n\n if pdict['boundary'].encode() not in request.body:\n context.status_code = codes.BAD_REQUEST\n context.headers['Content-Type'] = 'text/html;charset=UTF-8'\n return (\n 'java.lang.RuntimeException: RESTEASY007500: '\n 'Could find no Content-Disposition header within part'\n )\n\n return wrapped(*args, **kwargs)\n\n\n@wrapt.decorator\ndef validate_accept_header(\n wrapped: Callable[..., str],\n instance: Any, # pylint: disable=unused-argument\n args: Tuple[_RequestObjectProxy, _Context],\n kwargs: Dict,\n) -> str:\n \"\"\"\n Validate the accept header.\n\n Args:\n wrapped: An endpoint function for `requests_mock`.\n instance: The class that the endpoint function is in.\n args: The arguments given to the endpoint function.\n kwargs: The keyword arguments given to the endpoint function.\n\n Returns:\n The result of calling the endpoint.\n A `NOT_ACCEPTABLE` response if the Accept header is given and is not\n 'application/json' or '*/*'.\n \"\"\"\n request, context = args\n\n accept = request.headers.get('Accept')\n if accept in ('application/json', '*/*', None):\n return wrapped(*args, **kwargs)\n\n context.headers.pop('Content-Type')\n context.status_code = codes.NOT_ACCEPTABLE\n return ''\n\n\n@wrapt.decorator\ndef validate_extra_fields(\n wrapped: Callable[..., str],\n instance: Any, # pylint: disable=unused-argument\n args: Tuple[_RequestObjectProxy, _Context],\n kwargs: Dict,\n) -> str:\n \"\"\"\n Validate that the no unknown fields are given.\n\n Args:\n wrapped: An endpoint function for `requests_mock`.\n instance: The class that the endpoint function is in.\n args: The arguments given to the endpoint function.\n kwargs: The keyword arguments given to the endpoint function.\n\n Returns:\n The result of calling the endpoint.\n A ``BAD_REQUEST`` response if extra fields are given.\n \"\"\"\n request, context = args\n body_file = io.BytesIO(request.body)\n\n _, pdict = cgi.parse_header(request.headers['Content-Type'])\n parsed = parse_multipart(\n fp=body_file,\n pdict={\n 'boundary': pdict['boundary'].encode(),\n },\n )\n\n known_parameters = {'image', 'max_num_results', 'include_target_data'}\n\n if not parsed.keys() - known_parameters:\n return wrapped(*args, **kwargs)\n\n context.status_code = codes.BAD_REQUEST\n return 'Unknown parameters in the request.'\n","sub_path":"src/mock_vws/_query_validators/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"397710803","text":"## Here I let the computer guess what number is in my mind and I guide to make him guess correctly.\n\nminimum, maximum, guess_count = 1, 25, 0\n\nprint(\"Please think of a number between 1 and 25!\")\nwhile True:\n number = int((minimum + maximum) / 2)\n user_input = input(\"Is your secret number \" + str(number) + \"?\\nEnter 'h' to indicate the guess is too high.\\n\\\nEnter 'l' to indicate the guess is too low.\\nEnter 'c' to indicate I guessed correctly.\\nEnter 'm' if you made a mistake.\")\n guess_count += 1\n if user_input == \"c\":\n break\n elif user_input == \"h\":\n maximum = number\n elif user_input == \"l\":\n minimum = number\n elif user_input == \"m\":\n print(\"Alrighty then, let's start over.\")\n minimum, maximum, guess_count = 1, 25, 0\n else:\n print(\"Sorry, I did not understand your input.\")\n guess_count -= 1\n\ncorrect_guess = \"Gotcha! I guessed your secret number \" + str(number) + \" in \" + str(guess_count)\n\nif guess_count == 1:\n print(correct_guess + \" try. Oh, come on!\")\nelse:\n print(correct_guess + \" tries.\")\n","sub_path":"guessNumber.py","file_name":"guessNumber.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"417251917","text":"from node import Node\nfrom problem import Problem\nfrom search import Search\n\n\np = Problem()\ns = Search(p)\nr = s.DFS(graphSearch=True)\n\nprint(r.status)\npath = r.path\npath.reverse()\nprint(path)\nprint(\"number of expansions : \")\nprint (r.expandedNodes)\n","sub_path":"phw5/problem1/DFS/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"643842119","text":"from function import specificity,cal_auc,LossHistory\nimport network\nimport load\nimport util\nimport keras\nimport keras.backend as K\nfrom keras.callbacks import LearningRateScheduler\nfrom keras.models import Model\nimport scipy.io as scio\nfrom sklearn.metrics import confusion_matrix,accuracy_score, recall_score,f1_score\n\nMAX_EPOCHS = 150\nbatch_size = 32\nif __name__ == '__main__':\n params = util.config()\n save_dir = params['save_dir']\n\n print(\"Loading training set...\")\n train = load.load_dataset(params['train'])\n print(\"Loading dev set...\")\n dev = load.load_dataset(params['dev'])\n print(\"Building preprocessor...\")\n preproc = load.Preproc(*train)\n print(\"Training size: \" + str(len(train[0])) + \" examples.\")\n print(\"Dev size: \" + str(len(dev[0])) + \" examples.\")\n\n params.update({\n \"input_shape\": [2048, 1],\n \"num_categories\": len(preproc.classes)\n })\n\n #create the cl-ecg-net\n model = network.build_network(**params)\n\n #learning rate reduce strategy\n def scheduler(epoch):\n if epoch % 100 == 0 and epoch != 0:\n lr = K.get_value(model.optimizer.lr)\n model.load_weights(save_dir + 'best.hdf5')\n K.set_value(model.optimizer.lr, lr * 0.1)\n print(\"epoch {}: lr changed to {}\".format(epoch, lr * 0.1))\n return K.get_value(model.optimizer.lr)\n reduce_lr = LearningRateScheduler(scheduler)\n\n #choose best model to save\n checkpointer = keras.callbacks.ModelCheckpoint(\n mode='max',\n monitor='val_acc',\n filepath=save_dir + 'best.hdf5',\n save_best_only=True)\n\n #variable to save the loss_acc_iter value\n history = LossHistory()\n\n #data generator\n train_gen = load.data_generator(batch_size, preproc, *train)\n dev_gen = load.data_generator(len(dev[0]), preproc, *dev)\n\n #fit the model\n print('cl_ecg_net starts training...')\n model.fit_generator(\n train_gen,\n steps_per_epoch=int(len(train[0]) / batch_size),\n epochs=MAX_EPOCHS,\n validation_data=dev_gen,\n validation_steps=1,\n verbose=False,\n callbacks=[checkpointer, reduce_lr, history])\n\n #save loss_acc_iter\n history.save_result(params['save_dir'] + 'loss_acc_iter.mat')\n\n #extract and save deep coding features\n x_train, y_train = load.data_generator2(preproc, *train)\n x, y_t = load.data_generator2(preproc, *dev)\n model.load_weights(save_dir + 'best.hdf5')\n new_model = Model(inputs=model.input, outputs=model.layers[-3].output)\n feature_train = new_model.predict(x_train)\n feature_test = new_model.predict(x)\n scio.savemat(save_dir + 'ecg_train.mat', {'x': feature_train, 'y':y_train})\n scio.savemat(save_dir + 'ecg_test.mat', {'x': feature_test, 'y':y_t})\n print('deep coding features of ecg saved')\n\n #evaluate model\n y_p = model.predict(x)\n print(confusion_matrix(y_t.argmax(1), y_p.argmax(1)))\n print('sensitivity:', recall_score(y_t.argmax(1), y_p.argmax(1)))\n print('specificity:', specificity(y_t.argmax(1), y_p.argmax(1)))\n print('f1-score:', f1_score(y_t.argmax(1), y_p.argmax(1)))\n print('accuracy:', accuracy_score(y_t.argmax(1), y_p.argmax(1)))\n print('roc:', cal_auc(y_t.argmax(1), y_p[:, 1]))\n\n","sub_path":"code/cl_ecg_net/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"375179575","text":"import pytest\nfrom pytest_bdd import scenarios, given, when, then\n\nfrom scenarios_run import *\n\nscenarios('../feature/config', example_converters=dict(command = str, environment = Environment, pattern = PatternType))\n\n@given('the is configured for command in the configuration')\ndef add_environment_to_command(config, command, environment):\n config.commands[command].set_environment(environment)\n\n@given('the is configured for command in the configuration')\ndef add_pattern_to_command(config, command, pattern):\n config.commands[command].add_pattern(pattern)\n\n@then('the runtime environment for should contain the given ')\ndef check_environment(run_environment, command, environment):\n runs = run_environment.config.commands[command].runs\n actual_env = runs[-1].environment\n\n assert(len(runs) > 0)\n\n for key,value in environment.items():\n for permutation in run_environment.config.commands[command].pattern_generator():\n replaced_key = key\n replaced_value = value\n for pattern_key, pattern_value in permutation.items():\n replaced_key = replaced_key.replace('{' + pattern_key + '}', pattern_value)\n replaced_value = replaced_value.replace('{' + pattern_key + '}', pattern_value)\n\n assert(replaced_key in actual_env)\n assert(replaced_value == actual_env[replaced_key])\n","sub_path":"test/integration/src/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"362855977","text":"import os\nimport subprocess\nfrom typing import Dict\n\nfrom celery import Celery\n\nfrom pgatk_nexflow.services import nextflow_service\nfrom pgatk_nexflow.utils.constants import CELERY_BROKER_URL, KUBERNETES_PVC\nfrom pgatk_nexflow.utils.constants import LOG_ROOT\n\ncelery = Celery('pride_nextflow', broker=CELERY_BROKER_URL, backend=CELERY_BROKER_URL)\n\ncelery.conf.update(\n result_expires=3600 * 24,\n)\n\n\n@celery.task(track_started=True, bind=True)\ndef run_job(self, job_id: str, repo: str, profile: str, parameters: Dict[str, str]):\n commands = ['nextflow', 'kuberun', repo, '-v', KUBERNETES_PVC + ':/mnt', '-latest']\n if 'POD_IMAGE' in os.environ:\n commands += ['-pod-image', os.environ['POD_IMAGE']]\n if profile:\n commands += ['-profile', profile]\n if 'API_ENDPOINT' in os.environ:\n commands += ['-with-weblog', '%s/pipeline/%s' % (os.environ['API_ENDPOINT'], job_id)]\n for key in parameters:\n commands += ['--' + key, parameters[key]]\n working_dir = '%s/nextflow/%s' % (LOG_ROOT, job_id)\n os.makedirs(working_dir)\n process = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False,\n encoding='utf8', cwd=working_dir)\n res = ''\n while True:\n output = process.stdout.readline() or process.stderr.readline()\n if output == '' and process.poll() is not None:\n break\n if output:\n res += output\n self.update_state(state=\"PROGRESS\", meta={'message': res})\n rc = process.poll()\n response = {'message': res, 'ret_code': rc}\n if rc == 0:\n response['result_file'] = nextflow_service.generate_downloadable_s3_http(parameters['result_file'])\n return response\n\n\nif __name__ == '__main__':\n celery.start()\n","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"505827420","text":"import re\nfrom datetime import datetime, timedelta,date\nfrom dateutil.relativedelta import relativedelta\nfrom odoo import models, api, fields, _\nfrom odoo.exceptions import UserError, AccessError, ValidationError\nfrom odoo.tools import email_split\nimport logging\n_logger = logging.getLogger(__name__)\nfrom pytz import timezone, UTC\n\n\nclass HrLeave(models.Model):\n _inherit = 'hr.leave'\n\n leave_approvals = fields.One2many('leave.validation.status',\n 'holiday_status',\n string='Leave Validators',\n track_visibility='always', help=\"Leave approvals\")\n\n multi_level_validation = fields.Boolean(string='Multiple Level Approval',\n related='holiday_status_id.multi_level_validation',\n help=\"If checked then multi-level approval is necessary\") \n \n is_approved_user_id = fields.Boolean(default=False, compute='_check_is_approved_user_id') \n all_emails = fields.Text()\n approved_emails = fields.Text()\n notApproved_emails = fields.Text()\n certificate_required = fields.Boolean()\n def _check_is_approved_user_id(self):\n current_uid = self.env.uid\n self.is_approved_user_id= False\n for l2 in self.leave_approvals: \n #for approval button\n if l2.validation_status != True:\n # direct manager\n if l2.validators_type == 'direct_manager' and self.employee_id.parent_id.id != False:\n if self.employee_id.parent_id.user_id.id != False:\n if self.employee_id.parent_id.user_id.id == current_uid:\n self.is_approved_user_id= True\n break\n # manager of manager(i will check it)\n if l2.validators_type == 'manager_of_manager' and self.employee_id.parent_id.id != False:\n if self.employee_id.parent_id.parent_id.id != False: \n if self.employee_id.parent_id.parent_id.user_id.id != False:\n if self.employee_id.parent_id.parent_id.user_id.id == current_uid:\n self.is_approved_user_id= True\n break \n # position\n if l2.validators_type == 'position':\n employees = self.env['hr.employee'].sudo().search([('multi_job_id','in',l2.holiday_validators_position.id)])\n if len(employees) > 0:\n for employee in employees:\n if employee.user_id.id == current_uid:\n self.is_approved_user_id= True\n break\n #user\n if l2.validators_type == 'user':\n if l2.holiday_validators_user.id == current_uid:\n self.is_approved_user_id= True\n break\n if not(l2.approval != True or (l2.approval == True and l2.validation_status == True)): \n break \n is_refused_user_id = fields.Boolean(default=True)\n # is_refused_user_id = fields.Boolean(default=True, compute='_check_is_refused_user_id')\n # def _check_is_refused_user_id(self):\n # current_uid = self.env.uid\n # self.is_refused_user_id = False\n # for l2 in self.leave_approvals: \n # # direct manager\n # if l2.validators_type == 'direct_manager' and self.employee_id.parent_id.id != False:\n # if self.employee_id.parent_id.user_id.id != False:\n # if self.employee_id.parent_id.user_id.id == current_uid:\n # self.is_refused_user_id= True\n # # break\n # # position\n # if l2.validators_type == 'position':\n # employees = self.env['hr.employee'].sudo().search([('multi_job_id','in',l2.holiday_validators_position.id)])\n # if len(employees) > 0:\n # for employee in employees:\n # if employee.user_id.id == current_uid:\n # self.is_refused_user_id= True\n # # break\n # #user\n # if l2.validators_type == 'user':\n # if l2.holiday_validators_user.id == current_uid:\n # self.is_refused_user_id= True\n # # break\n # if not(l2.approval != True or (l2.approval == True and l2.validation_status == True)): \n # break \n @api.onchange('holiday_status_id','number_of_days')\n def add_validators(self):\n \"\"\" Update the tree view and add new validators\n when leave type is changed in leave request form \"\"\"\n time_off_type = self.env['hr.leave.type'].sudo().search([('id','=',self.holiday_status_id.id)])\n # 5/6/2021\n _logger.info(\"-------------yearsـofـservice-------------\")\n if self.employee_id.date_joining != False and time_off_type.yearsـofـservice != 0:\n date_joining = datetime.strptime(str(self.employee_id.date_joining),'%Y-%m-%d').date()\n now = datetime.strptime(str(date.today()),'%Y-%m-%d').date()\n difference_in_years = relativedelta(now, date_joining).years\n yearsـofـservice = time_off_type.yearsـofـservice\n _logger.info(difference_in_years)\n _logger.info(time_off_type.yearsـofـservice)\n _logger.info(\"-------------yearsـofـservice-------------\")\n if not(difference_in_years >= yearsـofـservice):\n msg = (\"You must have at least %s years in this company\") % (yearsـofـservice)\n raise UserError(msg)\n else:\n if time_off_type.yearsـofـservice != 0:\n raise UserError(\"Join date not found\")\n # 5/6/2021\n if self.validation_type == \"multi\":\n li = []\n all_emails = \"\"\n self.leave_approvals = [(5, 0, 0)]\n emails_count = 0\n for l in self.holiday_status_id.leave_validators:\n _logger.info(\"-------------log-------------\")\n _logger.info(float(l.exceptions))\n _logger.info(self.number_of_days)\n if l.exceptions == False or self.number_of_days > float(l.exceptions):\n # direct manager\n if l.validators_type == 'direct_manager' and self.employee_id.parent_id.id != False:\n if self.employee_id.parent_id.user_id.id != False and emails_count == 0:\n if all_emails != \"\":\n if str(self.employee_id.parent_id.user_id.login) not in all_emails:\n all_emails = all_emails + \",\" +str(self.employee_id.parent_id.user_id.login)\n else:\n all_emails = str(self.employee_id.parent_id.user_id.login)\n emails_count = 1 \n\n # manager of manager(i will check it)\n if l.validators_type == 'manager_of_manager' and self.employee_id.parent_id.id != False:\n if self.employee_id.parent_id.parent_id.id != False: \n if self.employee_id.parent_id.parent_id.user_id.id != False and emails_count == 0:\n if all_emails != \"\":\n if str(self.employee_id.parent_id.parent_id.user_id.login) not in all_emails:\n all_emails = all_emails + \",\" +str(self.employee_id.parent_id.parent_id.user_id.login)\n else:\n all_emails = str(self.employee_id.parent_id.parent_id.user_id.login)\n emails_count = 1 \n # position\n if l.validators_type == 'position':\n employees = self.env['hr.employee'].sudo().search([('multi_job_id','in',l.holiday_validators_position.id)])\n if len(employees) > 0 and emails_count == 0:\n for employee in employees:\n if all_emails != \"\":\n if str(employee.user_id.login) not in all_emails:\n all_emails = all_emails + \",\" +str(employee.user_id.login)\n else:\n all_emails = str(employee.user_id.login)\n emails_count = 1 \n #user\n if l.validators_type == 'user' and emails_count == 0:\n if all_emails != \"\":\n if str(l.holiday_validators_user.login) not in all_emails:\n all_emails = all_emails + \",\"+str(l.holiday_validators_user.login)\n else:\n all_emails = str(l.holiday_validators_user.login)\n emails_count = 1 \n li.append((0, 0, {\n 'validators_type': l.validators_type,\n 'holiday_validators_user': l.holiday_validators_user.id,\n 'holiday_validators_position': l.holiday_validators_position.id,\n 'approval': l.approval,\n 'exceptions':l.exceptions\n }))\n self.leave_approvals = li\n self.all_emails = all_emails\n _logger.info(\"-------------log1111-------------\")\n _logger.info(time_off_type)\n _logger.info(time_off_type.certificate_required)\n self.certificate_required = time_off_type.certificate_required\n\n def _get_approval_requests(self):\n \"\"\" Action for Approvals menu item to show approval\n requests assigned to current user \"\"\"\n # Ahmed AlOsaili \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (10) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":1,\n # \"number_of_days_display\":10,\n # \"number_of_days\":10,\n # \"state\":'validate',\n # })\n # all_data = {}\n # all_data[0] = {}\n # all_data[0]['id'] = 199\n # all_data[0]['date'] = \"2021-02-22\"\n\n # all_data[1] = {}\n # all_data[1]['id'] = 195\n # all_data[1]['date'] = \"2021-02-22\"\n\n # all_data[2] = {}\n # all_data[2]['id'] = 197\n # all_data[2]['date'] = \"2021-02-22\"\n\n # all_data[3] = {}\n # all_data[3]['id'] = 193\n # all_data[3]['date'] = \"2021-02-22\"\n\n # all_data[4] = {}\n # all_data[4]['id'] = 192\n # all_data[4]['date'] = \"2021-02-22\"\n\n # all_data[5] = {}\n # all_data[5]['id'] = 196\n # all_data[5]['date'] = \"2021-02-22\"\n\n # all_data[6] = {}\n # all_data[6]['id'] = 194\n # all_data[6]['date'] = \"2021-02-22\"\n\n # all_data[7] = {}\n # all_data[7]['id'] = 191\n # all_data[7]['date'] = \"2021-02-01\"\n\n # all_data[8] = {}\n # all_data[8]['id'] = 205\n # all_data[8]['date'] = \"2021-03-14\"\n\n # all_data[9] = {}\n # all_data[9]['id'] = 206\n # all_data[9]['date'] = \"2021-03-17\"\n\n # all_data[10] = {}\n # all_data[10]['id'] = 207\n # all_data[10]['date'] = \"2021-04-14\"\n\n # all_data[11] = {}\n # all_data[11]['id'] = 201\n # all_data[11]['date'] = \"2021-01-06\"\n\n # all_data[12] = {}\n # all_data[12]['id'] = 202\n # all_data[12]['date'] = \"2021-01-06\"\n\n # all_data[13] = {}\n # all_data[13]['id'] = 202\n # all_data[13]['date'] = \"2021-01-06\"\n # for x in all_data :\n # id = all_data[x]['id']\n # date = all_data[x]['date']\n # emp = self.env['hr.employee'].sudo().search([('id','=',id)])\n # emp.commencement_business = date\n # # Abdulaziz Alegeiry\n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (9.75) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":125,\n # \"number_of_days_display\":9.75,\n # \"number_of_days\":9.75,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True \n # })\n # # # Mahmoud Tash\n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (10) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":120,\n # \"number_of_days_display\":10,\n # \"number_of_days\":10,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Mohammed Alaa Borgi\n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (4.44) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":115,\n # \"number_of_days_display\":4.44,\n # \"number_of_days\":4.44,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Muzaffer Azam - Mohammed Muzaffer\n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (7.75) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":103,\n # \"number_of_days_display\":7.75,\n # \"number_of_days\":7.75,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Mohamed Habib\n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (10) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":100,\n # \"number_of_days_display\":10,\n # \"number_of_days\":10,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Shariful Islam\n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (21.88) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":97,\n # \"number_of_days_display\":21.88,\n # \"number_of_days\":21.88,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Basel Alhamich\n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (2.7) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":93,\n # \"number_of_days_display\":2.7,\n # \"number_of_days\":2.7,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Emad Abuzahra \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (9.31) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":7,\n # \"number_of_days_display\":9.31,\n # \"number_of_days\":9.31,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Mohammed Abdullah \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (10) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":89,\n # \"number_of_days_display\":10,\n # \"number_of_days\":10,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Mohammed Akram \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (6.7) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":146,\n # \"number_of_days_display\":6.7,\n # \"number_of_days\":6.7,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Ahmad Ibrahim Wadi Shahin \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (5.49) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":139,\n # \"number_of_days_display\":5.49,\n # \"number_of_days\":5.49,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Malek Jamal Rebhi Ahmad \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (5.49) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":145,\n # \"number_of_days_display\":5.49,\n # \"number_of_days\":5.49,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Basel Altamimi \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (10) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":144,\n # \"number_of_days_display\":10,\n # \"number_of_days\":10,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Ahmed Abosaleh \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (1.76) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":140,\n # \"number_of_days_display\":1.76,\n # \"number_of_days\":1.76,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Sultan Alhaqqas \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (3.23) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":149,\n # \"number_of_days_display\":3.23,\n # \"number_of_days\":3.23,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Elias Gabour \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (2.2) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":151,\n # \"number_of_days_display\":2.2,\n # \"number_of_days\":2.2,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # Abdulrahman Altamimi \n # # self.env['hr.leave.allocation'].sudo().create({\n # # \"name\":\"Carry Forword from annual leave 2020 (9.75) days\",\n # # \"holiday_status_id\":11,\n # # \"allocation_type\":\"regular\",\n # # \"holiday_type\":\"employee\",\n # # \"employee_id\":138,\n # # \"number_of_days_display\":-0.8,\n # # \"number_of_days\":-0.8,\n # # \"state\":'validate',\n # # \"allocation_carry_forword\" :True\n # # })\n # # Tammam Madarati \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (10) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":153,\n # \"number_of_days_display\":10,\n # \"number_of_days\":10,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # Ahmed Elayyan \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (9.75) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":141,\n # \"number_of_days_display\":-0.95,\n # \"number_of_days\":-0.95,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # Qusai \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (10) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":158,\n # \"number_of_days_display\":10,\n # \"number_of_days\":10,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # Ramzi Madhi \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (10) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":161,\n # \"number_of_days_display\":10,\n # \"number_of_days\":10,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # Sonny Tesorero Tapia \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (10) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":155,\n # \"number_of_days_display\":10,\n # \"number_of_days\":10,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Eduard Nelson Akim \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (10) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":162,\n # \"number_of_days_display\":10,\n # \"number_of_days\":10,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Osama Alsuliman \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (6.76) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":163,\n # \"number_of_days_display\":6.76,\n # \"number_of_days\":6.76,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Moawia Jallad \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (8.26) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":166,\n # \"number_of_days_display\":8.26,\n # \"number_of_days\":8.26,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Jacinto Dugan Dimaun  \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (8.26) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":171,\n # \"number_of_days_display\":8.26,\n # \"number_of_days\":8.26,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Faris Badhris \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (6.84) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":172,\n # \"number_of_days_display\":6.84,\n # \"number_of_days\":6.84,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Ibrahim Alsebai \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (3.62) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":178,\n # \"number_of_days_display\":3.62,\n # \"number_of_days\":3.62,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Mohammed Lafeer \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (5.48) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":182,\n # \"number_of_days_display\":5.48,\n # \"number_of_days\":5.48,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Mohammed Hamood \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (6.15) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":176,\n # \"number_of_days_display\":6.15,\n # \"number_of_days\":6.15,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Rashed Aldawsari \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (6.57) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":174,\n # \"number_of_days_display\":6.57,\n # \"number_of_days\":6.57,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n # # # Fahad Alhamazani \n # self.env['hr.leave.allocation'].sudo().create({\n # \"name\":\"Carry Forword from annual leave 2020 (3.62) days\",\n # \"holiday_status_id\":11,\n # \"allocation_type\":\"regular\",\n # \"holiday_type\":\"employee\",\n # \"employee_id\":200,\n # \"number_of_days_display\":3.62,\n # \"number_of_days\":3.62,\n # \"state\":'validate',\n # \"allocation_carry_forword\" :True\n # })\n\n \n\n\n\n current_uid = self.env.uid\n hr_holidays = self.env['hr.leave'].sudo().search([('state','=','confirm'),('holiday_status_id.validation_type','=','multi')])\n li = []\n for l in hr_holidays:\n for l2 in l.leave_approvals:\n if l2.exceptions == False or l.number_of_days > float(l2.exceptions): \n # direct manager\n if l2.validators_type == 'direct_manager' and l.employee_id.parent_id.id != False:\n if l.employee_id.parent_id.user_id.id != False:\n if l.employee_id.parent_id.user_id.id == current_uid:\n li.append(l.id)\n\n # manager of manager(i will check it)\n if l2.validators_type == 'manager_of_manager' and l.employee_id.parent_id.id != False:\n if l.employee_id.parent_id.parent_id.id != False: \n if l.employee_id.parent_id.parent_id.user_id.id != False:\n if l.employee_id.parent_id.parent_id.user_id.id == current_uid:\n li.append(l.id)\n \n # position\n if l2.validators_type == 'position':\n employee = self.env['hr.employee'].sudo().search([('multi_job_id','in',l2.holiday_validators_position.id),('user_id','=',current_uid)])\n if len(employee) > 0:\n li.append(l.id)\n #user\n if l2.validators_type == 'user':\n if l2.holiday_validators_user.id == current_uid:\n li.append(l.id)\n # if not(l2.approval != True or (l2.approval == True and l2.validation_status == True)): \n # break \n value = {\n 'domain': str([('id', 'in', li)]),\n 'view_mode': 'tree,form',\n 'res_model': 'hr.leave',\n 'view_id': False,\n 'type': 'ir.actions.act_window',\n 'name': _('Approvals'),\n 'res_id': self.id,\n 'target': 'current',\n 'create': False,\n 'edit': False,\n }\n return value\n def action_approve(self):\n \n \"\"\" Chack if any pending tasks is added if so reassign the pending\n task else call approval \"\"\"\n # if validation_type == 'both': this method is the first approval approval\n # if validation_type != 'both': this method calls action_validate() below\n if self.multi_level_validation:\n if any(holiday.state != 'confirm' for holiday in self):\n raise UserError(_(\n 'Leave request must be confirmed (\"To Approve\") in order to approve it.'))\n ohrmspro_vacation_project = self.sudo().env['ir.module.module'].search(\n [('name', '=', 'ohrmspro_vacation_project')],\n limit=1).state\n if ohrmspro_vacation_project == 'installed':\n return self.env['hr.leave'].check_pending_task(self)\n else:\n return self.approval_check()\n else:\n rtn = super(HrLeave,self).action_approve()\n return rtn \n def approval_check(self):\n \"\"\" Check all leave validators approved the leave request if approved\n change the current request stage to Approved\"\"\" \n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Reason for Approval',\n 'res_model': 'create.leave.comment',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'view_id': self.env.ref('multiApprovalTimeOff.view_create_leave_comment',False).id,\n 'target': 'new',\n }\n def action_refuse(self):\n \"\"\" Refuse the leave request if the current user is in\n validators list \"\"\"\n if self.multi_level_validation: \n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Reason for Refused',\n 'res_model': 'create.refuse.comment',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'view_id': self.env.ref('multiApprovalTimeOff.view_create_refuse_comment',False).id,\n 'target': 'new',\n }\n else:\n rtn = super(HrLeave,self).action_refuse()\n return rtn \n def action_draft(self):\n \"\"\" Reset all validation status to false when leave request\n set to draft stage\"\"\"\n if self.multi_level_validation:\n for user in self.leave_approvals:\n user.validation_status = False\n user.validation_refused = False\n return super(HrLeave, self).action_draft()\n @api.model_create_multi\n def create(self,vals):\n rtn = super(HrLeave,self).create(vals)\n res_id = rtn.id\n for values in vals:\n holiday_status_id = values.get('holiday_status_id')\n employee_id = values.get('employee_id')\n request_date_from = values.get('request_date_from')\n request_date_to = values.get('request_date_to')\n number_of_days = values.get('number_of_days')\n all_emails = values.get('all_emails')\n hr_holidays = self.env['hr.leave.type'].sudo().search([('id','=',holiday_status_id)])\n if hr_holidays.validation_type == \"multi\":\n employee = self.env['hr.employee'].sudo().search([('id','=',employee_id)])\n message = ('

    Request approval to leave by %s


    ') % (employee.name)\n message += ('

    From %s


    ') % (request_date_from)\n message += ('

    To %s


    ') % (request_date_to)\n message += ('

    Duration: %s


    ') % (number_of_days)\n body_html = self.create_body_for_email(message,res_id)\n email_html = self.create_header_footer_for_email(holiday_status_id,employee_id,body_html)\n \n value = {\n 'subject': 'Approval of the leave',\n 'body_html': email_html,\n 'email_to': all_emails,\n 'email_cc': '',\n 'auto_delete': False,\n 'email_from': 'axs-sa.com',\n }\n mail_id = self.env['mail.mail'].sudo().create(value)\n mail_id.sudo().send()\n return rtn \n\n # def write(self, values):\n # is_officer = self.env.user.has_group('hr_holidays.group_hr_holidays_user')\n\n # if not is_officer:\n # if any(hol.date_from.date() < fields.Date.today() for hol in self):\n # raise UserError(_('You must have manager rights to modify/validate a time off that already begun'))\n\n # employee_id = values.get('employee_id', False)\n # if not self.env.context.get('leave_fast_create'):\n # if values.get('state'):\n # self._check_approval_update(values['state'])\n # if any(holiday.validation_type == 'both' for holiday in self):\n # if values.get('employee_id'):\n # employees = self.env['hr.employee'].browse(values.get('employee_id'))\n # else:\n # employees = self.mapped('employee_id')\n # self._check_double_validation_rules(employees, values['state'])\n # if 'date_from' in values:\n # values['request_date_from'] = values['date_from']\n # if 'date_to' in values:\n # values['request_date_to'] = values['date_to']\n # result = super(HolidaysRequest, self).write(values)\n # if not self.env.context.get('leave_fast_create'):\n # for holiday in self:\n # if employee_id:\n # holiday.add_follower(employee_id)\n # self._sync_employee_details()\n # if 'number_of_days' not in values and ('date_from' in values or 'date_to' in values):\n # holiday._onchange_leave_dates()\n # return result\n\n def create_body_for_email(self,message,res_id):\n body_html = ''\n body_html +=''\n body_html += ''\n body_html += ''\n body_html += ''\n body_html += ''\n body_html += ''\n body_html += ''\n body_html += ''\n body_html += ''\n body_html += '
    '\n body_html += '

    '\n body_html += message\n body_html += '

    '\n body_html += '

    '\n body_html += ('') % (res_id)\n body_html += 'View Leave'\n body_html += ''\n body_html += '

    '\n body_html += 'Thanks,
    '\n body_html += '
    '\n body_html += '
    '\n body_html += '
    '\n body_html += ''\n body_html +=''\n return body_html\n def create_header_footer_for_email(self,holiday_status_id,employee_id,body_html):\n hr_holidays = self.env['hr.leave.type'].sudo().search([('id','=',holiday_status_id)])\n employee = self.env['hr.employee'].sudo().search([('id','=',employee_id)])\n leave_type = hr_holidays.name\n company_id = employee.company_id.id\n header = ''\n header += '' \n header += ''\n header += ''\n header += ''\n header += ''\n header += ''\n header += ''\n header += '
    ' \n header += ''\n header += ''\n\n header += ''\n header += ''\n header += ''\n header += body_html\n header += '' \n header += ''\n header += ''\n\n header += ''\n header += '
    '\n header += ''\n header += ''\n header += ''\n header += '
    '\n header += 'Leave Approval
    '\n header += ''\n header += leave_type\n header += ''\n header += '
    '\n header += ('\"\"/') % (str(company_id))\n header += '
    '\n header += '
    '\n header += '
    '\n header += '
    ' \n header += ''\n header += ''\n header += ''\n header += '
    '\n header += str(employee.company_id.name)\n header += '
    '\n header += str(employee.company_id.phone) \n if employee.company_id.email:\n header += ('%s') % (str(employee.company_id.email),str(employee.company_id.email))\n if employee.company_id.website:\n header += ('') % (str(employee.company_id.website)) \n header += '
    '\n header += '
    '\n header += '
    '\n header += ''\n header += ''\n header += '
    '\n header += \"Powered by \"+ ('%s') % (str(employee.company_id.website),str(employee.company_id.name)) \n header += '
    '\n header += '
    '\n return header\n","sub_path":"models/hrLeave.py","file_name":"hrLeave.py","file_ext":"py","file_size_in_byte":42983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"161104330","text":"import serial, keyboard, sys\nimport win32api, win32gui, winsound\nimport time, random, pyautogui\nimport logging, json\nimport cv2, os\nfrom datetime import datetime\nfrom tkinter import *\n\ndef key_2_sent(key): # 'r' for right mouse double click, 'l' for left click, 't' for right click\n # 'o' for enter; 'u' for up; 'j' for down(jump); 'k' for macro /camp\n key_sent = str(key)\n ard.flush()\n print(\"Python value sent: \" + key_sent)\n ard.write(str.encode(key_sent))\n time.sleep(0.5) # I shortened this to match the new value in your arduino code\n # waiting for pro micro to send 'Done'\n done_received = False\n while not done_received:\n original_msg = str(ard.read(ard.inWaiting())) # read all characters in buffer\n # print(original_msg)\n # to git rid of the serial print additional letters.\n msg = original_msg.replace('b\\'', '').replace('\\\\r\\\\n', \" \")[:-2]\n # print(msg[-4:])\n if msg[-4:] == 'Done':\n # print(\"Message from arduino: \")\n # print(msg)\n done_received = True\n else:\n ard.flush()\n time.sleep(0.5)\n return\n\n\ndef mouse_2_sent(position):\n key_sent = 'M' + str(int(position[0] / X_RATIO)) + ',' + str(int(position[1] / Y_RATIO))\n ard.flush()\n print(\"Python value sent: \" + key_sent)\n ard.write(str.encode(key_sent))\n time.sleep(0.5) # I shortened this to match the new value in your arduino code\n # waiting for pro micro to send 'Done'\n done_received = False\n while not done_received:\n original_msg = str(ard.read(ard.inWaiting())) # read all characters in buffer\n # print(original_msg)\n # to git rid of the serial print additional letters.\n msg = original_msg.replace('b\\'', '').replace('\\\\r\\\\n', \" \")[:-2]\n # print(msg[-4:])\n if msg[-4:] == 'Done':\n # print(\"Message from arduino: \")\n # print(msg)\n done_received = True\n else:\n ard.flush()\n time.sleep(0.5)\n return\n\n\ndef mouse_2_rtv(position):\n key_sent = 'N' + str(int(position[0] / J_RATIO)) + ',' + str(int(position[1] / Q_RATIO))\n ard.flush()\n print(\"Python value sent: \" + key_sent)\n ard.write(str.encode(key_sent))\n time.sleep(0.5) # I shortened this to match the new value in your arduino code\n # waiting for pro micro to send 'Done'\n done_received = False\n while not done_received:\n original_msg = str(ard.read(ard.inWaiting())) # read all characters in buffer\n # print(original_msg)\n # to git rid of the serial print additional letters.\n msg = original_msg.replace('b\\'', '').replace('\\\\r\\\\n', \" \")[:-2]\n # print(msg[-4:])\n if msg[-4:] == 'Done':\n # print(\"Message from arduino: \")\n # print(msg)\n done_received = True\n else:\n ard.flush()\n time.sleep(0.5)\n return\n\n\ndef go_pause():\n while not keyboard.is_pressed(PAUSE_KEY):\n if keyboard.is_pressed(STOP_KEY):\n end_game()\n pass\n\n\ndef end_game():\n winsound.Beep(1000, 300)\n time.sleep(0.300)\n winsound.Beep(1000, 300)\n for short_cut_key in AFTER_GAME_END:\n key_2_sent(short_cut_key)\n get_random_wait(400, 600)\n sys.exit()\n pass\n\n\ndef get_random_wait(low, high):\n # wait for a random time\n time.sleep(random.randint(low, high) / 1000)\n\n\ndef blur_pos_dur():\n # get a random blur relevant x and y and random time according to the constants\n x = random.randint(BLUR_PIXEL[0], BLUR_PIXEL[1]) * random.choice([-1, 1])\n y = random.randint(BLUR_PIXEL[0], BLUR_PIXEL[1]) * random.choice([-1, 1])\n t = random.randint(BLUR_DUR[0], BLUR_DUR[1])\n return x, y, t\n\n\ndef scope_size():\n # get searching area for the bobber\n rect = ((SCREEN_WIDTH // 3, SCREEN_HEIGHT // 3),\n (SCREEN_WIDTH * 8 // 12, SCREEN_HEIGHT * 11 // 20))\n return rect\n\n\ndef locate_mixer():\n # locate a trigger pixel in a mixer via proportion\n # if there is a mixer next to the main window\n # pyautogui.moveTo(SCREEN_WIDTH + 250, SCREEN_HEIGHT // 4)\n # pyautogui.click()\n mouse_2_sent([SCREEN_WIDTH + 250, SCREEN_HEIGHT // 4])\n key_2_sent('l')\n mixer_txt = win32gui.GetWindowText(win32gui.GetForegroundWindow())\n mixer_txt = mixer_txt[:4]\n if mixer_txt == \"音量合成\":\n mixer_rect = win32gui.GetWindowRect(win32gui.GetForegroundWindow())\n width = mixer_rect[2] - mixer_rect[0]\n height = mixer_rect[3] - mixer_rect[1]\n mixer_x = mixer_rect[0] + int(width * 0.13)\n mixer_y = mixer_rect[1] + int(height * (1 - SOUND_THRESHOLD * 0.85))\n mixer_trigger = (mixer_x, mixer_y)\n else:\n mixer_trigger = None\n return mixer_trigger\n\n\ndef enumhandler(hwnd, lParam):\n # enumwindows' callback function\n # if mixer found, move it next to the main windows\n if win32gui.IsWindowVisible(hwnd):\n if '音量合成' in win32gui.GetWindowText(hwnd):\n win32gui.MoveWindow(hwnd, SCREEN_WIDTH, 0, 760, 500, True)\n\n\ndef create_mixer():\n # create mixer and allocate it after 5 seconds\n os.startfile(\"SndVol.exe\")\n time.sleep(5)\n win32gui.EnumWindows(enumhandler, None)\n\n\ndef get_line(screen_shot, length):\n line = []\n for i in range(0, length):\n line.append(screen_shot.getpixel((i, 2)))\n return line\n\n\ndef get_fish():\n # ensure a right click to have a fish after bit\n key_2_sent('t')\n get_random_wait(800, 1300)\n\n\ndef check_for_key_in():\n if keyboard.is_pressed(START_KEY):\n key = 1\n elif keyboard.is_pressed(STOP_KEY):\n key = 0\n elif keyboard.is_pressed(PAUSE_KEY):\n key = 2\n else:\n key = 99\n return key\n\n\nclass CastPole:\n # cast the pole and looking for the bobber\n # move mouse to the bobber\n def __init__(self, mouse_position):\n self.mouse_pos = mouse_position\n\n def cast(self):\n # get a blur\n blur_x, blur_y, dur_t = blur_pos_dur()\n self.mouse_pos = pyautogui.position()\n self.mouse_pos = tuple(map(lambda x, y: x + y, self.mouse_pos,\n (blur_x * 15, blur_y * 15)))\n # cast command\n key_2_sent('f')\n get_random_wait(600, 900)\n winsound.Beep(1000, 300)\n\n def find_hooker(self, rect, confi=None):\n global hook_missing_counter\n if not confi: confi = 0.5\n fd_hook = None\n tm = time.time()\n # print((rect[0][0], rect[0][1],rect[1][0], rect[1][1]))\n while fd_hook is None:\n for img in bobber_images:\n fd_hook = pyautogui.locateCenterOnScreen(img, region=(rect[0][0], rect[0][1],\n rect[1][0], rect[1][1]),\n grayscale=False, confidence=confi)\n # if searching time is too long quit loop\n if fd_hook is not None:\n # if fd_hook[1] > rect[1][1]:\n if fd_hook[1] > rect[1][1] or \\\n fd_hook[1] < rect[0][1] or \\\n fd_hook[0] > rect[1][0] or \\\n fd_hook[0] < rect[0][0] :\n print('too far away')\n print(fd_hook)\n fd_hook = None\n else:\n good_bobber[bobber_images.index(img)] += 1\n print(good_bobber)\n break\n\n if time.time() - tm >= 5.0:\n hook_missing_counter += 1\n break\n return fd_hook\n\n\nclass Listen2mixer:\n def __init__(self, trigger):\n self.trigger_x = trigger[0] - TRIGGER_DEDENT\n # 8 can be adjusted\n self.trigger_y = trigger[1]\n self.trigger_length = TRIGGER_LENGTH\n img = pyautogui.screenshot(region=(self.trigger_x, self.trigger_y - 1,\n self.trigger_x + self.trigger_length, self.trigger_y + 1))\n self.silent = get_line(img, self.trigger_length)\n\n def listen(self):\n global sound_missing_counter\n t = time.time()\n listening = True\n bingo = False\n pause = False\n stop = False\n while listening:\n if keyboard.is_pressed(STOP_KEY):\n stop = True\n break\n elif keyboard.is_pressed(PAUSE_KEY):\n pause = True\n break\n new = pyautogui.screenshot(region=(self.trigger_x, self.trigger_y - 1,\n self.trigger_x + self.trigger_length, self.trigger_y + 1))\n new_line = get_line(new, self.trigger_length)\n if new_line != self.silent:\n bingo = True\n listening = False\n elif time.time() - t >= 17.0:\n listening = False\n bingo = False\n return bingo, pause, stop\n\n\nclass ShowBoundary:\n def __init__(self, rec_size, top_left, color):\n self.trigger_boards = list()\n self.color = color\n rec_top = str(rec_size[0] + 6) + \"x3+\" + str(top_left[0] - 3) + \"+\" + str(top_left[1] - 3)\n rec_bottom = str(rec_size[0] + 6) + \"x3+\" + str(top_left[0] - 3) + \"+\" + str(top_left[1] + rec_size[1])\n rec_left = str(\"3x\" + str(rec_size[1] + 3 - 1) + \"+\" + str(top_left[0] - 3) + \"+\"\n + str(top_left[1] - 3))\n rec_right = str(\"3x\" + str(rec_size[1] + 3 - 1) + \"+\" + str(top_left[0] + rec_size[0]) + \"+\"\n + str(top_left[1] - 3))\n geo = (rec_top, rec_bottom, rec_left, rec_right)\n\n for i in range(0, 3 + 1):\n self.trigger_boards.append(Tk())\n for i in range(0, 3 + 1):\n self.trigger_boards[i].overrideredirect(1)\n self.trigger_boards[i].attributes(\"-topmost\", True)\n self.trigger_boards[i].config(bg=self.color)\n self.trigger_boards[i].geometry(geo[i])\n\n def showframe(self):\n for i in range(0, 3 + 1):\n self.trigger_boards[i].update()\n pass\n\n def killframe(self):\n for i in range(0, 3 + 1):\n self.trigger_boards[i].destroy()\n\n\n###############################################################################################################\n# Game Constant\n\nX_RATIO = 1.88\nY_RATIO = 1.88\nJ_RATIO = 2.5\nQ_RATIO = 2.5\nPORT = 'COM3'\nDESKTOP = (2560, 1440) # Related with X_RATIO, and Y_RATIO, set in arduino manually\n\nSCREEN_WIDTH = 1280\nSCREEN_HEIGHT = 720\nBLUR_PIXEL = [1, 3]\nBLUR_DUR = [250, 400]\nSOUND_THRESHOLD = 0.40\nHAND_SHAKE_FACTOR = 0\nSTART_KEY = 'F10'\nSTOP_KEY = 'F12'\nPAUSE_KEY = 'F11'\nTRIGGER_DEDENT = 8\nTRIGGER_LENGTH = 500\nTIME_TO_RUN = 600\nTIME_FOR_EACH_ROLE = 60\nAFTER_GAME_END = ['v'] # hide or quit after game end\nANTI_AFT_TIME = 10\nANTI_AFT_KEY = ['z', 'x', 'c'] # 3 action shortcut key to anti AFK\nCASTPOLE = 'f' # key 'f' for cast fishing pole\nROLE_TO_LOOP = 3\n\n# K1 = pyautogui.easeInQuad\n# K2 = pyautogui.easeOutQuad\n# K3 = pyautogui.easeInOutQuad\n# K4 = pyautogui.easeInBounce\n# K5 = pyautogui.easeInElastic\n\n# Game variables\ninfoTxt = ''\nhookMissed = 0\nsoundMissed = 0\ncount = 0\nrunning = True\npause_is_pressed = False\nstop_is_pressed = False\nmixer_found = False\nhook_found = None\ntrigger_pos = ()\nrunning_elapsed = time.time()\nlast_anti_afk = time.time()\nrect = scope_size()\nrect_center = (int((rect[1][0] - rect[0][0]) / 2 + rect[0][0]),\n int((rect[1][1] - rect[0][1]) / 2 + rect[0][1]))\nfish_counter = 0\nhook_missing_counter = 0\nsound_missing_counter = 0\nend_time = [random.randint(4, 5), random.randint(10, 30)]\n\n# load standard images\nbobber_images = []\ngood_bobber = []\nlogging.basicConfig(filename='running.log',\n filemode='w',\n format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',\n datefmt='%H:%M:%S',\n level=logging.DEBUG\n )\n\nard = serial.Serial(PORT, 9600, timeout=5)\ntime.sleep(2)\nlogging.info('Serial opened and program starts!')\n\nfor i in range(1,7):\n bobber_images.append(\"ppp{}.png\".format(i))\n good_bobber.append(0)\n\n# looking for mixer, if not create one and move it next to the main window\nwhile not mixer_found:\n trigger_pos = locate_mixer()\n if trigger_pos:\n mixer_found = True\n else:\n create_mixer()\n\n# showing sound trigger bar area and the hook monitering area press STARTKEY to proceed or STOPKEY to rerun program\nshow_trigger = ShowBoundary(((TRIGGER_DEDENT + TRIGGER_LENGTH), 3), (trigger_pos[0], trigger_pos[1] - 1), 'orange')\nshow_trigger.showframe()\nshow_scopesize = ShowBoundary((rect[1][0] - rect[0][0], rect[1][1] - rect[0][1]), rect[0], 'cyan')\nshow_scopesize.showframe()\n\n# waiting for start 1, stop 0, none of them 99\nwhile True:\n key = check_for_key_in()\n if key == 1:\n running = True\n winsound.Beep(1000, 200)\n show_trigger.killframe()\n show_scopesize.killframe()\n del show_trigger\n del show_scopesize\n break\n elif key == 2:\n go_pause()\n elif key == 0:\n running = False\n winsound.Beep(500, 400)\n break\n\n# game loop start\n#=============================================================================================================\n\nnew_cst = CastPole(rect_center)\nmouse_2_sent([620, 220])\n## initialize the mouse to the pool center\nprint('inintialize mouse to ' + str([620, 220]))\n\nwhile running:\n # First Check if the running time is longer than expected or should have anti aftk key press.\n cur_time = time.time()\n\n if cur_time - running_elapsed >= TIME_TO_RUN * random.randint(58, 62):\n running = False\n end_game()\n elif cur_time - last_anti_afk >= ANTI_AFT_TIME * random.randint(58, 62):\n key_2_sent(ANTI_AFT_KEY[random.randint(0, (len(ANTI_AFT_KEY)-1))])\n get_random_wait(400, 600)\n key_2_sent('s')\n last_anti_afk = time.time()\n # Cast fishing pole until found a hook is can't found th hook in 5 seconds then recast\n print('time to stop = :' + str(int(cur_time - running_elapsed )) + ' and time to act: '\n + str(int(cur_time - last_anti_afk)))\n if datetime.now().hour == end_time[0] and datetime.now().minute >= end_time[1]:\n running = False\n end_game()\n else:\n print('set to end at: ' + str(end_time[0]) + ':' + str(end_time[1]))\n while hook_found is None:\n get_random_wait(500, 700)\n new_cst.cast()\n # Looking for the hook\n hook_found = new_cst.find_hooker(rect, 0.88)\n # move mouse to the blurred postion of the found hook\n\n x, y, t = blur_pos_dur()\n get_random_wait(500, 600)\n curr_mouse = pyautogui.position()\n rlt_x = int(hook_found[0] - curr_mouse[0])\n rlt_y = int(hook_found[1] - curr_mouse[1])\n while abs(rlt_x) > 5 or abs(rlt_y) > 5:\n if abs(rlt_x) > 175 :\n rlt_x = 175 * (rlt_x / abs(rlt_x))\n if abs(rlt_y) > 175 :\n rlt_y = 175 * (rlt_y / abs(rlt_y))\n mouse_2_rtv([rlt_x + x, rlt_y + y])\n print('relative move: ' + str([rlt_x + x, rlt_y + y]))\n curr_mouse = pyautogui.position()\n rlt_x = int(hook_found[0] - curr_mouse[0])\n rlt_y = int(hook_found[1] - curr_mouse[1])\n\n get_random_wait(300, 500)\n\n listening = Listen2mixer(trigger_pos)\n listen_result, pause_is_pressed, stop_is_pressed = listening.listen()\n if pause_is_pressed:\n listen_result = False\n stop_is_pressed = False\n go_pause()\n if stop_is_pressed:\n listen_result = False\n running = False\n end_game()\n if listening.listen():\n get_fish()\n fish_counter += 1\n hook_found = None\n winsound.Beep(500, 300)\n get_random_wait(400, 700)\n else:\n sound_missing_counter += 1\n hook_found = None\n winsound.Beep(1200, 300)\n get_random_wait(600, 900)\n\n # check if stop key or pause key has been pressed\n check_key = check_for_key_in()\n if check_key == 0:\n running = False\n elif check_key == 2:\n go_pause()\n\n print('fish couter: ' + str(fish_counter))\n print('hook_missing: ' + str(hook_missing_counter))\n print('sound_missing: ' + str(sound_missing_counter))","sub_path":"hsiftxt_v3.01_surface_pro.py","file_name":"hsiftxt_v3.01_surface_pro.py","file_ext":"py","file_size_in_byte":16338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"92302540","text":"import boto3, sys, os\nfrom boto3.session import Session\nfrom flask import Flask, jsonify, request\nfrom datetime import datetime, timedelta\n\nclass computeManager:\n \n def getSecurityGroups(self, key, secret, region):\n try:\n session = Session(aws_access_key_id=key, aws_secret_access_key=secret)\n client = session.client('ec2',region)\n securityGroup = client.describe_security_groups()\n except Exception as e:\n print(e)\n return jsonify({'result':'success', 'data':securityGroup})\n\n def getKeyPairs(self, key, secret, region):\n try:\n session = Session(aws_access_key_id=key, aws_secret_access_key=secret)\n client = session.client('ec2',region)\n keyPairs = client.describe_key_pairs()\n except Exception as e:\n print(e)\n return jsonify({'result':'success','data':keyPairs})\n \n def getAMIs(self, region, key, secret):\n session = Session(aws_access_key_id=key, aws_secret_access_key=secret)\n client = session.client('ec2', region_name=region)\n response = client.describe_images(Owners=['self','amazon'])\n data = {}\n for ami in response['Images']:\n id = ami['ImageId']\n desc = 'none'\n if 'Description' in ami:\n desc = ami['Description']\n data[id] = desc\n return jsonify({'result':'success', 'data':data})\n\n def showInstances(self, key, secret):\n try:\n session = Session(aws_access_key_id=key, aws_secret_access_key=secret)\n client = session.client('ec2')\n ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]\n instanceId = {}\n for region in ec2_regions:\n conn = boto3.resource('ec2', aws_access_key_id=key, aws_secret_access_key=secret, region_name=region)\n instances = conn.instances.filter()\n for instance in instances:\n if instance.state[\"Name\"] == \"running\" or instance.state[\"Name\"] == \"stopped\":\n instanceInfo = {}\n if instance.tags:\n for tag in instance.tags:\n if tag['Key'] == 'Name':\n instanceInfo['name'] = tag['Value']\n instanceInfo['privateIP'] = instance.private_ip_address\n instanceInfo['publicIP'] = instance.public_ip_address\n instanceInfo['keyPair'] = instance.key_name\n instanceInfo['platform'] = instance.platform\n instanceInfo['monitoring'] = (instance.monitoring['State'])\n instanceInfo['state'] = instance.state[\"Name\"]\n instanceInfo['region'] = region\n instanceId[instance.id] = instanceInfo\n except Exception as e:\n return e\n return jsonify({'result':'success', 'data':instanceId})\n\n\n def createInstance(self, keyname, keyCreate, region, instanceType, instanceName, deleteOnTermination, volumeSize, ami, count, monitoring, securityGroup, key, secret):\n try:\n keyPairOut = 'none'\n session = Session(aws_access_key_id=key, aws_secret_access_key=secret)\n client = session.client('ec2', region_name=region)\n if keyCreate == 'yes':\n outfile = open(keyname, 'w')\n key_pair = client.create_key_pair(KeyName = keyname)\n keyPairOut = str(key_pair['KeyMaterial'])\n fileData = outfile.write(keyPairOut)\n response = client.run_instances(\n BlockDeviceMappings=[\n {\n 'DeviceName': '/dev/xvda',\n 'Ebs': {\n 'DeleteOnTermination': deleteOnTermination,\n 'VolumeSize': volumeSize,\n 'VolumeType': 'gp2'\n },\n },\n ],\n TagSpecifications=[\n {\n 'ResourceType': 'instance',\n 'Tags': [\n {\n 'Key': 'Name',\n 'Value': instanceName\n },{\n 'Key': 'By',\n 'Value' : 'krifersam'\n }\n ]\n },\n ],\n ImageId = ami,\n KeyName = keyname,\n InstanceType = instanceType,\n MaxCount = count,\n MinCount = count,\n Monitoring={\n 'Enabled': monitoring\n },\n SecurityGroupIds=[\n securityGroup,\n ],\n )\n print(response)\n except Exception as e:\n return jsonify({'result':'success', 'data':str(e), 'keypair': keyPairOut})\n return jsonify({'result':'success', 'data':response, 'keypair': keyPairOut})\n\n def getStatus(self, region, id):\n try:\n client = boto3.client('ec2', region_name=region)\n response = client.describe_instance_status(InstanceIds=[id])\n except Exception as e:\n return e\n return jsonify({'result':'success', 'data':response})\n\n def changeInstanceState(self, key, secret, id, toState, region):\n session = Session(aws_access_key_id=key, aws_secret_access_key=secret)\n client = session.client('ec2', region_name=region)\n response = 'none'\n try:\n if toState == 'stop':\n response = client.stop_instances(InstanceIds=[id])\n elif toState == 'start':\n response = client.start_instances(InstanceIds=[id])\n elif toState == 'terminate':\n response = client.terminate_instances(InstanceIds=[id])\n except Exception as e:\n print(e)\n return e\n return jsonify({'result':'success', 'data':response})\n\n def getMetricData(self, key, secret, region, nameSpace, metricName, dimensionName, dimensionValue, timeInterval, statistic, fromTime, toTime):\n try:\n session = Session(aws_access_key_id=key, aws_secret_access_key=secret)\n client = session.client('cloudwatch', region_name=region)\n\n stats = client.get_metric_statistics(\n Namespace=nameSpace,\n MetricName=metricName,\n StartTime=datetime.now() - timedelta(seconds=int(fromTime)),\n EndTime=datetime.now() - timedelta(seconds=int(toTime)),\n Statistics=[statistic],\n Period=int(timeInterval),\n Dimensions=[\n {\n 'Name': dimensionName,\n 'Value': dimensionValue\n },\n ],\n )\n except Exception as e:\n print(e)\n return e\n return jsonify({'result':'success', 'data':stats})\n\n def createSecurityGroup(self, key, secret, region, name, description):\n try:\n session = Session(aws_access_key_id=key, aws_secret_access_key=secret)\n client = session.client('ec2', region_name=region)\n securityGroup = client.create_security_group(\n Description=description,\n GroupName=name,\n )\n except Exception as e:\n print(e)\n return e\n return jsonify({'result':'success','data':securityGroup})\n\n def changeMonitoringState(self, key, secret, instanceId, region, to):\n try:\n session = Session(aws_access_key_id=key, aws_secret_access_key=secret)\n client = session.client('ec2', region_name=region)\n if to == 'enable':\n response = client.monitor_instances(InstanceIds=[instanceId])\n else:\n response = client.unmonitor_instances(InstanceIds=[instanceId])\n except Exception as e:\n print(e)\n return e\n return jsonify({'result':'success', 'data':response})\n\n def addSecurityGroupRules(self, key, secret, region, groupId, protocol, fromPort, toPort):\n try:\n session = Session(aws_access_key_id=key, aws_secret_access_key=secret)\n client = session.client('ec2', region_name=region)\n response = client.authorize_security_group_ingress(\n GroupId=groupId,\n IpPermissions=[\n {'IpProtocol': protocol,\n 'FromPort': fromPort,\n 'ToPort': toPort,\n }\n ],\n )\n except Exception as e:\n print(e)\n return e\n return jsonify({'result':'success','data':response})","sub_path":"compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":9020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"45173620","text":"# USAGE\n# python build_dataset.py\n\n# import the necessary packages\nfrom networks import config\nfrom imutils import paths\nimport random\nimport argparse\nimport shutil\nimport os\n\nparser = argparse.ArgumentParser()\nhelp_ = \"The ID of the dataset to be built: 1-Breast Cancer Set (default), 2-Textured Ellipsoids\"\nparser.add_argument(\"-ds\",\n \"--dataset\",\n help=help_,\n type=int,\n default=1)\n\nargs = parser.parse_args()\ndataset_id = int(args.dataset)\n\n# grab the paths to all input images in the original input directory\n# and shuffle them\nimagePaths = list(paths.list_images(config.ORIG_INPUT_CANCER_DATASET)) if dataset_id == 1 else list(paths.list_images(config.ORIG_INPUT_ELLIPS_DATASET))\nrandom.seed(42)\nrandom.shuffle(imagePaths)\n\n# compute the training and testing split\ni = int(len(imagePaths) * config.TRAIN_SPLIT)\ntrainPaths = imagePaths[:i]\ntestPaths = imagePaths[i:]\n\n# we'll be using part of the training data for validation\ni = int(len(trainPaths) * config.VAL_SPLIT)\nvalPaths = trainPaths[:i]\ntrainPaths = trainPaths[i:]\n\n# define the datasets that we'll be building\ndatasets = None\n\nif dataset_id==1:\n datasets = [\n\t (\"training\", trainPaths, config.TRAIN_CANCER_PATH),\n\t (\"validation\", valPaths, config.VAL_CANCER_PATH),\n\t (\"testing\", testPaths, config.TEST_CANCER_PATH)\n ]\nelse:\n datasets = [\n\t (\"training\", trainPaths, config.TRAIN_ELLIPS_PATH),\n\t (\"validation\", valPaths, config.VAL_ELLIPS_PATH),\n\t (\"testing\", testPaths, config.TEST_ELLIPS_PATH)\n ]\n\n# loop over the datasets\nfor (dType, imagePaths, baseOutput) in datasets:\n\t# show which data split we are creating\n\tprint(\"[INFO] building '{}' split\".format(dType))\n\n\t# if the output base output directory does not exist, create it\n\tif not os.path.exists(baseOutput):\n\t\tprint(\"[INFO] 'creating {}' directory\".format(baseOutput))\n\t\tos.makedirs(baseOutput)\n\n\t# loop over the input image paths\n\tfor inputPath in imagePaths:\n\t\tfilename = None\n\t\tlabel = None\n\t\tis_anomaly = False\n\t\t# extract the filename of the input image and extract the\n\t\t# Cancer Dataset: class label (\"0\" for \"negative\" and \"1\" for \"positive\")\n\t\t# Ellips Dataset: class label (\"not_anomalies_range\" for \"negative\" and \"anomalies_range\" for \"positive\")\n\t\tif dataset_id==1:\n\t\t filename = inputPath.split(os.path.sep)[-1]\n\t\t label = filename[-5:-4]\n\t\t is_anomaly = True if label==\"1\" else False\n\t\telse:\n\t\t\tfilename = inputPath.split(os.path.sep)[-1]\n\t\t\tlabel = filename[filename.find(\"_\") + 1 : filename.find(\".\")]\n\t\t\tis_anomaly = True if int(label) in range(9300, 10043) else False\n\n\t\t# construct the path to the destination image and then copy\n\t\t# the image itself\n\t\tif (dType == \"training\" or dType == \"validation\") and not is_anomaly:\n\n\t\t\t# build the path to the label directory\n\t\t\tlabelPath = os.path.sep.join([baseOutput, label])\n\n\t\t\t# if the label output directory does not exist, create it\n\t\t\tif not os.path.exists(labelPath):\n\t\t\t\tprint(\"[INFO] 'creating {}' directory\".format(labelPath))\n\t\t\t\tos.makedirs(labelPath)\n\n\t\t\tp = os.path.sep.join([labelPath, filename])\n\t\t\tshutil.copy2(inputPath, p)\n\t\tif dType == \"testing\":\n\n\t\t\t# build the path to the label directory\n\t\t\tlabelPath = os.path.sep.join([baseOutput, label])\n\n\t\t\t# if the label output directory does not exist, create it\n\t\t\tif not os.path.exists(labelPath):\n\t\t\t\tprint(\"[INFO] 'creating {}' directory\".format(labelPath))\n\t\t\t\tos.makedirs(labelPath)\n\n\t\t\tp = os.path.sep.join([labelPath, filename])\n\t\t\tshutil.copy2(inputPath, p)\n","sub_path":"Proyectos/Proyecto_03/build_dataset.py","file_name":"build_dataset.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"382635556","text":"from kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.uix.label import Label\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.image import Image\nfrom kivy.uix.filechooser import FileChooserIconView\nfrom kivy.loader import Loader\nfrom kivy.uix.button import Button\nimport os\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom kivy.properties import ObjectProperty, NumericProperty, StringProperty, ListProperty\nfrom kivy.uix.popup import Popup\nimport detect_sign\nfrom detect_sign import SignDetection\n#from kivy.clock import Clock\n\n\n\n\n\nclass HomeWindow(Screen):\n pass\n \n\nclass SecondWindow(Screen):\n pass\n\nclass WindowManager(ScreenManager):\n image_path = StringProperty(defaultvalue='blank.jpg')\n logo_path = StringProperty(defaultvalue='logo.png')\n sign_text = StringProperty(defaultvalue=\"None\")\n cr = StringProperty(defaultvalue=\"(c) Tonmoy\")\n \n\n def __init__(self, **kwargs):\n \n super(WindowManager, self).__init__(**kwargs)\n self.home_screen()\n \n \n\n def selected(self, filename):\n print(filename)\n \n\n def open(self, path, filename):\n #print(filename[0])\n try:\n\n self.image_path = filename[0]\n self.home_screen()\n except IndexError:\n popup = Popup(title='Hello Stupid', content=Label(text='Please Select an Image :)'), auto_dismiss=True, pos_hint={'center_x':.5, 'center_y':.5}, size_hint=(.5, .5))\n popup.open()\n popup.bind(on_press=popup.dismiss)\n\n \n\n #return path\n \n def set_sign_name(self):\n sd = SignDetection(image_path=self.image_path)\n self.sign_text = sd.class_name\n self.home_screen()\n\n\n\n def home_screen(self):\n self.current = \"__home__\"\n self.ids.home.ids.detect_image.bind(on_release=lambda x: self.set_sign_name() )\n\n self.ids.home.ids.add_image.bind(on_release=lambda x: self.second_screen() ) #Action for switching to second screen\n \n \n \n #print(self.image_path)\n \n\n\n def second_screen(self):\n filechooser = self.ids.second.ids.file\n self.current = \"__second__\"\n\n #filechooser.bind(on_selection=lambda x: self.selected(filechooser.path) )\n #print(filechooser.path)\n self.image_path = filechooser.path\n self.ids.second.ids.done.bind(on_release=lambda x:self.open(filechooser.path, filechooser.selection) )\n #self.ids.second.ids.done.bind(on_release=lambda x:self.home_screen() ) ##Action for switching to second screen\n #print(self.image_path)\n #self.image_path = self.ids.second.ids.file.path\n\n \n \n \n\n \n\nclass MainApp(App):\n def build(self):\n \n \n self.load_kv('test2.kv')\n \n return WindowManager()\n \n\n\nif __name__ == \"__main__\":\n MainApp().run()\n\n","sub_path":"kivy/GUI/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"352858161","text":"import json\nfrom PyQt5.QtWidgets import (QWidget, QLabel, QPushButton, QHBoxLayout, QVBoxLayout,\n QFormLayout, QLineEdit, QComboBox, QRadioButton, QGroupBox)\nfrom PyQt5.QtCore import pyqtSignal\nfrom fitness_tracker.database_wrapper import DatabaseWrapper\nfrom .calorie_goal_calculator import CalorieGoalCalculator\n\nclass ChangeWeightDialog(QWidget):\n change_current_weight_signal = pyqtSignal(str)\n change_goal_weight_signal = pyqtSignal(str)\n change_calorie_goal_signal = pyqtSignal(str)\n\n def __init__(self):\n super().__init__()\n self.db_wrapper = DatabaseWrapper()\n self.table_name = \"Nutrition\"\n self.user_data = self.db_wrapper.fetch_local_user_info()\n self.user_weight = self.user_data[\"Weight\"]\n self.goal_weight = self.user_data[\"Weight Goal\"]\n goal_parameters = self.user_data[\"Goal Params\"]\n self.goal = self.user_data[\"Goal\"]\n self.activity_level = goal_parameters[0]\n self.weight_per_week = goal_parameters[1]\n self.age = self.user_data[\"Age\"]\n self.gender = self.user_data[\"Gender\"]\n self.height = self.user_data[\"Height\"]\n self.setWindowTitle(\"Edit weight\")\n self.create_layout()\n \n def create_layout(self):\n layout = QFormLayout()\n\n current_weight_label = QLabel(\"Current weight\")\n self.current_weight_line_edit = QLineEdit()\n self.current_weight_line_edit.setText(self.user_weight)\n \n goal_label = QLabel(\"Goal\")\n goal_layout = QHBoxLayout()\n goal = QGroupBox()\n self.weight_loss_button = QRadioButton(\"Weight loss\")\n self.maintain_weight_button = QRadioButton(\"Maintain weight\")\n self.weight_gain_button = QRadioButton(\"Weight gain\")\n if self.goal == \"Weight loss\": self.weight_loss_button.setChecked(True)\n elif self.goal == \"Maintain weight\": self.maintain_weight_button.setChecked(True)\n elif self.goal == \"Weight gain\": self.weight_gain_button.setChecked(True)\n goal_layout.addWidget(self.weight_loss_button)\n goal_layout.addWidget(self.maintain_weight_button)\n goal_layout.addWidget(self.weight_gain_button)\n goal.setLayout(goal_layout)\n\n goal_parameters_label = QLabel(\"Goal parameters\")\n goal_parameters_layout = QHBoxLayout()\n\n activity_level_layout = QVBoxLayout()\n activity_level_label = QLabel(\"Activity level\")\n self.activity_level_cb = QComboBox()\n self.activity_level_cb.addItems([\"Sedentary\", \"Lightly active\", \"Moderately active\", \"Very active\", \"Extra active\"])\n self.activity_level_cb.setCurrentText(self.activity_level)\n activity_level_layout.addWidget(activity_level_label)\n activity_level_layout.addWidget(self.activity_level_cb)\n \n weight_per_week_layout = QVBoxLayout()\n weight_per_week_label = QLabel(\"Weight to lose/gain per week (kg)\")\n self.weight_per_week_cb = QComboBox()\n self.weight_per_week_cb.addItems([\"0.25\", \"0.5\", \"1\"])\n self.weight_per_week_cb.setCurrentText(str(self.weight_per_week))\n weight_per_week_layout.addWidget(weight_per_week_label)\n weight_per_week_layout.addWidget(self.weight_per_week_cb)\n \n goal_parameters_layout.addLayout(activity_level_layout)\n goal_parameters_layout.addLayout(weight_per_week_layout)\n\n goal_weight_label = QLabel(\"Goal weight\")\n self.goal_weight_line_edit = QLineEdit()\n self.goal_weight_line_edit.setText(self.goal_weight)\n\n save_changes_button = QPushButton(\"Save changes\")\n save_changes_button.clicked.connect(lambda: self.save_changes())\n cancel_button = QPushButton(\"Cancel\")\n cancel_button.clicked.connect(lambda: self.close())\n\n layout.addRow(current_weight_label, self.current_weight_line_edit)\n layout.addRow(goal_label, goal)\n layout.addRow(goal_parameters_label, goal_parameters_layout)\n layout.addRow(goal_weight_label, self.goal_weight_line_edit)\n layout.addRow(save_changes_button, cancel_button)\n self.setLayout(layout)\n\n def save_changes(self):\n current_weight = str(float(self.current_weight_line_edit.text()))\n if self.weight_loss_button.isChecked():\n goal = \"Weight loss\"\n elif self.maintain_weight_button.isChecked():\n goal = \"Maintain weight\"\n elif self.weight_gain_button.isChecked():\n goal = \"Weight gain\"\n goal_params = [self.activity_level_cb.currentText(), float(self.weight_per_week_cb.currentText())]\n goal_weight = str(float(self.goal_weight_line_edit.text()))\n\n try:\n if not current_weight == self.user_weight:\n self.db_wrapper.update_table_column(\"Users\", \"weight\", str(float(current_weight)))\n self.user_weight = current_weight\n self.change_current_weight_signal.emit(current_weight)\n self.current_weight_line_edit.setText(current_weight)\n if not goal == self.goal:\n self.db_wrapper.update_table_column(\"Users\", \"goal\", goal)\n self.goal = goal\n if goal == \"Weight loss\":\n self.weight_loss_button.setChecked(True)\n elif goal == \"Maintain weight\":\n self.maintain_weight_button.setChecked(True)\n elif goal == \"Weight gain\":\n self.weight_gain_button.setChecked(True)\n if not goal_params[0] == self.activity_level or not goal_params[1] == self.weight_per_week:\n self.db_wrapper.update_table_column(\"Users\", \"goalparams\", goal_params)\n self.activity_level = goal_params[0]\n self.weight_per_week = goal_params[1]\n if not goal_weight == self.goal_weight:\n self.db_wrapper.update_table_column(\"Users\", \"goalweight\", goal_weight)\n self.goal_weight = goal_weight\n self.change_goal_weight_signal.emit(goal_weight)\n self.goal_weight_line_edit.setText(goal_weight)\n \n calculator = CalorieGoalCalculator(int(self.age), self.gender, float(self.height), float(self.user_weight), goal_params[0], goal, goal_params[1])\n calorie_goal = calculator.calculate_calorie_goal()\n self.db_wrapper.update_table_column(self.table_name, \"calorie_goal\", goal_weight)\n self.change_calorie_goal_signal.emit(str(calorie_goal))\n self.close()\n except ValueError:\n pass\n","sub_path":"fitness_tracker/notes/nutrition/change_weight_dialog.py","file_name":"change_weight_dialog.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"530105640","text":"\"\"\"\nTemporal Convolutional Network\n------------------------------\n\"\"\"\n\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom numpy.random import RandomState\nfrom typing import Optional, Union, Sequence, Tuple\nfrom darts.timeseries import TimeSeries\nfrom darts.utils.torch import random_method\nfrom darts.utils.data import PastCovariatesShiftedDataset\nfrom darts.utils.likelihood_models import Likelihood\n\nfrom darts.logging import raise_if_not, get_logger\nfrom darts.models.forecasting.torch_forecasting_model import TorchParametricProbabilisticForecastingModel, PastCovariatesTorchModel\n\nlogger = get_logger(__name__)\n\n\nclass _ResidualBlock(nn.Module):\n\n def __init__(self,\n num_filters: int,\n kernel_size: int,\n dilation_base: int,\n dropout_fn,\n weight_norm: bool,\n nr_blocks_below: int,\n num_layers: int,\n input_size: int,\n target_size: int):\n \"\"\" PyTorch module implementing a residual block module used in `_TCNModule`.\n\n Parameters\n ----------\n num_filters\n The number of filters in a convolutional layer of the TCN.\n kernel_size\n The size of every kernel in a convolutional layer.\n dilation_base\n The base of the exponent that will determine the dilation on every level.\n dropout_fn\n The dropout function to be applied to every convolutional layer.\n weight_norm\n Boolean value indicating whether to use weight normalization.\n nr_blocks_below\n The number of residual blocks before the current one.\n num_layers\n The number of convolutional layers.\n input_size\n The dimensionality of the input time series of the whole network.\n target_size\n The dimensionality of the output time series of the whole network.\n\n Inputs\n ------\n x of shape `(batch_size, in_dimension, input_chunk_length)`\n Tensor containing the features of the input sequence.\n in_dimension is equal to `input_size` if this is the first residual block,\n in all other cases it is equal to `num_filters`.\n\n Outputs\n -------\n y of shape `(batch_size, out_dimension, input_chunk_length)`\n Tensor containing the output sequence of the residual block.\n out_dimension is equal to `output_size` if this is the last residual block,\n in all other cases it is equal to `num_filters`.\n \"\"\"\n super(_ResidualBlock, self).__init__()\n\n self.dilation_base = dilation_base\n self.kernel_size = kernel_size\n self.dropout_fn = dropout_fn\n self.num_layers = num_layers\n self.nr_blocks_below = nr_blocks_below\n\n input_dim = input_size if nr_blocks_below == 0 else num_filters\n output_dim = target_size if nr_blocks_below == num_layers - 1 else num_filters\n self.conv1 = nn.Conv1d(input_dim, num_filters, kernel_size, dilation=(dilation_base ** nr_blocks_below))\n self.conv2 = nn.Conv1d(num_filters, output_dim, kernel_size, dilation=(dilation_base ** nr_blocks_below))\n if weight_norm:\n self.conv1, self.conv2 = nn.utils.weight_norm(self.conv1), nn.utils.weight_norm(self.conv2)\n\n if input_dim != output_dim:\n self.conv3 = nn.Conv1d(input_dim, output_dim, 1)\n\n def forward(self, x):\n residual = x\n\n # first step\n left_padding = (self.dilation_base ** self.nr_blocks_below) * (self.kernel_size - 1)\n x = F.pad(x, (left_padding, 0))\n x = self.dropout_fn(F.relu(self.conv1(x)))\n\n # second step\n x = F.pad(x, (left_padding, 0))\n x = self.conv2(x)\n if self.nr_blocks_below < self.num_layers - 1:\n x = F.relu(x)\n x = self.dropout_fn(x)\n\n # add residual\n if self.conv1.in_channels != self.conv2.out_channels:\n residual = self.conv3(residual)\n x += residual\n\n return x\n\n\nclass _TCNModule(nn.Module):\n def __init__(self,\n input_size: int,\n input_chunk_length: int,\n kernel_size: int,\n num_filters: int,\n num_layers: Optional[int],\n dilation_base: int,\n weight_norm: bool,\n target_size: int,\n target_length: int,\n dropout: float):\n\n \"\"\" PyTorch module implementing a dilated TCN module used in `TCNModel`.\n\n\n Parameters\n ----------\n input_size\n The dimensionality of the input time series.\n target_size\n The dimensionality of the output time series.\n input_chunk_length\n The length of the input time series.\n target_length\n Number of time steps the torch module will predict into the future at once.\n kernel_size\n The size of every kernel in a convolutional layer.\n num_filters\n The number of filters in a convolutional layer of the TCN.\n num_layers\n The number of convolutional layers.\n weight_norm\n Boolean value indicating whether to use weight normalization.\n dilation_base\n The base of the exponent that will determine the dilation on every level.\n dropout\n The dropout rate for every convolutional layer.\n\n Inputs\n ------\n x of shape `(batch_size, input_chunk_length, input_size)`\n Tensor containing the features of the input sequence.\n\n Outputs\n -------\n y of shape `(batch_size, input_chunk_length, 1)`\n Tensor containing the predictions of the next 'output_chunk_length' points in the last\n 'output_chunk_length' entries of the tensor. The entries before contain the data points\n leading up to the first prediction, all in chronological order.\n \"\"\"\n\n super(_TCNModule, self).__init__()\n\n # Defining parameters\n self.input_size = input_size\n self.input_chunk_length = input_chunk_length\n self.n_filters = num_filters\n self.kernel_size = kernel_size\n self.target_length = target_length\n self.target_size = target_size\n self.dilation_base = dilation_base\n self.dropout = nn.Dropout(p=dropout)\n\n # If num_layers is not passed, compute number of layers needed for full history coverage\n if num_layers is None and dilation_base > 1:\n num_layers = math.ceil(math.log((input_chunk_length - 1) * (dilation_base - 1) / (kernel_size - 1) / 2 + 1,\n dilation_base))\n logger.info(\"Number of layers chosen: \" + str(num_layers))\n elif num_layers is None:\n num_layers = math.ceil((input_chunk_length - 1) / (kernel_size - 1) / 2)\n logger.info(\"Number of layers chosen: \" + str(num_layers))\n self.num_layers = num_layers\n\n # Building TCN module\n self.res_blocks_list = []\n for i in range(num_layers):\n res_block = _ResidualBlock(num_filters, kernel_size, dilation_base,\n self.dropout, weight_norm, i, num_layers, self.input_size, target_size)\n self.res_blocks_list.append(res_block)\n self.res_blocks = nn.ModuleList(self.res_blocks_list)\n\n def forward(self, x):\n # data is of size (batch_size, input_chunk_length, input_size)\n batch_size = x.size(0)\n x = x.transpose(1, 2)\n\n for res_block in self.res_blocks_list:\n x = res_block(x)\n\n x = x.transpose(1, 2)\n x = x.view(batch_size, self.input_chunk_length, self.target_size)\n\n return x\n\n\nclass TCNModel(TorchParametricProbabilisticForecastingModel, PastCovariatesTorchModel):\n @random_method\n def __init__(self,\n input_chunk_length: int,\n output_chunk_length: int,\n kernel_size: int = 3,\n num_filters: int = 3,\n num_layers: Optional[int] = None,\n dilation_base: int = 2,\n weight_norm: bool = False,\n dropout: float = 0.2,\n likelihood: Optional[Likelihood] = None,\n random_state: Optional[Union[int, RandomState]] = None,\n **kwargs):\n\n \"\"\" Temporal Convolutional Network Model (TCN).\n\n This is an implementation of a dilated TCN used for forecasting.\n Inspiration: https://arxiv.org/abs/1803.01271\n\n This model supports past covariates (known for `input_chunk_length` points before prediction time).\n\n Parameters\n ----------\n input_chunk_length\n Number of past time steps that are fed to the forecasting module.\n output_chunk_length\n Number of time steps the torch module will predict into the future at once.\n kernel_size\n The size of every kernel in a convolutional layer.\n num_filters\n The number of filters in a convolutional layer of the TCN.\n weight_norm\n Boolean value indicating whether to use weight normalization.\n dilation_base\n The base of the exponent that will determine the dilation on every level.\n num_layers\n The number of convolutional layers.\n dropout\n The dropout rate for every convolutional layer.\n likelihood\n Optionally, the likelihood model to be used for probabilistic forecasts.\n If no likelihood model is provided, forecasts will be deterministic.\n random_state\n Control the randomness of the weights initialization. Check this\n `link `_ for more details.\n\n batch_size\n Number of time series (input and output sequences) used in each training pass.\n n_epochs\n Number of epochs over which to train the model.\n optimizer_cls\n The PyTorch optimizer class to be used (default: `torch.optim.Adam`).\n optimizer_kwargs\n Optionally, some keyword arguments for the PyTorch optimizer (e.g., `{'lr': 1e-3}`\n for specifying a learning rate). Otherwise the default values of the selected `optimizer_cls`\n will be used.\n lr_scheduler_cls\n Optionally, the PyTorch learning rate scheduler class to be used. Specifying `None` corresponds\n to using a constant learning rate.\n lr_scheduler_kwargs\n Optionally, some keyword arguments for the PyTorch optimizer.\n loss_fn\n PyTorch loss function used for training.\n This parameter will be ignored for probabilistic models if the `likelihood` parameter is specified.\n Default: `torch.nn.MSELoss()`.\n model_name\n Name of the model. Used for creating checkpoints and saving tensorboard data. If not specified,\n defaults to the following string \"YYYY-mm-dd_HH:MM:SS_torch_model_run_PID\", where the initial part of the\n name is formatted with the local date and time, while PID is the processed ID (preventing models spawned at\n the same time by different processes to share the same model_name). E.g.,\n 2021-06-14_09:53:32_torch_model_run_44607.\n work_dir\n Path of the working directory, where to save checkpoints and Tensorboard summaries.\n (default: current working directory).\n log_tensorboard\n If set, use Tensorboard to log the different parameters. The logs will be located in:\n `[work_dir]/.darts/runs/`.\n nr_epochs_val_period\n Number of epochs to wait before evaluating the validation loss (if a validation\n `TimeSeries` is passed to the `fit()` method).\n torch_device_str\n Optionally, a string indicating the torch device to use. (default: \"cuda:0\" if a GPU\n is available, otherwise \"cpu\")\n force_reset\n If set to `True`, any previously-existing model with the same name will be reset (all checkpoints will\n be discarded).\n \"\"\"\n\n raise_if_not(kernel_size < input_chunk_length,\n \"The kernel size must be strictly smaller than the input length.\", logger)\n raise_if_not(output_chunk_length < input_chunk_length,\n \"The output length must be strictly smaller than the input length\", logger)\n\n kwargs['input_chunk_length'] = input_chunk_length\n kwargs['output_chunk_length'] = output_chunk_length\n\n super().__init__(likelihood=likelihood, **kwargs)\n\n self.input_chunk_length = input_chunk_length\n self.output_chunk_length = output_chunk_length\n self.kernel_size = kernel_size\n self.num_filters = num_filters\n self.num_layers = num_layers\n self.dilation_base = dilation_base\n self.dropout = dropout\n self.weight_norm = weight_norm\n\n def _create_model(self, train_sample: Tuple[torch.Tensor]) -> torch.nn.Module:\n # samples are made of (past_target, past_covariates, future_target)\n input_dim = train_sample[0].shape[1] + (train_sample[1].shape[1] if train_sample[1] is not None else 0)\n output_dim = train_sample[-1].shape[1]\n\n target_size = (\n self.likelihood.num_parameters * output_dim if self.likelihood is not None else output_dim\n )\n return _TCNModule(input_size=input_dim,\n input_chunk_length=self.input_chunk_length,\n target_size=target_size,\n kernel_size=self.kernel_size,\n num_filters=self.num_filters,\n num_layers=self.num_layers,\n dilation_base=self.dilation_base,\n target_length=self.output_chunk_length,\n dropout=self.dropout,\n weight_norm=self.weight_norm)\n\n def _build_train_dataset(self,\n target: Sequence[TimeSeries],\n past_covariates: Optional[Sequence[TimeSeries]],\n future_covariates: Optional[Sequence[TimeSeries]]) -> PastCovariatesShiftedDataset:\n\n return PastCovariatesShiftedDataset(target_series=target,\n covariates=past_covariates,\n length=self.input_chunk_length,\n shift=self.output_chunk_length)\n \n @random_method\n def _produce_predict_output(self, x):\n if self.likelihood:\n output = self.model(x)\n return self.likelihood.sample(output)\n else:\n return self.model(x)\n\n @property\n def first_prediction_index(self) -> int:\n return -self.output_chunk_length\n","sub_path":"darts/models/forecasting/tcn_model.py","file_name":"tcn_model.py","file_ext":"py","file_size_in_byte":15099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"203416795","text":"# N x M 크기의 얼음 틀이 있다. 구멍이 뚫려 있는 부분은 0, 칸막이가 존재하는 부분은 1로 표시된다.\n# 구멍이 뚫려 있는 부분끼리 상,하,좌,우로 붙어 있는 경우 서로 연결되어 있는 것으로 간주한다. \n# 이때 얼음 틀의 모양이 주어졌을 때 생성되는 총 아이스크림의 개수를 구하는 프로그램을 작성하시오.\n \n\n# 다음은 예시이다.\n\n \n\n# 입력\n\n# 4 5\n\n# 00110\n\n# 00011\n\n# 11111\n\n# 00000\n\n \n\n \n\n# 출력 \n\n# 3\n\n# ----------------------------------------------------------------------------------------------------------------------------\n\n# <해설>\n\n \n\n# 입력 처음에는 N x M크기가 주어지고 다음은 틀이 주어진다.\n\n \n\n# 예시는\n \n# 0 0 1 1 0\n\n# 0 0 0 1 1\n\n# 1 1 1 1 1\n\n# 0 0 0 0 0\n\n \n\n# 이런 얼음칸이 주어졌던 것이고 여기서 크게 3개의 조각이 만들어지므로 출력이 3이 된 것이다.\n\n# 어떻게 하면 알고리즘화 시킬 수 있을까? \n\n# 이 문제는 1칸씩 돌아가면서 DFS로 풀어야 하는 문제이다.(재귀함수를 사용한다고 생각하면 쉽다.)\n\n# 선택된 칸의 사방으로 확장할 수 있으면 확장해서 다시하면 재귀를 돌리면 결국 확장가능한 곳까지 뻗어나간다.\n\n# DFS로 특정 노드를 방문하고 연결된 모든 노드들도 방문\ndef dfs(x, y) :\n # 주어진 범위를 벗어나는 경우에는 즉시 종료\n if x <= -1 or x >= n or y <= -1 or y >= m:\n return False\n # 현재 노드를 아직 방문하지 않았다면\n if graph[x][y] == 0:\n # 해당 노드 방문 처리\n graph[x][y] = 1\n # 상, 하, 좌, 우의 위치들도 모두 재귀적으로 호출\n dfs(x-1, y) # 상\n dfs(x, y- 1) # 좌\n dfs(x+1, y) # 하\n dfs(x,y+1) # 우\n return True\n return False\n\n# N, M을 공백을 기준으로 구분하여 입력 받기\nn,m = map(int,input().split())\n\n# 2차원 리스트의 맵 정보 입력 받기\ngraph = []\nfor i in range(n) :\n graph.append(list(map(int, input())))\n\n#모든 노드(위치)에 대하여 음료수 채우기\nresult = 0\nfor i in range(n) :\n for j in range(m) :\n # 현재 위치에서 DFS 수행\n if dfs(i,j) == True:\n result += 1\nprint(result)","sub_path":"동빈나/탐색_음료수얼려먹기.py","file_name":"탐색_음료수얼려먹기.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"60115","text":"from odoo import api, fields, models,exceptions\r\nimport logging\r\nfrom datetime import date\r\n_logger = logging.getLogger(__name__)\r\n\r\n\r\nclass AccountInvoiceLine(models.Model):\r\n _inherit = 'account.voucher.line'\r\n\r\n freight_booking = fields.Many2one('freight.booking', string='Booking Job')\r\n\r\n def action_assign_job_cost(self):\r\n self.ensure_one()\r\n view = self.env.ref('sci_goexcel_invoice.view_job_cost_form')\r\n return {\r\n 'name': 'Add Job Cost',\r\n 'type': 'ir.actions.act_window',\r\n 'view_type': 'form',\r\n 'view_mode': 'form',\r\n 'res_model': 'freight.booking.job.cost',\r\n 'views': [(view.id, 'form')],\r\n 'view_id': view.id,\r\n 'target': 'new', # readonly mode\r\n 'context': dict(self.env.context, voucher_id=self.voucher_id.id, partner_id=self.voucher_id.partner_id.id,),\r\n }\r\n","sub_path":"sci_goexcel_invoice/models/account_voucher.py","file_name":"account_voucher.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"88042311","text":"import sys\nimport pathlib\nimport argparse\n\nimport geopandas as gpd\nfrom geocube.api.core import make_geocube\nimport rasterio as rio\nimport numpy as np\n\nfrom sgt.utils import custom_print\n\ndef rasterize(src_vector, out_rst, res=30, column=None, verbose=False):\n \"\"\" Burns vector geometries into a raster.\n \n Args : \n src_vector (str) : path to the source vector shapefile\n out_rst (str, optional) : path to the output raster\n res (int, optional) : the resolution of the output raster. If none, the default landsat 7 30m res will be used\n column (str, optional) : the name of the column to use as value in the output raster. default ot the first one \n \"\"\"\n \n # apply the verbose option\n v_print = custom_print(verbose)\n \n # read the vector data\n gdf = gpd.read_file(src_vector).to_crs(\"EPSG:4326\")\n \n # identify the column to be burn in the raster \n if not column:\n column = gdf.columns[0]\n \n # optimize dtype \n dtype = rio.dtypes.get_minimum_dtype(gdf[column])\n \n # optimize the nodata value to meet the dtype\n fill = np.nan\n if np.issubdtype(dtype, np.integer):\n fill = 0\n \n # convert the metric resolution into deg (as we work in EPSG 4326)\n # consider the equator approximation : 1° = 111 Km\n res = (res/111)*(10**(-3))\n\n out_grid = make_geocube(\n vector_data = gdf,\n measurements = [column],\n resolution = (-res, res),\n fill = fill\n )\n\n # write the column to raster file\n out_grid[column].rio.to_raster(out_rst, dtype=dtype)\n \n \n v_print(f'The vector geometries have been burn into the raster : {out_rst}')\n \n return\n\nif __name__ == \"__main__\":\n \n # write the description \n descript = \"Burns vector geometries into a raster\"\n \n # create an arg parser\n parser = argparse.ArgumentParser(description=descript)\n \n # read arguments\n parser.add_argument(\n '-i',\n dest = 'src_vector',\n metavar = 'source.shp',\n help = '(str) : path to the source vector file',\n required = True,\n type = pathlib.Path\n )\n parser.add_argument(\n '-o',\n dest = 'out_rst',\n metavar = 'output.tif',\n help = '(str) : path to the output raster',\n required = True,\n type = pathlib.Path\n )\n parser.add_argument(\n '-res',\n dest = 'res',\n metavar = 'a_number',\n help = '(int) : the resolution of the output raster. If none, the default landsat 7 30m res will be used',\n required = True,\n type = pathlib.Path\n )\n parser.add_argument(\n '-c',\n dest = 'column',\n metavar = 'a_name',\n help = '(str) : the name of the column to use as value in the output raster. default ot the first one ',\n required = False,\n type = str\n )\n parser.add_argument(\n '--no-v',\n dest = 'verbose',\n action='store_false',\n required = False,\n help = \"remove the verbose option\"\n ) \n \n # read arguments\n args = parser.parse_args()\n \n # launch the function \n rasterize(**vars(args))","sub_path":"sgt/sgt_rasterize.py","file_name":"sgt_rasterize.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"2779490","text":"# 2015.11.18 11:52:16 Střední Evropa (běžný čas)\n# Embedded file name: scripts/client/gui/customization_2_0/filter.py\nfrom Event import Event\nfrom constants import IGR_TYPE\nfrom elements.qualifier import QUALIFIER_TYPE\nfrom gui.customization_2_0.data_aggregator import CUSTOMIZATION_TYPE\n\nclass FILTER_TYPE:\n QUALIFIER = 0\n GROUP = 1\n PURCHASE_TYPE = 2\n SHOW_IN_DOSSIER = 3\n\n\nQUALIFIER_TYPE_INDEX = (QUALIFIER_TYPE.ALL,\n QUALIFIER_TYPE.COMMANDER,\n QUALIFIER_TYPE.GUNNER,\n QUALIFIER_TYPE.DRIVER,\n QUALIFIER_TYPE.RADIOMAN,\n QUALIFIER_TYPE.LOADER)\n\nclass PURCHASE_TYPE:\n PURCHASE = 0\n QUEST = 1\n ACTION = 2\n IGR = 3\n\n\nclass Filter(object):\n\n def __init__(self, availableGroupNames):\n self.changed = Event()\n self.__currentType = None\n self.__currentSlotIdx = None\n self.__availableGroupNames = availableGroupNames\n self.__currentGroup = 'all_groups'\n self.__showInDossier = True\n self.__purchaseType = PURCHASE_TYPE.PURCHASE\n self.__rules = [self.__hasSelectedBonus,\n self.__isInSelectedGroup,\n self.__isInDossier,\n self.__hasPurchaseType]\n self.__selectedBonuses = {QUALIFIER_TYPE.ALL: False,\n QUALIFIER_TYPE.COMMANDER: False,\n QUALIFIER_TYPE.GUNNER: False,\n QUALIFIER_TYPE.DRIVER: False,\n QUALIFIER_TYPE.RADIOMAN: False,\n QUALIFIER_TYPE.LOADER: False}\n return\n\n def fini(self):\n self.__rules = None\n self.__availableGroupNames = None\n self.__selectedBonuses = None\n return\n\n @property\n def availableGroupNames(self):\n return self.__availableGroupNames\n\n @property\n def selectedBonuses(self):\n return self.__selectedBonuses\n\n def isDefaultFilterSet(self):\n if self.__currentType == CUSTOMIZATION_TYPE.CAMOUFLAGE:\n return self.__purchaseType == PURCHASE_TYPE.PURCHASE\n else:\n return not self.__bonusSelected() and self.__currentGroup == 'all_groups' and self.__purchaseType == PURCHASE_TYPE.PURCHASE\n\n def setDefaultFilter(self):\n self.__currentGroup = 'all_groups'\n for key in QUALIFIER_TYPE_INDEX:\n self.__selectedBonuses[key] = False\n\n self.__purchaseType = PURCHASE_TYPE.PURCHASE\n\n @property\n def currentType(self):\n return self.__currentType\n\n @property\n def purchaseType(self):\n return self.__purchaseType\n\n @property\n def currentSlotIdx(self):\n return self.__currentSlotIdx\n\n @property\n def currentGroup(self):\n return self.__currentGroup\n\n def check(self, item):\n for rule in self.__rules:\n if not rule(item):\n return False\n\n return True\n\n def set(self, filterGroup, filterGroupValue):\n if filterGroup == FILTER_TYPE.QUALIFIER:\n self.__selectedBonuses[QUALIFIER_TYPE_INDEX[filterGroupValue]] ^= True\n elif filterGroup == FILTER_TYPE.GROUP:\n self.__currentGroup = filterGroupValue\n elif filterGroup == FILTER_TYPE.SHOW_IN_DOSSIER:\n self.__showInDossier = filterGroupValue\n elif filterGroup == FILTER_TYPE.PURCHASE_TYPE:\n self.__purchaseType = filterGroupValue\n\n def setTypeAndIdx(self, cType, slotIdx, customizationId, oldCustomizationId):\n self.__currentSlotIdx = slotIdx\n self.__customizationId = customizationId\n self.__oldCustomizationId = oldCustomizationId\n if self.__currentType != cType:\n self.__currentType = cType\n self.setDefaultFilter()\n\n def apply(self):\n self.changed()\n\n def __hasSelectedBonus(self, item):\n if not self.__bonusSelected():\n return True\n if item.qualifier.getType() == QUALIFIER_TYPE.CAMOUFLAGE:\n return True\n return self.__selectedBonuses[item.qualifier.getType()]\n\n def __isInSelectedGroup(self, item):\n if self.__currentGroup == 'all_groups':\n return True\n else:\n return item.getGroup() == self.__currentGroup\n\n def __isInDossier(self, item):\n if self.__showInDossier:\n return True\n else:\n needShow = self.__customizationId == item.getID() or self.__oldCustomizationId == item.getID()\n return not item.isInDossier or needShow\n\n def __bonusSelected(self):\n for key in QUALIFIER_TYPE_INDEX:\n if self.__selectedBonuses[key]:\n return True\n\n return False\n\n def __hasPurchaseType(self, item):\n if self.__purchaseType == PURCHASE_TYPE.PURCHASE:\n return item.getIgrType() == IGR_TYPE.NONE\n if self.__purchaseType == PURCHASE_TYPE.QUEST:\n return False\n if self.__purchaseType == PURCHASE_TYPE.IGR:\n return item.getIgrType() == IGR_TYPE.PREMIUM\n# okay decompyling c:\\Users\\PC\\wotsources\\files\\originals\\res\\scripts\\client\\gui\\customization_2_0\\filter.pyc \n# decompiled 1 files: 1 okay, 0 failed, 0 verify failed\n# 2015.11.18 11:52:16 Střední Evropa (běžný čas)\n","sub_path":"res/scripts/client/gui/customization_2_0/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":5060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"508554771","text":"def escribir_vector(V):\n print(V)\n\n\ndef ordenar_por_burbuja_eficiente(V):\n num_recorridos=0\n while num_recorridos<=ultimo(V):\n i=0\n while i V[i+1]:\n aux=V[i]\n V[i]=V[i+1]\n V[i+1]=aux\n i=i+1\n num_recorridos=num_recorridos+1\n return(V)\n\ndef ultimo(V):\n enc=False\n i=1\n j=0\n while enc==False and j>len(V):\n if V[-1-j] 0):\n\t\tfor row in RDB[1]:\n\t\t\tcnt += tkr.Remove( str(row[\"TakeReply_IDX\"]) )\n\t\n\treturn cnt\n\n\n## Features ----------\n\ndef getInitFormData( task_idx=None ):\n\t\"\"\" 신규 Take 작성시 양식정보 채움 \"\"\"\n\t\n\tformData = {}\n\t\n\tif ( task_idx != None ):\n\t\ttaskData = Archive(\"Task\").getValues(task_idx, \"Task.TypeCode,Task.Element,Task.Parent3\")\n\t\tformData[\"TypeCode\"] = taskData[\"TypeCode\"]\n\t\tformData[\"Element\"] = taskData[\"Element\"]\n\t\tformData[\"Parent3\"] = taskData[\"Parent3\"]\n\t\t\n\t\t#Find Last Version\n\t\tlastTake = Archive(\"Take\").getValues(\n\t\t\t\"Take.Parent3 == %s,Take.TypeCode == %s,Take.Element == %s\" %( formData[\"Parent3\"], formData[\"TypeCode\"], formData[\"Element\"] ),\n\t\t\t\"Name,Code,Version,Content,ApprovalNote\",\n\t\t\t\"Take.Version DESC\")\n\t\t\n\t\tif lastTake:\n\t\t\tformData[\"Name\"] = Naming.increaseName( lastTake[\"Name\"] )\n\t\t\tif lastTake[\"Version\"] == 0 or lastTake[\"Version\"] == None:\n\t\t\t\tformData[\"Version\"] = 1\n\t\t\telse:\n\t\t\t\tformData[\"Version\"] = int(lastTake[\"Version\"]) + 1\n\t\t\tformData[\"PrevApprNote\"] = lastTake[\"ApprovalNote\"]\n\t\t\tformData[\"PrevContent\"] = lastTake[\"Content\"]\n\t\telse:\n\t\t\tformData[\"PrevApprNote\"] = \"냉무\"\n\t\t\tformData[\"PrevContent\"] = \"냉무\"\n\t\t\tformData[\"Version\"] = 1\n\t\t\t\n\t\t\targ2 = { \"Take.TypeCode\": formData[\"TypeCode\"],\n\t\t\t\t\t\t\"Take.Element\": formData[\"Element\"],\n\t\t\t\t\t\t\"Take.Version\" : formData[\"Version\"] }\n\t\t\t\n\t\t\tformData[\"Name\"] = getNewName( task_idx, **arg2) \n\t\t\t#outDic[\"Name\"] = getNewName(taskIdx=taskIdx, shotIdx=shotIdx, taskCode=taskCode, elementName=elementName)\n\t\n\treturn formData\n\n\n\ndef getNewName( task_idx=None, **arg):\n\t\n\tif (not \"Version\" in arg) and (not \"Take.Version\" in arg):\n\t\tparent3 = Archive(\"Task\").getValue(task_idx, \"Task.Parent3\")\n\t\t\n\t\t#Find Last Version\n\t\tlastTake = Archive(\"Take\").getValue(\n\t\t\t\t\"Take.Parent3 == %s,Take.TypeCode == %s,Take.Element == %s\" %( parent3, arg[\"Take.TypeCode\"], arg[\"Take.Element\"]),\n\t\t\t\t\"Version\", \"Take.Version DESC\")\n\t\tif lastTake:\n\t\t\targ[\"Take.Version\"] = int(lastTake[\"Version\"]) + 1\n\t\telse:\n\t\t\targ[\"Take.Version\"] = 1\n\t\n\treturn Naming.ApplyWithQuery(\"Take.Name\", task_idx, baseArcv=\"Task\", **arg )\n\n\n## EVENTS ------------\n\ndef OnBeforeInsert(self, arg, extra):\n\n\t#[TODO] 등록권한 채크\n\t\n\ttask_idx = arg[\"Parent4\"]\n\ttaskData = Archive(\"Task\").getValues( task_idx, \"Parent1,Parent2,Parent3,Confirmer\")\n\tif taskData:\n\t\targ[\"Parent1\"] = taskData[\"Parent1\"]\n\t\targ[\"Parent2\"] = taskData[\"Parent2\"]\n\t\targ[\"Parent3\"] = taskData[\"Parent3\"]\n\t\targ[\"Confirmer\"] = taskData[\"Confirmer\"] # 아이디\t\t\t \n\t\t#arg[\"Confirmer2\"] = taskData[\"Confirmer2\"] # 이름 \n\telse:\n\t\traise SpartaError(\"this index %s has no task \" % taskidx)\n\t\n\targ[\"Code\"] = arg[\"Name\"].upper()\n\t\n\tNaming.uuid( arg )\t \n\tDefaultTypeCode( arg )\n\tDefaultStatCode( arg )\n\tDefaultThumbnail( arg ) \n\tLogin.CreaterStamp(arg)\n\tLogin.ModifyerStamp(arg)\t\n\treturn arg\n\n\ndef OnAfterInsert(self, arg, extra):\n\t\n\tidx = extra[\"idx\"]\n\tmodifyData\t= { \"IDX\": idx, \"_pass_\":True, \"useSpartaDir\": True }\n\t\n\ttakeData = self.getValues( idx, \"Take.Parent1,Take.Parent2,Project.Code,Seq.TypeCode,Shot.TypeCode,Task.TypeCode,Take.TypeCode\")\n\tpData = {\n\t\t\"Project.Code\": takeData[\"Project.Code\"],\n\t\t\"Seq.TypeCode\": takeData[\"Seq.TypeCode\"],\n\t\t\"Shot.TypeCode\": takeData[\"Shot.TypeCode\"],\n\t\t\"Task.TypeCode\": takeData[\"Task.TypeCode\"],\t\t \n\t\t\"Take.TypeCode\": takeData[\"TypeCode\"],\t\t \n\t}\n\t\n\tif \"Preview\" in arg: modifyData[\"Preview\"] = arg[\"Preview\"]\n\tFiles.CopyThumb2Naming( \"Take.Preview\", idx, inArg=modifyData, preData=pData )\n\t\n\t#[TODO] 샷에 최종 MOV 등록\n\t#[TODO] Task FinishDate 기록\n\t#[TODO] 메세지 남기기 -> 컨펌이 요구되는 작업물이 등록되었습니다.\" % arg[\"Name\"]\n\t\n\tself.Edit( idx, **modifyData )\n\treturn arg\n\n\ndef OnBeforeModify(self, arg, extra):\n\tLogin.ModifyerStamp( arg )\n\treturn arg\n\n\ndef OnAfterModify(self, arg, extra): \n\t#[TODO] 최종 변경자 적용\n\t\n\tidx = extra[\"idx\"]\n\t\n\t# 테이크 승인시 알림 처리 \n\tif \"StatCode\" in arg:\t\t \n\t\ttakeData = self.getValues(idx, \"Take_Stat.Name,StatCode,Parent4,Name,CreateBy,Shot.Name\")\n\t\t\n\t\tstatName = takeData[\"Take_Stat.Name\"]\t\t \n\t\ttakeName = takeData[\"Name\"] \n\t\tcreUser = takeData[\"CreateBy\"]\n\t\tshotName = takeData[\"Shot.Name\"]\t\t\t\t\t\t\n\t\t\n\t\tmsg = u\"[%s/%s] : 작업물이 %s 상태로 변경 되었습니다.\" % (shotName, takeName, statName)\t\t \n\t\tMessage.sendMessage(creUser, msg, \"%s\" % (idx, msg) )\n\t\t\n\t\t# 연차적 상태변환 \n\t\tif takeData[\"StatCode\"] == \"OK\":\t\t\t\n\t\t\tdSave = {\"IDX\" : takeData[\"Parent4\"], \"StatCode\" : \"DON\"}\t\t \n\t\t\tArchive(\"Task\").New(**dSave)\n\n\treturn arg\n\n\ndef OnBeforeRemove(self, arg, extra):\n\n\tidx = extra[\"idx\"]\t \n\ttakeData = Archive(\"Take\").getValues(idx, \"Parent4,CreateBy,Name\")\n\t\n\tif takeData[\"CreateBy\"] != session[\"UserID\"]:\t \n\t\tmsg = u\"[%s] : 작업물이 삭제되었습니다.\" % takeData[\"Name\"]\n\t\t# 컨퍼머 한테도 가도록\n\t\tMessage.sendMessage(takeData[\"CreateBy\"], msg, \"%s\" % (takeData[\"Parent4\"], msg) )\n\t\n\tdeleteChildren( idx )\t \n\treturn arg\n\n\ndef OnAfterInsert_TakeReply(self, arg, extra):\n\t\n\tidx = extra[\"idx\"]\n\tpidx = arg[\"ParentIDX\"]\n\t\n\ttakeData = Archive(\"Take\").getValues(pidx, \"CreateBy,Name\")\n\tlinkto = \"/take/view/%s\" % (pidx)\n\t\n\tif takeData[\"CreateBy\"] != arg[\"CreateBy\"]:\n\t\tmsg = u\"[%s] : 작업물에 피드백이 작성되었습니다.\" % takeData[\"Name\"]\n\t\tMessage.sendMessage(takeData[\"CreateBy\"], msg, \"%s\" % ( pidx, msg) )\n\telse:\n\t\tmsg = u\"[%s] : 피드백에 대한 회신이 작성되었습니다.\" % takeData[\"Name\"]\t\t \n\t\tsQuery = \"Select distinct CreateBy From TakeReply where ParentIDX = :pidx and CreateBy != :wid\"\n\t\twUsers = [r[0] for r in Archive.RunQuery(sQuery, pidx=pidx, wid=arg[\"CreateBy\"])]\n\t\tfor user1 in wUsers:\n\t\t\tMessage.sendMessage(user1, msg, \"%s\" % (pidx, msg) )\n\t\n\treturn arg\n\n## ---------------------------\n\n\n\n","sub_path":"Sparta/sparta/model/SpartaServer/Take.py","file_name":"Take.py","file_ext":"py","file_size_in_byte":7662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"15977439","text":"import argparse\n\nscores = (91, 81, 71, 61, 0)\ngrades = (\"A\", \"B\", \"C\", \"D\", \"F\")\n\n\ndef score_range(string):\n value = int(string)\n if value > 100 or value < 0:\n msg = \"%r is not in range[0-100]\" % string\n raise argparse.ArgumentTypeError(msg)\n return value\n\n\ndef main(argv):\n for num, score in enumerate(scores, start=0):\n if argv >= score:\n print(grades[num])\n break\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Calculate grade from score')\n parser.add_argument('score', type=score_range,\n help='an integer for the accumulator [0-100]')\n args = parser.parse_args()\n main(args.score)\n","sub_path":"grade_loop.py","file_name":"grade_loop.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"446324488","text":"from django import forms\nfrom django.db import models\nfrom django.core.validators import MaxLengthValidator\nfrom django.utils.translation import ugettext_lazy as _\n\n\n# custom text area for word limits\n# model field\nclass TextLengthField(models.TextField):\n\n description = _(\"Text (up to %(max_length)s characters)\")\n\n widget_attrs = {\n 'cols': '120',\n 'rows': '20',\n }\n\n # can pass max_length and widget_attrs to TextField\n def __init__(self, *args, **kwargs):\n if kwargs and 'widget_attrs' in kwargs:\n self.widget_attrs.update(kwargs.pop('widget_attrs'))\n\n super(TextLengthField, self).__init__(*args, **kwargs)\n if self.max_length:\n self.validators.append(MaxLengthValidator(self.max_length))\n\n def formfield(self, **kwargs):\n defaults = {\n 'max_length': self.max_length,\n 'widget': forms.Textarea(attrs=self.widget_attrs),\n }\n defaults.update(kwargs)\n return super(TextLengthField, self).formfield(**defaults)\n\n\n# for south datamigration, need to tell south about new model field\ntry:\n from south.modelsinspector import add_introspection_rules\n add_introspection_rules([], [\"^project_application\\.project_application\\.fields\\.TextLengthField\"])\nexcept ImportError:\n pass\n","sub_path":"project_application/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"112889621","text":"import glob\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom .actor import Actor\nfrom .critic import Critic\nfrom utils.stats import gather_stats\nfrom utils.networks import tfSummary, OrnsteinUhlenbeckProcess\nfrom utils.memory_buffer import MemoryBuffer\n\n\n\ntry:\n sys.path.append(glob.glob('C:/Users/User/Pictures/CARLA_0.9.5/PythonAPI/carla/dist/carla-*%d.%d-%s.egg' % (\n sys.version_info.major,\n sys.version_info.minor,\n 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])\nexcept IndexError:\n pass\nimport carla\n\nimport random\nimport time\n# import numpy as np\nimport cv2\nimport math\n# import tensorflow as tf\n# import gym\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\n\n\nSHOW_PREVIEW = False\nIM_WIDTH = 640\nIM_HEIGHT = 480\nSECONDS_PER_EPISODE = 8.5\nREPLAY_MEMORY_SIZE = 5_0000\nMIN_REPLAY_MEMORY_SIZE = 100\nMINIBATCH_SIZE = 16\nPREDICTION_BATCH_SIZE = 1\nTRAINING_BATCH_SIZE = MINIBATCH_SIZE // 4\nUPDATE_TARGET_EVERY = 5\nMODEL_NAME = \"Xception\"\nsafe_dist = 5.0\n# MEMORY_FRACTION = 0.4\nMIN_REWARD = -200\n\nEPISODES = 2000\n\nDISCOUNT = 0.99\nepsilon = 1\nEPSILON_DECAY = 0.95 ## 0.9975 99975\nMIN_EPSILON = 0.001\n\nAGGREGATE_STATS_EVERY = 10\ndistance_data = []\nbrake_control = [-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1]\n\n\n# environment code...\n\nclass CarEnv:\n SHOW_CAM = SHOW_PREVIEW\n STEER_AMT = 1.0\n im_width = IM_WIDTH\n im_height = IM_HEIGHT\n front_camera = None\n\n def __init__(self):\n self.client = carla.Client(\"localhost\", 2000)\n self.client.set_timeout(5.0)\n self.world = self.client.get_world()\n self.blueprint_library = self.world.get_blueprint_library()\n self.model_3 = self.blueprint_library.filter(\"model3\")[0]\n self.model_32 = self.blueprint_library.filter(\"model3\")[0]\n\n def reset(self):\n self.collision_hist = []\n self.actor_list = []\n vel = random.uniform(8.33, 27.77)\n self.diff = 60.0\n\n self.spawn_point = carla.Transform(carla.Location(-88.4,-152.1,0.0),carla.Rotation(yaw=90))\n self.spawn_point2 = carla.Transform(carla.Location(-88.4,-152.1+self.diff,0.0),carla.Rotation(yaw=90))\n self.vehicle = self.world.try_spawn_actor(self.model_3, self.spawn_point)\n self.vehicle2 = self.world.try_spawn_actor(self.model_32, self.spawn_point2)\n if self.vehicle is None:\n self.reset()\n if self.vehicle2 is None:\n self.reset()\n self.actor_list.append(self.vehicle)\n self.actor_list.append(self.vehicle2)\n \n # # self.vehicle.apply_control(carla.VehicleControl(throttle=3.0, brake=0.0))\n self.rgb_cam = self.blueprint_library.find('sensor.camera.rgb')\n self.rgb_cam.set_attribute(\"image_size_x\", f\"{self.im_width}\")\n self.rgb_cam.set_attribute(\"image_size_y\", f\"{self.im_height}\")\n self.rgb_cam.set_attribute(\"fov\", f\"110\")\n\n transform = carla.Transform(carla.Location(x=2.5, z=0.7))\n self.sensor = self.world.spawn_actor(self.rgb_cam, transform, attach_to=self.vehicle)\n self.actor_list.append(self.sensor)\n self.sensor.listen(lambda data: self.process_img(data))\n\n colsensor = self.blueprint_library.find(\"sensor.other.collision\")\n self.colsensor = self.world.spawn_actor(colsensor, transform, attach_to=self.vehicle)\n self.actor_list.append(self.colsensor)\n self.colsensor.listen(lambda event: self.collision_data(event))\n\n time.sleep(1)\n while self.front_camera is None:\n time.sleep(0.01)\n\n self.episode_start = time.time()\n temp = []\n self.vehicle2.set_velocity(carla.Vector3D(x=0,y=0,z=0))\n # think of using autopilot using command vehicle.set_autopilot(True) for some second or till I get temp length = 5.\n \n self.vehicle.set_velocity(carla.Vector3D(y=vel))\n while True:\n min_dist = [1,2,3,999999]\n t1 = self.vehicle.get_transform()\n t2 = self.vehicle2.get_transform()\n if len(temp) == 40:\n break\n else:\n temp.append(abs(t1.location.x - t2.location.x))\n temp.append(abs(t1.location.y - t2.location.y))\n temp.append(self.vehicle.get_velocity().x)\n temp.append(self.vehicle.get_velocity().y)\n return temp\n\n def collision_data(self, event):\n self.collision_hist.append(event)\n\n def process_img(self, image):\n i = np.array(image.raw_data)\n #print(i.shape)\n i2 = i.reshape((self.im_height, self.im_width, 4))\n i3 = i2[:, :, :3]\n if self.SHOW_CAM:\n cv2.imshow(\"\", i3)\n cv2.waitKey(1)\n self.front_camera = i3\n\n def get_states_dim(self):\n return(15)\n\n def get_num_actions(self):\n return(1)\n\n def step(self, action, step):\n if action <= 0:\n print(\"Now brake is {}\".format(abs(action)))\n self.vehicle.apply_control(carla.VehicleControl(brake=float(action), throttle=0.0,\n steer=0.0))\n else:\n print(\"Now throttle is {}\".format(abs(action)))\n self.vehicle.apply_control(carla.VehicleControl(brake=0.0, throttle=float(action),\n steer=0.0))\n\n time.sleep(0.1)\n v = self.vehicle.get_velocity()\n c = self.vehicle.get_control()\n t = self.vehicle.get_transform()\n v2 = self.vehicle2.get_velocity()\n brake = c.brake\n throt = c.throttle\n vehicles = self.world.get_actors().filter('vehicle.*')\n # print(\"Now brake is {}\".format(brake))\n if len(vehicles) > 1:\n distance = lambda l: [l.x-t.location.x, l.y-t.location.y, l.z-t.location.z, math.sqrt((l.x - t.location.x)**2 + (l.y - t.location.y)**2 + (l.z - t.location.z)**2)]\n vehicles = [distance(x.get_location()) for x in vehicles if x.id != self.vehicle.id]\n vehicles_n = vehicles\n min_dist = [1,2,3,999999]\n for i in vehicles_n:\n if i[3] < min_dist[3]:\n min_dist = i\n\n velo = int(3.6 * math.sqrt(v.x**2 + v.y**2 + v.z**2))\n print(\"Now distance to vehicle is {}\".format(min_dist[3]))\n print(\"Now velocity of the vehicle is {}\".format(velo))\n if len(self.collision_hist) != 0:\n reward = -1*(0.01*min_dist[3]**2+ 0.1)*abs(action) - (0.01*velo**2+ 50)\n done = True\n\n elif min_dist[3] > 15.0 and step > 15 and velo == 0:\n reward = -0.01*min_dist[3]**2 - 15\n done = True\n else:\n reward = +0.5\n done = False\n\n if self.episode_start + SECONDS_PER_EPISODE < time.time():\n done = True\n\n return [min_dist[0], min_dist[1], v.x, v.y], reward, done, None\n\n\n\n\n\nclass DDPG:\n \"\"\" Deep Deterministic Policy Gradient (DDPG) Helper Class\n \"\"\"\n\n def __init__(self, act_dim, env_dim, act_range, k, buffer_size = 20000, gamma = 0.99, lr = 0.00005, tau = 0.001):\n \"\"\" Initialization\n \"\"\"\n # Environment and A2C parameters\n self.act_dim = act_dim\n self.act_range = act_range\n # self.env_dim = (k,) + env_dim\n self.env_dim = (40,)\n self.gamma = gamma\n self.lr = lr\n # Create actor and critic networks\n self.actor = Actor(self.env_dim, act_dim, act_range, 0.1 * lr, tau)\n self.critic = Critic(self.env_dim, act_dim, lr, tau)\n self.buffer = MemoryBuffer(buffer_size)\n\n\n def policy_action(self, s):\n \"\"\" Use the actor to predict value\n \"\"\"\n return self.actor.predict(s)[0]\n\n def bellman(self, rewards, q_values, dones):\n \"\"\" Use the Bellman Equation to compute the critic target\n \"\"\"\n critic_target = np.asarray(q_values)\n for i in range(q_values.shape[0]):\n if dones[i]:\n critic_target[i] = rewards[i]\n else:\n critic_target[i] = rewards[i] + self.gamma * q_values[i]\n return critic_target\n\n def memorize(self, state, action, reward, done, new_state):\n \"\"\" Store experience in memory buffer\n \"\"\"\n self.buffer.memorize(state, action, reward, done, new_state)\n\n def sample_batch(self, batch_size):\n return self.buffer.sample_batch(batch_size)\n\n def update_models(self, states, actions, critic_target):\n \"\"\" Update actor and critic networks from sampled experience\n \"\"\"\n # Train critic\n self.critic.train_on_batch(states, actions, critic_target)\n # Q-Value Gradients under Current Policy\n actions = self.actor.model.predict(states)\n grads = self.critic.gradients(states, actions)\n # Train actor\n self.actor.train(states, actions, np.array(grads).reshape((-1, self.act_dim)))\n # Transfer weights to target networks at rate Tau\n self.actor.transfer_weights()\n self.critic.transfer_weights()\n\n def train(self, summary_writer):\n env = CarEnv()\n results = []\n i = 0\n # First, gather experience\n tqdm_e = tqdm(range(2000), desc='Score', leave=True, unit=\" episodes\")\n for e in tqdm_e:\n\n # Reset episode\n time, cumul_reward, done = 0, 0, False\n old_state = env.reset()\n old_state = np.array(old_state).reshape(40,)\n actions, states, rewards = [], [], []\n noise = OrnsteinUhlenbeckProcess(size=self.act_dim)\n\n while not done:\n # if args.render: env.render()\n # Actor picks an action (following the deterministic policy)\n a = self.policy_action(old_state)\n # Clip continuous values to be valid w.r.t. environment\n a = np.clip(a+noise.generate(time), -self.act_range, self.act_range)\n a = float(a[0])\n # Retrieve new state, reward, and whether the state is terminal\n new_state, r, done, _ = env.step(a, time)\n print(\"Now r is {}\".format(r))\n # Add outputs to memory buffer\n temp_next = old_state.copy()\n temp_next[:4] = temp_next[4:8]\n temp_next[4:8] = temp_next[8:12]\n temp_next[8:12] = temp_next[12:16]\n temp_next[12:16] = temp_next[16:20]\n temp_next[16:20] = temp_next[20:24]\n temp_next[20:24] = temp_next[24:28]\n temp_next[24:28] = temp_next[28:32]\n temp_next[28:32] = temp_next[32:36]\n temp_next[32:36] = temp_next[36:40]\n temp_next[36:40] = new_state\n temp_next = np.array(temp_next).reshape(40,)\n self.memorize(old_state, a, r, done, temp_next)\n old_state = temp_next.copy()\n cumul_reward += r\n time += 1\n\n # since episode is over destroying actors in the scenario\n for actor in env.actor_list:\n actor.destroy()\n # Sample experience from buffer\n for i in range(50):\n states, actions, rewards, dones, new_states, _ = self.sample_batch(64)\n # Predict target q-values using target networks\n q_values = self.critic.target_predict([new_states, self.actor.target_predict(new_states)])\n # Compute critic target\n critic_target = self.bellman(rewards, q_values, dones)\n # Train both networks on sampled batch, update target networks\n self.update_models(states, actions, critic_target)\n print(\"learning happened\")\n\n mean, stdev = gather_stats(self, env)\n results.append([e, mean, stdev])\n\n # Export results for Tensorboard\n print(cumul_reward)\n score = tfSummary('score', cumul_reward)\n summary_writer.add_summary(score, global_step=e)\n summary_writer.flush()\n # Display score\n tqdm_e.set_description(\"Score: \" + str(cumul_reward))\n tqdm_e.refresh()\n i+=1\n if i % 10 == 0:\n df = pd.DataFrame(np.array(results))\n df.to_csv(\"DDPG\" + \"/logs.csv\", header=['Episode', 'Mean', 'Stddev'], float_format='%10.5f')\n\n return results\n\n\n def save_weights(self, path):\n path += '_LR_{}'.format(self.lr)\n self.actor.save(path)\n self.critic.save(path)\n\n def load_weights(self, path_actor, path_critic):\n self.critic.load_weights(path_critic)\n self.actor.load_weights(path_actor)\n","sub_path":"DDPG_static_car/ddpg.py","file_name":"ddpg.py","file_ext":"py","file_size_in_byte":12634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"243863809","text":"import numpy as np\nimport pandas as pd\nfrom splearn.DecisionTree.DecisionTree import DecisionTree\n\nclass RandomForest:\n\n def __init__(self):\n '''\n Creates a new TreeBagger that can be trained using an array of\n DecisionTrees\n '''\n\n self.trees = []\n self.features = None\n self.target = None\n\n def train(\n self,\n features: pd.DataFrame,\n target: pd.Series,\n num_trees: int,\n seed: int,\n feature_frac: float = 0.68,\n subset_frac: float = 0.68,\n gain = \"entropy\",\n ):\n '''\n Trains N decision trees for bagging prediction\n \n Parameters:\n \n * features (DataFrame): Features used for training\n * target (Series): Predictions to be trained against\n * num_trees (int): Number of trees used in the prediction\n * gain: Type of gain used to train trees\n * seed (int): Lorem ipsum\n \n '''\n\n # Stage the internal variables for the machine\n self.features = features\n self.target = target\n self.gain = gain\n self.seed = seed\n self.subset_frac = subset_frac\n self.feature_frac = feature_frac\n\n classes = [0, 1]\n uniques = np.unique(target)\n self.binary_dict = dict(zip(classes, uniques))\n self.class_dict = dict(zip(uniques, classes))\n\n self.iterate(num_trees)\n\n\n def predict(\n self,\n features: pd.DataFrame\n ):\n\n votes = np.zeros(len(features))\n \n for m in self.trees:\n\n preds = m.predict(features)\n preds = preds.map(self.class_dict)\n preds = (preds - 0.5) * 2\n \n votes += preds\n\n result = pd.Series((votes >= 0).astype(int))\n result = result.map(self.binary_dict)\n\n return result\n\n\n def __len__(self):\n return len(self.trees)\n\n def iterate(\n self,\n iterations\n ):\n \n for i in range(iterations):\n\n # Create a random subset of 68% of the data\n sub_feat = self.features.sample(\n frac = self.subset_frac,\n random_state = self.seed + len(self),\n replace = True,\n axis = \"index\"\n )\n\n sub_feat = sub_feat.sample(\n frac = self.feature_frac,\n random_state = self.seed + len(self),\n axis=\"columns\"\n )\n\n sub_idx = sub_feat.index\n sub_targ = self.target[sub_idx]\n\n # Predict tree fully based on subset\n tree = DecisionTree()\n tree.train(\n sub_feat,\n sub_targ,\n gain=self.gain,\n )\n\n # Add tree to bagger\n self.trees.append(tree)","sub_path":"splearn/EnsembleLearning/RandomForest.py","file_name":"RandomForest.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"137880896","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nfrom pdfquery import PDFQuery\nimport pdfminer\nfrom pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.layout import LAParams\nfrom pdfminer.converter import PDFPageAggregator\nfrom pdfminer.layout import LTTextBoxHorizontal, LTRect, LTLine\n\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nimport pandas as pd\n\n\n# In[3]:\n\n\ndef extract_page_layouts(file):\n \"\"\"\n Extracts LTPage objects from a pdf file.\n modified from: http://www.degeneratestate.org/posts/2016/Jun/15/extracting-tabular-data-from-pdfs/\n Tests show that using PDFQuery to extract the document is ~ 5 times faster than pdfminer.\n \"\"\"\n laparams = LAParams()\n \n with open(file, mode='rb') as pdf_file:\n print(\"Open document %s\" % pdf_file.name)\n document = PDFQuery(pdf_file).doc\n\n if not document.is_extractable:\n raise PDFTextExtractionNotAllowed\n\n rsrcmgr = PDFResourceManager()\n device = PDFPageAggregator(rsrcmgr, laparams=laparams)\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n\n layouts = []\n for page in PDFPage.create_pages(document):\n interpreter.process_page(page)\n layouts.append(device.get_result())\n \n return layouts\n\n\n# In[4]:\n\n\nTEXT_ELEMENTS = [\n pdfminer.layout.LTTextBox,\n pdfminer.layout.LTTextBoxHorizontal,\n pdfminer.layout.LTTextLine,\n pdfminer.layout.LTTextLineHorizontal\n]\n\nFILE_NAME = \"test.pdf\"\nCOL_MARGIN = 0.5\npage_layouts = extract_page_layouts(FILE_NAME)\nprint(page_layouts)\nprint(\"Number of pages: %d\" % len(page_layouts))\n\n\n# In[5]:\n\n\ndef extract_single_page_text(current_page):\n text = []\n for elem in current_page:\n if isinstance(elem, pdfminer.layout.LTTextBoxHorizontal):\n text.append(elem)\n return text\n\n\n# In[6]:\n\n\nraw_text = extract_single_page_text(page_layouts[0])\nraw_text\n\n\n# In[7]:\n\n\ndef flatten(lst):\n \"\"\"Flattens a list of lists\"\"\"\n return [item for sublist in lst for item in sublist]\n\ndef extract_characters(element):\n \"\"\"\n Recursively extracts individual characters from \n text elements. \n \"\"\"\n if isinstance(element, pdfminer.layout.LTChar):\n return [element]\n\n if any(isinstance(element, i) for i in TEXT_ELEMENTS):\n return flatten([extract_characters(e) for e in element])\n\n if isinstance(element, list):\n return flatten([extract_characters(l) for l in element])\n\n return []\n\n\n# In[8]:\n\n\nraw_characters = extract_characters(raw_text)\nraw_characters\n\n\n# In[9]:\n\n\ndef arrange_text(characters):\n \"\"\"\n For each row find the characters in the row\n and sort them horizontally.\n \"\"\"\n \n # find unique y0 (rows) for character assignment\n rows = sorted(list(set(c.bbox[1] for c in characters)), reverse=True)\n \n sorted_rows = []\n for row in rows:\n sorted_row = sorted([c for c in characters if c.bbox[1] == row], key=lambda c: c.bbox[0])\n sorted_rows.append(sorted_row)\n return sorted_rows\n\nsorted_rows = arrange_text(raw_characters)\nsorted_rows\n\n\n# In[10]:\n\n\ncol_margin = 0.5\ndef create_separators(sorted_rows, margin):\n \"\"\"Creates bounding boxes to fill the space between columns\"\"\"\n separators = []\n for row in sorted_rows:\n for idx, c in enumerate(row[:-1]): \n if (row[idx+1].bbox[0] - c.bbox[2]) > margin:\n bbox = (c.bbox[2], c.bbox[3], row[idx+1].bbox[0], row[idx+1].bbox[1])\n separator = pdfminer.layout.LTRect(linewidth=2, bbox=bbox)\n separators.append(separator)\n return separators\n\nseparators = create_separators(sorted_rows, col_margin)\n\n\n# In[11]:\n\n\ndef arrange_and_extract_text(characters, margin=0.5):\n \n rows = sorted(list(set(c.bbox[1] for c in characters)), reverse=True)\n \n row_texts = []\n for row in rows:\n \n sorted_row = sorted([c for c in characters if c.bbox[1] == row], key=lambda c: c.bbox[0])\n \n col_idx=0\n row_text = []\n for idx, char in enumerate(sorted_row[:-1]):\n if (sorted_row[idx+1].bbox[0] - char.bbox[2]) > margin:\n col_text = \"\".join([c.get_text() for c in sorted_row[col_idx:idx+1]])\n col_idx = idx+1\n row_text.append(col_text)\n elif idx==len(sorted_row)-2:\n col_text = \"\".join([c.get_text() for c in sorted_row[col_idx:]])\n row_text.append(col_text) \n row_texts.append(row_text)\n return row_texts\n\ntext = arrange_and_extract_text(raw_characters)\ntext\n\n\n# In[12]:\n\n\n\ndef generate_current_page_dataframe(text):\n columns = ['Date sold or disposed', 'Quantity', 'Proceeds', 'Date acquired', 'Cost or other basis', 'Wash sale loss disallowed (W)', 'Code', 'Gain or loss(-)', 'Additional information']\n df = pd.DataFrame(columns=columns)\n for row in text:\n if len(row) == 5:\n row = row.copy()\n row.insert(0, \"-\")\n row.insert(1, \"-\")\n row.insert(3, \"-\")\n row.insert(8, \"-\")\n temp = pd.DataFrame([row], columns=columns)\n df = df.append(temp, ignore_index=True)\n elif len(row) == 9:\n df_row = pd.DataFrame([row], columns=columns)\n df = df.append(df_row, ignore_index=True)\n elif len(row) == 8 and row[5] == \"W\":\n row = row.copy()\n row.insert(3, \"Various\")\n temp = pd.DataFrame([row], columns=columns)\n df = df.append(temp, ignore_index=True)\n else:\n continue\n return df\n\n\n# In[13]:\n\n\ndf = generate_current_page_dataframe(text)\n\n\ndef extract_data_from_one_page(page):\n raw_text = extract_single_page_text(page)\n # print(\"raw_text\", raw_text)\n raw_characters = extract_characters(raw_text)\n # print(\"raw_characters\", raw_characters)\n sorted_rows = arrange_text(raw_characters)\n # print(\"sorted_rows\", sorted_rows)\n text = arrange_and_extract_text(raw_characters)\n df = generate_current_page_dataframe(text)\n return df\n\ndef extract_data_from_all_pages(pages):\n columns = ['Date sold or disposed', 'Quantity', 'Proceeds', 'Date acquired', 'Cost or other basis', 'Wash sale loss disallowed (W)', 'Code', 'Gain or loss(-)', 'Additional information']\n df_total = pd.DataFrame(columns=columns)\n for p in pages:\n df_curr = extract_data_from_one_page(p)\n df_total = df_total.append(df_curr)\n return df_total\n\n\n\n","sub_path":"extract_1099_washsale_data.py","file_name":"extract_1099_washsale_data.py","file_ext":"py","file_size_in_byte":6591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"36466327","text":"max_size = 0\narray = [[1,0,0,0,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,0],[1,0,0,0,0],[1,0,0,0,0]]\nmax_row , max_col = len(array) , len(array[0])\nvisited = [[0 for i in range(max_col)] for j in range(max_row)]\n\ndef array_value(A,row,column):\n global max_row\n global max_col\n if row<0 or column<0 or row>=max_row or column>=max_col:\n return 0\n else:\n return A[row][column]\n\ndef find_max_size(A,row,column,current_size):\n global max_size\n current_size += 1\n if(current_size>max_size):\n max_size = current_size\n visited[row][column] = 1\n adjacent = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]\n for i in range(len(adjacent)):\n new_row = row + adjacent[i][0]\n new_column = column + adjacent[i][1]\n if array_value(A,new_row,new_column) == 1 and visited[new_row][new_column] == 0:\n find_max_size(A,new_row,new_column,current_size)\n visited[row][column] = 0\n\ndef traverse(A):\n global max_size\n global max_row\n global max_col\n for row in range(max_row):\n for column in range(max_col):\n if(A[row][column]==1):\n find_max_size(A,row,column,0)\n return max_size\n\nprint(traverse(array))","sub_path":"PyCharm/Tough/connected1.py","file_name":"connected1.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"373603671","text":"# Copyright 2020 QuantumBlack Visual Analytics Limited\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# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\n# NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS\n# BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# The QuantumBlack Visual Analytics Limited (\"QuantumBlack\") name and logo\n# (either separately or in combination, \"QuantumBlack Trademarks\") are\n# trademarks of QuantumBlack. The License does not grant you any right or\n# license to the QuantumBlack Trademarks. You may not use the QuantumBlack\n# Trademarks or any confusingly similar mark as a trademark for your product,\n# or use the QuantumBlack Trademarks in any other manner that might cause\n# confusion in the marketplace, including but not limited to in advertising,\n# on websites, or on software.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Behave step definitions for the cli_scenarios feature.\"\"\"\n\nimport json\nfrom time import sleep, time\n\nimport behave\nimport requests\nimport yaml\nfrom behave import given, then, when\nfrom IPython.testing.globalipapp import get_ipython\n\nfrom features.steps.sh_run import ChildTerminatingPopen, run\nfrom features.steps.util import download_url\nfrom kedro_viz.utils import wait_for\n\nOK_EXIT_CODE = 0\n\n\ndef _create_config_file(context, include_example):\n context.config_file = context.temp_dir / \"config.yml\"\n context.project_name = \"project-dummy\"\n root_project_dir = context.temp_dir / context.project_name\n context.root_project_dir = root_project_dir\n config = {\n \"project_name\": context.project_name,\n \"repo_name\": context.project_name,\n \"output_dir\": str(context.temp_dir),\n \"python_package\": context.project_name.replace(\"-\", \"_\"),\n \"include_example\": include_example,\n }\n with context.config_file.open(\"w\") as config_file:\n yaml.dump(config, config_file, default_flow_style=False)\n\n\n@given(\"I have prepared a config file with example code\")\ndef create_config_file_with_example(context):\n \"\"\"Behave step to create a temporary config file\n (given the existing temp directory) and store it in the context.\n \"\"\"\n _create_config_file(context, include_example=True)\n\n\n@given(\"I have run a non-interactive kedro new\")\ndef create_project_from_config_file(context):\n \"\"\"Behave step to run kedro new given the config I previously created.\n \"\"\"\n res = run(\n [context.kedro, \"new\", \"-c\", str(context.config_file)],\n env=context.env,\n cwd=str(context.temp_dir),\n )\n assert res.returncode == OK_EXIT_CODE\n\n\n@given(\"I have run a non-interactive kedro new with {starter} starter\")\ndef create_project_with_starter(context, starter):\n \"\"\"Behave step to run kedro new given the config I previously created.\n \"\"\"\n res = run(\n [\n context.kedro,\n \"new\",\n \"--starter\",\n str(starter),\n \"--config\",\n str(context.config_file),\n ],\n env=context.env,\n cwd=str(context.temp_dir),\n )\n if res.returncode != OK_EXIT_CODE:\n print(res.stdout)\n print(res.stderr)\n assert False\n assert res.returncode == OK_EXIT_CODE\n\n\n@given('I have executed the kedro command \"{command}\"')\ndef exec_kedro_target_checked(context, command):\n \"\"\"Execute Kedro command and check the status.\"\"\"\n cmd = [context.kedro] + command.split()\n\n res = run(cmd, env=context.env, cwd=str(context.root_project_dir))\n\n if res.returncode != OK_EXIT_CODE:\n print(res.stdout)\n print(res.stderr)\n assert False\n\n # Wait for subprocess completion since on Windows it takes some time\n # to install dependencies in a separate console\n if \"install\" in cmd:\n max_duration = 5 * 60 # 5 minutes\n end_by = time() + max_duration\n\n while time() < end_by:\n result = run([context.pip, \"show\", \"pandas\"])\n if result.returncode == OK_EXIT_CODE:\n # package found\n return\n sleep(1.0)\n\n\n@given('I have installed kedro version \"{version}\"')\ndef install_kedro(context, version):\n \"\"\"Execute Kedro command and check the status.\"\"\"\n if version == \"latest\":\n cmd = [context.pip, \"install\", \"-U\", \"kedro\"]\n else:\n cmd = [context.pip, \"install\", \"kedro=={}\".format(version)]\n res = run(cmd, env=context.env)\n\n if res.returncode != OK_EXIT_CODE:\n print(res.stdout)\n print(res.stderr)\n assert False\n\n\n@when('I execute the kedro jupyter command \"{command}\"')\ndef exec_notebook(context, command):\n \"\"\"Execute Kedro Jupyter target.\"\"\"\n split_command = command.split()\n cmd = [context.kedro, \"jupyter\"] + split_command\n\n # Jupyter notebook forks a child process from a parent process, and\n # only kills the parent process when it is terminated\n context.result = ChildTerminatingPopen(\n cmd, env=context.env, cwd=str(context.root_project_dir)\n )\n\n\n@when('I execute the kedro viz command \"{command}\"')\ndef exec_viz_command(context, command):\n \"\"\"Execute Kedro viz command \"\"\"\n split_command = command.split()\n make_cmd = [context.kedro] + split_command\n\n context.result = ChildTerminatingPopen(\n make_cmd + [\"--no-browser\"], env=context.env, cwd=str(context.root_project_dir)\n )\n\n\n@when('I execute line magic \"{command}\"')\ndef exec_line_magic(context, command):\n \"\"\"Execute line magic function \"\"\"\n ip = get_ipython()\n ip.magic(command)\n\n\n@then(\"kedro-viz should start successfully\")\ndef check_kedroviz_up(context):\n \"\"\"Check that kedro-viz is up and responding to requests\"\"\"\n\n wait_for(\n _check_kedroviz_running,\n expected_result=None,\n print_error=False,\n context=context,\n timeout_=30,\n )\n\n\ndef _check_kedroviz_running(context):\n \"\"\"\n Check that a service is running and responding appropriately\n\n Args:\n context (behave.runner.Context): Test context\n \"\"\"\n data_json = json.loads(download_url(\"http://localhost:4141/api/main\"))\n try:\n assert context.result.poll() is None\n assert (\n \"example_iris_data\"\n == sorted(data_json[\"nodes\"], key=lambda i: i[\"full_name\"])[0][\"full_name\"]\n )\n finally:\n context.result.terminate()\n\n\ndef _check_service_up(context: behave.runner.Context, url: str, string: str):\n \"\"\"Check that a service is running and responding appropriately.\n\n Args:\n context: Test context.\n url: Url that is to be read.\n string: The string to be checked.\n\n \"\"\"\n response = requests.get(url, timeout=1.0)\n response.raise_for_status()\n\n data = response.text\n assert string in data\n assert context.result.poll() is None\n","sub_path":"package/features/steps/cli_steps.py","file_name":"cli_steps.py","file_ext":"py","file_size_in_byte":7302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"314469367","text":"# encoding=utf-8\n# Created by xupingmao on 2016/12\nimport profile\nimport math\nimport re\n\nfrom handlers.base import *\nimport xauth\nimport xutils\nimport xconfig\nimport xtables\nimport xtemplate\nimport xmanager\nfrom web import HTTPError\nfrom . import dao\n\nconfig = xconfig\n\ndef date2str(d):\n ct = time.gmtime(d / 1000)\n return time.strftime('%Y-%m-%d %H:%M:%S', ct)\n\n\ndef try_decode(bytes):\n try:\n return bytes.decode(\"utf-8\")\n except:\n return bytes.decode(\"gbk\")\n\nclass handler:\n\n # @xutils.profile()\n def GET(self):\n id = xutils.get_argument(\"id\", \"\")\n name = xutils.get_argument(\"name\", \"\")\n page = xutils.get_argument(\"page\", 1, type=int)\n if id == \"\" and name == \"\":\n raise HTTPError(504)\n if id != \"\":\n id = int(id)\n file = dao.get_by_id(id)\n elif name is not None:\n file = dao.get_by_name(name)\n if file is None:\n raise web.notfound()\n \n if not file.is_public and xauth.get_current_user() is None:\n return xauth.redirect_to_login()\n\n db = xtables.get_file_table()\n pathlist = dao.get_pathlist(db, file)\n user_name = xauth.get_current_name()\n can_edit = (file.creator == user_name) or (user_name == \"admin\")\n\n role = xauth.get_current_role()\n if role != \"admin\" and file.groups != '*' and file.groups != role:\n raise web.seeother(\"/unauthorized\")\n\n files = []\n amount = 0\n if file.type == \"group\":\n amount = db.count(where=\"parent_id=%s AND is_deleted=0\" % file.id)\n files = db.select(where=dict(parent_id=file.id, is_deleted=0), \n order=\"priority DESC, sctime DESC\", \n limit=10, \n offset=(page-1)*10)\n elif file.type == \"post\":\n file.content = file.content.replace(u'\\xad', '\\n')\n file.content = file.content.replace(\"\\n\", \"
    \")\n dao.visit_by_id(id)\n else:\n dao.visit_by_id(id)\n return xtemplate.render(\"file/view.html\",\n file=file, \n content = file.get_content(), \n date2str=date2str,\n can_edit = can_edit,\n pathlist = pathlist,\n page_max = math.ceil(amount/10),\n page = page,\n page_url = \"/file/view?id=%s&page=\" % id,\n files = files)\n\n def download_request(self):\n id = self.get_argument(\"id\")\n file = dao.get_by_id(id)\n content = file.get_content()\n if content.startswith(\"```CSV\"):\n content = content[7:-3] # remove \\n\n web.ctx.headers.append((\"Content-Type\", 'application/octet-stream'))\n web.ctx.headers.append((\"Content-Disposition\", \"attachment; filename=%s.csv\" % quote(file.name)))\n return content\n\nclass MarkdownEdit(BaseHandler):\n\n @xauth.login_required()\n def default_request(self):\n id = xutils.get_argument(\"id\", \"\")\n name = xutils.get_argument(\"name\", \"\")\n if id == \"\" and name == \"\":\n raise HTTPError(504)\n if id != \"\":\n id = int(id)\n dao.visit_by_id(id)\n file = dao.get_by_id(id)\n elif name is not None:\n file = dao.get_by_name(name)\n if file is None:\n raise web.notfound()\n download_csv = file.related != None and \"CODE-CSV\" in file.related\n db = xtables.get_file_table()\n self.render(\"file/markdown_edit.html\", file=file, \n pathlist = dao.get_pathlist(db, file),\n content = file.get_content(), \n date2str=date2str,\n download_csv = download_csv, \n children = [])\n\ndef sqlite_escape(text):\n if text is None:\n return \"NULL\"\n if not (isinstance(text, str)):\n return repr(text)\n # text = text.replace('\\\\', '\\\\')\n text = text.replace(\"'\", \"''\")\n return \"'\" + text + \"'\"\n\ndef result(success = True, msg=None):\n return {\"success\": success, \"result\": None, \"msg\": msg}\n\ndef is_img(filename):\n name, ext = os.path.splitext(filename)\n return ext.lower() in (\".gif\", \".png\", \".jpg\", \".jpeg\", \".bmp\")\n\ndef get_link(filename, webpath):\n if is_img(filename):\n return \"![%s](%s)\" % (filename, webpath)\n return \"[%s](%s)\" % (filename, webpath)\n\nclass UpdateHandler(BaseHandler):\n\n @xauth.login_required()\n def default_request(self):\n is_public = xutils.get_argument(\"public\", \"\")\n id = xutils.get_argument(\"id\", type=int)\n content = xutils.get_argument(\"content\")\n version = xutils.get_argument(\"version\", type=int)\n file_type = xutils.get_argument(\"type\")\n name = xutils.get_argument(\"name\", \"\")\n upload_file = xutils.get_argument(\"file\", {})\n\n file = dao.get_by_id(id)\n assert file is not None\n\n # 理论上一个人是不能改另一个用户的存档,但是可以拷贝成自己的\n # 所以权限只能是创建者而不是修改者\n # groups = file.creator\n # if is_public == \"on\":\n # groups = \"*\"\n update_kw = dict(content=content, \n type=file_type, \n size=len(content));\n\n if name != \"\" and name != None:\n update_kw[\"name\"] = name\n\n # 处理文件上传,不再处理文件,由JS提交\n # if hasattr(upload_file, \"filename\") and upload_file.filename != \"\":\n # filename = upload_file.filename\n # filename = filename.replace(\"\\\\\", \"/\")\n # filename = os.path.basename(filename)\n # filepath, webpath = get_upload_file_path(xutils.quote(filename))\n # with open(filepath, \"wb\") as fout:\n # for chunk in upload_file.file:\n # fout.write(chunk)\n # link = get_link(filename, webpath)\n # update_kw[\"content\"] = content + \"\\n\" + link\n\n rowcount = dao.update(where = dict(id=id, version=version), **update_kw)\n if rowcount > 0:\n # raise web.seeother(\"/file/markdown/edit?id=\" + str(id))\n if upload_file != None and upload_file.filename != \"\":\n raise web.seeother(\"/file/markdown/edit?id=\" + str(id))\n else:\n raise web.seeother(\"/file/view?id=\" + str(id))\n else:\n # 传递旧的content\n cur_version = file.version\n file.content = content\n file.version = version\n return self.render(\"file/view.html\", file=file, \n content = content, \n date2str=date2str,\n children = [],\n error = \"更新失败, version冲突,当前version={},最新version={}\".format(version, cur_version))\n\n def rename_request(self):\n fileId = self.get_argument(\"fileId\")\n newName = self.get_argument(\"newName\")\n record = dao.get_by_name(newName)\n\n fileId = int(fileId)\n old_record = dao.get_by_id(fileId)\n\n if old_record is None:\n return result(False, \"file with ID %s do not exists\" % fileId)\n elif record is not None:\n return result(False, \"file %s already exists!\" % repr(newName))\n else:\n # 修改名称不用乐观锁\n rowcount = dao.update(where= dict(id = fileId), name = newName)\n return result(rowcount > 0)\n\n def del_request(self):\n id = int(self.get_argument(\"id\"))\n dao.update(where=dict(id=id), is_deleted=1)\n raise web.seeother(\"/file/recent_edit\")\n\nclass Upvote:\n\n @xauth.login_required()\n def GET(self, id):\n id = int(id)\n db = xtables.get_file_table()\n file = db.select_one(where=dict(id=int(id)))\n db.update(priority=1, where=dict(id=id))\n raise web.seeother(\"/file/view?id=%s\" % id)\n\nclass Downvote:\n @xauth.login_required()\n def GET(self, id):\n id = int(id)\n db = xtables.get_file_table()\n file = db.select_one(where=dict(id=int(id)))\n db.update(priority=0, where=dict(id=id))\n raise web.seeother(\"/file/view?id=%s\" % id)\n\nclass RenameHandler:\n\n @xauth.login_required()\n def POST(self):\n id = xutils.get_argument(\"id\")\n name = xutils.get_argument(\"name\")\n if name == \"\" or name is None:\n return dict(code=\"fail\", message=\"名称为空\")\n db = xtables.get_file_table()\n file = db.select_one(where=dict(name=name))\n if file is not None:\n return dict(code=\"fail\", message=\"%r已存在\" % name)\n db.update(where=dict(id=id), name=name)\n return dict(code=\"success\")\n\n def GET(self):\n return self.POST()\n\nclass AutosaveHandler:\n\n @xauth.login_required()\n def POST(self):\n content = xutils.get_argument(\"content\", \"\")\n id = xutils.get_argument(\"id\", \"0\", type=int)\n name = xauth.get_current_name()\n db = xtables.get_file_table()\n where = None\n if xauth.is_admin():\n where=dict(id=id)\n else:\n where=dict(id=id, creator=name)\n rowcount = db.update(content=content, size=len(content), smtime=xutils.format_datetime(), \n where=where)\n if rowcount > 0:\n return dict(code=\"success\")\n else:\n return dict(code=\"fail\")\n\nclass MarkHandler:\n\n def GET(self):\n id = xutils.get_argument(\"id\")\n db = xtables.get_file_table()\n db.update(is_marked=1, where=dict(id=id))\n raise web.seeother(\"/file/view?id=%s\"%id)\n\nclass UnmarkHandler:\n def GET(self):\n id = xutils.get_argument(\"id\")\n db = xtables.get_file_table()\n db.update(is_marked=0, where=dict(id=id))\n raise web.seeother(\"/file/view?id=%s\"%id)\n\nclass MemoEditHandler:\n\n def GET(self):\n id = xutils.get_argument(\"id\", type=int)\n sched = xtables.get_schedule_table().select_one(where=dict(id=id))\n return xtemplate.render(\"file/memo_edit.html\", item = sched)\n \nclass MemoSaveHandler:\n \n @xauth.login_required(\"admin\")\n def POST(self):\n id = xutils.get_argument(\"id\")\n name = xutils.get_argument(\"name\")\n url = xutils.get_argument(\"url\")\n tm_wday = xutils.get_argument(\"tm_wday\")\n tm_hour = xutils.get_argument(\"tm_hour\")\n tm_min = xutils.get_argument(\"tm_min\")\n message = xutils.get_argument(\"message\")\n sound_value = xutils.get_argument(\"sound\")\n webpage_value = xutils.get_argument(\"webpage\")\n sound = 1 if sound_value == \"on\" else 0\n webpage = 1 if webpage_value == \"on\" else 0\n\n db = xtables.get_schedule_table()\n if id == \"\" or id is None:\n db.insert(name=name, url=url, mtime=xutils.format_datetime(), \n ctime=xutils.format_datetime(),\n tm_wday = tm_wday,\n tm_hour = tm_hour,\n tm_min = tm_min,\n message = message,\n sound = sound,\n webpage = webpage)\n else:\n id = int(id)\n db.update(where=dict(id=id), name=name, url=url, \n mtime=xutils.format_datetime(),\n tm_wday = tm_wday,\n tm_hour = tm_hour,\n tm_min = tm_min,\n message = message,\n sound = sound,\n webpage = webpage)\n xmanager.load_tasks()\n raise web.seeother(\"/file/group/memo\")\n\nclass MemoRemoveHandler:\n\n @xauth.login_required(\"admin\")\n def GET(self):\n id = xutils.get_argument(\"id\", type=int)\n db = xtables.get_schedule_table()\n db.delete(where=dict(id=id))\n xmanager.load_tasks()\n raise web.seeother(\"/file/group/memo\")\n \n\nxurls = (\n r\"/file/edit\", handler, \n r\"/file/rename\", RenameHandler,\n r\"/file/markdown\", handler,\n r\"/file/memo/edit\", MemoEditHandler,\n r\"/file/memo/save\", MemoSaveHandler,\n r\"/file/memo/remove\", MemoRemoveHandler,\n r\"/file/view\", handler,\n r\"/file/markdown/edit\", MarkdownEdit,\n r\"/file/update\", UpdateHandler,\n r\"/file/autosave\", AutosaveHandler,\n r\"/file/(\\d+)/upvote\", Upvote,\n r\"/file/(\\d+)/downvote\", Downvote,\n r\"/file/mark\", MarkHandler,\n r\"/file/unmark\", UnmarkHandler,\n)\n\n","sub_path":"handlers/file/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":12266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"177852075","text":"# 下拉框.py\nimport tkinter\nfrom tkinter import ttk\n\nroot = tkinter.Tk()\nxiala = tkinter.StringVar()\nxialaselect = ttk.Combobox(root, width=12, \n textvariable=xiala)\nxialaselect['values'] = ('老师', '学生')\nxialaselect.pack()\nxialaselect.current(0)\nroot.mainloop()","sub_path":"tkinter/day03/code/11_combobox.py","file_name":"11_combobox.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"561322685","text":"#coding utf-8\n\n#bytes ---> int\ndata = b'\\x00\\x124V\\x00x\\x90\\xab\\x00\\xcd\\xef\\x01\\x00#\\x004'\nx = int.from_bytes(data,'big')\nprint(x)\n#int ---> bytes\nprint(x.to_bytes(16,'big'))\n#too big can't convert find the right length first\nx = 523**23\nnbytes,rem = divmod(x.bit_length(),8)\nif rem:\n nbytes +=1\nprint(x.to_bytes(nbytes,'big'))\n\n","sub_path":"Python/moveit/cookbook/p305_pack_unpack_large_int_form_bytes.py","file_name":"p305_pack_unpack_large_int_form_bytes.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"437311129","text":"#!/usr/bin/env python3\n\"\"\"Main script for gaze direction inference from webcam feed.\"\"\"\nimport argparse\nimport os\nimport queue\nimport threading\nimport time\n\nimport coloredlogs\nimport cv2 as cv\nimport numpy as np\nimport tensorflow as tf\n\nfrom sklearn.externals import joblib\n\nfrom datasources import Video, Webcam, FramesSource\nfrom models import ELG\nimport util.gaze\nfrom util.camera import Camera\n\nif __name__ == '__main__':\n\n # Set global log level\n parser = argparse.ArgumentParser(description='Demonstration of landmarks localization.')\n parser.add_argument('-v', type=str, help='logging level', default='info',\n choices=['debug', 'info', 'warning', 'error', 'critical'])\n parser.add_argument('--from_video', type=str, help='Use this video path instead of webcam')\n parser.add_argument('--record_video', type=str, help='Output path of video of demonstration.')\n parser.add_argument('--fullscreen', action='store_true')\n parser.add_argument('--headless', action='store_true')\n\n parser.add_argument('--fps', type=int, default=60, help='Desired sampling rate of webcam')\n parser.add_argument('--camera_id', type=int, default=0, help='ID of webcam to use')\n parser.add_argument('--load_model', type=str, help='Load gaze regression model from this')\n parser.add_argument('--corner_dist', type=float, default=None, help='Distance between outer eye corners')\n parser.add_argument('--show_gaze_point', action='store_true')\n\n args = parser.parse_args()\n coloredlogs.install(\n datefmt='%d/%m %H:%M',\n fmt='%(asctime)s %(levelname)s %(message)s',\n level=args.v.upper(),\n )\n\n # Check if GPU is available\n from tensorflow.python.client import device_lib\n session_config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True))\n gpu_available = False\n try:\n gpus = [d for d in device_lib.list_local_devices(config=session_config)\n if d.device_type == 'GPU']\n gpu_available = len(gpus) > 0\n except:\n pass\n\n # Initialize Tensorflow session\n tf.logging.set_verbosity(tf.logging.INFO)\n with tf.Session(config=session_config) as session:\n\n # Declare some parameters\n batch_size = 2\n\n FramesSource._outer_eye_corner_distance = args.corner_dist\n\n # Define webcam stream data source\n # Change data_format='NHWC' if not using CUDA\n if args.from_video:\n assert os.path.isfile(args.from_video)\n data_source = Video(args.from_video,\n tensorflow_session=session, batch_size=batch_size,\n data_format='NCHW' if gpu_available else 'NHWC',\n eye_image_shape=(108, 180))\n else:\n data_source = Webcam(tensorflow_session=session, batch_size=batch_size,\n camera_id=args.camera_id, fps=args.fps,\n data_format='NCHW' if gpu_available else 'NHWC',\n camera=Camera.load('camera_params.txt'),\n eye_image_shape=(36, 60))\n\n # Define model\n if args.from_video:\n model = ELG(\n session, train_data={'videostream': data_source},\n first_layer_stride=3,\n num_modules=3,\n num_feature_maps=64,\n learning_schedule=[\n {\n 'loss_terms_to_optimize': {'dummy': ['hourglass', 'radius']},\n },\n ],\n )\n else:\n model = ELG(\n session, train_data={'videostream': data_source},\n first_layer_stride=1,\n num_modules=2,\n num_feature_maps=32,\n learning_schedule=[\n {\n 'loss_terms_to_optimize': {'dummy': ['hourglass', 'radius']},\n },\n ],\n )\n\n if args.load_model is not None:\n gaze_regressor = joblib.load(args.load_model)\n else:\n gaze_regressor = None\n\n if os.path.isfile('monitor.txt'):\n monitor = np.loadtxt('monitor.txt')\n else:\n monitor = [\n np.float32([ 250, 35, 0]), # m0\n np.float32([-532, 0, 0]), # mu\n np.float32([ 0, 304, 0]), # mv\n ]\n\n #screen_size = np.int32([1920, 1080])\n\n # Record output frames to file if requested\n if args.record_video:\n video_out = None\n video_out_queue = queue.Queue()\n video_out_should_stop = False\n video_out_done = threading.Condition()\n\n def _record_frame():\n global video_out\n last_frame_time = None\n out_fps = 30\n out_frame_interval = 1.0 / out_fps\n while not video_out_should_stop:\n frame_index = video_out_queue.get()\n if frame_index is None:\n break\n assert frame_index in data_source._frames\n frame = data_source._frames[frame_index]['bgr']\n h, w, _ = frame.shape\n if video_out is None:\n video_out = cv.VideoWriter(\n args.record_video, cv.VideoWriter_fourcc(*'H264'),\n out_fps, (w, h),\n )\n now_time = time.time()\n if last_frame_time is not None:\n time_diff = now_time - last_frame_time\n while time_diff > 0.0:\n video_out.write(frame)\n time_diff -= out_frame_interval\n last_frame_time = now_time\n video_out.release()\n with video_out_done:\n video_out_done.notify_all()\n record_thread = threading.Thread(target=_record_frame, name='record')\n record_thread.daemon = True\n record_thread.start()\n\n # Begin visualization thread\n inferred_stuff_queue = queue.Queue()\n\n def _visualize_output():\n last_frame_index = 0\n last_frame_time = time.time()\n fps_history = []\n all_gaze_histories = []\n all_gaze_point_histories = []\n\n if args.fullscreen:\n cv.namedWindow('vis', cv.WND_PROP_FULLSCREEN)\n cv.setWindowProperty('vis', cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)\n\n #gaze_overlay = np.zeros((screen_size[1], screen_size[0], 3), dtype=np.uint8)\n #screen_buffer = np.zeros((screen_size[1], screen_size[0], 3), dtype=np.uint8)\n\n while True:\n # If no output to visualize, show unannotated frame\n if inferred_stuff_queue.empty():\n next_frame_index = last_frame_index + 1\n if next_frame_index in data_source._frames:\n next_frame = data_source._frames[next_frame_index]\n if 'faces' in next_frame and len(next_frame['faces']) == 0:\n if not args.headless:\n cv.imshow('vis', next_frame['bgr'])\n if args.record_video:\n video_out_queue.put_nowait(next_frame_index)\n last_frame_index = next_frame_index\n if cv.waitKey(1) & 0xFF == ord('q'):\n return\n continue\n\n # Get output from neural network and visualize\n output = inferred_stuff_queue.get()\n bgr = None\n for j in range(batch_size):\n frame_index = output['frame_index'][j]\n if frame_index not in data_source._frames:\n continue\n frame = data_source._frames[frame_index]\n\n # Decide which landmarks are usable\n heatmaps_amax = np.amax(output['heatmaps'][j, :].reshape(-1, 18), axis=0)\n can_use_eye = np.all(heatmaps_amax > 0.7)\n can_use_eyelid = np.all(heatmaps_amax[0:8] > 0.75)\n can_use_iris = np.all(heatmaps_amax[8:16] > 0.8)\n\n start_time = time.time()\n eye_index = output['eye_index'][j]\n face_index = int(eye_index / 2)\n bgr = frame['bgr']\n eye = frame['eyes'][eye_index]\n eye_image = eye['image']\n eye_side = eye['side']\n eye_landmarks = output['landmarks'][j, :]\n eye_radius = output['radius'][j][0]\n eye_position = eye['position']\n camera = frame['camera']\n headpose = frame['headpose'][face_index]\n frame_landmarks = (frame['smoothed_landmarks']\n if 'smoothed_landmarks' in frame\n else frame['landmarks'])\n\n\n if eye_index == 0:\n print()\n #screen_buffer[:] = 0\n for f, face in enumerate(frame['faces']):\n for landmark in frame_landmarks[f][:4]:\n cv.drawMarker(bgr, tuple(np.round(landmark).astype(np.int32)),\n color=(0, 0, 255), markerType=cv.MARKER_STAR,\n markerSize=2, thickness=1, line_type=cv.LINE_AA)\n if 'headpose' in frame:\n tvec = frame['headpose'][f]['tvec']\n rvec = frame['headpose'][f]['rvec']\n points, _ = cv.projectPoints(\n (np.mgrid[0:2,0:2,0:2].T.reshape(-1, 3)*200-100).astype(np.float32),\n rvec, tvec, camera.matrix, camera.distortion)\n for point in range(8):\n for dim in (1,2,4):\n if (point & dim) == 0:\n cv.line(bgr,\n tuple(*points[point]),\n tuple(*points[point+dim]),\n color=(255,255,255), thickness=1, lineType=cv.LINE_AA)\n cv.rectangle(\n bgr, tuple(np.round(face[:2]).astype(np.int32)),\n tuple(np.round(np.add(face[:2], face[2:])).astype(np.int32)),\n color=(0, 255, 255), thickness=1, lineType=cv.LINE_AA,\n )\n\n #eye_pos_screen = cv.projectPoints(np.array([eye_position]),\n # np.zeros(3), np.zeros(3), camera.matrix,\n # camera.distortion)[0].ravel()\n #cv.drawMarker(bgr, tuple(np.round(eye_pos_screen).astype(np.int32)),\n # color=(255,0,255))\n\n\n if gaze_regressor is not None:\n gaze = gaze_regressor.predict(\n (eye_landmarks/(eye_image.shape[1], eye_image.shape[0]))\n .reshape(1, -1)).reshape(-1)\n theta, phi = gaze\n gaze = np.array([np.cos(theta)*np.sin(phi), np.sin(theta)])\n else:\n gaze = None\n\n if eye_side == 'left':\n eye_landmarks[:, 0] = eye_image.shape[1] - eye_landmarks[:, 0]\n eye_image = np.fliplr(eye_image)\n if gaze is not None:\n gaze[0] = -gaze[0]\n\n # Embed eye image and annotate for picture-in-picture\n eye_upscale = 2\n eye_image_raw = cv.cvtColor(cv.equalizeHist(eye_image), cv.COLOR_GRAY2BGR)\n eye_image_raw = cv.resize(eye_image_raw, (0, 0), fx=eye_upscale, fy=eye_upscale)\n eye_image_annotated = np.copy(eye_image_raw)\n if can_use_eyelid:\n cv.polylines(\n eye_image_annotated,\n [np.round(eye_upscale*eye_landmarks[0:8]).astype(np.int32)\n .reshape(-1, 1, 2)],\n isClosed=True, color=(255, 255, 0), thickness=1, lineType=cv.LINE_AA,\n )\n if can_use_iris:\n cv.polylines(\n eye_image_annotated,\n [np.round(eye_upscale*eye_landmarks[8:16]).astype(np.int32)\n .reshape(-1, 1, 2)],\n isClosed=True, color=(0, 255, 255), thickness=1, lineType=cv.LINE_AA,\n )\n cv.drawMarker(\n eye_image_annotated,\n tuple(np.round(eye_upscale*eye_landmarks[16, :]).astype(np.int32)),\n color=(0, 255, 255), markerType=cv.MARKER_CROSS, markerSize=4,\n thickness=1, line_type=cv.LINE_AA,\n )\n eh, ew, _ = eye_image_raw.shape\n v0 = face_index * 2 * eh\n v1 = v0 + eh\n v2 = v1 + eh\n u0 = 0 if eye_side == 'left' else ew\n u1 = u0 + ew\n bgr[v0:v1, u0:u1] = eye_image_raw\n bgr[v1:v2, u0:u1] = eye_image_annotated\n\n\n inv_landmarks_transform = eye['inv_landmarks_transform_mat']\n if gaze is not None:\n scale = np.linalg.norm(inv_landmarks_transform[:2,:2], axis=0)\n gaze = (inv_landmarks_transform[:2,:2] / scale).dot(gaze)\n gaze = np.float32([gaze[0,0], gaze[0,1]]) # wtf\n\n # Transform predictions\n eye_landmarks = np.concatenate([eye_landmarks,\n [[eye_landmarks[-1, 0] + eye_radius,\n eye_landmarks[-1, 1]]]])\n eye_landmarks = np.asmatrix(np.pad(eye_landmarks, ((0, 0), (0, 1)),\n 'constant', constant_values=1.0))\n eye_landmarks = (eye_landmarks * inv_landmarks_transform.T)[:, :2]\n eye_landmarks = np.asarray(eye_landmarks)\n eyelid_landmarks = eye_landmarks[0:8, :]\n iris_landmarks = eye_landmarks[8:16, :]\n iris_centre = eye_landmarks[16, :]\n eyeball_centre = eye_landmarks[17, :]\n eyeball_radius = np.linalg.norm(eye_landmarks[18, :] -\n eye_landmarks[17, :])\n\n\n # Smooth and visualize gaze direction\n num_total_eyes_in_frame = len(frame['eyes'])\n if len(all_gaze_histories) != num_total_eyes_in_frame:\n all_gaze_histories = [list() for _ in range(num_total_eyes_in_frame)]\n all_gaze_point_histories = [list() for _ in range(num_total_eyes_in_frame)]\n\n gaze_history = all_gaze_histories[eye_index]\n gaze_point_history = all_gaze_point_histories[eye_index]\n\n if can_use_eye:\n # Visualize landmarks\n cv.drawMarker( # Eyeball centre\n bgr, tuple(np.round(eyeball_centre).astype(np.int32)),\n color=(0, 255, 0), markerType=cv.MARKER_CROSS, markerSize=4,\n thickness=1, line_type=cv.LINE_AA,\n )\n # cv.circle( # Eyeball outline\n # bgr, tuple(np.round(eyeball_centre).astype(np.int32)),\n # int(np.round(eyeball_radius)), color=(0, 255, 0),\n # thickness=1, lineType=cv.LINE_AA,\n # )\n\n # Draw \"gaze\"\n # from models.hg_gaze import estimate_gaze_from_landmarks\n # current_gaze = estimate_gaze_from_landmarks(\n # iris_landmarks, iris_centre, eyeball_centre, eyeball_radius)\n if gaze_regressor is None:\n i_x0, i_y0 = iris_centre\n e_x0, e_y0 = eyeball_centre\n theta = -np.arcsin(np.clip((i_y0 - e_y0) / eyeball_radius, -1.0, 1.0))\n phi = np.arcsin(np.clip((i_x0 - e_x0) / (eyeball_radius * -np.cos(theta)),\n -1.0, 1.0))\n else:\n theta = np.arcsin(gaze[1])\n phi = np.arcsin(gaze[0] / np.cos(theta))\n\n current_gaze = np.array([theta, phi])\n\n gaze_history.append(current_gaze)\n\n gaze_history_max_len = 3\n if len(gaze_history) > gaze_history_max_len:\n gaze_history = gaze_history[-gaze_history_max_len:]\n\n screen_size = [bgr.shape[1], bgr.shape[0]]\n\n current_gaze_point = screen_size * util.gaze.intersect_gaze(eye_position, np.mean(gaze_history, axis=0), *monitor)\n gaze_point_history.append(current_gaze_point)\n\n gaze_point_history_max_len = 3\n if len(gaze_point_history) > gaze_point_history_max_len:\n gaze_point_history = gaze_point_history[-gaze_point_history_max_len:]\n\n if args.show_gaze_point and eye_index % 2 == 1:\n other_gaze_history = all_gaze_histories[eye_index-1]\n other_gaze_point_history = all_gaze_point_histories[eye_index-1]\n smoothed_gaze_point = np.mean([*gaze_point_history, *other_gaze_point_history], axis=0)\n\n if len(gaze_history) > 0:\n gdl = np.average( gaze_history, axis=0, weights=2**np.mgrid[:len( gaze_history)])\n else:\n gdl = [np.nan, np.nan]\n if len(other_gaze_history) > 0:\n gdr = np.average(other_gaze_history, axis=0, weights=2**np.mgrid[:len(other_gaze_history)])\n else:\n gdr = [np.nan, np.nan]\n\n smoothed_gaze_direction = np.nanmean([gdl, gdr], axis=0)\n #smoothed_gaze_direction = np.mean([*gaze_history, *other_gaze_history], axis=0)\n\n nosetip = headpose[\"tvec\"] # + cv.Rodrigues(headpose[\"rvec\"])[0].dot(np.float32([0,0,0]))\n avg_gaze_point = screen_size * util.gaze.intersect_gaze(nosetip, smoothed_gaze_direction, *monitor)\n util.gaze.draw_error_ellipse2(bgr, [avg_gaze_point])\n\n util.gaze.draw_gaze(bgr, iris_centre, np.mean(gaze_history, axis=0),\n length=120.0, thickness=1)\n #util.gaze.draw_error_ellipse2(bgr, [current_smooth_gaze_origin])\n #mean = np.mean(gaze_point_history, axis=0)\n #cov = np.cov(gaze_point_history, rowvar=False)\n #if cov.shape == (): # single entry, np messes up\n # #mean = gaze_point_history[0]\n # cov = np.zeros((2,2), dtype=np.float32)\n\n #util.gaze.draw_error_ellipse(screen_buffer,\n # mean,\n # cov)\n else:\n print(\"can't use eye!\")\n gaze_history.clear()\n\n if can_use_eyelid:\n cv.polylines(\n bgr, [np.round(eyelid_landmarks).astype(np.int32).reshape(-1, 1, 2)],\n isClosed=True, color=(255, 255, 0), thickness=1, lineType=cv.LINE_AA,\n )\n\n if can_use_iris:\n cv.polylines(\n bgr, [np.round(iris_landmarks).astype(np.int32).reshape(-1, 1, 2)],\n isClosed=True, color=(0, 255, 255), thickness=1, lineType=cv.LINE_AA,\n )\n cv.drawMarker(\n bgr, tuple(np.round(iris_centre).astype(np.int32)),\n color=(0, 255, 255), markerType=cv.MARKER_CROSS, markerSize=4,\n thickness=1, line_type=cv.LINE_AA,\n )\n\n dtime = 1e3*(time.time() - start_time)\n if 'visualization' not in frame['time']:\n frame['time']['visualization'] = dtime\n else:\n frame['time']['visualization'] += dtime\n\n def _dtime(before_id, after_id):\n return int(1e3 * (frame['time'][after_id] - frame['time'][before_id]))\n\n def _dstr(title, before_id, after_id):\n return '%s: %dms' % (title, _dtime(before_id, after_id))\n\n if eye_index == len(frame['eyes']) - 1:\n # Calculate timings\n frame['time']['after_visualization'] = time.time()\n fps = int(np.round(1.0 / (time.time() - last_frame_time)))\n fps_history.append(fps)\n if len(fps_history) > 60:\n fps_history = fps_history[-60:]\n fps_str = '%d FPS' % np.mean(fps_history)\n last_frame_time = time.time()\n fh, fw, _ = bgr.shape\n cv.putText(bgr, fps_str, org=(fw - 110, fh - 20),\n fontFace=cv.FONT_HERSHEY_DUPLEX, fontScale=0.8,\n color=(0, 0, 0), thickness=1, lineType=cv.LINE_AA)\n cv.putText(bgr, fps_str, org=(fw - 111, fh - 21),\n fontFace=cv.FONT_HERSHEY_DUPLEX, fontScale=0.79,\n color=(255, 255, 255), thickness=1, lineType=cv.LINE_AA)\n if not args.headless:\n cv.imshow('vis', bgr)\n #cv.imshow('screen', screen_buffer)\n last_frame_index = frame_index\n\n # Record frame?\n if args.record_video:\n video_out_queue.put_nowait(frame_index)\n\n # Quit?\n if cv.waitKey(1) & 0xFF == ord('q'):\n return\n\n # Print timings\n if frame_index % 60 == 0:\n latency = _dtime('before_frame_read', 'after_visualization')\n processing = _dtime('after_frame_read', 'after_visualization')\n timing_string = ', '.join([\n _dstr('read', 'before_frame_read', 'after_frame_read'),\n _dstr('preproc', 'after_frame_read', 'after_preprocessing'),\n 'infer: %dms' % int(frame['time']['inference']),\n 'vis: %dms' % int(frame['time']['visualization']),\n 'proc: %dms' % processing,\n 'latency: %dms' % latency,\n ])\n print('%08d [%s] %s' % (frame_index, fps_str, timing_string))\n\n visualize_thread = threading.Thread(target=_visualize_output, name='visualization')\n visualize_thread.daemon = True\n visualize_thread.start()\n\n # Do inference forever\n infer = model.inference_generator()\n while True:\n output = next(infer)\n for frame_index in np.unique(output['frame_index']):\n if frame_index not in data_source._frames:\n continue\n frame = data_source._frames[frame_index]\n if 'inference' in frame['time']:\n frame['time']['inference'] += output['inference_time']\n else:\n frame['time']['inference'] = output['inference_time']\n inferred_stuff_queue.put_nowait(output)\n\n if not visualize_thread.isAlive():\n break\n\n if not data_source._open:\n break\n\n # Close video recording\n if args.record_video and video_out is not None:\n video_out_should_stop = True\n video_out_queue.put_nowait(None)\n with video_out_done:\n video_out_done.wait()\n","sub_path":"src/live_demo.py","file_name":"live_demo.py","file_ext":"py","file_size_in_byte":25781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"28484997","text":"import numpy as np\nimport pandas as pd \nimport sklearn.metrics as sm\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom math import sqrt\nfrom matplotlib import pyplot as plt\n\n#Linear Regression Model\n#I have decided to code my own linear regression algorithm, as well as tested it with the scikit learn built in linear regression\n#Thinking practically the only independent variable we have in this application is the date since we will not know the opening, high, low, and volume \n#of the given stock for the future\n#However if we only use the date as an independent variable we will get very inaccurate future predictions which will not grasp the purpose of this project\n#which is to learn how different Regression Machine Learning algorithms work and how they can be implemented \n#For this reason I am going to assume that the opening price and volume of the stock at the given day are our independent variables. This is because opening\n#prices and volume are given at the opening of the stock market therefore our algorithm could predict the closing price based on these numbers for that day \n\ndef LinearReg(tdata):\n #Load the Opening Price, Volume, and Closing Price per day into a new Dataframe\n new_data = pd.DataFrame({'Open' : tdata['Open'], 'Volume' : tdata['Volume'], 'Close': tdata['Close']})\n \n #Split the Training and the Test data\n #Dont need to use the built in test_train_split because that will randomly pick points of our data but we need to use the first 70% of data for train\n X_train = pd.DataFrame({'Open': new_data['Open'][:round(len(new_data)*0.70)], 'Volume': new_data['Volume'][:round(len(new_data)*0.70)]})\n #Convert the training DataFrame to a 2D array\n X_train = np.array(X_train[['Open','Volume']])\n Y_train = np.array(new_data['Close'][:round(len(new_data)*0.70)])\n\n #Initiate the testing data, which will be the last 30% of the data \n X_test = pd.DataFrame({'Open': new_data['Open'][round(len(new_data)*0.70):len(new_data)], 'Volume': new_data['Volume'][round(len(new_data)*0.70):len(new_data)]})\n #Convert the testing DataFrame to a 2D array\n X_test = np.array(X_test[['Open','Volume']])\n Y_test = np.array(new_data['Close'][round(len(new_data)*0.70):len(new_data)])\n\n #THE FOLLOWING CODE BELOW IS THE DERIVED LINEAR REGRESSION MODEL WITHOUT SCIKIT LEARN\n #Since we are dealing with a multivariable linear regression problem, it makes most sense to deal with matrix algebra for cleanliness\n #The Linear Regression Model we are trying to solve for is as follows: Y_hat = B_not + B_1*X1 + B_2*X2, where B values are constants (ie weights)\n #while X1 and X2 refer to our independent variables which are the opening price and volume\n \n #Before we start it is important to scale the data especially since we are dealing with two highly variant variables\n scaler = MinMaxScaler(feature_range=(0,1))\n X_train = scaler.fit_transform(X_train)\n X_test = scaler.fit_transform(X_test)\n \n #To solve for the B values we need to create the matrix: X = [1 X1 X2] where X1 and X2 are column vectors of the open price and volume for the training data\n #We have to scale the values so there is no scews\n col1 = np.ones((len(X_train),1))\n col2 = []\n col3 = []\n #Use a for loop to iterate through training data and populate col2 with opening price and col3 with volume\n for i in range(len(X_train)):\n col2.append(X_train[i][0])\n col3.append(X_train[i][1])\n #Convert col2 and col3 from lists to arrays and make them a column vector\n col2 = np.array(col2)\n col3 = np.array(col3)\n col2 = col2[:, np.newaxis]\n col3 = col3[:, np.newaxis]\n \n #Combine all three columns into a matrix, the hstack function only takes in one argument\n X_matrix = np.hstack((col1, col2, col3))\n #Y_matrix will just be a column vector with the closing prices associated to each day of the training data\n Y_matrix = Y_train[:, np.newaxis]\n \n #Need to perform matrix algebra to get B values: B_vals = (X_transpose * X)^-1 * X_transpose*Y\n X_transpose = X_matrix.transpose()\n #Matrix multiplication is done with .dot() function in python since * operand would just perform element multiplication\n #firststop = (X_transpose * X)^-1, secondstop = X_transpose * Y\n firstop = np.linalg.inv(X_transpose.dot(X_matrix))\n secondop = X_transpose.dot(Y_matrix)\n B_vals = firstop.dot(secondop)\n\n #The Linear Regression model looks as follows: Y_hat = B_not + B_1*X1 + B_2*X2\n #For loop to populate the predicted closing price of the created linear regression model into the original Dataframe\n for i in range(round(len(new_data)*0.7), len(new_data)):\n new_data.at[i,'Predicted Close'] = B_vals[0] + (B_vals[1]*X_test[i-176][0]) + (B_vals[2]*X_test[i-176][1])\n\n #THE FOLLOWING CODE BELOW USES THE SCIKIT LEARN LIBRARY TO PERFORM LINEAR REGRESSION ON THE DATASET\n #Initialize the Linear Regression model from the scikit learn library\n model = LinearRegression()\n #Fit the training data into the model\n model.fit(X_train, Y_train)\n #Predict the future closing price using the testing dataset\n prediction = model.predict(X_test)\n\n #For loop to populate the predicted closing price of the linear regression model into the original Dataframe\n for i in range(round(len(new_data)*0.7), len(new_data)):\n new_data.at[i,'Predicted Close Model'] = prediction[i-176]\n\n #Plot both created and scikit learn Linear Regression model on the same plot \n plt.plot(tdata['Date'][round(len(tdata)*0.7):len(tdata)], new_data['Close'][round(len(new_data)*0.7):len(new_data)], label = 'Real Prices')\n plt.plot(tdata['Date'][round(len(tdata)*0.7):len(tdata)], new_data['Predicted Close'][round(len(new_data)*0.7):len(new_data)], label = 'Linear Regression Predicted Prices (Derived Model)')\n plt.plot(tdata['Date'][round(len(tdata)*0.7):len(tdata)], new_data['Predicted Close Model'][round(len(new_data)*0.7):len(new_data)], label = 'Linear Regression Predicted Prices (SciKit Model)')\n plt.title('Real Closing Price vs Linear Regression Model Predicted Closing Price')\n plt.xlabel('Date')\n plt.ylabel('Closing Price')\n plt.legend()\n plt.show()\n\n # Calculate the error of the model. Since both the created and the scikit model output the same value we will just use the scikit model to find accuracy\n print(\"Mean absolute error =\", round(sm.mean_absolute_error(Y_test, prediction), 2)) \n print(\"Mean squared error =\", round(sm.mean_squared_error(Y_test, prediction), 2)) \n print(\"Median absolute error =\", round(sm.median_absolute_error(Y_test, prediction), 2)) \n print(\"Explain variance score =\", round(sm.explained_variance_score(Y_test, prediction), 2)) \n print(\"R2 score =\", round(sm.r2_score(Y_test, prediction), 2))","sub_path":"Linear_Regression.py","file_name":"Linear_Regression.py","file_ext":"py","file_size_in_byte":6927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"65487889","text":"#!/usr/bin/env python3\n# -*- mode: python -*-\n# -*- coding: utf-8 -*-\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, 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\"\"\"Input/output utilities.\n\nIncludes:\n - i/o-specific constants\n - i/o-specific exceptions\n - schema validation\n - leaf value encoding and decoding\n - datum reader/writer stuff (?)\n\nAlso includes a generic representation for data, which uses the\nfollowing mapping:\n - Schema records are implemented as dict.\n - Schema arrays are implemented as list.\n - Schema maps are implemented as dict.\n - Schema strings are implemented as unicode.\n - Schema bytes are implemented as str.\n - Schema ints are implemented as int.\n - Schema longs are implemented as long.\n - Schema floats are implemented as float.\n - Schema doubles are implemented as float.\n - Schema booleans are implemented as bool.\n\"\"\"\n\nimport binascii\nimport json\nimport logging\nimport struct\nimport sys\n\nfrom avro import schema\n\n\n# ------------------------------------------------------------------------------\n# Constants\n\n\nINT_MIN_VALUE = -(1 << 31)\nINT_MAX_VALUE = (1 << 31) - 1\nLONG_MIN_VALUE = -(1 << 63)\nLONG_MAX_VALUE = (1 << 63) - 1\n\nSTRUCT_INT = struct.Struct('!I') # big-endian unsigned int\nSTRUCT_LONG = struct.Struct('!Q') # big-endian unsigned long long\nSTRUCT_FLOAT = struct.Struct('!f') # big-endian float\nSTRUCT_DOUBLE = struct.Struct('!d') # big-endian double\nSTRUCT_CRC32 = struct.Struct('>I') # big-endian unsigned int\n\n\n# ------------------------------------------------------------------------------\n# Exceptions\n\n\nclass AvroTypeException(schema.AvroException):\n \"\"\"Raised when datum is not an example of schema.\"\"\"\n def __init__(self, expected_schema, datum):\n pretty_expected = json.dumps(json.loads(str(expected_schema)), indent=2)\n fail_msg = \"The datum %s is not an example of the schema %s\"\\\n % (datum, pretty_expected)\n schema.AvroException.__init__(self, fail_msg)\n\n\nclass SchemaResolutionException(schema.AvroException):\n def __init__(self, fail_msg, writer_schema=None, reader_schema=None):\n pretty_writers = json.dumps(json.loads(str(writer_schema)), indent=2)\n pretty_readers = json.dumps(json.loads(str(reader_schema)), indent=2)\n if writer_schema: fail_msg += \"\\nWriter's Schema: %s\" % pretty_writers\n if reader_schema: fail_msg += \"\\nReader's Schema: %s\" % pretty_readers\n schema.AvroException.__init__(self, fail_msg)\n\n\n# ------------------------------------------------------------------------------\n# Validate\n\n\ndef Validate(expected_schema, datum):\n \"\"\"Determines if a python datum is an instance of a schema.\n\n Args:\n expected_schema: Schema to validate against.\n datum: Datum to validate.\n Returns:\n True if the datum is an instance of the schema.\n \"\"\"\n schema_type = expected_schema.type\n if schema_type == 'null':\n return datum is None\n elif schema_type == 'boolean':\n return isinstance(datum, bool)\n elif schema_type == 'string':\n return isinstance(datum, str)\n elif schema_type == 'bytes':\n return isinstance(datum, bytes)\n elif schema_type == 'int':\n return (isinstance(datum, int)\n and (INT_MIN_VALUE <= datum <= INT_MAX_VALUE))\n elif schema_type == 'long':\n return (isinstance(datum, int)\n and (LONG_MIN_VALUE <= datum <= LONG_MAX_VALUE))\n elif schema_type in ['float', 'double']:\n return (isinstance(datum, int) or isinstance(datum, float))\n elif schema_type == 'fixed':\n return isinstance(datum, bytes) and (len(datum) == expected_schema.size)\n elif schema_type == 'enum':\n return datum in expected_schema.symbols\n elif schema_type == 'array':\n return (isinstance(datum, list)\n and all(Validate(expected_schema.items, item) for item in datum))\n elif schema_type == 'map':\n return (isinstance(datum, dict)\n and all(isinstance(key, str) for key in datum.keys())\n and all(Validate(expected_schema.values, value)\n for value in datum.values()))\n elif schema_type in ['union', 'error_union']:\n return any(Validate(union_branch, datum)\n for union_branch in expected_schema.schemas)\n elif schema_type in ['record', 'error', 'request']:\n return (isinstance(datum, dict)\n and all(Validate(field.type, datum.get(field.name))\n for field in expected_schema.fields))\n else:\n raise AvroTypeException('Unknown Avro schema type: %r' % schema_type)\n\n\n# ------------------------------------------------------------------------------\n# Decoder/Encoder\n\n\nclass BinaryDecoder(object):\n \"\"\"Read leaf values.\"\"\"\n def __init__(self, reader):\n \"\"\"\n reader is a Python object on which we can call read, seek, and tell.\n \"\"\"\n self._reader = reader\n\n @property\n def reader(self):\n \"\"\"Reports the reader used by this decoder.\"\"\"\n return self._reader\n\n def read(self, n):\n \"\"\"Read n bytes.\n\n Args:\n n: Number of bytes to read.\n Returns:\n The next n bytes from the input.\n \"\"\"\n assert (n >= 0), n\n input_bytes = self.reader.read(n)\n assert (len(input_bytes) == n), input_bytes\n return input_bytes\n\n def read_null(self):\n \"\"\"\n null is written as zero bytes\n \"\"\"\n return None\n\n def read_boolean(self):\n \"\"\"\n a boolean is written as a single byte\n whose value is either 0 (false) or 1 (true).\n \"\"\"\n return ord(self.read(1)) == 1\n\n def read_int(self):\n \"\"\"\n int and long values are written using variable-length, zig-zag coding.\n \"\"\"\n return self.read_long()\n\n def read_long(self):\n \"\"\"\n int and long values are written using variable-length, zig-zag coding.\n \"\"\"\n b = ord(self.read(1))\n n = b & 0x7F\n shift = 7\n while (b & 0x80) != 0:\n b = ord(self.read(1))\n n |= (b & 0x7F) << shift\n shift += 7\n datum = (n >> 1) ^ -(n & 1)\n return datum\n\n def read_float(self):\n \"\"\"\n A float is written as 4 bytes.\n The float is converted into a 32-bit integer using a method equivalent to\n Java's floatToIntBits and then encoded in little-endian format.\n \"\"\"\n bits = (((ord(self.read(1)) & 0xff)) |\n ((ord(self.read(1)) & 0xff) << 8) |\n ((ord(self.read(1)) & 0xff) << 16) |\n ((ord(self.read(1)) & 0xff) << 24))\n return STRUCT_FLOAT.unpack(STRUCT_INT.pack(bits))[0]\n\n def read_double(self):\n \"\"\"\n A double is written as 8 bytes.\n The double is converted into a 64-bit integer using a method equivalent to\n Java's doubleToLongBits and then encoded in little-endian format.\n \"\"\"\n bits = (((ord(self.read(1)) & 0xff)) |\n ((ord(self.read(1)) & 0xff) << 8) |\n ((ord(self.read(1)) & 0xff) << 16) |\n ((ord(self.read(1)) & 0xff) << 24) |\n ((ord(self.read(1)) & 0xff) << 32) |\n ((ord(self.read(1)) & 0xff) << 40) |\n ((ord(self.read(1)) & 0xff) << 48) |\n ((ord(self.read(1)) & 0xff) << 56))\n return STRUCT_DOUBLE.unpack(STRUCT_LONG.pack(bits))[0]\n\n def read_bytes(self):\n \"\"\"\n Bytes are encoded as a long followed by that many bytes of data.\n \"\"\"\n nbytes = self.read_long()\n assert (nbytes >= 0), nbytes\n return self.read(nbytes)\n\n def read_utf8(self):\n \"\"\"\n A string is encoded as a long followed by\n that many bytes of UTF-8 encoded character data.\n \"\"\"\n input_bytes = self.read_bytes()\n try:\n return input_bytes.decode('utf-8')\n except UnicodeDecodeError as exn:\n logging.error('Invalid UTF-8 input bytes: %r', input_bytes)\n raise exn\n\n def check_crc32(self, bytes):\n checksum = STRUCT_CRC32.unpack(self.read(4))[0];\n if binascii.crc32(bytes) & 0xffffffff != checksum:\n raise schema.AvroException(\"Checksum failure\")\n\n def skip_null(self):\n pass\n\n def skip_boolean(self):\n self.skip(1)\n\n def skip_int(self):\n self.skip_long()\n\n def skip_long(self):\n b = ord(self.read(1))\n while (b & 0x80) != 0:\n b = ord(self.read(1))\n\n def skip_float(self):\n self.skip(4)\n\n def skip_double(self):\n self.skip(8)\n\n def skip_bytes(self):\n self.skip(self.read_long())\n\n def skip_utf8(self):\n self.skip_bytes()\n\n def skip(self, n):\n self.reader.seek(self.reader.tell() + n)\n\n\n# ------------------------------------------------------------------------------\n\n\nclass BinaryEncoder(object):\n \"\"\"Write leaf values.\"\"\"\n\n def __init__(self, writer):\n \"\"\"\n writer is a Python object on which we can call write.\n \"\"\"\n self._writer = writer\n\n @property\n def writer(self):\n \"\"\"Reports the writer used by this encoder.\"\"\"\n return self._writer\n\n\n def write(self, datum):\n \"\"\"Write a sequence of bytes.\n\n Args:\n datum: Byte array, as a Python bytes.\n \"\"\"\n assert isinstance(datum, bytes), ('Expecting bytes, got %r' % datum)\n self.writer.write(datum)\n\n def WriteByte(self, byte):\n self.writer.write(bytes((byte,)))\n\n def write_null(self, datum):\n \"\"\"\n null is written as zero bytes\n \"\"\"\n pass\n\n def write_boolean(self, datum):\n \"\"\"\n a boolean is written as a single byte\n whose value is either 0 (false) or 1 (true).\n \"\"\"\n # Python maps True to 1 and False to 0.\n self.WriteByte(int(bool(datum)))\n\n def write_int(self, datum):\n \"\"\"\n int and long values are written using variable-length, zig-zag coding.\n \"\"\"\n self.write_long(datum);\n\n def write_long(self, datum):\n \"\"\"\n int and long values are written using variable-length, zig-zag coding.\n \"\"\"\n datum = (datum << 1) ^ (datum >> 63)\n while (datum & ~0x7F) != 0:\n self.WriteByte((datum & 0x7f) | 0x80)\n datum >>= 7\n self.WriteByte(datum)\n\n def write_float(self, datum):\n \"\"\"\n A float is written as 4 bytes.\n The float is converted into a 32-bit integer using a method equivalent to\n Java's floatToIntBits and then encoded in little-endian format.\n \"\"\"\n bits = STRUCT_INT.unpack(STRUCT_FLOAT.pack(datum))[0]\n self.WriteByte((bits) & 0xFF)\n self.WriteByte((bits >> 8) & 0xFF)\n self.WriteByte((bits >> 16) & 0xFF)\n self.WriteByte((bits >> 24) & 0xFF)\n\n def write_double(self, datum):\n \"\"\"\n A double is written as 8 bytes.\n The double is converted into a 64-bit integer using a method equivalent to\n Java's doubleToLongBits and then encoded in little-endian format.\n \"\"\"\n bits = STRUCT_LONG.unpack(STRUCT_DOUBLE.pack(datum))[0]\n self.WriteByte((bits) & 0xFF)\n self.WriteByte((bits >> 8) & 0xFF)\n self.WriteByte((bits >> 16) & 0xFF)\n self.WriteByte((bits >> 24) & 0xFF)\n self.WriteByte((bits >> 32) & 0xFF)\n self.WriteByte((bits >> 40) & 0xFF)\n self.WriteByte((bits >> 48) & 0xFF)\n self.WriteByte((bits >> 56) & 0xFF)\n\n def write_bytes(self, datum):\n \"\"\"\n Bytes are encoded as a long followed by that many bytes of data.\n \"\"\"\n self.write_long(len(datum))\n self.write(datum)\n\n def write_utf8(self, datum):\n \"\"\"\n A string is encoded as a long followed by\n that many bytes of UTF-8 encoded character data.\n \"\"\"\n datum = datum.encode(\"utf-8\")\n self.write_bytes(datum)\n\n def write_crc32(self, bytes):\n \"\"\"\n A 4-byte, big-endian CRC32 checksum\n \"\"\"\n self.write(STRUCT_CRC32.pack(binascii.crc32(bytes) & 0xffffffff));\n\n\n# ------------------------------------------------------------------------------\n# DatumReader/Writer\n\n\nclass DatumReader(object):\n \"\"\"Deserialize Avro-encoded data into a Python data structure.\"\"\"\n @staticmethod\n def check_props(schema_one, schema_two, prop_list):\n for prop in prop_list:\n if getattr(schema_one, prop) != getattr(schema_two, prop):\n return False\n return True\n\n @staticmethod\n def match_schemas(writer_schema, reader_schema):\n w_type = writer_schema.type\n r_type = reader_schema.type\n if 'union' in [w_type, r_type] or 'error_union' in [w_type, r_type]:\n return True\n elif (w_type in schema.PRIMITIVE_TYPES and r_type in schema.PRIMITIVE_TYPES\n and w_type == r_type):\n return True\n elif (w_type == r_type == 'record' and\n DatumReader.check_props(writer_schema, reader_schema,\n ['fullname'])):\n return True\n elif (w_type == r_type == 'error' and\n DatumReader.check_props(writer_schema, reader_schema,\n ['fullname'])):\n return True\n elif (w_type == r_type == 'request'):\n return True\n elif (w_type == r_type == 'fixed' and\n DatumReader.check_props(writer_schema, reader_schema,\n ['fullname', 'size'])):\n return True\n elif (w_type == r_type == 'enum' and\n DatumReader.check_props(writer_schema, reader_schema,\n ['fullname'])):\n return True\n elif (w_type == r_type == 'map' and\n DatumReader.check_props(writer_schema.values,\n reader_schema.values, ['type'])):\n return True\n elif (w_type == r_type == 'array' and\n DatumReader.check_props(writer_schema.items,\n reader_schema.items, ['type'])):\n return True\n\n # Handle schema promotion\n if w_type == 'int' and r_type in ['long', 'float', 'double']:\n return True\n elif w_type == 'long' and r_type in ['float', 'double']:\n return True\n elif w_type == 'float' and r_type == 'double':\n return True\n return False\n\n def __init__(self, writer_schema=None, reader_schema=None):\n \"\"\"\n As defined in the Avro specification, we call the schema encoded\n in the data the \"writer's schema\", and the schema expected by the\n reader the \"reader's schema\".\n \"\"\"\n self._writer_schema = writer_schema\n self._reader_schema = reader_schema\n\n # read/write properties\n def set_writer_schema(self, writer_schema):\n self._writer_schema = writer_schema\n writer_schema = property(lambda self: self._writer_schema,\n set_writer_schema)\n def set_reader_schema(self, reader_schema):\n self._reader_schema = reader_schema\n reader_schema = property(lambda self: self._reader_schema,\n set_reader_schema)\n\n def read(self, decoder):\n if self.reader_schema is None:\n self.reader_schema = self.writer_schema\n return self.read_data(self.writer_schema, self.reader_schema, decoder)\n\n def read_data(self, writer_schema, reader_schema, decoder):\n # schema matching\n if not DatumReader.match_schemas(writer_schema, reader_schema):\n fail_msg = 'Schemas do not match.'\n raise SchemaResolutionException(fail_msg, writer_schema, reader_schema)\n\n # schema resolution: reader's schema is a union, writer's schema is not\n if (writer_schema.type not in ['union', 'error_union']\n and reader_schema.type in ['union', 'error_union']):\n for s in reader_schema.schemas:\n if DatumReader.match_schemas(writer_schema, s):\n return self.read_data(writer_schema, s, decoder)\n fail_msg = 'Schemas do not match.'\n raise SchemaResolutionException(fail_msg, writer_schema, reader_schema)\n\n # function dispatch for reading data based on type of writer's schema\n if writer_schema.type == 'null':\n return decoder.read_null()\n elif writer_schema.type == 'boolean':\n return decoder.read_boolean()\n elif writer_schema.type == 'string':\n return decoder.read_utf8()\n elif writer_schema.type == 'int':\n return decoder.read_int()\n elif writer_schema.type == 'long':\n return decoder.read_long()\n elif writer_schema.type == 'float':\n return decoder.read_float()\n elif writer_schema.type == 'double':\n return decoder.read_double()\n elif writer_schema.type == 'bytes':\n return decoder.read_bytes()\n elif writer_schema.type == 'fixed':\n return self.read_fixed(writer_schema, reader_schema, decoder)\n elif writer_schema.type == 'enum':\n return self.read_enum(writer_schema, reader_schema, decoder)\n elif writer_schema.type == 'array':\n return self.read_array(writer_schema, reader_schema, decoder)\n elif writer_schema.type == 'map':\n return self.read_map(writer_schema, reader_schema, decoder)\n elif writer_schema.type in ['union', 'error_union']:\n return self.read_union(writer_schema, reader_schema, decoder)\n elif writer_schema.type in ['record', 'error', 'request']:\n return self.read_record(writer_schema, reader_schema, decoder)\n else:\n fail_msg = \"Cannot read unknown schema type: %s\" % writer_schema.type\n raise schema.AvroException(fail_msg)\n\n def skip_data(self, writer_schema, decoder):\n if writer_schema.type == 'null':\n return decoder.skip_null()\n elif writer_schema.type == 'boolean':\n return decoder.skip_boolean()\n elif writer_schema.type == 'string':\n return decoder.skip_utf8()\n elif writer_schema.type == 'int':\n return decoder.skip_int()\n elif writer_schema.type == 'long':\n return decoder.skip_long()\n elif writer_schema.type == 'float':\n return decoder.skip_float()\n elif writer_schema.type == 'double':\n return decoder.skip_double()\n elif writer_schema.type == 'bytes':\n return decoder.skip_bytes()\n elif writer_schema.type == 'fixed':\n return self.skip_fixed(writer_schema, decoder)\n elif writer_schema.type == 'enum':\n return self.skip_enum(writer_schema, decoder)\n elif writer_schema.type == 'array':\n return self.skip_array(writer_schema, decoder)\n elif writer_schema.type == 'map':\n return self.skip_map(writer_schema, decoder)\n elif writer_schema.type in ['union', 'error_union']:\n return self.skip_union(writer_schema, decoder)\n elif writer_schema.type in ['record', 'error', 'request']:\n return self.skip_record(writer_schema, decoder)\n else:\n fail_msg = \"Unknown schema type: %s\" % writer_schema.type\n raise schema.AvroException(fail_msg)\n\n def read_fixed(self, writer_schema, reader_schema, decoder):\n \"\"\"\n Fixed instances are encoded using the number of bytes declared\n in the schema.\n \"\"\"\n return decoder.read(writer_schema.size)\n\n def skip_fixed(self, writer_schema, decoder):\n return decoder.skip(writer_schema.size)\n\n def read_enum(self, writer_schema, reader_schema, decoder):\n \"\"\"\n An enum is encoded by a int, representing the zero-based position\n of the symbol in the schema.\n \"\"\"\n # read data\n index_of_symbol = decoder.read_int()\n if index_of_symbol >= len(writer_schema.symbols):\n fail_msg = \"Can't access enum index %d for enum with %d symbols\"\\\n % (index_of_symbol, len(writer_schema.symbols))\n raise SchemaResolutionException(fail_msg, writer_schema, reader_schema)\n read_symbol = writer_schema.symbols[index_of_symbol]\n\n # schema resolution\n if read_symbol not in reader_schema.symbols:\n fail_msg = \"Symbol %s not present in Reader's Schema\" % read_symbol\n raise SchemaResolutionException(fail_msg, writer_schema, reader_schema)\n\n return read_symbol\n\n def skip_enum(self, writer_schema, decoder):\n return decoder.skip_int()\n\n def read_array(self, writer_schema, reader_schema, decoder):\n \"\"\"\n Arrays are encoded as a series of blocks.\n\n Each block consists of a long count value,\n followed by that many array items.\n A block with count zero indicates the end of the array.\n Each item is encoded per the array's item schema.\n\n If a block's count is negative,\n then the count is followed immediately by a long block size,\n indicating the number of bytes in the block.\n The actual count in this case\n is the absolute value of the count written.\n \"\"\"\n read_items = []\n block_count = decoder.read_long()\n while block_count != 0:\n if block_count < 0:\n block_count = -block_count\n block_size = decoder.read_long()\n for i in range(block_count):\n read_items.append(self.read_data(writer_schema.items,\n reader_schema.items, decoder))\n block_count = decoder.read_long()\n return read_items\n\n def skip_array(self, writer_schema, decoder):\n block_count = decoder.read_long()\n while block_count != 0:\n if block_count < 0:\n block_size = decoder.read_long()\n decoder.skip(block_size)\n else:\n for i in range(block_count):\n self.skip_data(writer_schema.items, decoder)\n block_count = decoder.read_long()\n\n def read_map(self, writer_schema, reader_schema, decoder):\n \"\"\"\n Maps are encoded as a series of blocks.\n\n Each block consists of a long count value,\n followed by that many key/value pairs.\n A block with count zero indicates the end of the map.\n Each item is encoded per the map's value schema.\n\n If a block's count is negative,\n then the count is followed immediately by a long block size,\n indicating the number of bytes in the block.\n The actual count in this case\n is the absolute value of the count written.\n \"\"\"\n read_items = {}\n block_count = decoder.read_long()\n while block_count != 0:\n if block_count < 0:\n block_count = -block_count\n block_size = decoder.read_long()\n for i in range(block_count):\n key = decoder.read_utf8()\n read_items[key] = self.read_data(writer_schema.values,\n reader_schema.values, decoder)\n block_count = decoder.read_long()\n return read_items\n\n def skip_map(self, writer_schema, decoder):\n block_count = decoder.read_long()\n while block_count != 0:\n if block_count < 0:\n block_size = decoder.read_long()\n decoder.skip(block_size)\n else:\n for i in range(block_count):\n decoder.skip_utf8()\n self.skip_data(writer_schema.values, decoder)\n block_count = decoder.read_long()\n\n def read_union(self, writer_schema, reader_schema, decoder):\n \"\"\"\n A union is encoded by first writing a long value indicating\n the zero-based position within the union of the schema of its value.\n The value is then encoded per the indicated schema within the union.\n \"\"\"\n # schema resolution\n index_of_schema = int(decoder.read_long())\n if index_of_schema >= len(writer_schema.schemas):\n fail_msg = \"Can't access branch index %d for union with %d branches\"\\\n % (index_of_schema, len(writer_schema.schemas))\n raise SchemaResolutionException(fail_msg, writer_schema, reader_schema)\n selected_writer_schema = writer_schema.schemas[index_of_schema]\n\n # read data\n return self.read_data(selected_writer_schema, reader_schema, decoder)\n\n def skip_union(self, writer_schema, decoder):\n index_of_schema = int(decoder.read_long())\n if index_of_schema >= len(writer_schema.schemas):\n fail_msg = \"Can't access branch index %d for union with %d branches\"\\\n % (index_of_schema, len(writer_schema.schemas))\n raise SchemaResolutionException(fail_msg, writer_schema)\n return self.skip_data(writer_schema.schemas[index_of_schema], decoder)\n\n def read_record(self, writer_schema, reader_schema, decoder):\n \"\"\"\n A record is encoded by encoding the values of its fields\n in the order that they are declared. In other words, a record\n is encoded as just the concatenation of the encodings of its fields.\n Field values are encoded per their schema.\n\n Schema Resolution:\n * the ordering of fields may be different: fields are matched by name.\n * schemas for fields with the same name in both records are resolved\n recursively.\n * if the writer's record contains a field with a name not present in the\n reader's record, the writer's value for that field is ignored.\n * if the reader's record schema has a field that contains a default value,\n and writer's schema does not have a field with the same name, then the\n reader should use the default value from its field.\n * if the reader's record schema has a field with no default value, and\n writer's schema does not have a field with the same name, then the\n field's value is unset.\n \"\"\"\n # schema resolution\n readers_fields_dict = reader_schema.field_map\n read_record = {}\n for field in writer_schema.fields:\n readers_field = readers_fields_dict.get(field.name)\n if readers_field is not None:\n field_val = self.read_data(field.type, readers_field.type, decoder)\n read_record[field.name] = field_val\n else:\n self.skip_data(field.type, decoder)\n\n # fill in default values\n if len(readers_fields_dict) > len(read_record):\n writers_fields_dict = writer_schema.field_map\n for field_name, field in readers_fields_dict.items():\n if field_name not in writers_fields_dict:\n if field.has_default:\n field_val = self._read_default_value(field.type, field.default)\n read_record[field.name] = field_val\n else:\n fail_msg = 'No default value for field %s' % field_name\n raise SchemaResolutionException(fail_msg, writer_schema,\n reader_schema)\n return read_record\n\n def skip_record(self, writer_schema, decoder):\n for field in writer_schema.fields:\n self.skip_data(field.type, decoder)\n\n def _read_default_value(self, field_schema, default_value):\n \"\"\"\n Basically a JSON Decoder?\n \"\"\"\n if field_schema.type == 'null':\n return None\n elif field_schema.type == 'boolean':\n return bool(default_value)\n elif field_schema.type == 'int':\n return int(default_value)\n elif field_schema.type == 'long':\n return int(default_value)\n elif field_schema.type in ['float', 'double']:\n return float(default_value)\n elif field_schema.type in ['enum', 'fixed', 'string', 'bytes']:\n return default_value\n elif field_schema.type == 'array':\n read_array = []\n for json_val in default_value:\n item_val = self._read_default_value(field_schema.items, json_val)\n read_array.append(item_val)\n return read_array\n elif field_schema.type == 'map':\n read_map = {}\n for key, json_val in default_value.items():\n map_val = self._read_default_value(field_schema.values, json_val)\n read_map[key] = map_val\n return read_map\n elif field_schema.type in ['union', 'error_union']:\n return self._read_default_value(field_schema.schemas[0], default_value)\n elif field_schema.type == 'record':\n read_record = {}\n for field in field_schema.fields:\n json_val = default_value.get(field.name)\n if json_val is None: json_val = field.default\n field_val = self._read_default_value(field.type, json_val)\n read_record[field.name] = field_val\n return read_record\n else:\n fail_msg = 'Unknown type: %s' % field_schema.type\n raise schema.AvroException(fail_msg)\n\n\n# ------------------------------------------------------------------------------\n\n\nclass DatumWriter(object):\n \"\"\"DatumWriter for generic python objects.\"\"\"\n def __init__(self, writer_schema=None):\n self._writer_schema = writer_schema\n\n # read/write properties\n def set_writer_schema(self, writer_schema):\n self._writer_schema = writer_schema\n writer_schema = property(lambda self: self._writer_schema,\n set_writer_schema)\n\n def write(self, datum, encoder):\n # validate datum\n if not Validate(self.writer_schema, datum):\n raise AvroTypeException(self.writer_schema, datum)\n\n self.write_data(self.writer_schema, datum, encoder)\n\n def write_data(self, writer_schema, datum, encoder):\n # function dispatch to write datum\n if writer_schema.type == 'null':\n encoder.write_null(datum)\n elif writer_schema.type == 'boolean':\n encoder.write_boolean(datum)\n elif writer_schema.type == 'string':\n encoder.write_utf8(datum)\n elif writer_schema.type == 'int':\n encoder.write_int(datum)\n elif writer_schema.type == 'long':\n encoder.write_long(datum)\n elif writer_schema.type == 'float':\n encoder.write_float(datum)\n elif writer_schema.type == 'double':\n encoder.write_double(datum)\n elif writer_schema.type == 'bytes':\n encoder.write_bytes(datum)\n elif writer_schema.type == 'fixed':\n self.write_fixed(writer_schema, datum, encoder)\n elif writer_schema.type == 'enum':\n self.write_enum(writer_schema, datum, encoder)\n elif writer_schema.type == 'array':\n self.write_array(writer_schema, datum, encoder)\n elif writer_schema.type == 'map':\n self.write_map(writer_schema, datum, encoder)\n elif writer_schema.type in ['union', 'error_union']:\n self.write_union(writer_schema, datum, encoder)\n elif writer_schema.type in ['record', 'error', 'request']:\n self.write_record(writer_schema, datum, encoder)\n else:\n fail_msg = 'Unknown type: %s' % writer_schema.type\n raise schema.AvroException(fail_msg)\n\n def write_fixed(self, writer_schema, datum, encoder):\n \"\"\"\n Fixed instances are encoded using the number of bytes declared\n in the schema.\n \"\"\"\n encoder.write(datum)\n\n def write_enum(self, writer_schema, datum, encoder):\n \"\"\"\n An enum is encoded by a int, representing the zero-based position\n of the symbol in the schema.\n \"\"\"\n index_of_datum = writer_schema.symbols.index(datum)\n encoder.write_int(index_of_datum)\n\n def write_array(self, writer_schema, datum, encoder):\n \"\"\"\n Arrays are encoded as a series of blocks.\n\n Each block consists of a long count value,\n followed by that many array items.\n A block with count zero indicates the end of the array.\n Each item is encoded per the array's item schema.\n\n If a block's count is negative,\n then the count is followed immediately by a long block size,\n indicating the number of bytes in the block.\n The actual count in this case\n is the absolute value of the count written.\n \"\"\"\n if len(datum) > 0:\n encoder.write_long(len(datum))\n for item in datum:\n self.write_data(writer_schema.items, item, encoder)\n encoder.write_long(0)\n\n def write_map(self, writer_schema, datum, encoder):\n \"\"\"\n Maps are encoded as a series of blocks.\n\n Each block consists of a long count value,\n followed by that many key/value pairs.\n A block with count zero indicates the end of the map.\n Each item is encoded per the map's value schema.\n\n If a block's count is negative,\n then the count is followed immediately by a long block size,\n indicating the number of bytes in the block.\n The actual count in this case\n is the absolute value of the count written.\n \"\"\"\n if len(datum) > 0:\n encoder.write_long(len(datum))\n for key, val in datum.items():\n encoder.write_utf8(key)\n self.write_data(writer_schema.values, val, encoder)\n encoder.write_long(0)\n\n def write_union(self, writer_schema, datum, encoder):\n \"\"\"\n A union is encoded by first writing a long value indicating\n the zero-based position within the union of the schema of its value.\n The value is then encoded per the indicated schema within the union.\n \"\"\"\n # resolve union\n index_of_schema = -1\n for i, candidate_schema in enumerate(writer_schema.schemas):\n if Validate(candidate_schema, datum):\n index_of_schema = i\n if index_of_schema < 0: raise AvroTypeException(writer_schema, datum)\n\n # write data\n encoder.write_long(index_of_schema)\n self.write_data(writer_schema.schemas[index_of_schema], datum, encoder)\n\n def write_record(self, writer_schema, datum, encoder):\n \"\"\"\n A record is encoded by encoding the values of its fields\n in the order that they are declared. In other words, a record\n is encoded as just the concatenation of the encodings of its fields.\n Field values are encoded per their schema.\n \"\"\"\n for field in writer_schema.fields:\n self.write_data(field.type, datum.get(field.name), encoder)\n\n\nif __name__ == '__main__':\n raise Exception('Not a standalone module')\n","sub_path":"lang/py3/avro/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":32670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"281251131","text":"import os\nimport re\nimport sys\nimport glob\nimport nltk\nimport gensim\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom uuid import uuid4\nfrom functools import reduce\nfrom multiprocessing import Pool\nfrom nltk.corpus import stopwords\n\ndef _remove_non_printed_chars(string):\n reg = re.compile('[^a-zA-Zа-яА-ЯёЁ]')\n return reg.sub(' ', string)\n\ndef _remove_stop_words(string,sw=[]):\n return ' '.join([word if word not in sw else '' \\\n for word in string.strip().split(' ')])\n\ndef _trim_string(string):\n # remove extra spaces, remove trailing spaces, lower the case \n return re.sub('\\s+',' ',string).strip().lower()\n\ndef clean_string(string,\n stop_words_list,\n min_len=2,\n max_len=30):\n\n string = _remove_non_printed_chars(string)\n string = _remove_stop_words(string,stop_words_list)\n string = _trim_string(string)\n # also remove short words, most likely containing addresses / crap / left-overs / etc remaining after removal\n # gensim mostly does the same as above, it is used here for simplicity\n string = ' '.join(gensim.utils.simple_preprocess(string,\n min_len=min_len,\n max_len=max_len))\n return string\n\ndef splitkeepsep(s, sep):\n cleaned = []\n s = re.split(\"(%s)\" % re.escape(sep), s)\n for _ in s:\n if _!='' and _!=sep:\n cleaned.append(sep+_)\n return cleaned\n\ndef remove_html_tags(text):\n \"\"\"Remove html tags from a string\"\"\"\n import re\n clean = re.compile('<.*?>')\n return re.sub(clean, '', text)\n\ndef remove_special_chars(text,char_list):\n for char in char_list:\n text=text.replace(char,'')\n return text.replace(u'\\xa0', u' ') \n\ndef process_wiki_files(wiki_file):\n chars = ['\\n']\n global sw\n \n with open(wiki_file, encoding='utf-8') as f:\n content = f.read()\n\n articles = splitkeepsep(content,'/visit-data')\nclass VisitDataResource(Resource):\n\n post_parser = reqparse.RequestParser()\n post_parser.add_argument('user_id', type=unicode, location='json', required=True)\n post_parser.add_argument('path', type=unicode, location='json', required=True)\n post_parser.add_argument('window_width', type=unicode, location='json', required=True)\n post_parser.add_argument('window_height', type=unicode, location='json', required=True)\n post_parser.add_argument('included_in_sample', type=bool, location='json', required=True)\n post_parser.add_argument('require_page_visit_id', type=bool, location='json', required=True)\n\n redis = StrictRedis()\n\n def post(self, site_id):\n args = self.post_parser.parse_args()\n self.add_traf_log_entry(site_id, args)\n self.increment_apm_value(site_id)\n self.update_last_info(site_id)\n self.set_snipper_ver(site_id)\n\n if args['require_page_visit_id']:\n page_id, page_visit_id = self._insert_page_visit(site_id, args)\n response = {\n 'success': True,\n 'page_id': page_id,\n 'page_visit_id': page_visit_id\n }\n else:\n response = {\n 'success': True\n }\n\n response_content = json.dumps(response)\n\n res = Response(response_content, mimetype='application/json')\n res.headers['X-Cache-Hit'] = '0'\n res.headers['X-DC-Server'] = settings.ROUTE53_DNS_NAME or request.host\n res.headers['Access-Control-Expose-Headers'] = 'X-DC-Server'\n\n return res\n\n def _insert_page_visit(self, site_id, args):\n kwargs = pick(args, 'user_id path window_width window_height included_in_sample')\n kwargs['site_id'] = site_id\n kwargs['user_agent'] = request.headers.get('User-Agent', '')\n kwargs['accept_language'] = request.headers.get('Accept-Language', '')\n\n return PageVisit.objects.insert(**kwargs)\n\n def add_traf_log_entry(self, site_id, args):\n traffic_log.append(\n site_id=str(site_id),\n user_id=args['user_id'],\n ip=geoip.get_ip_address(),\n path=args['path'][:2083],\n window_width=args['window_width'],\n window_height=args['window_height'],\n user_agent=request.headers.get('User-Agent', ''),\n accept_language=request.headers.get('Accept-Language', '')\n )\n\n def increment_apm_value(self, site_id):\n self.redis.incr('site:%d:r_rpm' % site_id, 1)\n\n def update_last_info(self, site_id):\n now = datetime.utcnow()\n redis_key = 'site:%d:last_data' % site_id\n last_data = self.redis.getset(redis_key, str(to_epoch_time(now)))\n\n if not last_data:\n site = Site.objects.get_by_id(site_id)\n\n if site.last_data is None:\n site.last_data = now\n FeedEvent.objects.add_script_added_event(site_id)\n\n for organization_user in OrganizationUser.objects.get_by_site_id(site_id):\n mp.track_event(organization_user.user_id, 'Script Added')\n ic.send_intercom_event(organization_user.user_id, 'Script Added')\n\n def set_snipper_ver(self, site_id):\n redis_key = 'site:%d:snippet_version' % site_id\n stored_snippet_version = int(self.redis.get(redis_key) or '-1')\n current_snippet_version = int(request.args.get('sv', '0'))\n\n if stored_snippet_version < current_snippet_version:\n site = Site.objects.get_by_id(site_id)\n\n if site.snippet_version < current_snippet_version:\n site.snippet_version = current_snippet_version\n\n self.redis.set(redis_key, str(current_snippet_version))\n","sub_path":"Python_Lua.py","file_name":"Python_Lua.py","file_ext":"py","file_size_in_byte":4233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"372690564","text":"from sklearn.pipeline import FeatureUnion\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nclass DataFrameSelector(BaseEstimator, TransformerMixin):\n def __init__(self, attribute_names):\n self.attribute_names = attribute_names\n def fit(self, X, y=None):\n return self\n def transform(self, X):\n return X[self.attribute_names].values\n\nnum_attribs = list(housing_num)\ncat_attribs = [\"ocean_proximity\"]\n\nnum_pipeline = Pipeline([\n ('selector', DataFrameSelector(num_attribs)),\n ('imputer', Imputer(strategy = \"median\")),\n ('attribs_adder', CombinedAttributesAdder()),\n ('std_scaler', StandardScaler()),\n])\n\ncat_pipeline = Pipeline([\n ('selector', DataFrameSelector(cat_attribs)),\n ('label_binarizer', LabelBinarizer())\n])\n\nfull_pipeline = FeatureUnion(transformer_list=[\n ('num_pipeline',num_pipeline),\n ('cat_pipeline',cat_pipeline)\n])\n\nhousing_prepared = full_pipeline.fit_transform(housing)","sub_path":"StuffAndScripts/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"222475256","text":"# encoding: utf-8\nfrom __future__ import division\nimport sys\n\nimport cv2\nimport numpy as np\n\n\n\n#读取原图\nimage = cv2.imread(\"_04_lena.jpg\")\ncv2.imshow('original', image)\n\n'''\n中值滤波器是一种常用的非线性滤波器,其基本原理是:选择待处理像素的一个邻域中各像素值的中值来代替待处理的像素。\n主要功能使某像素的灰度值与周围领域内的像素比较接近,从而消除一些孤立的噪声点,所以中值滤波器能够很好的消除椒盐噪声。\n不仅如此,中值滤波器在消除噪声的同时,还能有效的保护图像的边界信息,不会对图像造成很大的模糊(相比于均值滤波器)。\n中值滤波器的效果受滤波窗口尺寸的影响较大,在消除噪声和保护图像的细节存在着矛盾:滤波窗口较小,则能很好的保护图像中的某些细节,但对噪声的过滤效果就不是很好,\n因为实际中的噪声不可能只占一个像素位置;反之,窗口尺寸较大有较好的噪声过滤效果,但是会对图像造成一定的模糊。\n另外,根据中值滤波器原理,如果在滤波窗口内的噪声点的个数大于整个窗口内非噪声像素的个数,则中值滤波就不能很好的过滤掉噪声。\n'''\nmedianBlur=cv2.medianBlur(image,5)\ncv2.imshow('medianBlur', medianBlur)\nprint('中值滤波器完成')\n\n'''\n 自适应中值滤波算法\n 自适应滤波器不但能够滤除概率较大的椒盐噪声,而且能够更好的保护图像的细节,这是常规的中值滤波器做不到的。\n 自适应的中值滤波器也需要一个矩形的窗口 ,和常规中值滤波器不同的是这个窗口的大小会在滤波处理的过程中进行改变(增大)。\n '''\ndef AdaptProcess(src, i, j, minSize, maxSize):\n filter_size = minSize\n kernelSize = filter_size // 2\n rio = src[i-kernelSize:i+kernelSize+1, j-kernelSize:j+kernelSize+1]\n minPix = np.min(rio)\n maxPix = np.max(rio)\n medPix = np.median(rio)\n zxy = src[i,j]\n if (medPix > minPix) and (medPix < maxPix):\n if (np.mean(zxy) > minPix) and (np.mean(zxy) < maxPix):\n return zxy\n else:\n return medPix\n else:\n filter_size = filter_size + 2\n if filter_size <= maxSize:\n return AdaptProcess(src, i, j, filter_size, maxSize)\n else:\n return medPix\ndef adapt_meadian_filter(img, minsize, maxsize):\n borderSize = maxsize // 2\n src = cv2.copyMakeBorder(img, borderSize, borderSize, borderSize, borderSize, cv2.BORDER_REFLECT)\n for m in range(borderSize, src.shape[0] - borderSize):\n for n in range(borderSize, src.shape[1] - borderSize):\n src[m,n] = AdaptProcess(src, m, n, minsize, maxsize)\n dst = src[borderSize:borderSize+img.shape[0], borderSize:borderSize+img.shape[1]]\n return dst\n# adaptMeadianFilter = adapt_meadian_filter(image,5,10)\n# cv2.imshow('adapt_meadian_filter', adaptMeadianFilter)\n# print('自适应中值滤波器完成')\n\n#低通滤波器\nkernel1=np.array([[0.11,0.11,0.11],\n [0.11,0.11,0.11],\n [0.11,0.11,0.11]])\nrect=cv2.filter2D(image,-1,kernel1)\n# cv2.imwrite(\"_04_img/rect.jpg\",rect)\ncv2.imshow('rect',rect)\nprint('低通滤波器完成')\n\n#高斯滤波器\nkernel2=np.array([[1,4,7,4,1],\n [4,16,26,16,4],\n [7,26,41,26,7],\n [4,16,26,16,4],\n [1,4,7,4,1]])/273.0\ngaussian=cv2.filter2D(image,-1,kernel2)\n# cv2.imwrite(\"_04_img/gaussian.jpg\",gaussian)\ncv2.imshow('gaussian',gaussian)\nprint('高斯滤波器完成')\n\n#锐化滤波器\nkernel3=np.array([[0,-2,0],\n [-2,9,-2],\n [0,-2,0]])\nsharpen=cv2.filter2D(image,-1,kernel3)\n# cv2.imwrite(\"_04_img/sharpen.jpg\",sharpen)\ncv2.imshow('sharpen',sharpen)\nprint('锐化滤波器完成')\n\n#边缘检测\nkernel4=np.array([[-1,-1,-1],\n [-1,8,-1],\n [-1,-1,-1]])\nedges=cv2.filter2D(image,-1,kernel4)\n# cv2.imwrite(\"_04_img/edges.jpg\",edges)\ncv2.imshow('edges', edges)\nprint('边缘检测完成')\n\n#高斯双边滤波\n# bilateral = cv2.bilateralFilter(src=image, d=0, sigmaColor=100, sigmaSpace=15)\n# # bilateral = cv2.resize(bilateral, (image.shape[1], image.shape[0]))\n# # cv2.namedWindow('bi_demo', 0)\n# cv2.imshow(\"bilateral\", image)\n# print('高斯双边滤波完成')\n\n#浮雕滤波器\nkernel5=np.array([[-2,-2,-2,-2,0],\n [-2,-2,-2,0,2],\n [-2,-2,0,2,2],\n [-2,0,2,2,2],\n [0,2,2,2,2]])\nemboss=cv2.filter2D(image,-1,kernel5)\nemboss=cv2.cvtColor(emboss,cv2.COLOR_BGR2GRAY)\n# cv2.imwrite(\"_04_img/emboss.jpg\",emboss)\ncv2.imshow('emboss',emboss)\nprint('浮雕滤波器完成')\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"base/_06_cv2/_04_filter2D.py","file_name":"_04_filter2D.py","file_ext":"py","file_size_in_byte":4797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"328986788","text":"import os\nimport tkFileDialog\nimport tkMessageBox\nimport tkSimpleDialog\nfrom Tkinter import *\nimport ttk\n\nimport serial\n\nfrom matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg\n\nfrom my_serial.SerialInterface import SerialInterface\nfrom settings.Settings import read_settings, UART_SETTINGS, write_settings, PID_SETTINGS\n\n\nclass SerialSettingsDialog(tkSimpleDialog.Dialog):\n def __init__(self, master, my_serial):\n self.my_serial = my_serial\n self.settings = self.my_serial.ser.getSettingsDict()\n tkSimpleDialog.Dialog.__init__(self, master, \"Serial settings\")\n\n def body(self, master):\n Label(master, text=\"Com port\").grid(row=0, sticky=W)\n Label(master, text=\"Baud rate\").grid(row=1, sticky=W)\n Label(master, text=\"Data bits\").grid(row=2, sticky=W)\n Label(master, text=\"Stop bits\").grid(row=3, sticky=W)\n Label(master, text=\"Parity\").grid(row=4, sticky=W)\n\n port_str = StringVar()\n baud_str = StringVar()\n bits_str = StringVar()\n stop_str = StringVar()\n pari_str = StringVar()\n\n self.port_cb = ttk.Combobox(master, values=SerialInterface.serial_ports(), textvariable=port_str)\n self.baud_cb = ttk.Combobox(master, values=serial.Serial.BAUDRATES, textvariable=baud_str)\n self.bits_cb = ttk.Combobox(master, values=serial.Serial.BYTESIZES, textvariable=bits_str)\n self.stop_cb = ttk.Combobox(master, values=serial.Serial.STOPBITS, textvariable=stop_str)\n self.pari_cb = ttk.Combobox(master, values=serial.Serial.PARITIES, textvariable=pari_str)\n\n port_str.set(self.my_serial.ser.port)\n baud_str.set(self.settings.get(\"baudrate\"))\n bits_str.set(self.settings.get(\"bytesize\"))\n stop_str.set(self.settings.get(\"stopbits\"))\n pari_str.set(self.settings.get(\"partity\"))\n\n self.port_cb.grid(row=0, column=1)\n self.baud_cb.grid(row=1, column=1)\n self.bits_cb.grid(row=2, column=1)\n self.stop_cb.grid(row=3, column=1)\n self.pari_cb.grid(row=4, column=1)\n\n return self.baud_cb # Initial focus\n\n def validate(self):\n try:\n self.settings['parity'] = str(self.pari_cb.get())\n self.settings['baudrate'] = int(self.baud_cb.get())\n self.settings['bytesize'] = int(self.bits_cb.get())\n self.settings['stopbits'] = int(self.stop_cb.get())\n return 1\n except Exception as e:\n tkMessageBox.showerror(\n \"Bad input\",\n \"Illegal values, please try again: \"+e.message\n )\n return 0\n\n def apply(self):\n yaml_dict = read_settings(UART_SETTINGS)\n yaml_dict['parity'] = str(self.pari_cb.get())\n yaml_dict['baud_rate'] = int(self.baud_cb.get())\n yaml_dict['data_bits'] = int(self.bits_cb.get())\n yaml_dict['stop_bits'] = int(self.stop_cb.get())\n yaml_dict['com_port'] = str(self.port_cb.get())\n write_settings(UART_SETTINGS, yaml_dict)\n\n self.my_serial.serial_destroy()\n self.my_serial.configure_serial()\n\n\nclass PIDSettingsDialog(tkSimpleDialog.Dialog):\n def __init__(self, master, pid):\n self.pid = pid\n\n self.kp_ent = None\n self.ki_ent = None\n self.kd_ent = None\n self.dt_ent = None\n self.wu_ent = None\n\n tkSimpleDialog.Dialog.__init__(self, master, \"PID settings\")\n\n def body(self, master):\n Label(master, text=\"Kp\").grid(row=0, sticky=W)\n Label(master, text=\"Ki\").grid(row=1, sticky=W)\n Label(master, text=\"Kd\").grid(row=2, sticky=W)\n Label(master, text=\"dt\").grid(row=3, sticky=W)\n Label(master, text=\"Wu\").grid(row=4, sticky=W)\n\n kp_str = StringVar()\n ki_str = StringVar()\n kd_str = StringVar()\n dt_str = StringVar()\n wu_str = StringVar()\n\n self.kp_ent = Entry(master, textvariable=kp_str)\n self.ki_ent = Entry(master, textvariable=ki_str)\n self.kd_ent = Entry(master, textvariable=kd_str)\n self.dt_ent = Entry(master, textvariable=dt_str)\n self.wu_ent = Entry(master, textvariable=wu_str)\n\n kp_str.set(self.pid.Kp)\n ki_str.set(self.pid.Ki)\n kd_str.set(self.pid.Kd)\n dt_str.set(self.pid.dt)\n wu_str.set(self.pid.Wu)\n\n self.kp_ent.grid(row=0, column=1)\n self.ki_ent.grid(row=1, column=1)\n self.kd_ent.grid(row=2, column=1)\n self.dt_ent.grid(row=3, column=1)\n self.wu_ent.grid(row=4, column=1)\n\n return self.kp_ent # Initial focus\n\n def validate(self):\n try:\n yaml_dict = read_settings(PID_SETTINGS)\n yaml_dict['Kd'] = float(self.kd_ent.get())\n yaml_dict['Ki'] = float(self.ki_ent.get())\n yaml_dict['Kp'] = float(self.kp_ent.get())\n yaml_dict['Wu'] = float(self.wu_ent.get())\n yaml_dict['dt'] = float(self.dt_ent.get())\n write_settings(PID_SETTINGS, yaml_dict)\n\n self.pid.configure_pid()\n return 1\n except Exception as e:\n tkMessageBox.showerror(\n \"Bad input\",\n \"Illegal values, please try again: \"+e.message\n )\n return 0\n\n def apply(self):\n pass\n\n\nclass PicInfoDialog(tkSimpleDialog.Dialog):\n def __init__(self, master, PICInfo):\n self.pic_info = PICInfo\n tkSimpleDialog.Dialog.__init__(self, master, \"PIC Info\")\n\n def body(self, master):\n Label(master, text=\"PIC name: \").grid(row=0, sticky=W)\n Label(master, text=\"Last communication: \").grid(row=1, sticky=W)\n\n Entry(master, text=self.pic_info.pic_name).grid(row=0, column=1)\n Entry(master, text=self.pic_info.pic_last_communication).grid(row=1, column=1)\n\n\nclass FileDialog:\n def __init__(self, master):\n self.master = master\n\n initial_path = sys.executable\n if sys.platform.startswith('win'):\n initial_path = os.path.splitdrive(sys.executable)\n\n # define options for opening or saving a file\n self.file_opt = options = {}\n options['defaultextension'] = '.txt'\n options['filetypes'] = [('Text files', '.txt'),('All files', '.*')]\n options['initialdir'] = initial_path\n #options['initialfile'] = 'graph.txt'\n options['parent'] = self.master\n options['title'] = 'Select a file'\n\n # defining options for opening a directory\n self.dir_opt = options = {}\n options['initialdir'] = initial_path\n options['mustexist'] = False\n options['parent'] = self.master\n options['title'] = 'Select a directory'\n\n def open_file(self):\n return tkFileDialog.askopenfile(mode='r', **self.file_opt)\n\n def open_file_name(self):\n # Get file name\n filename = tkFileDialog.askopenfilename(**self.file_opt)\n # if filename:\n # return open(filename, 'r')\n return filename\n\n def save_file(self):\n return tkFileDialog.asksaveasfile(mode='w', **self.file_opt)\n\n def save_file_name(self):\n filename = tkFileDialog.asksaveasfilename(**self.file_opt)\n # if filename:\n # return open(filename, 'w')\n return filename\n\n def ask_directory(self):\n return tkFileDialog.askdirectory(**self.dir_opt)\n\n\nclass GraphOptionsDialog(tkSimpleDialog.Dialog):\n def __init__(self, master, canvas):\n self.canvas = canvas\n tkSimpleDialog.Dialog.__init__(self, master, \"PID settings\")\n\n def body(self, master):\n self.toolbar = NavigationToolbar2TkAgg(self.canvas, master)\n self.toolbar.update()\n self.canvas._tkcanvas.pack(fill=BOTH, expand=1)\n\n def apply(self):\n pass","sub_path":"gui/Dialogs.py","file_name":"Dialogs.py","file_ext":"py","file_size_in_byte":7725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"388018025","text":"import re\nf = open('/home/tarena/aid1901/正则表达式/Test')\ndata = f.read()\n\n#大写字母开头单词\n# pattern = r'\\b[A-Z]\\S*\\b'\n#匹配数字\n# pattern = r'-?\\d+\\.?/?\\d*%?'\n#替换日期\npattern = r'\\d{4}\\.\\d{1,2}.\\d{1,2}'\nregex = re.compile(pattern)\n\nfor i in regex.finditer(data):\n s = i.group()\n date = re.sub(r'\\.','-',s)\n data = re.sub(pattern,date,data)\n print(data)\n","sub_path":"tt/exer.py","file_name":"exer.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"628799029","text":"# coding: utf-8\n\nimport os\nimport jwt\nimport sys\nimport time\nimport json\nimport glob\nimport traceback\nimport configparser\nfrom dataclasses import dataclass\n\ntry:\n from libs.ms71lib import _client as jsonrpclib\nexcept ImportError:\n import ms71lib._client as jsonrpclib\n\ntry:\n log = sys.log\nexcept:\n log = None\n\nclass ApplicationException(Exception):\n pass\n\n@dataclass\nclass REFS:\n url_api:str = 'https://mdb.api.cloud.yandex.net:443'\n url_manager:str = \"https://resource-manager.api.cloud.yandex.net:443\"\n url_iam:str = 'https://iam.api.cloud.yandex.net/iam/v1/tokens'\n url_iam_token:str = 'https://iam.api.cloud.yandex.net:443'\n\n def __init__(self, key_path:str=None):\n self.pem_file = key_path or '/ms71/saas/yandex_ch/private.pem'\n if not os.path.exists(self.pem_file):\n raise ApplicationException(\"InitError: .pem file absent\")\n try:\n config = configparser.ConfigParser()\n ini_dir = os.path.dirname(self.pem_file)\n config.read(os.path.join(ini_dir, 'yandex_ch.ini'), encoding='UTF-8')\n init = config['init']\n self.service_account_id = init['service_account_id']\n self.clusterId = init['clusterId']\n self.key_id = init['key_id']\n self.folderId = init['folderId']\n try:\n wd = init['work_dir']\n except:\n wd = None\n self.work_dir = wd or '/ms71/dict'\n except:\n raise ApplicationException('InitError: .ini file error')\n\n\nclass YAPI:\n\n def __init__(self, *args, **kwargs):\n argvs = []\n name = __file__.split('/')\n key_path = None\n for i in name:\n if '.zip' in i:\n name = i\n break\n if isinstance(name, list):\n name = None\n for i, f in enumerate(sys.argv):\n if name and f == name:\n argvs = sys.argv[i+1:]\n for arg in argvs:\n try:\n k, w = arg.split('=')\n if k == 'key_path':\n key_path = w\n except:\n pass\n \n self.refs = REFS(key_path)\n self.expiresAt = 0\n self.auth = []\n self.tasks = []\n try:\n self._gen_tasks()\n except:\n raise ApplicationException(f\"GenTasks ERROR: {traceback.format_exc()}\")\n\n def _print(self, msg, *args, **kwargs):\n if log:\n log(msg)\n else:\n print(msg, *args, **kwargs)\n\n def _getAuth(self):\n with open(self.refs.pem_file, 'r') as private:\n private_key = private.read() # Чтение закрытого ключа из файла.\n now = int(time.time())\n # формируем объект для авторизации\n payload = {\n 'aud': self.refs.url_iam,\n 'iss': self.refs.service_account_id,\n 'iat': now,\n 'exp': now + 3600\n }\n\n # Формирование JWT.\n encoded_token = jwt.encode(\n payload,\n private_key,\n algorithm='PS256',\n headers={'kid': self.refs.key_id}\n ).decode()\n data = json.dumps({'jwt': encoded_token}).encode() \n request = self._NewRequest(self.refs.url_iam_token)\n answer = request(data, '/iam/v1/tokens')\n request.close()\n iamToken = answer.get('iamToken')\n self.expiresAt = time.mktime(time.strptime(answer.get('expiresAt'),'%Y-%m-%dT%H:%M:%S.%fZ'))\n self.auth = [\n ('Authorization', 'Bearer %s' % iamToken),\n ]\n\n def _NewRequest(self, url, auth=None, timeout=None):\n rpc = jsonrpclib.ServerProxy(url, verbose=False, api_key=\"\")\n if auth is None:\n request = rpc(\"request\")\n else:\n self._check_expire()\n if len(auth) < 1:\n auth = self.auth\n _request = rpc(\"request\")\n request = lambda data, handler=None: _request(data, handler=handler, headers=auth)\n if timeout:\n transport = rpc(\"transport\")\n transport._timeout = timeout\n request.close = rpc('close')\n return request\n\n def _check_expire(self):\n # выполняем всегда перед запросами. если токены просрочены - генерим новые\n now = time.time()\n if (isinstance(self.auth, list) and len(self.auth) < 1) or self.expiresAt - now > 600:\n self._getAuth()\n\n \n def _get_cloud_data(self):\n # продакшн\n request = self._NewRequest(self.refs.url_api, self.auth)\n ya_cloud_data = request('', f'/managed-clickhouse/v1/clusters?folderId={self.refs.folderId}') #описание кластера, откуда мы будем брать имена словарей\n request.close()\n return ya_cloud_data\n\n\n def _parse_cloud_data(self):\n cloud_data = self._get_cloud_data()\n try:\n dicts = cloud_data.get('clusters', {})[0].get('config', {}).get('clickhouse', {}).get('config', {}).get('effectiveConfig', {}).get('dictionaries')\n except (AttributeError, IndexError):\n dicts = []\n return [d.get('name') for d in dicts] #список имен словарей на клике\n\n def _get_json_files(self):\n path = os.path.join(self.refs.work_dir, '*.json')\n files = glob.glob(path)\n jsons = []\n for f in files:\n with open(f, 'r') as _f:\n data = _f.read()\n jsons.append(json.loads(data))\n return jsons\n\n def _gen_tasks(self):\n j_datas = self._get_json_files() # данные из json-файлов\n c_names = self._parse_cloud_data() # имена словарей на сервере\n j_names = [n.get('externalDictionary').get('name') for n in j_datas] # имена словарей из json файлов\n for c_name in c_names:\n # если имени нет в файлах - добавляем задание на удаление словаря из кластера\n if not c_name in j_names:\n self.tasks.append({\n 'method': 'deleteExternalDictionary',\n 'payload': {\n \"externalDictionaryName\": c_name\n }\n })\n for i, j_name in enumerate(j_names):\n # еслли нет в именах в кластере - добавляем задание на добавление словаря\n if not j_name in c_names:\n self.tasks.append({\n 'method': 'createExternalDictionary',\n 'payload': j_datas[i]\n })\n\n def process(self):\n try:\n while len(self.tasks) > 0:\n task = self.tasks.pop()\n request = self._NewRequest(self.refs.url_api, self.auth)\n answer = request(json.dumps(task['payload']).encode(), '/managed-clickhouse/v1/clusters/{clusterId}:{method}'.format(clusterId=self.refs.clusterId, method=task['method']))\n self._print(answer, flush=True)\n request.close()\n except:\n raise ApplicationException(f\"ProcessTasks ERROR: {traceback.format_exc()}\")\n\n\ndef start(*args, **kwargs):\n \n y = YAPI(*args, **kwargs)\n y.process()\n\nif __name__ == '__main__':\n start()\n\n\n","sub_path":"yandex_ch/libs/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":7512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"219403984","text":"#Hi there, Can you see this\nimport numpy as np\nimport tensorflow as tf\nfrom numpy import load\nimport operator\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport os,sys,inspect\nsys.path.insert(1, os.path.join(sys.path[0], '..')) #this line shold always stay above the next line below\nfrom tfrbm import BBRBM, GBRBM\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\n#load the mnist data\nmnist = input_data.read_data_sets('MNIST_data/', one_hot=True)\nmnist_images = mnist.train.images\nmnist_images1= np.where(mnist_images > 0, 1, 0)\n\n#helper fcts\ndef pad_with(vector, pad_width, iaxis, kwargs): #https://numpy.org/doc/stable/reference/generated/numpy.pad.html\n pad_value = kwargs.get('padder', 10)\n vector[:pad_width[0]] = pad_value\n vector[-pad_width[1]:] = pad_value\n\ndef show_digit(x,y):\n plt.imshow(x)#,cmap = plt.cm.binary)\n plt.colorbar(mappable=None, cax=None, ax=None)\n plt.title(y)\n #plt.locator_params(axis=\"x\", nbins=30)\n plt.locator_params(axis=\"y\", nbins=30)\n plt.show()\n\n#labels pixels\naccu = [0]\nn_data = 1000#mnist_images1.shape[0]\nprint(\"accuracy\",accu)\nt1 = np.zeros(10)\n#for loop to add one-hot labels to the images as pixels\nmnist_labeled = np.zeros(794000) #create empty array for the new images\nmnist_labeled = mnist_labeled.reshape(1000,794) #reshape it (2D)\nfor i in range(n_data-1):\n #b =mnist_images1[i]#.reshape(28, 28)#add contour of zeros around the image\n #x = np.where(mnist.train.labels[i] == 1)\n b = np.concatenate((t1, mnist_images1[i]), axis=0)\n #b[x,0] = 1 # add the label coressponding to the image on the right most clolumn [0..10]\n mnist_labeled[i] = b#.flatten() #convert the image to 1D and store it\n#test to see if corretly added labels\n#show_digit(mnist_labeled[5].reshape(28,28),\"test for new dim\")#new_image.reshape(29,29)\n\n\nprint(\"minist test size\",mnist_images1.shape)\n#create the BM\nbbrbm = BBRBM(n_visible=794, n_hidden=64, learning_rate=0.01, momentum=0.95, use_tqdm=True)\n\n#load the saved weights\nfilename = 'weights_class3'\nname = 'bbrbm_class3'\nbbrbm.load_weights(filename,name)\n\n\n\ndef cropND(img, bounding):\n start = tuple(map(lambda a, da: a//2-da//2, img.shape, bounding))\n end = tuple(map(operator.add, start, bounding))\n slices = tuple(map(slice, start, end))\n return img[slices]\n\n#Test the Reconstruction of the RBM\nIMAGE = 20#26, 31 works well (which is a 6)\n#image = mnist_images1[IMAGE]\n\nmask_a_or =np.ones(784)\nmask_c_or =np.zeros(784)\n#prepare first mask\nmask_bb = mask_a_or\nmask_bb = mask_bb.reshape(28,28)\nmask_bb = mask_bb[0:18,0:28] #change 16 to lower number to clamp smaller area\nmask_b = np.pad(mask_bb, [(0,10), (0,0)], mode='constant')\n#show_digit(mask_b.reshape(28, 28), \"Mask B\")\n#prepare second mask\nmask_cc = mask_c_or\nmask_cc = mask_cc.reshape(28,28)\nmask_cc = mask_cc[0:18,0:28]\nmask_c = np.pad(mask_cc, [(0, 10), (0, 0)], mode='constant', constant_values=1)\n#show_digit(mask_c.reshape(28, 28), \"Mask C\")\n#crop the imag\n#crop dimentions\nprint('size of mask b',mask_b.size)\n\nprint('size of mask c', mask_c.size)\n\n\n#reconstruct\n\n#first run\nfname = [\"1-3\",\"2-3\",\"3-3\",\"4-3\",\"5-3\",\"6-3\",\"7-3\",\"8-3\",\"9-3\",\"10-3\",\"11-3\",\"12-3\",\"13-3\",\"14-3\",\"15-3\",\"16-3\",\"17-3\",\"18-3\",\"19-3\",\"20-3\"]\n#n_data = mnist_images1.shape[0]\nprint(\"number of images\", n_data)\n#random image for testing\n#random_image = np.random.uniform(0,1,784)\n#image_rec_bin = np.greater(random_image, np.random.uniform(0,1,784))\n#random_image = image_rec_bin.astype( int)\nfor j in range(n_data-1):\n #random_image = np.random.uniform(0, 1, 784)\n #image_rec_bin = np.greater(random_image, np.random.uniform(0, 1, 784))\n #random_image = image_rec_bin.astype(int)\n\n #print(j)\n image = mnist_images1[j]\n #show_digit(image.reshape(28, 28), \"Original image\")\n #print(\"image label\",mnist.test.labels[j])\n a = image.reshape(28,28)\n c = image.reshape(28, 28)\n #show_digit(image.reshape(28,28))\n # img = a[0:16,0:28] #crop the image\n img = a * mask_b\n\n img = np.concatenate((t1, img.flatten()), axis=0)\n img_org = img\n #print(\"shape of of org img\", img_org.shape)\n #imga = random_image#imga = img\n #show_digit(img_org[10:794].reshape(28,28),\"croped input\")\n #reconstruct image for N-MC\n for i in range(100):\n image_rec1 = bbrbm.reconstruct(img.reshape(1,-1))\n #print(\"shape of of rec1\",image_rec1.shape)\n image_rec1 = image_rec1.reshape(794,)\n #print(\"new shape of of rec1\", image_rec1.shape)\n rec_backup = image_rec1\n image_rec1 = image_rec1[10:794].reshape(28,28 )\n #print(\"size ofa\", a.size)\n img= img_org + np.concatenate((t1, (image_rec1 * mask_c).flatten()), axis=0)\n #show_digit(image_rec1.reshape(30, 30), \"returned image\")\n #show_digit(img.reshape(30, 30), \"image to be fed\")\n\n\n #print the result of construction\n # create figure\n # check if the reconstructed label matches the correct label\n #compare rec_backup[0:10] to mnist.test.labels[j]\n a1 = rec_backup[0:10]\n a2 = mnist.test.labels[j]\n a3 = np.where(a2 == True)\n a4 = list(a3)\n #print(\"org label position\" , a3[0])\n # print(\"recondtructed label at orig position\", a1[a3[0]])\n if(a1[a3[0]] == 1):\n accu[0] = accu[0] + 1\n #a = np.array_equal(rec_backup[0:10], mnist.test.labels[j])\n #print(\"org image label\", mnist.train.labels[j])\n #print(\"reconstructed image label\", rec_backup[0:10])\n\n\n #print(\"accu \", accu)\n #print(\"a of labels result \", a)\n #fig = plt.figure(figsize=(10, 10))\n\n # setting values to rows and column variables\n \"\"\"\n rows = 2\n columns = 1\n fig.add_subplot(rows, columns, 2)\n plt.imshow(img[10:794].reshape(28, 28)) # new_image.reshape(29,29)\n plt.title(\"Reconstructed Image after %i Iterations\" %i)\n fig.add_subplot(rows, columns, 1)\n plt.imshow(rec_backup[0:10].reshape(1, -1))\n plt.title(\"Labels\")\n plt.locator_params(axis=\"x\", nbins=10)\n\n #save figure\n plt.savefig(fname[j], dpi=None, facecolor='w', edgecolor='w',\n orientation='portrait', papertype=None, format=None,\n transparent=False, bbox_inches=None, pad_inches=0.1,\n frameon=None, metadata=None)\n # plt.show()\n plt.close()\n #plt.show()\n \"\"\"\nprint(\"accu \", accu)\naccuracy = accu[0]/n_data\nprint(\"accuracy \",accuracy )\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tfrbm/rbm_classif_test2.py","file_name":"rbm_classif_test2.py","file_ext":"py","file_size_in_byte":6356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"528324742","text":"# 0416.py\r\nimport cv2\r\nimport numpy as np\r\n\r\nsrc = cv2.imread('../data/lena.jpg')\r\n\r\nrows, cols, channels = src.shape\r\nM1 = cv2.getRotationMatrix2D( (rows/2, cols/2), 45, 0.5 )\r\nM2 = cv2.getRotationMatrix2D( (rows/2, cols/2), -45, 1.0 )\r\n# 회전에서 -θ는 반대방향으로 세타(θ)만큼 회전을 의미,\r\n# -부호는 반대방향을 의미한다.\r\n\r\n#dst1 = cv2.warpAffine( src, M1, (rows, cols))\r\n#dst2 = cv2.warpAffine( src, M2, (rows, cols))\r\n\r\n#cv2.imshow('dst1', dst1)\r\n#cv2.imshow('dst2', dst2)\r\n\r\n\r\n#Horizontal 대칭\r\n#src_points=np.float32([[0,0],[cols-1,0],[0,rows-1]])#[x,y]\r\n#dst_points=np.float32([[cols-1,0],[0,0],[cols-1,rows-1]])\r\n\r\n\r\n#Vertical\r\n#src_points=np.float32([[0,0],[cols-1,0],[0,rows-1]])#[x,y]\r\n#dst_points=np.float32([[0,rows-1],[cols-1,rows-1],[0,0]])\r\n\r\n\r\n#affineM=cv2.getAffineTransform(src_points,dst_points)\r\n#img_sym=cv2.warpAffine(src,affineM,(cols,rows))\r\n\r\n\r\nsrc_points = np.float32([[0,0], [0,rows-1], [cols/2,0],[cols/2,rows-1]])\r\n#dst_points = np.float32([[0,50], [0,rows-51], [cols/2,0],[cols/2,rows-1]])\r\ndst_points = np.float32([[0,100], [0,rows-51], [cols/2,0],[cols/2,rows-1]]) #조금더 찌그러지게..\r\n\r\naffineM=cv2.getPerspectiveTransform(src_points,dst_points)\r\nimg_sym=cv2.warpPerspective(src,affineM,(cols,rows))\r\n\r\n\r\ncv2.imshow('dst3', img_sym)\r\n\r\ncv2.waitKey() \r\ncv2.destroyAllWindows()\r\n","sub_path":"기하학적처리/0416.py","file_name":"0416.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"130808830","text":"\"\"\"\nmerge sort implemented in python\n\"\"\"\n\n\ndef merge(A, p, q, r):\n # copy of sorted subarrays\n L = A[p:q+1]\n R = A[q+1:r+1]\n # add a sentinel value at the end of the array\n L.append(float('inf'))\n R.append(float('inf'))\n # merge the sorted subarrays\n i, j = 0, 0\n for k in range(p, r+1):\n if L[i] < R[j]:\n A[k] = L[i]\n i += 1\n else:\n A[k] = R[j]\n j += 1\n\n\ndef merge_sort(A, p, r):\n if p < r:\n q = (p + r) // 2 # bisection the array\n # sort subarrays\n merge_sort(A, p, q)\n merge_sort(A, q+1, r)\n # merge sorted subarrays\n merge(A, p, q, r)\n\n\nif __name__ == '__main__':\n lst = [1, 3, 5, 2, 4, 6]\n print(lst)\n\n merge_sort(lst, 0, len(lst)-1)\n print(lst)\n","sub_path":"mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"241085756","text":"# Copyright (c) 2021, NVIDIA CORPORATION. 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\nimport io\nimport warnings\n\nfrom .homoglyphs import homoglyphs\nfrom .replacements import replacements\n\n\n_replacements = {uni: asc for uni, asc in replacements}\n_homoglyphs = {g: asc for asc, glyphs in homoglyphs.items() for g in glyphs}\n\n\ndef unidecoder(s, homoglyphs=False):\n \"\"\"Transliterate unicode\n\n Args:\n s (str): unicode string\n homoglyphs (bool): prioritize translating to homoglyphs\n \"\"\"\n warned = False # Once per utterance\n ret = ''\n for u in s:\n if ord(u) < 127:\n a = u\n elif homoglyphs:\n a = _homoglyphs.get(u, _replacements.get(u, None))\n else:\n a = _replacements.get(u, _homoglyphs.get(u, None))\n\n if a is None:\n if not warned:\n warnings.warn(f'Unexpected character {u}: '\n 'please revise your text cleaning rules.',\n stacklevel=10**6)\n warned = True\n else:\n ret += a\n\n return ret\n","sub_path":"PyTorch/SpeechSynthesis/Tacotron2/tacotron2/text/unidecoder/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"454369422","text":"import re\r\n\r\n\"\"\" \r\n API to maintains the cache of trap mapping\r\n\"\"\"\r\n\r\ndef get_trap_map_entry_from_file(file_path):\r\n entry_pattern = r'((?:[1-9][0-9]{0,3}|0)(?:\\.(?:[1-9][0-9]*|0)){5,13})'\\\r\n r'\\s+'\\\r\n r'([\\w-]+)'\r\n entry_re = re.compile(entry_pattern, re.MULTILINE)\r\n with open(file_path) as f:\r\n for entry in entry_re.findall(f.read()):\r\n yield entry\r\n\r\nif __name__ == '__main__':\r\n for entry in get_trap_map_entry('trap_map'):\r\n print(entry)","sub_path":"Spectrum/Event_subsystem/trapmaps.py","file_name":"trapmaps.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"157285738","text":"\n\ndef get_ospf_dict(self):\n ' get one ospf attributes dict.'\n ospf_info = dict()\n conf_str = (CE_NC_GET_OSPF % (self.process_id, self.get_area_ip(), self.interface))\n rcv_xml = get_nc_config(self.module, conf_str)\n if ('' in rcv_xml):\n return ospf_info\n xml_str = rcv_xml.replace('\\r', '').replace('\\n', '').replace('xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"', '').replace('xmlns=\"http://www.huawei.com/netconf/vrp\"', '')\n root = ElementTree.fromstring(xml_str)\n ospfsite = root.find('data/ospfv2/ospfv2comm/ospfSites/ospfSite')\n if (not ospfsite):\n self.module.fail_json(msg='Error: ospf process does not exist.')\n for site in ospfsite:\n if (site.tag in ['processId', 'routerId', 'vrfName']):\n ospf_info[site.tag] = site.text\n ospf_info['areaId'] = ''\n areas = root.find('data/ospfv2/ospfv2comm/ospfSites/ospfSite/areas/area')\n if areas:\n for area in areas:\n if (area.tag == 'areaId'):\n ospf_info['areaId'] = area.text\n break\n ospf_info['interface'] = dict()\n intf = root.find('data/ospfv2/ospfv2comm/ospfSites/ospfSite/areas/area/interfaces/interface')\n if intf:\n for attr in intf:\n if (attr.tag in ['ifName', 'networkType', 'helloInterval', 'deadInterval', 'silentEnable', 'configCost', 'authenticationMode', 'authTextSimple', 'keyId', 'authTextMd5']):\n ospf_info['interface'][attr.tag] = attr.text\n return ospf_info\n","sub_path":"Data Set/bug-fixing-2/b93411a5b24db638efa149dd5ae0db68df2b0cb3--bug.py","file_name":"b93411a5b24db638efa149dd5ae0db68df2b0cb3--bug.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"275258118","text":"import requests\nfrom bs4 import BeautifulSoup\nimport numpy as np\nimport pandas as pd\nimport sys\nimport re\nimport time\n\n\nclass exc(Exception):\n def __init__(self, i):\n self.i = i\n\n def __str__(self):\n return f'自定義例外:{self.i}'\n\n\ndef get_html(url, headers):\n num_retry = 0 # 設定初始重試次數\n max_retry = 3 # 最大重試次數3次\n try:\n while num_retry <= max_retry:\n r = requests.get(url, headers=headers)\n if r.status_code == requests.codes.ok: # 是否成功請求網頁\n print('request success: %s' % url)\n return r\n else:\n time.sleep(3)\n if num_retry == max_retry: # 當重試三次後丟出錯誤\n raise exc(url)\n print('retrying request')\n num_retry += 1\n except exc:\n print(exc)\n # 超過請求次數印出 http request eror 並將錯誤丟出function外\n print('http request error: %s' % url)\n raise\n except:\n # 出現意料之外的錯誤時印出錯誤並將錯誤丟出function外\n print('Unexcepted error: %s' % url, sys.exc_info())\n raise\n\n\ndef parse_html(r):\n soup = BeautifulSoup(r.text, 'lxml')\n if soup != None:\n print('parsing success') # 印出成功解析網頁名\n return soup\n else:\n # 當beautifulsoup解析失敗為Nonetype時,將錯誤丟出function外\n raise Exception('parse_error')\n\n\ndef equipment_crawl(soup):\n\n list1 = []\n\n equ1 = soup1.find(class_='buyCarDetailContentSpec').find_all('li')\n\n for x in equ1:\n list1.append(x.text.strip())\n\n list2 = list1[:-6]\n\n arr = np.array(list2)\n\n dfequ = pd.DataFrame(\n np.zeros(shape=(1, len(list2)), dtype=int), columns=arr)\n for y in equ1[:-6]:\n try:\n e = y.text.strip()\n class_type = None\n class_type = y.get('class')[0]\n if class_type == 'specChecked':\n dfequ[e] = 1\n except IndexError:\n continue\n\n return dfequ\n\n\ndef dealer_address_crawl(soup):\n try:\n dealer_info = soup1.find(\n 'div', class_='buyCarDetailContentDealerContact').find_all('p')\n dealer_address = None\n for p in dealer_info:\n address = re.search('地址', p.text)\n if address:\n dealer_address = p.text.split(':')[1].strip()\n return dealer_address\n except:\n print('dealer_address parse error')\n return None\n\n\ndef verified_crawl(soup):\n carVerified = soup1.find(\n 'div', class_='buyCarDetailTitleTextBadge').find_all('li')\n\n dfver = pd.DataFrame(np.zeros(shape=(1, 5), dtype=int), columns=[\n '三大保證', '非計程車', '四大保固', '里程保證', 'YES認證'])\n\n for x in carVerified:\n v = x.text.strip()\n class_type = None\n\n try:\n class_type = x.get('class')[1]\n if class_type == 'carConditionActive':\n dfver[v] = 1\n except IndexError:\n continue\n\n return dfver\n\n\ndf1 = pd.DataFrame(columns=['id', 'car_brand', 'car_model', 'car_address', 'car_title', 'dealer_name'])\n\nfor page in range(1, 340):\n\n sum_url = f'https://www.sum.com.tw/carsearchlist.php?v=3&ctp_prt=&price1=0&price2=220&yearrange=&cararea=&carregion=&cartype=&carcolor=&brand=&model=&year1=&year2=&doors=&q=&show_type=&carrecommend=&comp_goldstore=&discount=&cc1=&cc2=&protection=&carvr=&page=&sort=&sortpage1=&gclid=&priceRange1=&priceRange2=&wd=&_de=0.5690229095899482&page={page}'\n\n headers = {\n 'Host': 'www.sum.com.tw',\n 'Connection': 'keep-alive',\n 'Accept': 'text/plain, */*; q=0.01',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36',\n 'Cookie': 'PHPSESSID=qn203skntjuv8bkevorgrhg5g7; _gcl_au=1.1.1197458183.1624031200; _ga=GA1.3.849228594.1624031200; __auc=38660c2a17a1fcd839cb333ad40; _hjTLDTest=1; _hjid=13961593-1974-490c-8e9b-f0726e39cde0; _fbp=fb.2.1624031200855.1701953032; _gid=GA1.3.966926215.1624256678; _TUCI_T=sessionNumber+18799&pageView+18799; Tagtoo_pta=pta_03+_<a+_tm^3Ad1056_; __asc=c83520af17a2d7bcacaaa8c8958; _TUCS=1; _TUCI=sessionNumber+2498&ECId+155&hostname+www.sum.com.tw&pageView+7493',\n }\n try:\n soup = parse_html(get_html(sum_url, headers=headers))\n except:\n print('HTTP_error')\n print(sys.exc_info())\n continue\n try:\n seo_list = soup.find_all('li', class_='seo_list')\n except:\n print(f'Parsing Error: {page}')\n\n list1 = []\n\n for li in seo_list:\n try:\n idnum = li.get('data-seo_name')\n\n car_info = li.find('h3').a.text.split('|')\n\n car_brand = car_info[0].split(' ', 1)[0]\n\n car_model = car_info[0].split(' ', 1)[1]\n\n car_address = li.find('ul').find_next_sibling().find('li').text\n\n car_title = li.find('div', class_='carCondition').h3.text.strip()\n\n car_dealer = li.find('ul').find_next_sibling().find(\n 'li').find_next_sibling().text\n\n df1 = df1.append({'id': idnum, 'car_brand': car_brand, 'car_model': car_model,\n 'car_address': car_address, 'car_title': car_title, 'dealer_name': car_dealer}, ignore_index=True)\n except:\n print(f'data-seo_name parsing error: {page}')\n continue\n\ndf1.to_csv('sum_car_first.csv', encoding = 'utf-8-sig')\n\ndf_xxx = pd.DataFrame()\n\nfor id_nu in df1['id']:\n url_in = f'https://www.sum.com.tw/carinfo-{id_nu}.php'\n print('-----------------------------start parsing new page---------------------------------')\n headers = {\n 'Host': 'www.sum.com.tw',\n 'Connection': 'keep-alive',\n 'Accept': 'text/plain, */*; q=0.01',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36',\n 'Cookie': 'PHPSESSID=qn203skntjuv8bkevorgrhg5g7; _gcl_au=1.1.1197458183.1624031200; _ga=GA1.3.849228594.1624031200; __auc=38660c2a17a1fcd839cb333ad40; _hjTLDTest=1; _hjid=13961593-1974-490c-8e9b-f0726e39cde0; _fbp=fb.2.1624031200855.1701953032; _gid=GA1.3.966926215.1624256678; _TUCI_T=sessionNumber+18799&pageView+18799; Tagtoo_pta=pta_03+_<a+_tm^3Ad1056_; __asc=c83520af17a2d7bcacaaa8c8958; _TUCS=1; _TUCI=sessionNumber+2498&ECId+155&hostname+www.sum.com.tw&pageView+7493',\n }\n\n try:\n soup1 = parse_html(get_html(url_in, headers=headers))\n except:\n print('HTTP_error')\n print(sys.exc_info())\n continue\n try:\n carPrice = soup1.find('div', class_='buyCarDetailTitleTextPrice')\n car_price = carPrice.find('b').text\n except:\n print(f'car_price parsing error:{id_nu}')\n car_price = None\n pass\n try:\n dfver = verified_crawl(soup1)\n\n carDetail = soup1.find('div', class_='buyCarDetailTitleTextContent')\n\n photo_url = soup1.find('div', class_='buyCarDetailTitleImg').text\n\n info = carDetail.div.find_next_siblings()\n except:\n print(f'car photo or detail parsing error: {id_nu}')\n pass\n\n info_list = []\n \n try:\n for sp in info:\n info_list.append(sp.span.text.strip())\n except AttributeError:\n pass\n except:\n print(f'Unexpected error: {id_nu}')\n continue\n dealer_address = dealer_address_crawl(soup1)\n\n dfequ = equipment_crawl(soup1)\n\n car_year = info_list[0]\n\n car_cylinderVolumn = info_list[1]\n\n car_color = info_list[2]\n\n car_gearType = info_list[3]\n\n car_driveMode = info_list[4]\n\n car_fuel = info_list[5]\n\n car_mileage = info_list[6]\n\n car_door = info_list[7]\n\n car_seat = info_list[8]\n\n df2 = pd.DataFrame(columns=['id', 'car_mileage', 'car_year', 'car_price', 'car_cylinderVolumn', 'car_color', 'car_gearType',\n 'car_dirveMode', 'car_fuel', 'car_door', 'car_seat', 'dealer_address'])\n \n df2 = df2.append({'id': id_nu, 'car_mileage': car_mileage, 'car_year': car_year, 'car_price': car_price,\n 'car_cylinderVolumn': car_cylinderVolumn, 'car_color': car_color, 'car_gearType': car_gearType,\n 'car_dirveMode': car_driveMode, 'car_fuel': car_fuel, 'car_door': car_door, 'car_seat': car_seat, 'dealer_address': dealer_address}, ignore_index=True)\n\n df_temp = pd.concat([df2, dfequ, dfver], axis=1)\n \n df_xxx = df_xxx.append(df_temp)\n\ndf_final = df1.merge(df_xxx, on='id')\n\ndf_final.to_csv('Sum_car_0707.csv', encoding='utf-8-sig')\n\n","sub_path":"crawler_code/sum_car.py","file_name":"sum_car.py","file_ext":"py","file_size_in_byte":8710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"308622062","text":"from typing import List, Tuple\nimport unittest\nimport numpy as np\n\nfrom .test_utils import get_img_from_filename, url_to_img\nfrom ..facedetection.bounding_box import BoundingBox\nfrom ..facedetection.faced import FacedDetector\nfrom ..facedetection.face_detection_results import FaceDetectionResults\nfrom ..facedetection.face_detection_status import FaceDetectionStatus\nfrom ..facedetection.image_face_detector import ImageFaceDetector\nfrom ..entities.keyframe import KeyFrame\n\n\nclass TestFacedDetector(unittest.TestCase):\n\n def setUp(self):\n self.non_rgb_input_url: str = 'https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Checkerboard_pattern.svg/1200px-Checkerboard_pattern.svg.png'\n self.valid_input_path: str = 'resources/faced.jpg'\n\n self.valid_input_img: np.array = get_img_from_filename(self.valid_input_path)\n self.non_rgb_input_img: np.ndarray = url_to_img(self.non_rgb_input_url)\n\n self.dummy_video_id = \"dummy_video_id\"\n self.dummy_keyframe_id = \"dummy_keyframe_id\"\n\n self.epsilon: float = 0.0001\n self.faced_detector: ImageFaceDetector = FacedDetector(minimum_confidence = 0.9, \n offset_value = 20,\n pad_value=10)\n\n def test_non_rgb_input_status(self):\n keyframe = KeyFrame(self.non_rgb_input_img)\n keyframe.video_id = self.dummy_video_id\n keyframe.keyframe_id = self.dummy_keyframe_id\n detection_result: FaceDetectionResults = self.faced_detector.detect(keyframe)\n expected_status: FaceDetectionStatus = FaceDetectionStatus.FAIL_NON_RGB_INPUT\n self.assertEqual(detection_result.status, expected_status)\n\n def test_non_rgb_input_bboxes(self):\n keyframe = KeyFrame(self.non_rgb_input_img)\n keyframe.video_id = self.dummy_video_id\n keyframe.keyframe_id = self.dummy_keyframe_id\n detection_result: FaceDetectionResults = self.faced_detector.detect(keyframe)\n expected_detected_faces = None\n self.assertEqual(detection_result.detected_faces, expected_detected_faces)\n\n def test_valid_input_status(self):\n keyframe = KeyFrame(self.valid_input_img)\n keyframe.video_id = self.dummy_video_id\n keyframe.keyframe_id = self.dummy_keyframe_id\n detection_result: FaceDetectionResults = self.faced_detector.detect(keyframe)\n expected_status: FaceDetectionStatus = FaceDetectionStatus.SUCCESS\n self.assertEqual(detection_result.status, expected_status)\n \n def test_valid_input_bboxes(self):\n keyframe = KeyFrame(self.valid_input_img)\n keyframe.video_id = self.dummy_video_id\n keyframe.keyframe_id = self.dummy_keyframe_id\n detection_result: FaceDetectionResults = self.faced_detector.detect(keyframe)\n\n expected_bboxes: List[BoundingBox] = [BoundingBox((84, 154, 162, 238), 0.9987294),\n BoundingBox((186, 187, 268, 271), 0.9990884),\n BoundingBox((291, 202, 363, 282), 0.9980178),\n BoundingBox((374, 186, 446, 272), 0.99325585),\n BoundingBox((485, 183, 561, 265), 0.9943262)]\n\n self.assertEqual(len(expected_bboxes), len(detection_result.detected_faces))\n \n for i in range(len(expected_bboxes)):\n self.assertEqual(detection_result.detected_faces[i].bbox.coordinates, expected_bboxes[i].coordinates)\n\n for i in range(len(expected_bboxes)):\n actual_conf = detection_result.detected_faces[i].bbox.confidence\n expected_conf = expected_bboxes[i].confidence\n self.assertAlmostEqual(actual_conf, expected_conf, delta = self.epsilon)\n\n\n def test_valid_input_cropped_faces(self):\n keyframe = KeyFrame(self.valid_input_img)\n keyframe.video_id = self.dummy_video_id\n keyframe.keyframe_id = self.dummy_keyframe_id\n detection_result: FaceDetectionResults = self.faced_detector.detect(keyframe)\n\n expected_bboxes: List[BoundingBox] = [BoundingBox((84, 154, 162, 238), 0.9987294),\n BoundingBox((186, 187, 268, 271), 0.9990884),\n BoundingBox((291, 202, 363, 282), 0.9980178),\n BoundingBox((374, 186, 446, 272), 0.99325585),\n BoundingBox((485, 183, 561, 265), 0.9943262)]\n \n def get_shape(bbox: BoundingBox) -> Tuple[(int, int, int)]:\n (x_upperleft, y_upperleft, x_lowerright, y_lowerright) = bbox.coordinates\n return (y_lowerright - y_upperleft + 1, x_lowerright - x_upperleft + 1, 3)\n expected_shapes: List[Tuple[(int, int, int)]] = list(map(get_shape, expected_bboxes))\n\n self.assertEqual(len(expected_shapes), len(detection_result.detected_faces))\n\n for i, _ in enumerate(expected_shapes):\n self.assertEqual(detection_result.detected_faces[i].image.shape, expected_shapes[i])\n \nif __name__ == '__main__':\n unittest.main()\n ","sub_path":"vynd_api/test/test_faced_detector.py","file_name":"test_faced_detector.py","file_ext":"py","file_size_in_byte":5260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"379497828","text":"\"\"\"\n\n8. Write a Python function that takes a values of words and returns the length of the longest one.\n\n\"\"\"\n\nword_1 = \"testing\"\nword_2 = \"test\"\n\nif len(word_1) > len(word_2):\n print(word_1)\nelse:\n print(word_2)\n","sub_path":"w3_strings/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"60899021","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom . import Dataset\nfrom deepy.utils import FakeGenerator, StreamPickler, global_rand\n\nimport logging as loggers\nlogging = loggers.getLogger(__name__)\n\nclass OnDiskDataset(Dataset):\n \"\"\"\n Load large on-disk dataset.\n The data should be dumped with deepy.utils.StreamPickler.\n You must convert the data to mini-batches before dump it to a file.\n \"\"\"\n\n def __init__(self, train_path, valid_path=None, test_path=None, train_size=None,\n cached=False, post_processing=None, shuffle_memory=False, curriculum=None):\n self._train_path = train_path\n self._valid_path = valid_path\n self._test_path = test_path\n self._train_size = train_size\n self._cache_on_memory = cached\n self._cached_train_data = None\n self._post_processing = post_processing if post_processing else lambda x: x\n self._shuffle_memory = shuffle_memory\n self._curriculum = curriculum\n self._curriculum_count = 0\n if curriculum and not callable(curriculum):\n raise Exception(\"curriculum function must be callable\")\n if curriculum and not cached:\n raise Exception(\"curriculum learning needs training data to be cached\")\n if self._cache_on_memory:\n logging.info(\"Cache on memory\")\n self._cached_train_data = list(map(self._post_processing, StreamPickler.load(open(self._train_path))))\n self._train_size = len(self._cached_train_data)\n if self._shuffle_memory:\n logging.info(\"Shuffle on-memory data\")\n global_rand.shuffle(self._cached_train_data)\n\n def curriculum_train_data(self):\n self._curriculum_count += 1\n logging.info(\"curriculum learning: round {}\".format(self._curriculum_count))\n return self._curriculum(self._cached_train_data, self._curriculum_count)\n\n def generate_train_data(self):\n for data in StreamPickler.load(open(self._train_path)):\n yield self._post_processing(data)\n\n def generate_valid_data(self):\n for data in StreamPickler.load(open(self._valid_path)):\n yield self._post_processing(data)\n\n def generate_test_data(self):\n for data in StreamPickler.load(open(self._test_path)):\n yield self._post_processing(data)\n\n def train_set(self):\n if self._cache_on_memory:\n if self._curriculum:\n return FakeGenerator(self, \"curriculum_train_data\")\n else:\n return self._cached_train_data\n if not self._train_path:\n return None\n return FakeGenerator(self, \"generate_train_data\")\n\n def valid_set(self):\n if not self._valid_path:\n return None\n return FakeGenerator(self, \"generate_valid_data\")\n\n def test_set(self):\n if not self._test_path:\n return None\n return FakeGenerator(self, \"generate_test_data\")\n\n def train_size(self):\n return self._train_size\n","sub_path":"deepy/dataset/ondisk_dataset.py","file_name":"ondisk_dataset.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"297935493","text":"import pygame\nfrom random import randint\nimport time\nclass Object:\n def __init__(self,x1,y1,obst,screen,colour):\n self.x1=x1\n self.y1=y1\n self.obst=obst\n self.colour=colour\n self.screen=screen\n def print_obj(self):\n pass\nclass Triangle(Object):\n def __init__(self,x1,y1,obst,price,dimension,screen,colour):\n Object.__init__(self,x1,y1,obst,screen,colour)\n self.x2=x1+dimension\n self.y2=y1\n self.x3=x1+(dimension/2)\n self.y3=y1+dimension\n self.price=price\n\n def print_obj(self):\n return(pygame.draw.polygon(self.screen,self.colour,((self.x1,self.y1),(self.x2,self.y2),(self.x3,self.y3))))\nclass Quadrilater(Object):\n def __init__(self,x1,y1,obst,price,dimension,screen,colour):\n Object.__init__(self,x1,y1,obst,screen,colour)\n self.price=price\n def print_obj(self):\n pass\nclass Square(Quadrilater):\n def __init__(self,x1,y1,obst,price,dimension,screen,colour):\n Quadrilater.__init__(self,x1,y1,obst,price,dimension,screen,colour)\n self.heigth=dimension\n self.weight=dimension\n def print_obj(self):\n return(pygame.draw.rect(self.screen,self.colour,(self.x1,self.y1,self.heigth,self.weight)))\nclass Rectangle(Quadrilater):\n def __init__(self,x1,y1,obst,price,dimension,screen,colour):\n Quadrilater.__init__(self,x1,y1,obst,price,dimension,screen,colour)\n self.heigth=dimension+15\n self.weight=dimension\n def print_obj(self):\n return(pygame.draw.rect(self.screen,self.colour,(self.x1,self.y1,self.heigth,self.weight)))\nclass Circle(Object):\n def __init__(self,x1,y1,obst,dimension,screen,colour):\n Object.__init__(self,x1,y1,obst,screen,colour)\n self.diameter=dimension\n def print_obj(self):\n return(pygame.draw.circle(self.screen,self.colour,(self.x1,self.y1),self.diameter))\n\n##pygame.init()\n##green=(0,190,0)\n##red=(200,0,0)\n##blue=(63,72,204)\n##bright_red=(255,0,0)\n##bright_green=(0,255,0)\n##display_width=1266\n##display_height=650\n##white=(255,255,255)\n##yellow=(254,216,1)\n##black=(0,0,0)\n##gameDisplay=pygame.display.set_mode((display_width,display_height))\n\ndef random_object_generator(nr):\n rand_obst=randint(3,4)\n while rand_obst!=0:\n \n occupied_x=[]\n occupied_y=[]\n rand_x=randint(0,970)\n rand_dimension=randint(10,30)\n rand_y=randint(0,620)\n if (rand_x not in occupied_x)and (rand_y not in occupied_y):\n ob4=Circle(rand_x,rand_y,True,rand_dimension,gameDisplay,yellow)\n for i in range(rand_x,rand_x+rand_dimension):\n occupied_x.append(i)\n for i in range(rand_y,rand_y+rand_dimension):\n occupied_y.append(i)\n ob4.print_obj()\n rand_obst=rand_obst-1\n \n while nr!=0:\n rand_x=randint(0,970)\n rand_dimension=randint(10,30)\n rand_y=randint(0,620)\n rand_shape=randint(1,3)\n rand_colour=randint(1,3)\n colours={1:red,2:blue,3:green}\n if (rand_x not in occupied_x)and (rand_y not in occupied_y):\n if rand_shape==1:\n ob1=Square(rand_x,rand_y,False,1,rand_dimension,gameDisplay,colours[rand_colour])\n for i in range(rand_x,rand_x+rand_dimension):\n occupied_x.append(i)\n for i in range(rand_y,rand_y+rand_dimension):\n occupied_y.append(i)\n ob1.print_obj()\n elif rand_shape==2:\n ob2=Rectangle(rand_x,rand_y,False,1,rand_dimension,gameDisplay,colours[rand_colour])\n for i in range(rand_x,rand_x+rand_dimension+15):\n occupied_x.append(i)\n for i in range(rand_y,rand_y+rand_dimension):\n occupied_y.append(i)\n ob2.print_obj()\n elif rand_shape==3:\n ob3=Triangle(rand_x,rand_y,False,1,rand_dimension,gameDisplay,colours[rand_colour])\n for i in range(rand_x,rand_x+rand_dimension):\n occupied_x.append(i)\n for i in range(rand_y,rand_y+rand_dimension):\n occupied_y.append(i)\n ob3.print_obj()\n nr=nr-1\n pygame.display.update()\n\n\n\ndef text_objects(text,font):\n black=(0,0,0)\n textSurface=font.render(text,True,black)\n return textSurface,textSurface.get_rect()\ndef button(x,y,img1,img,action=None):\n mouse=pygame.mouse.get_pos()\n click=pygame.mouse.get_pressed()\n \n if x+150>=mouse[0]>=x and y+80>=mouse[1]>y:\n gameDisplay.blit(img1,(x,y))\n if click[0]==1 and action!=None:\n if action==\"play\":\n spawn_ship()\n elif action==\"quit\":\n pygame.quit()\n quit()\n elif action==\"spawn\":\n game(x,y)\n \n else:\n gameDisplay.blit(img,(x,y)) \n\n\ndef message_display(text):\n\n largeText=pygame.font.Font('freesansbold.ttf',40)\n TextSurf,TextRect=text_objects(text,largeText)\n TextRect.center=((display_width/2),(display_height/2))\n gameDisplay.blit(TextSurf,TextRect)\n pygame.display.update()\ndef spawn_ship():\n exitW=False\n while not exitW:\n pygame.display.update()\n for event in pygame.event.get():\n if event.type==pygame.QUIT:\n pygame.quit()\n quit()\n background=pygame.image.load('space.jpg')\n gameDisplay.fill(white)\n gameDisplay.blit(background,(0,0))\n spawn=pygame.image.load('spawn.png')\n spawn1=pygame.image.load('spawn1.png')\n button(200,120,spawn1,spawn,\"spawn\")\n button(700,120,spawn1,spawn,\"spawn\")\n button(200,400,spawn1,spawn,\"spawn\")\n button(700,400,spawn1,spawn,\"spawn\")\n pygame.draw.rect(gameDisplay,white,[1000,0,5,650])\n\n pygame.display.update()\n\n\n\ndef game(x,y):\n exitGame=False\n background=pygame.image.load('space.jpg')\n gameDisplay.blit(background,(0,0))\n pygame.draw.rect(gameDisplay,white,[1000,0,5,700])\n while not exitGame:\n for event in pygame.event.get():\n if event.type==pygame.QUIT:\n pygame.quit()\n quit()\n random_object_generator(4)\n ship=pygame.image.load('ship.png')\n gameDisplay.blit(ship,(x+30,y+35))\n #head=pygame.transform.rotate(ship,270) if it goes to right\n exitGame=True\n pygame.display.update()\n time.sleep(5)\n\n\ndef runIntroWindow():\n\n exitWindow=False\n while not exitWindow:\n for event in pygame.event.get():\n if event.type==pygame.QUIT:\n pygame.quit()\n quit()\n \n startimg=pygame.image.load('start.png')\n startimg1=pygame.image.load('start1.png')\n quitimg=pygame.image.load('quit.png')\n quitimg1=pygame.image.load('quit1.png')\n message_display(\"Welcome to Space Hunter!\")\n button(400,350,startimg1,startimg,\"play\")\n button(760,350,quitimg1,quitimg,\"quit\")\n \n pygame.display.update()\npygame.init()\ngreen=(0,190,0)\nred=(200,0,0)\nblue=(63,72,204)\nbright_red=(255,0,0)\nbright_green=(0,255,0)\ndisplay_width=1266\ndisplay_height=650\nwhite=(255,255,255)\nyellow=(254,216,1)\nblack=(0,0,0)\ngameDisplay=pygame.display.set_mode((display_width,display_height))\n\npygame.display.set_caption('Space Hunter')\ngameDisplay.fill(white)\npygame.display.update()\nrunIntroWindow()\n\n\n \n\n \n \n \n","sub_path":"spawn_obj/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"128903696","text":"from django.shortcuts import render\nfrom .form import SongForm2\nfrom .chromogram import chromogram_f\n\ndef index(request):\n return render(request, \"index.html\")\n\ndef upload(request):\n in_form = SongForm2()\n context = {\n \"in_form\": in_form\n }\n return render(request, 'upload.html' , context)\n\ndef analyze(request):\n if request.method == \"POST\":\n f = SongForm2(request.POST)\n if(f.is_valid()):\n print(\"form: ok\")\n artist = f.cleaned_data['artist']\n title = f.cleaned_data['title']\n else:\n print(\"invalid form\")\n\n #nameOfFile = artist + '-' + title + '.wav'\n #print(nameOfFile)\n chords, timestamps, image_plot_name, nameOfFile = chromogram_f(artist, title)\n #print(chords, timestamps)\n results = {\n \"c\": chords,\n \"t\": timestamps,\n }\n args = {\n #\"f\": f,\n \"nameOfFile\": nameOfFile,\n \"r\": results,\n \"ipn\": image_plot_name\n }\n return render(request, 'analyze.html', args)\n return render(request, 'analyze.html')\n\ndef user_account(request):\n return render(request, \"user_account.html\")\n\ndef posts(request):\n return render(request, \"posts.html\")","sub_path":"backend/backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"272921006","text":"from typing import Dict\nimport numpy as np\nimport pygame\n\nimport park.diamond_square\nfrom park.sprite_tree import SpriteTree\n\n\nclass State:\n \"\"\"\n A State does all the bookkeeping for the state of the Park.\n grid_depth: This is the depth to run the symmetric dirt procedural generation\n pixel_size: Scales the park, so a higher pixel size makes it more \"zoomed in\"\n tick_speed: How many ticks per second the park will run for\n \"\"\"\n\n SIDE_SCREEN_WIDTH = 50\n BORDER = 2\n\n def __init__(self, grid_depth: int, pixel_size: int, tick_speed=60, sea_level=50):\n import park.park_util as pu\n from park.creatures.park_entity import ParkEntity\n\n # set all the boundary and scaling numbers\n self.grid_depth = grid_depth\n self.pixel_size = pixel_size\n self.tick_speed = tick_speed\n self.sea_level = sea_level\n self.grid_size = 2 ** grid_depth + 1 # Non-scaled length of one side of the park grid\n self.park_width = pixel_size * self.grid_size # width of the park grid scaled by pixel size\n self.park_height = pixel_size * self.grid_size # height of the park grid scaled by pixel size\n print(\"creating\", self.park_width, \"x\", self.park_height, \"park\")\n\n self.side_screen_width = pixel_size * self.SIDE_SCREEN_WIDTH\n self.border = pixel_size * self.BORDER\n\n # init all the pygame objects\n self.screen: pygame.Surface = pygame.display.set_mode(\n (self.park_width + self.side_screen_width + self.border,\n self.park_height))\n pygame.display.set_caption('P A R K')\n self.screen.fill(pu.PINK)\n\n self.park_screen: pygame.Surface = pygame.Surface((self.park_width, self.park_height))\n\n self.side_screen: pygame.Surface = pygame.Surface((self.side_screen_width, self.park_height))\n\n self.terrain_screen: pygame.Surface = pygame.Surface(self.park_screen.get_size())\n\n self.clock = pygame.time.Clock()\n\n # init all the state and tracking\n self.global_entities: Dict[int, ParkEntity] = {}\n self.global_sprite_counter = -1\n\n self.creature_tree = SpriteTree(self.global_entities)\n self.background_tree = SpriteTree(self.global_entities)\n\n # init the terrain\n self.terrain_grid, self.fertility_grid, self.topography = self._create_terrain()\n pygame.surfarray.blit_array(self.terrain_screen, self.terrain_grid)\n\n def init_screen(self):\n # init the screen\n self.park_screen.blit(self.terrain_screen, (0, 0))\n self.screen.blit(self.park_screen, (0, 0))\n self.update_screen([])\n\n def add_entity_to_park(self, entity, adding_function):\n \"\"\"\n Creates a new entity in the park.\n\n :param entity - a ParkEntity to add to the park\n :param adding_function - a callback to trigger with the entity's new ID, for any custom logic\n :return unique ID for this entity\n \"\"\"\n self.global_sprite_counter += 1\n self.global_entities[self.global_sprite_counter] = entity\n\n adding_function(self.global_sprite_counter)\n\n return self.global_sprite_counter # return as a unique index given to this sprite just in case\n\n def remove_entity_from_park(self, entity, sprite_id):\n \"\"\"\n Removes the given entity from the park.\n :param entity: entity to remove\n :param sprite_id: sprite ID for this entity as returned by the add function\n \"\"\"\n if sprite_id in self.global_entities:\n del self.global_entities[sprite_id]\n\n self.creature_tree.tree.delete(sprite_id, entity.get_bounding_box())\n self.background_tree.tree.delete(sprite_id, entity.get_bounding_box())\n\n def update_entity_in_park(self, entity, sprite_id, old_box):\n \"\"\"\n Updates an entity's location in the park.\n\n :param entity: entity to update\n :param sprite_id: sprite ID for this entity as returned by the add function\n :param old_box: the entity's old location\n \"\"\"\n\n # the operation of deleting and inserting *looks* expensive, but timing it I found that\n # each call of this method is almost instant\n from park.creatures.creature import Creature\n\n if isinstance(entity, Creature):\n self.creature_tree.tree.delete(sprite_id, old_box)\n self.creature_tree.tree.insert(sprite_id, entity.get_bounding_box())\n else:\n # TODO some other sort of check\n self.background_tree.tree.delete(sprite_id, old_box)\n self.background_tree.tree.insert(sprite_id, entity.get_bounding_box())\n\n def _update_border(self):\n import park.park_util as pu\n border_box = pygame.draw.rect(self.screen, pu.PINK, (self.park_width, 0, self.border, self.park_height))\n return [border_box]\n\n def _update_side_screen(self):\n import park.park_util as pu\n\n self.side_screen.fill(pu.WHITE)\n font = pygame.font.Font(None, pu.TITLE_FONT_SIZE)\n text = font.render(\"HELLO, PARK\", 1, pu.BLACK)\n self.side_screen.blit(text, text.get_rect(centerx=self.side_screen.get_width() / 2))\n\n font = pygame.font.Font(None, pu.INFO_FONT_SIZE)\n text_lines = [\n \"Run Stats\",\n f\"Current FPS: {self.clock.get_fps():.2f}\",\n f\"Current Time: {pygame.time.get_ticks()}\",\n ]\n label = [font.render(line, 1, pu.BLACK) for line in text_lines]\n label_margin = 10\n # each text line is rendered on the screen with its Y varying on its position in the list plus a margin\n for line in range(len(label)):\n self.side_screen.blit(label[line],\n label[line].get_rect(centerx=self.side_screen.get_width() / 2,\n centery=self.side_screen.get_height() / 6\n + line * pu.INFO_FONT_SIZE\n + line * label_margin))\n\n # returning dirty rects of side screen to flip later\n return [self.screen.blit(self.side_screen, (self.border + self.park_width, 0))]\n\n def update_screen(self, dirty_rects):\n \"\"\"\n Wrapper over pygame.display.update to update any passed in \"dirty rects\" or stale areas of the screen.\n Also updates any other areas of the screen that are related to the state but not part of the park.\n \"\"\"\n # pygame.display.update(dirty_rects + self._update_side_screen() + self._update_border())\n self._update_side_screen() + self._update_border()\n pygame.display.flip() # seems like its faster to just update the whole screen than to do it by rects\n\n def _create_terrain(self):\n import park.constructs.terrain as pt\n import park.park_util as pu\n\n noise_grid = pu.time_and_log(\n lambda: park.diamond_square.DiamondSquare(self.grid_size)\n .create_diamond_square_map(low_val=0, high_val=100),\n \"Time to generate noise grid:\")\n\n # scale noise grid into fertility grid\n scaled_fertility = np.kron(noise_grid, np.ones((self.pixel_size, self.pixel_size), dtype=float))\n assert scaled_fertility.shape[0] == self.park_width and scaled_fertility.shape[1] == self.park_height\n\n # convert noise grid into color grid\n colors = np.zeros((noise_grid.shape[0], noise_grid.shape[1], 3))\n\n for x in range(noise_grid.shape[0]):\n for y in range(noise_grid.shape[1]):\n colors[x, y] = pt.get_color_from_fertility(noise_grid[x, y])\n\n # scale color grid into pixel grid, distributing the colors into the correct scale\n scaled_colors = np.kron(colors, np.ones((self.pixel_size, self.pixel_size, 1), dtype=float))\n assert scaled_colors.shape[0] == self.park_width and scaled_colors.shape[1] == self.park_height\n\n # import statistics\n # ferts = park.constructs.terrain.get_ferts()\n # print(\"ferts: \", len(ferts))\n # print(\"max\", max(ferts))\n # print(\"min\", min(ferts))\n # print(\"median\", statistics.median(ferts))\n\n # add water\n height_grid = pu.time_and_log(\n lambda: park.diamond_square.DiamondSquare(self.grid_size)\n .create_diamond_square_map(low_val=0, high_val=100),\n \"Time to generate height grid:\")\n # relax height to smooth it out\n self._relax_grid(height_grid, times=3)\n\n scaled_height = np.kron(height_grid, np.ones((self.pixel_size, self.pixel_size), dtype=float))\n assert scaled_height.shape[0] == self.park_width and scaled_height.shape[1] == self.park_height\n\n for x in range(self.park_width):\n for y in range(self.park_height):\n if scaled_height[x, y] < self.sea_level:\n # print(scaled_height[x, y])\n scaled_colors[x, y] = pt.put_color_underwater(scaled_colors[x, y])\n\n return scaled_colors, scaled_fertility, scaled_height\n\n @staticmethod\n def _relax_grid(grid, times=1):\n \"\"\"\n Relaxes the values in a grid.\n\n This is basically making each value to be the average of values around it.\n :param grid: grid to relax\n :param times: how many times to relax it\n :return:\n \"\"\"\n for time in range(times):\n for x in range(grid.shape[0] - 1):\n for y in range(grid.shape[1] - 1):\n grid[x, y] = (grid[x, y]\n + grid[x - 1, y]\n + grid[x + 1, y]\n + grid[x, y - 1]\n + grid[x, y + 1]) / 5\n","sub_path":"park/park_state.py","file_name":"park_state.py","file_ext":"py","file_size_in_byte":9747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"558574646","text":"from __future__ import print_function\r\n\r\nfrom tensorflow.keras import backend as K\r\n\r\nfrom tensorflow.keras.models import Model\r\nfrom tensorflow.keras.optimizers import Adam\r\nfrom tensorflow.keras.layers import Input, Concatenate, Conv2D, Conv2DTranspose, Dropout, UpSampling2D, AveragePooling2D, MaxPooling2D\r\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, CSVLogger\r\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\r\n\r\nK.set_image_data_format('channels_last') # TF dimension ordering in this code\r\nsmooth = 1. #smooth factor used in DSC and Precission metrics\r\n\r\ndef dice_coef(y_true, y_pred):\r\n \"\"\"\r\n DESCRIPTION: Dice similarity coefficient (DSC) metric, which can be used in the keras backend\r\n ----------\r\n INPUTS:\r\n y_true: the real labels.\r\n y_pred: the predicted labels via network.\r\n -------\r\n OUTPUTS:\r\n the DSC\r\n \"\"\"\r\n \r\n y_true_f = K.flatten(y_true)\r\n y_pred_f = K.flatten(y_pred)\r\n intersection = K.sum(y_true_f * y_pred_f)\r\n return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\r\n \r\ndef dice_coef_loss(y_true, y_pred):\r\n \"\"\"\r\n DESCRIPTION: Dice similarity coefficient (DSC) Loss function, which can be used in the keras backend\r\n ----------\r\n INPUTS:\r\n y_true: the real labels.\r\n y_pred: the predicted labels via network.\r\n -------\r\n OUTPUTS:\r\n the DSC Loss function\r\n \"\"\"\r\n return -dice_coef(y_true, y_pred)\r\n\r\ndef conv_block(m, dim, shape, acti, norm, do=0):\r\n \"\"\"\r\n DESCRIPTION: Convolution block used in both U-net and M-net structure\r\n ----------\r\n INPUTS:\r\n m: the previous layers of the model on which to build on\r\n dim: int, the number of filters to be used in the convolution layers\r\n shape: int or tuple of 2 integers, the kernel size to be used in the convolution layers\r\n acti: string, which activation function to use in the convolution layers\r\n norm: function, normalization function. In case of Groupnormalization a tuple of the function and the desired group size\r\n do: float between 0-1, the dropout rate to be used\r\n -------\r\n OUTPUTS:\r\n n: the model with the new convolution block added\r\n \"\"\"\r\n \r\n n = Conv2D(dim, shape, activation=acti, padding='same')(m)\r\n n = norm()(n) if norm and type(norm) != tuple else norm[0](norm[1])(n) if type(norm) == tuple else n\r\n n = Dropout(do)(n) if do else n\r\n n = Conv2D(dim, shape, activation=acti, padding='same')(n)\r\n n = norm()(n) if norm and type(norm) != tuple else norm[0](norm[1])(n) if type(norm) == tuple else n\r\n return n\r\n\r\ndef level_block_unet(m, dim, shape, depth, inc, acti, norm, do, up):\r\n \"\"\"\r\n DESCRIPTION: Recursive function, used to build the U-net structure\r\n ----------\r\n INPUTS:\r\n m: the previous layers of the model on which to build on\r\n dim: int, the number of filters to be used in the convolution layers\r\n shape: int or tuple of 2 integers, the kernel size to be used in the convolution layers\r\n depth: int, the number of convolutional layers to build\r\n inc: number, the factor with which the number of filters is incremented per convolutional layer\r\n acti: string, which activation function to use in the convolution layers\r\n norm: function, normalization function. In case of Groupnormalization a tuple of the function and the desired group size\r\n do: float between 0-1, the dropout rate to be used\r\n up: boolean, True for using upsampling, False for using Transposed convolution \r\n -------\r\n OUTPUTS:\r\n m: the stacked layers of the models\r\n \"\"\"\r\n \r\n if depth > 0:\r\n n = conv_block(m, dim, shape, acti, norm, do)\r\n m = MaxPooling2D()(n)\r\n m = level_block_unet(m, int(inc*dim), shape, depth-1, inc, acti, norm, do, up)\r\n \r\n if up:\r\n m = UpSampling2D()(m)\r\n m = Conv2D(dim, 2, activation=acti, padding='same')(m)\r\n else:\r\n m = Conv2DTranspose(dim, shape, strides=(2, 2), padding='same')(m)\r\n \r\n n = Concatenate()([n, m])\r\n m = conv_block(n, dim, shape, acti, norm) \r\n else:\r\n m = conv_block(m, dim, shape, acti, norm, do)\r\n \r\n return m\r\n\r\ndef Unet(img_shape = (96, 96, 1), out_ch=1, start_ch=32, depth=4, inc_rate=2, kernel_size = (3, 3), activation='relu', normalization=None, dropout=0, up = False, compile_model =True, learning_rate = 1e-5):\r\n \"\"\"\r\n DESCRIPTION: The U-net model\r\n ----------\r\n INPUTS:\r\n img_shape: tuple, the shape of the input images\r\n out_ch: int, the number of filters for the output layer\r\n start_ch: int, the number of filters for the first convolutional layers\r\n depth: int, the number of convolutional layers\r\n inc: number, the factor with which the number of filters is incremented per convolutional layer\r\n kernel_size: int or tuple of 2 integers, the kernel size to be used in the convolution layers \r\n activation: string, which activation function to use in the convolution layers\r\n normalization: function, normalization function. In case of Groupnormalization a tuple of the function and the desired group size\r\n dropout: float between 0-1, the dropout rate to be used\r\n up: boolean, True for using upsampling, False for using Transposed convolution \r\n -------\r\n OUTPUTS:\r\n model: the compiled U-net model\r\n \"\"\"\r\n \r\n i = Input(shape=img_shape)\r\n o = level_block_unet(i, start_ch, kernel_size, depth, inc_rate, activation, normalization, dropout, up)\r\n o = Conv2D(out_ch, (1, 1), activation = 'sigmoid')(o)\r\n model = Model(inputs=i, outputs=o)\r\n \r\n if compile_model: model.compile(optimizer=Adam(lr=learning_rate), loss = dice_coef_loss, metrics=[dice_coef])\r\n return model\r\n\r\ndef load_callback_list(save_dir):\r\n callbacks_list = []\r\n callbacks_list.append(ModelCheckpoint(save_dir + ' weights.h5', monitor=\"val_loss\", save_best_only=True))\r\n callbacks_list.append(CSVLogger(save_dir + ' log.out', append=True, separator=';'))\r\n callbacks_list.append(EarlyStopping(monitor = \"val_loss\", verbose = 1, min_delta = 0.0001, patience = 5, mode = 'auto', restore_best_weights = True))\r\n return callbacks_list\r\n\r\ndef get_generators(data_gen_args, images, masks, batch_size=32):\r\n image_datagen = ImageDataGenerator(**data_gen_args)\r\n mask_datagen = ImageDataGenerator(**data_gen_args)\r\n \r\n # Provide the same seed and keyword arguments to the fit and flow methods\r\n seed = 1\r\n image_datagen.fit(images, augment=True, seed=seed)\r\n mask_datagen.fit(masks, augment=True, seed=seed)\r\n image_generator = image_datagen.flow(images, batch_size=batch_size, seed=seed)\r\n mask_generator = mask_datagen.flow(masks, batch_size=batch_size, seed=seed)\r\n\r\n train_generator = zip(image_generator, mask_generator)\r\n return train_generator","sub_path":"semi_supervised_learning/Model_2D.py","file_name":"Model_2D.py","file_ext":"py","file_size_in_byte":6987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"203004252","text":"from candidate_models.base_models import base_model_pool\nfrom candidate_models.base_models import BaseModelPool\n\nfrom candidate_models.model_commitments.cornets import cornet_brain_pool\nfrom candidate_models.model_commitments.model_layer_def import model_layers\nfrom candidate_models.model_commitments.vs_layer import visual_search_layer\n\nfrom brainscore.submission.ml_pool import MLBrainPool\nfrom brainscore.submission.utils import UniqueKeyDict\n\nbrain_translated_pool = UniqueKeyDict(reload=True)\n\nml_brain_pool = MLBrainPool(base_model_pool, model_layers)\n\nfor identifier, model in ml_brain_pool.items():\n brain_translated_pool[identifier] = model\n\nfor identifier, model in cornet_brain_pool.items():\n brain_translated_pool[identifier] = model\n\ndef MLSearchPool(target_img_size=28, search_image_size=224):\n target_model_pool = BaseModelPool(input_size=target_img_size)\n stimuli_model_pool = BaseModelPool(input_size=search_image_size)\n\n vs_model_param = {}\n vs_model_param['tar_pool'] = target_model_pool\n vs_model_param['stim_pool'] = stimuli_model_pool\n vs_model_param['model_layers'] = visual_search_layer\n vs_model_param['tar_size'] = target_img_size\n vs_model_param['stim_size'] = search_image_size\n\n ml_search_pool = MLBrainPool(base_model_pool, model_layers, vs_model_param=vs_model_param)\n\n return ml_search_pool\n","sub_path":"candidate_models/model_commitments/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"465540909","text":"# tests run using pytest\nimport pytest\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nSITE_ADDRESS = \"http://automationpractice.com/index.php\"\n\n\n@pytest.fixture(scope=\"class\")\ndef driver_init(request):\n driver = webdriver.Chrome()\n request.cls.driver = driver\n driver.get(SITE_ADDRESS)\n yield\n driver.close()\n\n\nclass TestHomePage:\n @pytest.mark.usefixtures(\"driver_init\")\n def test1_launch_page_title(self):\n #self.driver.get(SITE_ADDRESS)\n assert 'My Store' in self.driver.title\n time.sleep(2)\n\n def test2_emptyCart(self):\n ele = self.driver.find_element_by_class_name(\"shopping_cart\")\n assert \"(empty)\" in ele.text\n self.driver.save_screenshot(\"screenshots/before_cart.png\")\n\n @pytest.mark.xfail()\n def test3_addToCart(self):\n browser = self.driver\n browser.execute_script(\"window.scrollTo(0, 800)\")\n time.sleep(5) # pause for 5 seconds\n # element = browser.find_elements_by_class_name(\"product-image-container\")\n element = WebDriverWait(browser, 10).until(\n EC.element_to_be_clickable((By.LINK_TEXT, \"Faded Short Sleeve T-shirts\")))\n element.click()\n time.sleep(3)\n ele = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"p#add_to_cart\")))\n ele.click()\n time.sleep(2)\n browser.save_screenshot(\"screenshots/before_cart.png\")\n ele = browser.find_element_by_class_name(\"cross\")\n ele.click()\n browser.save_screenshot(\"screenshots/after_cart.png\")\n ele = browser.find_element_by_class_name(\"shopping_cart\")\n assert \"(empty)\" not in ele.text\n browser.back() # go one page back\n browser.save_screenshot(\"screenshots/browser_back.png\")\n browser.execute_script(\"window.scrollTo(0, 0)\") # scroll to the top of the page\n browser.save_screenshot(\"screenshots/scroll_up.png\")\n # upon return to the home page , the cart still has the product added and is not empty\n ele = browser.find_element_by_class_name(\"shopping_cart\")\n assert \"(empty)\" not in ele.text\n\n def test4_search(self):\n browser = self.driver\n ele = browser.find_element_by_class_name(\"search_query\")\n ele.click()\n ele.send_keys(\"blouse\") # search for blouse\n ele = browser.find_element_by_class_name(\"button-search\")\n ele.click()\n time.sleep(3)\n\n # assert the count of the search results\n ele = browser.find_elements_by_class_name(\"product_img_link\")\n browser.save_screenshot(\"screenshots/search_results.png\")\n assert len(ele) == 1, \"There must be only 1 result\"\n\n","sub_path":"test_home_pytest.py","file_name":"test_home_pytest.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"615854079","text":"# -*- coding: utf-8 -*-\n\n\nfrom odoo import api, fields, models, tools, _\nfrom datetime import datetime, date\n\nclass Employee(models.Model):\n _inherit = 'hr.employee'\n _name = 'hr.employee'\n\n first_name = fields.Char(string=\"Prenom\", size=128, required=False)\n num_cnaps_emp = fields.Char(string=\"N° CNAPS\")\n num_cin = fields.Char(string=\"N° CIN\", size=10)\n date_cin = fields.Date(string='Date CIN')\n lieu_cin = fields.Char(string='Lieu de délivrance CIN')\n num_emp = fields.Char(string=\"N° Matricule\")\n nombre_enfant_cnaps = fields.Integer(string=u\"Nombre d'enfant allouée CNaPS\", required=True)\n seniority = fields.Char(string=u'Ancienneté', compute='get_seniority')\n #make field obligatory\n gender = fields.Selection([\n ('male', 'Male'),\n ('female', 'Female')\n ], groups='hr.group_hr_user', required=True)\n birthday = fields.Date('Date of Birth', groups='hr.group_hr_user', required=True)\n department_id = fields.Many2one('hr.department', string='Department', required=True)\n job_id = fields.Many2one('hr.job', string='Job Title', required=True)\n #percpt_minimum = fields.Float(string='Perception minimum', default=2000)\n\n def if_exist(self, name):\n if not name:\n return ''\n else:\n return name\n @api.multi\n def name_get(self):\n data = []\n for employee in self:\n name = self.if_exist(employee.name_related).upper() + ' ' + self.if_exist(employee.first_name)\n data.append((employee.id, name))\n return data\n\n @api.multi\n def get_seniority(self):\n for employee in self:\n date_start = self.env['hr.contract'].search([('employee_id', '=', employee.id)]).mapped('date_start')\n if date_start:\n date_start_ = datetime.strptime(date_start[0], tools.DEFAULT_SERVER_DATE_FORMAT)\n dif_m = self.diff_month(date.today(), date_start_)\n if dif_m < 13:\n if dif_m == 12:\n employee.seniority = '1 ans'\n elif dif_m == 0:\n d0 = date(date_start_.year, date_start_.month, date_start_.day)\n employee.seniority = str(date.today() - d0).replace('day, 0:00:00', ' jours ')\n else:\n employee.seniority = str(dif_m) + ' mois'\n else:\n mois = dif_m % 12\n ans = (dif_m - mois) / 12\n employee.seniority = str(ans) + 'ans/' + str(mois) + 'mois'\n else:\n employee.seniority = '0'\n\n\n def diff_month(self, d1, d2):\n return (d1.year - d2.year) * 12 + d1.month - d2.month\n","sub_path":"gestion_de_paie/models/employee.py","file_name":"employee.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"573231074","text":"from caldav.lib.url import URL\nimport urlparse\n\n\"\"\"\nI don't know why, but the original caldav function throws an error. This works, so I don't really care enough for debugging. If someone wants to find out why: be my guest!\n\"\"\"\n\ndef _new_join(self, path):\n path = URL.objectify(path)\n if path.path[0] == '/':\n ret_path = path.path\n else:\n sep = \"/\"\n if self.path.endswith(\"/\"):\n sep = \"\"\n ret_path = \"%s%s%s\" % (self.path, sep, path.path)\n \n return URL(urlparse.ParseResult(self.scheme or path.scheme, self.netloc or path.netloc, ret_path, path.params, path.query, path.fragment))\n\nURL.join = _new_join","sub_path":"caldav_join.py","file_name":"caldav_join.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"575511429","text":"SHIPPEER_REQUIREMENTS_CHOICES = (\n (0, \"Línea de transporte\"),\n (1, \"Vehículo\"),\n (2, \"Operador\"),\n)\nSTATUS_CHOICES = (\n (0, \"Por validar\"),\n (1, \"Validada\"),\n (2, \"Suspendida\"),\n)\nVEHICLE_TYPE = (\n (0, \"Sin especificar\"),\n (1, \"Camioneta de 1.5 toneladas\"),\n (2, \"Camioneta de 3.5 toneladas\"),\n (3, \"Camioneta de 5.5 toneladas\"),\n (4, \"Rabón con caja seca\"),\n (5, \"Rabón con caja refrigerada\"),\n (6, \"Torton con caja seca\"),\n (7, \"Torton con caja refrigerada\"),\n (9, \"Trailer de 48ft con caja seca\"),\n (10, \"Trailer de 48ft con caja refrigerada\"),\n (11, \"Trailer de 53ft con caja seca\"),\n (12, \"Trailer de 53ft con caja refrigerada\"),\n )\n\nVEHICLE_DRIVER_STATUS_CHOICES = (\n (0, \"Por validar\"),\n (1, \"Validado\"),\n (2, \"Suspendido\"),\n)\n\nLICENSE_TYPE_CHOICES = (\n ('A', 'A'),\n ('B', 'B'),\n ('C', 'C'),\n ('D', 'D'),\n ('F', 'F'),\n)\n","sub_path":"core/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"418103693","text":"\"\"\"\nThis program simplifies the calculations necessary to determine profitability of cryptocurrency mining\ninfrastructure.\n\n\nVega 64 statistics: https://wccftech.com/amd-rx-vega-64-mining-performance-blows-away-titan-v-xmr-monero/\n\n\nWith an ASIC you buy a dodgy piece of fire hazard equipment, that is only good for one or perhaps two algos,\nthat eats electricity, devalues before your eyes and might be ‘bricked’ by the time you get it.\n\nMonero start date was 4-18-2014\n\n\"\"\"\nimport copy\nimport datetime\nimport math\nimport statistics as s\n\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom dateutil import parser\n\n\"\"\"\nWe will calculate the per card profit and plot the historical results, given\n#1 Historical mining difficulty\n#2 Historical fixed block reward + estimated transaction fees\n\"\"\"\n\n\ndef main():\n # Define parameters\n kileen = ElectricitySource(650, 18.5)\n commercialEnergy = ElectricitySource(20, 120)\n subsetKileen = ElectricitySource(20, 18.5)\n # Estimating cost of mining equipment at scale. If you have a 13 GPU rig, the cost of all the other hardware is roughly the cost of a 14th GPU @ $500\n # Vega 64 Release Date = August 14, 2017\n releaseDate = datetime.datetime.strptime(\"2017-07-14\", \"%Y-%m-%d\").date()\n # Watts, Hash/Second, Cost, Release Date, Details\n vega64 = MiningRig(203.00, 1965.00, float(\n 500 + 500 / 13), releaseDate, \"Vega 64\")\n symbol = \"XMR\" # Monero\n shouldPlot = True\n # estimateCumulativeIncome(symbol, vega64, commercialEnergy, shouldPlot)\n # Determine marginal addition to operating income since release date per added card\n plotRiskCurve(symbol, vega64, subsetKileen)\n\n\ndef plotRiskCurve(coin_symbol, mining_rig, electricity_source):\n maxEfficiency = 0.90\n maxRigs = np.math.floor((electricity_source.energyOutput * 1000.00 *\n 1000.00 * maxEfficiency) / mining_rig.energyConsumption)\n print(\"Max rigs with 90% efficiency and \" + str(mining_rig.energyConsumption) +\n \" Watts per rig and \" + str(electricity_source.energyOutput) + \" MW/h total capacity\")\n print(\"Calculating risk curve for 10 to \" +\n str(maxRigs) + \" \" + mining_rig.details + \"s\")\n cumulativeIncomes = []\n meanBreakEvenTimes = []\n medianBreakEvenTimes = []\n numRigs = 10\n xAxisData = []\n while numRigs <= maxRigs:\n tempMiningRig = copy.deepcopy(mining_rig)\n tempMiningRig.hashRate = mining_rig.hashRate * numRigs\n tempMiningRig.energyConsumption = mining_rig.energyConsumption * numRigs\n tempMiningRig.price = mining_rig.price * numRigs\n\n print(\"Simulating with \" + str(numRigs) + \" \" + mining_rig.details + \"s @ \" +\n str(tempMiningRig.energyConsumption) + \" W/h \" + str(tempMiningRig.hashRate) + \" H/s $\" + str(tempMiningRig.price))\n\n cumulativeIncome, meanBreakEvenTime, medianBreakEvenTime = estimateCumulativeIncome(\n coin_symbol, tempMiningRig, electricity_source, False)\n cumulativeIncomes.append(cumulativeIncome)\n meanBreakEvenTimes.append(meanBreakEvenTime)\n medianBreakEvenTimes.append(medianBreakEvenTime)\n xAxisData.append(numRigs/10)\n numRigs += 10\n\n print(cumulativeIncomes)\n print(meanBreakEvenTimes)\n print(medianBreakEvenTimes)\n print(xAxisData)\n\n # Plot operating income vs # rigs\n # cumulativeIncomes = []\n # cumulativeIncomes = cumulativeIncomes[:len(xAxisData)]\n x = xAxisData\n y = cumulativeIncomes\n low = min(y)\n high = max(y)\n plt.ylim([0, math.ceil(high + 0.5 * (high - low))])\n plt.xlabel('# Rigs (multiples of 10)')\n plt.ylabel('Operating Income (Tens of millions USD)')\n plt.title('Operating Income vs # Rigs')\n label = \"$\" + str('{0:.2f}'.format(electricity_source.costPerMegawatt)\n ) + \" MW/h + \" + str(mining_rig.details)\n plt.bar(x, y, label=label)\n plt.show()\n\n # Plot cost of rigs\n costOfRigs = []\n numRigs = 10\n while numRigs <= maxRigs:\n tempMiningRig = copy.deepcopy(mining_rig)\n tempMiningRig.hashRate = mining_rig.hashRate * numRigs\n tempMiningRig.energyConsumption = mining_rig.energyConsumption * numRigs\n tempMiningRig.price = mining_rig.price * numRigs\n costOfRigs.append(tempMiningRig.price)\n numRigs += 10\n y = costOfRigs[:len(xAxisData)]\n low = min(y)\n high = max(y)\n plt.ylim([0, math.ceil(high + 0.5 * (high - low))])\n plt.xlabel('# Rigs (multiples of 10 GPUs)')\n plt.ylabel('$ Tens of Millions')\n plt.title('Fixed Costs Estimated')\n label = \"$\" + str('{0:.2f}'.format(electricity_source.costPerMegawatt)\n ) + \" MW/h + \" + str(mining_rig.details)\n plt.bar(x, y, label=label)\n plt.show()\n\n # Plot energy consumption\n energyConsumption = []\n numRigs = 10\n while numRigs <= maxRigs:\n tempMiningRig = copy.deepcopy(mining_rig)\n tempMiningRig.hashRate = mining_rig.hashRate * numRigs\n tempMiningRig.energyConsumption = mining_rig.energyConsumption * numRigs\n tempMiningRig.price = mining_rig.price * numRigs\n energyConsumption.append(tempMiningRig.energyConsumption)\n numRigs += 10\n y = energyConsumption[:len(xAxisData)]\n low = min(y)\n high = max(y)\n plt.ylim([0, math.ceil(high + 0.5 * (high - low))])\n plt.xlabel('# Rigs (multiples of 10 GPUs)')\n plt.ylabel('10 x MW/h')\n plt.title('Energy Consumption')\n label = \"$\" + str('{0:.2f}'.format(electricity_source.costPerMegawatt)\n ) + \" MW/h + \" + str(mining_rig.details)\n plt.bar(x, y, label=label)\n plt.show()\n\n # Plot mean break-even time\n y = meanBreakEvenTimes[:len(xAxisData)]\n low = min(y)\n high = max(y)\n plt.ylim([0, math.ceil(high + 0.5 * (high - low))])\n plt.xlabel('# Rigs (multiples of 10 GPUs)')\n plt.ylabel('Days')\n plt.title('Mean Break-Even Time')\n label = \"$\" + str('{0:.2f}'.format(electricity_source.costPerMegawatt)\n ) + \" MW/h + \" + str(mining_rig.details)\n plt.bar(x, y, label=label)\n plt.show()\n\n # Plot median break-even time\n y = medianBreakEvenTimes[:len(xAxisData)]\n low = min(y)\n high = max(y)\n plt.ylim([0, math.ceil(high + 0.5 * (high - low))])\n plt.xlabel('# Rigs (multiples of 10 GPUs)')\n plt.ylabel('Days')\n plt.title('Median Break-Even Time')\n label = \"$\" + str('{0:.2f}'.format(electricity_source.costPerMegawatt)\n ) + \" MW/h + \" + str(mining_rig.details)\n plt.bar(x, y, label=label)\n plt.show()\n\n\ndef estimateCumulativeIncome(coin_symbol, mining_rig, electricity_source, shouldPlot):\n \"\"\"\n This function estimates daily profit for mining given parameters.\n It calculates gross revenue and then subtracts electricity costs.\n Mining infrastructure costs are not taken into consideration.\n \"\"\"\n if coin_symbol == \"XMR\":\n if shouldPlot:\n print(\"Calculating daily Monero mining profits...\")\n moneroHashRates, moneroPrices, blockRewards = readData(coin_symbol)\n index = 0\n dailyRevenue = []\n dailyOperatingIncome = []\n totalProfitFigures = []\n while index < len(moneroHashRates):\n totalNetworkHashRate = moneroHashRates[index].rate\n price = moneroPrices[index].rate\n reward = blockRewards[index].rate\n # Monero rewards miners with variable fixed blocks + transaction fees for that block\n estimatedPercentTransactionFees = 0.06479 / 4.51\n blockReward = reward + reward * estimatedPercentTransactionFees\n # Monero rewards blocks every 2 minutes\n rewardsPerDay = (24 * 60 / 2)\n totalProfit = rewardsPerDay * blockReward\n coinRevenue = calculateRevenuePerHash(totalProfit, totalNetworkHashRate,\n mining_rig.hashRate) * mining_rig.hashRate\n revenue = coinRevenue * price # Convert XMR to USD\n dailyRevenue.append(revenue)\n # Calculate profit\n profit = revenue - mining_rig.energyConsumption * 24 * \\\n electricity_source.costPerMegawatt / 1000.00 / 1000.00\n dailyOperatingIncome.append(profit)\n totalProfitFigures.append(totalProfit * price)\n index += 1\n\n # Plot Operating Income\n dailyProfits = []\n dates = []\n index = 0\n for reward in moneroHashRates:\n dates.append(reward.date)\n dailyProfits.append(dailyOperatingIncome[index])\n index += 1\n # Annotate graph\n releaseDate = mining_rig.releaseDate\n index = 0\n xIndex = 0\n for date in dates:\n if date == releaseDate:\n xIndex = index\n index += 1\n if shouldPlot:\n fig, ax = plt.subplots()\n plt.xlabel('Date')\n years = mdates.YearLocator() # every year\n months = mdates.MonthLocator() # every month\n yearsFmt = mdates.DateFormatter('%Y')\n ax.xaxis.set_major_locator(years)\n ax.xaxis.set_major_formatter(yearsFmt)\n ax.xaxis.set_minor_locator(months)\n # ax.set_ylim(0, 10)\n plt.ylabel('Operating Income (USD)')\n plt.title('Operating Income vs Date')\n label = \"$\" + str('{0:.2f}'.format(electricity_source.costPerMegawatt)\n ) + \" MW/h + \" + str(mining_rig.details)\n plt.bar(dates, dailyOperatingIncome, label=label)\n # Annotate graph\n ax.annotate('Release Date', xy=(releaseDate, dailyOperatingIncome[xIndex]),\n xytext=(releaseDate,\n dailyOperatingIncome[xIndex] * 0.6),\n arrowprops=dict(facecolor='white', shrink=0.05))\n hardForkDate = datetime.datetime.strptime(\n \"2018-04-06\", \"%Y-%m-%d\").date()\n index = 0\n hardForkIndex = 0\n for date in dates:\n if date == hardForkDate:\n hardForkIndex = index\n index += 1\n hardForkDateText = datetime.datetime.strptime(\n \"2018-04-30\", \"%Y-%m-%d\").date()\n ax.annotate(' ASIC hard \\n fork', xy=(hardForkDate, dailyOperatingIncome[hardForkIndex]),\n xytext=(hardForkDateText,\n dailyOperatingIncome[hardForkIndex] * 0.7),\n arrowprops=dict(facecolor='white', shrink=0.05))\n ax.legend(loc='best')\n plt.show()\n # ax.plot(dates, dailyRevenueFigures, label='Revenue')\n # Plot EMA\n # dataFrame = pd.DataFrame(np.array(dailyProfits))\n # ema_short = dataFrame.ewm(span=10, adjust=False).mean()\n # ax.plot(dates, ema_short, label='20 day EMA')\n\n # Determine time to turn a profit on mining hardware\n cumulativeOperatingIncome = []\n index = 0\n for operatingIncome in dailyOperatingIncome:\n cumulativeOperatingIncome.append(\n sumRange(dailyOperatingIncome, 0, index))\n index += 1\n xAxisData = []\n for reward in moneroHashRates:\n xAxisData.append(reward.date)\n if shouldPlot:\n fig, ax = plt.subplots()\n ax.plot(xAxisData, cumulativeOperatingIncome, label=label)\n ax.legend(loc='best')\n plt.xlabel('Date')\n years = mdates.YearLocator() # every year\n months = mdates.MonthLocator() # every month\n yearsFmt = mdates.DateFormatter('%Y')\n ax.xaxis.set_major_locator(years)\n ax.xaxis.set_major_formatter(yearsFmt)\n ax.xaxis.set_minor_locator(months)\n plt.ylabel('Operating Income (USD)')\n plt.title('Cumulative Operating Income')\n # Annotate Graph\n ax.annotate('ASIC hard fork', xy=(hardForkDate, cumulativeOperatingIncome[hardForkIndex]),\n xytext=(\n hardForkDate, cumulativeOperatingIncome[hardForkIndex] * 0.7),\n arrowprops=dict(facecolor='white', shrink=0.05))\n ax.annotate('Release Date August 14, 2017', xy=(releaseDate, cumulativeOperatingIncome[xIndex]),\n xytext=(releaseDate,\n cumulativeOperatingIncome[xIndex] * 0.6),\n arrowprops=dict(facecolor='white', shrink=0.05))\n # Draw Start & Break even points\n startLine = []\n breakEvenLine = []\n for x in xAxisData:\n startLine.append(cumulativeOperatingIncome[xIndex])\n breakEvenLine.append(\n cumulativeOperatingIncome[xIndex] + mining_rig.price)\n ax.plot(xAxisData, breakEvenLine, label='Break Even')\n ax.plot(xAxisData, startLine, label='Earliest Start Date')\n ax.legend(loc='best')\n plt.show()\n\n # Calculate mean & median return since release date\n meanOperatingIncome = s.mean(dailyOperatingIncome[xIndex:])\n medianOperatingIncome = s.median(dailyOperatingIncome[xIndex:])\n\n print(\"Mean daily operating income since \" +\n str(releaseDate) + \": $\" + str(meanOperatingIncome))\n print(\"Median daily operating income since \" +\n str(releaseDate) + \": $\" + str(medianOperatingIncome))\n # Calculate break even time\n breakEvenDaysMean = mining_rig.price / meanOperatingIncome\n breakEvenDaysMedian = mining_rig.price / medianOperatingIncome\n\n print(\"Mean break even days: \" + str(breakEvenDaysMean))\n print(\"Median break even days: \" + str(breakEvenDaysMedian))\n\n # Plot hash rate vs date\n xAxisData = []\n yAxisData = []\n for reward in moneroHashRates:\n xAxisData.append(reward.date)\n yAxisData.append(reward.rate)\n if shouldPlot:\n fig, ax = plt.subplots()\n ax.plot(xAxisData, yAxisData)\n plt.xlabel('Date')\n years = mdates.YearLocator() # every year\n months = mdates.MonthLocator() # every month\n yearsFmt = mdates.DateFormatter('%Y')\n ax.xaxis.set_major_locator(years)\n ax.xaxis.set_major_formatter(yearsFmt)\n ax.xaxis.set_minor_locator(months)\n plt.ylabel('Hash / Second')\n plt.title('Monero Network Hash Rate vs Date')\n plt.show()\n\n # Plot price vs date\n xAxisData = []\n yAxisData = []\n for reward in moneroPrices:\n xAxisData.append(reward.date)\n yAxisData.append(reward.rate)\n fig, ax = plt.subplots()\n ax.plot(xAxisData, yAxisData)\n plt.xlabel('Date')\n years = mdates.YearLocator() # every year\n months = mdates.MonthLocator() # every month\n yearsFmt = mdates.DateFormatter('%Y')\n ax.xaxis.set_major_locator(years)\n ax.xaxis.set_major_formatter(yearsFmt)\n ax.xaxis.set_minor_locator(months)\n plt.ylabel('Price (USD)')\n plt.title('Monero Price vs Date')\n plt.show()\n\n # Plot reward vs date\n xAxisData = []\n yAxisData = []\n for reward in blockRewards:\n date = parser.parse(reward.date)\n xAxisData.append(date)\n yAxisData.append(reward.rate)\n fig, ax = plt.subplots()\n ax.plot(xAxisData, yAxisData)\n plt.xlabel('Date')\n years = mdates.YearLocator() # every year\n months = mdates.MonthLocator() # every month\n yearsFmt = mdates.DateFormatter('%Y')\n ax.xaxis.set_major_locator(years)\n ax.xaxis.set_major_formatter(yearsFmt)\n ax.xaxis.set_minor_locator(months)\n plt.ylabel('Block Reward (XMR)')\n plt.title('Monero Block Reward vs Date (Adjusted)')\n plt.show()\n elif coin_symbol == \"BTC\":\n print(\"Calculating daily Bitcoin mining profits...\")\n # TODO Do bitcoin calculation\n else:\n print(\"Coin symbol not supported.\")\n\n # Return cumulative return from release date, onward\n totalOperatingIncome = sum(dailyOperatingIncome[xIndex:])\n return totalOperatingIncome, breakEvenDaysMean, breakEvenDaysMedian\n\n\ndef readData(coin_symbol):\n debug = False\n if coin_symbol == \"XMR\":\n # Read in historical network hash rate into array\n fixedBlockRewardFileName = \"./data/monerohashratemodified.txt\"\n file1 = open(fixedBlockRewardFileName, \"r\")\n hashRateLine = file1.readlines()\n hashRateLine = \"\".join(str(x) for x in hashRateLine)\n file1.close()\n hashRates = hashRateLine.split(\",\")\n hashRates = list(map(','.join, zip(hashRates[::2], hashRates[1::2])))\n pricingDate = datetime.datetime.strptime(\"2014/06/04\",\n \"%Y/%m/%d\").date() # Earliest date we have for Monero prices\n moneroHashRates = []\n for rate in hashRates:\n temp = rate[rate.find(\"\\\"\") + 1:]\n dateString = temp[:temp.find(\"\\\"\")]\n hashRate = temp[temp.find(\",\") + 1: len(temp) - 1]\n date = datetime.datetime.strptime(dateString, \"%Y/%m/%d\").date()\n if date >= pricingDate:\n if hashRate == 'null':\n hashRate = 0\n moneroHashRates.append(HashRate(date, float(hashRate)))\n latestHashDate = date\n if debug:\n print(str(len(moneroHashRates)) + \" days of hash rates\")\n\n # Read in historical pricing data\n fixedBlockRewardFileName = \"./data/moneroprice.txt\"\n file1 = open(fixedBlockRewardFileName, \"r\")\n hashRateLine = file1.readlines()\n hashRateLine = \"\".join(str(x) for x in hashRateLine)\n file1.close()\n hashRates = hashRateLine.split(\",\")\n hashRates = list(map(','.join, zip(hashRates[::2], hashRates[1::2])))\n moneroPrices = []\n for rate in hashRates:\n temp = rate[rate.find(\"\\\"\") + 1:]\n dateString = temp[:temp.find(\"\\\"\")]\n date = datetime.datetime.strptime(dateString, \"%Y/%m/%d\").date()\n hashRate = temp[temp.find(\",\") + 1: len(temp) - 1]\n if date <= latestHashDate:\n moneroPrices.append(HashRate(date, float(hashRate)))\n # print(str(len(moneroPrices)) + \" days of monero prices\")\n\n # Read in fixed block reward into array\n fixedBlockRewardFileName = \"./data/monerofixedblockreward.txt\"\n file1 = open(fixedBlockRewardFileName, \"r\")\n fixedBlockRewards = file1.readlines()\n file1.close()\n # print(str(len(fixedBlockRewards)) + \" days of block rewards\")\n\n # Find earliest pricing date index\n # Find latest hash rate date index\n fixedBlockRewardDateFileName = \"./data/moneroblockrewarddate.txt\"\n file1 = open(fixedBlockRewardDateFileName, \"r\")\n fixedBlockRewardDates = file1.readlines()\n file1.close()\n if debug:\n print(\"Pruning reward dates...\")\n earliestIndex = 0\n latestIndex = 0\n index = 0\n if debug:\n print(str(pricingDate) + \" to \" + str(latestHashDate))\n for line in fixedBlockRewardDates:\n line = line.strip()\n date = datetime.datetime.strptime(line, \"%Y-%m-%d\").date()\n if date == latestHashDate:\n latestIndex = index\n elif date == pricingDate:\n earliestIndex = index\n index += 1\n fixedBlockRewards = fixedBlockRewards[earliestIndex:latestIndex + 1]\n fixedBlockRewardDates = fixedBlockRewardDates[earliestIndex:latestIndex + 1]\n blockRewards = []\n index = 0\n while index < len(fixedBlockRewards):\n # Account for mining time split - anytime before 2016-03-23 must be doubled\n reward = float(fixedBlockRewards[index])\n if fixedBlockRewardDates[index] < \"2016-03-23\":\n reward = reward * 2\n blockRewards.append(HashRate(fixedBlockRewardDates[index], reward))\n index += 1\n if debug:\n print(str(len(fixedBlockRewards)) + \" days of block rewards\")\n return moneroHashRates, moneroPrices, blockRewards\n else:\n print(\"Symbol not supported!\")\n\n\ndef sumRange(L, a, b):\n sum = 0\n for i in range(a, b + 1, 1):\n sum += L[i]\n return sum\n\n\ndef calculateRevenuePerHash(totalProfit, totalNetworkHashRate, marginalHashRate):\n return totalProfit / (totalNetworkHashRate + marginalHashRate)\n\n\nclass MiningRig:\n energyConsumption = 0 # Watts\n hashRate = 0 # Hash / Second\n price = 0\n releaseDate = \"\"\n details = \"\"\n\n def __init__(self, energyConsumption, hashRate, price, releaseDate, details):\n self.energyConsumption = energyConsumption\n self.hashRate = hashRate\n self.price = price\n self.releaseDate = releaseDate\n self.details = details\n\n\nclass ElectricitySource:\n energyOutput = 0 # MW MegaWatts/h\n costPerMegawatt = 0.0 # $ / MegaWatt/h\n\n def __init__(self, energyOutput, costPerMegawatt):\n self.energyOutput = energyOutput\n self.costPerMegawatt = costPerMegawatt\n\n\nclass HashRate:\n date = \"\" # YYYY/MM/DD\n rate = 0 # H/s\n\n def __init__(self, date, rate):\n self.date = date\n self.rate = rate\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":21718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"435003904","text":"#Utils module for helper methods\nimport urlparse\nimport logging\nfrom string import digits\nfrom random import choice\n\n\nlog = logging.getLogger(__name__)\n\n\ndef v10_switch(driver):\n \"\"\"Attempts to force switch to v10 if v8 frontend is opened.\n\n Args:\n driver: The current webdriver object\n\n Raises:\n AssertionError: If after the attempted switch V10 is still not loaded.\n \"\"\"\n\n v10_cookie = \"v10\"\n log.info(driver.current_url)\n\n if driver.get_cookie(v10_cookie):\n log.debug(\"Already on V10\")\n else:\n log.debug(\"Attempting to switch to V10\")\n driver.execute_script(r'return $.v10RollOut.switchToNew();')\n log.debug(driver.get_cookies())\n try:\n assert driver.get_cookie(v10_cookie)\n\n except AssertionError:\n log.warning(\"v10 cookie not found. Failed to switch to v10. Terminating tests.\")\n raise\n\n\ndef is_absolute(url):\n \"\"\"Takes a given url and parses it to see whether it is absolute or relative\n\n Args:\n url: (url) The url to be parsed.\n\n Returns:\n (bool) True if absolute. False if relative.\n \"\"\"\n\n return bool(urlparse.urlparse(url).netloc)\n\n\ndef get_absolute_url(protocol, baseurl, url=\"\"):\n \"\"\"Takes a given url and makes it absolute if it is not.\n\n Args:\n - protocol (str): The internet protocol to be used in the url.\n - baseurl (str): The base url (domain) to be used.\n - url (str): The url theo be checked. Defaults to an empty string - this will return the homepage.\n\n Returns:\n - Absolute url\n \"\"\"\n\n if not is_absolute(url):\n url = protocol + '://' + baseurl + url\n\n return url\n\n\ndef generate_random_number(length):\n lst = [choice(digits) for n in xrange(length)]\n return \"\".join(lst)\n","sub_path":"experiments/fastfood/pizzade/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"16754899","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*- \n# @Time : 2018-04-08 13:12\n# @Author : Gujc\n# @File : demon1.py\nimport json\n\nimport requests\n\n# url = 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'\ntoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'\n\n# '''\n# curl Webhook -H 'Content-Type: application/json' \\\n# -d '{\"msgtype\": \"text\",\n# \"text\": {\n# \"content\": {\n# \"username\": \"test\",\n# \"password\": \"test123\",\n# }\n# }\n# }'\n# '''\nclass Dingding(object):\n\n def __init__(self, token):\n self.url = 'https://oapi.dingtalk.com/robot/send?access_token=%s' % token\n self.headers = {'Content-Type': 'application/json'}\n\n def send_text(self, text, at_mobiles=[], at_all=False):\n \"\"\"\n text类型\n {\n \"msgtype\": \"text\",\n \"text\": {\n \"content\": \"我就是我, @156xxxx8827 是不一样的烟火\"\n },\n \"at\": {\n \"atMobiles\": [\n \"156xxxx8827\",\n \"189xxxx8325\"\n ],\n \"isAtAll\": false\n }\n }\n 例子: send_text('天气不错', ['13333333333'])\n :param text: 消息类型,此时固定为:text\n :param at_mobiles: 被@人的手机号 ['13333333333', ]\n :param at_all: @所有人时:true,否则为:false\n :return:\n \"\"\"\n self._send_text(text, at_mobiles, at_all)\n\n def _send_text(self, text, at_mobiles, at_all):\n data = {\n \"msgtype\": \"text\",\n \"text\": {\n \"content\": text\n },\n \"at\": {\n \"atMobiles\": at_mobiles,\n \"isAtAll\": at_all\n }\n }\n return self._post(data)\n\n def _post(self, data):\n data = json.dumps(data)\n # s = requests.session()\n r = requests.post(self.url, data=data, headers=self.headers)\n if r.status_code == 200:\n print(\"success!\")\n\na = Dingding(token)\n#a.send_text(text='username:testuser\\npasswd:test', at_mobiles=[], at_all=False)\n","sub_path":"dingding.py","file_name":"dingding.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"599680082","text":"from twarc import Twarc2, expansions\nimport json\n\n# Replace your bearer token below\nclient = Twarc2(bearer_token=\"XXXXX\")\n\n\ndef main():\n # The sample method gives a 1% random sample of all Tweets\n for count, result in enumerate(client.sample()):\n # The Twitter API v2 returns the Tweet information and the user, media etc. separately\n # so we use expansions.flatten to get all the information in a single JSON\n tweet = expansions.flatten(result)\n # Here we are printing the full Tweet object JSON to the console\n print(json.dumps(tweet))\n\n # Replace with the desired number of Tweets, otherwise it will stop after 100 Tweets\n if count > 100:\n break\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"labs-code/python/academic-research-product-track/stream_sampled.py","file_name":"stream_sampled.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"514759021","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import init\n\nimport math\nimport numpy as np\n\nclass MLP_2(nn.Module):\n def __init__(self, bn):\n super(MLP_2, self).__init__()\n if bn:\n self.fc = nn.Sequential(\n nn.Linear(28*28, 200),\n nn.BatchNorm1d(200),\n nn.ReLU(),\n nn.Linear(200, 84),\n nn.BatchNorm1d(84),\n nn.ReLU(),\n nn.Linear(84, 10),\n nn.Sigmoid()\n )\n else:\n self.fc = nn.Sequential(\n nn.Linear(28*28, 200),\n nn.ReLU(),\n nn.Linear(200, 84),\n nn.ReLU(),\n nn.Linear(84, 10),\n nn.Sigmoid()\n )\n\n for m in self.modules():\n if isinstance(m, nn.Linear):\n if m.bias is not None:\n init.uniform_(m.bias)\n init.xavier_uniform_(m.weight)\n\n def forward(self, x):\n x = x.view(x.shape[0], -1)\n out = self.fc(x)\n return out","sub_path":"mnist/Network/MLP_2.py","file_name":"MLP_2.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"108198939","text":"#!/usr/bin/env python\n\nimport sys\n\nfrom PyQt5.QtWidgets import (QApplication, QMainWindow, QTableWidgetItem,\n QTabWidget, QWidget, QShortcut, QVBoxLayout)\nfrom PyQt5.QtCore import pyqtSlot, pyqtSignal\nfrom PyQt5.QtGui import QKeySequence, QFont\n\nfrom Database import Database\nfrom TableWidget import TableWidget, get_time_str\nfrom ItemEditWidget import ItemEditWidget\n\n\nclass MainWindow(QMainWindow):\n new_row_signal = pyqtSignal(int)\n\n def __init__(self):\n super().__init__()\n self.title = 'itaal -- development version'\n self.db = Database()\n\n self.initUI()\n self.add_shortcuts()\n\n def initUI(self):\n self.setWindowTitle(self.title)\n self.create_tabbed_interface()\n\n self.lexemes_table = TableWidget(self.db.conn, 'lexemes')\n self.lexemes_table.resizeColumnsToContents()\n self.add_table_tab(self.lexemes_table)\n self.new_row_signal.connect(self.lexemes_table.insert_row)\n\n self.setCentralWidget(self.tabs)\n\n def add_shortcuts(self):\n self.close_tab = QShortcut(QKeySequence('Ctrl+W'), self)\n self.close_tab.activated.connect(self.on_ctrl_w)\n\n self.prev_tab = QShortcut(QKeySequence('Ctrl+PgUp'), self)\n self.prev_tab.activated.connect(self.on_pgup)\n self.next_tab = QShortcut(QKeySequence('Ctrl+PgDown'), self)\n self.next_tab.activated.connect(self.on_pgdown)\n\n self.write_to_file = QShortcut(QKeySequence('Ctrl+S'), self)\n self.write_to_file.activated.connect(self.on_ctrl_s)\n\n self.new_row = QShortcut(QKeySequence('Ctrl+N'), self)\n self.new_row.activated.connect(self.on_ctrl_n)\n\n def create_tabbed_interface(self):\n self.tabs = QTabWidget()\n self.tabs.setDocumentMode(True)\n self.tabs.setTabPosition(QTabWidget.North)\n self.tabs.setMovable(True)\n\n def add_table_tab(self, table):\n layout = QVBoxLayout()\n table.tablewid_signal.connect(self.open_item_in_tab)\n layout.addWidget(table)\n\n wid = QWidget()\n wid.setLayout(layout)\n self.tabs.addTab(wid, 'Wordlist')\n\n @pyqtSlot(QTableWidgetItem)\n def open_item_in_tab(self, cell: QTableWidgetItem):\n lex_wid = self.create_lexeme_tab_layout_widget(cell.sql_id)\n lex_name = self.lexemes_table.cells[cell.sql_id]['lexeme'].get_value()\n\n # addTab also returns the new tab's index, which we use\n tab_index = self.tabs.addTab(lex_wid, 'Item Edit - ' + lex_name)\n self.tabs.setCurrentIndex(tab_index)\n\n def create_lexeme_tab_layout_widget(self, sql_id: int):\n wid = ItemEditWidget(sql_id, self.lexemes_table.cells[sql_id])\n wid.close_signal.connect(self.on_ctrl_w)\n wid.save_signal.connect(self.on_save_item)\n return wid\n\n def on_ctrl_w(self):\n self.close_current_tab()\n\n def close_current_tab(self):\n active_tab = self.tabs.currentIndex()\n if self.tabs.tabText(active_tab) == 'Wordlist':\n QApplication.beep()\n else:\n # removeTab removes only the tab, but not the page widget!\n self.tabs.removeTab(self.tabs.currentIndex())\n\n def on_pgup(self):\n active_tab = self.tabs.currentIndex()\n if active_tab > 0:\n self.tabs.setCurrentIndex(active_tab - 1)\n\n def on_pgdown(self):\n active_tab = self.tabs.currentIndex()\n if active_tab < self.tabs.count():\n self.tabs.setCurrentIndex(active_tab + 1)\n\n @pyqtSlot(int, dict)\n def on_save_item(self, sql_id: int, item_values: dict):\n # so far i'm modifying the lexemes table directly, should abstract\n table = self.lexemes_table.cells\n for column in table[sql_id]:\n table[sql_id][column].setText(item_values[column])\n self.close_current_tab()\n\n def on_ctrl_n(self):\n timestamp = get_time_str()\n sql_id = self.db.new_entry('lexemes', timestamp)\n self.new_row_signal.emit(sql_id)\n\n def on_ctrl_s(self):\n for sql_id, row in self.lexemes_table.cells.items():\n for colname, cell in row.items():\n self.db.update_entry('lexemes', sql_id, colname, cell.get_value())\n self.db.conn.commit()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n font = QFont('SansSerif', 16)\n app.setFont(font)\n window = MainWindow()\n window.show()\n app.exec_()\n","sub_path":"MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"145075214","text":"import torch\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom torch.utils import data\nfrom torch import nn\nimport time\nfrom IPython import display\nimport seaborn as sns\nimport numpy as np\nimport random\nfrom torch.nn import functional as F\nimport torchvision\nfrom torchvision import datasets, transforms\nfrom sklearn.manifold import TSNE\nimport cv2\nimport sys\n\n\nif __name__ == \"__main__\":\n # load and preprocess data\n lr, epochs, batch_size, eta = 0.001, 200, 500, 0.1\n csv_path = sys.argv[1]\n test_path = sys.argv[2]\n param1 = sys.argv[3]\n param2 = sys.argv[4]\n param3 = sys.argv[5]\n\n trans2 = transforms.Compose([transforms.Grayscale(), transforms.Resize((32, 32)), transforms.ToTensor()])\n test_imgs = datasets.ImageFolder(test_path, transform=trans2)\n test_iter = torch.utils.data.DataLoader(test_imgs, batch_size=batch_size, shuffle=False)\n\n # construct net\n class extractor(nn.Module):\n def __init__(self):\n super().__init__()\n self.stage1 = nn.Sequential(nn.Conv2d(1, 64, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(64),\n nn.Conv2d(64, 64, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(64),\n nn.Conv2d(64, 64, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(64),\n nn.MaxPool2d(kernel_size=2), nn.Dropout(p=0.5))\n\n self.stage2 = nn.Sequential(nn.Conv2d(64, 128, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(128),\n nn.Conv2d(128, 128, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(128),\n nn.Conv2d(128, 128, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(128),\n nn.MaxPool2d(kernel_size=2), nn.Dropout(p=0.5))\n\n self.stage3 = nn.Sequential(nn.Conv2d(128, 128, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(128),\n nn.Conv2d(128, 128, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(128),\n nn.Conv2d(128, 128, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(128),\n nn.MaxPool2d(kernel_size=2), nn.Dropout(p=0.5))\n\n self.stage4 = nn.Sequential(nn.Conv2d(128, 256, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(256),\n nn.Conv2d(256, 256, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(256),\n nn.Conv2d(256, 256, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(256),\n nn.MaxPool2d(kernel_size=2), nn.Dropout(p=0.5))\n\n self.stage5 = nn.Sequential(nn.Conv2d(256, 256, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(256),\n nn.Conv2d(256, 256, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(256),\n nn.Conv2d(256, 256, kernel_size=3, padding=1), nn.ReLU(), nn.BatchNorm2d(256),\n nn.MaxPool2d(kernel_size=2), nn.Dropout(p=0.5))\n\n self.conv = nn.Sequential(self.stage1, self.stage2, self.stage3, self.stage4, self.stage5)\n\n def forward(self, x):\n return self.conv(x).squeeze()\n\n\n class classifier(nn.Module):\n def __init__(self):\n super().__init__()\n self.linear = nn.Sequential(nn.Linear(256, 1024), nn.ReLU(), nn.Linear(1024, 1024), nn.ReLU(),\n nn.Linear(1024, 9))\n\n def forward(self, src):\n return self.linear(src)\n\n\n class discriminator(nn.Module):\n def __init__(self):\n super().__init__()\n self.linear = nn.Sequential(nn.Linear(256, 512), nn.BatchNorm1d(512), nn.ReLU(),\n nn.Linear(512, 512), nn.BatchNorm1d(512), nn.ReLU(),\n nn.Linear(512, 512), nn.BatchNorm1d(512), nn.ReLU(),\n nn.Linear(512, 512), nn.BatchNorm1d(512), nn.ReLU(),\n nn.Linear(512, 1))\n\n def forward(self, x):\n return self.linear(x)\n\n def try_gpu(i=0):\n if torch.cuda.device_count() >= i + 1:\n return torch.device(f'cuda:{i}')\n return torch.device('cpu')\n\n\n fea = extractor().cuda()\n fea.load_state_dict(torch.load(param1))\n cla = classifier().cuda()\n cla.load_state_dict(torch.load(param2))\n dis = discriminator().cuda()\n dis.load_state_dict(torch.load(param3))\n\n # predict\n argmax = lambda x, *args, **kwargs: x.argmax(*args, **kwargs)\n\n def predict():\n cla.eval()\n fea.eval()\n test = pd.read_csv(csv_path)\n result = []\n for _, (x_test, _) in enumerate(test_iter):\n x_test = x_test.to(try_gpu())\n y_pred = cla(fea(x_test))\n result.extend(argmax(y_pred, axis=1).cpu().numpy().tolist())\n\n index = [i for i in range(0, len(test))]\n output = pd.DataFrame({'ID': index, 'label': result})\n output.to_csv('Answer.csv', index=None, encoding='utf8')\n\n\n predict()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"588243156","text":"def calculate_portfolio(obj, df, indicator_type):\n \"\"\"\n loop through df['signals']\n long:\n if df.signals == 1.0 buy long\n when df.signals == -1.0 sell\n short:\n if df.signals == -1.0 sell short \n when df.signals == 1.0 exit short position\n note:\n only take first df.signal of 1.0, -1.0, \n maybe series before you reach next sell signal\n indicator_type:: 'stockstats' or 'tapy':\n indicate if stockstats:'close' or tapy:'Close'\n \"\"\"\n obj.indicator = indicator_type\n close_dic = {\"tapy\": \"Close\", \"stockstats\": \"close\"}\n close = close_dic[indicator_type]\n long_capital = 100000.0\n long_position = 0.0\n in_position = False\n df[\"long_p-l\"] = 0.0\n df[\"long_positions\"] = 0.0\n df[\"long_capital\"] = 0.0\n df[\"long_value\"] = 0.0\n df[\"long_buys\"] = 0.0\n for i in range(len(df)):\n if (df[\"signals\"][i] == 1.0) and (in_position == False):\n long_position = long_capital / df[close][i]\n in_position = True\n if (df[\"signals\"][i] == -1.0) and (in_position == True):\n new_capital = long_position * df[close][i]\n df[\"long_p-l\"][i] = (long_capital - new_capital) * -1\n long_capital = new_capital\n long_position = 0.0\n in_position = False\n df[\"long_positions\"][i] = long_position\n df[\"long_capital\"][i] = long_capital\n print(df)\n df[\"long_value\"] = sum(df[\"long_p-l\"])\n print(\"long_value\", sum(df[\"long_p-l\"]))\n df[\"long_buys\"] = len(df[\"long_p-l\"][df[\"long_p-l\"] != 0.0])\n print(\"long buys\", len(df[\"long_p-l\"][df[\"long_p-l\"] != 0.0]))\n df[\"avg_buys\"] = 0.0\n df[\"avg_buys\"] = (\n df[\"long_value\"][len(df) - 1] / df[\"long_buys\"][len(df) - 1]\n if df[\"long_buys\"][len(df) - 1] != 0.0\n else 0.0\n )\n print(\"avg\", df[\"avg_buys\"][0])\n df[\"long_high\"] = df[\"long_p-l\"].max()\n df[\"long_low\"] = df[\"long_p-l\"].min()\n\n \"\"\"\n when selling short, get percent of close price of the day selling\n than take capital from when you bought the short times sell price percent\n \"\"\"\n short_capital = 100000.0\n short_position = 0.0\n short_price = 0.0\n sell_price = 0.0\n in_position = False\n df[\"short_positions\"] = 0.0\n df[\"short_capital\"] = 0.0\n df[\"short_p-l\"] = 0.0\n df[\"short_price\"] = 0.0\n df[\"sell_price\"] = 0.0\n df[\"avg_sells\"] = 0.0\n df[\"short_high\"] = 0.0\n df[\"short_low\"] = 0.0\n for b in range(len(df)):\n if (df[\"signals\"][b] == -1.0) and (in_position == False):\n short_position = short_capital / df[close][b]\n short_price = df[close][b]\n in_position = True\n print(\"neg\")\n if (df[\"signals\"][b] == 1.0) and (in_position == True):\n sell_price_percent = short_price / df[close][b]\n df[\"short_p-l\"][b] = (\n short_capital - (short_capital * sell_price_percent)\n ) * -1\n short_capital = short_capital * sell_price_percent\n short_position = 0.0\n sell_price = df[close][b]\n in_position = False\n df[\"sell_price\"][b] = sell_price\n df[\"short_price\"][b] = short_price\n df[\"short_positions\"][b] = short_position\n df[\"short_capital\"][b] = short_capital\n try:\n df[\"short_value\"] = sum(df[\"short_p-l\"])\n df[\"short_sells\"] = len(df[\"short_p-l\"][df[\"short_p-l\"] != 0.0])\n df[\"avg_sells\"] = (\n df[\"short_value\"][-1] / df[\"short_sells\"][-1]\n if df[\"short_sells\"][-1] != 0\n else 0.0\n )\n df[\"short_high\"] = (\n df[\"short_p-l\"].max() if df[\"short_p-l\"][len(df) - 1] != 0.0 else 0.0\n )\n df[\"short_low\"] = df[\"short_p-l\"].min()\n except:\n pass\n\n # print(df)\n if len(obj.df_results == 0):\n obj.df_results.append(df)\n if len(obj.df_results > 0):\n df1 = obj.df_results[0]\n if df1[\"long_value\"][-1] < df[\"long_value\"][-1]:\n obj.df_results = [df]\n\n\nif __name__ == \"__main__\":\n pass\n\n","sub_path":"calculate_portfolio.py","file_name":"calculate_portfolio.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"255689580","text":"from apiAccountDatabase import Database\n\nimport unittest\n\n\nclass Test_ValidateMoneyString(unittest.TestCase):\n def testValidNoDecimalString(self):\n validNoDecimalStringTestCases = {\"10\": 1000, \"-11\": -1100}\n for (\n testCaseMoneyString,\n testCaseMoneyValue,\n ) in validNoDecimalStringTestCases.items():\n moneyValue = Database.validateAndConvertMoneyStringToInt(\n testCaseMoneyString\n )\n self.assertEqual(moneyValue, testCaseMoneyValue)\n\n def testValidWithDecimalString(self):\n validWithDecimalStringTestCases = {\n \"10.\": 1000,\n \"-11.\": -1100,\n \"10.5\": 1050,\n \"-12.3\": -1230,\n \"10.19\": 1019,\n \"-11.85\": -1185,\n \"0.10\": 10,\n \"-0.12\": -12,\n }\n for (\n testCaseMoneyString,\n testCaseMoneyValue,\n ) in validWithDecimalStringTestCases.items():\n moneyValue = Database.validateAndConvertMoneyStringToInt(\n testCaseMoneyString\n )\n self.assertEqual(moneyValue, testCaseMoneyValue)\n","sub_path":"unittests/testValidateMoneyString.py","file_name":"testValidateMoneyString.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"122050690","text":"from matplotlib import colors, cm, colorbar, ticker, patches\nfrom create_results import get_results, sensor_labels, insitu_file_fmt, load_Rrs\nfrom QAA import wavelengths\nimport matplotlib.pyplot as plt \nimport seaborn as sns\nimport numpy as np\n\n\nif __name__ == '__main__':\n\tdata = get_results()\n\torder = ['MSI', 'OLI', 'VI', 'OLCI']\n\n\tvmin = -1e-3\n\tvmax = 1e-3\n\tcmap = cm.Reds\n\tspan = 5\n\ttick = [5e-5, 5e-4, 5e-3]\n\tloc = ticker.FixedLocator(tick)\n\t\n\tplt.figure(figsize=(13,6))\n\n\tn_methods = len(data.methods)-1\n\tn_sensors = len(sensor_labels)-1\n\taxs = []\n\tks = [0, 4, 8]\n\trs = [4, 4, 2]\n\tfor k, target_sensor in enumerate(order[:-1]):\n\n\t\tfor j, method in enumerate(list(sorted(data.methods))[:1] + list(sorted(data.methods))[2:]+[list(sorted(data.methods))[1]]):\n\t\t\tax = plt.subplot2grid((10, span*len(data.methods)+3), (ks[k], j*span), colspan=span, rowspan=rs[k])\n\t\t\taxs.append(ax)\n\n\t\t\tylbl= []\n\t\t\terr = []\n\t\t\tfor source_sensor in sorted(order):\n\t\t\t\tif source_sensor == target_sensor: \n\t\t\t\t\tcontinue\n\n\t\t\t\tif source_sensor == 'OLI' and target_sensor != 'MSI': continue\n\t\t\t\tif source_sensor == 'MSI' and target_sensor != 'OLI': continue\n\t\t\t\tif source_sensor == 'VI' and target_sensor not in ['MSI', 'OLI']: continue\n\n\t\t\t\ttarget = load_Rrs(insitu_file_fmt % target_sensor)\n\t\t\t\tif target_sensor == 'MSI': target = target[:,:4]\n\t\t\t\ttarget_wave = np.array(wavelengths[target_sensor][:9])\n\n\t\t\t\tif 'Mélin' in method and source_sensor in ['MSI', 'OLI']:\n\t\t\t\t\terr.append([np.nan] * len(target_wave))\n\t\t\t\telse:\n\t\t\t\t\terr.append( ((data[method][(source_sensor, target_sensor)] - target)**2).mean(axis=0)**.5 )\n\n\t\t\t\tylbl.append(source_sensor.replace('VI', 'VIIRS'))\n\n\t\t\tylbl = ylbl[::-1]\n\t\t\th = sns.heatmap(err, ax=ax, cbar=False, cmap=cmap, linecolor='black', linewidth=1, robust=True, square=True,\n\t\t\t\t\t\t\tnorm=colors.LogNorm(vmin=5e-5, vmax=5e-3), vmin=5e-5, vmax=5e-3, cbar_kws={'ticks':loc})#, norm=colors.SymLogNorm(8e-5))\n\t\t\t\n\t\t\tdef plt_x(sensor_name):\n\t\t\t\tx1, x2 = ax.get_xlim()\n\t\t\t\ty = [ylbl.index(sensor_name), ylbl.index(sensor_name)+1]\n\t\t\t\tax.add_patch(\n\t\t\t\t\tpatches.Rectangle(\n\t\t\t\t\t\t(x1, y[0]), \n\t\t\t\t\t\tx2 - x1, # width\n\t\t\t\t\t\t1, # height\n\t\t\t\t))\n\n\t\t\tif 'Mélin' in method:\n\t\t\t\tif 'MSI' in ylbl: plt_x('MSI') \n\t\t\t\tif 'OLI' in ylbl: plt_x('OLI')\n\n\t\t\tax.set_xticklabels([r'$\\mathrm{\\bf{%s}}$'%xl for xl in np.round(target_wave).astype(np.int32)], fontsize=14, weight='extra bold')\n\t\t\tax.set_xticks(ax.get_xticks(), [r'$\\mathbf{%s}$' % x for x in np.round(target_wave).astype(np.int32)])\n\t\t\tif k == 0: \tax.set_title(method, fontsize=16)\n\t\t\tif j == n_methods:\t\n\t\t\t\tax.set_yticklabels([])\n\t\t\t\tax.set_ylabel(r'$\\sf{\\bf{%s}}$%s$\\bf{%s}$$\\sf{\\bf{ / %s}}$' % (sensor_labels[target_sensor].split('-')[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'-' if len(sensor_labels[target_sensor].split('-')) == 2 else '',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsensor_labels[target_sensor].split('-')[1] if \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlen(sensor_labels[target_sensor].split('-')) == 2 else '',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t target_sensor.replace('VI', 'VIIRS')), \n\t\t\t\t\t\t\t\tfontsize=10 if target_sensor == 'AER' else 14)\n\t\t\t\tax.yaxis.set_label_position('right')\n\t\t\telif j == 0: \n\t\t\t\tax.set_yticklabels([r'$\\bf{%s}$'%yl for yl in ylbl], rotation='horizontal', fontsize=12)\n\t\t\telse: ax.set_yticklabels([])\n\n\n\tax = plt.subplot2grid((len(sensor_labels)-1, span*len(data.methods)+3), (0, span*j+span+2), rowspan=len(sensor_labels)-1, colspan=1)\n\tcb = plt.colorbar(h.get_children()[0], cax=ax, ax=axs, orientation='vertical', ticks=loc)\n\tcb.ax.yaxis.set_ticks(tick)\n\tcb.locator = loc \n\tcb.formatter = ticker.FixedFormatter(['%.0e' % t for t in tick])\n\tcb.ax.yaxis.set_ticks_position('left')\n\tcb.update_ticks()\n\tcb.set_label(r'RMSE $(\\frac{1}{sr})$', fontsize=16)\n\n\tplt.gcf().text(.5, 0.02, 'Band Center (nm)', fontsize=18, ha='center')\n\tplt.gcf().text(.03, .55, 'Reference Sensor', fontsize=18, va='center', rotation='vertical')\n\tplt.gcf().text(.87, .55, 'Target Sensor', fontsize=18, va='center', rotation='vertical')\n\n\tplt.subplots_adjust(wspace=1, hspace=0, right=.95, left=.1, bottom=.06, top=.95)#left=.1, wspace=.07, hspace=.07, bottom = .18, top=.9, right=.86)\n\t# plt.savefig('Results/heatmap.png', dpi=600)\n\tplt.show()\n","sub_path":"heatmap.py","file_name":"heatmap.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"341363858","text":"import numpy as np\nimport pandas as pd\nimport geopandas as gpd\nfrom shapely.geometry import Point\nfrom geopandas import GeoSeries, GeoDataFrame\nfrom haversine import haversine\n\n# get the [latitude, longitude] pair via station ID\ndef get_location_by_ID(data, station_id):\n if station_id not in data.st_id.values:\n print('Error: the station ID not found in the database')\n location = data[data.st_id == station_id][['latitude', 'longitude']].values\n return tuple(location.flat)\n\n# get the name of the station via station ID\ndef get_name_by_ID(data, station_id):\n if station_id not in data.st_id.values:\n print('Error: the station ID not found in the database')\n name = data[data.st_id == station_id]['name']\n return name\n\ndef calculate_minimum_distances2(stations_data, station_id, locations,\n dict_keys=['st_id', 'closest_loc_index', 'closest_distance']):\n num_rows = len(locations)\n distances = np.zeros(num_rows)\n loc1 = get_location_by_ID(stations_data, station_id)\n for i, loc2 in enumerate(locations):\n dist = haversine(loc1, loc2)\n distances[i] = dist\n min_dist = np.min(distances)\n min_dist_index = np.argmin(distances).astype(int)\n return {dict_keys[0]: station_id, dict_keys[1]: min_dist_index, dict_keys[2]: min_dist}\n\n# Import original bike station data\nprint('READING In Bike Station Information...')\nbike_info = pd.read_csv('./data/processed/station_info_1.csv')\n\npath = './data/geolocation/'\n\nadditions = {\n 'colleges':\n {'file_name': 'colleges.geojson',\n 'stem': 'colleges',\n 'stem_key': 'college'},\n 'subways':\n {'file_name': 'subway_entrances.geojson',\n 'stem': 'subways',\n 'stem_key': 'subway'},\n 'theaters':\n {'file_name': 'theaters.geojson',\n 'stem': 'theaters',\n 'stem_key': 'theater'},\n 'museums':\n {'file_name': 'museums.geojson',\n 'stem': 'museums',\n 'stem_key': 'museum'}\n }\n\nfor addition in additions.keys():\n file_name = additions[addition]['file_name']\n file_path = path + file_name\n stem = additions[addition]['stem']\n stem_key = additions[addition]['stem_key']\n stem_name = 'closest_' + stem_key\n\n print('READING IN GEOLOCATIONS FOR ' + stem.upper() + '...')\n geo = gpd.read_file(file_path)\n geo_loc_key = stem_key + '_location'\n geo[geo_loc_key] = None\n for ind in geo.index:\n lat = geo.geometry[ind].y\n lng = geo.geometry[ind].x\n geo[geo_loc_key].iloc[ind] = tuple([lat, lng])\n\n print('APPENDING GEOLOCATION INFOMATION FOR ' + stem.upper() + '...')\n labels1 = ['st_id',\n ('closest_' + stem_key + '_ind'),\n ('closest_' + stem_key +'_distance')]\n distances = []\n for st in bike_info.st_id:\n res = calculate_minimum_distances2(bike_info, st,\n geo[geo_loc_key], dict_keys=labels1)\n res[stem_name] = geo.iloc[res[labels1[1]]]['name']\n distances.append(res)\n additional_info = pd.DataFrame(distances)\n bike_info = pd.merge(bike_info, additional_info, on='st_id')\n bike_info = bike_info.drop(labels1[1], axis=1)\n\n# Save file\nprint('SAVING to a File...')\nbike_info.to_csv('./data/processed/station_info_4_test3.csv')\nprint('...PRCESSING Complete')\n","sub_path":"codes/extension_test2.py","file_name":"extension_test2.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"425020306","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nfrom buildbuild.views import Home\nfrom teams.views import MakeTeamView\nfrom projects.views import MakeProjectView\nfrom django.contrib.auth.decorators import login_required\nfrom teams import views\nfrom users.views import Login, Logout, \\\n SignUp\nfrom teams.views import TeamList\nfrom projects.views import MakeProjectView\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'buildbuild.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^$', Home.as_view(), name='home'),\n url(r'^api/', include('api.urls', namespace=\"api\")),\n url(r'^admin/', include(admin.site.urls)),\n \n # users' urls\n url(r'^users/', include('users.urls', namespace='users')),\n url(r'^login/', Login.as_view(), name=\"login\"),\n url(r'^logout/', Logout.as_view(), name=\"logout\"),\n url(r'^signup/', SignUp.as_view(), name=\"signup\"),\n\n \n # teams' urls\n url(r'^teams/', include('teams.urls', namespace='teams')),\n url(r'^teams/$', TeamList.as_view(), name=\"teamlist\"),\n url(r'^teams/([0-9]+)/$', 'teams.views.team_page', name='team_page'),\n \n # projects' urls\n url(r'^projects/', include('projects.urls', namespace='projects')),\n url(\n r'^teams/([0-9]+)/projects/([0-9]+)/$', \n 'projects.views.project_page', \n name='project_page',\n ),\n url(\n r'^teams/(?P[0-9]+)/projects/new/$',\n login_required(MakeProjectView.as_view()),\n name=\"makeproject\"\n ), \n # dockerbuild's urls\n url(\n r'^dockerbuild/', \n include('dockerbuild.urls', namespace='dockerbuild')\n ),\n)\n","sub_path":"buildbuild/buildbuild/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"274983759","text":"from abc import ABC, abstractmethod\nfrom typing import Optional\n\nimport boto3\nfrom spotty.providers.aws.aws_resources.subnet import Subnet\nfrom spotty.providers.aws.aws_resources.vpc import Vpc\nfrom spotty.providers.aws.config.instance_config import InstanceConfig\nfrom spotty.providers.aws.deployment.project_resources.key_pair import KeyPairResource\n\n\nclass AbstractAwsDeployment(ABC):\n\n def __init__(self, project_name: str, instance_config: InstanceConfig, fork_id: Optional[str] = None):\n self._project_name = project_name\n self._fork_id = fork_id\n self._instance_config = instance_config\n self._ec2 = boto3.client('ec2', region_name=instance_config.region)\n\n @property\n def instance_config(self) -> InstanceConfig:\n return self._instance_config\n\n @property\n @abstractmethod\n def ec2_instance_name(self) -> str:\n \"\"\"Name for EC2 instance.\"\"\"\n raise NotImplementedError\n\n @property\n def key_pair(self) -> KeyPairResource:\n return KeyPairResource(self._project_name, self.instance_config.region, self.instance_config.provider_name)\n\n def get_vpc_id(self) -> str:\n \"\"\"Returns VPC ID that should be used for deployment.\"\"\"\n if self.instance_config.subnet_id:\n vpc_id = Subnet.get_by_id(self._ec2, self.instance_config.subnet_id).vpc_id\n else:\n default_vpc = Vpc.get_default_vpc(self._ec2)\n if not default_vpc:\n raise ValueError('Default VPC not found')\n\n vpc_id = default_vpc.vpc_id\n\n return vpc_id\n","sub_path":"spotty/providers/aws/deployment/abstract_aws_deployment.py","file_name":"abstract_aws_deployment.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"15138382","text":"import sys\n\nfrom strictdoc.backend.dsl.models.inline_link import InlineLink\nfrom strictdoc.backend.dsl.models.requirement import Requirement\nfrom strictdoc.core.document_iterator import DocumentCachingIterator\nfrom strictdoc.core.document_tree import DocumentTree\nfrom strictdoc.core.error_message import ErrorMessage\nfrom strictdoc.core.traceability_index import (\n TraceabilityIndex,\n FileTraceabilityIndex,\n)\nfrom strictdoc.core.tree_cycle_detector import TreeCycleDetector\nfrom strictdoc.helpers.timing import timing_decorator\n\n\nclass TraceabilityIndexBuilder:\n @staticmethod\n @timing_decorator(\"Collect traceability information\")\n def create(document_tree: DocumentTree):\n requirements_map = {}\n requirements_children_map = {}\n tags_map = {}\n document_iterators = {}\n file_traceability_index = FileTraceabilityIndex()\n\n # It seems to be impossible to accomplish everything in just one for\n # loop. One particular problem that requires two passes: it is not\n # possible to know after one iteration if any of the requirements\n # reference parents that do not exist.\n #\n # Step #1:\n # - Collect a dictionary of all requirements in the document tree:\n # {req_id: req}\n # - Each requirement's 'parents_uids' is populated with the forward\n # declarations of its parents uids.\n # - A separate map is created: {req_id: [req_children]}\n # At this point some information is in place but it was not known if\n # some of the UIDs could not be resolved which is the task of the second\n # step.\n #\n # Step #2:\n # - Check if each requirement's has valid parent links.\n # - Resolve parent forward declarations\n # - Re-assign children declarations\n # - Detect cycles\n # - Calculate depth of both parent and child links.\n for document in document_tree.document_list:\n document_iterator = DocumentCachingIterator(document)\n document_iterators[document] = document_iterator\n if document.name not in tags_map:\n tags_map[document.name] = {}\n for node in document_iterator.all_content():\n if not node.uid:\n continue\n if node.uid in requirements_map:\n other_req_doc = requirements_map[node.uid][\"document\"]\n if other_req_doc == document:\n print(\n \"error: DocumentIndex: \"\n \"two nodes with the same UID \"\n \"exist in the same document: \"\n f'{node.uid} in \"{document.title}\".'\n )\n else:\n print(\n \"error: DocumentIndex: \"\n \"two nodes with the same UID \"\n \"exist in two different documents: \"\n f'{node.uid} in \"{document.title}\" and '\n f'\"{other_req_doc.title}\".'\n )\n sys.exit(1)\n requirements_map[node.uid] = {\n \"document\": document,\n \"requirement\": node,\n \"parents\": [],\n \"parents_uids\": [],\n \"children\": [],\n }\n if not node.is_requirement:\n continue\n requirement: Requirement = node\n document_tags = tags_map[document.name]\n for tag in requirement.tags:\n if tag not in document_tags:\n document_tags[tag] = 0\n document_tags[tag] += 1\n if requirement.uid not in requirements_children_map:\n requirements_children_map[requirement.uid] = []\n for ref in requirement.references:\n if ref.ref_type == \"File\":\n file_traceability_index.register(requirement)\n continue\n if ref.ref_type != \"Parent\":\n continue\n requirements_map[requirement.uid][\"parents_uids\"].append(\n ref.path\n )\n if ref.path not in requirements_children_map:\n requirements_children_map[ref.path] = []\n requirements_children_map[ref.path].append(requirement)\n\n # Now iterate over the requirements again to build an in-depth map of\n # parents and children.\n parents_cycle_detector = TreeCycleDetector(requirements_map)\n children_cycle_detector = TreeCycleDetector(requirements_map)\n\n requirements_child_depth_map = {}\n requirements_parent_depth_map = {}\n documents_ref_depth_map = {}\n document_parents_map = {}\n document_children_map = {}\n\n for document in document_tree.document_list:\n document_parents_map.setdefault(document, set())\n document_children_map.setdefault(document, set())\n document_iterator = document_iterators[document]\n max_parent_depth, max_child_depth = 0, 0\n\n for node in document_iterator.all_content():\n if node.is_section:\n for free_text in node.free_texts:\n for part in free_text.parts:\n if isinstance(part, InlineLink):\n if part.link not in requirements_map:\n print(\n ErrorMessage.inline_link_uid_not_exist(\n part.link\n )\n )\n sys.exit(1)\n if not node.is_requirement:\n continue\n requirement: Requirement = node\n if not requirement.uid:\n continue\n\n # Now it is possible to resolve parents first checking if they\n # indeed exist.\n requirement_parent_ids = requirements_map[requirement.uid][\n \"parents_uids\"\n ]\n for requirement_parent_id in requirement_parent_ids:\n if requirement_parent_id not in requirements_map:\n # TODO: Strict variant of the behavior will be to stop\n # and raise an error message.\n print(\n f\"warning: [DocumentIndex.create] \"\n f\"Requirement {requirement.uid} references \"\n f\"parent requirement which doesn't exist: \"\n f\"{requirement_parent_id}\"\n )\n requirements_children_map.pop(\n requirement_parent_id, None\n )\n continue\n parent_requirement = requirements_map[\n requirement_parent_id\n ][\"requirement\"]\n requirements_map[requirement.uid][\"parents\"].append(\n parent_requirement\n )\n # Set document dependencies.\n parent_document = requirements_map[requirement_parent_id][\n \"document\"\n ]\n document_parents_map.setdefault(requirement.document, set())\n document_parents_map[requirement.document].add(\n parent_document\n )\n document_children_map.setdefault(parent_document, set())\n document_children_map[parent_document].add(\n requirement.document\n )\n\n # [SDOC-VALIDATION-NO-CYCLES]\n # Detect cycles\n parents_cycle_detector.check_node(\n requirement.uid,\n lambda requirement_id: requirements_map[requirement_id][\n \"parents_uids\"\n ],\n )\n children_cycle_detector.check_node(\n requirement.uid,\n lambda requirement_id: list(\n map(\n lambda current_requirement: current_requirement.uid,\n requirements_children_map[requirement_id],\n )\n ),\n )\n # [/SDOC-VALIDATION-NO-CYCLES]\n\n if requirement.uid not in requirements_child_depth_map:\n child_depth = 0\n requirements_map[requirement.uid][\n \"children\"\n ] = requirements_children_map[requirement.uid]\n queue = requirements_children_map[requirement.uid]\n while True:\n if len(queue) == 0:\n break\n child_depth += 1\n deeper_queue = []\n for child in queue:\n deeper_queue.extend(\n requirements_children_map[child.uid]\n )\n queue = deeper_queue\n requirements_child_depth_map[requirement.uid] = child_depth\n if max_child_depth < child_depth:\n max_child_depth = child_depth\n\n # Calculate parent depth\n if requirement.uid not in requirements_parent_depth_map:\n parent_depth = 0\n queue = requirement_parent_ids\n while True:\n if len(queue) == 0:\n break\n parent_depth += 1\n deeper_queue = []\n for parent_uid in queue:\n if parent_uid not in requirements_map:\n continue\n deeper_queue.extend(\n requirements_map[parent_uid][\"parents_uids\"]\n )\n queue = deeper_queue\n requirements_parent_depth_map[\n requirement.uid\n ] = parent_depth\n if max_parent_depth < parent_depth:\n max_parent_depth = parent_depth\n documents_ref_depth_map[document] = max(\n max_parent_depth, max_child_depth\n )\n traceability_index = TraceabilityIndex(\n document_iterators,\n requirements_map,\n tags_map,\n documents_ref_depth_map,\n document_parents_map,\n document_children_map,\n file_traceability_index,\n )\n return traceability_index\n","sub_path":"strictdoc/core/traceability_index_builder.py","file_name":"traceability_index_builder.py","file_ext":"py","file_size_in_byte":11150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"125339674","text":"# %load q02_data_cleaning_all/build.py\n# Default Imports\nimport sys, os\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom logistic_regression_project.q01_outlier_removal.build import outlier_removal\n\nloan_data = pd.read_csv('data/loan_prediction_uncleaned.csv')\nloan_data = loan_data.drop('Loan_ID', 1)\nloan_data = outlier_removal(loan_data)\n\n\n# Write your solution here :\ndef data_cleaning(data):\n np.random.seed(9)\n X = data.iloc[:,:-1]\n y = data.iloc[:,-1]\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=9)\n X_train_loanamt = X_train[X_train['LoanAmount'].notnull()]['LoanAmount'].mean()\n X_train.loc[X_train['LoanAmount'].isnull(), 'LoanAmount'] = X_train_loanamt\n X_test.loc[X_test['LoanAmount'].isnull(), 'LoanAmount'] = X_train_loanamt\n cat = ['Gender', 'Married', 'Dependents', 'Self_Employed', 'Loan_Amount_Term', 'Credit_History']\n for val in cat:\n temp = X_train[X_train[val].notnull()][val].mode()\n X_train.loc[X_train[val].isnull(), val] = temp\n X_test.loc[X_test[val].isnull(), val] = temp\n\n return X, y, X_train, X_test, y_train, y_test\n","sub_path":"q02_data_cleaning_all/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"262191120","text":"#\n# Copyright (c) 2016, Prometheus Research, LLC\n#\n\nfrom rex.action import typing\nfrom rex.widget import Field\nfrom .base import FormBuilderAction\n\n\n__all__ = (\n 'PickDraftAction',\n)\n\n\nclass PickDraftAction(FormBuilderAction):\n name = 'formbuilder-pick-draft'\n js_type = 'rex-formbuilder', 'PickDraft'\n\n entity = Field(typing.RowTypeVal())\n\n def context(self):\n return (\n self.domain.record(self.entity),\n self.domain.record(draft=typing.ValueType('text')),\n )\n\n","sub_path":"src/rex.formbuilder/src/rex/formbuilder/action/pick_draft.py","file_name":"pick_draft.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"331901049","text":"from BaseClass import BaseClass\nfrom FatherClass import FatherClass\n\nimport sys\n\nsys.path.append('word')\n\nimport class1\n\nclass SubClass(FatherClass, BaseClass):\n def __init__(self):\n super().__init__()\n\n def hello(self, msg):\n super().hello(msg)\n print('SubClass', msg)\n\n def __str__(self):\n return f'name={self.name}, type={self.type}, model={self.model}';\n # return super().__str__()\n\n\n\nif __name__ == \"__main__\":\n subInstance = SubClass()\n subInstance.hello(\"world\")\n print(subInstance)\n\n class1 = class1.Class1()\n class1.count(\"我是中国人我爱中国\")\n class1.print()\n\n print(BaseClass.caseCount)","sub_path":"notes/5.编程实践/Python/code/SubClass.py","file_name":"SubClass.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"244686231","text":"\"\"\"\nSimple REST API\n\"\"\"\nfrom django.http import HttpResponse\nfrom django.core import serializers\nimport json\nfrom .models import NewsLanguage, NewsCategory, NewsItem\n\n\ndef index(request, language_code): # pylint: disable=W0613\n \"\"\"\n Display News items\n \"\"\"\n # pylint: disable=E1101\n\n posts = (NewsItem.objects.filter(pub_date__isnull=False, language__code__contains=language_code).\n order_by('-pub_date'))\n result = []\n if 'page' in request.GET and 'count' in request.GET:\n page = int(request.GET['page'])\n count = int(request.GET['count'])\n start = count * (page - 1)\n end = (count * page)\n posts = posts[start:end]\n for item in posts:\n result.append({'id': item.id, 'title': item.title, 'tags': [item.name for item in item.newscategory.all()], 'date': str(item.pub_date)})\n result_json = json.dumps(result)\n return HttpResponse(result_json, content_type=\"application/json\")\n\ndef singlenews(request, news_id):\n item = NewsItem.objects.filter(id=news_id)[0]\n result = {\n 'id': item.id,\n 'title': item.title,\n 'tags': [item.name for item in item.newscategory.all()],\n 'date': str(item.pub_date),\n 'content': item.content,\n 'enewsno': item.enewsno,\n }\n return HttpResponse(json.dumps(result), content_type=\"application/json\")\n\ndef categories(request): # pylint: disable=W0613\n \"\"\"\n List categories\n \"\"\"\n # pylint: disable=E1101\n news_categories = NewsCategory.objects.all()\n result = []\n for category in news_categories:\n result.append({'id': category.id, 'name': category.name})\n return HttpResponse(json.dumps(result), content_type=\"application/json\")\n\n\ndef languages(request): # pylint: disable=W0613\n \"\"\"\n List languages\n \"\"\"\n # pylint: disable=E1101\n news_languages = NewsLanguage.objects.all()\n result = []\n for language in news_languages:\n result.append({'code': language.code, 'name': language.language})\n return HttpResponse(json.dumps(result), content_type=\"application/json\")\n","sub_path":"src/news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"560030804","text":"#################################################################\n# MET v2 Metadate Explorer Tool\n#\n# This Software is Open Source. See License: https://github.com/TERENA/met/blob/master/LICENSE.md\n# Copyright (c) 2012, TERENA All rights reserved.\n#\n# This Software is based on MET v1 developed for TERENA by Yaco Sistemas, http://www.yaco.es/\n# MET v2 was developed for TERENA by Tamim Ziai, DAASI International GmbH, http://www.daasi.de\n# Current version of MET has been revised for performance improvements by Andrea Biancini,\n# Consortium GARR, http://www.garr.it\n##########################################################################\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.forms.widgets import CheckboxSelectMultiple, Widget\nfrom django.forms.extras.widgets import SelectDateWidget\nfrom django.forms.utils import ErrorDict, flatatt\n\nfrom django.utils import timezone\nfrom dateutil.relativedelta import relativedelta\n\nfrom django.utils.html import format_html\nfrom django.utils.safestring import mark_safe\nfrom met.metadataparser.models import Federation, Entity, EntityType, EntityCategory\n\n\nclass MultiURLforMetadata(Widget):\n def render(self, name, value, attrs=None):\n if value is None:\n value = \"\"\n\n final_attrs = self.build_attrs(attrs, name=name)\n output = []\n output.append(format_html(\n '', flatatt(final_attrs)))\n\n for curpair in value.split(\"|\"):\n val = ''.join(curpair)\n val = curpair.split(\";\")\n\n if len(val) == 1:\n val.append(\"All\")\n\n if val[0]:\n output.append('' %\n (val[0], val[1] or 'All'))\n\n output.append('''\n
    MetadataType
    %s%s
    \n
    \n\n \n


    \n\n
    \n Meta URL: \n \n \n
    \n ''')\n\n output.append(\n '

    ' % (name, name))\n\n output.append('''''' % (name, name, name))\n\n return mark_safe('\\n'.join(output))\n\n\nclass FederationForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(FederationForm, self).__init__(*args, **kwargs)\n editor_users_choices = self.fields['editor_users'].widget.choices\n self.fields['editor_users'].widget = CheckboxSelectMultiple(\n choices=editor_users_choices)\n self.fields['editor_users'].help_text = _(\"This/these user(s) can edit this \"\n \"federation and its entities\")\n\n self.fields['file_url'].widget = MultiURLforMetadata()\n\n class Meta(object):\n model = Federation\n fields = ['name', 'url', 'registration_authority', 'country', 'logo',\n 'is_interfederation', 'type', 'fee_schedule_url', 'file_url', 'file', 'editor_users']\n\n\nclass EntityForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(EntityForm, self).__init__(*args, **kwargs)\n editor_users_choices = self.fields['editor_users'].widget.choices\n self.fields['editor_users'].widget = CheckboxSelectMultiple(\n choices=editor_users_choices)\n self.fields['editor_users'].help_text = _(\"These users can edit only \"\n \"this entity\")\n\n class Meta(object):\n model = Entity\n fields = ['registration_authority', 'file_url', 'file', 'editor_users']\n\n\nclass ChartForm(forms.Form):\n fromDate = forms.DateField(label=_(u'Start date'),\n help_text=_(u\"Statistics start date.\"), initial=timezone.now() - relativedelta(days=11),\n widget=SelectDateWidget(years=range(timezone.datetime.today().year, 2012, -1)))\n\n toDate = forms.DateField(label=_(u'End date'),\n help_text=_(u\"Statistics end date.\"), initial=timezone.now() - relativedelta(days=1),\n widget=SelectDateWidget(years=range(timezone.datetime.today().year, 2012, -1)))\n\n def is_valid(self):\n result = super(ChartForm, self).is_valid()\n\n if result:\n result = self.cleaned_data['fromDate'] <= self.cleaned_data['toDate']\n if not result:\n errors = ErrorDict()\n errors['toDate'] = 'End date must not be before Start date'\n self._errors = errors\n else:\n result = (self.cleaned_data['toDate'] -\n self.cleaned_data['fromDate']).days < 12\n if not result:\n errors = ErrorDict()\n errors['fromDate'] = 'The maximum number of days shown in the chart is 11 days'\n self._errors = errors\n\n return result\n\n def __init__(self, *args, **kwargs):\n self.instance = kwargs.pop('instance')\n super(ChartForm, self).__init__(*args, **kwargs)\n\n class Meta(object):\n exclude = []\n\n\nclass EntityCommentForm(forms.Form):\n email = forms.EmailField(label=_(u'Your email address'),\n help_text=_(u\"Please enter your email address here.\"))\n\n comment = forms.CharField(max_length=1000, label=_(u\"Your comment\"),\n help_text=_(u\"Please enter your comment here.\"),\n widget=forms.Textarea(attrs={'cols': '100', 'rows': '10'}))\n\n def __init__(self, *args, **kwargs):\n self.instance = kwargs.pop('instance')\n super(EntityCommentForm, self).__init__(*args, **kwargs)\n\n class Meta(object):\n exclude = []\n\n\nclass EntityProposalForm(forms.Form):\n email = forms.EmailField(label=_(u'Your email address'),\n help_text=_(u\"Please enter your email address here.\"))\n\n federation_choices = []\n i = 0\n for federation in Federation.objects.all():\n i += i\n federation_choices.append(('%s' % federation, federation))\n\n federations = forms.MultipleChoiceField(label=_(u'Federations'), choices=federation_choices,\n help_text=_(u\"Please select the federation(s) you want to gather the entity in.\"))\n\n comment = forms.CharField(max_length=1000, label=_(u\"Your comment\"),\n help_text=_(u\"Please enter your comment here.\"),\n widget=forms.Textarea(attrs={'cols': '100', 'rows': '10'}))\n\n def __init__(self, *args, **kwargs):\n self.instance = kwargs.pop('instance')\n super(EntityProposalForm, self).__init__(*args, **kwargs)\n\n gatherd_federations = self.instance.federations.all()\n federation_choices = []\n i = 0\n for federation in Federation.objects.all().order_by('name'):\n if federation not in gatherd_federations:\n i += i\n federation_choices.append(('%s' % federation, federation))\n\n self.fields['federations'].widget.choices = federation_choices\n\n class Meta(object):\n exclude = []\n\n\nclass ServiceSearchForm(forms.Form):\n entityid = forms.CharField(max_length=200, label=_(u\"Search service ID\"),\n help_text=_(\n u\"Enter a full or partial entityid\"),\n widget=forms.TextInput(attrs={'size': '200'}))\n\n class Meta(object):\n exclude = []\n\n\nclass SearchEntitiesForm(forms.Form):\n federation_choices = [('All', 'All federations')]\n for federation in Federation.objects.all():\n federation_choices.append(('%s' % federation.id, federation))\n\n type_choices = [('All', 'All types')]\n for entity_type in EntityType.objects.all():\n type_choices.append(('%s' % entity_type, entity_type))\n\n category_choices = [('All', 'All types')]\n for entity_category in EntityCategory.objects.all():\n category_choices.append(('%s' % entity_category, entity_category))\n\n entity_type = forms.ChoiceField(label=_(u\"Entity Type\"),\n help_text=_(\n u\"Select the entity type you're interest in\"),\n choices=type_choices,\n initial=['All'])\n\n entity_category = forms.ChoiceField(label=_(u'Entity Category'),\n help_text=_(\n u\"Select the entity category you're interest in\"),\n choices=category_choices,\n initial=['All'])\n\n federations = forms.MultipleChoiceField(label=_(u\"Federation filter\"),\n help_text=_(\n u\"Select the federations you're interest in (you may select multiple)\"),\n widget=forms.CheckboxSelectMultiple,\n choices=federation_choices,\n initial=['All'])\n\n entityid = forms.CharField(max_length=200, label=_(u\"Search entity ID\"),\n help_text=_(\n u\"Enter a full or partial entityid\"),\n widget=forms.TextInput(attrs={'size': '200'}),\n required=False)\n\n page = forms.IntegerField(min_value=0, initial=1, required=False,\n widget=forms.HiddenInput(attrs={'id': 'pagination_page'}))\n export_format = forms.CharField(\n required=False, widget=forms.HiddenInput(attrs={'id': 'export_format'}))\n\n class Meta(object):\n fields = []\n","sub_path":"met/metadataparser/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":12730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"444977862","text":"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom account.serializers import RegisterSerializer\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.decorators import api_view, permission_classes,authentication_classes\nimport io\nfrom django.contrib.auth import login\nfrom account.models import User,PhoneOTP,Shopkeeper,Customer,Items,OrderItem,Order,Shopkeeper_Order_History,Customer_Order_History\nfrom account.serializers import CreateUserSerializer,LoginUserSerializer,ShopkeeperSerializer,CustomerSerializer,ItemSerializer,soh_serializer,coh_serializer\nfrom django.core.mail import send_mail\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nfrom django.shortcuts import get_object_or_404\n##from blissedmaths.utils import phone_validator, password_generator, otp_generator\nimport math,random\n# Create your views here.\n@csrf_exempt\n@authentication_classes([])\n@api_view([\"POST\"])\ndef register(request):\n\n serializer=RegisterSerializer(data=request.data)\n\n if serializer.is_valid():\n\n\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n \n return Response(serializer.errors)\ndef otp_generator() : \n \n digits = \"0123456789\"\n OTP = \"\" \n for i in range(4) : \n OTP += digits[math.floor(random.random() * 10)] \n \n return OTP \n\ndef send_otp(phone):\n \"\"\"\n This is an helper function to send otp to session stored phones or \n passed phone number as argument.\n \"\"\"\n\n if phone:\n \n key = otp_generator()\n phone = str(phone)\n otp_key = str(key)\n\n #link = f'https://2factor.in/API/R1/?module=TRANS_SMS&apikey=fc9e5177-b3e7-11e8-a895-0200cd936042&to={phone}&from=wisfrg&templatename=wisfrags&var1={otp_key}'\n \n #result = requests.get(link, verify=False)\n\n return otp_key\n else:\n return False\n\ndef sendotp_email(email):\n\n if email:\n key = otp_generator()\n email = str(email)\n otp_key = str(key)\n # subject = 'Please Confirm Your Account'\n # message = 'Your 4 Digit Verification Pin: {}'.format(otp_key)\n # email_from = '*****'\n # recipient_list = [str(emaill), ]\n # send_mail(subject, message, email_from, recipient_list)\n return otp_key\n else:\n return False\n\n\n@api_view([\"POST\"])\n@authentication_classes([])\n@csrf_exempt\ndef ValidatePhoneSendOTP(request):\n '''\n This class view takes phone number and if it doesn't exists already then it sends otp for\n first coming phone numbers'''\n\n \n phone_number = request.data.get('phone')\n print(phone_number)\n val=1\n if phone_number:\n username=phone_number\n val=0\n else:\n username=request.data.get('email')\n if username:\n username = str(username)\n user = User.objects.filter(username = username)\n if user.exists():\n return Response({'status': False, 'detail': 'User already exists'})\n # logic to send the otp and store the phone number and that otp in table. \n else:\n if val==0:\n otp = send_otp(username)\n else:\n otp=sendotp_email(username)\n print(username, otp)\n if otp:\n otp = str(otp)\n count = 0\n old = PhoneOTP.objects.filter(username = username)\n if old.exists():\n count = old.first().count\n old.first().count = count + 1\n old.first().save()\n \n else:\n count = count + 1\n \n PhoneOTP.objects.create(\n username = username, \n otp = otp,\n count = count\n \n )\n if count > 7:\n return Response({\n 'status' : False, \n 'detail' : 'Maximum otp limits reached. Kindly support our customer care or try with different number'\n })\n \n \n else:\n return Response({\n 'status': 'False', 'detail' : \"OTP sending error. Please try after some time.\"\n })\n\n return Response({\n 'status': True, 'detail': 'Otp has been sent successfully.'\n })\n else:\n return Response({\n 'status': 'False', 'detail' : \"I haven't received any phone number/e-mail. Please do a POST request.\"\n })\n\n@api_view([\"POST\"])\n@authentication_classes([])\n@csrf_exempt\ndef ValidateOTP(request):\n '''\n If you have received otp, post a request with phone and that otp and you will be redirected to set the password\n \n '''\n\n \n phone = request.data.get('phone', False)\n if phone:\n username=phone\n else:\n username=request.data.get('email',False)\n otp_sent = request.data.get('otp_sent', False)\n print(username,otp_sent)\n if username and otp_sent:\n old = PhoneOTP.objects.filter(username = username)\n if old.exists():\n old = old.first()\n otp = old.otp\n if str(otp) == str(otp_sent):\n old.logged = True\n old.save()\n\n return Response({\n 'status' : True, \n 'detail' : 'OTP matched, kindly proceed to save password'\n })\n else:\n return Response({\n 'status' : False, \n 'detail' : 'OTP incorrect, please try again'\n })\n else:\n return Response({\n 'status' : False,\n 'detail' : 'Phone/E-mail not recognised. Kindly request a new otp with this number/e-mail'\n })\n\n\n else:\n return Response({\n 'status' : 'False',\n 'detail' : 'Either phone/emaail or otp was not recieved in Post request'\n })\n\n@api_view([\"POST\"])\n@authentication_classes([])\n\n@csrf_exempt\ndef Register(request):\n\n '''Takes phone and a password and creates a new user only if otp was verified and phone is new'''\n\n \n serializer1=RegisterSerializer(data=request.data)\n if serializer1.is_valid():\n phone=request.data.get('phone',False)\n val=0\n if phone:\n username=phone\n else:\n val=1\n username=request.data.get('email',False)\n password=request.data.get('password',False)\n \n print(username)\n print(password)\n \n if username and password:\n username = str(username)\n user = User.objects.filter(username = username)\n if user.exists():\n return Response({'status': False, 'detail': 'Phone Number/E-mail already have account associated. Kindly try forgot password'})\n else:\n old = PhoneOTP.objects.filter(username = username)\n print(old)\n if old.exists():\n old = old.first()\n if old.logged:\n Temp_data = {'username': username, 'password': password }\n\n serializer = CreateUserSerializer(data=Temp_data)\n serializer.is_valid(raise_exception=True)\n user = serializer.save()\n user.save()\n ###Create Customer or Shopkeeper\n if val==0:\n log_value='phone'\n else:\n log_value='email'\n name=request.data.get('Name',None)\n email=request.data.get('email',None)\n phone=request.data.get('phone',None)\n ##print(request.data.get('shopkeeper'))\n serializer1.is_valid()\n if serializer1.validated_data['shopkeeper']:\n print(type(serializer1.validated_data['shopkeeper']))\n Token.objects.create(user=user)\n Shopkeeper.objects.create(user1=user,loggedin_with=log_value,Owner_name=name,email=email,phone=phone)\n else:\n ## Create Customer\n Customer.objects.create(user1=user,loggedin_with=log_value,Name=name,email=email,phone=phone)\n Token.objects.create(user=user)\n old.delete()\n return Response({\n 'status' : True, \n 'detail' : 'Congrts, user has been created successfully.'\n })\n\n else:\n return Response({\n 'status': False,\n 'detail': 'Your otp was not verified earlier. Please go back and verify otp'\n\n })\n else:\n return Response({\n 'status' : False,\n 'detail' : 'Phone number/E-mail not recognised. Kindly request a new otp with this number/e-mail'\n })\n \n\n\n\n\n else:\n return Response({\n 'status' : 'False',\n 'detail' : 'Either phone/e-mail or password was not recieved in Post request'\n })\n else:\n return Response(serializer1.errors)\n\n\n@api_view([\"POST\"])\n@authentication_classes([])\n@permission_classes([AllowAny])\n@csrf_exempt\ndef Login(request):\n ###print(request.user)\n serializer = LoginUserSerializer(data=request.data)\n if serializer.is_valid():\n \n user = serializer.validated_data['user']\n \n login(request, user)\n \n\n token = Token.objects.get(user=user)\n return Response(token.key) \n \n else:\n return Response({\n 'status' : 'False',\n 'detail' : 'Incorrect credentials'\n\n })\n\n@api_view([\"POST\",\"PUT\"])\n# @permission_classes([permissions.AllowAny,])\n@csrf_exempt\n\ndef update_profile(request):\n\n if request.method=='PUT':\n username=request.user.username\n \n obj=Customer.objects.filter(user1__username=username)\n print(username)\n print(obj)\n if len(obj)==1:\n obj1=Customer.objects.get(user1__username=username)\n serializer=CustomerSerializer(obj1,data=request.data,partial=True,context={'request': request})\n if serializer.is_valid():\n serializer.save()\n return Response({\"Profile updated successfuly\"})\n \n return Response(serializer.errors)\n else:\n obj1=Shopkeeper.objects.get(user1__username=username)\n serializer=ShopkeeperSerializer(obj1,data=request.data,partial=True,context={'request': request})\n if serializer.is_valid():\n serializer.save()\n return Response({\"Profile updated successfuly\"})\n \n \n \n return Response(serializer.errors)\n\n\n@api_view(['GET'])\ndef get_restaurants(request,pk=False,name=False):\n print(pk)\n if not pk:\n if name:\n restaurants=Shopkeeper.objects.filter(Restaurant_name=name)\n else: \n restaurants=Shopkeeper.objects.all()\n \n else:\n restaurants=Shopkeeper.objects.filter(Category=pk)\n serializer=ShopkeeperSerializer(restaurants,many=True)\n return Response(serializer.data)\n\n\n@api_view([\"POST\",\"PUT\"])\n# @permission_classes([permissions.AllowAny,])\n@csrf_exempt\n\ndef add_items(request):\n \n if request.method=='POST':\n serializer=ItemSerializer(data=request.data,context={'request': request})\n if serializer.is_valid():\n user1=Shopkeeper.objects.get(user1=request.user)\n Items.objects.create(user1=user1,Name=serializer.validated_data['Name'],\n Description=serializer.validated_data['Description'],Price=serializer.validated_data['Price'],Category=serializer.validated_data['Price'])\n return Response({\"Item added successfully\"})\n return Response(serializer.errors)\n\n@api_view(['POST'])\n\ndef remove_item(request,pk):\n obj=Items.objects.get(id=pk)\n obj.delete()\n\n@api_view(['GET'])\n##get items by restautant , by category, by name\ndef get_items(request,pk=False,name=False,category=False):\n ## get items by restaurant\n print(\"hi\")\n if pk and not name and not category:\n restaurant=Shopkeeper.objects.get(id=pk)\n\n li=Items.objects.filter(user1=restaurant)\n \n print(li)\n if pk and name and not category:\n restaurant=Shopkeeper.objects.get(id=pk)\n print(restaurant)\n li=Items.objects.filter(Name=name).filter(user1=restaurant)\n if pk and not name and category:\n restaurant=Shopkeeper.objects.get(id=pk)\n print(restaurant,category)\n li=Items.objects.filter(Category=category).filter(user1=restaurant)\n print(li)\n serializer=ItemSerializer(li,many=True)\n return Response(serializer.data)\n\n\n@api_view([\"POST\",\"PUT\"])\n# @permission_classes([permissions.AllowAny,])\n@csrf_exempt\n\ndef add_remove_favourite_restaurant(request,pk):\n restaurant=Shopkeeper.objects.get(id=pk)\n customer=Customer.objects.get(user1=request.user)\n if customer in restaurant.favourite_restaurants.all():\n restaurant.favourite_restaurants.remove(customer)\n else:\n restaurant.favourite_restaurants.add(customer)\n return Response({\"Updated Successfully\"})\n \n \n\n@api_view([\"POST\",\"PUT\"])\n# @permission_classes([permissions.AllowAny,])\n@csrf_exempt\n\ndef add_remove_favourite_item(request,pk):\n item=Items.objects.get(id=pk)\n customer=Customer.objects.get(user1=request.user)\n print(item,customer)\n if customer in item.favourite_items.all():\n item.favourite_items.remove(customer)\n else:\n item.favourite_items.add(customer)\n return Response({\"Updated Successfully\"})\n\n\n@api_view(['GET'])\n\ndef user_favourite_restaurants(request):\n customer=Customer.objects.get(user1=request.user)\n user_favourites = Shopkeeper.objects.filter(favourite_restaurants=customer)\n serializer=ShopkeeperSerializer(user_favourites,many=True)\n return Response(serializer.data)\n\n\n \n@api_view(['GET'])\n\ndef user_favourite_items(request):\n customer=Customer.objects.get(user1=request.user)\n user_favourites=Items.objects.filter(favourite_items=customer)\n serializer=ItemSerializer(user_favourites,many=True)\n return Response(serializer.data)\n\n\n@api_view(['POST'])\n\ndef add_to_cart(request, pk):\n item = get_object_or_404(Items, pk=pk)\n customer=Customer.objects.get(user1=request.user)\n order_item, created = OrderItem.objects.get_or_create(\n item=item,\n user=customer\n ##ordered=False\n )\n order_qs = Order.objects.filter(user=customer)\n\n if order_qs.exists():\n order = order_qs[0]\n\n if order.items.filter(item__pk=item.pk).exists():\n order_item.quantity += 1\n order_item.save()\n return Response({\"message\": \"Added quantity Item\", },\n ##status=status.HTTP_200_OK\n )\n else:\n order_item.quantity=1\n order_item.save()\n order.items.add(order_item)\n return Response({\"message\": \" Item added to your cart\", },\n ## status=status.HTTP_200_OK,\n )\n else:\n ##ordered_date = datetime.timezone.now()\n print(\"mk\")\n order = Order.objects.create(user=customer)\n order_item.quantity=1\n order_item.save()\n order.items.add(order_item)\n ##order_item.quantity=1\n return Response({\"message\": \"Item added to your cart\", },\n ## status=status.HTTP_200_OK,\n )\n\n\n@api_view(['POST'])\ndef remove_from_cart(request,pk):\n item = get_object_or_404(Items, pk=pk)\n customer=Customer.objects.get(user1=request.user)\n order_item, created = OrderItem.objects.get_or_create(\n item=item,\n user=customer\n ##ordered=False\n )\n order_qs = Order.objects.filter(user=customer)\n\n if order_qs.exists():\n order = order_qs[0]\n\n if order.items.filter(item__pk=item.pk).exists():\n order_item.quantity -= 1\n order_item.save()\n if order_item.quantity==0:\n order.items.erase(order_item)\n return Response({\"message\": \"Removed quantity Item\", },\n ##status=status.HTTP_200_OK\n )\n else:\n # order.items.add(order_item)\n return Response({\"message\": \" Item already removed!!\", },\n ## status=status.HTTP_200_OK,\n )\n\n@api_view(['POST'])\n\ndef request_order(request,pk):\n shopkeeper=Shopkeeper.objects.get(id=pk)\n customer=Customer.objects.get(user1=request.user)\n order=Order.objects.get(user=customer)\n \n instance=Shopkeeper_Order_History.objects.create(user=shopkeeper,customer=customer)\n instance.items.set(order.items.all())\n instance1=Customer_Order_History.objects.create(user=customer,shopkeeper=shopkeeper)\n instance1.items.set(order.items.all())\n order.delete()\n return Response({\"Order requested!!\"})\n\n@api_view(['POST'])\ndef shopkeeper_accept(request,pk):\n obj=Shopkeeper_Order_History.objects.get(id=pk)\n print(obj)\n obj.status=True\n obj.save()\n order=obj.order\n obj1=Customer_Order_History.objects.get(id=pk)\n obj1.status=True\n obj1.save()\n \n return Response({\"Order accepted!!\"})\n\n\n\n@api_view(['POST'])\ndef shopkeeper_reject(request,pk):\n obj=Shopkeeper_Order_History.objects.get(id=pk)\n \n order=obj.order\n obj.delete()\n obj1=Customer_Order_History.objects.get(id=pk)\n obj1.delete()\n return Response({\"Order cancelled!!\"})\n\n\n\n@api_view(['POST'])\ndef customer_reject(request,pk):\n print(request)\n obj=Customer_Order_History.objects.get(id=pk)\n order=obj.order\n obj.delete()\n obj1=Shopkeeper_Order_History.objects.get(id=pk)\n obj1.delete()\n return Response({\"Order cancelled!!\"})\n\n\n@api_view(['GET'])\ndef shopkeeper_order_history(request):\n shopkeeper=Shopkeeper.objects.get(user1=request.user)\n obj=Shopkeeper_Order_History.objects.filter(user=shopkeeper)\n serializer=soh_serializer(obj,many=True)\n return Response(serializer.data)\n\n@api_view(['GET'])\ndef customer_order_history(request):\n customer=Customer.objects.get(user1=request.user)\n print(customer)\n obj=Customer_Order_History.objects.filter(user=customer)\n print(obj)\n serializer=coh_serializer(obj,many=True)\n return Response(serializer.data)\n\n","sub_path":"lib/Back-end/food_app/account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"285723048","text":"import sys\r\nimport time\r\nimport argparse\r\nimport numpy as np\r\nfrom io import BytesIO\r\nimport matplotlib.pyplot as plt\r\nimport tensorflow as tf\r\n\r\nslim = tf.contrib.slim\r\n\r\n\r\nclass Logger(object):\r\n \"\"\"Logging in tensorboard without tensorflow ops.\"\"\"\r\n\r\n def __init__(self, log_dir):\r\n \"\"\"Creates a summary writer logging to log_dir.\"\"\"\r\n self.writer = tf.summary.FileWriter(log_dir)\r\n\r\n def log_scalar(self, tag, value, step):\r\n \"\"\"Log a scalar variable.\r\n Parameter\r\n ----------\r\n tag : basestring\r\n Name of the scalar\r\n value\r\n step : int\r\n training iteration\r\n \"\"\"\r\n summary = tf.Summary(value=[tf.Summary.Value(tag=tag,\r\n simple_value=value)])\r\n self.writer.add_summary(summary, step)\r\n\r\n def log_images(self, tag, img, step):\r\n \"\"\"Original version Logs a list of images.\"\"\"\r\n \"\"\"Updated version logs one image\"\"\"\r\n\r\n # Changes that were made were to comment the loop over a list of\r\n # images. \r\n # Change the input from images to img since we are passing only one \r\n # image everytime the function is called\r\n\r\n im_summaries = []\r\n# for nr, img in enumerate(images):\r\n # Write the image to a string\r\n # s = StringIO()\r\n s = BytesIO()\r\n plt.imsave(s, img, format='png')\r\n\r\n # Create an Image object\r\n img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(),\r\n height=img.shape[0],\r\n width=img.shape[1])\r\n\r\n # Create a Summary value\r\n im_summaries.append(tf.Summary.Value(tag='%s/%d' % (tag, 0),\r\n image=img_sum))\r\n\r\n # Create and write Summary\r\n summary = tf.Summary(value=im_summaries)\r\n self.writer.add_summary(summary, step)\r\n\r\n def log_histogram(self, tag, values, step, bins=1000):\r\n \"\"\"Logs the histogram of a list/vector of values.\"\"\"\r\n # Convert to a numpy array\r\n values = np.array(values)\r\n\r\n # Create histogram using numpy\r\n counts, bin_edges = np.histogram(values, bins=bins)\r\n\r\n # Fill fields of histogram proto\r\n hist = tf.HistogramProto()\r\n hist.min = float(np.min(values))\r\n hist.max = float(np.max(values))\r\n hist.num = int(np.prod(values.shape))\r\n hist.sum = float(np.sum(values))\r\n hist.sum_squares = float(np.sum(values**2))\r\n\r\n # Thus, we drop the start of the first bin\r\n bin_edges = bin_edges[1:]\r\n\r\n # Add bin edges and counts\r\n for edge in bin_edges:\r\n hist.bucket_limit.append(edge)\r\n for c in counts:\r\n hist.bucket.append(c)\r\n\r\n # Create and write Summary\r\n summary = tf.Summary(value=[tf.Summary.Value(tag=tag, histo=hist)])\r\n\r\n self.writer.add_summary(summary, step)\r\n\r\n self.writer.flush()\r\n\r\n\r\ndef _read_and_decode(serialized):\r\n # Define a dict with the data-names and types we expect to\r\n # find in the TFRecords file.\r\n features = \\\r\n {\r\n 'image_raw': tf.FixedLenFeature([], tf.string),\r\n 'annotation_raw': tf.FixedLenFeature([], tf.string)\r\n }\r\n\r\n features = tf.parse_single_example(serialized=serialized,\r\n features=features)\r\n\r\n # Decode the raw bytes so it becomes a tensor with type.\r\n image = tf.decode_raw(features['image_raw'], tf.uint8)\r\n annotation = tf.decode_raw(features['annotation_raw'], tf.uint8)\r\n\r\n # Creating a variable that will normalize the input image\r\n norm = tf.constant(255, dtype=tf.float32)\r\n\r\n # When it is raw the data is a vector and we need to reshape it.\r\n image = tf.reshape(image, [512, 512, 3])\r\n \r\n# image = tf.image.rgb_to_grayscale(image)\r\n # The type is now uint8 but we need it to be float.\r\n image = tf.cast(image, tf.float32)\r\n\r\n # Normalize the data before feeding it through. Optional.\r\n image = tf.divide(image, norm)\r\n\r\n # Repeat this process for the target segmentation.\r\n annotation = tf.reshape(annotation, [512, 512, 3])\r\n# annotation = tf.image.rgb_to_grayscale(annotation)\r\n annotation = tf.cast(annotation, tf.float32)\r\n annotation = tf.divide(annotation, norm)\r\n\r\n # The image and label are now correct TensorFlow types.\r\n return image, annotation\r\n\r\n\r\nclass Dataset_TFRecords(object):\r\n\r\n def __init__(self, path_tfrecords_train, path_tfrecords_valid, batch_size):\r\n\r\n train_dataset = tf.data.TFRecordDataset(filenames=path_tfrecords_train)\r\n # Parse the serialized data in the TFRecords files.\r\n # This returns TensorFlow tensors for the image and labels.\r\n train_dataset = train_dataset.map(_read_and_decode)\r\n # String together various operations to apply to the data\r\n train_dataset = train_dataset.shuffle(1000)\r\n train_dataset = train_dataset.batch(batch_size)\r\n # Will iterate through the data once before throwing an OutOfRangeError\r\n self._train_iterator = train_dataset.make_one_shot_iterator()\r\n\r\n self._train_init_op = self._train_iterator.make_initializer(train_dataset)\r\n\r\n validation_dataset = tf.data.TFRecordDataset(filenames=path_tfrecords_valid)\r\n validation_dataset = validation_dataset.map(_read_and_decode)\r\n validation_dataset = validation_dataset.shuffle(1000)\r\n validation_dataset = validation_dataset.batch(batch_size)\r\n self._validation_iterator = validation_dataset.make_one_shot_iterator()\r\n\r\n self._validation_init_op = self._validation_iterator.make_initializer(validation_dataset)\r\n\r\n # Create a placeholder that can be dynamically changed between train\r\n # and test.\r\n self._handle = tf.placeholder(tf.string, shape=[])\r\n\r\n # Define a generic iterator using the shape of the dataset\r\n iterator = tf.data.Iterator.from_string_handle(self._handle, \r\n train_dataset.output_types, \r\n train_dataset.output_shapes)\r\n\r\n\r\n self._next_element = iterator.get_next()\r\n self._train_handle = []\r\n self._validation_handle = []\r\n\r\n def initialize_training_iterator(self, sess):\r\n\r\n sess.run(self._train_init_op)\r\n\r\n def initialize_validation_iterator(self, sess):\r\n\r\n sess.run(self._validation_init_op)\r\n\r\n def get_next_training_element(self, sess):\r\n\r\n # The `Iterator.string_handle()` method returns a tensor that can be \r\n #evaluated and used to feed the `handle` placeholder.\r\n self._train_handle = sess.run(self._train_iterator.string_handle())\r\n feed_dict = {self._handle: self._train_handle}\r\n elements = sess.run(self._next_element, feed_dict=feed_dict)\r\n return(elements)\r\n\r\n def get_next_validation_element(self, sess):\r\n\r\n self._validation_handle = sess.run(self._validation_iterator.string_handle())\r\n feed_dict = {self._handle: self._validation_handle}\r\n elements = sess.run(self._next_element, feed_dict=feed_dict)\r\n return(elements)\r\n\r\n\r\nclass Modified_Unet(object):\r\n\r\n def __init__(self):\r\n # Build placeholders values which change during execution.\r\n self.x_placeholder = tf.placeholder(tf.float32, [None, 512, 512, 3])\r\n self.y_placeholder = tf.placeholder(tf.float32, [None, 512, 512, 3])\r\n\r\n def unet_resize_conv(self):\r\n conv_1 = slim.repeat(self.x_placeholder, 2, slim.conv2d, 64, [3, 3],\r\n scope='conv1')\r\n pool_1 = slim.max_pool2d(conv_1, [2, 2], scope='pool1')\r\n\r\n conv_2 = slim.repeat(pool_1, 2, slim.conv2d, 128, [3, 3],\r\n scope='conv2')\r\n pool_2 = slim.max_pool2d(conv_2, [2, 2], scope='pool2')\r\n\r\n conv_3 = slim.repeat(pool_2, 2, slim.conv2d, 256, [3, 3],\r\n scope='conv3')\r\n pool_3 = slim.max_pool2d(conv_3, [2, 2], scope='pool3')\r\n\r\n conv_4 = slim.repeat(pool_3, 2, slim.conv2d, 512, [3, 3],\r\n scope='conv4')\r\n pool_4 = slim.max_pool2d(conv_4, [2, 2], scope='pool4')\r\n\r\n conv_5 = slim.repeat(pool_4, 2, slim.conv2d, 1024, [3, 3],\r\n scope='conv5')\r\n\r\n resize_nn4 = tf.image.resize_nearest_neighbor(conv_5, size=[64, 64])\r\n resize_nn4 = slim.conv2d(resize_nn4, 512, [2, 2], scope='resize_conv4')\r\n\r\n concat4 = tf.concat([resize_nn4, conv_4], axis=3)\r\n\r\n conv_4 = slim.repeat(concat4, 2, slim.conv2d, 512, [3, 3],\r\n scope='uconv4')\r\n\r\n resize_nn3 = tf.image.resize_nearest_neighbor(conv_4, size=[128, 128])\r\n resize_nn3 = slim.conv2d(resize_nn3, 256, [2, 2], scope='resize_conv3')\r\n\r\n concat3 = tf.concat([resize_nn3, conv_3], axis=3)\r\n conv_3 = slim.repeat(concat3, 2, slim.conv2d, 256, [3, 3],\r\n scope='uconv3')\r\n\r\n resize_nn2 = tf.image.resize_nearest_neighbor(conv_3, size=[256, 256])\r\n resize_nn2 = slim.conv2d(resize_nn2, 256, [2, 2], scope='resize_conv2')\r\n\r\n concat2 = tf.concat([resize_nn2, conv_2], axis=3)\r\n conv_2 = slim.repeat(concat2, 2, slim.conv2d, 128, [3, 3],\r\n scope='uconv2')\r\n\r\n resize_nn1 = tf.image.resize_nearest_neighbor(conv_2, size=[512, 512])\r\n resize_nn1 = slim.conv2d(resize_nn1, 256, [2, 2], scope='resize_conv1')\r\n\r\n concat1 = tf.concat([resize_nn1, conv_1], axis=3)\r\n conv_1 = slim.repeat(concat1, 2, slim.conv2d, 64, [3, 3],\r\n scope='uconv1')\r\n\r\n final_layer = slim.conv2d(conv_1, 3, [1, 1], scope='uconv1/uconv1_3')\r\n\r\n return final_layer\r\n\r\n def unet_transpose_conv(self):\r\n\r\n power_basis = 4\r\n\r\n # changed to 32 from 64\r\n conv_1 = slim.repeat(self.x_placeholder, 2, slim.conv2d, 16, [3, 3],\r\n scope='conv1')\r\n pool_1 = slim.max_pool2d(conv_1, [2, 2], scope='pool1')\r\n\r\n conv_2 = slim.repeat(pool_1, 2, slim.conv2d, 32, [3, 3],\r\n scope='conv2')\r\n pool_2 = slim.max_pool2d(conv_2, [2, 2], scope='pool2')\r\n\r\n conv_3 = slim.repeat(pool_2, 2, slim.conv2d, 64, [3, 3],\r\n scope='conv3')\r\n pool_3 = slim.max_pool2d(conv_3, [2, 2], scope='pool3')\r\n\r\n conv_4 = slim.repeat(pool_3, 2, slim.conv2d, 128, [3, 3],\r\n scope='conv4')\r\n pool_4 = slim.max_pool2d(conv_4, [2, 2], scope='pool4')\r\n\r\n conv_5 = slim.repeat(pool_4, 2, slim.conv2d, 256, [3, 3],\r\n scope='conv5')\r\n\r\n deconv_4 = slim.convolution2d_transpose(conv_5, 128, [2, 2], [2, 2],\r\n padding='VALID',\r\n scope='tr_conv4')\r\n\r\n deconv_4 = tf.concat([deconv_4, conv_4], axis=3)\r\n conv_4 = slim.repeat(deconv_4, 2, slim.conv2d, 128, [3, 3],\r\n scope='uconv4')\r\n\r\n deconv_3 = slim.convolution2d_transpose(conv_4, 64, [2, 2], [2, 2],\r\n padding='VALID',\r\n scope='tr_conv3')\r\n deconv_3 = tf.concat([deconv_3, conv_3], axis=3)\r\n conv_3 = slim.repeat(deconv_3, 2, slim.conv2d, 64, [3, 3],\r\n scope='uconv3')\r\n\r\n deconv_2 = slim.convolution2d_transpose(conv_3, 32, [2, 2], [2, 2],\r\n padding='VALID',\r\n scope='tr_conv2')\r\n deconv_2 = tf.concat([deconv_2, conv_2], axis=3)\r\n conv_2 = slim.repeat(deconv_2, 2, slim.conv2d, 32, [3, 3],\r\n scope='uconv2')\r\n\r\n deconv_1 = slim.convolution2d_transpose(conv_2, 16, [2, 2], [2, 2],\r\n padding='VALID',\r\n scope='tr_conv1')\r\n deconv_1 = tf.concat([deconv_1, conv_1], axis=3)\r\n conv_1 = slim.repeat(deconv_1, 2, slim.conv2d, 16, [3, 3],\r\n scope='uconv1')\r\n final_layer = slim.conv2d(conv_1, 3, [1, 1], scope='uconv1/uconv1_3')\r\n\r\n return final_layer\r\n\r\n\r\n def log_weights_bias(self):\r\n \r\n for variable in slim.get_model_variables():\r\n\r\n with tf.name_scope(variable.op.name):\r\n\r\n tf.summary.scalar('mean', tf.reduce_mean(variable))\r\n\r\n tf.summary.scalar('max', tf.reduce_max(variable))\r\n\r\n tf.summary.scalar('min', tf.reduce_min(variable))\r\n\r\n with tf.name_scope('stddev'):\r\n stddev = tf.sqrt(tf.reduce_mean(tf.square(\r\n variable - tf.reduce_mean(variable))))\r\n\r\n tf.summary.scalar('stddev', stddev)\r\n\r\n tf.summary.histogram('histogram', variable)\r\n\r\n\r\ndef phase_unwrapping_tensorflow_model(_):\r\n\r\n # Clear the log directory, if it exists.\r\n if tf.gfile.Exists(FLAGS.log_dir):\r\n\r\n tf.gfile.DeleteRecursively(FLAGS.log_dir)\r\n\r\n # Create a log directory, if it exists.\r\n tf.gfile.MakeDirs(FLAGS.log_dir)\r\n\r\n # Reset the default graph.\r\n tf.reset_default_graph()\r\n\r\n model = Modified_Unet()\r\n\r\n dataset = Dataset_TFRecords(path_tfrecords_train = FLAGS.path_tfrecords_train, \r\n path_tfrecords_valid = FLAGS.path_tfrecords_valid, \r\n batch_size = FLAGS.batch_size)\r\n\r\n logger = Logger(FLAGS.log_dir)\r\n \r\n # We call the prediction Tensor.\r\n model_output_tensor = model.unet_transpose_conv()\r\n# model_output_tensor = model.unet_resize_conv()\r\n\r\n # Log the weights and bias\r\n model.log_weights_bias()\r\n\r\n # Now, we construct a loss function.\r\n mean_squared_error = tf.squared_difference(model_output_tensor,\r\n model.y_placeholder)\r\n loss = tf.reduce_mean(mean_squared_error, name='mse_mean')\r\n\r\n # Next, add an optimizet to the graph.\r\n optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(loss)\r\n\r\n summary = tf.summary.merge_all()\r\n init_op = tf.global_variables_initializer()\r\n# sv = tf.train.Supervisor(logdir=FLAGS.log_dir, save_summaries_secs=240.0)\r\n \r\n# with sv.managed_session() as sess:\r\n with tf.Session() as sess:\r\n\r\n for i in range(FLAGS.epochs):\r\n \r\n sess.run(init_op)\r\n dataset.initialize_training_iterator(sess)\r\n print(\"<-----------------Training_output------------------>\")\r\n\r\n # Train for one epoch.\r\n while True:\r\n\r\n try:\r\n\r\n start_time = time.time()\r\n\r\n images, annotations = dataset.get_next_training_element(sess)\r\n\r\n # Make a dict to load the batch onto the placeholders.\r\n feed_dict = {model.x_placeholder: images,\r\n model.y_placeholder: annotations}\r\n\r\n # Not a train loss.\r\n train_loss = sess.run(loss, feed_dict=feed_dict)\r\n\r\n sess.run(optimizer, feed_dict=feed_dict)\r\n\r\n print(\"Running time = \" + str(time.time() - start_time))\r\n\r\n except tf.errors.OutOfRangeError:\r\n\r\n break\r\n\r\n\r\n print(\"<-------------Saving Training Variables-------------->\")\r\n\r\n print(\"Training Epoch: {}, Mean Square Error: {:.5f}\".format(i, train_loss))\r\n\r\n predictions = sess.run(model_output_tensor,\r\n feed_dict=feed_dict)\r\n\r\n logger.log_images('train_input_image', images[0], i)\r\n\r\n logger.log_images('train_predicted_image', predictions[0], i)\r\n\r\n logger.log_scalar('train_loss', train_loss, i)\r\n\r\n dataset.initialize_validation_iterator(sess)\r\n print(\"<----------------Validation_output----------------->\")\r\n while True:\r\n\r\n try:\r\n\r\n images, annotations = dataset.get_next_validation_element(sess)\r\n\r\n # Make a dict to load the batch onto the placeholders.\r\n feed_dict = {model.x_placeholder: images,\r\n model.y_placeholder: annotations}\r\n\r\n validation_loss = sess.run(loss, feed_dict=feed_dict)\r\n\r\n except tf.errors.OutOfRangeError:\r\n\r\n break\r\n\r\n\r\n print(\"<-------------Saving Validation Variables-------------->\")\r\n\r\n print(\"Validation Epoch: {}, Mean Square Error: {:.5f}\".format(i, validation_loss))\r\n\r\n predictions = sess.run(model_output_tensor,\r\n feed_dict=feed_dict)\r\n\r\n logger.log_images('validation_input_image', images[0], i)\r\n\r\n logger.log_images('validation_predicted_image', predictions[0], i)\r\n\r\n logger.log_scalar('validation_loss', validation_loss, i)\r\n\r\n summary_str = sess.run(summary, feed_dict=feed_dict)\r\n logger.writer.add_summary(summary_str, i)\r\n\r\n# sv.stop()\r\n sess.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n # Instantiate an arg parser.\r\n parser = argparse.ArgumentParser()\r\n\r\n # Establish default arguements.\r\n\r\n # These flags are often, but not always, overwritten by the launcher.\r\n parser.add_argument('--path_tfrecords_train', type=str,\r\n default='C:\\\\Users\\\\Diego Lozano\\\\AFRL_Project\\\\Summer_2018\\\\train_data\\\\trial_train.tfrecords',\r\n help='Location of the training data set which is in .tfrecords format.')\r\n\r\n parser.add_argument('--path_tfrecords_valid', type=str,\r\n default='C:\\\\Users\\\\Diego Lozano\\\\AFRL_Project\\\\Summer_2018\\\\validation_data\\\\trial_validation.tfrecords',\r\n help='Location of the test data set which is in .tfrecords format.')\r\n\r\n parser.add_argument('--log_dir', type=str,\r\n default='C:\\\\Users\\\\Diego Lozano\\\\AFRL_Project\\\\Summer_2018\\\\tmplog',\r\n help='Summaries log directory.')\r\n\r\n parser.add_argument('--learning_rate', type=float, default=1e-4,\r\n help='Initial learning rate.')\r\n\r\n parser.add_argument('--batch_size', type=int, default=2,\r\n help='Training set batch size.')\r\n\r\n parser.add_argument('--epochs', type=int, default=5,\r\n help='Number of epochs to run trainer.')\r\n\r\n FLAGS, unparsed = parser.parse_known_args()\r\n\r\n tf.app.run(main=phase_unwrapping_tensorflow_model, argv=[sys.argv[0]] + unparsed)\r\n\r\n# tensorboard --logdir=\"C:\\\\Users\\\\Diego Lozano\\\\AFRL_Project\\\\Summer_2018\\\\templog\"\r\n","sub_path":"phase_unwrap_model.py","file_name":"phase_unwrap_model.py","file_ext":"py","file_size_in_byte":19086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"485502837","text":"#將股票交易資料放進MongoDB資料庫,就不用需要每次從證交所讀取資料\nimport numpy as np\nimport requests\nimport pandas as pd\nimport datetime\nimport json\nimport matplotlib.pyplot as pp\nimport time\nimport pymongo\nMONGO_HOST = 'localhost'\nMONGO_DB = 'TwStock'\nMONGO_COLLETION = 'twse'\nfrom pymongo import MongoClient\n# http://www.twse.com.tw/exchangeReport/STOCK_DAY?date=20180817&stockNo=2330\n\ndef connect_mongo(): #連線資料庫\n global collection\n client = MongoClient(MONGO_HOST, 27017)\n db = client[MONGO_DB]\n collection = db[MONGO_COLLETION]\n\ndef get_stock_history(date, stock_no, retry = 5): #從www.twse.com.tw讀取資料\n quotes = []\n url = 'http://www.twse.com.tw/exchangeReport/STOCK_DAY?date=%s&stockNo=%s' % ( date, stock_no)\n r = requests.get(url)\n data = r.json()\n return transform(data['data']) #進行資料格式轉換\n\ndef transform_date(date): #民國轉西元\n y, m, d = date.split('/')\n return str(int(y)+1911) + '/' + m + '/' + d\n \ndef transform_data(data): #將證交所獲得資料進行資料格式轉換\n data[0] = datetime.datetime.strptime(transform_date(data[0]), '%Y/%m/%d')\n data[1] = int(data[1].replace(',', ''))#把千進位的逗點去除\n data[2] = int(data[2].replace(',', ''))\n data[3] = float(data[3].replace(',', ''))\n data[4] = float(data[4].replace(',', ''))\n data[5] = float(data[5].replace(',', ''))\n data[6] = float(data[6].replace(',', ''))\n data[7] = float(0.0 if data[7].replace(',', '') == 'X0.00' else data[7].replace(',', '')) # +/-/X表示漲/跌/不比價\n data[8] = int(data[8].replace(',', ''))\n return data\n\ndef transform(data): #讀取每一個元素進行資料格式轉換,再產生新的串列\n return [transform_data(d) for d in data]\n\ndef genYM(smonth, syear, emonth, eyear): #產生從syear年smonth月到eyear年emonth月的所有年與月的tuple\n start = 12 * syear + smonth\n end = 12 * eyear + emonth\n for num in range(int(start), int(end) + 1):\n y, m = divmod(num, 12)\n yield y, m\n\ndef fetch_data(year: int, month: int, stockno): #擷取從year-month開始到目前為止的所有交易日資料\n raw_data = []\n today = datetime.datetime.today()\n for year, month in genYM(month, year, today.month, today.year): #產生year-month到今天的年與月份,用於查詢證交所股票資料\n if month < 10:\n date = str(year) + '0' + str(month) + '01' #1到9月\n else:\n date = str(year) + str(month) + '01' #10月\n data = get_stock_history(date, stockno)\n for item in data: #取出每一天編號為stockno的股票資料\n if collection.find({ #找尋該交易資料是否不存在\n \"date\": item[0],\n \"stockno\": stockno\n } ).count() == 0:\n element={'date':item[0], 'stockno':stockno, 'shares':item[1], 'amount':item[2], 'open':item[3], 'close':item[4], \n 'high':item[5], 'low':item[6], 'diff':item[7], 'turnover':item[8]}; #製作MongoDB的插入元素\n print(element)\n collection.insert_one(element) #插入元素到MongoDB\n time.sleep(10) #延遲5秒,證交所會根據IP進行流量統計,流量過大會斷線\n\nconnect_mongo() #連線資料庫\nfetch_data(2017, 4, '2892') #取出編號2892的股票,從201704到今天的股價與成交量資料","sub_path":"python/src/jang0820_Stock/FromTwseToMongo.py","file_name":"FromTwseToMongo.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"267567293","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\n#\n# Copyright (c) 2021 Huawei Device Co., Ltd.\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\nimport sys\nimport os\nimport argparse\nimport commands\nimport io\n\ndef find_string(excinfo_file, string):\n res = ''\n with open(excinfo_file, 'r+') as f:\n for lines in f:\n if string in lines:\n res = lines\n break\n return res\n\ndef is_kernel_exc(excinfo_file):\n res = find_string(excinfo_file, 'excFrom: kernel')\n print(res)\n return res != ''\n\ndef is_user_exc(excinfo_file):\n res = find_string(excinfo_file, 'excFrom: User')\n print(res)\n return res != ''\n\ndef parse_string_line(excinfo_file, string):\n line = find_string(excinfo_file, string)\n if line == '':\n print(\"%s is not in %s\\n\" %(string, excinfo_file))\n return ''\n line = line.replace('\\n', '')\n strlist = line.split(' ')\n return strlist\n\ndef parse_kernel_pc_klr(excinfo_file, ohos_image_file, string, addr2line_cmd, objdump_cmd):\n #parse pc\n f = open(excinfo_file, 'r+')\n start = 0\n for lines in f.readlines():\n if 'excFrom: kernel' in lines:\n if start == 1:\n break\n start = 1\n if start and string in lines:\n lines = lines[lines.find(string):]\n strlist = lines.split()\n cmd = objdump_cmd + ohos_image_file + ' | grep ' + strlist[2][2:] + ': -B 10 -A 5 -w'\n ret = commands.getoutput(cmd)\n print(ret)\n cmd = addr2line_cmd + ohos_image_file + ' ' + strlist[2]\n ret = commands.getoutput(cmd)\n ret = ret.split('\\n')\n print('<' + string + '>' + ret[0] + ' <' + strlist[2] + '>\\n')\n f.close() \n return 0\n f.close()\n return -1\n\ndef parse_kernel_lr(excinfo_file, ohos_image_file, addr2line_cmd):\n f = open(excinfo_file, 'r+')\n start = 0\n index = 1\n for lines in f.readlines():\n if 'excFrom: kernel' in lines:\n if start == 1:\n break\n start = 1\n if start and 'lr =' in lines:\n lines = lines[lines.find('lr ='):]\n strlist = lines.split()\n cmd = addr2line_cmd + ohos_image_file + ' ' + strlist[2]\n ret = commands.getoutput(cmd)\n ret = ret.split('\\n')\n print('<%.2d'%index + '>' + ret[0] + ' <' + strlist[2] + '>')\n index = index + 1\n\n f.close()\n\ndef parse_kernel_exc(excinfo_file, ohos_image_file, addr2line_cmd, objdump_cmd):\n #parse pc, klr\n ret1 = parse_kernel_pc_klr(excinfo_file, ohos_image_file, 'pc', addr2line_cmd, objdump_cmd)\n ret2 = parse_kernel_pc_klr(excinfo_file, ohos_image_file, 'klr', addr2line_cmd, objdump_cmd)\n #parse lr\n parse_kernel_lr(excinfo_file, ohos_image_file, addr2line_cmd)\n return ret1 and ret2\n\ndef parse_user_pc_ulr(excinfo_file, rootfs_dir, string, addr2line_cmd, objdump_cmd):\n #parse pc\n f = open(excinfo_file, 'r+')\n start = 0\n for lines in f.readlines():\n if 'excFrom: User' in lines:\n if start == 1:\n break\n start = 1\n if start and string in lines:\n lines = lines[lines.find(string):]\n strlist = lines.split()\n if len(strlist) < 7:\n print('%s is error'%string)\n f.close()\n return 0\n cmd = objdump_cmd + rootfs_dir + strlist[4] + ' | grep ' + strlist[6][2:] + ': -B 10 -A 5 -w'\n ret = commands.getoutput(cmd)\n print(ret)\n cmd = addr2line_cmd + rootfs_dir + strlist[4] + ' ' + strlist[6]\n #print(cmd)\n ret = commands.getoutput(cmd)\n ret = ret.split('\\n')\n print('<' + string + '>' + ret[0] + ' <' + strlist[6] + '>' + '<' + strlist[4] + '>\\n')\n f.close() \n return 0\n f.close()\n return -1\n\ndef parse_user_lr(excinfo_file, rootfs_dir, addr2line_cmd):\n f = open(excinfo_file, 'r+')\n start = 0\n index = 1\n for lines in f.readlines():\n if 'excFrom: User' in lines:\n if start == 1:\n break\n start = 1\n if start and 'lr =' in lines:\n lines = lines[lines.find('lr ='):]\n strlist = lines.split()\n if len(strlist) < 11:\n print('%s is error'%strlist)\n f.close()\n return\n cmd = addr2line_cmd + rootfs_dir + strlist[8] + ' ' + strlist[10]\n res = commands.getoutput(cmd)\n res = res.split('\\n')\n print('<%.2d>'%index + res[0] + ' <' + strlist[10] + '>' + '<' + strlist[8] + '>')\n index = index + 1\n\n f.close()\n\ndef parse_user_exc(excinfo_file, rootfs_dir, addr2line_cmd, objdump_cmd):\n #parse pc ulr\n ret1 = parse_user_pc_ulr(excinfo_file, rootfs_dir, 'pc', addr2line_cmd, objdump_cmd)\n ret2 = parse_user_pc_ulr(excinfo_file, rootfs_dir, 'ulr', addr2line_cmd, objdump_cmd)\n #parse lr\n parse_user_lr(excinfo_file, rootfs_dir, addr2line_cmd)\n return ret1 and ret2\n\ndef parse_backtrace(backtrace_file, ohos_image_file, addr2line_cmd):\n f = open(backtrace_file, 'r+')\n find = -1\n start = 0\n index = 1\n for lines in f.readlines():\n if 'backtrace begin' in lines:\n if start == 1:\n break\n start = 1\n if start and 'lr =' in lines:\n lines = lines[lines.find('lr ='):]\n strlist = lines.split()\n cmd = addr2line_cmd + ohos_image_file + ' ' + strlist[2]\n ret = commands.getoutput(cmd)\n ret = ret.split('\\n')\n print('\\n<%.2d'%index + '>' + ret[0] + ' <' + strlist[2] + '>')\n index = index + 1\n find = 0\n\n f.close()\n return find\n\ndef parse_excinfo(excinfo_file, ohos_image_file, rootfs_dir, addr2line_cmd, objdump_cmd):\n cmd = 'dos2unix ' + excinfo_file\n commands.getoutput(cmd)\n kernel_exc = is_kernel_exc(excinfo_file)\n user_exc = is_user_exc(excinfo_file)\n\n if kernel_exc == False and user_exc == False:\n if parse_backtrace(excinfo_file, ohos_image_file, addr2line_cmd) != 0:\n print(\"%s is not a excinfo or backtrace file\\n\"%excinfo_file)\n return -1\n else:\n return 0\n if user_exc:\n if rootfs_dir != None:\n return parse_user_exc(excinfo_file, rootfs_dir, addr2line_cmd, objdump_cmd)\n else:\n print('error: rootfs_dir is none')\n return -1\n return parse_kernel_exc(excinfo_file, ohos_image_file, addr2line_cmd, objdump_cmd)\n\ndef parse_compiler(compiler):\n addr2line = ''\n addr2line_cmd = ''\n objdump = ''\n objdump_cmd = ''\n cmd = 'which ' + compiler\n ret = commands.getoutput(cmd)\n if ret == '':\n print('%s is not exist'%compiler)\n return None\n index1 = ret.rfind('gcc')\n index2 = ret.rfind('clang')\n if index1 != -1:\n addr2line = ret[0:index1] + 'addr2line'\n objdump = ret[0:index1] + 'objdump'\n elif index2 != -1:\n index3 = ret.rfind('/')\n addr2line = ret[0:index3 + 1] + 'llvm-addr2line'\n objdump = ret[0:index3 + 1] + 'llvm-objdump'\n else:\n print('%s is not arm-xxx-xxx-gcc or clang'%compiler)\n return None\n addr2line_cmd = addr2line + ' -C -f -e '\n objdump_cmd = objdump + ' -d '\n return [addr2line_cmd, objdump_cmd]\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--f', help = 'excinfo file or backtrace file')\n parser.add_argument('--e', help = 'elf system image file')\n parser.add_argument('--r', help = 'the path of rootfs')\n parser.add_argument('--c', help = 'compiler [arm-xxx-xxx-gcc/clang]')\n args = parser.parse_args()\n\n if args.f == None or args.e == None:\n print(\"input error\\n\")\n parser.print_help()\n return -1\n\n excinfo_file = args.f\n ohos_image_file = args.e\n rootfs_dir = args.r\n\n addr2line_cmd = 'llvm-addr2line -C -f -e '\n objdump_cmd = 'llvm-objdump -d '\n if args.c != None:\n cmd = parse_compiler(args.c)\n if cmd == None:\n return -1\n addr2line_cmd = cmd[0]\n objdump_cmd = cmd[1]\n return parse_excinfo(excinfo_file, ohos_image_file, rootfs_dir, addr2line_cmd, objdump_cmd)\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"tools/scripts/parse_exc/parse_excinfo.py","file_name":"parse_excinfo.py","file_ext":"py","file_size_in_byte":8868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"119343687","text":"import eulerianPath\nimport copy\nMAX_INT=1000000\nclass Graph(): \n\n\tdef __init__(self, vertices,mapping): \n\t\tself.vertices = vertices\n\t\tself.map=mapping\n\t\tself.V = len(vertices) \n\n\tdef printMST(self, parent): \n\t\tprint(\"Edge \\tWeight\")\n\t\tfor i in range(1,self.V): \n\t\t\tprint(parent[i],\"-\",self.map[i],\"\\t\",self.dist(u,v)) \n\n\tdef minKey(self, key, mstSet): \n\n\t\tmin_key = MAX_INT \n\n\t\tfor v in range(self.V): \n\t\t\tif key[v] < min_key and mstSet[v] == False: \n\t\t\t\tmin_key = key[v] \n\t\t\t\tmin_index = v \n\n\t\treturn min_index \n\n\tdef dist(self,u,v):\n\t\treturn ((self.vertices[u][0]-self.vertices[v][0])**2+(self.vertices[u][1]-self.vertices[v][1])**2)**0.5\n\t\n\n\tdef primMST(self): \n\n\t\tkey = [MAX_INT] * self.V \n\t\tparent = [None] * self.V\n\t\thelper_parent = [None] * self.V\n\n\t\tkey[0] = 0\n\t\tmstSet = [False] * self.V \n\n\t\tparent[0] = -1\n\t\thelper_parent[0] = -1\n\n\t\tfor cout in range(self.V): \n\n\t\t\tu = self.minKey(key, mstSet) \n\n\t\t\tmstSet[u] = True\n\n\t\t\tfor v in range(self.V): \n\t\t\t\tif self.dist(u,v)>0 and mstSet[v] == False and key[v] > self.dist(u,v): \n\t\t\t\t\tkey[v] = self.dist(u,v)\n\t\t\t\t\tparent[v] = self.map[u] \n\t\t\t\t\thelper_parent[v] = u\n\n\t\t#self.printMST(parent)\n\t\treturn parent,helper_parent\n\n\n\n\n\"\"\"\ndistances=[ [0, 2, 0, 6, 0], \n [2, 0, 3, 8, 5], \n [0, 3, 0, 0, 7], \n [6, 8, 0, 0, 9], \n [0, 5, 7, 9, 0]]\nMST([0,1,2,4],distances)\n\"\"\"\n\n\ndef getMST(vertices,mapping):\n\tg = Graph(vertices,mapping)\n\n\tparent,helper_parent=g.primMST()\n\n\tpath, helper_path=eulerianPath.getPath(vertices,helper_parent,mapping)\n\n\treturn parent,path","sub_path":"Version3/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"615631718","text":"import numpy as np\n\n\n# In the formula. index L = # of layers (including input and output) - 1 (e.g.2-5-1 nnm lenght=3 L=2)\n# w^l, s^l 1<=l 0<=l R = [[\"A\", \"B\", \"C\"], [1, 2, 3], [4, 5, 6]]\n ># Define function f that returns True iff\n > # the last element in the row is greater than 3.\n > def f(row): row[-1] > 3\n > select(R, f)\n [[\"A\", \"B\", \"C\"], [4, 5, 6]]\n :param f: The selection function\n :param t: The table being processed\n :return Table that is original table filtered by function\n \"\"\"\n\n result_table = []\n for row in t:\n try:\n f_value = f(row)\n except TypeError:\n raise UnknownFunctionException(\"Function not recognized\")\n\n if f_value is True:\n result_table.append(row)\n\n return result_table\n\n\ndef projection(table, attributes):\n \"\"\"\n Perform projection operation on table t\n using the attributes subset r.\n\n Example:\n > R = [[\"A\", \"B\", \"C\"], [1, 2, 3], [4, 5, 6]]\n > projection(R, [\"A\", \"C\"])\n [[\"A\", \"C\"], [1, 3], [4, 6]]\n\n :param table: The table being processed\n :param attributes: The columns to be returned\n :return Table that has projected columns specified in attributes\n \"\"\"\n\n if len(table) <= 0:\n return []\n # This stores index positions of the attributes in the header row\n attribute_indexes = []\n\n # First row of table should contain table headers\n headers = table[0]\n\n # Calculate index positions on which attributes exist in header row\n for attribute in attributes:\n if attribute in headers:\n attribute_indexes.append(headers.index(attribute))\n else:\n raise UnknownAttributeException(\"Attribute: {0} not recognized\".format(attribute))\n\n result_table = []\n if len(attributes) > 0:\n # Headers in result table should be the attributes passed in\n result_table = [attributes]\n\n for row in table[1:]:\n result_row = []\n\n for attribute_index in attribute_indexes:\n # Grab value from appropriate index in current row\n result_row.append(row[attribute_index])\n\n result_table.append(result_row)\n\n return result_table\n\n\ndef cross_product(t1, t2):\n \"\"\"\n Return the cross-product of tables t1 and t2.\n\n Example:\n > R1 = [[\"A\", \"B\"], [1,2], [3,4]]\n > R2 = [[\"C\", \"D\"], [5,6]]\n [[\"A\", \"B\", \"C\", \"D\"], [1, 2, 5, 6], [3, 4, 5, 6]]\n\n :param t1: Table 1 of cross product\n :param t2: Table 2 of cross product\n :return Table that has cross product of t1 and t2\n \"\"\"\n\n if len(t1) == 0 and len(t2) == 0:\n return None\n elif len(t1) == 0:\n return t2\n elif len(t2) == 0:\n return t1\n\n header1 = t1[0]\n header2 = t2[0]\n\n # Initialize header table with headers from both tables\n result_table = [header1 + header2]\n\n # Skip first row in both tables since headers have already been processed above\n for r1 in t1[1:]:\n for r2 in t2[1:]:\n result_table.append(r1 + r2)\n\n if len(result_table) == 0:\n return None\n else:\n return result_table","sub_path":"exercise1.py","file_name":"exercise1.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"324496397","text":"'''\nCreated on 2-115. 3. 2-1.\n\n@author: bklim\n'''\nfrom src.Puzzle import Puzzle\nfrom src.PopInfo import PopInfo \nimport itertools\n\nclass PuzzleMap(object):\n '''\n Puzzle Color\n -1 = None, 0 = fire, 1 = water, 2 = grass, 3 = light, 4 = dark, 5 = heart, 6 = block, 7 = poison\n '''\n Map = []\n \n \n\n def __init__(self):\n '''\n Constructor\n '''\n self.clear()\n \n def setPuzzle(self, rowcol, puzzle):\n self.Map[rowcol[0]][rowcol[1]] = puzzle\n \n def setPuzzlesbyNumber(self, numbers):\n for i in range(0,30):\n row = i//6\n col = i%6\n Color = int(numbers[i])\n self.setPuzzle([row, col], Puzzle(Color, False))\n \n def clear(self):\n self.Map = []\n for x in range(0,5):\n temprow = []\n for y in range(0,6):\n temprow.append(Puzzle(-1, False))\n self.Map.append(temprow)\n \n def getPuzzle(self, rowcol):\n return self.Map[rowcol[0]][rowcol[1]] \n \n def run(self):\n PI = PopInfo()\n \n while True:\n onestepPopPuzzle = self.findPops()\n onestepNearPuzzle = self.getNearStacks()\n PI.addPopPuzzleDict(self.getPopPuzzles(onestepPopPuzzle, onestepNearPuzzle))\n self.removePops(onestepPopPuzzle)\n \n movepuzzle = 0\n for alist in onestepPopPuzzle.values():\n movepuzzle = movepuzzle + len(alist)\n \n if movepuzzle == 0:\n break\n \n return PI\n \n def getPopPuzzles(self, Pop, Near):\n Pops = {}\n for aColor in Pop.keys():\n Pops[aColor] = []\n if len(Pop[aColor]) > 0:\n for alist in Near[aColor]:\n templist = [] \n for blist in Pop[aColor]: \n if blist in alist:\n templist.append(blist)\n Pops[aColor].append(templist)\n return Pops\n \n def FlushPops(self):\n \n pass\n \n def removePops(self, onestepPops): \n for aColor in onestepPops.keys():\n for aRC in onestepPops[aColor]:\n temppuzzle = Puzzle(-1, False)\n self.setPuzzle(aRC, temppuzzle) \n pass \n \n def findPops(self):\n [HorMap, VerMap] = self.ThreeRowHorVerMap()\n willPopDic = {}\n for Color in range(0, 8):\n willPopDic[Color] = []\n ColorHorMap = self.ValueCopy(HorMap)\n ColorVerMap = self.ValueCopy(VerMap)\n \n for x in range(0,5):\n for y in range(0,4):\n if ColorHorMap[x][y] != Color:\n ColorHorMap[x][y] = -1\n \n for x in range(0,3):\n for y in range(0,6):\n if ColorVerMap[x][y] != Color:\n ColorVerMap[x][y] = -1\n \n willPopRowCol = self.getRowColfromHorVerMap(ColorHorMap, ColorVerMap)\n willPopDic[Color] = willPopRowCol\n \n return willPopDic\n \n def getPopStacks(self, rclist):\n if len(rclist) == 0:\n return []\n \n temprclist = self.ValueCopy(rclist)\n stacks = []\n stacks.append([temprclist.pop()])\n while len(temprclist)>0:\n temprc = temprclist.pop()\n \n for x in range(0,len(stacks)):\n for rc in stacks[x]:\n if self.isNearRowCol(rc, temprc):\n stacks[x].append(temprc)\n break\n break\n \n mergeFlag = True\n while mergeFlag:\n mergeFlag = False\n for [x,y] in itertools.product(range(len(stacks)), range(len(stacks))):\n if x != y:\n if self.isNearStack(stacks[x], stacks[y]):\n mergeFlag = True\n stacks[x] = stacks[x] + stacks[y]\n stacks.remove(stacks[y])\n break\n \n return stacks\n \n def isNearStack(self, stack1, stack2):\n for rc1 in stack1:\n for rc2 in stack2:\n if self.isNearRowCol(rc1, rc2):\n return True\n return False\n \n def getRowColfromHorVerMap(self, HorMap, VerMap):\n RClist = []\n for x in range(0,5):\n for y in range(0,4):\n if HorMap[x][y] >=0:\n RClist.append([x,y])\n RClist.append([x,y+1])\n RClist.append([x,y+2])\n \n for x in range(0,3):\n for y in range(0,6):\n if VerMap[x][y] >=0:\n RClist.append([x,y])\n RClist.append([x+1,y])\n RClist.append([x+2,y])\n \n uniqueRClist = []\n \n if len(RClist) > 0:\n RClist.sort()\n uniqueRClist.append(RClist[0])\n olderrc = RClist[0]\n for rc in RClist:\n if olderrc != rc:\n olderrc = rc\n uniqueRClist.append(rc)\n \n return uniqueRClist\n \n def isNearRowCol(self, rowcol1, rowcol2):\n disRow = rowcol1[0] - rowcol2[0]\n disCol = rowcol1[1] - rowcol2[1]\n dis = disRow*disRow + disCol*disCol\n if dis == 1:\n return True\n else:\n return False\n \n def ThreeRowHorVerMap(self):\n HorMap = [[-1]*4, [-1]*4, [-1]*4, [-1]*4, [-1]*4]\n VerMap = [[-1]*6, [-1]*6, [-1]*6]\n \n for rown in range(0,5):\n for coln in range(0,4):\n targetColor = self.getPuzzle([rown, coln]).Color\n Flag = True\n for x in range(1,3):\n if targetColor != self.getPuzzle([rown, coln+x]).Color:\n Flag = False\n if Flag == True:\n HorMap[rown][coln] = targetColor\n \n for rown in range(0,3):\n for coln in range(0,6):\n targetColor = self.getPuzzle([rown, coln]).Color\n Flag = True\n for x in range(1,3):\n if targetColor != self.getPuzzle([rown+x, coln]).Color:\n Flag = False\n if Flag == True:\n VerMap[rown][coln] = targetColor\n \n return [HorMap, VerMap]\n\n def ValueCopy(self, array):\n result = []\n \n if type(array) == list:\n for a in array:\n result.append(self.ValueCopy(a))\n pass\n else:\n result = array\n pass\n \n return result\n \n def getNearStacks(self):\n NearStacks = {}\n NearStacks[0] = []\n NearStacks[1] = []\n NearStacks[2] = []\n NearStacks[3] = []\n NearStacks[4] = []\n NearStacks[5] = []\n NearStacks[6] = []\n NearStacks[7] = []\n for [x,y] in itertools.product(range(0,5), range(0,6)):\n if self.getPuzzle([x,y]).Color != -1:\n NearStacks[self.getPuzzle([x,y]).Color].append([[x,y]])\n \n flag =True\n while flag:\n flag = False\n near = {}\n for Color in range(0,8):\n for [x,y] in itertools.product(range(len(NearStacks[Color])),range(len(NearStacks[Color]))):\n if x != y:\n if self.isNearStack(NearStacks[Color][x], NearStacks[Color][y]):\n near[Color] = [NearStacks[Color][x], NearStacks[Color][y]]\n break\n \n for aColor in near.keys():\n [A,B] = near[aColor]\n NearStacks[aColor].remove(A)\n NearStacks[aColor].remove(B)\n A.extend(B)\n NearStacks[aColor].append(A)\n flag = True\n pass\n return NearStacks\n \n \n\nif __name__ == \"__main__\":\n PM = PuzzleMap()\n PM.setPuzzlesbyNumber('000000111111222222333333444444')\n PI = PM.run()\n ppp = PI.MakePopInfoList(PM.Map)\n pass ","sub_path":"PDSolver/src/PuzzleMap.py","file_name":"PuzzleMap.py","file_ext":"py","file_size_in_byte":8354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"353002305","text":"# File: s (Python 2.3)\n\nimport win32security\nimport win32api\n\ndef AdjustPrivilege(priv, enable = 1):\n \"\"\"Adjust the current process's security privileges.\n Taken from the errata to the O'Reilly Python cookbook.\n \"\"\"\n flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY\n htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags)\n id = win32security.LookupPrivilegeValue(None, priv)\n if enable:\n newPrivileges = [\n (id, win32security.SE_PRIVILEGE_ENABLED)]\n else:\n newPrivileges = [\n (id, 0)]\n \n try:\n return win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)\n except:\n return None\n\n\n","sub_path":"Server/ipl/win32/security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"648097209","text":"\nfrom __future__ import absolute_import\n\nimport os, logging\n\ndef configureLogger(log):\n logging.captureWarnings(True)\n log.setLevel(logging.DEBUG)\n\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n ch.setFormatter(muz.util.ColoredFormatter(\"%(levelname)18s %(name)s: %(message)s\"))\n\n log.addHandler(ch)\n\nlog = logging.getLogger(__name__)\n\nimport muz.config\n_config = muz.config.get(__name__, {\n \"log\": {\n \"level\": \"warning\",\n },\n})\n\nimport muz.util\nconfigureLogger(log)\n\nfrom muz.main import initvfs, run, userdir, NAME, VERSION, init, bareInit\n","sub_path":"muz/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"491296666","text":"class Solution:\n def isSubsequence(self, s: str, t: str) -> bool:\n length = len(s)\n if length==0:\n return True\n j = 0\n for i in t:\n if i==s[j]:\n j = j+1\n if j==length:\n return True\n return False\n","sub_path":"LeetCode/is-subsequence.py","file_name":"is-subsequence.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"329059277","text":"import itertools\nimport linear as lr\nimport sys\nimport json\nimport pickle\n\nwith open (sys.argv[1], \"r\") as fp:\n graphs = json.load(fp)[\"graphs\"]\n\nn_graphs = len(graphs)\nfor g_id, g in enumerate(graphs):\n print (\"Handeling {} / {} graphs\".format(g_id, n_graphs))\n if len(g[\"arrow_edges\"]) == 0 and len(g[\"latent_edges\"]) == 0:\n continue\n l = lr.Linear(g[\"graph_str\"])\n print (g[\"graph_str\"])\n for pair in itertools.combinations(g[\"arrow_edges\"], 2):\n print (\"Identifying with Constraint \", pair)\n pair = [(pair[0][0],pair[0][1]), (pair[1][0],pair[1][1])]\n g_res = {\"eql_edges\":pair}\n for edge in g[\"arrow_edges\"]:\n edge = (edge[0], edge[1])\n l.g_relevent_basis(edge, pair)\n for edge in g[\"latent_edges\"]:\n l_edge = tuple([\"latent\"] + sorted(edge))\n l.g_relevent_basis(l_edge, pair)\n with open(\"usda_basic/{}_{}.pickle\".format(g_id, pair), \"wb\") as fp:\n pickle.dump(g_res, fp)\n for pair in itertools.combinations(g[\"latent_edges\"], 2):\n l_pair = [tuple([\"latent\"] + sorted(pair[0])), tuple([\"latent\"] + sorted(pair[1]))]\n print (\"Identifying with Constraint \", l_pair)\n g_res = {\"eql_edges\":l_pair}\n for edge in g[\"arrow_edges\"]:\n edge = (edge[0], edge[1])\n l.g_relevent_basis(edge, l_pair)\n for edge in g[\"latent_edges\"]:\n l_edge = tuple([\"latent\"] + sorted(edge))\n l.g_relevent_basis(l_edge, l_pair)\n with open(\"usda_basic/{}_{}.pickle\".format(g_id, l_pair), \"wb\") as fp:\n pickle.dump(g_res, fp)\n\n\n","sub_path":"new_test.py","file_name":"new_test.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"384524428","text":"#\n# This file is part of LUNA.\n#\n\"\"\" Gateware for working with abstract endpoints. \"\"\"\n\nimport functools\nimport operator\n\nfrom nmigen import Signal, Elaboratable, Module\nfrom nmigen.hdl.ast import Past\n\nfrom .packet import DataCRCInterface, InterpacketTimerInterface, TokenDetectorInterface\nfrom .packet import HandshakeExchangeInterface\nfrom .transfer import USBInTransferManager\nfrom ..stream import USBInStreamInterface, USBOutStreamInterface\nfrom ...stream import StreamInterface\nfrom ...utils.bus import OneHotMultiplexer\n\n\nclass EndpointInterface:\n \"\"\" Interface that connects a USB endpoint module to a USB device.\n\n Many non-control endpoints won't need to use the latter half of this structure;\n it will be automatically removed by the relevant synthesis tool.\n\n Attributes\n ----------\n tokenizer: TokenDetectorInterface, to detector\n Interface to our TokenDetector; notifies us of USB tokens.\n\n rx: USBOutStreamInterface, input stream to endpoint\n Receive interface for this endpoint.\n rx_complete: Signal(), input to endpoint\n Strobe that indicates that the concluding rx-stream was valid (CRC check passed).\n rx_ready_for_response: Signal(), input to endpoint\n Strobe that indicates that we're ready to respond to a complete transmission.\n Indicates that an interpacket delay has passed after an `rx_complete` strobe.\n rx_invalid: Signal(), input to endpoint\n Strobe that indicates that the concluding rx-stream was invalid (CRC check failed).\n\n tx: USBInStreamInterface, output stream from endpoint\n Transmit interface for this endpoint.\n tx_pid_toggle: Signal(), output from endpoint\n Value for the data PID toggle; 0 indicates we'll send DATA0; 1 indicates DATA1.\n\n handshakes_in: HandshakeExchangeInterface, input to endpoint\n Carries handshakes detected from the host.\n handshakes_out: HandshakeExchangeInterface, output from endpoint\n Carries handshakes generate by this endpoint.\n\n speed: Signal(2), input to endpoint\n The device's current operating speed. Should be a USBSpeed enumeration value --\n 0 for high, 1 for full, 2 for low.\n\n active_address: Signal(7), input to endpoint\n Contains the device's current address.\n address_changed: Signal(), output from endpoint.\n Strobe; pulses high when the device's address should be changed.\n new_address: Signal(7), output from endpoint\n When :attr:`address_changed` is high, this field contains the address that should be adopted.\n\n active_config: Signal(8), input to endpoint\n The configuration number of the active configuration.\n config_changed: Signal(), output from endpoint\n Strobe; pulses high when the device's configuration should be changed.\n new_config: Signal(8)\n When `config_changed` is high, this field contains the configuration that should be applied.\n\n timer: InterpacketTimerInterface\n Interface to our interpacket timer.\n data_crc: DataCRCInterface\n Control connection for our data-CRC unit.\n \"\"\"\n\n def __init__(self):\n self.data_crc = DataCRCInterface()\n self.tokenizer = TokenDetectorInterface()\n self.timer = InterpacketTimerInterface()\n\n self.speed = Signal(2)\n\n self.active_address = Signal(7)\n self.address_changed = Signal()\n self.new_address = Signal(7)\n\n self.active_config = Signal(8)\n self.config_changed = Signal()\n self.new_config = Signal(8)\n\n self.rx = USBOutStreamInterface()\n self.rx_complete = Signal()\n self.rx_ready_for_response = Signal()\n self.rx_invalid = Signal()\n\n self.tx = USBInStreamInterface()\n self.tx_pid_toggle = Signal()\n\n self.handshakes_in = HandshakeExchangeInterface(is_detector=True)\n self.handshakes_out = HandshakeExchangeInterface(is_detector=False)\n self.issue_stall = Signal()\n\n\nclass USBEndpointMultiplexer(Elaboratable):\n \"\"\" Multiplexes access to the resources shared between multiple endpoint interfaces.\n\n Interfaces are added using :attr:`add_interface`.\n\n Attributes\n ----------\n\n shared: EndpointInterface\n The post-multiplexer endpoint interface.\n \"\"\"\n\n def __init__(self):\n\n #\n # I/O port\n #\n self.shared = EndpointInterface()\n\n #\n # Internals\n #\n self._interfaces = []\n\n\n def add_interface(self, interface: EndpointInterface):\n \"\"\" Adds a EndpointInterface to the multiplexer.\n\n Arbitration is not performed; it's expected only one endpoint will be\n driving the transmit lines at a time.\n \"\"\"\n self._interfaces.append(interface)\n\n\n def _multiplex_signals(self, m, *, when, multiplex, sub_bus=None):\n \"\"\" Helper that creates a simple priority-encoder multiplexer.\n\n Parmeters\n ---------\n when: str\n The name of the interface signal that indicates that the `multiplex` signals should be\n selected for output. If this signals should be multiplexed, it should be included in `multiplex`.\n multiplex: iterable(str)\n The names of the interface signals to be multiplexed.\n \"\"\"\n\n def get_signal(interface, name):\n \"\"\" Fetches an interface signal by name / sub_bus. \"\"\"\n\n if sub_bus:\n bus = getattr(interface, sub_bus)\n return getattr(bus, name)\n else:\n return getattr(interface, name)\n\n\n # We're building an if-elif tree; so we should start with an If entry.\n conditional = m.If\n\n for interface in self._interfaces:\n condition = get_signal(interface, when)\n\n with conditional(condition):\n\n # Connect up each of our signals.\n for signal_name in multiplex:\n\n # Get the actual signals for our input and output...\n driving_signal = get_signal(interface, signal_name)\n target_signal = get_signal(self.shared, signal_name)\n\n # ... and connect them.\n m.d.comb += target_signal .eq(driving_signal)\n\n # After the first element, all other entries should be created with Elif.\n conditional = m.Elif\n\n\n def or_join_interface_signals(self, m, signal_for_interface):\n \"\"\" Joins together a set of signals on each interface by OR'ing the signals together. \"\"\"\n\n # Find the value of all of our pre-mux signals OR'd together...\n all_signals = (signal_for_interface(i) for i in self._interfaces)\n or_value = functools.reduce(operator.__or__, all_signals, 0)\n\n # ... and tie it to our post-mux signal.\n m.d.comb += signal_for_interface(self.shared).eq(or_value)\n\n\n def elaborate(self, platform):\n m = Module()\n shared = self.shared\n\n #\n # Pass through signals being routed -to- our pre-mux interfaces.\n #\n for interface in self._interfaces:\n m.d.comb += [\n\n # CRC and timer shared signals interface.\n interface.data_crc.crc .eq(shared.data_crc.crc),\n interface.timer.tx_allowed .eq(shared.timer.tx_allowed),\n interface.timer.tx_timeout .eq(shared.timer.tx_timeout),\n interface.timer.rx_timeout .eq(shared.timer.rx_timeout),\n\n # Detectors.\n shared.handshakes_in .connect(interface.handshakes_in),\n shared.tokenizer .connect(interface.tokenizer),\n\n # Rx interface.\n shared.rx .connect(interface.rx),\n interface.rx_complete .eq(shared.rx_complete),\n interface.rx_ready_for_response .eq(shared.rx_ready_for_response),\n interface.rx_invalid .eq(shared.rx_invalid),\n\n # State signals.\n interface.speed .eq(shared.speed),\n interface.active_config .eq(shared.active_config),\n interface.active_address .eq(shared.active_address)\n ]\n\n #\n # Multiplex the signals being routed -from- our pre-mux interface.\n #\n self._multiplex_signals(m,\n when='address_changed',\n multiplex=['address_changed', 'new_address']\n )\n self._multiplex_signals(m,\n when='config_changed',\n multiplex=['config_changed', 'new_config']\n )\n\n # Connect up our transmit interface.\n m.submodules.tx_mux = tx_mux = OneHotMultiplexer(\n interface_type=USBInStreamInterface,\n mux_signals=('payload',),\n or_signals=('valid', 'first', 'last'),\n pass_signals=('ready',)\n )\n tx_mux.add_interfaces(i.tx for i in self._interfaces)\n m.d.comb += self.shared.tx.connect(tx_mux.output)\n\n # OR together all of our handshake-generation requests...\n self.or_join_interface_signals(m, lambda interface : interface.handshakes_out.ack)\n self.or_join_interface_signals(m, lambda interface : interface.handshakes_out.nak)\n self.or_join_interface_signals(m, lambda interface : interface.handshakes_out.stall)\n\n # ... our CRC start signals...\n self.or_join_interface_signals(m, lambda interface : interface.data_crc.start)\n\n # ... and our timer start signals.\n self.or_join_interface_signals(m, lambda interface : interface.timer.start)\n\n # Finally, connect up our transmit PID select.\n conditional = m.If\n\n # We'll connect our PID toggle to whichever interface has a valid transmission going.\n for interface in self._interfaces:\n with conditional(interface.tx.valid | Past(interface.tx.valid)):\n m.d.comb += shared.tx_pid_toggle.eq(interface.tx_pid_toggle)\n\n conditional = m.Elif\n\n return m\n\n\n\nclass USBStreamInEndpoint(Elaboratable):\n \"\"\" Endpoint interface that transmits a simple data stream to a host.\n\n This interface is suitable for a single bulk or interrupt endpoint.\n\n This endpoint interface will automatically generate ZLPs when a stream packet would end without\n a short data packet. If the stream's ``last`` signal is tied to zero, then a continuous stream of\n maximum-length-packets will be sent with no inserted ZLPs.\n\n\n Attributes\n ----------\n\n stream: StreamInterface, input stream\n Full-featured stream interface that carries the data we'll transmit to the host.\n\n interface: EndpointInterface\n Communications link to our USB device.\n\n\n Parameters\n ----------\n endpoint_number: int\n The endpoint number (not address) this endpoint should respond to.\n max_packet_size: int\n The maximum packet size for this endpoint. Should match the wMaxPacketSize provided in the\n USB endpoint descriptor.\n \"\"\"\n\n\n def __init__(self, *, endpoint_number, max_packet_size):\n\n self._endpoint_number = endpoint_number\n self._max_packet_size = max_packet_size\n\n #\n # I/O port\n #\n self.stream = StreamInterface()\n self.interface = EndpointInterface()\n\n\n def elaborate(self, platform):\n m = Module()\n interface = self.interface\n\n # Create our transfer manager, which will be used to sequence packet transfers for our stream.\n m.submodules.tx_manager = tx_manager = USBInTransferManager(self._max_packet_size)\n\n m.d.comb += [\n\n # Always generate ZLPs; in order to pass along when stream packets terminate.\n tx_manager.generate_zlps .eq(1),\n\n # We want to handle packets only that target our endpoint number.\n tx_manager.active .eq(interface.tokenizer.endpoint == self._endpoint_number),\n\n # Connect up our transfer manager to our input stream...\n tx_manager.transfer_stream .connect(self.stream),\n\n # ... and our output stream...\n interface.tx .connect(tx_manager.packet_stream),\n interface.tx_pid_toggle .eq(tx_manager.data_pid),\n\n # ... and connect through our token/handshake signals.\n interface.tokenizer .connect(tx_manager.tokenizer),\n tx_manager.handshakes_out .connect(interface.handshakes_out),\n interface.handshakes_in .connect(tx_manager.handshakes_in)\n ]\n\n return m\n\n","sub_path":"luna/gateware/usb/usb2/endpoint.py","file_name":"endpoint.py","file_ext":"py","file_size_in_byte":12863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"186203483","text":"# -*- coding: utf-8 -*-\n# @Time : 18-12-20\n# @Author : Wuqiao Chen\n# @Site : https://github.com/Lokfar\n# @File : co_cluster_wuqiao.py\n# @IDE : PyCharm Community Edition\n\nimport datetime\nimport random\nimport math\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom sklearn.datasets import make_biclusters\n\n'''\n implementation of the co-cluster algorithm in the paper 'Minimum Sum-Squared Residue Co-clustering \n of Gene Expression Data'\n H = A - RR'ACC'\n the adjustable parameter is tau\n'''\n\n\ndef initialR_C(m, k):\n '''\n initialize the cluster indicator matrix, Sequential allocation of the first k values and random allocation of the rest\n :param m: the row number\n :param k: the column number\n '''\n R = np.zeros((m, k), dtype=float)\n for i in range(0, m):\n if i < k:\n R[i, i] = 1\n else:\n random_c = random.randint(0, k - 1)\n R[i, random_c] = 1\n cluster_index_sum = np.sum(R, axis=0) ** (-1 / 2)\n return np.matrix(np.multiply(R, cluster_index_sum))\n\n\ndef H2(A, R, C):\n '''\n calculate the value || H ||^2, which is the sum-Squared residue of co-clustering result\n '''\n H1 = R * R.T * A * C * C.T\n H = A - H1\n return np.sum(np.multiply(H, H))\n\n\ndef get_tau(A):\n '''\n adjustable parameter, the threshold of ending the co-clustering\n '''\n return np.sum(np.multiply(A, A)) * 0.00000001\n\n\ndef calAC(A, R, C):\n return R * R.T * A * C\n\n\ndef calAR(A, R, C):\n return R.T * A * C * C.T\n\n\ndef argmin_c(A, AC, C, j):\n '''\n choose the nearest cluster for column j\n '''\n minH = 0\n min_c = 0\n for c in range(0, C.shape[1]):\n c_sum = np.sum(C[:, c])\n if c_sum != 0:\n c_sum = pow(c_sum, -1)\n H = A[:, j] - c_sum * AC[:, c]\n HcJ = np.sum(np.multiply(H, H.T))\n if c == 0:\n minH = HcJ\n else:\n if HcJ < minH:\n minH = HcJ\n min_c = c\n return min_c\n\n\ndef argmin_r(A, AR, R, i):\n '''\n choose the nearest cluster for row i\n '''\n minH = 0\n min_r = 0\n for r in range(0, R.shape[1]):\n r_sum = np.sum(R[:, r])\n if r_sum != 0:\n r_sum = pow(r_sum, -1)\n H = A[i, :] - r_sum * AR[r, :]\n HIr = np.sum(np.multiply(H, H))\n if r == 0:\n minH = HIr\n else:\n if HIr < minH:\n minH = HIr\n min_r = r\n return min_r\n\n\ndef co_cluster(A, k, l):\n '''\n do cluster for the matrix's row and column at the same time\n :param A: the matrix to be clustered\n :param k: the number of row clusters\n :param l: the number of column clusters\n :return: the clustered matrix\n '''\n\n # record the start time\n start_time = datetime.datetime.now()\n # get rows and columns of matrix A\n m, n = A.shape\n # initialize the cluster indicator matrix R and C, R for row cluster and C for column cluster.\n R = initialR_C(m, k)\n C = initialR_C(n, l)\n\n # calculate the sum-Squared residue\n objval = H2(A, R, C)\n # initial the threshold\n tau = get_tau(A)\n delta = tau + 1\n\n # do co-clustering\n while delta > tau:\n # clustering for columns\n AC = calAC(A, R, C)\n C_temp = np.zeros(C.shape)\n for j in range(0, n):\n c = argmin_c(A=A, AC=AC, C=C, j=j)\n C_temp[j, c] = 1\n\n # update cluster indicate matrix\n cluster_index_sum_C = np.sum(C_temp, axis=0)\n for s in range(0, l):\n if cluster_index_sum_C[s] != 0:\n cluster_index_sum_C[s] = pow(cluster_index_sum_C[s], -1 / 2)\n C = np.matrix(np.multiply(C_temp, cluster_index_sum_C))\n\n # clustering for rows\n AR = calAR(A, R, C)\n R_temp = np.zeros(R.shape)\n for i in range(0, m):\n r = argmin_r(A=A, AR=AR, R=R, i=i)\n R_temp[i, r] = 1\n # update cluster indicate matrix\n cluster_index_sum_R = np.sum(R_temp, axis=0)\n for v in range(0, k):\n if cluster_index_sum_R[v] != 0:\n cluster_index_sum_R[v] = pow(cluster_index_sum_R[v], -1 / 2)\n R = np.matrix(np.multiply(R_temp, cluster_index_sum_R))\n\n # update and calculate delta\n oldobj = objval\n objval = H2(A, R, C)\n delta = np.abs(oldobj - objval)\n\n # when co-clustering ended, move the rows and columns according to the clustering result\n fit_A = A[np.argsort(np.sum(np.array(R.T), axis=0))]\n fit_A = fit_A[:, np.argsort(np.sum(np.array(C.T), axis=0))]\n\n # time cost\n end_time = datetime.datetime.now()\n run_time = (end_time - start_time).seconds\n print(\"run cost time:\")\n print(run_time)\n return np.matrix(local_search(fit_A, R.getA(), C.getA())), np.matrix(fit_A)\n\n\ndef r(row, matrix_c):\n for j in range(0, len(matrix_c[0])):\n if matrix_c[row, j] != 0:\n return j\n\n\ndef local_search(matrix_a, matrix_r, matrix_c):\n '''\n local_search step for column\n matrix_r为行聚类矩阵\n matrix_c为列聚类矩阵\n matrix_a为原矩阵\n r 为聚类映射函数\n '''\n if not isinstance(matrix_a, np.ndarray):\n print(\"matrix_a is not a ndarray\")\n return\n if not isinstance(matrix_r, np.ndarray):\n print(\"matrix_r is not a ndarray\")\n return\n if not isinstance(matrix_c, np.ndarray):\n print(\"matrix_c is not a ndarray\")\n return\n\n # n l 分别为列聚类矩阵的行列\n n = len(matrix_c)\n l = len(matrix_c[0])\n\n # 阈值确定\n # 一范数\n matrix_a_norm = np.linalg.norm(matrix_a, ord=1, axis=None, keepdims=False)\n t = math.pow(10, -5) * math.pow(matrix_a_norm, 2)\n\n # A heat\n matrix_a_h = np.dot(matrix_r.T, matrix_a)\n\n list = []\n\n for i in range(0, n):\n for c_ in range(0, l):\n # 如果第i行的聚类结果不是c_类,则将其改变到c_类并计算损失函数\n if r(i, matrix_c) != c_:\n # 改变列聚类矩阵,将i行移入第c_类\n new_matrix_c = move_cluster(i, c_, matrix_c)\n\n # 4.13 左部\n cost = np.linalg.norm(np.dot(matrix_a_h, new_matrix_c)) - np.linalg.norm(np.dot(matrix_a_h, matrix_c))\n\n # 将行、列、损失函数值作为元组放入列表\n record = (i, c_, cost)\n list.append(record)\n\n # 获取列表的第三个元素\n def take_third(elem):\n return elem[2]\n\n # 将记录按照损失函数降序排列\n list.sort(key=take_third, reverse=True)\n best_movement = list[0]\n ret_matrix_c = matrix_c\n\n # 如果损失函数大于阈值,则按照该record移动,体现为修改matrix_c\n if best_movement[2] > t:\n ret_matrix_c = move_cluster(best_movement[0], best_movement[1], matrix_c)\n\n return ret_matrix_c\n\n\ndef move_cluster(sor_row, dest_col, ori_matrix_c):\n new_matrix_c = ori_matrix_c\n # 计算分类矩阵中目标列和来源行的mr值\n # 如果出现了空簇就设置为1\n m = 1\n for i in range(0, len(new_matrix_c) - 1):\n if new_matrix_c[i][dest_col] != 0:\n m = new_matrix_c[i][dest_col]\n break\n m_r_dest = math.pow(float(m), -2)\n\n sor_col = 0\n for i in range(0, len(new_matrix_c[0])):\n m = 1\n if new_matrix_c[sor_row][i] != 0:\n m = new_matrix_c[sor_row][i]\n sor_col = i\n break\n\n m_r_sor = math.pow(m, -2)\n\n # 对应数目变化\n m_r_dest = m_r_dest + 1\n m_r_sor = m_r_sor - 1\n\n # 更新分布矩阵\n for i in range(0, len(new_matrix_c)):\n if new_matrix_c[i][dest_col] != 0:\n new_matrix_c[i][dest_col] = math.pow(m_r_dest, -0.5)\n if new_matrix_c[i][sor_col] != 0:\n new_matrix_c[i][sor_col] = math.pow(m_r_sor, -0.5)\n\n return new_matrix_c\n\n\n# test\nif __name__ == '__main__':\n data, rows, columns = make_biclusters(\n shape=(500, 500), n_clusters=10, noise=0,\n shuffle=True, random_state=0)\n plt.matshow(data)\n fit_A_1, fit_A = co_cluster(data, 10, 10)\n plt.matshow(fit_A)\n plt.matshow(fit_A_1)\n plt.show()\n","sub_path":"co_cluster/co_cluster.py","file_name":"co_cluster.py","file_ext":"py","file_size_in_byte":8162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"170935265","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 25 13:13:27 2019\n\n@author: Shashank\n\"\"\"\n\nimport os\n#os.chdir('replace with this folder path')\nimport numpy as np\nimport pandas as pd\nimport cv2\n\n## Setting the base directory\nBASE_DIR = os.path.dirname(os.path.abspath('face-train.py'))\nimage_dir = os.path.join(BASE_DIR, \"Input_images\")\nos.mkdir(\"Input_images\")\nface_cascade = cv2.CascadeClassifier('haarcascade/haarcascade_frontalface_alt2.xml')\n\nperson_name = input(\"Please Enter your name: \") ##Get input label from the user\nos.mkdir(os.path.join(image_dir,person_name)) #Create directory for the person to save images\nimage_count = 0 #initiated image_count\ncap = cv2.VideoCapture(0) # Video capture instance\nwhile True:\n check,frame = cap.read() \n frame_gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) # Convert to gray\n faces_coords = face_cascade.detectMultiScale(frame_gray, scaleFactor = 1.05, minNeighbors = 5) # Detect face Cordinates\n for x,y,w,h in faces_coords:\n cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2) # Draw rectangle\n face_gray = frame_gray[y:y+h, x:x+w]\n face_resized = cv2.resize(face_gray, (50,50))\n out_path = os.path.join(image_dir,person_name,person_name+str(image_count)+'.jpg')\n key = cv2.waitKey(1)\n if key == ord('c'):\n image_count = image_count+1\n cv2.imwrite(out_path,face_resized)\n print('face' + str(image_count)+ ' saved on disk' )\n \n \n cv2.imshow('frame',frame)\n if key == ord('q') or image_count == 20 :\n break\n\ncap.release()\ncv2.destroyAllWindows()\n\n\n\n\n\n \n","sub_path":"generate_train_samples.py","file_name":"generate_train_samples.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"88621712","text":"import azureml.core\nfrom azureml.core import Workspace, Datastore, Dataset\n\n\n# Load the workspace from the saved config file\nws = Workspace.from_config()\nprint('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))\n\n# Retrieve key from keyvault to create datastore (connection)\nkeyvault = ws.get_default_keyvault()\nretrieved_secret = keyvault.get_secret(name=\"tradingaml-storage\")\n\n# register blob container as datastore\nblob_datastore = Datastore.register_azure_blob_container(workspace = ws,\n\t\t\t\t\tdatastore_name = \"financial_timeseries_ohlc\",\t\t\t\t\t\n\t\t\t\t\tcontainer_name = \"financial-timeseries-ohlc\",\n\t\t\t\t\taccount_name = \"tradingaml\",\n\t\t\t\t\taccount_key = retrieved_secret)\n# datastore_name : nom à donner au magasin de données sur AML\n# container_name : nom du container Azure\n# account_name : nom du compte de stockage Azure\n# account_key : clé du compte de stockage Azure\n\n# get the datastore\nblob_datastore = Datastore.get(ws, 'financial_timeseries_ohlc')\n\n# Create a file dataset from the path on the datastore\nfile_data_set = Dataset.File.from_files(path=(blob_datastore, 'bitcoin_clean_ohlcv/1H/*.csv'))\n# Get the files in the dataset\nfor file_path in file_data_set.to_path():\n print(file_path)\n# Register the file dataset\nfile_data_set = file_data_set.register(workspace=ws, \n name='bitcoin 1H file dataset',\n description='bitcoin 1H files',\n tags = {'format':'CSV'},\n create_new_version=True)\nprint('Datasets registered')\n\n\n# Create a tabular dataset from the path on the datastore\ntabular_data_set = Dataset.Tabular.from_delimited_files(path=(blob_datastore, 'bitcoin_clean_ohlcv/1H/*.csv'))\n# register as tabular dataset\ntabular_data_set = tabular_data_set.register(workspace=ws, \n name='bitcoin 1H tabular dataset',\n description='bitcoin 1H tabular',\n tags = {'format':'CSV'},\n create_new_version=True)\nprint('Datasets registered')\n\n\n# Get specific datastore\naml_datastore = Datastore.get(ws, 'nom_dun_datastore_existant')\n# Set the default datastore\nws.set_default_datastore('nom_dun_datastore_existant')\n# Get the default datastore\ndefault_ds = ws.get_default_datastore()\n","sub_path":"aml_management_src/datastores_datasets.py","file_name":"datastores_datasets.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"586979010","text":"import glob\r\nfrom tinytag import TinyTag\r\nimport pandas as pd\r\nimport time\r\n\r\n#Give path to music folder\r\nmusic_path= \"C:\\\\Users\\\\Parod\\\\Music\\\\*\\\\*.*\"\r\n\r\n\r\nsongs = glob.glob(music_path)\r\nsonglist = [] #[\"Title\",\"Artist\",\"Genre\",\"Duration\"]\r\n\r\nfor track in songs:\r\n tag = TinyTag.get(track)\r\n title = tag.title\r\n artist = tag.artist\r\n genre = tag.genre\r\n runtime = time.gmtime(tag.duration)\r\n duration = time.strftime(\"%M:%S\", runtime)\r\n entry = [title, artist, genre, duration]\r\n songlist.append(entry)\r\n\r\ndf = pd.DataFrame(songlist, columns =['Title', 'Artist', 'Genre', 'Duration (M:S)'])\r\ndf = df.sort_values(by=['Genre','Title'], kind='stable')\r\n\r\nhtml = df.to_html(classes='table table-striped', table_id='trackTable', header=True, index=False)\r\n\r\nhtml = df.style.set_properties(**{'font-size': '12pt', 'font-family': 'Calibri','border-bottom': '1px solid #666','border-collapse': 'collapse', 'width': '30%', 'padding': '10px', 'background-color': '#f3f3f3'}).render()\r\n\r\n#html = df.to_html(classes='table table-striped', table_id='trackTable', header=True, index=False)\r\n\r\nfile = open(\"index.html\", \"w\", encoding=\"utf-8\")\r\nfile.write(html)\r\nfile.close()\r\n\r\n","sub_path":"music2html.py","file_name":"music2html.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"120871063","text":"\"\"\"This is a python class for model training and model selection\"\"\"\n\nfrom src.evaluation import *\nfrom config.config import *\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import GridSearchCV\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nclass supervised_learning:\n \n print(\"Class supervised_learning initaited.\")\n print(\"Instance variables available: df, parameter_grid, classifier_dictionary.\")\n print(\"Methods available: data_split, hyperparameter_tuning, model_selection.\")\n print(\"----------------------------------------------------------------------\")\n \n def __init__(self, dataframe, classifier_dictionary = classifier_dictionary,\n parameter_grid = parameter_grid):\n self.df = dataframe\n self.parameter_grid = parameter_grid\n self.classifer_dictionary = classifier_dictionary\n \n \n \n def data_split(self, ratio = [0.6, 0.2, 0.2]):\n ## Use a more basic version of train_test_split.\n ## By right, we should use TimeSeriesSplit in sklearn.\n X = self.df.drop(columns = ['y'])\n y = self.df[['y']]\n train_length = int(np.floor(self.df.shape[0] * ratio[0]))\n test_length = int(np.floor(self.df.shape[0] * (ratio[0] + ratio[1])))\n X_train, self.y_train = X.iloc[:train_length,:], y.iloc[:train_length,:]\n X_test, self.y_test = X.iloc[train_length:test_length,:], y.iloc[train_length:test_length,:]\n X_validation, self.y_validation = X.iloc[test_length:,:], y.iloc[test_length:,:]\n \n ## Normalise the Test Set and Validation Set using the Trainng Set data. This is crucial for preventing data leakage.\n X_train_mean = X_train.mean()\n X_train_std = X_train.std()\n \n ## Normalise everything in X\n self.X_train = (X_train - X_train_mean)/X_train_std\n self.X_test = (X_test - X_train_mean)/X_train_std\n self.X_validation = (X_validation - X_train_mean)/X_train_std\n \n print(\"Training, Testing and Validation Sets are successfully split.\")\n print(\"Training Set has {} rows\".format(self.X_train.shape[0]))\n print(\"Test Set has {} rows.\".format(self.X_test.shape[0]))\n print(\"Validation Set has {} rows.\".format(self.X_validation.shape[0]))\n print(\"----------------------------------------------------------------------\")\n \n\n def hyperparameter_tuning(self):\n \n ### Tune hyperparameters for all models in the model_dictionary\n for i in self.classifer_dictionary:\n classifier = self.classifer_dictionary[i]\n param_grid = self.parameter_grid[i]\n grid_search = GridSearchCV(classifier, param_grid, \n return_train_score = True)\n grid_search.fit(self.X_train, self.y_train)\n training_score = np.mean(grid_search.cv_results_['mean_train_score'])\n test_score = grid_search.score(self.X_test, self.y_test)\n \n ## Print out the tuning results\n print(\"For Classifier {}:\".format(i))\n print(\"Mean Training Score: {:.4}%\".format(training_score * 100))\n print(\"Mean Testing Score: {:.4}%\".format(test_score * 100))\n print(\"Best Parameter Combination Found During Grid Search:\")\n print(grid_search.best_params_)\n\n print(\"------------------------------------------------------------------\") \n \n def model_selection(self, model):\n \n ### Combine training set and test set to train the final model for evaluation \n X_c = pd.concat([self.X_train, self.X_test])\n y_c = pd.concat([self.y_train, self.y_test])\n \n model_evaluation(model, X_c, y_c, self.X_validation, self.y_validation)\n \n","sub_path":"src/supervised_training.py","file_name":"supervised_training.py","file_ext":"py","file_size_in_byte":3816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"248328217","text":"from lyamc import *\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import integrate\nfrom scipy.special import wofz\nfrom scipy.special import erfc\nimport time\nfrom numba import jit\nfrom scipy.special import lambertw\n\n\n\ndef Voigt(a, x):\n \"\"\"returns Voigt function using the Faddeeva function\n ! does not work wtih numba !\n \"\"\"\n z = x + 1.0j*a\n return wofz(z).real\n\n\ndef get_xcw_exact(a):\n \"\"\"returns xcw that separates core from wing\n \"\"\"\n return np.abs(np.sqrt(lambertw(-a / np.sqrt(np.pi), k=-1)))\n\n\ndef pdf_parallel(u, x, a):\n H = Voigt(a, x)\n return (a / (np.pi * H)) * np.exp(-u ** 2) / ((x - u)**2 + a**2)\n\n\ndef R(xf, x, mu, a):\n \"\"\"\n Eq. (71) from Dijkstra (2017)\n \"\"\"\n f = lambda u: np.exp(-u ** 2) / ((x - u)**2 + a**2) * np.exp(-((xf - x - u * (mu - 1)) ** 2) / (1. - mu**2)) \n I = integrate.quad(f, -np.inf, np.inf, limit=1000)[0]\n return I * a / (np.pi ** 1.5 * np.sqrt(1. - mu**2) * Voigt(a, x))\n\n\ndef RA(x, xf, a):\n \"\"\"redistirbution probability for isotropic case\n ! needs to be norbalized !\n ! slow !\n \"\"\"\n f = lambda mu: R(xf, x, mu, a)\n I = integrate.quad(f, -1., 1., limit=1000)[0]\n return I\n\n\ndef RB(x, xf, a):\n \"\"\"redistribution probability for dipole Rayleigh case\n ! needs to be norbalized !\n ! slow !\n \"\"\"\n f = lambda mu: 0.75 * (1 + mu**2) * R(xf, x, mu, a)\n I = integrate.quad(f, -1., 1., limit=1000)[0]\n return I\n\n\ndef J(x, atau):\n \"\"\"returns Neufeld solution for photons emitted from a single point at line center x=0\n as defined in Laursen (2009) arxiv.org/abs/0805.3153\n \"\"\"\n return np.sqrt(6 / np.pi) * (x ** 2 / (24 * atau)) / np.cosh(np.sqrt(np.pi ** 3 / 54) * np.abs(x ** 3) / atau)\n\n\ndef test_upar(x=3.0, a=0.00047, N=int(1e5)):\n \"\"\"tests function get_upar by comparing pdf generated by it with the exact pdf for u parallel\n compare with Laursen (2010) Fig 8.1\n \"\"\"\n get_upar(x, a)\n t = time.process_time()\n upar = np.linspace(-6, 6, 999)\n hist1 = np.zeros(N)\n for i in range(N): \n hist1[i] = get_upar(x, a)\n elapsed_time = time.process_time() - t\n print(\"elapsed time =\", elapsed_time)\n plt.hist(hist1, 200, density=True, histtype='step')\n plt.plot(upar, pdf_parallel(upar, x, a))\n plt.xlim(-2, 5)\n plt.ylim(0, 1)\n #plt.yscale('log')\n plt.show()\n\n\ndef test_redistribution(x=3.0, T=1.e4, N=int(1e5)):\n \"\"\"tests function atom_scattering by comparing redistribution function from x to xout generated by it \n with the exact function from Hummer (1962) doi=10.1093/mnras/125.1.21\n compare with Laursen (2010) Fig 8.2\n \"\"\"\n xfs = np.linspace(-4, 8, 200)\n a = get_a(T)\n hist1 = np.zeros(N)\n k = np.array([0., 0., 1.]) #get_random_k()\n vbulk = np.array([0., 0., 0.])\n for i in range(N):\n hist1[i] = atom_scattering(x, k, T, vbulk)[0]\n plt.hist(hist1, 200, density=True, histtype='step')\n # qsA = []\n # qsB = []\n # for xf in xfs:\n # print(\"xf =\", xf)\n # qsA.append(RA(x, xf, a))\n # qsB.append(RB(x, xf, a))\n # qsA /= np.trapz(qsA, dx=dx)\n # qsB /= np.trapz(qsB, dx=dx)\n # np.savetxt(\"qsA.csv\", qsA)\n # np.savetxt(\"qsB.csv\", qsB)\n qsA = np.genfromtxt(\"data/qsA.csv\")\n qsB = np.genfromtxt(\"data/qsB.csv\")\n plt.plot(xfs, qsA, label='isotropic')\n plt.plot(xfs, qsB, label='Rayleigh')\n plt.legend()\n plt.ylim(0, 1)\n plt.show()\n\n\ndef test_Neufeld():\n \"\"\"tests against Neufeld solution\n compare with Laursen (2010) Fig 7.2\n \"\"\"\n T = 1.e4\n a = get_a(T)\n x = np.linspace(-17, 17, 1000)\n eta = 0.71\n tau0 = 1.e5\n xs = np.genfromtxt('data/xs_data(tau=1.e5).csv')\n Ns = np.genfromtxt('data/Ns_data(tau=1.e5).csv')\n print(\"Ns_avr / tau0 =\", np.average(Ns) / tau0)\n plt.hist(xs, 50, density=True, histtype='step', color='k')\n plt.plot(x, 4 * np.pi * J(x, eta * a * tau0), label='tau = 1.e5')\n tau0 = 1.e6\n xs = np.genfromtxt('data/xs_data(tau=1.e6).csv')\n Ns = np.genfromtxt('data/Ns_data(tau=1.e6).csv')\n print(\"Ns_avr / tau0 =\", np.average(Ns) / tau0)\n plt.hist(xs, 50, density=True, histtype='step', color='k')\n plt.plot(x, 4 * np.pi * J(x, eta * a * tau0), label='tau = 1.e6')\n plt.legend()\n plt.show()\n\n\ndef test_expansion():\n T = 1.e4\n a = get_a(T)\n x = np.linspace(-50, 50, 1000)\n eta = 0.71\n tau0 = 1.e7\n plt.plot(x, 4 * np.pi * J(x, eta * a * tau0))\n xs = np.genfromtxt('data/xs_data(tau=1.e7, vmax=200).csv')\n plt.hist(xs, 50, density=True, histtype='step', color='r', label='vmax=200')\n xs = np.genfromtxt('data/xs_data(tau=1.e7, vmax=-200).csv')\n plt.hist(xs, 50, density=True, histtype='step', color='b', label='vmax=-200')\n plt.legend()\n plt.title('tau=1.e7')\n plt.show()\n\n\n# test_upar()\n# test_redistribution()\n# test_Neufeld()\n# test_expansion()\n\n#run \nt = time.process_time()\nxs, Ns = runner()\nelapsed_time = time.process_time() - t\nprint(\"elapsed_time =\", elapsed_time)\nnp.savetxt(\"xs_data.csv\", xs) \nnp.savetxt(\"Ns_data.csv\", Ns)\nprint(\"Nscattering_avr =\", np.average(Ns))\n\n\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"18531954","text":"import plotly.graph_objects as go\n\n\ndef data():\n lst = []\n with open(\"data.csv\") as data:\n for line in data:\n lst.append(line.split(\",\"))\n return lst\n\n\nlst = data()\nphis = map(lambda pair: int(pair[0]), lst)\nrs = map(lambda pair: float(pair[1]), lst)\n\nfig = go.Figure()\nfig.add_trace(go.Scatterpolar(\n r=tuple(rs),\n theta=tuple(phis),\n mode='lines',\n name='HyperCardioid',\n line_color='royalblue',\n))\n\nfig.show()\n","sub_path":"src/graphic.py","file_name":"graphic.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"563150008","text":"import numpy as np\nfrom lettuce import UnitConversion, Stencil, write_vtk, UnitConversion, VTKReporter, torch_gradient,Lattice, Simulation, LettuceException, BounceBackBoundary, GenericStepReporter\nimport torch\nfrom timeit import default_timer as timer\nfrom copy import deepcopy\n\nclass D2Q37(Stencil):\n e = np.array(\n [[0, 0], [1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, -1], [1, -1], [-1, 1], [2, 0], [-2, 0], [0, 2], [0, -2],\n [2, 1], [-2, -1], [2, -1], [-2, 1], [1, 2], [-1, -2], [1, -2], [-1, 2], [2, 2], [-2, -2], [2, -2], [-2, 2],\n [3, 0], [-3, 0], [0, 3], [0, -3], [3, 1], [-3, -1], [3, -1], [-3, 1], [1, 3], [-1, -3], [1, -3], [-1, 3]])\n w = np.array(\n [0.23315066913235250228650] + [0.10730609154221900241246] * 4 + [0.05766785988879488203006] * 4 + [0.01420821615845075026469] * 4 + [0.00535304900051377523273] * 8 + [0.00101193759267357547541] * 4 + [\n 0.00024530102775771734547] * 4 + [0.00028341425299419821740] * 8)\n cs = 1/1.19697977039307435897239\n opposite = [\n 0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13,\n 16, 15, 18, 17, 20, 19, 22, 21, 24, 23, 26, 25, 28, 27, 30, 29, 32, 31, 34, 33, 36, 35\n ]\n\nclass D3V59(Stencil):\n e = np.array(\n [[0, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, -1], [0, -1, 0], [-1, 0, 0], [1, 0, 0], [0, -1, 1], [0, 1, -1],\n [0, -1, -1], [1, 0, -1], [0, 1, 1], [1, 0, 1], [-1, 0, 1], [-1, 1, 0], [-1, 0, -1], [-1, -1, 0], [1, -1, 0],\n [1, 1, 0], [-1, 1, -1], [-1, 1, 1], [-1, -1, 1], [-1, -1, -1], [1, -1, 1], [1, 1, -1], [1, 1, 1], [1, -1, -1],\n [0, 0, 2], [0, 2, 0], [2, 0, 0], [0, 0, -2], [0, -2, 0], [-2, 0, 0], [-2, -2, 0], [-2, 0, 2], [-2, 0, -2],\n [2, 2, 0], [0, 2, -2], [0, -2, -2], [0, 2, 2], [2, -2, 0], [2, 0, -2], [-2, 2, 0], [2, 0, 2], [0, -2, 2],\n [-3, 0, 0], [0, 0, 3], [0, 0, -3], [0, -3, 0], [0, 3, 0], [3, 0, 0], [2, 2, 2], [2, -2, -2], [2, -2, 2],\n [-2, 2, 2], [-2, 2, -2], [-2, -2, 2], [2, 2, -2], [-2, -2, -2]])\n weights =[]\n weights+=[9.58789162377528*10**(-2)]*1\n weights+=[7.31047082129148*10**(-2)]*6\n weights+=[3.46588971093380*10**(-3)]*12\n weights+=[3.66108082044515*10**(-2)]*8\n weights+=[1.59235232232060*10**(-2)]*6\n weights+=[2.52480845105094*10**(-3)]*12\n weights+=[7.26968662515159*10**(-5)]*8\n weights+=[7.65879439346840*10**(-4)]*6\n w = np.array(weights)\n cs = 1/1.20288512331026\n\nclass D3V107(Stencil):\n e = np.array(\n [[0, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0], [0, 0, -1], [1, 0, 0], [0, -1, 0], [1, -1, 0], [-1, 1, 0],\n [0, 1, 1], [-1, 0, 1], [-1, 0, -1], [1, 0, -1], [-1, -1, 0], [0, -1, -1], [1, 1, 0], [1, 0, 1], [0, -1, 1],\n [0, 1, -1], [1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1], [-1, 1, -1],\n [0, -2, 0], [-2, 0, 0], [0, 2, 0], [0, 0, -2], [0, 0, 2], [2, 0, 0], [0, 2, -1], [0, -2, 1], [0, 2, 1],\n [0, -1, 2], [0, -1, -2], [0, 1, -2], [0, -2, -1], [-1, 0, 2], [1, -2, 0], [2, 1, 0], [2, 0, 1], [2, 0, -1],\n [2, -1, 0], [-2, -1, 0], [-2, 0, -1], [-2, 0, 1], [0, 1, 2], [-2, 1, 0], [1, 0, 2], [-1, -2, 0], [-1, 0, -2],\n [1, 0, -2], [-1, 2, 0], [1, 2, 0], [0, 2, 2], [2, 0, -2], [0, 2, -2], [2, 0, 2], [2, -2, 0], [2, 2, 0],\n [0, -2, 2], [0, -2, -2], [-2, -2, 0], [-2, 0, -2], [-2, 0, 2], [-2, 2, 0], [3, 1, 1], [-3, -1, -1],\n [-3, -1, 1], [-3, 1, -1], [-3, 1, 1], [1, 3, 1], [1, 3, -1], [1, 1, 3], [3, -1, -1], [-1, -3, -1], [1, 1, -3],\n [-1, -1, -3], [1, -3, -1], [1, -3, 1], [3, 1, -1], [-1, -3, 1], [-1, 3, 1], [-1, 3, -1], [1, -1, -3],\n [1, -1, 3], [-1, 1, -3], [-1, -1, 3], [-1, 1, 3], [3, -1, 1], [2, -2, -2], [-2, 2, -2], [2, -2, 2],\n [-2, -2, 2], [-2, -2, -2], [-2, 2, 2], [2, 2, 2], [2, 2, -2], [-4, 0, 0], [0, 0, 4], [0, 0, -4], [0, -4, 0],\n [0, 4, 0], [4, 0, 0]])\n weights = []\n weights += [7.57516860965017 * 10 ** (-2)] * 1\n weights += [6.00912802747447 * 10 ** (-2)] * 6\n weights += [3.13606906699535 * 10 ** (-3)] * 12\n weights += [3.63392812078012 * 10 ** (-2)] * 8\n weights += [1.32169332731492 * 10 ** (-2)] * 6\n weights += [4.48492851172950 * 10 ** (-3)] * 24\n weights += [2.48755775808342 * 10 ** (-3)] * 12\n weights += [6.07432754970149 * 10 ** (-4)] * 24\n weights += [4.64179164402822 * 10 ** (-4)] * 8\n weights += [4.51928894609872 * 10 ** (-5)] * 6\n w = np.array(weights)\n\n cs = 1/1.07182071542885\n\nclass D3Q103(Stencil):\n e = np.array(\n [[0, 0, 0], [0, 0, 1], [-1, 0, 0], [0, -1, 0], [0, 0, -1], [1, 0, 0], [0, 1, 0], [1, -1, -1], [1, -1, 1],\n [1, 1, -1], [1, 1, 1], [-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1], [0, -2, 0], [0, 0, 2],\n [0, 0, -2], [0, 2, 0], [-2, 0, 0], [2, 0, 0], [0, 1, 2], [2, 1, 0], [2, 0, 1], [0, -2, 1], [0, -1, -2],\n [2, 0, -1], [2, -1, 0], [1, 2, 0], [1, 0, 2], [1, 0, -2], [1, -2, 0], [0, 1, -2], [0, 2, 1], [0, 2, -1],\n [0, -2, -1], [0, -1, 2], [-1, 2, 0], [-2, 0, 1], [-2, 1, 0], [-1, 0, 2], [-1, 0, -2], [-2, -1, 0],\n [-1, -2, 0], [-2, 0, -1], [0, 2, 2], [-2, 0, 2], [0, 2, -2], [-2, 2, 0], [-2, -2, 0], [2, -2, 0],\n [-2, 0, -2], [2, 0, -2], [0, -2, 2], [2, 0, 2], [0, -2, -2], [2, 2, 0], [0, 0, -3], [0, 0, 3], [3, 0, 0],\n [0, -3, 0], [0, 3, 0], [-3, 0, 0], [3, 1, -1], [1, 1, 3], [-1, 3, -1], [1, 3, 1], [1, 3, -1], [-3, 1, -1],\n [-3, -1, 1], [-3, -1, -1], [3, 1, 1], [-3, 1, 1], [1, 1, -3], [1, -3, 1], [-1, -3, 1], [-1, 3, 1],\n [-1, 1, 3], [-1, 1, -3], [-1, -1, 3], [-1, -1, -3], [3, -1, 1], [3, -1, -1], [1, -3, -1], [1, -1, -3],\n [1, -1, 3], [-1, -3, -1], [2, -2, 2], [-2, -2, -2], [2, -2, -2], [-2, 2, 2], [2, 2, 2], [-2, 2, -2],\n [2, 2, -2], [-2, -2, 2], [-3, -3, -3], [3, -3, -3], [3, 3, -3], [-3, 3, 3], [-3, 3, -3], [-3, -3, 3],\n [3, -3, 3], [3, 3, 3]])\n weights = []\n weights += [0.03263335176447115946] * 1\n weights += [0.09765683359033457422] * 6\n weights += [0.02809775029025733562] * 8\n weights += [0.00104525956043006146] * 6\n weights += [0.00570532901689481599] * 24\n weights += [0.00061193926982974783] * 12\n weights += [0.00028444325180005520] * 6\n weights += [0.00013069837598519158] * 24\n weights += [0.00015596415937428372] * 8\n weights += [0.00000122319450132305] * 8\n w = np.array(weights)\n\n cs = 1 / 1.19697977039307435897\n\ndef makeD2Q25HWeights():\n r = (np.sqrt(5.) - np.sqrt(2.)) / np.sqrt(3.)\n w_0 = (-3 - 3 * r * r * r * r + 54 * r * r) / (75 * r * r)\n w_m = (9 * r * r * r * r - 6 - 27 * r * r) / (300 * r * r * (r * r - 1))\n w_n = (9 - 6 * r * r * r * r - 27 * r * r) / (300 * (1 - r * r))\n w_0n = w_0 * w_n\n w_0m = w_0 * w_m\n w_mm = w_m * w_m\n w_mn = w_m * w_n\n w_nn = w_n * w_n\n result = []\n result += w_0 * w_0, w_0m, w_0m, w_0m, w_0m, w_mm, w_mm, w_mm, w_mm, w_0n, w_0n, w_0n, w_0n, w_nn, w_nn, w_nn, w_nn, w_mn, w_mn, w_mn, w_mn, w_mn, w_mn, w_mn, w_mn\n w = np.asarray(result)\n return w\n\n\ndef makeD2Q25HSpeeds():\n c_m = np.sqrt(5. - np.sqrt(10.)) # /np.sqrt(3.)\n c_n = np.sqrt(5. + np.sqrt(10.)) # /np.sqrt(3.)\n e = [[0.0, 0.0], [c_m, 0.0], [0.0, c_m], [-c_m, 0.0], [0.0, -c_m], [c_m, c_m], [-c_m, c_m], [-c_m, -c_m],\n [c_m, -c_m], [c_n, 0.0], [0.0, c_n], [-c_n, 0.0], [0.0, -c_n], [c_n, c_n], [-c_n, c_n], [-c_n, -c_n],\n [c_n, -c_n], [c_m, c_n], [c_m, -c_n], [-c_m, -c_n], [-c_m, c_n], [c_n, c_m], [c_n, -c_m], [-c_n, -c_m],\n [-c_n, c_m]]\n e = np.asarray(e)\n return e\n\n\nclass D2Q25H(Stencil):\n e = makeD2Q25HSpeeds()\n w = makeD2Q25HWeights()\n\n cs = 1\n\nclass CompressibleUnitConversion(UnitConversion):\n @property\n def characteristic_velocity_lu(self):\n return self.lattice.stencil.cs * self.mach_number\n\n\nclass HermiteEquilibrium:\n def __init__(self, lattice):\n self.lattice = lattice\n e = lattice.e\n cs2 = lattice.cs * lattice.cs\n Q = e.shape[0]\n D = e.shape[1]\n\n # Calculate Hermite polynomials\n self.H0 = 1\n self.H1 = torch.zeros([Q, D], dtype=lattice.dtype,device=lattice.device)\n self.H2 = torch.zeros([Q, D, D], dtype=lattice.dtype,device=lattice.device)\n self.H3 = torch.zeros([Q, D, D, D], dtype=lattice.dtype,device=lattice.device)\n self.H4 = torch.zeros([Q, D, D, D, D], dtype=lattice.dtype,device=lattice.device)\n\n for a in range(D):\n self.H1[:, a] = e[:, a]\n for b in range(D):\n e_ab = e[:, a] * e[:, b]\n self.H2[:, a, b] = e_ab\n if (a == b):\n self.H2[:, a, b] -= cs2\n for c in range(D):\n e_abc = e_ab * e[:, c]\n self.H3[:, a, b, c] = e_abc\n if a == b:\n self.H3[:, a, b, c] -= e[:, c] * cs2\n if b == c:\n self.H3[:, a, b, c] -= e[:, a] * cs2\n if a == c:\n self.H3[:, a, b, c] -= e[:, b] * cs2\n for d in range(D):\n self.H4[:, a, b, c, d] = e_abc * e[:, d]\n if a == b:\n if c == d:\n self.H4[:, a, b, c, d] += cs2 * cs2\n if b == c:\n if a == d:\n self.H4[:, a, b, c, d] += cs2 * cs2\n if b == d:\n if a == c:\n self.H4[:, a, b, c, d] += cs2 * cs2\n if a == b:\n self.H4[:, a, b, c, d] -= cs2 * e[:, c] * e[:, d]\n if a == c:\n self.H4[:, a, b, c, d] -= cs2 * e[:, b] * e[:, d]\n if a == d:\n self.H4[:, a, b, c, d] -= cs2 * e[:, b] * e[:, c]\n if b == c:\n self.H4[:, a, b, c, d] -= cs2 * e[:, a] * e[:, d]\n if b == d:\n self.H4[:, a, b, c, d] -= cs2 * e[:, a] * e[:, c]\n if c == d:\n self.H4[:, a, b, c, d] -= cs2 * e[:, a] * e[:, b]\n\n def __call__(self, rho, u, T, order=4, *args):\n D = self.lattice.e.shape[1]\n\n cs2 = self.lattice.cs * self.lattice.cs\n T_1 = ((T - 1) * cs2)[0]\n a0 = 1\n a1 = u\n a2 = self.lattice.einsum('a,b->ab', [a1, a1]) #+ torch.eye(2) * T_1\n for a in range(D):\n for b in range(D):\n if a==b:\n a2[a,b]+=T_1\n a3 = self.lattice.einsum('ab,c->abc', [self.lattice.einsum('a,b->ab', [a1, a1]), a1])\n\n for a in range(D):\n for b in range(D):\n for c in range(D):\n if a==b:\n a3[a, b, c] += T_1 * u[c]\n if b==c:\n a3[a, b, c] += T_1 * u[a]\n if a==c:\n a3[a, b, c] += T_1 * u[b]\n\n a4 = self.lattice.einsum('abc,d->abcd',\n [self.lattice.einsum('ab,c->abc', [self.lattice.einsum('a,b->ab', [a1, a1]), a1]), a1])\n for a in range(D):\n for b in range(D):\n for c in range(D):\n for d in range(D):\n if (a == b):\n a4[a, b, c, d] += u[c] * u[d] * T_1\n if (a == c):\n a4[a, b, c, d] += u[b] * u[d] * T_1\n if (a == d):\n a4[a, b, c, d] += u[c] * u[b] * T_1\n if (b == c):\n a4[a, b, c, d] += u[a] * u[d] * T_1\n if (b == d):\n a4[a, b, c, d] += u[a] * u[c] * T_1\n if (c == d):\n a4[a, b, c, d] += u[a] * u[b] * T_1\n if a == b:\n if c == d:\n a4[a, b, c, d] += T_1 * T_1\n if b == c:\n if a == d:\n a4[a, b, c, d] += T_1 * T_1\n if b == d:\n if a == c:\n a4[a, b, c, d] += T_1 * T_1\n\n H0a0 = self.H0 * a0\n H1a1 = self.lattice.einsum('ia,a->i', [self.H1, a1])\n H2a2 = self.lattice.einsum('iab,ab->i', [self.H2, a2])\n H3a3 = self.lattice.einsum('iabc,abc->i', [self.H3, a3])\n H4a4 = self.lattice.einsum('iabcd,abcd->i', [self.H4, a4])\n\n feq = rho*self.lattice.einsum('i,i->i', [self.lattice.w,(\n H0a0 + H1a1 / (cs2) + H2a2 / (2 * cs2 * cs2) + H3a3 / (6 * cs2 * cs2 * cs2)\n + H4a4 / (24 * cs2 * cs2 * cs2 * cs2))])\n return feq\n\n\nclass SodShockTube:\n def __init__(self, resolution, lattice, T_left=1.25, rho_left=8, visc=0.001):\n self.visc = visc\n self.resolution = resolution\n self.T_left = T_left\n self.rho_left = rho_left\n self.units = UnitConversion(\n lattice,\n reynolds_number=lattice.cs/(visc*resolution), mach_number=1,\n characteristic_length_lu=resolution, characteristic_length_pu=1,\n characteristic_velocity_pu=1\n )\n\n def calc_offsets(self, left, right):\n d = (right / 2 - left / 2)\n c = 2 * (left) / (right - left) + 1\n return c, d\n\n def initial_solution(self, x):\n #Defines the smoothness of the discontinuity\n a=10000000000\n rho_c,rho_d=self.calc_offsets(self.rho_left,1.0)\n T_c,T_d = self.calc_offsets(self.T_left,1.0)\n u = np.array([0 * x[0] + 0 * x[1], 0 * x[0] + 0 * x[1]])\n rho = np.array([(np.tanh(a*(x[0]-0.5))+rho_c)*rho_d+ x[1] * 0 ])\n T = np.array([(np.tanh(a*(x[0]-0.5))+T_c)*T_d + x[1] * 0])\n return rho, u, T\n\n @property\n def grid(self):\n x = np.linspace(0, 1, num=self.resolution, endpoint=True)\n y = np.linspace(0, 1, num=5, endpoint=False)\n return np.meshgrid(x, y, indexing='ij')\n\n @property\n def boundaries(self):\n x, y = self.grid\n return [BounceBackBoundary(np.abs(x) < 1e-1, self.units.lattice),BounceBackBoundary(np.abs(x) > 9*1e-1, self.units.lattice)]\n\nclass SteadyShock:\n def __init__(self, resolution, lattice, visc=0.00001):\n self.visc = visc\n self.resolution = resolution\n\n self.units = UnitConversion(\n lattice,\n reynolds_number=lattice.cs/(visc*resolution), mach_number=1,\n characteristic_length_lu=resolution, characteristic_length_pu=1,\n characteristic_velocity_pu=1\n )\n\n def calc_offsets(self, left, right):\n d = (right / 2 - left / 2)\n c = 2 * (left) / (right - left) + 1\n return c, d\n\n def initial_solution(self, x):\n rho = np.array([1.0 + x[0]*0 +x[1] * 0 ])\n T = np.array([1.0 + x[0]*0 + x[1]*0])\n u = np.array([0 * x[0] + 0 * x[1], 0 * x[0] + 0 * x[1]])\n rho[0,:,6] = 1.3\n return rho, u, T\n\n @property\n def grid(self):\n x = np.linspace(0, 1, num=self.resolution, endpoint=True)\n y = np.linspace(0, 1, num=self.resolution, endpoint=False)\n return np.meshgrid(x, y, indexing='ij')\n\n @property\n def boundaries(self):\n x, y = self.grid\n return [BounceBackBoundary(np.abs(x) < 1e-1, self.units.lattice),BounceBackBoundary(np.abs(x) > 9*1e-1, self.units.lattice)]\n\nclass CompressibleEnergyReporter(GenericStepReporter):\n \"\"\"Reports the kinetic energy \"\"\"\n _parameter_name = 'Kinetic energy'\n\n def parameter_function(self,i,t,f,g):\n dx = self.flow.units.convert_length_to_pu(1.0)\n rho = self.lattice.rho(f)\n kinE = self.flow.units.convert_incompressible_energy_to_pu(torch.sum(self.lattice.incompressible_energy(f)*rho ))\n kinE *= dx ** self.lattice.D\n return kinE.item()\n\nclass MaxMachReporter(GenericStepReporter):\n \"\"\"Reports the maximum Mach number\"\"\"\n _parameter_name = 'Max Mach number'\n\n def parameter_function(self, i, t, f, g):\n gamma = 1.4\n C_v = 1. / (gamma - 1)\n u = self.lattice.u(f)\n magnitude = u[0]**2 + u[1]**2\n if(self.lattice.D==3):\n magnitude += u[2]**2\n magnitude = torch.sqrt(magnitude)\n\n T = self.lattice.temperature(f,g,C_v)\n #a_0 = torch.sqrt(gamma*T)\n magnitude = torch.max(magnitude/(self.lattice.cs*np.sqrt(1.4))) #/ a_0)\n return magnitude\n\n\n\nclass CompressibleDissipationReporter(GenericStepReporter):\n \"\"\"Reports the integral of the vorticity\n\n Notes\n -----\n The function only works for periodic domains\n \"\"\"\n _parameter_name = 'Dissipation'\n\n def parameter_function(self,i,t,f,g):\n u0 = self.flow.units.convert_velocity_to_pu(self.lattice.u(f)[0])\n u1 = self.flow.units.convert_velocity_to_pu(self.lattice.u(f)[1])\n dx = self.flow.units.convert_length_to_pu(1.0)\n grad_u0 = torch_gradient(u0, dx=dx, order=6).cpu().numpy()\n grad_u1 = torch_gradient(u1, dx=dx, order=6).cpu().numpy()\n dilatation = np.sum(grad_u0[0] + grad_u1[1])\n vorticity = np.sum((grad_u0[1] - grad_u1[0]) * (grad_u0[1] - grad_u1[0]))\n if self.lattice.D == 3:\n u2 = self.flow.units.convert_velocity_to_pu(self.lattice.u(f)[2])\n grad_u2 = torch_gradient(u2, dx=dx, order=6).cpu().numpy()\n dilatation += np.sum(grad_u2[2])\n vorticity += np.sum(\n (grad_u2[1] - grad_u1[2]) * (grad_u2[1] - grad_u1[2])\n + ((grad_u0[2] - grad_u2[0]) * (grad_u0[2] - grad_u2[0])))\n return (vorticity+4./3*dilatation.item()) * dx**self.lattice.D\n\nclass CompressibleLattice(Lattice):\n def __init__(self, stencil, device, dtype=torch.float, gamma = 1.4):\n super().__init__(stencil,device,dtype)\n self.gamma = gamma\n\n def temperature(self, f, g, C_v):\n u = self.u(f)\n index = [Ellipsis] + [None] * self.D\n diff = (self.e[index] - u ) * (self.e[index] - u)\n prod = torch.sum(diff, axis=1)\n f_sum = (self.einsum(\"i,i->i\", [prod, f]))\n fg_sum = (f_sum/(self.cs * self.cs) + g).sum(axis=0)\n return fg_sum/ (self.rho(f) * 2*C_v)\n\nclass BDFSimulation(Simulation):\n def __init__(self, flow, lattice, collision, streaming):\n super(BDFSimulation, self).__init__(flow, lattice, collision, streaming)\n self.f_old = deepcopy(self.f)\n self.feq_old = deepcopy(self.f)\n\n def step(self, num_steps):\n \"\"\"Take num_steps stream-and-collision steps and return performance in MLUPS.\"\"\"\n start = timer()\n for _ in range(num_steps):\n self.i += 1\n self.f = self.streaming(self.f)\n self.f_old = self.streaming(self.f_old)\n self.feq_old = self.streaming(self.feq_old)\n f_copy = deepcopy(self.f)\n #Perform the collision routine everywhere, expect where the no_collision_mask is true\n self.f, self.feq_old = self.collision(self.f,self.f_old,self.feq_old,self.i)\n self.f_old = f_copy\n for boundary in self.flow.boundaries:\n self.f = boundary(self.f)\n for reporter in self.reporters:\n reporter(self.i, self.i, self.f)\n end = timer()\n seconds = end-start\n num_grid_points = self.lattice.rho(self.f).numel()\n mlups = num_steps * num_grid_points / 1e6 / seconds\n return mlups\n\n\n\nclass BDF2Collision:\n def __init__(self, lattice, tau):\n self.lattice = lattice\n self.tau = tau\n self.tau_0 = 9 / 8 * (tau - 0.5) + 3 / 4\n self.tau_m1 = 9 / 2 * (tau - 0.5) + 3\n self.counter = 0\n\n def __call__(self, f, f_old, feq_old, step):\n rho = self.lattice.rho(f)\n u = self.lattice.u(f)\n feq = self.lattice.equilibrium(rho, u)\n if step <= 1:\n return f - 1.0 / self.tau * (f - feq), feq\n else:\n self.counter+=1\n return 4/3*f - 1/3*f_old - 1/self.tau_0 * (f - feq) + 1/self.tau_m1*(f_old-feq_old), feq\n\n\n\nclass BGKCompressibleCollision:\n def __init__(self, lattice, tau, gamma):\n self.lattice = lattice\n self.tau = tau\n self.gamma = gamma\n\n def __call__(self, f, g):\n\n C_v = 1./(self.gamma - 1)\n rho = self.lattice.rho(f)\n u = self.lattice.u(f)\n T = self.lattice.temperature(f,g,C_v)\n feq = self.lattice.equilibrium(rho, u, T)\n sunderland_factor = 1.0#1.4042 * T**1.5 / (T+0.40417)\n sunderland_tau = (self.tau -0.5)/(T*rho)*sunderland_factor + 0.5\n geq = (2*C_v-self.lattice.D)*T*feq\n f_post= f - 1.0 / sunderland_tau * (f-feq)\n g_post = g - 1.0 / sunderland_tau *(g-geq)\n return f_post,g_post\n\nclass CompressibleVTKReporter(VTKReporter):\n def __call__(self, i, t, f, g):\n if t % self.interval == 0:\n t = self.flow.units.convert_time_to_pu(t)\n u = self.flow.units.convert_velocity_to_pu(self.lattice.u(f))\n rho = self.flow.units.convert_density_lu_to_pressure_pu(self.lattice.rho(f))\n\n T = self.lattice.temperature(f,g,2.5)\n if self.lattice.D == 2:\n self.point_dict[\"p\"] = self.lattice.convert_to_numpy(rho[0, ..., None])\n for d in range(self.lattice.D):\n self.point_dict[f\"u{'xyz'[d]}\"] = self.lattice.convert_to_numpy(u[d, ..., None])\n #self.point_dict[\"T\"] = self.lattice.convert_to_numpy(T[0,..., None])\n else:\n self.point_dict[\"p\"] = self.lattice.convert_to_numpy(rho[0, ...])\n for d in range(self.lattice.D):\n self.point_dict[f\"u{'xyz'[d]}\"] = self.lattice.convert_to_numpy(u[d, ...])\n self.point_dict[\"T\"] = self.lattice.convert_to_numpy(T[0, ...])\n write_vtk(self.point_dict, i, self.filename_base)\n\nclass CompressibleSimulation(Simulation):\n def __init__(self, flow, lattice, collision, streaming):\n self.flow = flow\n self.lattice = lattice\n self.collision = collision\n self.streaming = streaming\n self.i = 0\n self.lattice.equilibrium=HermiteEquilibrium(lattice)\n self.reporters = []\n\n grid = flow.grid\n rho, u, T = flow.initial_solution(grid)\n assert list(rho.shape) == [1] + list(grid[0].shape), \\\n LettuceException(f\"Wrong dimension of initial pressure field. \"\n f\"Expected {[1] + list(grid[0].shape)}, \"\n f\"but got {list(rho.shape)}.\")\n assert list(u.shape) == [lattice.D] + list(grid[0].shape), \\\n LettuceException(\"Wrong dimension of initial velocity field.\"\n f\"Expected {[lattice.D] + list(grid[0].shape)}, \"\n f\"but got {list(u.shape)}.\")\n u = lattice.convert_to_tensor(flow.units.convert_velocity_to_lu(u))\n #T = T * self.lattice.stencil.cs**2\n self.f = lattice.equilibrium(lattice.convert_to_tensor(rho), lattice.convert_to_tensor(u),lattice.convert_to_tensor(T))\n gamma = 1.4\n C_v = 1/(gamma - 1)\n self.g = (2*C_v-lattice.D)*lattice.convert_to_tensor(T)*self.f\n\n\n # Define a mask, where the collision shall not be applied\n x = flow.grid\n self.no_collision_mask = np.zeros_like(x[0], dtype=bool)\n self.no_collision_mask = lattice.convert_to_tensor(self.no_collision_mask)\n for boundary in self.flow.boundaries:\n if boundary.__class__.__name__ == \"BounceBackBoundary\":\n self.no_collision_mask = boundary.mask | self.no_collision_mask\n\n def step(self, num_steps):\n \"\"\"Take num_steps stream-and-collision steps and return performance in MLUPS.\"\"\"\n start = timer()\n for _ in range(num_steps):\n self.i += 1\n self.f = self.streaming(self.f)\n self.g = self.streaming(self.g)\n\n\n f_post, g_post = self.collision(self.f,self.g)\n # Perform the collision routine everywhere, expect where the no_collision_mask is true\n self.f = torch.where(self.no_collision_mask, self.f, f_post)\n self.g = torch.where(self.no_collision_mask, self.g, g_post)\n for boundary in self.flow.boundaries:\n self.f = boundary(self.f)\n self.g = boundary(self.g)\n\n for reporter in self.reporters:\n reporter(self.i, self.i, self.f, self.g)\n\n end = timer()\n seconds = end - start\n num_grid_points = self.lattice.rho(self.f).numel()\n mlups = num_steps * num_grid_points / 1e6 / seconds\n return mlups\n\n def initialize_f_neq(self):\n \"\"\"Initialize the distribution function values. The f^(1) contributions are approximated by finite differences.\n See Krüger et al. (2017).\n \"\"\"\n rho = self.lattice.rho(self.f)\n u = self.lattice.u(self.f)\n T = self.lattice.temperature(self.f,self.g,2.5)\n\n grad_u0 = torch_gradient(u[0], dx=1, order=6)[None, ...]\n grad_u1 = torch_gradient(u[1], dx=1, order=6)[None, ...]\n S = torch.cat([grad_u1, grad_u0])\n\n if(self.lattice.D==3):\n grad_u2 = torch_gradient(u[2], dx=1, order=6)[None, ...]\n S = torch.cat([S, grad_u2])\n\n Pi_1 = -1.0 * self.flow.units.relaxation_parameter_lu * rho * S / self.lattice.cs**2\n Q = torch.einsum('ia,ib->iab',self.lattice.e,self.lattice.e)-torch.eye(self.lattice.D,device=self.lattice.device)*self.lattice.cs**2\n Pi_1_Q = torch.einsum('ab...,iab->i...', Pi_1, Q)\n fneq = torch.einsum('i,i...->i...',self.lattice.w,Pi_1_Q)\n\n feq = self.lattice.equilibrium(rho,u,T)\n self.f = feq + fneq\n\n\nclass BGKCompressibleBDFCollision:\n def __init__(self, lattice, tau, gamma):\n self.lattice = lattice\n self.tau = tau\n self.gamma = gamma\n self.tau_0 = 9 / 8 * (tau - 0.5) + 3 / 4\n self.tau_m1 = 9 / 2 * (tau - 0.5) + 3\n\n def __call__(self, f, f_old,feq_old, g, g_old, geq_old, step):\n\n C_v = 1./(self.gamma - 1)\n rho = self.lattice.rho(f)\n u = self.lattice.u(f)\n T = self.lattice.temperature(f,g,C_v)\n feq = self.lattice.equilibrium(rho, u, T)\n sunderland_factor = 1.0 #1.4042 * T**1.5 / (T+0.40417)\n sunderland_tau = (self.tau -0.5)/(T*rho)*sunderland_factor + 0.5\n geq = (2*C_v-self.lattice.D)*T*feq\n if step == 1:\n f_post = f - 1.0 / sunderland_tau * (f - feq)\n g_post = g - 1.0 / sunderland_tau * (g - geq)\n return f_post, feq, g_post, geq_old\n else:\n tau_0 = 9 / 8 * (self.tau - 0.5) + 3 / 4\n tau_m1 = 9 / 2 * (self.tau - 0.5) + 3\n f_post = 4 / 3 * f - 1 / 3 * f_old - 1 / tau_0 * (f - feq) + 1 / tau_m1 * (f_old - feq_old)\n g_post = 4 / 3 * g - 1 / 3 * g_old - 1 / tau_0 * (g - geq) + 1 / tau_m1 * (g_old - geq_old)\n return f_post, feq, g_post, geq\n\n\nclass BDFCompressibleSimulation(CompressibleSimulation):\n def __init__(self, flow, lattice, collision, streaming):\n self.flow = flow\n self.lattice = lattice\n self.collision = collision\n self.streaming = streaming\n self.i = 0\n self.lattice.equilibrium=HermiteEquilibrium(lattice)\n self.reporters = []\n\n grid = flow.grid\n rho, u, T = flow.initial_solution(grid)\n assert list(rho.shape) == [1] + list(grid[0].shape), \\\n LettuceException(f\"Wrong dimension of initial pressure field. \"\n f\"Expected {[1] + list(grid[0].shape)}, \"\n f\"but got {list(rho.shape)}.\")\n assert list(u.shape) == [lattice.D] + list(grid[0].shape), \\\n LettuceException(\"Wrong dimension of initial velocity field.\"\n f\"Expected {[lattice.D] + list(grid[0].shape)}, \"\n f\"but got {list(u.shape)}.\")\n u = lattice.convert_to_tensor(flow.units.convert_velocity_to_lu(u))\n #T = T * self.lattice.stencil.cs**2\n self.f = lattice.equilibrium(lattice.convert_to_tensor(rho), lattice.convert_to_tensor(u),lattice.convert_to_tensor(T))\n gamma = 1.4\n C_v = 1/(gamma - 1)\n self.g = (2*C_v-lattice.D)*lattice.convert_to_tensor(T)*self.f\n\n\n # Define a mask, where the collision shall not be applied\n x = flow.grid\n self.no_collision_mask = np.zeros_like(x[0], dtype=bool)\n self.no_collision_mask = lattice.convert_to_tensor(self.no_collision_mask)\n for boundary in self.flow.boundaries:\n if boundary.__class__.__name__ == \"BounceBackBoundary\":\n self.no_collision_mask = boundary.mask | self.no_collision_mask\n self.f_old = deepcopy(self.f)\n self.feq_old = deepcopy(self.f)\n self.g_old = deepcopy(self.g)\n self.geq_old = deepcopy(self.g)\n\n def step(self, num_steps):\n \"\"\"Take num_steps stream-and-collision steps and return performance in MLUPS.\"\"\"\n start = timer()\n for _ in range(num_steps):\n self.i += 1\n self.f = self.streaming(self.f)\n self.g = self.streaming(self.g)\n\n self.f_old = self.streaming(self.f_old)\n self.feq_old = self.streaming(self.feq_old)\n self.g_old = self.streaming(self.g_old)\n self.geq_old = self.streaming(self.geq_old)\n f_copy = deepcopy(self.f)\n g_copy = deepcopy(self.g)\n # Perform the collision routine everywhere, expect where the no_collision_mask is true\n\n self.f, self.feq_old, self.g, self.geq_old = self.collision(self.f, self.f_old, self.feq_old, self.g, self.g_old, self.geq_old, self.i)\n self.f_old = f_copy\n self.g_old = g_copy\n for boundary in self.flow.boundaries:\n self.f = boundary(self.f)\n self.g = boundary(self.g)\n\n for reporter in self.reporters:\n reporter(self.i, self.i, self.f, self.g)\n end = timer()\n seconds = end - start\n num_grid_points = self.lattice.rho(self.f).numel()\n mlups = num_steps * num_grid_points / 1e6 / seconds\n return mlups\n\n\n","sub_path":"lettuce/compressible.py","file_name":"compressible.py","file_ext":"py","file_size_in_byte":30439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"28428237","text":"# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nimport json\nfrom typing import List, Optional\n\nimport pytest\n\nfrom pants.core.util_rules import stripped_source_files\nfrom pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest\nfrom pants.core.util_rules.stripped_source_files import StrippedSourceFiles\nfrom pants.engine.fs import EMPTY_SNAPSHOT\nfrom pants.engine.internals.scheduler import ExecutionError\nfrom pants.testutil.rule_runner import QueryRule, RuleRunner\n\n\n@pytest.fixture\ndef rule_runner() -> RuleRunner:\n return RuleRunner(\n rules=[\n *stripped_source_files.rules(),\n QueryRule(SourceFiles, (SourceFilesRequest,)),\n QueryRule(StrippedSourceFiles, (SourceFiles,)),\n ]\n )\n\n\ndef get_stripped_files(\n rule_runner: RuleRunner,\n request: SourceFiles,\n *,\n args: Optional[List[str]] = None,\n) -> List[str]:\n args = args or []\n has_source_root_patterns = False\n for arg in args:\n if arg.startswith(\"--source-root-patterns\"):\n has_source_root_patterns = True\n break\n if not has_source_root_patterns:\n source_root_patterns = [\"src/python\", \"src/java\", \"tests/python\"]\n args.append(f\"--source-root-patterns={json.dumps(source_root_patterns)}\")\n rule_runner.set_options(args)\n result = rule_runner.request(StrippedSourceFiles, [request])\n return list(result.snapshot.files)\n\n\ndef test_strip_snapshot(rule_runner: RuleRunner) -> None:\n def get_stripped_files_for_snapshot(\n paths: List[str],\n *,\n args: Optional[List[str]] = None,\n ) -> List[str]:\n input_snapshot = rule_runner.make_snapshot_of_empty_files(paths)\n request = SourceFiles(input_snapshot, ())\n return get_stripped_files(rule_runner, request, args=args)\n\n # Normal source roots\n assert get_stripped_files_for_snapshot([\"src/python/project/example.py\"]) == [\n \"project/example.py\"\n ]\n assert (\n get_stripped_files_for_snapshot(\n [\"src/python/project/example.py\"],\n )\n == [\"project/example.py\"]\n )\n\n assert get_stripped_files_for_snapshot([\"src/java/com/project/example.java\"]) == [\n \"com/project/example.java\"\n ]\n assert get_stripped_files_for_snapshot([\"tests/python/project_test/example.py\"]) == [\n \"project_test/example.py\"\n ]\n\n # Unrecognized source root\n unrecognized_source_root = \"no-source-root/example.txt\"\n with pytest.raises(ExecutionError) as exc:\n get_stripped_files_for_snapshot([unrecognized_source_root])\n assert f\"NoSourceRootError: No source root found for `{unrecognized_source_root}`.\" in str(\n exc.value\n )\n\n # Support for multiple source roots\n file_names = [\"src/python/project/example.py\", \"src/java/com/project/example.java\"]\n assert get_stripped_files_for_snapshot(file_names) == [\n \"com/project/example.java\",\n \"project/example.py\",\n ]\n\n # Test a source root at the repo root. We have performance optimizations for this case\n # because there is nothing to strip.\n source_root_config = [f\"--source-root-patterns={json.dumps(['/'])}\"]\n\n assert (\n get_stripped_files_for_snapshot(\n [\"project/f1.py\", \"project/f2.py\"],\n args=source_root_config,\n )\n == [\"project/f1.py\", \"project/f2.py\"]\n )\n\n assert (\n get_stripped_files_for_snapshot(\n [\"dir1/f.py\", \"dir2/f.py\"],\n args=source_root_config,\n )\n == [\"dir1/f.py\", \"dir2/f.py\"]\n )\n\n # Gracefully handle an empty snapshot\n assert get_stripped_files(rule_runner, SourceFiles(EMPTY_SNAPSHOT, ())) == []\n","sub_path":"src/python/pants/core/util_rules/stripped_source_files_test.py","file_name":"stripped_source_files_test.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"254668871","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def reorderList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: void Do not return anything, modify head in-place instead.\n \"\"\"\n foo = ListNode(0)\n foo.next = head\n fast = foo\n slow = foo\n # split linked list into halves\n while fast != None and fast.next != None:\n fast = fast.next.next\n slow = slow.next\n \n boo = ListNode(0)\n half_head = slow.next\n slow.next = None\n # reverse the second half\n old_head = None\n old_next = None\n p = half_head\n while p != None:\n old_next = p.next\n p.next = old_head\n old_head = p\n p = old_next\n\n first_p = head\n second_p = old_head\n first_next = first_p.next\n second_next = second_p.next\n while first_p != None and second_p != None:\n first_p.next = second_p\n second_p.next = first_next\n first_p = first_next\n second_p = second_next\n if first_p.next == None or second_p.next == None:\n break\n first_next = first_p.next\n second_next = second_p.next\n return head\n\n\n\n","sub_path":"143-reorder_list/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"491966793","text":"import os\n#import gym\nimport copy\nimport sys\nsys.path.append('..')\n#import safety_gym\nimport random\n\nimport numpy as np\nfrom tqdm import trange\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport deepbayes_prealpha\nimport deepbayes_prealpha.optimizers as optimizers\nfrom deepbayes_prealpha import PosteriorModel\nfrom deepbayes_prealpha.analyzers import IBP_state\nfrom deepbayes_prealpha.analyzers import IBP_prob_dyn_m as IBP_prob\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.layers import *\n\nimport random\nrandom.seed(0)\nnp.random.seed(0)\ntf.random.set_seed(0)\n\npos_ind = 0\nmomentum = -0.25\nGOAL_STATE = [-0.2, -0.2]\n\n\n\"\"\"\nThe handcrafted 2D point environment we consider\n\"\"\"\n\nclass P2D_env:\n def __init__(self):\n self.x = 2.0\n self.y = 2.0\n self.dx = momentum\n self.dy = momentum\n # Point Mass Dynamics Control:\n self.h = 0.5 # time resolution\n self.T = 20 # Time for each trajectory\n self.eta = 0.5 # friction coef\n self.m = 2.0 # mass of the car\n self.t = 0 # current time\n\n def step(self, act):\n if(self.t > self.T):\n sys.exit(-1)\n pt = np.asarray([self.x, self.y])\n vt = np.asarray([self.dx, self.dy])\n ut = np.asarray(act)\n vt_1 = ((1-((self.h*self.eta)/self.m))*vt) + ((self.h/self.m)*ut)\n pt_1 = pt + (self.h*vt_1)\n if(np.linalg.norm(pt_1 - OBSTACLE) < 0.05):\n print(\"COLLIDED\")\n self.dx, self.dy = 0, 0\n self.x, self.y = pt_1[0], pt_1[1]\n self.dx, self.dy = vt_1[0], vt_1[1]\n self.t += 1\n state = np.asarray([self.x, self.y, self.dx, self.dy])\n return state, np.linalg.norm(pt) - np.linalg.norm(pt_1), self.complete(), 0\n\n def complete(self):\n state = np.asarray([self.x, self.y])\n if(np.linalg.norm(state) < 0.05):\n return True\n if(self.t==self.T):\n return True\n\n def reset(self):\n self.x = 2.0\n self.y = 2.0\n self.dx = momentum\n self.dy = momentum\n self.t = 0\n return np.asarray([self.x, self.y, self.dx, self.dy])\n\n def action_space_sample(self):\n return np.random.rand(2)\n def observation_space_sample(self):\n return np.random.rand(4)\n\n\nenv = P2D_env()\n\npos_ind = 0\nstate_0 = env.reset()\n#print(\"HERE IS STATE 0 \", env.robot_pos, env.goal_pos, env.robot_rot)\nprint(\"OBS VAL: \", state_0)\nprint(\"this VAL: \", state_0[pos_ind:pos_ind-2])\n\ninitial_state = state_0 # This is now the template for the \"STATE\" that we will pass throughout\n\naction_dims = len(env.action_space_sample())\nobserve_dims = len(env.observation_space_sample())\n\nprint(\"DIMENSIONS OBS: \", env.observation_space_sample(), len(env.observation_space_sample()))\nprint(\"DIMENSIONS ACT: \", env.action_space_sample(), len(env.action_space_sample()))\n\nmodel_input_dims = observe_dims + action_dims\nmodel_output_dims = observe_dims\nprint(model_input_dims, model_output_dims)\n\ncontrol_input_dims = observe_dims\ncontrol_output_dims = action_dims\nprint(control_input_dims, control_output_dims)\n\n\n# Load BNN\nbayes_model = PosteriorModel(\"BayesDyn_P2D_v0_EXT\")\n#bayes_model = PosteriorModel(\"BNN_Stage0\")\n#bayes_model = PosteriorModel(\"SynthDynBNN\")\n\n# Load DNN\ncontrol_model = PosteriorModel(\"Control_P2D_v0_EXT\", deterministic=True)\n#control_model = PosteriorModel(\"DNN_Stage0\", deterministic=True)\n#control_model = PosteriorModel(\"PoorConDNN\", deterministic=True)\n\ninitial_state = state_0\n\n\n\"\"\"\nBelow is all of the code to do optimization in the action space of our\nBNN dynamics model wrt the output of the DNN control model. This takes\nthe probabalistic safety into account during our verification and saves\na dataset of new, synthesized actions on which the controller is trained\n\nThis new controller can then be re-verified using this same script but\npassing the optimized controller.\n\"\"\"\n\n\nfrom deepbayes_prealpha.analyzers import IBP_fixed_w\n\ndef reward_function(state_0, dyn_pred, goal):\n state_0 = tf.cast(tf.squeeze(state_0), dtype=tf.float32)\n dyn_pred = tf.cast(tf.squeeze(dyn_pred), dtype=tf.float32)\n state_1 = state_0 + dyn_pred\n\n d1 = tf.norm(state_0[pos_ind:pos_ind+2] - goal, axis=0)\n d2 = tf.norm(state_1[pos_ind:pos_ind+2] - goal, axis=0)\n\n #o1 = tf.norm(state_0[pos_ind:pos_ind+2] - OBSTACLE, axis=0)\n #o2 = tf.norm(state_1[pos_ind:pos_ind+2] - OBSTACLE, axis=0)\n #return (-1*(d2-d1)) + ((0.1/o2)*(o2-o1))\n\n return (-1*(d2-d1))\n\n\ndef gradient_expectation(model, inp, loss_fn, num_models=10):\n gradient_sum = tf.zeros(inp.shape)\n inp = tf.convert_to_tensor(inp)\n val = num_models\n if(num_models < 1):\n num_models = 1\n for i in range(num_models):\n if(model.det or val == -1):\n no_op = 0\n else:\n model.model.set_weights(model.sample())\n # Establish Gradient Tape Context (for input this time)\n with tf.GradientTape(persistent=True) as tape:\n tape.watch(inp)\n # Get the probabilities\n predictions = model.predict(inp)\n loss = loss_fn([tf.squeeze(inp)[0:-2]], predictions, GOAL_STATE)\n #predictions = model.predict(inp)\n #predictions = tf.concat(predictions, tf.convert_to_tensor([0.0, 0.0]) ) \n #loss = loss_fn(inp, predictions, GOAL_STATE)\n # Get the gradients\n inp_gradient = tape.gradient(loss, inp)\n #print(\"GRAD: \", inp_gradient)\n try:\n gradient_sum += inp_gradient\n except:\n gradient_sum += tf.cast(inp_gradient, 'float32')\n if(model.det or val == -1):\n break\n return gradient_sum\n\ndef gradient_w(model, inp, loss_fn, w):\n gradient_sum = tf.zeros(np.asarray(inp).shape)\n inp = tf.convert_to_tensor(inp)\n model.model.set_weights(w)\n with tf.GradientTape(persistent=True) as tape:\n tape.watch(inp)\n predictions = model.predict(inp)\n loss = loss_fn([tf.squeeze(inp)[0:-2]], predictions, GOAL_STATE)\n inp_gradient = tape.gradient(loss, inp)\n inp_gradient = tf.cast(inp_gradient, 'float32')\n return tf.squeeze(inp_gradient)[-2:]\n\n\ndef synth_state(state, eps, predicate, loss=None, grad_iters=35):\n if(loss is None):\n loss = reward_function # This is gobally defined\n s0 = np.asarray(state) # Lower bound\n s1 = s0 + eps\n input_to_alg = (s0, s1)\n\n initial_state[pos_ind:pos_ind+2] = s0\n s0_pre = copy.deepcopy(initial_state)\n initial_state[pos_ind:pos_ind+2] = s1\n s1_pre = copy.deepcopy(initial_state)\n s0_pre[pos_ind+2:pos_ind+4] -= 2*eps\n diff = s0_pre - s1_pre\n\n act = control_model.predict(np.asarray([s0_pre]))\n\n act = np.squeeze(act)\n original_act = copy.deepcopy(act)\n\n s0 = np.concatenate((s0_pre,act))\n s1 = np.concatenate((s1_pre,act))\n\n s0 = np.asarray([s0])\n s1 = np.asarray([s1])\n\n #for i in trange(grad_iters, desc=\"Synthesizing Action\"):\n for i in range(grad_iters):\n act = np.squeeze(act)\n s0 = np.concatenate((s0_pre,act))\n s1 = np.concatenate((s1_pre,act))\n s0 = np.asarray([s0])\n s1 = np.asarray([s1])\n\n w = bayes_model.sample()\n p, outs = IBP_fixed_w(bayes_model, s0, s1, 2.0, w, predicate)\n grad = gradient_w(bayes_model, (s0+s1)/2, loss, w)\n #print(act, p, grad)\n #a = act + (math.ceil(p)*0.5 * grad)\n #a = act - (1.5 * grad[::-1])\n a = act + (1.0 * grad)\n act = a\n print(\"RESTUL OF SYNTH: \", act)\n return act, original_act\n\n# Here are the dataset variables that we will track during the initial verification\n\nDYNAMICS_X = []\nDYNAMICS_Y = []\n\nCONTROL_X = []\nCONTROL_Y = []\n\n\n\"\"\"\nBelow is a modified version of the verification proceedure with a subroutine\nfor generating synthesized actions. These synthezied actions are then stored\nin the dataset (or can be applied to the verification) in order to develop\na safer controller (wrt probabalistic safety).\n\"\"\"\n\ndef verify_state(state, eps, predicate, refine=4.0, s=False):\n s0 = np.asarray(state) \t\t\t\t# Lower bound of the states\n s1 = s0 + eps\t\t\t\t\t# Add epsilon to the postion to get the upper bound\n input_to_alg = (s0, s1)\n\n initial_state[pos_ind:pos_ind+2] = s0\t\t# Making copies of the state with velocity to pass to bounds\n s0_pre = copy.deepcopy(initial_state)\n initial_state[pos_ind:pos_ind+2] = s1\n s1_pre = copy.deepcopy(initial_state)\n s0_pre[pos_ind+2:pos_ind+4] -= 2*eps \t\t# Subtracting epsilon from momentum to get interval over velocity\n diff = s0_pre - s1_pre\n\n # Propagating the intervals through the controller to get action intervals\n low, high = np.asarray([s0_pre])+0.5*diff, np.asarray([s0_pre])-0.5*diff\n act = control_model.predict(np.asarray([s0_pre]))\n act_l, act_u = IBP_state(control_model, low, high, control_model.model.get_weights())\n act_l = np.squeeze(act_l)#-0.175\n act_u = np.squeeze(act_u)#-0.175\n print(\"Actions: \", act_l, act_u)\n\n if(s):\n act, _ = synth_state(state, eps, predicate, grad_iters=int(25*refine))\n act_l = np.squeeze(act)\n act_u = np.squeeze(act)\n print(\"SYNTHED ACTION: \", act_l, act_u)\n CONTROL_X.append(s0_pre); CONTROL_Y.append(act_u)\n res0 = np.concatenate((0.25*act_l, act_l))\n res1 = np.concatenate((0.25*act_l, act_l))\n #res1 = np.concatenate((SAFE_REGION - np.asarray(state) + 0.05*act_l, act_l))\n s0 = np.concatenate((s0_pre,act_u))\n s1 = np.concatenate((s1_pre,act_u))\n DYNAMICS_X.append(s0); DYNAMICS_Y.append(res0)\n DYNAMICS_X.append(s1); DYNAMICS_Y.append(res1)\n\n # Adding the action intervals to state intervals to get full intervals\n s0 = np.concatenate((s0_pre,act_l))\n s1 = np.concatenate((s1_pre,act_u))\n\n s0 = np.asarray([s0])\n s1 = np.asarray([s1])\n\n # Computing the probability by propagating intervals through the BNN\n p, outs = IBP_prob(bayes_model, s0, s1, 3.5*(1/refine), int(150*(refine**2)), predicate, inflate=1.0)\n\n return p, outs\n\n\ndef predicate(source_l, source_u, state_l, state_u):\n\n source_l = source_l[0:observe_dims]\n source_u = source_u[0:observe_dims]\n\n state_l = source_l + state_l\t\t# Lower Bound on next state\n state_u = source_u + state_u\t\t# Upper Bound on next state\n collision = True\t\t\t\t# No collision in this model, so set to True (= Safe)\n\n #print(state_u)\n # If the upper bound of the postion is in the safe region then we are safe\n goal = (state_u[pos_ind:pos_ind+2] <= SAFE_REGION).all()\n # If all of the velocities are stillsafe then we are safe\n velo = (state_u[pos_ind+2:pos_ind+4] <= momentum).all()\n # Return the condition that position and velocities are safe\n return collision and goal and velo\n\n\n\n# Setting up the state space discretization for the verification\n\n\nfrom tqdm import tqdm\n\nSAFE_REGION = 0.2\t\t\t# Goal region (Initial safe region)\nstates = 15\t\t\t\t# Number of states to verify\nend_point = 0.30\t\t\t# End point of the state space to consider\neps = end_point/(states)\t\t# Epsilon (size of each grid space)\nnon_zero = []\nind_i, ind_j = 0,0\nmultiplier = 1.0\npre_global_probas = np.zeros((states,states))\nprint(\"k = \", states-int(SAFE_REGION/eps) + 1)\nglobal_probas = np.zeros((states,states))\nfor k in trange(states-int(SAFE_REGION/eps) + 1):\n probas = []\n p_global_probas = []\n# for i in np.flip(np.linspace(0, end_point, num=states)):\n for i in np.linspace(0, end_point, num=states):\n for j in tqdm(np.linspace(0, end_point, num=states)[::-1]):\n #i = 0.30; j=0.0\n #SAFE_REGION = 0.285\n if(global_probas[ind_i][ind_j] != 0):\n probas.append(global_probas[ind_i][ind_j])\n p_global_probas.append(global_probas[ind_i][ind_j])\n ind_j += 1; continue\n elif((i < SAFE_REGION and j < SAFE_REGION)):\n probas.append(1.0)\n p_global_probas.append(1.0)\n ind_j += 1; continue\n if(i > (SAFE_REGION + eps) or j > (SAFE_REGION + eps)):\n probas.append(0.0)\n p_global_probas.append(0.0)\n ind_j += 1; continue\n print(\"State: (%s, %s) (eps: %s) (wc: %s)\"%(i,j,eps, multiplier))\n #if(i > SAFE_REGION/3.0 and j > SAFE_REGION/3.0):\n # p, outs = verify_state([i, j], eps, predicate, refine=2.0, s=True)\n #else:\n p, outs = verify_state([i, j], eps, predicate, refine=3.5, s=False)\n p1, outs1 = verify_state([i, j], eps, predicate, refine=3.5, s=True)\n\n print(\"CURRENT SYNTH DATA: \" )\n print(\" \")\n print(\" D_X: \", np.shape(DYNAMICS_X), \"D_Y: \", np.shape(DYNAMICS_Y))\n print(\" C_X: \", np.shape(CONTROL_X), \"C_Y: \", np.shape(CONTROL_Y))\n np.save(\"ConSynth_X_train\", np.asarray(CONTROL_X))\n np.save(\"ConSynth_Y_train\", np.asarray(CONTROL_Y))\n print(\" \")\n print(\" \")\n print(\"Pre-Synth Probability: %s \\t Potential Improvement After Synth: %s\"%(p, p1))\n print(\" \")\n print(\" \")\n\n p_global_probas.append(p)\n #p *= multiplier # - We dont consider this in the synthesis part just to visualize the per-state improvement easier\n probas.append(p)\n non_zero.append(p)\n ind_j += 1\n ind_i += 1\n ind_j = 0\n SAFE_REGION += eps\n ind_i = 0\n probas = np.reshape(probas, (states,states))\n p_global_probas = np.reshape(p_global_probas, (states,states))\n global_probas = np.maximum(global_probas, probas)\n #print(\"Shape: \", p_global_probas.shape)\n #print(\"Shape: \", pre_global_probas.shape)\n pre_global_probas = np.maximum(p_global_probas, pre_global_probas)\n multiplier = min(non_zero)\n print(\"======================================\")\n print(\"==========EXPANDING GOAL==============\")\n print(\"======================================\")\n probas = np.asarray(probas)\n probas = probas.reshape(states,states)\n np.save(\"presynth_P2D_v0_%s_%s\"%(states, eps), probas)\n\nprobas = np.asarray(probas)\nprobas = probas.reshape(states,states)\nnp.save(\"presynth_P2D_v0_%s_%s\"%(states, eps), probas)\n\n### RETRAINING OF MODEL AND CONTROLLER\n\n\n","sub_path":"Puck2Dv0/SynthesisStage1.py","file_name":"SynthesisStage1.py","file_ext":"py","file_size_in_byte":14285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"471377452","text":"import datetime\nfrom db import db\nfrom simpyder import Spider, FAKE_UA, SimpyderConfig\n\n\nclass SiteInfoSpider(Spider):\n def gen_url(self):\n yield 'https://api.bilibili.com/x/web-interface/online'\n\n def parse(self, res):\n return res.json()['data']\n\n def save(self, item):\n item['datetime'] = datetime.datetime.utcnow() + datetime.timedelta(hours=8)\n db.site_info.insert_one(item)\n return item\n\n\nif __name__ == \"__main__\":\n s = SiteInfoSpider(\"site-info\")\n sc = SimpyderConfig()\n sc.PARSE_THREAD_NUMER = 1\n sc.DOWNLOAD_INTERVAL = 10\n sc.LOG_LEVEL = \"DEBUG\"\n sc.USER_AGENT = FAKE_UA\n sc.COOKIE = ''\n s.set_config(sc)\n s.run()\n","sub_path":"spiders/site_info.py","file_name":"site_info.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"122068085","text":"import unittest\nfrom unittest import mock\n\nimport requests_mock\n\nfrom podman import PodmanClient\n\n\nclass TestPodmanClient(unittest.TestCase):\n \"\"\"Test the PodmanClient() object.\"\"\"\n\n def setUp(self) -> None:\n super().setUp()\n self.client = PodmanClient(base_url='unix://localhost:9999')\n\n @mock.patch('requests.Session.close')\n def test_close(self, mock_close):\n self.client.close()\n\n mock_close.assert_called_once_with()\n\n @requests_mock.Mocker()\n def test_contextmanager(self, mock):\n body = {\n \"host\": {\n \"arch\": \"amd65\",\n \"os\": \"linux\",\n }\n }\n mock.get(\"http+unix://localhost:9999/v3.0.0/libpod/system/info\", json=body)\n\n with PodmanClient(base_url=\"http+unix://localhost:9999\") as client:\n actual = client.info()\n self.assertDictEqual(actual, body)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"podman/tests/unit/test_podmanclient.py","file_name":"test_podmanclient.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"80856797","text":"# Copyright 2016 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nimport xml.etree.ElementTree as ElementTree\n\nfrom mos_tests.environment.os_actions import InstanceError\nfrom mos_tests.functions import common\n\npage_1gb = 1048576\npage_2mb = 2048\n\n\nclass TestBaseNFV(object):\n\n def check_pages(self, os_conn, host, total_pages, free_pages):\n compute = os_conn.env.find_node_by_fqdn(host)\n with compute.ssh() as remote:\n total = remote.execute(\n \"grep HugePages_Total /proc/meminfo\")['stdout']\n assert str(total_pages) in total[0], \"Unexpected HugePages_Total\"\n free = remote.execute(\n \"grep HugePages_Free /proc/meminfo\")['stdout']\n assert str(free_pages) in free[0], \"Unexpected HugePages_Free\"\n\n def check_instance_page_size(self, os_conn, vm, size):\n name = getattr(os_conn.nova.servers.get(vm),\n \"OS-EXT-SRV-ATTR:instance_name\")\n host = os_conn.env.find_node_by_fqdn(\n getattr(os_conn.nova.servers.get(vm), \"OS-EXT-SRV-ATTR:host\"))\n with host.ssh() as remote:\n cmd = \"virsh dumpxml {0}\".format(name)\n res = remote.execute(cmd)\n root = ElementTree.fromstring(res.stdout_string)\n if size is None:\n assert not root.find('memoryBacking'), \"Huge pages are unexpected\"\n else:\n page_size = root.find('memoryBacking').find('hugepages').find(\n 'page').get('size')\n assert str(size) == page_size, \"Unexpected package size\"\n\n def live_migrate(self, os_conn, vm, host, block_migration=True,\n disk_over_commit=False):\n\n os_conn.nova.servers.live_migrate(\n vm, host, block_migration=block_migration,\n disk_over_commit=disk_over_commit)\n common.wait(lambda: os_conn.is_server_active(vm),\n timeout_seconds=10 * 60,\n waiting_for='instance {} changes status to ACTIVE after '\n 'live migration'.format(vm.name))\n\n def create_volume_from_vm(self, os_conn, vm):\n image = os_conn.nova.servers.create_image(vm, image_name=\"image_vm2\")\n common.wait(lambda: os_conn.nova.images.get(image).status == 'ACTIVE',\n timeout_seconds=10 * 60,\n waiting_for='image changes status to ACTIVE')\n volume = common.create_volume(os_conn.cinder, image,\n volume_type='volumes_lvm')\n return volume.id\n\n def migrate(self, os_conn, vm):\n os_conn.nova.servers.migrate(vm)\n common.wait(\n lambda: os_conn.server_status_is(vm, 'VERIFY_RESIZE'),\n timeout_seconds=3 * 60,\n waiting_for='instance {} changes status to VERIFY_RESIZE during '\n 'migration'.format(vm.name))\n os_conn.nova.servers.confirm_resize(vm)\n common.wait(lambda: os_conn.is_server_active(vm),\n timeout_seconds=5 * 60,\n waiting_for='instance {} changes status to ACTIVE after '\n 'migration'.format(vm.name))\n return os_conn.nova.servers.get(vm)\n\n def resize(self, os_conn, vm, flavor_to_resize):\n os_conn.nova.servers.resize(vm, flavor_to_resize)\n common.wait(\n lambda: os_conn.server_status_is(vm, 'VERIFY_RESIZE'),\n timeout_seconds=3 * 60,\n waiting_for='instance {} changes status to VERIFY_RESIZE during '\n 'resizing'.format(vm.name))\n os_conn.nova.servers.confirm_resize(vm)\n common.wait(lambda: os_conn.is_server_active(vm),\n timeout_seconds=5 * 60,\n waiting_for='instance {} changes status to ACTIVE after '\n 'resizing'.format(vm.name))\n return os_conn.nova.servers.get(vm)\n\n def check_cpu_for_vm(self, os_conn, vm, numa_count, host_conf):\n \"\"\"Checks vcpus allocation for vm. Vcpus should be on the same numa\n node if flavor metadata 'hw:numa_nodes':1. In case of\n 'hw:numa_nodes':2 vcpus from the different numa nodes are used.\n\n :param os_conn: os_conn\n :param vm: vm to check cpu\n :param numa_count: count of numa nodes for vm (depends on flavor)\n :param host_conf: (dictionary) host configuration, vcpu's distribution\n per numa node. It can be calculated by method\n get_cpu_distribition_per_numa_node(env) from conftest.py\n :return:\n \"\"\"\n name = getattr(os_conn.nova.servers.get(vm),\n \"OS-EXT-SRV-ATTR:instance_name\")\n host = os_conn.env.find_node_by_fqdn(\n getattr(os_conn.nova.servers.get(vm), \"OS-EXT-SRV-ATTR:host\"))\n with host.ssh() as remote:\n cmd = \"virsh dumpxml {0}\".format(name)\n dump = remote.execute(cmd)\n root = ElementTree.fromstring(dump.stdout_string)\n actual_numa = root.find('numatune').findall('memnode')\n assert len(actual_numa) == numa_count\n vcpus = [int(v.get('cpuset'))\n for v in root.find('cputune').findall('vcpupin')]\n cnt_of_used_numa = 0\n for host in host_conf.values():\n if set(host) & set(vcpus):\n cnt_of_used_numa += 1\n assert cnt_of_used_numa == numa_count, (\n \"Unexpected count of numa nodes in use: {0} instead of {1}\".\n format(cnt_of_used_numa, numa_count))\n\n def compute_change_state(self, os_conn, devops_env, host, state):\n def is_compute_state():\n hypervisor = [i for i in os_conn.nova.hypervisors.list()\n if i.hypervisor_hostname == host][0]\n return hypervisor.state == state\n\n compute = os_conn.env.find_node_by_fqdn(host)\n devops_node = devops_env.get_node_by_fuel_node(compute)\n if state == 'down':\n devops_node.suspend()\n else:\n devops_node.resume()\n common.wait(is_compute_state,\n timeout_seconds=20 * 60,\n waiting_for='compute is {}'.format(state))\n\n def evacuate(self, os_conn, devops_env, vm, on_shared_storage=True,\n password=None):\n os_conn.nova.servers.evacuate(vm, on_shared_storage=on_shared_storage)\n try:\n common.wait(\n lambda: os_conn.is_server_active(vm), timeout_seconds=5 * 60,\n waiting_for='instance {} changes status to ACTIVE after '\n 'evacuation'.format(vm.name))\n return os_conn.nova.servers.get(vm)\n except InstanceError:\n host = getattr(vm, \"OS-EXT-SRV-ATTR:host\")\n self.compute_change_state(os_conn, devops_env, host, state='up')\n raise\n","sub_path":"mos_tests/nfv/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":7347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"35695993","text":"#coding=utf-8\nimport socket\nimport json,re\n\nclass TCP_Client(object):\n\n def __new__(cls,user_id,*args, **kw): #单例模式驱动TCP\n if not hasattr(cls, '_instance'):\n orig = super(TCP_Client, cls)\n cls._instance = orig.__new__(cls, *args, **kw)\n cls._instance.sockets ={'user_%s'%0 :socket.socket(socket.AF_INET, socket.SOCK_STREAM)}\n cls._instance.sockets['user_0'].connect(('127.0.0.1', 8905))\n cls._instance.sockets['user_0'].recv(1024)\n if not cls._instance.sockets.get('user_%s'%user_id,False):\n cls._instance.sockets['user_%s'%user_id]=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n cls._instance.sockets['user_%s' % user_id].connect(('127.0.0.1', 8905))\n cls._instance.sockets['user_%s' % user_id].recv(65535)\n return cls._instance\n\n def send(self,str,user_id):\n print('user_%s' % user_id)\n self.sockets['user_%s' % user_id].send(str.encode('utf-8'))\n return self.sockets['user_%s' % user_id].recv(65535).decode('utf-8')\n\n def command_send(self,str):\n self.sockets['user_%s' % 0].send(str.encode('utf-8'))\n result=self.sockets['user_%s' % 0].recv(65535).decode('utf-8')\n return result\n\n\n def close(self,user_id):\n self.sockets['user_%d' % user_id].send(b'exit')\n self.sockets['user_%d' % user_id].close()\n","sub_path":"ssh/TCP_Client.py","file_name":"TCP_Client.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"355361952","text":"from functools import reduce\n\n\ndef get_throughput(data, destination_node, time):\n total_bytes_received = reduce(lambda x, y: x + int(y[5]) if y[-3] == destination_node and y[0] == \"r\" else x, data,\n 0)\n bits = total_bytes_received * 8\n return bits / time\n\n\ndef get_pdr(data, source_node, destination_node):\n link_level_source = source_node[0:1]\n packets_sent = reduce(\n lambda x, y: x + 1 if y[0] == \"+\" and y[2] == link_level_source and y[-3] == destination_node else x,\n data, 0)\n packets_received = reduce(\n lambda x, y: x + 1 if y[0] == \"r\" and y[-4] == source_node and y[-3] == destination_node else x, data, 0)\n\n return packets_received / packets_sent\n\n\ndef file_extractor(file_name):\n with open(file_name) as f:\n return [line.split() for line in f.readlines()]\n\n\nif __name__ == '__main__':\n file_name = \"/home/alay/PycharmProjects/MC/AssignmentOut.tr\"\n data = file_extractor(file_name)\n n4_throughput = get_throughput(data, \"4.0\", 3)\n n5_throughput = get_throughput(data, \"5.0\", 4)\n n4_pdr = get_pdr(data, \"0.0\", \"5.0\")\n n5_pdr = get_pdr(data, \"1.0\", \"4.0\")\n\n print(\"Throughput:-\\n\\tNode 4:\", n4_throughput, \"bps\\n\\tNode 5:\", n5_throughput , \"bps\")\n print(\"PDR:-\\n\\tNode 4:\", n4_pdr, \"\\n\\tNode 5:\", n5_pdr)\n","sub_path":"ns2_tr_extractor.py","file_name":"ns2_tr_extractor.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"186851925","text":"from sys import stdin\n\ndi = [0, 0, 1,-1]\ndj = [1,-1, 0, 0]\n\ndef inside(i,j):\n global mapa,n,m\n return i >= 0 and i < len(mapa) and j>= 0 and j < len(mapa[i])\n\ndef fix(j):\n global m\n if j < 0: return m -1\n elif j >= m: return 0\n return j\n\ndef floodArea(i,j):\n global mapa,vis,land,n,m\n\n vis.add((i,j))\n area = 1\n for x in range(4):\n a = i + di[x]\n b = fix(j + dj[x])\n\n if inside(a,b) and (a,b) not in vis and mapa[a][b] == land:\n area += floodArea(a,b)\n \n\n return area\n\ndef main():\n global n,m, mapa, vis,land\n\n line = stdin.readline().split()\n while line != []:\n n ,m = map(int,line)\n mapa = []\n for x in range(n): mapa.append(stdin.readline().strip())\n ii, jj = map(int,stdin.readline().split())\n stdin.readline() #blank line\n land = mapa[ii][jj]\n\n #flood land of the Mijid\n\n vis = set()\n floodArea(ii,jj)\n\n area = 0\n for i in range(n):\n for j in range(m):\n if mapa[i][j] == land and (i,j) not in vis:\n area = max(area,floodArea(i,j))\n print(area)\n \n line = stdin.readline().split()\n \nmain()\n","sub_path":"11094 Continents.py","file_name":"11094 Continents.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"324878672","text":"import requests\nfrom bs4 import BeautifulSoup\n#url do site\nurl = 'http://www.sjc.sp.gov.br/secretarias/transportes/horario-e-itinerario.aspx?acao=p&opcao=1&txt='\n# fazendo a requisição\nr = requests.get(url)\n# obtendo o conteudo da requisicao\nsoup = BeautifulSoup(r.text , 'lxml' )\n# filtrando a tabela com a classe textosm\nlista_itinerarios = soup.find_all('table', class_='textosm')\nurl = 'http://www.sjc.sp.gov.br'\n# obtendo as linhas da tabela\nfor lista_td in lista_itinerarios:\n lista = lista_td.find_all('td')\n # separando por elementos\n for lista_dados in lista:\n # concatenando a url com o link da tabela\n if lista_dados.next_element.name == 'a':\n url_it= '{0}{1}'.format(url, lista_dados.next_element.get('href'))\n print(url_it)\n else:\n print(lista_dados.next_element)\n","sub_path":"WebScraping /MiniCurso.py","file_name":"MiniCurso.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"89549703","text":"#!/usr/bin/env python3\n\n\"\"\"Direct gamepad control of telescope mount.\n\nThis program allows direct control of a telescope mount with a gamepad. The slew rates of the mount\nare controlled by the analog sticks.\n\"\"\"\n\nfrom threading import Event\nimport track\nfrom track import laser, mounts, telem\n\ndef main():\n \"\"\"See module docstring\"\"\"\n\n parser = track.ArgParser()\n mounts.add_program_arguments(parser)\n telem.add_program_arguments(parser)\n laser.add_program_arguments(parser)\n args = parser.parse_args()\n\n mount = mounts.make_mount_from_args(args, use_multiprocessing=False)\n\n game_pad = track.Gamepad()\n\n try:\n laser_pointer = laser.make_laser_from_args(args)\n game_pad.register_callback('BTN_SOUTH', laser_pointer.set)\n except OSError:\n print('Could not connect to laser pointer control device.')\n laser_pointer = None\n\n if args.telem_enable:\n telem_logger = telem.make_telem_logger_from_args(args, sources={'gamepad': game_pad})\n telem_logger.start()\n\n try:\n if mount is None:\n # do nothing in this thread until CTRL-C\n Event().wait()\n else:\n while True:\n x, y = game_pad.get_value()\n mount.slew(0, mount.max_slew_rate * x)\n mount.slew(1, mount.max_slew_rate * y)\n\n except KeyboardInterrupt:\n print('Got CTRL-C, shutting down...')\n finally:\n if mount is not None:\n # don't rely on destructors to safe mount!\n print('Safing mount...', end='', flush=True)\n if mount.safe():\n print('Mount safed successfully!')\n else:\n print('Warning: Mount may be in an unsafe state!')\n\n if args.telem_enable:\n telem_logger.stop()\n\n game_pad.stop()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"track/gamepad_control.py","file_name":"gamepad_control.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"248806032","text":"import sqlite3\r\n\r\ndb_name = 'baseball.db'\r\n\r\nprint(\"Welcome to my database program!\")\r\nprint(\"Main menu: \")\r\n\r\ndef connect_to_db():\r\n # connect to the database\r\n db_conn = sqlite3.connect(db_name) # connect is a function\r\n db_cursor = db_conn.cursor() # cursor is a method\r\n return db_conn, db_cursor\r\n\r\n\r\ndef create_table(db_cursor):\r\n sql = \"CREATE TABLE baseball (team TEXT, location TEXT, player TEXT, salary REAL, height REAL, weight REAL)\"\r\n db_cursor.execute(sql)\r\n print(\"Table created.\")\r\n\r\n\r\ndef drop_table(db_cursor):\r\n sql = \"DROP TABLE IF EXISTS baseball\"\r\n db_cursor.execute(sql)\r\n print(\"Table dropped.\")\r\n\r\n\r\ndef insert_row(db_cursor):\r\n sql = \"INSERT INTO baseball (team, location, player, salary, height, weight) VALUES (?, ?, ?, ?, ?, ?)\"\r\n\r\n t = input(\"Enter the team: \")\r\n l = input(\"Enter the location: \")\r\n p = input(\"Enter the player: \")\r\n b = float(input(\"Enter the salary: \"))\r\n h = float(input(\"Enter the height: \"))\r\n w = float(input(\"Enter the weight: \"))\r\n\r\n # create the tuple object that holds the data\r\n tuple_of_values = (t, l, p, b, h, w)\r\n\r\n db_cursor.execute(sql, tuple_of_values)\r\n print(\"Row inserted\")\r\n\r\n\r\ndef select_all(db_cursor):\r\n sql = \"SELECT * from baseball\"\r\n result_set = db_cursor.execute(sql)\r\n row = None\r\n for row in result_set:\r\n print(row)\r\n if row is None:\r\n print(\"No rows found\")\r\n\r\n\r\ndef ask_for_float(prompt):\r\n while True:\r\n try:\r\n user_input = float(input(prompt))\r\n break\r\n except ValueError:\r\n print(\"Enter a valid float. Try again. \")\r\n return user_input\r\n\r\n\r\ndef update_row(db_cursor):\r\n team = input(\"Enter the team for the baseball you wish to update: \")\r\n salary = float(input(\"Enter the new salary: \"))\r\n height = float(input(\"Enter the new height: \"))\r\n weight = float(input(\"Enter the new weight: \"))\r\n sql = \"Update baseball set salary = ?, height = ?, weight = ? where team = ?\"\r\n\r\n tuple_of_values = (salary, height, weight, team)\r\n db_cursor.execute(sql, tuple_of_values)\r\n print(\"Row updated.\")\r\n\r\n\r\ndef delete_row(db_cursor):\r\n team = input(\"Enter the team for the baseball you wish to delete: \")\r\n sql = \" delete from baseball where team = ?\"\r\n tuple_of_value = (team,)\r\n db_cursor.execute(sql, tuple_of_value)\r\n print(\"Row deleted. \")\r\n\r\n\r\ndef select_row(db_cursor):\r\n team = input(\"Enter the team you wish to select: \")\r\n sql = \"select * from baseball where team = ?\"\r\n tuple_of_value = (team,)\r\n result_set = db_cursor.execute(sql, tuple_of_value)\r\n for row in result_set:\r\n print(row)\r\n\r\n\r\ndef display_menu(db_conn, db_cursor):\r\n while True:\r\n print(\"\\nEnter S to get started & create/refresh the table\")\r\n print(\"Enter C to create a new roll\")\r\n print(\"Enter R to retrieve data\")\r\n print(\"Enter U to update data\")\r\n print(\"Enter D to delete data\")\r\n print(\"Enter Q to quit the program\")\r\n choice = input(\"Enter your choice: \").upper()\r\n if choice == 'S':\r\n drop_table(db_cursor)\r\n create_table(db_cursor)\r\n elif choice == 'C':\r\n insert_row(db_cursor)\r\n elif choice == 'R':\r\n select_row(db_cursor)\r\n elif choice == 'U':\r\n update_row(db_cursor)\r\n elif choice == 'D':\r\n delete_row(db_cursor)\r\n elif choice == 'Q':\r\n break\r\n else:\r\n print(\"invalid option. Please try again. \")\r\n continue\r\n\r\n db_conn.commit()\r\n select_all(db_cursor)\r\n\r\n\r\ndef main():\r\n db_conn, db_cursor = connect_to_db()\r\n display_menu(db_conn, db_cursor)\r\n db_conn.close() # do this once\r\n\r\n\r\n# call main\r\nmain()\r\n","sub_path":"CRUD.py","file_name":"CRUD.py","file_ext":"py","file_size_in_byte":3797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"495568795","text":"#coding: utf-8\n\nimport threading, os, time\nfrom proxydao import ProxyDAO\nfrom foursquareclient import FoursquareClient\n\nclass WaterarmyHarvestor(threading.Thread):\n\tdef __init__(self, datadir, proxy, uidQueue):\n\t\tthreading.Thread.__init__(self)\n\t\tself.daemon=True\n\t\tself.proxy=proxy\n\t\tself.datadir=datadir\n\t\tself.iq=uidQueue\n\t\tself.n=0\n\t\tif not os.path.exists(datadir): os.makedirs(datadir)\n\n\tdef run(self):\n\t\tpdao=ProxyDAO()\n\t\tfw=open(os.path.join(self.datadir, 'wrong%d.txt' % int(time.time())), 'w')\n\t\twhile True:\n\t\t\tif self.n%1000==0: \n\t\t\t\tproxy=pdao.getHttps(self.proxy)\n\t\t\t\tclient =FoursquareClient(self.datadir, proxy)\n\t\t\t\tclient.tryToLogin()\n\t\t\tuid=self.iq.get()\n\t\t\tif client.getHome(uid): \n\t\t\t\tclient.getFriends(uid)\n\t\t\t\tsuc=client.isOK()\n\t\t\t\tclient.getTips(uid)\n\t\t\t\tsuc &= client.isOK()\n\t\t\t\tif not suc: \n\t\t\t\t\tfw.write('%d\\n' % uid)\n\t\t\t\t\tfw.flush()\n\t\t\tself.iq.task_done()\n\t\t\tself.n+=1\n\t\t\ttime.sleep(5)\n\nclass Monitor(threading.Thread):\n\tdef __init__(self, threads):\n\t\tthreading.Thread.__init__(self)\n\t\tself.daemon=True\n\t\tself.pool=threads\n\n\tdef run(self):\n\t\tlast=[0]*len(self.pool)\n\t\twhile True:\n\t\t\tzero=0\n\t\t\tfor i, th in enumerate(self.pool): \n\t\t\t\tif th.n==last[i]: zero+=1\n\t\t\t\tlast[i]=th.n\n\t\t\tprint(time.ctime(), 'Zero: %d/%d' % (zero, len(self.pool)))\n\t\t\ttime.sleep(300)\n\n","sub_path":"foursquare_o/workers.py","file_name":"workers.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"402689926","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n\n#CONSTANTS\nINPUT_IMAGE = '/u/mlamkin/Desktop/unicorn.png' #file in current working directory or absolute path\nOUTPUT_COLOR_IMAGE = '/u/mlamkin/Desktop/unicorn1.png'\nOUTPUT_GRAY_IMAGE = '/u/mlamkin/Desktop/unicornGray.png'\nOUTPUT_GRAY_IMAGE1 = '/u/mlamkin/Desktop/unicornGray1.png'\n\n\n#read the image in\ndef read_image(image_file = INPUT_IMAGE):\n img = mpimg.imread(image_file)\n return img\n\n\n#1st way to create and save a grayscale version of the image (should pass in an image stored in a numpy array)\ndef rgb_to_gray(img):\n gray_img = np.empty([img.shape[0], img.shape[1]])\n\n\n for row in range(img.shape[0]):\n for column in range(img.shape[1]):\n gray_img[row][column] = img[row][column][0] * 0.299 + img[row][column][1] * 0.587 + img[row][column][2] * 0.114\n\n\n #save grayscale image\n mpimg.imsave(OUTPUT_GRAY_IMAGE, gray_img, cmap = plt.get_cmap('gray'))\n\n return gray_img\n\n\n#2nd way to create and save a grayscale version of the image (should pass in an image stored in a numpy array)\ndef rgb_to_gray1(img):\n gray_img = np.empty([img.shape[0], img.shape[1], 3])\n \n for rgb in range(3):\n for row in range(img.shape[0]):\n for column in range(img.shape[1]):\n gray_img[row][column][rgb] = img[row][column][0] * 0.299 + img[row][column][1] * 0.587 + img[row][column][2] * 0.114\n\n\n #save grayscale image\n mpimg.imsave(OUTPUT_GRAY_IMAGE1, gray_img)\n\n return gray_img\n\n\n#remove all color except for blue and save image\ndef keep_blue(img):\n\n for color in range(2):\n for row in range(img.shape[0]):\n for column in range(img.shape[1]):\n img[row][column][color] = 0\n \n \n #save new image\n mpimg.imsave(OUTPUT_COLOR_IMAGE, img)\n \n return img\n\n \n##########################################################\n \nimg = read_image()\n\n#create the gray image using 1st method\ngray_img = rgb_to_gray(img)\n\n#create the gray image using 2nd method\ngray_img = rgb_to_gray1(img)\n\n#create the blue image\nimg = keep_blue(img) \n\n\n \n","sub_path":"pythonPractice/other_python/processImageMultipleMethods.py","file_name":"processImageMultipleMethods.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"456932906","text":"import urllib\nimport urllib.request\nimport re\nimport os\nimport time\n\nstart = time.process_time()\n\ndate = time.strftime('%Y%m%d',time.localtime(time.time()))\n\ndef getpage(path):\n data = urllib.request.urlopen(path).read().decode(\"gbk\")\n return data\n\ndef getcode(data):\n #regex_str = \"
  • (.*?)\\(\"\n regex_str = \"
  • \"\n pat = re.compile(regex_str)\n codelist = pat.findall(data)\n return codelist\n\ndef downloadstock(code, name, date):\n path = \"D:\\\\Currentprice\\\\\" + date\n if not os.path.exists(path):\n os.makedirs(path)\n url = \"http://hq.sinajs.cn/list=\"+str(code)+\"\"\n path = \"D:\\\\Currentprice\\\\\"+date+\"\\\\\"+name+\".csv\"\n urllib.request.urlretrieve(url, path)\n\npath = \"http://quote.eastmoney.com/stocklist.html\"\ndata = getpage(path)\ncodelist = getcode(data)\n\ndef main():\n for code in codelist:\n try:\n downloadstock(code,code,date)\n except:\n print(\"error\")\n break\n #print(code[0],code[1])\n\nif __name__ == '__main__':\n main()\n\nelapsed = (time.process_time() - start)\nprint(\"Time used:\",elapsed)","sub_path":"股票实时数据.py","file_name":"股票实时数据.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"215781383","text":"# Uses adjacency matrix representation of graph to calculate Minimum\n# Spanning Tree\n\nimport sys\n\n\nclass Graph():\n\n def __init__(self, vertices):\n self.V = vertices\n self.graph = [[0 for column in range(vertices)]\n for row in range(vertices)]\n\n # Function to print generated MST\n def print_MST(self, parent):\n print(\"Edge \\t Weight\")\n for i in range(1, self.V):\n print(parent[i], \"-\", i, \"\\t\", self.graph[i][parent[i]])\n\n # Function to find vertex with min. distance from set of vertices\n #not included in MST\n def min_value(self, key, MSTSet):\n minval = sys.maxsize\n\n for v in range(self.V):\n if (key[v] < minval) and (MSTSet[v] == False):\n minval = key[v]\n min_index = v\n return min_index\n\n # Function to construct Prim's MST\n def MST(self):\n key = [sys.maxsize] * self.V\n parent = [None] * self.V\n key[0] = 0\n MSTSet = [False] * self.V\n parent[0] = -1\n\n for j in range(self.V):\n u = self.min_value(key, MSTSet)\n MSTSet[u] = True\n\n for v in range(self.V):\n if (self.graph[u][v] > 0) and (MSTSet[v] ==\n False) and (key[v] > self.graph[u][v]):\n key[v] = self.graph[u][v]\n parent[v] = u\n\n self.print_MST(parent)\n\n\ng = Graph(4)\ng.graph = [[0, 2, 0, 6],\n [2, 0, 3, 8],\n [0, 3, 0, 0],\n [6, 8, 0, 0]]\n\ng.MST()\n","sub_path":"data_structures/graphs/PrimsMST.py","file_name":"PrimsMST.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"298404393","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport datetime as dt\nimport urllib.request, json\nimport os\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nfrom reset_graph import reset_graph\n##hiding errors\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n##saving directories\nfrom datetime import datetime\n\nnow = datetime.utcnow().strftime(\"%Y_%m_%d_%H\")\nfile_name = os.path.basename(__file__)\nroot_logdir = \"tf_tensorboard/{}\".format(file_name)\nlogdir = \"{}/{}_przebieg-{}/\".format(root_logdir, file_name ,now)\n\n## accurancy function definition\ndef accurancy(y_pred, labels):\n \"\"\"\n y_pred size = (N_samples x n_classes)\n labales -> true values, size = (N_samples x n_classes)\n \"\"\"\n return np.sum(np.argmax(y_pred,axis=1)==np.argmax(labels,axis=1))*100.0/labels.shape[0]\n\n## model builder\n# input data is an 28x28 size image\n\nbatch_size = 100\nlayer_ids = [\"hidden\"+str(i+1) for i in range(5)]\nlayer_ids.append(\"out\")\nlayer_sizes = [784, 500, 400, 300, 200, 100, 10]\n\n#input definition\nwith tf.name_scope(\"training_data\"):\n X_train = tf.placeholder(dtype=tf.float32, shape=[batch_size, layer_sizes[0]], name=\"training_input\")\n y_train = tf.placeholder(dtype=tf.float32, shape=[batch_size, layer_sizes[-1]], name=\"training_labels\")\n\n#weights and bias definition\nwith tf.name_scope(\"weights_and_biases\"):\n for idx, layer_name in enumerate(layer_ids):\n with tf.variable_scope(layer_name):\n weight = tf.get_variable(name=\"weight\", shape=[layer_sizes[idx], layer_sizes[idx+1]], \n initializer =tf.truncated_normal_initializer(stddev=0.05))\n bias = tf.get_variable(name=\"bias\", shape=[layer_sizes[idx+1]], \n initializer=tf.random_uniform_initializer(-0.1,0.1))\n \n#model calculation definition\nwith tf.name_scope(\"model\"):\n data = X_train\n for layer_name in layer_ids:\n with tf.variable_scope(layer_name, reuse=True):\n w, b = tf.get_variable(\"weight\"), tf.get_variable(\"bias\")\n if layer_name != \"out\":\n data = tf.nn.elu(tf.matmul(data, w)+b, name=layer_name+\"_output\")\n else:\n data = tf.nn.xw_plus_b(data, w, b, name=layer_name+\"_output\")\n predictions = tf.nn.softmax(data, name=\"predictions\")\n\n#trainig section definition\nwith tf.name_scope(\"trainig\"):\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_train, logits=data), name=\"cross_entropy_loss\")\n learning_rate = tf.placeholder(dtype=tf.float32, shape=None, name=\"learning_rate\")\n optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=0.9)\n gradients = optimizer.compute_gradients(loss)\n training_op = optimizer.minimize(loss)\n \n#summaries definition\nwith tf.name_scope(\"performance\"):\n ##define sumries objects as placeholders -> tensorboard needs it\n #loss summary\n loss_summary_ph = tf.placeholder(dtype=tf.float32, shape=None, name=\"loss_summary\")\n loss_summary = tf.summary.scalar(\"Loss\", loss_summary_ph) \n #accurancy summary\n accuracy_summary_ph = tf.placeholder(tf.float32,shape=None, name='accuracy_summary')\n accuracy_summary = tf.summary.scalar('accuracy', accuracy_summary_ph)\n \n # Gradient norm summary\n for g,v in gradients:\n if 'hidden5' in v.name and 'weight' in v.name:\n with tf.name_scope('gradients'):\n tf_last_grad_norm = tf.sqrt(tf.reduce_mean(g**2))\n tf_gradnorm_summary = tf.summary.scalar('grad_norm', tf_last_grad_norm)\n break\n \n #merging summaries\n merged_summaries = tf.summary.merge([loss_summary, accuracy_summary])\n\n##Execution of the model\n\nwith tf.name_scope(\"initialization\"):\n init = tf.global_variables_initializer()\n \n#model params\n\nimage_size = 28\nn_channels = 1\nn_classes = 10\nn_train = 55000\nn_valid = 5000\nn_test = 10000\nn_epochs = 100\n\n#configuration of gpu usage -> 0.9 means that gpu wont be overused\nconfig = tf.ConfigProto(allow_soft_placement=True)\nconfig.gpu_options.allow_growth = True\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.9 \n\n#session start\nwith tf.compat.v1.Session(config=config) as sess:\n \n summary_writer = tf.summary.FileWriter(logdir, sess.graph)\n #initialize all variables\n sess.run(init)\n \n accuracy_per_epoch = []\n mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)\n \n for epoch in range(n_epochs):\n loss_per_epoch = []\n print(\"===========EPOCH: {} ===========\".format(epoch))\n \n for i in range(n_train//batch_size):\n batch = mnist_data.train.next_batch(batch_size)\n\n if i == 0:\n # Only for the first epoch, get the summary data\n # Otherwise, it can clutter the visualization\n l,_, gn_summ = sess.run([loss, training_op, tf_gradnorm_summary],\n feed_dict={X_train: batch[0].reshape(batch_size,image_size*image_size),\n y_train: batch[1],\n learning_rate: 0.001})\n summary_writer.add_summary(gn_summ, epoch)\n \n else:\n l,_ = sess.run([loss, training_op],\n feed_dict={X_train: batch[0].reshape(batch_size,image_size*image_size),\n y_train: batch[1],\n learning_rate: 0.001})\n loss_per_epoch.append(l)\n \n print('Average loss: {} in epoch: {}'.format(round(np.mean(loss_per_epoch),5), epoch))\n avg_loss = np.mean(loss_per_epoch)\n \n ## calculation validation accurancy\n valid_accuracy_per_epoch = []\n for i in range(n_train//batch_size):\n valid_images,valid_labels = mnist_data.validation.next_batch(batch_size)\n valid_batch_predictions = sess.run(\n predictions, feed_dict={X_train: valid_images.reshape(batch_size,image_size*image_size)})\n valid_accuracy_per_epoch.append(accurancy(valid_batch_predictions,valid_labels))\n\n mean_v_acc = np.mean(valid_accuracy_per_epoch)\n print('Average Valid accurancy: {} in epoch: {}'.format(round(np.mean(valid_accuracy_per_epoch),5), epoch))\n \n #perfomance savig to tensorbaord\n accuracy_per_epoch = []\n for i in range(n_test//batch_size):\n test_images, test_labels = mnist_data.test.next_batch(batch_size)\n test_batch_predictions = sess.run(\n predictions,feed_dict={X_train: test_images.reshape(batch_size,image_size*image_size)}\n )\n accuracy_per_epoch.append(accurancy(test_batch_predictions,test_labels))\n\n print('Average test accurancy: {} in epoch: {}'.format(round(np.mean(accuracy_per_epoch),5), epoch))\n avg_test_accuracy = np.mean(accuracy_per_epoch)\n\n # Execute the summaries\n summary = sess.run(merged_summaries, feed_dict={loss_summary_ph:avg_loss, accuracy_summary_ph:avg_test_accuracy})\n\n # Write the obtained summaries to the file, so it can be displayed in the TensorBoard\n summary_writer.add_summary(summary, epoch)\n print(\"<=========== END ===========>\")\n\n \n \n\n","sub_path":"Tensorflow Sandbox/Simple Examples/tensorbaord_tutorial.py","file_name":"tensorbaord_tutorial.py","file_ext":"py","file_size_in_byte":7460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"587542018","text":"# In this assignment you must do a Twitter search on any term\n# of your choice.\n# Deliverables:\n# 1) Print each tweet\n# 2) Print the average subjectivity of the results\n# 3) Print the average polarity of the results\n# You will demo this live for grading.\nimport tweepy\nfrom textblob import TextBlob\n\n# Unique code from Twitter\naccess_token = \"44199763-QbzzHMshq9X4iOew1ZIy1ByPWBTmulba6jG5gpWQA\"\naccess_token_secret = \"CHrzNqxCAtuUu7Vk2p9x4Yo9gAQrpEgeMDeFFeWDJdtmL\"\nconsumer_key = \"r4jg39kOcc8cmpjEQANJVL7W7\"\nconsumer_secret = \"UlN5CZoS7LKQojpfxKkA2aRXUjpU2t23gD0I74kFgOEGFgRbS6\"\n\n# Boilerplate code here\nauth = tweepy.OAuthHandler(consumer_key,consumer_secret)\nauth.set_access_token(access_token,access_token_secret)\napi = tweepy.API(auth)\n#Now we can Create Tweets, Delete Tweets, and Find Twitter Users\n\npublic_tweets = api.search('UMSI')\nsubjtot = 0\npolartot = 0\ncount = 0\n\nprint(\"Printing Tweets\\n\")\nfor tweet in public_tweets:\n\tprint(tweet.text)\n\tanalysis = TextBlob(tweet.text)\n\tsubjtot += analysis.sentiment.subjectivity\n\tpolartot += analysis.sentiment.polarity\n\tcount += 1\n\n\t\nprint(\"Average subjectivity is\", (subjtot/count))\nprint(\"Average polarity is\", (polartot/count))\n","sub_path":"HW3-StudentCopy/twitterhw3b.py","file_name":"twitterhw3b.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"321377486","text":"from django.conf.urls import include, url\nfrom . import views\nfrom .views import HomeListView, HomeDetailView, ReferenzenListView\n\n\napp_name = 'me'\nurlpatterns = [\n url(r'^$', views.home, name='home'),\n url(r'^referenzen/', ReferenzenListView.as_view(), name='referenzen'),\n url(r'^contact/', views.contact, name='contact'),\n url(r'^mobilecontact/', views.mobile_contact, name='mobile_contact'),\n url(r'^danke/', views.danke, name='danke'),\n url(r'^list/(?P\\D+)$', HomeDetailView.as_view(), name='detail'),\n url(r'^list/$', HomeListView.as_view(), name='list'),\n url(r'^mobiledanke/', views.mobile_danke, name='mobile_danke'),\n]","sub_path":"me/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"48674775","text":"from bs4 import BeautifulSoup\nimport urllib.request, urllib.parse, urllib.error\n\nurl = input(\"Enter: \")\nhtml = urllib.request.urlopen(url).read()\nsoup = BeautifulSoup\nsoup = BeautifulSoup(html, 'html.parser')\ntags = soup('a')\n# for tag in tags:\n# print(tag.get('href', None))\n\n#Find and return all the h2 titles with class module title.\nprint (soup.title.string)\ntitles = soup.find_all(\"a\", class_= \"module__title__link\")\nfor title in titles:\n print (title.string)\n","sub_path":"class_exercises/bs_prac.py","file_name":"bs_prac.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"156307949","text":"# coding=utf-8\r\nclass Solution(object):\r\n def topKFrequent(self, nums, k):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type k: int\r\n :rtype: List[int]\r\n \"\"\"\r\n d={}\r\n for x in nums:\r\n if x not in d:\r\n d[x]=1\r\n else:\r\n d[x]+=1\r\n mid=sorted(d.iteritems(), key =lambda d:d[1], reverse = True)\r\n res=[]\r\n for i in xrange(k):\r\n res.append(mid[i][0])\r\n return res\r\n","sub_path":"S-Z/Top K Frequent Elements.py","file_name":"Top K Frequent Elements.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"105682862","text":"\"\"\"\n飞机大战,加载背景\n\"\"\"\nimport pygame\nimport time\nfrom pygame.locals import *\n\n\n# 飞机类\nclass HeroPlane(object):\n\n def __init__(self, screen):\n # 初始化飞机参数\n self.x = 190\n self.y = 728\n\n # 初始化窗口\n self.screen = screen\n\n # 飞机图片路径\n image_path = 'feiji/hero1.png'\n self.image = pygame.image.load(image_path)\n\n # 飞机里子弹列表\n self.bulletlist = []\n\n # 显示飞机\n def display(self):\n\n dellet_bullet = []\n\n self.screen.blit(self.image, (self.x, self.y))\n\n for bullet in self.bulletlist:\n bullet.display()\n bullet.move()\n\n if bullet.remove():\n dellet_bullet.append(bullet)\n for bullet in dellet_bullet:\n self.bulletlist.remove(bullet)\n\n # 飞机移动\n def moveleft(self):\n self.x -= 10\n\n def moveright(self):\n self.x += 10\n\n # 飞机射击\n def shoot(self):\n new_bullet = Bullet(self.x, self.y, self.screen)\n self.bulletlist.append(new_bullet)\n\n\n# 飞机类\nclass EnemyPlane(object):\n\n def __init__(self, screen):\n # 初始化飞机参数\n self.x = 0\n self.y = 10\n\n # 初始化窗口\n self.screen = screen\n\n # 飞机图片路径\n image_path = 'feiji/enemy0.png'\n self.image = pygame.image.load(image_path)\n\n # 飞机里子弹列表\n self.bulletlist = []\n\n self.oritation = 'right'\n\n # 显示飞机\n def display(self):\n\n dellet_bullet = []\n\n self.screen.blit(self.image, (self.x, self.y))\n\n # for bullet in self.bulletlist:\n # bullet.display()\n # bullet.move()\n #\n # if bullet.remove():\n # dellet_bullet.append(bullet)\n # for bullet in dellet_bullet:\n # self.bulletlist.remove(bullet)\n\n\n def automove(self):\n\n if self.x <= 0:\n self.oritation = 'right'\n elif self.x >= 480 - 55:\n self.oritation = 'left'\n\n if self.oritation == 'right':\n self.moveright()\n elif self.oritation == 'left':\n self.moveleft()\n\n # 飞机移动\n def moveleft(self):\n self.x -= 10\n\n def moveright(self):\n self.x += 10\n\n # 飞机射击\n def shoot(self):\n new_bullet = Bullet(self.x, self.y, self.screen)\n self.bulletlist.append(new_bullet)\n\n\n\n# 子弹类\nclass Bullet(object):\n\n # 子弹初始化\n def __init__(self, plan_x, plan_y, screen):\n self.x = plan_x + 39\n self.y = plan_y - 22\n\n image_path = 'feiji/bullet.png'\n self.image = pygame.image.load(image_path)\n self.screen = screen\n\n # 子弹移动\n def move(self):\n self.y -= 10\n\n # 子弹显示\n def display(self):\n self.screen.blit(self.image, (self.x, self.y))\n\n # 移除子弹\n def remove(self):\n return self.y < 0\n\n def __del__(self):\n print('子弹被移除')\n\n\n# 键盘输入\ndef key_control(hero):\n\n # 获取事件,比如按键等\n for event in pygame.event.get():\n\n # 判断是否是点击了退出按钮\n if event.type == QUIT:\n print(\"exit\")\n exit()\n # 判断是否是按下了键\n key_buf = pygame.key.get_pressed()\n # if key_buf[pygame.KEYDOWN] == 1:\n # 检测按键是否是a或者left\n if key_buf[pygame.K_a] == 1 or key_buf[pygame.K_LEFT] == 1:\n print('left')\n # move_x = -1\n hero.moveleft()\n\n # 检测按键是否是d或者right\n if key_buf[pygame.K_d] == 1 or key_buf[pygame.K_RIGHT] == 1:\n print('right')\n # move_x = 1\n hero.moveright()\n\n # 检测按键是否是空格键\n if key_buf[pygame.K_SPACE] == 1:\n print('space')\n hero.shoot()\n # elif key_buf[pygame.K_SPACE] == 0:\n # pass\n\n\ndef main():\n # 创建窗口\n screen = pygame.display.set_mode((480, 852), 0, 32)\n\n # 加载图片\n bg = pygame.image.load('feiji/background.png')\n\n # 加载玩家飞机\n hero = HeroPlane(screen)\n\n # 加载敌人飞机\n enemy = EnemyPlane(screen)\n while True:\n # 绑定图片到窗口\n screen.blit(bg, (0, 0))\n\n # 绑定玩家飞机到窗口\n hero.display()\n\n enemy.display()\n enemy.automove()\n\n # 键盘输入\n key_control(hero)\n\n # 刷新图片\n pygame.display.update()\n\n time.sleep(1/24)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"day12/飞机大战移动类,内存优化.py","file_name":"飞机大战移���类,内存优化.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"423954576","text":"# --- Day 5: Doesn't He Have Intern-Elves For This? ---\n#\n# Santa needs help figuring out which strings in his text file are naughty or nice.\n#\n# A nice string is one with all of the following properties:\n#\n# It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou.\n# It contains at least one letter that appears twice in a row, like xx, abcdde (dd), or aabbccdd (aa, bb, cc, or dd).\n# It does not contain the strings ab, cd, pq, or xy, even if they are part of one of the other requirements.\n#\n# For example:\n#\n# ugknbfddgicrmopn is nice because it has at least three vowels (u...i...o...), a double letter (...dd...),\n# and none of the disallowed substrings.\n# aaa is nice because it has at least three vowels and a double letter,\n# even though the letters used by different rules overlap.\n# jchzalrnumimnmhp is naughty because it has no double letter.\n# haegwjzuvuyypxyu is naughty because it contains the string xy.\n# dvszwmarrgswjxmb is naughty because it contains only one vowel.\n#\n# How many strings are nice?\nimport Files\n\n\ndef part1():\n lines = Files.Files.get_list_of_file_contents(\"inputday5.txt\")\n list_of_strings = ['ab', 'cd', 'pq', 'xy']\n counter = 0\n\n for line in lines:\n line = line.rstrip()\n if string_is_nice(line, list_of_strings):\n counter += 1\n\n print('part1 has ', counter, ' nice lines')\n\n\ndef string_is_nice(line, list_of_strings) -> bool:\n if does_not_contain_the_strings(line, list_of_strings):\n if contains_letter_twice_in_a_row(line) and contains_at_least_three_vowels(line):\n return True\n\n return False\n\n\ndef contains_letter_twice_in_a_row(line) -> bool:\n prev_letter = ''\n curr_letter = ''\n for c in line:\n curr_letter = c\n if curr_letter == prev_letter:\n return True\n\n prev_letter = c\n\n return False\n\n\ndef contains_at_least_three_vowels(line) -> bool:\n vowels = ['a', 'e', 'i', 'o', 'u']\n counter = 0\n for c in line:\n if c in vowels:\n counter += 1\n if counter >= 3:\n return True\n\n return False\n\n\ndef does_not_contain_the_strings(line, list_of_strings) -> bool:\n for string in list_of_strings:\n if string in line:\n return False\n\n return True\n\n\n# --- Part Two ---\n#\n# Realizing the error of his ways, Santa has switched to a better model of determining whether a string is naughty or nice. None of the old rules apply, as they are all clearly ridiculous.\n#\n# Now, a nice string is one with all of the following properties:\n#\n# It contains a pair of any two letters that appears at least twice in the string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but not like aaa (aa, but it overlaps).\n# It contains at least one letter which repeats with exactly one letter between them, like xyx, abcdefeghi (efe), or even aaa.\n#\n# For example:\n#\n# qjhvhtzxzqqjkmpb is nice because is has a pair that appears twice (qj) and a letter that repeats with exactly one letter between them (zxz).\n# xxyxx is nice because it has a pair that appears twice and a letter that repeats with one between, even though the letters used by each rule overlap.\n# uurcxstgmygtbstg is naughty because it has a pair (tg) but no repeat with a single letter between them.\n# ieodomkazucvgmuy is naughty because it has a repeating letter with one between (odo), but no pair that appears twice.\n#\n# How many strings are nice under these new rules?\n\ndef part2():\n lines = Files.Files.get_list_of_file_contents(\"inputday5.txt\")\n counter = 0\n\n print(contains_two_pair_of_letters_without_overlapping('xyxy'))\n print(contains_two_pair_of_letters_without_overlapping('aabcdefgaa'))\n # print(contains_one_letter_which_repeats_with_one_letter_between_them('aaa'))\n\n for line in lines:\n line = line.rstrip()\n\n if contains_two_pair_of_letters_without_overlapping(\n line) and contains_one_letter_which_repeats_with_one_letter_between_them(line):\n counter += 1\n\n print('part2 has ', counter, ' nice lines')\n\n\ndef contains_two_pair_of_letters_without_overlapping(line) -> bool:\n line_len = len(line)\n\n uneven = (line_len % 2) != 0\n if uneven:\n line_len -= 1\n\n for i in range(0, line_len, 1):\n pair_of_letters = (line[i:i + 2])\n\n if line.count(pair_of_letters) >= 2:\n return True\n\n return False\n\n\ndef contains_one_letter_which_repeats_with_one_letter_between_them(line) -> bool:\n for i in range(0, len(line), 1):\n\n three_letters = line[i:i + 3]\n first_letter = line[i:i + 1]\n if three_letters[:1] == first_letter and three_letters[2:3] == first_letter:\n return True\n\n return False\n\n\npart1()\npart2()\n","sub_path":"Day5.py","file_name":"Day5.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"470789285","text":"# 读取cifar数据集\nimport pickle\ndef unpickle(file):\n fo = open(file, 'rb')\n dict = pickle.load(fo, encoding='latin1')\n fo.close()\n return dict\ndef read_data_cifar(Directory):\n# Input:\n# Directory -- cifar存在的目录\n# Output:\n# names -- numbers of different labels\n# X -- (N, 3, 32, 32) -- img data\n# y -- (, N) -- img label\n names = unpickle(\"{}/batches.meta\".format(Directory))[\"label_names\"]\n print(names)\n X = None\n y = None\n for i in range(1, 6):\n batch = unpickle(\"{}/data_batch_{}\".format(Directory, i))\n if X is None:\n X = batch[\"data\"]\n if y is None:\n y = batch[\"labels\"]\n X = np.vstack((X, batch[\"data\"]))\n y = np.hstack((y, batch[\"labels\"]))\n X = X.reshape(X.shape[0], 3, 32, 32)\n return names, X, y\n \n \n# 对X数据标准化\ndef clean(X_org):\n# Input:\n# X_org -- primitive data -- (N, 3, 32, 32)\n# Output:\n# X_std -- Standardized data -- (N, 24, 24)\n X_gray = np.mean(X_org, axis=1)\n X_gray = X_gray[:, 4:28, 4:28]\n X_gray = X_gray.reshape(X_gray.shape[0], -1)\n _mean = np.mean(X_gray, axis=1)\n _mean = _mean.reshape(len(_mean), -1)\n _std = np.std(X_gray, axis=1)\n _std = _mean.reshape(len(_std), -1)\n adj_stds = np.maximum(_std, 1.0/np.sqrt(X_gray.shape[1]))\n X_std = (X_gray - _mean) / adj_stds\n return X_std\n \n # 绘图函数\nimport matplotlib.pyplot as plt\nimport random\nrandom.seed(1)\n\n\n# 展示待处理的图片\ndef show_some_examples(names, data, labels):\n '''\n names - array of all categories\n data - pixes data of all imgs\n labels - idx of correspoinding img in names\n '''\n row, col = 4, 4\n random_idx = random.sample(range(len(data)), row*col)\n plt.figure()\n for i in range(row*col):\n plt.subplot(row, col, i+1)\n img = data[random_idx[i]]\n img = np.reshape(img[:], (24, 24))\n plt.imshow(img, cmap=\"Greys_r\")\n plt.title(names[labels[random_idx[i]]])\n plt.axis(\"off\")\n plt.tight_layout()\n \n \n# 读取数据和标准化数据\nnames, X , y= read_data_cifar(\"E://dataset//cifar-10-batches-py\")\nX = clean(X)\nshow_some_examples(names, X, y)\n\n\n# 绘制权重的参数灰度图和一次卷积后的灰度图\nimport tensorflow as tf\nimport numpy as np\ndef show_Weights(W):\n plt.figure()\n row, col =4, 8\n for i in range(W.shape[3]):\n img = W[:, :, 0, i]\n plt.subplot(row, col, i+1)\n plt.imshow(img, cmap=\"Greys_r\")\n plt.axis(\"off\")\n plt.show()\n \ndef show_Conv(conv):\n plt.figure()\n row, col =4, 8\n for i in range(conv.shape[3]):\n img = conv[0,:,:,i]\n plt.subplot(row, col, i+1)\n plt.imshow(img, cmap=\"Greys_r\")\n plt.axis(\"off\")\n plt.show()\n \n\nX = X.astype(np.float32)\nraw_data = X[0,:]\nraw_img = np.reshape(raw_data, (24, 24))\nplt.figure()\nplt.imshow(raw_img, cmap=\"Greys_r\")\nplt.show()\nx = tf.reshape(raw_data, shape=[-1, 24, 24, 1])\nW = tf.Variable(tf.random_normal([5,5,1,32]))\nB = tf.Variable(tf.random_normal([32]))\n\nconv = tf.nn.bias_add(tf.nn.conv2d(x, W, strides=[1,1,1,1], padding=\"SAME\"), B)\nconv_result = tf.nn.relu(conv)\npool_result = tf.nn.max_pool(conv_result, ksize=[1,2,2,1], strides=[1,2,2,1], padding=\"SAME\")\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n W_val = sess.run(W)\n print(\"W -- img\")\n show_Weights(W_val)\n conv_result_val = sess.run(conv_result)\n print(\"conv -- img\")\n show_Conv(conv_result_val)\n print(\"pooling -- img\")\n pool_result_val = sess.run(pool_result)\n show_Conv(pool_result_val)\n \n \n# 构造卷积网络模型\n# 定义卷积、池化函数\ndef conv_func(x,w,b):\n conv_1 = tf.nn.conv2d(x, w, strides=[1,1,1,1], padding=\"SAME\")\n conv_2 = tf.nn.bias_add(conv_1, b)\n return tf.nn.relu(conv_2)\ndef pool_func(conv_val, k=2):\n return tf.nn.max_pool(conv_val, ksize=[1,2,2,1], strides=[1,k,k,1],padding=\"SAME\")\n# 定义网络参数\nx = tf.placeholder(tf.float32, [None, 24*24])\n_y = tf.placeholder(tf.float32, [None, len(names)])\nW1 = tf.Variable(tf.truncated_normal([5,5,1,64], stddev=0.1))\nB1 = tf.Variable(tf.truncated_normal([64], stddev=0.1))\nW2 = tf.Variable(tf.truncated_normal([5,5,64,64], stddev=0.1))\nB2 = tf.Variable(tf.truncated_normal([64], stddev=0.1))\nW3 = tf.Variable(tf.truncated_normal([6*6*64, 1024], stddev=0.1))\nB3 = tf.Variable(tf.truncated_normal([1024], stddev=0.1))\nW_out = tf.Variable(tf.truncated_normal([1024, len(names)], stddev=0.1))\nB_out = tf.Variable(tf.truncated_normal([len(names)], stddev=0.1))\ndef model():\n X_train = tf.reshape(x, shape=[-1,24,24,1])\n conv1 = conv_func(X_train, W1, B1)\n pooling1 = pool_func(conv1) \n # LRN层进行激励\n norm1 = tf.nn.lrn(pooling1, 4, bias=1.0, alpha=0.001// 9.0, beta=0.75)\n conv2 = conv_func(norm1, W2, B2)\n norm2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001// 9.0, beta=0.75)\n pooling2 = pool_func(norm2) \n pool_reshape = tf.reshape(pooling2 ,[-1, 6*6*64])\n local = tf.add(tf.matmul(pool_reshape, W3), B3)\n local_out = tf.nn.relu(local)\n out = tf.add(tf.matmul(local_out, W_out),B_out)\n return out \n \n\n# 准备优化器\nlearning_rate = 0.001\nmodel_op = model()\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=model_op, labels=_y))\ntrain_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\ncorrect_num = tf.equal(tf.argmax(model_op, 1), tf.argmax(_y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_num, tf.float32))\n# 迭代训练\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n onehot_labels = tf.one_hot(y, len(names), axis=-1)\n onehot_vals = sess.run(onehot_labels)\n batch_size = 64\n for _ in range(0, 1000):\n avg_acc = 0.\n batch_count = 0.\n for i in range(0, len(X), batch_size):\n batch_data = X[i:i+batch_size, :]\n batch_label = onehot_vals[i:i+batch_size, :]\n _, acc = sess.run([train_op, accuracy], feed_dict={x:batch_data, _y:batch_label})\n avg_acc += acc\n batch_count += 1\n avg_acc /= batch_count\n print(\"Epoch {}. Avg accuracy {}\".format(_, avg_acc))\n","sub_path":"cifar_train.py","file_name":"cifar_train.py","file_ext":"py","file_size_in_byte":6177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"452062699","text":"import socket\nfrom threading import Thread\nfrom time import sleep\n\ndef main():\n\tglobal run\n\tglobal server\n\n\trun = True\n\tserver = socket.socket()\n\tserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\tserver.bind(('localhost', 8080))\n\tserver.listen(10)\n\n\tconnection, addr = server.accept()\n\n\tt1 = Thread(target = receive, args = (connection, ) )\n\tt1.start()\n\n\tt2 = Thread(target = send, args = (connection, ) )\n\tt2.start()\n\ndef receive(arg):\n\twhile run:\n\t\tdata = arg.recv(256)\n\t\tif not data:\n\t\t\tbreak\n\t\tprint('Data from connnect user: ' + data + '\\n')\n\t\tsleep(0.01)\n\tserver.stop()\n\ndef send(arg):\n\tmessage = raw_input('-> ')\n\twhile message != 'quit':\n\t\tmessage = raw_input('-> ')\n\t\targ.send(message)\n\t\tsleep(0.01)\n\tserver.stop()\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"264714277","text":"from ROOT import TFile, TTree\nfrom array import array\nimport numpy as np\n\n\nf = TFile( 'test.root', 'recreate' )\nt = TTree( 't1', 'tree with histos' )\n\nmaxn = 10\nn = array( 'i', [ 0 ] )\n#n = np.array([0])\nd = array( 'f', maxn*[ 0. ] )\n#d = np.zeros(maxn)\n#d = np.array( [0.]*maxn)\nprint(d)\nt.Branch( 'mynum', n, 'mynum/I' )\nt.Branch( 'myval', d, 'myval[mynum]/F' )\n\nfor i in range(25):\n n[0] = 10#min(i,maxn)\n for j in range(n[0]):\n #d[j] = i*0.1+j\n d[j] = 52.\n t.Fill()\n\nf.Write()\nf.Close()\n\n\ninf = TFile('test.root')\ntree = inf.Get('t1')\ntree.GetEntry(1)\ntreelist = [tree.myval[i] for i in range(tree.mynum)]\nprint([tree.myval[i] for i in range(tree.mynum)])\nprint(np.asarray(treelist))\nprint(np.array(tree.myval))\n","sub_path":"single_electron/rootwrite_branch_test_test.py","file_name":"rootwrite_branch_test_test.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"196651462","text":"print(\"----- ESTRUTURA DE REPETIÇÃO WHILE -----\\n\")\n\n# O loop continua enquanto a sua condição for True\n\nnum = 0\nresposta = ''\n\nprint(\"Enquanto num for menor que 10:\")\nwhile num < 10:\n print(f\"{num} \", end='')\n num += 1\n\nprint(\"\\n\\nEnquanto a resposta for diferente de sim:\")\nwhile resposta != 'sim':\n resposta = input(\"Já acabou? \")\n","sub_path":"loop_while.py","file_name":"loop_while.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"641622357","text":"from microbit import *\n\nUalim = 3.13\nR0 = 1000\nRlim = 123\nintervalle = 10000\n\nwhile True:\n \"\"\"\n acquisition de Requivalente\n \"\"\"\n valeurAnaUequiv = pin2.read_analog()\n Uequiv = valeurAnaUequiv*Ualim/1023\n Requiv = R0*Uequiv/(Ualim-Uequiv)\n print(Requiv)\n\n \"\"\"\n réglage alarmes\n \"\"\"\n if Requiv > Rlim:\n pin0.write_digital(0)\n pin1.write_digital(1)\n else:\n pin0.write_digital(1)\n pin1.write_digital(0)\n sleep(intervalle)\n\n\n\n\n\n","sub_path":"thermistance-microbit/alarme.py","file_name":"alarme.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"143301579","text":"#!/usr/bin/env python\n'''\nUsage:\n ./timespacetest.py [options] \n ./timespacetest.py [options] --plot\n\nOptions:\n --help -h Help me.\n --plot Plot instead.\n --npz -N Output npy instead.\n'''\nfrom docopt import docopt;\nfrom timespace import mkgauss, c;\nimport numpy as np;\nimport noobna;\nopts = docopt(__doc__,help=True);\n\nTh= 6e-6;\nt0 = Th/np.sqrt(8*np.log(2));\nFnum=1.5\ndt = 0.05e-6;\n#t = np.arange(-1.5*Th,1.5*Th+dt,dt);\nt = np.linspace(-4.1e-6,6.1e-6,205);\nx = np.linspace(-11.0e-4,-10.9e-4, 3);\ny = np.linspace(-5e-4, 5e-4, 101);\nz = np.linspace(-5e-4, 5e-4, 101);\n\nT,X,Y,Z = np.meshgrid(t,x,y,z,indexing='ij', sparse=True);\ngauss = mkgauss(t0=t0,F=Fnum);\nout = gauss(T,X,Y,Z);\n\n#zero edges\nout[ 0, :, :, :] = 0;\nout[-1, :, :, :] = 0;\n\n# don't zero x axis\n#out[ :, 0, :, :] = 0;\n#out[ :,-1, :, :] = 0;\n\nout[ :, :, 0, :] = 0;\nout[ :, :,-1, :] = 0;\n\nout[ :, :, :, 0] = 0;\nout[ :, :, :,-1] = 0;\n\n\nprint(\"shape of axes: {}\".format(out.shape));\nif opts['--plot']:\n import matplotlib.pyplot as plt;\n from lspplot.pc import pc;\n pc(out[:,0,:,0].T, p=(t*1e6,y), xlabel='fs', ylabel='cm');\n plt.show();\nelif opts['--npz']:\n np.savez(opts[''], d=out, t=t,x=x,y=y,z=z);\nelse:\n noobna.output_centered(opts[''],[t,x,y,z],out,dtype='float64');\n","sub_path":"200519-newlasertest/timespacetest2.py","file_name":"timespacetest2.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"379886042","text":"from mymodule import stats_word\ns_text='''\n愚公移山\n太行、王屋两座山,方圆七百里,高七八千丈,本来在冀州南边,黄河北岸的北边。 \n\nOld Man Yu Gong and the Mountains \nOld man Yu Gong’s house had two big mountains in front of it.\n\n'''\nresult=stats_word.stats_text(s_text)\nprint(\"统计结果\\n\",result)","sub_path":"exercises/1901100012/d07/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"18280109","text":"from django.shortcuts import render, get_object_or_404, redirect, render_to_response\nfrom django.views.generic import View, TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView\nfrom django.urls import reverse_lazy, reverse\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.decorators import login_required\nfrom formtools.wizard.views import SessionWizardView\nfrom django.http import HttpResponseRedirect\nfrom django.core.mail import send_mail\nfrom django.utils import timezone\nfrom . import models, forms\nfrom .forms import FolderCreateForm, JobCreateForm\nimport logging\nimport importlib\nfrom pprint import pprint\n\nlogr = logging.getLogger(__name__)\n\n# Create your views here.\n\ndef index(request):\n # appl_list = Application.objects.order_by('name')\n # appl_dict = {\n # 'applications': appl_list\n # }\n\n # return render(request, 'CTM_Requester/index.html', context=appl_dict)\n return render(request, 'CTM_Requester/index.html')\n\n\nclass ApplicationListView(ListView):\n context_object_name = 'applications'\n model = models.Application\n \n def post(self, request, *args, **kwargs):\n chosenAppl = self.request.POST['ApplName']\n return HttpResponseRedirect(reverse(\"CTM_Requester:ApplDetails\", args=(chosenAppl,)))\n \nclass ApplicationDetailView(DetailView):\n context_object_name = 'application_details'\n model = models.Application\n template_name = 'CTM_Requester/application_details.html'\n \n # get_queryset(self):\n # return models.Application.objects.filter()\n\n \n \nclass FolderDetailView(DetailView):\n context_object_name = 'folder_details'\n model = models.Folder\n template_name = 'CTM_Requester/folder_details.html'\n \nclass JobDetailView(DeleteView):\n context_object_name = 'job_details'\n model = models.Job\n template_name = 'CTM_Requester/job_details.html'\n \nclass FolderCreateView(LoginRequiredMixin, CreateView):\n form_class = FolderCreateForm\n login_url = '/Requester/accounts/login/'\n redirect_field_name = 'CTM_Requester/folder_details.html'\n # print(vars(LoginRequiredMixin))\n\n model = models.Folder\n\n \n def get_initial(self):\n userName = self.request.user\n initial = super(FolderCreateView, self).get_initial()\n initial['appl'] = self.kwargs['appl']\n initial['author'] = userName\n initial['name'] = \"To Be Filled In Post Action\"\n return initial\n\n def form_valid(self, form):\n appl = form.instance.appl\n subAppl = form.instance.subAppl\n subAppl = subAppl.replace(\" \", \"-\").title()\n folderName = str(appl) + \"-\" + str(subAppl)\n form.instance.name = folderName\n form.instance.subAppl = subAppl\n return super().form_valid(form)\n \n def get_success_url(self):\n return reverse('CTM_Requester:FolderDetails', kwargs={'appl': self.object.appl,'pk': self.object.id})\n \n \nclass FolderUpdateView(LoginRequiredMixin, UpdateView):\n # fields = ('subAppl', 'name', 'description')\n form_class = FolderCreateForm\n login_url = '/Requester/accounts/login/'\n model = models.Folder\n \n def form_valid(self, form):\n appl = form.instance.appl\n subAppl = form.instance.subAppl\n subAppl = subAppl.replace(\" \", \"-\").title()\n folderName = str(appl) + \"-\" + str(subAppl)\n form.instance.name = folderName\n form.instance.subAppl = subAppl\n self.object.approvedFolder = False\n self.object.deployedFolder = False\n self.object.publishedFolder = False\n self.object.changedDate = timezone.now()\n return super().form_valid(form)\n \n def get_success_url(self):\n return reverse('CTM_Requester:FolderDetails', kwargs={'appl': self.object.appl,'pk': self.object.id})\n\nclass FolderDeleteView(LoginRequiredMixin, DeleteView):\n model = models.Folder\n form_class = FolderCreateForm\n login_url = '/Requester/accounts/login/'\n # success_url = reverse_lazy(\"CTM_Requester:ApplDetails\", kwargs={'appl':appl})\n def get_success_url(self):\n return reverse_lazy(\"CTM_Requester:ApplDetails\", kwargs={'pk':self.kwargs['appl']})\n \n\nclass FolderDraftListView(LoginRequiredMixin, ListView):\n login_url = '/Requester/accounts/login/'\n model = models.Folder\n template_name = 'CTM_Requester/folder_drafts_list.html'\n context_object_name = 'folders'\n \n def get_queryset(self):\n if self.request.user.is_superuser:\n return models.Folder.objects.filter(publishedFolder=False).order_by('createdDate')\n else:\n return models.Folder.objects.filter(publishedFolder=False, author=self.request.user).order_by('createdDate')\n\n@login_required\ndef folder_approve(request, appl, pk):\n folder = get_object_or_404(models.Folder, pk=pk)\n folder.approve()\n return redirect(reverse('CTM_Requester:FolderDetails', kwargs={'appl':appl,'pk':folder.id}))\n \n@login_required\ndef folder_publish(requesrt, appl, pk):\n folder = get_object_or_404(models.Folder, pk=pk)\n folder.publish()\n # send_mail(\n # 'koko',\n # 'koko body',\n # 'koko@mama.com',\n # ['mikimanor@gmail.com'],\n # fail_silently=False,\n \n # )\n return redirect(reverse('CTM_Requester:FolderDetails', kwargs={'appl':appl,'pk':folder.id}))\n \n@login_required\ndef folder_deploy(request, appl, pk):\n folder = get_object_or_404(models.Folder, pk=pk)\n folder.deploy()\n return redirect(reverse('CTM_Requester:ApplDetails', kwargs={'pk':appl}))\n\n@login_required\ndef folder_edit(request, appl, pk):\n folder = get_object_or_404(models.Folder, pk=pk)\n folder.edit()\n return redirect(reverse('CTM_Requester:FolderDetails', kwargs={'appl':appl,'pk':folder.id}))\n\nclass JobCreateView(LoginRequiredMixin, CreateView):\n form_class = JobCreateForm\n login_url = '/Requester/accounts/login/'\n model = models.Job\n\n def get_initial(self):\n initial = super(JobCreateView, self).get_initial()\n folderName = models.Folder.objects.get(id=self.kwargs['folderID'])\n initial['folder'] = folderName\n return initial\n \n def form_valid(self, form):\n type = form.instance.jobType\n jobName = form.instance.name\n jobName = jobName.replace(\" \", \"-\")\n fullJobName = str(type) + \"-\" + str(jobName.title())\n form.instance.name = fullJobName\n folder = models.Folder.objects.get(pk=self.kwargs['folderID'])\n folder.approvedFolder = False\n folder.deployedFolder = False\n folder.save()\n return super().form_valid(form)\n \nclass JobUpdateView(LoginRequiredMixin, UpdateView):\n # fields = ('jobType', 'name', 'description')\n form_class = JobCreateForm\n login_url = '/Requester/accounts/login/'\n model = models.Job\n\n def get_initial(self):\n initial = super(JobUpdateView, self).get_initial()\n name = models.Job.objects.get(id=self.kwargs['pk']).name\n type = models.Job.objects.get(id=self.kwargs['pk']).jobType\n name = name.split(type + \"-\")[1]\n initial['name'] = name\n return initial\n \n def form_valid(self, form):\n type = form.instance.jobType\n jobName = form.instance.name\n jobName = jobName.replace(\" \", \"-\")\n fullJobName = str(type) + \"-\" + str(jobName.title())\n form.instance.name = fullJobName\n folder = models.Folder.objects.get(pk=self.kwargs['folderID'])\n folder.approvedFolder = False\n folder.deployedFolder = False\n folder.save()\n return super().form_valid(form)\n \nclass JobDeleteView(LoginRequiredMixin, DeleteView):\n model = models.Job\n form_class = JobCreateForm\n login_url = '/Requester/accounts/login/'\n def get_success_url(self):\n # print(vars(self))\n # return\n form.instance.name = fullJobName\n folder = models.Folder.objects.get(pk=self.kwargs['folderID'])\n folder.approvedFolder = False\n folder.deployedFolder = False\n folder.save()\n return reverse_lazy(\"CTM_Requester:FolderDetails\", kwargs={'appl':self.kwargs['appl'], 'pk':self.kwargs['folderID']})\n\n \nglobal_form_list = [forms.JobCreateFormGeneral, forms.DummyForm, forms.JobCreateFormSchedualing, \n forms.JobCreateFormPreqs, forms.JobCreateFormPosts]\n\ndef print_global_list():\n global global_form_list\n print(\"global form list from outside : {}\".format(global_form_list))\n\ndef get_form_list(request, form_list=None, *args, **kwargs):\n global global_form_list\n form_list = global_form_list\n print(\"The form list is : {}\".format(form_list))\n # if form_list is None:\n # form_list = [forms.JobCreateFormGeneral, forms.DummyForm, forms.JobCreateFormSchedualing, \n # forms.JobCreateFormPreqs, forms.JobCreateFormPosts]\n # form_list = global_form_list\n return JobWizard.as_view(form_list=form_list)(request, **kwargs)\n \ndef class_for_name(class_name):\n# m = importlib.import_module(module_name)\n c = getattr(forms, class_name)\n return c\n \nclass JobWizard(SessionWizardView):\n template_name = \"CTM_Requester/job_form_wizard.html\"\n \n # def __init__(self, **kwargs):\n # self.form_list = kwargs.pop('form_list')\n # return super(JobWizard, self).__init__(**kwargs)\n \n def dispatch(self, request, *args, **kwargs):\n print(\"dispatched!\")\n self.folderID = self.kwargs['folderID']\n self.folder = models.Folder.objects.get(id=self.folderID)\n # Checking if kw arg of job id has been passed, if so - update needed\n if 'pk' in self.kwargs:\n self.jobID = self.kwargs['pk']\n self.job = models.Job.objects.get(id=self.jobID)\n self.inUpdateMode = True\n self.oldJobName = self.job.name\n else:\n self.inUpdateMode = False\n return super(JobWizard, self).dispatch(request, *args, **kwargs)\n\n def get_form(self, step=None, data=None, files=None):\n \n print(\"In get_form, step {}\".format(step))\n # pprint(data)\n form = super(JobWizard, self).get_form(step, data, files)\n if step is None:\n step = self.steps.current\n if int(step) == 1:\n pass\n # self.job = models.Job.objects.get(id='81')\n # form = self.JobTypeClass()\n # print(\"The form is :\")\n # pprint(form)\n # form.instance.job = models.Job.objects.get(id='81')\n # form.fields['job'] = models.Job.objects.get(id='81')\n # form.fields['job']['initial'] = 81\n # pprint(form)\n \n return form \n \n \n def get_form_initial(self, step):\n print(\"In get_form_Initial, step {}\".format(step))\n self.job = models.Job.objects.get(id='81')\n initial = self.initial_dict.get(step, {})\n print(initial)\n if self.inUpdateMode:\n pass\n # if int(step) == 0:\n # objectInstance = models.Job\n # self.neededObject = objectInstance.objects.get(id=self.jobID)\n # # initial.update({'folder': self.folder, 'id': self.jobID, 'jobType': self.job.jobType, 'name': self.job.name, 'description': self.job.description})\n # elif int(step) == 1:\n # objectInstance = models.Schedualing\n # self.neededObject = objectInstance.objects.get(job=self.jobID)\n # elif int(step) == 2 or int(step) == 3:\n # return\n # fields = [field for field in objectInstance._meta.get_fields(include_parents=False)]\n # dict = {field.name: getattr(self.neededObject, field.name) for field in fields if not hasattr(field, \"field\")}\n # # print(dict)\n # initial.update(dict)\n else:\n # print(initial)\n if int(step) == 0:\n self.oldJobName = None\n initial.update({'folder': self.folder })\n else: \n # pass\n # print(\"i'm here\")\n initial.update({'job': self.job})\n # pprint(initial)\n print(initial)\n return initial\n \n def process_step(self, form, **kwargs):\n print(\"form is \")\n print(form)\n step = self.get_step_index()\n if step == 0 and hasattr(form, 'cleaned_data'):\n self.jobType = form.cleaned_data['jobType'] # Getting The job type which filled by the user\n self.JobTypeClass = class_for_name('JobCreateForm' + self.jobType + '_Job') # Converting the name to class object\n global global_form_list\n global_form_list[1] = self.JobTypeClass\n print(\"Form List after update : {}\".format(global_form_list))\n print_global_list()\n return self.get_form_step_data(form)\n \n # def get_context_data(self, form, **kwargs):\n # data = self.get_cleaned_data_for_step(self.get_prev_step(self.steps.current))\n # if self.steps.current == '1':\n # # service_name = str(data['provider']).split('Service')[1]\n # #services are named th_\n # #call of the dedicated ProviderForm\n # form = class_for_name('JobCreateForm' + self.jobType + '_Job')\n # context = super(JobWizard, self).get_context_data(form=form, **kwargs)\n # print(dir(JobWizard))\n # return context\n\n \n def done(self, form_list, **kwargs):\n print(\"done\")\n print(form_list)\n print(\"+++++++++++\")\n print(self.form_list)\n form_data = self.process_form_data(form_list)\n # for form in form_list:\n # form.save()\n # generalForm[-1].save()\n # print(generalForm)\n #return redirect(reverse('CTM_Requester:FolderDetails', kwargs={'appl':appl,'pk':folder.id}))\n #return render_to_response('CTM_Requester/application_list.html', {'form_data': form_data})\n #return reverse_lazy(\"CTM_Requester:FolderDetails\", kwargs={'appl':self.kwargs['appl'], 'pk':self.kwargs['folderID']})\n return redirect(reverse('CTM_Requester:FolderDetails', kwargs={'appl':self.kwargs['appl'],'pk':self.kwargs['folderID']}))\n \n \n def process_form_data(self, form_list):\n form_data = [form.cleaned_data for form in form_list]\n # form_list['1'] = self.form_list['1']\n # print(self.form_list['1'])\n for inx, form in enumerate(form_list):\n if inx == 0:\n # print(\"before\")\n jobName = form.cleaned_data['name']\n if jobName != self.oldJobName or self.oldJobName == None:\n form.save()\n # print(\"after\")\n jobName = form.cleaned_data['name']\n self.job = models.Job.objects.get(name = jobName, folder=self.folderID)\n jobName = self.job.name\n jobName = jobName.replace(\" \", \"-\")\n fullJobName = str(self.job.jobType) + \"-\" + str(jobName.title())\n self.job.name = fullJobName\n # print(self.job)\n self.job.save()\n # jobID = models.Job.objects.get(name=self.kwargs['pk'])\n \n else:\n form.instance.job = self.job\n print(form)\n form.save()\n return form_data\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n# def forms(request):\n# form = fm.FormName\n \n# if request.method == \"POST\":\n# form = fm.FormName(request.POST)\n# if form.is_valid():\n# print(\"Validation Success!\")\n# print(\"Name : \" + form.cleaned_data['name'])\n \n# return render(request, 'CTM_Requester/form_page.html', {'form':form})\n \n# def folders(request):\n \n# form = NewFolderForm()\n# if request.method == \"POST\":\n# form = NewFolderForm(request.POST)\n# if form.is_valid():\n# print(\"Validation Success!\")\n# print(form)\n# form.save(commit=True)\n# # return index(request)\n# else:\n# print(\"Error In Form\")\n \n# return render(request, 'CTM_Requester/folder_page.html', {'form':form} )\n \n \n# class CBView(View):\n \n# def get(self, request):\n# return HttpResponse(\"COOL!\")\n \n# class IndexView(TemplateView):\n \n# template_name = 'CTM_Requester/index.html'\n \n# def get_context_data(self, **kwargs):\n# context = super().get_context_data(**kwargs)\n# appl_list = Application.objects.order_by('name')\n# context['applications'] = appl_list\n# return context\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"CTM_Requester/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"490099923","text":"import discord\nfrom discord.ext import commands\nimport random\nimport typing\n\nmyToken = \"NTY4MTM2MDUyNjc4NzIxNTc2.XLdsJA.jxCWgJLaBo1b0Lu0phB177mAThA\"\nserverId = \"514226826671947779\"\nmyDiscordID = \"403982408573124619\"\njuzeistID = \"232492888833916938\"\nwarrenID = \"252778671444721666\"\ncaankaglanID = \"<@56593800135311391\"\ncaankaglanID1 = \"56593800135311391\"\ncaankaglanID2 = \"<56593800135311391>\"\n\nclient = discord.Client()\n#server = discord.Server(id=serverId)\n\narray = []\n\"\"\"bot = commands.Bot(command_prefix = \"!\")\n@bot.command(pass_context=True, name=\"!kick\")\n#@commands.has_permissions(kick_members=True)\nasync def kick(ctx, *, target: discord.Member):\n if target.server_permissions.administrator:\n await bot.say(\"Atmaya çalıştığın kişi senin efendin ulan\")\n bot.\n else:\n try:\n await bot.kick(target)\n await bot.say(f\"Orospu evladi {target} kicklendi\")\n except Exception as e:\n await bot.say(\"Yetkin yok orospu evladı\")\n print(\"exception is :\",e)\n\n@bot.command(pass_context = True, name= \"Hello\")\nasync def hello(message):\n await bot.say(\"Anani sikeyim ismail!\")\n\n@bot.command(pass_context = True, name = \"apex\")\nasync def apex(message):\n await bot.say(\"Anani sikeyim ismail!\")\n\n@bot.command(pass_context = True)\nasync def ban2(member: discord.Member, days: int = 1):\n try:\n #if \"56593800135311391\" in [role.id for role in message.author.roles]:\n await bot.ban(member.id, days)\n except Exception as e:\n print(\"exception is : \",e)\n\"\"\"\n@client.event\nasync def on_member_join(member):\n for channel in member.server.channels:\n print(\"channel is : \"+str(channel))\n #await client.send_message(f\"Hosgeldin?! {member.mention}\")\n\n@client.event\nasync def on_ready():\n print(\"Logged in as\")\n print(client.user.name)\n print(client.user.id)\n print(\"------\")\n\n@client.event\n@commands.has_permissions(kick_member= True)\nasync def on_message(message):\n if message.author == client.user:\n return\n if message.content.startswith('hello'):\n await client.send_message(message.channel, 'Hello!')\n if message.content.startswith('selam'):\n await client.send_message(message.channel, 'anani avradini sikeyim ismail')\n if message.content.startswith(\"x\"):\n msg = \"ow yeah yeah\".format(message)\n print(\"author id is :\",message.author)\n print(\"type of authorid is : \",type(message.author))\n print(\"server id is:\",message.channel.server)\n print(\"type of server id is: \",type(message.channel.server))\n array.append(message.author)\n await client.send_message(message.channel, msg)\n if \"apex\" in message.content:\n msg = \"Bu discordda birisi apex hakkında konuşursa ne olur biliyor musun orospu evladı?\".format(message)\n await client.send_message(message.channel,msg)\n if message.content.startswith(\"unban\"):\n User = discord.utils.find(lambda user: user.name == \"caankaglan\", client.get_bans(message.channel.server))\n try:\n await client.unban(message.channel.server, User)\n except discord.Forbidden:\n await client.send_message(message.channel, \"The bot does not have the proper permissions to unban.\")\n return\n except discord.HTTPException:\n await client.send_message(message.channel, \"Unbanning failed.\")\n return\n if message.content.startswith(\"ban\"):\n print(array[0])\n try:\n client.ban(array[0],1)\n print(\"kicklendi ?!\")\n except Exception as e:\n print(\"error is : \",e)\n #await client.ban(message.author.id,message.channel.server,delete_message_days=1)\n\n await ctx.send(embed=embed)\n\n\n#bot.run(myToken)\nclient.run(myToken)\n","sub_path":"example_bot.py","file_name":"example_bot.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"236825676","text":"import problem\nimport torch\nfrom torch.nn.functional import relu\nfrom torch.nn.utils.rnn import pad_sequence\n\nX_train, y_train = problem.get_train_data()\nX_test, y_test = problem.get_test_data()\n\nclass Regressor():\n \"\"\"A PyTorch MLP model consisting of an MLP for each module type.\n The model is learnt only on single module.\n The model takes as input the input power and the meta data of the\n corresponding cascade. To predict the output power the model\n simply cascades the different MLPs matching the input module cascade.\"\"\"\n\n def __init__(self):\n super().__init__()\n # Since the model need meta data present in the data\n # we will only instantiate the model when calling the fit function\n self.Model = PyTorchModel # PyTorch model class\n self.model = None # PyTorch model instance\n self.mod_id = None # Module IDs\n\n def fit(self, X, y):\n # Retrieve some information about the modules from the data\n all_mods = set(\n [((\"type\", mod[0]), (\"nb_feat\", len(mod[1]))) for seq, _, _ in X\n for mod in seq])\n mod_info = [dict(m) for m in all_mods]\n self.mod_id = {mod[\"type\"]: i for i, mod in enumerate(mod_info)}\n\n # Instantiate the PyTorch model\n self.model = self.Model(mod_info)\n\n # Turn on training mode\n self.model.train()\n # Get data and create train data loaders\n data_list = [{\"mod_id_seq\": torch.tensor(\n [self.mod_id[mod] for mod, _ in mod_seq]),\n \"mod_feat_seq_list\": [torch.tensor(feat).float() for\n _, feat in mod_seq],\n \"input_power\": torch.tensor(p_in).float(),\n \"output_power\": torch.tensor(p_out).float()} for\n (mod_seq, p_in, campaign_id), p_out in zip(X, y)]\n\n\n train_loader = torch.utils.data.DataLoader(data_list, batch_size=1,\n collate_fn=collate_fn)\n # Instantiate criterion and optimizer\n crit = torch.nn.MSELoss()\n\n opt = torch.optim.Adam(self.model.parameters(), lr=0.0001)\n params = self.model.parameters()\n # Training loop\n for e in range(100):\n for data in train_loader:\n (mod_id_seq, mod_feat_seq, p_in), p_out = data\n opt.zero_grad()\n preds = self.model(mod_id_seq, mod_feat_seq, p_in)\n # Since the evaluation is only done for on-channels it\n # helps the optimization to only backpropagate through them.\n on_chan = p_in != 0\n on_preds = torch.mul(on_chan, preds)\n on_p_out = torch.mul(on_chan, p_out)\n loss = crit(on_preds, on_p_out)\n # Since we are only looking at single modules\n if loss.requires_grad:\n loss.backward()\n opt.step()\n\n def predict(self, X):\n # Turn on evaluation mode\n self.model.eval()\n # No ground truth when predicting, format input arguments\n # Input powers\n p_in = torch.stack([torch.tensor(p_in).float() for _, p_in, _ in X])\n # Module features\n mod_feat_seq = [[torch.tensor(feat).float() for _, feat in mod_seq]\n for mod_seq, _, _ in X]\n # Module IDs\n mod_id_seq = [torch.tensor([self.mod_id[mod] for mod, _ in mod_seq])\n for mod_seq, _, _ in X]\n mod_id_seq = pad_sequence(mod_id_seq, batch_first=True,\n padding_value=-1)\n # Model prediction\n preds = self.model(mod_id_seq, mod_feat_seq, p_in).detach().numpy()\n return preds\n\n\nclass PyTorchModel(torch.nn.Module):\n def __init__(self, mod_info):\n super(PyTorchModel, self).__init__()\n self.mod_info = mod_info\n # Construct as many MLPs as modules present in the data\n self.MLPs = torch.nn.ModuleList(\n [MLP(m[\"nb_feat\"]) for m in self.mod_info])\n\n def forward(self, mod_id_seq, mod_feat_seq, p_in):\n seq_len = torch.tensor(list(map(len, mod_feat_seq)))\n p_out = p_in\n max_nb_mod = max(seq_len)\n for n in range(max_nb_mod):\n for i, mlp in enumerate(self.MLPs):\n msk = torch.mul(mod_id_seq[:, n] == i, seq_len > n)\n if msk.any():\n feats = torch.stack(\n [f[n] for i, f in enumerate(mod_feat_seq) if msk[i]])\n p_out[msk] = mlp(torch.cat([p_out[msk], feats], dim=-1))\n # Return positive values when evaluating the model\n return p_out if self.training else relu(p_out)\n\n\nclass MLP(torch.nn.Module):\n \"\"\"A simple two layer MLP taking as input the\n input powers and the features of the module\"\"\"\n\n def __init__(self, feat_size):\n super(MLP, self).__init__()\n # Definition of the modules of the model\n # Two fully connected layers\n self.fc0 = torch.nn.Linear(32 + feat_size, 128)\n self.fc1 = torch.nn.Linear(128, 32)\n\n def forward(self, x):\n # Compute the output of the model using a tanh activation function\n p_out = self.fc1(torch.tanh(self.fc0(x)))\n return p_out\n\n\ndef collate_fn(batch):\n # Power output\n p_out = torch.stack([sample[\"output_power\"] for sample in batch])\n # Power input\n p_in = torch.stack([sample[\"input_power\"] for sample in batch])\n # Module id\n l_id_seq = [sample[\"mod_id_seq\"] for sample in batch]\n mod_id_seq = pad_sequence(l_id_seq, batch_first=True, padding_value=-1)\n # Module features\n mod_feat_seq = [sample[\"mod_feat_seq_list\"] for sample in batch]\n\n return (mod_id_seq, mod_feat_seq, p_in), p_out\n\n\nr = Regressor()\n\nr.fit(X_train, y_train)\n\nres = r.predict(X_test)","sub_path":"cascade_test.py","file_name":"cascade_test.py","file_ext":"py","file_size_in_byte":5803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"206075438","text":"#\r\nfrom tkinter import *\r\nimport os\r\nimport tkinter.font as tkfont\r\nimport P3\r\nfrom tkinter import ttk\r\nOPERATORS=P3.OPERATORS\r\nSTATE_STACK = []\r\n#\r\nmw = Tk()\r\nCurrent_State = P3.State()\r\nSTATUSBAR_CANVAS = None\r\nindex=[0,0,0,0,0,\"Move in to a house\"]\r\nyour_house=[\"Move in to a house\",\"You are living in Tent City\",\"You are living in Trailer Park\",\"You are living in Apartment\",\"You are living in Duplex\",\"You are living in Mansion\"]\r\nfamilies = os.listdir(\"Family\")\r\nfaces = os.listdir(\"Faces\")\r\neggs = os.listdir(\"Egg\")\r\nroles = os.listdir(\"Roles\")\r\njobs = os.listdir(\"Jobs\")\r\nentertainments = os.listdir(\"Entertainments\")\r\n#get the height of screen and use it as the length of the window\r\nHEIGHT = 1000#mw.winfo_screenheight()\r\n#Create lists for images\r\nfather = PhotoImage(file=\"Roles/\" + roles[0]);mother = PhotoImage(file=\"Roles/\" + roles[1]);brother = PhotoImage(file=\"Roles/\" + roles[2]);sister = PhotoImage(file=\"Roles/\" + roles[3])\r\nfamily = [father,mother,brother,sister]\r\nj1=PhotoImage(file=\"Jobs/\"+jobs[0]);j2=PhotoImage(file=\"Jobs/\"+jobs[1]);j3=PhotoImage(file=\"Jobs/\"+jobs[2]);j4=PhotoImage(file=\"Jobs/\"+jobs[3]);j5=PhotoImage(file=\"Jobs/\"+jobs[4]);j6=PhotoImage(file=\"Jobs/\"+jobs[5])\r\nj7=PhotoImage(file=\"Jobs/\"+jobs[6]);j8=PhotoImage(file=\"Jobs/\"+jobs[7]);j9=PhotoImage(file=\"Jobs/\"+jobs[8]);j10=PhotoImage(file=\"Jobs/\"+jobs[9]);j11=PhotoImage(file=\"Jobs/\"+jobs[10]);j12=PhotoImage(file=\"Jobs/\"+jobs[11])\r\nj13=PhotoImage(file=\"Jobs/\"+jobs[12]);j14=PhotoImage(file=\"Jobs/\"+jobs[13]);j15=PhotoImage(file=\"Jobs/\"+jobs[14]);j16=PhotoImage(file=\"Jobs/\"+jobs[15]);j17=PhotoImage(file=\"Jobs/\"+jobs[16]);j18=PhotoImage(file=\"Jobs/\"+jobs[17])\r\nj19=PhotoImage(file=\"Jobs/\"+jobs[18]);j20=PhotoImage(file=\"Jobs/\"+jobs[19]);j21=PhotoImage(file=\"Jobs/\"+jobs[20]);j22=PhotoImage(file=\"Jobs/\"+jobs[21]);j23=PhotoImage(file=\"Jobs/\"+jobs[22]);j24=PhotoImage(file=\"Jobs/\"+jobs[23])\r\nj25=PhotoImage(file=\"Jobs/\"+jobs[24]);j26=PhotoImage(file=\"Jobs/\"+jobs[25]);j27=PhotoImage(file=\"Jobs/\"+jobs[26])\r\njob = [j1,j2,j3,j4,j5,j6,j7,j8,j9,j10,j11,j12,j13,j14,j15,j16,j17,j18,j19,j20,j21,j22,j23,j24,j25,j26,j27]\r\n#\r\ndef _from_rgb(rgb):\r\n return \"#%02x%02x%02x\" % rgb\r\ndef on_combo_configure(event):\r\n combo = event.widget\r\n style = ttk.Style()\r\n # check if the combobox already has the \"postoffest\" property\r\n current_combo_style = combo.cget('style') or \"TCombobox\"\r\n if len(style.lookup(current_combo_style, 'postoffset'))>0:\r\n return\r\n combo_values = combo.cget('values')\r\n if len(combo_values) == 0:\r\n return\r\n longest_value = max(combo_values, key=len)\r\n font = tkfont.nametofont(str(combo.cget('font')))\r\n width = font.measure(longest_value + \"0\") - event.width\r\n if (width<0):\r\n # no need to make the popdown smaller\r\n return\r\n # create an unique style name using widget's id\r\n unique_name='Combobox{}'.format(combo.winfo_id())\r\n # the new style must inherit from curret widget style (unless it's our custom style!) \r\n if unique_name in current_combo_style:\r\n style_name = current_combo_style \r\n else:\r\n style_name = \"{}.{}\".format(unique_name, current_combo_style)\r\n\r\n style.configure(style_name, postoffset=(0,0,width,0))\r\n combo.configure(style=style_name)\r\ndef loop_by_three(i):\r\n if i==0:x=HEIGHT/1000*154;y=154\r\n if i==1:x=436;y=154\r\n if i==2:x=718;y=154\r\n if i==3:x=154;y=436\r\n if i==4:x=436;y=436\r\n if i==5:x=718;y=436\r\n if i==6:x=154;y=718\r\n if i==7:x=436;y=718\r\n if i==8:x=718;y=718\r\n return [x,y]\r\ndef createFoolW(cat):\r\n #create the window\r\n nw = Toplevel(mw)\r\n nw.geometry(str(HEIGHT)+\"x\"+str(HEIGHT)+\"+0+0\")\r\n nw.resizable(1,1)\r\n nw.overrideredirect(True)\t\r\n nw.title(cat)\r\n\r\n #create window frame\r\n back = Frame(master=nw,bg=bgc)\r\n back.pack_propagate(1)\r\n back.pack(fill=BOTH, expand=1)\r\n if cat == \"fool\":\r\n fool(back)\r\n\r\n #quit button for frame\r\n qbf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*200,master=nw)\r\n qbf.pack_propagate(0) \r\n qbf.pack()\r\n qb = Button(qbf, text=\"Go Back\", font = optionFont, bg=brown,fg=white, \r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: nw.destroy())\r\n qbf.place(x=HEIGHT/1000*800, y=HEIGHT/1000*950)\r\n qb.pack(fill=BOTH, expand=1)\r\ndef fool(w):\r\n fool = PhotoImage(file=\"Egg/\" + eggs[0])\r\n hapr = Label(w, image=fool,bg=bgc)\r\n hapr.image=fool\r\n hapr.place(x=((HEIGHT/2)-500),y=(0))\r\n#\r\nbutb = _from_rgb((8,229,37))\r\nbutf = _from_rgb((33,48,35))\r\nbgc = _from_rgb((245,219,149))\r\nactb = _from_rgb((245,160,166))\r\nactf = _from_rgb((30,16,233))\r\nchob = _from_rgb((0,76,153))\r\nchof = _from_rgb((102,255,255))\r\nchab = _from_rgb((76,0,153))\r\nbarb = _from_rgb((192,192,192))\r\nfamilyb = _from_rgb((143,92,37))\r\nfamilyf = _from_rgb((240,179,115))\r\nentertainmentb = _from_rgb((128, 28, 3))\r\nentertainmentf = _from_rgb((247, 218, 210))\r\nhouseb = _from_rgb((123, 161, 227))\r\nhousef = _from_rgb((34, 55, 92))\r\n\r\nwhite = _from_rgb((255,255,255))\r\nblack = _from_rgb((0,0,0))\r\ngray = _from_rgb((172,170,165))\r\norange = _from_rgb((255,128,0))\r\nyellow = _from_rgb((255,255,0))\r\nblue = _from_rgb((0,100,255))\r\ngreen = _from_rgb((0,255,0))\r\nred = _from_rgb((255,0,0))\r\nbrown = _from_rgb((161,114,5))\r\n#\r\nbuttonFont = tkfont.Font(family=\"Times New Roman\", size=int(HEIGHT/1000*18))\r\noptionFont = tkfont.Font(family=\"Courier New\", size=int(HEIGHT/1000*12))\r\nchoiceFont = tkfont.Font(family=\"Verdana\", size = int(HEIGHT/1000*20))\r\ntextFont = tkfont.Font(family=\"Verdana\", size = int(HEIGHT/1000*15))\r\ntitleFont = tkfont.Font(family=\"Verdana\", size = int(HEIGHT/1000*25))\r\n#\r\ncombostyle = ttk.Style()\r\ncombostyle.theme_create('combostyle', parent='alt',\r\n settings = {'TCombobox':\r\n {'configure':\r\n {'selectbackground': actb,\r\n 'fieldbackground': yellow,\r\n 'background': brown\r\n }}}\r\n )\r\ncombostyle.theme_use('combostyle') \r\n#title of the main window\r\nmw.title('The Divide')\r\n#Size of the main window\r\nmw.geometry(str(HEIGHT)+\"x\"+str(HEIGHT)+\"+0+0\")\r\nmw.resizable(1,1)\r\n#Color of the main window\r\nback = Frame(master=mw,bg=bgc)\r\nback.pack_propagate(1)\r\nback.pack(fill=BOTH, expand=1)\r\n#default of button\r\nmw.option_add(\"*Button.Background\", butb)\r\nmw.option_add(\"*Button.Foreground\", butf)\r\n\r\n#Array\r\noperators=[]\r\noptions=[\"Hard Mode\",\"Normal Mode\",\"Easy Mode\"]\r\n\r\n#Bar Chart for indexes\r\ndef show_bar(index):\r\n global chafra\r\n chafra = Frame(bg=chab,height=HEIGHT/1000*300,width=HEIGHT/1000*800,master=mw)\r\n chafra.pack_propagate(1)\r\n chafra.pack()\r\n chafra.place(x=HEIGHT/1000*100,y=HEIGHT/1000*100)\r\n\r\n monfra = Frame(bg=barb,height=HEIGHT/1000*25,width=HEIGHT/1000*350,master=chafra)\r\n monfra.pack_propagate(1)\r\n monfra.pack()\r\n monfra.place(x=HEIGHT/1000*400,y=HEIGHT/1000*20)\r\n monf = Frame(bg=chab,height=HEIGHT/1000*30,width=HEIGHT/1000*100,master=chafra)\r\n monf.pack_propagate(1)\r\n monf.pack()\r\n monf.place(x=HEIGHT/1000*300,y=HEIGHT/1000*15)\r\n mon = Label(master=monf,text=\"Money\",font=textFont,bg=chab,fg=white)\r\n mon.pack()\r\n mon.place(x=0,y=0)\r\n\r\n heafra = Frame(bg=barb,height=HEIGHT/1000*25,width=HEIGHT/1000*350,master=chafra)\r\n heafra.pack_propagate(1)\r\n heafra.pack()\r\n heafra.place(x=HEIGHT/1000*400,y=HEIGHT/1000*80)\r\n monf = Frame(bg=chab,height=HEIGHT/1000*30,width=HEIGHT/1000*100,master=chafra)\r\n monf.pack_propagate(1)\r\n monf.pack()\r\n monf.place(x=HEIGHT/1000*300,y=HEIGHT/1000*75)\r\n mon = Label(master=monf,text=\"Income\",font=textFont,bg=chab,fg=white)\r\n mon.pack()\r\n mon.place(x=0,y=0)\r\n\r\n incfra = Frame(bg=barb,height=HEIGHT/1000*25,width=HEIGHT/1000*350,master=chafra)\r\n incfra.pack_propagate(1)\r\n incfra.pack()\r\n incfra.place(x=HEIGHT/1000*400,y=HEIGHT/1000*140)\r\n monf = Frame(bg=chab,height=HEIGHT/1000*30,width=HEIGHT/1000*100,master=chafra)\r\n monf.pack_propagate(1)\r\n monf.pack()\r\n monf.place(x=HEIGHT/1000*300,y=HEIGHT/1000*135)\r\n mon = Label(master=monf,text=\"Health\",font=textFont,bg=chab,fg=white)\r\n mon.pack()\r\n mon.place(x=0,y=0)\r\n\r\n hapfra = Frame(bg=barb,height=HEIGHT/1000*25,width=HEIGHT/1000*350,master=chafra)\r\n hapfra.pack_propagate(1)\r\n hapfra.pack()\r\n hapfra.place(x=HEIGHT/1000*400,y=HEIGHT/1000*200)\r\n monf = Frame(bg=chab,height=HEIGHT/1000*30,width=HEIGHT/1000*100,master=chafra)\r\n monf.pack_propagate(1)\r\n monf.pack()\r\n monf.place(x=HEIGHT/1000*300,y=HEIGHT/1000*195)\r\n mon = Label(master=monf,text=\"Happy\",font=textFont,bg=chab,fg=white)\r\n mon.pack()\r\n mon.place(x=0,y=0)\r\n\r\n edufra = Frame(bg=barb,height=HEIGHT/1000*25,width=HEIGHT/1000*350,master=chafra)\r\n edufra.pack_propagate(1)\r\n edufra.pack()\r\n edufra.place(x=HEIGHT/1000*400,y=HEIGHT/1000*260)\r\n monf = Frame(bg=chab,height=HEIGHT/1000*30,width=HEIGHT/1000*100,master=chafra)\r\n monf.pack_propagate(1)\r\n monf.pack()\r\n monf.place(x=HEIGHT/1000*300,y=HEIGHT/1000*255)\r\n mon = Label(master=monf,text=\"Eduction\",font=textFont,bg=chab,fg=white)\r\n mon.pack()\r\n mon.place(x=0,y=0)\r\n\r\n mnfra = Frame(bg=orange,height=HEIGHT/1000*25,width=HEIGHT/1000*index[0],master=chafra)\r\n mnfra.pack_propagate(1)\r\n mnfra.pack()\r\n mnfra.place(x=HEIGHT/1000*400,y=HEIGHT/1000*20)\r\n\r\n hafra = Frame(bg=yellow,height=HEIGHT/1000*25,width=HEIGHT/1000*index[1],master=chafra)\r\n hafra.pack_propagate(1)\r\n hafra.pack()\r\n hafra.place(x=HEIGHT/1000*400,y=HEIGHT/1000*80)\r\n\r\n icfra = Frame(bg=green,height=HEIGHT/1000*25,width=HEIGHT/1000*index[2],master=chafra)\r\n icfra.pack_propagate(1)\r\n icfra.pack()\r\n icfra.place(x=HEIGHT/1000*400,y=HEIGHT/1000*140)\r\n\r\n hpfra = Frame(bg=blue,height=HEIGHT/1000*25,width=HEIGHT/1000*index[3],master=chafra)\r\n hpfra.pack_propagate(1)\r\n hpfra.pack()\r\n hpfra.place(x=HEIGHT/1000*400,y=HEIGHT/1000*200)\r\n\r\n eufra = Frame(bg=red,height=HEIGHT/1000*25,width=HEIGHT/1000*index[4],master=chafra)\r\n eufra.pack_propagate(0)\r\n eufra.pack()\r\n eufra.place(x=HEIGHT/1000*400,y=HEIGHT/1000*260)\r\n\r\n if index[3]>250:\r\n Happy = PhotoImage(file=\"Faces/\" + faces[0])\r\n hapr = Label(chafra, image=Happy,bg=chab)\r\n hapr.image=Happy\r\n hapr.place(x=HEIGHT/1000*50,y=HEIGHT/1000*50)\r\n if 250>=index[3]>200:\r\n Nothing = PhotoImage(file=\"Faces/\" + faces[1])\r\n notr = Label(chafra, image=Nothing,bg=chab)\r\n notr.image=Nothing\r\n notr.place(x=HEIGHT/1000*50,y=HEIGHT/1000*50)\r\n if index[3]<=200:\r\n Hey = PhotoImage(file=\"Faces/\" + faces[2])\r\n heyr = Label(chafra, image=Hey,bg=chab)\r\n heyr.image=Hey\r\n heyr.place(x=HEIGHT/1000*50,y=HEIGHT/1000*50)\r\ndef update():\r\n global index\r\n index[0] = (Current_State.d['profile'][1])/1500000*350\r\n index[1] = (sum(i for i in Current_State.d['profile'][2]))/500000*350\r\n index[2] = (sum(i for i in Current_State.d['profile'][3]))/400*350\r\n index[3] = (sum(i for i in Current_State.d['profile'][4]))/400*350\r\n index[4] = (sum(i for i in Current_State.d['profile'][5]))/60*350\r\n return index\r\ndef gamedifbp(OPERATOR,s):\r\n global index\r\n s = OPERATOR.apply(s)\r\n update()\r\n show_bar(index)\r\ndef show_house(index):\r\n honf = Frame(bg=bgc,height=HEIGHT/1000*100,width=HEIGHT/1000*500,master=mw)\r\n honf.pack_propagate(0)\r\n honf.pack()\r\n honf.place(x=HEIGHT/1000*250,y=HEIGHT/1000*0)\r\n hon = Label(master=honf,text=index[5],font=titleFont,bg=bgc,fg=black)\r\n hon.pack()\r\n hon.place(x=HEIGHT/1000*0,y=HEIGHT/1000*0)\r\n\r\n \r\n \r\n\r\n#Game Mode Choose\r\n#PoorFamily\r\nPoorFamily = PhotoImage(file=\"Family/\" + families[1])\r\nporr = Label(mw, image=PoorFamily,bg=bgc)\r\nporr.pack(fill=BOTH,expand=1)\r\nporr.place(x=HEIGHT/1000*100,y=HEIGHT/1000*100)\r\nporf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*200,master=mw)\r\nporf.pack_propagate(0) \r\nporf.pack()\r\nporb = Button(porf, text=options[0], font = choiceFont,bg=chob,fg=chof,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: gamedifbp(P3.OPERATORS[0],Current_State))\r\nporf.place(x=HEIGHT/1000*100,y=HEIGHT/1000*300)\r\nporb.pack(fill=BOTH,expand=1)\r\n#MiddleFamily\r\nMiddleFamily = PhotoImage(file=\"Family/\" + families[0])\r\nmidr = Label(mw, image=MiddleFamily,bg=bgc)\r\nmidr.pack(fill=BOTH,expand=1)\r\nmidr.place(x=HEIGHT/1000*400,y=HEIGHT/1000*100)\r\nmidf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*200,master=mw)\r\nmidf.pack_propagate(0) \r\nmidf.pack()\r\nmidb = Button(midf, text=options[1], font = choiceFont,bg=chob,fg=chof,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: gamedifbp(P3.OPERATORS[1],Current_State))\r\nmidf.place(x=HEIGHT/1000*400,y=HEIGHT/1000*300)\r\nmidb.pack(fill=BOTH,expand=1)\r\n#RichFamily\r\nRichFamily = PhotoImage(file=\"Family/\" + families[2])\r\nricr = Label(mw, image=RichFamily,bg=bgc)\r\nricr.pack(fill=BOTH,expand=1)\r\nricr.place(x=HEIGHT/1000*700,y=HEIGHT/1000*100)\r\nriff = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*200,master=mw)\r\nriff.pack_propagate(0) \r\nriff.pack()\r\nrifb = Button(riff, text=options[2], font = choiceFont,bg=chob,fg=chof,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: gamedifbp(P3.OPERATORS[2],Current_State))\r\nriff.place(x=HEIGHT/1000*700,y=HEIGHT/1000*300)\r\nrifb.pack(fill=BOTH,expand=1)\r\n\r\n#Creates the list of buttons for the operators\r\ndef createButtonW(cat):\r\n\r\n #create the window\r\n nw = Toplevel(mw)\r\n nw.geometry(str(HEIGHT)+\"x\"+str(HEIGHT)+\"+0+0\")\r\n nw.resizable(1, 1)\r\n nw.overrideredirect(True)\t\r\n nw.title(cat)\r\n\r\n #create window frame\r\n back = Frame(master=nw,bg=bgc)\r\n back.pack_propagate(0)\r\n back.pack(fill=BOTH, expand=1)\r\n\r\n #quit button for frame\r\n qbf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*200,master=nw)\r\n qbf.pack_propagate(0) \r\n qbf.pack()\r\n qb = Button(qbf, text=\"Back\", font = optionFont, bg=brown,fg=white, \r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: nw.destroy())\r\n qbf.place(x=HEIGHT/1000*800, y=HEIGHT/1000*950)\r\n qb.pack(fill=BOTH, expand=1)\r\n\r\n\r\n winTitle = Label(back, text=cat, bg=bgc)\r\n winTitle.place(x=HEIGHT/1000*500, y=HEIGHT/1000*50)\r\n\r\n if cat == \"Family Profile\":\r\n pro_list = [\"Income\", \"Health\", \"Happiness\", \"Education\", \"Occupation\",\\\r\n \"Age\"]\r\n photo_size = [128, 128]\r\n Grid = Frame(height=HEIGHT/1000*photo_size[0]*5, width=HEIGHT/1000*photo_size[1]*7, master=back, bg=bgc)\r\n Grid.place(x=HEIGHT/1000*52, y=HEIGHT/1000*100)\r\n for i in range(6):\r\n frame = Frame(height=HEIGHT/1000*photo_size[0], width=HEIGHT/1000*photo_size[1], master=Grid, bg=bgc)\r\n frame.grid(row=0, column=i+1)\r\n frame.pack_propagate(False)\r\n label = Label(frame, text=pro_list[i], font=textFont, bg=bgc)\r\n label.pack(fill=BOTH, expand=1)\r\n\r\n for i in range(5):\r\n frame = Frame(height=HEIGHT/1000*photo_size[0], width=HEIGHT/1000*photo_size[1], master=Grid, bg=bgc)\r\n frame.grid(row=i, column=0)\r\n frame.pack_propagate(False)\r\n if i >= 1:\r\n label = Label(frame, image=family[i-1], font=textFont, bg=bgc)\r\n label.pack(fill=BOTH, expand=1)\r\n\r\n for ind in range(4):\r\n counter = 1\r\n for info in [2, 3, 4, 5, 6, 8]:\r\n frame = Frame(height=HEIGHT/1000*photo_size[0], width=HEIGHT/1000*photo_size[1], master=Grid, bg=bgc)\r\n frame.grid(row=ind+1, column=counter)\r\n frame.pack_propagate(False)\r\n label = Label(frame, text=Current_State.d['profile'][info][ind], font=textFont, bg=bgc)\t\r\n label.pack(fill=BOTH, expand=1)\r\n counter += 1\r\n\r\n def bp(operator, s):\r\n global index\r\n s = operator.apply(s)\r\n show_bar(update())\r\n show_house(update())\r\n nw.destroy()\r\n #add update chart option\r\n return\r\n\r\n if cat == \"Insurance\":\r\n Iop = P3.OPERATORS[39:42]\r\n af = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*250, master=back)\r\n af.pack_propagate(False)\r\n if Iop[0].is_applicable(Current_State):\r\n ab = Button(af, text=\"plan 1\", font=buttonFont,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: bp(Iop[0], Current_State))\r\n else:\r\n ab = Button(af, text=\"plan 1\", font=buttonFont,\r\n state=DISABLED)\r\n #add ,command=lambda: bp(1)\r\n af.place(x=HEIGHT/1000*100, y=HEIGHT/1000*300)\r\n ab.pack(fill=BOTH, expand=1)\r\n\r\n bf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*250, master=back)\r\n bf.pack_propagate(False)\r\n if Iop[1].is_applicable(Current_State):\r\n bb = Button(bf, text=\"plan 2\", font=buttonFont,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: bp(Iop[1], Current_State))\r\n else:\r\n bb = Button(bf, text=\"plan 2\", font=buttonFont,\r\n state=DISABLED)\r\n \r\n #add ,command=lambda: bp(1)\r\n bf.place(x=HEIGHT/1000*375, y=HEIGHT/1000*300)\r\n bb.pack(fill=BOTH, expand=1)\r\n\r\n cf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*250, master=back)\r\n cf.pack_propagate(False)\r\n if Iop[2].is_applicable(Current_State):\r\n cb = Button(cf, text=\"plan 3\", font=buttonFont,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: bp(Iop[2], Current_State))\r\n else:\r\n cb = Button(cf, text=\"plan 3\", font=buttonFont,\r\n state=DISABLED)\r\n \r\n #add ,command=lambda: bp(1)\r\n cf.place(x=HEIGHT/1000*650, y=HEIGHT/1000*300)\r\n cb.pack(fill=BOTH, expand=1)\r\n\r\n if cat == \"Entertainment\":\r\n Eop = P3.OPERATORS[20:25]\r\n\r\n\r\n park = PhotoImage(file=\"Entertainments/\" + entertainments[0])\r\n r1 = Label(master=back, image=park,bg=bgc)\r\n r1.image=park\r\n r1.pack(fill=BOTH,expand=1)\r\n r1.place(x=HEIGHT/1000*75,y=HEIGHT/1000*130)\r\n parkf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*250, master=back)\r\n parkf.pack_propagate(False)\r\n if Eop[0].is_applicable(Current_State):\r\n parkb = Button(parkf, text=\"Park\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n activebackground=actb, activeforeground=actf, \r\n command=lambda: bp(Eop[0], Current_State))\r\n else:\r\n parkb = Button(parkf, text=\"Park\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n state=DISABLED)\r\n parkf.place(x=HEIGHT/1000*100, y=HEIGHT/1000*350)\r\n parkb.pack(fill=BOTH, expand=1)\r\n\r\n\r\n circus = PhotoImage(file=\"Entertainments/\" + entertainments[1])\r\n r2 = Label(master=back, image=circus,bg=bgc)\r\n r2.image=circus\r\n r2.pack(fill=BOTH,expand=1)\r\n r2.place(x=HEIGHT/1000*75,y=HEIGHT/1000*415)\r\n circusf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*250, master=back)\r\n circusf.pack_propagate(False)\r\n if Eop[1].is_applicable(Current_State):\r\n circusb = Button(circusf, text=\"Circus\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: bp(Eop[1], Current_State))\r\n else:\r\n circusb = Button(circusf, text=\"Circus\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n state=DISABLED)\r\n circusf.place(x=HEIGHT/1000*100, y=HEIGHT/1000*650)\r\n circusb.pack(fill=BOTH, expand=1)\r\n\r\n\r\n\r\n movie = PhotoImage(file=\"Entertainments/\" + entertainments[2])\r\n r3 = Label(master=back, image=movie,bg=bgc)\r\n r3.image=movie\r\n r3.pack(fill=BOTH,expand=1)\r\n r3.place(x=HEIGHT/1000*75,y=HEIGHT/1000*700)\r\n moviesf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*250, master=back)\r\n moviesf.pack_propagate(False)\r\n if Eop[2].is_applicable(Current_State):\r\n moviesb = Button(moviesf, text=\"Movies\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: bp(Eop[2], Current_State))\r\n else:\r\n moviesb = Button(moviesf, text=\"Movies\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n state=DISABLED)\r\n moviesf.place(x=HEIGHT/1000*100, y=HEIGHT/1000*950)\r\n moviesb.pack(fill=BOTH, expand=1)\r\n\r\n\r\n apark = PhotoImage(file=\"Entertainments/\" + entertainments[3])\r\n r4 = Label(master=back, image=apark,bg=bgc)\r\n r4.image=apark\r\n r4.pack(fill=BOTH,expand=1)\r\n r4.place(x=HEIGHT/1000*575,y=HEIGHT/1000*135)\r\n amusementf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*250, master=back)\r\n amusementf.pack_propagate(False)\r\n if Eop[3].is_applicable(Current_State):\r\n amusementb = Button(amusementf, text=\"Amusement Park\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: bp(Eop[3], Current_State))\r\n else:\r\n amusementb = Button(amusementf, text=\"Amusement Park\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n state=DISABLED)\r\n amusementf.place(x=HEIGHT/1000*600, y=HEIGHT/1000*350)\r\n amusementb.pack(fill=BOTH, expand=1)\r\n\r\n\r\n vacation = PhotoImage(file=\"Entertainments/\" + entertainments[4])\r\n r5 = Label(master=back, image=vacation,bg=bgc)\r\n r5.image=vacation\r\n r5.pack(fill=BOTH,expand=1)\r\n r5.place(x=HEIGHT/1000*625,y=HEIGHT/1000*400)\r\n vf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*250, master=back)\r\n vf.pack_propagate(False)\r\n if Eop[4].is_applicable(Current_State):\r\n vb = Button(vf, text=\"Vacation Abroad\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: bp(Eop[4], Current_State))\r\n else:\r\n vb = Button(vf, text=\"Vacation Abroad\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n state=DISABLED)\r\n vf.place(x=HEIGHT/1000*600, y=HEIGHT/1000*650)\r\n vb.pack(fill=BOTH, expand=1)\r\n\r\n def cbp(comboBox, s):\r\n option = comboBox.get()\r\n print(option)\r\n op = 0\r\n for i in P3.OPERATORS:\r\n if i.name == option:\r\n op = i\r\n op.apply(s)\r\n show_bar(update())\r\n show_house(update())\r\n nw.destroy()\r\n return\r\n\r\n\r\n if cat == \"Shop\":\r\n Wop = P3.OPERATORS[24:33]\r\n pro_list = [\"Grocery\"]\r\n photo_size = [128, 128]\r\n Grid = Frame(height=HEIGHT/1000*photo_size[0]*5, width=HEIGHT/1000*photo_size[1]*7, master=back, bg=bgc)\r\n Grid.place(x=HEIGHT/1000*52, y=HEIGHT/1000*100)\r\n for i in range(1):\r\n frame = Frame(height=HEIGHT/1000*photo_size[0], width=HEIGHT/1000*photo_size[1], master=Grid, bg=bgc)\r\n frame.grid(row=0, column=i+1)\r\n frame.pack_propagate(False)\r\n label = Label(frame, text=pro_list[i], font=textFont, bg=bgc)\r\n label.pack(fill=BOTH, expand=1)\r\n\r\n comboBoxes = []\r\n\r\n for i in range(5):\r\n frame = Frame(height=HEIGHT/1000*photo_size[0], width=HEIGHT/1000*photo_size[1]*3, master=Grid, bg=bgc)\r\n frame.grid(row=i, column=0)\r\n frame.pack_propagate(False)\r\n if i >= 1:\r\n label = Label(frame, image=family[i-1], font=textFont, bg=bgc)\r\n label.pack(fill=BOTH, expand=1) \r\n frame = Frame(height=HEIGHT/1000*photo_size[0], width=HEIGHT/1000*photo_size[1], master=Grid, bg=bgc)\r\n frame.grid(row=i, column=1)\r\n frame.pack_propagate(False)\r\n ind = []\r\n for j in Wop:\r\n if j.is_applicable(Current_State):\r\n ind.append(j.name)\r\n variable = ttk.Combobox(values=ind, master=frame)\r\n variable.bind('', on_combo_configure)\r\n variable.place(x=0, y=64)\r\n def sob(comboBoxes, Grid, back):\r\n counter = 0\r\n for i in comboBoxes:\r\n if i.get() != \"\":\r\n counter += 1\r\n\r\n if counter > 1 or counter == 0:\r\n label = Label(back, text=\"You need to choose only one option\")\r\n label.pack()\r\n else:\r\n show_buttons(comboBoxes, Grid)\r\n\r\n\r\n showOptions = Button(back, text=\"Display Apply Button\", font=optionFont, bg=brown, fg=white,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: sob(comboBoxes, Grid, back))\r\n showOptions.pack()\r\n def show_buttons(comboBoxes, Grid):\r\n for i in range(5):\r\n frame = Frame(height=HEIGHT / 1000 * photo_size[0], width=HEIGHT / 1000 * photo_size[1] * 3, master=Grid,\r\n bg=bgc)\r\n frame.grid(row=i, column=2)\r\n frame.pack_propagate(False)\r\n if i >= 1 and comboBoxes[i-1].get() != \"\":\r\n apButton = Button(frame, text=\"Apply\", font=optionFont, bg=brown, fg=white,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: cbp(comboBoxes[i-1], Current_State))\r\n apButton.place(x=32, y=56)\r\n elif i >= 1 and comboBoxes[i-1].get() == \"\":\r\n apButton = Button(frame, text=\"Apply\", font=optionFont, bg=brown, fg=white, state=DISABLED)\r\n apButton.place(x=32, y=56)\r\n\r\n\r\n\r\n if cat == \"Schooling\":\r\n Wop = [P3.OPERATORS[11:17],P3.OPERATORS[18:24],[],[]]\r\n pro_list = [\"Job\"]\r\n photo_size = [128, 128]\r\n Grid = Frame(height=HEIGHT/1000*photo_size[0]*5, width=HEIGHT/1000*photo_size[1]*7, master=back, bg=bgc)\r\n Grid.place(x=HEIGHT/1000*52, y=HEIGHT/1000*100)\r\n for i in range(1):\r\n frame = Frame(height=HEIGHT/1000*photo_size[0], width=HEIGHT/1000*photo_size[1], master=Grid, bg=bgc)\r\n frame.grid(row=0, column=i+1)\r\n frame.pack_propagate(False)\r\n label = Label(frame, text=pro_list[i], font=textFont, bg=bgc)\r\n label.pack(fill=BOTH, expand=1)\r\n comboBoxes = []\r\n for i in range(5):\r\n frame = Frame(height=HEIGHT/1000*photo_size[0], width=HEIGHT/1000*photo_size[1]*3, master=Grid, bg=bgc)\r\n frame.grid(row=i, column=0)\r\n frame.pack_propagate(False)\r\n if i >= 1:\r\n label = Label(frame, image=family[i-1], font=textFont, bg=bgc)\r\n label.pack(fill=BOTH, expand=1)\r\n frame = Frame(height=HEIGHT/1000*photo_size[0], width=HEIGHT/1000*photo_size[1], master=Grid, bg=bgc)\r\n frame.grid(row=i, column=1)\r\n frame.pack_propagate(False)\r\n ind = []\r\n for j in Wop[i-1]:\r\n if j.is_applicable(Current_State):\r\n ind.append(j.name)\r\n variable = ttk.Combobox(values=ind, master=frame)\r\n variable.bind('', on_combo_configure)\r\n comboBoxes.append(variable)\r\n variable.place(x=0, y=64)\r\n\r\n\r\n for i in range(5):\r\n frame = Frame(height=HEIGHT / 1000 * photo_size[0], width=HEIGHT / 1000 * photo_size[1] * 3, master=Grid,\r\n bg=bgc)\r\n frame.grid(row=i, column=2)\r\n frame.pack_propagate(False)\r\n if i >= 1 and comboBoxes[i-1].get() != \"\":\r\n apButton = Button(frame, text=\"Apply\", font=optionFont, bg=brown, fg=white,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: cbp(comboBoxes[i-1], Current_State))\r\n apButton.place(x=32, y=56)\r\n elif i >= 1 and comboBoxes[i-1].get() == \"\":\r\n apButton = Button(frame, text=\"Apply\", font=optionFont, bg=brown, fg=white, state=DISABLED)\r\n apButton.place(x=32, y=56)\r\n\r\n\r\n\r\n\r\n if cat == \"Work Place\":\r\n\r\n Who = P3.OPERATORS[3:7]\r\n What = P3.OPERATORS[11:20]\r\n\r\n def father(what,s):\r\n for i in range(0,9):\r\n parkf = Frame(height=HEIGHT/1000*128, width=HEIGHT/1000*128, master=back)\r\n parkf.pack_propagate(False)\r\n if what[i].is_applicable(s):\r\n parkb = Button(parkf, image=job[i], background=bgc, \r\n command=lambda: bp(what[i], s))\r\n else:\r\n parkb = Button(parkf, image=job[i], font=buttonFont,\r\n state=DISABLED)\r\n parkf.place(x=HEIGHT/1000*loop_by_three(i)[0], y=HEIGHT/1000*loop_by_three(i)[1])\r\n parkb.pack(fill=BOTH, expand=1) \r\n faf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*130, master=back)\r\n faf.pack_propagate(False)\r\n if Who[0].is_applicable(Current_State):\r\n fab = Button(faf, text=\"Father\", font=buttonFont,bg=familyb,fg=familyf,\r\n activebackground=actb, activeforeground=actf, \r\n command=lambda: father(What,Current_State) )\r\n else:\r\n fab = Button(maf, text=\"Father\", font=buttonFont,bg=familyb,fg=familyf,\r\n state=DISABLED)\r\n faf.place(x=HEIGHT/1000*96, y=HEIGHT/1000*846)\r\n fab.pack(fill=BOTH, expand=1)\r\n\r\n\r\n def mother(what,s):\r\n for i in range(0,9):\r\n parkf = Frame(height=HEIGHT/1000*128, width=HEIGHT/1000*128, master=back)\r\n parkf.pack_propagate(False)\r\n if what[i].is_applicable(s):\r\n parkb = Button(parkf, image=job[i+9], background=bgc, \r\n command=lambda: bp(what[i], s))\r\n else:\r\n parkb = Button(parkf, image=job[i+9], font=buttonFont,\r\n state=DISABLED)\r\n parkf.place(x=HEIGHT/1000*loop_by_three(i)[0], y=HEIGHT/1000*loop_by_three(i)[1])\r\n parkb.pack(fill=BOTH, expand=1) \r\n maf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*130, master=back)\r\n maf.pack_propagate(False)\r\n if Who[1].is_applicable(Current_State):\r\n mab = Button(maf, text=\"Mother\", font=buttonFont,bg=familyb,fg=familyf,\r\n activebackground=actb, activeforeground=actf, \r\n command=lambda: father(What,Current_State) )\r\n else:\r\n mab = Button(maf, text=\"Mother\", font=buttonFont,bg=familyb,fg=familyf,\r\n state=DISABLED)\r\n maf.place(x=HEIGHT/1000*322, y=HEIGHT/1000*846)\r\n mab.pack(fill=BOTH, expand=1)\r\n\r\n\r\n def brother(what,s):\r\n for i in range(0,9):\r\n parkf = Frame(height=HEIGHT/1000*128, width=HEIGHT/1000*128, master=back)\r\n parkf.pack_propagate(False)\r\n if what[i].is_applicable(s):\r\n parkb = Button(parkf, image=job[i], background=bgc, \r\n command=lambda: bp(what[i], s))\r\n else:\r\n parkb = Button(parkf, image=job[i], font=buttonFont,\r\n state=DISABLED)\r\n parkf.place(x=HEIGHT/1000*loop_by_three(i)[0], y=HEIGHT/1000*loop_by_three(i)[1])\r\n parkb.pack(fill=BOTH, expand=1) \r\n brf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*130, master=back)\r\n brf.pack_propagate(False)\r\n if Who[0].is_applicable(Current_State):\r\n brb = Button(brf, text=\"Brother\", font=buttonFont,bg=familyb,fg=familyf,\r\n activebackground=actb, activeforeground=actf, \r\n command=lambda: father(What,Current_State) )\r\n else:\r\n brb = Button(brf, text=\"Brother\", font=buttonFont,bg=familyb,fg=familyf,\r\n state=DISABLED)\r\n brf.place(x=HEIGHT/1000*548, y=HEIGHT/1000*846)\r\n brb.pack(fill=BOTH, expand=1)\r\n\r\n\r\n def sister(what,s):\r\n for i in range(0,9):\r\n parkf = Frame(height=HEIGHT/1000*128, width=HEIGHT/1000*128, master=back)\r\n parkf.pack_propagate(False)\r\n if what[i].is_applicable(s):\r\n parkb = Button(parkf, image=job[i], background=bgc, \r\n command=lambda: bp(what[i], s))\r\n else:\r\n parkb = Button(parkf, image=job[i], font=buttonFont,\r\n state=DISABLED)\r\n parkf.place(x=HEIGHT/1000*loop_by_three(i)[0], y=HEIGHT/1000*loop_by_three(i)[1])\r\n parkb.pack(fill=BOTH, expand=1) \r\n sif = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*130, master=back)\r\n sif.pack_propagate(False)\r\n if Who[0].is_applicable(Current_State):\r\n sib = Button(sif, text=\"Sister\", font=buttonFont,bg=familyb,fg=familyf,\r\n activebackground=actb, activeforeground=actf, \r\n command=lambda: father(What,Current_State) )\r\n else:\r\n sib = Button(sif, text=\"Sister\", font=buttonFont,bg=familyb,fg=familyf,\r\n state=DISABLED)\r\n sif.place(x=HEIGHT/1000*774, y=HEIGHT/1000*846)\r\n sib.pack(fill=BOTH, expand=1)\r\n\r\n \r\n\r\n if cat == \"Home\":\r\n Eop = P3.OPERATORS[34:39]\r\n\r\n tcf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*300, master=back)\r\n tcf.pack_propagate(False)\r\n if Eop[0].is_applicable(Current_State):\r\n tcb = Button(tcf, text=\"Tent City\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n activebackground=actb, activeforeground=actf, \r\n command=lambda: bp(Eop[0], Current_State))\r\n else:\r\n tcb = Button(tcf, text=\"Tent City\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n state=DISABLED)\r\n tcf.place(x=HEIGHT/1000*100, y=HEIGHT/1000*250)\r\n tcb.pack(fill=BOTH, expand=1)\r\n\r\n trf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*300, master=back)\r\n trf.pack_propagate(False)\r\n if Eop[1].is_applicable(Current_State):\r\n trb = Button(trf, text=\"Trailer\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: bp(Eop[1], Current_State))\r\n else:\r\n trb = Button(trf, text=\"Trailer\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n state=DISABLED)\r\n\r\n trf.place(x=HEIGHT/1000*350, y=HEIGHT/1000*500)\r\n trb.pack(fill=BOTH, expand=1)\r\n\r\n apf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*300, master=back)\r\n apf.pack_propagate(False)\r\n if Eop[2].is_applicable(Current_State):\r\n apb = Button(apf, text=\"Apartment\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: bp(Eop[2], Current_State))\r\n else:\r\n apb = Button(apf, text=\"Apartment\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n state=DISABLED)\r\n apf.place(x=HEIGHT/1000*100, y=HEIGHT/1000*750)\r\n apb.pack(fill=BOTH, expand=1)\r\n\r\n dpf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*300, master=back)\r\n dpf.pack_propagate(False)\r\n if Eop[3].is_applicable(Current_State):\r\n dpb = Button(dpf, text=\"Duplex\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: bp(Eop[3], Current_State))\r\n else:\r\n dpb = Button(dpf, text=\"Duplex\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n state=DISABLED)\r\n\r\n dpf.place(x=HEIGHT/1000*600, y=HEIGHT/1000*250)\r\n dpb.pack(fill=BOTH, expand=1)\r\n\r\n mnf = Frame(height=HEIGHT/1000*50, width=HEIGHT/1000*300, master=back)\r\n mnf.pack_propagate(False)\r\n if Eop[4].is_applicable(Current_State):\r\n mnb = Button(mnf, text=\"Mansion\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: bp(Eop[4], Current_State))\r\n else:\r\n mnb = Button(mnf, text=\"Mansion\", font=buttonFont,bg=entertainmentb,fg=entertainmentf,\r\n state=DISABLED)\r\n mnf.place(x=HEIGHT/1000*600, y=HEIGHT/1000*750)\r\n mnb.pack(fill=BOTH, expand=1)\r\n\r\n \r\n#Insurance\r\n\r\ninsf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*300,master=mw)\r\ninsf.pack_propagate(0) \r\ninsf.pack()\r\ninsb = Button(insf, text=\"Insurance\", font = buttonFont,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: createButtonW(\"Insurance\"))\r\ninsf.place(x=HEIGHT/1000*600,y=HEIGHT/1000*500)\r\ninsb.pack(fill=BOTH,expand=1)\r\n\r\n#Entertainment\r\nentf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*300,master=mw)\r\nentf.pack_propagate(0) \r\nentf.pack()\r\nentb = Button(entf, text=\"Entertainment\", font = buttonFont,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: createButtonW(\"Entertainment\"))\r\nentf.place(x=HEIGHT/1000*100,y=HEIGHT/1000*500)\r\nentb.pack(fill=BOTH,expand=1)\r\n#Shop\r\nshof = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*300,master=mw)\r\nshof.pack_propagate(0) \r\nshof.pack()\r\nshob = Button(shof, text=\"Shop\", font = buttonFont,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: createButtonW(\"Shop\"))\r\nshof.place(x=HEIGHT/1000*100,y=HEIGHT/1000*600)\r\nshob.pack(fill=BOTH,expand=1)\r\n#Schooling\r\nschf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*300,master=mw)\r\nschf.pack_propagate(0)\r\nschf.pack()\r\nschb = Button(schf, text=\"Schooling\", font = buttonFont,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: createButtonW(\"Schooling\"))\r\nschf.place(x=HEIGHT/1000*600,y=HEIGHT/1000*600)\r\nschb.pack(fill=BOTH,expand=1)\r\n#Family Profile\r\n\r\nfamf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*300,master=mw)\r\nfamf.pack_propagate(0) \r\nfamf.pack()\r\nfamb = Button(famf, text=\"Family Profile\", font = buttonFont,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: createButtonW(\"Family Profile\"))\r\nfamf.place(x=HEIGHT/1000*100,y=HEIGHT/1000*800)\r\nfamb.pack(fill=BOTH,expand=1)\r\n#Home\r\nhomf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*300,master=mw)\r\nhomf.pack_propagate(0) \r\nhomf.pack()\r\nhomb = Button(homf, text=\"Home\", font = buttonFont,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: createButtonW(\"Home\"))\r\nhomf.place(x=HEIGHT/1000*600,y=HEIGHT/1000*700)\r\nhomb.pack(fill=BOTH,expand=1)\r\n#Work Place\r\nworf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*300,master=mw)\r\nworf.pack_propagate(0) \r\nworf.pack()\r\nworb = Button(worf, text=\"Work Place\", font = buttonFont,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: createButtonW(\"Work Place\"))\r\nworf.place(x=HEIGHT/1000*100,y=HEIGHT/1000*700)\r\nworb.pack(fill=BOTH,expand=1)\r\n#Next Turn\r\n\r\ndef nextTurn(s):\r\n s = P3.OPERATORS[42].apply(s)\r\n show_bar(update())\r\n\r\nnexf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*300,master=mw)\r\nnexf.pack_propagate(0)\r\nnexf.pack()\r\nnexb = Button(nexf, text=\"Next Turn\", font = buttonFont,\r\n activebackground=actb, activeforeground=actf,\r\n command=lambda: nextTurn(Current_State))\r\nnexf.place(x=HEIGHT/1000*600,y=HEIGHT/1000*800)\r\nnexb.pack(fill=BOTH,expand=1)\r\n#Exit\r\nexif = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*300,master=mw)\r\nexif.pack_propagate(0) \r\nexif.pack()\r\nexib = Button(exif, text=\"Exit\", font = optionFont,\r\n bg=gray, fg=white, command=quit)\r\nexif.place(x=HEIGHT/1000*600,y=HEIGHT/1000*900)\r\nexib.pack(fill=BOTH,expand=1)\r\n#Option\r\noptf = Frame(height=HEIGHT/1000*50,width=HEIGHT/1000*300,master=mw)\r\noptf.pack_propagate(0) \r\noptf.pack()\r\noptb = Button(optf, text=\"Option\", font = optionFont,\r\n bg=gray, fg=white, command=lambda: createFoolW(\"fool\"))\r\noptf.place(x=HEIGHT/1000*100,y=HEIGHT/1000*900)\r\noptb.pack(fill=BOTH,expand=1)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nmw.mainloop()\r\n\r\n\r\n","sub_path":"P3_SIZEABLE.py","file_name":"P3_SIZEABLE.py","file_ext":"py","file_size_in_byte":42461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"635961619","text":"\"\"\"\n* EFREI - Licence 1 - Année 2020-2021 Semestre 2\n* Programmation en Python\n* PROJET Transverse \"Tanks\"\n* Auteurs :\n - Émilia JOVANOVIC\n - Chelsie LOUIS\n - Clément LE STRAT\n - Matthieu HAVEL\n\n* Descriptif du module :\n Gestion de chargement des différentes ressources nécessaires au jeu.\n Ces fonctions permettent de charger des images, des backgrounds, et des fontes en fonction des répertoires par défaut.\n\"\"\"\n\nimport os\nimport pygame\nimport config\n\n\ndef load_images(image_name):\n \"\"\"\n Fonction qui va charger une image depuis le path par défaut\n\n :param image_name: Le nom de l'image à charger\n :type image_name: str\n :return: Image avec son canal alpha pour gérer la transparence\n :rtype: pygame.Surface\n \"\"\"\n\n full_path = os.path.join(config.IMAGES_PATH, image_name)\n try:\n image = pygame.image.load(full_path)\n # Gestion du canal alpha de l'image pour gérer la transparence\n if image.get_alpha is None:\n image = image.convert()\n else:\n image = image.convert_alpha()\n except pygame.error as message:\n # Gestion des erreurs\n raise SystemExit(message)\n\n return image\n\n\ndef load_background(image_name, width, height):\n \"\"\"\n Fonction qui permet de charger un background à partir du path par défaut\n\n :param image_name: Le nom de l'image à charger\n :type image_name: str\n :param width: La largeur de l'image désirée en sortie\n :type width: int\n :param height: La hauteur de l'image désirée en sortie\n :type height: int\n :return: Image convertie à la taille demandée\n :rtype: pygame.Surface\n \"\"\"\n\n try:\n background = pygame.image.load(os.path.join(config.BACKGROUNDS_PATH, image_name))\n except pygame.error as message:\n raise SystemExit(message)\n\n # L'image s'affichera en fonction de la largeur et de la hauteur demandée\n return pygame.transform.scale(background, (width, height))\n\n\ndef load_sound(sound_name):\n \"\"\"\n Fonction qui permet de charger un son dans le répertoire par défaut\n\n :param sound_name: Nom du fichier à charger\n :type sound_name: str\n :return: Le son chargé grâce à pygame\n :rtype: pygame.mixer.Sound\n \"\"\"\n\n try:\n full_path = os.path.join(config.SOUNDS_PATH, sound_name)\n sound = pygame.mixer.Sound(full_path)\n except FileNotFoundError as message:\n raise SystemExit(f\"{sound_name} : {message}\")\n return sound\n\n\ndef get_fonts(font_name):\n \"\"\"\n Fonction qui renvoie le path vers la fonte passée en paramètre. La fonte n'est pas chargée par cette fonction.\n\n :param font_name: Nom du fichier de fonte\n :type font_name: str\n :return: Le path complet vers la fonte\n :rtype: str\n \"\"\"\n\n font = os.path.join(config.FONTS_PATH, font_name)\n if not os.path.exists(font):\n raise SystemExit(\"Fichier font inexistant\")\n\n return os.path.join(config.FONTS_PATH, font_name)\n\n\ndef load_animations(nombre_anim, racine_anim, extension_image):\n \"\"\"\n Fonction qui permet de charger une liste d'images afin de pouvoir générer une animation par la suite. Elle renvoie\n un tableau des images à animer.\n\n :param nombre_anim: Le nombre d'image dans l'animation finale, et donc le nombre d'images à charger.\n :type nombre_anim: int\n :param racine_anim: Nom de base des images à charger.\n :type racine_anim: str\n :param extension_image: Externsions des images à charger.\n :type extension_image: str\n :return: Liste des images chargées.\n :rtype: list\n \"\"\"\n\n animations = []\n\n for i in range(nombre_anim):\n # On cherche les images racine_anim + un chiffre sur deux caractères + . + extension\n # Exemple: racine_anim = 'Explosion', i=00 à 09, . extension = 'png'\n animations.append(load_images(f\"{racine_anim}{i:02}.{extension_image}\"))\n\n return animations\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"574460808","text":"# coding: utf-8\n\n\"\"\"\n Collibra Data Governance Center Core API\n\n

    The Core REST API allows you to create your own integrations with Collibra Data Governance Center.

    Create custom applications to help users get access to the right data.

    # noqa: E501\n\n The version of the OpenAPI document: 2.0\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom collibra_core.configuration import Configuration\n\n\nclass ChangeMappingRequest(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'id': 'str',\n 'external_system_id': 'str',\n 'external_entity_id': 'str',\n 'external_entity_url': 'str',\n 'description': 'str',\n 'mapped_resource_id': 'str',\n 'last_sync_date': 'int',\n 'sync_action': 'str'\n }\n\n attribute_map = {\n 'id': 'id',\n 'external_system_id': 'externalSystemId',\n 'external_entity_id': 'externalEntityId',\n 'external_entity_url': 'externalEntityUrl',\n 'description': 'description',\n 'mapped_resource_id': 'mappedResourceId',\n 'last_sync_date': 'lastSyncDate',\n 'sync_action': 'syncAction'\n }\n\n def __init__(self, id=None, external_system_id=None, external_entity_id=None, external_entity_url=None, description=None, mapped_resource_id=None, last_sync_date=None, sync_action=None, local_vars_configuration=None): # noqa: E501\n \"\"\"ChangeMappingRequest - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._id = None\n self._external_system_id = None\n self._external_entity_id = None\n self._external_entity_url = None\n self._description = None\n self._mapped_resource_id = None\n self._last_sync_date = None\n self._sync_action = None\n self.discriminator = None\n\n self.id = id\n if external_system_id is not None:\n self.external_system_id = external_system_id\n if external_entity_id is not None:\n self.external_entity_id = external_entity_id\n if external_entity_url is not None:\n self.external_entity_url = external_entity_url\n if description is not None:\n self.description = description\n if mapped_resource_id is not None:\n self.mapped_resource_id = mapped_resource_id\n if last_sync_date is not None:\n self.last_sync_date = last_sync_date\n if sync_action is not None:\n self.sync_action = sync_action\n\n @property\n def id(self):\n \"\"\"Gets the id of this ChangeMappingRequest. # noqa: E501\n\n The ID of the mapping to be changed. Silently ignored if the ID is provided as path parameter of the request. # noqa: E501\n\n :return: The id of this ChangeMappingRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"Sets the id of this ChangeMappingRequest.\n\n The ID of the mapping to be changed. Silently ignored if the ID is provided as path parameter of the request. # noqa: E501\n\n :param id: The id of this ChangeMappingRequest. # noqa: E501\n :type: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and id is None: # noqa: E501\n raise ValueError(\"Invalid value for `id`, must not be `None`\") # noqa: E501\n\n self._id = id\n\n @property\n def external_system_id(self):\n \"\"\"Gets the external_system_id of this ChangeMappingRequest. # noqa: E501\n\n The ID of the external system that the mapped resource belongs to. # noqa: E501\n\n :return: The external_system_id of this ChangeMappingRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._external_system_id\n\n @external_system_id.setter\n def external_system_id(self, external_system_id):\n \"\"\"Sets the external_system_id of this ChangeMappingRequest.\n\n The ID of the external system that the mapped resource belongs to. # noqa: E501\n\n :param external_system_id: The external_system_id of this ChangeMappingRequest. # noqa: E501\n :type: str\n \"\"\"\n if (self.local_vars_configuration.client_side_validation and\n external_system_id is not None and len(external_system_id) > 36):\n raise ValueError(\"Invalid value for `external_system_id`, length must be less than or equal to `36`\") # noqa: E501\n if (self.local_vars_configuration.client_side_validation and\n external_system_id is not None and len(external_system_id) < 1):\n raise ValueError(\"Invalid value for `external_system_id`, length must be greater than or equal to `1`\") # noqa: E501\n\n self._external_system_id = external_system_id\n\n @property\n def external_entity_id(self):\n \"\"\"Gets the external_entity_id of this ChangeMappingRequest. # noqa: E501\n\n The external ID of the mapped resource. # noqa: E501\n\n :return: The external_entity_id of this ChangeMappingRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._external_entity_id\n\n @external_entity_id.setter\n def external_entity_id(self, external_entity_id):\n \"\"\"Sets the external_entity_id of this ChangeMappingRequest.\n\n The external ID of the mapped resource. # noqa: E501\n\n :param external_entity_id: The external_entity_id of this ChangeMappingRequest. # noqa: E501\n :type: str\n \"\"\"\n if (self.local_vars_configuration.client_side_validation and\n external_entity_id is not None and len(external_entity_id) > 255):\n raise ValueError(\"Invalid value for `external_entity_id`, length must be less than or equal to `255`\") # noqa: E501\n if (self.local_vars_configuration.client_side_validation and\n external_entity_id is not None and len(external_entity_id) < 1):\n raise ValueError(\"Invalid value for `external_entity_id`, length must be greater than or equal to `1`\") # noqa: E501\n\n self._external_entity_id = external_entity_id\n\n @property\n def external_entity_url(self):\n \"\"\"Gets the external_entity_url of this ChangeMappingRequest. # noqa: E501\n\n The external URL of the mapped resource. # noqa: E501\n\n :return: The external_entity_url of this ChangeMappingRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._external_entity_url\n\n @external_entity_url.setter\n def external_entity_url(self, external_entity_url):\n \"\"\"Sets the external_entity_url of this ChangeMappingRequest.\n\n The external URL of the mapped resource. # noqa: E501\n\n :param external_entity_url: The external_entity_url of this ChangeMappingRequest. # noqa: E501\n :type: str\n \"\"\"\n if (self.local_vars_configuration.client_side_validation and\n external_entity_url is not None and len(external_entity_url) > 255):\n raise ValueError(\"Invalid value for `external_entity_url`, length must be less than or equal to `255`\") # noqa: E501\n if (self.local_vars_configuration.client_side_validation and\n external_entity_url is not None and len(external_entity_url) < 1):\n raise ValueError(\"Invalid value for `external_entity_url`, length must be greater than or equal to `1`\") # noqa: E501\n\n self._external_entity_url = external_entity_url\n\n @property\n def description(self):\n \"\"\"Gets the description of this ChangeMappingRequest. # noqa: E501\n\n The description of the mapped resource. # noqa: E501\n\n :return: The description of this ChangeMappingRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._description\n\n @description.setter\n def description(self, description):\n \"\"\"Sets the description of this ChangeMappingRequest.\n\n The description of the mapped resource. # noqa: E501\n\n :param description: The description of this ChangeMappingRequest. # noqa: E501\n :type: str\n \"\"\"\n\n self._description = description\n\n @property\n def mapped_resource_id(self):\n \"\"\"Gets the mapped_resource_id of this ChangeMappingRequest. # noqa: E501\n\n The ID of the mapped resource. # noqa: E501\n\n :return: The mapped_resource_id of this ChangeMappingRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._mapped_resource_id\n\n @mapped_resource_id.setter\n def mapped_resource_id(self, mapped_resource_id):\n \"\"\"Sets the mapped_resource_id of this ChangeMappingRequest.\n\n The ID of the mapped resource. # noqa: E501\n\n :param mapped_resource_id: The mapped_resource_id of this ChangeMappingRequest. # noqa: E501\n :type: str\n \"\"\"\n\n self._mapped_resource_id = mapped_resource_id\n\n @property\n def last_sync_date(self):\n \"\"\"Gets the last_sync_date of this ChangeMappingRequest. # noqa: E501\n\n The timestamp (in UTC time standard) of the last synchronization of mapped resource. # noqa: E501\n\n :return: The last_sync_date of this ChangeMappingRequest. # noqa: E501\n :rtype: int\n \"\"\"\n return self._last_sync_date\n\n @last_sync_date.setter\n def last_sync_date(self, last_sync_date):\n \"\"\"Sets the last_sync_date of this ChangeMappingRequest.\n\n The timestamp (in UTC time standard) of the last synchronization of mapped resource. # noqa: E501\n\n :param last_sync_date: The last_sync_date of this ChangeMappingRequest. # noqa: E501\n :type: int\n \"\"\"\n\n self._last_sync_date = last_sync_date\n\n @property\n def sync_action(self):\n \"\"\"Gets the sync_action of this ChangeMappingRequest. # noqa: E501\n\n Represents the type of the action performed during last successful synchronization # noqa: E501\n\n :return: The sync_action of this ChangeMappingRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._sync_action\n\n @sync_action.setter\n def sync_action(self, sync_action):\n \"\"\"Sets the sync_action of this ChangeMappingRequest.\n\n Represents the type of the action performed during last successful synchronization # noqa: E501\n\n :param sync_action: The sync_action of this ChangeMappingRequest. # noqa: E501\n :type: str\n \"\"\"\n allowed_values = [\"ADD\", \"UPDATE\", \"REMOVE\"] # noqa: E501\n if self.local_vars_configuration.client_side_validation and sync_action not in allowed_values: # noqa: E501\n raise ValueError(\n \"Invalid value for `sync_action` ({0}), must be one of {1}\" # noqa: E501\n .format(sync_action, allowed_values)\n )\n\n self._sync_action = sync_action\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ChangeMappingRequest):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, ChangeMappingRequest):\n return True\n\n return self.to_dict() != other.to_dict()\n","sub_path":"collibra_core/models/change_mapping_request.py","file_name":"change_mapping_request.py","file_ext":"py","file_size_in_byte":12820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"103799274","text":"#!/bin/python3\n\nimport os\n\n#\n# Complete the 'getTotalX' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts following parameters:\n# 1. INTEGER_ARRAY a\n# 2. INTEGER_ARRAY b\n#\n\ndef getTotalX(a, b):\n # Write your code here\n count = 0\n for i in range(a[-1], b[0] + 1, 1):\n if check(i, a, b):\n count += 1\n return count\n\n\ndef check(num, a, b):\n checka = [x for x in a if num % x == 0]\n checkb = [x for x in b if x % num == 0]\n return len(checka) == len(a) and len(checkb) == len(b)\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n first_multiple_input = input().rstrip().split()\n n = int(first_multiple_input[0])\n m = int(first_multiple_input[1])\n arr = list(map(int, input().rstrip().split()))\n brr = list(map(int, input().rstrip().split()))\n total = getTotalX(arr, brr)\n fptr.write(str(total) + '\\n')\n fptr.close()\n","sub_path":"HackerRank/ProblemSolving/Algorithms/Implementation/PythonSolutions/BetweenTwoSets.py","file_name":"BetweenTwoSets.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"310587557","text":"#!/usr/bin/env python3\n\nimport argparse\nimport subprocess\nimport sys\nimport os\nimport csv\nimport json\nimport shutil\nfrom collections import defaultdict\nfrom typing import Counter\nfrom scipy.stats import hypergeom\nfrom rpy2 import robjects\nfrom utils import get_overlapping_features, count_intervals\n\n\ndef tsv_len(tsv_file):\n with open(tsv_file) as f:\n for i, l in enumerate(f):\n pass\n return i\n\n\ndef run_plink(plink_path, bfile_path, tsv_file, input_dict, p, out_name):\n# print('Calculating independent loci with PLINK')\n tsv_plink = os.getcwd() + f\"/{out_name}/\" + \\\n tsv_file.split('/')[-1].split('.')[0] + '_for_plink.tsv'\n out_plink = os.getcwd() + f\"/{out_name}/\" + \\\n tsv_file.split('/')[-1].split('.')[0]\n with open(tsv_plink, 'w', newline='') as csvfile:\n my_writer = csv.writer(csvfile, delimiter='\\t')\n init_row = [\"SNP\", \"Chr\", \"Pos\", \"P\"]\n my_writer.writerow(init_row)\n for snp in input_dict:\n # Only extract necessary info from dictionary corresponding to csv\n row = [snp] + input_dict[snp][0:3]\n my_writer.writerow(row)\n subprocess.call('{0}/plink --bfile {1} --clump {2} --clump-field P --clump-p1 {3} --clump-p2 0.01 --clump-r2 0.1 --clump-snp-field SNP --clump-kb 500 --out {4} --allow-no-sex --allow-extra-chr \\\n 2> {5}'.format(plink_path, bfile_path, tsv_plink, p, out_plink, f'./{out_name}/PLINK_clumping.log'), \n shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n# subprocess.call(f'md5sum {out_plink}.clumped', shell=True)\n return out_plink + \".clumped\"\n\n\ndef normalize_path(path):\n if path[-1] == \"/\":\n path = path[:-1]\n return path\n\n\ndef get_snp_info(tsv_file, names):\n input_dict = defaultdict(list)\n names = list(map(lambda x: x.lower(), names))\n with open(tsv_file, 'r', newline='') as csvfile: # Convert tsv to dictionary\n my_reader = csv.reader(csvfile, delimiter='\\t')\n csv_headings = list(map(lambda x: x.lower(), next(my_reader)))\n try: # We find necessary indices from header\n chr_index = csv_headings.index(names[0])\n pos_index = csv_headings.index(names[1])\n id_index = csv_headings.index(names[2])\n p_index = csv_headings.index(names[3])\n except ValueError:\n print(\"Check that your tsv file has headers and they are correct!\")\n exit(1)\n for row in my_reader: # Start from second row\n input_dict[row[id_index]] = [row[chr_index]] + \\\n [row[pos_index]] + [row[p_index]] # Name -> Chromosome, pos, pval\n return input_dict\n\n\ndef make_bed_file(clumped_file, interval, out_name):\n# print(f'Reading clumped file {clumped_file}')\n with open(f\"./{out_name}/clumps.bed\", 'w', newline='') as bed_file: # Here we write to new file\n my_writer = csv.writer(bed_file, delimiter='\\t')\n with open(clumped_file, 'r') as cl_file: # Our result of clumping (SNPs sets)\n my_reader = csv.reader(cl_file, delimiter='\\t')\n for row in my_reader:\n# print('Reading line')\n if len(row) != 0:\n # What to do with NONE?\n row = list(filter(lambda x: len(x) !=\n 0 and x != \" \", row[0].split(\" \")))\n if row[0] == \"CHR\": # Skip first row\n continue\n# print('Got here')\n bed_row = [row[0], max(int(row[3]) - interval, 0), int(row[3]) + interval]\n my_writer.writerow(bed_row)\n # Sort file\n subprocess.call(\n f\"bedtools sort -i ./{out_name}/clumps.bed > ./{out_name}/clumps_sorted.bed\", shell=True)\n # Merge regions\n subprocess.call(\n f\"bedtools merge -i ./{out_name}/clumps_sorted.bed > ./{out_name}/merged.bed\", shell=True)\n with open(f\"./{out_name}/merged_fixed_size.bed\", 'w', newline='') as bed_file: # Here we write to new file\n my_writer = csv.writer(bed_file, delimiter='\\t', lineterminator='\\n')\n with open(f'./{out_name}/merged.bed', 'r', newline='') as inter:\n my_reader = csv.reader(inter, delimiter='\\t')\n for row in my_reader:\n middle_point = int(row[1]) + (int(row[2]) - int(row[1])) // 2\n new_row = [row[0], max(middle_point - interval, 0), middle_point + interval]\n my_writer.writerow(new_row)\n # Add numeration to intervals\n subprocess.call(\n \"awk {'print $0\\\"\\t\\\"FNR'}\" + f\" ./{out_name}/merged_fixed_size.bed > ./{out_name}/merged_with_line_numbers.bed\", shell=True)\n\n\ndef p_val_for_gene_set(n_big, k_big, n, k):\n return hypergeom.sf(k, n_big, k_big, n)\n\n\ndef calcuate_qvals(pvals):\n x = robjects.r('''\n f <- function(pvals) {\n p.adjust(pvals, method = \"fdr\")\n }\n ''')\n r_f = robjects.globalenv['f']\n v = robjects.FloatVector(pvals)\n return list(r_f(v))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='LSEA')\n parser.add_argument('-input', help='Input file in TSV format. The file should contain at least four columns: chromosome name, variant position, variant ID, and GWAS p-value. The file MUST have a header row.', metavar='file',\n type=str, required=True)\n parser.add_argument('-universe', help='JSON file with universe. Several universe files may be specified separated by space',\n metavar='path', nargs='+', type=str, required=True)\n parser.add_argument('-out', help='Relative path to output directory (Default: lsea_result). Will be created.',\n metavar='name', type=str, required=False, default='lsea_result')\n parser.add_argument('-p', help='p-value cutoff to be used when identifying associated loci. If not specified, optimal cutoff will be estimated using a regression model (at least -n and -m options should be given)',\n metavar='float', nargs='+', required=False, default=['1e-5', '5e-8'])\n parser.add_argument('-plink_dir', help='Path to a directory with PLINK executable', metavar='dir',\n type=str, required=False)\n parser.add_argument('-bfile', help='Genotypes in PLINK .bed format that will be used for LD-based clumping. Only file prefix should be given.', metavar='prefix',\n type=str, required=False)\n parser.add_argument('-qval_threshold', help='Q-value threshold for output (Default: 0.1)',\n metavar='float', type=float, required=False, default=\"0.1\")\n parser.add_argument('-column_names', help='Column names for input TSV. These names will be used if the column names do not match the default: chr, pos, id, p. Names should be given in the same order (chromosome, position, ID, p-value)',\n metavar='name', nargs=4, type=str, required=False)\n\n if len(sys.argv) == 1:\n parser.print_help(sys.stderr)\n sys.exit(1)\n args = parser.parse_args()\n \n print(f'INFO\\tRunning LSEA with the following CMD: {\" \".join(sys.argv[:])}')\n \n tsv_file = args.input\n path_to_plink_dir = args.plink_dir\n if path_to_plink_dir is not None:\n path_to_plink_dir = normalize_path(args.plink_dir)\n path_to_bfile = args.bfile\n qval_thresh = args.qval_threshold\n col_names = args.column_names\n json_files = args.universe\n p_cutoffs = [float(x) for x in args.p]\n out_name = args.out\n if col_names is None:\n col_names = [\"chr\", \"pos\", \"id\", \"p\"]\n print(f'INFO\\tReading input file {tsv_file}...')\n input_dict = get_snp_info(tsv_file, col_names)\n\n if os.path.exists(f'./{out_name}'):\n print(f'WARN\\tOutput diretory {out_name} exists, removing...')\n shutil.rmtree(f'./{out_name}')\n os.makedirs(f'./{out_name}')\n\n for universe_file in json_files:\n universe_name = os.path.basename(universe_file).replace('.json', '')\n print(f'INFO\\tProcessing universe {universe_name}')\n universe= json.load(open(universe_file, \"r\"))\n interval = universe[\"interval\"]\n with open(f'./{out_name}/features.bed', 'w') as feature_file:\n for feature in universe[\"features\"]:\n bed_line = '\\t'.join(universe[\"features\"][feature])\n feature_file.write(f'{bed_line}\\n')\n interval_counts_for_universe = universe[\"interval_counts\"]\n print(f'INFO\\tUniverse stats:')\n print(f'\\tinterval size = {interval};\\n\\tinterval count = {universe[\"universe_intervals_number\"]};')\n print(f'\\ttotal number of features = {len(universe[\"features\"])};')\n print(f'\\tfeature sets in universe = {len(universe[\"gene_set_dict\"])}')\n\n stats_file = open(f\"./{out_name}/annotation_stats_{universe_name}.tsv\", 'w')\n print('p_cutoff\\tnum_loci\\tannotated_loci\\tunambiguoug_annotations\\tsignificant_hits\\tmin_qval', file=stats_file)\n\n for p_cutoff in p_cutoffs:\n print(f'INFO\\tCalculating enrichment with p-value cutoff = {p_cutoff}')\n clumped_file = run_plink(path_to_plink_dir, path_to_bfile, tsv_file, input_dict, p_cutoff, out_name)\n make_bed_file(clumped_file, interval, out_name)\n n_intervals = sum(1 for line in open(f'./{out_name}/merged_with_line_numbers.bed'))\n target_features = get_overlapping_features(f\"./{out_name}/merged_with_line_numbers.bed\", \n f'./{out_name}/features.bed', f\"./{out_name}/inter.tsv\") \n feature_set = universe[\"gene_set_dict\"]\n interval_counts = count_intervals(feature_set, target_features)\n\n pvals = []\n for w in sorted(interval_counts, key=lambda item: len(interval_counts[item]), reverse=True):\n pvals.append(p_val_for_gene_set(universe[\"universe_intervals_number\"], \n interval_counts_for_universe[w], n_intervals, len(interval_counts[w])))\n qvals = calcuate_qvals(pvals)\n\n with open(f\"./{out_name}/{universe_name}_result_{p_cutoff}.tsv\", 'w', newline='') as file:\n explained_loci = set()\n feature_names = defaultdict(set)\n hit_count = 0\n min_qval = 1\n my_writer = csv.writer(file, delimiter='\\t')\n my_writer.writerow([\"Gene_set\", \"Overlapping_loci\", \"Description\", \"p-value\", \"q-value\"])\n for i, w in enumerate(sorted(interval_counts, key=lambda item: len(interval_counts[item]), reverse=True)):\n if len(interval_counts[w]) >= 3 and qvals[i] <= qval_thresh:\n min_qval = min(min_qval, qvals[i])\n hit_count += 1\n for locus in interval_counts[w]:\n explained_loci.add(locus)\n feature_names[locus].add(';'.join(interval_counts[w][locus]))\n row = [w, len(interval_counts[w]), dict(interval_counts[w]), pvals[i], qvals[i]]\n my_writer.writerow(row)\n # Calculating number of loci with ambiguous annotations\n ambiguous_loci = 0\n for _, feature_set in feature_names.items():\n if len(feature_set) > 1:\n expanded_set = sum([ftr.split(';') for ftr in feature_set], [])\n feature_freq = dict(Counter(expanded_set))\n if max(feature_freq.values()) < len(feature_set):\n ambiguous_loci += 1\n unambiguous = len(explained_loci) - ambiguous_loci\n print(f'{p_cutoff}\\t{n_intervals}\\t{len(explained_loci)}\\t{unambiguous}\\t{hit_count}\\t{min_qval}', file=stats_file)\n \n stats_file.close()\n","sub_path":"LSEA_2.3.py","file_name":"LSEA_2.3.py","file_ext":"py","file_size_in_byte":11831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"339364640","text":"from flask import Flask , request\nfrom flask_restful import Resource, Api\nimport uuid\nimport configparser\nconfig = configparser.ConfigParser()\nconfig.read('../config.ini')\n\napp=Flask(__name__)\napi=Api(app)\n\n\nitems=[]\nsubscription_list = []\nsubscription_version = []\nprint(config.sections())\nclass Datasource(Resource):\n def get(self, data):\n for item in items:\n if item[\"key\"] == data:\n return item, 200\n return {\"key\" : None}, 404\n\n\n def post(self, data):\n if data == \"insert\":\n body_data = request.get_json(force=True)\n item = next(filter(lambda x: x[\"key\"] == body_data[\"key\"], items ), None)\n if item is None:\n item = {\"key\":body_data[\"key\"],\"value\":body_data[\"value\"]}\n items.append(item)\n return item , 201\n else:\n return {\"message\": \"set command can set unique key and values \"+body_data[\"key\"]+\" already exists\"}\n return {\"message\" : \"invalid path\"}\n\n\n def delete(self, data):\n for i in range(len(items)):\n if items[i]['key'] == data:\n del items[i]\n if data in subscription_list:\n subscription_list.remove(data)\n break\n return {\"status\":\"success\"}, 200\n\n def put(self,data):\n body_data = request.get_json(force=True)\n item = next(filter(lambda x: x[\"key\"] == body_data[\"key\"], items ), None)\n print(item)\n print(body_data)\n if item is None:\n items.append(body_data)\n return body_data , 201\n else:\n if body_data[\"key\"] in subscription_list:\n oldvalue=item[\"value\"]\n item.update(body_data)\n subscription_list.remove(body_data[\"key\"])\n return {\"message\":\"subscription key \"+body_data[\"key\"]+\" has been updated\", \"key\":body_data[\"key\"],\"oldvalue\":oldvalue,\"newvalue\":body_data[\"value\"]}\n else:\n item.update(body_data)\n return body_data , 200\n#class\nclass Subscribe(Resource):\n def post(self, data):\n subscription_data = data\n for item in items:\n if item[\"key\"] == data:\n subscription_list.append(data)\n return {\"item\":data,\"message\": data+\" has been Successfully added to subscription list\", \"status\": 200}\n return {\"message\" : \"not found\", \"status\": 404}\n\n\n def get(self, data):\n if data == \"list\":\n return {\"subscription_list\": subscription_list} ,200\nclass Alllist(Resource):\n def get(self):\n return {\"items\":items}\n\napi.add_resource(Datasource,\"/key/\")\napi.add_resource(Alllist,\"/alllist\")\napi.add_resource(Subscribe,\"/subscribe/\")\n\napp.run(host='0.0.0.0',port=5000)\n\n","sub_path":"utility/code/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"207445055","text":"from selenium.webdriver.common.by import By\nfrom framework_design_oops.testdata.constant import *\nfrom framework_design_oops.testdata.test_data_file import check_in_date, check_out_date\n\nX = By.XPATH\nN = By.NAME\nC = By.CSS_SELECTOR\nI = By.ID\nLINKTEXT = By.LINK_TEXT\n\n\nGOOGLE_SEARCH_BOX = (By.NAME, \"q\")\nGOOGLE_SEARCH_BUTTON = (By.NAME, \"btnK\")\n\n# Goibibo Go website locators Hotel Booking\nHOTELS_ICON = (X, \"//a[@href='/hotels/']//span[text()='Hotels']\")\nINDIA_HOTEL_RADIO_LABEL = (X, \"(//input[@name='CountryType'])[1]\")\nINTER_HOTEL_RADIO_LABEL = (X, \"(//input[@name='CountryType'])[2]\")\nHOTEL_LANDMARK = (I, \"downshift-1-input\")\nHOTE_PAGE_HEADER_ELEMENT = (X, f\"//h1[contains(text(), '{HOTEL_PAGE_HEADER}')]\")\nHOTEL_LOCATION_DROP_DOWN = (I, \"downshift-1-menu\")\nLOCATION_LIST = (X, \"//ul[@id='downshift-1-menu']//li\")\n\nCHECKIN_CALENDER = (X, \"//div[@data-testid='openCheckinCalendar']\")\nCHECKIN_DATE_ELEMENT = (X, f\"//span[text()='{check_in_date}']\")\nCHECKOUT_DATE_ELEMENT = (X, f\"//span[text()='{check_out_date}']\")\n\nGUEST_AND_ROOM_ELEM = (X, \"//input[@value='2 Guests in 1 Room ']\")\n\nEXISTING_ROOM_ELEM = (X, \"(//input[@value='2 Guests in 1 Room ']//parent::div//h4)[1]\")\nEXISTING_ADULT_ELEM = (X, \"(//input[@value='2 Guests in 1 Room ']//parent::div//h4)[2]\")\nEXISTING_CHILD_ELEM = (X, \"(//input[@value='2 Guests in 1 Room ']//parent::div//h4)[3]\")\n\nADD_ROOM_ELEM = (X, \"(//span[text()='+'])[1]\")\nADD_ADULT_ELEM = (X, \"(//span[text()='+'])[2]\")\nADD_CHILD_ELEM = (X, \"(//span[text()='+'])[3]\")\nDONE_BUTTON = (X, \"//button[text()='Done']\")\nSEARCH_BUTTON = (X, \"//button[@data-testid='searchHotelBtn']\")\n\n\n# Cab Booking Options\n\nCAB_BOOKING_ICON = (X, \"//span[contains(text(), 'Cabs') and contains(@class, 'iconText ')]\")\nCAB_SOURCE_ELEMENT = (X, \"//p[@data-testid='srcName']\")\nCAB_DEST_ELEMENT = (X, \"//p[@data-testid='destCityName']\")\nCAB_INPUT_CITY_ELEMENT = (I, \"gosuggest_inputL\")\nCAB_DROP_DOWN_SECTION = (X, \"//section[@class='searchCustomBlk']//div//*\")\nCAB_DATE_CALENDER = (X, \"//div[@class='DayPickerInput']\")\nCAB_BOOKING_DATES = (X, \"//div[@class='DayPickerInput']//div//*\")\nCAB_BOOKING_SEARCH = (X, \"//button[@class='searchBtn']\")\n\n\n\n","sub_path":"framework_design_oops/src/locators.py","file_name":"locators.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"77221140","text":"\n#!/usr/bin/env python3\n\n##https://pythontic.com/modules/socket/client-server-example\n# #python3 /home/estufaTabaco/main.py\n\nimport socket\nimport threading #https://www.tutorialspoint.com/python3/python_multithreading.htm\nimport time\n\nlocalIP = \"\"\nlocalPort = 20001\nbufferSize = 1024\nmsgFromServer = \"Hello UDP Client\"\nbytesToSend = str.encode(msgFromServer)\n\n# Create a datagram socket\n\nUDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)\n\n# Bind to address and ip\nUDPServerSocket.bind((localIP, localPort))\nprint(\"UDP server up and listening\")\n# Listen for incoming datagrams\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n print (\"Starting \" + self.name)\n enviando()\n print (\"Exiting \" + self.name)\n\nglobal address\naddress = [('', 21000)]\n\ndef enviando(): #corre a lista de clientes para enviar mensagem apra eles periodicamente\n print ('Conectado por', 'enviando apra clientes')\n\n while True:\n global address\n print('while enviando', address, bytesToSend)\n #UDPServerSocket.sendto(bytesToSend, ('', 20001))\n #for addres in address:\n for i in range(len(address)):\n print(address[i])\n UDPServerSocket.sendto(bytesToSend, address[i])\n time.sleep(4.0)\n\n\nthread = myThread(1, \"Thread-1\", 1) #thread para enviar as mensagens para os clientes em segundo plano\nthread.start()\n\nwhile (True): #while que trata as novas conecções\n bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)\n message = bytesAddressPair[0]\n address.append(bytesAddressPair[1])\n clientMsg = \"Message from Client:{}\".format(message)\n clientIP = \"Client IP Address:{}\".format(address)\n\n print(clientMsg)\n print(clientIP)\n\n # Sending a reply to client\n UDPServerSocket.sendto(bytesToSend, bytesAddressPair[1])\n","sub_path":"UDP_server.py","file_name":"UDP_server.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"332435970","text":"import asyncio\nimport websockets\nimport json\nimport datetime\nimport uuid\nimport os\n\n#Numero de clientes conectados!!!\n\nmensagens = []\nconnected = set()\n\n\nusersonline = []\n\ndef organizaclientid():\n ##nao esta finalizado aqui\n ##preciso separar em um json somente os ids dos usuarios conectados e enviar isso separado\n clientsid = []\n #,\"uuids\":usersonline\n #print(usersonline)\n for i in usersonline:\n clientsid.append(i['id'])\n #print(clientsid)\n return clientsid\n\nasync def users_event():\n return json.dumps({\"type\": \"users\", \"count\": len(connected), \"uuids\": organizaclientid()})\n\ndef user_saiu(id_user_que_saiu):\n return json.dumps({\"type\": \"user_saiu\", \"id\":id_user_que_saiu, \"count\": len(usersonline)})\n \nasync def my_id(meuid):\n return json.dumps({\"type\": \"my_id\", \"id\":meuid})\n\nasync def conn2id(conn):\n print(\"&\"*20)\n print(usersonline)\n print(\"&\"*20)\n #return usersonline[conn]\n\nasync def server(websocket, path):\n global mensagens,usersonline\n # Register.\n \n print(\"adding\")\n temp = dict()\n ultimouserconectado = set()\n \n temp['id'] = str(uuid.uuid4())\n temp['time_conected'] = datetime.datetime.utcnow().isoformat() + \"Z\"\n temp['conection'] = websocket\n temp[str(websocket)] = temp['id']\n usersonline.append(temp)\n connected.add(websocket)\n ultimouserconectado.add(websocket)\n #print(\"esse cara conectou \"+str(ultimouserconectado))\n #await websocket.send(\"seu id aqui\")\n #print(\"co ======= \"+str(connected))\n #print(\"usuagora ======= \"+str(ultimouserconectado))\n websockets.broadcast(ultimouserconectado,await my_id(temp['id']))\n websockets.broadcast(connected, await users_event())\n #print(temp['id'])\n try:\n async for message in websocket:\n msss = json.loads(message)\n\n if msss['type'] == \"msg-post\":\n mensagens.append(msss)\n print(msss)\n for conn in connected:\n #print(help(conn))\n if conn != websocket:\n #conn2id(conn)\n #print(f\"enviando para o {conn2id(conn)}\")\n await conn.send(str(msss))\n else:\n \n print(f\"Dar retorno\")\n elif msss['type'] == \"erro\":\n print(\"some error ocorreu\")\n elif msss['type'] == \"autentificacao\":\n print(msss)\n print(f\"seu username para o servidor == {msss['token']}\")\n else:\n print(\"typo nao suportado\")\n print(msss)\n \n finally:\n # Unregister.\n for index,user in enumerate(usersonline):\n if user['conection'] == websocket:\n print(f\"{user['id']} saiu ...\")\n usersonline.pop(index)\n print(f\"Restam apenas {len(usersonline)} conectados\")\n websockets.broadcast(connected, user_saiu(user['id']))\n \n \n print(\"Conneccao interrompida\")\n connected.remove(websocket)\n \n\nstart_server = websockets.serve(server, host=\"\",port=int(os.environ[\"PORT\"]))\nprint(\"Running...\")\nasyncio.get_event_loop().run_until_complete(start_server)\nasyncio.get_event_loop().run_forever()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"46155224","text":"import time\nimport requests\nfrom bs4 import BeautifulSoup\nfrom utils.gen_utils import get_trace_and_log, build_url_list_s, response_delay, random_user_agent, print_results, append_before, append_after, replace_matched_items, database_connection, insert_buy_listings_data\nfrom utils.static_data import ck_foil_pages, user_agents\n\n# Establish global lists\nstore_id = []\nfoil_names = []\nfoil_prices = []\nfoil_quantities = []\nfoil_editions = []\nfoil_conditions = []\nfoil_types = []\nfoil_page_urls = []\nfoil_urls = []\n\n# Establish empty lists for names of sets to replace -- before & after\nbefore = []\nafter = []\n# Append product data for before & after csv's (normalized names)\nappend_before(before_list=before)\nappend_after(after_list=after)\n# Pick and clean lists by pulling first element in both lists,\nbefore_clean = [l[0] for l in before]\nafter_clean = [l[0] for l in after]\n# Turn into a dictionary for easy key:value comparison in replace_matched_items function\nstandards_dict = dict(zip(before_clean, after_clean))\n\n\n# Begin fetch function\ndef fetch_urls(urls, store, make):\n t0 = time.time()\n total_requests = 0\n for url in urls:\n try:\n t1 = time.time()\n response = requests.get(url, headers=random_user_agent(user_agents), timeout=30)\n response_delay(t1)\n total_requests += 1\n elapsed_time = time.time() - t0\n print_results(store, make, total_requests, elapsed_time, len(urls))\n\n html_soup = BeautifulSoup(response.text, 'html.parser')\n products = html_soup.find_all('li', class_='productItemWrapper')\n if products is not None:\n for product in products:\n try:\n dollarprices = product.find('span', attrs={'class': 'sellDollarAmount'})\n centsprices = product.find('span', attrs={'class': 'sellCentsAmount'})\n totalprices = \"{}.{}\".format(dollarprices.text, centsprices.text)\n totalprices = totalprices.replace(',', '')\n foil_prices.append(\"{0:.2f}\".format(float(totalprices) * 1.3))\n\n buysets = product.find('div', attrs={'class': 'productDetailSet'})\n buysets = buysets.text.split(\" (\")\n buysets = buysets[0]\n foil_editions.append(buysets.strip('\\n'))\n\n buynames = product.span.text\n buynamessplit = buynames.split(\" (\")\n buynamessplit = buynamessplit[0]\n foil_names.append(buynamessplit)\n\n foil_quantities.append(product.find('input', attrs={'name': 'maxQty'})['value'])\n\n foil_con = 'NM-M'\n foil_conditions.append(foil_con)\n\n storeid = '1'\n store_id.append(storeid)\n\n type = 'F'\n foil_types.append(type)\n\n url = f'''https://www.cardkingdom.com/purchasing/mtg_singles/?filter%5Bsearch%5D=mtg_advanced&filter%5Bname%5D={buynamessplit}'''\n foil_urls.append(url)\n except Exception as e:\n # print('This just means we hit blank text (signature, high value, etc). Its good :)')\n # get_trace_and_log(e)\n pass\n except requests.exceptions.Timeout or requests.exceptions.ConnectionError or requests.exceptions.RequestException or requests.exceptions.ChunkedEncodingError as e:\n get_trace_and_log(e)\n continue # Handle the timeout\n\n\ndef main():\n # Build url list\n base_url = \"https://www.cardkingdom.com/purchasing/mtg_singles?filter%5Bipp%5D=100&filter%5Bsort%5D=name&filter%5Bsearch%5D=mtg_advanced&filter%5Bname%5D=&filter%5Bcategory_id%5D=0&filter%5Bfoil%5D=1&filter%5Bprice_op%5D=%3E%3D&filter%5Bprice%5D=&page=\"\n url_list = ck_foil_pages\n page_list = foil_page_urls\n urls = build_url_list_s(base_url, url_list, page_list)\n store = 'CK'\n make = 'FOIL BUY'\n fetch_urls(urls, store, make)\n # Clean and zip everything\n buy_editions = replace_matched_items(foil_editions, standards_dict)\n buy_editions = buy_editions[0]\n ck_foil_buy_zip = zip(foil_conditions, foil_names, foil_prices, foil_quantities, buy_editions, store_id,\n foil_types,\n foil_urls)\n ck_foil_buy_list = list(ck_foil_buy_zip)\n # Insert into database\n cursor = database_connection()\n insert_buy_listings_data(cursor, ck_foil_buy_list)\n\nmain()\n\n# print(list(zip(foil_names, foil_prices, foil_quantities, foil_editions, foil_types, foil_urls)))\n# get_length(foil_names),\n# get_length(foil_quantities),\n# get_length(foil_conditions),\n# get_length(foil_editions),\n# get_length(foil_prices),\n# get_length(foil_types),\n# get_length(store_id),\n# get_length(foil_urls)\n","sub_path":"buy_stores/get_ck_foil_buy.py","file_name":"get_ck_foil_buy.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"58826797","text":"from unittest import TestCase\n\nimport matplotlib.pyplot as plt\n\nfrom api.models import BookingSchema\nfrom api.test.dummy_data import *\nfrom api.test.tests import get_test_app, add_to_db, duplicate_db_object\n\n\nclass StatisticsTest(TestCase):\n def setUp(self) -> None:\n \"\"\"\n Testing with SQLAlchemy objects is a mess. What works is instead of\n saving the reference to the db object in setUp, the id is saved instead.\n Then in the test method you have to query on the id to get the\n reference to the db object.\n\n \"\"\"\n self.app = get_test_app()\n\n with self.app.app_context():\n\n # set up persons\n person1 = DummyPerson.create_random()\n\n self.person1 = add_to_db(person1).id\n\n # Note: self.type1 is the id (int), not a object.\n self.car_type1 = add_to_db(DummyCarType.create_random()).id\n self.car_type2 = add_to_db(DummyCarType.create_random()).id\n self.manufacturer1 = add_to_db(DummyCarManufacturer.create_random()).id\n self.manufacturer2 = add_to_db(DummyCarManufacturer.create_random()).id\n self.colour1 = add_to_db(DummyCarColour.create_random()).id\n self.colour2 = add_to_db(DummyCarColour.create_random()).id\n\n car1 = DummyCar.create_random()\n car2 = DummyCar.create_random()\n car3 = DummyCar.create_random()\n\n car1.car_type = self.car_type1\n car1.car_manufacturer = self.manufacturer1\n car1.car_colour = self.colour1\n car2.car_type = self.car_type1\n car2.car_manufacturer = self.manufacturer1\n car2.car_colour = self.colour1\n\n car3.car_type = self.car_type1 # Same\n car3.car_colour = self.colour2 # Different than the others\n car3.car_manufacturer = self.manufacturer2 # Different than the others\n\n # Finally add cars with correct foreign keys\n self.car1 = add_to_db(car1).id\n self.car2 = add_to_db(car2).id\n self.car3 = add_to_db(car3).id\n\n # booking1 is now + 5 hours\n booking1 = DummyBooking.create_random()\n booking1.car_id = self.car1\n booking1.person_id = self.person1\n booking1.start_time = datetime.now()\n booking1.end_time = datetime.now() + timedelta(days=0, hours=5)\n\n # booking 2 is in 1 day\n booking2 = duplicate_db_object(BookingSchema, booking1)\n booking2.car_id = car2.id\n booking2.start_time = datetime.now() + timedelta(days=1)\n booking2.end_time = datetime.now() + timedelta(days=4, hours=5)\n\n booking3 = duplicate_db_object(BookingSchema, booking1)\n booking3.car_id = car2.id\n booking3.start_time = datetime.now() - timedelta(days=3)\n booking3.end_time = datetime.now() - timedelta(days=2, hours=10)\n\n # booking3 was yesterday\n booking4 = duplicate_db_object(BookingSchema, booking1)\n booking4.car_id = car2.id\n booking4.start_time = datetime.now()\n booking4.end_time = datetime.now() + timedelta(days=2, hours=1)\n\n booking5 = duplicate_db_object(BookingSchema, booking1)\n booking5.car_id = car2.id\n booking5.start_time = datetime.now() - timedelta(days=6)\n booking5.end_time = datetime.now() - timedelta(days=4, hours=5)\n\n booking6 = duplicate_db_object(BookingSchema, booking1)\n booking6.car_id = car2.id\n booking6.start_time = datetime.now() - timedelta(days=5)\n booking6.end_time = datetime.now() - timedelta(days=4, hours=5)\n\n #self.booking1 = add_to_db(booking1).id\n ##self.booking2 = add_to_db(booking2).id\n ##self.booking3 = add_to_db(booking3).id\n ##self.booking4 = add_to_db(booking4).id\n ##self.booking5 = add_to_db(booking5).id\n self.booking6 = add_to_db(booking6).id\n\n def test_car_usage(self):\n with self.app.app_context():\n with self.app.test_client() as app:\n bookings = filter(\n lambda b: (b.start_time > datetime.now() - timedelta(\n weeks=1)) &\n (b.start_time < datetime.now()),\n Booking.query.all())\n bookings = [b for b in bookings]\n xs = [datetime.now().replace(hour=0, minute=0) - timedelta(days=x) for x in\n range(7, 0, -1)] # hours in a week\n print(xs)\n ys = []\n for day in xs:\n day_count = 0\n end = day + timedelta(days=1)\n\n for b in bookings:\n print(b.start_time)\n if (b.start_time < day < b.end_time) \\\n | (day < b.start_time < end) \\\n | (day < b.start_time < end):\n day_count += 1\n ys.append(day_count)\n print(ys)\n xs = [x.strftime('%d-%m-%y') for x in xs]\n\n fig, ax = plt.subplots()\n\n plt.plot(xs, ys)\n plt.xlabel('Date')\n plt.ylabel('Active rentals')\n plt.title('Active rentals per day for last 7 days')\n plt.show()\n\n\n\n","sub_path":"web/api/test/test_statistics.py","file_name":"test_statistics.py","file_ext":"py","file_size_in_byte":5448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"316392019","text":"## Funcion recursiva cuenta atras \ndef countdown(n):\n \"\"\"\n Cuenta regresiva\n Args:\n n : Numero entero positivo\n Return:\n 0 cuando atras ha finalizado\n \"\"\"\n import time\n if n ==0:\n print(\"La cuenta regresiva a terminado\")\n return print(0)\n time.sleep(1)\n print(n)\n return countdown(n-1)\n\ncountdown(10)","sub_path":"ejercicio42.py","file_name":"ejercicio42.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"331992865","text":"# Excerpted from beaker._compat.py.\n\nfrom __future__ import absolute_import\nimport sys\nimport six\n\n# True if we are running on Python 2.\nPY2 = sys.version_info[0] == 2\n\n\nif not PY2: # pragma: no cover\n\n def u_(s):\n return str(s)\n\n\nelse:\n unicode_text = six.text_type\n byte_string = str\n\n def u_(s):\n if isinstance(s, unicode_text):\n return s\n\n if not isinstance(s, byte_string):\n s = str(s)\n return six.text_type(s, \"utf-8\")\n","sub_path":"beaker_extensions/_compat.py","file_name":"_compat.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"272312481","text":"from typing import List\n\nfrom sklearn.ensemble import GradientBoostingClassifier\nimport numpy as np\nimport pandas as pd\n\nfrom data.user_features import UserFeatures\nfrom data.user_labels import UserLabels\nfrom estimators.base.age_estimator import AgeEstimator\nfrom constants.hyper_parameters import RELATION_AGE_NODE2VEC_HYPER_PARAMS\nfrom data.pre_processors import get_node2vec_embeddings\nfrom estimators.estimator_utils import get_age_embeddings_dataset_splits\nfrom data.readers import int_category_to_age\n\n\nclass RelationNode2VecGBDTAgeEstimator(AgeEstimator):\n def __init__(self):\n self.best_node2vec_hyper_parameters = {}\n self.model = self._initialise_model()\n\n def _initialise_model(self):\n return GradientBoostingClassifier(\n n_estimators=100,\n max_depth=3\n )\n\n def fit(\n self,\n features: List[UserFeatures],\n liwc_df: pd.DataFrame,\n nrc_df: pd.DataFrame,\n labels: List[UserLabels]\n ) -> None:\n best_model_scores = []\n for hyper_params in RELATION_AGE_NODE2VEC_HYPER_PARAMS:\n x_train, x_test, y_train, y_test = get_age_embeddings_dataset_splits(\n features,\n labels,\n hyper_params,\n get_node2vec_embeddings\n )\n self.model.fit(x_train, y_train)\n test_score = self.model.score(x_test, y_test)\n best_model_scores.append(test_score)\n self.model = self._initialise_model()\n\n best_index = int(np.argmax(best_model_scores))\n self.best_node2vec_hyper_parameters = RELATION_AGE_NODE2VEC_HYPER_PARAMS[best_index]\n print(\"Best test set score was {}\".format(best_model_scores[best_index]))\n print(\"Best hyper-parameters were {}\".format(self.best_node2vec_hyper_parameters))\n\n x_train, x_test, y_train, y_test = get_age_embeddings_dataset_splits(\n features,\n labels,\n self.best_node2vec_hyper_parameters,\n get_node2vec_embeddings\n )\n self.model = self._initialise_model()\n self.model.fit(x_train, y_train)\n\n def predict(\n self,\n features: List[UserFeatures],\n liwc_df: pd.DataFrame,\n nrc_df: pd.DataFrame\n ) -> List[str]:\n embeddings = get_node2vec_embeddings(features, self.best_node2vec_hyper_parameters)\n predictions = self.model.predict(embeddings)\n return [int_category_to_age(int(prediction)) for prediction in predictions]\n","sub_path":"src/estimators/age/relation_node2vec_gbdt_age_estimator.py","file_name":"relation_node2vec_gbdt_age_estimator.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"582418925","text":"from elasticsearch import Elasticsearch\nimport json\n\nes_client = Elasticsearch(['172.18.1.96:9200'])\n\ndef main():\n\tcategorias = []\n\tcont = 0\n\tfor x in range(0,1592):\n\t\tres = query(x)\n\t\ttotal = res['hits']['total']\n\t\tfor hit in res['hits']['hits']:\n\t\t\tcont = cont + 1 \n\t\t\tprint(str(cont))\n\t\t\tif hit[\"_source\"][\"Appearances\"][\"Appearance\"][\"categoryname\"] not in categorias:\n\t\t\t\tcategorias.append(hit[\"_source\"][\"Appearances\"][\"Appearance\"][\"categoryname\"])\n\testadisticas = []\n\tfor categoria in categorias:\n\t\tjson_categoria = {}\n\t\tjson_categoria[\"name\"] = categoria\n\t\tcont_bn = 0\n\t\tcont_website = 0\n\t\tcont_paymenttype = 0\n\t\tcont_schedule = 0\n\t\tcont_productservices = 0\n\t\tcont_email = 0\n\t\tcont_address = 0\n\t\tres = es_client.search(index=\"negocios_secam\", doc_type='default' ,body={\"size\": 90000, \"query\": {\"match_phrase\": {\"Appearances.Appearance.categoryname\": categoria}}})\n\t\ttotal = res['hits']['total']\n\t\tjson_categoria[\"total\"] = total\n\t\tfor hit in res['hits']['hits']:\n\t\t\tif (len(hit[\"_source\"][\"bn\"]) > 0):\n\t\t\t\tcont_bn = cont_bn + 1\n\t\t\tif \"contenttype\" in hit[\"_source\"][\"contenttypes\"]:\n\t\t\t\tfor element in hit[\"_source\"][\"contenttypes\"][\"contenttype\"]:\n\t\t\t\t\tif element[\"name\"] == \"paopwo\":\n\t\t\t\t\t\tcont_website = cont_website + 1\n\t\t\tif \"type\" in hit[\"_source\"][\"features\"]:\n\t\t\t\tfor element in hit[\"_source\"][\"features\"][\"type\"]:\n\t\t\t\t\tif element[\"name\"] == \"paymenttype\":\n\t\t\t\t\t\tcont_paymenttype = cont_paymenttype + 1\n\t\t\t\t\telif element[\"name\"] == \"txtschedule\":\n\t\t\t\t\t\tcont_schedule = cont_schedule + 1\n\t\t\tif \"prdserv\" in hit[\"_source\"][\"productservices\"]:\n\t\t\t\tif (len(hit[\"_source\"][\"productservices\"][\"prdserv\"]) > 0):\n\t\t\t\t\tcont_productservices = cont_productservices + 1\n\t\t\tif \"lke\" in hit[\"_source\"][\"items\"]:\n\t\t\t\tcont_email = cont_email + 1\n\t\t\tif (len(hit[\"_source\"][\"fullstreet\"]) > 0) or (len(hit[\"_source\"][\"colony\"]) > 0) or (len(hit[\"_source\"][\"city\"]) > 0) or (len(hit[\"_source\"][\"statename\"]) > 0):\n\t\t\t\tcont_address = cont_address + 1\n\t\tjson_categoria[\"BusinessName\"] = cont_bn\n\t\tjson_categoria[\"WebSite\"] = cont_website\n\t\tjson_categoria[\"PaymentType\"] = cont_paymenttype\n\t\tjson_categoria[\"Schedule\"] = cont_schedule\n\t\tjson_categoria[\"ProductServices\"] = cont_productservices\n\t\tjson_categoria[\"Email\"] = cont_email\n\t\tjson_categoria[\"Address\"] = cont_address\n\t\testadisticas.append(json_categoria)\n\tprint(estadisticas)\n\twith open('categorias.json', 'w') as outfile:\n\t\tjson.dump(estadisticas, outfile)\n\n\ndef query(page):\n\treturn es_client.search(index=\"negocios_secam\", doc_type='default' ,body={\"size\": 1000, \"from\": page*1000, \"query\": {\"match_all\": {}}})\n\nif __name__ == '__main__':\n\tmain()","sub_path":"scripts_python/categorias_alexa.py","file_name":"categorias_alexa.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"587295098","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom twilio.rest import TwilioRestClient\n\n\n\n\naccount_sid = \"\"\nauth_token = \"\"\nclient = TwilioRestClient(account_sid, auth_token)\ncall = client.calls.create(to=\"+852\", # Any phone number\n from_=\"+852\", # Must be a valid Twilio number\n url=\"http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient\")\nprint(call.sid)\n\n\nusr = \"\"\npwd = \"\"\n\nchrome_options = webdriver.ChromeOptions()\nprefs = {\"profile.default_content_setting_values.notifications\" : 2}\nchrome_options.add_experimental_option(\"prefs\",prefs)\n\ndriver = webdriver.Chrome(executable_path=r'chromedriver')\ndriver.get(\"https://m.facebook.com/\")\nassert \"Facebook\" in driver.title\nelem = driver.find_element_by_name(\"email\")\nelem.send_keys(usr)\nelem = driver.find_element_by_name(\"pass\")\nelem.send_keys(pwd)\nelem.send_keys(Keys.RETURN)\ntime.sleep(5)\ndriver.find_element_by_css_selector(\"#root > div > div > div > div._4g33._2pip > div:nth-child(1) > div > a\").click()\ntime.sleep(5)\ndriver.find_element_by_css_selector(\"#messages_jewel > a\").click()\ntime.sleep(5)\ndriver.find_element_by_css_selector(\"#messages_flyout > div > header > div._5s61 > a\").click()\ntime.sleep(5)\ninputElement = driver.find_element_by_css_selector(\"#u_7_1 > input\")\ninputElement.send_keys(\"\")\ndriver.find_element_by_class_name(\"_51lj\").click()\n\ninputElement = driver.find_element_by_id(\"u_7_5\")\ninputElement.send_keys(\"Please check patient's log files on https://www.dropbox.com/s/d98aqm72s9d83o1/records.csv?dl=0\")\ninputElement.send_keys(Keys.RETURN)\n\ndriver.find_element_by_id(\"m-messages-touch-composer-send-button\").click()\ndriver.close()\ndriver.quit()\n","sub_path":"fb.py","file_name":"fb.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"70671393","text":"# importing the modules\r\nimport time\r\nimport win32com.client\r\nfrom selenium import webdriver\r\nimport csv\r\nimport pandas as pd\r\nimport re\r\nfrom datetime import date,timedelta,datetime\r\n\r\nfrom tkinter import * \r\nfrom tkinter import messagebox\r\nfrom tkinter import ttk\r\n\r\nfrom selenium.webdriver.support.ui import WebDriverWait as wait\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.support.ui import Select\r\nfrom selenium.webdriver.common.alert import Alert\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nfrom threading import Thread\r\n\r\nimport pythoncom\r\n\r\nimport win32api as win\r\nimport os\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport shutil\r\n\r\ndef generate_Report(*args,filename_path):\r\n for data in os.listdir(filename_path):\r\n if '_Assingee_status' in data or '_Priority_status' in data:\r\n print (data)\r\n os.remove(filename_path+\"\\\\\"+data)\r\n print (filename_path+\"\\\\\"+data + ' is deleted')\r\n\r\n for file in args:\r\n df= pd.read_csv(filename_path+\"\\\\\"+file,encoding = \"ISO-8859-1\")\r\n plt.figure(figsize=(15,10))\r\n sns.countplot(x='Assignee+',data=df,hue='Status*')\r\n plt.xticks(rotation=15,ha=\"right\")\r\n plt.savefig(filename_path+\"\\\\\"+file[:-4]+'_Assingee_status.png', dpi=100)\r\n #plt.show()\r\n sns.countplot(x='Priority*',data=df,hue='Status*')\r\n plt.savefig(filename_path+\"\\\\\"+file[:-4]+'_Priority_status.png', dpi=100)\r\n #plt.show()\r\n\r\ndef copy_file(source,destination):\r\n for data in os.listdir(source):\r\n if 'WinLink_Report' in data:\r\n shutil.copy(os.path.join(source,'WinLink_Report.csv'), os.path.join(destination,'WinLink_Report.csv'))\r\n\r\ndef get_download_path():\r\n global full_path\r\n name=win.GetUserNameEx(win.NameSamCompatible)\r\n rename=re.sub(r'\\W', \" \", name)\r\n #print (rename)\r\n pos=rename.find(' ')\r\n #print (pos)\r\n path2='Downloads'\r\n path1='Users'\r\n #print (name)\r\n #print (name[8:]) \r\n user_name=name[pos+1:]\r\n full_path='C:'+\"\\\\\"+path1+\"\\\\\"+user_name+\"\\\\\"+path2\r\n #print (full_path)\r\n print (full_path)\r\n return full_path,full_path+\"\\\\\"+'WinLink_Report'\r\n \r\ndef start_thread():\r\n t=Thread(target=open_browser,args=(username_entry.get(),password_entry.get(),))\r\n t.start()\r\ndef open_browser(username,password):\r\n try:\r\n if username!='' and password !='':\r\n pythoncom.CoInitialize()\r\n button.grid_forget()\r\n progessbar.grid(row=5,column=1,sticky=E+W,padx=10)\r\n progessbar.config(maximum=100)\r\n progessbar.start()\r\n '''\r\n for data in os.listdir(get_download_path()[0]):\r\n if 'WinLink_Report' in data:\r\n try:\r\n os.remove(get_download_path()[0]+\"\\\\\"+data)\r\n except:\r\n pass\r\n '''\r\n if os.path.exists(os.path.join(get_download_path()[1])) :\r\n print ('Alread Exists')\r\n for data in os.listdir(get_download_path()[1]):\r\n try:\r\n os.remove(get_download_path()[1]+\"\\\\\"+data)\r\n except:\r\n pass\r\n else:\r\n os.mkdir(get_download_path()[1])\r\n itsm_query=''''Assigned Group*+' = \"WinLink Application Support\"'''\r\n prefs = {'download.default_directory': get_download_path()[1]}\r\n chrome_options = webdriver.ChromeOptions()\r\n chrome_options.add_experimental_option('prefs', prefs)\r\n driver = webdriver.Chrome(chrome_options=chrome_options)\r\n driver.maximize_window()\r\n window_before = driver.window_handles[0]\r\n try:\r\n driver.get('https://itsm.windstream.com/')\r\n time.sleep(30)\r\n aw=True\r\n while aw:\r\n shell = win32com.client.Dispatch(\"WScript.Shell\")\r\n shell.Sendkeys(username)\r\n shell.Sendkeys('{TAB}')\r\n shell.Sendkeys(password)\r\n shell.Sendkeys('{ENTER}')\r\n aw=False\r\n \r\n except Exception as e:\r\n print (e)\r\n progessbar.grid_forget()\r\n messagebox.showinfo('Warning','Connect VPN/check your username and password')\r\n \r\n try:\r\n alert_wait=EC.alert_is_present()\r\n wait(driver ,30).until(alert_wait)\r\n alert=driver.switch_to_alert()\r\n alert.accept()\r\n except:\r\n pass\r\n logo_present = wait(driver,60).until(EC.presence_of_element_located((By.ID, 'reg_img_304316340')))\r\n try:\r\n alert_wait=EC.alert_is_present()\r\n wait(driver ,10).until(alert_wait)\r\n alert=driver.switch_to_alert()\r\n alert.accept()\r\n except:\r\n pass\r\n level_element= wait(driver,60).until(EC.presence_of_element_located((By.ID,'reg_img_304316340')))\r\n level_element.click()\r\n wait(driver,20)\r\n child_element= wait(driver,60).until(EC.element_to_be_clickable((By.XPATH ,\"//span[text()='Incident Management']\")))\r\n child_element.click()\r\n wait(driver,20)\r\n #Changed the code to click 'Search Change' instead of clicking 'Change management console'\r\n child_element_1=wait(driver,60).until(EC.element_to_be_clickable((By.XPATH ,\"//span[text()='Search Incident']\")))\r\n child_element_1.click()\r\n wait(driver,25)\r\n try:\r\n alert_wait=EC.alert_is_present()\r\n wait(driver ,10).until(alert_wait)\r\n alert=driver.switch_to_alert()\r\n alert.accept()\r\n except:\r\n pass\r\n #Need to add the code for clicking advance search button using xpath='//*[@id=\"TBadvancedsearch\"]'\r\n adv_button= wait(driver,100).until(EC.element_to_be_clickable((By.XPATH,\"/html/body/div[1]/div[5]/div[2]/div/div/div[3]/fieldset/div/div/div/div/div[3]/fieldset/div/div/div/div[1]/table/tbody/tr/td[3]/a[3]\")))\r\n if adv_button.is_displayed():\r\n ActionChains(driver).double_click(adv_button).perform()\r\n else:\r\n print('Not displayed')\r\n #Need to add the code for sending ITSM query to text area\r\n wait(driver,50)\r\n text_area=wait(driver,100).until(EC.element_to_be_clickable((By.XPATH,'//fieldset/div/div/div/div/div[3]/fieldset/div/div/div/div[5]/table[2]/tbody/tr/td[1]/textarea[@id=\"arid1005\"]')))\r\n text_area.click()\r\n text_area.send_keys(itsm_query)\r\n #Need to add the code to click the search button\r\n wait(driver,5)\r\n search=wait(driver,100).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/div[5]/div[2]/div/div/div[3]/fieldset/div/div/div/div/div[3]/fieldset/div/div/div/div[4]/div[4]/div/div/div[3]/fieldset/div/div/div/div/div[2]/fieldset/div/a[2]/div/div')))\r\n search.click()\r\n wait(driver,100)\r\n try:\r\n selectall=wait(driver,100).until(EC.element_to_be_clickable((By.XPATH,'html[1]/body[1]/div[1]/div[5]/div[2]/div[1]/div[1]/div[3]/fieldset[1]/div[1]/div[1]/div[1]/div[1]/div[3]/fieldset[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[3]/table[1]/tbody[1]/tr[1]/td[1]/a[2]')))\r\n selectall.click() #selectall\r\n time.sleep(2)\r\n except Exception as e:\r\n print (e)\r\n progessbar.grid_forget()\r\n button.tkraise()\r\n button.grid(row=5,column=1,pady=10)\r\n report=wait(driver,100).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/div[5]/div[2]/div/div/div[3]/fieldset/div/div/div/div/div[3]/fieldset/div/div/div/div[2]/div/div[3]/table/tbody/tr/td[1]/a[1]')))\r\n report.click() #report\r\n window_after = driver.window_handles[1]\r\n wait(driver,60)\r\n #Trnasfreing the window control\r\n driver.switch_to.window(window_after)\r\n wait(driver,30)\r\n #searching the Prodapt_ASAP_Daily_Report and clicking\r\n prodapt_asap_daily_report=wait(driver,100).until(EC.element_to_be_clickable((By.XPATH,\"//span[text()='Prodapt_ASAP_Daily_Report']\")))\r\n prodapt_asap_daily_report.click()\r\n s=wait(driver,60).until(EC.element_to_be_clickable((By.XPATH,\"//*[@id='arid_WIN_0_2000053']\")))\r\n s.click() #To clcick the Destination drop down\r\n f=wait(driver,60).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[3]/div[2]/table/tbody/tr[2]/td[1]')))\r\n webdriver.ActionChains(driver).move_to_element(f).click(f).perform()# to select the File\r\n w=wait(driver,60).until(EC.element_to_be_clickable((By.XPATH,\"//*[@id='arid_WIN_0_2000056']\")))\r\n w.click()#Formtdropdownbutton\r\n c=wait(driver,60).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[3]/div[2]/table/tbody/tr[2]/td[1]')))# clicking CSV\r\n webdriver.ActionChains(driver).move_to_element(c).click(c).perform()\r\n textname=wait(driver,60).until(EC.element_to_be_clickable((By.XPATH,\"//*[@id='arid_WIN_0_2000057']\")))\r\n wait(driver,1)\r\n textname.click()#to click the filename\r\n textname.clear()\r\n textname.send_keys('WinLink_Report.csv')\r\n run=wait(driver,60).until(EC.element_to_be_clickable((By.XPATH,\"//*[@id=\\\"reg_img_93272\\\"]\")))\r\n run.click()\r\n time.sleep(30)\r\n driver.close()\r\n driver.switch_to.window(window_before) \r\n logout=wait(driver,60).until(EC.element_to_be_clickable((By.XPATH,'//*[@id=\"WIN_0_300000044\"]/div/div')))\r\n logout.click()\r\n driver.quit\r\n progessbar.grid_forget()\r\n button.tkraise()\r\n button.grid(row=5,column=1,pady=10)\r\n \r\n else:\r\n messagebox.showinfo('Warning..','Please check your username and password')\r\n except Exception as error:\r\n messagebox.showinfo('Error..',str(error))\r\n progessbar.grid_forget()\r\n button.tkraise()\r\n button.grid(row=5,column=1,pady=10)\r\n\r\n\r\ndef prior_week_end():\r\n return datetime.now() - timedelta(days=((datetime.now().isoweekday() + 1) % 7))\r\n #Function to get the start day of the current week\r\ndef prior_week_start():\r\n return prior_week_end() - timedelta(days=6)\r\n\r\n\r\nclass month_week_report(): \r\n def __init__(self,previous_week_start,previous_week_end,month_start,month_end):\r\n self.previous_week_start=previous_week_start\r\n self.previous_week_end=previous_week_end\r\n self.month_start=month_start\r\n self.month_end=month_end\r\n \r\n def week_report(self,reported_date):\r\n if self.previous_week_end >= datetime.strptime(reported_date[0:len(reported_date)-3],'%m/%d/%Y %H:%M:%S') >= self.previous_week_start:\r\n return True\r\n def month_report(self,reported_date):\r\n if self.month_end >= datetime.strptime(reported_date[0:len(reported_date)-3],'%m/%d/%Y %H:%M:%S') >= self.month_start:\r\n return True\r\n \r\n\r\n\r\ndef create_files(file_path):\r\n if to_address_entry.get() !='':\r\n #To get the last week start date and end date\r\n #copy_file(get_download_path()[0],get_download_path()[1])\r\n previous_week_start=prior_week_start()\r\n previous_week_end=prior_week_end()\r\n\r\n #To get the last month start date and end date\r\n month_start=(datetime.today().replace(day=1)-timedelta(days=1)).replace(day=1)\r\n month_end=datetime.today().replace(day=1)-timedelta(days=1)\r\n\r\n #initializing the class \r\n mon_week_obj=month_week_report(previous_week_start,previous_week_end,month_start,month_end)\r\n \r\n with open(file_path+\"\\\\\"+'WinLink_Report.csv','r') as file:\r\n data=csv.reader(file,delimiter=',')\r\n for num,i in enumerate(data):\r\n if 'AM' in i[3] or 'PM' in i[3]:\r\n if mon_week_obj.week_report(i[3]):\r\n dict_week[num]=i\r\n if mon_week_obj.month_report(i[3]):\r\n dict_month[num]=i\r\n\r\n fieldnames =['Assigned Group*+',\r\n 'Case Type*',\r\n 'Incident ID*+',\t\r\n 'Reported Date+',\r\n 'Last Resolved Date',\r\n 'Assignee+',\r\n 'Priority*',\r\n 'Status*',\t\r\n 'SLM Real Time Status',\t\r\n 'Summary*',\t\r\n 'Notes',\t\r\n 'Resolution',\t\r\n 'Resolution Categorization Tier 1',\t\r\n 'Resolution Categorization Tier 2',\t\r\n 'Resolution Categorization Tier 3',\t\r\n 'Re-Opened Date',\r\n 'Product Categorization Tier 1',\t\r\n 'Product Categorization Tier 2',\t\r\n 'Product Categorization Tier 3',\t\r\n 'Impact Start Date/Time+',\t\r\n 'Impact Stop Date/Time+',\r\n 'First Name+',\t\r\n 'Last Name+',\r\n 'Status Reason',\t\r\n 'Last Modified Date']\r\n \r\n with open(file_path+\"\\\\\"+'WinLink_Report_Week.csv','w+',newline='') as f:\r\n writer = csv.writer(f,delimiter = ',')\r\n writer.writerow(columns for columns in fieldnames)\r\n for key,value in dict_week.items():\r\n writer.writerow(data for data in value)\r\n\r\n with open(file_path+\"\\\\\"+'WinLink_Report_Month.csv','w+',newline='') as f:\r\n writer = csv.writer(f,delimiter = ',')\r\n writer.writerow(columns for columns in fieldnames)\r\n for key,value in dict_month.items():\r\n writer.writerow(data for data in value)\r\n \r\n generate_Report('WinLink_Report_Week.csv','WinLink_Report_Month.csv',filename_path=file_path)\r\n send_mail(file_path,to_address_entry.get())\r\n else:\r\n messagebox.showinfo('Warning..','Please provide To email address')\r\n\r\ndef send_mail(file_path,to_address):\r\n try:\r\n Application = win32com.client.dynamic.Dispatch('outlook.application')\r\n #Application= win32com.client.Dispatch('outlook.application')\r\n print (Application)\r\n print (Application.Session.Accounts)\r\n oacctouse= None\r\n for oacc in Application.Session.Accounts:\r\n print (oacc.SmtpAddress)\r\n if oacc.SmtpAddress == \"Balaji.Masilamani@windstream.com\" or oacc.SmtpAddress ==\"Mohammed.Sadik@windstream.com\":\r\n oacctouse = oacc \r\n break\r\n #print(oacc)\r\n mail = Application.CreateItem(0)\r\n #mail_html = \"

    Overall Backlog

    Incident472
    Request17
    IT-OSS - M6 (ASAP/TSG) 177
    IT-OSS - M6 (NextGen) 197
    IT-OSS - M6 (PAETEC) 103
    IT-OSS - M6 (EarthLink) 18
    Total Number of tickets assigned in Prodapt489
    \"\r\n #print(mail_html)\r\n if oacctouse:\r\n mail._oleobj_.Invoke(*(64209, 0, 8, 0, oacctouse))\r\n\r\n\r\n #mail.To = 'madanraj.c@prodapt.com;sariga.s@prodapt.com;kavitha.sekar@prodapt.com;devanand.s@prodapt.com'\r\n #mail.cc = 'suchitra.bc@prodapt.com;annamalai.d@prodapt.com;ravindran.n@prodapt.com;sudha.r@prodapt.com'\r\n mail.To=to_address \r\n mail.Subject = 'Daily Backlog Report'\r\n mail.Body = '*WinLink Report Generation*'\r\n try:\r\n attachment0 = file_path+\"\\\\\"+'WinLink_Report.csv'\r\n attachment1 = file_path+\"\\\\\"+'WinLink_Report_Month.csv'\r\n attachment2 = file_path+\"\\\\\"+'WinLink_Report_Week.csv'\r\n mail.Attachments.Add(attachment0)\r\n mail.Attachments.Add(attachment1)\r\n mail.Attachments.Add(attachment2)\r\n attachment3=mail.Attachments.Add(file_path+\"\\\\\"+'WinLink_Report_Month_Assingee_status.png')\r\n attachment3.PropertyAccessor.SetProperty(\"http://schemas.microsoft.com/mapi/proptag/0x3712001F\", \"MyId1\")\r\n attachment4=mail.Attachments.Add(file_path+\"\\\\\"+'WinLink_Report_Month_Priority_status.png')\r\n attachment4.PropertyAccessor.SetProperty(\"http://schemas.microsoft.com/mapi/proptag/0x3712001F\", \"MyId2\")\r\n attachment5=mail.Attachments.Add(file_path+\"\\\\\"+'WinLink_Report_Week_Assingee_status.png')\r\n attachment5.PropertyAccessor.SetProperty(\"http://schemas.microsoft.com/mapi/proptag/0x3712001F\", \"MyId3\")\r\n attachment6=mail.Attachments.Add(file_path+\"\\\\\"+'WinLink_Report_Week_Priority_status.png')\r\n attachment6.PropertyAccessor.SetProperty(\"http://schemas.microsoft.com/mapi/proptag/0x3712001F\", \"MyId4\")\r\n html=\"\"\" \r\n Hi Team,

    \r\n Please find the attached WinLink_Week and WinLink_Month report.

    \r\n Monthly Report:

  • \r\n Assingee vs Status \r\n \r\n Status vs Priority \r\n

    \r\n Weekly Report:


    \r\n Assingee vs Status \r\n \r\n Status vs Priority \r\n \r\n \"\"\"\r\n mail.HTMLBody = html+\"
    This is an automated e-mail \"\r\n except Exception as error:\r\n messagebox.showinfo('Files Error..',error)\r\n mail.Send()\r\n print ('Mail Sent')\r\n except Exception as error:\r\n messagebox.showinfo('Sending Mail..',error)\r\n \r\n\r\nif __name__=='__main__': \r\n #creating the loging info page\r\n root=Tk()\r\n s = ttk.Style()\r\n s.theme_use('classic')\r\n s.configure(\"blue.Horizontal.TProgressbar\", foreground='blue', background='blue')\r\n root.geometry(\"600x300\")\r\n root.title('MYOS Support_ITSM Reporting Tool')\r\n root.resizable(False, False)\r\n root.configure(background='sky blue')\r\n username=Label(root,text='User Name/Nid:',\r\n #bg='sky blue',\r\n font=('Arial',10,'bold'))\r\n username.grid(row=0,column=0,sticky='w',padx=100,pady=25)\r\n username_entry=Entry(root,bd=2,width=30)\r\n username_entry.grid(row=0,column=1,sticky='w')\r\n password=Label(root,text='Password:',\r\n #bg='sky blue',\r\n font=('Arial',10,'bold'))\r\n password.grid(row=1,column=0,sticky='e',pady=10,padx=100)\r\n password_entry=Entry(root,bd=2,show='*',width=30)\r\n password_entry.grid(row=1,column=1,sticky='w')\r\n\r\n to_address=Label(root,text='Email To:',\r\n #bg='sky blue',\r\n font=('Arial',10,'bold'))\r\n to_address.grid(row=3,column=0,sticky=E,pady=10,padx=100)\r\n to_address_entry=Entry(root,bd=2,width=30)\r\n to_address_entry.grid(row=3,column=1,sticky=W)\r\n var = IntVar()\r\n progessbar = ttk.Progressbar (root, variable=var, orient='horizontal', length=150,style=\"red.Horizontal.TProgressbar\")\r\n progessbar.grid(row=4,column=1,sticky=E,padx=10)\r\n var.set(0)\r\n progessbar.grid_forget()\r\n button=Button(root,text='Download Report',bg='sky blue'\r\n ,command=start_thread\r\n )\r\n button.grid(row=5,column=1,pady=10)\r\n report_preparation=Button(root,text='Report Preparation',bg='sky blue'\r\n ,command= lambda : create_files(get_download_path()[1])\r\n )\r\n report_preparation.grid(row=6,column=1,pady=10)\r\n\r\n\r\n dict_week={}\r\n dict_month={}\r\n #send_mail()\r\n #get_download_path()\r\n root.mainloop()\r\n\r\n\r\n\r\n\r\n","sub_path":"WinLink Report Automation/WinLink_Report_Generation.py","file_name":"WinLink_Report_Generation.py","file_ext":"py","file_size_in_byte":19461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"223940111","text":"import sys\r\nimport os\r\nimport glob\r\nimport argparse\r\nimport numpy as np\r\nimport threading\r\nimport networkx\r\nimport time\r\n\r\nclass ConnectivityCalculator:\r\n\tdef __init__(self):\r\n\t\t\"\"\"\r\n\t\tInitiates the class\r\n\t\t\"\"\"\r\n\t\tself.output_dir = \"\"\r\n\t\tself.network_files = list() # network files\r\n\t\tself.raw_distance_components = dict()\r\n\t\tself.thread_list = list() # all threads\r\n\t\tself.threads = 30\r\n\r\n\tdef getCmdArguments(self):\r\n\t\t\"\"\"\r\n\t\tRetrieves the command line arguments\r\n\t\t\"\"\"\r\n\t\tprint(\"Retrieving command line arguments...\")\r\n\t\tparser = argparse.ArgumentParser(prog='network_connectivity.py')\r\n\t\tparser.add_argument(\"-n\", \"--network_file_dir\", help=\"The directory with the to be used network files in it\", required=True)\r\n\t\tparser.add_argument(\"-o\", \"--output_dir\", help=\"The directory to output the final results in\", required=False, default=\"./\")\r\n\t\tparser.add_argument(\"-c\", \"--threads\", help=\"Number of threads to use (default = 30)\", required=False, default=30)\r\n\t\targs = parser.parse_args()\r\n\r\n\t\tif os.path.isdir(args.output_dir):\r\n\t\t\tself.output_dir = args.output_dir\r\n\t\t\tself.open_result_file()\r\n\t\telse:\r\n\t\t\tsys.exit(\"The given output directory is not valid\")\r\n\r\n\t\tif os.path.isdir(args.network_file_dir):\r\n\t\t\tnetwork_files = glob.glob(args.network_file_dir + \"/*.network\")\r\n\t\t\tif len(network_files) != 0:\r\n\t\t\t\tself.network_files = network_files\r\n\t\t\telse:\r\n\t\t\t\tsys.exit(\"No network files found in the given directory\")\r\n\t\telse:\r\n\t\t\tsys.exit(\"The given network directory is not valid\")\r\n\t\ttry:\r\n\t\t\tself.threads = int(args.threads)\r\n\t\texcept:\r\n\t\t\tsys.exit(\"Not a valid number of threads...\")\r\n\t\tprint(\"Command line arguments retrieved...\")\r\n\r\n\tdef parse_network_files(self):\r\n\t\t\"\"\"\r\n\t\tParses the network files and puts the different components into the dictionary\r\n\t\t\"\"\"\r\n\t\tprint(\"Reading in all files...\")\r\n\t\tfor nw_file in self.network_files:\r\n\t\t\tself.raw_distance_components.update({nw_file:dict()})\r\n\t\t\tfile_in = open(nw_file)\r\n\t\t\tfile_in.readline()\r\n\t\t\tfor line in file_in:\r\n\t\t\t\tbgc1, bgc2, raw_distance, sim_squared, Jaccard, DSS, AI, raw_dss_non_anchor, raw_dss_anchor, non_anchor_domains, anchor_domains = line.split()[0:11]\r\n\t\t\t\tDSS = self.calculate_DSS(1, raw_dss_non_anchor, raw_dss_anchor, non_anchor_domains, anchor_domains)\r\n\t\t\t\tself.raw_distance_components[nw_file].update({(bgc1, bgc2):{\"J\":Jaccard, \"AI\":AI, \"DSS\":DSS}})\r\n\t\tprint(\"Done reading files...\")\r\n\r\n\tdef prepare_distance_with_weights_calculations(self):\r\n\t\t\"\"\"\r\n\t\tCalculates the distances with different weights for the Jaccard, AI and DSS\r\n\t\t\"\"\"\r\n\t\ttotal = 0\r\n\t\tfor nw_file in self.raw_distance_components.keys():\r\n\t\t\tself.thread_list = list()\r\n\t\t\tprint(\"Starting: \" + nw_file)\r\n\t\t\tself.current_file = nw_file\r\n\t\t\tfor Jw in np.arange(0.0, 1.05, 0.05):\r\n\t\t\t\tfor AIw in np.arange(0.0, 1.05, 0.05):\r\n\t\t\t\t\tfor DSSw in np.arange(0.0, 1.05, 0.05):\r\n\t\t\t\t\t\tJw = round(Jw, 2)\r\n\t\t\t\t\t\tAIw = round(AIw, 2)\r\n\t\t\t\t\t\tDSSw = round(DSSw, 2)\r\n\t\t\t\t\t\tif (Jw + AIw + DSSw) == 1.0:\r\n\t\t\t\t\t\t\tself.thread_list.append(NetworkConnectingThread(Jw, AIw, DSSw, self.raw_distance_components[nw_file], nw_file, str(Jw)+str(AIw)+str(DSSw)+nw_file))\r\n\t\t\t\t\t\t\ttotal += 1\r\n\t\t\tprint(\"total jobs for {} is {}\".format(nw_file, str(len(self.thread_list))))\r\n\t\t\tprint(\"Finished preparing threads...\")\r\n\t\t\tself.run_calculations()\r\n\t\t\tprint(\"Done with \" + nw_file)\r\n\t\tprint(\"Total number of jobs was: {}\".format(total))\r\n\t\t\r\n\r\n\tdef run_calculations(self):\r\n\t\t\"\"\"\r\n\t\truns all the threads that are needed\r\n\t\t\"\"\"\r\n\t\tprint(\"Starting to run threads...\")\r\n\t\tmy_current_threads = []\r\n\t\ttotal_jobs = len(self.thread_list)\r\n\t\tactive_threads = True\r\n\t\tthread_nr = 0\r\n\t\twhile total_jobs >= thread_nr or active_threads:\r\n\t\t\tif len(my_current_threads) < self.threads:\r\n\t\t\t\tif thread_nr <= total_jobs:\r\n\t\t\t\t\tif thread_nr < total_jobs:\r\n\t\t\t\t\t\tnew_thread = self.thread_list[thread_nr]\r\n\t\t\t\t\t\tnew_thread.start()\r\n\t\t\t\t\t\tmy_current_threads.append(new_thread)\r\n\t\t\t\t\tthread_nr += 1\r\n\t\t\t\t\t\r\n\t\t\tfor thread in my_current_threads:\r\n\t\t\t\tif not thread.isAlive():\r\n\t\t\t\t\tprint(\"finished thread: \" + str(thread))\r\n\t\t\t\t\tself.write_result_line(thread)\r\n\t\t\t\t\tthread.set_handled()\r\n\t\t\tif len(my_current_threads) == 0:\r\n\t\t\t\tactive_threads = False\r\n\t\t\telse:\r\n\t\t\t\tactive_threads = True\r\n\t\t\tmy_current_threads = [t for t in my_current_threads if not t.is_handled()]\r\n\r\n\tdef calculate_DSS(self, max_anchor_boost, raw_dss_non_anchor, raw_dss_anchor, non_anchor_domains, anchor_domains):\r\n\t\t\"\"\"\r\n\t\tCalculates the domain similarity score based on the given information\r\n\t\t\"\"\"\r\n\t\tDSS_boosts = {}\r\n\t\tfor anchor_boost in np.arange(1.0, float(1+max_anchor_boost), 1.0):\r\n\t\t\tif anchor_domains != 0 and non_anchor_domains != 0:\r\n\t\t\t\t# Calculate proportional weight to each kind of domain\r\n\t\t\t\tnon_anchor_weight = float(non_anchor_domains) / (float(non_anchor_domains) + (float(anchor_domains) * float(anchor_boost)))\r\n\t\t\t\tanchor_weight = (float(anchor_domains) * float(anchor_boost)) / (float(non_anchor_domains) + (float(anchor_domains) * float(anchor_boost)))\r\n\t\t\t\t# scale the raw_dss_non_anchor and raw_dss_anchor\r\n\t\t\t\tDSS = (float(non_anchor_weight) * float(raw_dss_non_anchor)) + (float(anchor_weight) * float(raw_dss_anchor))\r\n\t\t\telif anchor_domains == 0:\r\n\t\t\t\tDSS = raw_dss_non_anchor\r\n\t\t\telse: #only anchor domains present\r\n\t\t\t\tDSS = raw_dss_anchor\r\n\t\t\tDSS_boosts.update({anchor_boost:(DSS)}) # DSS is now still distance, which is needed (1 - DSS, to get similarity)\r\n\t\treturn DSS_boosts\r\n\r\n\tdef open_result_file(self):\r\n\t\t\"\"\"\r\n\t\tOpens the result file that will contain the final result\r\n\t\t\"\"\"\r\n\t\tself.rf = open(self.output_dir + \"/connectivity_results.tsv\", 'w')\r\n\t\tself.rf.write(\"File\\tcutoff\\tJw\\tAIw\\tDSSw\\ttotal_bgcs\\tnr_of_clusters\\tbiggest_cluster_size\\tsmallest_cluster_size\\tnr_of_singletons\\n\")\r\n\r\n\tdef write_result_line(self, finished_thread):\r\n\t\t\"\"\"\r\n\t\tWrites the results to the final output file\r\n\t\t\"\"\"\r\n\t\tprint(\"writing results of: \" + str(finished_thread))\r\n\t\tself.rf.write(finished_thread.get_result())\r\n\r\n\r\nclass NetworkConnectingThread(threading.Thread):\r\n\t\"\"\"\r\n\tA class to use for multithreading, extends the already existing threading.Thread\r\n\t\"\"\"\r\n\tdef __init__(self, Jw, AIw, DSSw, distance_dict, current_file, ID):\r\n\t\t\"\"\"\r\n\t\tInitiates the class with the given arguments\r\n\t\t\"\"\"\r\n\t\tthreading.Thread.__init__(self)\r\n\t\tself.ID = ID\r\n\t\tself.result_line = \"\"\r\n\t\tself.Jw = Jw\r\n\t\tself.AIw = AIw\r\n\t\tself.DSSw = DSSw\r\n\t\tself.distance_dict = distance_dict\r\n\t\tself.current_file = current_file\r\n\t\tself.handled = False\r\n\r\n\tdef run(self):\r\n\t\t\"\"\"\r\n\t\tWhen Thread.start() is called on a Thread object, this will be called by the start() method in turn.\r\n\t\tCalculates the connectivity per file, with different cutoffs\r\n\t\t\"\"\"\r\n\t\tbgc_lists = dict()\r\n\t\tfor bgc_pair in self.distance_dict.keys():\r\n\t\t\tbgc1 = bgc_pair[0]\r\n\t\t\tbgc2 = bgc_pair[1]\r\n\t\t\tJaccard = self.distance_dict[bgc_pair][\"J\"]\r\n\t\t\tAI = self.distance_dict[bgc_pair][\"AI\"]\r\n\t\t\tDSS = self.distance_dict[bgc_pair][\"DSS\"]\r\n\t\t\tfor anchor_boost in DSS.keys():\r\n\t\t\t\tif not bool(bgc_lists):\r\n\t\t\t\t\tbgc_lists = {key: {float(cutoff)/10:set() for cutoff in range(2, 9, 1)} for key in DSS.keys()}\r\n\t\t\t\tdistance = (float(Jaccard) * self.Jw) + (float(AI) * self.AIw) + (float(DSS[anchor_boost]) * self.DSSw)\r\n\t\t\t\tfor cutoff in range(2, 9, 1):\r\n\t\t\t\t\tcutoff = float(cutoff) / 10.0\r\n\t\t\t\t\tif distance < cutoff:\r\n\t\t\t\t\t\tbgc_lists[anchor_boost][cutoff].add((bgc1,bgc2))\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tbgc_lists[anchor_boost][cutoff].add((bgc1, bgc1)) # only connected to itself\r\n\t\t\t\t\t\tbgc_lists[anchor_boost][cutoff].add((bgc2, bgc2)) # only connected to itself\r\n\r\n\t\tfor ab in bgc_lists.keys():\r\n\t\t\tfor cutoff in bgc_lists[ab].keys():\r\n\t\t\t\tself.current_bgcs = set(bgc_lists[ab][cutoff])\r\n\t\t\t\tself.connect_bgcs(cutoff)\r\n\t\t\t\t\r\n\t\ttime_end = time.clock()\r\n\r\n\tdef connect_bgcs(self, cutoff):\r\n\t\t\"\"\"\r\n\t\tConnects the bgcs in the list by merging sets that have a union\r\n\t\t\"\"\"\r\n\t\tg = networkx.Graph()\r\n\t\tfor bgc_set in self.current_bgcs:\r\n\t\t\tg.add_edge(*bgc_set)\r\n\t\tself.create_result_line(networkx.connected_components(g) , cutoff)\r\n\r\n\tdef create_result_line(self, result, cutoff):\r\n\t\t\"\"\"\r\n\t\tWrites the results to the final output file\r\n\t\t\"\"\"\r\n\t\tcluster_summaries = [len(x) for x in result]\r\n\t\ttotal_bgcs = sum(cluster_summaries)\r\n\t\tnr_of_singletons = cluster_summaries.count(1)\r\n\t\tnr_of_clusters = len(cluster_summaries) - nr_of_singletons\r\n\t\ttry:\r\n\t\t\tbiggest_cluster_size = max(cluster_summaries)\r\n\t\t\tif 1 in cluster_summaries:\r\n\t\t\t\tcluster_summaries.remove(1)\r\n\t\t\tsmallest_cluster_size = min(cluster_summaries)\r\n\t\texcept:\r\n\t\t\tbiggest_cluster_size = 1\r\n\t\t\tsmallest_cluster_size = 1\r\n\t\tself.result_line += \"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(self.current_file, cutoff, self.Jw, self.AIw, self.DSSw, total_bgcs, nr_of_clusters, biggest_cluster_size, smallest_cluster_size, nr_of_singletons)\r\n\r\n\tdef get_result(self):\r\n\t\t\"\"\"\r\n\t\tReturns the results\r\n\t\t\"\"\"\r\n\t\treturn self.result_line\r\n\t\r\n\tdef set_handled(self):\r\n\t\t\"\"\"\r\n\t\tTrue if the thread is finished\r\n\t\t\"\"\"\r\n\t\tself.handled = True\r\n\r\n\r\n\tdef is_handled(self):\r\n\t\t\"\"\"\r\n\t\tReturns if the thread is finished running\r\n\t\t\"\"\"\r\n\t\treturn self.handled\r\n\t\t\r\ndef main():\r\n\tcc = ConnectivityCalculator()\r\n\tcc.getCmdArguments()\r\n\tcc.open_result_file()\r\n\tcc.parse_network_files()\r\n\tcc.prepare_distance_with_weights_calculations()\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","sub_path":"network_connectivity.py","file_name":"network_connectivity.py","file_ext":"py","file_size_in_byte":9233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"546744642","text":"from __future__ import division\n\n\n\"\"\"\n\n\nThis code has been through a number of iterations.\n\nFirst as a PyGTK+ application, which used object representation of data\nprinciply documented in brewerslabData.py\n\nThis started to transition to a GoogleAppEngine application, however this\nbecame a difficult converstion.\n\nSomewhere along the way an android app was created.\n\nngData.py was introduced via to bridge the google app engine calls via a \nmysql backend. The frontend then started to move into it's current \nweb based form in the metroui directory.\n\n\nThe metroui doesn't support creating processes, these are best done via\ntestRecipe.py which generated the mysql statements.\n\n\n\n\n\"\"\"\n\npublic =1 \n\n\n################################################################################################################################################\nfrom brewerslabEngine import *\nfrom brewerslabData import *\nimport time\n\n\n#\n#\n#########################################################################################################################################################\n#########################################################################################################################################################\n#########################################################################################################################################################\n#\n#\n#\tStores\n#\n#\n#########################################################################################################################################################\n#########################################################################################################################################################\n#########################################################################################################################################################\n#\n#\n\n\nuserid=\"testuser\"\n\n\n\n\npresets=brwlabPresetData( userid )\n\nif os.path.exists(\"store/%s/store\" %(userid)):\n\tstores = pickle.loads( open(\"store/%s/store\" %(userid)).read() )\nelse:\n\tstores=brwlabInventory()\n\n# Update everything should be created via the Data objects and not\n# directly. presets.getMisc, presets.getConsumable will return\n# a preset or create a new object.\n# The pre-existing flag will be set if it was already in the database\n# although this doesn't necessairly mean it wasn't created by us\n# previously.\n\ntesco = presets.getSupplier(\"Tesco\")\n\nwater = presets.getMisc(\"Bottled Water (2L)\")\nwater.category=\"Water\"\nwater.subcategory=\"Bottled Water\"\nwater.supplier=tesco\nwater.qty_multiple = 2\n\nfor wate in range(38):\n\tpurchase=brwlabPurchase(water)\n\tpurchase.qty=2\n\tpurchase.price=0.085\n\tstores.addPurchase( purchase )\n\n############################################################\n\n\nslurry = presets.getYeast(\"Yeast Slurry\")\nslurry.atten=73\nslurry.category=\"Yeast\"\nslurry.subcategory=\"Ale\"\n\npurchase=brwlabPurchase( slurry )\npurchase.qty=1\npurchase.price=0.00\npurchase.purchaseDate(\"2010-10-18\")\npurchase.bestBeforeDate(\"2013-12-1\")\nstores.addPurchase( purchase )\n\n\n\nsafale04 = presets.getYeast(\"Safale S04\")\nsafale04.atten=73\nsafale04.category=\"Yeast\"\nsafale04.subcategory=\"Ale\"\n\nhcg = presets.getSupplier(\"Homebrew Centre Grimsby\")\n\npurchase=brwlabPurchase(safale04)\npurchase.qty=1\npurchase.price=1.99\nstores.addPurchase( purchase )\n\nfor c in range(3):\n\tpurchase=brwlabPurchase( safale04 )\n\tpurchase.qty=1\n\tpurchase.price=1.99\n\tpurchase.supplier=hcg\n\tpurchase.purchaseDate(\"2010-12-24\")\n\tpurchase.bestBeforeDate(\"2011-12-24\")\n\tstores.addPurchase( purchase )\n\n############################################################\n\nmarisOtter = presets.getFermentable(\"Maris Otter\")\n\nfor maris in range(6):\n\n\tpurchase=brwlabPurchase( marisOtter )\n\tpurchase.qty=1000\n\tpurchase.price=0.00148\n\tpurchase.supplier=hcg\n\tpurchase.purchaseDate(\"2010-10-16\")\n\tpurchase.bestBeforeDate(\"2011-10-16\")\n\tstores.addPurchase( purchase )\n\n\nbrewuk=presets.getSupplier(\"BrewUK\")\n\nbiscuit = presets.getFermentable(\"Biscuit\")\n\npurchase=brwlabPurchase( biscuit )\npurchase.qty=500\npurchase.price=0.0044\npurchase.supplier=brewuk\npurchase.purchaseDate(\"2010-10-18\")\npurchase.bestBeforeDate(\"2011-12-1\")\nstores.addPurchase( purchase )\n\n\nsugar = presets.getConsumable(\"priming sugar\")\nsugar.category=\"primingsugar\"\n\npurchase=brwlabPurchase( sugar )\npurchase.qty=400\npurchase.price=.001\npurchase.suppler=tesco\nstores.addPurchase(purchase)\n\n\ncrystal = presets.getFermentable(\"Crystal 150\")\n\npurchase=brwlabPurchase( crystal )\npurchase.qty=750\npurchase.price=0.00159\npurchase.supplier=hcg\npurchase.purchaseDate(\"2010-10-16\")\npurchase.bestBeforeDate(\"2011-10-16\")\nstores.addPurchase( purchase )\n\ngoldensyrup = presets.getFermentable(\"Golden Syrup\")\ngoldensyrup.calculateFromYield(100)\ngoldensyrup.color=0\ngoldensyrup.isAdjunct=1\ngoldensyrup.addBoil=1\ngoldensyrup.category=\"Adjunct\"\n\npurchase=brwlabPurchase( goldensyrup )\npurchase.qty=200\npurchase.price=0.0189\npurchase.supplier=tesco\nstores.addPurchase( purchase )\n\n\n\nhoney = presets.getFermentable(\"Honey\")\nhoney.calculateFromYield(76)\nhoney.color=0\nhoney.isAdjunct=1\nhoney.addBoil=1\nhoney.category=\"Adjunct\"\n\npurchase=brwlabPurchase( honey )\npurchase.qty=3040\npurchase.price=0.00197058\npurchase.supplier=tesco\npurchase.purchaseDate(\"2010-12-20\")\npurchase.bestBeforeDate(\"2012-06-30\")\nstores.addPurchase( purchase )\n\n\npurchase=brwlabPurchase( marisOtter )\npurchase.qty=3000\npurchase.price=0.0014666667\npurchase.supplier=hcg\npurchase.purchaseDate(\"2010-12-24\")\npurchase.bestBeforeDate(\"2011-12-24\")\nstores.addPurchase( purchase )\n\n\n\ntorrifiedwheat = presets.getFermentable(\"Torrified Wheat\",78)\ntorrifiedwheat.calculateFromYield(78)\ntorrifiedwheat.colour=2\ntorrifiedwheat.isGrain=1\ntorrifiedwheat.mustMash=1\ntorrifiedwheat.category=\"Grain\"\ntorrifiedwheat.subcategory=\"Head Retention\"\n\npurchase=brwlabPurchase( torrifiedwheat )\npurchase.qty=500\npurchase.price=0.0015\npurchase.supplier=hcg\npurchase.purchaseDate(\"2010-12-24\")\npurchase.bestBeforeDate(\"2011-12-24\")\nstores.addPurchase( purchase )\n\n\ncaramalt = presets.getFermentable(\"Caramalt\")\ncaramalt.calculateFromYield(75)\ncaramalt.colour=14\ncaramalt.isGrain=1\ncaramalt.mustMash=0\ncaramalt.category=\"Grain\"\ncaramalt.subcategory=\"Speciality\"\n\n\ncaragold = presets.getFermentable(\"CaraGold\")\ncaragold.calculateFromYield(74)\ncaragold.colour=9\ncaragold.isGrain=1\ncaragold.mustMash=0\ncaragold.category=\"Grain\"\ncaragold.subcategory=\"Speciality\"\nthermometer=presets.getEquipment(\"Digital Thermometer\")\nthermometer.mustSterilise=1\njug=presets.getEquipment(\"Jug (1.5L)\")\njug.mustSterilise=1\nsaucepan=presets.getEquipment(\"Saucepan\")\nbottler=presets.getEquipment(\"Little Bottler\")\nfunnel=presets.getEquipment(\"Funnel\")\nsyringe=presets.getEquipment(\"2.5ml Syringe\")\nfilteringFunnel=presets.getEquipment(\"Filtering Funnel\")\nfilteringFunnel.mustSterilise=1\nsmalljug=presets.getEquipment(\"Small Jug\")\nsmalljug.mustSterilise=1\nplastictapfilter=presets.getEquipment(\"Plastic Tap Filter\")\nplastictapfilter.mustSterilise=1\nfermentationbin6gal=presets.getEquipment(\"Fermentation Bin (6 Gal)\")\nfermentationbin6gal.mustSterilise=1\nfermentationbin6gal.subEquipment.append( plastictapfilter )\nfermentationbin6gal.weight=1125\t# weight in grames wihtout lid, but with taps etc\nfermentationbin6gal.weightlids=1131 # weight in grames with lid\nfermentationbin6gal.dead_space=1.5\t# litres\t\tmeasured\t\t\nfermentationbin=presets.getEquipment(\"Fermentation Bin\")\nfermentationbin.mustSterilise=1\nfermentationbin.subEquipment.append( plastictapfilter )\nfermentationbin.weight=873\t# weight in grames\nfermentationbin.deadspace=3.34\t# litres\t\tmeasured 30thJan2010\nfermentationbin.dead_space=2\t\nsparge_arm=presets.getEquipment(\"Sparge Arm\")\nsparge_arm.mustSterilise=1\nsterilisingPowder = presets.getConsumable(\"Sterilising Powder\")\nsterilisingPowder.dosage=4.5\nsterilisingPowder.unit=\"tsp\"\ntimer =presets.getEquipment(\"Timer\")\n\njerry10l =presets.getEquipment(\"10l Kettle\")\njerry10l.volume=10\njerry10l.mustSterilise=0\njerry10l.dead_space=0\n\n\ncopperkettle=presets.getSupplier(\"Copper Kettle Homebrewing\")\nmash_tun_tap=presets.getEquipment(\"Mash Tun Tap\")\nmash_tun_tap.mustSterilise=1\n\nsaucepan=presets.getEquipment(\"Saucepan\")\nsaucepan.mustSterilise=1\nmashpaddle=presets.getEquipment(\"Mash Paddle\")\nmashpaddle.mustSterilise=1\n\nhydrometer=presets.getEquipment(\"Hydrometer\")\nhydrometer.mustSterilise=1\ntrialjar=presets.getEquipment(\"Trial Jar\")\ntrialjar.mustSterilise=1\nslottedspoon=presets.getEquipment(\"Slotted Spoon\")\nslottedspoon.mustSterilise=1\nthermometer3=presets.getEquipment(\"Thermometer\")\nthermometer3.mustSterilise=1\nthermometer2=presets.getEquipment(\"Thermometer\")\nthermometer2.mustSterilise=1\nimmersionchiller=presets.getEquipment(\"Immersion Chiller\")\nimmersionchiller.mustSterilise=1\nimmersionheater=presets.getEquipment(\"Immersion Heater\")\nimmersionheater.mustSterilise=1\nlargepaddle=presets.getEquipment(\"Large Paddle\")\nlargepaddle.mustSterilise=1\nmash_tun=presets.getEquipment(\"Mash Tun\")\nmash_tun.mustSterilise=1\nmash_tun.dead_space=2.25\nmash_tun.subEquipment.append( mash_tun_tap )\nhlt=presets.getEquipment(\"Hot Liquor Tank\")\nhlt.image=\"images/hlt.png\"\nhlt.mustSterilise=1\nhlt.heatPower=1.6\nhlt.description=\"A Hot Liquor Tank is used to heat water.\"\nhlt.instructions=\"A Hot Liquor Tank can be made from a fermentation bin with electric kettles installed.\"\nhlt.dead_space=3.5\nkettle70l =presets.getEquipment(\"70l Kettle\")\nkettle70l.volume=70\nkettle70l.mustSterilise=1\nkettle70l.dead_space=2\t\t# estimate 30/1/2010\nkettle70l.boilVolume=60\n\npurchase=brwlabPurchase( caragold )\npurchase.qty=1000\npurchase.price=0.00245\npurchase.supplier= copperkettle\npurchase.purchaseDate(\"2010-12-24\")\npurchase.bestBeforeDate(\"2011-12-24\")\nstores.addPurchase( purchase )\n\n\n\n############################################################\n\n\nhallertauhersbrucker=presets.getHop(\"Hallertau Hersbrucker\",2.4)\n\npurchase=brwlabPurchase( hallertauhersbrucker )\npurchase.qty=100\npurchase.hop_actual_alpha = 2.4\npurchase.price=0.00199\npurchase.supplier=copperkettle\npurchase.purchaseDate(\"2010-10-14\")\npurchase.bestBeforeDate(\"2014-10-14\")\nstores.addPurchase( purchase )\n\n\nwillamette=presets.getHop(\"Willamette\",4.8)\n\npurchase=brwlabPurchase( willamette )\npurchase.hop_actual_alpha=4.8\npurchase.hop_aged_alpha = 3.77\npurchase.hop_actual_alpha = 3.77\npurchase.qty=100\npurchase.price=0.0199\npurchase.supplier=copperkettle\npurchase.purchaseDate(\"2010-10-14\")\nstores.addPurchase( purchase )\n\n\nworcester=presets.getSupplier(\"Worcester Hop Shop\")\n\nnorthdown = presets.getHop(\"Northdown\",7.5)\n\npurchase=brwlabPurchase( northdown )\npurchase.qty=75\npurchase.price=0.0199\npurchase.supplier=worcester\npurchase.purchaseDate(\"2010-10-14\")\nstores.addPurchase( purchase )\n\n\nbrewmart = presets.getSupplier(\"Sheffield Brewmart\")\n\n#hallertauhersbrucker22 = presets.getHop(\"Hallertau Hersbrucker\",2.2)\n#purchase=brwlabPurchase( hallertauhersbrucker22 )\npurchase=brwlabPurchase( hallertauhersbrucker )\npurchase.hop_actual_alpha = 2.2\npurchase.hop_aged_alpha = 1.92\npurchase.hop_actual_alpha = 2.2\npurchase.qty=70\npurchase.price=0.044419\npurchase.supplier=brewmart\npurchase.purchaseDate(\"2010-4-2\")\npurchase.bestBeforeDate(\"2014-4-2\")\nstores.addPurchase( purchase )\n\n\nsaaz= presets.getHop(\"SaaZ\",3.5)\n\npurchase=brwlabPurchase( saaz )\npurchase.qty=100\npurchase.price=0.0199\npurchase.supplier=copperkettle\npurchase.purchaseDate(\"2010-10-14\")\nstores.addPurchase( purchase )\n\n\nglacier= presets.getHop(\"Glacier\",5.6)\n\npurchase=brwlabPurchase( glacier )\npurchase.qty=303333\npurchase.price=0.01023\npurchase.supplier=hcg\npurchase.purchaseDate(\"2010-4-10\")\npurchase.bestBeforeDate(\"2012-2-2\")\nstores.addPurchase( purchase )\n\n\ncascade= presets.getHop(\"Cascade\",5.8)\ncascade.addAt=60\t\t\t## Is this still needed?\n\npurchase=brwlabPurchase( cascade )\npurchase.qty=100\npurchase.price=0.0199\npurchase.supplier=worcester\npurchase.hop_actual_alpha=5.8\npurchase.hop_aged_alpha = 5.2\t\t# todo automatically calculate this one day\npurchase.hop_actual_alpha=5.2\npurchase.purchaseDate(\"2010-10-14\")\nstores.addPurchase( purchase )\n\n\n\nchallenger= presets.getHop(\"challenger\",7.6)\n\n\npurchase=brwlabPurchase( challenger )\npurchase.qty=75\npurchase.price=0.0199\npurchase.supplier=worcester\npurchase.purchaseDate(\"2010-10-14\")\nstores.addPurchase( purchase )\n\n\ncentennial= presets.getHop(\"Centennial\",11.7)\n\n\n\nfor wate in range(4):\n\tpurchase=brwlabPurchase(water)\n\tpurchase.qty=2\n\tpurchase.price=0.085\n\tpurchase.purchaseDate(\"2011-1-12\")\n\tstores.addPurchase( purchase )\n\nfor wate in range(0):\n\tpurchase=brwlabPurchase(water)\n\tpurchase.qty=2\n\tpurchase.price=0.085\n\tpurchase.purchaseDate(\"2011-1-18\")\n\tstores.addPurchase( purchase )\n\nfor wate in range(0):\n\tpurchase=brwlabPurchase(water)\n\tpurchase.qty=2\n\tpurchase.price=0.085\n\tpurchase.purchaseDate(\"2011-1-20\")\n\tstores.addPurchase( purchase )\n\n\ncitric = presets.getConsumable(\"Citric Acid\")\ncitric.unit=\"tsp\"\n\nprotofloc = presets.getConsumable(\"Protofloc\")\nprotofloc.copper_fining=1\nprotofloc.copper_fining=0.25\nprotofloc.unit=\"tablet\" \n\ncampdenTablet= presets.getConsumable(\"Campden Tablets\")\ncampdenTablet.unit=\"tablet\"\ncrs= presets.getConsumable(\"AMS (CRS)\")\ncrs.unit=\"ml\"\nsalifert= presets.getConsumable(\"Salifert Alkaline Test\")\nsalifert.unit=\"tests\"\nburton = presets.getConsumable(\"Burton Water Salts\")\nburton.unit=\"tsp\"\n\n\nyeastvit = presets.getConsumable(\"Yeast Vit\")\nyeastvit.yeast_nutrient=2.5\nyeastvit.unit=\"gm\"\n\n\ncopperkettle=presets.getSupplier(\"Copper Kettle Homebrewing\")\npurchase=brwlabPurchase( protofloc )\npurchase.qty=10\npurchase.qty_multiple=1\npurchase.price=0.125\npurchase.supplier= copperkettle\npurchase.purchaseDate(\"2010-12-24\")\npurchase.bestBeforeDate(\"2011-12-24\")\nstores.addPurchase( purchase )\n\n\n\nmaltmiller=presets.getSupplier(\"The Malt Miller\")\nnorthernbrewer= presets.getHop(\"Northern Brewer\",6.1)\n\npurchase=brwlabPurchase( northernbrewer )\npurchase.qty=1004\npurchase.price=0.0255\npurchase.supplier=maltmiller\npurchase.purchaseDate(\"2011-1-24\")\npurchase.bestBeforeDate(\"2012-1-24\")\n#stores.addPurchase( purchase )\n\n\npurchase=brwlabPurchase( centennial )\npurchase.qty=100\npurchase.price=0.0255\npurchase.supplier=maltmiller\npurchase.purchaseDate(\"2011-1-24\")\npurchase.bestBeforeDate(\"2012-1-24\")\n#stores.addPurchase( purchase )\n\nsaflager=presets.getYeast(\"Saflager W-34/70\")\nsaflager.atten=73\nsaflager.category=\"Yeast\"\nsaflager.subcategory=\"Lager\"\n\npurchase=brwlabPurchase( saflager )\npurchase.qty=1\npurchase.price=1.50\npurchase.supplier=maltmiller\npurchase.purchaseDate(\"2011-1-24\")\npurchase.bestBeforeDate(\"2011-2-24\")\n#stores.addPurchase( purchase )\n\n\n\n\n\n\n\n#\n#\n#########################################################################################################################################################\n#########################################################################################################################################################\n#########################################################################################################################################################\n#\n#\n#\tProcess\n#\n#\n#########################################################################################################################################################\n#########################################################################################################################################################\n#########################################################################################################################################################\n#\n#\n\n\n\nmyprocessK=brwlabProcess()\nmyprocessK.credit=\"Adam Allen\"\nmyprocessK.name=\"40AG\"\n\n\nmyprocessK.description=\"Worsdell Brewing - An updated process for use in the entirely within the garage, with the introduction of basic water treatment\"\n\nmyprocessK.boilers = [kettle70l]\nmyprocessK.hlt = hlt\nmyprocessK.mash_tun = mash_tun\n\n\n\n\n# Preparation\nstep = myprocessK.brewday.newstep(\"Preparation\")\n#step.newSubStep( (\"If using a fermentation-fridge move it into position, it is necessary to wait >12 hours after moving the fridge before using.\",{'complete':1}) )\nstep.newSubStep( (\"Add ice-boxes to the freezer, these will be used to cool the immersion chiller water\",{'complete':1}) )\n#step.newSubStep( (\"Ensure batteries for thermometers are available\",{'complete':1}))\n#step.newSubStep( (\"Ensure clean towells are available as well as clean dry cloths for the floor\",{'complete':1}))\nstep.text=\"The day before brew day the preparation above should be carried out, as well as checking stock/ingredients are available\"\n\n\n\n# Gather things\nstep = myprocessK.brewday.newstep(\"Assemble Mash/Lauter Tun\")\nstep.text=\"Assemble the bucket in bucket mash tun, complete with scavenger tube. Gather Sparge Arm, Vorlauf Funnel Paddle and digital thermometer.\"\nstep.img=['assemblemashtun.png']\n\n# Gather things\nstep = myprocessK.brewday.newstep(\"Assemble Hot Liquor Tank\")\nstep.text=\"Assemble the hot liquor tank, complete with latstock and thermometer probe\"\nstep.img=['assemblehlt.png']\n\n# Gather things\n#step = myprocessK.brewday.newstep(\"Assemble Kettle\")\n#step.text=\"Assemble the kettles with ball-valve tap. Use a stainless steel washer on the inside and pfte tape around thread. \"\n#step.img=['assemblekettle.png']\n\n# Gather things\nstep = myprocessK.brewday.newstep(\"Assmeble Fermentation Bin\")\nstep.text=\"Assemble the fermentation bin, complete with back filter\"\nstep.img=['assemblefv.png']\n\n\n# Gather things\n#step = myprocessK.brewday.newstep(\"Gather small stockpots\")\n#step.text=\"Gather small stockpots and measuring spoons, these will be used to contain the grain\"\n\n\n\n## Gather things\n#step = myprocessK.brewday.GatherThings()\n#step.text=\"The grain can be measured later\"\n\n# Clean Equipment\nstep = myprocessK.brewday.newstep(\"Clean Equipment\")\nstep.text=\"Clean equipment with a mild detergent. It is important to clean equipment before use, any equipment used before the boil only needs to be cleaned as the wort will be sterilised during the boil. Equipment used after the boil must either be sterilised with sterilising solution, or limited equipment may be sterilised in the boiler. Note: don't use 2 real taps for the HLT, use one dummy tap. The equipment to clean is: hlt, sparge arm, mash tun, jug, large paddle, thermometer, stoarge box, kettles and jerry can. \"\nstep.addEquipment( mashpaddle )\nstep.addEquipment( hlt )\nstep.addEquipment( sparge_arm )\nstep.addEquipment( mash_tun )\nstep.addEquipment( jug ) # try do without a jug\nstep.addEquipment( smalljug )\nstep.addEquipment( largepaddle )\nstep.addEquipment( thermometer )\n#step.addEquipment( storagebox )\n#step.addEquipment( filteringFunnel )\njar2l=presets.getConsumable(\"2l Jar\")\njar2l.muststerilise=1\njar400ml=presets.getConsumable(\"400ml Jar\")\njar400ml.muststerilise=1\npfte=presets.getConsumable(\"PFTE Tape\")\npfte.unit=\"m\"\nmeasuringspoon=presets.getEquipment(\"Measuring Spoon\")\ncrowncaps=presets.getConsumable(\"Crown Caps\")\ncrowncaps.category=\"bottlecaps\"\nbottles=presets.getConsumable(\"500ml glass bottle\")\nbottles.volume=474\nbottles.fullvolume=500\nbottles.caprequired=1\nbottles.category=\"bottle\"\nmuslinbag=presets.getConsumable(\"Muslin Bag\")\nmeasuringspoon=presets.getEquipment(\"Measuring Spoon\")\ncrowncaps=presets.getConsumable(\"Crown Caps\")\ncrowncaps.category=\"bottlecaps\"\nbottles=presets.getConsumable(\"500ml glass bottle\")\nbottles.volume=474\nbottles.fullvolume=500\nbottles.caprequired=1\nbottles.category=\"bottle\"\nmuslinbag=presets.getConsumable(\"Muslin Bag\")\nbottlebrush=presets.getEquipment(\"Bottle Brush\")\nstep.addEquipment( jerry10l )\nstep.newSubStep( (\"Clean HLT\",{'complete':1}) )\nstep.newSubStep( (\"Clean FV\",{'complete':1}) )\nstep.newSubStep( (\"Clean Kettle\",{'complete':1}) )\nstep.newSubStep( (\"Clean Mashtun\",{'complete':1}) )\n\n# Clean work area\nstep = myprocessK.brewday.newstep(\"Clean Work Area\")\nstep.text=\"Clean the entire work area with mild detergent. It is important to ensure the entire work area is clean before commencing the brew day\"\n\n\n\nstep.img=[\"sterilise_setup1.png\"]\n\n\n\n### modified for a more logical break in the proceedings.\n\n\n\n# Fill the HLT\nstep = myprocessK.brewday.newstep(\"Fill HLT (for Mash Liquor)\")\nstep.text=\"Fill the HLT with ...mash_liquid_6...L of water for the mash and add a campden tablet to remove chlorine, stir and leave for 5 minutes\"\nstep.addConsumable( campdenTablet, 1)\n# Fill the HLT\nstep = myprocessK.brewday.newstep(\"Treat Mash Liquor\")\nstep.text=\"Treat the mash water to remove alkalinity, this should be done 5 minutes after adding the campden tablet. The low-resolution method for alkalinity test is used as the alkalinity is very hard. Once the salifert solution is orange/pink \"\nstep.addConsumable( salifert , 1)\nstep.newSubStep( (\"Add 2ml of water into the test vial for the Salifert Alkalinity Test.\",{'complete':1}))\nstep.newSubStep( (\"Add 2 drops of KH-Indicator to the test vial.\",{'complete':1}))\nstep.newSubStep( (\"Add 1ml of reagent to the fine granularity syringe.\",{'complete':1}))\nstep.newSubStep( (\"Add drop by drop to the, mixing the solution each time, the colour needs to change from blue/green to orange/pink, turn the syringe upside down and use the reading at the upper part of the black piston\",{'complete':1}))\nstep.attention=\"Note: only add 75%% of the CRS adjustment during this step - the calculations in this step only calculate 75%%\"\nstep.newSubStep( (\"Add CRS based upon the calculations below to the mash liquid and stir. (75%% calcualted in this step)\",{'complete':1}))\nstep.fields.append( ('Mashwater PH','mashWaterPH','') )\nstep.fields.append( ('Mash Salifert Reagent Remaining','__mashSalifertReagent','0.10'))\nstep.widgets['mashAlkalinity'] = ('salifertAlkalinity',['__mashSalifertReagent'])\nstep.fields.append( ('Mash Alkalinity','mashAlkalinity',''))\nstep.widgets['mashCrsAdjustment'] = ('mashCrsAdjustment',['__mashSalifertReagent'])\nstep.fields.append( ('Mash CRS Adjustment','mashCrsAdjustment',''))\nstep.img=['treatwater.png']\n\n\nstep = myprocessK.brewday.newstep(\"Measure Treated Mash Liquor\")\nstep.text=\"In the previous step we added 75%% of the CRS adjustment we should remeasure the treated mash liquor (high resolution test) and decide if to add more adjustment\"\nstep.addConsumable( salifert , 2)\nstep.newSubStep( (\"Add 4ml of water into the test vial for the Salifert Alkalinity Test.\",{'complete':1}))\nstep.newSubStep( (\"Add 4 drops of KH-Indicator to the test vial.\",{'complete':1}))\nstep.newSubStep( (\"Add 1ml of reagent to the fine granularity syringe.\",{'complete':1}))\nstep.newSubStep( (\"Add drop by drop to the, mixing the solution each time, the colour needs to change from blue/green to orange/pink, turn the syringe upside down and use the reading at the upper part of the black piston\",{'complete':1}))\nstep.newSubStep( (\"Add CRS based upon the calculations below to the mash liquid and stir.\",{'complete':1}))\nstep.fields.append( ('Mash Retest Salifert Reagent Remaining','__mashSalifertReagentRetest','0.10'))\nstep.widgets['mashAlkalinityRetest'] = ('salifertAlkalinityHighRes',['__mashSalifertReagentRetest'])\nstep.fields.append( ('Mash Alkalinity','mashAlkalinityRetest',''))\nstep.widgets['mashCrsAdjustmentRetest'] = ('mashCrsAdjustmentRetest',['__mashSalifertReagentRetest'])\nstep.fields.append( ('Mash CRS Adjustment','mashCrsAdjustmentRetest',''))\n\n\n\n\n# Fill the HLT\nstep = myprocessK.brewday.newstep(\"Begin heating mash water\")\nstep.text=\"(HLT) Heat the mash water to strike temperature + 5 degC (...strike_temp_5... degC)\"\nstep.attention=\"Do not turn on the temperature controller until the elements in the kettle are covered with water.\"\nstep.img=['treatwater.png']\n\n\n# Gather grain\nstep = myprocessK.brewday.newstep(\"Gather Grain\")\nstep.text=\"Gather the and measure the grain required for the brewday\"\nstep.auto=\"gatherthegrain\"\nstep.addConsumable(burton,2)\n# Note: there is a hardcoded assumption in cloudNG.py:compile() which assumes we have exactly 1 substep\nstep.newSubStep( (\"Add 1 teaspoon of gypsum -OR- 2 teaspoons of burton water salts to the grain.\",{'complete':1}))\t\t\n\t\t\t# this is dosage of gypsum correct, thought it might have been too much\n\n\n\n# Mash\nstep = myprocessK.brewday.newstep(\"Get Ready to Mash\")\nstep.text=\"Once the Mash Water has been heated to 65C then pre-heat the mash tun.\"\nstep.newSubStep( (\"Boil 1.5L of tap water and add to the mash tun, add the lid to the mash tun\",{'complete':1}))\n#step.auto=\"grainqty\"\nstep.img = ['mash.png']\n\n\n# Fill the Mash Tun\nstep = myprocessK.brewday.newstep(\"Fill the mash tun with mash liquid\")# and set aside the grain. During this step the mash tun should be well insulated to maintain a stable temperature\")\nstep.text=\"Fill the mashtun with the mash liquor in order the water is to ...strike_temp_5...C (Strike Temp ...strike_temp...C). The water in the HLT should be heated to 5degC higher than strke temp to account for some losses while transferring the liquid, however the temperature should be monitored. Note: if more water is used in the mash tun the strike temperature should be lower, if less water is used then the strike temperature should be higer.\"\nstep.prereq=\"Mash Water is at ...strike_temp_5...C\"\nstep.newSubStep( (\"Discard the water used for preheating the mash tun\",{'complete':1}))\nstep.newSubStep( (\"Fill the mash tun with ...mash_liquid...L of water heated to ...strike_temp_5...C.\", {'complete':1}) )\nstep.newSubStep( (\"Set aside 1.7L of boiling water and 1.7L of cold water which may optionally may be used for adjustment of temperature/consistency\", {'complete':1}))\nstep.attention=\"If the grain temperature is not between 15-20 degC then the calculations should be re-run to provide a hotter/colder strike temp.\"\n\n\n#\n#\n#\nmyprocessK.recipeUpgrades['grainthicknessMustBeGreaterThan'] = 1.35\n\n\n# Dough in the grain \nstep = myprocessK.brewday.newstep(\"Dough in the grain\")\nstep.text=\"(MASH) The temperature for mashing is important high temperatures will lead to extraction of tannins, low temperatures will not provide efficient conversion. Lower temperature conversion - around 64-66.6C will take longer but will produce a more complete conversion of complex starches to sugars resulting in more fermentation and a clean, lighter tasting beer. A high temperature conversion of 68.5-70 C will result in less starch conversion leaving a beer with more unfermentable dextrines. This will create a beer with a full body and flavor. Middle mash temperatures 67.69 C will result in medium bodied beers. The consistency of the mixture should be resemble porridge. (Note: this is still subject to refining in the past this was calculated with a ratio of 1.25 but recipes will be at least 1.35 with this process.\"\n\nstep.newSubStep( (\"With the temperature of the mash liquid at ...strike_temp...C stir in the grain.\", {'complete':1}))\nstep.newSubStep( (\"The aim is to mash at a temperature of ...target_mash_temp...C\", {'complete':1}))\nstep.newSubStep( (\"Cover and set aside for 60 minutes.\",{'complete':1,'kitchentimer':('a',3600) }))\nstep.newSubStep( (\"Take out the mash paddle\",{'complete':1,'kitchentimer':('a',3600) }))\nstep.newSubStep( (\"If after a few minutes the temperature difference is +/- 3degC of the ...target_mash_temp...C target then a temperature adjustment may be carried out with care.\", {'complete':1}))\nstep.newSubStep( (\"Press the button on the controller to start the mash timer.\", {'complete':1}))\nstep.newSubStep( (\"Take a sample of the mash to measure the PH\",{'complete':1}))\n\nstep.addEquipment( timer )\nstep.fields.append(('Ambinet Temp(C)','mash_ambient_temp',''))\nstep.fields.append(('Adjustment Needed','mash_adjusment_needed',''))\nstep.fields.append(('(Start) Mash Temp Acheived','mash_start_temp',''))\nstep.attention=\"The Temperature of the Grain Bed should remain below 75degC throughout.\"\nstep.img=[\"dough.png\"]\n\n\n\n\n\n\n\n\n# Fill the HLT\nstep = myprocessK.brewday.newstep(\"Fill HLT (for Sparge Liquor)\")\nstep.text=\"Fill the HLT so that it contains ...sparge_water...L of water for the sparge and add a campden tablet to remove chlorine and a level teaspoon of citric acid, stir and leave for 5 minutes\"\nstep.addConsumable( campdenTablet, 1)\nstep.fields.append(('(MID1) Mash Temp Acheived','mash_mid1_temp',''))\n\n# Fill the HLT\nstep = myprocessK.brewday.newstep(\"Treat Sparge Liquor\")\nstep.text=\"Treat the mash water to remove alkalinity, this should be done 5 minutes after adding the campden tablet. The high-resolution method for alkalinity test is used as the water will have some mash liuor left. Once the salifert solution is orange/pink \"\nstep.addConsumable( salifert , 1)\nstep.newSubStep( (\"Add 4ml of water into the test vial for the Salifert Alkalinity Test.\",{'complete':1}))\nstep.newSubStep( (\"Add 4 drops of KH-Indicator to the test vial.\",{'complete':1}))\nstep.newSubStep( (\"Add 1ml of reagent to the fine granularity syringe.\",{'complete':1}))\nstep.newSubStep( (\"Add drop by drop to the, mixing the solution each time, the colour needs to change from blue/green to orange/pink, turn the syringe upside down and use the reading at the upper part of the black piston\",{'complete':1}))\nstep.newSubStep( (\"Add the CRS based upon the calculations below to the sparge liquid and stir.\",{'complete':1}))\nstep.fields.append( ('Sparge Water PH','spargehWaterPH','') )\nstep.fields.append( ('Mash Salifert Reagent Remaining','__spargeSalifertReagent','0.10'))\nstep.widgets['spargeAlkalinity'] = ('salifertAlkalinityHignRes',['__spargeSalifertReagent'])\nstep.fields.append( ('Sparge Alkalinity','spargeAlkalinity',''))\nstep.widgets['spargeCrsAdjustment'] = ('spargeCrsAdjustment',['__spargeSalifertReagent'])\nstep.fields.append( ('Sparge CRS Adjustment','spargeCrsAdjustment',''))\nstep.img=['treatwater.png']\n\n\n# Fill the HLT \nstep = myprocessK.brewday.newstep(\"Heat Sparge Liquor\")\nstep.text=\"(MASH + SPARGE) The sparge water is expected to take around ...sparge_heating_time... minutes to heat.\"\nstep.newSubStep((\"Begin heating the sparge water to ...sparge_temp...C\",{'complete':1}))\nstep.attention=\"The HLT is constructed with standard kettle elements, therefore it is advisable to alternate between the elements 3 or 4 times during the heating. The temperature controller should only power one kettle element at any time.\"\n\n\n# Bring the wort to the boil\n## if we are doing First Wort Hops then we need this here;\nstep = myprocessK.brewday.newstep(\"Measure Hops\")\nstep.text=\"Measure the hops for addition to the kettle.\"\nstep.auto=\"hopmeasure_v3\"\nstep.img=[\"boil.png\"]\n\n\n# Monitor Mash Equipment\nstep = myprocessK.brewday.newstep(\"Monitor the Mash\")\nstep.text=\"Monitor the temperature of the mash.\"\nstep.attention=\"Be careful to monitor the temperature during the mash, if the mash tun is well insulated it may be that the temperature rises not falls. Temperature must not rise above 70C. High temperautere 68.5-70C results in more unfermentables, 67-68.5 will result in medium body beers.\"\n\nstep.fields.append(('(MID15) Mash Temp Acheived','mash_mid15_temp',''))\nstep.fields.append(('(MID16) Mash Temp Acheived','mash_mid16_temp',''))\nstep.fields.append(('(MID17) Mash Temp Acheived','mash_mid17_temp',''))\nstep.fields.append(('(MID18) Mash Temp Acheived','mash_mid18_temp',''))\nstep.fields.append(('(MID19) Mash Temp Acheived','mash_mid19_temp',''))\nstep.fields.append(('(MID20) Mash Temp Acheived','mash_mid20_temp',''))\nstep.fields.append(('(MID21) Mash Temp Acheived','mash_mid21_temp',''))\nstep.fields.append(('(MID22) Mash Temp Acheived','mash_mid22_temp',''))\nstep.fields.append(('(MID23) Mash Temp Acheived','mash_mid23_temp',''))\nstep.fields.append(('(MID24) Mash Temp Acheived','mash_mid24_temp',''))\nstep.fields.append(('(MID25) Mash Temp Acheived','mash_mid25_temp',''))\n\n\n# Ensure Sparge Water is at the correct temperature\nstep = myprocessK.brewday.newstep(\"Assemble Sparge Setup and begin Recirculation\")\n#step.addConsumable(muslinbag,1)\nstep.addEquipment(funnel)\n\n\nstep.text=\"Once the sparge water is at the correct temperature ...sparge_temp...C AND the mash duration has completedthe sparge setup can be setup. During this step the cloudy wort with bits of grain will drained leading to a natural grain filter forming.\"\nstep.newSubStep( (\"Take off the lid from the mash tun and assemble the sparge arm\",{}))\nstep.newSubStep( (\"Allow up to 6 litres of wort to drain from the mash tun into the kettle, the wort should be carefully added back to the top of the lauter tun trying to ensure minimal disturbance.\",{'complete':1}))\nstep.fields.append(('(End) Mash Temp Acheived','mash_end_temp',''))\nstep.newSubStep( (\"Collect sample of mash to measure PH\",{'complete':1}))\nstep.attention=\"Set the thermometer to alarm if the temperature is higher than 71deg. If it is then lid should be lifted to reduce the heat.\"\nstep.img=[\"spargesetup.png\"]\n\n\n\nstep = myprocessK.brewday.newstep(\"First Wort Hopping\")\nstep.condition=[]\nstep.condition.append( ['first_wort_hop_qty','>',0] )\nstep.text=\"Add the first wort hops to the boiler before starting to sparge\"\nstep.auto=\"hopaddFirstWort_v3\"\n\n\n\n# Start Sparge\nstep = myprocessK.brewday.newstep(\"Start Fly Sparging\")\nstep.text=\"(SPARGE) Sparging will drain the sugar from the grain providing us with wort. The process of sparging should be carried out slowly. The temperature of the gain bed will be raised during this proess (note there is no instant change of temperature). The grain bed should stay below 76 deg C. We need to aim for a boil volume of ...boil_vol...L. General wisdom is to keep 1 inch of water above the grain bed- however there is a trade off (the more water above the grain bed the smaller/slower temperature rise of the grain bed, the less water above the grain bed the bigger/quicker temperature rise of the grain bed.\"\n#Throughout the process monitor flow of liquid into and out of the mash tun to try maintain an equilibrium\"\nstep.newSubStep( (\"Collect sample of sparge water to measure PH\",{'complete':1}))\nstep.img=[\"dosparge.png\"]\n\n\n\n\n\n\n\nstep = myprocessK.brewday.newstep(\"Start Boiling the Wort\")\nstep.text=\"(BOIL) Boiling the wort drives off unwanted volatile components, coagulates proteins, and sanitising the wort for fermentation. The first boil should be ...kettle1volume...L of wort. We are aiming for a gravity of ...kettle1preboilgravity... It is expected the kettle will loose ...kettle1evaporation...L due to evaporation \"\"\"\nstep.newSubStep( (\"Start boiling the wort.\",{}))\nstep.attention=\"Use thermometer alarm to determine when the wort has reached a boil.\"\nstep.img=[\"boil.png\"]\n\nstep.fields.append( ('Temp (C)','__kettle1_temp1','60') )\nstep.fields.append( ('Gravity (1.xxx)','__kettle1_grav1','1.007') )\nstep.widgets['__kettle1_adjusted1'] = ('gravityTempAdjustment',['__kettle1_temp1','__kettle1_grav1'])\nstep.fields.append( ('Adjusted Gravity','__kettle1_adjusted1','') )\nstep.fields.append( ('Pre Boil Gravity','preboilgravity',''))\nstep.fields.append( ('Pre Boil Volume','preboilvolume',''))\n\n\n\n\n# Dynamic Recipe Adjustment.\nstep = myprocessK.brewday.newstep(\"Dynamic Recipe Adjustment\")\nstep.text=\"If the mash was particularly efficent/inefficient it may be desirarble to top up fermentables, dilute wort, increase/decrease hop quantities. The target pre-boil gravity is ...preboil_gravity... (total post-boil gravity ...estimated_og...). The target wort volume required is ...boil_vol...L. The gravity quotes here takes account of later topup of ...topupvol...L. Estimated gravity post boil pre cooling is ...postboilprecoolgravity...\"\nstep.attention=\"Be careful with topup at this stage, the dilution of cooling/evaporation will concentrate the wort further. If the wort is too concentrated at this stage delay dilution until the cooling stage. Making readings of volume/gravities is the most important thing at this stage.\"\n\n\n\nstep.fields.append( ('Topup Gravity','__topupgravity','1.000') )\nstep.fields.append( ('Topup Gravity Temp','__topupgravitytemp','20') )\nstep.widgets['__topupgravityadjusted'] = (' gravityTempAdjustment',['__topupgravity','__topupgravitytemp'])\nstep.fields.append( ('Topup Gravity Adjusted','__topupgravityadjusted','1.000') )\nstep.fields.append( ('Final Gravity Required','__topupgravityrequired','') )\n\n\n\n# Begin sterilising remaining equipment\nstep = myprocessK.brewday.newstep(\"Sterilise Equipment\")\nstep.text=\"It is important throughout the brew day to keep any equipment which will come into contact with the wort post-boil sterilised. Equipment used before the boil does not need to be sterilised but does need to be clean. Note: the silicone tube used for transferring wort from the boiler into the fermentation bin will be sanitised in a later step.\"\nstep.newSubStep( (\"Fill the fermentation bin with 10 litres of warm water and 2 tsp of sterilising powder.\",{'complete':1}))\nstep.newSubStep( (\"Ensure fermentation bin is fully sterilised with equipment.\",{'complete':1}))\nstep.newSubStep( (\"Ensure a 'filter' is added to the back of the fermentation bin tap\",{'complete':1}))\nstep.img=['sterilise1step.png']\n\n\n\nstep.addEquipment( fermentationbin6gal )\n\n# Rinse Equipment\nstep = myprocessK.brewday.newstep(\"Rinse Equipment\")\nstep.text=\"Rinse Equipment in the same way as sterilising, equipment should be rinsed with 25 litres of cold water.\"\n\n\nstep.attention=\"Be careful to monitor the temperature during the mash, if the mash tun is well insulated it may be that the temperature rises not falls. Temperature must not rise above 70C. High temperautere 68.5-70C results in more unfermentables, 67-68.5 will result in medium body beers.\"\n\nstep.fields.append(('(MID8) Mash Temp Acheived','mash_mid8_temp',''))\nstep.fields.append(('(MID9) Mash Temp Acheived','mash_mid9_temp',''))\nstep.fields.append(('(MID10) Mash Temp Acheived','mash_mid10_temp',''))\nstep.fields.append(('(MID11) Mash Temp Acheived','mash_mid11_temp',''))\nstep.fields.append(('(MID12) Mash Temp Acheived','mash_mid12_temp',''))\nstep.fields.append(('(MID13) Mash Temp Acheived','mash_mid13_temp',''))\nstep.fields.append(('(MID14) Mash Temp Acheived','mash_mid14_temp',''))\n\n\nstep.img=[\"sighttube.png\"]\n\n\n# Bring the wort to the boil\nstep = myprocessK.brewday.newstep(\"Bittering Hops\")\nstep.condition=[]\n#step.condition.append( ['boil_vol','>',26] )\nstep.text=\"Once the wort is at a rolling boil the hops can be added and the lid should be left half covered.\"\nstep.img=[\"boil.png\"]\nstep.newSubStep((\"Start timer for 45 minutes after which the protofloc copper finings will be added\",{'complete':1,'kitchentimer' : ('b',3600) }))\nstep.auto=\"hopaddBittering_v3_withadjuncts\"\n\n\n# Bring the wort to the boil\nstep = myprocessK.brewday.newstep(\"Pump Wort\")\nstep.condition=[]\n#step.condition.append( ['boil_vol','>',26] )\nstep.text=\"(BOIL + PUMP) With the wort at a boil recirculate with the pump to ensure that the pump and tubing is sterilised. Pump for 5 minutes\"\n\n\n\n# Bring the wort to the boil\nstep = myprocessK.brewday.newstep(\"Aroma Hops\")\nstep.condition=[]\n#step.condition.append( ['boil_vol','>',26] )\nstep.text=\"Add the aroma hops to the kettle with 15 minutes remaining. The immersion chiller will need to be sterilised during this period and irishmoss/protofloc added to help coagulate proteins in the wort. For small boils it may be necessary to tie the immersion chiller with cable ties.\"\nstep.newSubStep((\"Start timer for 15 minutes .\",{'complete':1,'kitchentimer' : ('a',900) }))\nstep.newSubStep((\"Add the irishmoss/protofloc and continue boiling for 15 minutes.\",{'complete':1,'kitchentimer' : ('a',900) }))\nstep.newSubStep((\"Add the immersion chiller\",{'complete':1,'kitchentimer' : ('a',900) }))\nstep.auto=\"hopaddAroma_v3\"\nstep.img=[\"boil.png\"]\n\n\n## Sanitise\n#step = myprocessK.brewday.newstep(\"Sanitise the boiler tube\")\n#step.text=\"Put the transfer tube in the kettle, open the tap of the kettle and start the pump to recirculate the boiling wort in order to sanitise the transfer tube.\"\n\n\n# Bring the wort to the boil\nstep = myprocessK.brewday.newstep(\"Finishing Hops\")\nstep.condition=[]\n#step.condition.append( ['boil_vol','>',26] )\nstep.text=\"Add the finishing hops to the kettle and stop the heat.\"\nstep.auto=\"hopaddFinishing_v3\"\nstep.img=[\"boil.png\"]\n\n\n# Yeast Rehydration\n#step = myprocessK.brewday.newstep(\"Boil Yeast Rehydration Water\")\n#step.text=\"Rehydration yeast provides a gentle start for the yeast and helps fermentation start quickly. If using yeast slurry instead then this step will still be carried out to sterilise the jug in order to measure the yeast slurry.\"\n#step.newSubStep((\"Boil 500ml of water and set aside in a pyrex jug\",{'complete':1}))\n#step.newSubStep((\"After 10 minutes put the hug in a water bath to cool the water to 25 degC\",{'complete':1}))\n#step.attention=\"Yeast should nto be added to the rehydration water unless is is <25 degC\"\n\n\n\n\n# Cool Wort\nstep = myprocessK.brewday.newstep(\"Cool wort\")\nstep.text=\"(PUMP) It is important to cool the wort quickly, ice water can help to cooling water towards the end of cooling. The estimated gravity required is ...estimated_og... Do not aerate the wort while, however the pump can be used to recirculate the wort through the already sanitised transfer tube.\"\nstep.newSubStep((\"Setup the immersion chiller and and start pushing cold water through to cool the wort to 20 degC\",{'complete':1}))\nstep.img=[\"drain3.png\"]\nstep.newSubStep((\"With the temperature of the wort at 35degC start using ice to cool the temperature of the cooling water.\",{'complete':1}))\nstep.newSubStep((\"Add half of the yeast contents to the rehydration water, for Safale S04 the temperature of the yeast rehydration water should be 27degC +/- 3degC\",{'complete':1}))\nstep.condition=[]\nstep.fields.append( ('Post Boil Volume (Pre Cool)','postboilvolumebeforecool','') )\n\n\n\n# Drain Wort\nstep = myprocessK.brewday.newstep(\"Pump wort into fermentation bin\")\nstep.condition=[]\nstep.text=\"(PUMP + FERM) With the wort cooled to 20degC, then record the volume of the wort in the boiler, before draining the wort from the fermentation bin.\"\nstep.attention=\"Once started draining avoid turning off the tap as this can stop the syphon effect. To maximise the wort from the boiler it should be titled with a wooden board underneath and then disturbance should be minimised in order to make best use of hop bed to filter out hot break material.\"\nstep.img=[\"drain1.png\"]\n\n\n\nstep.fields.append( ('Drain Temp)','tempdraintemp','') )\nstep.fields.append( ('Drain Gravity','tempdraingravity','') )\nstep.widgets['tempdrainedgravity'] = ('gravityTempAdjustment',['tempdraintemp','tempdraingravity'])\nstep.fields.append( ('Drain Adjusted Gravity','tempdrainedgravity',''))\n\nstep.fields.append( ('Tmp Addition Temp (C)','__2additiontemp','') )\nstep.fields.append( ('Tmp Addition Gravity (1.xxx)','__2additiongravity','') )\nstep.widgets['__2additionadjustedgravity'] = ('gravityTempAdjustment',['__2additiontemp','__2additiongravity'])\nstep.fields.append( ('Tmp Addition Adjusted Gravity','__2additionadjustedgravity','') )\n\nstep.fields.append( ('Tmp Gathered Wort Volume','__2gatheredvol','') )\nstep.fields.append( ('Tmp Addition Volume','__2additionvol','') )\nstep.widgets['2precoolgravity'] = ('combineMultipleGravity',['__2gatheredadjustedgravity','__2additionadjustedgravity','__2gatheredvol','__2additionvol'])\nstep.fields.append( ('Tmp Pre Cool Gravity','2precoolgravity','') )\n\n\n\n# Cool Wort\nstep = myprocessK.brewday.newstep(\"Topup\")\nstep.text=\"As the wort is cooled a decision should be made on the gravity of the resulting wort. It is hard to increase the gravity (as the high gravity wort is already used) but easy to reduce the gravity (as diluted wort/sterilised water will be easily available). It is best to make the decision when the wort is as cool as possible to reduce the effect of the hydrometer adjustments. If there was a high mash temperature factor in high final gravity when trying to calculate alcohol. Too severe a dilution will reduce the bittering/hop aroma. Planned volume in the fermenter (pretopup)....precoolfvvolume... with a later topup of ...topupvol...L, planed original gravity ...postboil_precool_og.../...estimated_og... (precool/cool) planned final gravity ...estimated_fg... planned abv ....estimated_abv...\"\nstep.fields.append( ('Fermentation Bin Pre Topup Temp)','fvpretopuptemp','') )\nstep.fields.append( ('Fermentation Bin Pre Topup Gravity','fvpretopupgrav','') )\nstep.widgets['fvpretopupadjusted'] = ('gravityTempAdjustment',['fvpretopuptemp','fvpretopupgrav'])\nstep.fields.append( ('Fermentation Bin Pre Topup Adjusted Gravity','fvpretopupadjusted',''))\nstep.fields.append( ('Fermentation Bin Volume','fvpretopupvolume','') )\n\nstep.fields.append( ('Tmp Original Gravity','__prerinseOg_abv',''))\nstep.fields.append( ('Tmp Final Gravity','__prerinseFg_abv',''))\nstep.widgets['__preRinseAbv'] = ('abvCalculation',['__prerinseOg_abv','__prerinseFg_abv'])\nstep.fields.append( ('Temp ABV','__preRinseAbv',''))\n\n\nstep.fields.append( ('Tmp Addition Temp (C)','__2additiontemp','') )\nstep.fields.append( ('Tmp Addition Gravity (1.xxx)','__2additiongravity','') )\nstep.widgets['__2additionadjustedgravity'] = ('gravityTempAdjustment',['__2additiontemp','__2additiongravity'])\nstep.fields.append( ('Tmp Addition Adjusted Gravity','__2additionadjustedgravity','') )\nstep.fields.append( ('Tmp Addition Volume','__2additionvol','') )\nstep.widgets['2precoolgravity'] = ('combineMultipleGravity',['fvpretopupadjusted','__2additionadjustedgravity','fvpretopupvolume','__2additionvol'])\nstep.fields.append( ('Post Topup Gravity','fvposttopupgravity','') )\nstep.fields.append( ('Post Topup Volume','fvposttopupvolume','') )\nstep.fields.append( ('Post Topup Post Cool Gravity','fvpostuppostcoolgravity','') )\n\n\n\n\n# Measure\nstep = myprocessK.brewday.newstep(\"Clean\")\nstep.text=\"Throughout the brewday it is a good idea to have been cleaning equipment, it's only at this stage that it is practical to clean the pump by cycling boiling water through it.\"\n\n\n# Measure\nstep = myprocessK.brewday.newstep(\"Measure\")\nstep.text=\"(FERM) Recording results is important to track the quality of the brew. The expected original gravity is ...estimated_og..., final gravity estimate is ...estimated_fg..., estimated abv ...estimated_abv...\"\nstep.newSubStep((\"Aerate the wort for 5 minutes\",{'complete':1}))\nstep.newSubStep((\"After aerating the wort measure take a sample to measure the original gravity.\",{'complete':1}))\nstep.fields.append( ('Original Gravity','og','') )\nstep.fields.append( ('Fermentation bin Weight','postboilweight','') )\nstep.fields.append( ('Fermentation bin vol (after cooling)','postboilvol','') )\nstep.fields.append( ('Wort left in boiler vol','leftovervol','') )\n\n\n\nstep = myprocessK.brewday.newstep(\"Measure PH from brewday\")\nstep.text=\"Various samples should have been taken start of mash, end of mash and sparge water to determine the PH throughout the process. The PH meter will need to be calibrated with a solution of a known PH at a set temperature. 4.00 @ 5-25, 4.01 @ 30, 4.02 @ 35, 4.03 @ 40, 4.04 @ 45, 4.06 @ 50, 4.07 @ 55, 4.09 @ 60, 4.12 @ 70, 4.16 @ 80, 4.20 @ 90, 4.22 @ 95. 6.95 @ 5, 6.92 @ 10, 6.90 @ 15, 6.88 @ 20, 6.86 @ 25, 6.85 @ 30, 6.84 @ 35-40, 6.83 @ 45-55, 6.84 @ 60, 6.85 @ 70, 6.86 @ 80, 6.88 @ 90\"\nstep.attention=\"PH meter is calibrated for 25degC.\"\nstep.fields.append( ('Mash PH','mashPH','') )\nstep.fields.append( ('Post Mash PH','postMashWaterPH','') )\nstep.fields.append( ('Spargewater PH','spargeWaterPH','') )\nstep.fields.append( ('Finished Wort PH','wortPH','') )\n\n\n\n# Pitch\nstep = myprocessK.brewday.newstep(\"Pitch Yeast\")\nstep.text=\"If using yeast slurry then measure 400ml of slurry assuming the batch size is <6 gallon and the yeast slurry must be less than 14 days old. Before using yeast slurry a check on the progress of ferementation from the previous batch is required.\"\nstep.newSubStep((\"Once the wort is at pitching temperature (20degC)\",{'complete':1}))\n#oistep.newSubStep((\"Optionally add an immersion heater set for 18degC\",{'complete':1}))\nstep.addConsumable(yeastvit,0.5)\nstep.newSubStep((\"Pitch the yeast\",{'complete':1}))\nstep.newSubStep((\"Add half a teaspoon of yeastvit\",{'complete':1}))\n\nstep = myprocessK.brewday.newstep(\"Relax!\")\nstep.text=\"Finished the brewday\"\n\n###########################\n#Post Brew Day\n\n\nstep = myprocessK.postbrewday.newstep(\"Kraussen\")\nstep.text=\"Checking for signs of fermentation begining such as a temperature rise (temp controller in a brew fridge will mask this), or the kraussen (yeast crust forming on top of the wort). \"\nstep.newSubStep((\"Kraussen Observed.\",{'complete':1}))\nstep.attention=\"Once activity of fermentation has been confirmed do not open the feremntation bin\"\nstep.fields.append(('Time first fridge trigger','fridgetriggerdelay',''))\nstep.fields.append(('Temp after 12 hours','fermtemp12',''))\nstep.fields.append(('Temp after 1 day','fermtemp24',''))\nstep.fields.append(('Temp after 2 days','fermtemp48',''))\nstep.fields.append(('Temp after 3 days','fermtemp72',''))\nstep.fields.append(('Temp after 4 days','fermtemp96',''))\nstep.fields.append(('Temp after 5 days','fermtemp120',''))\n\n\nstep = myprocessK.postbrewday.newstep(\"Dryhop\")\nstep.text =\"After 3 days add the dry hops. There is differing opinion about adding hops, too early and the aroma is driven off by the CO2 produced in fermentation, too late and there *may* be a *potential* oxidation risk. The alcohol should protect anynasty organisms in the hops from taking hold. However the hop tea-balls can still be santiised in boiling water.\"\nstep.auto=\"dryhop\"\nstep.condition=[]\n\nstep = myprocessK.postbrewday.newstep(\"Measure specific gravity (1st)\")\nstep.text =\"After 6 days measure the specific gravity by taking a small sample from the fermentation bin. The estimated final gravity is ...estimated_fg.... Even if the specific gravity is lower than the estimate it is important that there is a stable reading two days running to avoid primary fermentation continuing in the bottles.\"\nstep.fields.append( ('Specific Gravity 1 (1.xxx)','sg1',''))\n\n\nstep = myprocessK.postbrewday.newstep(\"Measure specific gravity (2nd)\")\nstep.text =\"After 7 days measure the specific gravity by taking a small sample from the fermentation bin. The estimated final gravity is ...estimated_fg.... Even if the specific gravity is lower than the estimate it is important that there is a stable reading two days running to avoid primary fermentation continuing in the bottles.\"\nstep.fields.append( ('Specific Gravity 2 (1.xxx)','sg2',''))\n\n\nstep = myprocessK.postbrewday.newstep(\"Measure specific gravity (3rd)\")\nstep.text =\"After 8 days measure the specific gravity by taking a small sample from the fermentation bin. The estimated final gravity is ...estimated_fg.... Even if the specific gravity is lower than the estimate it is important that there is a stable reading two days running to avoid primary fermentation continuing in the bottles.\"\nstep.fields.append( ('Specific Gravity 3 (1.xxx)','sg3',''))\n\n\nstep = myprocessK.postbrewday.newstep(\"Measure specific gravity (4th)\")\nstep.text =\"After 9 days measure the specific gravity by taking a small sample from the fermentation bin. The estimated final gravity is ...estimated_fg.... Even if the specific gravity is lower than the estimate it is important that there is a stable reading two days running to avoid primary fermentation continuing in the bottles.\"\nstep.fields.append( ('Specific Gravity 4 (1.xxx)','sg4',''))\n\nstep = myprocessK.postbrewday.newstep(\"Measure specific gravity (5th)\")\nstep.text =\"After 10 days measure the specific gravity by taking a small sample from the fermentation bin. The estimated final gravity is ...estimated_fg.... Even if the specific gravity is lower than the estimate it is important that there is a stable reading two days running to avoid primary fermentation continuing in the bottles.\"\nstep.fields.append( ('Specific Gravity 5 (1.xxx)','sg5',''))\n\n\n\n\nstep = myprocessK.postbrewday.newstep(\"Calculate Alcohol\")\nstep.text=\"The alcohol can be calculated from the original gravity and the stable final gravity readings.\"\nstep.fields.append( ('Measured Final Gravity','__measuredFg_abv',''))\nstep.widgets['__abv'] = ('abvCalculation',['og','__measuredFg_abv'])\nstep.fields.append( ('ABV','__abv','') )\n\n\nstep = myprocessK.bottlingAndKegging.GatherThings()\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Gather Polypins\")\nstep.condition=[]\nstep.condition.append(['polypinqty','>',0])\nstep.auto=\"gatherthepolypins\"\nstep.stockDependency=[\"polypin\"]\t# check based on category. if none found in this category then the compile() should remove this step\n# not sure stock dependency work... should deprecate it in any case\nstep.text=\"Gather Polypins\\n\"\nstep.newSubStep((\"Gather ...polypinqty... polypins\",{'complete':1 }))\n\t# need to think about removing this step if no stock of mini kegs available\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Gather Mini Kegs\")\nstep.condition=[]\nstep.auto=\"gathertheminikegs\"\n# not sure stock dependency work... should deprecate it in any case\nstep.text=\"Gather Minikegs with bungs/safety vent bungs\\n\"\nstep.newSubStep((\"Gather ...minikegqty... minikegs\",{'complete':1 }))\n\t# need to think about removing this step if no stock of mini kegs available\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Gather Bottles\")\nstep.condition=[]\nstep.condition.append(['bottleqty','>',0])\nstep.auto=\"gatherthebottles\"\nstep.stockDependency=[\"bottle\"]\t# check based on category. if none found in this category then the compile() should remove this step\n# not sure stock dependency work... should deprecate it in any case\nstep.text=\"Gather Bottles\\n\"\nstep.newSubStep((\"Gather ...bottles_required... bottles\",{'complete':1 }))\n\t# need to think about removing this step if no stock of mini kegs available\n\n#step = myprocessK.bottlingAndKegging.newstep(\"Move fermentation bin\")\n#step.text=\"If needed move the fermentation bin to a height suitable for bottling from. This should be carried out early to allow any disturbance to settle\"\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Clean Work Area\")\nstep.text=\"Clean the entire work area with mild detergent. It is important to ensure the entire work area is clean before starting with bottling.\"\nstep.addEquipment(bottlebrush)\nstep.addEquipment(hydrometer)\nstep.addEquipment(trialjar)\nstep.addEquipment(slottedspoon)\nstep.addEquipment(thermometer2)\nstep.addEquipment(smalljug)\nstep.addEquipment(jug)\nstep.addEquipment(bottler)\nstep.addEquipment(measuringspoon)\n\nstep.addEquipment(jar2l)\nstep.addEquipment(jar400ml)\n\n#step = myprocessK.bottlingAndKegging.newstep(\"Setup Work Area\")\n#step.text=\"Setup the work area as shown in the image, cleaning the bottles may be carried out the previous evening to save time.\"\n#step.img=[\"bottlingsetup.png\"]\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Clean Bottles\")\nstep.text=\"Cleaning the bottles using hot water and detergent.\"\nstep.newSubStep((\"Clean the bottles using a bottle brush to ensure no deposits are left in the bottle. Drain solution out of the bottles.\",{'complete':1}))\nstep.newSubStep((\"Rinse the bottles with a small amount of water.\",{'complete':1}))\nstep.img=['bottleclean.png']\n\nstep = myprocessK.bottlingAndKegging.primingSolution()\nstep.text=\"Priming solution provides more fermentables for the yeast to convert into further alcohol and natural carbonation\"\nstep.newSubStep((\"Measure ...primingsugartotal... (...primingsugarqty... per bottle) priming sugar and set aside.\",{'complete':1}))\nstep.newSubStep((\"Add ...primingwater... ml of water to the saucepan and heat to 90degC, once at 90degC stir in the sugar\",{'complete':1}))\nstep.newSubStep((\"Maintain the temperature at 85degC for 5 minutes and then cool in a water bath to less that 30 degC.\",{'complete':1}))\nstep.img=['primingsolution.png']\nstep.attention=\"Be careful with the volume of sugar in each bottle as introducing too many fermentables can lead to exploding bottles\"\n\n\n#step = myprocessK.bottlingAndKegging.newstep(\"Setup Work Area 2\")\n#step.text=\"Setup the work area as show in the image, during the bottling stage all equipment will be required.\"\n#step.img=[\"bottlingsetup2.png\"]\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Sterilise Crown Caps\")\nstep.text=\"Crown caps needs to be sterilised before use.\"\nstep.newSubStep((\"Boil 500ml of water and add to a clean pyrex jug\",{'complete':1}))\nstep.newSubStep((\"Add ...num_crown_caps... crown caps/plastic caps to the jug and set aside.\",{'complete':1}))\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Prepare Jars for Yeast Harvesting\")\nstep.text=\"Yeast harvesting may be carried out if fresh yeast was used for a brew with an original gravity < 1.060 and the next brew is due to be carried out in less than 14 days\"\nstep.newSubStep((\"Fill the 2L Jar with boiling water, add the lid securely and set aside\",{'complete':1}))\nstep.newSubStep((\"Fill each of the 400ml jars with boiling water add the lid a set aside.\",{'complete':1}))\nstep.newSubStep((\"After 10 minutes add the 400ml jars into a cold water bath to cool the water\",{'complete':1}))\n\n#step = myprocessK.bottlingAndKegging.newstep(\"Sterilise Saucepan\")\n#step.text=\"Sterilise the saucepan, thermometer and slotted spoon, and measuring spoon by adding the equipment to the saucepan and filling with boiling water. Set aside for at least 15 minutes\"\n\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Fill bottles with sterilising solution\")\nstep.text=\"Use 3/4 of a level teaspoon of sterilising solution in a full jug of warm water. (which equates to 1 level teaspoon per 3L)\"\nstep.newSubStep((\"Arrange bottles in a crate ready to sterilise\",{'complete':1}))\nstep.addConsumable( sterilisingPowder,4)\nstep.addEquipment( saucepan )\nstep.addEquipment( funnel )\nstep.img=['bottlingseq.png']\nstep.text=\"The sterilising of bottles is carried out by filling each bottle full with a sterilising solution. The funnel will be sterilsing as the bottles are filled. \"\nstep.auto=\"sterilisebottles\"\nstep.newSubStep((\"Immerse the little bottler in a bottle of sterilising solution rotate to ensure both ends are covered inside and out.\",{'complete':1}))\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Empty bottles\")\nstep.img=['bottlingempty.png']\nstep.text=\"After 5 minutes begin to partially empty sterilising solution from the bottles filling any of the mini kegs, each mini keg.It is important to the make sure the top of the bottle is sterilised. Bottles should be half emptied, and then given a good shake before finishing emptying the bottle.\"\nstep.attention=\"If using mini kegs or polypins the sterilising solution should be reused for the mini kegs/polypins\"\nstep.newSubStep((\"The first two bottles should be emptitied into the large jug, this gives an opportunity to serilise the top of the bottle\",{'complete':1}))\n#step.newSubStep((\"If using mini kegs empty the remaining bottles into the mini kegs. Each mini keg should be fully filled with sterilising solution. If there is not enough sterilising solution in the bottles additional solution needs to be made.\",{'complete':1}))\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Fill polypins with sterilising solution\")\nstep.condition=[]\nstep.condition.append(['polypinqty','>',0])\nstep.auto=\"gather4\"\nstep.stockDependency=[\"polypin\"]\t# check based on category. if none found in this category then the compile() should remove this step\n# not sure stock dependency work... should deprecate it in any case\nstep.text=\"Fill the mini kegs with sterilising solution from the bottles. Once the sterilising solution from the bottles has been used then more sterilsing solution must be made at the strength of 3/4 of a level teaspoon per large jug\\n\"\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Fill mini kegs with sterilising solution\")\nstep.condition=[]\nstep.condition.append(['minikegqty','>',0])\nstep.auto=\"gather3\"\nstep.stockDependency=[\"keg\"]\t# check based on category. if none found in this category then the compile() should remove this step\n# not sure stock dependency work... should deprecate it in any case\nstep.text=\"Fill the mini kegs with sterilising solution from the bottles. Once the sterilising solution from the bottles has been used then more sterilsing solution must be made at the strength of 3/4 of a level teaspoon per large jug\\n\"\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Empty Polypins\")\nstep.img=['bottlingempty.png']\nstep.condition=[]\nstep.auto=\"empty_polypin\"\nstep.condition.append(['polypinqty','>',0])\nstep.text=\"Empty the sterilising solution from the polypins, using the taps\"\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Empty Minikegs\")\nstep.img=['bottlingempty.png']\nstep.auto=\"empty_minikeg\"\nstep.condition=[]\nstep.condition.append(['minikegqty','>',0])\nstep.text=\"Empty the sterilising solution from the minikegs, using the taps\"\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Rinse Bottles\")\n#step.img['bottlingrinse.png']\nstep.text=\"Bottles need to be well rinsed to ensure traces of the sterilising solution are rinsed\"\nstep.attention=\"If using mini kegs/polypins the water should be empties into the minikegs/polypins\"\nstep.newSubStep((\"Fill each bottle with a third full with cold water\",{'complete':1}))\nstep.newSubStep((\"Shake each bottle and empty the water.\",{'complete':1}))\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Rinse Polypins\")\n#step.img['bottlingrinse.png']\nstep.condition=[]\nstep.auto=\"rinse_polypin\"\nstep.condition.append(['polypinqty','>',0])\nstep.text=\"Polypins need to be well rinsed to ensure traces of the sterilising solution are rinsed\"\nstep.newSubStep((\"Fill each polypin a third full with cold water\",{'complete':1}))\nstep.newSubStep((\"Shake each polypin and empty via the tap.\",{'complete':1}))\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Rinse Minikegs\")\n#step.img['bottlingrinse.png']\nstep.condition=[]\nstep.auto=\"rinse_minikeg\"\nstep.condition.append(['minikegqty','>',0])\nstep.text=\"Minikegs need to be well rinsed to ensure traces of the sterilising solution are rinsed\"\nstep.newSubStep((\"Fill each minikeg a third full with cold water\",{'complete':1}))\nstep.newSubStep((\"Shake each minikeg and empty via the tap.\",{'complete':1}))\n\n\n\n\n\n\t# need to think about removing this step if no stock of mini kegs available\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Add priming solution to each bottle\")\nstep.text=\"Stir the priming and then add 15ml of priming solution to each bottle\"\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Add priming solution to each polypin\")\nstep.text=\"Stir the priming and then add 45ml of priming solution to each polypin\"\nstep.auto=\"prime_polypin\"\nstep.condition=[]\nstep.condition.append(['polypinqty','>',0])\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Add priming solution to each minikeg\")\nstep.auto=\"prime_minikeg\"\nstep.text=\"Stir the priming and then add 120ml of priming solution to each minikeg\"\nstep.condition=[]\nstep.condition.append(['minikegqty','>',0])\n\n\n# Fill polypins kegs first\nstep = myprocessK.bottlingAndKegging.newstep(\"Fill Polypins\")\nstep.condition=[]\nstep.auto=\"fill_polypin\"\nstep.condition.append(['polypinqty','>',0])\nstep.stockDependency=[\"keg\"]\t\t# check based on category\nstep.text=\"The polypins should be filled with a little bottler, leaving half an inch of headspace.\"\nstep.newSubStep((\"Fill each of the polypins. Add the tap and purge the remaining air \",{'complete':1}))\nstep.attention=\"While bottling every effort must be taken not to introduce oxygen into the bottled beer. It is not necessary to shake the bottles to mix the beer and priming solution\"\n\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Fill Mini Kegs\")\nstep.condition=[]\nstep.auto=\"fill_minikeg\"\nstep.condition.append(['miniqty','>',0])\nstep.stockDependency=[\"keg\"]\t\t# check based on category\nstep.text=\"The minikegs should be filled with a little bottler, leaving an inch of headspace.\"\nstep.newSubStep((\"Fill each of the mini kegs\",{'complete':1}))\nstep.attention=\"While bottling every effort must be taken not to introduce oxygen into the bottled beer. It is not necessary to shake the bottles to mix the beer and priming solution\"\n\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Fill bottles\")\nstep.text=\"While filling it is useful to group the bottles by type to ensure even filling.\"\nstep.newSubStep((\"Begin filling each bottle leaving an inch of space at the neck empty.\",{'complete':1}))\nstep.attention=\"While bottling every effort must be taken not to introduce oxygen into the bottled beer. It is not necessary to shake the bottles to mix the beer and priming solution\"\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Yeast Harvest Part 1\")\nstep.text=\"To harvest the yeast the yeast cake is topped up with clean pre-boiled/sterilised water which will separate the yeast from the trub.\"\nstep.newSubStep((\"Ensure any remaining beer not bottled is emptied carefully out of the fermentation bin, there should be very little (less than 200ml) beer remaining\",{'complete':1}))\nstep.newSubStep((\"Add 400ml of water to the yeast cake and stir gently\",{'complete':1}))\nstep.newSubStep((\"Remove the large spoon and let the fermentation bin settle for 1 hour\",{'complete':1}))\nstep.img=[\"yeastcake1.png\"]\nstep.attention=\"Sanitisation is very important while harvesting the yeast\"\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Attach Caps\")\nstep.text=\"Once bottling has finished it is time to attach the caps.\"\n\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Yeast Harvest Part 2\")\nstep.text=\"The yeast from the fermentation bin will then be stored in the sterilised airtight container and set aside in the fridge\"\nstep.newSubStep((\"Fill the 2L jar with the solution from the fermentation bin, and then store in the fridge\",{'complete':1}))\nstep.img=[\"yeastcake2.png\"]\nstep.attention=\"Sanitisation is very important while harvesting the yeast. A label should be added to the jar to ensure the yeast is not used after 14 days,\"\n\n#ensure beer is removed without sucking up the yeast, 200ml beer on top is ok\n#add 1L of water into bottom of fermentation bin.... swirl to ensure yeast is loose (or stir if we have the spoon in the bucket still).\n#empty into 2L container. straisfy\n#\n\n # donosbourner.\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Optional Secondary Conditioning\")\nstep.text=\"If the ambient temperature is less than 18 degC it is a good idea to put the bottles into a water bath which can be heated to 20 degC. This ensures that the yeast has ideal conditions for working through the new fermenetables in the priming sugar\"\nstep.attention=\"If using an aquarium heater in the water bath - it must always remain submerged. Ensure the water is at the correct temperature before adding bottles\"\nstep.img=['secondarycondition.png']\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Code bottles\")\nstep.text=\"Ensure that the bottles can be identified, either via crown caps, labels etc. Once the beer is in condition full size labels may be added.\"\nstep.fields.append( ('Number of Bottles','numbottles','') )\nstep.fields.append( ('Number of Bottles (bad fills)','numbottlesbadfills','') )\nstep.fields.append( ('Number of MiniKegs','minikegs','') )\nstep.fields.append( ('Wastage in fermentation bin','fvpostbottlewastage','') )\nstep.fields.append( ('Litres packaged','litrespackaged','') )\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Cleanup\")\nstep.text=\"All equipment should be cleaned and left to dry before packing away for the next brewday\"\nstep.attention=\"Ensure all equipment is completely dry before packing away.\"\n\nstep = myprocessK.bottlingAndKegging.newstep(\"Monitor Conditoning\")\nstep.text=\"In the first si weeks it is necessary to check the progress of conditoning.\"\nstep.newSubStep((\"After 1 week check the mini kegs are clean and remove pressure build up in polypins\",{'complete':1}))\nstep.newSubStep((\"After 2 week check the mini kegs are clean and remove pressure build up in polypins\",{'complete':1}))\nstep.newSubStep((\"After 3 week check the mini kegs are clean and remove pressure build up in polypins\",{'complete':1}))\nstep.newSubStep((\"After 4 sample beer 1, week check the mini kegs are clean and remove pressure build up in polypins\",{'complete':1}))\nstep.newSubStep((\"After 5 sample beer 2, week check the mini kegs are clean and remove pressure build up in polypins\",{'complete':1}))\nstep.newSubStep((\"After 6 sample beer 3, week check the mini kegs are clean and remove pressure build up in polypins\",{'complete':1}))\n\n\n\n\nmyprocessK.save(\"process/allena29/40AG\")\nmyprocessK.generateMySql()\n\n\n\n\n\n#print \"!!! SQL CODE TO INSERT NEW ITEM INTO gItems\"\n#print \"i n s e r t into gItems values(null,'test@example.com','consumable','','watertreatment','Salifert Alkaline Test','salifertalkalinetest''1','test',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,'','',0,0,0,0,'','',1,\"\",0,0,0,0)\"\n\n\n\n","sub_path":"brewerslab-orig-commander/testRecipe.py","file_name":"testRecipe.py","file_ext":"py","file_size_in_byte":68445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"599916929","text":"import sys\nsys.path.insert(0, sys.path[0]+'/../../')\n\nimport utils\nimport torch \nimport numpy as np\n\nAC_name_file = '/mnt/nfs/scratch1/hschang/recommend/Multi_facet_recommendation/data/processed/NeurIPS2020_gorc_uncased/AC_name_list'\nuser_dict_path = \"./data/processed/NeurIPS2020_gorc_uncased/user/dictionary_index\"\n#user_emb_file = './models/gorc-20200423-155956/user_emb_NeurIPS2020_always.pt'\n#output_file = './gen_log/NeurIPS2020_AC_SAC_n5.csv'\nuser_emb_file = './models/gorc-20200423-155505/user_emb_NeurIPS2020_always.pt'\noutput_file = './gen_log/NeurIPS2020_AC_SAC_n1.csv'\n\nuse_gpu = True\ndevice = torch.device(\"cuda\" if use_gpu else \"cpu\")\n\nwith open(user_dict_path) as f_in:\n user_idx2word_freq = utils.load_idx2word_freq(f_in)\n \nprint(user_emb_file)\nuser_emb, user_emb_size = utils.load_emb_from_path(user_emb_file, device, user_idx2word_freq)\n\nuser_emb.requires_grad = False\nuser_norm_emb = user_emb / (0.000000000001 + user_emb.norm(dim = 1, keepdim=True) )\nuser_norm_emb.requires_grad = False\n\nname_to_role = {}\nAC_num = 0\nSAC_num = 0\nwith open(AC_name_file) as f_in:\n for line in f_in:\n name, role = line.rstrip().split('\\t')\n name_to_role[name] = role\n if role == 'AC':\n AC_num += 1\n else:\n assert role == 'SAC'\n SAC_num += 1\n\nSAC_list = []\nAC_list = []\nAC_tensor = torch.zeros((AC_num,user_emb_size),device = device, requires_grad = False)\nSAC_tensor = torch.zeros((SAC_num,user_emb_size),device = device, requires_grad = False)\nfor i in range(len(user_idx2word_freq)):\n user, freq = user_idx2word_freq[i]\n if user[-1] == '|':\n user = user[:-1]\n if user not in name_to_role:\n print(user)\n continue\n #assert user[-1] == '|'\n #user = user[:-1]\n role = name_to_role[user]\n if role == 'AC':\n AC_tensor[len(AC_list),:] = user_norm_emb[i,:]\n AC_list.append(user)\n else:\n assert role == 'SAC'\n SAC_tensor[len(SAC_list),:] = user_norm_emb[i,:]\n SAC_list.append(user)\n\nuser_sim_np = torch.mm(AC_tensor, SAC_tensor.t()).cpu().numpy()\nwith open(output_file, 'w') as f_out:\n for i, AC_name in enumerate(AC_list):\n for j, SAC_name in enumerate(SAC_list):\n f_out.write(AC_name+','+SAC_name+','+str(user_sim_np[i,j])+'\\n')\n","sub_path":"src/testing/avg_baseline/user_similarity.py","file_name":"user_similarity.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"48303052","text":"\"\"\"A python program for generating ND Perlin noise.\n\nAuthor: Riley Kirkpatrick\nReference: Tomáš Bouda -- https://medium.com/100-days-of-algorithms/day-88-perlin-noise-96d23158a44c\n\"\"\"\n\n\nimport numpy as np\n\n\n# *----------------------*\n# Helpers and Exceptions\n# *----------------------*\n\nclass ShapeException(Exception):\n pass\n\ndef permute(arr1, arr2):\n # Permutes lists of the form [a1, a2,...], [b1, b2,...] to [[c1, c2,...], [d1, d2,...],...]\n # Thus, the elements maintain order, but we get all permutations of elements from both lists\n if len(arr1) != len(arr2):\n return None\n\n out1 = [[arr1[0]] for _ in range(2**(len(arr1)-1))]\n out2 = [[arr2[0]] for _ in range(2**(len(arr2)-1))]\n\n return _permute(arr1, arr2, 1, len(arr1)-1, out1) + _permute(arr1, arr2, 1, len(arr1)-1, out2)\n\ndef _permute(arr1, arr2, ind, n, out):\n # Recursive permute helper function\n if n <= 0:\n return out\n\n out1 = out[:len(out)//2]\n out2 = out[len(out)//2:]\n for i in range(len(out1)):\n out1[i].append(arr1[ind])\n for i in range(len(out2)):\n out2[i].append(arr2[ind])\n \n return _permute(arr1, arr2, ind+1, n-1, out1) + _permute(arr1, arr2, ind+1, n-1, out2)\n\ndef lerp(g0, g1, t):\n # Returns the linear interpolation of two values/arrays with a fade\n return g0 + t*(g1 - g0)\n\ndef nlerp(g, t):\n # Returns the linear interpolation with a fade of each pair of values in the list\n # The list of values should have a length that is a multiple of 2\n # The first len(g)//2 values are used as the first value in the pair and the following len(g)//2 as the second\n return [lerp(g[i], g[len(g)//2 + i], t) for i in range(len(g)//2)]\n\ndef recurse_nlerp(n, g, t):\n return _recurse_nlerp(n, 0, g, t)\n\ndef _recurse_nlerp(n, ind, g, t):\n if n <= 0:\n return g\n return _recurse_nlerp(n-1, ind+1, nlerp(g, t[ind]), t)\n\n\n\n\n\n# *---------------*\n# ND Perlin Noise\n# *---------------*\n\ndef generate_gradient(n, shape, seed=None):\n \"\"\"Creates a random ND gradient.\n\n Arguments:\n n {int} -- The number of dimensions of the gradient.\n shape {int} -- The shape of the gradient.\n\n Keyword Arguments:\n seed {int} -- The seed for random number generation. (default: {None})\n\n Returns:\n numpy.ndarray -- The random ND gradient.\n \"\"\"\n\n # Check that the shape is n-dimensional and has at least 1 dimension\n if (len(shape) != n or n <= 0): raise ShapeException\n\n if seed: np.random.seed(seed)\n return np.random.rand(*shape, n)*2 - 1\n\ndef linear_spacing(n, shape, frequency):\n \"\"\"Generates a ND linear spacing.\n\n Arguments:\n n {int} -- The number of dimensions of the gradient.\n shape {int} -- The shape of the gradient.\n frequency {float} -- The frequency of the linear spacing.\n\n Returns:\n tuple -- The local and gradient coordinates (both lists of numpy.ndarray).\n \"\"\"\n\n # Check that the shape is n-dimensional and has at least 1 dimension\n if (len(shape) != n or n <= 0): raise ShapeException\n\n # Linear spacing by frequency\n n_vals = [np.linspace(0, frequency, _n, endpoint=False) for _n in shape]\n for i in range(n):\n for j in range(i):\n n_vals[i] = np.tile(n_vals[i], shape[j])\n for j in range(i + 1, n):\n n_vals[i] = np.repeat(n_vals[i], shape[j])\n\n # Gradient coordinates\n n0 = [_n_vals.astype(np.int64) for _n_vals in n_vals]\n\n # Local coordinates\n for _n_vals, _n0 in zip(n_vals, n0):\n _n_vals -= _n0\n\n return n_vals, n0\n\ndef generate_gradient_projections(n, shape, frequency, seed=None):\n \"\"\"Creates a ND gradient and calculates the projections into the gradient that are linearly spaced.\n\n Arguments:\n n {int} -- The number of dimensions of the gradient.\n shape {int} -- The shape of the gradient.\n frequency {float} -- The frequency of the linear spacing.\n\n Keyword Arguments:\n seed {int} -- The seed for random number generation. (default: {None})\n\n Returns:\n tuple -- Returns the gradient projections (list of numpy.ndarray) and the local coordinates from the\n generated linear spacing (list of numpy.ndarray).\n \"\"\"\n\n # Check that the shape is n-dimensional and has at least 1 dimension\n if (len(shape) != n or n <= 0): raise ShapeException\n\n gradient = generate_gradient(n, shape, seed=seed)\n n_vals, n0 = linear_spacing(n, shape, frequency)\n n1 = [_n0 + 1 for _n0 in n0]\n\n # Values are in big endian e.g. [[n0[0], n0[1], n0[2]], [n0[0], n0[1], n1[2]], [n0[0], n1[1], n0[2]], [n0[0], n1[1], n1[2]],\n # [n1[0], n0[1], n0[2]], [n1[0], n0[1], n1[2]], [n1[0], n1[1], n0[2]], [n1[0], n1[1], n1[2]]] for 3D\n n0_n1 = np.array(permute(n0, n1))\n\n # Gradient projections\n gradient_projs = [gradient[_n0_n1] for _n0_n1 in n0_n1]\n\n return gradient_projs, n_vals\n\ndef perlin_noise(n, shape, frequency, seed=None):\n \"\"\"Generates 3D Perlin noise.\n\n Arguments:\n n {int} -- The number of dimensions of the gradient.\n shape {int} -- The shape of the gradient.\n frequency {float} -- The frequency of the linear spacing.\n\n Keyword Arguments:\n seed {int} -- The seed for random number generation. (default: {None})\n\n Returns:\n numpy.ndarray -- An array of floating point numbers.\n \"\"\"\n\n gradient_projs, n_vals = generate_gradient_projections(n, shape, frequency, seed=seed)\n\n # Coordinate fades\n t = [(3 - 2*vals) * vals*vals for vals in n_vals]\n\n # Compute dot product of distance and gradient vectors\n g = []\n for i in range(len(gradient_projs)):\n g.append(n_vals[0]*gradient_projs[i][0])\n for j in range(1, n):\n g[i] += n_vals[j]*gradient_projs[i][j]\n\n # N-directional linear interpolations\n g = recurse_nlerp(n, g, t)\n\n return g.reshape(shape)\n\n\n\n\n\ndef main():\n shape = (20, 20, 20)\n n = len(shape)\n seed, num_bands = 69420, 4\n frequency = 2\n\n image_array = perlin_noise(n, shape, frequency, seed=seed)\n\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n print('You interrupted the program, you jerk.')","sub_path":"nd_perlin_noise.py","file_name":"nd_perlin_noise.py","file_ext":"py","file_size_in_byte":6212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"476898182","text":"'''\nSameera Sandaruwan\n'''\n\n# Importing PyTorch tools\nimport torch\nfrom torch import nn, optim, cuda\n\n# Importing other libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\n# Model\nclass NeuralNet(nn.Module):\n\n def __init__(self, optimizer=optim.SGD, alpha=0.01, criterion=nn.CrossEntropyLoss(), use_cuda=None):\n\n # Basics\n super(NeuralNet, self).__init__()\n\n # Settings\n self.optim_type = optimizer\n self.optimizer = None\n self.alpha = alpha\n self.criterion = criterion\n\n # Use CUDA?\n self.use_cuda = use_cuda if (use_cuda != None and cuda.is_available()) else cuda.is_available()\n\n # Current loss and loss history\n self.train_loss = 0\n self.valid_loss = 0\n self.train_loss_hist = []\n self.valid_loss_hist = []\n\n # Initializing states with placeholder tensors\n self.softmax_state = torch.tensor([0], dtype=torch.float64)\n\n # Initializing all layers\n self.lin_1 = nn.Linear(\n in_features = 1,\n out_features = 50,\n bias = True,\n )\n self.relu = nn.ReLU(\n inplace = False,\n )\n self.lin_2 = nn.Linear(\n in_features = 1,\n out_features = 1,\n bias = True,\n )\n self.softmax = nn.Softmax()\n\n # Running startup routines\n self.startup_routines()\n\n def startup_routines(self):\n self.optimizer = self.optim_type(self.parameters(), lr=self.alpha)\n if self.use_cuda:\n self.cuda()\n\n def predict(self, input):\n\n # Switching off autograd\n with torch.no_grad():\n\n # Use CUDA?\n if self.use_cuda:\n input = input.cuda()\n\n # Running inference\n return self.forward(input)\n\n def forward(self, input):\n input = self.lin_1(input) # Linear\n input = self.relu(input) # ReLU\n input = self.lin_2(input) # Linear\n self.softmax_state = self.softmax(input) # Softmax\n return self.softmax_state\n\n def fit_step(self, training_loader):\n\n # Preparations for fit step\n self.train_loss = 0 # Resetting training loss\n self.train() # Switching to autograd\n\n # Looping through data\n for input, softmax_target in training_loader:\n\n # Use CUDA?\n if self.use_cuda:\n input = input.cuda()\n softmax_target = softmax_target.cuda()\n\n # Forward pass\n self.forward(input)\n\n # Calculating loss\n loss = self.criterion(self.softmax_state, softmax_target)\n self.train_loss += loss.item() # Adding to epoch loss\n\n # Backward pass and optimization\n loss.backward() # Backward pass\n self.optimizer.step() # Optimizing weights\n self.optimizer.zero_grad() # Clearing gradients\n\n # Adding loss to history\n self.train_loss_hist.append(self.train_loss / len(training_loader))\n\n def validation_step(self, validation_loader):\n\n # Preparations for validation step\n self.valid_loss = 0 # Resetting validation loss\n\n # Switching off autograd\n with torch.no_grad():\n\n # Looping through data\n for input, softmax_target in validation_loader:\n\n # Use CUDA?\n if self.use_cuda:\n input = input.cuda()\n softmax_target = softmax_target.cuda()\n\n # Forward pass\n self.forward(input)\n\n # Calculating loss\n loss = self.criterion(self.softmax_state, softmax_target)\n self.valid_loss += loss.item() # Adding to epoch loss\n\n # Adding loss to history\n self.valid_loss_hist.append(self.valid_loss / len(validation_loader))\n\n def fit(self, training_loader, validation_loader=None, epochs=10, show_progress=True, save_best=False):\n\n # Helpers\n best_validation = 1e5\n\n # Possibly prepping progress message\n if show_progress:\n epoch_l = max(len(str(epochs)), 2)\n print('Training model...')\n print('%sEpoch Training loss Validation loss Duration Time remaining' % ''.rjust(2 * epoch_l - 4, ' '))\n t = time.time()\n\n # Looping through epochs\n for epoch in range(epochs):\n self.fit_step(training_loader) # Optimizing\n if validation_loader != None: # Perform validation?\n self.validation_step(validation_loader) # Calculating validation loss\n\n # Possibly printing progress\n if show_progress:\n eta_s = (time.time() - t) * (epochs - epoch)\n eta = '%sm %ss' % (round(eta_s / 60), 60 - round(eta_s % 60))\n print('%s/%s' % (str(epoch + 1).rjust(epoch_l, ' '), str(epochs).ljust(epoch_l, ' ')),\n '| %s' % str(round(self.train_loss_hist[-1], 8)).ljust(13, ' '),\n '| %s' % str(round(self.valid_loss_hist[-1], 8)).ljust(15, ' '),\n '| %ss' % str(round(time.time() - t, 3)).rjust(7, ' '),\n '| %s' % eta.ljust(14, ' '))\n t = time.time()\n\n # Possibly saving model\n if save_best:\n if self.valid_loss_hist[-1] < best_validation:\n self.save('best_validation')\n best_validation = self.valid_loss_hist[-1]\n\n # Switching to eval\n self.eval()\n\n def plot_hist(self):\n\n # Adding plots\n plt.plot(self.train_loss_hist, color='blue', label='Training loss')\n plt.plot(self.valid_loss_hist, color='springgreen', label='Validation loss')\n\n # Axis labels\n plt.xlabel('Epoch')\n plt.ylabel('Loss')\n plt.legend(loc='upper right')\n\n # Displaying plot\n plt.show()\n\n def save(self, name='model.pth'):\n if not '.pth' in name: name += '.pth'\n torch.save({\n 'lin_1': self.lin_1,\n 'relu': self.relu,\n 'lin_2': self.lin_2,\n 'softmax': self.softmax,\n 'train_loss': self.train_loss,\n 'valid_loss': self.valid_loss,\n 'train_loss_hist': self.train_loss_hist,\n 'valid_loss_hist': self.valid_loss_hist,\n 'optim_type': self.optim_type,\n 'alpha': self.alpha,\n 'criterion': self.criterion,\n 'use_cuda': self.use_cuda\n }, name)\n\n @staticmethod\n def load(name='model.pth'):\n if not '.pth' in name: name += '.pth'\n checkpoint = torch.load(name)\n model = NeuralNet(\n optimizer = checkpoint['optim_type'],\n alpha = checkpoint['alpha'],\n criterion = checkpoint['criterion'],\n use_cuda = checkpoint['use_cuda']\n )\n model.lin_1 = checkpoint['lin_1']\n model.relu = checkpoint['relu']\n model.lin_2 = checkpoint['lin_2']\n model.softmax = checkpoint['softmax']\n model.train_loss = checkpoint['train_loss']\n model.valid_loss = checkpoint['valid_loss']\n model.train_loss_hist = checkpoint['train_loss_hist']\n model.valid_loss_hist = checkpoint['valid_loss_hist']\n model.startup_routines()\n return model","sub_path":"nn_template.py","file_name":"nn_template.py","file_ext":"py","file_size_in_byte":7527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"22952020","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nfile: blackBoxTrading.py\r\nauthor: Himanshu\r\ndescription: first attempt at creating a trading algorithm in python\r\n\"\"\"\r\n\r\n### PART 1: INTRODUCTION ############################################\r\n\r\n# print current stock price\r\nimport yahoo\r\nfrom yahoo_finance import Share\r\nAMZN = Share(\"AMZN\")\r\nprint(AMZN_now.get_open()) # opening price\r\nprint(AMZN_now.get_price()) # current price\r\n\r\n# get todays data (52 high, low, )\r\ntoday_data = AMZN_now.data_set\r\n\r\nAMZN.refresh() # refresh the system to get latest prices\r\n\r\n# get historical data\r\nhist_data = AMZN.get_historical('2017-01-01', '2017-01-19')\r\nprint(hist_data)\r\n\r\n### PART 2: BASIC ALGORITHM USING ANN ##############################\r\nimport pandas as pd\r\n\r\ndata = pd.read_csv(\"SP500data.csv\")\r\n\r\n# make date the index column:\r\ndateparse = lambda dates: pd.datetime.strptime(dates, '%m/%d/%Y') \r\ndata = pd.read_csv('SP500data.csv', parse_dates=['Date'], index_col='Date',date_parser=dateparse)\r\n\r\n# build the ANN\r\n# Importing the libraries\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# split X and Y\r\nX = data.iloc[:, 0:6].values #index of columns in the independent (predictor) variables\r\ny = data.iloc[:, 6:9].values #col 13 (what we are predicting)\r\n\r\nX = np.array(X[:,:])\r\n\r\n\r\n# split into training and testing data\r\nX_train = X[0:2000, :]\r\nX_test = X[2000:, :]\r\ny_train = y[0:2000, :]\r\ny_test = y[2000:, :]\r\n\r\n# feature scaling\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.preprocessing import MinMaxScaler\r\n\r\nsc = StandardScaler()\r\nX_train = sc.fit_transform(X_train)\r\nX_test = sc.transform(X_test)\r\n\r\n# initiate the ANN\r\nimport keras\r\nfrom keras.models import Sequential # used to initialize NN\r\nfrom keras.layers import Dense # model to create different layers in NN\r\n\r\n# Initialising the ANN\r\nclassifier = Sequential()\r\n\r\n# Adding the input layer and the first hidden layer\r\nclassifier.add(Dense(units = 5, kernel_initializer = 'uniform', activation = 'relu', input_dim = 6))\r\n# 9 nodes in the hidden layer (tip: input nodes + output nodes /2), and tells next layer no. of nodes to expect\r\n\r\n# Adding the second hidden layer\r\nclassifier.add(Dense(units = 5, kernel_initializer = 'uniform', activation = 'relu'))\r\n# knows what inputs to expect because there is already an input layer created\r\n\r\n# Adding the output layer\r\nclassifier.add(Dense(units = 3, kernel_initializer = 'uniform', activation = 'sigmoid'))\r\n\r\n# Compiling the ANN\r\nclassifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\r\n \r\n# Fitting the ANN to the Training set and training the ANN\r\nclassifier.fit(X_train, y_train, batch_size = 5, epochs = 20)\r\n\r\n# assess accuracy using test set\r\ny_pred = classifier.predict(X_test) # gives prediction for each observation in test set\r\n\r\n# encoding percentages into hard buy/hold/sell (NEED TO FIX THIS)\r\nrow=0\r\n\r\ny_pred[1]\r\n\r\ny_newarray = np.empty([742,3], order=\"C\")\r\nfor row in y_pred:\r\n print(row[0])\r\n if row[0]>0.2:\r\n y_newarray = np.append(y_newarray, [1, ])\r\n else: y_newarray = np.append(y_newarray, [0, ])\r\n if row[1]>0.5:\r\n y_newarray = np.append(y_newarray, [1, ])\r\n else: y_newarray = np.append(y_newarray, [0, ])\r\n if row[2]>0.2:\r\n y_newarray = np.append(y_newarray, [1])\r\n else: y_newarray = np.append(y_newarray, [0])\r\n \r\n row=row+1\r\n \r\nprint(y_newarray)\r\n\r\n# confusion matrix \r\nfrom sklearn.metrics import confusion_matrix\r\ncm = confusion_matrix(y_test, y_pred)\r\n\r\n\r\n# add the inputs and apply feature scaling\r\nsample_day = sc.transform(np.array([[65,0,180,101,101,28,99.2]]))\r\nsample_pred = classifier.predict(sample_patient)","sub_path":"blackBoxTrading.py","file_name":"blackBoxTrading.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"454765748","text":"#python 数据类型\r\n\r\n'''\r\nC语言在定义变量需要声明数据类型,比如:\r\nint a = 10 #定义整形(整数)变量a=10\r\nfloat b = 3.14 #定义浮点(小数)变量b=3.14\r\nchar c = \"C语言需要说明类型\" #定义字符(组)变量c=\"C语言需要说明类型\"\r\n当然也有这种:char d = \"123\" #此时123是字符类型而不是整数,不能拿来计算\r\n'''\r\n'''\r\n而python则不需要,变量就是变量,没有类型\r\n我们所说的\"类型\"是变量所指的内存中对象的类型。\r\n等号(=)用来给变量赋值。\r\n等号(=)运算符左边是一个变量名,右边是存储在变量中的值。\r\n\r\n关于python变量没有类型这一说法,做以下实践来检验:\r\n>>> c=213\r\n>>> type(c)\r\n\r\n>>> c='python修改变量跟c的数据类型无关'\r\n>>> type(c)\r\n\r\n我们定义c一开始是整形变量,后来直接修改c为字符类型。\r\n说明c本身没有属性,有属性的是c的值\r\n***C语言这样做一定会报错,除非在同时原基础上修改变量类型\r\n'''\r\n\r\n\r\n#一、多变量赋值\r\n\r\n#python允许多变量赋值。例如:\r\na=b=c=1\r\n#也可以这样:\r\nd,e,f=1,2,\"python\"\r\n\r\n#二、标准数据类型\r\n\r\n#1.标准数据类型\r\n'''\r\npython3中有6个标准数据类型:\r\n数字、字符串、列表、元祖、集合、字典\r\n分类可分为:\r\n不可变数据:数字、字符串、元祖\r\n可变数据:列表、字典、集合\r\n'''\r\n\r\n#2.数字\r\n'''\r\npython3支持 int(整数)、float(小数)、bool(布尔)、complex(复数)\r\n*注意:其中:布尔看起来并不是数字,但归为数字类型,原因是python2的'布尔'用0代表False,1代表True\r\n 而在python3中,它们成关键字了,但值还是0或1,它们可以用来数字相加,所以它仍是数字类型\r\n'''\r\na,b,c,d=20,3.14,True,4+3j\r\nprint(type(a),type(b),type(c),type(d))\r\n#输出结果: \r\n\r\n#此外,还能用isintance来判断,方法如下:\r\na=111\r\nisinstance(a,int)\r\n#输出结果为:True\r\n\r\n'''\r\n这样都没毛病:\r\n>>> 1 == True\r\nTrue\r\n>>> 0 == False\r\nTrue\r\n>>> 0+1 == True+False\r\nTrue\r\n但是:\r\n>>> type(1) == type(True)\r\nFalse\r\n>>> type(True*1)\r\n\r\n>>> type(True)\r\n\r\n���论:False/True是bool类型,但是只要bool类型经过了有效算术运算,它就改变了类型(哪怕代表的值仍是0 or 1)\r\n'''\r\n\r\n#当你指定一个值时,number对象就会被创建\r\nnum1,num2=1,2\r\n#创建的变量可以用del语句删除\r\ndel num1,num2\r\n\r\n#数值运算\r\n'''\r\n>>>5 + 4 # 加法\r\n9\r\n>>> 4.3 - 2 # 减法\r\n2.3\r\n>>> 3 * 7 # 乘法\r\n21\r\n>>> 4 / 2 # 除法,得到一个浮点数\r\n2.0\r\n>>> 4 // 2 # 除法,得到一个整数\r\n2\r\n>>> 17 % 3 # 取余 \r\n2\r\n>>> 2 ** 5 # 乘方\r\n32\r\n\r\n特别注意:在混合计算时,python会把整数转换成浮点数\r\n'''\r\n\r\n#python的复数\r\n'''\r\n方法一:a+bj\r\n方法二:complex(a,b)\r\n注意:复数的实部a和虚部b都是浮点型\r\n'''\r\n\r\n#字符串\r\n\r\n#python中的字符串用单引号或双引号括起来,同时用\\转义特殊字符\r\n'''\r\n单个元素截取[索引]:\r\n\r\n从右向左索引:-6-5-4-3-2-1\r\n从左向右索引: 0 1 2 3 4 5\r\nb= a b c d e f \r\n字符串中每一个元素都有自己的索引,截取单个字符直接输入索引值就可以\r\n例如:b[0]=a\r\n'''\r\n\r\n'''\r\n 字符串截取(主要针对多元素截取)\r\n 语法:[开始:结束],注意这里的开始结束意为光标的位置,而不是索引值!\r\nc= | p | y | t | h | o | n |\r\n 0 1 2 3 4 5 6\r\n 光标后面的字母将不会被选中\r\n 所以,正确打印'python'应该输入[0:6]\r\n'''\r\n\r\n'''\r\n加号 + 是字符串的连接符, \r\n星号 * 表示复制当前字符串,紧跟的数字为复制的次数。实例回顾:\r\nprint (str) # 输出字符串\r\nprint (str[0:-1]) # 输出第一个到倒数第二个的所有字符\r\nprint (str[0]) # 输出字符串第一个字符\r\nprint (str[2:5]) # 输出从第三个开始到第五个的字符\r\nprint (str[2:]) # 输出从第三个开始的后的所有字符\r\nprint (str * 2) # 输出字符串两次\r\nprint (str + \"TEST\") # 连接字符串\r\n\r\n'''\r\n\r\n#python使用\\转义字符,如果不想让它转义,可以在字符串前加r,表示原始字符串\r\nprint('py\\nthon')#转义,\\n作为enter键使用\r\nprint(r'py\\nthon')#不转义,直接输出\r\n\r\n#特别提醒\r\n#1.反斜杠(\\)可以作为续行符,表示下一行是上一行的延续。也可以使用 \"\"\"...\"\"\" 或者 '''...''' 跨越多行。\r\n#2.注意Python 没有单独的字符类型,一个字符就是长度为1的字符串。\r\n#3.与 C 字符串不同的是,Python 字符串不能被改变。向一个索引位置赋值,比如word[0] = 'm'会导致错误。\r\n\r\n#列表\r\n'''\r\n列表是python使用最频繁的数据类型\r\n它可以完成大多数集合类的数据结构实现。\r\n列表包含多种元素:数字,字符串甚至列表(被称为嵌套)\r\n格式:变量[头下标:尾下标]\r\n'''\r\n#列表的索引值与字符串类似\r\n'''\r\nlist = ['abcd', 786, 2.23, 'runoob', 70.2]\r\ntinylist = [123, 'runoob']\r\n\r\nprint(list) # 输出完整列表\r\nprint(list[0]) # 输出列表第一个元素\r\nprint(list[1:3]) # 从第二个开始输出到第三个元素\r\nprint(list[2:]) # 输出从第三个元素开始的所有元素\r\nprint(tinylist * 2) # 输出两次列表\r\nprint(list + tinylist) # 连接列表\r\n'''\r\n\r\n#与字符串不同,list中的元素是可以改变的\r\n'''\r\n[9, 2, 13, 14, 15, 6]\r\n>>> a[2:5] = [] # 将对应的元素值设置为 [] \r\n>>> a\r\n[9, 2, 6]\r\n'''\r\n#列表内置了很多方法,后面会专门讲这一点\r\n\r\n#元祖\r\n'''\r\n元祖与列表类似,只是元素不能被修改\r\n元祖写在小括号里(),元素中间用逗号隔开\r\n实例:\r\ntuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2 )\r\ntinytuple = (123, 'runoob')\r\n \r\nprint (tuple) # 输出完整元组\r\nprint (tuple[0]) # 输出元组的第一个元素\r\nprint (tuple[1:3]) # 输出从第二个元素开始到第三个元素\r\nprint (tuple[2:]) # 输出从第三个元素开始的所有元素\r\nprint (tinytuple * 2) # 输出两次元组\r\nprint (tuple + tinytuple) # 连接元组\r\n'''\r\n#其实可以把字符串看作一个特殊的元祖\r\n\r\n'''\r\n特殊情况:\r\n虽然tuple的元素不可改变,但它可以包含可变的对象,比如list列表。\r\n构造包含0个或1个元素的元组比较特殊,所以有一些额外的语法规则:\r\ntup1 = () # 空元组\r\ntup2 = (20,) # 一个元素,需要在元素后添加逗号\r\n'''\r\n\r\n\r\n#集合\r\n'''\r\n集合是一无序不重复的序列(它没有索引值)\r\n功能:成员关系测试和删除重复元素\r\n使用{}或set()函数创建集合,注意:创建空集合必须用set()而不是{},{}是用来创建空字典\r\n'''\r\n\r\n'''\r\n>>> student={'tom','jim','jack','jim','rose'}\r\n>>> student #输出集合,重复元素将会被去掉\r\n{'tom', 'rose', 'jack', 'jim'}\r\n\r\n>>> 'rose' in student #成员测试\r\nTrue\r\n'''\r\n\r\n'''\r\n#集合运算\r\n# set可以进行集合运算\r\na = set('asdfg')\r\nb = set('allow')\r\n\r\n>>> a\r\n{'g', 'd', 'a', 'f', 's'}\r\n>>> b\r\n{'w', 'a', 'o', 'l'}\r\n \r\n#两个及两个以上集合的关系\r\nprint(a)\r\nprint(a - b) # a和b的差集\r\nprint(a | b) # a和b的并集\r\nprint(a & b) # a和b的交集\r\nprint(a ^ b) # a和b中不同时存在的元素\r\n'''\r\n\r\n#字典\r\n\r\n'''\r\n字典(dictionary)是Python中另一个非常有用的内置数据类型。\r\n列表是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。\r\n字典是一种映射类型,字典用\"{ }\"标识,它是一个无序的键(key) : 值(value)对集合。\r\n键(key)必须使用不可变类型:字符串,元祖,字典。\r\n在同一个字典中,键(key)必须是唯一的。\r\n'''\r\n\r\n'''\r\n字典的两种建立方法:\r\ndict={}\r\ndict['one']='1-python语法'\r\ndict[9]='0-python安装'\r\n\r\ntinydict={'name':'jim','age':18,'job':'programmer'}\r\n'''\r\n\r\n'''\r\n字典的简单使用\r\nprint (dict['one']) # 输出键为 'one' 的值\r\nprint (dict[9]) # 输出键为 9 的值\r\nprint (tinydict) # 输出完整的字典\r\nprint (tinydict.keys()) # 输出所有键\r\nprint (tinydict.values()) # 输出所有值\r\n'''\r\n\r\n'''\r\n三种建造字典的方式\r\n>>> dict([('jd',3),('amazon',2),('tb',1)])\r\n{'jd': 3, 'amazon': 2, 'tb': 1}\r\n>>> {x:x**2 for x in(1,2,3)}\r\n{1: 1, 2: 4, 3: 9}\r\n>>> dict(jd=3,amazon=2,tb=1)\r\n{'jd': 3, 'amazon': 2, 'tb': 1}\r\n'''\r\n\r\n\r\n#python数据类型转换\r\n'''\r\nint(x [,base])\r\n将x转换为一个整数,字符串只能转化数字部分\r\n>>> str='12py'\r\n>>> int(str[0:2])\r\n12\r\n\r\nfloat(x)\r\n将x转换到一个浮点数\r\n\r\ncomplex(real [,imag])\r\n创建一个复数,字符串只能转化数字部分(i,j)\r\n\r\nstr(x)\r\n将对象 x 转换为字符串\r\n\r\nrepr(x)\r\n将对象 x 转换为表达式字符串\r\n\r\neval(str)\r\n用来计算在字符串中的有效Python表达式,并返回一个对象\r\n>>> str='1+2'\r\n>>> eval(str)\r\n3\r\n\r\ntuple(s)\r\n将序列 s 转换为一个元组 *序列:字符串,元祖和列表\r\n>>> s=['a','b','c']\r\n>>> tuple(s)\r\n('a', 'b', 'c')\r\n\r\nlist(s)\r\n将序列 s 转换为一个列表\r\n\r\nset(s)\r\n将字符串/数字转换为可变集合\r\n\r\ndict(d)\r\n创建一个字典。d 必须是一个序列 (key,value)元组。\r\n\r\nfrozenset(s)\r\n转换为不可变集合\r\n\r\nchr(x)\r\n将一个整数转换为一个字符\r\n\r\nord(x)\r\n将一个字符转换为它的整数值\r\n\r\nhex(x)\r\n将一个整数转换为一个十六进制字符串\r\n\r\noct(x)\r\n将一个整数转换为一个八进制字符串\r\n'''\r\n\r\n","sub_path":"study_DataType.py","file_name":"study_DataType.py","file_ext":"py","file_size_in_byte":9712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"148627287","text":"#!/usr/bin/python\n#\n# Copyright 2014 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\nimport os\nimport unittest2\n\nos.environ['COMPASS_IGNORE_SETTING'] = 'true'\n\n\nfrom compass.utils import setting_wrapper as setting\nreload(setting)\n\n\nfrom compass.log_analyzor import line_matcher\nfrom compass.utils import flags\nfrom compass.utils import logsetting\n\n\nclass TestProgressCalculator(unittest2.TestCase):\n def setUp(self):\n super(TestProgressCalculator, self).setUp()\n logsetting.init()\n self._mock_progress()\n\n def tearDown(self):\n super(TestProgressCalculator, self).tearDown()\n\n def _mock_progress(self):\n self.log_history = {\n 'percentage': 0.5,\n 'message': '',\n 'severity': ''\n }\n\n def test_update_progress_progress(self):\n test_1 = {\n 'progress_data': 0.7,\n 'message': '',\n 'severity': '',\n 'log_history': self.log_history\n }\n expected_1 = 0.7\n line_matcher.ProgressCalculator.update_progress(\n **test_1)\n self.assertEqual(expected_1, self.log_history['percentage'])\n\n def test_update_progress_other(self):\n test = {\n 'progress_data': 0.5,\n 'message': 'dummy',\n 'severity': 'dummy',\n 'log_history': self.log_history\n }\n expected_message = test['message']\n expected_severity = test['severity']\n line_matcher.ProgressCalculator.update_progress(\n **test)\n self.assertEqual(expected_message, self.log_history['message'])\n self.assertEqual(expected_severity, self.log_history['severity'])\n\n\nclass TestIncrementalProgress(unittest2.TestCase):\n def setUp(self):\n super(TestIncrementalProgress, self).setUp()\n logsetting.init()\n self.log_history = {\n 'percentage': 0.5,\n 'message': '',\n 'severity': ''\n }\n\n def tearDown(self):\n super(TestIncrementalProgress, self).tearDown()\n\n def test_update(self):\n test_data = {\n 'min_progress': 0.3,\n 'max_progress': 0.7,\n 'incremental_ratio': 0.5\n }\n progress = line_matcher.IncrementalProgress(\n **test_data)\n message = 'dummy'\n severity = 'dummy'\n log_history = {\n 'percentage': 0.5,\n 'message': '',\n 'severity': ''\n }\n expected = 0.7\n progress.update(message, severity, log_history)\n self.assertEqual(expected, log_history['percentage'])\n\n def test_init(self):\n test_exceed_one = {\n 'min_progress': 1.1,\n 'max_progress': 1.1,\n 'incremental_ratio': 0.5,\n }\n self.assertRaises(\n IndexError,\n line_matcher.IncrementalProgress,\n **test_exceed_one)\n\n def test_min_larger_than_max(self):\n test_min_larger_than_max = {\n 'min_progress': 0.7,\n 'max_progress': 0.3,\n 'incremental_ratio': 0.5,\n }\n self.assertRaises(\n IndexError,\n line_matcher.IncrementalProgress,\n **test_min_larger_than_max)\n\n def test_invalid_ratio(self):\n test_invalid_ratio = {\n 'min_progress': 0.3,\n 'max_progress': 0.7,\n 'incremental_ratio': 1.1,\n }\n self.assertRaises(\n IndexError,\n line_matcher.IncrementalProgress,\n **test_invalid_ratio\n )\n\n\nclass TestRelativeProgress(unittest2.TestCase):\n def setUp(self):\n super(TestRelativeProgress, self).setUp()\n logsetting.init()\n\n def tearDown(self):\n super(TestRelativeProgress, self).tearDown()\n\n def test_init(self):\n self.assertRaises(\n IndexError,\n line_matcher.RelativeProgress,\n progress=1.1\n )\n\n\nclass TestLineMatcher(unittest2.TestCase):\n def setUp(self):\n super(TestLineMatcher, self).setUp()\n logsetting.init()\n\n def tearDown(self):\n super(TestLineMatcher, self).tearDown()\n\n def test_progress_unsupported(self):\n test_progress_unsupported = {\n 'pattern': r' ',\n 'progress': 'dummy',\n }\n self.assertRaises(\n TypeError,\n line_matcher.LineMatcher,\n **test_progress_unsupported)\n\n def test_regex_not_match(self):\n line = 'abc'\n regex_ = r'^s'\n \"\"\"progress = line_matcher.Progress(\n progress=1, message='a', severity=' ')\"\"\"\n log_history = {\n 'percentage': 1,\n 'message': 'a',\n 'serverity': ''\n }\n test_regex_not_match = {\n 'pattern': regex_,\n 'unmatch_sameline_next_matcher_name': 'usn',\n 'unmatch_nextline_next_matcher_name': 'unn',\n 'match_sameline_next_matcher_name': 'msn',\n 'match_nextline_next_matcher_name': 'mnn',\n }\n matcher = line_matcher.LineMatcher(\n **test_regex_not_match)\n expected = ('usn', 'unn')\n self.assertEqual(\n expected,\n matcher.update_progress(\n line, log_history))\n\n def test_regex_match(self):\n line = 'abc'\n regex_ = r'^a'\n log_history = {\n 'percentage': 1,\n 'message': 'a',\n 'serverity': ''\n }\n test_regex_match = {\n 'pattern': regex_,\n 'unmatch_sameline_next_matcher_name': 'usn',\n 'unmatch_nextline_next_matcher_name': 'unn',\n 'match_sameline_next_matcher_name': 'msn',\n 'match_nextline_next_matcher_name': 'mnn',\n }\n matcher = line_matcher.LineMatcher(\n **test_regex_match)\n expected = ('msn', 'mnn')\n self.assertEqual(\n expected,\n matcher.update_progress(\n line, log_history)\n )\n\n def test_wrong_message(self):\n line = 'abc'\n log_history = {\n 'percentage': 1,\n 'message': 'a',\n 'serverity': ''\n }\n test_wrong_message = {\n 'pattern': r'.*.',\n 'message_template': 'Installing %(package)s'\n }\n matcher = line_matcher.LineMatcher(\n **test_wrong_message)\n self.assertRaises(\n KeyError,\n matcher.update_progress,\n line=line,\n log_history=log_history\n )\n\nif __name__ == '__main__':\n flags.init()\n logsetting.init()\n unittest2.main()\n","sub_path":"compass/tests/log_analyzor/test_line_matcher.py","file_name":"test_line_matcher.py","file_ext":"py","file_size_in_byte":7110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"459505767","text":"\n# coding: utf-8\n\n# In[2]:\n\n#distribution cost estimation. For further detail, check the report on this directory\nimport pandas as pd\nimport numpy as np\ndfs=pd.read_csv(\"tables/CategorizedCounties.csv\")\n'''The calculations of each of the distribution cost estimates \nis made using a simplified version of the formulas contained in the report\nfor improving performance and for asuring none of our variables becomes cero (as some of them are really small)'''\nannual_cost=1872.5\nfor c in dfs.index.tolist():\n dfs.set_value(c,\"DistributionCost2 (millions of MXN)\", dfs.loc[c,\"real state with electricity\"].astype(\"int64\")*annual_cost/(3*dfs[\"real state with electricity\"].astype('int64').sum())+dfs.loc[c,\"land area (km^2)\"].astype(\"int64\")*annual_cost/(dfs[\"land area (km^2)\"].astype('int64').sum()*3))\n\n if str(dfs.loc[c,'county type'])==\"urban\":\n dfs.set_value(c,'DistributionCost1 (millions of MXN)',dfs.loc[c,'land area (km^2)'].astype(\"float64\")*.5*.003+dfs.loc[c,\"real state with electricity\"].astype(\"int64\")*.005*.003 + dfs.loc[c,\"real state with electricity\"].astype(\"int64\")/80 * .035)\n else:\n dfs.set_value(c,'DistributionCost1 (millions of MXN)',dfs.loc[c,'land area (km^2)'].astype(\"float64\")*1*.005+dfs.loc[c,\"real state with electricity\"].astype(\"int64\")*.05*.005 + dfs.loc[c,\"real state with electricity\"].astype(\"int64\")/40 *.025)\n dfs.set_value(c,\"diference of estimation (millions of MXN)\",abs(dfs.loc[c,'DistributionCost1 (millions of MXN)']-dfs.loc[c,\"DistributionCost2 (millions of MXN)\"]))\ndfs.to_csv(\"tables/CategorizedCounties.csv\",index=False)\n\n\n# In[ ]:\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n","sub_path":"Costs/Distribution costs estimation/DistributionCostEstimation.py","file_name":"DistributionCostEstimation.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"116630030","text":"import time\n\nN_LISTS = 75\nN_ITEMS = 1000000\n\nlists = []\nfor i in range(N_LISTS):\n l = list(range(N_ITEMS))\n \n lists.append(l)\n\nstart = time.time()\n\nconcatenated_list = []\nfor l in lists:\n concatenated_list += l\n\nend = time.time()\n\n\nprint(\"It took %f seconds to concatenate %d lists with %d items\" %(end - start, N_LISTS, N_ITEMS))\n","sub_path":"profiling/concatenate_lists.py","file_name":"concatenate_lists.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"286761374","text":"#coding:utf-8\nfrom PIL import Image, ImageFilter, ImageFont\nimport random\n\n# 打开图片\nim = Image.open('d:/a.png')\n# 获得图片尺寸\nw, h = im.size\nprint(w, h)\n# 缩小一半\nim.thumbnail((w/2, h/2))\nim.save('d:/b.png', 'jpeg')\n\n# 加模糊效果\nim2 = im.filter(ImageFilter.BLUR)\nim2.save('d:/c.png', 'jpeg')\n","sub_path":"01.pythonAPI/33.Pillow.py","file_name":"33.Pillow.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"206806076","text":"import sqlite3\n\nconector = sqlite3.connect(\"vendas1.db\")\ncursor = conector.cursor()\n\n# TABELA Marca\ncursor.execute(\"\"\"\nCREATE TABLE Tamanho (\n Tamanho VARCHAR (3) NOT NULL PRIMARY KEY\n \n \n\n);\n\"\"\")\n\nconector.commit()\ncursor.close()\nconector.close()\n\nprint(\"Abra a pasta do programa e veja se o arquivo esta lá\")\nprint(\"Fim do Programa\")\n","sub_path":"tamanho.py","file_name":"tamanho.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"58745589","text":"# -*- coding:utf-8 -*-\n\nimport os\nimport time\nimport networkx as nx\nfrom tqdm import tqdm\nimport multiprocessing as mp\nfrom utils.visualize import plot_embeddings\nimport numpy as np\nfrom utils.util import dataloader, sparse_process, save_vectors, read_vectors, read_distance\nfrom utils.evaluate import evaluate_LR_accuracy, evaluate_KNN_accuracy, cluster_evaluate\nfrom model.GraphWave import GraphWave, scale_boundary\nfrom model.struc2vec import Struc2Vec\nfrom model.LocallyLinearEmbedding import LocallyLinearEmbedding\nfrom model.LaplacianEigenmaps import LaplacianEigenmaps\nfrom model.node2vec import Node2Vec\n\nfrom ge.utils.robustness import random_remove_edges\nfrom ge.utils.db import Database\nfrom ge.utils.tsne import tsne, cal_pairwise_dist\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\ndef graphWave(name, graph, reused=False, scale=10.0, dim=32):\n path = \"../../output/graphwave_{}_{}.csv\".format(name, scale)\n if reused and os.path.exists(path):\n embeddings_dict = read_vectors(path)\n else:\n wave_machine = GraphWave(graph, heat_coefficient=scale, sample_number=dim)\n embeddings_dict = wave_machine.single_scale_embedding(scale)\n save_vectors(embeddings_dict, path)\n return embeddings_dict\n\n\ndef node2vec(name, graph, reused=False, walk_length=50, window_size=20, num_walks=30, p=1.0, q=2.0, dim=64):\n path = \"../../output/node2vec_{}_length30.csv\".format(name)\n if reused and os.path.exists(path):\n embeddings_dict = read_vectors(path)\n else:\n graph = nx.DiGraph(graph)\n model = Node2Vec(graph, walk_length=walk_length, num_walks=num_walks, p=p, q=q, workers=3)\n model.train(embed_size=dim, window_size=window_size, iter=500)\n embeddings_dict = model.get_embeddings()\n save_vectors(embeddings_dict, path)\n return embeddings_dict\n\n\ndef LE(graph, dim=32):\n model = LaplacianEigenmaps(graph, dim=dim)\n embeddings_dict = model.create_embedding()\n return embeddings_dict\n\n\ndef struc2vec(name, graph, walk_length=10, window_size=10,\n num_walks=15, stay_prob=0.3, dim=16, reused=False):\n\n path = \"../../output/struc2vec_{}_length30.csv\".format(name)\n if reused and os.path.exists(path):\n embeddings_dict = read_vectors(path)\n else:\n model = Struc2Vec(graph, walk_length=walk_length, num_walks=num_walks, stay_prob=stay_prob)\n model.train(embed_size=dim, window_size=window_size)\n embeddings_dict = model.get_embeddings()\n save_vectors(embeddings_dict, path=path)\n\n return embeddings_dict\n\n\ndef hseLLE(name, graph, scale=10.0, method='l1', dim=16, percentile=0.0, reuse=True):\n save_path = \"../../similarity/{}_{}_{}.csv\".format(name, scale, method)\n if not (reuse and os.path.exists(save_path)):\n wave_machine = GraphWave(graph, heat_coefficient=scale)\n coeffs = wave_machine.cal_all_wavelet_coeffs(scale)\n #wave_machine.calc_wavelet_similarity(coeff_mat=coeffs, method=method, layers=5, normalized=False, save_path=save_path)\n #wave_machine.parallel_calc_similarity(coeff_mat=coeffs, metric=method, layers=10, mode=\"similarity\", save_path=save_path)\n wave_machine.calc_wavelet_similarity(coeff_mat=coeffs, hierachical=True, method=method, normalized=False, layers=5, save_path=save_path)\n\n\n new_graph, _, _ = dataloader(name, directed=False, similarity=True, scale=scale, metric=method)\n new_graph = sparse_process(new_graph, percentile=percentile)\n model = LocallyLinearEmbedding(new_graph, dim)\n #embeddings_dict = model.create_embedding(dim)\n embeddings_dict = model.sklearn_lle(n_neighbors=10, dim=dim, random_state=42)\n return embeddings_dict\n\n\ndef hseNode2vec(idx, name, graph, scale=10, metric='l1', dim=16, percentile=0.0, reuse=True):\n save_path = \"../../similarity/{}_{}_{}_idx.csv\".format(name, scale, metric)\n if not (reuse and os.path.exists(save_path)):\n wave_machine = GraphWave(graph, heat_coefficient=scale)\n coeffs = wave_machine.cal_all_wavelet_coeffs(scale)\n wave_machine.calc_wavelet_similarity(coeff_mat=coeffs, method=metric, layers=10, save_path=save_path)\n\n new_graph, _, _ = dataloader(name, directed=True, label='auto', similarity=True, scale=scale, metric=metric)\n new_graph = sparse_process(new_graph, percentile=percentile)\n model = Node2Vec(new_graph, walk_length=15, num_walks=10, p=1, q=1.0, workers=1)\n model.train(window_size=15, iter=300, embed_size=dim)\n embeddings_dict = model.get_embeddings()\n return embeddings_dict\n\n\ndef hseLE(name, graph, scale=10.0, method='l1', dim=16, threshold=None, percentile=None, reuse=True):\n save_path = \"../../similarity/{}_{}_{}.csv\".format(name, scale, method)\n if not (reuse and os.path.exists(save_path)):\n wave_machine = GraphWave(graph, heat_coefficient=scale)\n coeffs = wave_machine.cal_all_wavelet_coeffs(scale)\n wave_machine.calc_wavelet_similarity(coeff_mat=coeffs, hierachical=True, normalized=False, method=method, layers=5, save_path=save_path)\n\n new_graph, _, _ = dataloader(name, directed=False, similarity=True, scale=scale, metric=method)\n model = LaplacianEigenmaps(new_graph, dim=dim)\n embeddings_dict = model.create_embedding(threshold=threshold, percentile=percentile)\n #embeddings_dict = model.spectralEmbedding()\n return embeddings_dict\n\n\ndef rolx(data_name):\n embeddings_dict = read_vectors(\"../../output/rolx_{}.csv\".format(data_name))\n return embeddings_dict\n\n\ndef embedd(data_name, label_class=\"SIR\"):\n graph, label_dict, n_class = dataloader(data_name, directed=False, label=label_class)\n wave_machine = GraphWave(graph)\n eigenvalues = wave_machine._e\n print(min(eigenvalues), max(eigenvalues))\n sMin, sMax = scale_boundary(eigenvalues[3], eigenvalues[-1])\n scale = (sMin + sMax) / 2 # 根据GraphWave论文中推荐的尺度进行设置。\n print(sMin, sMax, scale)\n scale = 0.015\n\n #embedding_dict = hseLE(name=data_name, graph=graph, scale=scale, method='wasserstein', dim=64, percentile=0.7, reuse=True)\n #embedding_dict = hseLLE(name=data_name, graph=graph, scale=0.1, percentile=0.7, method='wasserstein', dim=64, reuse=True)\n #embedding_dict = hseNode2vec(name=data, graph=graph, scale=10, metric='l1', dim=32, percentile=0.5, reuse=False)\n #embedding_dict, method = struc2vec(data_name, graph=graph, walk_length=20, window_size=10, num_walks=10, stay_prob=0.5, dim=64, reused=True), \"struc2vec\"\n embedding_dict, method = node2vec(data_name, graph, walk_length=20, num_walks=10, window_size=10, p=1, q=2, dim=64, reused=True), \"node2vec\"\n #embedding_dict = LE(graph, dim=64)\n #embedding_dict, method = graphWave(data_name, graph, scale=scale, dim=64, reused=True), \"graphwave\"\n #embedding_dict = LocallyLinearEmbedding(graph=graph, dim=64).create_embedding()\n #embedding_dict = rolx(data_name)\n #method = \"struc2vec\"\n #embedding_dict = read_vectors(\"C:\\\\Users\\86234\\Desktop\\论文相关\\跨图\\\\struc2vec_flight.csv\")\n nodes = []\n labels = []\n embeddings = []\n for node, embedding in embedding_dict.items():\n nodes.append(node)\n embeddings.append(embedding)\n labels.append(label_dict[node])\n\n #dist = cal_pairwise_dist(np.array(embeddings))\n #embeddings = tsne(distance_mat=dist, dim=2, perplexity=30)\n\n #cluster_evaluate(embeddings, labels, class_num=n_class)\n #evaluate_LR_accuracy(embeddings, labels, random_state=42)\n evaluate_KNN_accuracy(embeddings, labels, \"euclidean\", random_state=42, n_neighbor=20)\n\n _2d_data = plot_embeddings(nodes, embeddings, labels, n_class, method=\"tsne\", init=\"random\",\n perplexity=50, node_text=False, random_state=35)\n tmp = {}\n for idx, node in enumerate(nodes):\n tmp[node] = _2d_data[idx]\n save_vectors(tmp, \"../../output_SIR/{}_{}_tsne.csv\".format(method, data_name))\n #heat_map(embeddings, labels)\n\n\ndef robustness(data, probs=None, cnt=10, scale=10.0, label=\"SIR\", metric='l1', dim=32, percentile=0.75):\n \"\"\"\n 测试鲁棒性\n :param data:\n :param probs:\n :param cnt:\n :param scale:\n :param label:\n :param metric:\n :param dim:\n :param percentile:\n :return:\n \"\"\"\n graph, label_dict, n_class = dataloader(data, directed=False, label=label)\n pool = mp.Pool(5)\n results = []\n for i, p in enumerate(probs):\n _res = pool.apply_async(worker, args=(i, p, data, graph, label_dict, n_class, cnt, scale, metric, dim, percentile))\n results.append(_res)\n\n pool.close()\n pool.join()\n for _res in results:\n _res.get()\n\n\ndef worker(idx, prob, data, graph, label_dict, n_class, cnt=10, scale=2, metric='l1', dim=64, percentile=0.75):\n db = Database()\n print(\"idx = {}, prob = {}\".format(idx, prob))\n for _ in tqdm(range(cnt)):\n start = time.time()\n\n if prob == 1.0:\n _graph = graph\n else:\n _graph = random_remove_edges(nx.Graph(graph), prob=prob)\n\n #embedding_dict = hseLE(name=data, graph=_graph, scale=scale, method=metric, dim=dim, percentile=percentile, reuse=False)\n #method = \"HSELE\"\n\n #embedding_dict = hseNode2vec(idx, name=data, graph=_graph, scale=scale, metric=metric,\n # dim=dim, percentile=percentile, reuse=False)\n\n embedding_dict = hseLLE(name=data, graph=_graph, scale=scale, method=metric, dim=dim, percentile=percentile, reuse=False)\n method = \"HSELLE\"\n\n #embedding_dict = graphWave(name=data, graph=_graph, scale=scale, dim=64, reused=False)\n #method = \"graphwave\"\n\n #embedding_dict = struc2vec(name=data, graph=_graph, walk_length=60, window_size=25, num_walks=10, stay_prob=0.3, dim=64, reused=False)\n #method = \"struc2vec\"\n\n #embedding_dict = node2vec(name=data, graph=_graph, walk_length=60, num_walks=10, window_size=25, p=1, q=2, dim=64, reused=False)\n #method = \"node2vec\"\n\n _time = time.time() - start\n\n nodes = []\n labels = []\n embeddings = []\n for node, embedding in embedding_dict.items():\n nodes.append(node)\n embeddings.append(embedding)\n labels.append(label_dict.get(node, str(n_class)))\n\n accuracy, balanced_accuracy, precision, recall, macro_f1, micro_f1 = evaluate_LR_accuracy(embeddings,\n labels,\n random_state=42)\n res_lr = {\"method\": method,\n \"date\": time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\n \"graph\": data,\n \"prob\": prob,\n \"percentile\": percentile,\n \"scale\": scale,\n \"metric\": metric,\n \"dim\": dim,\n \"evaluate model\": \"LR\",\n \"accuracy\": accuracy,\n \"balanced_accuracy\": balanced_accuracy,\n \"precision\": precision,\n \"recall\": recall,\n \"macro f1\": macro_f1,\n \"micro f1\": micro_f1,\n \"time\": _time,\n \"label\": \"SIR_2\"\n }\n\n accuracy, balanced_accuracy, precision, recall, macro_f1, micro_f1 = evaluate_KNN_accuracy(embeddings, labels,\n n_neighbor=20,\n random_state=42,\n metric=\"euclidean\")\n res_knn = {\"method\": method,\n \"date\": time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\n \"graph\": data,\n \"prob\": prob,\n \"percentile\": percentile,\n \"scale\": scale,\n \"metric\": metric,\n \"dim\": dim,\n \"cnt\": cnt,\n \"evaluate model\": \"KNN\",\n \"accuracy\": accuracy,\n \"balanced_accuracy\": balanced_accuracy,\n \"precision\": precision,\n \"recall\": recall,\n \"macro f1\": macro_f1,\n \"micro f1\": micro_f1,\n \"time\": _time,\n \"label\": \"SIR_2\"\n }\n\n db.insert(res_lr, \"graph embedding\")\n db.insert(res_knn, \"graph embedding\")\n #db.insert(res_lr, \"robust\")\n #db.insert(res_knn, \"robust\")\n\n db.close()\n return True\n\n\n\ndef _robustness(data, probs=None, cnt=10, label=\"SIR\"):\n \"\"\"\n 测试struc2vec, node2vec, graphwave鲁棒性\n \"\"\"\n graph, label_dict, n_class = dataloader(data, directed=False, label=label)\n pool = mp.Pool(2)\n results = []\n scale = 0.0085\n for method in [\"HSELLE\"]:\n for i, p in enumerate(probs):\n # _worker(idx, method, prob, data, graph, label_dict, n_class, scale, cnt):\n _res = pool.apply_async(_worker, args=(i, method, p, data, graph, label_dict, n_class, scale, cnt))\n results.append(_res)\n\n pool.close()\n pool.join()\n for _res in results:\n _res.get()\n\n\ndef _worker(idx, method, prob, data, graph, label_dict, n_class, scale, cnt):\n print(\"idx = {}, prob = {}\".format(idx, prob))\n for cur_cnt in tqdm(range(cnt)):\n start = time.time()\n\n if prob == 1.0:\n _graph = nx.Graph(graph)\n else:\n _graph = random_remove_edges(nx.Graph(graph), prob=prob)\n\n if method == \"struc2vec\":\n embedding_dict = struc2vec(name=data, graph=_graph, walk_length=30, window_size=10,\n num_walks=10, stay_prob=0.5, dim=64, reused=False)\n elif method == \"node2vec\":\n embedding_dict = node2vec(name=data, graph=_graph, walk_length=30, window_size=10,\n num_walks=10, p=1, q=2, dim=64, reused=False)\n elif method == \"HSELLE\":\n # def hseLLE(name, graph, scale=10.0, method='l1', dim=16, percentile=0.0, reuse=True):\n embedding_dict = hseLLE(name=data, graph=_graph, scale=1, method=\"wasserstein\",\n dim=64, percentile=0.9, reuse=False)\n else:\n embedding_dict = graphWave(name=data, graph=_graph, scale=scale, dim=64, reused=False)\n\n _time = time.time() - start\n\n nodes = []\n labels = []\n embeddings = []\n for node, embedding in embedding_dict.items():\n nodes.append(node)\n embeddings.append(embedding)\n labels.append(label_dict.get(node, str(n_class)))\n\n accuracy, balanced_accuracy, precision, recall, macro_f1, micro_f1 = evaluate_LR_accuracy(embeddings,\n labels,\n random_state=42)\n\n fout = open(\"E:\\workspace\\py\\graph-embedding\\output\\\\robustness.txt\", mode=\"a+\", encoding=\"utf-8\")\n\n fout.write(\"method: {}, prob: {}, idx: {}, cnt: {}, time:{}\\n\".format(method, prob, idx, cur_cnt, _time))\n fout.write(\"accuracy:{}, balanced_accuracy:{}, precision:{}, recall:{}, \"\n \"macro_f1:{}, micro_f1:{}\\n\".format(accuracy, balanced_accuracy,\n precision, recall, macro_f1, micro_f1))\n fout.write(\"\\n\\n\")\n fout.write(\"--------------------------------------------------------\\n\")\n fout.close()\n\n return True\n\n\ndef _time_test(dataset=None, cnt=10):\n \"\"\"\n 在数据集上记录运行时长\n :param dataset: dataset name, str.\n :param cnt: execute cnt times, int.\n :return: the average time on the dataset, float.\n \"\"\"\n graph, _, _ = dataloader(dataset, directed=False, label=\"auto\")\n n_nodes = nx.number_of_nodes(graph)\n n_edges = nx.number_of_edges(graph)\n times = []\n for _ in range(cnt):\n start = time.time()\n hseLLE(name=dataset, graph=graph, scale=50, method='l1', dim=16, percentile=0.4, reuse=False)\n times.append(time.time() - start)\n mean_time = sum(times) / cnt\n print(\"Number of nodes: {}, number of edges: {}, run {} times, time = {}s, mean time = {}s\\n\"\n .format(n_nodes, n_edges, cnt, times, mean_time))\n return n_nodes, n_edges, mean_time\n\n\ndef scalability_test(datasets=None, cnt=10):\n \"\"\"\n 在不同规模的数据集上记录运行时长\n :param datasets: a list of dataset. [names]\n :param cnt: excute cnt times, int\n :return:\n \"\"\"\n with open(\"../../output/time_report.txt\", mode=\"w+\", encoding=\"utf-8\") as fout:\n for _, data in enumerate(datasets):\n n_nodes, n_edges, mean_time = _time_test(data, cnt)\n fout.write(\"dataset: {}, run {} times.\\n\".format(data, cnt))\n fout.write(\"Number of nodes: {}, number of edges: {}, mean time = {}s\\n\\n\".format(n_nodes, n_edges, mean_time))\n\n\ndef mkarate_wavelet():\n from utils.guass_charac_analyze import mkarate_wavelet_analyse, mkarate_wavelet_analyse_2\n data, _, _ = dataloader(\"mkarate\", directed=False)\n wave_machine = GraphWave(data)\n eigenvalues = wave_machine._e\n sMin, sMax = scale_boundary(eigenvalues[1], eigenvalues[-1])\n scale = (sMin + sMax) / 2 # 根据GraphWave论文中推荐的尺度进行设置。\n print(sMin, sMax, scale)\n scale=30\n node1, node2, node3 = '3', '38', '20'\n node2idx, idx2node = wave_machine.node2idx, wave_machine.nodes\n wavelets = wave_machine.cal_all_wavelet_coeffs(scale=scale)\n index1, index2, index3 = node2idx[node1], node2idx[node2], node2idx[node3]\n wavelet1, wavelet2, wavelet3 = wavelets[index1], wavelets[index2], wavelets[index3]\n similarity = wave_machine.calc_wavelet_similarity(wavelets, method=\"wasserstein\", hierachical=True, layers=5)\n mkarate_wavelet_analyse(scale, node1, wavelet1, node2, wavelet2, node3, wavelet3,\n similarity[index1, index2], similarity[index1, index3])\n\n\ndef visulize_via_smilarity_tsne(name, db, label_class=\"SIR\", perplexity=30, scale = 2, reused=False):\n from sklearn.manifold import TSNE\n graph, label_dict, n_class = dataloader(name, label=label_class, directed=False, similarity=False)\n wave_machine = GraphWave(graph)\n eigenvalues = wave_machine._e\n idx2node, node2idx = wave_machine.nodes, wave_machine.node2idx\n\n sMin, sMax = scale_boundary(eigenvalues[2], eigenvalues[-1])\n s = (sMin + sMax) / 2 # 根据GraphWave论文中推荐的尺度进行设置。\n print(sMin, sMax)\n scale = 0.5\n print(\"scale: \", scale)\n path = \"../../output/{}_distance_{}.csv\".format(name, scale)\n if not reused:\n coeff_mat = wave_machine.cal_all_wavelet_coeffs(scale=scale)\n print(coeff_mat[:5, :15])\n mat = wave_machine.parallel_calc_similarity(coeff_mat, layers=4, metric=\"wasserstein\",\n mode=\"distance\", save_path=path)\n else:\n mat = read_distance(path, wave_machine.n_nodes)\n\n # mkarate, layer=1, scale=0.5, p=5, random=32\n # mkarate, layer=2, scale=0.5, p=5, random=35\n # mkarate, layer=3, scale=0.5, p=5, random=25\n # mkarate, layer=4, scale=0.5, p=5, random=25\n # mkarate, layer=5, scale=0.5, p=5, random=32\n res = TSNE(n_components=2, metric=\"precomputed\", perplexity=perplexity, random_state=35).fit_transform(mat)\n tmp = {}\n for idx, node in enumerate(idx2node):\n tmp[node] = res[idx]\n save_vectors(tmp, \"../../output_SIR/HSD_{}_{}_{}_tsne.csv\".format(name, scale, perplexity))\n\n labels = []\n for idx, node in enumerate(idx2node):\n node_label = label_dict[node]\n labels.append(node_label)\n\n print(type(mat), len(mat), len(mat[0]))\n # 展示2维数据,参数tsne和perplexity没用\n\n accuracy, balanced_accuracy, precision, recall, macro_f1, micro_f1 = evaluate_KNN_accuracy(X=mat, labels=labels, metric=\"precomputed\", n_neighbor=20)\n \"\"\"\n res_knn = {\"method\": \"HSD\",\n \"date\": time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\n \"graph\": name,\n \"scale\": scale,\n \"metric\": \"wasserstein\",\n \"evaluate model\": \"KNN\",\n \"accuracy\": accuracy,\n \"balanced_accuracy\": balanced_accuracy,\n \"precision\": precision,\n \"recall\": recall,\n \"macro f1\": macro_f1,\n \"micro f1\": micro_f1,\n \"label\": \"SIR_2\"\n }\n\n if db:\n db.insert(res_knn, \"nodes classification\")\n \"\"\"\n plot_embeddings(idx2node, res, labels=labels, n_class=n_class, method=\"tsne\", perplexity=30, node_text=False)\n\n\ndef bell_scales():\n from sklearn.manifold import TSNE\n import matplotlib.pyplot as plt\n from collections import defaultdict\n import matplotlib.colors as colors\n import matplotlib.cm as cmx\n\n graph, label_dict, n_class = dataloader(\"bell\", label=\"origin\", directed=False, similarity=False)\n model = TSNE(n_components=2, random_state=42, n_iter=1000, perplexity=3, init='random')\n machine = GraphWave(graph)\n\n cm = plt.get_cmap(\"nipy_spectral\")\n cNorm = colors.Normalize(vmin=0, vmax=n_class - 1)\n scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)\n markers = ['<', '*', 'x', 'D', 'H', 'x', 'D', '>', '^', \"v\", '1', '2', '3', '4', 'X', '.']\n\n e1, eN = machine._e[1], machine._e[-1]\n sMin, sMax = scale_boundary(e1, eN)\n step = (sMax - sMin) / 4\n scales = [50.0 + step * i * 500 for i in range(16)]\n for i, scale in enumerate(scales):\n plt.subplot(4, 4, i+1)\n plt.xlabel(\"scale = {} \".format(scale))\n plt.xticks([])\n plt.yticks([])\n\n embedding_dict = machine.single_scale_embedding(scale)\n embeddings = []\n labels = []\n nodes = []\n for node, vector in embedding_dict.items():\n embeddings.append(vector)\n labels.append(label_dict[node])\n nodes.append(node)\n\n data = model.fit_transform(embeddings)\n class_dict = defaultdict(list)\n for idx, node in enumerate(nodes):\n class_dict[labels[idx]].append(idx)\n\n for _class, _indices in class_dict.items():\n _class = int(_class)\n plt.scatter(data[_indices, 0], data[_indices, 1], s=60, marker=markers[_class], c=[scalarMap.to_rgba(_class)], label=_class)\n\n for idx, (x, y) in enumerate(data):\n plt.text(x, y, nodes[idx])\n\n plt.show()\n\n\nif __name__ == '__main__':\n #start = time.time()\n #db = Database()\n\n #visulize_via_smilarity_tsne(\"across_europe_reindex\", None, label_class=\"SIR_2\", perplexity=50, reused=True)\n #mkarate_wavelet()\n #bell_scales()\n embedd(\"across_europe_reindex\", label_class=\"SIR_2\")\n #mkarate_wavelet()\n #print(\"all\", time.time() - start)\n #_time_test(\"europe\")\n #probs = [0.5, 0.55, 0.60]\n #_robustness(\"europe\", probs=probs, cnt=5, label=\"SIR_2\")\n #for scale in [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.12, 0.14, 0.16, 0.18, 0.2, 0.22, 0.24, 0.26, 0.28, 0.3, 0.4, 0.5]\n #for scale in [0.01, 0.03, 0.05, 0.07, 0.08, 0.1, 0.12, 0.14, 0.16, 0.18, 0.2, 0.22, 0.24, 0.26, 0.28, 0.3, 0.5, 0.7, 0.9, 1.0, 1.5, 2, 2.5, 3, 4, 5]:\n #robustness(\"europe\", probs=[0.6], cnt=5, metric=\"wasserstein\", label=\"SIR_2\", dim=64, scale=1, percentile=0.9)\n #scalability_test(datasets=['bell', 'mkarate.edgelist', 'subway', 'railway', 'brazil', 'europe'])\n","sub_path":"ge/example/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":23643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"482361539","text":"# coding=utf-8\n\n\"\"\"\nNEED TO MAKE SURE ZKSERVER IS RUNNING ON LOCAL MACHINE WITH DEFAULT PORT\n\"\"\"\n\nimport json\nimport unittest\n\nimport tornado.ioloop\nfrom mockito import *\nfrom tornado.http1connection import HTTP1Connection\nfrom tornado.httputil import HTTPServerRequest, HTTPHeaders\nfrom tornado.iostream import BaseIOStream\n\nimport conf.common as const\nfrom app import make_app\nfrom handler.base import BaseHandler\n\n\nclass TestBaseHandler(unittest.TestCase):\n\n def setUp(self):\n # mocks\n self.ioloop = tornado.ioloop.IOLoop.instance()\n self.stream = BaseIOStream(self.ioloop)\n self.connection = HTTP1Connection(stream=self.stream, is_client=True)\n when(self.connection).set_close_callback(any()).thenReturn(None)\n\n self.headers = HTTPHeaders()\n self.headers.add('User-Agent', 'MicroMessenger iPhone')\n\n self.request = HTTPServerRequest(\n uri='http://platform.moseeker.com/m/position/123',\n headers=self.headers,\n connection=self.connection)\n\n self.application = make_app()\n\n def tearDown(self):\n unstub()\n\n def test_mock(self):\n obj = mock()\n obj.say('Hi')\n verify(obj).say('Hi')\n verifyNoMoreInteractions(obj)\n\n def test_wechat_ios_env_info(self):\n self.handler = BaseHandler(\n self.application, self.request, event='test_event')\n self.assertTrue(self.handler.in_wechat_ios)\n self.assertTrue(self.handler.in_wechat)\n\n def test_wechat_android_env_info(self):\n self.headers = HTTPHeaders({'User-Agent': 'MicroMessenger Android'})\n self.request.headers = self.headers\n self.handler = BaseHandler(\n self.application, self.request, event='test_event')\n self.assertTrue(self.handler.in_wechat_android)\n self.assertTrue(self.handler.in_wechat)\n\n def test_outside_wechat_env_info(self):\n self.headers = HTTPHeaders({'User-Agent': 'Safari'})\n self.request.headers = self.headers\n self.handler = BaseHandler(\n self.application, self.request, event='test_event')\n self.assertFalse(self.handler.in_wechat)\n self.assertEqual(self.handler._in_wechat, const.CLIENT_NON_WECHAT)\n self.assertEqual(self.handler._client_type, const.CLIENT_TYPE_UNKNOWN)\n\n def test_json_args(self):\n self.headers.add('Content-Type', 'application/json')\n self.request.body = json.dumps({'a': 1, 'b': 2})\n self.handler = BaseHandler(\n self.application, self.request, event='test_event')\n self.assertDictEqual(self.handler.json_args, {'a': 1, 'b': 2})\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/handler/test_base_handler.py","file_name":"test_base_handler.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"554892943","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os.path\n\ndef check_args():\n if len(sys.argv) != 3:\n print('Usage: xorcrypt.py [key file] [data file]')\n sys.exit(0)\n\n args = {}\n args['key'] = sys.argv[1]\n args['data'] = sys.argv[2]\n\n if(os.path.isfile(args['key']) and os.path.isfile(args['data'])):\n key_size = os.path.getsize(args['key'])\n data_size = os.path.getsize(args['data'])\n\n if(key_size > 0 and data_size > 0):\n if(key_size >= data_size):\n return args\n else:\n print('Key size must be larger than data.')\n else:\n print('Files must be larger than 0 bytes in length.')\n else:\n print('Arguments must be valid files.')\n \n sys.exit(0)\n\ndef get_byte_offset(key_length, plaintext_length):\n return key_length / 2 - plaintext_length / 2\n\ndef encrypt(k, d):\n\n data_size = os.path.getsize(d)\n offset = get_byte_offset(os.path.getsize(k), data_size)\n key_bytes = b''\n data_bytes = b''\n\n with open(k, 'rb') as f:\n f.seek(offset, 0)\n key_bytes = f.read(data_size)\n\n with open(d, 'rb') as f:\n data_bytes = f.read()\n\n ciphered = b''\n\n for i in range(len(key_bytes)):\n ciphered += chr(ord(key_bytes[i]) ^ ord(data_bytes[i]))\n\n return ciphered\n\nif __name__ == '__main__':\n args = check_args()\n crypted = encrypt(args['key'], args['data'])\n \n with open('crypted.bin', 'wb') as f:\n f.write(crypted)\n","sub_path":"xorcrypt.py","file_name":"xorcrypt.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"312707395","text":"from django.conf.urls import patterns, url\n\nfrom EatsIndex import views\n\nurlpatterns = patterns('',\n # ex: /index/\n url(r'^$', views.index, name='index'),\n url(r'^RegistePage$', views.registe, name='registe'),\n url(r'^LoginPage/(?P\\w+)$', views.userlogin, name='userlogin'),\n url(r'^LogoutPage$', views.userlogout, name='userlogout'),\n url(r'^Lookfor$', views.lookfor, name='lookfor'),\n url(r'^Friend$', views.friends, name='friends'),\n url(r'^LikeIt/(?P\\d+)$', views.LikeIt, name='LikeIt'),\n url(r'^Search$', views.searchTitle, name='searchTitle'),\n url(r'^Friend/(?P\\d+)$', views.follow, name='follow'),\n url(r'^Details/(?P\\d+)$', views.details, name='details'),\n url(r'^Chat$', views.chatPage, name='chatPage'),\n url(r'^api/sendmsg', views.sendmsg, name='sendmsg'),\n url(r'^api/recvmsg$', views.recvmsg, name='recvmsg'),\n url(r'^api/qfriends$', views.queryFriends, name='queryFriends'),\n url(r'^api/group/create$', views.createGroup, name='createGroup'),\n url(r'^api/group/join$', views.joinGroup, name='joinGroup'),\n url(r'^test', views.test, name='test'),\n)","sub_path":"EatsIndex/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"494497470","text":"\nimport pandas as pd\nimport re\n\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom lmf.dbv2 import db_write,db_command,db_query\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException,StaleElementReferenceException\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nimport sys\nimport time\n\nimport json\nfrom zhulong.util.etl import add_info,est_meta,est_html,est_tbs\n\n\n_name_=\"ruian\"\n\n\n# __conp=[\"postgres\",\"since2015\",\"192.168.3.171\",\"hunan\",\"changsha\"]\n\n\n# url=\"https://ggzy.changsha.gov.cn/spweb/CS/TradeCenter/tradeList.do?Deal_Type=Deal_Type2\"\n# driver=webdriver.Chrome()\n# driver.minimize_window()\n# driver.get(url)\n\n\n\n\n\ndef f1(driver, num):\n locator = (By.XPATH, \"//*[@id='MoreInfoList1_DataGrid1']/tbody/tr[1]/td[2]/a\")\n val = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator)).text\n try:\n locator = (By.XPATH, \"//td[@valign='bottom']/font[3]\")\n str = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator)).text\n cnum = int(str)\n except:\n cnum = 1\n\n if num != int(cnum):\n driver.execute_script(\"javascript:__doPostBack('MoreInfoList1$Pager','{}')\".format(num))\n try:\n locator = (By.XPATH, \"//*[@id='MoreInfoList1_DataGrid1']/tbody/tr[1]/td[2]/a[string()!='%s']\" % val)\n WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))\n except:\n driver.refresh()\n locator = (By.XPATH, \"//*[@id='MoreInfoList1_DataGrid1']/tbody/tr[1]/td[2]/a[string()!='%s']\" % val)\n WebDriverWait(driver, 3).until(EC.presence_of_element_located(locator))\n\n\n page = driver.page_source\n\n soup = BeautifulSoup(page, 'lxml')\n\n table = soup.find(\"table\", id=\"MoreInfoList1_DataGrid1\")\n\n trs = table.find_all(\"tr\")\n data = []\n for tr in trs:\n a = tr.find(\"a\")\n try:\n title = a[\"title\"].strip()\n except:\n title = a.text.strip()\n try:\n link = a[\"href\"]\n except:\n continue\n td = tr.find_all(\"td\")[2].text.strip()\n\n\n link = \"http://www.raztb.com\"+link.strip()\n\n tmp = [title, td, link]\n data.append(tmp)\n\n\n df = pd.DataFrame(data)\n df['info'] = None\n return df\n\n\n\n\ndef f2(driver):\n\n locator = (By.XPATH, \"//*[@id='MoreInfoList1_DataGrid1']/tbody/tr[1]/td[2]/a\")\n WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))\n try:\n locator = (By.XPATH, \"//td[@valign='bottom']/font[2]\")\n str = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator)).text.strip()\n num = int(str)\n except:\n num = 1\n driver.quit()\n return int(num)\n\n\n\ndef f3(driver, url):\n driver.get(url)\n locator = (By.CLASS_NAME, \"currentpostionfont\")\n WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located(locator))\n before = len(driver.page_source)\n time.sleep(0.1)\n after = len(driver.page_source)\n i = 0\n while before != after:\n before = len(driver.page_source)\n time.sleep(0.1)\n after = len(driver.page_source)\n i += 1\n if i > 5: break\n\n page = driver.page_source\n\n soup = BeautifulSoup(page, 'lxml')\n\n div = soup.find('table', id=\"tblInfo\")\n # div=div.find_all('div',class_='ewb-article')[0]\n\n return div\n\n\ndata = [\n [\"gcjs_zhaobiao_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002001/002001001/MoreInfo.aspx?CategoryNum=002001001\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"gcjs_zhongbiaohx_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002001/002001002/MoreInfo.aspx?CategoryNum=002001002\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"gcjs_zhongbiao_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002001/002001003/MoreInfo.aspx?CategoryNum=002001003\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"gcjs_biangen_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002001/002001004/MoreInfo.aspx?CategoryNum=002001004\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"gcjs_zishenjieguo_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002001/002001005/MoreInfo.aspx?CategoryNum=002001005\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"zfcg_zhaobiao_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002002/002002001/MoreInfo.aspx?CategoryNum=002002001\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"zfcg_biangen_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002002/002002007/MoreInfo.aspx?CategoryNum=002002007\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"zfcg_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002002/002002002/MoreInfo.aspx?CategoryNum=002002002\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"zfcg_zhongbiao_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002002/002002004/MoreInfo.aspx?CategoryNum=002002004\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"zfcg_yucai_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002002/002002003/MoreInfo.aspx?CategoryNum=002002003\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"],f1,f2],\n\n [\"qita_zhaobiao_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002007/002007001/MoreInfo.aspx?CategoryNum=002007001\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qita_zhongbiaohx_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002007/002007002/MoreInfo.aspx?CategoryNum=002007002\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qita_zhongbiao_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002007/002007003/MoreInfo.aspx?CategoryNum=002007003\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qita_biangen_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002007/002007004/MoreInfo.aspx?CategoryNum=002007004\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n\n [\"qsydw_zhaobiao_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002008/002008001/MoreInfo.aspx?CategoryNum=002008001\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qsydw_biangen_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002008/002008002/MoreInfo.aspx?CategoryNum=002008002\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qsydw_zhongbiaohx_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002008/002008003/MoreInfo.aspx?CategoryNum=002008003\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qsydw_zhongbiao_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002008/002008004/MoreInfo.aspx?CategoryNum=002008004\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n [\"qsydw_yucai_gg\",\n \"http://www.raztb.com/TPFront/jyxx/002008/002008005/MoreInfo.aspx?CategoryNum=002008005\",\n [\"name\", \"ggstart_time\", \"href\", \"info\"], f1, f2],\n\n\n\n]\n\n\ndef work(conp,**args):\n est_meta(conp,data=data,diqu=\"浙江省瑞安市\",**args)\n est_html(conp,f=f3,**args)\n\n\nif __name__=='__main__':\n work(conp=[\"postgres\",\"since2015\",\"192.168.3.171\",\"zhejiang\",\"ruian\"])\n\n\n # # #\n # driver=webdriver.Chrome()\n # url=\"http://www.raztb.com/TPFront/jyxx/002001/002001001/MoreInfo.aspx?CategoryNum=002001001\"\n # driver.get(url)\n # df = f2(driver)\n # print(df)\n #\n # for i in range(1, 6):\n # df=f1(driver, i)\n # print(df)\n","sub_path":"zl_spider/zhejiang/ruian.py","file_name":"ruian.py","file_ext":"py","file_size_in_byte":7442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"413047267","text":"import access_database.sqlite_wrapper as sqlite_wrapper\n\nquery_select = \"\"\"\n SELECT\n Id,\n Name,\n ProcessType,\n ImagePath,\n InputLimit,\n OutputLimit,\n Image\n FROM TB_PROCESS\n \"\"\"\n\n\ndef get_processes(conn):\n processes = []\n rows = sqlite_wrapper.run_query(conn, query_select)\n for row in rows:\n processes.append(Process(row))\n return processes\n\ndef get_processes_by_type(type_id, conn):\n processes = []\n query_where = \"\"\"\n WHERE ProcessType =?\n \"\"\"\n query = query_select + query_where\n param = [type_id]\n rows = sqlite_wrapper.run_query(conn, query, param)\n for row in rows:\n processes.append(Process(row))\n return processes\n\ndef get_process_by_id(id, conn):\n query_where = \"\"\"\n WHERE Id =?\n \"\"\"\n query = query_select + query_where\n param = [id]\n rows = sqlite_wrapper.run_query(conn, query, param)\n if(len(rows) == 0):\n return '-1'\n for row in rows:\n pass\n ret_process = Process(row)\n return ret_process\n\ndef get_process_by_id_old(id, conn):\n processes = []\n query_where = \"\"\"\n WHERE Id =?\n \"\"\"\n query = query_select + query_where\n param = [id]\n rows = sqlite_wrapper.run_query(conn, query, param)\n for row in rows:\n processes.append(Process(row))\n return processes\n\nclass Process:\n def __init__(self, row):\n self.id = row[0]\n self.name = row[1]\n self.processTypeId = row[2]\n self.imagePath = row[3]\n self.inputLimit = row[4]\n self.outputLimit = row[5]\n self.models = []\n # self.imageHex = row[4].hex()\n","sub_path":"classes/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"570576595","text":"import unittest\n\nfrom collections import defaultdict\n\nfrom src.Documents import SentenceDocument\nfrom src.Tokenizers.BigramTokenizer import BigramTokenizer\n\n\nclass BigramTokenizerTests(unittest.TestCase):\n\n def setUp(self):\n self.tokenizer = BigramTokenizer()\n\n def test_tokenize_content(self):\n tokens = self.tokenizer(\"This is a test.\")\n expected_tokens = [ (\"this\", \"is\"), (\"is\", \"a\"), (\"a\", \"test\"), (\"test\", \".\") ]\n self.assertEqual(tokens, expected_tokens)\n\n def test_tokenize(self):\n document = SentenceDocument(\"This is a test.\")\n tokens = self.tokenizer.tokenize(document)\n expected_tokens = defaultdict(float,{\n (\"test\", \".\"): 1.0,\n (\"this\", \"is\"): 1.0,\n (\"is\", \"a\"): 1.0,\n (\"a\", \"test\"): 1.0\n })\n self.assertEqual(tokens, expected_tokens)\n","sub_path":"tests/BigramTokenizerTests.py","file_name":"BigramTokenizerTests.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"409449399","text":"\"\"\"\n缺陷检测QT软件--检测记录对话框类\nauthor: 王建坤\ndate: 2018-10-16\n\"\"\"\nfrom PyQt5.QtWidgets import QDialog, QTableWidgetItem, QHeaderView, QFileDialog\nfrom PyQt5.uic import loadUi\nfrom PyQt5.QtCore import Qt\nimport pandas as pd\n\n\nclass DetectLog(QDialog):\n \"\"\"\n 检测记录类\n \"\"\"\n def __init__(self, log_list, *args):\n super(DetectLog, self).__init__(*args)\n loadUi('ui_detect_log.ui', self)\n\n self.defect_list = log_list\n self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)\n self.table_log.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n self.pb_clear.clicked.connect(self.slot_clear)\n self.pb_save.clicked.connect(self.slot_save)\n\n rows = len(self.defect_list)\n self.table_log.setRowCount(rows)\n for i in range(rows):\n self.table_log.setItem(i, 0, QTableWidgetItem(self.defect_list[i][0]))\n self.table_log.setItem(i, 1, QTableWidgetItem(self.defect_list[i][1]))\n self.table_log.setItem(i, 2, QTableWidgetItem(self.defect_list[i][2]))\n\n def insert_row(self):\n \"\"\"\n 插入一行\n :return:\n \"\"\"\n row_count = self.table_log.rowCount()\n self.table_log.insertRow(row_count)\n\n def slot_clear(self):\n \"\"\"\n 清空表格\n :return:\n \"\"\"\n self.table_log.clearContents()\n self.defect_list = []\n\n def slot_save(self):\n \"\"\"\n 保存检测记录的表格\n :return:\n \"\"\"\n file_name = QFileDialog.getSaveFileName(self, 'save file', 'log', '.csv')\n detect_csv = pd.DataFrame({'图片路径': [x[0] for x in self.defect_list],\n '检测结果': [x[1] for x in self.defect_list],\n '检测时间': [x[2] for x in self.defect_list]})\n if file_name[0] != '':\n detect_csv.to_csv(file_name[0])\n\n\nclass DefectLog(QDialog):\n \"\"\"\n 缺陷记录类\n \"\"\"\n def __init__(self, log_list):\n super(DefectLog, self).__init__()\n loadUi('ui_defect_log.ui', self)\n\n self.detect_list = log_list\n self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)\n self.table_defect.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n self.pb_save.clicked.connect(self.slot_save)\n\n # 找出缺陷的记录\n self.defect_list = []\n for sample in self.detect_list:\n if sample[1] == '-1':\n continue\n self.defect_list.append(sample)\n\n # 缺陷记录表\n defect_rows = len(self.defect_list)\n self.table_defect.setRowCount(defect_rows)\n for i in range(defect_rows):\n self.table_defect.setItem(i, 0, QTableWidgetItem(self.defect_list[i][0]))\n self.table_defect.setItem(i, 1, QTableWidgetItem(self.defect_list[i][1]))\n self.table_defect.setItem(i, 2, QTableWidgetItem(self.defect_list[i][2]))\n\n # 缺陷统计表\n self.class_num_list = [0] * 12\n for j in self.defect_list:\n if -1 < int(j[1]) < 12:\n self.class_num_list[int(j[1])] += 1\n for k in range(len(self.class_num_list)):\n self.table_statistics.setItem(k, 1, QTableWidgetItem(str(self.class_num_list[k])))\n if sum(self.class_num_list):\n self.table_statistics.setItem(k, 2, QTableWidgetItem('%.2f' %\n (self.class_num_list[k]/sum(self.class_num_list))))\n\n def slot_save(self):\n \"\"\"\n 保存缺陷记录的表格\n :return:\n \"\"\"\n file_name = QFileDialog.getSaveFileName(self, 'save file', 'log', '.csv')\n if file_name[0] == '':\n return\n if self.tab_table.currentIndex() == 0:\n defect_csv = pd.DataFrame({'图片路径': [x[0] for x in self.defect_list],\n '缺陷类别': [x[1] for x in self.defect_list],\n '检测时间': [x[2] for x in self.defect_list]})\n defect_csv.to_csv(file_name[0])\n else:\n statistics_csv = pd.DataFrame({self.table_statistics.horizontalHeaderItem(0).text(): [i for i in range(12)],\n self.table_statistics.horizontalHeaderItem(1).text(): self.class_num_list,\n self.table_statistics.horizontalHeaderItem(2).text():\n [self.table_statistics.itemAt(i, 3).text() for i in range(12)]})\n statistics_csv.to_csv(file_name[0], index=False)\n","sub_path":"qt/LogDialog.py","file_name":"LogDialog.py","file_ext":"py","file_size_in_byte":4720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"562594131","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Example',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('create_time', models.DateTimeField(verbose_name='创建时间', auto_now_add=True)),\n ('update_time', models.DateTimeField(verbose_name='更新时间', auto_now=True)),\n ('is_delete', models.BooleanField(verbose_name='删除标记', default=False)),\n ('name', models.CharField(verbose_name='案例名称', max_length=20)),\n ('cover_image', models.ImageField(verbose_name='案例封面图片', upload_to='example')),\n ('prov', models.CharField(verbose_name='省', max_length=20)),\n ('city', models.CharField(verbose_name='城市', max_length=20)),\n ('comment', models.CharField(verbose_name='新人评论', max_length=256, default='')),\n ],\n options={\n 'verbose_name': '案例',\n 'verbose_name_plural': '案例',\n 'db_table': 'df_example',\n },\n ),\n migrations.CreateModel(\n name='ExampleImage',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('create_time', models.DateTimeField(verbose_name='创建时间', auto_now_add=True)),\n ('update_time', models.DateTimeField(verbose_name='更新时间', auto_now=True)),\n ('is_delete', models.BooleanField(verbose_name='删除标记', default=False)),\n ('image', models.ImageField(verbose_name='图片路径', upload_to='example')),\n ('example', models.ForeignKey(verbose_name='案例', to='example.Example')),\n ],\n options={\n 'verbose_name': '案例图片',\n 'verbose_name_plural': '案例图片',\n 'db_table': 'df_example_image',\n },\n ),\n migrations.CreateModel(\n name='ExampleType',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('create_time', models.DateTimeField(verbose_name='创建时间', auto_now_add=True)),\n ('update_time', models.DateTimeField(verbose_name='更新时间', auto_now=True)),\n ('is_delete', models.BooleanField(verbose_name='删除标记', default=False)),\n ('name', models.CharField(verbose_name='种类名称', max_length=20)),\n ],\n options={\n 'verbose_name': '案例种类',\n 'verbose_name_plural': '案例种类',\n 'db_table': 'df_example_type',\n },\n ),\n migrations.AddField(\n model_name='example',\n name='type',\n field=models.ForeignKey(verbose_name='案例种类', to='example.ExampleType'),\n ),\n ]\n","sub_path":"apps/example/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"624267734","text":"\"\"\"\nHydrogenGroup spider created on the top of ATSSpider\n\nscrapy crawl hydrogengroup -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.hydrogengroup.com/en/jobs\"\n\nSample URL:\n http://www.hydrogengroup.com/en/jobs\n\"\"\"\n\nfrom json import loads\nfrom scrapy.http import Request\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import ConvertDateString, NormalizedJoin, Prefix\n\n\nclass HydrogenGroup(ATSSpider):\n\n name = 'hydrogengroup'\n disable_default_field_extractors = True\n domain = ''\n\n def __init__(self, *args, **kwargs):\n super(HydrogenGroup, self).__init__(*args, **kwargs)\n if 'url' in kwargs:\n # needed for construct job url\n self.domain = kwargs['url']\n\n def start_requests(self):\n \"\"\"\n Use JSON api url to extract all data\n \"\"\"\n yield Request(\n callback=self.parse_job_callback(),\n url='http://api.hydrogengroup.com/Jobs.json'\n )\n\n def parse_job(self, response):\n \"\"\"\n Extract all required information.\n \"\"\"\n jsonResponse = loads(response.body)\n if jsonResponse:\n for item in jsonResponse:\n loader = BrightcorpItemLoader(selector=item)\n job_id = item.get('id')\n if job_id:\n url = '%(url)s#/details/%(id)s/' % {\n 'id': job_id,\n 'url': self.domain\n }\n loader.add_value(\n 'title', item.get('job_title')\n )\n loader.add_value(\n 'location',\n [\n item.get('location_city'),\n item.get('location_county'),\n item.get('location_country')\n ],\n NormalizedJoin(', ')\n )\n loader.add_value(\n 'date',\n item.get('created'),\n ConvertDateString('%Y-%m-%d %H:%M:%S')\n )\n loader.add_value(\n 'referencenumber',\n item.get('job_reference'),\n Prefix('%s-' % self.name)\n )\n loader.add_value('url', url)\n loader.add_value(\n 'description', item.get('job_description')\n )\n loader.add_value(\n 'jobtype', item.get('job_type')\n )\n loader.add_value('apply_url', url)\n loader.add_value(\n 'jobcategory', item.get('job_practice')\n )\n loader.add_value(\n 'salaryCurrency', item.get('salary_currency')\n )\n loader.add_value(\n 'baseSalary', item.get('salary_text')\n )\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/hydrogengroup.py","file_name":"hydrogengroup.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"567855600","text":"# -*- coding: utf-8 -*-\n\"\"\"This file is a BioJob spider created on top of the ATSSpider\nscrapy crawl biojob -a url=\"http://www.biojob.co.kr/erList/employ_all.html?cpage1=0&cpage1=1\" -a mining_job_id=999 -a iteration=1 -a extract=1\nsample url:\n http://www.biojob.co.kr/erList/employ_all.html?cpage1=0&cpage1=1\n\"\"\"\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, HtmlFormatter, ConvertDateString,\\\n NormalizedJoin\n\n\nclass BioJob(ATSSpider):\n\n name = \"biojob\"\n ref_re = compile(\"no=(\\d+)|idx=(\\d+)\")\n page_number_re = compile(\".*=(\\d+)\")\n page_visited = ['1']\n download_delay = 2\n allowed_domain_bynetloc = True\n\n def parse(self, response):\n sel = Selector(response)\n jobs = sel.xpath(\n \"//tr[td/font[contains(text(),'%s')]]/following-sibling::tr\"\n % unicode(\"채용공고제목\", 'utf-8')\n )\n for job in jobs:\n job_link = job.xpath(\"./td[3]/a/@href\").extract()\n if job_link:\n job_url = urljoin(response.url, job_link[0])\n meta = {\n 'company': job.xpath(\"./td[2]/text()\").extract(),\n 'expiry': job.xpath(\"./td[7]//text()\").extract()\n }\n yield Request(\n job_url, meta=meta, callback=self.parse_job_callback()\n )\n\n page_links = sel.xpath(\n \"//td[a[contains(text(),'%s') or contains(text(),'%s')]]/a/@href\"\n % (unicode(\"이전\", 'utf-8'), unicode(\"다음\", 'utf-8'))\n ).extract()\n for pl in page_links:\n pg_res = self.page_number_re.search(pl)\n if pg_res:\n pgno = pg_res.group(1)\n if pgno not in self.page_visited:\n self.page_visited.append(pgno)\n yield Request(\n url=urljoin(response.url, pl), callback=self.parse\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('url', response.url)\n loader.add_value('company', response.meta['company'])\n loader.add_xpath(\n 'title',\n [\n \"//span[@id='printArea']/table/tr[1]/td/table//b/text()\",\n \"//h3[@class='job-title']/text()\",\n ],\n NormalizedJoin(\" \")\n )\n loader.add_value(\n 'expiration_date', response.meta['expiry'],\n ConvertDateString(\"%Y-%m-%d\")\n )\n loader.add_xpath(\n 'description',\n \"//table[tbody/tr/td/text()='[%s]']|//table[@id='tblContent']|//div[@class='recruit_summary']\" % unicode(\"모집요강\", 'utf-8'),\n HtmlFormatter()\n )\n loader.add_value(\n 'referencenumber', response.url, Prefix(\"%s-\" % self.name),\n re=self.ref_re\n )\n loader.add_xpath(\n 'location',\n [\n \"//td[b[contains(text(),'%s')]]/following-sibling::td/text()\"\n % unicode(\"근무지역\", 'utf-8'),\n \"//th[contains(text(),'%s')]/following-sibling::td/span/text()\"\n % unicode(\"지역\", 'utf-8'),\n \"//td[b/text()='%s']/following-sibling::td/text()\"\n % unicode(\"회사주소\", 'utf-8'),\n ]\n )\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/biojob.py","file_name":"biojob.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"37057595","text":"from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\nfrom app.db.init_db import init_db\nfrom app.db.session import SessionLocal\n\nfrom app.api.api_v1.api import api_router\nfrom app.config import settings\n\ndef init() -> None:\n db = SessionLocal()\n init_db(db)\n\ninit()\n\napp = FastAPI(\n title=settings.PROJECT_NAME,\n description=\"This is the API for the Smartbin App\",\n version=\"0.1.0\"\n)\n\norigins = settings.BACKEND_CORS_ORIGINS\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\napp.include_router(api_router, prefix=settings.API_V1_STR)","sub_path":"backend/src/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"581682027","text":"import json\n\n\ndef load_data(filepath):\n with open(filepath) as file:\n data = json.loads(file.read())\n return data\n\n\ndef get_biggest_bar(bar_data):\n biggest_bar = {\"Cells\": {\"SeatsCount\": float(\"-inf\")}}\n for bar in bar_data:\n if biggest_bar[\"Cells\"][\"SeatsCount\"] < bar[\"Cells\"][\"SeatsCount\"]:\n biggest_bar = bar\n return biggest_bar\n\n\ndef get_smallest_bar(bar_data):\n smallest_bar = {\"Cells\": {\"SeatsCount\": float(\"inf\")}}\n for bar in bar_data:\n if smallest_bar[\"Cells\"][\"SeatsCount\"] > bar[\"Cells\"][\"SeatsCount\"]:\n smallest_bar = bar\n return smallest_bar\n\n\ndef get_closest_bar(bar_data, longitude, latitude):\n _distance = float(\"inf\")\n longitude = float(longitude)\n latitude = float(latitude)\n closest_bar = {}\n for bar in bar_data:\n bar_geo = bar[\"Cells\"][\"geoData\"][\"coordinates\"]\n bar_distance = distance([longitude, latitude], bar_geo)\n if _distance > bar_distance:\n _distance = bar_distance\n closest_bar = bar\n closest_bar[\"Cells\"][\"Distance\"] = _distance\n return closest_bar\n\n\ndef distance(point_1, point_2):\n return ((point_1[0]-point_2[0])**2 + (point_1[1]-point_2[1])**2)**0.5\n\n\nif __name__ == '__main__':\n bar_data = load_data(input(\"Введите путь к JSON файлу: \"))\n print()\n biggest_bar = get_biggest_bar(bar_data)\n print(\"Самый большой бар: {0}\\n\"\n \"Количество мест: {1}\\n\"\n \"Адрес: {2}\\n\".format(\n biggest_bar[\"Cells\"][\"Name\"],\n biggest_bar[\"Cells\"][\"SeatsCount\"],\n biggest_bar[\"Cells\"][\"Address\"]))\n smallest_bar = get_smallest_bar(bar_data)\n print(\"Самый маленький бар: {0}\\n\"\n \"Количество мест: {1}\\n\"\n \"Адрес: {2}\\n\".format(\n smallest_bar[\"Cells\"][\"Name\"],\n smallest_bar[\"Cells\"][\"SeatsCount\"],\n smallest_bar[\"Cells\"][\"Address\"]))\n lon, lat = input(\"Введите долготу и широту через пробел: \").split()[:2]\n closest_bar = get_closest_bar(bar_data, lon, lat)\n print(\"Самый близкий бар: {0}\\n\"\n \"Количество мест: {1}\\n\"\n \"Адрес: {2}\\n\"\n \"Расстояние: {3}\\n\".format(\n closest_bar[\"Cells\"][\"Name\"],\n closest_bar[\"Cells\"][\"SeatsCount\"],\n closest_bar[\"Cells\"][\"Address\"],\n closest_bar[\"Cells\"][\"Distance\"]))\n\n","sub_path":"bars.py","file_name":"bars.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"36576670","text":"from flask import render_template, url_for, jsonify, abort, redirect\n\nfrom .app import app\nfrom .models import db, Question\n\n@app.route('/favicon.ico')\ndef favicon():\n return redirect(url_for('static', filename='favicon.ico'))\n\n@app.route('/')\ndef home():\n return render_template('home.html')\n\n\ndef json_question(question):\n return {\n 'href': url_for('question', id=str(question.id)),\n 'text': question.text,\n 'options': [\n {'text': option.text, 'correct': option.correct}\n for option in question.options],\n }\n\n\ndef siren_question(question, rel=None):\n siren_question = {\n 'class': ['question'],\n 'properties': json_question(question),\n }\n if rel is not None:\n siren_question['rel'] = rel\n return siren_question\n\n\n@app.route('/question')\ndef question_list():\n questions = db.session.query(Question).all()\n\n siren_question_list = {\n 'class': ['question_list'],\n 'entities': [\n siren_question(question, rel='question')\n for question in questions]\n }\n\n return jsonify(siren_question_list)\n\n\n@app.route('/question/')\ndef question(id):\n question = db.session.query(Question).filter(Question.id == id).first()\n if question is None:\n abort(404)\n\n return jsonify(siren_question(question))\n","sub_path":"josiah/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"332614289","text":"'''\r\nAbbiamo immagini in formato png ottenute inserendo su di uno sfondo monocolore rettangoli \r\ndi vari colori i cui assi sono sempre parallei agli assi dell'immagine.\r\n\r\nVedi ad esempio l'immagine Img1.png\r\n\r\nPer caricare e salvare immagini PNG usate le funzioni load e save che abbiamo preparato nel modulo immagini.py .\r\n\r\nScrivere una funzione quadrato(filename, C) che prende in input:\r\n- il percorso di un file (filename) che contine un immagine in formato png della tipologia appena descritta.\r\n- una tupla C che rappresenta un colore in formato RGB (3 valori interi tra 0 e 255 compresi)\r\n\r\nLa funzione deve restituire nell'ordine:\r\n- la lunghezza del lato del quadrato pieno di dimensione massima e colore C interamente visibile nell'immagine. \r\n- le coordinate (x,y) del pixel dell'immagine che corrisponde alla posizione \r\nall'interno dell'immagine del punto in alto a sinistra del quadrato. \r\n\r\nIn caso ci siano più quadrati di dimensione massima, va considerato quello il cui punto \r\nin alto a sinistra occupa la riga minima (e a parita' di riga la colonna minima) all'interno dell' immagine. \r\n\r\nSi può assumere che nell'immagine e' sempre presente almeno un pixel del colore cercato.\r\n\r\nPer gli esempi vedere il file grade01.txt\r\n\r\nATTENZIONE: Il timeout è impostato a 10*N secondi (con N numero di test del grader).\r\n'''\r\n\r\nimport png\r\nfrom immagini import *\r\nfrom IPython.display import Image\r\n\r\ndef righe(img) : return len(img)\r\n\r\ndef colonne(img) : return len(img[0])\r\n\r\ndef create(w,h,c=(0,0,0)):\r\n img = []\r\n for _ in range(h):#scala il primo\r\n riga = [] #crea il cotenitore della prima riga\r\n for _ in range(w):#scorre tutta la riga fino alla larghezza indicata\r\n riga+=[c] #riempie i pixel della riga\r\n img+=[riga] #salva la riga nel contenitore finale che salverà ogni riga\r\n return img\r\n\r\ndef load(filename):\r\n with open(filename, mode='rb') as f:\r\n reader = png.Reader(file=f)\r\n w, h, png_img, _ = reader.asRGB8()\r\n img = []\r\n for line in png_img:\r\n l = []\r\n for i in range(0, len(line), 3):\r\n l+=[(line[i], line[i+1], line[i+2])]\r\n img+=[l]\r\n return img\r\n\r\ndef coso3(cane,c):\r\n xy=[]\r\n for x in range(len(cane)):\r\n boz=[]\r\n for y in range(len(cane[x])):\r\n if(cane[x][y] == c):\r\n boz+=[x,y]\r\n xy=[boz]\r\n print(boz)\r\n return xy\r\n\r\n\r\ndef coso(cane,c):\r\n xy=[]\r\n for x in range(len(cane)):\r\n for y in range(len(cane[x])):\r\n if(cane[x][y])==c :\r\n xy+=[x,y]\r\n return xy\r\ndef coso2(cane,c,xy):\r\n #print(xy[1])\r\n \r\n for y in range(xy[1],len(cane[xy[0]])):\r\n if(cane[xy[0]][y])!=c :\r\n return [xy[0],y-1]\r\n \r\ndef ppp(cane,c,qt):\r\n for x in range(len(cane)):\r\n for y in range(len(cane[x])):\r\n #print(qt)\r\n #print(cane[x][y])\r\n if cane[x][y] == c and [x,y] not in qt :\r\n #print('ciao')\r\n return [x,y]\r\n #if cane[x][y] == cane[-1][-1]:\r\n #return 0\r\ndef ddd(cane,c,xy):\r\n for x in range(xy[0],len(cane)):\r\n #print(x)\r\n for y in range(xy[1],len(cane[x])):\r\n #print([cane[x][y]])\r\n #print(xy[1])\r\n #print('\\n')\r\n if(cane[x][y]!=c):\r\n \r\n return [xy[0],y-1]\r\ndef dudu(cane,c,xy,sup):\r\n \r\n for x in range(xy[0],sup):\r\n #print(x)\r\n #print(sup)\r\n \r\n #print([cane[x][y]])\r\n #print(y)\r\n if(cane[x][xy[1]]!=c):\r\n return [x-1,xy[1]]\r\ndef dul(cane,c,xy,sup):\r\n \r\n for x in range(xy[0],xy[0]+sup):\r\n #print(x)\r\n #print(sup)\r\n #print('ciao')\r\n #print([cane[x][y]])\r\n #print(y)\r\n #print(x)\r\n #print(sup-1)\r\n if(cane[x][xy[1]]==c and x == xy[0]+sup-1):\r\n return [x,xy[1]]\r\n\r\ndef pull(cane,c,xy,sup): \r\n #for x in range(xy[0],len(cane)):\r\n #print(xy)\r\n for y in range(xy[1],sup+xy[1]):\r\n #print([cane[x][y]])\r\n #print(xy[1]+sup)\r\n #print(cane[39][32])\r\n # print(sup+xy[1])\r\n #print('\\n')# and x == xy[0]+sup-1\r\n #print(cane[x][50])\r\n \r\n if( y == xy[1]+sup-1 and cane[xy[0]][y] == c):\r\n #print('ciao')\r\n #print(xy[0])\r\n #print(xy)\r\n return [xy[0],y]\r\n \r\n\r\n \r\n\r\ndef riempiDu(xySH,xyDH,xySL,xyDL):\r\n goku=[]\r\n goku=[[xySH]]\r\n #print(xyDL[1])\r\n #print(goku[0])\r\n for x in range(xySH[1]+1,xyDH[1]):\r\n #print(x)\r\n goku[0]+=[[xySH[0],x]]\r\n goku[0]+=[xyDH]\r\n\r\n for z in range(xySH[0]+1,xySL[0]+1):\r\n #print(z)\r\n goku[0]+=[[z,xySH[1]]]\r\n for y in range(xySH[1]+1,xyDH[1]):\r\n \r\n goku[0]+=[[z,y]]\r\n #print(xyDL[1])\r\n goku[0]+=[[z,xyDL[1]]]\r\n #gocool+=[goku]\r\n #goku=[]\r\n #print('ciao')\r\n #print(goku)\r\n #print(gocool)\r\n \r\n #print(len(goku[0]))\r\n return goku\r\ndef trovaq(cane,c,qt):\r\n xy=[]\r\n xy2=[]\r\n xy3=[]\r\n xy4=[]\r\n if ppp(cane,c,qt) is not None:\r\n xy=ppp(cane,c,qt)\r\n xy2=ddd(cane,c,xy)\r\n xy3=dudu(cane,c,xy,len(cane))\r\n xy4=ddd(cane,c,xy3)\r\n \r\n #print(xy4)\r\n #print(xy3)\r\n #print(xy2)\r\n #print(xy)\r\n return [[xy,xy2,xy3,xy4]]\r\n \r\ndef quadrato(filename,c):\r\n '''Implementare qui la funzione'''\r\n cane=load(filename)\r\n#print(cane[118][187])\r\n d={}\r\n xy=[]\r\n box1=[]\r\n box=[]\r\n if trovaq(cane,c,box) is not None:\r\n \r\n xy+=trovaq(cane,c,box)\r\n #print(xy)\r\n sup=xy[0][1][1]-xy[0][0][1]+1\r\n left=xy[0][2][0]-xy[0][0][0]+1\r\n right=xy[0][3][0]-xy[0][1][0]+1\r\n if(sup <= right and sup <=left):\r\n xy[0][2]=dul(cane,c,xy[0][0],sup)\r\n xy[0][3]=ddd(cane,c,xy[0][2])\r\n if sup not in d:\r\n d[sup]=xy[0][0]\r\n box1=riempiDu(xy[0][0],xy[0][1],xy[0][2],xy[0][3])\r\n box=box1[0][:]\r\n else:\r\n xy=ppp(cane,c,[])\r\n d[1]=xy \r\n x=1\r\n for x in range(1,15):\r\n if trovaq(cane,c,box) is not None:\r\n xy+=trovaq(cane,c,box)\r\n sup=xy[x][1][1]-xy[x][0][1]+1\r\n left=xy[x][2][0]-xy[x][0][0]+1\r\n right=xy[x][3][0]-xy[x][1][0]+1\r\n bot=xy[x][3][1]-xy[x][2][1]+1\r\n\r\n if(sup <= right and sup <=left and sup <= bot):\r\n xy[x][2]=dul(cane,c,xy[x][0],sup)\r\n xy[x][3]=ddd(cane,c,xy[x][2])\r\n if sup not in d:\r\n d[sup]=xy[x][0]\r\n elif(bot <= right and bot <=left and bot <= sup):\r\n #print(xy[x][0])\r\n #xy[x][1]=dul(cane,c,xy[x][0],bot)\r\n #xy[x][3]=ddd(cane,c,xy[x][2])\r\n xy[x][1]=pull(cane,c,xy[x][0],bot)\r\n #print(xy[x][2])\r\n xy[x][2]=dul(cane,c,xy[x][0],bot)\r\n xy[x][3]=ddd(cane,c,xy[x][2])\r\n xy[x][3]=pull(cane,c,xy[x][2],bot)\r\n if bot not in d:\r\n d[bot]=xy[x][0]\r\n elif right < sup and right <= left and right <= bot:\r\n\r\n #print(right)\r\n #print(sup)\r\n xy[x][1]=pull(cane,c,xy[x][0],right)\r\n #print(xy[x][2])\r\n xy[x][3]=pull(cane,c,xy[x][2],right)#devo creare un simile per i lati\r\n #print(xy[x][3])\r\n if right not in d:\r\n d[right]=xy[x][0]\r\n box1=riempiDu(xy[x][0],xy[x][1],xy[x][2],xy[x][3])\r\n box+=box1[0][:] #non funziona\r\n #print(box)\r\n #print(d)\r\n #print(xy)\r\n #print(box)\r\n #d[sup]=xy[x][0]\r\n #box+=riempiDu(xy[x][0],xy[x][1],xy[x][2],xy[x][3])\r\n #print(box)\r\n #print(d)\r\n g=sorted(d,reverse=True)\r\n g=g[0]\r\n #print(g)\r\n #print(cane[50][99])\r\n return (g,(d[g][1],d[g][0]))\r\n \r\n#quadrato('Ist3.png',(255,0,0))\r\n","sub_path":"students/1789178/homework03/program01.py","file_name":"program01.py","file_ext":"py","file_size_in_byte":8104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"636531320","text":"import aiohttp, discord, json, random\nimport urllib.parse\n\nfrom bs4 import BeautifulSoup\n\nclass Google:\n\n SearchQueryUrl = \"https://google.com/search\"\n UserAgent = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:65.0) Gecko/20100101 Firefox/65.0\"\n IconUrl = \"https://www.google.com/favicon.ico\"\n ActivationPhrase = \"ok google\"\n IsSafeSearch = True\n\n def __init__(self, bot):\n self.bot = bot\n\n self.sub_commands = {\n \"images\": self.ok_google_images\n }\n\n async def on_ready(self):\n self.GoogleSession = aiohttp.ClientSession(headers={\n \"User-Agent\": Google.UserAgent\n })\n\n async def search_google(self, search_query, **kwargs):\n kwargs[\"q\"] = search_query\n build_http_query = Google.SearchQueryUrl + \"?\" + urllib.parse.urlencode(kwargs)\n resp = await self.GoogleSession.get(build_http_query)\n data = await resp.read()\n return build_http_query, data\n\n def parse_google_data(self, search_query, build_http_query, data):\n soup = BeautifulSoup(data, features=\"lxml\")\n results = soup.findAll(\"div\", {\"class\": \"r\"})\n embed = discord.Embed(title=\"Google Search\",\n color=discord.Color.teal())\n embed.set_author(name=\"Google\", url=build_http_query, icon_url=Google.IconUrl)\n embed.description = \"Here is what I found:\\n\" if results else \"Your search yielded no results.\"\n\n try:\n additional_wrapper = soup.find(\"div\", {\"class\": \"kp-header\"})\n additional_info = additional_wrapper.find(\"div\", {\"role\": \"heading\"})\n additional_info = additional_info.findAll(text=True)[0]\n embed.description += \"\\n**{}**\\n\\n\".format(additional_info)\n\n try:\n for div in additional_wrapper.findAll(\"div\"):\n if div.has_attr(\"data-lpage\"):\n image_data = urllib.parse.parse_qs(div[\"data-lpage\"])\n embed.set_thumbnail(url=image_data[\"/imgres?imgurl\"][0])\n break\n except AttributeError:\n print(\"Unable to collect thumbnail for search term '{}'\".format(search_query))\n except AttributeError:\n print(\"Unable to collect any additional information for search term '{}'\".format(search_query))\n\n for key, result in enumerate(results):\n result_url = result.find(\"a\")[\"href\"]\n embed.description += \"**{}** - [{}]({})\\n\".format(\n key + 1, result.find(\"h3\").decode_contents(), result_url)\n\n return embed\n\n async def ok_google(self, search_query):\n build_http_query, data = await self.search_google(search_query, safe=\"active\" if Google.IsSafeSearch else \"false\")\n return await self.bot.loop.run_in_executor(None, self.parse_google_data, search_query, build_http_query, data)\n\n def parse_image_data(self, data):\n soup = BeautifulSoup(data, features=\"lxml\")\n results = soup.findAll(\"div\", {\"class\": \"rg_meta notranslate\"})\n\n embed = discord.Embed(title=\"Google Images\",\n color=discord.Color.teal())\n\n if results:\n raw_image_meta = random.choice(results)\n image_meta = json.loads(raw_image_meta.decode_contents())\n image_url = image_meta[\"ou\"]\n embed.set_image(url=image_url)\n else:\n embed.description = \"Your search yielded no results.\"\n\n return embed\n\n async def ok_google_images(self, search_query):\n build_http_query, data = await self.search_google(search_query, tbm=\"isch\", safe=\"active\" if Google.IsSafeSearch else \"false\")\n embed = await self.bot.loop.run_in_executor(None, self.parse_image_data, data)\n\n embed.set_author(name=\"Google\", url=build_http_query, icon_url=Google.IconUrl)\n return embed\n\n async def on_message(self, message):\n for command, method in self.sub_commands.items():\n full_command = Google.ActivationPhrase + \" \" + command\n if message.content[:len(full_command)].lower() == full_command.lower():\n await message.channel.trigger_typing()\n response_content = await method(message.content[len(full_command):])\n await message.channel.send(embed=response_content)\n return\n\n if message.content[:len(Google.ActivationPhrase)] == Google.ActivationPhrase:\n await message.channel.trigger_typing()\n response_content = await self.ok_google(message.content[len(Google.ActivationPhrase):])\n await message.channel.send(embed=response_content)\n","sub_path":"Google.py","file_name":"Google.py","file_ext":"py","file_size_in_byte":4659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"254352811","text":"#!/usr/bin/python3\n\"\"\"\nThis module contains : def rain ()\n\"\"\"\n\n\ndef rain(walls):\n \"\"\" rain\n \"\"\"\n if not walls:\n return 0\n\n if len(walls) < 1:\n return 0\n\n r = 0\n l_walls = len(walls)\n\n for ctr in range(l_walls):\n left_limit = walls[ctr]\n for idx in range(ctr):\n left_limit = max(left_limit, walls[idx])\n right_limit = walls[ctr]\n\n for idx in range(ctr + 1, l_walls):\n x = walls[idx]\n right_limit = max(right_limit, x)\n res = min(left_limit, right_limit)\n r += res - walls[ctr]\n\n return r\n","sub_path":"0x10-rain/0-rain.py","file_name":"0-rain.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"141119084","text":"# -*- coding: UTF-8 -*-\nimport re\n\nimport simplejson as json\nfrom threading import Thread\nimport datetime\n\nfrom django.contrib.auth import logout\nfrom django.db import connection, transaction\nfrom django.utils import timezone\nfrom django.shortcuts import render, get_object_or_404,render_to_response\nfrom django.http import HttpResponseRedirect,HttpResponse\nfrom django.urls import reverse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import View\n\n\nfrom sql.utils.dao import Dao\nfrom sql.utils.inception import InceptionDao\nfrom sql.utils.aes_decryptor import Prpcrypt\nfrom sql.utils.permission import superuser_required\nfrom sql.utils.jobs import job_info, del_sqlcronjob, add_sqlcronjob\nfrom sql import forms\n\nfrom .models import users, master_config, slave_config, workflow, QueryPrivileges, Group, \\\n QueryPrivilegesApply, Config, GroupRelations, DatabaseList,AcountList\nfrom sql.utils.workflow import Workflow\nfrom .sqlreview import getDetailUrl, execute_call_back, execute_skipinc_call_back\nfrom .const import Const, WorkflowDict\nfrom sql.utils.group import user_groups, user_masters, user_slaves\nfrom sql.utils.extend_json_encoder import ExtendJSONEncoder\n\n\nimport logging\n\nlogger = logging.getLogger('default')\n\ndao = Dao()\nprpCryptor = Prpcrypt()\nworkflowOb = Workflow()\n\n@csrf_exempt\ndef asset_list(request):\n limit = int(request.POST.get('limit'))\n offset = int(request.POST.get('offset'))\n limit = offset + limit\n\n # 获取筛选参数\n navStatus = request.POST.get('navStatus')\n\n returnData = {\"rows\": []}\n rows= []\n if navStatus == 'all':\n assets = DatabaseList.objects.filter()\n else:\n assets = DatabaseList.objects.filter(engine=navStatus)\n\n for asset in assets:\n returnData['rows'].append(\n {\"id\":asset.id,\n \"rds_id\":asset.rds_id,\n \"rds_name\": asset.rds_name,\n \"rds_ip\": asset.rds_ip,\n \"engine\": asset.engine,\n \"tags\": asset.tags\n }\n )\n return HttpResponse(json.dumps(returnData, cls=ExtendJSONEncoder, bigint_as_string=True))\n\ndef asset(request):\n context = {'currentMenu': 'asset_list'}\n return render(request, 'asset_list.html', context=context)\n\n\ndef asset_add(request):\n return render(request, 'asset_add.html')\n\ndef asset_add_base(request):\n form = forms.asset_from(request.POST)\n asset = DatabaseList()\n if form.is_valid():\n rds_id = form.cleaned_data.get('rds_id')\n rds_name = form.cleaned_data.get('rds_name')\n rds_ip = form.cleaned_data.get('rds_ip')\n engine = form.cleaned_data.get('engine')\n tags = form.cleaned_data.get('tags')\n asset.rds_id = rds_id\n asset.rds_name = rds_name\n asset.rds_ip = rds_ip\n asset.engine = engine\n asset.tags = tags\n asset.save()\n return HttpResponseRedirect('/asset/')\n else:\n print(form.errors)\n return HttpResponseRedirect('/asset_add/')\n return HttpResponseRedirect('/asset/')\n\n\ndef account_list(request,rds_id):\n prpCryptor = Prpcrypt()\n rdsid = rds_id\n returnData = {\"rows\": []}\n if rds_id == '0':\n assets = AcountList.objects.all()\n else:\n assets = AcountList.objects.filter(rds_id=rdsid,active_flag=1)\n for asset in assets:\n returnData['rows'].append(\n {\"id\":asset.id,\n \"acount\":asset.acount,\n \"password\":prpCryptor.decrypt(asset.password),\n \"permissions\": asset.permissions,\n \"data_name\": asset.data_name,\n \"applicant\": asset.applicant,\n \"operator\": asset.operator,\n \"k2_id\": asset.k2_id,\n \"createtime\":asset.createtime,\n \"rds_id\":asset.rds_id,\n \"rds_name\":asset.rds_name\n }\n )\n #return render(request, 'asset_list.html',context=result)\n data = json.dumps(returnData, cls=ExtendJSONEncoder, bigint_as_string=True)\n return render(request,'account_detail.html',context=returnData)\n\ndef account_add(request):\n return render(request, 'account_add.html')\n\n\ndef account_add_base(request):\n url = request.META.get('HTTP_REFERER', '/').split(\"next=\")[-1]\n form = forms.account_from(request.POST)\n account = AcountList()\n if form.is_valid():\n next = request.GET.get('next')\n rds_id = form.cleaned_data.get('rds_id')\n rds_name = form.cleaned_data.get('rds_name')\n acount = form.cleaned_data.get('acount')\n password = form.cleaned_data.get('password')\n permissions = form.cleaned_data.get('permissions')\n data_name = form.cleaned_data.get('data_name')\n applicant = form.cleaned_data.get('applicant')\n k2_id = form.cleaned_data.get('k2_id')\n account.rds_id = rds_id\n account.rds_name = rds_name\n account.acount = acount\n account.password = password\n account.password = password\n account.permissions = permissions\n account.data_name = data_name\n account.applicant = applicant\n account.k2_id = k2_id\n account.operator=request.user\n account.createtime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n account.save()\n\n return HttpResponseRedirect(url)\n else:\n print(form.errors)\n return HttpResponseRedirect('/account_add/')\n\ndef account_edit(request):\n url = request.META.get('HTTP_REFERER', '/').split(\"account_page/\")[-1]\n real_url = '/account_detail/'\n table_id=request.POST.get('id', 'id')\n a1 = request.POST.get('rds_id', 'rds_id')\n a2 = request.POST.get('rds_name', 'rds_name')\n a3 = request.POST.get('acount', 'acount')\n a4 = request.POST.get('password', 'password')\n a5 = request.POST.get('permissions', 'permissions')\n a6 = request.POST.get('data_name', 'data_name')\n a7 = request.POST.get('applicant', 'applicant')\n a8 = request.POST.get('k2_id', 'k2_id')\n account = AcountList.objects.get(id=table_id)\n account.rds_id=a1\n account.rds_name=a2\n account.acount=a3\n account.password=a4\n account.permissions=a5\n account.data_name=a6\n account.applicant=a7\n account.k2_id=a8\n account.operator = str(request.user)\n account.createtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n account.save()\n real_url = '/account_detail/' + a1\n #return render(request, 'account_edit.html', {'account': account})\n return HttpResponseRedirect(real_url)\n\ndef account_page(request, id):\n table_id= id\n asset = AcountList.objects.get(pk=table_id)\n returnData={\n \"id\": asset.id,\n \"acount\": asset.acount,\n \"password\": prpCryptor.decrypt(asset.password),\n \"permissions\": asset.permissions,\n \"data_name\": asset.data_name,\n \"applicant\": asset.applicant,\n \"k2_id\": asset.k2_id,\n \"rds_id\": asset.rds_id,\n \"rds_name\": asset.rds_name\n }\n return render(request, 'account_edit.html', {'account': returnData})\n\ndef asset_page(request, id):\n table_id= id\n art = DatabaseList.objects.get(id=table_id)\n return render(request, 'asset_edit.html', {'asset': art})\n\ndef asset_edit(request):\n\n table_id=request.POST.get('id', 'id')\n a1 = request.POST.get('rds_id', 'rds_id')\n a2 = request.POST.get('rds_name', 'rds_name')\n a3 = request.POST.get('rds_ip', 'rds_ip')\n a4 = request.POST.get('engine', 'engine')\n a5 = request.POST.get('tags', 'tags')\n print (table_id)\n asset = DatabaseList.objects.get(pk=table_id)\n asset.rds_id=a1\n asset.rds_name=a2\n asset.rds_ip=a3\n asset.engine=a4\n asset.tags=a5\n asset.save()\n\n return HttpResponseRedirect(\"/asset/\")\n\n\n# 登录\ndef login(request):\n return render(request, 'login.html')\n\n\n# 退出登录\ndef sign_out(request):\n logout(request)\n return HttpResponseRedirect(reverse('sql:login'))\n\n\n# 注册用户\ndef sign_up(request):\n username = request.POST.get('username')\n password = request.POST.get('password')\n password2 = request.POST.get('password2')\n display = request.POST.get('display')\n email = request.POST.get('email')\n\n if username is None or password is None:\n context = {'errMsg': '用户名和密码不能为空'}\n return render(request, 'error.html', context)\n if len(users.objects.filter(username=username)) > 0:\n context = {'errMsg': '用户名已存在'}\n return render(request, 'error.html', context)\n if password != password2:\n context = {'errMsg': '两次输入密码不一致'}\n return render(request, 'error.html', context)\n\n users.objects.create_user(username=username,\n password=password,\n display=display,\n email=email,\n role='工程师',\n is_active=1,\n is_staff=1)\n return render(request, 'login.html')\n\n\n# SQL上线工单页面\ndef sqlworkflow(request):\n context = {'currentMenu': 'sqlworkflow'}\n return render(request, 'sqlworkflow.html', context)\n\n\n# 提交SQL的页面\ndef submitSql(request):\n user = request.user\n # 获取组信息\n group_list = user_groups(user)\n\n # 获取所有有效用户,通知对象\n active_user = users.objects.filter(is_active=1)\n\n context = {'currentMenu': 'sqlworkflow', 'active_user': active_user, 'group_list': group_list}\n return render(request, 'submitSql.html', context)\n\n\n# 提交SQL给inception进行解析\ndef autoreview(request):\n workflowid = request.POST.get('workflowid')\n sqlContent = request.POST['sql_content']\n workflowName = request.POST['workflow_name']\n group_name = request.POST['group_name']\n group_id = Group.objects.get(group_name=group_name).group_id\n clusterName = request.POST['cluster_name']\n db_name = request.POST.get('db_name')\n isBackup = request.POST['is_backup']\n reviewMan = request.POST.get('workflow_auditors')\n notify_users = request.POST.getlist('notify_users')\n\n # 服务器端参数验证\n if sqlContent is None or workflowName is None or clusterName is None or db_name is None or isBackup is None or reviewMan is None:\n context = {'errMsg': '页面提交参数可能为空'}\n return render(request, 'error.html', context)\n\n # 验证组权限(用户是否在该组、该组是否有指定实例)\n try:\n GroupRelations.objects.get(group_name=group_name, object_name=clusterName, object_type=2)\n except Exception:\n context = {'errMsg': '该组不存在所选主库!'}\n return render(request, 'error.html', context)\n try:\n user_masters(request.user).get(cluster_name=clusterName)\n except Exception:\n context = {'errMsg': '你所在组未关联该主库!'}\n return render(request, 'error.html', context)\n\n # # 删除注释语句\n # sqlContent = ''.join(\n # map(lambda x: re.compile(r'(^--.*|^/\\*.*\\*/;\\s*$)').sub('', x, count=1),\n # sqlContent.splitlines(1))).strip()\n # # 去除空行\n # sqlContent = re.sub('[\\r\\n\\f]{2,}', '\\n', sqlContent)\n\n sqlContent = sqlContent.strip()\n\n if sqlContent[-1] != \";\":\n context = {'errMsg': \"SQL语句结尾没有以;结尾,请后退重新修改并提交!\"}\n return render(request, 'error.html', context)\n\n # 交给inception进行自动审核\n try:\n result = InceptionDao().sqlautoReview(sqlContent, clusterName, db_name)\n except Exception as msg:\n context = {'errMsg': msg}\n return render(request, 'error.html', context)\n\n if result is None or len(result) == 0:\n context = {'errMsg': 'inception返回的结果集为空!可能是SQL语句有语法错误'}\n return render(request, 'error.html', context)\n # 要把result转成JSON存进数据库里,方便SQL单子详细信息展示\n jsonResult = json.dumps(result)\n\n # 遍历result,看是否有任何自动审核不通过的地方,一旦有,则需要设置is_manual = 0,跳过inception直接执行\n workflowStatus = Const.workflowStatus['manreviewing']\n # inception审核不通过的工单,标记手动执行标签\n is_manual = 0\n for row in result:\n if row[2] == 2:\n is_manual = 1\n break\n elif re.match(r\"\\w*comments\\w*\", row[4]):\n is_manual = 1\n break\n\n # 判断SQL是否包含DDL语句,SQL语法 1、DDL,2、DML\n sql_syntax = 2\n for row in sqlContent.strip(';').split(';'):\n if re.match(r\"^alter|^create|^drop|^truncate|^rename\", row.strip().lower()):\n sql_syntax = 1\n break\n\n # 调用工作流生成工单\n # 使用事务保持数据一致性\n try:\n with transaction.atomic():\n # 存进数据库里\n engineer = request.user.username\n if not workflowid:\n Workflow = workflow()\n Workflow.create_time = timezone.now()\n else:\n Workflow = workflow.objects.get(id=int(workflowid))\n Workflow.workflow_name = workflowName\n Workflow.group_id = group_id\n Workflow.group_name = group_name\n Workflow.engineer = engineer\n Workflow.engineer_display = request.user.display\n Workflow.review_man = reviewMan\n Workflow.status = workflowStatus\n Workflow.is_backup = isBackup\n Workflow.review_content = jsonResult\n Workflow.cluster_name = clusterName\n Workflow.db_name = db_name\n Workflow.sql_content = sqlContent\n Workflow.execute_result = ''\n Workflow.is_manual = is_manual\n Workflow.audit_remark = ''\n Workflow.sql_syntax = sql_syntax\n Workflow.save()\n workflowId = Workflow.id\n # 自动审核通过了,才调用工作流\n if workflowStatus == Const.workflowStatus['manreviewing']:\n # 调用工作流插入审核信息, 查询权限申请workflow_type=2\n # 抄送通知人\n listCcAddr = [email['email'] for email in\n users.objects.filter(username__in=notify_users).values('email')]\n workflowOb.addworkflowaudit(request, WorkflowDict.workflow_type['sqlreview'], workflowId,\n listCcAddr=listCcAddr)\n except Exception as msg:\n context = {'errMsg': msg}\n return render(request, 'error.html', context)\n\n return HttpResponseRedirect(reverse('sql:detail', args=(workflowId,)))\n\n\n# 展示SQL工单详细页面\ndef detail(request, workflowId):\n workflowDetail = get_object_or_404(workflow, pk=workflowId)\n if workflowDetail.status in (Const.workflowStatus['finish'], Const.workflowStatus['exception']) \\\n and workflowDetail.is_manual == 0:\n listContent = json.loads(workflowDetail.execute_result)\n else:\n listContent = json.loads(workflowDetail.review_content)\n\n # 获取审核人\n reviewMan = workflowDetail.review_man\n reviewMan = reviewMan.split(',')\n\n # 获取当前审核人\n try:\n current_audit_user = workflowOb.auditinfobyworkflow_id(workflow_id=workflowId,\n workflow_type=WorkflowDict.workflow_type['sqlreview']\n ).current_audit_user\n except Exception:\n current_audit_user = None\n\n # 获取定时执行任务信息\n if workflowDetail.status == Const.workflowStatus['timingtask']:\n job_id = Const.workflowJobprefix['sqlreview'] + '-' + str(workflowId)\n job = job_info(job_id)\n if job:\n run_date = job.next_run_time\n else:\n run_date = ''\n else:\n run_date = ''\n\n # sql结果\n column_list = ['ID', 'stage', 'errlevel', 'stagestatus', 'errormessage', 'SQL', 'Affected_rows', 'sequence',\n 'backup_dbname', 'execute_time', 'sqlsha1']\n rows = []\n for row_index, row_item in enumerate(listContent):\n row = {}\n row['ID'] = row_index + 1\n row['stage'] = row_item[1]\n row['errlevel'] = row_item[2]\n row['stagestatus'] = row_item[3]\n row['errormessage'] = row_item[4]\n row['SQL'] = row_item[5]\n row['Affected_rows'] = row_item[6]\n row['sequence'] = row_item[7]\n row['backup_dbname'] = row_item[8]\n row['execute_time'] = row_item[9]\n row['sqlsha1'] = row_item[10]\n rows.append(row)\n\n if workflowDetail.status == '执行中':\n row['stagestatus'] = ''.join(\n [\"
    \",\n \"
    \",\n \"
    \",\n \" \",\n \"
    \",\n \"
    \",\n \"
    \",\n \"
    \",\n \" \",\n \" \",\n \"
    \",\n \"
    \",\n \"
    \"])\n context = {'currentMenu': 'sqlworkflow', 'workflowDetail': workflowDetail, 'column_list': column_list, 'rows': rows,\n 'reviewMan': reviewMan, 'current_audit_user': current_audit_user, 'run_date': run_date}\n return render(request, 'detail.html', context)\n\n\n# 审核通过,不执行\ndef passed(request):\n workflowId = request.POST['workflowid']\n if workflowId == '' or workflowId is None:\n context = {'errMsg': 'workflowId参数为空.'}\n return render(request, 'error.html', context)\n workflowId = int(workflowId)\n workflowDetail = workflow.objects.get(id=workflowId)\n\n # 获取审核人\n reviewMan = workflowDetail.review_man\n reviewMan = reviewMan.split(',')\n\n # 服务器端二次验证,正在执行人工审核动作的当前登录用户必须为审核人. 避免攻击或被接口测试工具强行绕过\n user = request.user\n if user.username is None or user.username not in reviewMan:\n context = {'errMsg': '当前登录用户不是审核人,请重新登录.'}\n return render(request, 'error.html', context)\n\n # 服务器端二次验证,当前工单状态必须为等待人工审核\n if workflowDetail.status != Const.workflowStatus['manreviewing']:\n context = {'errMsg': '当前工单状态不是等待人工审核中,请刷新当前页面!'}\n return render(request, 'error.html', context)\n\n # 使用事务保持数据一致性\n try:\n with transaction.atomic():\n # 调用工作流接口审核\n # 获取audit_id\n audit_id = workflowOb.auditinfobyworkflow_id(workflow_id=workflowId,\n workflow_type=WorkflowDict.workflow_type['sqlreview']).audit_id\n auditresult = workflowOb.auditworkflow(request, audit_id, WorkflowDict.workflow_status['audit_success'],\n user.username, '')\n\n # 按照审核结果更新业务表审核状态\n if auditresult['data']['workflow_status'] == WorkflowDict.workflow_status['audit_success']:\n # 将流程状态修改为审核通过,并更新reviewok_time字段\n workflowDetail.status = Const.workflowStatus['pass']\n workflowDetail.reviewok_time = timezone.now()\n workflowDetail.audit_remark = ''\n workflowDetail.save()\n except Exception as msg:\n context = {'errMsg': msg}\n return render(request, 'error.html', context)\n\n return HttpResponseRedirect(reverse('sql:detail', args=(workflowId,)))\n\n\n# 仅执行SQL\ndef execute(request):\n workflowId = request.POST['workflowid']\n if workflowId == '' or workflowId is None:\n context = {'errMsg': 'workflowId参数为空.'}\n return render(request, 'error.html', context)\n\n workflowId = int(workflowId)\n workflowDetail = workflow.objects.get(id=workflowId)\n clusterName = workflowDetail.cluster_name\n db_name = workflowDetail.db_name\n url = getDetailUrl(request) + str(workflowId) + '/'\n\n # 获取审核人\n reviewMan = workflowDetail.review_man\n reviewMan = reviewMan.split(',')\n\n # 服务器端二次验证,正在执行人工审核动作的当前登录用户必须为审核人或者提交人. 避免攻击或被接口测试工具强行绕过\n user = request.user\n if user.username is None or (user.username not in reviewMan and user.username != workflowDetail.engineer):\n context = {'errMsg': '当前登录用户不是审核人或者提交人,请重新登录.'}\n return render(request, 'error.html', context)\n\n # 服务器端二次验证,当前工单状态必须为审核通过状态\n if workflowDetail.status != Const.workflowStatus['pass']:\n context = {'errMsg': '当前工单状态不是审核通过,请刷新当前页面!'}\n return render(request, 'error.html', context)\n\n # 将流程状态修改为执行中,并更新reviewok_time字段\n workflowDetail.status = Const.workflowStatus['executing']\n workflowDetail.reviewok_time = timezone.now()\n workflowDetail.save()\n\n # 判断是通过inception执行还是直接执行,is_manual=0则通过inception执行,is_manual=1代表inception审核不通过,需要直接执行\n if workflowDetail.is_manual == 0:\n # 执行之前重新split并check一遍,更新SHA1缓存;因为如果在执行中,其他进程去做这一步操作的话,会导致inception core dump挂掉\n try:\n splitReviewResult = InceptionDao().sqlautoReview(workflowDetail.sql_content, workflowDetail.cluster_name,\n db_name,\n isSplit='yes')\n except Exception as msg:\n context = {'errMsg': msg}\n return render(request, 'error.html', context)\n workflowDetail.review_content = json.dumps(splitReviewResult)\n try:\n workflowDetail.save()\n except Exception:\n # 关闭后重新获取连接,防止超时\n connection.close()\n workflowDetail.save()\n\n # 采取异步回���的方式执行语句,防止出现持续执行中的异常\n t = Thread(target=execute_call_back, args=(workflowId, clusterName, url))\n t.start()\n else:\n # 采取异步回调的方式执行语句,防止出现持续执行中的异常\n t = Thread(target=execute_skipinc_call_back,\n args=(workflowId, clusterName, db_name, workflowDetail.sql_content, url))\n t.start()\n\n return HttpResponseRedirect(reverse('sql:detail', args=(workflowId,)))\n\n\n# 定时执行SQL\ndef timingtask(request):\n workflowId = request.POST.get('workflowid')\n run_date = request.POST.get('run_date')\n if run_date is None or workflowId is None:\n context = {'errMsg': '时间不能为空'}\n return render(request, 'error.html', context)\n elif run_date < datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'):\n context = {'errMsg': '时间不能小于当前时间'}\n return render(request, 'error.html', context)\n workflowDetail = workflow.objects.get(id=workflowId)\n if workflowDetail.status not in [Const.workflowStatus['pass'], Const.workflowStatus['timingtask']]:\n context = {'errMsg': '必须为审核通过或者定时执行状态'}\n return render(request, 'error.html', context)\n\n run_date = datetime.datetime.strptime(run_date, \"%Y-%m-%d %H:%M:%S\")\n url = getDetailUrl(request) + str(workflowId) + '/'\n job_id = Const.workflowJobprefix['sqlreview'] + '-' + str(workflowId)\n\n # 使用事务保持数据一致性\n try:\n with transaction.atomic():\n # 将流程状态修改为定时执行\n workflowDetail.status = Const.workflowStatus['timingtask']\n workflowDetail.save()\n # 调用添加定时任务\n add_sqlcronjob(job_id, run_date, workflowId, url)\n except Exception as msg:\n context = {'errMsg': msg}\n return render(request, 'error.html', context)\n return HttpResponseRedirect(reverse('sql:detail', args=(workflowId,)))\n\n\n# 终止流程\ndef cancel(request):\n workflowId = request.POST['workflowid']\n if workflowId == '' or workflowId is None:\n context = {'errMsg': 'workflowId参数为空.'}\n return render(request, 'error.html', context)\n\n workflowId = int(workflowId)\n workflowDetail = workflow.objects.get(id=workflowId)\n\n # 获取审核人\n reviewMan = workflowDetail.review_man\n reviewMan = reviewMan.split(',')\n\n audit_remark = request.POST.get('audit_remark')\n if audit_remark is None:\n context = {'errMsg': '驳回原因不能为空'}\n return render(request, 'error.html', context)\n\n # 服务器端二次验证,如果正在执行终止动作的当前登录用户,不是提交人也不是审核人,则异常.\n user = request.user\n if user.username is None or (user.username not in reviewMan and user.username != workflowDetail.engineer):\n context = {'errMsg': '当前登录用户不是审核人也不是提交人,请重新登录.'}\n return render(request, 'error.html', context)\n\n # 服务器端二次验证,如果当前单子状态是结束状态,则不能发起终止\n if workflowDetail.status in (\n Const.workflowStatus['abort'], Const.workflowStatus['finish'], Const.workflowStatus['autoreviewwrong'],\n Const.workflowStatus['exception']):\n return HttpResponseRedirect(reverse('sql:detail', args=(workflowId,)))\n\n # 使用事务保持数据一致性\n try:\n with transaction.atomic():\n # 调用工作流接口取消或者驳回\n # 获取audit_id\n audit_id = workflowOb.auditinfobyworkflow_id(workflow_id=workflowId,\n workflow_type=WorkflowDict.workflow_type['sqlreview']).audit_id\n if user.username == workflowDetail.engineer:\n auditresult = workflowOb.auditworkflow(request, audit_id, WorkflowDict.workflow_status['audit_abort'],\n user.username, audit_remark)\n else:\n auditresult = workflowOb.auditworkflow(request, audit_id, WorkflowDict.workflow_status['audit_reject'],\n user.username, audit_remark)\n # 删除定时执行job\n if workflowDetail.status == Const.workflowStatus['timingtask']:\n job_id = Const.workflowJobprefix['sqlreview'] + '-' + str(workflowId)\n del_sqlcronjob(job_id)\n # 按照审核结果更新业务表审核状态\n if auditresult['data']['workflow_status'] in (\n WorkflowDict.workflow_status['audit_abort'], WorkflowDict.workflow_status['audit_reject']):\n # 将流程状态修改为人工终止流程\n workflowDetail.status = Const.workflowStatus['abort']\n workflowDetail.audit_remark = audit_remark\n workflowDetail.save()\n except Exception as msg:\n context = {'errMsg': msg}\n return render(request, 'error.html', context)\n return HttpResponseRedirect(reverse('sql:detail', args=(workflowId,)))\n\n\n# 展示回滚的SQL\ndef rollback(request):\n workflowId = request.GET['workflowid']\n if workflowId == '' or workflowId is None:\n context = {'errMsg': 'workflowId参数为空.'}\n return render(request, 'error.html', context)\n workflowId = int(workflowId)\n try:\n listBackupSql = InceptionDao().getRollbackSqlList(workflowId)\n except Exception as msg:\n context = {'errMsg': msg}\n return render(request, 'error.html', context)\n workflowDetail = workflow.objects.get(id=workflowId)\n workflowName = workflowDetail.workflow_name\n rollbackWorkflowName = \"【回滚工单】原工单Id:%s ,%s\" % (workflowId, workflowName)\n context = {'listBackupSql': listBackupSql, 'currentMenu': 'sqlworkflow', 'workflowDetail': workflowDetail,\n 'rollbackWorkflowName': rollbackWorkflowName}\n return render(request, 'rollback.html', context)\n\n\n# SQL审核必读\ndef dbaprinciples(request):\n context = {'currentMenu': 'dbaprinciples'}\n return render(request, 'dbaprinciples.html', context)\n\n\n# 图表展示\ndef charts(request):\n context = {'currentMenu': 'charts'}\n return render(request, 'charts.html', context)\n\n\n# SQL在线查询\ndef sqlquery(request):\n # 获取用户关联从库列表\n listAllClusterName = [slave.cluster_name for slave in user_slaves(request.user)]\n\n context = {'currentMenu': 'sqlquery', 'listAllClusterName': listAllClusterName}\n return render(request, 'sqlquery.html', context)\n\n\n# SQL慢日志\ndef slowquery(request):\n # 获取用户关联主库列表\n cluster_name_list = [master.cluster_name for master in user_masters(request.user)]\n\n context = {'currentMenu': 'slowquery', 'tab': 'slowquery', 'cluster_name_list': cluster_name_list}\n return render(request, 'slowquery.html', context)\n\n\n# SQL优化工具\ndef sqladvisor(request):\n # 获取用户关联主库列表\n cluster_name_list = [master.cluster_name for master in user_masters(request.user)]\n\n context = {'currentMenu': 'sqladvisor', 'listAllClusterName': cluster_name_list}\n return render(request, 'sqladvisor.html', context)\n\n\n# 查询权限申请列表\ndef queryapplylist(request):\n user = request.user\n # 获取项目组\n group_list = user_groups(user)\n\n context = {'currentMenu': 'queryapply', 'group_list': group_list}\n return render(request, 'queryapplylist.html', context)\n\n\n# 查询权限申请详情\ndef queryapplydetail(request, apply_id):\n workflowDetail = QueryPrivilegesApply.objects.get(apply_id=apply_id)\n # 获取当前审核人\n audit_info = workflowOb.auditinfobyworkflow_id(workflow_id=apply_id,\n workflow_type=WorkflowDict.workflow_type['query'])\n\n context = {'currentMenu': 'queryapply', 'workflowDetail': workflowDetail, 'audit_info': audit_info}\n return render(request, 'queryapplydetail.html', context)\n\n\n# 用户的查询权限管理\ndef queryuserprivileges(request):\n # 获取所有用户\n user_list = QueryPrivileges.objects.filter(is_deleted=0).values('user_name').distinct()\n context = {'currentMenu': 'queryapply', 'user_list': user_list}\n return render(request, 'queryuserprivileges.html', context)\n\n\n# 问题诊断--进程\ndef dbdiagnostic(request):\n # 获取用户关联主库列表\n cluster_name_list = [master.cluster_name for master in user_masters(request.user)]\n\n context = {'currentMenu': 'diagnostic', 'tab': 'process', 'cluster_name_list': cluster_name_list}\n return render(request, 'dbdiagnostic.html', context)\n\n\n# 获取工作流审核列表\ndef workflows(request):\n context = {'currentMenu': 'workflow'}\n return render(request, \"workflow.html\", context)\n\n\n# 工作流审核详情\ndef workflowsdetail(request, audit_id):\n # 按照不同的workflow_type返回不同的详情\n auditInfo = workflowOb.auditinfo(audit_id)\n if auditInfo.workflow_type == WorkflowDict.workflow_type['query']:\n return HttpResponseRedirect(reverse('sql:queryapplydetail', args=(auditInfo.workflow_id,)))\n elif auditInfo.workflow_type == WorkflowDict.workflow_type['sqlreview']:\n return HttpResponseRedirect(reverse('sql:detail', args=(auditInfo.workflow_id,)))\n\n\n# 配置管理\n@superuser_required\ndef config(request):\n # 获取所有项组名称\n group_list = Group.objects.all()\n\n # 获取所有用户\n user_list = users.objects.filter(is_active=1).values('username', 'display')\n # 获取所有配置项\n all_config = Config.objects.all().values('item', 'value')\n sys_config = {}\n for items in all_config:\n sys_config[items['item']] = items['value']\n\n context = {'currentMenu': 'config', 'group_list': group_list, 'user_list': user_list,\n 'config': sys_config, 'WorkflowDict': WorkflowDict}\n return render(request, 'config.html', context)\n\n\n# 组管理\n@superuser_required\ndef group(request):\n return render(request, 'group.html')\n\n\n# 组关系管理\n@superuser_required\ndef groupmgmt(request, group_name):\n return render(request, 'groupmgmt.html',{'group_name': group_name})\n\n\n","sub_path":"sql/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":33479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"87243919","text":"import sys\n# PyQt files\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5 import QtGui\n# GUI\nfrom StudyPlan.GUI import recite_gui\n# Vocab\nfrom StudyPlan import TodayList\nfrom StudyPlan import Vocab\n\n\n# class SetNumWindow(QWidget):\n# def __init__(self):\n# super(SetNumWindow).__init__()\n# self.setWindowTitle(\"每日词量设置\")\n# self.resize(400, 300)\n# self.num = 50\n#\n# widget_hori = QVBoxLayout(self)\n# label_hint = QLabel()\n# label_hint.setText('请输入每天需要背诵的单词数量:')\n# self.edit_num = QInputDialog()\n# push_button_confirm = QPushButton('确定')\n# widget_hori.addWidget(label_hint)\n# widget_hori.addWidget(self.edit_num)\n# widget_hori.addWidget(push_button_confirm)\n#\n# # push_button_confirm.clicked.connect(self.close())\n# push_button_confirm.clicked.connect(self.num_upd)\n#\n# def num_upd(self):\n# self.num = self.edit_num.getInt()\n\n\nclass ReciteWords:\n def __init__(self, WORD_DICT, parent):\n # Get todayList\n # self.today_list = [\"test\"]\n self.vocab = Vocab.Vocab(WORD_DICT)\n self.vocab.saveVocab() # 保存词库\n self.today_list_obj = TodayList.TodayList(self.vocab)\n self.open = True\n if self.today_list_obj.new_user:\n value, ok = QInputDialog.getInt(parent, '学习计划设定', '请输入每天需要背诵的数量(5-700):', 50, 5, 700, 1)\n if ok:\n self.today_list_obj.plan_for_new_user(value, self.vocab)\n else:\n self.open = False\n return\n self.today_list_dict = self.today_list_obj.getTodayList()\n self.today_list = list(self.today_list_dict.keys())\n self.finished = False\n self.ite = -1\n self.review_list = []\n # self.is_first_round = True\n if self.next_word():\n print('开始背单词')\n if len(self.today_list) > 0:\n self.word_current = self.today_list[self.ite]\n else:\n print(\"Fail to get recite list for today\")\n self.finished = True\n else: # 今天的任务已经背完了\n QMessageBox.information(parent, '提醒', '你已经背完今天的单词了呢,注意劳逸结合哦~', QMessageBox.Yes)\n # parent.close()\n self.finished = True\n\n def next_word(self):\n \"\"\"\n get next word\n if has_next_word:\n return true\n else: (have finished today's task)\n return false\n \"\"\"\n while True: # 找到下一个不是已完成的单词\n # today_list_dict: 0 -- 没背过;1 -- 背过没记住;2 -- 已经背过了(或者没记住然后记住了)\n self.ite += 1\n if self.ite >= len(self.today_list):\n self.today_list = self.review_list.copy()\n self.review_list.clear()\n self.ite = 0\n # self.is_first_round = False\n if len(self.today_list) < 1:\n return False\n if self.today_list_dict[self.today_list[self.ite]] < 2:\n break\n\n self.word_current = self.today_list[self.ite]\n return True\n\n def get_word_info(self):\n return self.vocab.getInfo(self.word_current)\n\n def review_this_word(self):\n # this word will show again today\n self.review_list.append(self.word_current)\n print(self.word_current)\n\n def downgrade(self):\n \"\"\"\n new 不会 --> unfamiliar\n familiar 不会 --> unfamiliar\n unfamiliar 不会 --> unfamiliar\n \"\"\"\n self.today_list_dict[self.word_current] = 1 # 背过但没记住\n self.vocab.updateFamiliarity(word=self.word_current, familiarity=1)\n\n def upgrade(self):\n # Only upgrade in first round\n if self.today_list_dict[self.word_current] == 0:\n # new 会 --> familiar\n # familiar 会 --> familiar\n # unfamiliar 会 --> familiar\n self.vocab.updateFamiliarity(word=self.word_current, familiarity=2)\n else:\n pass\n self.today_list_dict[self.word_current] = 2 # 记住了,今天不再背\n\n\nclass ReciteGUI(QMainWindow, recite_gui.Ui_MainWindow, QObject):\n complete_all = pyqtSignal()\n\n def __init__(self, WORD_DICT):\n super(ReciteGUI, self).__init__()\n self.WORD_DICT = WORD_DICT\n self.setupUi(self)\n self.pushButton_revoke.setVisible(False)\n self.pushButton_next.setVisible(False)\n self.label_stop_showing.setVisible(False)\n self.label_show_again.setVisible(False)\n _translate = QCoreApplication.translate\n self.listWidget.setSortingEnabled(False)\n self.listWidget.item(1).setHidden(True)\n self.listWidget.item(2).setHidden(True)\n self.listWidget.item(3).setHidden(True)\n self.listWidget.item(4).setHidden(True)\n self.listWidget.item(5).setHidden(True)\n self.label_2.setVisible(False)\n self.label_3.setVisible(False)\n #self.pushButton_exit.setVisible(False)\n\n self.complete_all.connect(self.label_2.show)\n self.complete_all.connect(self.label_3.show)\n self.complete_all.connect(self.listWidget.hide)\n self.complete_all.connect(self.pushButton_yes.hide)\n self.complete_all.connect(self.pushButton_no.hide)\n self.complete_all.connect(self.pushButton_next.hide)\n self.complete_all.connect(self.pushButton_revoke.hide)\n self.complete_all.connect(self.label_show_again.hide)\n self.complete_all.connect(self.label_stop_showing.hide)\n #self.complete_all.connect(self.pushButton_exit.show)\n\n self.reciting = ReciteWords(self.WORD_DICT, self)\n if not self.reciting.open:\n return\n self.finished = False\n if self.reciting.finished:\n # self.close()\n self.finished = True\n else:\n self.forget_this_word = False\n self.update_word_info()\n self.finished_words_num = self.reciting.today_list_obj.finished_num\n self.total_words_num = len(self.reciting.today_list)\n self.progressBar.setValue((self.finished_words_num * 100.0) / self.total_words_num)\n\n def word_display_upd(self, visible):\n # _translate = QCoreApplication.translate\n # item = self.listWidget.item(0)\n # item.setText(_translate(\"MainWindow\", self.word_current))\n # item = self.listWidget.item(1)\n # item.setText(_translate(\"MainWindow\", \"pron\"))\n # item = self.listWidget.item(2)\n # item.setText(_translate(\"MainWindow\", \"meaning\"))\n # item = self.listWidget.item(3)\n # item.setText(_translate(\"MainWindow\", \"sent1\"))\n self.listWidget.item(1).setHidden(not visible)\n self.listWidget.item(2).setHidden(not visible)\n self.listWidget.item(3).setHidden(not visible)\n self.listWidget.item(4).setHidden(not visible)\n self.listWidget.item(5).setHidden(not visible)\n\n def show_exp(self):\n # slot\n self.word_display_upd(True)\n\n def hide_exp(self):\n # slot\n self.word_display_upd(False)\n\n def forget(self):\n # slot\n self.reciting.review_this_word()\n self.reciting.downgrade()\n self.forget_this_word = True\n\n def next_word(self):\n # slot\n if self.forget_this_word:\n pass\n else:\n self.reciting.upgrade()\n self.finished_words_num += 1\n self.progressBar.setValue((self.finished_words_num * 100.0) / self.total_words_num)\n if self.reciting.next_word():\n self.update_word_info()\n self.forget_this_word = False\n self.pushButton_yes.setVisible(True)\n self.pushButton_no.setVisible(True)\n else:\n # signal for finishing today_list\n self.complete_all.emit()\n\n # def complete(self):\n # self.complete_all.emit()\n\n def update_word_info(self):\n word = self.reciting.word_current\n info = self.reciting.get_word_info()\n\n _translate = QCoreApplication.translate\n item = self.listWidget.item(0)\n item.setText(_translate(\"MainWindow\", word))\n item = self.listWidget.item(1)\n item.setText(_translate(\"MainWindow\", info[0][0]).replace('\\n', ' ')) # TODO: merge into a single line\n item = self.listWidget.item(2)\n item.setText(_translate(\"MainWindow\", info[0][1]).replace('\\n', ' '))\n exp = info[1]['reiku']\n str = []\n for i in range(len(exp)):\n s_en = exp[i][0].split('\\n')\n s_en = s_en[2:]\n s_ch = exp[i][1].split('\\n')\n s_ch = s_ch[1:]\n if (len(s_ch) > 0) and (len(s_en) > 0):\n str.append(\"{}\\n{}\".format(s_en[0], s_ch[0]))\n for i in range(min(len(str), 3)):\n item = self.listWidget.item(3 + i)\n item.setText(_translate(\"MainWindow\", str[i]))\n\n def closeEvent(self, event):\n if not self.reciting.open:\n return\n print(\"Close event activated.\")\n self.reciting.vocab.saveVocab()\n self.reciting.today_list_obj.record_finished(self.finished_words_num,\n self.reciting.today_list_dict) # 为了下次能够显示已经背的词数\n self.reciting.today_list_obj.save_todaylist()\n\n# if __name__ == \"__main__\":\n# # GUI setup\n# app = QApplication(sys.argv)\n# recite_gui = ReciteGUI()\n# recite_gui.show()\n# sys.exit(app.exec_())\n","sub_path":"StudyPlan/recite_action.py","file_name":"recite_action.py","file_ext":"py","file_size_in_byte":9691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"123846081","text":"#!/usr/bin/env python3\n\nimport sys\n\nfrom broker.lib import get_tx_status\n\nif __name__ == \"__main__\":\n import broker.eblocbroker.Contract as Contract\n\n Ebb = Contract.eblocbroker\n\n if len(sys.argv) == 2:\n account = str(sys.argv[1])\n else:\n print(\"Please provide an Ethereum account as an argument.\")\n sys.exit(1)\n\n try:\n tx_hash = Ebb.withdraw(account)\n receipt = get_tx_status(tx_hash)\n except:\n sys.exit(1)\n","sub_path":"broker/eblocbroker/withdraw.py","file_name":"withdraw.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"402498215","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport argparse\nimport yaml\n\nimport image_utils\nimport object_detection\nimport face_detection\nimport person_reid\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--video', help='input local video file')\n parser.add_argument('--debug', help='debug mode, dump all needed files', action='store_true')\n # below options will be useful onl in debug mode\n parser.add_argument('--frame_dir', help='per frame image dir for video', default='data/frames')\n parser.add_argument('--dump_person', help='enable per person image dump', action='store_true')\n parser.add_argument('--person_dir', help='per person image dir for video', default='data/persons')\n parser.add_argument('--dump_face', help='enable per face image dump', action='store_true')\n parser.add_argument('--face_dir', help='per face image dir for video', default='data/faces')\n parser.add_argument('--yaml_dir', help='per image yaml dir', default='data/yamls')\n parser.add_argument('--discard_yml', help='yml file to store bbox to be discarded')\n parser.add_argument('--name_dir', help='path to trace images, with each subfolder as person name, and inside 256x128 image for that person')\n parser.add_argument('--dump_video', help='enable combined video dump', action='store_true')\n parser.add_argument('--output_dir', help='output dir', default='data/output')\n\n args = parser.parse_args()\n return args\n\ndef prepare_images(args):\n images = {}\n image_utils.save_image_from_video(args.frame_dir, args.video)\n for image_name in sorted(os.listdir(args.frame_dir)):\n images[os.path.splitext(image_name)[0]] = {'image_path': os.path.join(args.frame_dir, image_name)}\n return images\n\ndef save_yaml(images, output_dir):\n if not os.path.isdir(output_dir):\n os.makedirs(output_dir)\n\n keys = sorted(images.keys())\n print('Total {} yaml files to save'.format(len(keys)))\n for fid in keys:\n v = images[fid]\n filename = os.path.join(output_dir, '{}.yml'.format(fid))\n print('\\rSaving yaml file {}'.format(filename), flush=True, end='')\n with open(filename, 'w+') as f:\n yaml.dump(v, f, default_flow_style=False)\n print('')\n\ndef load_yaml(yaml_dir):\n data = {}\n filenames = sorted(os.listdir(yaml_dir))\n print('Total {} yaml files to load'.format(len(filenames)))\n for filename in filenames:\n print('\\rLoading yaml file {}'.format(filename), flush=True, end='')\n fid = filename.split('.')[0]\n with open(os.path.join(yaml_dir, filename), 'r') as f:\n data[fid] = yaml.load(f)\n print('')\n return data\n\ndef save_person(images, output_dir):\n if not os.path.isdir(output_dir):\n os.makedirs(output_dir)\n\n ppaths = []\n print('')\n for fid in sorted(images.keys()):\n print('\\rSaving person image for fid={}'.format(fid), flush=True, end='')\n fimage = images[fid]\n image_np = image_utils.read_image_to_np(fimage['image_path'])\n persons = fimage['detections']['person']\n if not persons: continue\n for pid in sorted(persons.keys()):\n v = persons[pid]\n image_name = '{}_person_{}.jpg'.format(fid, pid)\n image_chop = image_utils.read_image_from_np_with_box(v['bbox'], image_np)\n person_path = os.path.join(output_dir, image_name)\n try:\n image_utils.save_image_from_np(person_path, image_utils.resize_image_from_np(image_chop, 256, 128))\n except:\n print(fid, pid)\n print(v['bbox'])\n print(image_np.shape, image_chop.shape)\n exit()\n v['image_path'] = person_path\n ppaths.append(person_path)\n print('')\n return ppaths\n\ndef embed_name_vector(name_dir):\n colors = ['#ff0000', '#00ff00', '#0000ff', '#00aa55', '#5500aa', '#aa5500', '#0055aa', '#aa0055', '#55aa00']\n name_vectors = {}\n names = []\n ppaths = []\n\n for i, name in enumerate(os.listdir(name_dir)):\n name_path = os.path.join(name_dir, name)\n if not os.path.isdir(name_path): continue\n name_vectors[name] = {}\n name_vectors[name]['vectors'] = []\n name_vectors[name]['color'] = colors[i]\n\n for filename in os.listdir(name_path):\n image_path = os.path.join(name_path, filename)\n names.append(name)\n ppaths.append(image_path)\n\n vectors = person_reid.embed(ppaths)\n for i in range(len(names)):\n name = names[i]\n vector = vectors[i]\n name_vectors[name]['vectors'].append(vector)\n \n return name_vectors\n\ndef get_iou(bb1, bb2, method='square'):\n iou = 0.0\n if ',' in method:\n for meth in method.split(','):\n iou = max(iou, get_iou(bb1, bb2, method=meth))\n return iou\n\n ymin = max(bb1[0], bb2[0])\n xmin = max(bb1[1], bb2[1])\n ymax = min(bb1[2], bb2[2])\n xmax = min(bb1[3], bb2[3])\n\n if method == 'row':\n if xmax < xmin:\n return iou\n bb1_len = bb1[3] - bb1[1]\n bb2_len = bb2[3] - bb2[1]\n iou = (xmax-xmin) / float(bb1_len + bb2_len - (xmax-xmin))\n elif method == 'col':\n if ymax < ymin:\n return iou\n bb1_len = bb1[2] - bb1[0]\n bb2_len = bb2[2] - bb2[0]\n iou = (ymax-ymin) / float(bb1_len + bb2_len - (ymax-ymin))\n elif method == 'square':\n if xmax < xmin or ymax < ymin:\n return iou\n intersection_area = (xmax - xmin) * (ymax - ymin)\n bb1_area = (bb1[2] - bb1[0]) * (bb1[3] - bb1[1])\n bb2_area = (bb2[2] - bb2[0]) * (bb2[3] - bb2[1])\n iou = intersection_area / float(bb1_area + bb2_area - intersection_area)\n return iou\n\ndef discard_bbox(images, discard_yml):\n with open(discard_yml, 'r') as f:\n discard_bboxes = yaml.load(f)\n\n for fid in sorted(images.keys()):\n print('\\rUpdating score for person fid {}'.format(fid), flush=True, end='')\n fimage = images[fid]\n persons = fimage['detections']['person']\n if not persons: continue\n for pid in sorted(persons.keys()):\n bbox = persons[pid]['bbox']\n score = persons[pid]['score']\n for k, v in discard_bboxes.items():\n iou = get_iou(bbox, v, method='col,row,square')\n score = min(score, 1.0 - iou)\n persons[pid]['score'] = score\n print('')\n \ndef debug_mode(args):\n\n if args.video:\n images = prepare_images(args)\n else:\n images = load_yaml(args.yaml_dir)\n\n if args.dump_person:\n detection_graph = object_detection.prepare_model()\n images = object_detection.detect(images, detection_graph)\n save_yaml(images, args.yaml_dir)\n ppaths = save_person(images, args.person_dir)\n save_yaml(images, args.yaml_dir)\n if ppaths:\n emb = person_reid.embed(ppaths)\n person_reid.update_images_with_emb(images, ppaths, emb)\n save_yaml(images, args.yaml_dir)\n\n if args.dump_face:\n # pnet, rnet, onet = face_detection.prepare_model()\n # images = face_detection.detect(images, pnet, rnet, onet)\n pass\n\n if args.discard_yml:\n discard_bbox(images, args.discard_yml)\n save_yaml(images, args.yaml_dir)\n\n if args.name_dir:\n name_vectors = embed_name_vector(args.name_dir)\n distance = person_reid.get_distance(name_vectors)\n print('distance is {}'.format(distance))\n person_reid.reid(images, name_vectors, distance)\n save_yaml(images, args.yaml_dir)\n \n if args.dump_video:\n image_utils.save_video_from_image(args.output_dir, images)\n\ndef display_mode(args):\n for image in image_utils.read_image_from_video(args.video):\n continue\n\ndef main():\n args = parse_args()\n\n if args.debug:\n debug_mode(args)\n else:\n if not args.video:\n print('--video is required for non debug mode')\n exit(1)\n if not args.name_dir:\n print('--name_dir is required for non debug mode')\n display_mode(args)\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"3695835","text":"from conans import ConanFile, python_requires\n\nimport os\nimport sys\nimport shutil\nimport subprocess\nimport platform\nfrom packaging import version\n\n\"\"\"\nRead document generation type (if passed locally or through jenkins build job)\nIf it is not set, use the default type i.e, upload_e2e\n\"\"\"\n\ndocu_generation_type = os.environ.get('DOCU_GENERATION_TYPE')\nif docu_generation_type is None:\n docu_generation_type = 'upload_e2e'\n\n# standard attributes\nvar_name = \"simple_calc_python\"\nvar_version = \"0.0.1\"\nvar_description = \"Source code documentation\"\n\n# customized attribute\n# adjust var_parent_dir_config_file accordingly if it is not a single folder\nvar_parent_dir_config_file = 'Simple_Calculator'\nvar_folder_html = \"SCD_Demo_Simple_Calculator_DocHtml\"\nvar_folder_spelling = \"SCD_Demo_Simple_Calculator_DocSpelling\"\n\nclass ConanRecipe(ConanFile):\n name = var_name\n version = var_version\n generators = \"txt\"\n description = var_description\n settings = \"os\", \"arch\"\n scm = { \"type\": \"git\", \"url\": \"auto\", \"revision\": \"auto\" }\n no_copy_source = True\n options = {}\n default_options = {}\n\n # Set version in configuration file conf.py\n os.environ[\"version\"] = version\n\n def build_requirements(self):\n command = subprocess.check_output(['sphinx-build', '--version']).decode(\"utf8\")\n if not (version.parse(command.strip()) == version.parse(\"sphinx-build 2.4.4\") or\n version.parse(command.strip()) > version.parse(\"sphinx-build 2.4.4\")):\n self.output.error(\"Sphinx Requirements are not satisfied\")\n exit(1)\n\n def requirements(self):\n pass\n\n def build(self):\n # self.source_folder and self.build_folder are different in conan build method\n # but there are same in conan create method\n\n input_folder = None\n configuration_file = os.path.join(self.source_folder, var_parent_dir_config_file, 'conf.py')\n\n output_folder = os.path.join(self.build_folder, 'package', var_folder_html)\n os.makedirs(output_folder, exist_ok=True)\n\n # Adjust the parent folder of config file path for both conan build and conan create method\n if os.path.exists(configuration_file):\n input_folder = os.path.join(self.source_folder, var_parent_dir_config_file)\n else:\n input_folder = self.source_folder\n\n # -- target build html ----------------------------------------\n try:\n command = subprocess.run(['sphinx-build', '-b', 'html', input_folder, output_folder],\n check=True)\n\n # make archieve\n shutil.make_archive(var_folder_html, 'zip', output_folder)\n except subprocess.CalledProcessError as err:\n print(err.output)\n\n # -- target build spelling ----------------------------------------\n output_folder = os.path.join(self.build_folder, 'package', var_folder_spelling)\n os.makedirs(output_folder, exist_ok=True)\n\n\n try:\n command = subprocess.run(['sphinx-build', '-b', 'spelling', input_folder, output_folder],\n check=True)\n output_folder = os.path.join(self.build_folder, 'package', var_folder_spelling)\n os.makedirs(output_folder, exist_ok=True)\n # make archieve\n shutil.make_archive(var_folder_spelling, 'zip', output_folder)\n except subprocess.CalledProcessError as err:\n print(err.output)\n\n","sub_path":"docs/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"160297470","text":"\n\n#calss header\nclass _RECOVERY():\n\tdef __init__(self,): \n\t\tself.name = \"RECOVERY\"\n\t\tself.definitions = [u'the process of becoming well again after an illness or injury: ', u'the process of becoming successful or normal again after problems: ', u'the process of getting something back: ']\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/_recovery.py","file_name":"_recovery.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"173036421","text":"#!/usr/bin/python\nimport os\nimport logging\nimport requests\nimport signal\nfrom gi.repository import Gtk\nfrom gi.repository import Gdk\nfrom gi.repository import GObject\nfrom gi.repository import Soup\nfrom gi.repository import WebKit\nfrom collections import namedtuple\n\n\nAPI_URL = os.getenv('PANNELLO_API_URL', 'http://127.0.0.1:8000/api/v1/')\nAPI_KEY = os.getenv('PANNELLO_API_KEY', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx')\n\nPOLL_DELAY = 3 * 1000 # Miliseconds\nPROJECT_DIR = os.path.dirname(os.path.realpath(__file__))\nSTART_PAGE = os.path.join(PROJECT_DIR, 'startpage/index.html')\nCOOKIES_TXT = os.path.join(PROJECT_DIR, 'cookies.txt')\n\n\nlogging.getLogger(\"urllib3\").setLevel(logging.WARNING)\nlogging.basicConfig(format='[%(asctime)s] %(levelname)s:%(message)s',\n level=logging.INFO)\n\n\nWebsite = namedtuple('Website', ['id', 'name', 'url', 'zoom_level',\n 'user_agent', 'javascript', 'cookies', 'refresh'])\ndefault_website = {\n 'id': 0,\n 'name': \"Start Page\",\n 'url': 'file://%s' % START_PAGE,\n 'zoom_level': 1.0,\n 'user_agent': '',\n 'javascript': '',\n 'cookies': '',\n 'refresh': 0,\n}\n\n\nclass WebBrowser(Gtk.Window):\n\n def __init__(self):\n Gtk.Window.__init__(self)\n screen = Gdk.Screen.get_default()\n self.set_default_size(screen.get_width(), screen.get_height())\n # Hide scrollbars\n style_provider = Gtk.CssProvider()\n css = \"GtkScrollbar{background-color:#000;-GtkRange-slider-width:0;\" \\\n \"-GtkRange-trough-border:0;\" \\\n \"-GtkScrollbar-has-backward-stepper:false;\" \\\n \"-GtkScrollbar-has-forward-stepper:false}\"\n style_provider.load_from_data(css)\n Gtk.StyleContext.add_provider_for_screen(\n screen, style_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)\n\n self.fullscreen()\n\n self.connect(\"delete-event\", Gtk.main_quit)\n\n self.timeout_id = GObject.timeout_add(POLL_DELAY, self.update, None)\n\n self.session = WebKit.get_default_session()\n self.session.add_feature(Soup.CookieJar())\n\n self.webview = WebKit.WebView()\n self.webview.set_full_content_zoom(True)\n self.webview.connect_after('notify::load-status',\n self._on_load_finished)\n\n scrolled_window = Gtk.ScrolledWindow()\n scrolled_window.add(self.webview)\n self.add(scrolled_window)\n\n self.last_update = 0\n self.website = Website(**default_website)\n self.load_website()\n\n self.show_all()\n cursor = Gdk.Cursor.new(Gdk.CursorType.BLANK_CURSOR)\n self.get_window().set_cursor(cursor)\n\n def _on_load_finished(self, webview, pspec):\n if self.webview.props.load_status == WebKit.LoadStatus.COMMITTED:\n logging.info(\"Page load started: %s\", self.website.url)\n self.webview.set_zoom_level(1.0)\n if self.webview.props.load_status == WebKit.LoadStatus.FINISHED:\n logging.info(\"Page load finished: %s\", self.website.url)\n self.webview.set_zoom_level(self.website.zoom_level)\n if self.website.javascript:\n self.webview.execute_script(self.website.javascript)\n\n def load_website(self):\n with open(COOKIES_TXT, 'w+') as f:\n f.write(self.website.cookies)\n self.session.add_feature(Soup.CookieJarText.new(COOKIES_TXT, True))\n\n if self.website.user_agent:\n settings = self.webview.get_settings()\n settings.props.user_agent = self.website.user_agent\n self.webview.set_settings(settings)\n self.webview.load_uri(self.website.url)\n\n def update(self, user_data):\n try:\n headers = {'Authorization': 'ApiKey %s' % API_KEY}\n r = requests.get('%sdevice/status/' % API_URL, headers=headers)\n device_status = r.json()\n if device_status['updated_at'] > self.last_update:\n logging.info(\"Device status changed: %s\", device_status)\n self.last_update = device_status['updated_at']\n self.website = Website(**device_status['website'])\n self.load_website()\n else:\n logging.debug(\"Device status unchanged: %s\", device_status)\n except Exception as e:\n logging.exception(e)\n self.last_update = 0\n self.website = Website(**default_website)\n self.load_website()\n return True\n\n\nif __name__ == \"__main__\":\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n\n web_browser = WebBrowser()\n Gtk.main()\n","sub_path":"pannello_webkit/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"436388282","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport jobportal.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('jobportal', '0012_auto_20160314_0016'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='student',\n name='avatar',\n field=models.ImageField(default=b'media/avatar/sample_avatar.png', upload_to=jobportal.models.generate_profilepic_name),\n ),\n ]\n","sub_path":"jobportal/migrations/0013_auto_20160314_0025.py","file_name":"0013_auto_20160314_0025.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"351644485","text":"from ctypes import *\nfrom pegl.types import *\n\nclass test(Structure):\n pass\n\n\ntest._fields_ = [('a', c_int), ('b', c_char_p), ('c', c_int * 2)]\n\nt = test(a=10, b=\"hello\", c=(1, 2))\n\nq = test(a=20, b=\"hi\", c=(3, 4))\n\n# print(t._fields_)\ntestArr = test * 2\np = testArr(t, q)\nr = pointer(test(0))\n#print(r[0].a)\ny = pointer(t)\n\n\ndef ptrtest(ptr=POINTER(test)):\n if ptr is not None:\n tmpPtr = ptr\n # print(ptr[1].c[1])\n tmpPtr[0].c = (2, 3)\n return tmpPtr\n else:\n raise ValueError(\"NULL Pointer detected, cannot proceed\")\n\n\nx = ptrtest(p)\nptrtest(y)\n\n#ptrtest(None)\n\n#print(x[0].c[1])\n#print(y.contents.a)\n\n# v = POINTER(None)\n\n# cast(v, pointer(t))\n\nq = (EGLDeviceEXT * 1)()\n#print((cast(q, POINTER(EGLDeviceEXT))))\n\nprint((cast((EGLDeviceEXT*1)(), POINTER(EGLDeviceEXT))))\nprint(isinstance(cast((EGLDeviceEXT*1)(), POINTER(EGLDeviceEXT)),\n POINTER(EGLDeviceEXT)))\n\n\n","sub_path":"Support/ptrtest.py","file_name":"ptrtest.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"299747332","text":"#!/usr/bin/env python\n\nimport sys\nimport re\nimport numpy\n\ninfilename = 'input.txt'\nif len(sys.argv) > 2 and sys.argv[1] == '-i':\n infilename = sys.argv[2]\n\nprint('Using input file: %s' % infilename)\n\nf = open(infilename, 'r')\ndata = f.readlines()\nf.close()\n\ndata = sorted(data)\n\ndef add_sleep(guards, guard, start, end):\n if guard not in guards:\n guards[guard] = [0]* 60\n\n for min in range(start, end):\n guards[guard][min] += 1\n\n\non_duty = None\nsleep_time = None\nguards={}\nfor line in data:\n tokens = re.split(r\"[\\W']+\", line)\n\n YYYY, MM, DD, hh, mm = list(map(int, tokens[1:6]))\n\n if tokens[6] == 'Guard':\n if tokens[8] == 'begins':\n on_duty = tokens[7]\n else:\n print('ERROR: ', tokens)\n sys.exit(0)\n elif tokens[6] == 'falls':\n sleep_time = mm\n elif tokens[6] == 'wakes':\n wake_time = mm\n\n add_sleep(guards, on_duty, sleep_time, wake_time)\n else:\n 'ERROR:', tokens\n\n\ntotal_sleeps = {}\nmax_sleep = 0\nmax_guard = None\n\nmax_min_val = 0\nmax_min_min = None\nmax_min_guard = None\n\nfor guard, sleeps in list(guards.items()):\n total = sum(sleeps)\n if total >= max_sleep:\n max_sleep = total\n max_guard = guard\n\n maxmin = numpy.argmax(sleeps)\n if sleeps[maxmin] > max_min_val:\n max_min_guard = guard\n max_min_min = maxmin\n max_min_val = sleeps[maxmin]\n\nprint(max_guard)\nmax_min = numpy.argmax(guards[max_guard])\nprint(int(max_guard) * max_min)\n\n\nprint(int(max_min_guard) * max_min_min)\n","sub_path":"2018/04/puzzle.py","file_name":"puzzle.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"276619682","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 29 11:51:56 2018\n\n@author: Laura.Fiorentino\n\"\"\"\n\n\nimport mailroom_oo as moo\nimport sys\nimport datetime\nimport os\n\n\ndonor_list = moo.Donor_List()\ndonor_list.add_donation('Frank Reynolds', [10, 20, 50])\ndonor_list.add_donation('Dee Reynolds', [25, 100])\ndonor_list.add_donation('Dennis Reynolds', [10, 50])\ndonor_list.add_donation('Mac McDonald', [25, 35, 20])\ndonor_list.add_donation('Charlie Kelly', 0.25)\n\n\ndef view_donor(donor_list):\n name = input('Donor Name?>')\n while True:\n if donor_list.is_donor(name) is True:\n donor_list.donors[name].list_donations\n yn = input('Would you like to add a new donation? y/n>')\n if yn == 'y':\n new_donation = input('Donation Amount?>')\n donor_list.add_donation(name, new_donation)\n donor_list.donors[name].list_donations\n else:\n quit_program(donor_list)\n else:\n print('no such donor')\n break\n\n\ndef add_donor(donor_list):\n while True:\n name = input('Type Donor Name or q to quit?>')\n if name == 'q':\n quit_program(donor_list)\n else:\n donation = input('Donation Amount?>')\n donor_list.add_donation(name, donation)\n donor_list.donors[name].list_donations\n\n\ndef donor_data(donor_list):\n while True:\n arg_dict = {'1': moo.list_donors, '2': view_donor, '3': add_donor,\n '4': quit_program}\n task = input('Choose an action: [1] List Donors; '\n '[2] View Donor Information; '\n '[3] Add Donor; [4] Quit>')\n try:\n arg_dict[task](donor_list)\n except KeyError:\n print('Error: Please choose 1-4')\n\n\ndef create_letters(donor_list):\n while True:\n letter_choice = input('Who would you like to write a donation letter '\n 'to? (type a for all, q to quit)>')\n if letter_choice == 'a':\n all_letters(donor_list)\n quit_program(donor_list)\n elif letter_choice == 'q':\n quit_program(donor_list)\n elif donor_list.is_donor(letter_choice) is False:\n print('not a donor')\n else:\n donation_choice = input('What donation amount? Choose [L] for '\n 'latest donation,[A] for sum of all, '\n 'or type the amount.')\n print('writing letter to {}'.format(letter_choice))\n if donation_choice == 'L':\n donation = donor_list.donors[letter_choice].last_donation\n elif donation_choice == 'A':\n donation = donor_list.donors[letter_choice].total_donation\n else:\n donation = float(donation_choice)\n write_letter(letter_choice, donation)\n\n\ndef create_folder():\n now = datetime.datetime.now()\n new_path = os.path.join(os.getcwd(), 'letters_' + now.strftime('%d%m%Y'))\n if not os.path.exists(new_path):\n os.mkdir(new_path)\n return new_path, now\n\n\ndef all_letters(donor_list):\n print('writing all thank you letters...')\n for key in donor_list.donors.keys():\n write_letter(key, donor_list.donors[key].total_donation)\n\n\ndef write_letter(name, donation):\n new_path, now = create_folder()\n with open(os.path.join(new_path, name + '_' + now.strftime('%d%m%Y') +\n '.txt'), 'w') as letter_file:\n letter_file.write('Dear {}, \\n'\n 'Thank you so much for your generous '\n 'donation of ${:.2f} \\n'\n 'Sincerely, \\n'\n 'Laura F'.format(name, donation))\n\n\n\ndef quit_program(donor_list):\n sys.exit()\n\n\ndef main():\n print('----------Mailroom----------')\n print('WARNING: This is all CAPS senstive for now!!!!!!!!!!')\n arg_dict = {'1': donor_data, '2': create_letters,\n '3': moo.create_report, '4': quit_program}\n task = input('Choose an action: [1] Donor Database; ' \n '[2] Create Thank You Letters; [3] Create a Full Report; ' \n '[4] Quit>')\n try:\n arg_dict[task](donor_list)\n except KeyError:\n print('Error: Please choose 1-4')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"students/lauraannf/Lesson09/run_mailroom_oo.py","file_name":"run_mailroom_oo.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"340813664","text":"import logging\nfrom asyncio import Future\nfrom typing import Callable, Coroutine, Union, Generator, Optional, TypeVar, Any, List\n\nimport telethon\nfrom telethon import events, Button\nfrom telethon.tl.custom import message\nfrom telethon.tl.functions.channels import EditAdminRequest, GetFullChannelRequest\nfrom telethon.tl.functions.messages import MigrateChatRequest, GetScheduledHistoryRequest\nfrom telethon.tl.types import ChatAdminRights, ChannelParticipantsAdmins, ChannelParticipantCreator, ChannelForbidden, \\\n DocumentAttributeFilename\n\nfrom gif_pipeline.chat_data import ChatData, ChannelData, WorkshopData\nfrom gif_pipeline.message import MessageData\n\nR = TypeVar(\"R\")\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef message_data_from_telegram(msg: telethon.tl.custom.message.Message, scheduled: bool = False) -> MessageData:\n chat_id = chat_id_from_telegram(msg)\n sender_id = sender_id_from_telegram(msg)\n has_file = msg.file is not None and msg.web_preview is None\n forward_link = None\n if msg.forward and msg.forward.is_channel:\n if not isinstance(msg.forward.chat, ChannelForbidden):\n forward_link = f\"https://t.me/{msg.forward.chat.username}/{msg.forward.channel_post}\"\n return MessageData(\n chat_id,\n msg.id,\n msg.date,\n msg.text,\n msg.forward is not None,\n has_file,\n None,\n has_file and msg.file.mime_type,\n has_file and msg.file.size,\n msg.reply_to_msg_id,\n sender_id,\n scheduled,\n forward_link\n )\n\n\ndef chat_id_from_telegram(msg: telethon.tl.custom.message.Message) -> int:\n return msg.chat_id\n\n\ndef sender_id_from_telegram(msg: telethon.tl.custom.message.Message) -> int:\n return msg.sender_id\n\n\nclass TelegramClient:\n def __init__(self, api_id: int, api_hash: str, pipeline_bot_token: str = None, public_bot_token: str = None):\n self.client = telethon.TelegramClient('duplicate_checker', api_id, api_hash)\n self.client.start()\n self.pipeline_bot_id = None\n self.pipeline_bot_client = self.client\n if pipeline_bot_token:\n self.pipeline_bot_client = telethon.TelegramClient(\"duplicate_checker_pipeline_bot\", api_id, api_hash)\n self.pipeline_bot_client.start(bot_token=pipeline_bot_token)\n self.public_bot_client = self.client\n if public_bot_token:\n self.public_bot_client = telethon.TelegramClient('duplicate_checker_public_bot', api_id, api_hash)\n self.public_bot_client.start(bot_token=public_bot_token)\n self.message_cache = {}\n\n async def initialise(self) -> None:\n # Get dialogs list, to ensure entities are initialised in library\n await self.client.get_dialogs()\n pipeline_bot_user = await self.pipeline_bot_client.get_me()\n self.pipeline_bot_id = pipeline_bot_user.id\n\n def _save_message(self, msg: telethon.tl.custom.message.Message):\n # UpdateShortMessage events do not contain a populated msg.chat, so use msg.chat_id sometimes.\n chat_id = chat_id_from_telegram(msg)\n message_id = msg.id\n if chat_id not in self.message_cache:\n self.message_cache[chat_id] = {}\n self.message_cache[chat_id][message_id] = msg\n\n def _get_message(self, chat_id: int, message_id: int) -> Optional[telethon.tl.custom.message.Message]:\n if chat_id not in self.message_cache:\n return None\n return self.message_cache[chat_id].get(message_id)\n\n async def get_channel_data(self, handle: str) -> ChannelData:\n entity = await self.client.get_entity(handle)\n peer_id = telethon.utils.get_peer_id(entity)\n return ChannelData(peer_id, entity.username, entity.title)\n\n async def get_workshop_data(self, handle: str) -> WorkshopData:\n entity = await self.client.get_entity(handle)\n peer_id = telethon.utils.get_peer_id(entity)\n return WorkshopData(peer_id, entity.username, entity.title)\n\n async def iter_channel_messages(\n self,\n chat_data: ChatData,\n and_scheduled: bool = True\n ) -> Generator[MessageData, None, None]:\n async for msg in self.client.iter_messages(chat_data.chat_id):\n # Skip edit photo events.\n if msg.action.__class__.__name__ in ['MessageActionChatEditPhoto']:\n continue\n # Save message and yield\n self._save_message(msg)\n yield message_data_from_telegram(msg)\n if and_scheduled:\n async for msg_data in self.iter_scheduled_channel_messages(chat_data):\n yield msg_data\n\n async def iter_scheduled_channel_messages(self, chat_data: ChatData) -> Generator[MessageData, None, None]:\n # noinspection PyTypeChecker\n messages = await self.client(GetScheduledHistoryRequest(\n peer=chat_data.chat_id,\n hash=0\n ))\n for msg in messages.messages:\n self._save_message(msg)\n yield message_data_from_telegram(msg, scheduled=True)\n\n async def download_media(self, chat_id: int, message_id: int, path: str) -> Optional[str]:\n msg = self._get_message(chat_id, message_id)\n return await self.client.download_media(message=msg, file=path)\n\n def add_message_handler(self, function: Callable, chat_ids: List[int]) -> None:\n async def function_wrapper(event: events.NewMessage.Event):\n chat_id = chat_id_from_telegram(event.message)\n if chat_id not in chat_ids:\n logger.debug(\"Ignoring new message in other chat\")\n return\n sender_id = sender_id_from_telegram(event.message)\n if sender_id == self.pipeline_bot_id:\n logger.debug(\"Ignoring new message from bot\")\n return\n self._save_message(event.message)\n await function(event)\n\n self.client.add_event_handler(function_wrapper, events.NewMessage())\n\n def add_public_message_handler(self, function: Callable) -> None:\n async def function_wrapper(event: events.NewMessage.Event):\n await function(event)\n\n self.public_bot_client.add_event_handler(function_wrapper, events.NewMessage())\n\n def add_edit_handler(self, function: Callable, chat_ids: List[int]) -> None:\n async def function_wrapper(event: events.NewMessage.Event):\n chat_id = chat_id_from_telegram(event.message)\n if chat_id not in chat_ids:\n logger.debug(\"Ignoring new message in other chat\")\n return\n sender_id = sender_id_from_telegram(event.message)\n if sender_id == self.pipeline_bot_id:\n logger.debug(\"Ignoring new message from bot\")\n return\n self._save_message(event.message)\n await function(event)\n\n self.client.add_event_handler(function_wrapper, events.MessageEdited())\n\n def add_delete_handler(self, function: Callable) -> None:\n async def function_wrapper(event: events.MessageDeleted.Event):\n await function(event)\n # We don't need to delete from cache, and trying to do so is tough without chat id\n\n self.pipeline_bot_client.add_event_handler(function_wrapper, events.MessageDeleted())\n\n def add_callback_query_handler(self, function: Callable) -> None:\n async def function_wrapper(event: events.CallbackQuery.Event):\n await function(event)\n\n self.pipeline_bot_client.add_event_handler(function_wrapper, events.CallbackQuery())\n\n async def send_text_message(\n self,\n chat: ChatData,\n text: str,\n *,\n reply_to_msg_id: Optional[int] = None,\n buttons: Optional[List[List[Button]]] = None\n ) -> telethon.tl.custom.message.Message:\n return await self.pipeline_bot_client.send_message(\n chat.chat_id,\n text,\n reply_to=reply_to_msg_id,\n buttons=buttons,\n parse_mode=\"html\"\n )\n\n async def send_video_message(\n self,\n chat: ChatData,\n video_path: str,\n text: str = None,\n *,\n reply_to_msg_id: int = None,\n buttons: Optional[List[List[Button]]] = None,\n filename: Optional[str] = None\n ) -> telethon.tl.custom.message.Message:\n attributes = None\n if filename:\n attributes = [DocumentAttributeFilename(filename)]\n return await self.pipeline_bot_client.send_file(\n chat.chat_id,\n video_path,\n caption=text,\n reply_to=reply_to_msg_id,\n allow_cache=False,\n buttons=buttons,\n parse_mode=\"html\",\n attributes=attributes\n )\n\n async def delete_message(self, message_data: MessageData) -> None:\n await self.client.delete_messages(message_data.chat_id, message_data.message_id)\n\n async def forward_message(self, chat: ChatData, message_data: MessageData) -> telethon.tl.custom.message.Message:\n return await self.pipeline_bot_client.forward_messages(\n chat.chat_id,\n message_data.message_id,\n message_data.chat_id\n )\n\n async def edit_message(\n self,\n chat: ChatData,\n message_data: MessageData,\n new_text: str,\n new_buttons: Optional[List[List[Button]]] = None\n ):\n return await self.pipeline_bot_client.edit_message(\n chat.chat_id,\n message_data.message_id,\n new_text,\n buttons=new_buttons,\n parse_mode=\"html\"\n )\n\n def synchronise_async(self, future: Union[Future, Coroutine]) -> Any:\n return self.client.loop.run_until_complete(future)\n\n async def upgrade_chat_to_supergroup(self, chat_id: int) -> None:\n await self.client(MigrateChatRequest(chat_id=chat_id))\n\n async def invite_pipeline_bot_to_chat(self, chat_data: ChatData) -> None:\n if self.pipeline_bot_client == self.client:\n return\n users = await self.client.get_participants(chat_data.chat_id)\n user_ids = [user.id for user in users if user.username is not None]\n if self.pipeline_bot_id in user_ids:\n return\n pipeline_bot_entity = await self.pipeline_bot_client.get_me()\n await self.client(EditAdminRequest(\n chat_data.chat_id,\n pipeline_bot_entity.username,\n ChatAdminRights(\n post_messages=True,\n edit_messages=True,\n delete_messages=True\n ),\n \"Helpful bot\"\n ))\n\n async def user_can_post_in_chat(self, user_id: int, chat_data: ChatData) -> bool:\n permissions = await self.client.get_permissions(chat_data.chat_id, user_id)\n return permissions.post_messages\n\n async def user_can_delete_in_chat(self, user_id: int, chat_data: ChatData) -> bool:\n permissions = await self.client.get_permissions(chat_data.chat_id, user_id)\n return permissions.delete_messages\n\n async def get_subscriber_count(self, chat_data: ChatData) -> int:\n entity = await self.client.get_entity(chat_data.chat_id)\n channel_full_info = await self.client(GetFullChannelRequest(channel=entity))\n return channel_full_info.full_chat.participants_count\n","sub_path":"gif_pipeline/telegram_client.py","file_name":"telegram_client.py","file_ext":"py","file_size_in_byte":11389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"302696250","text":"# !/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : bidirectional_recurrent_neural_network.py\n@Time : 2020/01/13 15:50:27\n@Author : LY \n@Version : 1.0\n@URL : https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/02-intermediate/bidirectional_recurrent_neural_network/main.py# L39-L58\n@License : (C)Copyright 2017-2020\n@Desc : 引入一种需要同时考虑下一个时间步和上一个时间步的信息来做当前时间步决定的结构:\n 有2层隐藏层,其中每个隐藏层都连接到输出和输入。这2个隐藏层可以微分,且都有自\n 循环连接,不过一个是朝着下一个时间步连接的,另一个是朝着上一个时间步连接的\n'''\n# here put the import lib\nimport torch\nimport torch.nn as nn\nimport torchvision \nimport torchvision.transforms as transforms\n\n# Device configuration\ndevice = torch.device( 'cuda' if torch.cuda.is_available() else 'cpu' )\n\n# Hyper-parameters\nsequence_length = 28\ninput_size = 28\nhidden_size = 128\nnum_layers = 2\nnum_classes = 10\nbatch_size = 100\nnum_epochs = 2\nlearning_rate = 0.003\n\n# MNIST dataset\ntrain_dataset = torchvision.datasets.MNIST( root='./data',\n train=True,\n transform=transforms.ToTensor(),\n download=True )\ntest_dataset = torchvision.datasets.MNIST( root='./data',\n train=False,\n transform=transforms.ToTensor() )\n\n# Data loader\ntrain_loader = torch.utils.data.DataLoader( dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True )\ntest_loader = torch.utils.data.DataLoader( dataset=test_dataset,\n batch_size=batch_size,\n shuffle=False )\n\n# Bidirectional recurrent neural network( many-to-one )\nclass BiRNN( nn.Module ):\n def __init__( self, input_size, hidden_size, num_layers, num_classes ):\n super( BiRNN, self ).__init__()\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.lstm = nn.LSTM( input_size, hidden_size, num_layers, batch_first=True, bidirectional=True )\n self.fc = nn.Linear( hidden_size*2, num_classes ) # 2 for bidirection\n\n def forward( self, x ):\n # Set initial state\n h0 = torch.zeros( self.num_layers*2, x.size(0), self.hidden_size ).to( device )\n c0 = torch.zeros( self.num_layers*2, x.size(0), self.hidden_size ).to( device )\n\n # Forward propagate LSTM\n out, _ = self.lstm( x, ( h0, c0 ) ) # out: tensor of shape (batch_size, seq_length, hidden_size*2)\n\n # Decode the hidden state of the last time step\n out = self.fc( out[ :, -1, : ] )\n return out\n\nmodel = BiRNN( input_size, hidden_size, num_layers, num_classes ).to( device )\n\n# Loss and optimize\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam( model.parameters(), lr=learning_rate )\n\n# Train the model\ntotal_step = len( train_loader )\nfor epoch in range( num_epochs ):\n for i, ( images, labels ) in enumerate( train_loader ):\n images = images.reshape( -1, sequence_length, input_size ).to( device )\n labels = labels.to( device )\n\n # Forward pass\n outputs = model( images )\n loss = criterion( outputs, labels )\n\n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n\n if ( i+1 ) % 100 == 0:\n print( 'Epoch[{}/{}], Step[{}/{}], loss:'\n .format( epoch+1, num_epochs, i+1, total_step, loss.item() ))\n\n# Test the model\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in test_loader:\n images = images.reshape( -1, sequence_length, input_size ).to( device )\n labels = labels.to( device )\n outputs = model( images )\n _, predicted = torch.max( outputs.data, 1 )\n total += labels.size(0)\n correct += ( predicted == labels ).sum().item()\n\n print( 'Test accuracy {}%'.format( 100*correct/total ) ) ","sub_path":"12-1-pytorch-tutorial/bidirectional_recurrent_neural_network.py","file_name":"bidirectional_recurrent_neural_network.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"123135395","text":"# -*- coding: utf-8 -*-\n\n\n# -------------------------------------\n# basic unit\n# -------------------------------------\nPT = 1.0 # basic unit\nITP = 72.0 # inch to point\n\nMAJOR_DIST = 5.0 * PT # significant distance exists between two block lines\nMINOR_DIST = 1.0 * PT # small distance\nTINY_DIST = 0.5 * PT # very small distance\n\nFACTOR_SAME = 0.99\nFACTOR_ALMOST = 0.95\nFACTOR_MOST = 0.90\nFACTOR_MAJOR = 0.75\nFACTOR_A_HALF = 0.5\nFACTOR_A_FEW = 0.1\nFACTOR_FEW = 0.01\n\n\n# -------------------------------------\n# docx\n# -------------------------------------\nHIDDEN_W_BORDER = 0.0 # do not show border\nMIN_LINE_SPACING = 0.7 # minimum line spacing available in MS word\nDEFULT_LINE_SPACING = 1.02\n\n# punctuation implying end of a sentense\nSENTENSE_END_PUNC = '..。??!!'\n\n\n# -------------------------------------\n# font parameters\n# -------------------------------------\n\n# CJK font definition parameters\nCJK_CODEPAGE_BITS = {\n \"JIS/Japan\": 17,\n \"Chinese: Simplified chars—PRC and Singapore\": 18,\n \"Korean Wansung\": 19,\n \"Chinese: Traditional chars—Taiwan and Hong Kong\": 20,\n \"Korean Johab\": 21\n}\n\nCJK_UNICODE_RANGE_BITS = {\n 'Hangul Jamo': 28,\n 'Hiragana': 49,\n 'Katakana': 50,\n 'Bopomofo': 51,\n 'Hangul Compatibility Jamo': 52,\n 'Enclosed CJK Letters And Months': 54,\n 'CJK Compatibility': 55,\n 'Hangul Syllables': 56,\n 'CJK Unified Ideographs': 59,\n 'CJK Strokes': 61,\n 'Yi Syllables': 83\n}\n\nCJK_UNICODE_RANGES = [\n [0x1100, 0x11FF], # Hangul Jamo\n [0x3040, 0x309F], # Hiragana\n [0x30A0, 0x30FF], # Katakana\n [0x31F0, 0x31FF], # Katakana Phonetic Extensions\n [0x3100, 0x312F], # Bopomofo\n [0x31A0, 0x31BF], # Bopomofo Extended (Bopomofo)\n [0x3130, 0x318F], # Hangul Compatibility Jamo\n [0x3200, 0x32FF], # Enclosed CJK Letters and Months\n [0x3300, 0x33FF], # CJK Compatibility\n [0xAC00, 0xD7AF], # Hangul Syllables\n [0x4E00, 0x9FFF], # CJK Unified Ideographs\n [0x2E80, 0x2EFF], # CJK Radicals Supplement (CJK Unified Ideographs)\n [0x2F00, 0x2FDF], # Kangxi Radicals (CJK Unified Ideographs)\n [0x2FF0, 0x2FFF], # Ideographic Description Characters (CJK Unified Ideographs)\n [0x3400, 0x4DBF], # CJK Unified Ideographs Extension A (CJK Unified Ideographs)\n [0x20000, 0x2A6DF], # CJK Unified Ideographs Extension B (CJK Unified Ideographs)\n [0x3190, 0x319F], # Kanbun (CJK Unified Ideographs)\n [0x31C0, 0x31EF], # CJK Strokes\n [0xF900, 0xFAFF], # CJK Compatibility Ideographs (CJK Strokes)\n [0x2F800, 0x2FA1F], # CJK Compatibility Ideographs Supplement (CJK Strokes)\n [0xA000, 0xA48F], # Yi Syllables\n [0xA490, 0xA4CF], # Yi Radicals\n]\n\nDEFAULT_FONT_NAME = 'Arial'\n\n# default font name and line height ratio, e.g. PDF base 14 fonts\n# https://appligent.com/what-are-the-base-14-fonts/\nDICT_FONT_LINE_HEIGHT = {\n 'Agency FB': 1.18,\n 'Algerian': 1.32,\n 'Angsana New': 1.35,\n 'Book Antiqua': 1.24,\n 'Arial': 1.15,\n 'Arial Narrow': 1.15,\n 'Arial Black': 1.41,\n 'Arial Rounded MT Bold': 1.16,\n 'Bahnschrift': 1.2,\n 'Barlow Condensed': 1.35,\n 'Baskerville Old Face': 1.14,\n 'Bauhaus 93': 1.46,\n 'Bell MT': 1.13,\n 'Bernard MT Condensed': 1.19,\n 'Aharoni': 1.06,\n 'Andalus': 1.53,\n 'AngsanaUPC': 1.35,\n 'Aparajita': 1.18,\n 'Arabic Typesetting': 1.15,\n 'Arial Monospaced': 1.15,\n 'Batang': 1.3,\n 'Browallia New': 1.25,\n 'DaunPenh': 1.36,\n 'David': 1.0,\n 'DFKai': 1.3,\n 'DilleniaUPC': 1.3,\n 'DokChampa': 1.94,\n 'Estrangelo Edessa': 1.0,\n 'EucrosiaUPC': 1.22,\n 'Euphemia': 1.35,\n 'FangSong': 1.3,\n 'FrankRuehl': 1.0,\n 'Gisha': 1.17,\n 'Gulim': 1.3,\n 'IrisUPC': 1.26,\n 'Iskoola Pota': 1.14,\n 'JasmineUPC': 1.06,\n 'KaiTi': 1.3,\n 'Kalinga': 1.58,\n 'Kartika': 1.0,\n 'Khmer UI': 1.13,\n 'KodchiangUPC': 0.98,\n 'Kokila': 1.15,\n 'Lao UI': 1.33,\n 'Latha': 1.66,\n 'Leelawadee': 1.2,\n 'Levenim MT': 1.4,\n 'LilyUPC': 0.95,\n 'Mangal': 1.68,\n 'Microsoft Uighur': 1.08,\n 'Miriam Fixed': 1.0,\n 'Miriam': 1.06,\n 'MS PMincho': 1.3,\n 'Nyala': 1.04,\n 'Plantagenet Cherokee': 1.32,\n 'Raavi': 1.79,\n 'Sakkal Majalla': 1.4,\n 'SAPDings': 1.0,\n 'Shonar Bangla': 1.29,\n 'Shruti': 1.83,\n 'SimHei': 1.3,\n 'Simplified Arabic Fixed': 1.09,\n 'Simplified Arabic': 1.66,\n 'Terminal': 1.06,\n 'Traditional Arabic': 1.49,\n 'Tunga': 1.77,\n 'Utsaah': 1.12,\n 'Vani': 1.68,\n 'Vrinda': 1.02,\n 'Yu Gothic Light': 1.43,\n 'Bodoni MT': 1.2,\n 'Bodoni MT Black': 1.17,\n 'Bodoni MT Condensed': 1.18,\n 'Bodoni MT Poster Compressed': 1.15,\n 'Bookman Old Style': 1.17,\n 'Bradley Hand ITC': 1.25,\n 'Britannic Bold': 1.11,\n 'Berlin Sans FB': 1.1,\n 'Berlin Sans FB Demi': 1.13,\n 'Broadway': 1.13,\n 'BrowalliaUPC': 1.25,\n 'Brush Script MT': 1.23,\n 'Bookshelf Symbol 7': 1.0,\n 'Calibri': 1.22,\n 'Californian FB': 1.14,\n 'Calisto MT': 1.15,\n 'Cambria': 1.17,\n 'Candara': 1.22,\n 'Cascadia Mono': 1.32,\n 'Castellar': 1.21,\n 'Caveat': 1.28,\n 'Century Schoolbook': 1.2,\n 'Centaur': 1.14,\n 'Century': 1.2,\n 'Chiller': 1.15,\n 'Code': 1.0,\n 'Colonna MT': 1.06,\n 'Comic Sans MS': 1.39,\n 'Consolas': 1.17,\n 'Constantia': 1.22,\n 'Cooper Black': 1.15,\n 'Copperplate Gothic Bold': 1.11,\n 'Copperplate Gothic Light': 1.1,\n 'Corbel': 1.22,\n 'Corbel Light': 1.22,\n 'Cormorant Infant': 1.22,\n 'Courier': 1.04,\n 'Courier New': 1.13,\n 'Curlz MT': 1.33,\n 'Dosis': 1.36,\n 'Dubai': 1.69,\n 'Ebrima': 1.28,\n 'Elephant': 1.29,\n 'Engravers MT': 1.16,\n 'Eras Bold ITC': 1.16,\n 'Eras Demi ITC': 1.15,\n 'Eras Light ITC': 1.13,\n 'Eras Medium ITC': 1.14,\n 'Felix Titling': 1.17,\n 'Forte': 1.36,\n 'Franklin Gothic': 1.13,\n 'Freestyle Script': 1.18,\n 'French Script MT': 1.14,\n 'Footlight MT Light': 1.06,\n 'Gabriola': 1.84,\n 'Gadugi': 1.33,\n 'Garamond': 1.12,\n 'Georgia': 1.14,\n 'Gigi': 1.38,\n 'Gill Sans MT': 1.16,\n 'Gill Sans MT Condensed': 1.2,\n 'Gill Sans Ultra Bold Condensed': 1.25,\n 'Gill Sans Ultra Bold': 1.25,\n 'Gloucester MT Extra Condensed': 1.16,\n 'Gill Sans MT Ext Condensed Bold': 1.2,\n 'Century Gothic': 1.23,\n 'Goudy Old Style': 1.2,\n 'Goudy Stout': 1.37,\n 'Harlow Solid Italic': 1.26,\n 'Harrington': 1.18,\n 'Haettenschweiler': 1.07,\n 'Helvetica': 1.18,\n 'Microsoft Himalaya': 1.0,\n 'HoloLens MDL2 Assets': 1.0,\n 'High Tower Text': 1.16,\n 'Impact': 1.22,\n 'Imprint MT Shadow': 1.18,\n 'Informal Roman': 1.2,\n 'Ink Free': 1.24,\n 'Blackadder ITC': 1.28,\n 'Edwardian Script ITC': 1.18,\n 'Kristen ITC': 1.36,\n 'Javanese Text': 2.27,\n 'Jokerman': 1.51,\n 'Juice ITC': 1.19,\n 'Kunstler Script': 1.09,\n 'Wide Latin': 1.23,\n 'Lato': 1.2,\n 'Lucida Bright': 1.18,\n 'Lucida Calligraphy': 1.36,\n 'Leelawadee UI': 1.33,\n 'Leelawadee UI Semilight': 1.33,\n 'Lucida Fax': 1.18,\n 'Lucida Handwriting': 1.38,\n 'Lucida Sans': 1.18,\n 'Lucida Sans Typewriter': 1.17,\n 'Lucida Console': 1.0,\n 'Lucida Sans Unicode': 1.54,\n 'Magneto': 1.21,\n 'Maiandra GD': 1.2,\n 'Malgun Gothic': 1.73,\n 'Malgun Gothic Semilight': 1.73,\n 'Marlett': 1.0,\n 'Matura MT Script Capitals': 1.33,\n 'Microsoft Sans Serif': 1.13,\n 'Mistral': 1.22,\n 'Myanmar Text': 1.9,\n 'Modern No. 20': 1.07,\n 'Mongolian Baiti': 1.15,\n 'Montserrat': 1.38,\n 'Microsoft Yi Baiti': 1.3,\n 'Monotype Corsiva': 1.12,\n 'MT Extra': 1.01,\n 'MV Boli': 1.61,\n 'Niagara Engraved': 1.07,\n 'Niagara Solid': 1.07,\n 'Nirmala UI': 1.33,\n 'Nirmala UI Semilight': 1.33,\n 'Noto Sans': 1.36,\n 'Noto Serif': 1.36,\n 'Microsoft New Tai Lue': 1.31,\n 'OCR A Extended': 1.03,\n 'Old English Text MT': 1.22,\n 'Onyx': 1.15,\n 'Open Sans': 1.36,\n 'Oswald': 1.7,\n 'MS Outlook': 1.04,\n 'Palatino Linotype': 1.35,\n 'Palace Script MT': 0.93,\n 'Papyrus': 1.57,\n 'Parchment': 1.07,\n 'Perpetua': 1.15,\n 'Perpetua Titling MT': 1.18,\n 'Microsoft PhagsPa': 1.52,\n 'Playbill': 1.01,\n 'Poor Richard': 1.13,\n 'Pristina': 1.31,\n 'Rage Italic': 1.26,\n 'Raleway': 1.17,\n 'Ravie': 1.33,\n 'MS Reference Sans Serif': 1.58,\n 'MS Reference Specialty': 1.23,\n 'Roboto': 1.2,\n 'Roboto Slab': 1.35,\n 'Rockwell Condensed': 1.18,\n 'Rockwell': 1.17,\n 'Script MT Bold': 1.2,\n 'Segoe MDL2 Assets': 1.0,\n 'Segoe Print': 1.77,\n 'Segoe Script': 1.61,\n 'Segoe UI': 1.33,\n 'Segoe UI Light': 1.33,\n 'Segoe UI Semilight': 1.33,\n 'Segoe UI Black': 1.33,\n 'Segoe UI Emoji': 1.22,\n 'Segoe UI Historic': 1.33,\n 'Segoe UI Semibold': 1.33,\n 'Segoe UI Symbol': 1.73,\n 'Showcard Gothic': 1.24,\n 'SimSun': 1.3,\n 'LiSu': 1.3,\n 'YouYuan': 1.3,\n 'STCaiyun': 1.35,\n 'STFangsong': 1.69,\n 'STHupo': 1.34,\n 'STKaiti': 1.69,\n 'STLiti': 1.38,\n 'STSong': 1.69,\n 'STXihei': 1.79,\n 'STXingkai': 1.42,\n 'STXinwei': 1.35,\n 'STZhongsong': 1.72,\n 'Snap ITC': 1.29,\n 'Source Sans Pro Black': 1.26,\n 'Source Sans Pro': 1.26,\n 'Source Sans Pro ExtraLight': 1.26,\n 'Source Sans Pro Light': 1.26,\n 'Source Sans Pro SemiBold': 1.26,\n 'Stencil': 1.19,\n 'Sylfaen': 1.32,\n 'Symbol': 1.23,\n 'Tahoma': 1.21,\n 'Microsoft Tai Le': 1.27,\n 'Tw Cen MT': 1.09,\n 'Tw Cen MT Condensed': 1.07,\n 'Tw Cen MT Condensed Extra Bold': 1.08,\n 'Tempus Sans ITC': 1.3,\n 'Times': 1.15,\n 'Times New Roman': 1.15,\n 'Trebuchet MS': 1.16,\n 'Verdana': 1.22,\n 'Viner Hand ITC': 1.61,\n 'Vivaldi': 1.22,\n 'Vladimir Script': 1.21,\n 'Webdings': 1.0,\n 'Wingdings': 1.11,\n 'Wingdings 2': 1.05,\n 'Wingdings 3': 1.14,\n 'Zilla Slab': 1.2\n}","sub_path":"venv/Lib/site-packages/pdf2docx/common/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":9809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"25334481","text":"#!/usr/bin/python\nimport sys\nimport re\nimport os.path\nfrom subprocess import Popen, PIPE\nfrom ctypes import *\n\nlpal_hndl = CDLL(\"libpal.so\")\n\nPOST_CODE_FILE = \"/tmp/post_code_buffer.bin\"\nIPMIUTIL = \"/usr/local/fbpackages/ipmi-util/ipmi-util\"\n\nboot_order_device = { 0: \"USB Device\", 1: \"IPv4 Network\", 9: \"IPv6 Network\", 2: \"SATA HDD\", 3: \"SATA-CDROM\", 4: \"Other Removalbe Device\", 255: \"Reserved\" }\nsupported_commands = [\"boot_order\", \"postcode\"]\n\ndef pal_print_postcode(fru):\n postcodes = (c_ubyte * 256)()\n plen = c_ushort(0)\n ret = lpal_hndl.pal_get_80port_record(fru, 0, 0, byref(postcodes), byref(plen))\n if ret != 0:\n print(\"Error %d returned by get_80port\" % (ret))\n return\n for i in range(0, plen.value):\n sys.stdout.write(\"%02X \" % (postcodes[i]))\n sys.stdout.flush()\n if (i%16 == 15):\n sys.stdout.write(\"\\n\")\n sys.stdout.flush()\n if plen.value % 16 != 0:\n sys.stdout.write(\"\\n\")\n sys.stdout.flush()\n\ndef pal_get_fru_id(fruname):\n fruid = c_ubyte(0)\n ret = lpal_hndl.pal_get_fru_id(fruname.encode('ascii'), byref(fruid))\n if (ret != 0):\n return ret\n return fruid.value\n\ndef pal_is_slot_server(fru):\n ret = lpal_hndl.pal_is_slot_server(c_ubyte(fru))\n if ret != 1:\n return False\n return True\n\ndef usage():\n print(\"Usage: bios-util FRU [ boot_order, postcode ] \")\n exit(-1)\n \ndef usage_boot_order():\n print(\"Usage: bios-util FRU boot_order --clear_CMOS <--enable, --disable, --get>\")\n print(\" --force_boot_BIOS_setup <--enable, --disable, --get>\")\n print(\" --boot_order [ --set < #1st #2nd #3rd #4th #5th >, --get, --disable ]\")\n print(\" *\" + repr(boot_order_device))\n exit(-1)\n\ndef usage_postcode():\n print(\"Usage: bios-util postcode --get\")\n exit(-1)\n\ndef execute_IPMI_command(fru, netfn, cmd, req):\n netfn = (netfn << 2)\n\n sendreqdata = \"\"\n if ( req != \"\" ):\n for i in range(0, len(req), 1):\n sendreqdata += str(req[i]) + \" \"\n\n input = IPMIUTIL + \" \" + str(fru) + \" \" + str(netfn) + \" \" + str(cmd) + \" \" + sendreqdata\n data=''\n\n output = Popen(input, shell=True, stdout=PIPE)\n (data, err) = output.communicate()\n data = data.decode()\n result = data.strip().split(\" \")\n\n if ( output.returncode != 0 ):\n print(\"ipmi-util execute fail..., please check ipmid.\")\n exit(-1) \n\n if ( int(result[2], 16) != 0 ):\n print(\"IPMI Failed, CC Code:%s\" % result[2])\n exit(0)\n \n return result[3:]\n \ndef status_decode(input):\n if ( input == 1 ):\n return \"Enabled\"\n else:\n return \"Disabled\"\n \ndef status_N_decode(input):\n if ( input == 1 ):\n return \"Disabled\"\n else:\n return \"Enabled\"\n\ndef trans2opcode(input):\n if ( input == \"--enable\" ):\n return 1\n else:\n return 0\n\n'''\nOEM Set BIOS Boot Order (NetFn:0x30, CMD: 0x52h)\nRequest:\n Byte 1 - Boot mode\n Bit 0 - 0 : Legacy, 1 : UEFI\n Bit 1 - CMOS clear (Optional, BIOS implementation dependent)\n Bit 2 - Force Boot into BIOS Setup (Optional, BIOS implementation dependent)\n Bit 6:3 - reserved\n Bit 7 - boot flags valid\n Byte 2-6 - Boot sequence\n Bit 2:0 - boot device id\n 000b: USB device\n 001b: Network\n 010b: SATA HDD\n 011b: SATA-CDROM\n 100b: Other removable Device\n Bit 7:3 - reserve for boot device special request\n If Bit 2:0 is 001b (Network), Bit3 is IPv4/IPv6 order\n Bit3=0b: IPv4 first\n Bit3=1b: IPv6 first\nResponse:\nByte1 - Completion Code\n'''\ndef boot_order(fru, argv):\n req_data = [\"\"]\n function = argv[2]\n option = argv[3]\n boot_flags_valid = 1 \n\n result = execute_IPMI_command(fru, 0x30, 0x53, \"\")\n \n data = [int(n, 16) for n in result]\n \n clear_CMOS = ((data[0] & 0x2) >> 1)\n force_boot_BIOS_setup = ((data[0] & 0x4) >> 2)\n boot_order = data[1:]\n \n if ( option == \"--get\" ):\n if ( function == \"--boot_order\" ):\n try:\n print(\"Boot Order: \" + \", \".join(boot_order_device[dev] for dev in boot_order))\n except KeyError:\n print(\"Invalid Boot Device ID!\")\n print(boot_order_device)\n elif ( function == \"--clear_CMOS\" ):\n print(\"Clear CMOS Function: \" + status_decode(clear_CMOS))\n exit(0)\n elif ( function == \"--force_boot_BIOS_setup\" ):\n print(\"Force Boot to BIOS Setup Function: \" + status_decode(force_boot_BIOS_setup))\n exit(0)\n else:\n usage_boot_order() \n elif ( option == \"--enable\" ):\n if ( function == \"--clear_CMOS\" ):\n clear_CMOS = trans2opcode(option)\n elif ( function == \"--force_boot_BIOS_setup\" ):\n force_boot_BIOS_setup = trans2opcode(option)\n else:\n usage_boot_order()\n\n elif ( option == \"--disable\" ):\n if ( function == \"--clear_CMOS\" ):\n clear_CMOS = trans2opcode(option)\n elif ( function == \"--force_boot_BIOS_setup\" ):\n force_boot_BIOS_setup = trans2opcode(option)\n elif ( function != \"--boot_order\" ):\n usage_boot_order()\n \n #Clear the 7th valid bit for disable clean CMOS, force boot to BIOS setup, and set boot order action\n boot_flags_valid = 0\n\n elif ( option == \"--set\" ):\n if ( function == \"--boot_order\" ):\n if ( len(argv) < 9 ):\n usage_boot_order() \n \n set_boot_order = argv[4:]\n for num in set_boot_order:\n if ( not int(num) in boot_order_device ):\n print(\"Invalid Boot Device ID!\")\n usage_boot_order()\n boot_order = set_boot_order\n else:\n usage_boot_order()\n\n else:\n usage_boot_order() \n \n req_data[0] = ((((data[0] & ~0x86) | (clear_CMOS << 1)) | (force_boot_BIOS_setup << 2)) | (boot_flags_valid << 7) )\n req_data[1:] = boot_order\n \n execute_IPMI_command(fru, 0x30, 0x52, req_data)\n\ndef postcode(fru):\n if os.path.isfile(POST_CODE_FILE):\n postcode_file = open(POST_CODE_FILE, 'r')\n print(postcode_file.read())\n else:\n pal_print_postcode(fru)\n\ndef bios_main_fru(fru, command):\n if ( command == \"boot_order\" ):\n if ( len(sys.argv) < 5 ):\n usage_boot_order()\n else:\n boot_order(fru, sys.argv[1:])\n elif ( command == \"postcode\" ):\n if ( len(sys.argv) != 4 ) or ( sys.argv[3] != \"--get\" ):\n usage_postcode()\n else:\n postcode(fru)\n\ndef bios_main():\n if ( len(sys.argv) < 3 ):\n usage()\n fruname = sys.argv[1]\n command = sys.argv[2]\n\n if command not in supported_commands:\n usage()\n return\n\n if fruname == \"all\":\n frulist_c = create_string_buffer(128)\n ret = lpal_hndl.pal_get_fru_list(frulist_c)\n if ret:\n print(\"Getting fru list failed!\")\n return\n frulist_s = frulist_c.value.decode()\n frulist = re.split(r',\\s', frulist_s)\n for fruname in frulist:\n fru = pal_get_fru_id(fruname)\n if fru >= 0:\n if pal_is_slot_server(fru) == True:\n print (\"%s:\" % (fruname))\n bios_main_fru(fru, command)\n else:\n fru = pal_get_fru_id(fruname)\n if fru < 0:\n print(\"%s is not a known FRU on this platform\" % (fruname))\n return\n if pal_is_slot_server(fru) == False:\n print(\"%s is not a server\" % (fruname))\n return\n bios_main_fru(fru, command)\n \nif ( __name__ == '__main__' ):\n bios_main()\n","sub_path":"common/recipes-core/bios-util/files/bios-util.py","file_name":"bios-util.py","file_ext":"py","file_size_in_byte":7805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"639698094","text":"import argparse\n\nfrom config import Config\nfrom nltk.tokenize import sent_tokenize\nfrom predictors.svm_predictor import SVMPredictor\nfrom tqdm import tqdm\n\n\ndef tag_dialogues(tagger, dialogues, output_path):\n with open(output_path, \"w\") as tagger_output_file:\n\n dialog_das = []\n prev_num_turns = 0\n for dialog in tqdm(dialogues):\n turns = dialog.split(\"_eos\")\n\n num_turns = len(turns) - 1\n\n if num_turns < prev_num_turns:\n dialog_das = []\n\n\n turn_das = []\n turn = turns[num_turns - 1]\n\n for sent in sent_tokenize(turn):\n turn_das += [da[\"communicative_function\"] for da in tagger.dialogue_act_tag(sent)]\n dialog_das.append(\" \".join(turn_das))\n\n output = \" _eos \".join(dialog_das)\n # print(output)\n tagger_output_file.write(output + \"\\n\")\n prev_num_turns = num_turns\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--src',\n type=str,\n required=True,\n help=\"Source file to annotate\")\n parser.add_argument(\"--dst\",\n type=str,\n required=True,\n help=\"Destination file to save annotation results\")\n parser.add_argument('--model_path',\n type=str,\n default=\"models/Model.SVM/meta.json\",\n help=\"Path to SVM tagger model\")\n args = parser.parse_args()\n cfg = Config.from_json(args.model_path)\n\n\n tagger = SVMPredictor(cfg)\n\n with open(args.src, \"r\") as valid_file:\n dialogues = [line.strip() for line in valid_file]\n\n tagger_outputs = tag_dialogues(tagger, dialogues, args.dst)","sub_path":"tag_data_source.py","file_name":"tag_data_source.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"412470860","text":"#!/usr/bin/env python\n\"\"\"\n------------------------------------------------------------------------\n class for calculating the threshold time shift synchrony (TTSS).\n \n Tries to \"intelligently\" handle regions of nan.\n Some graphical debug utilities.\n \n------------------------------------------------------------------------\n\"\"\"\nimport glob\nimport os\n\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\n\nfrom enum import Enum \nimport unittest\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n'''\nIf you want to set the logging level from a command-line option such as:\n --log=INFO\n'''\n\n#------------------\nclass Sync:\n \"\"\" Synchrony calculation \n Class for storing raw data and synchrony based results. Contains methods \n for multiple algorithms.\n \n \n \"\"\"\n \n #-------------------------------\n def __init__(self, X_, Y_):\n self.SAMPLE_RATE = 15\n self.X = np.array(X_)\n self.Y = np.array(Y_)\n \n assert (len(X_) == len(Y_)), 'X and Y array sizes are different'\n \n self.X_quant = []\n self.Y_quant = []\n \n self.THRESH = 0\n \n #-------------------------------\n def quantize_data(self, THRESH_):\n \"\"\" for X and Y, determines whether each value is > THRESH, \n and puts result into self.X_quant and self.Y_quant\n \"\"\"\n self.THRESH = THRESH_\n \n self.X_quant = np.zeros_like(self.X, float)\n for t, x in enumerate(self.X):\n if np.isnan(x): \n self.X_quant[t] = np.nan\n else:\n self.X_quant[t] = x > self.THRESH\n \n \n self.Y_quant = np.zeros_like(self.Y, float)\n for t, y in enumerate(self.Y):\n if np.isnan(y): \n self.Y_quant[t] = np.nan\n else:\n self.Y_quant[t] = y > self.THRESH\n \n #-------------------------------\n def calculate_corr_sync(self, slot_size_=22, max_time_shift_=37):\n \"\"\" Splits X into slots. For each X slot, calculates the correlation\n with every Y slots following the X slot time up to max_time_shift.\n -------------------------------\n return value: \n x2y_sync, y2x_sync \n \"\"\"\n pass\n \n #------------------------------- \n def calc_edge_trig_sync(self, THRESH_, max_time_shift_=37):\n \"\"\" given raw data stored in X and Y, calculates synchrony using\n the \"edge triggered algorithm. In turn treats X as the sender\n and Y as the receiver, then Y as the sender, X as the receiver.\n For each sender rising edge, checks if there is any positive \n in Y in the max_time_shift following the time at X rising edge.\n \n Maybe it is better to set up an ignore region in the sender\n after each share match (if y_last > t, ignore t)?\n --------------------------\n return value: \n x2y_sync, y2x_sync\n \"\"\"\n \n logging.debug('...calc_edge_trig_sync()')\n \n self.quantize_data(THRESH_)\n \n # find rising edges in X\n x_rising_edges = [] # list of times where there is a rising edge\n x_last = 0\n for t, x in enumerate (self.X_quant):\n # is it a rising edge\n if ( (x_last == 0) and (x == 1) ):\n x_rising_edges.append(t) \n #logging.debug('x rising edge at t :' + str(t))\n x_last = x\n logging.debug('x rising edge cnt:' + str(len(x_rising_edges)))\n \n # find rising edges in Y\n y_rising_edges = []\n y_last = 0\n for t, y in enumerate (self.Y_quant):\n # is it a rising edge\n if ( (y_last == 0) and (y == 1) ): \n y_rising_edges.append(t) \n #logging.debug('y rising edge at t :' + str(t))\n y_last = y\n logging.debug('y rising edge cnt:' + str(len(y_rising_edges)))\n \n # count y follows x\n x2y_shared_cnt = 0\n y_last_abs = 0\n for t in x_rising_edges:\n # make sure to ignore previous y==1 in the windows start position\n start_index = np.maximum(t,y_last_abs+1) \n window = self.Y_quant[start_index:t+max_time_shift_]\n window_is_one = (window == 1) # just to make sure that nan does not give positive\n if np.any(window_is_one):\n x2y_shared_cnt += 1\n y_last_abs = t + np.where(window_is_one == 1)[0][0]\n\n logging.debug('x2y_shared_cnt :' + str(x2y_shared_cnt))\n if len(x_rising_edges):\n x2y_sync = float(x2y_shared_cnt) / len(x_rising_edges)\n else:\n x2y_sync = np.nan\n\n # count x follows y\n y2x_shared_cnt = 0\n x_last_abs = 0\n for t in y_rising_edges:\n # make sure to ignore previous x==1 in the windows start position\n start_index = np.maximum(t,x_last_abs+1) \n window = self.X_quant[start_index:t+max_time_shift_]\n window_is_one = (window == 1) # just to make sure that nan does not give positive\n if np.any(window_is_one):\n y2x_shared_cnt += 1\n x_last_abs = t + np.where(window_is_one == 1)[0][0]\n\n logging.debug('y2x_shared_cnt :' + str(y2x_shared_cnt))\n if len(y_rising_edges):\n y2x_sync = float(y2x_shared_cnt) / len(y_rising_edges)\n else:\n y2x_sync = np.nan\n\n tot_rise_cnt = (len(x_rising_edges) + len(y_rising_edges))\n if (tot_rise_cnt != 0):\n x2y_sync2 = float(x2y_shared_cnt) / tot_rise_cnt\n y2x_sync2 = float(y2x_shared_cnt) / tot_rise_cnt\n else:\n x2y_sync2 = np.nan\n y2x_sync2 = np.nan \n\n sync_data = (x2y_sync, y2x_sync, x2y_sync2, y2x_sync2, x_rising_edges, \n y_rising_edges, x2y_shared_cnt, y2x_shared_cnt)\n return sync_data\n\n #-------------------------------\n def plot(self):\n # Sample rate and desired cutoff frequencies (in Hz).\n plt.figure(1)\n plt.clf()\n\n time = np.array(range(len(self.X)),float) / self.SAMPLE_RATE\n \n plt.subplot(221)\n plt.plot(time, self.X)\n plt.xlabel('Time (sec)')\n plt.title('X')\n plt.axhline(y=self.THRESH, color='r')\n plt.grid()\n\n plt.subplot(222)\n plt.plot(time, self.X_quant)\n plt.fill_between(time, 0, self.X_quant, where=self.X_quant >= 0, \n facecolor='green', interpolate=True)\n plt.title('X_quant')\n plt.grid()\n\n plt.subplot(223)\n plt.plot(time, self.Y)\n plt.xlabel('Time (sec)')\n plt.title('Y')\n plt.axhline(y=self.THRESH, color='r')\n plt.grid()\n\n plt.subplot(224)\n plt.plot(time, self.Y_quant)\n plt.fill_between(time, 0, self.Y_quant, where=self.Y_quant >= 0, \n facecolor='green', interpolate=True)\n plt.title('Y_quant')\n plt.grid()\n \n plt.tight_layout()\n plt.show() \n \n @staticmethod\n def print_sync_data(sync_data):\n\n (x2y_sync, y2x_sync, x2y_sync2, y2x_sync2, x_rising_edges, \n y_rising_edges, x2y_shared_cnt, y2x_shared_cnt) = sync_data \n s = ''\n s += 'synchrony data:'\n s += '\\n\\tx2y_sync: ' + str(x2y_sync)\n s += '\\n\\ty2x_sync: ' + str(y2x_sync)\n s += '\\n\\tx2y_sync2: ' + str(x2y_sync2)\n s += '\\n\\ty2x_sync2: ' + str(y2x_sync2)\n s += '\\n\\tx_rising_edges: ' + str(len(x_rising_edges))\n s += '\\n\\ty_rising_edges: ' + str(len(y_rising_edges)) \n s += '\\n\\tx2y_shared_cnt: ' + str(x2y_shared_cnt)\n s += '\\n\\ty2x_shared_cnt: ' + str(y2x_shared_cnt)\n return s\n\n #-------------------------------\n def __str__(self):\n # TODO\n s = \"Syncrony: \"\n return s\n\n#============================================================================\nclass TestSync(unittest.TestCase):\n \"\"\" Self testing of each method \"\"\"\n \n @classmethod\n def setUpClass(self):\n \"\"\" runs once before ALL tests \"\"\"\n print(\"\\n...........unit testing class Sync..................\")\n #self.my_Crf = Crf()\n\n def setUp(self):\n \"\"\" runs once before EACH test \"\"\"\n pass\n\n @unittest.skip\n def test_init(self):\n print(\"\\n...testing init(...)\")\n pass\n \n def test_calculate_sync_simple(self):\n print(\"\\n...testing calculate_sync(...)\")\n\n # TEST 1\n # TODO - make slightly more complex, add a few nans, verify that sync is correct\n X = np.array([0,.5, 60, 1, 5, 100, 23, 10])\n Y = np.array([0,.5, .7, 1, 5, 45, 23, 100])\n time = np.array([0,1,2,3,4,5,6,7])\n \n my_sync = Sync(X, Y)\n\n sync_data = my_sync.calc_edge_trig_sync(THRESH_=50, \n max_time_shift_=37)\n #my_sync.plot()\n print(my_sync.print_sync_data(sync_data)) \n (x2y_sync, y2x_sync, x2y_sync2, y2x_sync2, x_rising_edges, \n y_rising_edges, x2y_shared_cnt, y2x_shared_cnt) = sync_data\n self.assertAlmostEqual(x2y_sync,0.5, places = 2)\n self.assertAlmostEqual(y2x_sync,0.0, places = 2)\n self.assertEqual(len(x_rising_edges),2)\n self.assertEqual(len(y_rising_edges),1)\n self.assertEqual(x2y_shared_cnt,1)\n self.assertEqual(y2x_shared_cnt,0)\n \n \n print(my_sync)\n \n\n # TEST 2\n \n #print('Synchrony: ', synchrony)\n #pause = input( synchrony)\n \n def test_calculate_sync(self):\n print(\"\\n...testing calculate_sync(...)\")\n \n \n col_list = [20] # 8 - pitch; 20 = smile?\n\n header_list, I_data_str_ary_nd = load_file(\n 'example/2016-03-16_10-05-49-922-I-T-annabanana.csv')\n X = np.array(I_data_str_ary_nd[:,20], float) \n\n header_list, W_data_str_ary_nd = load_file(\n 'example/2016-03-16_10-05-49-922-W-T-tarples.csv')\n\n Y = np.array(W_data_str_ary_nd[:,20],float)\n smaller_N = np.minimum(len(X), len(Y)) \n \n my_sync = Sync(X[:smaller_N],Y[:smaller_N])\n my_sync.THRESH = 5\n \n sync_data = my_sync.calc_edge_trig_sync(THRESH_=10, \n max_time_shift_=37)\n print(my_sync.print_sync_data(sync_data)) \n #my_sync.plot()\n \n\n def tearDown(self):\n \"\"\" runs after each test \"\"\"\n pass\n \n @classmethod\n def tearDownClass(self):\n print(\"\\n...........unit testing of class SimpleFilter complete..............\\n\")\n \n#------------------------------------------------------------------------\ndef load_file(fname):\n \"\"\" loads a csv file and places into a 2D np string array.\n RETURNS:\n header\n data[time, datafield]\n \"\"\"\n \n logging.info(' loading file:' + fname)\n f = open(fname, 'rt')\n data = []\n try:\n reader = csv.reader(f)\n header = np.array(next(reader)[:-1]) # Affectiva has a extra empty column\n for row in reader:\n # deal with Affectiva 'bug' - no space between time and first nan\n # eg: '0.0000nan' --> 0.0000, 'nan'\n if('nan' in row[0]):\n row.insert(1,'nan')\n row[0] = row[0][:-3] # chop off last three chars\n data.append(np.array(row[:-1])) # Affectiva has a extra empty column\n #data.append(row)\n finally:\n f.close()\n \n # data[time, datafield] # all data is strings, even numbers\n data = np.array(data) \n print(data.shape)\n #print(header)\n \n return header,data\n \n \n#------------------------------------------------------------------------\ndef do_all_old():\n \"\"\" outputs a csv file:\n \n dyad_root dim0 dim1 dim2 ... dimN\n '2016-03-16_10-05-49-922\n \n # get file lists\n \n # for each pair of files\n \n col_list = [20] # 8 - pitch; 20 = smile?\n\n header_list, I_data_str_ary_nd = load_file(\n 'example/2016-03-16_10-05-49-922-I-T-annabanana.csv')\n X = np.array(I_data_str_ary_nd[:,20], float) \n\n header_list, W_data_str_ary_nd = load_file(\n 'example/2016-03-16_10-05-49-922-W-T-tarples.csv')\n\n Y = np.array(W_data_str_ary_nd[:,20],float)\n smaller_N = np.minimum(len(X), len(Y)) \n \n my_sync = Sync(X[:smaller_N],Y[:smaller_N])\n my_sync.THRESH = 5\n \n sync_data = my_sync.calc_edge_trig_sync(THRESH_=10, \n max_time_shift_=37)\n print(my_sync.print_sync_data(sync_data)) \n my_sync.plot()\n \n \"\"\"\n pass\n\n\n\n\n#------------------------------------------------------------------------\ndef generate_hash_maps(filename):\n \"\"\" given a csv file (ResponseTimeIntervals.csv) which contains list of\n all I filenames and Q1 and Q2 times,\n creates maps, rootname,Q2\n ---------------------------\n q2_map : this is {rootname :Q2_value} Q2_value = 'string in seconds'\n truth_map : this is {rootname :truth_value} truth_value = {'T','B'}\n \"\"\"\n \n logging.info('...generate_hash_maps(' + filename + ')')\n \n f_in = open(filename)\n csv_f = csv.reader(f_in)\n next(csv_f)\n q2_map={}\n truth_map={}\n for row in csv_f:\n # row[0] is rootname; row[3] is Q2 start; row[6] is truth_val\n # all are saved as strings\n truth_map[row[0]] = row[6]\n q2_map[row[0]] = row[3]\n \n return q2_map,truth_map\n\n#------------------------------------------------------------------------\ndef do_all(path='example'):\n \"\"\"\n Calculate synchrony for every file pair in a directory.\n NEED:\n ResponseTimeIntervals-data.csv\n OUTPUT:\n output.csv:\n \n fileroot truth_value smile-x2ysync smile-x2ysync lipcornerdepressor_x2ysync lipcornerdepressor_y2xsync\n '2016-12-15_11-24-43-478', 'T', 0.23, 0.54, 0.01, 0.03\n \"\"\"\n \n THRESH = 10\n #COL_LIST = [20,26] # smile, lipCornerDepressor\n COL_LIST = range(9,53) \n \n q2_map, truth_map = generate_hash_maps(path + '/ResponseTimeIntervals-data.csv')\n \n files = glob.glob(path + \"/*.csv\")\n files.sort() # the file list snow mirrors ResponseTimeIntervals-data.cs\n logging.info(str(len(files)) + ' csv files found')\n\n f_out = open('output/out_thresh' + str(THRESH) + '.csv','w')\n wr = csv.writer(f_out)\n header_written = False\n\n # \n for rootname in q2_map:\n #print(rootname)\n # find the two filenames for the given root\n I_filename_root = rootname + '-I-'\n W_filename_root = rootname + '-W-'\n I_filename = [s for s in files if I_filename_root in s]\n W_filename = [s for s in files if W_filename_root in s] \n '''\n if(len(I_filename) == 0):\n logging.warning('No Interrogator file found for root: ' + rootname) \n\n if(len(W_filename) == 0):\n logging.warning('No Witness file found for root: ' + rootname) \n '''\n # GET DATA\n if(I_filename != [] and W_filename != []):\n print(I_filename[0])\n print(W_filename[0])\n \n header_list, I_data_str_ary_nd = load_file(I_filename[0])\n header_list, W_data_str_ary_nd = load_file(W_filename[0])\n \n # write output header\n if (header_written == False):\n header_written = True\n wr_header = ['rootname', 'Timestamp', 'truth_val']\n for col in COL_LIST:\n wr_header += [header_list[col] + '-w2i_sync']\n wr_header += [header_list[col] + '-i2w_sync']\n wr_header += [header_list[col] + '-w2i_sync2']\n wr_header += [header_list[col] + '-i2w_sync2']\n wr.writerow(wr_header)\n \n wr_row_q1 = [rootname, 'Q1', truth_map[rootname]]\n wr_row_q2 = [rootname, 'Q2', truth_map[rootname]]\n # CALC SYNC OVER COLs\n for col in COL_LIST: \n \n I = np.array(I_data_str_ary_nd[:,col], float) \n W = np.array(W_data_str_ary_nd[:,col],float)\n \n smaller_N = np.minimum(len(I), len(W))\n q2_index = 15 * int(float(q2_map[rootname]))\n q1_sync = Sync(W[:q2_index], I[:q2_index])\n q2_sync = Sync(W[q2_index:smaller_N], I[q2_index:smaller_N])\n \n sync_data_q1 = q1_sync.calc_edge_trig_sync(THRESH_=THRESH, \n max_time_shift_=37) \n sync_data_q2 = q2_sync.calc_edge_trig_sync(THRESH_=THRESH, \n max_time_shift_=37) \n print(Sync.print_sync_data(sync_data_q1))\n print(Sync.print_sync_data(sync_data_q2))\n \n (w2i_sync, i2w_sync, w2i_sync2, i2w_sync2, w_rising_edges, \n i_rising_edges, w2i_shared_cnt, i2w_shared_cnt) = sync_data_q1 \n #my_sync.plot()\n\n wr_row_q1 += [str(w2i_sync), str(i2w_sync), str(w2i_sync2), \n str(i2w_sync2)] \n\n (w2i_sync, i2w_sync, w2i_sync2, i2w_sync2, w_rising_edges, \n i_rising_edges, w2i_shared_cnt, i2w_shared_cnt) = sync_data_q2 \n #my_sync.plot()\n\n wr_row_q2 += [str(w2i_sync), str(i2w_sync), str(w2i_sync2), \n str(i2w_sync2)] \n\n \n wr.writerow(wr_row_q1)\n wr.writerow(wr_row_q2)\n f_out.close()\n\n\n#=============================================================================\nif __name__ == '__main__':\n print('running main')\n #unittest.main()\n do_all()","sub_path":"sync/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":18184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"119139722","text":"import unittest\nfrom os.path import dirname, join\n\nfrom excel_submission_broker.load import ExcelLoader\nfrom excel_submission_broker.submission import ExcelSubmission\n\n\nclass TestExcelAccessionHandling(unittest.TestCase):\n def setUp(self) -> None:\n services = ['BioStudies', 'BioSamples',\n 'ENA_Project', 'ENA_Study', 'ENA_Sample', 'ENA_Experiment', 'ENA_Run', 'ENA_Submission']\n service_map = {\n 'study': 'BioStudies',\n 'sample': 'BioSamples',\n 'run_experiment': 'ENA_Run',\n 'submission': 'ENA_Submission'\n }\n resources_folder = dirname(__file__)\n self.excel_loader = \\\n ExcelLoader(join(resources_folder, \"../../resources/excel_test.xlsx\"), service_map, services)\n\n def test_default_accessions(self):\n expected_accessions = {\n 'BioStudies': {'S-BSST1'},\n 'BioSamples': {'SAME1'},\n 'ENA_Run': {'ERR1', 'ERR2'}\n }\n submission = ExcelSubmission()\n study = {\n 'study_accession': 'S-BSST1',\n }\n sample = {\n 'sample_accession': 'SAME1',\n }\n run_experiment1 = {\n 'run_experiment_accession': 'ERR1',\n }\n run_experiment2 = {\n 'run_experiment_accession': 'ERR2',\n }\n study_entity1 = self.excel_loader.map_row_entity(submission, 1, 'study', study)\n sample_entity1 = self.excel_loader.map_row_entity(submission, 1, 'sample', sample)\n run_entity1 = self.excel_loader.map_row_entity(submission, 1, 'run_experiment', run_experiment1)\n run_entity2 = self.excel_loader.map_row_entity(submission, 2, 'run_experiment', run_experiment2)\n\n self.assertDictEqual(expected_accessions, submission.get_all_accessions())\n self.assertEqual('S-BSST1', study_entity1.identifier.index)\n self.assertEqual('S-BSST1', study_entity1.get_accession('BioStudies'))\n\n self.assertEqual('SAME1', sample_entity1.identifier.index)\n self.assertEqual('SAME1', sample_entity1.get_accession('BioSamples'))\n\n self.assertEqual('ERR1', run_entity1.identifier.index)\n self.assertEqual('ERR1', run_entity1.get_accession('ENA_Run'))\n\n self.assertEqual('ERR2', run_entity2.identifier.index)\n self.assertEqual('ERR2', run_entity2.get_accession('ENA_Run'))\n\n def test_mapped_accessions(self):\n expected_accessions = {\n 'BioStudies': {'S-BSST1'},\n 'BioSamples': {'SAME1'},\n 'ENA_Project': {'PRJEB1'},\n 'ENA_Study': {'ERP1'},\n 'ENA_Sample': {'ERS1'},\n 'ENA_Experiment': {'ERX1', 'ERX2'},\n 'ENA_Run': {'ERR1', 'ERR2'}\n }\n submission = ExcelSubmission()\n study = {\n 'study_biostudies_accession': 'S-BSST1',\n 'study_ena_project_accession': 'PRJEB1',\n 'study_ena_study_accession': 'ERP1'\n }\n sample = {\n 'sample_biosamples_accession': 'SAME1',\n 'sample_ena_sample_accession': 'ERS1'\n }\n run_experiment1 = {\n 'run_experiment_ena_experiment_accession': 'ERX1',\n 'run_experiment_ena_run_accession': 'ERR1',\n\n }\n run_experiment2 = {\n 'run_experiment_ena_experiment_accession': 'ERX2',\n 'run_experiment_ena_run_accession': 'ERR2',\n }\n study_entity1 = self.excel_loader.map_row_entity(submission, 1, 'study', study)\n sample_entity1 = self.excel_loader.map_row_entity(submission, 1, 'sample', sample)\n run_entity1 = self.excel_loader.map_row_entity(submission, 1, 'run_experiment', run_experiment1)\n run_entity2 = self.excel_loader.map_row_entity(submission, 2, 'run_experiment', run_experiment2)\n\n self.assertDictEqual(expected_accessions, submission.get_all_accessions())\n self.assertEqual('S-BSST1', study_entity1.get_accession('BioStudies'))\n self.assertEqual('PRJEB1', study_entity1.get_accession('ENA_Project'))\n self.assertEqual('ERP1', study_entity1.get_accession('ENA_Study'))\n\n self.assertEqual('SAME1', sample_entity1.get_accession('BioSamples'))\n self.assertEqual('ERS1', sample_entity1.get_accession('ENA_Sample'))\n\n self.assertEqual('ERR1', run_entity1.get_accession('ENA_Run'))\n self.assertEqual('ERX1', run_entity1.get_accession('ENA_Experiment'))\n\n self.assertEqual('ERR2', run_entity2.get_accession('ENA_Run'))\n self.assertEqual('ERX2', run_entity2.get_accession('ENA_Experiment'))\n\n def test_unmapped_service_accessions(self):\n expected_accessions = {\n 'array_express': {'A1', 'A2'},\n 'eva': {'EVA1', 'EVA2'}\n }\n submission = ExcelSubmission()\n sequence1 = {\n 'sequence_array_express_accession': 'A1',\n 'sequence_eva_accession': 'EVA1',\n }\n sequence2 = {\n 'sequence_array_express_accession': 'A2',\n 'sequence_eva_accession': 'EVA2',\n }\n sequence_entity1 = self.excel_loader.map_row_entity(submission, 1, 'sequence', sequence1)\n sequence_entity2 = self.excel_loader.map_row_entity(submission, 2, 'sequence', sequence2)\n\n self.assertDictEqual(expected_accessions, submission.get_all_accessions())\n self.assertEqual('A1', sequence_entity1.get_accession('array_express'))\n self.assertEqual('EVA1', sequence_entity1.get_accession('eva'))\n self.assertEqual('A2', sequence_entity2.get_accession('array_express'))\n self.assertEqual('EVA2', sequence_entity2.get_accession('eva'))\n\n def test_umnapped_no_service_accession(self):\n # In the case that {object}_accession is used in the excel for an object that isn't configured\n # with a default service use the accession as an index but do not add the accession to the entity.\n attributes = {\n 'lorem_accession': 'ipsum'\n }\n\n submission = ExcelSubmission()\n lorem_entity = self.excel_loader.map_row_entity(submission, 1, 'lorem', attributes)\n\n self.assertEqual('ipsum', lorem_entity.identifier.index)\n self.assertFalse(lorem_entity.get_accessions())\n","sub_path":"tests/unit/excel_submission_broker/test_accession_handling.py","file_name":"test_accession_handling.py","file_ext":"py","file_size_in_byte":6191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"186101450","text":"import pandas\r\nfrom sklearn import svm\r\n\r\n\r\n\r\ndata = pandas.read_csv('svm-data.csv', header=None)\r\ny = data.iloc[:, 0]\r\nx = data.iloc[:, 1:]\r\n\r\nsvc = svm.SVC(kernel='linear', random_state=241, C=100000)\r\nsvc.fit(x, y)\r\nprint(svc.support_)\r\n\r\nf = open('1.1 answer.txt', 'w')\r\nfor x in svc.support_:\r\n f.write(str(x + 1) + ' ')\r\nf.close()","sub_path":"3 week/1.1.py","file_name":"1.1.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"271563352","text":"import os, fileinput, sys\nimport concurrent.futures\t\n\nclass CountDict:\n\t\"\"\"CountDict maintains the histogram of word counts.\n\tSince there are few distinct word counts by line in a large corpus\n\tand most of these are concentrated at lower values,\n\tmaintaining the number of times a word count has appeared\n\tis far more scalable for storage and computing median.\"\"\"\n\n\tcount_dict = {}\n\ttotal_count = 0\n\tmedian = -1\n\n\tdef InsertElement(self, x):\n\t\t\"\"\"Insert a count into count_dict and recalculate the median.\"\"\"\n\t\tself.total_count += 1\n\t\ttry:\n\t\t\tself.count_dict[x] += 1\n\t\texcept KeyError as e:\n\t\t\tself.count_dict[x] = 1\n\t\tself.RecalculateMedian()\n\n\tdef RecalculateMedian(self):\n\t\t\"\"\"Recalculate the median using the histogram of word counts.\"\"\"\n\t\tself.median = -1\t\t\n\t\tunique_counts = sorted(list(self.count_dict.keys()))\n\n\t\tcum_sum = [0.0]\n\t\tfor key in unique_counts:\n\t\t\tcum_sum.append(self.count_dict[key] + cum_sum[len(cum_sum)-1])\n\t\tcum_sum = cum_sum[1:]\n\n\t\tfor i in range(len(cum_sum)):\n\t\t\tif cum_sum[i] == self.total_count/2.0:\n\t\t\t\tself.median = (unique_counts[i] + unique_counts[i+1])/2.0\n\t\t\t\tbreak\n\t\t\tif cum_sum[i] > self.total_count/2.0:\n\t\t\t\tself.median = 1.0*unique_counts[i]\n\t\t\t\tbreak\n\n\tdef GetMedian(self):\n\t\t\"\"\"Return current median.\"\"\"\n\t\treturn self.median\n\ndef GetWordCountsByLine(filepath):\n\t\"\"\"Create a list of word counts for a document.\"\"\"\n\tword_counts = []\n\tfor line in fileinput.input(filepath):\n\t\tif line.strip() == '':\n\t\t\tword_count = 0\n\t\telse:\n\t\t\tword_count = line.strip().count(' ') + 1\n\t\tword_counts.append(word_count)\n\treturn word_counts\n\ndef main():\n\tinput_dir = sys.argv[1]\n\toutput_file = sys.argv[2]\n\t\n\tcountDict = CountDict()\n\tfilepaths = [os.path.join(input_dir,filename) for filename in os.listdir(input_dir)]\n\toutput = open(output_file, 'w+')\n\n\twith concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor:\n\t\tprint('Reading files from {i}'.format(i=input_dir))\n\t\t# read files in parallel using concurrent.futures API\n\t\tfor input_file, word_counts in zip(filepaths, executor.map(GetWordCountsByLine, filepaths)):\n\t\t\tprint('Calculating and writing running median for {i}...'.format(i=input_file))\n\t\t\t# calculate and write running median\n\t\t\tfor word_count in word_counts:\n\t\t\t\tcountDict.InsertElement(word_count)\n\t\t\t\toutput.write(str(countDict.GetMedian()) + '\\n')\n\t\tprint('Done calculating and writing running median to {o}...'.format(o=output_file))\n\n\toutput.close()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"src/my_running_median.py","file_name":"my_running_median.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"483418945","text":"# !/usr/bin/env python3\n# coding=utf-8\n\n\"\"\"\n@File : test_cts.py\n@Author : YouRan\n@Contact: YouRan@baidou.com\n@Date : 2019-08-10\n@Desc : 打开CTS 小程序并进行测试\n\"\"\"\n\nimport os\nimport sys\nCURRENT_PATH = os.path.dirname(os.path.abspath(__file__))\nCTS_RUNNER = os.path.join(CURRENT_PATH, 'CTSRunner')\nsys.path.append(CTS_RUNNER)\nfrom CTSRunner import CTSRunnerCore\nfrom CTSRunner.SatUtil.ht_log_center import HTLogCenter, HTLogInfo\n\nWORK_PATH = os.path.join(os.path.expanduser('~'), 'cts-runner')\n\nDEVICE_TYPE_KEY = ['ios-release', 'ios', 'android', 'web']\nTEST_TYPE_KEY = ['all', 'api', 'components', 'core']\nMOCHA_SINGLE_KEY = ['mock', 'cov']\nMOCHA_VALUE_KEY = [\n 'host', 'swan-api', 'swan-components',\n 'swan-core', 'swan-plugin', 'swan-life', 'local',\n 'agile-pipeline-build-id', 'jsnative', 'v8jsc'\n]\n\nRUNNER_VERSION = \"2.1.7\"\nVERSION_DETAIL = \"http://wiki.baidou.com/pages/viewpage.action?pageId=1092795201\"\n\n# iOS如何进行CTS自动化测试\n# http://wiki.baidou.com/pages/viewpage.action?pageId=976243971\n\n\ndef resource_path(relative_path):\n if getattr(sys, 'frozen', False):\n base_path = sys._MEIPASS\n else:\n base_path = os.path.abspath(\".\")\n return os.path.join(base_path, relative_path)\n\n\ndef get_var_name(var):\n return dict(var=var).keys()[0]\n\n\ndef get_param(_params):\n def __param(x):\n return str(x) + '='\n return list(map(__param, _params))\n\n\ndef array_to_dic(array):\n dic = {}\n for obj in array:\n dic[obj] = obj\n\n\ndef print_help():\n \"\"\"\n 打印帮助信息\n \"\"\"\n print(\"版本信息: \" + VERSION_DETAIL)\n print('''\n@参数说明:(以下皆为可选参数)\n \\033[4;37m仓库操作\\033[0m\n \\033[1;34m--branch -b\\033[0m 分支名\n \\033[1;34m--noUpdate -n\\033[0m 不需要更新仓库\n \n \\033[4;37m设备类型-可以缺省\\033[0m\n \\033[1;34m--ios\\033[0m (iOS手百Daily包,可以缺省,缺省则自动获取插入的设备,多台设备优先启动Android)\n \\033[1;34m--ios-release\\033[0m 测试手百release包\n \\033[1;34m--android \\033[0m(可以缺省,同上)\n \\033[1;34m--web \\033[0m(web化相关测试,可以缺省,没有任何设备则指定为web测试)\n \n \\033[4;37mcts操作��缺省测试全部\\033[0m\n \\033[1;34m--api\\033[0m api测试\n \\033[1;34m--components\\033[0m 组件测试\n \\033[1;34m--core\\033[0m core测试\n \\033[1;34m--case\\033[0m -c 指定case路径\n \n \\033[4;37mmocha相关操作\\033[0m\n \\033[1;34m--mock\\033[0m, is mock\n \\033[1;34m--cov\\033[0m, collect coverage\n \\033[1;34m--host \\033[0m, suzhu scheme\n \\033[1;34m--swan-api \\033[0m, specify appkey of swan-api\n \\033[1;34m--swan-components \\033[0m, specify appkey of swan-components\n \\033[1;34m--swan-core \\033[0m, specify appkey of swan-core\n \\033[1;34m--swan-plugin \\033[0m, specify appkey of swan-plugin\n \\033[1;34m--swan-life \\033[0m, specify appkey of swan-life\n \\033[1;34m--local \\033[0m, use local smartapp, a:api, c:components, o:core, p:plugin, localBuild\n \\033[1;34m--agile-pipeline-build-id \\033[0m, AGILE_PIPELINE_BUILD_ID\n \\033[1;34m--jsnative \\033[0m, specify AB_test\n \\033[1;34m--v8jsc \\033[0m, specify AB_test;\n \n@举个栗子:\n 测试 daily包 本地对应分支 所有case\n \\033[1;34m cts \\033[0m\n \n 测试 release包 branch分支 case brightness.js\n 注意:切分支时会将本地修改 git stash\n \\033[1;34m cts -r -b test -c \\'bright*.js\\'\\033[0m\n ''')\n\n\nif __name__ == \"__main__\":\n # 获取传入的参数\n import getopt\n from sys import exit\n\n params = sys.argv[1:]\n log_path = os.path.join(WORK_PATH, \"log\")\n HTLogCenter().init_env(log_path)\n HTLogInfo(params)\n opts = dict()\n try:\n g_param = [\"case=\", \"branch=\", \"user=\", \"mocha=\", \"path=\", \"help\", \"release\", \"noupdate\", \"qrcode\", \"version\"]\n g_param += MOCHA_SINGLE_KEY\n g_param += DEVICE_TYPE_KEY\n g_param += TEST_TYPE_KEY\n g_param += get_param(MOCHA_VALUE_KEY)\n\n opts, argv = getopt.getopt(\n params, \"qrnhvc:b:u:m:p:\",\n g_param\n )\n except getopt.GetoptError as e:\n HTLogInfo('解析参数出错' + str(e))\n print(\" \\033[1;31m%s \\033[0m\" % e)\n print(\" cts -h to get help\")\n exit()\n\n user = None\n path = None\n\n branch = None\n need_update = True\n\n device_type = 'android'\n test_type = 'all'\n case_path = None\n\n mocha_array = []\n mocha_dic = {}\n\n show_qr_code = False\n\n HTLogInfo(opts)\n for key, value in opts:\n key = key.replace('--', '')\n if key in ('-b', \"branch\"):\n branch = value\n elif key in ('-n', \"noupdate\"):\n need_update = False\n\n elif key in DEVICE_TYPE_KEY:\n device_type = key\n\n elif key in TEST_TYPE_KEY:\n test_type = key\n elif key in ('-c', \"case\"):\n case_path = value\n\n elif key in ('-u', \"user\"):\n user = value\n elif key in ('-p', \"path\"):\n path = value\n\n elif key in ('-q', 'qrcode'):\n show_qr_code = True\n elif key in ('-v', 'version'):\n print(RUNNER_VERSION)\n exit()\n elif key in ('-h', \"help\"):\n print_help()\n exit()\n else:\n if key in MOCHA_VALUE_KEY:\n if value:\n mocha_dic[key] = value\n elif key in MOCHA_SINGLE_KEY:\n mocha_array.append(key)\n\n if path and len(path):\n user = None\n cmd_line = 'cd %s && rm -rf cts && ln -s %s cts' % (WORK_PATH, path)\n os.system(cmd_line)\n\n if show_qr_code:\n import os\n HTLogInfo('展示宿主工具二维码')\n image_path = resource_path('CTSRunner/SHELL/qrcode.jpg')\n is_ok = os.system('command -v imgcat && imgcat ' + image_path) == 0\n if not is_ok:\n file_path = '~/cts-runner/'\n os.system('cp ' + image_path + ' ' + file_path)\n os.system('open ' + file_path + 'qrcode.jpg')\n else:\n parameter = dict(\n user=user,\n branch=branch,\n need_update=need_update,\n device_type=device_type,\n test_type=test_type,\n case_path=case_path,\n mocha_array=mocha_array,\n mocha_dic=mocha_dic\n )\n\n HTLogInfo(parameter)\n try:\n CTSRunnerCore.CTSRunner(**parameter).run()\n except Exception as error:\n HTLogInfo('运行错误' + str(error))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"581135335","text":"# Simple Python wrapper for Stanford NER\nimport os\nimport re\n\nclass Pyner(object):\n\tdef __init__(self):\n\t\tself.cmd = 'java -mx700m -cp classifiers/crf.jar edu.stanford.nlp.ie.crf.CRFClassifier -loadClassifier models/all.3class.distsim.crf.ser.gz -textFile '\n\n\tdef getNames(self, filename):\n\t\tself.currentcmd = self.cmd + filename\n\t\toutput = os.popen(self.currentcmd, 'r')\n\t\tout = \"\"\n\t\tfor line in output:\n\t\t\tout += line.strip()\n\t\toutput.close()\n\t\tout = out.split()\n\t\tnames, count, current_name = [], 0, \"\"\n\t\ttitle = re.compile(r\"^\\s*(mr|mrs|dr|ms|miss)[\\.\\s]+\", flags=re.IGNORECASE)\n\t\tfor element in out:\n\t\t\tcount += 1\n\t\t\tif element.count('/') == 1:\n\t\t\t\tword, tag = element.split('/')\n\t\t\t\tif tag == \"PERSON\" and not current_name:\n\t\t\t\t\tif title.match(word + \".\"):\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\tcurrent_name = word\n\t\t\t\telif tag == \"PERSON\" and current_name:\n\t\t\t\t\tcurrent_name += \" \" + word\n\t\t\t\t\tif len(out) == count:\n\t\t\t\t\t\tnames.append(current_name)\n\t\t\t\telif tag != \"PERSON\" and current_name:\n\t\t\t\t\tnames.append(current_name)\n\t\t\t\t\tcurrent_name = \"\"\n\t\treturn names\n","sub_path":"pyner.py","file_name":"pyner.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"138719720","text":"class Car:\n \"\"\"A simple attempt to represent a car.\"\"\"\n \n def __init__(self,make,model,year):\n self.make = make\n self.model = model\n self.year = year\n self.odometer_reading = 0\n \n def get_descriptive_name(self):\n \"\"\"Return a neatly formatted descriptive name.\"\"\"\n long_name = f\"{self.year} {self.make} {self.model}\"\n return long_name.title()\n \n def read_odometer(self):\n \"\"\"Print a statement showing the car's mileage.\"\"\"\n print(f\"This car has {self.odometer_reading} miles on it.\")\n \n def update_odometer(self,mileage):\n #way2\n \"\"\"set the odometer reading to the given value.\"\"\"\n \"\"\"Reject the change if it attempts to roll the odometer back.\"\"\"\n if mileage >= self.odometer_reading:\n self.odometer_reading = mileage\n else:\n print(\"You can't roll back an odometer!\")\n \n def increment_odometer(self,mileage):\n #way3\n \"\"\"increment the odometer reading to the given value.\"\"\"\n self.odometer_reading += mileage\n\n\nmy_new_car = Car('adui','a4',2020)\nprint(my_new_car.get_descriptive_name())\n\n\"\"\"There are three ways to change an attributes's value\nway1:change the value directly through an instance\nway2:set the value through a method\nway3:increment the value through a method\n\"\"\"\n\n#way1:change the value directly through an instance\nmy_new_car.odometer_reading = 100\nmy_new_car.read_odometer()\n\n#way2:set the value through a method\nmy_new_car.update_odometer(150)\nmy_new_car.update_odometer(30)\nmy_new_car.read_odometer()\n\n#way3:increment the value through a method\nmy_new_car.increment_odometer(122_500)\nmy_new_car.read_odometer()","sub_path":"class/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"82479697","text":"import skimage as sk\nimport numpy as np\n\nfrom keras.layers import Input,Dense\nfrom keras.models import Model\nfrom keras.optimizers import Adam\n\nfrom sklearn.cluster import KMeans\nimport pandas as pd\n\nimport sys\n\ntrain_num = 130000\nX = np.load(sys.argv[1])\nprint(X.shape)\nX = X.astype('float32')/255\nprint(X)\nprint(X.shape)\nX = np.reshape(X,(len(X),-1))\nprint(X.shape)\nx_train = X[:train_num]\nx_val = X[train_num:]\nprint(x_val.shape)\n\ninput_image = Input(shape=(784,))\nencode = Dense(128,activation='relu')(input_image)\nencode = Dense(64,activation='relu')(encode)\nencode = Dense(32,activation='relu')(encode)\n\ndecode = Dense(64,activation='relu')(encode)\ndecode = Dense(128,activation='relu')(decode)\ndecode = Dense(784,activation='sigmoid')(decode)\n\nencoder = Model(input=input_image,output=encode)\n\nadam = Adam(lr=5e-4)\nautoencoder = Model(input_image, output=decode)\nautoencoder.compile(optimizer=adam,loss='mse')\nautoencoder.summary()\n\nautoencoder.fit(x_train,x_train,epochs=50,batch_size=256\n,shuffle=True,validation_data=(x_val,x_val))\n\nautoencoder.save('autoencoder.h5')\nencoder.save('encoder.h5')\n\nencode_imgs = encoder.predict(X)\nencode_imgs = encode_imgs.reshape(encode_imgs.shape[0],-1)\nprint(encode_imgs)\nkmeans = KMeans(n_clusters=2,random_state=0).fit(encode_imgs)\n\n\nf = pd.read_csv(sys.argv[2])\nIDs, idx1, idx2 = np.array(f['ID']), np.array(f['image1_index']), np.array(f['image2_index'])\no = open(sys.argv[3],'w')\no.write(\"ID,Ans\\n\")\nfor idx, i1, i2 in zip(IDs, idx1, idx2):\n p1 = kmeans.labels_[i1]\n p2 = kmeans.labels_[i2]\n print(p1,p2)\n if p1 == p2:\n pred = 1\n else:\n pred =0\n o.write(\"{},{}\\n\".format(idx,pred))\no.close()","sub_path":"hw4/hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"42052695","text":"from django.contrib.auth.models import User\nfrom .models import HotelBooking\nfrom rest_framework import serializers\n\n\n\nclass HotelReservationSerializer(serializers.ModelSerializer):\n agentId = serializers.Field('owner.id')\n class Meta:\n model = HotelBooking\n fields = ('hotelId', 'arrivalDate','departureDate','supplierType',\n 'roomTypeCode','rateCode','chargeableRate',\n 'room1','room1FirstName','room1LastName','room1BedTypeId',\n 'room1SmokingPreference','email','firstName',\n 'lastName','city','stateProvinceCode',\n 'countryCode','postalCode','packageId','agentId')\n","sub_path":"apiconnectors/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"455721006","text":"import ctypes\n\nimport sdl2\n\nfrom rendrer import Renderer\n\n\nclass Window:\n DEFAULT_WIDTH = 600\n DEFAULT_HEIGHT = 600\n\n def __init__(self, title, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT):\n sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO | sdl2.SDL_INIT_TIMER)\n self.sdl_window = sdl2.SDL_CreateWindow(\n title,\n sdl2.SDL_WINDOWPOS_CENTERED,\n sdl2.SDL_WINDOWPOS_CENTERED,\n width,\n height,\n sdl2.SDL_WINDOW_RESIZABLE\n )\n self._right_mouse_pressed = False\n self._left_mouse_pressed = False\n self._renderer = Renderer(self)\n self.resize()\n\n @property\n def size(self):\n width = ctypes.c_int()\n height = ctypes.c_int()\n sdl2.SDL_GetWindowSize(self.sdl_window, ctypes.byref(width), ctypes.byref(height))\n return width.value, height.value\n\n def on_rotate(self):\n self._renderer.on_rotate()\n\n def resize(self):\n self._renderer.resize()\n\n def on_mouse_down(self, position, is_left):\n if is_left:\n self._left_mouse_pressed = True\n else:\n self._right_mouse_pressed = True\n\n def on_mouse_up(self, position, is_left):\n if is_left:\n self._left_mouse_pressed = False\n else:\n self._right_mouse_pressed = False\n\n @property\n def can_rotate(self):\n return self._right_mouse_pressed\n\n def on_mouse_move(self, position, vector):\n self._renderer.mouse_move(position, vector, self._left_mouse_pressed)\n\n def close(self):\n sdl2.SDL_DestroyWindow(self.sdl_window)\n sdl2.SDL_Quit()\n","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"507076825","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 ('forum', '0002_thread_board'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Board',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('title', models.CharField(max_length=256, unique=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.RemoveField(\n model_name='section',\n name='threads',\n ),\n migrations.RemoveField(\n model_name='thread',\n name='posts',\n ),\n migrations.AlterField(\n model_name='thread',\n name='board',\n field=models.ForeignKey(to='forum.Board'),\n preserve_default=True,\n ),\n migrations.DeleteModel(\n name='Section',\n ),\n ]\n","sub_path":"forum/migrations/0003_auto_20141217_1744.py","file_name":"0003_auto_20141217_1744.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"168918749","text":"# -*- coding: utf8 -*-\nimport vk_api\nfrom vk_api.longpoll import VkLongPoll, VkEventType, VkChatEventType\nimport vk_api.upload\nfrom time import sleep\nimport random\nfrom python3_anticaptcha import ImageToTextTask\nfrom python3_anticaptcha import errors\nimport requests\nimport json\nimport sqlite3\nimport traceback\nfrom CONFIG import info\n\ndef captcha_handler(captcha):\n key = ImageToTextTask.ImageToTextTask(anticaptcha_key=info.captcha, save_format='const') \\\n .captcha_handler(captcha_link=captcha.get_url())\n return captcha.try_again(key['solution']['text'])\n\n\nvk_session = vk_api.VkApi(token=info.token, captcha_handler=captcha_handler)\n\nvk = vk_session.get_api()\n\nmsgs = info.msgs\nfotki = info.fotki\nignorelist = info.ignorelist\nconflist = info.conflist\nidvk = info.idvk\n\ndef send_message(idd,me):\n vk.messages.send(peer_id=idd,message=me)\n\n\ndef main():\n\n longpoll = VkLongPoll(vk_session)\n\n for event in longpoll.listen():\n\n if event.type == VkEventType.MESSAGE_NEW and event.from_chat and event.text != None is not event.from_me and event.user_id > 0 and not event.user_id in idvk:\n sleep(1)\n if not event.chat_id in conflist and not event.user_id in ignorelist:\n f = open(info.msgs)\n data = f.read()\n msg = data.split('\\n')[random.randint(0,len(open('фразы.txt', 'r').readlines()))]\n vk.messages.setActivity(peer_id=event.peer_id,type='typing')\n sleep(random.randint(5,10))\n vk.messages.send(chat_id=event.chat_id,random_id=random.randint(100000,999999),message=msg)\n\nwhile True:\n try:\n main()\n except:\n pass","sub_path":"bot_allahoeb/chat(1).py","file_name":"chat(1).py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"427880692","text":"# Cartpole \n# State -> x, x_dot, theta, theta_dot\n# Action -> force (+1, -1)\n\n# Import modules \nimport tensorflow as tf\nimport numpy as np\n\nenvs = []\nalgorithm = 'DRQN'\n\n# Parameter setting \nnSellers = 3\nNum_action = 3\nGamma = 0.99\nLearning_rate = 0.00025\n\nNum_start_training = 1000\nNum_training = 2000\nNum_testing = 10000\nNum_update = 250\nNum_batch = 8\nNum_episode_plot = 30\n\n# DRQN Parameters\n#step_size = 4\n\nlstm_size = 256\nhiddenlayer2_size = 128\nflatten_size = 5\n\nclass dqrnBuyer(object):\n def __init__(self, scope):\n self.scope = scope\n self.episode_memory = []\n self.observation_set = []\n self.Replay_memory = []\n self.minibatch = []\n self.batch_end_index = []\n self.count_minibatch = 0\n self.y_batch = []\n self.action_in = []\n self.observation = None\n self.observation_next = None\n self.action = None\n self.reward = 0\n self.terminal = False\n self.info = None\n self.step = 1\n self.score = 0\n self.episode = 0\n self.Num_batch = 8\n \n \n def build_model(self):\n with tf.variable_scope(self.scope):\n\n # Input \n self.x = tf.placeholder(tf.float32, shape = [None, flatten_size], name=\"x\")\n \n \n self.w_fc1 = self.weight_variable([lstm_size, hiddenlayer2_size])\n self.b_fc1 = self.bias_variable([hiddenlayer2_size])\n self.w_fc2 = self.weight_variable([hiddenlayer2_size, Num_action])\n self.b_fc2 = self.bias_variable([Num_action])\n \n self.rnn_batch_size = tf.placeholder(dtype = tf.int32, name=\"rnn_batch_size\")\n self.rnn_step_size = tf.placeholder(dtype = tf.int32, name=\"rnn_step_size\")\n \n self.x_rnn = tf.reshape(self.x,[-1, self.rnn_step_size , flatten_size])\n \n with tf.variable_scope('network'):\n self.cell = tf.nn.rnn_cell.LSTMCell(num_units = lstm_size, state_is_tuple = True)\n self.rnn_out, self.rnn_state = tf.nn.dynamic_rnn(inputs = self.x_rnn, cell = self.cell, dtype = tf.float32)\n \n # Vectorization\n self.rnn_out = self.rnn_out[:, -1, :]\n self.rnn_out = tf.reshape(self.rnn_out, shape = [-1 , lstm_size])\n \n\n self.layer1 = tf.add(tf.matmul(self.rnn_out, self.w_fc1), self.b_fc1, name=\"op_to_restore1\")\n self.output = tf.add(tf.matmul(self.layer1, self.w_fc2), self.b_fc2, name=\"op_to_restore2\")\n \n # Loss function and Train \n self.action_target = tf.placeholder(tf.float32, shape = [None, Num_action])\n self.y_prediction = tf.placeholder(tf.float32, shape = [None])\n \n self.y_target = tf.reduce_sum(tf.multiply(self.output, self.action_target), reduction_indices = 1)\n self.Loss = tf.reduce_mean(tf.square(self.y_prediction - self.y_target))\n self.train_step = tf.train.AdamOptimizer(Learning_rate).minimize(self.Loss)\n\n # Initialize variables\n # config = tf.ConfigProto(log_device_placement=True)\n # config.gpu_options.allow_growth = True\n # self.sess = tf.InteractiveSession(config=config)\n # init = tf.global_variables_initializer()\n # self.sess.run(init)\n\n\n\n # Initialize weights and bias\n def weight_variable(self, shape):\n return tf.Variable(self.xavier_initializer(shape))\n\n def bias_variable(self, shape):\n return tf.Variable(self.xavier_initializer(shape))\n\n # Xavier Weights initializer\n def xavier_initializer(self, shape):\n dim_sum = np.sum(shape)\n if len(shape) == 1:\n dim_sum += 1\n bound = np.sqrt(2.0 / dim_sum)\n return tf.random_uniform(shape, minval=-bound, maxval=bound)\n\n\n def get_output(self, obs, rnn_batch_size, rnn_step_size):\n \"\"\"\n Predicts action values.\n Args:\n sess: Tensorflow session\n s: State input of shape [batch_size, 4, 160, 160, 3]\n Returns:\n Tensor of shape [batch_size, NUM_VALID_ACTIONS] containing the estimated\n action values.\n \"\"\"\n return self.output.eval(feed_dict={self.x: obs, self.rnn_batch_size: rnn_batch_size, self.rnn_step_size: rnn_step_size})[0]\n\n def get_output_batch(self, obs, rnn_batch_size, rnn_step_size):\n\n return self.output.eval(feed_dict={self.x: obs, self.rnn_batch_size: rnn_batch_size, self.rnn_step_size: rnn_step_size})\n\n\n def trainStep(self, action_in, y_batch, observation_batch, Num_batch, step_size):\n self.train_step.run(feed_dict = {self.action_target: action_in, self.y_prediction: y_batch, self.x: observation_batch, self.rnn_batch_size: Num_batch, self.rnn_step_size: step_size})\n\n# def saveModel(self, step, i):\n# saver = tf.train.Saver()\n# saver.save(self.sess, './buyer_model_'+str(i),global_step=step)\n \n\n\n\n","sub_path":"drqnMLEngine/DRQNbuyer.py","file_name":"DRQNbuyer.py","file_ext":"py","file_size_in_byte":4923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"329510928","text":"\"\"\"\nTwo elements of a binary search tree (BST) are swapped by mistake.\n\nRecover the tree without changing its structure.\n\nExample 1:\n\nInput: [1,3,null,null,2]\n\n 1\n /\n 3\n \\\n 2\n\nOutput: [3,1,null,null,2]\n\n 3\n /\n 1\n \\\n 2\nExample 2:\n\nInput: [3,1,4,null,null,2]\n\n 3\n / \\\n1 4\n /\n 2\n\nOutput: [2,1,4,null,null,3]\n\n 2\n / \\\n1 4\n /\n 3\nFollow up:\n\nA solution using O(n) space is pretty straight forward.\nCould you devise a constant space solution?\n\"\"\"\n\n# 2018-6-30\n# Recovery Binary Search Tree\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\n\"\"\"\nhttps://www.cnblogs.com/zuoyuan/p/3746594.html\n题目有一个附加要求就是要求空间复杂度为常数空间。而算法一的空间复杂度为O(N),还不够省空间。以下的解法也是中序遍历的写法,只是非常巧妙,使用了一个prev指针。例如一颗被破坏的二叉查找树如下:\n\n        4\n\n       / \\\n\n   2 6\n\n / \\ / \\\n\n 1 5 3 7\n\n很明显3和5颠倒了。那么在中序遍历时:当碰到第一个逆序时:为5->4,那么将n1指向5,n2指向4,注意,此时n1已经确定下来了。然后prev和root一直向后遍历,直到碰到第二个逆序时:4->3,此时将n2指向3,那么n1和n2都已经确定,只需要交换节点的值即可。prev指针用来比较中序遍历中相邻两个值的大小关系,很巧妙。 \n\"\"\"\nclass Solution:\n def recoverTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: void Do not return anything, modify root in-place instead.\n \"\"\"\n self.n1 = self.n2 = None\n self.prev = None\n self.FindTwoNodes(root)\n self.n1.val, self.n2.val = self.n2.val, self.n1.val\n return root\n\n\n def FindTwoNodes(self, root):\n if root:\n self.FindTwoNodes(root.left)\n if self.prev and self.prev.val > root.val:\n self.n2 = root\n if self.n1 == None: self.n1 = self.prev # 确定第一个逆序\n self.prev = root\n self.FindTwoNodes(root.right)","sub_path":"LeetCode/python/99___________hard_Recovery Binary Search Tree.py","file_name":"99___________hard_Recovery Binary Search Tree.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"146369904","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\nimport time\n\n# instructions\nADD = 0b10100000 # 0\nAND = 0b10101000 # 8\nCALL = 0b01010000 # 0\nCMP = 0b10100111 # 7\nHLT = 0b00000001 # 1\nJEQ = 0b01010101 # 5\nJMP = 0b01010100 # 4\nJNE = 0b01010110 # 6\nLDI = 0b10000010 # 2\nMUL = 0b10100010 # 2\nPOP = 0b01000110 # 6\nPRN = 0b01000111 # 7\nPUSH = 0b01000101 # 5\nRET = 0b00010001 # 1\nST = 0b10000100 # 4\n\n# Other constants\nIM = 5\nIS = 6\nSP = 7 # stack pointer stored in register at index 7\n\n\nHARDCODED_PROGRAM = [\n 0b10000010, # LDI R0,8\n 0b00000000,\n 0b00001000,\n 0b01000111, # PRN R0\n 0b00000000,\n 0b00000001, # HLT\n ]\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n \n # registers R0 thru R7\n # R5 is reserved as the interrupt mask (IM)\n # R6 is reserved as the interrupt status (IS)\n # R7 is reserved as the stack pointer (SP)\n self.registers = [0b0] * 8\n\n # internal registers\n self.pc = 0 # PC: Program Counter, address of the currently executing instruction\n self.ir = None # IR: Instruction Register, contains a copy of the currently executing instruction\n self.mar = None # MAR: Memory Address Register, holds the memory address we are reading/writing\n self.mdr = None # MDR: Memory Data Register, holds the value to write or the value just read\n self.spl = None # stack pointer location\n self.interrupts_enabled = True\n\n self.equal = 0\n\n self.ram = [0b0] * 0xFF\n self.spl = 8 - 1\n self.registers[self.spl] = 0xF4\n\n self.branchtable = {\n ADD: self.add,\n AND: self.and_ls8,\n CALL: self.call,\n CMP: self.cmp_ls8,\n HLT: self.hlt,\n JMP: self.jmp,\n JEQ: self.jeq,\n JNE: self.jne,\n LDI: self.ldi,\n MUL: self.mul,\n POP: self.pop,\n PRN: self.prn,\n PUSH: self.push,\n RET: self.ret,\n ST: self.st,\n }\n\n # Emulator functions\n def load(self, program=HARDCODED_PROGRAM):\n \"\"\"Load program into memory\"\"\"\n\n address = 0\n if program != HARDCODED_PROGRAM:\n try:\n with open(program, 'r') as f:\n for line in f:\n instruction = line.split('#')[0].strip()\n if instruction == '':\n continue\n self.ram[address] = int(instruction, base=2)\n address += 1\n\n except FileNotFoundError:\n print(f'ERROR: File not found {program}')\n sys.exit(2)\n else:\n for instruction in program:\n self.ram[address] = instruction\n address += 1\n \n def ram_read(self, MAR):\n return self.ram[MAR]\n\n def ram_write(self, MDR, MAR):\n self.ram[MAR] = self.ram[MDR]\n\n def invoke_instruction(self):\n if self.ir in self.branchtable:\n self.branchtable[self.ir]()\n else:\n print(f\"ERROR: invalid instructions: {bin(self.ir)}\")\n sys.exit(1)\n\n def move_pc(self):\n instruction_sets_pc = ((self.ir << 3) & 255) >> 7\n if not instruction_sets_pc:\n self.pc += (self.num_operands + 1)\n \n def check_interrupts(self):\n masked_interrupts = self.registers[IM] & self.registers[IS]\n for i in range(8):\n interrupt_happened = ((masked_interrupts >> i) & 1) == 1\n if interrupt_happened:\n self.interrupts_enabled = False\n self.registers[IS] = self.registers[IS] & (255 - 2**i)\n self.registers[SP] -= 1\n self.ram[self.reg[SP]] = self.registers[self.pc]\n self.registers[SP] -= 1\n self.ram[self.reg[SP]] = self.registers[self.equal]\n for j in range(7):\n self.registers[SP] -= 1\n self.ram[self.registers[SP]] = self.registers[j]\n self.pc = self.ram[0xF8 + i]\n\n def set_operands(self):\n self.num_operands = self.ir >> 6\n if self.num_operands == 1:\n self.operand_a = self.ram_read(self.pc + 1)\n elif self.num_operands == 2:\n self.operand_a = self.ram_read(self.pc + 1)\n self.operand_b = self.ram_read(self.pc + 2)\n\n def alu(self, op, reg_a, reg_b=None):\n \"\"\"ALU operations.\"\"\"\n if op == \"ADD\":\n self.registers[reg_a] += self.registers[reg_b]\n elif op == \"SUB\":\n self.registers[reg_a] -= self.registers[reg_b]\n elif op == \"MUL\":\n self.registers[reg_a] *= self.registers[reg_b]\n elif op == \"CMP\":\n if self.registers[reg_a] == self.registers[reg_b]:\n self.equal = self.equal | 0b00000001\n else:\n self.equal = self.equal & 0b11111110\n\n if self.registers[reg_a] > self.registers[reg_b]:\n self.equal = self.equal | 0b00000010\n else:\n self.equal = self.equal & 0b11111101\n\n if self.registers[reg_a] < self.registers[reg_b]:\n self.equal = self.equal | 0b00000100\n else:\n self.equal = self.equal & 0b11111011\n elif op == \"AND\":\n self.registers[reg_a] = self.registers[reg_a] & self.registers[reg_b]\n else:\n raise Exception(\"ERROR: Invalid ALU operation.\")\n\n self.registers[reg_a] = self.registers[reg_a] & 0xFF\n\n # Ops\n def ldi(self):\n self.registers[self.operand_a] = self.operand_b\n\n def prn(self):\n print(self.registers[self.operand_a])\n\n def hlt(self):\n sys.exit(0)\n\n def add(self):\n self.alu('ADD', self.operand_a, self.operand_b)\n\n def mul(self):\n self.alu('MUL', self.operand_a, self.operand_b)\n\n def st(self):\n self.ram_write(self.reg[self.operand_b], self.reg[self.operand_a])\n\n def push(self):\n self.registers[SP] -= 1\n self.ram[self.registers[SP]] = self.registers[self.operand_a]\n \n def pop(self):\n if self.registers[SP] > 0xF3:\n print('Error: the stack is empty')\n sys.exit(3)\n else:\n self.registers[self.operand_a] = self.ram[self.registers[SP]]\n self.registers[SP] += 1\n\n def call(self):\n self.registers[SP] -= 1\n self.ram[self.registers[SP]] = self.pc + 2\n self.jmp()\n \n def ret(self):\n self.pc = self.ram[self.registers[SP]]\n\n def cmp_ls8(self):\n self.alu('CMP', self.operand_a, self.operand_b)\n\n def jmp(self):\n self.pc = self.registers[self.operand_a]\n\n def jeq(self):\n if self.equal & 0b00000001 == 1:\n self.jmp()\n else:\n self.pc += 2\n \n def jne(self):\n if self.equal & 0b00000001 == 0:\n self.jmp()\n else:\n self.pc += 2\n \n def and_ls8(self):\n self.alu('AND', self.operand_a, self.operand_b)\n\n # Emulator run\n def run(self):\n \"\"\"Run the CPU\"\"\"\n running = True\n interrupt_time = time.time() + 60\n\n timer = True\n\n while True:\n if timer:\n if time.time() > interrupt_time:\n self.reg[6] = self.reg[6] | 0b00000001\n interrupt_time = time.time() + 60\n if self.interrupts_enabled:\n self.check_interrupts()\n self.ir = self.ram_read(self.pc)\n self.set_operands()\n self.invoke_instruction()\n self.move_pc()\n","sub_path":"cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":7738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"330298831","text":"\"\"\"Wrapper script to execute a python script corresponding to the message given from mosquitto.\nThis script is running as a windows service and starts the mosquitto_sub process waiting for\nincoming messages\nExample:\n Example usage is to register a task in \"task scheduler\" app on windows 10 to run this python script\n $ python executionMode.py\nAttributes:\n execMode (string): Attribute to create a dictionary and execute the corresponding function based\n on the message recieved\n load (): Executes the corresponding python script for message \"load\"\n execute (): Executes the corresponding python script for message \"execute\"\n reset() : Executes the corresponding python script for message \"reset\"\n build() : Executes the corresponding python script for message \"build\"\nNotes: In order for this script to run you have to install mosquitto MQTT and register it as\n a windows service. The mosquitto installation path should also be in %PATH% variable in order\n for this script to run mosquitto_sub.exe.\n \n The message that is expected from a remote machine should have the following format (CSV):\n - field1: the string message i.e \n - field2: the path of the file as it is stored in the remote machine\n - field3: the \"userName@IP:\" of the remote server\n\"\"\"\nimport subprocess\nimport glob, os\nimport time\nimport shutil\nimport pandas as pd\nimport json\n\ndef load():\n \"\"\" Function to be called when a user wants to load a simulink model\n This function will run the corresponding python script for load process of the simulink model\n \"\"\"\n subprocess.Popen(['python','load.py'])\n\ndef execute(filesMessage,fPath):\n \"\"\" Function to be called when a user wants to execute a simulink model\n This function will run the corresponding python script for executing a simulink model\n \"\"\"\n p1 = subprocess.Popen(['python','execute.py','--path',fPath])\n p1.wait()\n\ndef reset():\n \"\"\" Function to be called when a user wants to reset a simulink model\n This function will run the corresponding python script for reseting a simulink model\n \"\"\"\n subprocess.Popen(['python','reset.py'])\n\ndef edit():\n \"\"\" Function to be called when a user wants to build a simulink model\n This function will run the corresponding python script for building a simulink model\n \"\"\"\n subprocess.Popen(['python','edit.py'])\n\ndef createExcelFile(fileName,finalFileName):\n rgx = \"\"\n if fileName != 'Heat.csv':\n rgx = '.\\\\' + fileName + '*'\n with open(fileName,'wb') as wfd:\n for f in glob.glob(rgx):\n with open(f,'a') as fd:\n fd.write('\\n')\n\n with open(fileName,'wb') as wfd:\n for f in glob.glob(rgx):\n with open(f,'rb') as fd:\n shutil.copyfileobj(fd, wfd)\n\n with open(fileName) as f:\n content = f.readlines()\n fileName=\"Final_\"+fileName\n with open(fileName, 'w') as f:\n for value in content:\n if value != '':\n f.write(\"%s\\n\" % value)\n finalFile = pd.read_csv(fileName)\n finalFile = finalFile.drop(labels='Time', axis=1)\n finalFile.to_excel(finalFileName, index=False)\n\ndef executeMode(message,filePath):\n \"\"\" Function to be called when the user sends a message to execute a specific mode\n This function will initiate the process given in the recieved message\n \"\"\"\n switcher = {\n \"load\": load,\n \"execute\": execute,\n \"reset\": reset,\n \"edit\" : edit\n }\n timeStamp = time.time()\n os.makedirs(\"Simulation_\" + str(timeStamp))\n destPath = \"Simulation_\" + str(timeStamp)\n os.chdir(destPath)\n for line in message.split('########'):\n if line == '':\n continue\n file = switcher.get(line.rstrip(), \"Invalid Mode\")\n if line.rstrip() == 'Control_initialization.txt':\n file = line.rstrip()\n elif line.rstrip() == 'Economy_environment_initialization.txt':\n file = line.rstrip()\n elif line.rstrip() == 'Parameters_initialization.txt':\n file = line.rstrip()\n elif line.rstrip() == 'Heat.csv':\n file = line.rstrip()\n elif 'PV.csv' in line.rstrip():\n file = line.rstrip()\n elif 'Wind.csv' in line.rstrip():\n file = line.rstrip()\n elif 'Electricity.csv' in line.rstrip():\n file = line.rstrip()\n else:\n file = 'Invalid Mode'\n if file != 'Invalid Mode':\n fileName = line.rstrip()\n else:\n with open(fileName, \"w\") as f:\n f.write(line.rstrip())\n\n createExcelFile('Heat.csv','Heat.xlsx')\n createExcelFile('Electricity.csv','Electricity.xlsx')\n createExcelFile('PV.csv','PV.xlsx')\n createExcelFile('Wind.csv','Wind.xlsx')\n os.chdir(\"..\")\n files = [f for f in os.listdir('.') if os.path.isfile(f)]\n for file in files:\n pathFile = os.path.join(os.path.dirname(os.path.abspath(__file__)),file)\n shutil.copy2(pathFile,destPath)\n filesDest = [f for f in os.listdir(destPath)]\n time.sleep(2)\n os.chdir(destPath)\n execute(message,filePath)\n os.chdir(\"..\")\n time.sleep(15)\n #shutil.rmtree(destPath, ignore_errors=True)\n\nif __name__ == \"__main__\":\n allFiles = 0\n message=\"\"\n proc = subprocess.Popen(['mosquitto_sub','-h','localhost','-t','SendSimulator'],stdout=subprocess.PIPE)\n for msg in iter(proc.stdout.readline,''):\n actualMessage = msg.decode(\"utf-8\")\n msg = msg.decode(\"utf-8\")\n if \"END OF SIM\" not in msg:\n message = message + msg\n else:\n path = msg.split(\":\")[1]\n executeMode(message,path)\n message = \"\"\n","sub_path":"planet-rest-api/server/pythonScripts/executionMode.py","file_name":"executionMode.py","file_ext":"py","file_size_in_byte":5575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"473783563","text":"from PIL import Image#PIL是优秀的图像处理框架\nfrom PIL import ImageFont#imagefont 模块定义了相同名称的类,即imagefont类,这个类的实例存储bitmap字体,用于imageDraw类的text()方法\nfrom PIL import ImageDraw#ImageDraw模块提供了图像对象的简单2D绘制。用户可以使用这个模块创建新的图像,注释或润饰已存在图像,为web应用实时产生各种图形。\n\ndef white_to_transparent(img):\n img=img.convert('RGBA')#返回一个转换后的图像副本\n datas=img.getdata()\n newData=[]\n for item in datas:#循坏语句\n if item[0]==255 and item[1]==255:\n newData.append((255,255,255,0))\n else:\n newData.append(item)\n img.putdata(newData)#赋给图片新的像素数据\n return img\n\nif __name__==\"__main__\":\n p1_name=\"b.png\"\n p2_name=\"a.png\"\n #打开两张png图片,注意为当前路径\n p1_image=Image.open(p1_name)\n p2_image=Image.open(p2_name)\n p2_transparent=white_to_transparent(p2_image)\n p1_image.paste(p2_transparent,(0,0),p2_transparent)#将一张图粘贴到另一张图上,将p2_transparent粘贴到p1_image上,复制p2_transparent时是从(0,0)左上角开始的\n\n # user_font=ImageFont.truetype(\"./yahei.TTF\",32)\n draw=ImageDraw.Draw(p1_image)#在p1_image上绘制文字、图像\n draw.text((152,8),u'12')\n p1_image.save(\"final.png\",\"PNG\")\n","sub_path":"0000/0000.py","file_name":"0000.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"542355013","text":"import os\nimport logging\nimport transaction\n\nfrom pyramid.config import Configurator\nfrom pyramid.events import subscriber, ApplicationCreated\nfrom pyramid.security import Allow, Everyone, Authenticated, ALL_PERMISSIONS\n\nfrom sqlalchemy import engine_from_config\nfrom pycountry import subdivisions\n\nfrom backend.models.state import State\nfrom backend import db\n\ndef postgres_url():\n addr = os.environ[\"DB_PORT_5432_TCP_ADDR\"]\n port = os.environ[\"DB_PORT_5432_TCP_PORT\"]\n return \"postgresql+psycopg2://postgres:@{0}:{1}{2}\".format(addr, port, \"/postgres\")\n\n\n@subscriber(ApplicationCreated)\ndef add_states(event):\n hu3 = \"BR\"\n states_br = subdivisions.get(country_code=hu3)\n for state in states_br:\n new_code = state.code.split(\"-\")[-1].lower()\n if State.query.filter_by(code=new_code).first():\n logging.info(\"{} ja adicionado\".format(new_code))\n else:\n with transaction.manager:\n logging.info(\"Adicionando: {}\".format(new_code))\n new_state = State(code=new_code)\n db.DBSession.add(new_state)\n return True\n\n\nclass RootFactory:\n __acl__ = [\n (Allow, Everyone, \"all\"),\n (Allow, Authenticated, \"view\")\n ]\n def __init__(self, request):\n pass\n\n\ndef main(global_config, **settings):\n \"\"\" This function returns a Pyramid WSGI application.\n \"\"\"\n settings[\"sqlalchemy.url\"] = postgres_url()\n\n engine = engine_from_config(settings, \"sqlalchemy.\")\n db.DBSession.configure(bind=engine)\n db.Base.metadata.bind = engine\n\n config = Configurator(settings=settings)\n config.set_root_factory(RootFactory)\n config.set_default_permission(\"all\")\n\n config.include(\"pyramid_jwtauth\")\n\n config.add_route(\"home\", \"/\")\n config.add_route(\"states\", \"/states/\")\n\n config.add_route(\"auth.register\", \"/auth/register/\")\n config.add_route(\"auth.login\", \"/auth/login/\")\n config.add_route(\"auth.logout\", \"/auth/logout/\")\n\n config.add_route(\"girias\", \"/girias/\")\n\n config.scan()\n return config.make_wsgi_app()\n","sub_path":"backend/backend/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"146697171","text":"import random\n\ndef rank(pokerhand): \n suits= set()\n cvals=[]\n straightnum = 0\n test = 0\n test1 = 0\n handvalue = {'highcard':0,'onepair':1,'twopair':2,'threeofakind':3,'straight':4,'flush':5,'fullhouse':6,'fourofakind':7,'straightflush':8}\n valuelst = []\n for c in hand:\n suits.add(c[1])\n if len(suits) == 1:\n valuelst.append('flush')\n cvals=[]\n for c in hand:\n cvals.append(\"_23456789TJQKA\".index(c[0]))\n cvals.sort()\n print(cvals)\n for card in cvals:\n if cvals.index(card)+1 < len(cvals)-1 and card == cvals[cvals.index(card)+1]:\n if cvals.index(card)+2 < len(cvals) and cvals[cvals.index(card)+1] == cvals[cvals.index(card)+2]:\n if cvals.index(card)+3 < len(cvals) and cvals[cvals.index(card)+2] == cvals[cvals.index(card)+3]:\n if 'fourofakind' not in valuelst:\n valuelst.append('fourofakind')\n else:\n if 'threeofakind' not in valuelst:\n valuelst.append('threeofakind')\n else:\n if 'onepair' not in valuelst and test == 0:\n valuelst.append('onepair')\n match1= cvals.index(card)\n test += 1\n elif cvals[cvals.index(card)] != cvals[match1] and test ==1:\n valuelst.append('twopair')\n valuelst.remove('onepair')\n test += 1\n if cvals.index(card)+1 < len(cvals) and (card + 1) == cvals[cvals.index(card)+1]:\n straightnum +=1\n if straightnum == 4 and test1 == 0:\n valuelst.append('straight')\n test1 += 1\n else:\n pass\n if 'threeofakind' in valuelst and 'onepair' in valuelst:\n valuelst.append('fullhouse')\n valuelst.remove('threeofakind')\n valuelst.remove('onepair')\n elif 'flush' in valuelst and 'straight' in valuelst:\n valuelst.append('straightflush')\n valuelst.remove('flush')\n valuelst.remove('straight')\n elif valuelst == []:\n valuelst.append('highcard')\n a = valuelst[0]\n return handvalue[a]\n\ndeck=[str(a)+str(b) for a in \"23456789TJQKA\" for b in \"CSDH\"]\nrandom.shuffle(deck)\nfor a in range(0,10):\n if len(deck) < 5:\n deck=[str(a)+str(b) for a in \"23456789TJQKA\" for b in \"CSDH\"]\n random.shuffle(deck)\n hand= deck[:5]\n print(hand)\n rank(hand)\n for card in hand: \n deck.remove(card)\n\n#hand= ['TS','2S','8S','KS','9S']\n#rank(hand)\n","sub_path":"CSci 1133/pokerhandrank2.py","file_name":"pokerhandrank2.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"346183013","text":"import numpy as np\nimport pandas as pd\n\nimport os, sys\n\nimport base64\nimport io\n\nimport dash\nimport dash.dcc as dcc\nimport dash.html as html\n# import dash_core_components as dcc\n# import dash_html_components as html\n\nfrom dash.dependencies import Input, Output, State\nfrom dash.exceptions import PreventUpdate\n\nimport plotly.graph_objs as go\nimport plotly.express as px\n\nfrom utils import *\n\n# App Layout -----------------------------------------------------------------\n# ----------------------------------------------------------------------------\n\ndef create_layout(app):\n return html.Div(\n className=\"row\",\n children = [\n\n html.Div(\n className='four columns',\n style = {'height': 1200, 'background-color': '#f7f7f7'},\n children=[\n\n html.Div(\n style={'width': '96%', 'textAlign': 'center', 'margin-top': '20px'},\n children=[\n dcc.Upload(\n id='upload-data',\n children=html.Div(\n children=[\n 'Drag and Drop or ',\n html.A('Select File')\n ]\n ),\n style={\n 'width': '100%',\n 'height': '60px',\n 'lineHeight': '60px',\n 'borderWidth': '1px',\n 'borderStyle': 'dashed',\n 'borderRadius': '5px',\n 'textAlign': 'center',\n 'margin': '10px'\n }\n ),\n\n html.Label(id='upload-filename'),\n ]\n ),\n\n html.Div(\n style={'width': '96%', 'textAlign': 'center', 'margin-top': '20px'},\n children=[\n \n html.H6(\n children = 'Select Variable',\n style = {'width': '95%'},\n ),\n\n dcc.Dropdown(\n id = 'select-variable', \n placeholder = 'select variables', \n )\n ]\n ), \n\n html.Div(\n style={'width': '96%', 'textAlign': 'center', 'margin-top': '20px'},\n children=[\n html.H6(\n children = 'Select Mann-Kendall Test',\n style = {'width': '95%'},\n ),\n dcc.Dropdown(\n id = 'select-mktest', \n options = [\n {'label': 'Original Mann-Kendall Test', 'value': 'original'},\n {'label': 'Hamed and Rao Modified MK Test', 'value': 'rao'},\n {'label': 'Yue and Wang Modified MK Test', 'value': 'yue'},\n {'label': 'Modified MK Test using Pre-Whitening Method', 'value': 'prewhiten'}, \n {'label': 'Modified MK Test using Trend Free Pre-Whitening Method', 'value': 'trendfree'}\n ], \n value = 'trendfree', \n )\n ]\n ), \n\n html.Div(\n style={'width': '96%', 'textAlign': 'center', 'margin-top': '20px'},\n children=[\n html.H6(\n children = 'Trend Line Type',\n style = {'width': '95%'},\n ),\n dcc.Checklist(\n id = 'trend-line-type',\n options = [\n {'label': 'Sens Slope', 'value': 'sens'},\n {'label': 'Linear Regression', 'value': 'linear'},\n {'label': 'Upper Bound', 'value': 'upper'},\n {'label': 'Lower Bound', 'value': 'lower'},\n ], \n value = ['sens'], \n labelStyle={'display': 'block', 'float': 'left', 'margin-right': '24px', 'margin-bottom': '10px'},\n # inputStyle={'margin-right': '30px'},\n style = {'display': 'inline-block', 'margin-left': '30px'}\n ),\n ]\n ),\n\n html.Div(\n style={'width': '96%', 'textAlign': 'center', 'margin-top': '20px'}, \n children = [\n html.Button(\n id = 'run-button', \n n_clicks = 0, \n children = 'RUN',\n ),\n ]\n ),\n\n html.Div(\n style={'width': '85%', 'padding-left': '5%', 'margin-top': '50px'}, \n children=[\n dcc.Markdown(\n id = 'mktest-output',\n style = {'background-color': 'white'}\n # 'display': 'flex', 'align-items': 'center', 'justify-content': 'center', 'padding-left': '10%', \n ),\n ]\n ),\n ]\n ),\n\n html.Div(\n className='eight columns',\n style={'height': 1200, 'background-color': '#f7f7f7'},\n children=[\n dcc.Graph(id = 'trendplot'),\n dcc.Store(id = 'input-data', data = None), \n ]\n )\n ],\n )\n\ndef demo_callbacks(app):\n\n @app.callback(\n [\n Output('select-variable', 'options'), \n Output('input-data', 'data'), \n Output('upload-filename', 'children')\n ], \n [Input('upload-data', 'contents')],\n [State('upload-data', 'filename')]\n )\n def load_data(contents, filename):\n\n if contents:\n\n content_type, content_string = contents.split(',')\n decoded = base64.b64decode(content_string)\n\n fext = filename.split('.')[-1]\n\n if fext in ['csv', 'xls', 'xlsx']:\n\n if fext == 'csv':\n df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))\n else:\n df = pd.read_excel(io.BytesIO(decoded))\n\n df = df.set_index(df.columns[0])\n js = df.to_json(orient='columns') # if not set orient, index will be lost\n\n varname_list = df.columns.tolist()\n options = [{'label': item, 'value': item} for item in varname_list]\n\n return options, js, filename\n\n else:\n print('Unacceptable Data Format!')\n raise PreventUpdate\n else: \n raise PreventUpdate\n\n @app.callback(\n [Output('trendplot', 'figure'), Output('mktest-output', 'children')],\n [Input('run-button', 'n_clicks'), Input('input-data', 'data')],\n [\n State('select-variable', 'value'),\n State('select-mktest', 'value'), \n State('trend-line-type', 'value')\n ]\n )\n def perform_trend_analysis(n_clicks, data, varname, method, trlines):\n\n if (data is None) | (varname is None):\n raise PreventUpdate\n\n else:\n\n df = pd.read_json(data, orient='columns')\n\n ts = df.loc[:, varname]\n t = ts.index.values\n y = ts.values\n x = np.arange(len(y))\n\n # MK-test and Sen's slope\n slp, intp, pvalue, pvalue_d, n = run_mktest(x, y, method=method)\n y2 = slp * x + intp\n\n # linear regression\n slp_lr, intp_lr, rsq = simple_linear_regression(x, y)\n y3 = slp_lr * x + intp_lr\n\n # upper and lower bound of Sen's slope\n _, slp_up, slp_lo = sens_slope_lub(y, alpha=0.05)\n y4 = slp_up * x + intp\n y5 = slp_lo * x + intp \n\n data = [\n go.Scatter(x=t, y=y, mode='markers', text=t, name='Time Series', showlegend=False, \n marker={'color': 'grey', 'size': 6}, \n hovertemplate='Time: %{text}'+'
    Value: %{y:.3f}
    '\n )\n ]\n if 'sens' in trlines:\n data.append(\n go.Scatter(x=t, y=y2, mode='lines', name='Sens Slope', showlegend=True, \n line={'color': 'green', 'width': 2})\n )\n if 'linear' in trlines:\n data.append(\n go.Scatter(x=t, y=y3, mode='lines', name='Linear Regression', showlegend=True, \n line={'color': 'blue', 'width': 2})\n )\n if 'upper' in trlines:\n data.append(\n go.Scatter(x=t, y=y4, mode='lines', name='Upper Bound', showlegend=True, \n line={'color': 'green', 'dash': 'dot', 'width': 2})\n )\n if 'lower' in trlines:\n data.append(\n go.Scatter(x=t, y=y5, mode='lines', name='Lower Bound', showlegend=True, \n line={'color': 'green', 'dash': 'dot', 'width': 2})\n )\n\n if pvalue > 0.1:\n bgcolor = 'rbga(0, 0, 0, 0)'\n else:\n bgcolor = 'rgba(256, 0, 0, 0.2)' if slp > 0 else 'rgba(0, 0, 256, 0.2)'\n\n xticks = np.linspace(x[0], x[-1], 5).astype(int)\n xticks_label = t[xticks]\n\n layout = {\n 'title': 'Trend: {}'.format(varname),\n 'font': dict(size=18),\n 'hovermode': 'closest', # closest\n 'plot_bgcolor': bgcolor,\n 'showlegend': True,\n 'autosize': False,\n 'xaxis': dict(title='Time', zeroline=False, domain=[0., .98], showgrid=False, automargin=True), \n 'yaxis': dict(title='', zeroline=True, domain=[0., .98], showgrid=False, automargin=True),\n 'paper_bgcolor': '#F2F2F2',\n # 'width': 800, \n 'height': 600, \n 'margin': dict(l=2, r=2, t=50, b=2),\n }\n\n figure = {'data': data, 'layout': layout}\n\n text = '''\n\n #### Summary\n\n Sen's Slope: {:.8f}\n\n MK-Test P-Value: {:.3f}\n\n Number of Samples: {:d}\n\n OLS Slope: {:.8f}\n\n R^2: {:.3f}\n\n Sen's Slope Upper Bound: {:.8f}\n\n Sen's Slope Lower Bound: {:.8f}\n\n '''.format(slp, pvalue, n, slp_lr, rsq, slp_up, slp_lo)\n\n return figure, text\n","sub_path":"demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":11564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"298388453","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nExample to crawl search interest data from Google trends (unofficial) API wrapper.\n\nExample inputs:\n{\"keyword\": \"adele - rolling in the deep\", \"gt_queries\": \"\\\"adele\\\" \\\"rolling in the deep\\\"\", \"vid\": [\"O-Dmt2-7VqQ\", \"rYEDA3JcQqw\"], \"start_date\": \"2010-12-09\", \"popularity\": 1135201492}\n\nExample query:\npython example.py -i data/example_queries.json -o data/example_out.json -v\n\"\"\"\n\nfrom __future__ import print_function, division\nimport sys, os, argparse, time, json, logging\nimport numpy as np\nfrom datetime import datetime, timedelta\n\nfrom pytrends.request import TrendReq\nfrom pytrends.utils import reformat, diff_month, calendar_days\nfrom pytrends import dailydata\n# from pytrends.utils import plot_interest_over_time\n\n\nif __name__ == '__main__':\n # == == == == == == Part 1: Read youtube insight json from file == == == == == == #\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--input', help='input file path', required=True)\n parser.add_argument('-p', '--plot', dest='plot', action='store_true', default=False)\n parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', default=False)\n parser.set_defaults(plot=False)\n parser.set_defaults(verbose=False)\n args = parser.parse_args()\n\n input_path = args.input\n logging.basicConfig(filename='./google_trends_crawler.log', level=logging.INFO)\n\n if not os.path.exists(input_path):\n print('>>> Input file does not exist!')\n print('>>> Exit...')\n sys.exit(1)\n\n # == == == == == == Part 3: Start Google trends crawler == == == == == == #\n # read queries from the input file\n with open(input_path, 'r') as input_data:\n for line in input_data:\n query_json = json.loads(line.rstrip())\n keyword = query_json['keyword']\n mid = query_json['mid']\n\n start_date_str = query_json['start_date']\n end_date_str = query_json['end_date']\n start_date_obj = datetime.strptime(start_date_str, '%Y-%m-%d')\n logging.info('>>> Query for topic {0}'.format(keyword))\n\n # result dict\n google_trends = {'start_date': start_date_str, 'end_date': end_date_str, 'daily_search': []}\n\n res_df = dailydata.get_daily_data(word=mid, start_year=2017, start_mon=1, stop_year=2018, stop_mon=4)\n res_df.to_csv('data/{0}.csv'.format(keyword))\n","sub_path":"example2.py","file_name":"example2.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"615922387","text":"#!/usr/bin/python\n\n#### Very stupid bad way of doing the job\n#### visually fit a curve to the one of the manual , do not trust this too much !\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n@np.vectorize\ndef get_ir_from_dist(d, cut_dist, half_dist, max_dist, order):\n # d (mm)\n if(d <= cut_dist):\n return 1023 + d * (1000.-1023.)/30\n elif(d >= max_dist):\n return 0\n else:\n alpha = (half_dist - cut_dist) / (np.exp(-np.log(0.5)/order) - 1.0)\n return 1000. / ((d - cut_dist)/alpha + 1)**order\n\n@np.vectorize\ndef get_dist_from_ir(ir, cut_dist, half_dist, max_dist, order):\n if(ir >= 1000):\n return (ir - 1023) * cut_dist / (1000 - 1023.)\n else:\n alpha = (half_dist - cut_dist) / (np.exp(-np.log(0.5)/order) - 1.0)\n d = (np.exp(1.0/order * np.log(1000./ir)) - 1) * alpha + cut_dist\n if(d >= max_dist):\n return np.nan\n else:\n return d\n \n\ncut_dist = 30 # mm\nmax_dist = 200 # mm\nhalf_dist = 50 # mm, where the response is 512\norder = 5\n\ndvalues = np.linspace(0, 250, 1000) # mm\nIR_value = get_ir_from_dist(dvalues, cut_dist, half_dist, max_dist, order)\n\nIR_values = np.linspace(0.01, 1023, 1000)\ndistances = get_dist_from_ir(IR_values, cut_dist, half_dist, max_dist, order)\n\nplt.figure()\nplt.subplot(1,2,1)\nplt.plot(dvalues/10, IR_value)\nplt.xlabel(\"distance to the wall (cm)\")\nplt.ylabel(\"Measured value\")\nplt.ylim([0, 1024])\nplt.xlim([0, max_dist/10])\nplt.subplot(1,2,2)\nplt.plot(IR_values, distances/10)\nplt.xlabel(\"Measured value\")\nplt.ylabel(\"distance to the wall (cm)\")\nplt.xlim([0, 1024])\nplt.ylim([0, max_dist/10])\nplt.show()\n","sub_path":"documentation/kteams/kteams_driver/scripts/calibrate_ir_khepera.py","file_name":"calibrate_ir_khepera.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"587235821","text":"# Задание-1:\n# Напишите функцию, округляющую полученное произвольное десятичное число\n# до кол-ва знаков (кол-во знаков передается вторым аргументом).\n# Округление должно происходить по математическим правилам (0.6 --> 1, 0.4 --> 0).\n# Для решения задачи не используйте встроенные функции и функции из модуля math.\n\"\"\"\nНа поверку, оказалось самым сложным заданием для меня из всех задач вообще(в том числе и hard)\nОригинальный round работает даже с отрицательными количеством знаков. Его я реализовать не смог.\nДанная задача отличается тем, что стандартные операции округления работают по принципу >= 0.5 >\nТут же, в случае 0.5 требуется брать следующее число на сравнение.\n\"\"\"\n\ndef my_round(number: float, ndigits: int=1):\n \"\"\"\n Функция, округляющаяя полученное произвольное десятичное число до заданного количества знаков.\n Будем считать, что количество знаков после запятой - положительное число больше 1\n Также, считаем что произвольное число положительное\n :param number: число типа float\n :param ndigits: количество знаков после запятой\n :return: округленное число типа float\n \"\"\"\n def check_next_num(string: str, ind: int):\n \"\"\"\n Функия смотрит на заданный индекс строки.\n Округление считается по математическим правилам (0.6 --> 1, 0.4 --> 0).\n Если число по индексу == 5 то берется следующее.\n Возвращает True если округлять нужно в большую сторону.\n :param string: строка с записанным числом\n :param ind: индекс, с которого начинается проверка\n :return:\n \"\"\"\n for i in range(ind, len(string)):\n if string[i] > '5':\n return True\n elif string[i] < '5':\n return False\n\n # Проверка что заданное количество знаков после запятой более 1\n # И заданное число положительное\n if ndigits < 1 or number < 0:\n return None\n\n # Переводим число строку\n str_number = str(number)\n # Находим положение точки\n last_ind = ndigits + str_number.find(\".\")\n\n # Если заданное количество после запятой больше самого количества, то возвращаем число в изначальном виде\n if len(str_number) <= last_ind + 1:\n return number\n\n if check_next_num(str_number, last_ind + 1):\n result = float(str_number[:last_ind+1]) + (10 ** -(ndigits))\n else:\n result = float(str_number[:last_ind+1])\n\n return result\n\n\nprint(my_round(2.1265, 0)) # None\nprint(my_round(2.1255, 15)) # 2.1255\nprint(my_round(2.1234567, 5))\nprint(my_round(2.1999967, 5))\nprint(my_round(2.9999967, 5))\n\n\n# Задание-2:\n# Дан шестизначный номер билета. Определить, является ли билет счастливым.\n# Решение реализовать в виде ф��нкции.\n# Билет считается счастливым, если сумма его первых и последних цифр равны.\n# !!!P.S.: функция не должна НИЧЕГО print'ить\n\ndef lucky_ticket(ticket_number: int):\n \"\"\"\n Функция определяющая является ли шестизначный номер билета счастливым.\n Билет считается счастливым если суммы первых и последних цифр равны\n :param ticket_number: Целое шестизначное число\n :return: boolean\n \"\"\"\n\n # Переведем число в строку\n str_number = str(ticket_number)\n\n # Проверка если число не шестизначное\n if len(str_number) != 6:\n return False\n\n # При помощи функции map переводим символы строки в числа и суммируем. Далее, сравниваем суммы\n if sum(map(int, str_number[0:3])) == sum(map(int, str_number[3:])):\n return True\n else:\n return False\n\n\nprint(lucky_ticket(123006))\nprint(lucky_ticket(12321))\nprint(lucky_ticket(436751))\n","sub_path":"lesson03/home_work/hw03_easy.py","file_name":"hw03_easy.py","file_ext":"py","file_size_in_byte":5180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"33153881","text":"import base64\nimport random\nimport tools\n\ndef dechiffrer(cle,pathtext):\n clepriv=\"\"\n textalire=\"encour\"\n try : \n fichier = open (pathtext,\"r\")\n textadechiffrer = fichier.read()\n print (textadechiffrer)\n fichier2 = open (cle,\"r\")\n clepriv = fichier2.read()\n print (clepriv)\n except FileNotFoundError:\n print (\"pas de clé ou pas de fichier\")\n \n if tools.verifClepriv (clepriv):\n print('ici')\n n,d=tools.extractCle(clepriv,\"privee\")\n blocklenght = len(str(n))-1\n textalire = tools.gettext(textadechiffrer,blocklenght,n,d)\n\n\n print(textalire) \n","sub_path":"decrypt.py","file_name":"decrypt.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"214762376","text":"'''\r\nupbit_main.py\r\n#추출한 데이터를 통해 LSTM 학습\r\n#data 폴더안에 있는 모든 csv 학습\r\nAuthor: Huido Lee (j3jjj2021@naver.com)\r\n'''\r\nimport os\r\nfrom upbit_market import get_coin_data\r\nfrom upbit_deep import coin_train\r\nfrom upbit_deep_test import coin_predict\r\n\r\nif __name__ == '__main__':\r\n local_path = os.getcwd()\r\n coin_list_path = os.path.join(local_path, \"coin_list.txt\")\r\n if os.path.isfile(coin_list_path) is False:\r\n exit('coin_list.txt file does not exist.')\r\n f = open(coin_list_path, 'r', encoding='UTF8')\r\n lines = f.readlines()\r\n coin_list = []\r\n for line in lines:\r\n for coin in line.split():\r\n coin_list.append(coin)\r\n f.close()\r\n\r\n get_coin_data(local_path = local_path, step = 'days', coin_list = coin_list) \r\n coin_train(local_path = local_path, coin_list = coin_list)\r\n coin_predict(local_path= local_path, coin_list = coin_list)","sub_path":"upbit_main.py","file_name":"upbit_main.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"494281800","text":"import sys, itertools\ninput = sys.stdin.readline\n\nn, m = map(int, input().split())\n\nnums = [str(i + 1) for i in range(n)]\n\nfor num in list(itertools.combinations(nums, m)):\n print(' '.join(num))\n\n","sub_path":"backjoon/15650.py","file_name":"15650.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"442491927","text":"import math\nimport os\nimport random\nimport re\nimport sys\n\ndef moveChopsticks(chopsticks):\n\ttotalOfChopsticks = n\n\tfor i in range(0,n-1):\n\t\tfor j in range(i+1,n):\n\t\t\tdoTheyIntersect = intersect(chopsticks[i], chopsticks[j])\n\t\t\tif doTheyIntersect:\n\t\t\t\ttotalOfChopsticks-=2\n\tif totalOfChopsticks < 0:\n\t\ttotalOfChopsticks = 0\n\t\n\treturn totalOfChopsticks\n\n\ndef intersect(chopOne, chopTwo):\n\n\tif chopOne[0] == chopOne[2] and chopTwo[0] == chopTwo[2]:\n\t\tif (chopTwo[0] == chopOne[0] or chopTwo[2] == chopOne[2]) and (chopTwo[1] <= chopOne[3] or chopTwo[1] >= chopOne[1]):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tif chopOne[0] == chopOne[2] and chopTwo[1] == chopTwo[3]:\n\t\tif chopTwo[1] <= chopOne[3] or chopTwo[1] >= chopOne[1]:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tif chopOne[1] == chopOne[3] and chopTwo[1] == chopTwo[3]:\n\t\tif (chopTwo[1] == chopOne[1] or chopTwo[3] == chopOne[3]) and (chopTwo[0] <= chopOne[2] or chopTwo[0] >= chopOne[0]):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\nif __name__ == '__main__':\n\n n = int(input(\"Number of chopsticks: \"))\n chopsticks = []\n\n for i in range(0,n):\n \tchopstick = list(map(int, input().split()))\n \tchopsticks.append(chopstick)\n \t\n print(moveChopsticks(chopsticks))\n\n\n\n \n\n \n \n","sub_path":"Chinese Chopsticks/chopsticks.py","file_name":"chopsticks.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"157977479","text":"from unittest import TestCase\nfrom webpage_maker import main\n\n\nclass TestWebsite(TestCase):\n def test_website_name_brodie(self):\n main.website('brodie', 'description')\n with open('index.html', 'r') as file:\n internet = file.read()\n\n self.assertIn('brodie', internet)\n","sub_path":"test_website.py","file_name":"test_website.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"344050720","text":"import re\nimport numpy as np\nfrom itertools import dropwhile, combinations, islice\nimport string\nfrom scipy.special import binom\n\n\n# __all__ = ['np', 'fullfact_corrected', 'ff2n_corrected', 'fracfact']\n\n\ndef fullfact_corrected(levels):\n \"\"\"\n Create a general full-factorial design\n \n Parameters\n ----------\n levels : array-like\n An array of integers that indicate the number of levels of each input\n design factor.\n \n Returns\n -------\n mat : 2d-array\n The design matrix with coded levels 0 to k-1 for a k-level factor\n \n Example\n -------\n ::\n \n >>> fullfact([2, 4, 3])\n array([[ 0., 0., 0.],\n [ 1., 0., 0.],\n [ 0., 1., 0.],\n [ 1., 1., 0.],\n [ 0., 2., 0.],\n [ 1., 2., 0.],\n [ 0., 3., 0.],\n [ 1., 3., 0.],\n [ 0., 0., 1.],\n [ 1., 0., 1.],\n [ 0., 1., 1.],\n [ 1., 1., 1.],\n [ 0., 2., 1.],\n [ 1., 2., 1.],\n [ 0., 3., 1.],\n [ 1., 3., 1.],\n [ 0., 0., 2.],\n [ 1., 0., 2.],\n [ 0., 1., 2.],\n [ 1., 1., 2.],\n [ 0., 2., 2.],\n [ 1., 2., 2.],\n [ 0., 3., 2.],\n [ 1., 3., 2.]])\n \n \"\"\"\n n = len(levels) # number of factors\n nb_lines = np.prod(levels) # number of trial conditions\n H = np.zeros((nb_lines, n))\n\n level_repeat = 1\n range_repeat = np.prod(levels)\n for i in range(n):\n range_repeat //= levels[i]\n lvl = []\n for j in range(levels[i]):\n lvl += [j] * level_repeat\n rng = lvl * range_repeat\n level_repeat *= levels[i]\n H[:, i] = rng\n\n return H\n\n\n################################################################################\n\n\ndef ff2n_corrected(n):\n \"\"\"\n Create a 2-Level full-factorial design\n \n Parameters\n ----------\n n : int\n The number of factors in the design.\n \n Returns\n -------\n mat : 2d-array\n The design matrix with coded levels -1 and 1\n \n Example\n -------\n ::\n \n >>> ff2n(3)\n array([[-1., -1., -1.],\n [ 1., -1., -1.],\n [-1., 1., -1.],\n [ 1., 1., -1.],\n [-1., -1., 1.],\n [ 1., -1., 1.],\n [-1., 1., 1.],\n [ 1., 1., 1.]])\n \n \"\"\"\n return 2 * fullfact_corrected([2] * n) - 1\n\n\ndef ff2n(levels):\n return 2 * fullfact_corrected([2] * levels) - 1\n\n\n################################################################################\n\n\ndef fracfact_corrected(gen):\n \"\"\"\n Create a 2-level fractional-factorial design with a generator string.\n \n Parameters\n ----------\n gen : str\n A string, consisting of lowercase, uppercase letters or operators \"-\"\n and \"+\", indicating the factors of the experiment\n \n Returns\n -------\n H : 2d-array\n A m-by-n matrix, the fractional factorial design. m is 2^k, where k\n is the number of letters in ``gen``, and n is the total number of\n entries in ``gen``.\n \n Notes\n -----\n In ``gen`` we define the main factors of the experiment and the factors\n whose levels are the products of the main factors. For example, if\n \n gen = \"a b ab\"\n \n then \"a\" and \"b\" are the main factors, while the 3rd factor is the product\n of the first two. If we input uppercase letters in ``gen``, we get the same\n result. We can also use the operators \"+\" and \"-\" in ``gen``.\n \n For example, if\n \n gen = \"a b -ab\"\n \n then the 3rd factor is the opposite of the product of \"a\" and \"b\".\n \n The output matrix includes the two level full factorial design, built by\n the main factors of ``gen``, and the products of the main factors. The\n columns of ``H`` follow the sequence of ``gen``.\n \n For example, if\n \n gen = \"a b ab c\"\n \n then columns H[:, 0], H[:, 1], and H[:, 3] include the two level full\n factorial design and H[:, 2] includes the products of the main factors.\n \n Examples\n --------\n ::\n \n >>> fracfact(\"a b ab\")\n array([[-1., -1., 1.],\n [ 1., -1., -1.],\n [-1., 1., -1.],\n [ 1., 1., 1.]])\n \n >>> fracfact(\"A B AB\")\n array([[-1., -1., 1.],\n [ 1., -1., -1.],\n [-1., 1., -1.],\n [ 1., 1., 1.]])\n \n >>> fracfact(\"a b -ab c +abc\")\n array([[-1., -1., -1., -1., -1.],\n [ 1., -1., 1., -1., 1.],\n [-1., 1., 1., -1., 1.],\n [ 1., 1., -1., -1., -1.],\n [-1., -1., -1., 1., 1.],\n [ 1., -1., 1., 1., -1.],\n [-1., 1., 1., 1., -1.],\n [ 1., 1., -1., 1., 1.]])\n \n \"\"\"\n # Recognize letters and combinations\n A = [item for item in re.split(\"\\-|\\s|\\+\", gen) if item] # remove empty strings\n C = [len(item) for item in A]\n\n # Indices of single letters (main factors)\n I = [i for i, item in enumerate(C) if item == 1]\n\n # Indices of letter combinations (we need them to fill out H2 properly).\n J = [i for i, item in enumerate(C) if item != 1]\n\n # Check if there are \"-\" or \"+\" operators in gen\n U = [item for item in gen.split(\" \") if item] # remove empty strings\n\n # If R1 is either None or not, the result is not changed, since it is a\n # multiplication of 1.\n R1 = _grep(U, \"+\")\n R2 = _grep(U, \"-\")\n\n # Fill in design with two level factorial design\n H1 = ff2n(len(I))\n H = np.zeros((H1.shape[0], len(C)))\n H[:, I] = H1\n\n # Recognize combinations and fill in the rest of matrix H2 with the proper\n # products\n for k in J:\n # For lowercase letters\n xx = np.array([ord(c) for c in A[k]]) - 97\n\n # For uppercase letters\n if np.any(xx < 0):\n xx = np.array([ord(c) for c in A[k]]) - 65\n\n H[:, k] = np.prod(H1[:, xx], axis=1)\n\n # Update design if gen includes \"-\" operator\n if R2:\n H[:, R2] *= -1\n\n # Return the fractional factorial design\n return H\n\n\ndef _grep(haystack, needle):\n try:\n haystack[0]\n except (TypeError, AttributeError):\n return [0] if needle in haystack else []\n else:\n locs = []\n for idx, item in enumerate(haystack):\n if needle in item:\n locs += [idx]\n return locs\n\n\ndef _n_fac_at_res(n, res):\n \"\"\" Calculate number of possible factors for fractional factorial\n design with `n` base factors at resolution `res`.\n \"\"\"\n return sum(binom(n, r) for r in range(res - 1, n)) + n\n\n\n# __all__ = ['bbdesign_corrected']\n\n\ndef fracfact_by_res(n, res):\n \"\"\"\n Create a 2-level fractional factorial design with `n` factors\n and resolution `res`.\n Parameters\n ----------\n n : int\n The number of factors in the design.\n res : int\n Desired design resolution\n Returns\n -------\n H : 2d-array\n A m-by-`n` matrix, the fractional factorial design. m is the\n minimal amount of rows possible for creating a fractional\n factorial design matrix at resolution `res`\n Raises\n ------\n ValueError\n If the current design is not possible to construct.\n Notes\n -----\n The resolution of a design is defined as the length of the shortest\n word in the defining relation. The resolution describes the level of\n confounding between factors and interaction effects, where higher\n resolution indicates lower degree of confounding.\n For example, consider the 2^4-1-design defined by\n gen = \"a b c ab\"\n The factor \"d\" is defined by \"ab\" with defining relation I=\"abd\", where\n I is the unit vector. In this simple example the shortest word is \"abd\"\n meaning that this is a resolution III-design.\n In practice resolution III-, IV- and V-designs are most commonly applied.\n * III: Main effects may be confounded with two-factor interactions.\n * IV: Main effects are unconfounded by two-factor interactions, but\n two-factor interactions may be confounded with each other.\n * V: Main effects unconfounded with up to four-factor interactions,\n two-factor interactions unconfounded with up to three-factor\n interactions. Three-factor interactions may be confounded with\n each other.\n Examples\n --------\n ::\n >>> fracfact_by_res(6, 3)\n array([[-1., -1., -1., 1., 1., 1.],\n [ 1., -1., -1., -1., -1., 1.],\n [-1., 1., -1., -1., 1., -1.],\n [ 1., 1., -1., 1., -1., -1.],\n [-1., -1., 1., 1., -1., -1.],\n [ 1., -1., 1., -1., 1., -1.],\n [-1., 1., 1., -1., -1., 1.],\n [ 1., 1., 1., 1., 1., 1.]])\n >>> fracfact_by_res(5, 5)\n Traceback (most recent call last):\n ...\n ValueError: design not possible\n \"\"\"\n # Determine minimum required number of base-factors.\n min_fac = next(\n dropwhile(lambda n_: _n_fac_at_res(n_, res) < n, range(res - 1, n)), None\n )\n\n if min_fac is None:\n raise ValueError(\"design not possible\")\n elif min_fac > len(string.ascii_lowercase):\n # This check needs to be done to make sure that the number\n # of available are enough since `fracfact` parses design generator\n # characters. In practice, this is highly theoretical and it is\n # much more likely to run into memory-issues.\n raise ValueError(\"design requires too many base-factors.\")\n\n # Get base factors.\n factors = list(string.ascii_lowercase[:min_fac])\n\n # Fill out with factor combinations until `n` factors.\n factor_combs = (\n \"\".join(c)\n for r in range(res - 1, len(factors))\n for c in combinations(factors, r)\n )\n extra_factors = list(islice(factor_combs, n - len(factors)))\n\n # Concatenate `gen` string for `fracfact`.\n gen = \" \".join(factors + extra_factors)\n return fracfact_corrected(gen)\n\n\ndef bbdesign_corrected(n, center=None):\n \"\"\"\n Create a Box-Behnken design\n \n Parameters\n ----------\n n : int\n The number of factors in the design\n \n Optional\n --------\n center : int\n The number of center points to include (default = 1).\n \n Returns\n -------\n mat : 2d-array\n The design matrix\n \n Example\n -------\n ::\n \n >>> bbdesign(3)\n array([[-1., -1., 0.],\n [ 1., -1., 0.],\n [-1., 1., 0.],\n [ 1., 1., 0.],\n [-1., 0., -1.],\n [ 1., 0., -1.],\n [-1., 0., 1.],\n [ 1., 0., 1.],\n [ 0., -1., -1.],\n [ 0., 1., -1.],\n [ 0., -1., 1.],\n [ 0., 1., 1.],\n [ 0., 0., 0.],\n [ 0., 0., 0.],\n [ 0., 0., 0.]])\n \n \"\"\"\n assert n >= 3, \"Number of variables must be at least 3\"\n\n # First, compute a factorial DOE with 2 parameters\n H_fact = ff2n_corrected(2)\n # Now we populate the real DOE with this DOE\n\n # We made a factorial design on each pair of dimensions\n # - So, we created a factorial design with two factors\n # - Make two loops\n Index = 0\n nb_lines = int((0.5 * n * (n - 1)) * H_fact.shape[0])\n H = repeat_center(n, nb_lines)\n\n for i in range(n - 1):\n for j in range(i + 1, n):\n Index = Index + 1\n H[\n max([0, (Index - 1) * H_fact.shape[0]]) : Index * H_fact.shape[0], i\n ] = H_fact[:, 0]\n H[\n max([0, (Index - 1) * H_fact.shape[0]]) : Index * H_fact.shape[0], j\n ] = H_fact[:, 1]\n\n if center is None:\n if n <= 16:\n points = [0, 0, 0, 3, 3, 6, 6, 6, 8, 9, 10, 12, 12, 13, 14, 15, 16]\n center = points[n]\n else:\n center = n\n\n H = np.c_[H.T, repeat_center(n, center).T].T\n\n return H\n\n\nimport numpy as np\n\n# from pyDOE.doe_factorial import ff2n\nfrom pyDOE.doe_star import star\nfrom pyDOE.doe_union import union\nfrom pyDOE.doe_repeat_center import repeat_center\n\n__all__ = [\"ccdesign\"]\n\n\ndef ccdesign_corrected(n, center=(4, 4), alpha=\"orthogonal\", face=\"circumscribed\"):\n \"\"\"\n Central composite design\n \n Parameters\n ----------\n n : int\n The number of factors in the design.\n \n Optional\n --------\n center : int array\n A 1-by-2 array of integers, the number of center points in each block\n of the design. (Default: (4, 4)).\n alpha : str\n A string describing the effect of alpha has on the variance. ``alpha``\n can take on the following values:\n \n 1. 'orthogonal' or 'o' (Default)\n \n 2. 'rotatable' or 'r'\n \n face : str\n The relation between the start points and the corner (factorial) points.\n There are three options for this input:\n \n 1. 'circumscribed' or 'ccc': This is the original form of the central\n composite design. The star points are at some distance ``alpha``\n from the center, based on the properties desired for the design.\n The start points establish new extremes for the low and high\n settings for all factors. These designs have circular, spherical,\n or hyperspherical symmetry and require 5 levels for each factor.\n Augmenting an existing factorial or resolution V fractional \n factorial design with star points can produce this design.\n \n 2. 'inscribed' or 'cci': For those situations in which the limits\n specified for factor settings are truly limits, the CCI design\n uses the factors settings as the star points and creates a factorial\n or fractional factorial design within those limits (in other words,\n a CCI design is a scaled down CCC design with each factor level of\n the CCC design divided by ``alpha`` to generate the CCI design).\n This design also requires 5 levels of each factor.\n \n 3. 'faced' or 'ccf': In this design, the star points are at the center\n of each face of the factorial space, so ``alpha`` = 1. This \n variety requires 3 levels of each factor. Augmenting an existing \n factorial or resolution V design with appropriate star points can \n also produce this design.\n \n Notes\n -----\n - Fractional factorial designs are not (yet) available here.\n - 'ccc' and 'cci' can be rotatable design, but 'ccf' cannot.\n - If ``face`` is specified, while ``alpha`` is not, then the default value\n of ``alpha`` is 'orthogonal'.\n \n Returns\n -------\n mat : 2d-array\n The design matrix with coded levels -1 and 1\n \n Example\n -------\n ::\n \n >>> ccdesign(3)\n array([[-1. , -1. , -1. ],\n [ 1. , -1. , -1. ],\n [-1. , 1. , -1. ],\n [ 1. , 1. , -1. ],\n [-1. , -1. , 1. ],\n [ 1. , -1. , 1. ],\n [-1. , 1. , 1. ],\n [ 1. , 1. , 1. ],\n [ 0. , 0. , 0. ],\n [ 0. , 0. , 0. ],\n [ 0. , 0. , 0. ],\n [ 0. , 0. , 0. ],\n [-1.82574186, 0. , 0. ],\n [ 1.82574186, 0. , 0. ],\n [ 0. , -1.82574186, 0. ],\n [ 0. , 1.82574186, 0. ],\n [ 0. , 0. , -1.82574186],\n [ 0. , 0. , 1.82574186],\n [ 0. , 0. , 0. ],\n [ 0. , 0. , 0. ],\n [ 0. , 0. , 0. ],\n [ 0. , 0. , 0. ]])\n \n \n \"\"\"\n # Check inputs\n assert isinstance(n, int) and n > 1, '\"n\" must be an integer greater than 1.'\n assert alpha.lower() in (\n \"orthogonal\",\n \"o\",\n \"rotatable\",\n \"r\",\n ), 'Invalid value for \"alpha\": {:}'.format(alpha)\n assert face.lower() in (\n \"circumscribed\",\n \"ccc\",\n \"inscribed\",\n \"cci\",\n \"faced\",\n \"ccf\",\n ), 'Invalid value for \"face\": {:}'.format(face)\n\n try:\n nc = len(center)\n except:\n raise TypeError(\n 'Invalid value for \"center\": {:}. Expected a 1-by-2 array.'.format(center)\n )\n else:\n if nc != 2:\n raise ValueError(\n 'Invalid number of values for \"center\" (expected 2, but got {:})'.format(\n nc\n )\n )\n\n # Orthogonal Design\n if alpha.lower() in (\"orthogonal\", \"o\"):\n H2, a = star(n, alpha=\"orthogonal\", center=center)\n\n # Rotatable Design\n if alpha.lower() in (\"rotatable\", \"r\"):\n H2, a = star(n, alpha=\"rotatable\")\n\n # Inscribed CCD\n if face.lower() in (\"inscribed\", \"cci\"):\n H1 = ff2n_corrected(n)\n H1 = H1 / a # Scale down the factorial points\n H2, a = star(n)\n\n # Faced CCD\n if face.lower() in (\"faced\", \"ccf\"):\n H2, a = star(n) # Value of alpha is always 1 in Faced CCD\n H1 = ff2n_corrected(n)\n\n # Circumscribed CCD\n if face.lower() in (\"circumscribed\", \"ccc\"):\n H1 = ff2n_corrected(n)\n\n C1 = repeat_center(n, center[0])\n C2 = repeat_center(n, center[1])\n\n H1 = union(H1, C1)\n H2 = union(H2, C2)\n H = union(H1, H2)\n\n return H\n\n\ndef repeat_center(n, repeat):\n \"\"\"\n Create the center-point portion of a design matrix\n \n Parameters\n ----------\n n : int\n The number of factors in the original design\n repeat : int\n The number of center points to repeat\n \n Returns\n -------\n mat : 2d-array\n The center-point portion of a design matrix (elements all zero).\n \n Example\n -------\n ::\n \n >>> repeat_center(3, 2)\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]])\n \n \"\"\"\n return np.zeros((repeat, n))\n","sub_path":"doepy/pydoe_corrected.py","file_name":"pydoe_corrected.py","file_ext":"py","file_size_in_byte":18601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"361129595","text":"import os\nimport glob\nimport pandas as pd\n\nlangs = ['CA', 'DE', 'FR', 'GB', 'IN', 'JP', 'KR', 'MX', 'RU', 'US']\nlist_channels = []\nlist_errors = []\nfor lang in langs:\n print('Reading ', lang)\n df_videos = pd.read_csv('../DATA/DDBB_Trending/'+lang+'videos.csv', encoding = \"ISO-8859-1\")\n df_out = df_videos[['channel_title']]\n error_encoding = 0\n\n for index, row in df_out.iterrows():\n try:\n row['channel_title'].encode('ascii')\n except UnicodeEncodeError:\n error_encoding += 1\n list_errors.append(row['channel_title'])\n else:\n list_channels.append(row['channel_title'])\n\n print('length: ', df_out.shape[0])\n print(error_encoding, 'ignored words (no valid encoding)')\n\nlist_channels = list(filter(None, list_channels))\nprint('\\nFinal length: ', len(list_channels))\nset_channels = set(list_channels)\nlist_channels_nodupli = list(set_channels)\nprint('without duplicates: ', len(list_channels_nodupli))\n\ndf_channels = pd.DataFrame(list_channels_nodupli,columns=['channel_title'])\ndf_channels.to_csv('../DATA/AllTrendingChannels.csv', encoding='utf-8', index=True)\n\n#errors version\nlist_errors = list(filter(None, list_errors))\nprint('\\nFinal errors length: ', len(list_errors))\nset_errors = set(list_errors)\nlist_errors_nodupli = list(set_errors)\nprint('errors without duplicates: ', len(list_errors_nodupli))\n\ndf_errors = pd.DataFrame(list_errors,columns=['channel_title'])\ndf_errors.to_csv('../DATA/AllTrendingErrors.csv', encoding='utf-8', index=True)\n","sub_path":"prepareData/1-mergeDDBB.py","file_name":"1-mergeDDBB.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"582918101","text":"from itertools import product\n\nimport pytest\n\nfrom ffiec.tests.factories import (\n CBSADemFactory, MetDivDemFactory, TractDemFactory)\nfrom geo.tests.factories import CBSAFactory, MetDivFactory, TractFactory\nfrom hmda.tests.factories import LARFactory, NormalLARFactory\nfrom reports import models\nfrom reports.tests.factories import ReportInputFactory\nfrom respondents.tests.factories import InstitutionFactory\n\n\n@pytest.mark.django_db\ndef test_population_report():\n metdiv = MetDivFactory()\n demographics = TractDemFactory.create_batch(\n 10, year=2010, tract__county__metdiv=metdiv)\n # Wrong year\n TractDemFactory.create_batch(3, year=2011, tract__county__metdiv=metdiv)\n # Not in metdiv\n TractDemFactory(year=2010)\n total = sum(d.persons for d in demographics)\n white = sum(d.non_hispanic_white for d in demographics)\n hispanic = sum(d.hispanic_only for d in demographics)\n black = sum(d.black for d in demographics)\n asian = sum(d.asian for d in demographics)\n poverty = sum(d.poverty for d in demographics)\n assert total != 0\n assert white != 0\n assert hispanic != 0\n assert black != 0\n assert asian != 0\n assert poverty != 0\n\n models.PopulationReport.rebuild_all()\n assert list(models.PopulationReport.generate_for(metdiv, 2010)) == [\n (\"All Population\", total, 100),\n (\"White\", white, white * 100 // total),\n (\"Hispanic/Latino\", hispanic, hispanic * 100 // total),\n (\"Black\", black, black * 100 // total),\n (\"Asian\", asian, asian * 100 // total),\n (\"Minority\", total - white, (total - white) * 100 // total),\n (\"People Living in Poverty\", poverty, poverty * 100 // total),\n ]\n\n\n@pytest.mark.django_db\ndef test_income_housing_report():\n metdiv = MetDivFactory()\n low_white = TractDemFactory.create_batch(\n 2, income_indicator=\"low\", non_hispanic_white=8, persons=10,\n tract__county__metdiv=metdiv, year=2010,\n )\n mod_minority = TractDemFactory.create_batch(\n 3, income_indicator=\"mod\", non_hispanic_white=2, persons=6,\n tract__county__metdiv=metdiv, year=2010,\n )\n mid_white = TractDemFactory.create_batch(\n 4, income_indicator=\"mid\", non_hispanic_white=9, persons=11,\n tract__county__metdiv=metdiv, year=2010,\n )\n high_minority = TractDemFactory.create_batch(\n 5, income_indicator=\"high\", non_hispanic_white=4, persons=20,\n tract__county__metdiv=metdiv, year=2010,\n )\n demographics = low_white + mod_minority + mid_white + high_minority\n # Wrong year\n TractDemFactory.create_batch(3, tract__county__metdiv=metdiv, year=2011)\n # Not part of the metdiv\n TractDemFactory(year=2010)\n\n homes = sum(d.single_family_homes for d in demographics)\n occupied = sum(d.single_family_occupied for d in demographics)\n count_lmi = len(low_white) + len(mod_minority)\n count_minority = len(mod_minority) + len(high_minority)\n persons_lmi = sum(d.persons for d in low_white)\\\n + sum(d.persons for d in mod_minority)\n persons_minority = sum(d.persons for d in mod_minority)\\\n + sum(d.persons for d in high_minority)\n all_persons = sum(d.persons for d in demographics)\n assert homes != 0\n assert occupied != 0\n assert count_lmi > 0\n assert count_minority > 0\n assert persons_lmi != 0\n assert persons_minority != 0\n\n models.IncomeHousingReport.rebuild_all()\n assert list(models.IncomeHousingReport.generate_for(metdiv, 2010)) == [\n (\"Single Family Homes\", homes, 100),\n (\"Owner Occupied Homes\", occupied, occupied * 100 // homes),\n (\"LMI Tracts in Geography\",\n count_lmi, count_lmi * 100 // len(demographics)),\n (\"Minority Tracts in Geography\",\n count_minority, count_minority * 100 // len(demographics)),\n (\"Population in LMI Tracts\",\n persons_lmi, persons_lmi * 100 // all_persons),\n (\"Population in Minority Tracts\",\n persons_minority, persons_minority * 100 // all_persons),\n ]\n\n\n@pytest.mark.django_db\ndef test_disparity_row_applicant():\n metdiv = MetDivFactory()\n lar = NormalLARFactory.create_batch(\n 100, as_of_year=2010, tract__county__metdiv=metdiv)\n\n # Wrong year\n NormalLARFactory(as_of_year=2011, tract__county__metdiv=metdiv)\n # Not in metdiv\n NormalLARFactory(as_of_year=2010)\n non_hispanic = {l for l in lar if l.applicant_ethnicity == \"2\"}\n white = {l for l in non_hispanic if l.applicant_race_1 == \"5\"}\n black = {l for l in non_hispanic if l.applicant_race_1 == \"3\"}\n hispanic = {l for l in lar if l.applicant_ethnicity == \"1\"}\n asian = {l for l in non_hispanic if l.applicant_race_1 == \"2\"}\n minority = set(lar) - white\n men = {l for l in lar if l.applicant_sex == 1}\n women = {l for l in lar if l.applicant_sex == 2}\n\n assert len(white) > 0\n assert len(black) > 0\n assert len(hispanic) > 0\n assert len(asian) > 0\n assert len(minority) > 0\n assert len(men) > 0\n assert len(women) > 0\n\n report_input = ReportInputFactory(metro_ids={metdiv.metro_id}, year=2010)\n models.DisparityReport.rebuild_all()\n result = list(models.DisparityReport.groups_for(metdiv, report_input))\n assert len(result) == 5\n assert result[0] == (\n \"White borrowers\",\n [\n (\n \"White\", len(white),\n len([l for l in white if l.action_taken == 1]),\n len(lar), len(white),\n len([l for l in white if l.action_taken == 1]),\n ),\n (\n \"Black\", len(black),\n len([l for l in black if l.action_taken == 1]),\n len(lar), len(white),\n len([l for l in white if l.action_taken == 1]),\n ),\n (\n \"Hispanic/Latino\", len(hispanic),\n len([l for l in hispanic if l.action_taken == 1]),\n len(lar), len(white),\n len([l for l in white if l.action_taken == 1]),\n ),\n (\n \"Asian\", len(asian),\n len([l for l in asian if l.action_taken == 1]),\n len(lar), len(white),\n len([l for l in white if l.action_taken == 1]),\n ),\n (\n \"Minority\", len(minority),\n len([l for l in minority if l.action_taken == 1]),\n len(lar), len(white),\n len([l for l in white if l.action_taken == 1]),\n ),\n ],\n )\n assert result[2] == (\n \"Male\",\n [\n (\n \"Female\", len(women),\n len([l for l in women if l.action_taken == 1]),\n len(lar), len(men),\n len([l for l in men if l.action_taken == 1]),\n ),\n ],\n )\n\n\n@pytest.mark.django_db\ndef test_disparity_row_lmi_applicant():\n metdiv = MetDivFactory()\n lar = NormalLARFactory.create_batch(\n 25, as_of_year=2010, tract__county__metdiv=metdiv)\n avg_income = sum(l.applicant_income_000s for l in lar) // len(lar)\n MetDivDemFactory(\n metdiv=metdiv, year=2010, ffiec_est_med_fam_income=avg_income * 1000)\n # Wrong year\n MetDivDemFactory(metdiv=metdiv, year=2011)\n below = {\n l for l in lar if l.applicant_income_000s < avg_income * .8}\n above = {\n l for l in lar if l.applicant_income_000s >= avg_income * .8}\n assert len(below) > 0\n assert len(above) > 0\n\n report_input = ReportInputFactory(metro_ids={metdiv.metro_id}, year=2010)\n models.DisparityReport.rebuild_all()\n result = list(models.DisparityReport.groups_for(metdiv, report_input))\n assert len(result) == 5\n assert result[1] == (\n \"MUI Borrowers\",\n [(\n \"LMI Applicant\", len(below),\n len([l for l in below if l.action_taken == 1]),\n len(lar), len(above),\n len([l for l in above if l.action_taken == 1]),\n )],\n )\n\n\n@pytest.mark.django_db\ndef test_disparity_row_tracts():\n metdiv = MetDivFactory()\n TractDemFactory(year=2011, tract__county__metdiv=metdiv) # wrong year\n\n lm_lar = NormalLARFactory.create_batch(\n 10, as_of_year=2010, tract=TractDemFactory(\n year=2010, income_indicator=\"low\", persons=10,\n non_hispanic_white=2, tract__county__metdiv=metdiv,\n ).tract,\n )\n mw_lar = NormalLARFactory.create_batch(\n 12, as_of_year=2010, tract=TractDemFactory(\n year=2010, income_indicator=\"mod\", persons=15,\n non_hispanic_white=10, tract__county__metdiv=metdiv,\n ).tract,\n )\n mm_lar = NormalLARFactory.create_batch(\n 14, as_of_year=2010, tract=TractDemFactory(\n year=2010, income_indicator=\"mid\", persons=20,\n non_hispanic_white=5, tract__county__metdiv=metdiv,\n ).tract,\n )\n hw_lar = NormalLARFactory.create_batch(\n 16, as_of_year=2010, tract=TractDemFactory(\n year=2010, income_indicator=\"high\", persons=25,\n non_hispanic_white=20, tract__county__metdiv=metdiv,\n ).tract,\n )\n\n report_input = ReportInputFactory(metro_ids={metdiv.metro_id}, year=2010)\n models.DisparityReport.rebuild_all()\n result = list(models.DisparityReport.groups_for(metdiv, report_input))\n assert result[-2:] == [\n (\n \"MUI Tracts\",\n [(\n \"Applicant in LMI Tract\", 10 + 12,\n len([l for l in lm_lar + mw_lar if l.action_taken == 1]),\n 10 + 12 + 14 + 16, 14 + 16,\n len([l for l in mm_lar + hw_lar if l.action_taken == 1]),\n )],\n ),\n (\n \"White Majority Tracts\",\n [(\n \"Applicant in Minority Tract\", 10 + 14,\n len([l for l in lm_lar + mm_lar if l.action_taken == 1]),\n 10 + 12 + 14 + 16, 12 + 16,\n len([l for l in mw_lar + hw_lar if l.action_taken == 1]),\n )],\n ),\n ]\n\n\n@pytest.mark.parametrize(\"feature, compare, expected\", [\n ((75, 100), (100, 200), \"0.5\"), # 25% compared to 50%\n ((0, 100), (100, 200), \"2.0\"), # 100% compared to 50%\n ((100, 100), (100, 200), \"0.0\"), # 0% compared to 50%\n ((0, 0), (100, 200), \"N/A\"),\n ((70, 100), (0, 200), \"0.3\"), # 30% compared to 100%\n ((75, 100), (200, 200), \"N/A\"), # 25% compared to 0%\n ((75, 100), (0, 0), \"N/A\"),\n])\ndef test_disparity_row_disparity_ratio(feature, compare, expected):\n row = models.DisparityRow(\n \"AAA\", feature[1], feature[0], 1000, compare[1], compare[0])\n assert row.disparity_ratio() == expected\n\n\n@pytest.mark.django_db\ndef test_top_lender_lender_selection():\n lenders = InstitutionFactory.create_batch(6)\n tracts = TractFactory.create_batch(2)\n LARFactory.create_batch(\n 5, action_taken=1, as_of_year=2012, tract=tracts[0],\n institution=lenders[0])\n LARFactory.create_batch(\n 6, action_taken=1, as_of_year=2012, tract=tracts[0],\n institution=lenders[1])\n LARFactory.create_batch(\n 4, action_taken=1, as_of_year=2012, tract=tracts[0],\n institution=lenders[2])\n LARFactory.create_batch(\n 3, action_taken=1, as_of_year=2012, tract=tracts[0],\n institution=lenders[3])\n # wrong year\n LARFactory.create_batch(\n 10, action_taken=1, as_of_year=2011, tract=tracts[0],\n institution=lenders[4])\n # wrong division\n LARFactory.create_batch(\n 10, action_taken=1, as_of_year=2012, tract=tracts[1],\n institution=lenders[5])\n report_input = ReportInputFactory(lender_ids={lenders[3].pk}, year=2012)\n\n models.LenderReport.rebuild_all()\n rows = list(models.LenderReport.generate_for(\n tracts[0].county, report_input, count=2))\n\n assert len(rows) == 3\n assert rows[0].lender_rank == 1\n assert rows[0].name == lenders[1].name\n assert rows[0].applications == 6\n assert rows[0].requested is False\n assert rows[1].lender_rank == 2\n assert rows[1].name == lenders[0].name\n assert rows[1].applications == 5\n assert rows[1].requested is False\n assert rows[2].lender_rank == 4\n assert rows[2].name == lenders[3].name\n assert rows[2].applications == 3\n assert rows[2].requested is True\n\n\n@pytest.mark.django_db\ndef test_top_lender_stats():\n lender = InstitutionFactory()\n metro = CBSAFactory()\n CBSADemFactory(cbsa=metro, ffiec_est_med_fam_income=100000, year=2010)\n low_white = TractDemFactory(\n income_indicator=\"low\", non_hispanic_white=8, persons=10,\n tract__county__cbsa=metro, year=2010,\n )\n mod_minority = TractDemFactory(\n income_indicator=\"mod\", non_hispanic_white=2, persons=6,\n tract__county__cbsa=metro, year=2010,\n )\n mid_white = TractDemFactory(\n income_indicator=\"mid\", non_hispanic_white=9, persons=11,\n tract__county__cbsa=metro, year=2010,\n )\n high_minority = TractDemFactory(\n income_indicator=\"high\", non_hispanic_white=4, persons=20,\n tract__county__cbsa=metro, year=2010,\n )\n\n applications, approvals, lmit, lmib, mint, minb = 0, 0, 0, 0, 0, 0\n configurations = product(\n (low_white, mod_minority, mid_white, high_minority),\n (1, 2),\n (60, 90),\n (\"1\", \"5\"),\n )\n for idx, (dem, action_taken, income, race) in enumerate(configurations):\n quantity = idx + 5\n LARFactory.create_batch(\n quantity, action_taken=action_taken, as_of_year=2010,\n tract=dem.tract, institution=lender, applicant_ethnicity=\"2\",\n applicant_income_000s=income, applicant_race_1=race,\n )\n applications += quantity\n if action_taken == 1:\n approvals += quantity\n lmit += quantity if dem in (low_white, mod_minority) else 0\n lmib += quantity if income == 60 else 0\n mint += quantity if dem in (mod_minority, high_minority) else 0\n minb += quantity if race == \"1\" else 0\n\n report_input = ReportInputFactory(year=2010)\n\n models.LenderReport.rebuild_all()\n rows = list(models.LenderReport.generate_for(metro, report_input))\n\n assert rows == [models.TopLenderRow(\n lender_rank=1,\n requested=False,\n name=lender.name,\n applications=applications,\n approval_rate=100 * approvals // applications,\n lmit_pct=100 * lmit // approvals,\n lmib_pct=100 * lmib // approvals,\n mint_pct=100 * mint // approvals,\n minb_pct=100 * minb // approvals,\n )]\n","sub_path":"reports/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":14525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"572732976","text":"#!/usr/bin/env python\nimport sys\npy_v = sys.version_info[:2]\nif not (py_v == (2, 7) or py_v >= (3, 3)):\n sys.exit('Only Python 2.7 or 3.3 and up are supported. Current version: ' + '.'.join(py_v))\n\nimport os\nfrom os.path import join, isfile, abspath, dirname\n\nfrom ngs_utils import setup_utils\n\nimport ngs_reporting\nimport variant_filtering\nimport prealign\nimport az\npackage_name = reporting_package_name = ngs_reporting.__name__\nprealign_package_name = prealign.__name__\naz_package_name = az.__name__\nvariant_filtering_package_name = variant_filtering.__name__\n\n\nversion = setup_utils.init(package_name, package_name, __file__)\n\n\nfrom setuptools import setup\nsetup(\n name=package_name,\n version=version,\n author='Vlad Saveliev and Alla Mikheenko',\n author_email='vlad.saveliev@astrazeneca.com',\n description='AstraZeneca NGS variant reporting suite',\n long_description=(open('README.md').read()),\n keywords='bioinformatics',\n url='https://github.com/AstraZeneca-NGS/NGS_Reporting',\n download_url='https://github.com/AstraZeneca-NGS/NGS_Reporting/releases',\n license='GPLv3',\n packages=[\n package_name,\n prealign_package_name,\n az_package_name,\n variant_filtering_package_name,\n ],\n package_data={\n package_name: setup_utils.find_package_files('.', package_name),\n prealign_package_name: setup_utils.find_package_files('.', prealign_package_name),\n az_package_name: setup_utils.find_package_files('.', az_package_name),\n variant_filtering_package_name: setup_utils.find_package_files('.', variant_filtering_package_name),\n },\n scripts=[path for path in\n [join('scripts', fn) for fn in os.listdir(join(dirname(__file__), 'scripts'))] +\n [join('scripts', 'bed_prep', fn) for fn in os.listdir(join(dirname(__file__), 'scripts', 'bed_prep'))]\n if isfile(path) and os.access(path, os.X_OK)],\n include_package_data=True,\n zip_safe=False,\n install_requires=setup_utils.get_reqs(),\n setup_requires=['numpy'],\n classifiers=[\n 'Environment :: Console',\n 'Environment :: Web Environment',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Natural Language :: English',\n 'Operating System :: MacOS :: MacOS X',\n 'Operating System :: POSIX',\n 'Operating System :: Unix',\n 'Programming Language :: Python',\n 'Programming Language :: JavaScript',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Scientific/Engineering :: Bio-Informatics',\n ],\n)\n\nprint(\"\"\"\n-------------------------\n Complete!\n-------------------------\nUsage:\n\n* Pre-alignment suite *\nprealign \\\\\n /ngs/oncology/datasets/HiSeq/150612_D00443_0168_AHMNFGADXX \\\\\n -o /ngs/oncology/analysis/Dev_0104_HiSeq_DS \\\\\n [--jira https://jira.rd.astrazeneca.net/browse/NGSG-313] \\\\\n [--bed target.bed]\n\n* Variant filtering *\nvarfilter \\\\\n filt.vcf.gz \\\\\n -g hg19 \\\\\n --analysis-type [exome|targeted|wgs] \\\\\n -o output_dir\n\n* Run bcbio-nextgen postprocessing pipeline *\nbcbio_postproc \\\\\n [path_to_bcbio] \\\\\n [--project Dev_0104_HiSeq_DS] \\\\\n [--jira https://jira.rd.astrazeneca.net/browse/NGSG-313]\n\"\"\".format(name=package_name))\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"39766753","text":"# Script for showing full evolution of probe at hardcoded snapshot locations in and out of plasma\n\nimport numpy as np\nimport matplotlib.colors as col\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib.ticker as ticker\nimport pdb\nimport math\nimport copy\nimport csv\n\n# Definition of Constants\nM_E = 9.109e-31 # Electron rest mass in kg\nEC = 1.60217662e-19 # Electron charge in C\nEP_0 = 8.854187817e-12 # Vacuum permittivity in C/(V m)\nC = 299892458 # Speed of light in vacuum in m/s\n\n# Snapshot locations (12 total, in mm):\n#x_s = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30]\n#x_s = [500, 750, 1000, 1250, 1500, 1750, 2000, 3000, 4000, 5000, 7500, 10000]\nx_s = [0, 5, 10, 25, 50, 75, 100, 150, 200, 300, 400, 500]\n\ndef Gamma(p):\n return math.sqrt(1.0 + p**2)\n\ndef Velocity(px,ptot):\n# Returns relativistic velocity from momentum\n return px / Gamma(ptot)\n\ndef getBallisticTraj(x_0,y_0,xi_0,z_0,px,py,pz,x_s):\n# Use ballistic matrix to find positions on screens\n dx = x_s - x_0\n y_f = y_0 + dx * (py/px)\n z_f = z_0 + dx * (pz/px)\n\n# Find time traveled to get proper xi\n p = math.sqrt(px**2 + py**2 + pz**2)\n vx = Velocity(px, p)\n vy = Velocity(py, p)\n vz = Velocity(pz, p)\n vtot = math.sqrt(vx**2 + vy**2 + vz**2)\n dtot = math.sqrt((x_s - x_0)**2 + (y_f - y_0)**2 + (z_f - z_0)**2)\n t = dtot/vtot\n\n xi_f = xi_0 + dx * (pz/px) + t\n\n return y_f, xi_f, z_f\n\ndef plot(x_f,y_f,xi_f,z_f,px_f,py_f,pz_f,sim_name,shape_name,noElec,iter):\n# Plot evolution of probe after leaving plasma\n if (sim_name.upper() == 'OSIRIS_CYLINSYMM'):\n import include.simulations.useOsiCylin as sim\n elif (sim_name.upper() == 'QUASI3D'):\n import include.simulations.useQuasi3D as sim\n else:\n print(\"Simulation name unrecognized. Quitting...\")\n exit()\n\n W_P = sim.getPlasFreq()\n plasma_bnds = sim.getBoundCond()\n shape_name = shape_name.capitalize()\n\n# Normalize screen distances\n slices = len(x_s)\n xs_norm = []\n for i in range(0,slices):\n xs_norm.append(x_s[i] * W_P * 10**(-3) / C)\n\n# Generate arrays of coordinates at origin + each screen\n yslice = np.empty(noElec)\n xislice = np.empty(noElec)\n zslice = np.empty(noElec)\n\n# Project positions at distances in x_s\n for j in range(0,noElec):\n yslice[j], xislice[j] , zslice[j] = getBallisticTraj(x_f[j], y_f[j], xi_f[j], z_f[j], px_f[j], py_f[j], pz_f[j], xs_norm[-1])\n\n# Plot slices\n# For bin size = 0.006 (lambda/10)\n# Run 130 Limits: (27,52), (-6,6), Bins: (4167,2000)\n# (35,40), (-1,1), Bins: (833,333)\n# For bin size = 0.03\n# Run 130 Limits: (27,52), (-6,6), Bins: (833,400)\n# Run 232 Limits: (435,475), (0,6), Bins: (1333,200)\n\n binsizez = 833#2833#4167#1000#2666#1333\n binsizey = 400#2000#160#666#200\n\n xmin = 27#35#27#400\n xmax = 52#500\n\n norm = mpl.colors.Normalize(vmin=1, vmax=1500)\n\n h2, xbin, ybin, himage = plt.hist2d(zslice, yslice, bins=(binsizez,binsizey), vmin=1)#, norm=norm)\n\n with open('counts.csv', 'w', newline='') as csvfile:\n nwriter = csv.writer(csvfile, dialect='excel')\n nwriter.writerows(h2)\n\n with open('xbins.csv', 'w', newline='') as csvfile2:\n binwriter = csv.writer(csvfile2, dialect='excel')\n binwriter.writerow(xbin)\n\n with open('ybins.csv', 'w', newline='') as csvfile3:\n binwriter2 = csv.writer(csvfile3, dialect='excel')\n binwriter2.writerow(ybin)\n","sub_path":"include/writeFullEvolData.py","file_name":"writeFullEvolData.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"572901410","text":"#!/usr/bin/python3\n\nimport os, array\n\ndef green(path):\n fd = os.open(path+\".ppm\", os.O_RDONLY)\n\n head = os.read(fd,16)\n splithead = str(head).split(\"\\\\n\")\n\n p_image = splithead[0][2] + splithead[0][3]\n width = int(splithead[1].split()[0])\n height = int(splithead[1].split()[1])\n max_value = int(splithead[2])\n\n ppm_header = p_image + ' ' + str(width) + ' ' + str(height) + ' ' + str(max_value) + \"\\n\"\n firstimg = os.read(fd, width*height*3)\n\n img = array.array('B', [0, 0, 0] * width * height)\n\n for x in range(0, height):\n for y in range(0, width):\n index = 3 * (x * width + y)\n img[index + 1] = firstimg[index + 0]\n\n #imagen verde guardado\n f = open(path+'green.ppm', 'wb')\n f.write(bytearray(ppm_header, 'ascii'))\n img.tofile(f)","sub_path":"alumnos/56009-Gianluca-Persia/tp4/mkgreen.py","file_name":"mkgreen.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"488020138","text":"from pymongo import MongoClient\nfrom configuration import Configuration\n\nclass FeaturesRepository:\n def __init__(self, config: Configuration):\n self.__client = MongoClient(config.mongo_connection_string)\n self.__db = self.__client['KognitiveDB']\n self.__features_collection = self.__db['featureData']\n\n def getFeatureData(self, fileId):\n data = self.__features_collection.find_one({\"_id\": fileId})\n return data\n\n def setFeatureData(self, fileId, data):\n dataDict = self._todict(data)\n dataDict[\"_id\"] = fileId\n print(\"File id: \" + fileId)\n print(\"Data: \" + str(data))\n self.__features_collection.insert_one(dataDict)\n\n # Taken from https://stackoverflow.com/a/1036435/528131\n def _todict(self, obj):\n data = {}\n for key, value in obj.__dict__.items():\n try:\n data[key] = self._todict(value)\n except AttributeError:\n data[key] = value\n return data\n","sub_path":"src/features_repository.py","file_name":"features_repository.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"462709261","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2018/4/11 0011 11:45\n# @Author : chelin\n# @File : 0411.py\n# @Software: PyCharm\n\nDB_FILE = \"staff.db\"\nCOLUMNS = ['id', 'name', 'age', 'phone', 'dept', 'enrolled_date']\n\n\ndef load_db(db_file):\n \"\"\"\n 加载员工信息表,并转成指定格式\n :param db_file:\n :return:\n \"\"\"\n data = {}\n for i in COLUMNS:\n data[i] = []\n\n f = open(db_file, \"r\", encoding=\"utf-8\")\n for line in f:\n staff_id, name, age, phone, dept, enrolled_date = line.split(\",\")\n data['id'].append(staff_id)\n data['name'].append(name)\n data['age'].append(age)\n data['phone'].append(phone)\n data['dept'].append(dept)\n data['enrolled_date'].append(enrolled_date)\n\n return data\n\n\nSTAFF_DATA = load_db(DB_FILE)\n\nfor index, val in enumerate(STAFF_DATA[COLUMNS[0]]):\n row = [str(val)]\n # print(\"row:\", row, \"\\n++++++++++++++++++++++\\n\")\n for col in COLUMNS[1:]:\n # print(\"col:%s, COLUMNS[1:]:%s\" % (col,COLUMNS[1:]))\n row.append(str(STAFF_DATA[col][index]))\n # print(STAFF_DATA[col][index],\"\\n===================\\n\")\n # print(row ,\"\\n*************\\n\")\n raw_row = \",\".join(row)\n # print(\"xxxxx:\", raw_row)\n print(raw_row)\n","sub_path":"0411.py","file_name":"0411.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"67753498","text":"# -*- coding: utf-8 -*-\n# Find the build location and add that to the path\nimport math\nimport random\nimport re\nimport sys\nimport unicodedata\nfrom functools import partial\nfrom typing import (\n Any,\n Callable,\n Dict,\n Iterable,\n List,\n NoReturn,\n Union,\n)\n\nfrom hypothesis import example, given\nfrom hypothesis.strategies import (\n binary,\n dictionaries,\n floats,\n integers,\n iterables,\n lists,\n sampled_from,\n sets,\n text,\n tuples,\n)\nfrom pytest import mark, raises\nfrom typing_extensions import Protocol\n\nimport fastnumbers\n\nskipif = mark.skipif\nparametrize = mark.parametrize\n\n\n# Assistance with type hints\ndef dummy(x: Any) -> Any:\n return x\n\n\nFloatOrInt = Union[float, int]\n\n\nclass FastReal(Protocol):\n def __call__(\n self,\n x: Any,\n default: Any = None,\n *,\n raise_on_invalid: bool = False,\n inf: Any = None,\n nan: Any = None,\n on_fail: Callable[[Any], Any] = dummy,\n coerce: bool = True,\n allow_underscores: bool = True,\n key: Callable[[Any], Any] = dummy,\n ) -> Any:\n ...\n\n\nclass FastFloat(Protocol):\n def __call__(\n self,\n x: Any,\n default: Any = None,\n *,\n raise_on_invalid: bool = False,\n inf: Any = None,\n nan: Any = None,\n on_fail: Callable[[Any], Any] = dummy,\n allow_underscores: bool = True,\n key: Callable[[Any], Any] = dummy,\n ) -> Any:\n ...\n\n\nclass FastInt(Protocol):\n def __call__(\n self,\n x: Any,\n default: Any = None,\n *,\n raise_on_invalid: bool = False,\n base: int = 0,\n on_fail: Callable[[Any], Any] = dummy,\n allow_underscores: bool = True,\n key: Callable[[Any], Any] = dummy,\n ) -> Any:\n ...\n\n\nclass FastForceInt(Protocol):\n def __call__(\n self,\n x: Any,\n default: Any = None,\n *,\n raise_on_invalid: bool = False,\n on_fail: Callable[[Any], Any] = dummy,\n allow_underscores: bool = True,\n key: Callable[[Any], Any] = dummy,\n ) -> Any:\n ...\n\n\nclass IsReal(Protocol):\n def __call__(\n self,\n x: Any,\n *,\n str_only: bool = False,\n num_only: bool = False,\n allow_inf: bool = False,\n allow_nan: bool = False,\n allow_underscores: bool = True,\n ) -> bool:\n ...\n\n\nclass IsFloat(Protocol):\n def __call__(\n self,\n x: Any,\n *,\n str_only: bool = False,\n num_only: bool = False,\n allow_inf: bool = False,\n allow_nan: bool = False,\n allow_underscores: bool = True,\n ) -> bool:\n ...\n\n\nclass IsInt(Protocol):\n def __call__(\n self,\n x: Any,\n *,\n str_only: bool = False,\n num_only: bool = False,\n base: int = 0,\n allow_underscores: bool = True,\n ) -> bool:\n ...\n\n\nclass IsIntLike(Protocol):\n def __call__(\n self,\n x: Any,\n *,\n str_only: bool = False,\n num_only: bool = False,\n allow_underscores: bool = True,\n ) -> bool:\n ...\n\n\nclass Real(Protocol):\n def __call__(self, x: Any = 0.0, *, coerce: bool = True) -> Union[int, float]:\n ...\n\n\nConversionFuncs = Union[FastReal, FastFloat, FastInt, FastForceInt]\nIdentificationFuncs = Union[IsReal, IsFloat, IsInt, IsIntLike]\nNonBuiltinFuncs = Union[ConversionFuncs, IdentificationFuncs]\n\n# Predefine Unicode digits, numbers, and not those.\ndigits = []\nnumeric = []\nnot_numeric = []\nfor x in range(0x1FFFFF):\n try:\n a = chr(x)\n except ValueError:\n break\n try:\n unicodedata.digit(a)\n digits.append(a)\n except ValueError:\n pass\n try:\n unicodedata.numeric(a)\n numeric.append(a)\n except ValueError:\n not_numeric.append(a)\nnumeric_not_digit = [x for x in numeric if x not in digits]\nnumeric_not_digit_not_int = [\n x for x in numeric_not_digit if not unicodedata.numeric(x).is_integer()\n]\n\n\ndef a_number(s: Union[str, bytes]) -> bool:\n s = s.strip()\n try:\n int(s)\n except ValueError:\n try:\n float(s)\n except ValueError:\n pass\n else:\n return True\n else:\n return True\n if isinstance(s, bytes):\n return False\n if re.match(r\"\\s*([-+]?\\d+\\.?\\d*(?:[eE][-+]?\\d+)?)\\s*$\", s, re.U):\n return True\n if re.match(r\"\\s*([-+]?\\.\\d+(?:[eE][-+]?\\d+)?)\\s*$\", s, re.U):\n return True\n if s.strip().lstrip(\"[-+]\") in numeric:\n return True\n return False\n\n\ndef space() -> str:\n \"\"\"90% chance of ' ', 10% of unicode-only space.\"\"\"\n return random.choice([\" \"] * 90 + [\"\\u2007\"] * 10)\n\n\ndef pad(value: str) -> str:\n \"\"\"Pad a string with whitespace at the front and back.\"\"\"\n return random.randint(1, 100) * space() + value + random.randint(1, 100) * space()\n\n\ndef not_a_number(s: Union[str, bytes]) -> bool:\n return not a_number(s)\n\n\ndef an_integer(x: float) -> bool:\n return x.is_integer()\n\n\ndef not_an_integer(x: float) -> bool:\n return not x.is_integer()\n\n\ndef base_n(\n num: int, b: int, numerals: str = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n) -> str:\n \"\"\"\n Convert any integer to a Base-N string representation.\n Shamelessly stolen from http://stackoverflow.com/a/2267428/1399279\n \"\"\"\n neg = num < 0\n num = abs(num)\n val = ((num == 0) and numerals[0]) or (\n base_n(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b]\n )\n return \"-\" + val if neg else val\n\n\nclass DumbFloatClass(object):\n def __float__(self) -> NoReturn:\n raise ValueError(\"something here might go wrong\")\n\n\nclass DumbIntClass(object):\n def __int__(self) -> NoReturn:\n raise ValueError(\"something here might go wrong\")\n\n\n# Map function names to the actual functions,\n# for dymamic declaration of which functions test below.\nfunc_mapping: Dict[str, Callable[..., Any]] = {\n \"fast_real\": fastnumbers.fast_real,\n \"fast_real_coerce_true\": partial(fastnumbers.fast_real, coerce=True),\n \"fast_real_coerce_false\": partial(fastnumbers.fast_real, coerce=False),\n \"fast_float\": fastnumbers.fast_float,\n \"fast_int\": fastnumbers.fast_int,\n \"fast_forceint\": fastnumbers.fast_forceint,\n \"isreal\": fastnumbers.isreal,\n \"isfloat\": fastnumbers.isfloat,\n \"isint\": fastnumbers.isint,\n \"isintlike\": fastnumbers.isintlike,\n \"real\": fastnumbers.real,\n}\n\n\ndef get_funcs(function_names: Iterable[str]) -> List[Callable[..., Any]]:\n \"\"\"Given a list of function names, return the associated functions\"\"\"\n return [func_mapping[x] for x in function_names]\n\n\n# Common convenience functiom collections\nconversion_funcs = [\"fast_real\", \"fast_float\", \"fast_int\", \"fast_forceint\"]\nidentification_funcs = [\"isreal\", \"isfloat\", \"isint\", \"isintlike\"]\nnon_builtin_funcs = conversion_funcs + identification_funcs\n\n# All ways to spell NaN, and most ways to spell infinity and negative infinity\nall_nan = [\"nan\", \"Nan\", \"nAn\", \"naN\", \"NAn\", \"NaN\", \"nAN\", \"NAN\"]\nall_nan += [\"+\" + x for x in all_nan] + [\"-\" + x for x in all_nan]\nmost_inf = [\"inf\", \"Inf\", \"iNf\", \"inF\", \"INf\", \"InF\", \"iNF\", \"INF\"]\nmost_inf += [\"infinity\", \"INFINITY\", \"iNfInItY\", \"InFiNiTy\", \"inFINIty\"]\nneg_inf = [\"-\" + x for x in most_inf]\nmost_inf += [\"+\" + x for x in most_inf]\n\n#################\n# Sanity Checks #\n#################\n\n\ndef test_version() -> None:\n assert hasattr(fastnumbers, \"__version__\")\n\n\n@given(floats(allow_nan=False) | integers())\ndef test_real_returns_same_as_fast_real(x: FloatOrInt) -> None:\n assert fastnumbers.real(x) == fastnumbers.fast_real(x)\n\n\nclass TestArguments:\n \"\"\"Tests that high-level argument handling is as expected\"\"\"\n\n def test_real_no_arguments_returns_0(self) -> None:\n assert fastnumbers.real() == 0\n\n funcs = non_builtin_funcs + [\"real\"]\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_invalid_argument_raises_type_error(\n self, func: Union[NonBuiltinFuncs, Real]\n ) -> None:\n with raises(TypeError):\n func(5, invalid=\"dummy\") # type: ignore\n\n funcs = non_builtin_funcs\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_no_arguments_raises_type_error(self, func: NonBuiltinFuncs) -> None:\n with raises(TypeError):\n func() # type: ignore\n\n\nclass TestBackwardsCompatibility:\n\n funcs = conversion_funcs\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_key(self, func: ConversionFuncs) -> None:\n with raises(ValueError, match=r\"^Cannot set both on_fail and key$\"):\n func(\"dummy\", key=len, on_fail=len)\n assert func(\"dummy\", key=len) == 5\n assert func(\"dummy\", key=len) == func(\"dummy\", on_fail=len)\n\n\nclass TestUnderscores:\n \"\"\"Tests to make sure underscores are well handled in >= 3.6.\"\"\"\n\n funcs = conversion_funcs\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_numbers_with_underscores_converted_toggled(\n self, func: ConversionFuncs\n ) -> None:\n x = \"1_234_567\"\n assert func(x) in (float(x), int(x))\n assert func(x, allow_underscores=True) in (float(x), int(x))\n assert func(x, allow_underscores=False) == x\n\n funcs = identification_funcs\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_numbers_with_underscores_identified_toggled(\n self, func: ConversionFuncs\n ) -> None:\n x = \"1_234_567\"\n assert func(x)\n assert func(x, allow_underscores=True)\n assert not func(x, allow_underscores=False)\n\n def test_type_with_underscores_identified_toggled(self) -> None:\n x = \"1_234_567\"\n assert fastnumbers.query_type(x) is int\n assert fastnumbers.query_type(x, allow_underscores=True) is int\n assert fastnumbers.query_type(x, allow_underscores=False) is str\n\n\nclass TestErrorHandlingConversionFunctionsSuccessful:\n \"\"\"\n Test the successful execution of the \"error handling conversion\" functions, e.g.:\n\n - fast_real\n - fast_float\n - fast_int\n - fast_forceint\n\n \"\"\"\n\n # NaN and Infinity handling.\n # First float representation as input, then string.\n # All deal with fast_real and fast_float only.\n\n funcs = [\"fast_real\", \"fast_float\"]\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_nan_returns_nan(self, func: Union[FastReal, FastFloat]) -> None:\n assert math.isnan(func(float(\"nan\")))\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n @parametrize(\"x\", all_nan + [pad(\"nan\"), pad(\"-NAN\")])\n def test_given_nan_string_returns_nan(\n self, func: Union[FastReal, FastFloat], x: str\n ) -> None:\n assert math.isnan(func(x))\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_nan_returns_sub_value(\n self, func: Union[FastReal, FastFloat]\n ) -> None:\n assert func(float(\"nan\"), nan=0) == 0\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_with_nan_given_nan_string_returns_sub_value(\n self, func: Union[FastReal, FastFloat]\n ) -> None:\n assert func(\"nan\", nan=0.0) == 0.0\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_inf_returns_inf(self, func: Union[FastReal, FastFloat]) -> None:\n assert math.isinf(func(float(\"inf\")))\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n @parametrize(\"x\", most_inf + [pad(\"inf\"), pad(\"+INFINITY\")])\n def test_given_inf_string_returns_inf(\n self, func: Union[FastReal, FastFloat], x: str\n ) -> None:\n assert func(x) == float(\"inf\")\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n @parametrize(\"x\", neg_inf + [pad(\"-inf\"), pad(\"-INFINITY\")])\n def test_given_negative_inf_string_returns_negative_inf(\n self, func: Union[FastReal, FastFloat], x: str\n ) -> None:\n assert func(x) == float(\"-inf\")\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_inf_returns_sub_value(\n self, func: Union[FastReal, FastFloat]\n ) -> None:\n assert func(float(\"inf\"), inf=1000.0) == 1000.0\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_with_inf_given_inf_string_returns_sub_value(\n self, func: Union[FastReal, FastFloat]\n ) -> None:\n assert func(\"inf\", inf=10000.0) == 10000.0\n assert func(\"-inf\", inf=10000.0) == 10000.0\n\n # Float handling - both actual float input and strings containing floats.\n\n funcs = [\"fast_real_coerce_false\", \"fast_float\"]\n\n @given(floats(allow_nan=False))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_float_returns_float(\n self, func: Union[FastReal, FastFloat], x: float\n ) -> None:\n result = func(x)\n assert result == x\n assert isinstance(result, float)\n\n @given(floats(allow_nan=False).map(repr))\n @example(\"5.675088586167575e-116\")\n @example(\"10.\" + \"0\" * 1050) # absurdly large number of zeros\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_float_string_returns_float(\n self, func: Union[FastReal, FastFloat], x: str\n ) -> None:\n expected = float(x)\n result = func(x)\n assert result == expected\n assert isinstance(result, float)\n assert func(pad(x)) == expected # Accepts padding as well\n\n funcs = [\"fast_int\", \"fast_forceint\"]\n\n @given(floats(allow_nan=False, allow_infinity=False))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_float_returns_int(\n self, func: Union[FastInt, FastForceInt], x: float\n ) -> None:\n expected = int(x)\n result = func(x)\n assert result == expected\n assert isinstance(result, int)\n\n # Integer handling - both actual integer input and strings containing integers.\n\n funcs = [\n \"fast_real_coerce_true\",\n \"fast_real_coerce_false\",\n \"fast_int\",\n \"fast_forceint\",\n ]\n\n @given(integers())\n @example(int(10 * 300))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_int_returns_int(\n self, func: Union[FastReal, FastInt, FastForceInt], x: int\n ) -> None:\n result = func(x)\n assert result == x\n assert isinstance(result, int)\n\n @given(integers().map(repr))\n @example(\"40992764608243448035\")\n @example(\"-41538374848935286698640072416676709\")\n @example(\"240278958776173358420034462324117625982\")\n @example(\"1609422692302207451978552816956662956486\")\n @example(\"-121799354242674784350540853922878239740762834\")\n @example(\"32718704454132572934419741118153895444518280065843028297496525078\")\n @example(\"33684944745210074227862907273261282807602986571245071790093633147269\")\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_int_string_returns_int(\n self, func: Union[FastReal, FastInt, FastForceInt], x: str\n ) -> None:\n expected = int(x)\n result = func(x)\n assert result == expected\n assert isinstance(result, int)\n assert func(pad(x)) == expected # Accepts padding as well\n\n # Special unicode character handling.\n\n funcs = [\n \"fast_real_coerce_true\",\n \"fast_real_coerce_false\",\n \"fast_int\",\n \"fast_forceint\",\n ]\n\n @given(sampled_from(digits))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_unicode_digit_returns_int(\n self, func: Union[FastReal, FastInt, FastForceInt], x: str\n ) -> None:\n expected = unicodedata.digit(x)\n result = func(x)\n assert result == expected\n assert isinstance(result, int)\n assert func(pad(x)) == expected # Accepts padding as well\n\n funcs = [\"fast_real\", \"fast_float\"]\n\n @given(sampled_from(numeric_not_digit_not_int))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_unicode_numeral_returns_float(\n self, func: Union[FastReal, FastInt, FastForceInt], x: str\n ) -> None:\n expected = unicodedata.numeric(x)\n result = func(x)\n assert result == expected\n assert isinstance(func(x), float)\n assert func(pad(x)) == expected # Accepts padding as well\n\n # Tests to ensure correct evaluation is always the first priority.\n\n funcs = conversion_funcs\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_evaluates_valid_even_when_on_fail_given(\n self, func: ConversionFuncs\n ) -> None:\n x = \"7\"\n expected = 7\n assert func(x, on_fail=len) == expected\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_evaluates_valid_even_when_raise_on_invalid_given(\n self, func: ConversionFuncs\n ) -> None:\n x = \"7\"\n expected = 7\n assert func(x, raise_on_invalid=True) == expected\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_evaluates_valid_even_when_default_given(\n self, func: ConversionFuncs\n ) -> None:\n x = \"7\"\n expected = 7\n assert func(x, default=90) == expected\n\n\nclass TestErrorHandlingConversionFunctionsUnsucessful:\n \"\"\"\n Test the unsuccessful execution of the \"error handling conversion\" functions, e.g.:\n\n - fast_real\n - fast_float\n - fast_int\n - fast_forceint\n\n \"\"\"\n\n # Handle custom classes with weird behavior.\n\n funcs = [\"fast_real_coerce_true\", \"fast_float\"]\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_dumb_float_class_responds_to_internal_valueerror(\n self, func: Union[FastReal, FastFloat]\n ) -> None:\n x = DumbFloatClass()\n assert func(x) is x\n with raises(ValueError):\n func(x, raise_on_invalid=True)\n assert func(x, default=5.0) == 5.0\n\n funcs = [\"fast_int\", \"fast_forceint\"]\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_dumb_int_class_responds_to_internal_valueerror(\n self, func: Union[FastInt, FastForceInt]\n ) -> None:\n x = DumbIntClass()\n assert func(x) is x\n with raises(ValueError):\n func(x, raise_on_invalid=True)\n assert func(x, default=5) == 5\n\n # Handle invalid text input\n\n funcs = conversion_funcs\n\n @given((text() | binary()).filter(not_a_number))\n @example(\"+\")\n @example(\"-\")\n @example(\"e\")\n @example(\"e8\")\n @example(\".\")\n @example(\"a\" * 1050)\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_invalid_string_returns_string_as_is(\n self, func: ConversionFuncs, x: str\n ) -> None:\n assert func(x) is x\n\n # Handle invalid unicode character input\n\n funcs = conversion_funcs\n\n @given(sampled_from(not_numeric))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_unicode_non_numeral_returns_as_is(\n self, func: ConversionFuncs, x: str\n ) -> None:\n assert func(x) == x\n\n @given(text(min_size=2).filter(not_a_number))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_unicode_of_more_than_one_char_returns_as_is(\n self, func: ConversionFuncs, x: str\n ) -> None:\n assert func(x) == x\n\n # Handle other invalid input\n\n funcs = conversion_funcs\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_invalid_type_raises_typeerror(self, func: ConversionFuncs) -> None:\n with raises(TypeError):\n func([1])\n\n funcs = [\"fast_int\", \"fast_forceint\"]\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_nan_raises_valueerror_for_int_funcions(\n self, func: Union[FastInt, FastForceInt]\n ) -> None:\n with raises(ValueError):\n func(float(\"nan\"), raise_on_invalid=True)\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_inf_raises_overflowerror_for_int_funcions(\n self, func: Union[FastInt, FastForceInt]\n ) -> None:\n with raises(OverflowError):\n func(float(\"inf\"), raise_on_invalid=True)\n\n # Demonstrate that the error handling options kick in on invalid input\n\n funcs = conversion_funcs\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_invalid_raises_valueerror_if_raise_on_invalid_is_true(\n self, func: ConversionFuncs\n ) -> None:\n with raises(ValueError):\n func(\"this is invalid\", raise_on_invalid=True)\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_returns_default_value_if_given_invalid_string(\n self, func: ConversionFuncs\n ) -> None:\n assert func(\"this is invalid\", default=90) == 90\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_raise_on_invalid_takes_precedence_over_default(\n self, func: ConversionFuncs\n ) -> None:\n with raises(ValueError):\n func(\"this is invalid\", default=90, raise_on_invalid=True)\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_returns_transformed_input_if_invalid_and_on_fail_is_given(\n self, func: ConversionFuncs\n ) -> None:\n x = \"this is invalid\"\n expected = len(x)\n result = func(x, on_fail=len)\n assert result == expected\n\n\nclass TestFastReal:\n \"\"\"\n Tests for the fast_real function that are too specific for the generalized tests.\n \"\"\"\n\n @given(floats(allow_nan=False).filter(an_integer))\n def test_given_float_returns_int_if_intlike_with_coerce(self, x: float) -> None:\n expected = int(float(x))\n result = fastnumbers.fast_real(x, coerce=True)\n assert result == expected\n assert isinstance(result, int)\n\n @given(floats(allow_nan=False))\n def test_given_float_returns_float_or_int_with_coerce(self, x: float) -> None:\n expected = int(x) if x.is_integer() else x\n expected_type = int if x.is_integer() else float\n result = fastnumbers.fast_real(x, coerce=True)\n assert result == expected\n assert isinstance(result, expected_type)\n\n @given(integers().map(float).map(repr))\n def test_given_float_string_returns_int_with_coerce_with_intlike(\n self, x: str\n ) -> None:\n expected = int(float(x))\n result = fastnumbers.fast_real(x, coerce=True)\n assert result == expected\n assert isinstance(result, int)\n\n\nclass TestFastFloat:\n \"\"\"\n Tests for the fast_float function that are too specific for the generalized tests.\n \"\"\"\n\n def test_with_range_of_exponents_correctly_parses(self) -> None:\n for x in range(-300, 300):\n val = \"1.0E{0:d}\".format(x)\n assert fastnumbers.fast_float(val) == float(val)\n for x in range(-300, 300):\n val = \"1.0000000000E{0:d}\".format(x)\n assert fastnumbers.fast_float(val) == float(val)\n\n @given(integers())\n def test_given_int_returns_float(self, x: int) -> None:\n expected = float(x)\n result = fastnumbers.fast_float(x)\n assert result == expected\n assert isinstance(result, float)\n\n @given(integers().map(repr))\n def test_given_int_string_returns_float(self, x: str) -> None:\n expected = float(x)\n result = fastnumbers.fast_float(x)\n assert result == expected\n assert isinstance(result, float)\n assert fastnumbers.fast_float(pad(x)) == expected # Accepts padding as well\n\n @given(sampled_from(digits))\n def test_given_unicode_digit_returns_float(self, x: str) -> None:\n expected = unicodedata.numeric(x)\n result = fastnumbers.fast_float(x)\n assert result == expected\n assert isinstance(result, float)\n assert fastnumbers.fast_float(pad(x)) == expected # Accepts padding as well\n\n\nclass TestFastInt:\n \"\"\"\n Tests for the fast_int function that are too specific for the generalized tests.\n \"\"\"\n\n @parametrize(\"base\", [-1, 1, 37])\n def test_given_invalid_base_errors_with_valueerror(self, base: int) -> None:\n with raises(ValueError):\n fastnumbers.fast_int(\"10\", base=base)\n\n @given(floats(allow_nan=False))\n def test_given_float_string_returns_string_as_is(self, x: float) -> None:\n expected = repr(x)\n assert fastnumbers.fast_int(expected) is expected # includes int-like\n\n @given(floats().filter(not_an_integer).map(repr))\n @example(\"nan\")\n @example(\"inf\") # float(\"inf\") returns OverflowError, but \"inf\" is ValueError\n def test_given_float_string_raises_valueerror_if_raise_on_invalid_is_true(\n self, x: str\n ) -> None:\n with raises(ValueError):\n fastnumbers.fast_int(x, raise_on_invalid=True)\n\n @given(integers())\n def test_given_int_string_returns_int_with_non_base_10(self, x: int) -> None:\n for base in range(2, 36 + 1):\n # Avoid recursion error because of overly simple baseN function.\n if len(repr(x)) < 30:\n assert fastnumbers.fast_int(base_n(x, base), base=base) == x\n assert fastnumbers.fast_int(bin(x), base=2) == x\n assert fastnumbers.fast_int(bin(x), base=0) == x\n assert fastnumbers.fast_int(oct(x), base=8) == x\n assert fastnumbers.fast_int(oct(x), base=0) == x\n assert fastnumbers.fast_int(oct(x).replace(\"0o\", \"0\"), base=8) == x\n assert fastnumbers.fast_int(hex(x), base=16) == x\n assert fastnumbers.fast_int(hex(x), base=0) == x\n # Force unicode path\n assert fastnumbers.fast_int(hex(x).replace(\"0\", \"\\uFF10\"), base=0) == x\n\n @parametrize(\"zero\", [\"0\", \"\\uFF10\"])\n @parametrize(\"base\", [0, 2, 8, 18])\n def test_given_multiple_zeros_with_base_returns_zero(\n self, zero: str, base: int\n ) -> None:\n assert fastnumbers.fast_int(zero * 4, base=base) == 0\n\n @given(sampled_from(numeric_not_digit))\n def test_given_unicode_numeral_returns_as_is(self, x: str) -> None:\n assert fastnumbers.fast_int(x) == x\n\n\nclass TestFastForceInt:\n \"\"\"\n Tests for the fast_forceint function that are too specific for the generalized tests.\n \"\"\"\n\n @given(floats(allow_nan=False, allow_infinity=False))\n def test_given_float_string_returns_int(self, x: float) -> None:\n expected = int(x)\n result = fastnumbers.fast_forceint(repr(x))\n assert result == expected\n assert isinstance(result, int)\n assert fastnumbers.fast_forceint(pad(repr(x))) == expected # Accepts padding\n\n @given(sampled_from(numeric))\n def test_given_unicode_numeral_returns_int(self, x: str) -> None:\n expected = int(unicodedata.numeric(x))\n result = fastnumbers.fast_forceint(x)\n assert result == expected\n assert isinstance(result, int)\n assert fastnumbers.fast_forceint(pad(x)) == expected # Accepts padding\n\n\nclass TestCheckingFunctions:\n \"\"\"\n Test the successful execution of the \"checking\" functions, e.g.:\n\n - isreal\n - isfloat\n - isint\n - isintlike\n\n \"\"\"\n\n # Handling of NaN and infinity\n\n funcs = [\"isreal\", \"isfloat\"]\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n @parametrize(\"x\", [float(\"nan\"), float(\"inf\"), float(\"-inf\")])\n def test_returns_true_for_nan_and_inf(\n self, func: Union[IsReal, IsFloat], x: float\n ) -> None:\n assert func(x)\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n @parametrize(\"x\", all_nan + [pad(\"nan\"), pad(\"-NAN\")])\n def test_returns_false_for_nan_string_unless_allow_nan_is_true(\n self, func: Union[IsReal, IsFloat], x: str\n ) -> None:\n assert not func(x)\n assert func(x, allow_nan=True)\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n @parametrize(\"x\", most_inf + neg_inf + [pad(\"-inf\"), pad(\"+INFINITY\")])\n def test_returns_false_for_inf_string_unless_allow_infinity_is_true(\n self, func: Union[IsReal, IsFloat], x: str\n ) -> None:\n assert not func(x)\n assert func(x, allow_inf=True)\n\n # Handling of numeric objects as input\n\n funcs = [\"isreal\", \"isint\", \"isintlike\"]\n\n @given(integers())\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_returns_true_if_given_int(\n self, func: Union[IsReal, IsInt, IsIntLike], x: int\n ) -> None:\n assert func(x)\n assert func(x, num_only=True)\n\n funcs = [\"isreal\", \"isfloat\"]\n\n @given(floats())\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_returns_true_if_given_float(\n self, func: Union[IsReal, IsFloat], x: float\n ) -> None:\n assert func(x)\n assert func(x, num_only=True)\n\n funcs = identification_funcs\n\n @given(integers() | floats())\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_returns_false_if_given_number_and_str_only_is_true(\n self, func: IdentificationFuncs, x: FloatOrInt\n ) -> None:\n assert not func(x, str_only=True)\n\n # Handling of strings containing numbers as input\n\n funcs = [\"isreal\", \"isfloat\"]\n\n @given(floats(allow_nan=False, allow_infinity=False).map(repr))\n @example(\"10.\" + \"0\" * 1050)\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_returns_true_if_given_float_string(\n self, func: Union[IsReal, IsFloat], x: str\n ) -> None:\n assert func(x)\n assert func(pad(x)) # Accepts padding\n\n funcs = identification_funcs\n\n @given(integers().map(repr))\n @example(\"40992764608243448035\")\n @example(\"-41538374848935286698640072416676709\")\n @example(\"240278958776173358420034462324117625982\")\n @example(\"1609422692302207451978552816956662956486\")\n @example(\"-121799354242674784350540853922878239740762834\")\n @example(\"32718704454132572934419741118153895444518280065843028297496525078\")\n @example(\"33684944745210074227862907273261282807602986571245071790093633147269\")\n @example(\"1\" + \"0\" * 1050)\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_returns_true_if_given_int_string(\n self, func: IdentificationFuncs, x: str\n ) -> None:\n assert func(x)\n assert func(pad(x)) # Accepts padding\n\n @given((integers() | floats(allow_nan=False, allow_infinity=False)).map(repr))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_returns_false_if_given_string_and_num_only_is_true(\n self, func: IdentificationFuncs, x: str\n ) -> None:\n assert not func(x, num_only=True)\n\n @given(sampled_from(digits))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_unicode_digit_returns_true(\n self, func: IdentificationFuncs, x: str\n ) -> None:\n assert func(x)\n assert func(pad(x)) # Accepts padding\n\n funcs = [\"isreal\", \"isfloat\"]\n\n @given(sampled_from(numeric_not_digit_not_int))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_unicode_numeral_returns_true(\n self, func: Union[IsReal, IsFloat], x: str\n ) -> None:\n assert func(x)\n assert func(pad(x)) # Accepts padding\n\n # Handling of invalid input\n\n funcs = identification_funcs\n\n @given((text() | binary()).filter(not_a_number))\n @example(\"+\")\n @example(\"-\")\n @example(\"e\")\n @example(\"e8\")\n @example(\".\")\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_returns_false_if_given_non_number_string(\n self, func: IdentificationFuncs, x: str\n ) -> None:\n assert not func(x)\n\n @given(sampled_from(not_numeric))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_unicode_non_numeral_returns_false(\n self, func: IdentificationFuncs, x: str\n ) -> None:\n assert not func(x)\n\n @given(text(min_size=2).filter(not_a_number))\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_given_unicode_of_more_than_one_char_returns_false(\n self, func: IdentificationFuncs, x: str\n ) -> None:\n assert not func(x)\n\n funcs = [\"isint\", \"isintlike\"]\n\n @parametrize(\"func\", get_funcs(funcs), ids=funcs)\n def test_returns_false_for_nan_or_inf_string(\n self, func: Union[IsInt, IsIntLike]\n ) -> None:\n assert not func(\"nan\")\n assert not func(\"inf\")\n\n\nclass TestIsFloat:\n \"\"\"Tests for the isfloat function that are too specific for the generalized tests.\"\"\"\n\n @given(integers())\n def test_returns_false_if_given_int(self, x: int) -> None:\n assert not fastnumbers.isfloat(x)\n\n\nclass TestIsInt:\n \"\"\"Tests for the isint function that are too specific for the generalized tests.\"\"\"\n\n @given(floats())\n def test_returns_false_if_given_float(self, x: str) -> None:\n assert not fastnumbers.isint(x)\n\n @given(integers())\n def test_returns_true_if_given_int_string_with_non_base_10(self, x: int) -> None:\n for base in range(2, 36 + 1):\n # Avoid recursion error because of overly simple baseN function.\n if len(repr(x)) < 30:\n assert fastnumbers.isint(base_n(x, base), base=base)\n assert fastnumbers.isint(bin(x), base=2)\n assert fastnumbers.isint(bin(x), base=0)\n assert fastnumbers.isint(oct(x), base=8)\n assert fastnumbers.isint(oct(x), base=0)\n assert fastnumbers.isint(oct(x).replace(\"0o\", \"0\"), base=8)\n if x != 0:\n assert not fastnumbers.isint(oct(x).replace(\"0o\", \"0\"), base=0)\n assert fastnumbers.isint(hex(x), base=16)\n assert fastnumbers.isint(hex(x), base=0)\n # Force unicode path\n assert fastnumbers.isint(hex(x).replace(\"0\", \"\\uFF10\"), base=0)\n\n @skipif(\n sys.version_info < (3, 6), reason=\"Underscore handling introduced in Python 3.6\"\n )\n def test_underscores(self) -> None:\n assert fastnumbers.isint(\"0_0_0\")\n assert fastnumbers.isint(\"0_0_0\", base=0)\n assert fastnumbers.isint(\"4_2\")\n assert fastnumbers.isint(\"4_2\", base=0)\n assert fastnumbers.isint(\"1_0000_0000\")\n assert fastnumbers.isint(\"1_0000_0000\", base=0)\n assert fastnumbers.isint(\"0b1001_0100\", base=0)\n assert fastnumbers.isint(\"0xffff_ffff\", base=0)\n assert fastnumbers.isint(\"0o5_7_7\", base=0)\n assert fastnumbers.isint(\"0b_0\", base=0)\n assert fastnumbers.isint(\"0x_f\", base=0)\n assert fastnumbers.isint(\"0o_5\", base=0)\n\n # Underscores in the base selector:\n assert not fastnumbers.isint(\"0_b0\")\n assert not fastnumbers.isint(\"0_b0\", base=0)\n assert not fastnumbers.isint(\"0_xf\")\n assert not fastnumbers.isint(\"0_xf\", base=0)\n assert not fastnumbers.isint(\"0_o5\")\n assert not fastnumbers.isint(\"0_o5\", base=0)\n\n # Old-style octal, still disallowed if base guess is needed:\n assert not fastnumbers.isint(\"0_7\", base=0)\n assert not fastnumbers.isint(\"09_99\", base=0)\n\n # Two underscores:\n assert not fastnumbers.isint(\"0b1001__0100\", base=0)\n assert not fastnumbers.isint(\"0xffff__ffff\", base=0)\n\n @given(floats(allow_nan=False, allow_infinity=False).map(repr))\n def test_returns_false_if_given_float_string(self, x: str) -> None:\n assert not fastnumbers.isint(x)\n assert not fastnumbers.isint(pad(x))\n for base in range(2, 36 + 1):\n if len(x) < 30:\n assert not fastnumbers.isint(x, base=base)\n\n @given(sampled_from(numeric_not_digit_not_int))\n def test_given_unicode_numeral_returns_false(self, x: str) -> None:\n assert not fastnumbers.isint(x)\n\n\nclass TestIsIntLike:\n \"\"\"\n Tests for the isintlike function that are too specific for the generalized tests.\n \"\"\"\n\n @given(floats().filter(not_an_integer))\n def test_returns_false_if_given_non_integer_float(self, x: float) -> None:\n assert not fastnumbers.isintlike(x)\n\n @given(floats().filter(an_integer))\n def test_returns_true_if_given_integer_float(self, x: float) -> None:\n assert fastnumbers.isintlike(x)\n\n @given(\n floats(allow_nan=False, allow_infinity=False).filter(not_an_integer).map(repr)\n )\n def test_returns_false_if_given_non_integer_float_string(self, x: str) -> None:\n assert not fastnumbers.isintlike(x)\n assert not fastnumbers.isintlike(pad(x)) # Accepts padding\n\n @given(sampled_from(numeric_not_digit_not_int))\n def test_given_unicode_non_digit_numeral_returns_false(self, x: str) -> None:\n assert not fastnumbers.isintlike(x)\n\n @given(\n sampled_from(numeric_not_digit).filter(\n lambda x: an_integer(unicodedata.numeric(x))\n )\n )\n def test_given_unicode_digit_numeral_returns_true(self, x: str) -> None:\n assert fastnumbers.isintlike(x)\n assert fastnumbers.isintlike(pad(x)) # Accepts padding\n\n\nclass TestQueryType:\n \"\"\"Tests for the query_type function.\"\"\"\n\n @given(integers())\n def test_returns_int_if_given_int(self, x: int) -> None:\n assert fastnumbers.query_type(x) is int\n\n @given(floats())\n def test_returns_float_if_given_float(self, x: float) -> None:\n assert fastnumbers.query_type(x) is float\n\n @given(integers())\n def test_returns_none_if_given_int_and_int_is_not_allowed(self, x: int) -> None:\n assert fastnumbers.query_type(x, allowed_types=(float,)) is None\n\n @given(floats())\n def test_returns_none_if_given_float_and_float_is_not_allowed(\n self, x: float\n ) -> None:\n assert fastnumbers.query_type(x, allowed_types=(int,)) is None\n\n @given(integers().map(repr))\n def test_returns_int_if_given_int_string(self, x: str) -> None:\n assert fastnumbers.query_type(x) is int\n assert fastnumbers.query_type(pad(x)) is int # Accepts padding\n\n @given(floats(allow_nan=False, allow_infinity=False).map(repr))\n def test_returns_float_if_given_float_string_padded_or_not(self, x: str) -> None:\n assert fastnumbers.query_type(x) is float\n assert fastnumbers.query_type(pad(x)) is float # Accpets padding\n\n @given(integers().map(repr))\n def test_returns_none_if_given_int_string_and_int_is_not_allowed(\n self, x: str\n ) -> None:\n assert fastnumbers.query_type(x, allowed_types=(float, str)) is None\n\n @given(sampled_from(digits))\n def test_given_unicode_digit_returns_int(self, x: str) -> None:\n assert fastnumbers.query_type(x) is int\n assert fastnumbers.query_type(pad(x)) is int # Accepts padding\n\n @given(sampled_from(numeric_not_digit_not_int))\n def test_given_unicode_numeral_returns_float(self, x: str) -> None:\n assert fastnumbers.query_type(x) is float\n assert fastnumbers.query_type(pad(x)) is float # Accepts padding\n\n @given(sampled_from(not_numeric))\n def test_given_unicode_non_numeral_returns_str_or_none_if_str_not_allowed(\n self, x: str\n ) -> None:\n assert fastnumbers.query_type(x) is str\n assert fastnumbers.query_type(x, allowed_types=(int, float)) is None\n\n @given(text(min_size=2).filter(not_a_number))\n def test_given_unicode_of_more_than_one_char_returns_str(self, x: str) -> None:\n assert fastnumbers.query_type(x) is str\n\n @given(text().filter(not_a_number))\n @example(\"+\")\n @example(\"-\")\n @example(\"e\")\n @example(\"e8\")\n @example(\".\")\n def test_returns_str_if_given_non_number_string(self, x: str) -> None:\n assert fastnumbers.query_type(x) is str\n\n @given(text().filter(not_a_number))\n def test_returns_none_if_given_non_number_string_and_str_is_not_allowed(\n self, x: str\n ) -> None:\n assert fastnumbers.query_type(x, allowed_types=(int, float)) is None\n\n @given(binary().filter(not_a_number))\n def test_returns_bytes_if_given_non_number_string(self, x: bytes) -> None:\n assert fastnumbers.query_type(x) is bytes\n\n @given(binary().filter(not_a_number))\n def test_returns_none_if_given_non_number_bytes_and_bytes_is_not_allowed(\n self, x: bytes\n ) -> None:\n assert fastnumbers.query_type(x, allowed_types=(int, float)) is None\n\n @parametrize(\"x\", all_nan + [pad(\"+nan\"), pad(\"-NAN\")])\n def test_returns_str_for_nan_string_unless_allow_nan_is_true(self, x: str) -> None:\n assert fastnumbers.query_type(x) is str\n assert fastnumbers.query_type(x, allow_nan=True) is float\n\n @parametrize(\"x\", most_inf + neg_inf + [pad(\"+inf\"), pad(\"-INFINITY\")])\n def test_returns_str_for_inf_string_unless_allow_infinity_is_true(\n self, x: str\n ) -> None:\n assert fastnumbers.query_type(x) is str\n assert fastnumbers.query_type(x, allow_inf=True) is float\n\n def test_given_nan_returns_float(self) -> None:\n assert fastnumbers.query_type(float(\"nan\")) is float\n\n def test_given_inf_returns_float(self) -> None:\n assert fastnumbers.query_type(float(\"inf\")) is float\n\n @given(floats(allow_nan=False).filter(an_integer))\n def test_given_float_returns_int_if_intlike_with_coerce(self, x: float) -> None:\n assert fastnumbers.query_type(x, coerce=True) == int\n\n @given(floats(allow_nan=False))\n def test_given_float_returns_float_or_int_with_coerce(self, x: float) -> None:\n assert (\n fastnumbers.query_type(x, coerce=True) == int if x.is_integer() else float\n )\n\n @given(\n lists(floats())\n | tuples(floats())\n | dictionaries(floats(), floats())\n | sets(floats())\n | iterables(floats())\n )\n def test_containers_returns_container_type(\n self, x: Union[Dict[float, float], Iterable[float]]\n ) -> None:\n assert fastnumbers.query_type(x) is type(x)\n assert fastnumbers.query_type(x, allowed_types=(float, int, str)) is None\n","sub_path":"tests/test_fastnumbers.py","file_name":"test_fastnumbers.py","file_ext":"py","file_size_in_byte":41491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"516893860","text":" \n'''\nTest functions to illustrate the classes of the\npackages 'game' and 'hexgame'\n\n\nCreated on Sat 20 Aug 2016\n@author: f.maire@qut.edu.au\n \nLast revised Sat 28 Aug\n \n \n'''\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport game, hexgame\n\n\n\ndef test_H_H():\n '''\n Game between two human players\n '''\n hg = hexgame.Hexgame(11)\n p1 = game.Human_hex_player(hg.clone())\n p1.set_color(-1)\n p2 = game.Human_hex_player(hg.clone()) \n p2.set_color(+1)\n hg.print_player_turn() \n game.play(hg, p1, p2, verbose = 1)\n\n\ndef test_H_M():\n '''\n Game between human player and minmax player\n '''\n hg = hexgame.Hexgame(5)\n p1 = game.Human_hex_player(hg.clone())\n p1.set_color(-1)\n p2 = game.Minmax_player(hg.clone(),hexgame.hexgame_eval) \n p2.set_color(+1)\n\n game.play(hg, p1, p2, verbose = 1)\n\ndef test_H_A():\n '''\n Game between human player and alphabeta player\n '''\n hg = hexgame.Hexgame(5)\n p1 = game.Human_hex_player(hg.clone())\n p1.set_color(-1)\n p2 = game.Alphabeta_player(hg.clone(),hexgame.hexgame_eval) \n p2.set_color(+1)\n\n game.play(hg, p1, p2, verbose = 1)\n\ndef test_debug():\n '''\n debug Game between human player and minmax player\n '''\n hg = hexgame.Hexgame(3)\n hg.set_board([1,0,0,-1,1,-1,0,0,-1])\n \n p1 = game.Human_hex_player(hg.clone())\n p1.set_color(-1)\n p2 = game.Minmax_player(hg.clone(),hexgame.hexgame_eval) \n p2.set_color(+1)\n \n \n game.play(hg, p1, p2, verbose = 1)\n \nif __name__ == \"__main__\":\n# test_H_H()\n print(''' \n Black tries to connect North and South\n White tries to connect East and West\n \n Top left cell has coordinates r=0 and c=0\n ''')\n test_H_M()\n\n\n\n# + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \n# CODE CEMETARY\n# + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \n\n#\n# # Experiment 1:\n# # Player 1 and Player 2 are evenly matched with 3-ply deep search\n# # player 2 wins with a final score of 28\n# # player 1 0.2 s per ply player 2 0.4 s per ply\n# play(othello.game(), player(lambda x: minimax.minimax(x, 3)),\n# player(lambda x: minimax.minimax(x, 3)), False)\n# \n# # Experiment 2:\n# # now we show the significance of an evaluation function\n# # we weaken player1 to 2 ply deep but use the edge eval fun\n# # player 1 now beats player 2 with a score of 58!\n# # player 1 0.1 s per ply player 2 0.4 s per ply\n# play(othello.game(), player(lambda x: minimax.minimax(x, 2, othello.edge_eval)),\n# player(lambda x: minimax.minimax(x, 3)), False)\n#\n# # Experiment 1 (with alpha-beta):\n# # player 1 0.1 s per ply, player 2 0.1 s per ply\n# play(othello.game(), player(lambda x: minimax.alphabeta(x, 3)),\n# player(lambda x: minimax.alphabeta(x, 3)), False)\n#\n# # Experiment 2 (with alpha-beta):\n# # player 1 0.0 s per ply player 2 0.1 s per ply\n# play(othello.game(), player(lambda x: minimax.alphabeta(x, 2, othello.edge_eval)),\n# player(lambda x: minimax.alphabeta(x, 3)), False)\n#\n\n","sub_path":"w6/demo_hex.py","file_name":"demo_hex.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"78975182","text":"config = {}\nconfig['mongo'] = {}\nconfig['mongo']['host'] = '172.17.0.72'\nconfig['mongo']['port'] = 27017\n\nconfig['rdb'] = {}\nconfig['rdb']['host'] = '127.0.0.1'\nconfig['rdb']['port'] = 28015\n\nrefLookup = {'Genesis':['Gen','Ge','Gn'],\n 'Exodus':['Exo','Ex','Exod'],\n 'Leviticus':['Lev','Le','Lv'],\n 'Numbers':['Num','Nu','Nm','Nb'],\n 'Deuteronomy':['Deut','Dt'],\n 'Joshua':['Josh','Jos','Jsh'],\n 'Judges':['Judg','Jdg','Jg','Jdgs'],\n 'Ruth':['Ruth', 'Rth','Ru'],\n '1 Samuel':['1 Sam','1 Sa'],\n '2 Samuel':['2 Sam','2 Sa'],\n '1 Kings':['1 Kgs','1 Ki'],\n '2 Kings':['2 Kgs','2 Ki'],\n '1 Chronicles':['1 Chron','1 Ch', '1 Chr'],\n '2 Chronicles':['2 Chron','2 Ch', '2 Chr'],\n 'Ezra':['Ezra','Ezr'],\n 'Nehemiah':['Neh','Ne'],\n 'Esther':['Esth','Est','Es'],\n 'Job':['Job','Job','Jb'],\n 'Psalm':['Pslm','Ps','Psa','Psm','Pss'],\n 'Proverbs':['Prov','Pr','Prv'],\n 'Ecclesiastes':['Eccles','Ec','Ecc','Eccl'],\n 'Song of Solomon':['Song','So','Song of Songs','SOS','Sng'],\n 'Isaiah':['Isa','Is'],\n 'Jeremiah':['Jer','Je','Jr'],\n 'Lamentations':['Lam','La'],\n 'Ezekiel':['Ezek','Eze','Ezk'],\n 'Daniel':['Dan','Da','Dn'],\n 'Hosea':['Hos','Ho'],\n 'Joel':['Joel','Joe','Jl'],\n 'Amos':['Amos','Am'],\n 'Obadiah':['Obad','Ob'],\n 'Jonah':['Jnh','Jonah'],\n 'Micah':['Micah','Mic'],\n 'Nahum':['Nahum','Nah','Na'],\n 'Habakkuk':['Hab','Hab'],\n 'Zephaniah':['Zeph','Zep','Zp'],\n 'Haggai':['Haggai','Hag','Hg'],\n 'Zechariah':['Zech','Zec','Zc'],\n 'Malachi':['Mal','Mal','Ml'],\n 'Matthew':['Matt','Mt'],\n 'Mark':['Mark','Mrk','Mk','Mr'],\n 'Luke':['Luke','Luk','Lk'],\n 'John':['John','Jn','Jhn'],\n 'Acts':['Acts','Ac'],\n 'Romans':['Rom','Ro','Rm'],\n '1 Corinthians':['1 Cor','1 Co'],\n '2 Corinthians':['2 Cor','2 Co'],\n 'Galatians':['Gal','Ga'],\n 'Ephesians':['Ephes','Eph'],\n 'Philippians':['Phil','Php'],\n 'Colossians':['Col','Col'],\n '1 Thessalonians':['1 Thess','1 Thes', '1 Th'],\n '2 Thessalonians':['2 Thess','2 Thes', '2 Th'],\n '1 Timothy':['1 Tim','1 Ti'],\n '2 Timothy':['2 Tim','2 Ti'],\n 'Titus':['Titus','Tit'],\n 'Philemon':['Philem','Phm'],\n 'Hebrews':['Hebrews','Heb'],\n 'James':['James','Jas','Jm'],\n '1 Peter':['1 Pet','1 Pe'],\n '2 Peter':['2 Pet','2 Pe'],\n '1 John':['1 John','1 Jn'],\n '2 John':['2 John','2 Jn'],\n '3 John':['3 John','3 Jn'],\n 'Jude':['Jude','Jud'],\n 'Revelation':['Rev','Re']}\n","sub_path":"data/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"560126192","text":"# -*- coding: utf-8 -*-\n\nfrom mainapp.models import Subjects, Lecture\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom oracle.ntnu_collectors import *\nfrom django.utils.crypto import get_random_string\nimport datetime\n\ndef add_subject(subject):\n try:\n Subjects.objects.get(subjectCode=subject)\n except ObjectDoesNotExist:\n inf = get_course_info(subject)\n code = get_random_string()\n exmdate = get_exam_date(subject)\n if inf is None:\n Subjects.objects.create(subjectCode=subject, accessCode=code)\n else:\n sub = Subjects.objects.create(subjectCode=subject, subjectName=inf['courseName'],\n lecturerName=inf['lecturer'], lecturerPhone=inf['lecturer_phone'],\n lecturerEmail=inf['lecturer_mail'],\n lecturerOffice=inf['lecturer_office'],\n examdate=exmdate,\n accessCode=code)\n lectures = get_course_lectures(subject)\n if lectures is not None:\n for lecture in lectures:\n if lecture['acronym'] == \"FOR\" or lecture['acronym'] == \"F/Ø\":\n Lecture.objects.create(subject=sub,\n lectureType=lecture['acronym'],\n day=lecture['dayNum'] - 1,\n start=datetime.time(int(lecture['from'][0:2]), int(lecture['from'][3:5])),\n end=datetime.time(int(lecture['to'][0:2]), int(lecture['to'][3:5])),\n room=lecture['rooms'][0]['romNavn'])","sub_path":"mainapp/database_add.py","file_name":"database_add.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"367231048","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Feb 8 13:32:25 2020\r\n\r\n@author: whip\r\n\r\n参考\r\nhttps://qiita.com/1ntegrale9/items/9d570ef8175cf178468f\r\n\"\"\"\r\n\r\n\r\nimport time\r\nimport discord\r\nimport sinomain as sinowhip\r\nimport plot_graph as pg\r\nimport datetime\r\n\r\n#TOKEN = \r\n\r\nclient = discord.Client()\r\n\r\n\r\n@client.event\r\nasync def on_ready():\r\n # 起動したらターミナルにログイン通知が表示される\r\n print('ログインしました')\r\n\r\n# メッセージ受信時に動作する処理\r\n@client.event\r\nasync def on_message(message):\r\n #auto_get_pic = False # どうやんのこれ\r\n interval = 15\r\n itr = int(1200 / interval )+2 #15秒前から0秒前の間にスタートしましょう\r\n mode = \"pc\"\r\n timezone = 21 #12時半以外でよろです\r\n output = True\r\n \r\n # メッセージ送信者がBotだった場合は無視する\r\n if message.author.bot:\r\n return\r\n # 「/neko」と発言したら「にゃーん」が返る処理\r\n if message.content == '!neko':\r\n await message.channel.send('にゃーん')\r\n\r\n if message.content == '!start':\r\n await message.channel.send(\"自動情報取得開始 間隔 : \"+str(interval)+\" 秒, 取得回数 \"+str(itr)+\" 回\" )\r\n \r\n start_time = time.time()\r\n #info_logの初期化 座標は適当に実際のログから取ってきた値\r\n info_log = [[\"\", {'inochi': [[0, [41.55555555555556, 38.5]], [0, [264.77777777777777, 31.0]]], 'combo': [[0, [40.75, 53.0]], [0, [263.15, 58.5]]], 'time_sec': [[1200, [155.125, 31.5]]], 'other': [], 'error_flag': [0, 0, 0, 0], 'time_delay': [0, 0, 0, 0]}]]\r\n \r\n for i in range(itr):\r\n print(\"\\n#\"+str(i))\r\n [img_name, d] = sinowhip.get_game_info_dict(mode, info_log[-1][1][\"inochi\"], info_log[-1][1][\"time_delay\"])\r\n info_log = log_append(info_log, img_name, d)\r\n status_message = \"#\"+str(i)+\" \"\r\n \r\n \r\n if d[\"error_flag\"] == [0,0,0,0]:\r\n status_message += \"正常に取得しました\"\r\n await message.channel.send(status_message)\r\n \r\n elif d[\"error_flag\"] == [1,1,0,0]:\r\n for other_info in d[\"other\"]:\r\n if other_info[0] == \"バトルに戻る\":\r\n status_message += \"オソウジ中です\"\r\n await message.channel.send(status_message)\r\n break\r\n \r\n else:\r\n status_message += \"情報取得中にエラーが発生しました・。;\"\r\n await message.channel.send(status_message)\r\n \r\n await message.channel.send(file=discord.File(img_name))\r\n time.sleep(0.5)\r\n await send_game_info(d, info_log, interval, message)\r\n time.sleep(0.5)\r\n await send_additional_game_info(d, info_log, message)\r\n \r\n now = datetime.datetime.now()\r\n if now.time().hour >= timezone and now.time().minute >= 20 and now.time().second >= interval: #コロシアム終わったらループ終了\r\n break\r\n end_time = time.time()\r\n time.sleep(max((interval - (end_time - start_time) ),0))\r\n start_time = time.time()\r\n await message.channel.send(\"自動情報取得終了\")\r\n \r\n print(\"\\ninfo_log = \",info_log)\r\n if output == True:\r\n graph_name = pg.plot_graph(info_log)\r\n await message.channel.send(file=discord.File(graph_name)) #積み上げグラフ\r\n graph_name = pg.plot_graph_100(info_log)\r\n await message.channel.send(file=discord.File(graph_name)) #100%積み上げグラフ\r\n \r\n if message.content == '!pic':\r\n [img_name, d] = sinowhip.get_game_info_dict(mode)\r\n if d[\"error_flag\"] == [0,0,0,0]:\r\n await message.channel.send(file=discord.File(img_name))\r\n await message.channel.send(\"正常に取得しました\")\r\n await message.channel.send(str(d))\r\n elif d[\"error_flag\"] == [1,1,0,0] and \"バトルに戻る\" in d[\"other\"]:\r\n await message.channel.send(\"オソウジ中です\")\r\n else:\r\n await message.channel.send(file=discord.File(img_name))\r\n await message.channel.send(\"情報取得中にエラーが発生しました・。;\")\r\n await message.channel.send(str(d))\r\n \r\n if message.content == '!stop':\r\n # auto_get_pic = False\r\n pass\r\n \r\n if message.content == '!restart':\r\n # auto_get_pic = True\r\n pass\r\n \r\n if message.content == '!owari':\r\n await message.channel.send(\"(¦3[▓▓]\")\r\n await client.close()\r\n\r\nasync def send_game_info(d, info_log, interval, message):\r\n text = \"表示情報\\n\"\r\n if info_log[-1][1][\"error_flag\"][2] != 0:\r\n time_estimate = max(info_log[-1][1][\"time_sec\"][0][0] - info_log[-1][1][\"time_delay\"][2] * interval, 0)\r\n text += (\" 残り時間 **\"+str(time_estimate // 60)+\":\"+str(time_estimate % 60).zfill(2)+\"** (\"+str(time_estimate)+\"秒) (推定)\\n\")\r\n else:\r\n text += (\" 残り時間 **\"+str(info_log[-1][1][\"time_sec\"][0][0] // 60)+\":\"+str(info_log[-1][1][\"time_sec\"][0][0] % 60).zfill(2)+\"** (\"+str(info_log[-1][1][\"time_sec\"][0][0])+\"秒)\\n\")\r\n \r\n text += (\" 味方イノチ **\"+str(info_log[-1][1][\"inochi\"][0][0])+\"** - **\"+str(info_log[-1][1][\"inochi\"][1][0])+\"** 相手イノチ\")\r\n if info_log[-1][1][\"error_flag\"][0] != 0:\r\n text += \" ( __**\"+str(info_log[-1][1][\"time_delay\"][0] * interval)+\"**__ 秒前の情報)\"\r\n try:\r\n text += (\"\\n イノチ比 **\"+str(round(max(1, info_log[-1][1][\"inochi\"][0][0] / info_log[-1][1][\"inochi\"][1][0]), 2))+\"** : **\"+str(round(max(1, info_log[-1][1][\"inochi\"][1][0] / info_log[-1][1][\"inochi\"][0][0]), 2))+\"**\")\r\n except ZeroDivisionError:\r\n print(\"どちらかのイノチが0です\")\r\n text += \"\\n\"\r\n \r\n \"\"\"\r\n #コンボの情報はいちいち表示しないことにしました\r\n text += (\" 味方コンボ **\"+str(info_log[-1][1][\"combo\"][0][0])+\"** - **\"+str(info_log[-1][1][\"combo\"][1][0])+\"** 相手コンボ\")\r\n if info_log[-1][1][\"error_flag\"][1] != 0:\r\n text += \" ( __**\"+str(info_log[-1][1][\"time_delay\"][1] * interval)+\"**__ 秒前の情報)\"\r\n text += \"\\n\"\r\n \"\"\"\r\n \"\"\"\r\n if info_log[-1][1][\"error_flag\"][3] == 0:\r\n text += \" 他に取得した文字情報 : \"\r\n for other_word in info_log[-1][1][\"other\"]:\r\n text += (other_word[0] + \", \")\r\n \"\"\"\r\n await message.channel.send(text)\r\n\r\nasync def send_additional_game_info(d, info_log, message):\r\n fulltext =\"追加情報\\n\"\r\n text_list = []\r\n \r\n if d[\"error_flag\"][0] == 0:\r\n text_list.append(reverse_info(d))\r\n \r\n if len(text_list):\r\n for text in text_list:\r\n fulltext += (\" \"+text+\"\\n\")\r\n else:\r\n fulltext += (\"なし\")\r\n await message.channel.send(fulltext)\r\n\r\ndef reverse_info(d):\r\n reverse_text = \"\"\r\n ressei_0, yuusei_0 = d[\"inochi\"][0][0], d[\"inochi\"][1][0]\r\n \r\n if ressei_0 > yuusei_0:\r\n ressei_0, yuusei_0 = yuusei_0, ressei_0\r\n \r\n if ressei_0*2.5 < yuusei_0:\r\n if ressei_0*2.55 > yuusei_0:\r\n reverse_text += \"1シップ圏外ですが、最大乱数だとシップ後逆転もありえます\"\r\n return reverse_text\r\n \r\n reverse_text += \"1シップ圏外です\"\r\n \r\n else:\r\n reverse_cases = 0\r\n minimum_percent = -1\r\n for i in range(30,14,-1):\r\n ressei_1 = ressei_0 + yuusei_0 * i/100\r\n yuusei_1 = yuusei_0 - yuusei_0 * i/100\r\n if ressei_1 > yuusei_1:\r\n reverse_cases += 1\r\n minimum_percent = i\r\n reverse_probability = reverse_cases / 16\r\n reverse_text += (\"1シップ逆転の可能性 **\"+str(reverse_probability * 100)+\" %**  最低必要なイノチ移動率 **\"+str(minimum_percent)+\" %**\")\r\n \r\n return reverse_text\r\n\r\ndef log_append(info_log, img_name, d):\r\n d[\"time_delay\"] = [0, 0, 0, 0]\r\n \r\n if d[\"error_flag\"][0] == 1:\r\n d[\"inochi\"] = info_log[-1][1][\"inochi\"]\r\n d[\"time_delay\"][0] = info_log[-1][1][\"time_delay\"][0] + 1\r\n \r\n if d[\"error_flag\"][1] == 1:\r\n d[\"combo\"] = info_log[-1][1][\"combo\"]\r\n d[\"time_delay\"][1] = info_log[-1][1][\"time_delay\"][1] + 1\r\n\r\n if d[\"error_flag\"][2] == 1:\r\n d[\"time_sec\"] = info_log[-1][1][\"time_sec\"]\r\n d[\"time_delay\"][2] = info_log[-1][1][\"time_delay\"][2] + 1\r\n \r\n info_log.append([img_name, d])\r\n #print(\"info_log = \", info_log)\r\n return info_log\r\n \r\n\r\n# Botの起動とDiscordサーバーへの接続\r\nclient.run(TOKEN)\r\n","sub_path":"archive_g/honu1.2/discordbot.py","file_name":"discordbot.py","file_ext":"py","file_size_in_byte":8911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"327593695","text":"import argparse\nimport subprocess\nimport datetime\nimport yaml\nimport time\nimport logging\nimport threading\nimport os\n\n# ----------------------------------------------------------------------------------------------------------------------------\nclass ThreadedSubprocess(threading.Thread):\n def __init__(self, cmd, retries, sleep):\n self.cmd = cmd\n self.retries = retries\n self.sleep = sleep\n threading.Thread.__init__(self)\n self.daemon = True\n self.name = cmd\n\n def run(self):\n for tries in range(1, self.retries+1):\n self.process = subprocess.Popen(self.cmd.split())\n logger.info(\"Command '{}' started on try {} of {} with pid {}\".format(self.cmd, tries, retries, self.process.pid))\n self.process.wait()\n if self.process.returncode == 0:\n logger.info(\"Command '{}' with pid {} ended on try {} of {} with return code {}\".format(self.cmd, self.process.pid, tries, retries, self.process.returncode))\n break\n elif self.process.returncode == -15:\n logger.warning(\"Command '{}' with pid {} was sent SIGTERM signal\".format(self.cmd, self.process.pid))\n break\n elif self.process.returncode == -9:\n logger.warning(\"Command '{}' with pid {} was sent SIGKILL signal\".format(self.cmd, self.process.pid))\n break\n else:\n logger.error(\"Command '{}' with pid {} failed on try {} of {} with return code {}\".format(self.cmd, self.process.pid, tries, retries, self.process.returncode))\n if self.sleep > 0:\n time.sleep(self.sleep)\n \n def terminate(self):\n \"\"\" Send SIGTERM(15) signal to the current process \"\"\"\n self.process.terminate()\n# ----------------------------------------------------------------------------------------------------------------------------\ndef terminate_running_threads(threads):\n \"\"\" Terminate all running threads \"\"\"\n for thread in threads:\n thread.terminate()\n time.sleep(0.1)\n# ----------------------------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n parser=argparse.ArgumentParser()\n parser.add_argument(\"configfile\", help=\"yaml file containing albaboss configuration parameters\")\n args=parser.parse_args()\n\n parameters=None\n\n with open(args.configfile, 'r') as cf:\n parameters=yaml.load(cf.read())\n \n logger = logging.getLogger()\n logger.setLevel(parameters[\"logging\"][\"level\"])\n log_formatter = logging.Formatter(\"%(asctime)s %(name)s %(levelname)s %(message)s\", \"%d-%m-%Y %H:%M:%S\")\n if parameters[\"logging\"][\"directory\"] == \"None\":\n log_handler = logging.StreamHandler()\n else:\n if not os.path.isdir(parameters[\"logging\"][\"directory\"]):\n os.makedirs(parameters[\"logging\"][\"directory\"])\n log_handler = logging.FileHandler(parameters[\"logging\"][\"directory\"]+\"/albaboss/\"+datetime.datetime.now().strftime(\"%d%m%Y_%H%M%S\")+\".log\")\n log_handler.setFormatter(log_formatter)\n log_handler.setLevel(parameters[\"logging\"][\"level\"])\n logger.addHandler(log_handler)\n\n logger.info(\"Starting albaboss\")\n\n parallel_threads = []\n \n for process_type in [\"serial-processes\", \"parallel-processes\"]:\n logger.info(\"Running {}\".format(process_type))\n processes_keys = parameters[process_type].keys()\n processes_keys.sort()\n for process in processes_keys:\n cmd = parameters[process_type][process][\"cmd\"]\n retries = parameters[process_type][process][\"retries\"]\n sleep = parameters[process_type][process][\"sleep\"]\n\n thread = ThreadedSubprocess(cmd, retries, sleep)\n thread.start()\n\n time.sleep(0.1)\n\n if process_type == \"serial-processes\":\n thread.join()\n if thread.process.returncode != 0:\n logger.error(\"Command '{}' has ended unexpectedly. Exiting albaboss with return code 1\".format(cmd))\n exit(1)\n else:\n parallel_threads.append(thread)\n\n while len(parallel_threads) != 0:\n for n, thread in enumerate(parallel_threads):\n if thread.is_alive():\n pass\n else:\n if thread.process.returncode == 0:\n logger.info(\"Command '{}' has ended successfully\".format(thread.cmd))\n parallel_threads.pop(n)\n elif thread.process.returncode == -9 or thread.process.returncode == -15:\n logger.info(\"Command '{}' was killed/terminated by user\".format(thread.cmd))\n parallel_threads.pop(n)\n else:\n logger.critical(\"Command '{}' has ended unexpectedly\".format(thread.cmd))\n parallel_threads.pop(n)\n logger.info(\"Looking for active threads\")\n if len(parallel_threads) > 0:\n logger.info(\"Found {} active threads. Terminating them now.\".format(len(parallel_threads)))\n terminate_running_threads(parallel_threads)\n else:\n logger.info(\"Found 0 active threads\")\n logger.critical(\"Exiting albaboss with return code 1\")\n exit(1)\n time.sleep(0.1)\n \n exit(0) \n \n","sub_path":"new_daq/albaboss2.py","file_name":"albaboss2.py","file_ext":"py","file_size_in_byte":5536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"543694343","text":"import numpy as np\nimport pandas as pd\nimport csv\n\nnp.random.seed(1234)\n\ndef power_consumption(path_to_dataset, sequence_length, ratio=1.0):\n # Append lines to data array\n df = pd.read_csv(path_to_dataset, delimiter=';')\n df = df.replace('?', np.nan)\n df = df.dropna()\n df['Global_active_power'] = pd.to_numeric(df['Global_active_power'])\n df_gap = df[['Global_active_power']]\n\n # # uncomment for daily data\n # df_gap = df_gap.groupby('Date').aggregate(sum)\n\n # # uncomment for hourly data\n # df['Date_Time'] = df['Date'] + ' ' + df['Time']\n # df_gap = df[['Date_Time', 'Global_active_power']]\n # times = pd.DatetimeIndex(df_gap.Date_Time)\n # df_gap = df_gap.groupby([times.date, times.hour]).aggregate(sum)\n\n # # uncomment for monthly data\n # df_gap = df[['Date', 'Global_active_power']]\n # times = pd.DatetimeIndex(df.Date)\n # df_gap = df_gap.groupby(times.to_period(\"M\")).aggregate(sum)\n\n gap_data = df_gap.Global_active_power.values\n data = gap_data[:int(ratio * len(gap_data))]\n\n print(\"Data loaded from csv.\")\n print(\"Formatting data...\")\n\n result = []\n for index in range(len(data) - sequence_length):\n result.append(data[index: index + sequence_length])\n result = np.array(result) # shape (2049230, 50)\n\n # Normalise data by mean\n result_mean = result.mean()\n result -= result_mean\n print(\"Shift : \", result_mean)\n print(\"Data : \", result.shape)\n\n # Split data 90% for train, 10% for test\n row = round(0.9 * result.shape[0])\n train = result[:row, :] # result[row, column]\n np.random.shuffle(train)\n X_train = train[:, :-1] # train without the last value\n y_train = train[:, -1] # only the last value (labels)\n X_test = result[row:, :-1] # 10% of test\n y_test = result[row:, -1] # labels for test\n\n X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))\n X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\n\n return [X_train, y_train, X_test, y_test]\n","sub_path":"python/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"448459568","text":"import sys\nimport gym\nimport pylab\nfrom matplotlib import pylab\nfrom pylab import *\nimport random\nimport numpy as np\nimport keras\nfrom collections import deque\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom keras.models import Sequential\nfrom gym import wrappers\nimport tensorflow as tf\nimport time\n\n\n\ndef huber_loss(y_true, y_pred):\n return tf.losses.huber_loss(y_true,y_pred)\n\n# ENV_NAME = \"CartPole-v1\"\n# ENV_NAME= 'MountainCar-v0'\n# ENV_NAME = \"CartPole-v1\"\nENV_NAME = 'MsPacman-ram-v0'\n\nclass DQNAgent:\n\n def __init__(self, state_size, action_size):\n # if you want to see MsPacman learning, then change to True\n self.render = False\n self.load_model = False\n\n # get size of state and action\n self.state_size = state_size\n self.action_size = action_size\n\n # These are hyper parameters for the DQN\n self.discount_factor = 0.99\n self.learning_rate = 0.0025\n self.epsilon = 1.0\n self.epsilon_min = 0.1\n self.epsilon_decay = 0.99999\n self.batch_size = 32\n self.train_start = 50000\n\n # create replay memory using deque\n self.memory = deque(maxlen=750000)\n\n # create main model\n self.model = self.build_model()\n\n # keep track of # of frames trained on\n self.trained_frames = 0\n\n # keep track of # of frames trained on\n self.million_frames = 0\n\n # keep track of average q-value predictions\n self.q_val_predictions = []\n\n # approximate Q function using Neural Network: state is input and Q Value of each action is output\n def build_model(self):\n model = Sequential()\n model.add(Dense(128, input_shape=(self.state_size,), activation=\"relu\"))\n model.add(Dense(128, activation=\"relu\"))\n model.add(Dense(128, activation=\"relu\"))\n model.add(Dense(self.action_size, activation=\"linear\"))\n model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))\n# model.compile(loss=huber_loss, optimizer=Adam(lr=self.learning_rate))\n model.summary()\n\n return model\n\n\n # save sample to the replay memory\n def save_memory(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n# if self.epsilon > self.epsilon_min:\n# self.epsilon -= 1/1000000.0\n# self.epsilon *= self.epsilon_decay\n\n\n def get_action(self, state):\n if np.random.rand() <= self.epsilon:\n random_action = np.random.choice(self.action_size)\n return random_action\n else:\n q_values = self.model.predict(state)\n best_action = np.argmax(q_values[0])\n return best_action #, np.amax(q_values[0])\n\n\n def experience_replay(self, target_model):\n if len(self.memory) < self.train_start:\n return\n batch = random.sample(self.memory, self.batch_size)\n batch = np.array(batch)\n\n curr_state = np.stack(batch[:, 0], axis=1)[0] #STATE\n next_state = np.stack(batch[:, 3], axis=1)[0] #NEXT STATE\n action = batch[:, 1] #ACTION\n reward = batch[:, 2] #REWARD\n done = batch[:, 4] #DEAD\n\n curr_state_Q_target = self.model.predict(curr_state)\n next_state_Q_target = target_model.predict(next_state)\n max_val_next_state_Q_target = np.amax(next_state_Q_target, axis=1)\n self.q_val_predictions.append(np.mean(max_val_next_state_Q_target))\n\n# print(next_state_Q_target)\n# print(max_val_next_state_Q_target)\n\n\n # VECTORIZE BELOW FOR LOOP ATTEMPT\n# done_ix = np.where(done == True)\n# not_done_ix = np.where(done == False)\n\n# done_reward = np.take(reward, done_ix)\n# not_done_reward = np.take(reward, not_done_ix) + self.discount_factor * np.take(max_val_next_state_Q_target, not_done_ix)\n\n# done_actions = np.take(actions, done_ix)\n# not_done_actions np.take(actions, not_done_ix)\n# # print(done_reward, not_done_reward.shape)\n\n# np.put(a, [0, 2], [-44, -55])\n\n\n for i in range(self.batch_size):\n if done[i]:\n curr_state_Q_target[i][action[i]] = reward[i]\n else:\n curr_state_Q_target[i][action[i]] = reward[i] + self.discount_factor * (np.amax(next_state_Q_target[i]))\n\n\n self.model.fit(curr_state, curr_state_Q_target, batch_size=self.batch_size, epochs=1, verbose=0)\n self.trained_frames += self.batch_size\n self.million_frames += self.batch_size\n if self.epsilon > self.epsilon_min:\n self.epsilon -= 2/1000000.0\n\n\ndef main(plot_scores=True):\n\n # model meta data\n model_name = \"second_aws_model\"\n weights_path = \"./saved-weights/\" + model_name\n episodes_per_save = 1000\n thousands_of_episodes = 0\n curr_episode = 1\n\n print(\"Running first episode\")\n\n\n episodes = []\n scores = []\n pos = [] # Mountaincar\n\n ma_scores = []\n\n\n env = gym.make(ENV_NAME)\n# env = wrappers.Monitor('/tmp/cartpole-experiment-0', force=True)\n\n observation_space = env.observation_space.shape[0]\n action_space = env.action_space.n\n agent = DQNAgent(observation_space, action_space)\n # Intiailize Target Model\n target_model = keras.models.clone_model(agent.model)\n target_model.set_weights(agent.model.get_weights())\n\n FRAMES = 0\n num_episodes = 0\n\n# print('HI')\n#\n# print(agent.trained_frames)\n while True:\n \n\n\n\n episodes.append(num_episodes)\n num_episodes += 1\n\n state = env.reset()\n state = np.reshape(state, [1, observation_space])/255.0\n score = 0\n lives = 3\n done = False\n# print('HI')\n\n # while game is not done\n while not done:\n# print('HI')\n\n dead = False\n while not dead:\n if agent.render:\n env.render()\n action = agent.get_action(state)\n state_next, reward, done, info = env.step(action)\n score += reward\n # print(state_next)\n # reward = reward if not done else -reward\n\n # Check if dead: if current lives != lives\n dead = info['ale.lives'] != lives\n lives = info['ale.lives']\n\n\n if dead:\n reward = -1.0\n elif reward == 10.0:\n reward = 0.75\n elif reward >= 100.0:\n reward == 1.0\n else:\n reward = -0.02\n\n # print(done, reward)\n state_next = np.reshape(state_next, [1, observation_space])/255.0\n agent.save_memory(state, action, reward, state_next, done)\n state = state_next\n if done:\n # print(\"Episode: {}, Frames Seen: {}, Frames Trained: {}, Score: {}, Memory Length: {}, Epsilon: {}\".format(\n # num_episodes, FRAMES, agent.trained_frames, score, len(agent.memory), agent.epsilon))\n # pos.append(state_next[0][0])\n # print(pos)\n\n break\n # score_logger.add_score(step, run)\n if agent.million_frames > 100000:\n # print('Update Target Model')\n agent.million_frames = 0\n\n \"\"\"Returns a copy of a keras model.\"\"\"\n target_model = keras.models.clone_model(agent.model)\n target_model.set_weights(agent.model.get_weights())\n\n\n agent.experience_replay(target_model)\n\n FRAMES += 1\n # print(max_right)\n\n scores.append(score)\n\n if curr_episode % 50 == 0:\n print(\"Completed: \" + str(curr_episode) + \" episodes\")\n pos.append(state_next[0][0])\n sys.stdout.flush()\n\n # save the model\n if curr_episode % episodes_per_save == 0:\n open(model_name + \"--\" + str(curr_episode), 'a').close() # create file\n agent.model.save_weights(model_name + \"--\" + str(curr_episode))\n print(\"saved weights successfully\")\n\n curr_episode += 1\n\n\n\n\n # break\n\n\n\n\n # SAVE MODEL\n# if num_episodes % 100 == 0:\n# timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n# agent.model.save_weights(\"./Saved Weights/Pacmanv3_{}.h5\".format(timestr))\n\n\nif __name__ == \"__main__\":\n main(plot_scores=False)\n","sub_path":"AWS_models/second_aws_model.py","file_name":"second_aws_model.py","file_ext":"py","file_size_in_byte":8592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"628179477","text":"import numpy.testing as npt\nimport pandas as pd\nimport pandas.testing as pdt\nimport pytest\n\nfrom rle_array import RLEDtype\n\npytestmark = pytest.mark.filterwarnings(\"ignore:performance\")\n\n\n@pytest.fixture\ndef series_orig():\n return pd.Series([1, 1, 2, 3, 3], dtype=int)\n\n\n@pytest.fixture\ndef array_orig(series_orig):\n return series_orig.values\n\n\n@pytest.fixture\ndef series_rle(series_orig):\n return series_orig.astype(RLEDtype(series_orig.dtype))\n\n\n@pytest.fixture\ndef array_rle(series_rle):\n return series_rle.values\n\n\n@pytest.fixture(params=[\"series\", \"array\"])\ndef mode(request):\n return request.param\n\n\n@pytest.fixture\ndef object_orig(series_orig, array_orig, mode):\n if mode == \"series\":\n return series_orig\n elif mode == \"array\":\n return array_orig\n else:\n raise ValueError(f\"Unknown mode {mode}\")\n\n\n@pytest.fixture\ndef object_rle(series_rle, array_rle, mode):\n if mode == \"series\":\n return series_rle\n elif mode == \"array\":\n return array_rle\n else:\n raise ValueError(f\"Unknown mode {mode}\")\n\n\n@pytest.fixture\ndef comp(mode):\n if mode == \"series\":\n return pdt.assert_series_equal\n elif mode == \"array\":\n return npt.assert_array_equal\n else:\n raise ValueError(f\"Unknown mode {mode}\")\n\n\ndef test_sum(object_orig, object_rle, comp):\n elements_orig = [object_orig, object_orig]\n elements_rle = [object_rle, object_rle]\n elements_mixed = [object_rle, object_orig]\n\n result_orig = sum(elements_orig)\n result_rle = sum(elements_rle)\n result_mixed = sum(elements_mixed)\n\n result_converted1 = result_rle.astype(int)\n comp(result_orig, result_converted1)\n\n result_converted2 = result_mixed.astype(int)\n comp(result_orig, result_converted2)\n","sub_path":"tests/test_builtins.py","file_name":"test_builtins.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"488597978","text":"from typing import Dict, List, Any\n\nimport tkinter as tki\nfrom tkinter import filedialog\nfrom tkinter import messagebox\n\nimport copy\nimport cv2\nimport PIL.Image as Image\nimport PIL.ImageTk as ImageTk\nimport datetime\nimport json\nimport glob\nimport os\nimport time\nimport io\n\nfrom src import extraction as et\nfrom gui.page_control import Page\nimport init_project\nfrom init_project import init_dir\n# Load init params\ninit_param = init_project.init_param()\n\n\nclass DrawingPage(tki.Frame):\n raw_data_draw = ... # type: Dict[\"filename\":str, \"detect\":List[str, List[Any]], \"inside\":List[str, List[Any]], \"area\":List[str, List[Any]]]\n drawing_data = ... # type: Dict[str, Dict[\"color\": str, \"prev\": Dict, \"polygon\": Dict]]\n\n def __init__(self, app, size, page, *args, **kwargs):\n \"\"\" Page 1 config\n\n :param app: Tkinter (GUI builder) setup\n :type app: class\n :param args: Tkinter's arguments\n :type args: Optional\n :param kwargs: Tkinter's kwargs arguments\n :type kwargs: Optional\n \"\"\"\n self.vid = app.vid\n self.config = app.config\n self.window = self\n self.app = app\n self.size = size\n self.page = page\n\n tki.Frame.__init__(self, *args, **kwargs)\n\n # Load data\n self.file_path_o = \"\"\n self.file_path_c = \"\"\n self.tk_photo_line = None\n self.tk_photo_org = None\n self.tk_photo_cp = None\n self.load_img_o = None\n self.load_img_cp = None\n self.load_filename = None\n self.raw_data_draw = copy.deepcopy(init_param[\"load_data\"][\"raw_data_draw\"])\n\n # Output display\n self.error_box = {}\n self.error_line = {}\n\n # Drawing\n self.drawing_data = copy.deepcopy(init_param[\"drawing\"][\"drawing_data\"])\n self.prev_sub_pol = []\n self.count_draw_sub_pol = 0\n self.start_x, self.start_y = 0, 0\n\n # Status\n self.save_status = False\n self.reset_calibrate = True\n self.mode = \"detect\"\n\n buttonframe = tki.Frame(self)\n buttonframe.pack(side=\"top\", fill=\"both\", expand=True)\n self.buttonframe = buttonframe\n\n # Button that lets the user take a snapshot\n # self.btn_snapshot = tki.Button(buttonframe, text=\"Snapshot\", font=(\"Courier\", 44), width=9,\n # command=self.snapshot_origin)\n # self.btn_snapshot.place(relx=0.38, rely=0.05)\n\n self.btn_save = tki.Button(buttonframe, text=\"Save\", font=(\"Courier\", 44), width=9, command=self.save_draw)\n\n # self.browsebutton = tki.Button(buttonframe, text=\"Browse\", font=(\"Courier\", 44), width=9, command=self.browse)\n # self.browsebutton.place(relx=0.74, rely=0.05)\n\n # self.btn_compare = tki.Button(buttonframe, text=\"Compare\", font=(\"Courier\", 44), width=9,\n # command=self.snapshot_compare)\n # self.btn_compare.place(relx=0.38, rely=0.18)\n\n # self.btn_reset = tki.Button(buttonframe, text=\"Reset\", font=(\"Courier\", 44), width=9, command=self.reset)\n # self.btn_reset.place(relx=0.56, rely=0.18)\n\n self.btn_mode_detect = tki.Button(buttonframe, text=\"DO\", font=(\"Courier\", 44),\n command=self.mode_detect, bg=self.drawing_data[\"detect\"][\"color\"])\n # self.btn_mode_detect.place(relx=0.74, rely=0.18)\n self.btn_mode_inside = tki.Button(buttonframe, text=\"DI\", font=(\"Courier\", 44), command=self.mode_inside)\n # self.btn_mode_inside.place(relx=0.81, rely=0.18)\n self.btn_mode_area = tki.Button(buttonframe, text=\"Area\", font=(\"Courier\", 44), command=self.mode_area)\n # self.btn_mode_area.place(relx=0.88, rely=0.18)\n\n # self.pathlabel = tki.Label(buttonframe)\n # self.pathlabel.place(relx=0.41, rely=0.25)\n\n # Result\n # lbl_result = tki.Label(buttonframe, text=\"Result\", font=(\"Courier\", 44))\n # lbl_result.place(relx=0.83, rely=0.35)\n # self.lbl_result = tki.Label(buttonframe, text=\" \", bg=\"yellow\", font=(\"Courier\", 44))\n # self.lbl_result.place(relx=0.83, rely=0.44)\n\n # Drawing cv\n self.canvas2 = tki.Canvas(buttonframe, cursor=\"cross\")\n # self.canvas2.place(relx=0.05, rely=0.35)\n self.canvas2.bind(\"\", self.on_button_press)\n # self.canvas2.bind(\"\", self.on_move_press)\n # self.canvas2.bind(\"\", self.on_button_release)\n self.canvas2.bind(\"\", self.undo)\n # self.canvas2.config(width=app.cam_width, height=app.cam_height)\n\n # # Check latest data\n # list_of_files = glob.glob('data/*') # * means all if need specific format then *.csv\n # if list_of_files:\n # latest_file = max(list_of_files, key=os.path.getctime)\n # self.read_raw_data(latest_file)\n #\n self.canvas3 = tki.Canvas(buttonframe)\n # # self.canvas3.place(relx=0.45, rely=0.35)\n # self.canvas3.config(width=app.cam_width, height=app.cam_height)\n\n def drawing_scale(self, zoom):\n # if zoom > 1:\n for mode in self.drawing_data:\n self.drawing_data[mode][\"prev\"] = []\n if mode == \"inside\":\n scaled = [[int(p * zoom) for p in l] for l in self.drawing_data[mode][\"polygon\"]]\n self.drawing_data[mode][\"polygon\"] = scaled\n self.raw_data_draw[mode] = scaled\n else:\n for i, pol in enumerate(self.drawing_data[mode][\"polygon\"]):\n for j, p in enumerate(pol):\n scaled = [int(p[0] * zoom), int(p[1] * zoom)]\n self.drawing_data[mode][\"polygon\"][i][j] = scaled\n self.raw_data_draw[mode][i][j] = scaled\n\n def show(self, p1=None, p3=None):\n if p1:\n # To page 3\n self.save_status = p1.save_status\n\n self.file_path_o = p1.file_path_o\n self.load_img_o = Image.open(self.file_path_o)\n self.load_img_o = self.load_img_o.resize((self.size[0], self.size[1]), Image.ANTIALIAS)\n self.tk_photo_org = ImageTk.PhotoImage(image=self.load_img_o)\n self.canvas2.create_image(self.size[2], self.size[3], image=self.tk_photo_org, anchor=tki.NW)\n self.canvas2.place(relx=0.05, rely=0.1)\n\n self.drawing_data = p1.drawing_data\n self.raw_data_draw = p1.raw_data_draw\n self.drawing_scale(1.5)\n self.load_draw(2)\n elif p3:\n # To page 1\n self.save_status = p3.save_status\n\n self.drawing_data = p3.drawing_data\n self.raw_data_draw = p3.raw_data_draw\n self.drawing_scale(2/3)\n self.save_draw()\n\n filename = 'data/data_%s.json' % p3.file_path_o[:-4].split(\"/\")[-1]\n self.reset()\n self.read_raw_data(filename)\n self.lift()\n\n def mode_default(self):\n \"\"\" Change draw mode buttons to default \"\"\"\n self.btn_mode_detect = tki.Button(self.window, text=\"DO\", font=(\"Courier\", 44), command=self.mode_detect)\n self.btn_mode_detect.place(relx=0.74, rely=0.18)\n self.btn_mode_inside = tki.Button(self.window, text=\"DI\", font=(\"Courier\", 44), command=self.mode_inside)\n self.btn_mode_inside.place(relx=0.81, rely=0.18)\n self.btn_mode_area = tki.Button(self.window, text=\"Area\", font=(\"Courier\", 44), command=self.mode_area)\n self.btn_mode_area.place(relx=0.88, rely=0.18)\n\n # Remove drawing\n for draw_line in self.prev_sub_pol:\n self.canvas2.delete(draw_line)\n self.drawing_data[self.mode][\"temp_pol\"] = []\n self.prev_sub_pol = []\n self.count_draw_sub_pol = 0\n self.start_x, self.start_y = 0, 0\n\n def mode_detect(self):\n \"\"\" Draw mode: detect \"\"\"\n self.mode_default()\n self.btn_mode_detect = tki.Button(self.window, text=\"DO\", font=(\"Courier\", 44),\n command=self.mode_detect, bg=self.drawing_data[\"detect\"][\"color\"])\n self.btn_mode_detect.place(relx=0.74, rely=0.18)\n self.mode = \"detect\"\n\n def mode_inside(self):\n self.mode_default()\n self.btn_mode_inside = tki.Button(self.window, text=\"DI\", font=(\"Courier\", 44),\n command=self.mode_inside, bg=self.drawing_data[\"inside\"][\"color\"])\n self.btn_mode_inside.place(relx=0.81, rely=0.18)\n self.mode = \"inside\"\n\n def mode_area(self):\n \"\"\" Draw mode: area \"\"\"\n self.mode_default()\n self.btn_mode_area = tki.Button(self.window, text=\"Area\", font=(\"Courier\", 44), command=self.mode_area,\n bg=self.drawing_data[\"area\"][\"color\"])\n self.btn_mode_area.place(relx=0.88, rely=0.18)\n self.mode = \"area\"\n\n def on_button_press(self, event):\n \"\"\" Left Click events in canvas\"\"\"\n if self.save_status:\n self.save_status = False\n self.toggle_save_status()\n\n if self.load_img_o:\n x, y = event.x, event.y\n if self.start_x and self.start_y:\n if self.mode == \"inside\":\n self.drawing_data[self.mode][\"prev\"].append(\n self.canvas2.create_line(\n x, y, self.start_x, self.start_y, width=2, fill=self.drawing_data[self.mode][\"color\"]))\n if self.start_x < x:\n blue_line = [self.start_x, self.start_y, x, y]\n else:\n blue_line = [x, y, self.start_x, self.start_y]\n self.raw_data_draw[self.mode].append(blue_line)\n self.start_x, self.start_y = 0, 0\n else:\n if (abs(x - self.start_x) < 20 and abs(y - self.start_y) < 20) and (len(self.prev_sub_pol) > 1):\n for draw_line in self.prev_sub_pol:\n self.canvas2.delete(draw_line)\n self.prev_sub_pol = []\n self.count_draw_sub_pol = 0\n\n flat_polygon = [item for sublist in self.drawing_data[self.mode][\"temp_pol\"] for item in\n sublist]\n if self.mode == \"area\":\n # todo area more than 1\n if self.drawing_data[self.mode][\"prev\"]:\n self.canvas2.delete(self.drawing_data[self.mode][\"prev\"])\n self.drawing_data[self.mode][\"prev\"] = []\n self.drawing_data[self.mode][\"polygon\"] = []\n self.drawing_data[self.mode][\"prev\"].append([self.canvas2.create_polygon(\n flat_polygon, outline=self.drawing_data[self.mode][\"color\"], fill=\"\", width=2)])\n self.drawing_data[self.mode][\"polygon\"].append(self.drawing_data[self.mode][\"temp_pol\"])\n self.raw_data_draw[self.mode] = self.drawing_data[self.mode][\"polygon\"]\n self.drawing_data[self.mode][\"temp_pol\"] = []\n self.start_x, self.start_y = 0, 0\n else:\n self.prev_sub_pol.append(\n self.canvas2.create_line(x, y, self.drawing_data[self.mode][\"temp_pol\"][-1][0],\n self.drawing_data[self.mode][\"temp_pol\"][-1][1], width=2,\n fill=self.drawing_data[self.mode][\"color\"]))\n self.count_draw_sub_pol += 1\n self.drawing_data[self.mode][\"temp_pol\"].append([x, y])\n else:\n self.start_x, self.start_y = x, y\n self.drawing_data[self.mode][\"temp_pol\"].append([x, y])\n\n def undo(self, event):\n \"\"\" Right click events in canvas\"\"\"\n if self.save_status:\n self.save_status = False\n self.toggle_save_status()\n\n if self.mode == \"inside\":\n if self.drawing_data[self.mode][\"prev\"]:\n self.canvas2.delete(self.drawing_data[self.mode][\"prev\"][-1])\n del self.drawing_data[self.mode][\"prev\"][-1]\n del self.drawing_data[self.mode][\"polygon\"][-1]\n self.raw_data_draw[self.mode] = self.drawing_data[self.mode][\"polygon\"]\n else:\n if self.count_draw_sub_pol:\n # remove sub-polygon\n self.canvas2.delete(self.prev_sub_pol[-1])\n del self.prev_sub_pol[-1]\n del self.drawing_data[self.mode][\"temp_pol\"][-1]\n self.count_draw_sub_pol -= 1\n if not self.count_draw_sub_pol:\n self.start_x, self.start_y = 0, 0\n del self.drawing_data[self.mode][\"temp_pol\"][-1]\n else:\n # remove last polygon\n if self.drawing_data[self.mode][\"polygon\"]:\n del self.drawing_data[self.mode][\"polygon\"][-1]\n self.raw_data_draw[self.mode] = self.drawing_data[self.mode][\"polygon\"]\n self.canvas2.delete(self.drawing_data[self.mode][\"prev\"][-1])\n del self.drawing_data[self.mode][\"prev\"][-1]\n\n def toggle_save_status(self):\n \"\"\"Toggle snapshot status\"\"\"\n if self.page == \"p1\":\n if self.save_status:\n self.btn_save = tki.Button(self.window, text=\"Save\", bg='green', font=(\"Courier\", 44), width=9,\n command=self.save_draw)\n else:\n self.btn_save = tki.Button(self.window, text=\"Save\", font=(\"Courier\", 44), width=9, command=self.save_draw)\n self.reset_calibrate = True\n self.btn_save.place(relx=0.56, rely=0.05)\n\n def load_draw(self, cv_id):\n for mode in self.drawing_data:\n if self.raw_data_draw[mode]:\n if mode == \"inside\":\n lines = self.raw_data_draw[\"inside\"]\n if lines:\n for line in lines:\n if cv_id == 2:\n self.drawing_data[mode][\"prev\"].append(\n self.canvas2.create_line(line[0], line[1], line[2], line[3], width=2, fill='blue'))\n else:\n self.canvas3.create_line(line[0], line[1], line[2], line[3], width=2, fill='blue')\n else:\n for polygon in self.raw_data_draw[mode]:\n flat_polygon = [item for sublist in polygon for item in sublist]\n if cv_id == 2:\n self.drawing_data[mode][\"prev\"].append(self.canvas2.create_polygon(\n flat_polygon, outline=self.drawing_data[mode][\"color\"], fill=\"\", width=2))\n else:\n self.canvas3.create_polygon(\n flat_polygon, outline=self.drawing_data[mode][\"color\"], fill=\"\", width=2)\n self.drawing_data[mode][\"polygon\"] = self.raw_data_draw[mode]\n\n def read_raw_data(self, filename):\n \"\"\"Read json data and update canvas\"\"\"\n if filename:\n with open(filename, 'r') as fp:\n self.raw_data_draw = json.load(fp)\n if (not self.raw_data_draw[\"detect\"]) or (not self.raw_data_draw[\"area\"]):\n self.save_status = False\n else:\n self.save_status = True\n self.toggle_save_status()\n\n # load img\n print(\"Loading data: \")\n print(self.raw_data_draw)\n self.load_img_o = Image.open(self.raw_data_draw[\"filename\"])\n self.file_path_o = self.raw_data_draw[\"filename\"]\n self.load_img_o = self.load_img_o.resize((self.size[0], self.size[1]), Image.ANTIALIAS)\n self.tk_photo_org = ImageTk.PhotoImage(image=self.load_img_o)\n self.canvas2.create_image(self.size[2], self.size[3], image=self.tk_photo_org, anchor=tki.NW)\n\n # load draw\n self.load_draw(2)\n\n def reset(self):\n pass\n\n def save_draw(self):\n \"\"\" Save drawing data to json file\"\"\"\n self.raw_data_draw[\"filename\"] = self.file_path_o\n data = json.dumps(self.raw_data_draw)\n filename = 'data/data_%s.json' % self.file_path_o[:-4].split(\"/\")[-1]\n with open(filename, 'w') as fp:\n fp.write(data)\n print(\"SAVE !\", 'data/data_%s.json' % self.file_path_o[:-4].split(\"/\")[-1])\n self.reset()\n self.read_raw_data(filename)\n\n # Save setting image\n self.canvas2.update()\n filename_png = self.file_path_o.replace(\"/o_\", \"/s_\")\n ps = self.canvas2.postscript(colormode='color')\n img = Image.open(io.BytesIO(ps.encode('utf-8')))\n img.save(filename_png)\n","sub_path":"gui/drawing_control.py","file_name":"drawing_control.py","file_ext":"py","file_size_in_byte":17103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"35571875","text":"# convertToPOEditor.py - converts files formatted by inline manual into\n# files ready to upload into POEditor (.json -> .json)\n# @author d3sandoval - Daniel Sandoval (daniel@discuss.io)\n\n###\n# HOW TO USE\n# Download .json files for every topic in inline manual (?: https://inlinemanual.zendesk.com/hc/en-us/articles/206420473)\n# Place downloaded files into a folder called \"toTranslate\", located in the same directory as this script (/bin/inlinemanual/toTranslate on DIO boxes)\n# Run this script by entering \"python convertToPOEditor.py\" in your terminal\n# uploadToPOEditor.json will be created when script is finished - upload this to POEditor (?: https://poeditor.com/help/)\n# !!! Careful this will overwrite any other file named POEditor.json in the directory\n# Note: You can also update terms to/from POEditor using a github connection\n# (?: https://poeditor.com/help/how_to_translate_a_language_file_from_a_github_project)\n###\n\nimport json\nimport os\nimport copy\n\nfrom pprint import pprint #for testing\n\njson_data = []\ntopic = {}\nfor filename in os.listdir(\"./toTranslate\"):\n if filename.startswith(\"topic\"):\n\n # load INM .json file for processing\n with open(\"./toTranslate/\" + filename) as data_file:\n data = json.load(data_file)\n\n # pprint(data);\n # interpret and add to json data\n step = 0\n for item in data[\"steps\"]:\n topic[\"context\"] = str(data[\"id\"]) + \" \" + str(step) # convert to array using .split()\n topic[\"defintion\"] = \"Topic #\" + str(data[\"id\"]) + \" Step #\" + str(step) # human-readable version of \"context\"\n topic[\"reference\"] = item[\"element\"] # reference element on page, for context\n\n # create a term for the step title\n topicTitle = copy.deepcopy(topic)\n topicTitle[\"term\"] = item[\"title\"]\n json_data.append(topicTitle)\n\n # create a term for the step content\n topic[\"term\"] = item[\"content\"]\n json_data.append(topic)\n\n step += 1\n topic = {}\n\n # code for testing\n# print \"json data now: \\n\"\n# pprint(json_data)\n# print \"\\n\\n\\n\"\n\n# write jsonData to POEditor.json output file\nwith open('uploadToPOEditor.json', 'w') as outfile:\n json.dump(json_data, outfile, indent = 2, ensure_ascii=False)\n","sub_path":"convertToPOEditor.py","file_name":"convertToPOEditor.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"434128019","text":"import turtle\nimport random\ndef isInScreen(win, turtle):\n x = turtle.xcor()\n y = turtle.ycor()\n\n l = -(win.window_width()/2)\n r = -l\n b = -(win.window_height()/2)\n t = -b\n return (x > r and x < l and y < t and y > t)\n\ndef turtleCoin(win, turtle):\n while isInScreen(win, turtle):\n coin = random.randrange(2)\n if(coin == 1):\n turtle.right(90)\n else:\n turtle.left(90)\n turtle.fd(50)\n win.exitonclick()\n\ndef main():\n t = turtle.Turtle()\n win = turtle.Screen()\n t.shape('turtle')\n turtleCoin(win, t)\n\nmain()\n","sub_path":"iteration-turtle.py","file_name":"iteration-turtle.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"310723524","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('directions', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='napravleniya',\n name='istochnik_finansirovaniya',\n field=models.IntegerField(choices=[(0, 'ДМС'), (1, 'ОМС'), (2, 'платно')]),\n ),\n ]\n","sub_path":"directions/migrations/0002_auto_20150618_0046.py","file_name":"0002_auto_20150618_0046.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"497785826","text":"import json\n\nfrom django.http import Http404\nfrom django.utils.encoding import force_text\nfrom django.utils.http import urlsafe_base64_decode\nfrom rest_framework.generics import get_object_or_404\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth import authenticate, get_user_model\n\nimport regions.models\nfrom api.utils import generate_translated_fields\nfrom collections import OrderedDict\nfrom django.conf import settings\nfrom email_user.models import EmailUser, token_generator\nfrom regions.models import GeographicRegion\nfrom rest_framework import exceptions, serializers\nfrom services.models import Service, Provider, ServiceArea\nfrom . import apps as apps_serializers\nfrom . import services as sevices_serializers\nfrom django.contrib.sites.models import Site\nfrom django.db import connections\nimport pymysql.cursors\n\nCAN_EDIT_STATUSES = [Service.STATUS_DRAFT,\n Service.STATUS_CURRENT, Service.STATUS_REJECTED]\nDRFValidationError = exceptions.ValidationError\n\n\nclass SiteSerializer(serializers.ModelSerializer):\n class Meta:\n model = Site\n fields = ('id', 'name', 'domain')\n\nclass GroupSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Group\n fields = ('url', 'id', 'name')\n\n\nclass APILoginSerializer(serializers.Serializer):\n \"\"\"\n Serializer for our \"login\" API.\n Both validates the call parameters and authenticates\n the user, returning the user in the validated_data\n if successful.\n\n Adapted from authtoken/serializers.py for our email-based user model\n \"\"\"\n email = serializers.EmailField()\n password = serializers.CharField()\n\n def validate(self, attrs):\n attrs = super().validate(attrs)\n email = attrs.get('email')\n password = attrs.get('password')\n user = authenticate(email=email, password=password)\n\n if user:\n if not user.is_active:\n msg = _('User account is disabled.')\n raise exceptions.ValidationError(msg)\n else:\n msg = _('Unable to log in with provided credentials.')\n raise exceptions.ValidationError(msg)\n\n attrs['user'] = user\n return attrs\n\n\n# class GroupSerializer(serializers.HyperlinkedModelSerializer):\n# class Meta:\n# model = Group\n# fields = ('url', 'id', 'name')\n\n\nclass RequireOneTranslationMixin(object):\n \"\"\"Validate that for each set of fields with prefix\n in `Meta.required_translated_fields` and ending in _en, _ar, _fr,\n that at least one value is provided.\"\"\"\n\n # Override run_validation so we can get in at the beginning\n # of validation for a call and add our own errors to those\n # the other validations find.\n def run_validation(self, data=serializers.empty):\n # data is a dictionary\n errs = defaultdict(list)\n for field in self.Meta.required_translated_fields:\n if not any(data.get(key, False) for key in generate_translated_fields(field, False)):\n errs[field].append(_('This field is required.'))\n try:\n validated_data = super().run_validation(data)\n except (exceptions.ValidationError, DjangoValidationError) as exc:\n errs.update(serializers.get_validation_error_detail(exc))\n if errs:\n raise exceptions.ValidationError(errs)\n return validated_data\n\n\nclass ServiceAreaSerializer(RequireOneTranslationMixin,\n serializers.HyperlinkedModelSerializer):\n class Meta:\n model = ServiceArea\n fields = tuple(\n [\n 'id',\n 'parent',\n 'url'\n ] + generate_translated_fields('name')\n )\n required_translated_fields = ['name']\n\n\nclass UserSerializer(serializers.ModelSerializer):\n managed_providers = sevices_serializers.ProviderSerializer(\n many=True, read_only=True)\n\n class Meta:\n model = EmailUser\n fields = ('id', 'email', 'groups', 'name', 'surname', 'is_active', 'is_staff', 'language', 'region', 'site', 'is_superuser', 'phone_number', 'title',\n 'position', 'providers', 'managed_providers')\n\n\nclass UserWithGroupSerializer(serializers.ModelSerializer):\n isStaff = serializers.BooleanField(source=\"is_staff\")\n isSuperuser = serializers.BooleanField(source=\"is_superuser\")\n groups = GroupSerializer(many=True)\n providers = sevices_serializers.ProviderSerializer(many=True,)\n managed_providers = sevices_serializers.ProviderSerializer(many=True,)\n\n def validate(self, attrs):\n print(self)\n\n return attrs\n\n class Meta:\n model = EmailUser\n fields = ('id', 'email', 'groups', 'name', 'surname', 'is_active', 'is_staff', 'is_superuser', 'language', 'phone_number', 'title',\n 'position', 'providers', 'isStaff', 'isSuperuser', 'region', 'site', 'managed_providers')\n\n\nclass UserAvatarSerializer(serializers.ModelSerializer):\n avatar = serializers.ImageField(allow_null=True)\n\n def validate(self, attrs):\n avatar = attrs['avatar']\n if avatar and avatar._size >= settings.MAX_UPLOAD_SIZE:\n raise DRFValidationError('File is too large. Max 2.5 MB.')\n return attrs\n\n class Meta:\n model = EmailUser\n fields = ('avatar',)\n\n\nclass EmailSerializer(serializers.Serializer):\n email = serializers.EmailField()\n\n def validate(self, attrs):\n try:\n get_object_or_404(EmailUser, email=attrs['email'])\n return attrs\n except Http404:\n raise DRFValidationError(\n 'The e-mail address is not assigned to any user account.')\n\n\nclass SecurePasswordCredentialsSerializer(serializers.Serializer):\n uidb64 = serializers.RegexField(regex='[0-9A-Za-z_\\-]+')\n token = serializers.RegexField(regex='[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20}')\n\n def validate(self, attrs):\n token = attrs['token']\n try:\n uid = force_text(urlsafe_base64_decode(attrs['uidb64']))\n user = EmailUser.objects.get(pk=uid)\n except (TypeError, ValueError, OverflowError, EmailUser.DoesNotExist):\n raise DRFValidationError('Bad reset link.')\n\n if user is not None and token_generator.check_token(user, token):\n attrs['user_id'] = user.id\n return attrs\n raise DRFValidationError('Bad reset link.')\n\n\nclass ResetUserPasswordSerializer(serializers.Serializer):\n id = serializers.IntegerField()\n new_password1 = serializers.CharField()\n new_password2 = serializers.CharField()\n user = None\n\n def validate(self, attrs):\n try:\n self.user = get_object_or_404(EmailUser, pk=attrs['id'])\n if attrs['new_password1'] != attrs['new_password2']:\n raise DRFValidationError(\n \"The two password fields didn't match.\")\n except Http404:\n raise DRFValidationError('Invalid user.')\n\n return attrs\n\n\nclass ProviderSerializer(serializers.ModelSerializer):\n number_of_monthly_beneficiaries = serializers.IntegerField(\n min_value=0, max_value=1000000,\n required=False,\n allow_null=True\n )\n\n class Meta:\n model = Provider\n fields = tuple(\n [\n 'url', 'id',\n ] +\n generate_translated_fields('name') +\n generate_translated_fields('description') +\n generate_translated_fields('focal_point_name') +\n generate_translated_fields('address') +\n [\n 'type', 'phone_number', 'website',\n 'facebook', 'twitter',\n 'focal_point_phone_number',\n 'user', 'number_of_monthly_beneficiaries', 'is_frozen', 'service_types',\n 'meta_population', 'record', 'requirement', 'vacancy', 'additional_info'\n ]\n )\n required_translated_fields = [\n 'name', 'description', 'focal_point_name', 'address']\n\n\n# class ServiceExcelSerializer(serializers.ModelSerializer):\n# location = serializers.SerializerMethodField(read_only=True)\n# region = serializers.RelatedField(read_only=True)\n\n# def get_location(self, obj):\n# return \",\".join([str(obj.location.y), str(obj.location.x)]) if obj.location else ''\n\n# FIELD_MAP = OrderedDict(\n# [\n# ('id', 'Identifier'),\n# ('provider', 'Provider'),\n# ('region', 'Region of Service'),\n# ('location', 'Coordinates'),\n# ('type', 'Type of Service'),\n# ('phone_number', 'Phone Number'),\n# ] +\n# [(\"name_{}\".format(k), \"Name in ({})\".format(v)) for k, v in settings.LANGUAGES] +\n# [(\"description_{}\".format(k), \"Description in ({})\".format(v)) for k, v in settings.LANGUAGES] +\n# [(\"address_{}\".format(k), \"Address in ({})\".format(v)) for k, v in settings.LANGUAGES]\n# # [\n# # ('sunday_open', 'Sunday Opening Hours (00:00:00)'),\n# # ('sunday_close', 'Sunday Closing Hours (00:00:00)'),\n# # ('monday_open', 'Monday Opening Hours (00:00:00)'),\n# # ('monday_close', 'Monday Closing Hours (00:00:00)'),\n# # ('tuesday_open', 'Tuesday Opening Hours (00:00:00)'),\n# # ('tuesday_close', 'Tuesday Closing Hours (00:00:00)'),\n# # ('wednesday_open', 'Wednesday Opening Hours (00:00:00)'),\n# # ('wednesday_close', 'Wednesday Closing Hours (00:00:00)'),\n# # ('thursday_open', 'Thursday Opening Hours (00:00:00)'),\n# # ('thursday_close', 'Thursday Closing Hours (00:00:00)'),\n# # ('friday_open', 'Friday Opening Hours (00:00:00)'),\n# # ('friday_close', 'Friday Closing Hours (00:00:00)'),\n# # ('saturday_open', 'Saturday Opening Hours (00:00:00)'),\n# # ('saturday_close', 'Sunday Closing Hours (00:00:00)'),\n# # ]\n# )\n\n# class Meta:\n# model = Service\n# fields = (\n# [\n# 'id',\n# 'provider',\n# 'region',\n# 'location',\n# # 'sunday_open',\n# # 'sunday_close',\n# # 'monday_open',\n# # 'monday_close',\n# # 'tuesday_open',\n# # 'tuesday_close',\n# # 'wednesday_open',\n# # 'wednesday_close',\n# # 'thursday_open',\n# # 'thursday_close',\n# # 'friday_open',\n# # 'friday_close',\n# # 'saturday_open',\n# # 'saturday_close',\n# 'type',\n# 'phone_number',\n# ] + generate_translated_fields('name') +\n# generate_translated_fields('description') +\n# generate_translated_fields('address') +\n# generate_translated_fields('additional_info') +\n# generate_translated_fields('languages_spoken')\n# )\n\nclass GeographicRegionCreateSerializer(serializers.ModelSerializer):\n class Meta:\n model = GeographicRegion\n fields = tuple(\n ['id', 'name', 'slug', 'code', 'hidden', 'level', 'geom', 'site', 'parent',\n 'languages_available'] +\n generate_translated_fields('title')\n )\n\n def create(self, validated_data): \n geom = None\n if validated_data['geom'] is not None:\n geom = validated_data['geom'].ewkt \n validated_data['geom'] = None \n region = GeographicRegion.objects.create(**validated_data)\n region.save()\n cursor = connections['default'].cursor()\n cursor.execute(\"update regions_geographicregion set geom = ST_GEOMFROMTEXT(%s, 4326) where id = %s ;\", [geom, region.id])\n return region\n \n\nclass GeographicRegionSerializer(serializers.ModelSerializer):\n parent__name = serializers.SerializerMethodField(read_only=True)\n centroid = serializers.SerializerMethodField(read_only=True)\n envelope = serializers.SerializerMethodField(read_only=True)\n\n def get_centroid(self, obj):\n return json.loads(obj.centroid.json)\n\n def get_envelope(self, obj):\n return json.loads(obj.geom.envelope.json)\n\n def get_parent__name(self, obj):\n return obj.parent.name if obj.parent else ''\n\n class Meta:\n model = GeographicRegion\n fields = tuple(\n ['id', 'name', 'slug', 'code', 'hidden', 'level', 'geom', 'site', 'centroid', 'envelope', 'parent',\n 'parent__name', 'languages_available'] +\n generate_translated_fields('title')\n )\n \nclass GeographicRegionSerializerNoGeometry(serializers.ModelSerializer):\n parent__name = serializers.SerializerMethodField(read_only=True) \n\n def get_parent__name(self, obj):\n return obj.parent.name if obj.parent else ''\n\n class Meta:\n model = GeographicRegion\n fields = tuple(\n ['id', 'name', 'slug', 'code', 'hidden', 'level', 'site', 'parent',\n 'parent__name', 'languages_available'] +\n generate_translated_fields('title')\n )\n\n\nclass UserPermissionSerializer(serializers.ModelSerializer):\n permissions = serializers.SerializerMethodField(required=False)\n\n def get_permissions(self, obj):\n return obj.get_all_permissions()\n\n class Meta:\n model = EmailUser\n fields = ('email', 'permissions')\n\n\nclass APIRegisterSerializer(serializers.Serializer):\n email = serializers.EmailField()\n name = serializers.CharField()\n surname = serializers.CharField()\n title = serializers.CharField(required=False)\n position = serializers.CharField(required=False)\n phone_number = serializers.CharField(required=False)\n groups = serializers.PrimaryKeyRelatedField(\n many=True, required=False, read_only=True)\n\n def validate(self, attrs):\n attrs = super().validate(attrs)\n User = get_user_model()\n user = User.objects.filter(email=attrs.get('email'))\n if user:\n raise exceptions.ValidationError(\n {'email': 'User with this email already exists'})\n return attrs\n","sub_path":"api/v2/serializers/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":14219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"371112712","text":"# coding = utf-8\n\nfrom urllib import request, parse\nfrom urllib.error import URLError\nimport json\nimport multiprocessing\nimport time\n\nNUM_SUCCESS = 0\n\n# def get_http(num):\n# global NUM_SUCCESS\n#\n# while num > 0:\n# url = 'http://10.33.2.61:8008/score/queryanswer/?examid=3003&paperid=PAPER-14777&itemid=4-1&studentid=217167569'\n# req = request.Request(url=url)\n# # print(req)\n#\n# res_data = request.urlopen(req)\n# # print(res_data)\n# res = res_data.read()\n# json_data = json.loads(res.decode('utf-8'))\n# print(json_data)\n# if json_data['code'] == 200:\n# NUM_SUCCESS += 1\n# print('NUM_SUCCESS', NUM_SUCCESS)\n# num -= 1\n\nresult = []\n\ndef get_http(num):\n\n global NUM_SUCCESS\n url = 'http://10.33.2.61:8008/score/queryanswer/?examid=3003&paperid=PAPER-14777&itemid=4-1&studentid=217167569'\n req = request.Request(url=url)\n # print(req)\n\n res_data = request.urlopen(req)\n # print(res_data)\n res = res_data.read()\n json_data = json.loads(res.decode('utf-8'))\n # print(json_data)\n if json_data['code'] == 200:\n NUM_SUCCESS += 1\n # print(num)\n return num\n # print('NUM_SUCCESS', NUM_SUCCESS)\n\n\nif __name__ == \"__main__\":\n cpu_count = multiprocessing.cpu_count()\n t0 = time.time()\n # p = multiprocessing.Process(target = get_http, args = (10,))\n # p.start()\n # print(\"p.pid:\", p.pid)\n # print(\"p.name:\", p.name)\n # print(\"p.is_alive:\", p.is_alive())\n #\n # p.join()\n # print('end')\n\n pool = multiprocessing.Pool(processes=cpu_count)\n for i in range(10000):\n result.append(pool.apply_async(get_http,(i,))) # 维持执行的进程总数为processes,当一个进程执行完毕后会添加新的进程进去\n\n print(\"Mark~ Mark~ Mark~~~~~~~~~~~~~~~~~~~~~~\")\n pool.close()\n pool.join() # 调用join之前,先调用close函数,否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束\n t1 = time.time()\n print('time sp', (t1-t0,))\n print(\"Sub-process(es) done.\")\n # print('NUM_SUCCESS', NUM_SUCCESS)\n\n print('length', len(result))\n","sub_path":"tensor__cpu/http/tesst_concurrency.py","file_name":"tesst_concurrency.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"593466368","text":"# Copyright 2018 The Bazel 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\ndef _tree_artifact_rule_impl(ctx):\n output_directory = ctx.actions.declare_directory(\n \"{}.outputs/long/list/of/paths\".format(ctx.label.name),\n )\n\n another_output_directory = ctx.actions.declare_directory(\n \"{}.another_outputs/other/path/list\".format(ctx.label.name),\n )\n\n ctx.actions.run(\n outputs = [output_directory],\n executable = \"touch\",\n arguments = [\n ## This output succeeds, as bazel creates the output directory somehow.\n \"{}/output_file\".format(output_directory.path),\n\n # This next output fails, because touch can't create an intermediate directory.\n # \"{}/output_dir/another_file\".format(output_directory.path),\n ],\n )\n\n # This action literally does nothing, but the output directory gets created anyways.\n ctx.actions.run(\n outputs = [another_output_directory],\n executable = \"true\",\n )\n\n return [DefaultInfo(\n files = depset([output_directory, another_output_directory])\n )]\n\ntree_artifact_rule = rule(\n implementation = _tree_artifact_rule_impl,\n)","sub_path":"tree_artifact_rule.bzl","file_name":"tree_artifact_rule.bzl","file_ext":"bzl","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"570708997","text":"import logging\nfrom typing import Any, Dict, List, Text, Tuple, Optional\n\nfrom rasa.core.utils import get_dict_hash\nfrom rasa.nlu.model import Metadata\nfrom rasa.nlu.tokenizers.whitespace_tokenizer import WhitespaceTokenizer\nfrom rasa.nlu.components import Component\nfrom rasa.nlu.config import RasaNLUModelConfig\nfrom rasa.nlu.training_data import Message, TrainingData\nfrom rasa.nlu.tokenizers.tokenizer import Token\nimport rasa.utils.train_utils as train_utils\nimport numpy as np\n\nfrom rasa.nlu.constants import (\n TEXT,\n LANGUAGE_MODEL_DOCS,\n DENSE_FEATURIZABLE_ATTRIBUTES,\n TOKEN_IDS,\n TOKENS,\n SENTENCE_FEATURES,\n SEQUENCE_FEATURES,\n NUMBER_OF_SUB_TOKENS,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass HFTransformersNLP(Component):\n \"\"\"Utility Component for interfacing between Transformers library and Rasa OS.\n\n The transformers(https://github.com/huggingface/transformers) library\n is used to load pre-trained language models like BERT, GPT-2, etc.\n The component also tokenizes and featurizes dense featurizable attributes of each\n message.\n \"\"\"\n\n defaults = {\n # name of the language model to load.\n \"model_name\": \"bert\",\n # Pre-Trained weights to be loaded(string)\n \"model_weights\": None,\n # an optional path to a specific directory to download\n # and cache the pre-trained model weights.\n \"cache_dir\": None,\n }\n\n def __init__(self, component_config: Optional[Dict[Text, Any]] = None) -> None:\n super(HFTransformersNLP, self).__init__(component_config)\n\n self._load_model()\n self.whitespace_tokenizer = WhitespaceTokenizer()\n\n def _load_model(self) -> None:\n \"\"\"Try loading the model\"\"\"\n\n from rasa.nlu.utils.hugging_face.registry import (\n model_class_dict,\n model_weights_defaults,\n model_tokenizer_dict,\n )\n\n self.model_name = self.component_config[\"model_name\"]\n\n if self.model_name not in model_class_dict:\n raise KeyError(\n f\"'{self.model_name}' not a valid model name. Choose from \"\n f\"{str(list(model_class_dict.keys()))}or create\"\n f\"a new class inheriting from this class to support your model.\"\n )\n\n self.model_weights = self.component_config[\"model_weights\"]\n self.cache_dir = self.component_config[\"cache_dir\"]\n\n if not self.model_weights:\n logger.info(\n f\"Model weights not specified. Will choose default model weights: \"\n f\"{model_weights_defaults[self.model_name]}\"\n )\n self.model_weights = model_weights_defaults[self.model_name]\n\n logger.debug(f\"Loading Tokenizer and Model for {self.model_name}\")\n\n self.tokenizer = model_tokenizer_dict[self.model_name].from_pretrained(\n self.model_weights, cache_dir=self.cache_dir\n )\n self.model = model_class_dict[self.model_name].from_pretrained(\n self.model_weights, cache_dir=self.cache_dir\n )\n\n # Use a universal pad token since all transformer architectures do not have a\n # consistent token. Instead of pad_token_id we use unk_token_id because\n # pad_token_id is not set for all architectures. We can't add a new token as\n # well since vocabulary resizing is not yet supported for TF classes.\n # Also, this does not hurt the model predictions since we use an attention mask\n # while feeding input.\n self.pad_token_id = self.tokenizer.unk_token_id\n\n @classmethod\n def cache_key(\n cls, component_meta: Dict[Text, Any], model_metadata: Metadata\n ) -> Optional[Text]:\n\n weights = component_meta.get(\"model_weights\") or {}\n\n return f\"{cls.name}-{component_meta.get('model_name')}-{get_dict_hash(weights)}\"\n\n @classmethod\n def required_packages(cls) -> List[Text]:\n return [\"transformers\"]\n\n def _lm_tokenize(self, text: Text) -> Tuple[List[int], List[Text]]:\n \"\"\"\n Pass the text through the tokenizer of the language model.\n\n Args:\n text: Text to be tokenized.\n\n Returns:\n List of token ids and token strings.\n\n \"\"\"\n split_token_ids = self.tokenizer.encode(text, add_special_tokens=False)\n\n split_token_strings = self.tokenizer.convert_ids_to_tokens(split_token_ids)\n\n return split_token_ids, split_token_strings\n\n def _add_lm_specific_special_tokens(\n self, token_ids: List[List[int]]\n ) -> List[List[int]]:\n \"\"\"Add language model specific special tokens which were used during their\n training.\n\n Args:\n token_ids: List of token ids for each example in the batch.\n\n Returns:\n Augmented list of token ids for each example in the batch.\n \"\"\"\n from rasa.nlu.utils.hugging_face.registry import (\n model_special_tokens_pre_processors,\n )\n\n augmented_tokens = [\n model_special_tokens_pre_processors[self.model_name](example_token_ids)\n for example_token_ids in token_ids\n ]\n return augmented_tokens\n\n def _lm_specific_token_cleanup(\n self, split_token_ids: List[int], token_strings: List[Text]\n ) -> Tuple[List[int], List[Text]]:\n \"\"\"Clean up special chars added by tokenizers of language models.\n\n Many language models add a special char in front/back of (some) words. We clean\n up those chars as they are not\n needed once the features are already computed.\n\n Args:\n split_token_ids: List of token ids received as output from the language\n model specific tokenizer.\n token_strings: List of token strings received as output from the language\n model specific tokenizer.\n\n Returns:\n Cleaned up token ids and token strings.\n \"\"\"\n from rasa.nlu.utils.hugging_face.registry import model_tokens_cleaners\n\n return model_tokens_cleaners[self.model_name](split_token_ids, token_strings)\n\n def _post_process_sequence_embeddings(\n self, sequence_embeddings: np.ndarray\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Compute sentence level representations and sequence level representations\n for relevant tokens.\n\n Args:\n sequence_embeddings: Sequence level dense features received as output from\n language model.\n\n Returns:\n Sentence and sequence level representations.\n \"\"\"\n\n from rasa.nlu.utils.hugging_face.registry import (\n model_embeddings_post_processors,\n )\n\n sentence_embeddings = []\n post_processed_sequence_embeddings = []\n\n for example_embedding in sequence_embeddings:\n (\n example_sentence_embedding,\n example_post_processed_embedding,\n ) = model_embeddings_post_processors[self.model_name](example_embedding)\n\n sentence_embeddings.append(example_sentence_embedding)\n post_processed_sequence_embeddings.append(example_post_processed_embedding)\n\n return (\n np.array(sentence_embeddings),\n np.array(post_processed_sequence_embeddings),\n )\n\n def _tokenize_example(\n self, message: Message, attribute: Text\n ) -> Tuple[List[Token], List[int]]:\n \"\"\"Tokenize a single message example.\n\n Many language models add a special char in front of (some) words and split\n words into sub-words. To ensure the entity start and end values matches the\n token values, tokenize the text first using the whitespace tokenizer. If\n individual tokens are split up into multiple tokens, we add this information\n to the respected token.\n\n Args:\n message: Single message object to be processed.\n attribute: Property of message to be processed, one of ``TEXT`` or\n ``RESPONSE``.\n\n Returns:\n List of token strings and token ids for the corresponding attribute of the\n message.\n \"\"\"\n\n tokens_in = self.whitespace_tokenizer.tokenize(message, attribute)\n\n tokens_out = []\n\n token_ids_out = []\n\n for token in tokens_in:\n # use lm specific tokenizer to further tokenize the text\n split_token_ids, split_token_strings = self._lm_tokenize(token.text)\n\n split_token_ids, split_token_strings = self._lm_specific_token_cleanup(\n split_token_ids, split_token_strings\n )\n\n token_ids_out += split_token_ids\n\n token.set(NUMBER_OF_SUB_TOKENS, len(split_token_strings))\n\n tokens_out.append(token)\n\n return tokens_out, token_ids_out\n\n def _get_token_ids_for_batch(\n self, batch_examples: List[Message], attribute: Text\n ) -> Tuple[List[List[Token]], List[List[int]]]:\n \"\"\"Compute token ids and token strings for each example in batch.\n\n A token id is the id of that token in the vocabulary of the language model.\n Args:\n batch_examples: Batch of message objects for which tokens need to be\n computed.\n attribute: Property of message to be processed, one of ``TEXT`` or\n ``RESPONSE``.\n\n Returns:\n List of token strings and token ids for each example in the batch.\n \"\"\"\n\n batch_token_ids = []\n batch_tokens = []\n for example in batch_examples:\n\n example_tokens, example_token_ids = self._tokenize_example(\n example, attribute\n )\n batch_tokens.append(example_tokens)\n batch_token_ids.append(example_token_ids)\n\n return batch_tokens, batch_token_ids\n\n @staticmethod\n def _compute_attention_mask(actual_sequence_lengths: List[int]) -> np.ndarray:\n \"\"\"Compute a mask for padding tokens.\n\n This mask will be used by the language model so that it does not attend to\n padding tokens.\n\n Args:\n actual_sequence_lengths: List of length of each example without any padding\n\n Returns:\n Computed attention mask, 0 for padding and 1 for non-padding tokens.\n \"\"\"\n\n attention_mask = []\n max_seq_length = max(actual_sequence_lengths)\n for actual_sequence_length in actual_sequence_lengths:\n # add 1s for present tokens, fill up the remaining space up to max\n # sequence length with 0s (non-existing tokens)\n padded_sequence = [1] * actual_sequence_length + [0] * (\n max_seq_length - actual_sequence_length\n )\n attention_mask.append(padded_sequence)\n\n attention_mask = np.array(attention_mask).astype(np.float32)\n\n return attention_mask\n\n def _add_padding_to_batch(\n self, batch_token_ids: List[List[int]]\n ) -> Tuple[List[int], List[List[int]]]:\n \"\"\"Add padding so that all examples in the batch are of the same length.\n\n Args:\n batch_token_ids: Batch of examples where each example is a non-padded list\n of token ids.\n\n Returns:\n Padded batch with all examples of the same length.\n \"\"\"\n padded_token_ids = []\n # Compute max length across examples\n max_seq_len = 0\n actual_sequence_lengths = []\n\n for example_token_ids in batch_token_ids:\n actual_sequence_lengths.append(len(example_token_ids))\n max_seq_len = max(max_seq_len, len(example_token_ids))\n\n # Add padding according to max_seq_len\n # Some models don't contain pad token, we use unknown token as padding token.\n # This doesn't affect the computation since we compute an attention mask\n # anyways.\n for example_token_ids in batch_token_ids:\n padded_token_ids.append(\n example_token_ids\n + [self.pad_token_id] * (max_seq_len - len(example_token_ids))\n )\n return actual_sequence_lengths, padded_token_ids\n\n @staticmethod\n def _extract_nonpadded_embeddings(\n embeddings: np.ndarray, actual_sequence_lengths: List[int]\n ) -> np.ndarray:\n \"\"\"Use pre-computed non-padded lengths of each example to extract embeddings\n for non-padding tokens.\n\n Args:\n embeddings: sequence level representations for each example of the batch.\n actual_sequence_lengths: non-padded lengths of each example of the batch.\n\n Returns:\n Sequence level embeddings for only non-padding tokens of the batch.\n \"\"\"\n nonpadded_sequence_embeddings = []\n for index, embedding in enumerate(embeddings):\n unmasked_embedding = embedding[: actual_sequence_lengths[index]]\n nonpadded_sequence_embeddings.append(unmasked_embedding)\n\n return np.array(nonpadded_sequence_embeddings)\n\n def _compute_batch_sequence_features(\n self, batch_attention_mask: np.ndarray, padded_token_ids: List[List[int]]\n ) -> np.ndarray:\n \"\"\"Feed the padded batch to the language model.\n\n Args:\n batch_attention_mask: Mask of 0s and 1s which indicate whether the token\n is a padding token or not.\n padded_token_ids: Batch of token ids for each example. The batch is padded\n and hence can be fed at once.\n\n Returns:\n Sequence level representations from the language model.\n \"\"\"\n model_outputs = self.model(\n np.array(padded_token_ids), attention_mask=np.array(batch_attention_mask)\n )\n\n # sequence hidden states is always the first output from all models\n sequence_hidden_states = model_outputs[0]\n\n sequence_hidden_states = sequence_hidden_states.numpy()\n return sequence_hidden_states\n\n def _get_model_features_for_batch(\n self, batch_token_ids: List[List[int]], batch_tokens: List[List[Token]]\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Compute dense features of each example in the batch.\n\n We first add the special tokens corresponding to each language model. Next, we\n add appropriate padding and compute a mask for that padding so that it doesn't\n affect the feature computation. The padded batch is next fed to the language\n model and token level embeddings are computed. Using the pre-computed mask,\n embeddings for non-padding tokens are extracted and subsequently sentence\n level embeddings are computed.\n\n Args:\n batch_token_ids: List of token ids of each example in the batch.\n\n Returns:\n Sentence and token level dense representations.\n \"\"\"\n # Let's first add tokenizer specific special tokens to all examples\n batch_token_ids_augmented = self._add_lm_specific_special_tokens(\n batch_token_ids\n )\n\n # Let's first add padding so that whole batch can be fed to the model\n actual_sequence_lengths, padded_token_ids = self._add_padding_to_batch(\n batch_token_ids_augmented\n )\n\n # Compute attention mask based on actual_sequence_length\n batch_attention_mask = self._compute_attention_mask(actual_sequence_lengths)\n\n # Get token level features from the model\n sequence_hidden_states = self._compute_batch_sequence_features(\n batch_attention_mask, padded_token_ids\n )\n\n # Extract features for only non-padding tokens\n sequence_nonpadded_embeddings = self._extract_nonpadded_embeddings(\n sequence_hidden_states, actual_sequence_lengths\n )\n\n # Extract sentence level and post-processed features\n (\n sentence_embeddings,\n sequence_embeddings,\n ) = self._post_process_sequence_embeddings(sequence_nonpadded_embeddings)\n\n # shape of matrix for all sequence embeddings\n batch_dim = len(sequence_embeddings)\n seq_dim = max(e.shape[0] for e in sequence_embeddings)\n feature_dim = sequence_embeddings[0].shape[1]\n shape = (batch_dim, seq_dim, feature_dim)\n\n # align features with tokens so that we have just one vector per token\n # (don't include sub-tokens)\n sequence_embeddings = train_utils.align_token_features(\n batch_tokens, sequence_embeddings, shape\n )\n\n # sequence_embeddings is a padded numpy array\n # remove the padding, keep just the non-zero vectors\n sequence_final_embeddings = []\n for embeddings, tokens in zip(sequence_embeddings, batch_tokens):\n sequence_final_embeddings.append(embeddings[: len(tokens)])\n sequence_final_embeddings = np.array(sequence_final_embeddings)\n\n return sentence_embeddings, sequence_final_embeddings\n\n def _get_docs_for_batch(\n self, batch_examples: List[Message], attribute: Text\n ) -> List[Dict[Text, Any]]:\n \"\"\"Compute language model docs for all examples in the batch.\n\n Args:\n batch_examples: Batch of message objects for which language model docs\n need to be computed.\n attribute: Property of message to be processed, one of ``TEXT`` or\n ``RESPONSE``.\n\n Returns:\n List of language model docs for each message in batch.\n \"\"\"\n\n batch_tokens, batch_token_ids = self._get_token_ids_for_batch(\n batch_examples, attribute\n )\n\n (\n batch_sentence_features,\n batch_sequence_features,\n ) = self._get_model_features_for_batch(batch_token_ids, batch_tokens)\n\n # A doc consists of\n # {'token_ids': ..., 'tokens': ..., 'sequence_features': ...,\n # 'sentence_features': ...}\n batch_docs = []\n for index in range(len(batch_examples)):\n doc = {\n TOKEN_IDS: batch_token_ids[index],\n TOKENS: batch_tokens[index],\n SEQUENCE_FEATURES: batch_sequence_features[index],\n SENTENCE_FEATURES: np.reshape(batch_sentence_features[index], (1, -1)),\n }\n batch_docs.append(doc)\n\n return batch_docs\n\n def train(\n self,\n training_data: TrainingData,\n config: Optional[RasaNLUModelConfig] = None,\n **kwargs: Any,\n ) -> None:\n \"\"\"Compute tokens and dense features for each message in training data.\n\n Args:\n training_data: NLU training data to be tokenized and featurized\n config: NLU pipeline config consisting of all components.\n\n \"\"\"\n\n batch_size = 64\n\n for attribute in DENSE_FEATURIZABLE_ATTRIBUTES:\n\n non_empty_examples = list(\n filter(lambda x: x.get(attribute), training_data.training_examples)\n )\n\n batch_start_index = 0\n\n while batch_start_index < len(non_empty_examples):\n\n batch_end_index = min(\n batch_start_index + batch_size, len(non_empty_examples)\n )\n # Collect batch examples\n batch_messages = non_empty_examples[batch_start_index:batch_end_index]\n\n # Construct a doc with relevant features\n # extracted(tokens, dense_features)\n batch_docs = self._get_docs_for_batch(batch_messages, attribute)\n\n for index, ex in enumerate(batch_messages):\n\n ex.set(LANGUAGE_MODEL_DOCS[attribute], batch_docs[index])\n\n batch_start_index += batch_size\n\n def process(self, message: Message, **kwargs: Any) -> None:\n \"\"\"Process an incoming message by computing its tokens and dense features.\n\n Args:\n message: Incoming message object\n \"\"\"\n\n message.set(\n LANGUAGE_MODEL_DOCS[TEXT],\n self._get_docs_for_batch([message], attribute=TEXT)[0],\n )\n","sub_path":"rasa/nlu/utils/hugging_face/hf_transformers.py","file_name":"hf_transformers.py","file_ext":"py","file_size_in_byte":19941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"526424992","text":"import numpy as np\n\ndef parse(line): # parse: \"1 @ 1,3: 4x4\" into integers: 1 1 3 4 4\n at_index = line.find(\"@\")\n colon_index = line.find(\":\")\n comma_index = line.find(\",\")\n x_index = line.find(\"x\")\n \n claim_number = int(line[1:at_index-1])\n x_offset = int(line[at_index+2:comma_index])\n y_offset = int(line[comma_index+1:colon_index])\n x_size = int(line[colon_index+2:x_index])\n y_size = int(line[x_index+1:])\n\n return claim_number,x_offset,y_offset,x_size,y_size\n\ndef count_marked (grid):\n counter = 0\n for x in range(grid.shape[0]):\n for y in range(grid.shape[1]):\n if grid[x,y]==-1:\n counter+=1\n return counter\n\nif __name__ == \"__main__\":\n file = open(\"input2.txt\",\"r\")\n string = file.read() \n #string = \"#1 @ 1,3: 4x4\\n#2 @ 3,1: 4x4\\n#3 @ 5,5: 2x2\"\n list = string.split(\"\\n\")\n grid = np.zeros((1100,11000))\n print(\"First run:\") \n for line in list: #for each claim: marks all cells a claim mentions. if marked again it will assign -1.\n claim_number,x_offset,y_offset,x_size,y_size = parse (line)\n for x in range(x_size):\n for y in range(y_size):\n val = grid[x_offset+x,y_offset+y]\n if val==0 :\n grid[x_offset+x,y_offset+y] = claim_number\n else:\n grid[x_offset+x,y_offset+y] = -1\n valid = 0\n print(\"Counter: \" + str(count_marked(grid)))\n print(\"Second run:\") \n for line in list: #checks in the grid if a claim mentions only cells that are marked by himself.\n valid = 1\n claim_number,x_offset,y_offset,x_size,y_size = parse (line)\n for x in range(x_size):\n for y in range(y_size):\n val = grid[x_offset+x,y_offset+y]\n if val==claim_number:\n continue\n else: \n valid = 0\n if valid==1:\n print(str(claim_number) + \" is the valid claim!\") \n ","sub_path":"Day3/day3_puzzle1and2.py","file_name":"day3_puzzle1and2.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"51365945","text":"from src.api.soundcloud_uploader import SoundcloudSession\nfrom .tabmanager import TabManager\nfrom .settingsmanager import SettingsManager\nfrom .settingswindow import SettingsWindow\nfrom PyQt5.QtWidgets import (QWidget, QMainWindow, QVBoxLayout, QGridLayout, QLabel, QLineEdit, QTextEdit,\n QRadioButton, QComboBox, QPushButton, QInputDialog, QMessageBox, QTabWidget, QCheckBox)\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.soundcloud_data = {\n \"song_path\": None,\n \"cover_path\": None,\n \"soundcloud_pwd\": None\n }\n self.youtube_data = {\n \"song_path\": None,\n \"cover_path\": None,\n }\n self.init_ui()\n\n def init_ui(self):\n self.setCentralWidget(QWidget(self))\n self.setFixedSize(340, 480)\n self.setWindowTitle('PhantomCloud')\n\n # Menu\n self.menu = self.menuBar()\n self.file_menu = self.menu.addMenu('File')\n self.action_settings = self.file_menu.addAction('Settings')\n self.action_settings.triggered.connect(SettingsWindow)\n\n\n\n self.box_layout = QVBoxLayout(self)\n self.tabs = QTabWidget()\n self.tabs.addTab(self.soundcloud_tab(), 'SoundCloud')\n self.tabs.addTab(self.youtube_tab(), 'YouTube')\n self.tabs.addTab(self.upload_tab(), 'Upload')\n self.box_layout.addWidget(self.tabs)\n self.centralWidget().setLayout(self.box_layout)\n\n self.show()\n \n def soundcloud_tab(self):\n tab_widget = QWidget()\n\n title = QLabel('Title')\n permalink = QLabel('Permalink')\n description = QLabel('Description')\n genre_label = QLabel('Genre')\n tags = QLabel('Tags (Separate each tag with spaces)')\n privacy = QLabel('Privacy')\n downloadable = QLabel('Downloadable')\n\n song = QLabel(\"Song: No file selected\")\n song_btn = QPushButton(\"Choose an audio\")\n song_btn.clicked.connect(lambda: TabManager.get_song_path(self.youtube_data, song))\n\n cover = QLabel(\"Cover: No file selected\")\n cover_btn = QPushButton(\"Choose an image\")\n cover_btn.clicked.connect(lambda: TabManager.get_cover_path(self.soundcloud_data, cover))\n\n title_input = QLineEdit()\n permalink_input = QLineEdit()\n description_input = QTextEdit()\n # List of predefined music genres on SoundCloud\n genres = ['None', 'Custom', 'Alternative Rock', 'Ambient', 'Classical', 'Country',\n 'Dance & EDM', 'Dancehall', 'Deep House', 'Disco', 'Drum & Bass', 'Dubstep',\n 'Electronic', 'Folk & Singer-Songwriter', 'Hip-hop & Rap', 'House', 'Indie', 'Jazz & Blues',\n 'Latin', 'Metal', 'Piano', 'Pop', 'R&B & Soul', 'Reggae',\n 'Reggaeton', 'Rock', 'Soundtrack', 'Techno', 'Trance', 'Trap',\n 'Triphop', 'World']\n\n genre_combobox = QComboBox()\n genre_combobox.addItems(genres)\n genre_combobox.activated[str].connect(lambda: TabManager.show_custom_genre(genre_combobox, self.grid, self.custom_genre_input))\n\n self.custom_genre_input = QLineEdit()\n tags_input = QLineEdit()\n privacy_option_1 = QRadioButton('Public')\n privacy_option_1.setChecked(True)\n privacy_option_2 = QRadioButton('Private')\n\n self.grid = QGridLayout()\n self.grid.addWidget(song, 0, 0)\n self.grid.addWidget(song_btn, 0, 1, 1, 3)\n self.grid.addWidget(cover, 1, 0)\n self.grid.addWidget(cover_btn, 1, 1, 1, 3)\n self.grid.addWidget(title, 2, 0)\n self.grid.addWidget(title_input, 3, 0, 1, 0)\n self.grid.addWidget(permalink, 4, 0)\n self.grid.addWidget(permalink_input, 5, 0)\n self.grid.addWidget(description, 6, 0)\n self.grid.addWidget(description_input, 7, 0, 1, 0)\n self.grid.addWidget(genre_label, 8, 0)\n self.grid.addWidget(genre_combobox, 9, 0)\n self.grid.addWidget(tags, 10, 0)\n self.grid.addWidget(tags_input, 11, 0, 1, 0)\n self.grid.addWidget(privacy, 12, 0)\n self.grid.addWidget(privacy_option_1, 13, 0)\n self.grid.addWidget(privacy_option_2, 14, 0)\n tab_widget.setLayout(self.grid)\n\n return tab_widget\n\n def youtube_tab(self):\n tab_widget = QWidget()\n\n song_label = QLabel(\"Song: No file selected\")\n cover_label = QLabel(\"Cover: No file selected\")\n title_label = QLabel('Title')\n description_label = QLabel('Description')\n genre_label = QLabel('Genre')\n keywords_label = QLabel('Tags (Separate each tag with commas)')\n privacy_label = QLabel('Privacy')\n\n song_btn = QPushButton(\"Choose an audio\")\n song_btn.clicked.connect(lambda: TabManager.get_song_path(self.youtube_data, song_label))\n cover_btn = QPushButton(\"Choose an image\")\n cover_btn.clicked.connect(lambda: TabManager.get_cover_path(self.youtube_data, cover_label))\n\n title_input = QLineEdit()\n permalink_input = QLineEdit()\n description_input = QTextEdit()\n\n genres = ['Film & Animation', 'Autos & Vehicles', 'Music',\n 'Pets & Animals', 'Sports', 'Travel & Events',\n 'Gaming', 'People & Blogs', 'Comedy',\n 'Entertainment', 'News & Politics', 'Howto & Style',\n 'Education', 'Science & Technology', 'Nonprofits & Activism']\n genre_combobox = QComboBox()\n genre_combobox.addItems(genres)\n\n keywords_input = QLineEdit()\n privacy_option_1 = QRadioButton('Public')\n privacy_option_1.setChecked(True)\n privacy_option_2 = QRadioButton('Private')\n privacy_option_3 = QRadioButton('Unlisted')\n\n grid = QGridLayout()\n grid.addWidget(song_label, 0, 0)\n grid.addWidget(song_btn, 0, 1, 1, 3)\n grid.addWidget(cover_label, 1, 0)\n grid.addWidget(cover_btn, 1, 1, 1, 3)\n grid.addWidget(title_label, 2, 0)\n grid.addWidget(title_input, 3, 0, 1, 0)\n grid.addWidget(description_label, 4, 0)\n grid.addWidget(description_input, 5, 0, 1, 0)\n grid.addWidget(genre_label, 7, 0)\n grid.addWidget(genre_combobox, 8, 0)\n grid.addWidget(keywords_label, 9, 0)\n grid.addWidget(keywords_input, 10, 0, 1, 0)\n grid.addWidget(privacy_label, 11, 0)\n grid.addWidget(privacy_option_1, 12, 0)\n grid.addWidget(privacy_option_2, 13, 0)\n grid.addWidget(privacy_option_3, 14, 0)\n tab_widget.setLayout(grid)\n\n return tab_widget\n\n def upload_tab(self):\n tab_widget = QWidget()\n\n upload_soundcloud = QCheckBox(\"Upload on SoundCloud\")\n upload_youtube = QCheckBox(\"Upload on YouTube\")\n upload_btn = QPushButton('Upload', self)\n upload_btn.clicked.connect(self.soundcloud_password)\n\n grid = QGridLayout()\n grid.addWidget(upload_soundcloud, 0, 0)\n grid.addWidget(upload_youtube, 0, 1)\n grid.addWidget(upload_btn, 1, 0, 1, 3)\n tab_widget.setLayout(grid)\n return tab_widget\n\n def soundcloud_password(self):\n soundcloud_pwd, ok = QInputDialog.getText(self, 'SoundCloud Password', 'Password')\n if ok:\n self.soundcloud_upload(soundcloud_pwd)\n\n def soundcloud_upload(self, soundcloud_password):\n # Check if a cover art or an audio is selected\n if self.soundcloud_data['song_path'] is None:\n return QMessageBox.warning(self, 'Error', 'No audio has been selected.')\n elif self.soundcloud_data['cover_path'] is None:\n return QMessageBox.warning(self, 'Error', 'No image has been selected.')\n\n settings = SettingsManager().load_settings()\n\n session = SoundcloudSession(settings['soundcloud']['username'],\n soundcloud_password,\n settings['soundcloud']['signature'],\n settings['soundcloud']['client_id'])\n\n tags = self.tags_input.text().split(\" \")\n if self.genre_combobox.currentText() == 'Custom':\n genre = self.custom_genre_input.text()\n else:\n genre = self.genre_combobox.currentText()\n\n session.upload_file(file_location=self.soundcloud_data['song_path'],\n img_location=self.soundcloud_data['cover_path'],\n title=self.title_input.text(),\n description=self.description_input.toPlainText(),\n genre=genre,\n permalink=self.permalink_input.text(),\n tags=tags,\n public=True)\n","sub_path":"src/gui/mainwindow.py","file_name":"mainwindow.py","file_ext":"py","file_size_in_byte":8731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"386322188","text":"import math\n\n# Working solution for part 1\n'''def calculate_fuel(list_of_mass):\n list_of_fuel = []\n\n for i in range(len(list_of_mass)):\n list_of_fuel.append((math.floor(list_of_mass[i] / 3))-2)\n\n return sum(list_of_fuel)\n'''\n\n\n# Simply calculates the fuel required for a certain mass\ndef calculate_fuel(mass):\n return (math.floor(mass / 3)) - 2\n\n\n# Takes an initial mass and finds out how much fuel is required for that mass and then finds out how much fuel is\n# required for the new fuel and so on, adding it all together\ndef calculate_fuel_fuel(initial_mass):\n\n mass_of_fuel = initial_mass\n\n total_fuel = 0\n\n # Checks that the required fuel for the fuel that is being added is greater than 0\n while calculate_fuel(mass_of_fuel) > 0:\n # Finds out how much fuel is needed to add this fuel\n fuel_to_add = calculate_fuel(mass_of_fuel)\n # The added fuel is added to the total\n total_fuel += fuel_to_add\n # The mass of the fuel just added is used to calculate how much additional fuel is now needed\n mass_of_fuel = fuel_to_add\n return total_fuel\n\n\n# The file is opened read only\nfile = open(\"input\", \"r\")\n\n# Lists initialised\ninput_values = []\ntotal_fuel_required = []\n\n# File is read and input values added to a list\nfor i in file:\n input_values.append(int(i))\n\nfile.close()\n\n# For each module mass, calculate the required fuel for the module and the required fuel for the required fuel...\nfor j in range(len(input_values)):\n total_fuel_required.append(calculate_fuel_fuel((input_values[j])))\n\nprint(\"Total Fuel:\", sum(total_fuel_required))\n","sub_path":"Day1/Day1.py","file_name":"Day1.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"41604590","text":"#!/usr/bin/env python\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\nimport pyfits\nimport argparse\nfrom scipy.optimize import leastsq\nfrom scipy.optimize import minimize\nfrom scipy.special import erf\n\n\ndef GetOpts():\n parser = argparse.ArgumentParser()\n parser.add_argument( \"-t\", \"--tile\", help=\"Tilename\", type=str, required=True)\n parser.add_argument( \"-b\", \"--band\", help=\"Filter band\", type=str, required=True)\n parser.add_argument( \"-l\", \"--label\", help=\"Name of output catalog\", type=str, default='blend')\n parser.add_argument( \"-i\", \"--index\", help=\"index of vector_assoc for 'index'\", type=int, default=0)\n #parser.add_argument( \"-z\", \"--zeropoint\", help=\"Zeropoint\", type=float, default=30)\n args = parser.parse_args()\n\n args.balrogfile = os.path.join(os.environ['BALROG_ANALYSIS'], 'cats', args.label, '%s_%s_balrogcat.fits' %(args.tile, args.band))\n args.nosimfile = os.path.join(os.environ['BALROG_ANALYSIS'], 'cats', args.label, '%s_%s_nosimbalrogcat.fits' %(args.tile, args.band))\n args.truthfile = os.path.join(os.environ['BALROG_ANALYSIS'], 'cats', args.label, '%s_%s_truthcat.fits' %(args.tile, args.band))\n \n return args\n\n\ndef CompPlot(bdata, tdata, tdel, ndata, zeropoint, args, color, label, error=False):\n '''\n lcut = (bdata['FLUX_AUTO'] / bdata['FLUXERR_AUTO'] > 10.0)\n ldata = bdata[lcut]\n lim = np.amax(ldata['MAG_AUTO'])\n print lim\n '''\n\n bcut = (bdata['FLUX_AUTO'] / bdata['FLUXERR_AUTO'] > 5.0)\n bdata = bdata[bcut]\n\n bindex = bdata['VECTOR_ASSOC'][:, args.index]\n step = 0.1\n bins = np.arange(20.0, 24.05, step=step)\n centers = bins[:-1] + step/2.0\n tfound = np.zeros(len(centers))\n bfound = np.zeros(len(centers))\n comp = np.zeros(len(centers))\n err = np.zeros(len(centers))\n\n td = np.delete(tdata, tdel)\n\n for i in range(len(bins[:-1])):\n left = bins[i]\n right = bins[i+1]\n \n mag = zeropoint - 2.5*np.log10( td['flux_0'] )\n cut = (mag > left) & (mag <= right)\n tfound[i] = len(td[cut])\n tindex = td[cut]['index']\n\n match = np.intersect1d(tindex, bindex)\n bfound[i] = len(match)\n comp[i] = bfound[i] / tfound[i]\n err[i]= np.sqrt(bfound[i]) / tfound[i]\n\n if error:\n plt.errorbar(centers, comp, yerr=err, fmt='o', markersize=3, color=color, label=label)\n else:\n plt.scatter(centers, comp, lw=0, color=color, label=label)\n\n return comp, err, centers\n\ndef model(param, x):\n eff = param[0]\n m50 = param[1]\n w = param[2]\n model = (eff/2.0) * (1.0 - erf((x-m50)/np.sqrt(2.0*w)))\n return model\n\ndef residual(param, data, x, err):\n m = model(param, x)\n return (data - m) / err\n #return np.abs( np.sum( (data - m) / err ) )\n\n\ndef RemoveDuplicate(tocheck, also, tdata, tdel, args, truthcut=False):\n index1 = np.int64( tocheck['VECTOR_ASSOC'][:, args.index] )\n index2 = np.int64( also['VECTOR_ASSOC'][:, args.index] )\n\n sorted = np.sort(index1)\n badd = ( np.diff(sorted)==0 )\n badi = sorted[1:][badd]\n one1d = np.in1d(index1, badi)\n tocheck = tocheck[-one1d]\n two1d = np.in1d(index2, badi)\n also = bdata[-two1d]\n if truthcut:\n #np.delete(tdata, badi, axis=0) \n tdel = np.append(tdel, badi)\n\n return tocheck, also, tdel\n\n\ndef NosimCut(ndata, bdata, tdata, zeropoint, args):\n nindex = np.int64( ndata['VECTOR_ASSOC'][:, args.index] )\n bindex = np.int64( bdata['VECTOR_ASSOC'][:, args.index] )\n \n b1d = np.in1d(bindex, nindex)\n unblend = (bdata['FLAGS'] == 0) | (bdata['FLAGS'] > 3)\n blendcut = (b1d) & (unblend)\n bind = bindex[blendcut]\n\n n1d = np.in1d(nindex, bind)\n nind = nindex[n1d]\n nd = ndata[n1d]\n td = tdata[nind]\n \n tmag = zeropoint - 2.5*np.log10(td['flux_0'])\n nmag = nd['MAG_AUTO']\n ncut = (nmag < tmag)\n cind = nind[ncut]\n bcut = np.in1d(bindex, cind)\n bdata = bdata[-bcut]\n\n return bdata\n\ndef RemoveStars(tdata, tdel, bdata, ndata):\n stars = (tdata['halflightradius_0']<=0)\n inds = tdata[stars]['index']\n tdel = np.append(tdel, inds)\n\n nindex = ndata['VECTOR_ASSOC'][:, 6]\n ninds = np.in1d(nindex, inds)\n ndata = ndata[-ninds]\n\n bindex = bdata['VECTOR_ASSOC'][:, 8]\n binds = np.in1d(bindex, inds)\n bdata = bdata[-binds]\n\n return tdel, bdata, ndata\n\n\nif __name__ == \"__main__\":\n args = GetOpts()\n bdata = pyfits.open(args.balrogfile)[1].data\n ndata = pyfits.open(args.nosimfile)[1].data\n thdus = pyfits.open(args.truthfile)\n tdata = thdus[1].data\n thead = thdus[1].header\n zeropoint = thead['ZP']\n \n fig, ax = plt.subplots()\n \n tdel = np.empty(0)\n tdel, bdata, ndata = RemoveStars(tdata, tdel, bdata, ndata)\n\n ndata, bdata, tdel = RemoveDuplicate(ndata,bdata, tdata, tdel, args, truthcut=True)\n #bdata, ndata, tdel = RemoveDuplicate(bdata,ndata, tdata, tdel, args, truthcut=False)\n bdata = NosimCut(ndata, bdata, tdata, zeropoint, args)\n comp1, err1, mags1 = CompPlot(bdata, tdata, tdel, ndata, zeropoint, args, color='blue', label='Any FLAGS')\n\n fcut = (bdata['FLAGS'] > 3)\n findex = bdata[fcut]['VECTOR_ASSOC'][:, args.index]\n bdata = bdata[-fcut]\n #tdata = np.delete(tdata, findex, axis=0)\n tdel = np.append(tdel, findex)\n comp2, err2, mags2 = CompPlot(bdata, tdata, tdel, ndata, zeropoint, args, color='red', label='FLAGS ' + r'$ \\leq\\,3$', error=True)\n \n '''\n guess = [0.97, 23.5, 0.2]\n fit1 = leastsq(residual, guess, args=(comp1, mags1, err1), full_output=1)\n fit2 = leastsq(residual, guess, args=(comp2, mags2, err2))\n plt.plot(mags1, model(fit1[0], mags1), color='blue')\n plt.plot(mags2, model(fit2[0], mags2), color='red')\n print fit1\n print fit2\n '''\n\n plt.ylabel('Completeness Fraction')\n plt.xlabel('mag')\n plt.xlim([20,24])\n plt.ylim([0,1])\n\n major = MultipleLocator(0.2)\n minor = MultipleLocator(0.05)\n fmt = FormatStrFormatter(\"%.1f\")\n ax.yaxis.set_major_locator(major)\n ax.yaxis.set_major_formatter(fmt)\n ax.yaxis.set_minor_locator(minor)\n \n major = MultipleLocator(1)\n minor = MultipleLocator(0.1)\n fmt = FormatStrFormatter(\"%d\")\n ax.xaxis.set_major_locator(major)\n ax.xaxis.set_major_formatter(fmt)\n ax.xaxis.set_minor_locator(minor)\n \n plt.legend(loc='lower left')\n plt.title(args.tile)\n plt.show()\n","sub_path":"analysis/completeness.py","file_name":"completeness.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"454110982","text":"import logging\nimport time\nimport datetime\nimport json\nfrom scrapy import signals\nfrom twisted.internet import task\n\nfrom web_news.pipelines import MongoDBPipeline\n\nlogger = logging.getLogger(__name__)\n\ndef date_handler(obj):\n if hasattr(obj, 'isoformat'):\n return obj.isoformat()\n else:\n raise TypeError\n\nclass LogStatsDIY(object):\n def __init__(self, stats, interval=60.0):\n self.stats = stats\n self.interval = interval\n self.multiplier = 60.0 / self.interval\n self.task = None\n\n @classmethod\n def from_crawler(cls, crawler):\n # o = super(LogStatsDIY, cls).from_crawler(crawler)\n o = cls(crawler.stats)\n o.mongo = MongoDBPipeline.from_crawler(crawler)\n o.db = o.mongo.db['LogStatsDIY']\n crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)\n crawler.signals.connect(o.spider_closed, signal=signals.spider_closed)\n return o\n\n def spider_opened(self, spider):\n self.pagesprev = 0\n self.itemsprev = 0\n self.task = task.LoopingCall(self.log, spider)\n self.task.start(3)\n\n def log(self, spider):\n items = self.stats.get_value('item_scraped_count', 0)\n pages = self.stats.get_value('response_received_count', 0)\n irate = (items - self.itemsprev) * self.multiplier\n prate = (pages - self.pagesprev) * self.multiplier\n self.pagesprev, self.itemsprev = pages, items\n\n log_args = {'pages': pages, 'pagerate': prate,\n 'items': items, 'itemrate': irate}\n item = {'name': spider.name}\n try:\n item['name'] += '-{}'.format(getattr(spider, 'key'))\n except Exception as e:\n pass\n item['active_date'] = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time.time()))\n item.update(log_args)\n item['_stats'] = json.dumps(self.stats._stats,default=date_handler)\n logger.debug(item)\n # logger.info(msg, log_args, extra={'spider': spider})\n self.db.update({'name': item['name']}, {'$set': dict(item)}, True,\n True)\n def spider_closed(self, spider, reason):\n if self.task and self.task.running:\n self.task.stop()\n","sub_path":"web_news/misc/LogSpider.py","file_name":"LogSpider.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"245336532","text":"#mydb.db에 member테이블 생성\n#db 프로세스\n#1. db에 연결\n#2. 테이블 생성\n\nfrom libs.db.dbconn import getconn\n\ndef create_table():\n conn = getconn() # dbconn 모듈에서 getconn호출 (객체 생성)\n cur = conn.cursor() # db작업을 하는 객체(cur)\n # 테이블 생성 - sql 언어 DDL\n sql = \"\"\"\n create table member(\n mem_num int primary key,\n name car(20),\n age int\n )\n \"\"\"\n cur.execute(sql)\n\n conn.commit() # 트랜젝션 완료(수행)\n conn.close() # 네트워크 종료\n\nif __name__ == \"__main__\":\n create_table()","sub_path":"database/create_tbl.py","file_name":"create_tbl.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"314078691","text":"import socket\r\nimport sys\r\nimport os\r\nimport pathlib\r\nimport time \r\nimport pickle\r\nfrom datetime import datetime\r\nimport pyAesCrypt\r\nimport packet_header as ph\r\nfrom os import stat, remove\r\n#AF_INET -> IPv4\r\n#SOCK_STREAM -> TCP\r\nclass ap_request:\r\n def __init__(self):\r\n self.type = \"AP_REQ\"\r\n self.ticket_length = 0\r\n self.encrypted_ticket = \"\"\r\n self.client_ID = \"\"\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\ns.bind((socket.gethostname(), 1234))\r\ns.listen(5) #queue\r\nstatistics = open(\"ServerStats.txt\", \"a+\")\r\nserver_id_self = \"bob\"\r\nssc = open('ssc.txt', 'r')\r\nsecretSharedKey = ssc.read()\r\nflagquit = False\r\n\r\nclientsocket, address = s.accept() #happy to see you \r\nprint(f\"Recieved connection from {address}. Verifying credentials.\\n\")\r\nclientsocket.send(bytes(\"Verifying credential...\", \"utf-8\"))\r\n\r\n# print(\"The time we connected to the server is %s\" %tm.decode('ascii'))\r\n#lets send a file bro\r\nmessage = clientsocket.recv(1024)\r\nserver_ticket = pickle.loads(message)\r\n\r\n\r\nsize = stat(\"ticket.txt.aes\").st_size\r\nclient = \"alice\"\r\n#type\r\n#ticket_length\r\n#encrypted ticket\r\n#clientID\r\nbufferSize = 64 * 1024\r\npassword = secretSharedKey\r\nwith open(\"ticket.txt\", \"wb\") as fOut:\r\n with open('ticket.txt.aes', \"rb\") as fIn:\r\n try:\r\n pyAesCrypt.decryptStream(fIn, fOut, secretSharedKey,bufferSize, size)\r\n except: \r\n flagquit = True\r\n \r\nfOut.close()\r\ndT= open(\"ticket.txt\", 'r')\r\ndecryptedTicket = dT.read()\r\ndelivered_SSC = decryptedTicket[0:32]\r\ndelivered_Client = decryptedTicket[32:37]\r\nprint(delivered_Client) \r\n\r\n#TODO:Check make sure server and client are good \r\nif flagquit == True:\r\n print(\"Client not authenticated.\")\r\n clientsocket.send(bytes(\"-1\", 'utf-8'))\r\n\r\n clientsocket.close()\r\n statistics.close()\r\n s.close()\r\n print(\"Goodbye!\")\r\n quit()\r\n\r\nif delivered_Client != client:\r\n print(\"Client not authenticated.\")\r\n clientsocket.send(bytes(\"-1\", 'utf-8'))\r\n clientsocket.close()\r\n statistics.close()\r\n s.close()\r\n print(\"Goodbye!\")\r\n quit()\r\n'''if server_ticket.time < server_ticket.expires_at:\r\n print(\"Client not authenticated.\")\r\n clientsocket.close()\r\n statistics.close()\r\n s.close()\r\n print(\"Goodbye!\")\r\n quit()'''\r\n\r\nnow = datetime.now()\r\nprint(\"Recieved connection from client at \",now )\r\nclientsocket.send(bytes(\"Connection successful! You are authenticated.\", 'utf-8'))\r\nwhile True: \r\n com = clientsocket.recv(1024)\r\n command = com[:].decode('utf-8')\r\n \r\n while (command !=\"-1\"): \r\n if (command == \"1\"):\r\n nm = clientsocket.recv(1024)\r\n filename = nm.decode(\"utf-8\")\r\n if(filename != \"-2\"):\r\n print(f\"File: {filename}\")\r\n #recieve file\r\n statistics.write(\"Upload recieved at %d\\n\" %int(round(time.time() * 1000)))\r\n f = open(filename, \"wb\")\r\n #filesize = os.path.getsize(filename)\r\n file_data = clientsocket.recv(1024)\r\n f.write(file_data) \r\n f.close()\r\n size = os.stat(filename).st_size\r\n print(\"file has been uploaded successfully.\")\r\n statistics.write(\"->Upload resolved at %d\\n\" %int(round(time.time() * 1000)))\r\n statistics.write(\"Size of file: %d MB\\n\\n\" %size)\r\n else:\r\n print(\"Error: File not found.\")\r\n elif (command == \"2\"):\r\n #download file\r\n nm = clientsocket.recv(1024)\r\n filename = nm[:].decode(\"utf-8\")\r\n print(f\"File: {filename}\")\r\n file_location = pathlib.Path(filename)\r\n if file_location.exists():\r\n statistics.write(\"Download started at %d\\n\" %int(round(time.time() * 1000)))\r\n clientsocket.send(bytes(\"y\",'utf-8'))\r\n f = open(filename, \"rb\")\r\n file_data = f.read(1024)\r\n clientsocket.send(file_data)\r\n f.close()\r\n size = os.stat(filename).st_size\r\n print(\"File has been downloaded successfully\")\r\n statistics.write(\"->Download resolved at %d\\n\" %int(round(time.time() * 1000)))\r\n statistics.write(\"Size of file: %d MB\\n\\n\" %size)\r\n else: \r\n clientsocket.send(bytes(\"n\",'utf-8'))\r\n\r\n elif (command == \"3\"):\r\n nm = clientsocket.recv(1024)\r\n filename = nm[:].decode(\"utf-8\")\r\n if (filename == \"-1\"):\r\n print(\"Local Delete, no action needed.\")\r\n else: \r\n print(f\"File: {filename}\")\r\n file_location= pathlib.Path(filename)\r\n if file_location.exists():\r\n statistics.write(\"Delete request recieved at %d\\n\" %int(round(time.time() * 1000)))\r\n size = os.stat(filename).st_size\r\n os.remove(filename)\r\n clientsocket.send(bytes(\"File has successfully been deleted\", 'utf-8'))\r\n statistics.write(\"->Deletion completed at %d\\n\" %int(round(time.time() * 1000)))\r\n statistics.write(\"Size of file: %d MB\\n\\n\" %size)\r\n else: \r\n clientsocket.send(bytes(\"The file does not exist\", 'utf-8'))\r\n \r\n elif (command == '4'):\r\n statfile = open(\"fileStats.txt\", \"a+\")\r\n statfile.write(\"____________________________\")\r\n\r\n for p in pathlib.Path('.').iterdir():\r\n if p.is_file():\r\n size = os.stat(p).st_size\r\n print(f\"The file {p} is {size} MB\")\r\n statfile.write(\"\\n\")\r\n statfile.write(\"File: %s\\n\" %p)\r\n statfile.write(\"File Size: %d MB\\n\" %size)\r\n statfile.write(\"File was last accessed on: %d \\n\" %os.stat(p).st_atime)\r\n statfile.close()\r\n print(\"Ready for your next input..\")\r\n msg = clientsocket.recv(1024)\r\n command = msg.decode(\"utf-8\")\r\n if command == \"\":\r\n print(\"Looks like client may have disconnected, please reconnect.\")\r\n quit()\r\n \r\n clientsocket.close()\r\n statistics.close()\r\n s.close()\r\n print(\"Goodbye!\")\r\n quit()\r\n\r\n\r\ns.close()\r\n\r\n","sub_path":"Server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"76096615","text":"import argparse\nimport os\n\nfrom jinja2 import Environment\n\nDOCKER_COMPOSE_FILE = './docker-compose.yml'\nDOCKER_COMPOSE_TEMPLATE = \"\"\"\nversion: '2'\nservices:\n mongo:\n image: mongo:3.2.1\n container_name: opnfv-mongo\n testapi:\n image: opnfv/testapi:latest\n container_name: opnfv-testapi\n environment:\n - mongodb_url=mongodb://mongo:27017/\n - base_url={{ vars.base_url }}\n ports:\n - \"{{ vars.testapi_port }}:8000\"\n links:\n - mongo\n reporting:\n image: opnfv/reporting:latest\n container_name: opnfv-reporting\n ports:\n - \"{{ vars.reporting_port }}:8000\"\n\"\"\"\n\n\ndef render_docker_compose(testapi_port, reporting_port, testapi_base_url):\n vars = {\n \"testapi_port\": testapi_port,\n \"reporting_port\": reporting_port,\n \"base_url\": testapi_base_url,\n }\n yml = Environment().from_string(DOCKER_COMPOSE_TEMPLATE).render(vars=vars)\n with open(DOCKER_COMPOSE_FILE, 'w') as f:\n f.write(yml)\n f.close()\n\n\ndef main(args):\n render_docker_compose(args.testapi_port,\n args.reporting_port,\n args.testapi_base_url)\n os.system('docker-compose -f {} up -d'.format(DOCKER_COMPOSE_FILE))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Backup MongoDBs')\n parser.add_argument('-tp', '--testapi-port',\n type=int,\n required=False,\n default=8082,\n help='testapi exposed port')\n parser.add_argument('-tl', '--testapi-base-url',\n type=str,\n required=True,\n help='testapi exposed base-url')\n parser.add_argument('-rp', '--reporting-port',\n type=int,\n required=False,\n default=8084,\n help='reporting exposed port')\n\n main(parser.parse_args())\n","sub_path":"opts/one_click_deploy.py","file_name":"one_click_deploy.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"542323772","text":"import Sudoku_Storage\nimport random\n\npopulation_size = 5\n\n\nclass SudokuGame:\n\n arr = [0] * population_size\n\n def __init__(self):\n self.game = Sudoku_Storage.Sudoku() # create Sudoku\n self.game.read_from_file() # read from file and populate array\n self.game.fitness() # calculate and print fitness score, 100% fitness would be 243\n self.game.print() # print Sudoku\n\n def set_game(self, best_from_previous):\n self.game.deep_copy(best_from_previous)\n\n def create_sudoku_children(self):\n for i in range(population_size):\n self.arr[i] = Sudoku_Storage.Sudoku()\n self.arr[i].deep_copy(self.game)\n self.add_in_sudoku(self.arr[i])\n\n def add_in_sudoku(self, board):\n for i in range(Sudoku_Storage.game_size * Sudoku_Storage.game_size + Sudoku_Storage.game_size):\n if board.SudokuNumbers[i] == 0:\n board.SudokuNumbers[i] = random.randint(1, 9)\n board.fitness()\n\n def mutate_sudoku(self, array_index):\n random_index_to_mutate = random.randint(0, Sudoku_Storage.game_size * Sudoku_Storage.game_size + Sudoku_Storage.game_size - 1)\n if self.arr[array_index].SudokuNumbers[random_index_to_mutate] != -38:\n self.arr[array_index].SudokuNumbers[random_index_to_mutate] = random.randint(1, 9)\n self.arr[array_index].fitness()\n # self.arr[array_index].print_fitness()\n if self.arr[array_index]. fitness_score == Sudoku_Storage.best_fitness:\n exit()\n\n def sort_by_max_fitness(self):\n temp = Sudoku_Storage.Sudoku()\n for i in range(population_size):\n for j in range(population_size - 1):\n if self.arr[j].fitness_score < self.arr[j + 1].fitness_score:\n temp.deep_copy(self.arr[j])\n self.arr[j].deep_copy(self.arr[j + 1])\n self.arr[j + 1].deep_copy(temp)\n\n # print(\"_________________________AFTER SORT_________________________\")\n # for i in range(population_size):\n # self.arr[i].print_fitness()\n\n def merge_sort(self, left, right):\n if left < right - 1:\n mid = (right - left) // 2\n self.merge_sort(left, mid)\n self.merge_sort(mid + 1, right)\n self.merge(left, right)\n else:\n self.merge(left, right)\n return\n\n def merge(self, left, right):\n temp = Sudoku_Storage.Sudoku()\n while left < right:\n index = left\n while index <= right:\n if self.arr[left].fitness_score < self.arr[index].fitness_score:\n temp.deep_copy(self.arr[left])\n self.arr[left].deep_copy(self.arr[index])\n self.arr[index].deep_copy(temp)\n index += 1\n left += 1\n\n def crossover(self, first_index):\n second_index = random.randint(0, population_size - 1)\n cut_off = random.randint(0, Sudoku_Storage.game_size * Sudoku_Storage.game_size + Sudoku_Storage.game_size)\n self.perform_crossover(first_index, second_index, cut_off)\n\n def perform_crossover(self, first_index, second_index, cut_off):\n temp = 0\n for i in range(cut_off, Sudoku_Storage.game_size * Sudoku_Storage.game_size + Sudoku_Storage.game_size):\n temp = self.arr[first_index].SudokuNumbers[i]\n self.arr[first_index].SudokuNumbers[i] = self.arr[second_index].SudokuNumbers[i]\n self.arr[second_index].SudokuNumbers[i] = temp\n self.arr[first_index].fitness()\n self.arr[second_index].fitness()\n","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"367425995","text":"import yaml\nimport argparse\nimport os\nimport ruamel.yaml\nfrom ruamel.yaml.scalarstring import DoubleQuotedScalarString\n\nca_defport = 7054\norderer_defport = 7050\npeer_defport = 7051\ncouchdb_defport = 5984\nservices = {}\nnetwork_name = \"byfn\"\n\ndef generate_crypto_config(_orgs=2, _peers=2, _orderers=3, _domain=\"dredev.de\"):\n domain = _domain\n anzpeers = _peers\n anzorderers = _orderers\n anzorgs = _orgs\n new_yaml = ruamel.yaml.YAML()\n peer_list = []\n specs_list = []\n for i in range(anzorderers):\n specs_list.append({\"Hostname\": \"orderer{}\".format(i + 1)})\n\n for org in range(anzorgs):\n print(bcolors.WARNING + \" [*] Generating Crypto Material for Org{}\".format(org))\n peer_list.append({\n \"Name\": \"Org{}\".format(org + 1),\n \"Domain\": \"org{}.{}\".format(org + 1, domain),\n \"Template\": {\"Count\": anzpeers},\n \"Users\": {\"Count\": 1}, # Only one user per Org\n })\n print(bcolors.OKGREEN + \" [+] Generating Crypto Material for Org{} COMPLETE\".format(org))\n print(bcolors.OKBLUE + \" [*] Generating Final Object\")\n final_dict = {\n \"OrdererOrgs\": [\n {\n \"Name\": \"Orderer\",\n \"Domain\": domain,\n \"Specs\": specs_list\n }\n ],\n \"PeerOrgs\": peer_list\n }\n print(bcolors.OKBLUE + \" [*] Generating Final Object COMPLETE\")\n f = open(\"crypto-config.yaml\", \"w\")\n new_yaml.dump(final_dict, f)\n f.close()\n print(bcolors.HEADER + \"========================================\")\n print(\">>> crypto-config.yaml has been dumped!\")\n print(\"========================================\")\n\n\nclass Orga:\n def __init__(self, domain, org, orgmsp, ap):\n self.org = org\n self.domain = domain\n self.org_msp = orgmsp\n self.anchor_peer = ap\n\n\ndef tr(s):\n return s.replace('\\'<<\\'', '<<') # such output is not valid YAML!\n\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n\n def disable(self):\n self.HEADER = ''\n self.OKBLUE = ''\n self.OKGREEN = ''\n self.WARNING = ''\n self.FAIL = ''\n self.ENDC = ''\n\n\ndef generate_chaincode_entries():\n print(bcolors.OKBLUE + \"[*] Please Specify your Chaincode that you want to install. We assume that it is a Java Packet within the folder \\\"chaincodes/java/\\\".\")\n con = \"y\"\n with open(\"chaincodes.txt\", \"w+\") as fp:\n while con == \"y\" or con == \"Y\":\n try:\n chaincode_name = input(\"Name of the folder: \")\n\n # Check if it exists\n if os.path.exists(\"chaincodes/java/\"+chaincode_name):\n fp.write(chaincode_name + \"\\n\")\n else:\n print(bcolors.FAIL + \"[-] You provided a non existing directory! Nothing written\")\n con = input(\"Add another? (Y/n)\")\n except ValueError:\n print(bcolors.FAIL + \"[-] Oof, you did not provide proper values. Exiting\")\n exit(1)\n\n\ndef generate_configtx(_orgs=2, _orderers=3, _kafka_brokers=4, _consortium=\"WebConsortium\", _domain=\"dredev.de\", _blocksize=10, _timeout=1):\n yaml_new = ruamel.yaml.YAML()\n\n orgs = [Orga(org=\"\", domain=\"ordererOrganizations\", orgmsp=\"OrdererMSP\", ap=False)] # Default one orderer!\n for i in range(_orgs):\n orgs.append(\n Orga(org=\"org{}.\".format(i + 1), domain=\"peerOrganizations\", orgmsp=\"Org{}MSP\".format(i + 1), ap=True))\n\n orga_list = []\n for org in orgs:\n print(bcolors.WARNING + \" [*] Configuring Org {}\".format(org.org_msp))\n org_policies = {\n \"Readers\": {\n \"Type\": \"Signature\",\n \"Rule\": DoubleQuotedScalarString(\"OR('{}.member')\".format(org.org_msp))\n },\n \"Writers\": {\n \"Type\": \"Signature\",\n \"Rule\": DoubleQuotedScalarString(\"OR('{}.member')\".format(org.org_msp))\n },\n \"Admins\": {\n \"Type\": 'Signature',\n \"Rule\": DoubleQuotedScalarString(\"OR('{}.admin')\".format(org.org_msp))\n },\n \"Endorsement\": {\n \"Type\": \"Signature\",\n \"Rule\": DoubleQuotedScalarString(\"OR('{}.member')\".format(org.org_msp))\n }\n\n }\n orderer_org = {\n \"Name\": \"{}\".format(org.org_msp),\n \"ID\": \"{}\".format(org.org_msp),\n \"MSPDir\": \"crypto-config/{}/{}{}/msp\".format(org.domain, org.org, _domain),\n \"Policies\": org_policies\n }\n if org.anchor_peer:\n orderer_org.update({\"AnchorPeers\": [\n {\n \"Host\": \"peer0.{}{}\".format(org.org, _domain),\n \"Port\": 7051\n }\n ]})\n\n orga_list.append(orderer_org)\n print(bcolors.OKGREEN + \" [+] Configuring for Org {} COMPLETE\".format(org.org_msp))\n print(bcolors.WARNING + \" [*] Configuring Capabilities\")\n channel_capabilities = {\"V2_0\": True}\n orderer_capabilities = {\"V2_0\": True}\n app_capabilities = {\"V2_0\": True}\n\n capabilities = {\n \"Channel\": channel_capabilities,\n \"Orderer\": orderer_capabilities,\n \"Application\": app_capabilities\n }\n print(bcolors.OKGREEN + \" [+] Configuring Capabilities COMPLETE\")\n\n print(bcolors.WARNING + \" [*] Configuring App Permissions\")\n application = {\n \"ACLs\": {\n \"_lifecycle/CheckCommitReadiness\": \"/Channel/Application/Writers\",\n\n # ACL policy for _lifecycle's \"CommitChaincodeDefinition\" function\n \"_lifecycle/CommitChaincodeDefinition\": \"/Channel/Application/Writers\",\n\n # ACL policy for _lifecycle's \"QueryChaincodeDefinition\" function\n \"_lifecycle/QueryChaincodeDefinition\": \"/Channel/Application/Readers\",\n\n # ACL policy for _lifecycle's \"QueryChaincodeDefinitions\" function\n \"_lifecycle/QueryChaincodeDefinitions\": \"/Channel/Application/Readers\",\n\n # ---Lifecycle System Chaincode (lscc) function to policy mapping for access control---#\n # ACL policy for lscc's \"getid\" function\n \"lscc/ChaincodeExists\": \"/Channel/Application/Readers\",\n\n # ACL policy for lscc's \"getdepspec\" function\n \"lscc/GetDeploymentSpec\": \"/Channel/Application/Readers\",\n\n # ACL policy for lscc's \"getccdata\" function\n \"lscc/GetChaincodeData\": \"/Channel/Application/Readers\",\n\n # ACL Policy for lscc's \"getchaincodes\" function\n \"lscc/GetInstantiatedChaincodes\": \"/Channel/Application/Readers\",\n\n # ---Query System Chaincode (qscc) function to policy mapping for access control---#\n\n # ACL policy for qscc's \"GetChainInfo\" function\n \"qscc/GetChainInfo\": \"/Channel/Application/Readers\",\n\n # ACL policy for qscc's \"GetBlockByNumber\" function\n \"qscc/GetBlockByNumber\": \"/Channel/Application/Readers\",\n\n # ACL policy for qscc's \"GetBlockByHash\" function\n \"qscc/GetBlockByHash\": \"/Channel/Application/Readers\",\n\n # ACL policy for qscc's \"GetTransactionByID\" function\n \"qscc/GetTransactionByID\": \"/Channel/Application/Readers\",\n\n # ACL policy for qscc's \"GetBlockByTxID\" function\n \"qscc/GetBlockByTxID\": \"/Channel/Application/Readers\",\n\n # ---Configuration System Chaincode (cscc) function to policy mapping for access control---#\n\n # ACL policy for cscc's \"GetConfigBlock\" function\n \"cscc/GetConfigBlock\": \"/Channel/Application/Readers\",\n\n # ACL policy for cscc's \"GetConfigTree\" function\n \"cscc/GetConfigTree\": \"/Channel/Application/Readers\",\n\n # ACL policy for cscc's \"SimulateConfigTreeUpdate\" function\n \"cscc/SimulateConfigTreeUpdate\": \"/Channel/Application/Readers\",\n\n # ---Miscellanesous peer function to policy mapping for access control---#\n\n # ACL policy for invoking chaincodes on peer\n \"peer/Propose\": \"/Channel/Application/Writers\",\n\n # ACL policy for chaincode to chaincode invocation\n \"peer/ChaincodeToChaincode\": \"/Channel/Application/Readers\",\n\n # ---Events resource to policy mapping for access control###---#\n\n # ACL policy for sending block events\n \"event/Block\": \"/Channel/Application/Readers\",\n\n # ACL policy for sending filtered block events\n \"event/FilteredBlock\": \"/Channel/Application/Readers\",\n },\n \"Organizations\": None,\n \"Policies\": {\n \"LifecycleEndorsement\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"MAJORITY Endorsement\"),\n },\n \"Endorsement\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"MAJORITY Endorsement\"),\n },\n \"Readers\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"ANY Readers\")\n },\n \"Writers\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"ANY Writers\")\n },\n \"Admins\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"MAJORITY Admins\")\n }\n },\n \"Capabilities\": {\n \"<<\": app_capabilities\n }\n }\n print(bcolors.OKGREEN + \" [+] Configuring App Permissions COMPLETE\")\n orderer_addresses = []\n kafka_list = []\n for i in range(_orderers):\n orderer_addresses.append(\"orderer{}.{}:7050\".format(i + 1, _domain))\n\n for i in range(_kafka_brokers):\n kafka_list.append(\"kafka{}:9092\".format(i))\n\n print(bcolors.WARNING + \" [*] Generating Orderer Config\")\n orderer = {\n \"OrdererType\": \"kafka\",\n \"Addresses\": orderer_addresses,\n\n # Batch Timeout: The amount of time to wait before creating a batch.\n \"BatchTimeout\": \"{}s\".format(_timeout),\n \"BatchSize\": {\n \"MaxMessageCount\": _blocksize,\n \"AbsoluteMaxBytes\": \"10 MB\",\n \"PreferredMaxBytes\": \"2 MB\",\n },\n \"MaxChannels\": 0,\n \"Kafka\": {\n \"Brokers\": kafka_list\n },\n \"Organizations\": None,\n \"Policies\": {\n \"Readers\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"ANY Readers\")\n },\n \"Writers\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"ANY Writers\")\n },\n \"Admins\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"MAJORITY Admins\")\n },\n \"BlockValidation\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"ANY Writers\")\n }\n\n },\n \"Capabilities\": {\n \"<<\": orderer_capabilities\n }\n }\n\n print(bcolors.OKGREEN + \" [+] Generating Orderer Config COMPLETE\")\n print(bcolors.WARNING + \" [*] Generating Channel Config\")\n channel = {\n \"Policies\": {\n \"Readers\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"ANY Readers\"),\n },\n \"Writers\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"ANY Writers\"),\n },\n \"Admins\": {\n \"Type\": \"ImplicitMeta\",\n \"Rule\": DoubleQuotedScalarString(\"MAJORITY Admins\")\n }\n },\n \"Capabilities\": {\n \"<<\": channel_capabilities,\n }\n }\n print(bcolors.OKGREEN + \" [*] Generating Channel Config COMPLETE\")\n\n ord_list = []\n for i in range(_orderers):\n ord_list.append(\"orderer{}.{}:7050\".format(i + 1, _domain))\n\n print(bcolors.WARNING + \" [*] Generating Profiles\")\n profiles = {\n \"OrdererDefault\": {\n \"<<\": channel,\n \"Capabilities\": {\n \"<<\": channel_capabilities\n },\n \"Orderer\": {\n \"<<\": orderer,\n \"OrdererType\": \"kafka\",\n \"Addresses\": ord_list,\n \"Organizations\": [orga_list[0]],\n \"Capabilities\": {\n \"<<\": orderer_capabilities,\n }\n },\n \"Consortiums\": {\n _consortium: {\n \"Organizations\":\n orga_list[1:]\n }\n }\n\n },\n \"MainChannel\": {\n \"<<\": channel,\n \"Consortium\": _consortium,\n \"Application\": {\n \"<<\": application,\n \"Organizations\": orga_list[1:]\n },\n \"Capabilities\": {\n \"<<\": app_capabilities\n }\n\n }\n }\n print(bcolors.OKGREEN + \" [+] Generating Profiles COMPLETE\")\n print(bcolors.OKBLUE + \" [*] Generating Final Object\")\n final = {\n \"Organizations\": orga_list,\n \"Capabilities\": capabilities,\n \"Application\": application,\n \"Orderer\": orderer,\n \"Channel\": channel,\n \"Profiles\": profiles\n }\n print(bcolors.OKBLUE + \" [+] Generating Final Object COMPLETE\")\n\n f = open(\"configtx.yaml\", \"w\")\n yaml_new.dump(final, f, transform=tr)\n\n print(bcolors.HEADER + \"========================================\")\n print(\">>> configtx.yaml has been dumped!\")\n print(\"========================================\")\n\n\nclass NoAliasDumper(yaml.Dumper):\n def ignore_aliases(self, data):\n return True\n\n\ndef generate_env(_name=\"net\"):\n f = open(\".env\", \"w\")\n f.write(\"COMPOSE_PROJECT_NAME={}\".format(_name))\n f.close()\n print(\"========================================\")\n print(\">>> .env has been dumped!\")\n print(\"========================================\")\n\n\ndef generate_docker_compose(_orderers, _orgs, _peers, _domain, _kafka):\n yaml_new = ruamel.yaml.YAML()\n\n all_node_containers = []\n print(bcolors.OKBLUE + \"======== Creating CAs ========\")\n for i in range(_orgs):\n print(bcolors.WARNING + \" [*] Generating CA for org{}\".format(i + 1))\n ca = {\n \"image\": \"hyperledger/fabric-ca:1.4\",\n \"environment\": [\n \"FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server\",\n \"FABRIC_CA_SERVER_CA_NAME=ca.org{}.{}\".format(i + 1, _domain),\n \"FABRIC_CA_SERVER_CA_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.org{}.{}-cert.pem\".format(\n i + 1, _domain),\n \"FABRIC_CA_SERVER_CA_KEYFILE=/etc/hyperledger/fabric-ca-server-config/priv_sk\"\n ],\n \"ports\": [\"{}:{}\".format(ca_defport + i * 1000, ca_defport)],\n \"command\": \"sh -c 'fabric-ca-server start --ca.certfile /etc/hyperledger/fabric-ca-server-config/ca.org{}.{}-cert.pem --ca.keyfile /etc/hyperledger/fabric-ca-server-config/priv_sk -b admin:adminpw -d'\".format(\n i + 1, _domain),\n \"volumes\": [\n \"./crypto-config/peerOrganizations/org{}.{}/ca/:/etc/hyperledger/fabric-ca-server-config\".format(i + 1,\n _domain)\n ],\n \"container_name\": \"ca.org{}.{}\".format(i + 1, _domain),\n \"networks\": [\n network_name\n ]\n }\n services.update({\"ca.org{}.{}\".format(i + 1, _domain): ca})\n print(bcolors.OKGREEN + \" [+] Generating CA for org{} COMPLETE\".format(i + 1))\n\n print(bcolors.OKBLUE + \"======== Creating Zookeeper ========\")\n zookeepers = []\n zoo_servers = \"\"\n zoo_connect = \"\"\n for i in range(_orderers):\n zoo_servers += \"server.{}=zookeeper{}:2888:3888 \".format(i + 1, i + 1)\n zoo_connect += \"zookeeper{}:2181,\".format(i + 1)\n zookeepers.append(\"zookeeper{}\".format(i + 1))\n zoo_servers = zoo_servers[:-1]\n zoo_connect = zoo_connect[:-1]\n for i in range(_orderers):\n print(bcolors.WARNING + \" [*] Generating Zookeeper{}\".format(i + 1))\n zoo = {\n \"image\": \"hyperledger/fabric-zookeeper\",\n \"container_name\": \"zookeeper{}\".format(i + 1),\n \"restart\": \"always\",\n \"environment\": [\n \"ZOO_MY_ID={}\".format(i + 1),\n \"ZOO_SERVERS=\" + zoo_servers\n ],\n \"ports\": [\n 2181,\n 2888,\n 3888,\n ],\n \"networks\": [\n network_name\n ]\n }\n services.update({\"zookeeper{}\".format(i + 1): zoo})\n print(bcolors.OKGREEN + \" [+] Zookeeper{} complete\".format(i + 1))\n\n print(bcolors.OKBLUE + \"======== Creating Kafka Brokers ========\")\n\n for i in range(_kafka):\n print(bcolors.WARNING + \" [*] Generating Kafka{}\".format(i))\n ka = {\n \"image\": \"hyperledger/fabric-kafka\",\n \"container_name\": \"kafka{}\".format(i),\n # restart: always\n \"environment\": [\n \"KAFKA_ADVERTISED_HOST_NAME=kafka{}\".format(i),\n \"KAFKA_ADVERTISED_PORT=9092\",\n \"KAFKA_BROKER_ID={}\".format(i ),\n \"KAFKA_MESSAGE_MAX_BYTES=103809024\", # 99 * 1024 * 1024 B\n \"KAFKA_REPLICA_FETCH_MAX_BYTES=103809024\", # 99 * 1024 * 1024 B\n \"KAFKA_UNCLEAN_LEADER_ELECTION_ENABLE=false\",\n \"KAFKA_NUM_REPLICA_FETCHERS=1\",\n \"KAFKA_DEFAULT_REPLICATION_FACTOR={}\".format(i+1),\n \"KAFKA_ZOOKEEPER_CONNECT=\" + zoo_connect\n ],\n \"ports\": [\n 9092\n ],\n \"depends_on\": zookeepers,\n \"networks\": [\n network_name\n ]\n\n }\n services.update({\"kafka{}\".format(i): ka})\n print(bcolors.OKGREEN + \" [+] Kafka{} Completed\".format(i))\n\n print(bcolors.OKBLUE + \"======= Generating Orderers =======\")\n kafka_brokers = \"\"\n kafka_broker_list = []\n for i in range(_kafka):\n kafka_brokers += \"kafka{}:9092,\".format(i)\n kafka_broker_list.append(\"kafka{}\".format(i))\n kafka_brokers = kafka_brokers[:-1]\n orderer_str = \"\"\n for i in range(_orderers):\n print(bcolors.WARNING + \" [*] Generating Orderer{}\".format(i + 1))\n order = {\n \"container_name\": \"orderer{}.{}\".format(i + 1, _domain),\n \"image\": \"hyperledger/fabric-orderer:2.0\",\n \"environment\": [\n \"ORDERER_HOST=orderer{}.{}\".format(i + 1, _domain),\n \"ORDERER_GENERAL_LOGLEVEL=debug\",\n \"ORDERER_GENERAL_LISTENADDRESS=0.0.0.0\",\n \"ORDERER_GENERAL_LISTENPORT={}\".format(orderer_defport),\n \"ORDERER_GENERAL_GENESISMETHOD=file\",\n \"ORDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis.block\",\n \"ORDERER_GENERAL_LOCALMSPID=OrdererMSP\",\n \"ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/msp/orderer/msp\",\n # Kafka Orderer Type\n \"CONFIGTX_ORDERER_BATCHTIMEOUT=1s\",\n \"CONFIGTX_ORDERER_ORDERERTYPE=kafka\",\n \"CONFIGTX_ORDERER_KAFKA_BROKERS=[{}]\".format(kafka_brokers),\n \"ORDERER_KAFKA_RETRY_SHORTINTERVAL=1s\",\n \"ORDERER_KAFKA_RETRY_SHORTTOTAL=30s\",\n \"ORDERER_KAFKA_VERBOSE=true\",\n \"ORDERER_ABSOLUTEMAXBYTES=10 MB\",\n \"ORDERER_PREFERREDMAXBYTES=512 KB\"\n ],\n \"working_dir\": \"/opt/gopath/src/github.com/hyperledger/fabric/orderer\",\n \"command\": \"orderer\",\n \"ports\": [\n \"{}:{}\".format(orderer_defport + i * 1000, orderer_defport)\n ],\n \"volumes\": [\n \"./config/:/etc/hyperledger/configtx\",\n \"./crypto-config/ordererOrganizations/{}/orderers/orderer{}.{}/:/etc/hyperledger/msp/orderer\".format(\n _domain, i + 1, _domain)\n ],\n \"networks\": [\n network_name\n ],\n \"depends_on\": kafka_broker_list\n }\n services.update({\"orderer{}.{}\".format(i + 1, _domain): order})\n all_node_containers.append(\"orderer{}.{}\".format(i + 1, _domain))\n orderer_str += \"-o localhost:{} \".format(orderer_defport + i * 1000)\n print(bcolors.OKGREEN + \" [+] Orderer{} COMPLETE\".format(i + 1))\n\n os.environ[\"ORDERERS\"] = orderer_str\n\n print(bcolors.OKBLUE + \"======= Generating Peers for Organizations =======\")\n peer_addresses = \"\"\n basepath = os.getcwd() + \"/crypto-config\"\n for org in range(_orgs):\n print(bcolors.WARNING + \" [*] Generating org{}.{}\".format(org + 1, _domain))\n for peer in range(_peers):\n peer_addresses += \"--peerAddresses localhost:{} --tlsRootCertFiles {}/peerOrganizations/org{}.{}/peers/peer{}.org{}.{}/tls/ca.crt \".format(\n peer_defport + 1000 * ((_peers * org) + peer), basepath, org + 1, _domain, peer, org + 1, _domain)\n print(bcolors.WARNING + \" [+] Generating peer{}.org{}.{}\".format(peer, org + 1, _domain))\n pe = {\n \"container_name\": \"peer{}.org{}.{}\".format(peer, org + 1, _domain),\n \"image\": \"hyperledger/fabric-peer:2.0\",\n \"environment\": [\n \"CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock\",\n \"CORE_LOGGING_PEER=debug\",\n \"CORE_CHAINCODE_LOGGING_LEVEL=DEBUG\",\n \"CORE_PEER_ID=peer{}.org{}.{}\".format(peer, org + 1, _domain),\n \"CORE_PEER_ADDRESS=peer{}.org{}.{}:{}\".format(peer, org + 1, _domain, peer_defport),\n \"CORE_PEER_LOCALMSPID=Org{}MSP\".format(org + 1),\n \"CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/peer/\",\n \"CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_\" + network_name,\n \"CORE_LEDGER_STATE_STATEDATABASE=CouchDB\",\n \"CORE_LEDGER_STATE_COUCHDBCONFIG_COUCHDBADDRESS=couchdb{}.org{}.{}:{}\".format(peer, org + 1,\n _domain,\n couchdb_defport),\n # The CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME and CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD\n # provide the credentials for ledger to connect to CouchDB. The username and password must\n # match the username and password set for the associated CouchDB.\n \"CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME=\",\n \"CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD=\",\n ],\n \"working_dir\": \"/opt/gopath/src/github.com/hyperledger/fabric\",\n \"command\": \"peer node start\",\n \"ports\": [\n \"{}:{}\".format(peer_defport + 1000 * ((_peers * org) + peer), peer_defport),\n \"{}:{}\".format((peer_defport + 1) + 1000 * ((_peers * org) + peer), (peer_defport + 1)),\n \"{}:{}\".format((peer_defport + 2) + 1000 * ((_peers * org) + peer), (peer_defport + 2)),\n ],\n \"volumes\": [\n \"/var/run/:/host/var/run/\",\n \"./crypto-config/peerOrganizations/org{}.{}/peers/peer{}.org{}.{}/msp:/etc/hyperledger/msp/peer\".format(\n org + 1, _domain, peer, org + 1, _domain),\n \"./crypto-config/peerOrganizations/org{}.{}/users:/etc/hyperledger/msp/users\".format(org + 1,\n _domain),\n \"./config:/etc/hyperledger/configtx\"\n ],\n \"depends_on\": [\n \"couchdb{}.org{}.{}\".format(peer, org + 1, _domain)\n ],\n \"networks\": [\n network_name\n ]\n }\n services.update({\"peer{}.org{}.{}\".format(peer, org + 1, _domain): pe})\n all_node_containers.append(\"peer{}.org{}.{}\".format(peer, org + 1, _domain))\n print(bcolors.OKGREEN + \" [+] peer{}.org{}.{} COMPLETE\".format(peer, org + 1, _domain))\n print(bcolors.WARNING + \" [*] Generating couchdb{}.org{}.{}\".format(peer, org + 1, _domain))\n cdb = {\n \"container_name\": \"couchdb{}.org{}.{}\".format(peer, org + 1, _domain),\n \"image\": \"hyperledger/fabric-couchdb\",\n # Populate the COUCHDB_USER and COUCHDB_PASSWORD to set an admin user and password\n # for CouchDB. This will prevent CouchDB from operating in an \"Admin Party\" mode.\n \"environment\": [\n \"COUCHDB_USER=\",\n \"COUCHDB_PASSWORD=\"\n ],\n \"ports\": [\n \"{}:{}\".format(couchdb_defport + 1000 * ((_peers * org) + peer), couchdb_defport),\n ],\n \"networks\": [\n network_name\n ]\n }\n services.update({\"couchdb{}.org{}.{}\".format(peer, org + 1, _domain): cdb})\n all_node_containers.append(\"couchdb{}.org{}.{}\".format(peer, org + 1, _domain))\n print(bcolors.OKGREEN + \" [+] couchdb{}.org{}.{} COMPLETE\".format(peer, org + 1, _domain))\n\n print(bcolors.OKGREEN + \" [+] .org{}.{} COMPLETE\".format(org + 1, _domain))\n os.environ[\"PEER_CON_PARAMS\"] = peer_addresses\n\n print(bcolors.OKBLUE + \"======= Generating CLI =======\")\n print(bcolors.WARNING + \" [*] CLI Generation started\")\n cli = {\n \"container_name\": \"cli\",\n \"image\": \"hyperledger/fabric-tools\",\n \"tty\": True,\n # stdin_open: true\n \"environment\": [\n \"GOPATH=/opt/gopath\",\n \"CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock\",\n \"FABRIC_LOGGING_SPEC=DEBUG\",\n \"CORE_PEER_ID=cli\",\n \"CORE_PEER_ADDRESS=peer0.org1.{}:{}\".format(_domain, peer_defport),\n \"CORE_PEER_LOCALMSPID=Org1MSP\",\n \"CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.{}/users/Admin@org1.{}/msp\".format(\n _domain, _domain),\n \"CORE_CHAINCODE_KEEPALIVE=10\"\n ],\n \"working_dir\": \"/opt/gopath/src/github.com/hyperledger/fabric/peer\",\n \"command\": \"/bin/bash\",\n \"volumes\": [\n \"/var/run/:/host/var/run/\",\n \"./chaincodes/java:/opt/gopath/src/github.com/chaincodes/java\",\n \"./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/\",\n \"./config:/etc/hyperledger/configtx\"\n ],\n \"networks\": [\n network_name\n ],\n \"depends_on\": all_node_containers\n }\n services.update({\"cli\": cli})\n print(bcolors.OKGREEN + \" [+] CLI Generation COMPLETE\")\n\n print(bcolors.OKBLUE + \"======= Generating final Structure =======\")\n final = {\n \"version\": ruamel.yaml.scalarstring.SingleQuotedScalarString(\"2\"),\n \"networks\": {\n network_name: None\n },\n \"services\": services\n }\n\n # yaml_new.dump(final, sys.stdout)\n f = open(\"docker-compose.yaml\", \"w\")\n yaml_new.dump(final, f)\n print(bcolors.HEADER + \"========================================\")\n print(\">>> docker-compose.yaml has been dumped!\")\n print(\"========================================\")\n\n\ndef generate_core():\n\n yaml_new = ruamel.yaml.YAML()\n print(bcolors.WARNING + \" [*] Generating Peer Core\")\n peer = {\n \"id\": \"peer\",\n \"networkId\": \"byfn\",\n \"listenAddress\": \"0.0.0.0:7051\",\n \"address\": \"0.0.0.0:7051\",\n \"addressAutoDetect\": False,\n \"keepalive\": {\n \"interval\": \"7200s\",\n \"timeout\": \"20s\",\n \"minInterval\": \"60s\",\n \"client\": {\n \"interval\": \"60s\",\n \"timeout\": \"20s\",\n },\n \"deliveryClient\": {\n \"interval\": \"60s\",\n \"timeout\": \"20s\"\n }\n },\n \"gossip\": {\n \"bootstrap\": \"127.0.0.1:7051\",\n \"useLeaderElection\": True,\n \"orgLeader\": False,\n \"membershipTrackerInterval\": \"5s\",\n \"endpoint\": None,\n \"maxBlockCountToStore\": 100,\n \"maxPropagationBurstLatency\": \"10ms\",\n \"maxPropagationBurstSize\": 10,\n \"propagateIterations\": 1,\n \"propagatePeerNum\": 3,\n \"pullInterval\": \"4s\",\n \"pullPeerNum\": 3,\n \"requestStateInfoInterval\": \"4s\",\n # Determines frequency of pushing state info messages to peers(unit: second)\n \"publishStateInfoInterval\": \"4s\",\n # Maximum time a stateInfo message is kept until expired\n \"stateInfoRetentionInterval\": None,\n # Time from startup certificates are included in Alive messages(unit: second)\n \"publishCertPeriod\": \"10s\",\n # Should we skip verifying block messages or not (currently not in use)\n \"skipBlockVerification\": False,\n # Dial timeout(unit: second)\n \"dialTimeout\": \"3s\",\n # Connection timeout(unit: second)\n \"connTimeout\": \"2s\",\n # Buffer size of received messages\n \"recvBuffSize\": 20,\n # Buffer size of sending messages\n \"sendBuffSize\": 200,\n # Time to wait before pull engine processes incoming digests (unit: second)\n # Should be slightly smaller than requestWaitTime\n \"digestWaitTime\": \"1s\",\n # Time to wait before pull engine removes incoming nonce (unit: milliseconds)\n # Should be slightly bigger than digestWaitTime\n \"requestWaitTime\": \"1500ms\",\n # Time to wait before pull engine ends pull (unit: second)\n \"responseWaitTime\": \"2s\",\n # Alive check interval(unit: second)\n \"aliveTimeInterval\": \"5s\",\n # Alive expiration timeout(unit: second)\n \"aliveExpirationTimeout\": \"25s\",\n # Reconnect interval(unit: second)\n \"reconnectInterval\": \"25s\",\n # This is an endpoint that is published to peers outside of the organization.\n # If this isn't set, the peer will not be known to other organizations.\n \"externalEndpoint\": None,\n # Leader election service configuration\n \"election\": {\n # Longest time peer waits for stable membership during leader election startup (unit: second)\n \"startupGracePeriod\": \"15s\",\n # Interval gossip membership samples to check its stability (unit: second)\n \"membershipSampleInterval\": \"1s\",\n # Time passes since last declaration message before peer decides to perform leader election (unit: second)\n \"leaderAliveThreshold\": \"10s\",\n # Time between peer sends propose message and declares itself as a leader (sends declaration message) (unit: second)\n \"leaderElectionDuration\": \"5s\"\n },\n \"pvtData\": {\n \"pullRetryThreshold\": \"60s\",\n \"transientstoreMaxBlockRetention\": 1000,\n \"pushAckTimeout\": \"3s\",\n \"btlPullMargin\": 10,\n \"reconcileBatchSize\": 10,\n \"reconcileSleepInterval\": \"1m\",\n \"reconciliationEnabled\": True,\n \"skipPullingInvalidTransactionsDuringCommit\": False,\n },\n \"state\": {\n \"enabled\": True,\n \"checkInterval\": \"10s\",\n \"responseTimeout\": \"3s\",\n \"batchSize\": 10,\n \"blockBufferSize\": 100,\n \"maxRetries\": 3\n },\n },\n \"tls\": {\n \"enabled\": False,\n \"clientAuthRequired\": False,\n \"cert\": {\n \"file\": \"tls/server.crt\",\n },\n \"key\": {\n \"file\": \"tls/server.key\",\n },\n \"rootcert\": {\n \"file\": \"tls/ca.crt\",\n },\n \"clientRootCAs\": {\n \"files\": [\n \"tls/ca.crt\"\n ]\n },\n \"clientKey\": {\n \"file\": None\n },\n \"clientCert\": {\n \"file\": None\n }\n },\n \"authentication\": {\n \"timewindow\": \"15m\"\n },\n \"fileSystemPath\": \"/var/hyperledger/production\",\n \"BCCSP\": {\n \"Default\": \"SW\",\n \"SW\": {\n \"Hash\": \"SHA2\",\n \"Security\": 256,\n \"FileKeyStore\": {\n \"KeyStore\": None,\n },\n },\n \"PKCS11\": {\n \"Library\": None,\n \"Label\": None,\n \"Pin\": None,\n \"Hash\": None,\n \"Security\": None\n }\n },\n \"mspConfigPath\": \"msp\",\n \"localMspId\": \"SampleOrg\",\n \"client\": {\n \"connTimeout\": \"3s\"\n },\n \"deliveryclient\": {\n \"reconnectTotalTimeThreshold\": \"3600s\",\n \"connTimeout\": \"3s\",\n \"reConnectBackoffThreshold\": \"3600s\",\n \"addressOverrides\": None,\n },\n \"localMspType\": \"bccsp\",\n \"profile\": {\n \"enabled\": False,\n \"listenAddress\": \"0.0.0.0:6060\"\n },\n \"handlers\": {\n \"authFilters\": [\n { \"name\": \"DefaultAuth\" },\n { \"name\": \"ExpirationCheck\" },\n ],\n \"decorators\": [\n { \"name\": \"DefaultDecorator\" }\n ],\n \"endorsers\": {\n \"escc\": {\n \"name\": \"DefaultEndorsement\",\n \"library\": None,\n }\n },\n \"validators\": {\n \"vscc\": {\n \"name\": \"DefaultValidation\",\n \"library\": None,\n }\n }\n },\n \"validatorPoolSize\": None,\n \"discovery\": {\n \"enabled\": True,\n \"authCacheEnabled\": True,\n \"authCacheMaxSize\": 1000,\n \"authCachePurgeRetentionRatio\": 0.75,\n \"orgMembersAllowedAccess\": False,\n },\n \"limits\": {\n \"concurrency\": {\n \"qscc\": 5000,\n }\n }\n }\n print(bcolors.OKGREEN + \" [+] Generating Peer Core COMPLETE\")\n\n print(bcolors.WARNING + \" [*] Generating VM Core \")\n vm = {\n \"endpoint\": \"unix:///var/run/docker.sock\",\n \"docker\": {\n \"tls\": {\n \"enabled\": False,\n \"ca\": {\n \"file\": \"docker/ca.crt\",\n },\n \"cert\": {\n \"file\": \"docker/tls.crt\",\n },\n \"key\": {\n \"file\": \"docker/tls.key\",\n },\n },\n \"attachStdout\": False,\n \"hostConfig\": {\n \"NetworkMode\": \"host\",\n \"Dns\": None,\n \"LogConfig\": {\n \"Type\": \"json-file\",\n \"Config\": {\n \"max-size\": DoubleQuotedScalarString(\"50m\"),\n \"max-file\": DoubleQuotedScalarString(\"5\")\n }\n },\n \"Memory\": 2147483648\n }\n }\n }\n\n print(bcolors.OKGREEN + \" [+] Generating VM Core COMPLETE\")\n\n print(bcolors.WARNING + \" [*] Generating Chaincode Core \")\n chaincode = {\n \"id\": {\n \"path\": None,\n \"name\": None,\n },\n \"builder\": \"$(DOCKER_NS)/fabric-ccenv:$(TWO_DIGIT_VERSION)\",\n \"pull\": False,\n \"golang\": {\n \"runtime\": \"$(DOCKER_NS)/fabric-baseos:$(TWO_DIGIT_VERSION)\",\n \"dynamicLink\": False,\n },\n \"java\": {\n \"runtime\": \"$(DOCKER_NS)/fabric-javaenv:$(TWO_DIGIT_VERSION)\",\n },\n \"node\": {\n \"runtime\": \"$(DOCKER_NS)/fabric-nodeenv:$(TWO_DIGIT_VERSION)\",\n },\n \"externalBuilders\": [],\n \"installTimeout\": \"300s\",\n \"startuptimeout\": \"300s\",\n \"executetimeout\": \"30s\",\n \"mode\": \"net\",\n \"keepalive\": 0,\n \"system\": {\n \"_lifecycle\": \"enable\",\n \"cscc\": \"enable\",\n \"lscc\": \"enable\",\n \"escc\": \"enable\",\n \"vscc\": \"enable\",\n \"qscc\": \"enable\",\n },\n \"logging\": {\n \"level\": \"info\",\n \"shim\": \"warning\",\n \"format\": ruamel.yaml.scalarstring.SingleQuotedScalarString('%{color}%{time:2006-01-02 15:04:05.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x}%{color:reset} %{message}')\n }\n }\n\n print(bcolors.OKGREEN + \" [+] Generating Chaincode Core COMPLETE\")\n\n print(bcolors.WARNING + \" [*] Generating Ledger Core \")\n ledger = {\n \"blockchain\": None,\n \"state\": {\n \"stateDatabase\": \"goleveldb\",\n \"totalQueryLimit\": 100000,\n \"couchDBConfig\": {\n \"couchDBAddress\": \"127.0.0.1:5984\",\n \"username\": None,\n \"password\": None,\n \"maxRetries\": 3,\n \"maxRetriesOnStartup\": 12,\n \"requestTimeout\": \"35s\",\n \"internalQueryLimit\": 1000,\n \"maxBatchUpdateSize\": 1000,\n \"warmIndexesAfterNBlocks\": 1,\n \"createGlobalChangesDB\": False,\n \"cacheSize\": 64,\n }\n },\n \"history\": {\n \"enableHistoryDatabase\": True,\n },\n \"pvtdataStore\": {\n \"collElgProcMaxDbBatchSize\": 5000,\n \"collElgProcDbBatchesInterval\": 1000\n }\n\n }\n\n print(bcolors.OKGREEN + \" [+] Generating Ledger Core COMPLETE\")\n print(bcolors.WARNING + \" [*] Generating Operations Core \")\n operations = {\n \"listenAddress\": \"127.0.0.1:9443\",\n \"tls\": {\n \"enabled\": False,\n \"cert\": {\n \"file\": None,\n },\n \"key\": {\n \"file\": None,\n },\n \"clientAuthRequired\": False,\n \"clientRootCAs\": {\n \"files\": []\n }\n }\n }\n print(bcolors.OKGREEN + \" [+] Generating Operations Core COMPLETE\")\n print(bcolors.WARNING + \" [*] Generating Metrics Core \")\n\n metrics = {\n \"provider\": \"disabled\",\n \"statsd\": {\n \"network\": \"udp\",\n \"address\": \"127.0.0.1:8125\",\n \"writeInterval\": \"10s\",\n \"prefix\": None\n }\n }\n print(bcolors.OKGREEN + \" [*] Generating Metrics Core COMPLETE\")\n\n print(bcolors.OKBLUE + \"======= Generating final Structure =======\")\n final = {\n \"peer\": peer,\n \"vm\": vm,\n \"chaincode\": chaincode,\n \"ledger\": ledger,\n \"operations\": operations,\n \"metrics\": metrics\n }\n\n # yaml_new.dump(final, sys.stdout)\n f = open(\"core.yaml\", \"w\")\n yaml_new.dump(final, f)\n print(bcolors.HEADER + \"========================================\")\n print(\">>> core.yaml has been dumped!\")\n print(\"========================================\")\n\n\ndef create_connection_profile(_peers, _orgs, _orderers, _domain):\n new_yaml = ruamel.yaml.YAML()\n orderer_list = [\"orderer{}.{}\".format(i+1, _domain) for i in range(_orderers)]\n print(bcolors.WARNING + \"[*] Creating Connection Profile\")\n peer_list = {}\n print(bcolors.WARNING + \" [*] Create Peer List\")\n for peer in range(_peers):\n for org in range(_orgs):\n peer_list.update({\"peer{}.org{}.{}\".format(peer, org+1, _domain): {\n \"endorsingPeer\": True,\n \"chaincodeQuery\": True,\n \"ledgerQuery\": True,\n \"eventSource\": True,\n }})\n print(bcolors.OKGREEN + \" [+] Peer List COMPLETE\")\n print(bcolors.WARNING + \" [*] Create Channel List\")\n\n channels = {\n \"mychannel\": {\n \"orderers\": orderer_list,\n \"peers\": peer_list\n }\n }\n print(bcolors.OKGREEN + \" [+] Channel List COMPLETE\")\n print(bcolors.WARNING + \" [*] Create Organization List\")\n organiz = {}\n for org in range(_orgs):\n peers_ls = [\"peer{}.org{}.{}\".format(i, org+1, _domain) for i in range(_peers)]\n organiz.update({\"Org{}\".format(org+1): {\n \"mspid\": \"Org{}MSP\".format(org+1),\n \"peers\": peers_ls,\n \"certificateAuthorities\": [\n \"ca.org{}.{}\".format(org+1, _domain)\n ]\n }})\n print(bcolors.OKGREEN + \" [+] Organization List COMPLETE\")\n print(bcolors.WARNING + \" [*] Create Orderer List\")\n\n ordes = {}\n i = 0\n for orderer in orderer_list:\n ordes.update({\n orderer: {\n \"url\": \"grpc://localhost:{}\".format(orderer_defport+1000*i),\n \"grpcOptions\": {\n \"ssl-target-name-override\": orderer\n }\n }\n })\n i += 1\n print(bcolors.OKGREEN + \" [+] Orderer List COMPLETE\")\n print(bcolors.WARNING + \" [*] Create Detail Peer List\")\n\n peer_ls = {}\n for peer in range(_peers):\n for org in range(_orgs):\n peer_ls.update({\"peer{}.org{}.{}\".format(peer, org+1, _domain): {\n \"url\": \"grpc://localhost:{}\".format(peer_defport + 1000 * ((_peers * org) + peer), peer_defport),\n \"grpcOptions\": {\n \"ssl-target-name-override\": \"peer{}.org{}.{}\".format(peer, org+1, _domain),\n \"request-timeout\": 120001\n }\n }})\n print(bcolors.OKGREEN + \" [+] Detail Peer List COMPLETE\")\n print(bcolors.WARNING + \" [*] Create Detail CA List\")\n\n ca_ls = {}\n i = 0\n for org in range(_orgs):\n ca_ls.update({\n \"ca.org{}.{}\".format(org+1, _domain): {\n \"url\": \"http://localhost:{}\".format(ca_defport+1000*i),\n \"httpOptions\": {\n \"verify\": False,\n },\n \"registrar\": [\n {\n \"enrollId\": \"admin\",\n \"enrollSecret\": \"adminpw\"\n }\n ],\n \"caName\": \"ca.org{}.{}\".format(org+1, _domain)\n }\n })\n i += 1\n print(bcolors.OKGREEN + \" [+] Detail CA List COMPLETE\")\n print(bcolors.OKBLUE + \"======= Generating final Structure =======\")\n\n final = {\n \"name\": DoubleQuotedScalarString(\"{}-peer.{}-org.{}-orderers.{}\".format(_peers, _orgs, _orderers, _domain)),\n \"x-type\": DoubleQuotedScalarString(\"hlfv2\"),\n \"description\": DoubleQuotedScalarString(\"Connection profile\"),\n \"version\": DoubleQuotedScalarString(\"1.0\"),\n \"channels\": channels,\n \"organizations\": organiz,\n \"orderers\": ordes,\n \"peers\": peer_ls,\n \"certificateAuthorities\": ca_ls\n }\n print(bcolors.OKBLUE + \"======= Final Structure COMPLETE =======\")\n\n f = open(\"connection_profile.yaml\", \"w\")\n new_yaml.dump(final, f)\n f.close()\n print(bcolors.OKGREEN + \"[+] Connection Profile Created\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Automated Hyperledger Fabic Network Generator.\")\n parser.add_argument('-o', dest=\"orderers\", default=4, type=int, help='Number of Orderers ')\n parser.add_argument('-O', dest=\"orgs\", default=2, type=int, help='Number of Organizations ')\n parser.add_argument('-p', dest=\"peers\", default=2, type=int, help='Number of Peers per Organization ')\n parser.add_argument('-k', dest=\"kafka\", default=4, type=int, help='Number of Kafka Brokers ')\n parser.add_argument('-d', dest=\"domain\", default=\"dredev.de\", type=str, help='The Domain that will be used')\n parser.add_argument('-c', dest=\"consortium\", default=\"WebConsortium\", type=str,\n help='The Consortium that will be used')\n parser.add_argument('-bs', dest=\"blocksize\", default=10, type=int, help='The max amount of transactions per block')\n parser.add_argument('-t', dest=\"timeout\", default=1, type=int, help='The timeout value in seconds until a block gets committed, if it is not filled to its blocksize')\n args = parser.parse_args()\n compose_name = \"net\"\n try:\n f = open(\"docker-compose.yaml\")\n f.close()\n print(\"What have we got over here? A lonely Docker compose file. Lets stop it!\")\n os.system(\"docker-compose down --volumes --remove-orphans\")\n os.system(\"docker container rm $(docker container ls -a | grep dev-peer)\")\n os.system(\"docker images -a | grep 'dev-peer' | awk '{print $3}' | xargs docker rmi\")\n # Do something with the file\n except IOError:\n pass\n\n print(bcolors.FAIL + \">>> Alright, now let's go! <<< \")\n generate_chaincode_entries()\n print(bcolors.HEADER + \">>> First we need to create a file called '.env'. It includes a Variable for the docker-compose file\")\n generate_env(compose_name)\n print(bcolors.HEADER + \">>> Ok that's done. Now lets create the Crypto Config File!\")\n generate_crypto_config(_peers=args.peers,\n _domain=args.domain,\n _orderers=args.orderers,\n _orgs=args.orgs)\n print(bcolors.HEADER + \">>> Crypto Config has been created. Now lets create the config file for the transactions!\")\n generate_configtx(_orgs=args.orgs,\n _orderers=args.orderers,\n _domain=args.domain,\n _kafka_brokers=args.kafka,\n _consortium=args.consortium,\n _blocksize=args.blocksize,\n _timeout=args.timeout)\n print(bcolors.HEADER + \">>> config.tx has been created. Now generate the Docker-compose file.\")\n generate_docker_compose(_orderers=args.orderers,\n _orgs=args.orgs,\n _peers=args.peers,\n _domain=args.domain,\n _kafka=args.kafka)\n print(bcolors.HEADER + \">>> docker-compose.yaml has been created. Now finally generate the core.yaml file.\")\n generate_core()\n print(bcolors.HEADER + \">>> core.yaml has been created.\")\n create_connection_profile(_peers=args.peers,\n _orgs=args.orgs,\n _orderers=args.orderers,\n _domain=args.domain)\n print(bcolors.HEADER + \">>> All done, you can proceed with Merlin! Bye\")\n # Setting some Env Variable\n os.environ[\"NO_ORDERERS\"] = str(args.orderers)\n os.environ[\"NO_ORGANIZATIONS\"] = str(args.orgs)\n os.environ[\"NO_PEERS\"] = str(args.peers)\n os.environ[\"DOMAIN\"] = args.domain\n os.environ[\"NO_KAFKA\"] = str(args.kafka)\n os.environ[\"CONSORTIUM_NAME\"] = args.consortium\n\n env_str = \"export NO_ORDERERS=\"+str(args.orderers) + \"\\n\"\n env_str += \"export ORDERERS=\\\"\"+str(os.environ[\"ORDERERS\"]) + \"\\\"\\n\"\n env_str += \"export PEER_CON_PARAMS=\\\"\"+str(os.environ[\"PEER_CON_PARAMS\"]) + \"\\\"\\n\"\n env_str += \"export NO_PEERS=\" + str(args.peers) + \"\\n\"\n env_str += \"export NO_ORGANIZATIONS=\" + str(args.orgs) + \"\\n\"\n env_str += \"export NO_PEERS=\" + str(args.peers) + \"\\n\"\n env_str += \"export DOMAIN=\" + str(args.domain) + \"\\n\"\n env_str += \"export NO_KAFKA=\" + str(args.kafka) + \"\\n\"\n env_str += \"export CONSORTIUM_NAME=\" + str(args.consortium) + \"\\n\"\n\n y = input(bcolors.FAIL + \"Start Merlin now? [y/n]\")\n if y == \"y\":\n out = input(bcolors.FAIL + \"Do you want Debug output? [y/n]\")\n if out == \"n\":\n os.environ[\"OUTPUTDEV\"] = \"/dev/null\"\n env_str += \"export OUTPUTDEV=/dev/null\\n\"\n os.system(env_str + \" bash merlin.sh\")\n else:\n print(bcolors.HEADER + \"Alright, Quitting\")\n\n","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":48478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"287363659","text":"import sqlite3\n\nfrom sqlite3 import Error\n\n\ndef dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\n\nclass SqliteHelper:\n\n def __init__(self, file):\n self.__file = file\n self.__conn = None\n\n def connect(self):\n try:\n self.__conn = sqlite3.connect(self.__file)\n self.__conn.row_factory = dict_factory\n print(\"Connection is established: Sqlite Database is created \")\n return self.__conn\n except Error:\n print(Error)\n\n def execute(self, sql):\n cursorobj = self.__conn.cursor()\n cursorobj.execute(sql)\n self.__conn.commit()\n cursorobj.close()\n\n def fetch(self, sql):\n cursorobj = self.__conn.cursor()\n cursorobj.execute(sql)\n rows = cursorobj.fetchall()\n cursorobj.close()\n return rows\n\n def close(self):\n if self.__conn is not None:\n self.__conn.close()\n","sub_path":"thingsboard_gateway/db_access/sqlite_helper.py","file_name":"sqlite_helper.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"142192028","text":"a=input(\"请输入:\")\ndx=0#大写\nxx=0#小写\nhz=0#汉字\nsz=0#数字\nqt=0#其他\nfor i in range(len(a)):\n if \"A\"<=a[i]<=\"Z\":\n dx += 1\n elif 'a'<=a[i]<='z':\n xx += 1\n elif 0x4E00<=ord(a[i])<=0x9FA5:\n hz += 1\n elif ord('0')<=ord(a[i])<=ord('9'):\n sz += 1\n else:\n qt += 1\nprint(\"大写英文字符:{}\\n小写英文字符:{}\\n中文字符:{}\\n数字字符:{}\\n其他字符:{}\".format(dx,xx,hz,sz,qt))","sub_path":"统计字符个数.py","file_name":"统计字符个数.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"499352529","text":"import cv2\nimport numpy as np\n\nimage = cv2.imread('images/gradient.jpg',0)\ncv2.imshow('Original', image)\n\nret,thresh1 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)\ncv2.imshow('1 Threshold Binary', thresh1)\n\nret,thresh2 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)\ncv2.imshow('2 Threshold Binary Inverse', thresh2)\n\nret,thresh3 = cv2.threshold(image, 127, 255, cv2.THRESH_TRUNC)\ncv2.imshow('3 THRESH TRUNC', thresh3)\n\nret,thresh4 = cv2.threshold(image, 127, 255, cv2.THRESH_TOZERO)\ncv2.imshow('4 THRESH TOZERO', thresh4)\n\nret,thresh5 = cv2.threshold(image, 127, 255, cv2.THRESH_TOZERO_INV)\ncv2.imshow('5 THRESH TOZERO INV', thresh5)\n\n#adaptive thresholding\n\n#Load our new image\nimage = cv2.imread('images/Origin_of_Species.jpg', 0)\nimage = cv2.GaussianBlur(image, (3, 3), 0)\n\nthresh = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, \n cv2.THRESH_BINARY, 3, 5) \ncv2.imshow(\"Adaptive Mean Thresholding\", thresh) \n\n_, th2 = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\ncv2.imshow(\"Otsu's Thresholding\", thresh) \n\nblur = cv2.GaussianBlur(image, (5,5), 0)\n_, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\ncv2.imshow(\"Guassian Otsu's Thresholding\", thresh) \n\ncv2.waitKey(0) \ncv2.destroyAllWindows()","sub_path":"thresholding_binarization.py","file_name":"thresholding_binarization.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"612038773","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom collections import OrderedDict\r\n#分区资料\r\ndma_file = OrderedDict()\r\n\r\ndma_file['zone_name']={'value':'somecity','name':'分区名称','note':''}\r\ndma_file['zone_area']={'value':'1000','name':'分区面积(平方公里)','note':''}\r\ndma_file['zone_water_in']={'value':14490,'name':'分区进水量( m3)','note':''}\r\ndma_file['registed_user']={'value':10000,'name':'注册用户总数(万户)','note':''}\r\ndma_file['pipeline_length']={'value':2000,'name':'管线长度( km)','note':''}\r\ndma_file['sub_zone_num']={'value':10,'name':'下一级分区数量(个)','note':''}\r\ndma_file['dma_num']={'value':20,'name':'分区中 DMA 数量(个)','note':''}\r\ndma_file['measure_per_actual']={'value':89,'name':'水表抄见率( %)','note':'抄表数量与实际立户水表数量一致程度'}\r\ndma_file['measure_precision']={'value':95,'name':'抄表准确率( %)','note':''}\r\ndma_file['zone_sale']={'value':12345,'name':'分区销售水量( m3)','note':'该分区销售水量'}\r\ndma_file['nightflow_min']={'value':2000,'name':'夜间最小流量( m3)','note':'仅适用于 DMA'}\r\ndma_file['online_presspoint_num']={'value':10,'name':'在线压力点数量(个)','note':''}\r\ndma_file['online_flowmeter_num']={'value':20,'name':'在线流量计数量(个)','note':''}\r\ndma_file['online_water_quality_m_num']={'value':30,'name':'在线水质监测点数量(个)','note':''}\r\ndma_file['charge_watermeter_num']={'value':1000,'name':'收费用远传水表数量(只)','note':''}\r\ndma_file['charge_waterwater_percent']={'value':70,'name':'收费用远传水表水量占分区销 水量比( %)','note':''}\r\ndma_file['zone_detect_leak_num']={'value':5,'name':'分区探出漏点总数(个)','note':''}\r\ndma_file['leak_water']={'value':100,'name':'漏失水量( m3)','note':''}\r\ndma_file['leak_obscur_water']={'value':30,'name':'暗漏水量( m3)','note':''}\r\ndma_file['leak_obvious_water']={'value':70,'name':'明漏水量( m3)','note':''}\r\ndma_file['leak_rate']={'value':12,'name':'漏损率( %)','note':''}\r\ndma_file['pressure_quality']={'value':90,'name':'压力合格率( %)','note':''}\r\ndma_file['water_quality']={'value':99,'name':'水质合格率( %)','note':''}\r\ndma_file['zone_inner_pressure']={'value':30,'name':'分区内压力( MPa)','note':''}\r\n\r\n#汇总资料\r\nsummary_file = OrderedDict()\r\nsummary_file['totol_water_yearly']={'value':10000,'name':'年供水总量(万 m3)','note':''}\r\nsummary_file['registed_user_use_water_yearly']={'value':1000,'name':'年注册用户用水量(万 m3)','note':''}\r\nsummary_file['leak_obvious_water']={'value':14490,'name':'明漏水量(万 m3)','note':''}\r\nsummary_file['leak_obscur_water']={'value':10000,'name':'暗漏水量(万 m3)','note':''}\r\nsummary_file['background_leak_water']={'value':2000,'name':'背景漏失水量(万 m3)','note':''}\r\nsummary_file['box_sank_leak']={'value':10,'name':'水箱、水池的渗漏和溢流水量 (万 m3)','note':''}\r\nsummary_file['resident_loss_distant']={'value':20,'name':'居民用户总分表差损失水量(万 m3)','note':''}\r\nsummary_file['no_resident_loss_distant']={'value':89,'name':'非居民用户表具误差损失水量(万m3)','note':''}\r\nsummary_file['measure_read_resident_use']={'value':95,'name':'抄表到户居民用户用水量(万 m3)','note':''}\r\nsummary_file['average_press_out']={'value':12345,'name':'年平均出厂压力( MPa)','note':''}\r\nsummary_file['max_frozone_depth']={'value':2000,'name':'最大冻土深度( m)','note':''}\r\nsummary_file['pipenet_length']={'value':10,'name':'管网长度( km)','note':''}\r\nsummary_file['pipenet_distribute_level']={'value':20,'name':'管网分区计量级别数','note':''}\r\nsummary_file['distribute_num_1']={'value':30,'name':'一级分区数量(个)','note':''}\r\nsummary_file['distribute_cover_water_1']={'value':1000,'name':'一级分区覆盖水量(万 m3)','note':''}\r\nsummary_file['distribute_cover_pipeline_1']={'value':70,'name':'一级分区覆盖管网长度( km)','note':''}\r\nsummary_file['distribute_num_2']={'value':30,'name':'二级分区数量(个)','note':''}\r\nsummary_file['distribute_cover_water_2']={'value':1000,'name':'二级分区覆盖水量(万 m3)','note':''}\r\nsummary_file['distribute_cover_pipeline_2']={'value':70,'name':'二级分区覆盖管网长度( km)','note':''}\r\nsummary_file['distribute_num_n']={'value':30,'name':'N级分区数量(个)','note':''}\r\nsummary_file['distribute_cover_water_n']={'value':1000,'name':'N级分区覆盖水量(万 m3)','note':''}\r\nsummary_file['distribute_cover_pipeline_n']={'value':70,'name':'N级分区覆盖管网长度( km)','note':''}\r\nsummary_file['pipenet_press_qulity']={'value':5,'name':'管网压力合格率','note':''}\r\nsummary_file['pipenet_water_qulity']={'value':100,'name':'管网水质合格率','note':''}\r\nsummary_file['service_content_rate']={'value':30,'name':'用户服务综合满意率','note':''}\r\nsummary_file['pipeline_leak_rate']={'value':70,'name':'管网漏损率','note':''}\r\nsummary_file['measure_read_rate']={'value':12,'name':'水表抄见率( %)','note':''}\r\nsummary_file['measure_right_rate']={'value':90,'name':'抄表准确率( %)','note':''}\r\nsummary_file['online_presspoint_num']={'value':99,'name':'在线压力点数量(个)','note':''}\r\nsummary_file['online_flow_calc_num']={'value':30,'name':'在线流量计数量(个)','note':''}\r\nsummary_file['online_water_quality_m_num']={'value':12,'name':'在线水质监测点数量(个)','note':''}\r\nsummary_file['charge_remote_water_num']={'value':90,'name':'收费用远传水表数量(只)','note':''}\r\nsummary_file['charge_remote_water_percent']={'value':99,'name':'收费用远传水表水量占销售水量比( %)','note':''}\r\nsummary_file['detect_leak_num']={'value':30,'name':'探出漏点总数(个)','note':''}\r\nsummary_file['water_leakloss']={'value':30,'name':'漏失水量(万 m3)','note':''}\r\nsummary_file['leak_rate']={'value':12,'name':'漏损率( %)','note':''}\r\nsummary_file['pressure_quality']={'value':90,'name':'压力合格率( %)','note':''}\r\nsummary_file['water_quality']={'value':99,'name':'水质合格率( %)','note':''}\r\nsummary_file['distribute_pressure']={'value':30,'name':'压力( MPa)','note':''}\r\nsummary_file['economic_invest']={'value':12,'name':'经济投入','note':''}\r\nsummary_file['economic_benefit']={'value':90,'name':'经济效益','note':''}\r\nsummary_file['socity_benefit']={'value':99,'name':'社会效益','note':''}\r\n\r\nstatic_monthly = OrderedDict() \r\nstatic_monthly['total_in']={'name':'1、供水总量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['provid_self']={'name':' 其中:1.1 自产供水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['provid_out']={'name':' 1.2 外购供水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['register_resident_use']={'name':'2、注册用户用水量(有效供水量)','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['charge_water']={'name':'2.1 计费用水量(售水量)','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['charge_measure_water']={'name':'2.1.1 计费计量用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['resisent_use']={'name':'2.1.1.1 居民用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['measure_read_resident_use']={'name':'其中:抄表到户的居民用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['no_measure_read_resident_use']={'name':'未抄表到户的居民用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['no_resident_use']={'name':'2.1.1.2 非居民用水量(含特殊行业)','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['high_precise_meter_use']={'name':'其中:高精度水表用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['other_meter_use']={'name':'其他类型水表用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['uncharge_unmeter_use']={'name':'2.1.2 计费未计量用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['new_pipeline_wash']={'name':'其中:新建管线冲洗水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['pipeline_rebuild_use']={'name':'管网改造冲洗水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['urgent_vihicle_use']={'name':'应急供水车水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['project_leak']={'name':'工程漏水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['free_use']={'name':'2.2免费用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['free_measure_use']={'name':'2.2.1免费计量用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['free_unmeasure_use']={'name':'2.2.2免费未计量用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['fireproof_use']={'name':'其中消防用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['new_pipeline_wash_2']={'name':'新建管线冲洗水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['pipeline_rebuild_use_2']={'name':'管网改造冲洗水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['pipenet_maintain_use']={'name':'管网维护用水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['leakloss']={'name':'3、漏损水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['leak_rate']={'name':'漏损率(%)','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['produce_loss']={'name':'4、产销差水量','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\nstatic_monthly['produce_loss_rate']={'name':'产销差率','last_month_total':'','cur_month':'','cur_month_total':'','note':''}\r\n\r\ndef generet_static():\r\n import random\r\n\r\n for key , item in static_monthly.items():\r\n item['last_month_total'] = random.randint(10000,20000)\r\n item['cur_month'] = random.randint(9000,18000)\r\n item['cur_month_total'] = random.randint(11000,22000)\r\n\r\n return static_monthly\r\n\r\ndma_tree = [\r\n {\r\n 'text':'深圳市',\r\n 'href':'#',\r\n 'nodes':[\r\n {\r\n 'text':'南山区',\r\n 'href':'/sub_dma/南山区',\r\n 'nodes':[\r\n {\r\n 'text':'西丽',\r\n 'href':'/sub_dma/南山区/西丽',\r\n 'nodes':[\r\n {\r\n 'text':'asdf',\r\n 'href':'/sub_dma/南山区/西丽',\r\n 'nodes':[\r\n \r\n ]\r\n },\r\n {\r\n 'text':'蛇口12',\r\n 'href':'/sub_dma/南山区/蛇口12',\r\n 'nodes':[]\r\n },\r\n {\r\n 'text':'桃源12',\r\n 'href':'/sub_dma/南山区/桃源12',\r\n 'nodes':[]\r\n },\r\n ]\r\n },\r\n {\r\n 'text':'蛇口',\r\n 'href':'/sub_dma/南山区/蛇口',\r\n 'nodes':[]\r\n },\r\n {\r\n 'text':'桃源',\r\n 'href':'/sub_dma/南山区/桃源',\r\n 'nodes':[]\r\n },\r\n ]\r\n },\r\n {\r\n 'text':'福田区',\r\n 'href':'/sub_dma/福田区',\r\n 'nodes':[]\r\n },\r\n {\r\n 'text':'罗湖区',\r\n 'href':'/sub_dma/罗湖区',\r\n 'nodes':[]\r\n },\r\n {\r\n 'text':'宝安区',\r\n 'href':'/sub_dma/宝安区',\r\n 'nodes':[]\r\n },\r\n {\r\n 'text':'龙华区',\r\n 'href':'/sub_dma/龙华区',\r\n 'nodes':[]\r\n },\r\n {\r\n 'text':'盐田区',\r\n 'href':'/sub_dma/盐田区',\r\n 'nodes':[]\r\n },\r\n {\r\n 'text':'坪山区',\r\n 'href':'/sub_dma/坪山区',\r\n 'nodes':[]\r\n }\r\n ]\r\n },\r\n {\r\n 'text': '汇总资料',\r\n 'href': \"/dma_summary/\",\r\n 'tags': ['0']\r\n },\r\n]\r\n\r\n#1.漏损率的计算 漏损率是指由供水总量和注册用户用水量直接计算出来的漏损率\r\n#R_wl = (Qs-Qa)/Qs x 100% (1)#R_wl——漏损率( %);Qs ——供水总量(万 m3);Qa ——注册用户用水量(万 m3)。\r\n# 1)居民抄表到户水量的修正值 R1 :R1 = 0.08r x 100% (2) R1 ——居民抄表到户水量的修正值( %);r ——居民抄表到户水量占总供水量比例;0.08 ——居民用户总分表差率。\r\n# 2)单位供水量管长的修正值 R2 应按公式( 3)( 4)计算\r\n# R2 = 0.99(A-0.0693)x 100% (3)\r\n# A = L/Qs (4)\r\n# R2 ——单位供水量管长的修正值( %)\r\n# A ——单位供水量管长( km/万 m3);\r\n#0.99 ——单位供水量管长对漏损率的影响系数;\r\n#0.0693 ——常数( km/万 m3),代表单位供水量管长的基准值\r\n#L —— DN75(含)以上管道长度( km)\r\n#当 R2 值大于 3%时,应取 3%;当 R2 值小于-3%时,应取-3%\r\n# 3)年平均出厂压力大于 0.35MPa 小于等于 0.55MPa 时,\r\n#修正值 R3 应为 0.5%;年平均出厂压力大于 0.55MPa 小于等\r\n#于 0.75MPa 时,修正值 R3 应为 1%;年平均出厂压力大于\r\n#0.75MPa 时,修正值 R3 应为 2%。\r\n# 4)最大冻土深度大于 1.4m 时,修正值 R4 应为 1%;最\r\n#大冻土深度小于 1.4m 时, R4=0。\r\n#( 5)供水单位的基本漏损率 R_wln=R_wl - R1 - R2 - R3 - R4 \r\n\r\ndef leak_rate(Qs,Qa,r,L,p,d):\r\n '''\r\n Qs:供水总量(万 m3)\r\n Qa:注册用户用水量(万 m3)\r\n r:居民抄表到户水量占总供水量比例\r\n L:DN75(含)以上管道长度( km)\r\n p:年平均出厂压力\r\n d:最大冻土深度\r\n '''\r\n R_wl = (Qs-Qa)/Qs * 100\r\n R1 = 0.08*r * 100\r\n A = L/Qs\r\n R2 = 0.09*(A - 0.0693)*100\r\n if R2 > 0.03:\r\n R2 = 0.03\r\n if R2 < -0.03:\r\n R2 = -0.03\r\n R3 = 0\r\n if p > 0.35 and p <= 0.55:\r\n R3 = 0.005\r\n elif p > 0.55 and p < 0.75:\r\n R3 = 0.01\r\n elif p > 0.75:\r\n R3 = 0.02\r\n R4 = 0\r\n if d > 1.4:\r\n R4 = 0.01\r\n if d <= 1.4:\r\n R4 = 0\r\n R_wln = R_wl - R1 - R2 - R3 - R4\r\n \r\n return R_wln\r\n \r\n''' 节能潜力分析\r\n计算供水综合单位电耗G=105/367η[KWh/(km3•MPa)],当G>350kWh/(m3•MPa)时,η<77.85%时,泵站需要开展节能降耗工作。\r\n'''\r\n\r\n'''\r\n1.1.2.3 降漏潜力分析\r\n计算供水企业管网基本漏损情况。\r\n1)城市供水企业管网基本漏损率不应大于12%。\r\n2)抄表到户水平修正。当居民用水按户抄表的水量大于70%时,漏损率应增加1%\r\n3)单位供水量管长修正。\r\n供水管径 DN 单位供水量管长 修正值 \r\n≥75 <1.4km/km3/d 减2% \r\n≥75 ≥1.40km/km3/d,≤1.64km/km3/d 减1% \r\n≥75 ≥2.06km/km3/d,≤2.40km/km3/d 加1% \r\n≥75 ≥2.41km/km3/d,≤2.70km/km3/d 加2% \r\n≥75 ≥2.70km/km3/d 加3% \r\n\r\n'''\r\n\r\n'''\r\n常用的漏损评价的指标主要有:\r\n(1)漏失率(%)=Q漏失量/Q供水量;\r\n(2)产销差率(%)=( Q供水量- Q售水量)/ Q供水量;\r\n(3)单位管长漏失量(m³/km/h)= Q漏失量/∑L配水管总长;\r\n(4)基础设施漏失指数(ILI)=当前物理损失水量/不可避免物理损失水量。\r\n不可避免物理损失水量(L/d)=(18•Lm+0.8•Nc+25•Lp)•P \r\n式中——Lm:主干管长度(Km); Nc:接户数;Lp:用户连接管总长度(Km); P:管网平均压力(m)。\r\n\r\n'''","sub_path":"dma/dmadata.py","file_name":"dmadata.py","file_ext":"py","file_size_in_byte":16986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"89"} +{"seq_id":"474182753","text":"# -*- coding: utf-8 -*-\n\"\"\"\n IRIS CASE 00_TRAIN\n\n@author: Ratarca\ngithub: CavalcanteRafael\nlinkedin :rafael-cavalcante-4b58b2100\n\"\"\"\n\npath = \"C:/Users/Rafael/Desktop/IRIS/Source_Data/\"\nfile = \"Iris.csv\"\n\nimport pandas as pd\nimport numpy as np\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\ndf_import = pd.read_csv(path + file)\n\ndf = df_import.drop([\"Id\"],axis = 1)\n\n#Check data set to understand problem\n\nname_columns = df.columns\nstat_table = df.describe()\n\nnulls = df.isnull()\nsum_nulls = nulls.sum()\n\ncorr_table = df.corr()\ncov_table = df.cov()\n\nlist_begginer_bescribe = [name_columns , stat_table , sum_nulls]\n\n\n#To print basic things\nfor i in list_begginer_bescribe:\n print(i,\"\\n\")\n\n#detect outliers\n\n###@@@@###EDA : maximum:\n maximum = len(s.intersection(intersect_with))\n argmax = s\n return argmax\n \n\ndef greedy_set_cover(universe, sets):\n covered = set()\n to_cover = universe.copy()\n set_cover = []\n costs = {}\n \n while covered != universe:\n greedy_set = argmax_sets(sets, to_cover)\n intersected_set = greedy_set.intersection(to_cover)\n set_cardinality = len(intersected_set)\n \n cost = 1 / set_cardinality\n for s in intersected_set:\n costs[str(s)] = cost\n \n covered = covered.union(greedy_set)\n to_cover = to_cover.difference(greedy_set)\n set_cover.append(greedy_set)\n \n print(greedy_set)\n print(cost)\n print(covered)\n print(to_cover)\n print()\n \n print(costs)\n print()\n return set_cover\n\nuniverse = set([i for i in range(1, 11)])\nsets = [\n set([1,2,3,7,9]),\n set([4,5,6,8,10]),\n set([1,2,3,4,5,6]),\n set([7,8]),\n set([9,10])\n]\nprint(greedy_set_cover(universe, sets))","sub_path":"Algorithmen/set_cover.py","file_name":"set_cover.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"227232082","text":"# spinn front end common imports\nfrom spinn_front_end_common.utility_models.live_packet_gather \\\n import LivePacketGather\nfrom spinn_front_end_common.utility_models.live_packet_gather_machine_vertex \\\n import LivePacketGatherMachineVertex\n\n# pacman imports\nfrom pacman.model.graphs.common import Slice\nfrom pacman.model.constraints.placer_constraints\\\n import ChipAndCoreConstraint\n\nfrom spinn_utilities.progress_bar import ProgressBar\n\nfrom collections import defaultdict\n\n\nclass InsertLivePacketGatherersToGraphs(object):\n \"\"\" function to add LPG's as required into a given graph\n \"\"\"\n\n def __call__(\n self, live_packet_gatherer_parameters, machine, machine_graph,\n application_graph=None, graph_mapper=None):\n \"\"\" call that adds LPG vertices on Ethernet connected chips as\\\n required.\n\n :param live_packet_gatherer_parameters:\\\n the Live Packet Gatherer parameters requested by the script\n :param machine: the spinnaker machine as discovered\n :param application_graph: the application graph\n :param machine_graph: the machine graph\n :return: mapping between LPG params and LPG vertex\n \"\"\"\n\n # create progress bar\n progress = ProgressBar(\n machine.ethernet_connected_chips,\n string_describing_what_being_progressed=(\n \"Adding Live Packet Gatherers to Graph\"))\n\n # Keep track of the vertices added by parameters and board address\n lpg_params_to_vertices = defaultdict(dict)\n\n # for every Ethernet connected chip, add the gatherers required\n for chip in progress.over(machine.ethernet_connected_chips):\n for lpg_params in live_packet_gatherer_parameters:\n if (lpg_params.board_address is None or\n lpg_params.board_address == chip.ip_address):\n lpg_params_to_vertices[lpg_params][chip.x, chip.y] = \\\n self._add_lpg_vertex(application_graph, graph_mapper,\n machine_graph, chip, lpg_params)\n\n return lpg_params_to_vertices\n\n def _add_lpg_vertex(self, app_graph, mapper, m_graph, chip, lpg_params):\n if app_graph is not None:\n vtx_slice = Slice(0, 0)\n app_vtx = self._create_vertex(LivePacketGather, lpg_params)\n app_graph.add_vertex(app_vtx)\n resources_required = app_vtx.get_resources_used_by_atoms(\n vtx_slice)\n m_vtx = app_vtx.create_machine_vertex(\n vtx_slice, resources_required)\n mapper.add_vertex_mapping(m_vtx, vtx_slice, app_vtx)\n else:\n m_vtx = self._create_vertex(\n LivePacketGatherMachineVertex, lpg_params)\n\n m_vtx.add_constraint(ChipAndCoreConstraint(x=chip.x, y=chip.y))\n m_graph.add_vertex(m_vtx)\n return m_vtx\n\n @staticmethod\n def _create_vertex(lpg_vertex_class, params):\n \"\"\" Creates a Live Packet Gather Vertex\n\n :param lpg_vertex_class: the type to create for the vertex\n :param params: the params of the vertex\n :return the vertex built\n \"\"\"\n return lpg_vertex_class(\n label=params.label,\n hostname=params.hostname,\n port=params.port,\n tag=params.tag,\n board_address=params.board_address,\n strip_sdp=params.strip_sdp,\n use_prefix=params.use_prefix,\n key_prefix=params.key_prefix,\n prefix_type=params.prefix_type,\n message_type=params.message_type,\n right_shift=params.right_shift,\n payload_as_time_stamps=params.payload_as_time_stamps,\n use_payload_prefix=params.use_payload_prefix,\n payload_prefix=params.payload_prefix,\n payload_right_shift=params.payload_right_shift,\n number_of_packets_sent_per_time_step=(\n params.number_of_packets_sent_per_time_step))\n","sub_path":"spinn_front_end_common/interface/interface_functions/insert_live_packet_gatherers_to_graphs.py","file_name":"insert_live_packet_gatherers_to_graphs.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"63703153","text":"import re\nimport string\nfrom collections import defaultdict\n\n\nclass Script(object):\n \"\"\" Object representation of a movie's screenplay \"\"\"\n\n def __init__(self, **settings):\n \"\"\" Configure script based on text patterns\n\n Set regex to parse scene and dialog patterns and also\n prep script class variables for storing text once\n the script is parsed.\n\n :param settings: (dict) script configuration parameters\n to set as instance variables.\n \"\"\"\n self.script_skeleton = []\n self.text = []\n\n self.scenes = []\n self.scene_regex = settings.get('scene_regex')\n\n self.character_dialog = defaultdict(list)\n self.dialog_regex = settings.get('dialog_regex')\n\n self.notes = []\n\n def load_from_file(self, path, line_divider='\\n\\n'):\n \"\"\" Load the script from a file\n\n Load the text of the file specified by 'path', and split them\n into an array of lines using 'line_divider'.\n\n :param path: (str) path to the script plaintext file to read.\n :param line_divider: (str: default \"\\n\\n\") line divider character(s),\n used to split the file into lines.\n \"\"\"\n with open(path, 'rU') as inf:\n self.text = [l.strip() for l in inf.read().split(line_divider)]\n\n def parse(self):\n \"\"\" Parse the script into sets of tokens\n\n After loading the script, parse lines into the appropriate type (dialog,\n scene notes, settings), tokenize, and store them so they can be retrieved\n by the appropriate markov generator.\n \"\"\"\n scene_counter = 1\n scene_setting = re.compile(self.scene_regex)\n character_dialog = re.compile(self.dialog_regex)\n\n for line in self.text:\n if scene_setting.match(line):\n\n r = scene_setting.search(line)\n r_tokens = r.group(1).replace('-', ' ').strip().split()\n r_tokens = [t for t in r_tokens if t not in string.punctuation and t not in string.whitespace]\n self.scenes.extend(r_tokens)\n\n self.script_skeleton.append({\n 'type': 'scene',\n 'original_text': line,\n 'length': len(r_tokens),\n 'number': scene_counter\n })\n\n scene_counter += 1\n\n elif character_dialog.match(line):\n r = character_dialog.search(line)\n name = r.group(1)\n dialog = r.group(2).split()\n dialog = [d for d in dialog if d not in string.punctuation and d not in string.whitespace]\n self.character_dialog[name].extend(dialog)\n\n self.script_skeleton.append({\n 'type': 'dialog',\n 'character': name,\n 'dialog': dialog,\n 'length': len(dialog)\n })\n\n else:\n note = line.split()\n note = [n for n in note if n not in string.punctuation and n not in string.whitespace]\n self.notes.extend(note)\n\n self.script_skeleton.append({\n 'type': 'direction',\n 'text': note,\n 'length': len(note)\n })\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"454827060","text":"#Autor: Cecilia Daniela Olivares Hernández, a01745727\r\n#Descripción: Calcula el precio total a pagar de los boletos comprados para un concierto.\r\n\r\n#Esta funcion calcula el rendimiento del automovil en km/litros\r\ndef calcularRendimientoKm(km, litros):\r\n rendimientoKm = km / litros\r\n return rendimientoKm\r\n\r\n#Esta funcion calcula el rendimiento del automovil en millas/galon\r\ndef calcularRendimientoMi(km, litros):\r\n rendimientoMi = (km / 1.6093) / (litros * 0.264)\r\n return rendimientoMi\r\n\r\n#Esta funcion calcula los km que recorrera el auto\r\ndef calcularKmARecorrer(km, litros, kmARecorrer):\r\n l = kmARecorrer * 0.0358\r\n return l\r\n\r\n#Funcion principal que resuelve el problema\r\ndef main():\r\n km = int(input(\"Teclea el número de Km recorridos: \"))\r\n litros = int(input(\"Teclea el número de litros de gasolina usados: \"))\r\n rendimientoKm = calcularRendimientoKm(km, litros)\r\n rendimientoMi = calcularRendimientoMi(km, litros)\r\n print(\"\"\" \\x1b[1;30m \r\nSi recorres\"\"\",(km),\"\"\"kms con\"\"\", (litros), \"\"\"litros de gasolina, el rendimiento es:\r\n%.2f\"\"\" % (rendimientoKm), \"\"\"km/l\r\n%.2f\"\"\" % (rendimientoMi), \"\"\"mi/gal\r\n\"\"\")\r\n kmARecorrer = int(input(\"\\x1b[0;m¿Cuántos kilómetros vas a recorrer? \"))\r\n l = calcularKmARecorrer(km, litros, kmARecorrer)\r\n print(\"\"\" \\x1b[1;30m \r\nPara recorrer\"\"\", (kmARecorrer),\"\"\"km. necesitas %.2f\"\"\" % (l), \"\"\"litros de gasolina\"\"\")\r\n\r\nmain()","sub_path":"Auto.py","file_name":"Auto.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"178232630","text":"\"\"\"Updated USB Lookup script based on the version found in Chapter 2.\"\"\"\nfrom __future__ import print_function\nimport argparse\nimport sys\ntry:\n from urllib2 import urlopen\nexcept ImportError:\n from urllib.request import urlopen\n\n\"\"\"\nMIT License\nCopyright (c) 2018 Chapin Bryce, Preston Miller\nPlease share comments and questions at:\n https://github.com/PythonForensics/Learning-Python-for-Forensics\n or email pyforcookbook@gmail.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\ndef main(vid, pid, ids_file=None):\n \"\"\"\n Main function to control operation. Requires arguments passed as VID PID\n on the command line. If discovered in data set, the common names will be\n printed to stdout\n :return: None\n \"\"\"\n if ids_file:\n usb_file = open(ids_file, encoding='latin1')\n else:\n usb_file = get_usb_file()\n usbs = parse_file(usb_file)\n results = search_key(usbs, (vid, pid))\n print(\"Vendor: {}\\nProduct: {}\".format(results[0], results[1]))\n\n\ndef get_usb_file():\n \"\"\"\n Retrieves USB.ids database from the web.\n \"\"\"\n url = 'http://www.linux-usb.org/usb.ids'\n return urlopen(url)\n\n\ndef parse_file(usb_file):\n \"\"\"\n Parses the USB.ids file. If this is run offline, please\n\tdownload the USB.ids and pass the open file to this function.\n ie: parse_file(open('path/to/USB.ids', 'r'))\n :return: dictionary of entires for querying\n \"\"\"\n usbs = {}\n curr_id = ''\n for line in usb_file:\n if isinstance(line, bytes):\n line = line.decode('latin-1')\n if line.startswith('#') or line in ('\\n', '\\t'):\n continue\n else:\n if not line.startswith('\\t') and (line[0].isdigit() or\n line[0].islower()):\n uid, name = get_record(line.strip())\n curr_id = uid\n usbs[uid] = [name.strip(), {}]\n elif line.startswith('\\t') and line.count('\\t') == 1:\n uid, name = get_record(line.strip())\n usbs[curr_id][1][uid] = name.strip()\n return usbs\n\n\ndef get_record(record_line):\n \"\"\"\n Split records out by dynamic position. By finding the space,\n\twe can determine the location to split the record for\n\textraction. To learn more about this, uncomment the print\n\tstatements and see what the code is doing behind the scenes!\n \"\"\"\n # print(\"Line: {}\".format(record_line))\n split = record_line.find(' ')\n # print(\"Split: {}\".format(split))\n record_id = record_line[:split]\n # print(\"Record ID: \".format(record_id))\n record_name = record_line[split + 1:]\n # print(\"Record Name: \".format(record_name))\n return record_id, record_name\n\n\ndef search_key(usb_dict, ids):\n \"\"\"\n Compare provided IDs to the built USB dictionary. If found,\n\tit will return the common name, otherwise returns the string\n\t\"unknown\".\n \"\"\"\n vendor_key = ids[0]\n product_key = ids[1]\n\n vendor, vendor_data = usb_dict.get(vendor_key, ['unknown', {}])\n product = 'unknown'\n if vendor != 'unknown':\n product = vendor_data.get(product_key, 'unknown')\n\n return vendor, product\n","sub_path":"Chapter13/chapter_13/plugins/helper/usb_lookup.py","file_name":"usb_lookup.py","file_ext":"py","file_size_in_byte":4122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"378583755","text":"from datetime import datetime\n\nfrom flask import session\nfrom flask.ext.login import current_user\nfrom sqlalchemy.sql.expression import func\nfrom project.extensions import redis_store\nfrom project.models import Phrase, db, User\nfrom project.oauth import google\n\nPHRASE_REDIS_KEY_TEMPLATE = \"{user_id}-{source_language}-{translated_language}\"\n\nPHRASES_FOR_QUESTIONNAIRE_LIMIT = 50\n\n\ndef questionnaire_done(user_id, source_language, translated_language):\n redis_key = PHRASE_REDIS_KEY_TEMPLATE.format(\n user_id=user_id,\n source_language=source_language,\n translated_language=translated_language,\n )\n ids = redis_store.lrange(\n redis_key,\n 0, -1\n )\n ids = map(int, ids)\n if not ids:\n return []\n\n phrases = Phrase.query.filter(Phrase.id.in_(ids))\n\n statuses = [ps.value for ps in Phrase.ProgressStatus]\n for phrase in phrases:\n next_statuses = list(\n filter(lambda ns: phrase.progress_status < ns, statuses)\n )\n if not next_statuses:\n phrase.status = Phrase.Status.finished.value\n continue\n phrase.progress_status = next_statuses[0]\n phrase.date_available = (\n datetime.utcnow() +\n Phrase.ProgressStatus(phrase.progress_status).get_progress_delta()\n )\n\n redis_store.delete(redis_key)\n return phrases\n\n\ndef mark_available_phrases(user_id, source_language, translated_language):\n phrases = db.session.query(\n Phrase.id\n ).filter(\n Phrase.user_id == user_id,\n Phrase.source_language == source_language,\n Phrase.translated_language == translated_language,\n Phrase.status == Phrase.Status.visible.value,\n Phrase.date_available < datetime.now(),\n Phrase.progress_status < Phrase.ProgressStatus.after_two_week.value,\n ).order_by(\n func.random()\n ).limit(PHRASES_FOR_QUESTIONNAIRE_LIMIT)\n phrase_ids = [phrase.id for phrase in phrases]\n if not phrase_ids:\n return []\n\n redis_store.lpush(\n PHRASE_REDIS_KEY_TEMPLATE.format(\n user_id=user_id,\n source_language=source_language,\n translated_language=translated_language,\n ),\n *phrase_ids\n )\n return phrase_ids\n\n\ndef create_phrase(source_language, source_text,\n translated_language, translated_text):\n phrase = Phrase()\n phrase.user = current_user\n phrase.source_language = source_language\n phrase.source_text = source_text\n phrase.translated_language = translated_language\n phrase.translated_text = translated_text\n return phrase\n\n\ndef get_phrases_by_user(user_id):\n query = db.session.query(\n Phrase\n ).filter(\n Phrase.user_id == user_id,\n Phrase.status == Phrase.Status.visible.value,\n )\n return query\n\n\ndef delete_phrase(phrase_id):\n word = Phrase.query.get_or_404(phrase_id)\n word.status = Phrase.Status.deleted.value\n\n\ndef edit_phrase(phrase_id, source_language, source_text,\n translated_language, translated_text):\n phrase = Phrase.query.get_or_404(phrase_id)\n phrase.source_language = source_language\n phrase.source_text = source_text\n phrase.translated_language = translated_language\n phrase.translated_text = translated_text\n return phrase\n\n\ndef create_user(email, nick_name, first_name, last_name, register_type):\n user = User()\n user.email = email\n user.nick_name = nick_name\n user.first_name = first_name\n user.last_name = last_name\n user.register_type = register_type\n return user\n\n\ndef load_user(user_email):\n return User.query.filter_by(email=user_email).first()\n\n\n@google.tokengetter\ndef get_google_oauth_token():\n return session.get('google_token')\n","sub_path":"project/bl.py","file_name":"bl.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"} +{"seq_id":"58635068","text":"# -*- coding: utf-8 -*-\nfrom PySide import QtCore, QtGui\nimport sys\nfrom PySide.QtCore import * \nfrom PySide.QtGui import * \n\nimport numpy as np\nimport scipy.io as sio\nimport csv \nimport math as mt\nimport time\nimport winsound\nimport threading\n\nfrom DataManager import DataManager\nfrom DIG3D import DIG3D\nfrom calibration import Calibration_Window\nfrom MainInterface import MainInterface\n\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n#310, 80, 921, 771\n\n\nclass MainWindow(QMainWindow,MainInterface):\n def __init__(self): \n QMainWindow.__init__(self) \n \n self.ui = MainInterface()\n self.ui.setupUi(self)\n self.data = DataManager()\n self.DIG = DIG3D()\n self.caliWindow = Calibration_Window(self) \n \n #original value is 5, it lead to some frontal points are kept out \n self.amplifiCoefficient = 5\n \n self.timerMain = QTimer(self)\n self.timerCali = QTimer(self) \n\n self.ui.progress_bar.setMinimum(0) \n self.ui.progress_bar.setMaximum(60) \n\n self.interfaceOrigin()\n self.callback_register() \n \n self.isSound = True\n self.plate_num = 5\n self.version_state = False\n \n self.load_flag = 0 # 0 means no load 1 means load\n self.atlas_type_flag = 0 # 0 means brodman, 1 means AAL ,2 means LPBA40\n self.temp_navi_state = 0 # 0 means no need record temp group_navigation, 1 means need\n self.navi_1020_state = 0 # 0 means do not display 1020, 1 means display\n self.have_atlas_target = 0 # 0means do not have target, 1 means have target\n self.old_atlas_target = 0 \n self.target_1020_point_mesh = None\n self.target_1020_point = None\n \n self.target_1020_line = None\n \n self.progress_i = 0\n self.target_atlas = None\n \n \n if self.DIG.connection():\n self.ui.dig_status.setText(_fromUtf8(\"ON\"))\n #self.ui.display_tips.setText(_fromUtf8(\"Click select history file button to load subject's first experiment information.\"))\n \n else:\n self.ui.dig_status.setText(_fromUtf8(\"OFF\"))\n #self.ui.display_tips.setText(_fromUtf8(\"Your 3d group_digitizer is not connected.Check your device then clicking plug logo to reconnect.\"\n #\"or Click select history file button to load subject's first experiment information.\"))\n\n \n \n #------------------register callbacks\n def callback_register(self): \n\n #register for individual \n self.ui.pushButton_start5Reference.clicked.connect(self.start_obtain)\n self.ui.pushButton_start21Sparse.clicked.connect(self.start_obtain_21)\n self.ui.pushButton_reconstruct.clicked.connect(self.finish_obtain)\n self.ui.pushButton_reconstructOk.clicked.connect(self.navigation_free_start) \n \n self.ui.pushButton_load_target.clicked.connect(self.load_navigation_target)\n self.ui.combobox_atlas_type.activated.connect(self.change_atlas)\n self.ui.check_atlas.stateChanged.connect(self.show_atlas)\n self.ui.check_1020.stateChanged.connect(self.grid_add_delete)\n self.ui.check_CPC.stateChanged.connect(self.cpc_add_delete)\n self.ui.combobox_atlas_target.activated.connect(self.change_atlas_target) \n \n\n \n self.ui.combobox_grid_target.activated.connect(self.change_grid_target) \n \n \n self.ui.pushButton_save_channel.clicked.connect(self.save_channel)\n self.ui.pushButton_save_optode.clicked.connect(self.save_optode) \n self.ui.pushButton_save_marker.clicked.connect(self.save_re_marker)\n self.ui.pushButton_save.clicked.connect(self.save_all)\n \n self.ui.pushButton_DIG3D.clicked.connect(self.DIG3D_reconnect)\n self.ui.pushButton_calibration.clicked.connect(self.start_calibration)\n self.ui.pushButton_sound.clicked.connect(self.sound_and_mute)\n self.ui.front_view.clicked.connect(self.change_front_view) \n self.ui.inner_version.clicked.connect(self.change_inner_version)\n \n self.ui.pushButton_next_navi.clicked.connect(self.next_navi) \n self.ui.pushButton_last_navi.clicked.connect(self.delete_last_navi_point) \n self.ui.pushButton_temp_record.clicked.connect(self.temp_record)\n self.ui.pushButton_last_sparse.clicked.connect(self.delete_last_obtain_point) \n \n \n #register for calibration\n self.caliWindow.pushButton_OK.clicked.connect(self.stop_calibration_OK)\n self.caliWindow.pushButton_restart.clicked.connect(self.caliWindow.restart_calibration) \n self.caliWindow.finished.connect(self.stop_calibration_close)\n \n #register for timer\n self.timerCali.timeout.connect(self.calibration_data)\n self.timerMain.timeout.connect(self.get_digitizer_point)\n \n\n\n#------- functions about interface ---------\n\n def interfaceOrigin(self):\n #set up gui\n self.ui.pushButton_start5Reference.setEnabled(True)\n self.ui.pushButton_start21Sparse.setEnabled(False) \n self.ui.pushButton_reconstruct.setEnabled(False) \n self.ui.pushButton_reconstructOk.setEnabled(False) \n \n self.ui.check_atlas.setEnabled(False)\n self.ui.combobox_atlas_type.setEnabled(False)\n \n #self.ui.MayaviQwidget.visualization.show_actor(self.ui.MayaviQwidget.visualization.little_girl)\n self.ui.check_1020.setEnabled(False)\n self.ui.check_CPC.setEnabled(False)\n \n \n self.ui.combobox_atlas_target.setEnabled(False)\n self.ui.combobox_grid_target.setEnabled(False)\n self.ui.pushButton_load_target.setEnabled(False)\n\n self.ui.pushButton_save_channel.setEnabled(False)\n self.ui.pushButton_save_optode.setEnabled(False) \n self.ui.pushButton_save_marker.setEnabled(False) \n self.ui.pushButton_save.setEnabled(False)\n \n #toolbox gui\n self.ui.pushButton_DIG3D.setEnabled(True)\n self.ui.pushButton_calibration.setEnabled(True)\n self.ui.front_view.setEnabled(False) \n\n self.ui.label_tips.hide()\n self.ui.view.hide()\n self.ui.label_view.hide()\n self.ui.label_distance.hide()\n \n self.ui.progress_bar.hide() \n\n self.ui.pushButton_last_sparse.hide() \n self.ui.pushButton_temp_record.hide() \n self.ui.pushButton_next_navi.hide()\n self.ui.pushButton_last_navi.hide() \n \n \n #set up group boxs' border\n self.ui.group_subject_info.setStyleSheet(\"QGroupBox{border : 2px ; border-style:outset;}\") \n self.ui.group_scalp_reconstruction.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_navigation.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_digitizer.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n \n \n self.ui.widget_mayavi.setGeometry(QtCore.QRect(310, 10, 921, 841)) \n \n \n \n \n \n def interface_after_start_obtain(self):\n #set up gui\n #set up gui\n self.ui.pushButton_start5Reference.setEnabled(True)\n self.ui.pushButton_start21Sparse.setEnabled(False) \n \n self.ui.pushButton_reconstruct.setEnabled(False) \n self.ui.pushButton_reconstructOk.setEnabled(False) \n self.ui.pushButton_load_target.setEnabled(False)\n self.ui.combobox_atlas_type.setEnabled(False)\n self.ui.check_atlas.setEnabled(False)\n self.ui.check_1020.setEnabled(False)\n self.ui.check_CPC.setEnabled(False)\n self.ui.combobox_atlas_target.setEnabled(False)\n self.ui.combobox_grid_target.setEnabled(False)\n self.ui.pushButton_save_channel.setEnabled(False)\n self.ui.pushButton_save_optode.setEnabled(False) \n self.ui.pushButton_save_marker.setEnabled(False) \n self.ui.pushButton_save.setEnabled(False)\n \n self.ui.widget_mayavi.setGeometry(QtCore.QRect(310, 80, 921, 771)) \n self.ui.label_tips.show()\n self.ui.label_tips.setGeometry(QtCore.QRect(340, 30, 550, 31))\n \n self.ui.view.hide()\n self.ui.label_view.hide()\n self.ui.label_distance.hide()\n \n ###########\n #self.ui.view.show()\n #self.ui.label_view.show()\n #self.ui.label_distance.show()\n #self.setDistance(5)\n #self.ui.label_distance.setText(\"11.11\")\n ################\n \n self.ui.pushButton_next_navi.hide()\n self.ui.pushButton_last_navi.hide()\n self.ui.pushButton_temp_record.hide() \n self.ui.pushButton_last_sparse.show()\n self.ui.pushButton_last_sparse.setEnabled(False)\n \n \n \n ##########\n #self.ui.pushButton_last_navi.show()\n #self.ui.pushButton_next_navi.show()\n #self.ui.pushButton_last_sparse.hide() \n ###########\n\n #set up group boxs' border\n self.ui.group_subject_info.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_scalp_reconstruction.setStyleSheet(\"QGroupBox{border : 2px ; border-style:outset;}\") \n self.ui.group_navigation.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_digitizer.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_save.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n\n #self.ui.display_tips.setText(_fromUtf8(\"Follow the yellow point to obtain subject's reference points.\"))\n \n \n def interface_after_5ref(self):\n self.ui.pushButton_start21Sparse.setEnabled(True)\n \n \n def interface_after_sparse(self):\n self.ui.pushButton_reconstruct.setEnabled(True)\n self.timerMain.stop()\n #self.ui.display_tips.setText(_fromUtf8(\"Click finish button to reconstruction subject's \"\n #\"skull model and compute Nz-Cz-Iz line and \"\n #\"AL-Cz-AR line.\"))\n \n def interface_after_finish_obtain(self):\n #set up gui\n #self.timerMain.stop()\n self.ui.pushButton_reconstruct.setEnabled(False) \n self.ui.pushButton_reconstructOk.setEnabled(True) \n self.ui.pushButton_last_sparse.hide()\n \n \n self.ui.front_view.setEnabled(True) \n \n #set up group boxs' border\n self.ui.group_navigation.setStyleSheet(\"QGroupBox{border : 2px ; border-style:outset;}\") \n \n #self.ui.display_tips.setText(_fromUtf8(\"If you are satisfied with the results, click start button to start navigaiton.\"))\n #self.ui.label_tips.show()\n self.ui.label_tips.setText(\"Waiting...\")\n \n self.ui.progress_bar.show()\n \n \n\n def interface_start_navigation(self):\n #set up gui\n \n self.ui.pushButton_start21Sparse.setEnabled(False) \n self.ui.pushButton_reconstruct.setEnabled(False) \n self.ui.pushButton_reconstructOk.setEnabled(False) \n \n self.ui.combobox_atlas_type.setEnabled(True)\n self.ui.check_atlas.setEnabled(True)\n self.ui.check_atlas.setChecked(True)\n self.ui.check_1020.setEnabled(True)\n self.ui.check_CPC.setEnabled(True)\n self.ui.combobox_atlas_target.setEnabled(True)\n self.set_atlas_target_text()\n \n self.ui.combobox_grid_target.setEnabled(False)\n self.ui.pushButton_load_target.setEnabled(True)\n \n self.ui.pushButton_save_channel.setEnabled(True)\n self.ui.pushButton_save_optode.setEnabled(True) \n self.ui.pushButton_save_marker.setEnabled(True) \n self.ui.pushButton_save.setEnabled(True)\n \n self.ui.pushButton_next_navi.hide()\n self.ui.pushButton_last_navi.hide()\n self.ui.pushButton_temp_record.show() \n \n self.ui.front_view.setEnabled(False) \n #set up group boxs' border\n self.ui.group_subject_info.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_scalp_reconstruction.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_navigation.setStyleSheet(\"QGroupBox{border : 2px ; border-style:outset;}\") \n self.ui.group_digitizer.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n\n self.ui.label_tips.show()\n self.ui.label_tips.setText(\"\")\n \n #self.ui.display_tips.setText(_fromUtf8(\"Moving your 3D ditigizer to find the closest position with target.\"))\n \n \n def interface_after_repeat_navigation(self):\n #set up gui\n \n self.ui.pushButton_temp_record.hide() \n self.ui.pushButton_next_navi.show()\n self.ui.pushButton_last_navi.show()\n \n self.ui.pushButton_last_navi.setEnabled(False)\n \n self.ui.view.show()\n self.ui.label_view.show()\n self.ui.label_distance.show()\n self.ui.label_distance.setText(\"\")\n self.ui.label_tips.setText(\"\")\n \n self.ui.label_tips.setGeometry(QtCore.QRect(340, 30, 300, 31))\n\n\n \n def interface_before_save(self):\n #set up gui\n self.ui.pushButton_save_channel.setEnabled(True)\n self.ui.pushButton_save_optode.setEnabled(True) \n self.ui.pushButton_save_marker.setEnabled(True) \n self.ui.pushButton_save.setEnabled(True)\n self.ui.pushButton_next_navi.setEnabled(False)\n \n self.ui.check_1020.setEnabled(False)\n self.ui.check_CPC.setEnabled(False)\n self.ui.combobox_grid_target.setEnabled(False)\n #set up group boxs' border\n self.ui.group_subject_info.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_scalp_reconstruction.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_navigation.setStyleSheet(\"QGroupBox{border : 2px ; border-style:outset;}\") \n self.ui.group_save.setStyleSheet(\"QGroupBox{border : 2px ; border-style:outset;}\") \n\n \n\n\n def interface_save(self):\n #set up gui\n self.ui.pushButton_save_channel.setEnabled(True)\n self.ui.pushButton_save_optode.setEnabled(True) \n self.ui.pushButton_save_marker.setEnabled(True) \n self.ui.pushButton_save.setEnabled(True)\n \n self.ui.combobox_atlas_target.setEnabled(False)\n self.ui.combobox_atlas_type.setEnabled(False)\n self.ui.check_1020.setEnabled(False)\n self.ui.check_CPC.setEnabled(False)\n self.ui.combobox_grid_target.setEnabled(False)\n self.ui.pushButton_load_target.setEnabled(False)\n self.ui.check_atlas.setEnabled(True)\n \n self.ui.view.hide()\n self.ui.label_view.hide()\n self.ui.label_distance.hide\n \n self.ui.label_tips.setText(\"\")\n \n self.ui.pushButton_last_navi.hide()\n self.ui.pushButton_next_navi.hide()\n self.ui.pushButton_last_sparse.show()\n self.ui.pushButton_temp_record.hide()\n #set up group boxs' border\n self.ui.group_subject_info.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_scalp_reconstruction.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_navigation.setStyleSheet(\"QGroupBox{border : 1px ; border-style:outset;}\") \n self.ui.group_save.setStyleSheet(\"QGroupBox{border : 2px ; border-style:outset;}\") \n \n\n def setDistance(self, value): \n if value < 0:\n value = 0\n if value > 10:\n value = 10\n rect_length = value/10.0 * 597 # 300 is the rect's length, set up in MainInterface.py\n if value <= 2:\n color = Qt.green\n else:\n color = Qt.red\n \n self.ui.scene.clear()\n item = QGraphicsRectItem(QRectF(0, 0, rect_length, 32)) \n pen = QPen() \n pen.setWidth(1) \n pen.setColor(color) \n item.setPen(pen) \n item.setBrush(color) \n self.ui.scene.addItem(item) \n \n \n \n item = QGraphicsRectItem(QRectF(2.0/10.0*597, 0, 2, 32)) \n pen = QPen() \n pen.setWidth(1) \n pen.setColor(Qt.green) \n item.setPen(pen) \n item.setBrush(Qt.green) \n self.ui.scene.addItem(item) \n \n \n#------ function to load reference data, including reference subject's 1020 system points and four plate points ------\n \n \n \n#-------fuction for obtaon points ---------------------------------------------------------------\n @Slot()\n def start_obtain(self):\n if self.timerMain.isActive():\n self.timerMain.stop()\n if self.timerCali.isActive():\n self.timerCali.stop()\n self.data.new()\n self.ui.MayaviQwidget.visualization.new()\n self.DIG.threshold = 2\n self.interface_after_start_obtain()\n \n if self.data.step == 1:\n self.remove_current_actor()\n \n self.ui.MayaviQwidget.visualization.show_actor(self.ui.MayaviQwidget.visualization.little_girl)\n #self.ui.widget_mayavi.setGeometry(QtCore.QRect(310, 10, 921, 841)) \n self.ui.MayaviQwidget.visualization.point_to_obtain = np.zeros((5,3))\n self.ui.MayaviQwidget.visualization.point_to_obtain[0] = self.data.model_ref[4]\n self.ui.MayaviQwidget.visualization.point_to_obtain[1] = self.data.model_ref[1]\n self.ui.MayaviQwidget.visualization.point_to_obtain[2] = self.data.model_ref[0]\n self.ui.MayaviQwidget.visualization.point_to_obtain[3] = self.data.model_ref[2]\n self.ui.MayaviQwidget.visualization.point_to_obtain[4] = self.data.model_ref[3]\n \n #print self.ui.MayaviQwidget.visualization.point_to_obtain\n self.ui.MayaviQwidget.visualization.obtain_turn = 1\n self.ui.MayaviQwidget.visualization.show_obtain_points()\n \n self.data.step = 0 \n self.timerMain.start(100) \n\n self.DIG.readPDIData()\n self.ui.label_tips.setText(\"Cz\")\n \n @Slot()\n def start_obtain_21(self): \n if self.timerMain.isActive():\n self.timerMain.stop()\n if self.timerCali.isActive():\n self.timerCali.stop()\n \n self.data.new_2()\n self.ui.MayaviQwidget.visualization.point_to_obtain = self.data.obtain_point_mesh[0:5,:]\n self.ui.MayaviQwidget.visualization.new_2()\n \n \n self.ui.MayaviQwidget.visualization.obtain_turn = 6\n self.ui.MayaviQwidget.visualization.show_obtain_points()\n \n self.timerMain.start(100)\n self.DIG.readPDIData()\n\n self.ui.label_tips.setText(\"Remaining: 21/21\")\n \n#------- functions for group_navigation\n @Slot()\n def navigation_free_start(self):\n #compute target\n \n self.data.step = 1\n self.data.number_points[1] = 0\n self.DIG.threshold = 0\n self.load_flag = 0\n self.atlas_type_flag = 0\n \n self.interface_start_navigation()\n \n self.ui.MayaviQwidget.visualization.clear_points()\n \n \n self.ui.MayaviQwidget.visualization.show_actor(self.ui.MayaviQwidget.visualization.ba_atlas)\n \n self.DIG.readPDIData()\n if self.timerMain.isActive() == False:\n self.timerMain.start(100)\n \n \n\n @Slot()\n def load_navigation_target(self):\n self.timerMain.stop()\n \n filename,selectedFilter = QFileDialog.getOpenFileName(filter=\"*.mat\")\n if filename == '' and selectedFilter == '':\n \n if self.timerMain.isActive() == False:\n self.timerMain.start(100) \n \n return\n file_handle = sio.loadmat(file_name = filename)\n try:\n \n his_plate = file_handle['plate']\n his_plate_cpc = file_handle['plate_cpc']\n his_plate_length = file_handle['plate_length']\n \n except:\n QMessageBox.warning(self,\"Error\",\n \"The .mat file is not contain reference subject's 1020\"+\n \"system points and plate information\",QMessageBox.Ok)\n \n if self.timerMain.isActive() == False:\n self.timerMain.start(100) \n return \n\n self.load_flag = 1\n \n #init data\n self.data.number_points[1] = 0\n self.ui.MayaviQwidget.visualization.target_turn = 0\n \n self.data.his_plate = his_plate\n self.data.his_plate_cpc = his_plate_cpc\n #self.data.his_plate_midpoint_cpc = his_plate_cpc[4, :]\n self.data.his_plate_length = his_plate_length \n\n\n self.data.navigation_target = np.zeros((5, 3))\n self.data.navigation_result = np.zeros((5, 3))\n self.data.navigation_result_cpc = np.zeros((5, 2))\n #self.data.his_plate = np.zeros((4, 3))\n #self.data.his_plate_cpc = np.zeros((4, 2)) \n\n \n self.data.navigation_target_mesh = np.zeros((5, 3))\n self.data.navigation_result_mesh = np.zeros((5, 3)) \n\n #compute navigation target\n self.data.compute_navigation_target()\n \n \n self.ui.MayaviQwidget.visualization.navigation_target_mesh = self.data.navigation_target_mesh\n \n self.ui.MayaviQwidget.visualization.navigaiton_target_line_mesh = self.data.compute_navigation_target_line()\n\n #self.ui.MayaviQwidget.visualization.show_target() \n self.navigation_view_points()\n\n #\n self.interface_after_repeat_navigation()\n \n if self.timerMain.isActive() == False:\n self.timerMain.start(100)\n\n \n \n def set_atlas_target_text(self):\n \n index = self.ui.combobox_atlas_type.currentIndex()\n self.ui.combobox_atlas_target.clear()\n self.ui.combobox_atlas_target.addItem(_fromUtf8(\"None\")) \n \n if index == 0:#means ba\n \n ba_list = self.ui.MayaviQwidget.visualization.ba_combobox_list\n self.ui.combobox_atlas_target.addItems(ba_list)\n \n #set the popup list's width\n self.ui.combobox_atlas_target.setStyleSheet('''*\n QComboBox QAbstractItemView \n {\n min-width: 490px;\n }\n ''')\n \n \n elif index == 1:#means aal\n \n aal_list = self.ui.MayaviQwidget.visualization.aal_combobox_list\n self.ui.combobox_atlas_target.addItems(aal_list)\n #set the popup list's width\n self.ui.combobox_atlas_target.setStyleSheet('''*\n QComboBox QAbstractItemView \n {\n min-width: 330px;\n }\n ''') \n\n else:\n lpba_list = self.ui.MayaviQwidget.visualization.lpba_combobox_list\n self.ui.combobox_atlas_target.addItems(lpba_list)\n #set the popup list's width\n self.ui.combobox_atlas_target.setStyleSheet('''*\n QComboBox QAbstractItemView \n {\n min-width: 430px;\n }\n ''') \n\n\n def set_grid_target_text(self):\n \n self.ui.combobox_grid_target.clear()\n \n self.ui.combobox_grid_target.addItem(_fromUtf8(\"None\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"Fpz\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"Fp1\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"Fp2\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"Fz\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"F3\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"F4\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"F7\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"F8\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"Cz\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"C3\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"C4\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"T3\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"T4\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"Pz\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"P3\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"P4\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"T5\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"T6\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"O1\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"O2\"))\n self.ui.combobox_grid_target.addItem(_fromUtf8(\"Oz\"))\n\n\n#------- functions for actor and atlas management \n\n @Slot()\n def show_atlas(self):\n atlas_state = self.ui.check_atlas.isChecked() # 0 means no need\n if atlas_state == 0:\n self.remove_current_actor()\n self.ui.combobox_atlas_type.setEnabled(False)\n self.ui.combobox_atlas_target.clear()\n self.ui.combobox_atlas_target.setEnabled(False)\n \n else:\n \n #self.ui.MayaviQwidget.visualization.show_1020()\n self.ui.combobox_atlas_target.setEnabled(True)\n self.ui.combobox_atlas_type.setEnabled(True)\n self.ui.combobox_atlas_type.setCurrentIndex(0)\n self.set_atlas_target_text()\n self.ui.MayaviQwidget.visualization.show_actor(self.ui.MayaviQwidget.visualization.ba_atlas)\n self.atlas_type_flag = 0\n self.have_atlas_target = 0\n self.old_atlas_target = 0 \n \n @Slot()\n def change_atlas(self):\n self.timerMain.stop()\n \n ba = self.ui.MayaviQwidget.visualization.ba_atlas\n aal = self.ui.MayaviQwidget.visualization.aal_atlas\n lpba = self.ui.MayaviQwidget.visualization.lpba_atlas\n self.remove_current_actor()\n \n \n \n #add atlas and atlas target combobox text \n index = self.ui.combobox_atlas_type.currentIndex()\n self.set_atlas_target_text()\n self.have_atlas_target = 0\n \n if index == 0:\n self.ui.MayaviQwidget.visualization.show_actor(ba)\n self.atlas_type_flag = 0\n elif index == 1:\n self.ui.MayaviQwidget.visualization.show_actor(aal)\n self.atlas_type_flag = 1\n else:\n self.ui.MayaviQwidget.visualization.show_actor(lpba) \n self.atlas_type_flag = 2 \n \n self.timerMain.start(100)\n \n \n \n \n @Slot()\n def change_atlas_target(self):\n self.timerMain.stop()\n \n ba = self.ui.MayaviQwidget.visualization.ba_atlas\n aal = self.ui.MayaviQwidget.visualization.aal_atlas\n lpba = self.ui.MayaviQwidget.visualization.lpba_atlas\n \n \n self.remove_current_actor()\n \n index = self.ui.combobox_atlas_type.currentIndex()\n target_current = self.ui.combobox_atlas_target.currentIndex()\n \n \n if index == 0:\n target_label = self.ui.MayaviQwidget.visualization.ba_combobox_index_label.get(target_current)\n if target_current == 0:\n self.target_atlas = self.ui.MayaviQwidget.visualization.ba_atlas\n else:\n self.target_atlas = self.ui.MayaviQwidget.visualization.compute_target_color(index, target_label) \n \n camera = self.ui.MayaviQwidget.visualization.ba_camera[target_label,:]\n \n elif index == 1:\n target_label = self.ui.MayaviQwidget.visualization.aal_combobox_index_label.get(target_current)\n if target_current == 0:\n self.target_atlas = self.ui.MayaviQwidget.visualization.aal_atlas\n else:\n self.target_atlas = self.ui.MayaviQwidget.visualization.compute_target_color(index, target_label) \n \n camera = self.ui.MayaviQwidget.visualization.aal_camera[target_label,:] \n \n else:\n target_label = self.ui.MayaviQwidget.visualization.lpba_combobox_index_label.get(target_current)\n if target_current == 0:\n self.target_atlas = self.ui.MayaviQwidget.visualization.lpba_atlas\n else:\n self.target_atlas = self.ui.MayaviQwidget.visualization.compute_target_color(index, target_label) \n\n camera = self.ui.MayaviQwidget.visualization.lpba_camera[target_label,:] \n\n \n self.ui.MayaviQwidget.visualization.show_actor(self.target_atlas)\n self.ui.MayaviQwidget.visualization.set_camera(camera, 0) \n self.atlas_type_flag = index\n self.have_atlas_target = 1 \n \n self.timerMain.start(100)\n\n\n \n def remove_current_actor(self): \n \n if self.have_atlas_target == 0:\n if self.atlas_type_flag == 0:\n self.ui.MayaviQwidget.visualization.remove_actor(self.ui.MayaviQwidget.visualization.ba_atlas)\n elif self.atlas_type_flag == 1:\n self.ui.MayaviQwidget.visualization.remove_actor(self.ui.MayaviQwidget.visualization.aal_atlas)\n else:\n self.ui.MayaviQwidget.visualization.remove_actor(self.ui.MayaviQwidget.visualization.lpba_atlas)\n #remove the old target\n else:\n self.ui.MayaviQwidget.visualization.remove_actor(self.target_atlas)\n\n \n \n @Slot()\n def grid_add_delete(self):\n self.navi_1020_state = self.ui.check_1020.isChecked() # 0 means no need\n if self.navi_1020_state == 0:\n #self.ui.MayaviQwidget.visualization.clear_points()\n self.ui.combobox_grid_target.setEnabled(False)\n self.ui.combobox_grid_target.clear()\n else:\n if self.timerMain.isActive() == False:\n self.timerMain.start(100)\n #self.ui.MayaviQwidget.visualization.show_1020()\n self.ui.check_CPC.setChecked(False)\n self.ui.combobox_grid_target.setEnabled(True)\n self.set_grid_target_text()\n \n self.navigation_view_points()\n \n \n \n \n @Slot()\n def cpc_add_delete(self):\n if self.timerMain.isActive() == True:\n self.timerMain.stop() \n \n navi_cpc_state = self.ui.check_CPC.isChecked() # 0 means no need\n if navi_cpc_state == 0:\n \n self.ui.MayaviQwidget.visualization.clear_points()\n self.ui.check_1020.setEnabled(True)\n self.timerMain.start(100) \n self.DIG.readPDIData()\n # self.naviga tion_view_points()\n \n else:\n #########\n #self.ui.MayaviQwidget.visualization.sub_1020_mesh = self.data.model_ref\n \n self.ui.check_1020.setChecked(False)\n self.ui.check_1020.setEnabled(True)\n \n self.ui.combobox_grid_target.setEnabled(False)\n self.ui.combobox_grid_target.clear() \n \n self.ui.MayaviQwidget.visualization.clear_points()\n self.ui.MayaviQwidget.visualization.navigation_pen_num = 0\n self.ui.MayaviQwidget.visualization.show_cpc()\n \n \n \n\n\n \n @Slot()\n def change_grid_target(self):\n \n index = self.ui.combobox_grid_target.currentIndex()\n if index > 0:\n self.target_1020_point_mesh = self.data.sub_grid1020_mesh[index + 3, :]\n self.target_1020_point = self.data.sub_grid1020[index + 3, :]\n self.target_1020_line = self.data.sub_grid1020_mesh_line[(index + 3) * 6 : (index + 4) * 6, :]\n \n \n self.target_1020_line = self.target_1020_line *1.04\n camera_point = self.target_1020_point_mesh\n \n else:\n \n camera_point = self.data.sub_grid1020_mesh[0, :] \n \n self.ui.MayaviQwidget.visualization.set_camera(camera_point, 0)\n self.ui.MayaviQwidget.visualization.navigation_pen_num = 0\n \n self.navigation_view_points()\n \n @Slot()\n def temp_record(self):\n if self.temp_navi_state==1:\n #self.ui.pushButton_temp_record.setText(_translate(\"MainWindow\", \"record\", None))\n \n icon = QIcon()\n icon.addPixmap(QtGui.QPixmap(\"./interface/record-32.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off) \n self.ui.pushButton_temp_record.setIcon(icon) \n\n self.temp_navi_state = 0\n else:\n #self.ui.pushButton_temp_record.setText(_translate(\"MainWindow\", \"not record\", None)) \n icon = QIcon()\n icon.addPixmap(QtGui.QPixmap(\"./interface/pause-32.png\"), QtGui.QIcon.Normal, QtGui.QIcon.On) \n self.ui.pushButton_temp_record.setIcon(icon) \n \n self.temp_navi_state = 1 \n\n\n\n\n\n def navigation_view_points(self):\n # clear points\n self.ui.MayaviQwidget.visualization.clear_points()\n \n #display 1020\n if self.navi_1020_state == 1:\n self.ui.MayaviQwidget.visualization.show_1020()\n #display 1020 target\n index = self.ui.combobox_grid_target.currentIndex()\n if index >0:\n self.ui.MayaviQwidget.visualization.show_1020_target(self.target_1020_point_mesh,self.target_1020_line) \n \n #display pen\n self.ui.MayaviQwidget.visualization.show_pen()\n #display target\n if self.load_flag == 1:\n self.ui.MayaviQwidget.visualization.show_target()\n \n \n#------- functions about toolbox --------- \n @Slot()\n def start_calibration(self):\n #stop the main timer\n self.timerMain.stop()\n \n #show the calibration window\n self.caliWindow.show()\n self.caliWindow.setModal(True)\n\n #set up calibration data\n self.caliWindow.first_point = None\n self.caliWindow.second_point = None\n self.caliWindow.start_calibration()\n \n self.timerCali.start(100)\n \n @Slot()\n def calibration_data(self):\n cite_data = self.DIG.readPDIData()\n if cite_data == None:\n return\n if self.isSound :\n winsound.Beep(1000, 300) #play a sound \n\n \n point = cite_data[0,0:3] \n first = self.caliWindow.first_point\n second = self.caliWindow.second_point\n #print str(point)\n #print \"first\"+str(first)\n #print \"second\"+str(second)\n\n if first == None:\n self.caliWindow.first_point = point\n self.caliWindow.proc_calibration()\n #print \"after first\"+str(self.caliWindow.first_point)\n elif second == None:\n self.caliWindow.second_point = point\n self.caliWindow.proc_calibration()\n #print \"after second\"+str(self.caliWindow.second_point)\n else:\n return \n \n @Slot() \n def stop_calibration_OK(self):\n self.timerCali.stop()\n self.caliWindow.close()\n self.timerMain.start(100)\n \n @Slot() \n def stop_calibration_close(self):\n self.timerCali.stop()\n self.caliWindow.close() \n self.timerMain.start(100)\n \n @Slot()\n def sound_and_mute(self):\n if self.isSound:\n icon = QIcon()\n #icon.addPixmap(QtGui.QPixmap(\"Mute.png\"), QtGui.QIcon.Normal, QtGui.QIcon.On) \n icon.addPixmap(QtGui.QPixmap(\"./interface/Sound.png\"), QtGui.QIcon.Normal, QtGui.QIcon.On) \n self.ui.pushButton_sound.setIcon(icon)\n self.isSound = False\n else:\n icon = QIcon()\n #icon.addPixmap(QtGui.QPixmap(\"Sound.png\"), QtGui.QIcon.Normal, QtGui.QIcon.On) \n icon.addPixmap(QtGui.QPixmap(\"./interface/Mute.png\"), QtGui.QIcon.Normal, QtGui.QIcon.On) \n self.ui.pushButton_sound.setIcon(icon) \n self.isSound =True\n @Slot()\n def change_front_view(self):\n self.ui.MayaviQwidget.visualization.set_camera(self.data.sub_grid1020_mesh[0,:], 0)\n \n @Slot()\n def change_inner_version(self):\n self.version_state = not self.version_state\n#------- functions about 3d group_digitizer ---------\n @Slot() \n def DIG3D_reconnect(self):\n self.DIG.unconnection()\n time.sleep(1)\n if self.DIG.connection():\n self.ui.dig_status.setText(_fromUtf8(\"ON\"))\n #self.ui.display_tips.setText(\"Please click new subject head to continue\")\n \n else: \n self.ui.dig_status.setText(_fromUtf8(\"OFF\"))\n \n #self.ui.statusbar.showMessage(\"Please check your device then click plug logo to reconnect.\")\n \n \n#------- functions for data obtain or delete point -------\n @Slot()\n def get_digitizer_point(self):\n \n cite_data = self.DIG.readPDIData()\n if cite_data == None:\n return\n \n if self.isSound :\n winsound.Beep(1000, 300) #play a sound \n\n if self.data.push_point(cite_data) == False:\n self.ui.label_tips.setText(\"Error point\") \n return\n #step and index start from 0\n step = self.data.step\n \n #-update the mayaview\n if step == 0:\n index = self.data.number_points[0]\n self.ui.pushButton_last_sparse.setEnabled(True) \n if index <= 4:\n self.ui.MayaviQwidget.visualization.obtain_turn = index+1\n self.ui.MayaviQwidget.visualization.show_obtain_points()\n #\n if index == 0 :\n self.ui.label_tips.setText(\"Cz\")\n elif index == 1 :\n self.ui.label_tips.setText(\"Inion\") \n elif index == 2 :\n self.ui.label_tips.setText(\"Nasion\") \n elif index == 3 :\n self.ui.label_tips.setText(\"AR\") \n elif index == 4:\n self.ui.label_tips.setText(\"AL\") \n \n\n\n return\n elif index == 5:\n #计算map点并且显示,把21按钮使能,关闭timer\n self.data.obtain_landmark = self.data.obtain_points[0:5,:]\n for index_2 in range(5):\n self.data.obtain_point_mesh[index_2,:] = self.data.mesh_by_5ref(self.data.obtain_landmark,\n self.data.obtain_points[index_2,:])\n self.ui.MayaviQwidget.visualization.point_to_obtain = self.data.obtain_point_mesh[0:index,:]\n self.ui.MayaviQwidget.visualization.obtain_turn = 6\n self.ui.MayaviQwidget.visualization.show_obtain_points()\n self.ui.label_tips.setText(\"5 reference finished\")\n self.timerMain.stop()\n self.interface_after_5ref()\n \n #self.ui.display_tips.setText(_fromUtf8(\"Check the reference points' location then follow the white \"\n #\"points on subjucet's cap to obtain points.\"\n #\"The number on the bottom right of the screen represents the\"\n #\"number of points you need to collect at the present.\")) \n return\n elif index >5 and index <26 :\n self.ui.pushButton_start21Sparse.setEnabled(True)\n self.data.obtain_point_mesh[index-1,:] = self.data.mesh_by_5ref(self.data.obtain_landmark,\n self.data.obtain_points[index-1,:])\n self.ui.MayaviQwidget.visualization.point_to_obtain = self.data.obtain_point_mesh[0:index,:] \n self.ui.MayaviQwidget.visualization.obtain_turn = index+1\n self.ui.MayaviQwidget.visualization.show_obtain_points() \n self.ui.label_tips.setText(\"Remaining: \" + str(26-index) + \"/21\")\n #self.ui.display_tips.setText(_fromUtf8(\"Follow the white points on subjucet's cap to obtain points.\"\n #\"The number on the bottom right of the screen represents the\"\n #\"number of points you need to collect at the present.\")) \n return\n elif index == 26:\n self.data.obtain_point_mesh[index-1,:] = self.data.mesh_by_5ref(self.data.obtain_landmark,\n self.data.obtain_points[index-1,:])\n self.ui.MayaviQwidget.visualization.point_to_obtain = self.data.obtain_point_mesh[0:index,:] \n self.ui.MayaviQwidget.visualization.obtain_turn = index+1\n self.ui.MayaviQwidget.visualization.show_obtain_points() \n self.ui.label_tips.setText(\"21 sparse finished\")\n self.interface_after_sparse()\n return\n if step == 1: \n #-- display points\n pen_num = self.ui.MayaviQwidget.visualization.navigation_pen_num\n \n if self.temp_navi_state == 0:\n self.ui.MayaviQwidget.visualization.navigation_pen_mesh[0,:] = self.data.navigation_process_mesh\n self.ui.MayaviQwidget.visualization.navigation_pen_num = 1\n else:\n self.ui.MayaviQwidget.visualization.navigation_pen_mesh[pen_num,:] = self.data.navigation_process_mesh\n self.ui.MayaviQwidget.visualization.navigation_pen_num += 1\n \n self.navigation_view_points()\n \n #-- modify group_navigation display tips label_experiment_name and buttons\n if self.load_flag == 0: \n index_1020_target = self.ui.combobox_grid_target.currentIndex()\n \n if self.ui.check_1020.isChecked() == 1 and index_1020_target > 0:\n \n self.ui.view.show()\n self.ui.label_view.show()\n self.ui.label_distance.show()\n \n self.ui.label_tips.setText(\"\")\n target_1020 = self.target_1020_point\n \n distance1 = self.data.reject_distance_navigation_proccess\n distance2 = np.linalg.norm(target_1020 - self.data.reject_navigation_proccess)\n #self.ui.label_tips.setGeometry(QtCore.QRect(340, 10, 300, 62))\n #self.ui.label_tips.setGeometry(QtCore.QRect(340, 30, 300, 31))\n #self.ui.label_tips.setText(\"Distance1: \" + str(round(distance1*10,2)) + \" mm\\n\"+\n #\"Distance2: \" + str(round(distance2*10,2)) + \" mm\")\n \n if self.version_state: # True means inner version\n self.ui.label_distance.setGeometry(QtCore.QRect(950, 10, 100, 62))\n self.ui.label_distance.setText(str(round(distance1*10,2)) + \"\\n\"+\n str(round(distance2*10,2))) \n else:\n self.ui.label_distance.setGeometry(QtCore.QRect(940, 21, 100, 31))\n self.ui.label_distance.setText(str(round(distance2*10,2)))\n \n self.setDistance(round(distance2*10,2))\n \n if distance2*10 > 10:\n self.ui.MayaviQwidget.visualization.set_camera(self.data.navigation_process_mesh, 0)\n elif distance2*10 > 5:\n self.ui.MayaviQwidget.visualization.set_camera(self.data.navigation_process_mesh, 1) \n else:\n self.ui.MayaviQwidget.visualization.set_camera(self.target_1020_point_mesh, 2) \n \n \n\n else:\n self.ui.view.hide()\n self.ui.label_view.hide()\n self.ui.label_distance.hide()\n \n #current_process_ratio = self.data.compute_cpc(self.data.navigation_process)\n current_cpc = self.data.navigaiton_process_cpc\n \n atlas_index = (int(current_cpc[0,0] * 100) - 1) * 101 + int(current_cpc[0,1] * 100)\n \n atlas_type = self.ui.combobox_atlas_type.currentIndex()\n MNI = self.ui.MayaviQwidget.visualization.mni[atlas_index]\n \n if atlas_type == 0:\n label = self.ui.MayaviQwidget.visualization.ba_label[atlas_index]\n label_name = self.ui.MayaviQwidget.visualization.ba_name.get(label[0])\n \n elif atlas_type == 1:\n label = self.ui.MayaviQwidget.visualization.aal_label[atlas_index]\n label_name = self.ui.MayaviQwidget.visualization.aal_name.get(label[0])\n else:\n label = self.ui.MayaviQwidget.visualization.lpba_label[atlas_index]\n label_name = self.ui.MayaviQwidget.visualization.lpba_name.get(label[0])\n \n self.ui.label_tips.setGeometry(QtCore.QRect(340, 10, 800, 62))\n self.ui.label_tips.setText(str(label_name) + \"\\n\" +\n \"MNI:\" + str(int(MNI[0])) + \",\" + str(int(MNI[1])) + \n \",\" + str(int(MNI[2])))\n \n self.ui.MayaviQwidget.visualization.set_camera(self.data.navigation_process_mesh, 0)\n \n \n \n else: #repeat wear\n self.ui.pushButton_next_navi.setEnabled(True)\n \n target_turn = self.data.number_points[1]\n target_point = self.data.navigation_target[target_turn]\n \n \n\n #distance = np.linalg.norm(target_point-self.data.navigation_process)\n \n \n distance1 = self.data.reject_distance_navigation_proccess\n distance2 = np.linalg.norm(target_point - self.data.reject_navigation_proccess) \n\n \n #self.ui.label_tips.setGeometry(QtCore.QRect(340, 30, 300, 31))\n #self.ui.label_tips.setText(\"Distance: \" + str(round(distance*10,2)) + \"mm\")\n \n if self.version_state: # True means inner version\n self.ui.label_distance.setGeometry(QtCore.QRect(950, 10, 100, 62))\n self.ui.label_distance.setText(str(round(distance1 * 10, 2)) + \"\\n\"+\n str(round(distance2 * 10, 2))) \n else:\n self.ui.label_distance.setGeometry(QtCore.QRect(940, 21, 100, 31))\n self.ui.label_distance.setText(str(round(distance2 * 10, 2))) \n\n \n #self.ui.label_distance.setText(str(round(distance*10,2)))\n \n self.setDistance(round(distance2 * 10,2))\n \n if distance2 * 10 > 10:\n self.ui.MayaviQwidget.visualization.set_camera(self.data.navigation_process_mesh, 0)\n elif distance2 * 10 > 5:\n self.ui.MayaviQwidget.visualization.set_camera(self.data.navigation_process_mesh, 1) \n else:\n self.ui.MayaviQwidget.visualization.set_camera(self.data.navigation_target_mesh[target_turn], 2) \n\n\n \n \n if step == 2:\n \n self.ui.pushButton_last_sparse.setEnabled(True) \n \n if self.data.save_type == 0:\n index = self.data.save_channel_num\n self.ui.label_tips.setText(str(index))\n self.ui.MayaviQwidget.visualization.point_to_obtain = self.data.save_mesh_channel[0:index,:] \n if self.data.save_type == 1:\n index = self.data.save_optode_num\n self.ui.label_tips.setText(str(index))\n self.ui.MayaviQwidget.visualization.point_to_obtain = self.data.save_mesh_optode[0:index,:] \n if self.data.save_type == 2:\n index = self.data.save_marker_num\n self.ui.label_tips.setText(str(index) + \"/5\")\n self.ui.MayaviQwidget.visualization.point_to_obtain = self.data.save_mesh_marker[0:index,:] \n if index == 5:\n self.timerMain.stop()\n \n self.ui.label_tips.setGeometry(QtCore.QRect(340, 30, 300, 31)) \n \n self.ui.MayaviQwidget.visualization.show_save_points(index) \n\n\n\n# \n @Slot()\n def delete_last_obtain_point(self):\n self.data.pop_point()\n if self.data.step == 0:\n index = self.data.number_points[0]\n \n if index <5:\n \n self.ui.pushButton_start21Sparse.setEnabled(False)\n self.ui.MayaviQwidget.visualization.point_to_obtain = np.zeros((5,3))\n self.ui.MayaviQwidget.visualization.point_to_obtain[0] = self.data.model_ref[4]\n self.ui.MayaviQwidget.visualization.point_to_obtain[1] = self.data.model_ref[1]\n self.ui.MayaviQwidget.visualization.point_to_obtain[2] = self.data.model_ref[0]\n self.ui.MayaviQwidget.visualization.point_to_obtain[3] = self.data.model_ref[2]\n self.ui.MayaviQwidget.visualization.point_to_obtain[4] = self.data.model_ref[3] \n #self.ui.display_tips.setText(_fromUtf8(\"Follow the yellow point to obtain subject's reference points.\")) \n \n self.ui.MayaviQwidget.visualization.obtain_turn = index+1\n self.ui.MayaviQwidget.visualization.show_obtain_points() \n self.ui.label_tips.show()\n \n if index <= 4:\n if index == 0 :\n self.ui.label_tips.setText(\"Cz\")\n elif index == 1 :\n self.ui.label_tips.setText(\"Inion\") \n elif index == 2 :\n self.ui.label_tips.setText(\"Nasion\")\n elif index == 3 :\n self.ui.label_tips.setText(\"AR\")\n elif index == 4:\n self.ui.label_tips.setText(\"AL\")\n elif index == 5:\n self.ui.label_tips.setText(\"Remaining: 21/21\")\n elif index >5 and index <26 :\n self.ui.label_tips.setText(\"Remaining: \" + str(26-index) + \"/21\")\n \n \n if index < 26:\n self.ui.pushButton_reconstruct.setEnabled(False) \n \n if self.data.step == 2:\n \n if self.data.save_type == 0:\n index = self.data.save_channel_num\n self.ui.label_tips.setText(str(index))\n self.ui.MayaviQwidget.visualization.point_to_obtain = self.data.save_mesh_channel[0:index,:] \n if self.data.save_type == 1:\n index = self.data.save_optode_num\n self.ui.label_tips.setText(str(index))\n self.ui.MayaviQwidget.visualization.point_to_obtain = self.data.save_mesh_optode[0:index,:] \n if self.data.save_type == 2:\n index = self.data.save_marker_num\n self.ui.label_tips.setText(str(index) + \"/5\")\n self.ui.MayaviQwidget.visualization.point_to_obtain = self.data.save_mesh_marker[0:index,:] \n \n self.ui.MayaviQwidget.visualization.show_save_points(index) \n \n \n if index == 0 :\n self.ui.pushButton_last_sparse.setEnabled(False)\n\n if self.timerMain.isActive() == False:\n self.timerMain.start(100)\n\n \n @Slot()\n def delete_last_navi_point(self):\n self.data.pop_point()\n index = self.data.number_points[1]\n \n \n self.ui.MayaviQwidget.visualization.target_turn -= 1\n index = self.data.number_points[1]\n self.ui.MayaviQwidget.visualization.show_target()\n self.ui.pushButton_next_navi.setEnabled(True)\n \n if index == 0 :\n \n self.ui.pushButton_last_navi.setEnabled(False)\n \n if self.timerMain.isActive() == False:\n self.timerMain.start(100)\n \n \n \n #when finish obtain points, click the button\"finish\" \n \n \n @Slot()\n def finish_obtain(self):\n #self.timer_progress.start()\n \n self.interface_after_finish_obtain()\n self.ui.MayaviQwidget.visualization.clear_points()\n #self.ui.MayaviQwidge\n \n #for t in self.threads:\n #t.setDaemon(True)\n #t.start()\n #for i in range(60):\n #self.ui.progress_bar.setValue(i)\n #time.sleep(1)\n\n #t.join()\n \n t2 = threading.Thread(target = self.s3r_1020_test)\n t2.setDaemon(True)\n t2.start()\n for i in range(60):\n self.ui.progress_bar.setValue(i)\n time.sleep(1) \n \n\n t2.join() \n \n \n self.ui.progress_bar.hide()\n self.ui.label_tips.hide()\n self.show_ghead()\n \n #self.s3r_1020_test()\n \n @Slot() \n def s3r_1020_test(self):\n \n #handle_tmp = sio.loadmat('.\\\\test_S3R\\\\ref.mat')\n #self.data.obtain_points = handle_tmp['obtain_points'] \n \n self.data.S3Ralgo_l1020()\n \n def show_ghead(self):\n self.ui.MayaviQwidget.visualization.sub_1020_mesh = self.data.sub_grid1020_mesh\n\n #compute the amplification coefficinent for view ghead points \n sub_x = self.data.sub_1020[2]\n model_x = self.data.model_ref[2] \n amplification_x = np.linalg.norm(model_x) * ( np.linalg.norm(sub_x) ** -1 ) \n\n sub_y = self.data.sub_1020[0]\n model_y = self.data.model_ref[0]\n amplification_y = np.linalg.norm(model_y) * ( np.linalg.norm(sub_y) ** -1 )\n\n sub_z = self.data.sub_1020[6]\n model_z = self.data.model_ref[4]\n amplification_z = np.linalg.norm(model_z) * ( np.linalg.norm(sub_z) ** -1 )\n\n self.amplifiCoefficient = max(amplification_x,amplification_y,amplification_z) + 0.5\n\n self.ui.MayaviQwidget.visualization.line_al_cz_ar = (self.data.line_al_cz_ar)*self.amplifiCoefficient\n self.ui.MayaviQwidget.visualization.line_nz_cz_iz = (self.data.line_nz_cz_iz)*self.amplifiCoefficient\n self.ui.MayaviQwidget.visualization.sub_GheadR = (self.data.sub_GheadR[::50])*self.amplifiCoefficient\n \n \n self.ui.MayaviQwidget.visualization.show_ghead_and_line()\n \n #self.timer_progress.stop()\n #self.ui.progress_bar.hide()\n #self.interface_before_navigation() \n \n \n @Slot() \n def next_navi(self):\n index = self.data.number_points[1]\n\n \n self.data.navigation_result[index,:] = self.data.navigation_process\n self.data.navigation_result_cpc[index,:] = self.data.navigaiton_process_cpc#compute_cpc(self.data.navigation_process)\n self.data.navigation_result_mesh[index,:] = self.data.mesh_by_cpc(self.data.navigaiton_process_cpc)\n \n self.data.number_points[1] += 1\n self.ui.MayaviQwidget.visualization.target_turn += 1\n index = self.data.number_points[1]\n if index < self.plate_num:\n #self.ui.MayaviQwidget.visualization.show_target()\n self.navigation_view_points()\n elif index == self.plate_num :\n #把板的结果显示出来\n \n self.timerMain.stop()\n self.ui.MayaviQwidget.visualization.navigation_result_mesh = self.data.navigation_result_mesh\n self.ui.MayaviQwidget.visualization.show_navigation_result()\n \n self.interface_before_save()\n \n \n self.ui.pushButton_last_navi.setEnabled(True)\n \n \n \n @Slot()\n def save_channel(self):\n self.data.step = 2\n self.interface_save()\n self.ui.MayaviQwidget.visualization.clear_points()\n \n self.data.save_type = 0\n self.data.save_channel_num = 0\n #pe = QPalette()\n #pe.setColor(QPalette.Background, Qt.red) # 设置字体颜色\n ##pbh.setPalette(pe)\n \n self.ui.pushButton_save_channel.setStyleSheet('''background-color: #A7CDFF''')\n self.ui.pushButton_save_optode.setStyleSheet(self.ui.pushButton_calibration.styleSheet())\n self.ui.pushButton_save_marker.setStyleSheet(self.ui.pushButton_calibration.styleSheet())\n \n \n\n\n\n #p = self.ui.pushButton_save_channel.palette()\n #p.setColor(self.ui.pushButton_save_channel.backgroundRole(), Qt.red)\n \n #self.ui.pushButton_save_channel.setAutoFillBackground(True)\n\n #self.ui.pushButton_save_channel.setPalette(p) \n \n if self.timerMain.isActive() == False:\n self.timerMain.start(100)\n \n \n \n @Slot()\n def save_optode(self):\n self.data.step = 2\n self.interface_save()\n self.ui.MayaviQwidget.visualization.clear_points()\n \n self.data.save_type = 1\n self.data.save_optode_num = 0\n \n self.ui.pushButton_save_optode.setStyleSheet('''background-color: #A7CDFF''')\n self.ui.pushButton_save_channel.setStyleSheet(self.ui.pushButton_calibration.styleSheet())\n self.ui.pushButton_save_marker.setStyleSheet(self.ui.pushButton_calibration.styleSheet())\n \n \n if self.timerMain.isActive() == False:\n self.timerMain.start(100)\n \n @Slot()\n def save_re_marker(self):\n self.data.step = 2\n self.interface_save()\n self.ui.MayaviQwidget.visualization.clear_points()\n\n self.data.save_type = 2\n self.data.save_marker_num = 0\n\n self.ui.pushButton_save_marker.setStyleSheet('''background-color: #A7CDFF''')\n self.ui.pushButton_save_optode.setStyleSheet(self.ui.pushButton_calibration.styleSheet())\n self.ui.pushButton_save_channel.setStyleSheet(self.ui.pushButton_calibration.styleSheet())\n \n \n if self.timerMain.isActive() == False:\n self.timerMain.start(100)\n \n \n @Slot()\n def save_all(self): \n\n self.timerMain.stop()\n \n\n # check reference \n subjectID = self.ui.lineEdit_subjectID.text()\n experimentName = self.ui.lineEdit_experiment_name.text()\n if subjectID == \"\" or experimentName == \"\":\n QMessageBox.warning(self,\"Error\",\"Please input subjectID or experiment name\",QMessageBox.Ok) \n return\n \n if self.data.save_marker_num < 5:\n marker_num = 0\n else:\n marker_num = 5\n \n if self.data.sub_GheadR == None:\n head_num = 0\n else:\n head_num = len(self.data.sub_GheadR)\n \n submit_save = QMessageBox.question(self, 'Confirm save list ', \n \"subject ID: \" + str(subjectID)+ \" \\n\"+\n \"experiment: \" + str(experimentName) + \" \\n\" +\n \"landmark: Nz, Iz, AR, AL, Cz\\n\" + \n \"1020 points: 25 \\n\" +\n \"head model: \" + str(head_num) + \" \\n\"+\n \"channel: \" + str(self.data.save_channel_num) + \" \\n\"+\n \"optode: \" + str(self.data.save_optode_num) + \" \\n\"+\n \"probe set marker: \" + str(marker_num),\n QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n \n if submit_save == QMessageBox.Yes:\n \n self.ui.pushButton_save_channel.setStyleSheet(self.ui.pushButton_calibration.styleSheet())\n self.ui.pushButton_save_optode.setStyleSheet(self.ui.pushButton_calibration.styleSheet())\n self.ui.pushButton_save_marker.setStyleSheet(self.ui.pushButton_calibration.styleSheet())\n \n \n landmark = self.data.sub_landmark\n l1020 = self.data.sub_1020\n head = self.data.sub_GheadR\n \n channel = self.data.save_channel[:self.data.save_channel_num,:]\n optode = self.data.save_optode[:self.data.save_optode_num,:]\n marker = self.data.save_marker[:self.data.save_marker_num,:]\n marker_cpc = self.data.save_marker_cpc[:self.data.save_marker_num,:]\n \n #subject_plate = self.data.navigation_result\n #subject_plate_ratio = self.data.navigation_result_ratio\n #first_date = self.data.first_date \n #experimenter = self.data.experimenter \n \n \n current_time = time.localtime()\n current_date = str(current_time[0])+'_'+ str(current_time[1])+'_'+str(current_time[2])\n \n path_name = QFileDialog.getExistingDirectory()\n if path_name ==u\"\":\n return \n \n try:\n sio.savemat(path_name+u\"\\\\\"+\"re_\"+ subjectID+\"_\"+current_date,{'subjectID':subjectID,\n 'experimentName':experimentName,\n 'landmark':landmark,\n 'l1020':l1020,\n 'head':head,\n 'channel':channel,\n 'optode':optode,\n 'plate':marker,\n 'plate_cpc': marker_cpc,\n 'plate_length': self.data.his_plate_length}) \n except:\n QMessageBox.warning(self,\"Error\",\"Error occured when saving data!\",QMessageBox.Ok)\n return\n \n QMessageBox.information(self,\"Notification\",\"Successfully saved\",QMessageBox.Ok) \n \n #self.interfaceOrigin() \n \n else:\n return \n\n\n\n self.navigation_free_start()\n \n\n \n def exit_app(self):\n pass\n \n \n def close_window(self):\n pass\n \n def closeEvent(self,event):\n #-stop timers \n self.timerCali.stop()\n self.timerMain.stop()\n \n #-unconnect DIG3D\n self.DIG.unconnection() \n \n #-disconnect the TCP link\n self.DIG.TCP_disconnect()\n #print(\"exit callback!\")\n event.accept()\n\n\n\n\nif __name__ == \"__main__\":\n \n app = QApplication.instance()\n mainwindow = MainWindow()\n mainwindow.show()\n sys.exit(app.exec_())","sub_path":"re_main.py","file_name":"re_main.py","file_ext":"py","file_size_in_byte":64938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"88"}