diff --git "a/718.jsonl" "b/718.jsonl" new file mode 100644--- /dev/null +++ "b/718.jsonl" @@ -0,0 +1,716 @@ +{"seq_id":"83710273","text":"import numpy as np\n\n\nclass Cluster:\n def __init__(self, centre):\n self.centre = centre\n\n def update_centre(self, x, iteration):\n self.centre += (x - self.centre) / (1 + iteration)\n\n\nclass OnlineKMeans:\n def __init__(self, k_num, data):\n self.cluster_list = [Cluster(i) for i in data[np.random.choice(data.shape[0], k_num, replace=False)]]\n self.data = self.normalize(data)\n self.cluster_data()\n self.error = self.calc_error()\n\n def calc_error(self):\n error = 0\n for x in self.data:\n closest_cluster = self.calc_closest(x)\n error += np.linalg.norm(x - closest_cluster.centre) ** 2\n return error\n\n def calc_closest(self, x):\n closest = self.cluster_list[0]\n for mu in self.cluster_list:\n if np.linalg.norm(x - mu.centre) < np.linalg.norm(x - closest.centre):\n closest = mu\n return closest\n\n def cluster_data(self):\n iterations = 0\n while iterations < 100:\n iterations += 1\n for x in self.data:\n max_dot_product = np.dot(x, self.cluster_list[0].centre)\n best_cluster=self.cluster_list[0]\n for mu in self.cluster_list:\n if np.dot(x, mu.centre) > max_dot_product:\n best_cluster = mu\n best_cluster.update_centre(x, iterations)\n\n def normalize(self, data):\n norms = np.linalg.norm(data, axis=1).reshape(data.shape[0], 1)\n return data / norms\n","sub_path":"OnlineKMeans.py","file_name":"OnlineKMeans.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"128034370","text":"from zope.i18n import interpolate\nfrom zope.i18n import negotiate\nfrom zope.i18n import translate\nfrom zope.i18nmessageid import Message\n\nimport StringIO\n\nimport expressions\nimport utils\n\nimport z3c.pt.generation\nfrom z3c.pt.config import DISABLE_I18N\n\nwrapper = \"\"\"\\\ndef render(%starget_language=None):\n\\tglobal generation\n\n\\t(_out, _write) = generation.initialize_stream()\n\\t(_attributes, repeat) = generation.initialize_tal()\n\\t(_domain, _negotiate, _translate) = generation.initialize_i18n()\n\\t(_escape, _marker) = generation.initialize_helpers()\n\\t_path = generation.initialize_traversal()\n\n\\t_target_language = _negotiate(_context, target_language)\n%s\n\\treturn _out.getvalue()\n\"\"\"\n\ndef _fake_negotiate(context, target_language):\n return target_language\n\ndef _fake_translate(msgid, domain=None, mapping=None, context=None,\n target_language=None, default=None):\n if isinstance(msgid, Message):\n default = msgid.default\n mapping = msgid.mapping\n\n if default is None:\n default = unicode(msgid)\n\n return interpolate(default, mapping)\n\ndef _negotiate(context, target_language):\n if target_language is not None:\n return target_language\n return negotiate(context)\n\ndef _escape(s, quote=0, string=1):\n \"\"\"Replace special characters '&', '<' and '>' by SGML entities.\n\n If string is set to False, we are dealing with Unicode input.\n \"\"\"\n if string:\n s = str(s)\n if '&' in s:\n s = s.replace(\"&\", \"&\") # Must be done first!\n if '<' in s:\n s = s.replace(\"<\", \"<\")\n if '>' in s:\n s = s.replace(\">\", \">\")\n if quote:\n s = s.replace('\"', \""\")\n return s\n\ndef initialize_i18n():\n if DISABLE_I18N:\n return (None, _fake_negotiate, _fake_translate)\n return (None, _negotiate, translate)\n\ndef initialize_tal():\n return ({}, utils.repeatdict())\n\ndef initialize_helpers():\n return (_escape, object())\n\ndef initialize_stream():\n out = BufferIO()\n return (out, out.write)\n\ndef initialize_traversal():\n return expressions.PathTranslation.traverse\n\nclass Generator(object):\n def __init__(self, params):\n self.params = tuple(params)\n self.stream = CodeIO(indentation=1, indentation_string=\"\\t\")\n\n # initialize variable scope\n self.stream.scope.append(set(params + ['_out', '_write']))\n\n def __call__(self):\n # prepare template arguments\n args = self.params\n # We need to ensure we have _context for the i18n handling in the\n # arguments. The default template implementations pass this in\n # explicitly.\n if '_context' not in args:\n args = args + ('_context=None', )\n args = ', '.join(args)\n if args:\n args += ', '\n\n code = self.stream.getvalue().encode('utf-8')\n return wrapper % (args, code), {'generation': z3c.pt.generation}\n\nclass BufferIO(list):\n write = list.append\n\n def getvalue(self):\n return ''.join(self)\n\nclass CodeIO(StringIO.StringIO):\n \"\"\"A I/O stream class that provides facilities to generate Python code.\n\n * Indentation is managed using ``indent`` and ``outdent``.\n\n * Annotations can be assigned on a per-line basis using ``annotate``.\n\n * Convenience methods for keeping track of temporary variables\n \n * Methods to process clauses (see ``begin`` and ``end``).\n \n \"\"\"\n\n t_prefix = '_tmp'\n v_prefix = '_var'\n\n def __init__(self, indentation=0, indentation_string=\"\\t\"):\n StringIO.StringIO.__init__(self)\n self.indentation = indentation\n self.indentation_string = indentation_string\n self.queue = u''\n self.scope = [set()]\n self.annotations = {}\n \n self._variables = {}\n self.t_counter = 0\n self.l_counter = 0\n \n def save(self):\n self.t_counter += 1\n return \"%s%d\" % (self.t_prefix, self.t_counter)\n \n def restore(self):\n var = \"%s%d\" % (self.t_prefix, self.t_counter)\n self.t_counter -= 1\n return var\n \n def indent(self, amount=1):\n if amount > 0:\n self.cook()\n self.indentation += amount\n\n def outdent(self, amount=1):\n if amount > 0:\n self.cook()\n self.indentation -= amount\n\n def annotate(self, item):\n self.annotations[self.l_counter] = item\n\n def out(self, string):\n self.queue += string\n \n def cook(self):\n if self.queue:\n queue = self.queue\n self.queue = ''\n self.write(\"_write('%s')\" %\n queue.replace('\\n', '\\\\n').replace(\"'\", \"\\\\'\"))\n \n def write(self, string):\n if isinstance(string, str):\n string = string.decode('utf-8')\n\n self.l_counter += len(string.split('\\n'))-1\n \n self.cook()\n StringIO.StringIO.write(\n self, self.indentation_string * self.indentation + string + '\\n')\n\n def getvalue(self):\n self.cook()\n return StringIO.StringIO.getvalue(self)\n \n def begin(self, clauses):\n if isinstance(clauses, (list, tuple)):\n for clause in clauses:\n self.begin(clause)\n else:\n clauses.begin(self)\n \n def end(self, clauses):\n if isinstance(clauses, (list, tuple)):\n for clause in reversed(clauses):\n self.end(clause)\n else:\n clauses.end(self)\n \n","sub_path":"z3c.pt/branches/chrism-gen-unicode-fix/src/z3c/pt/generation.py","file_name":"generation.py","file_ext":"py","file_size_in_byte":5501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"185714097","text":"print(\"Python Classes Lesson\")\n\nclass Employee:\n def __init__(self, first, last):\n self.first = first\n self.last = last\n self.email = first + \".\" + last + '@gmail.com'\n self.init = first[:1] + last[:1]\n self.pay = float(pay)\n self.bonus = int(pay) * .05\n\nemp_1 = Employee(\"Spencer\", \"Colaço\")\nemp_2 = Employee(\"Max\", \"Rushmore\")\n\nprint(\"{} {} - {} {} {} {}\".format(emp_1.first, emp_1.last, emp_1.email, emp_1.init, emp_1.pay, emp_1.bonus))\n","sub_path":"w9d3-python-classes/python-classes.py","file_name":"python-classes.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"496944186","text":"from flask import flash\nfrom wtforms.validators import ValidationError\nimport re\n\n\ndef validate_regx(Form, field):\n pattern = r'^[a-zA-Z0-9\\._\\-]+$'\n match = re.match(pattern, field.data)\n if match is None:\n flash('\"{}\" is not valid. Please do not use whitespace, '\n 'backslash and slash!'.format(field.data), 'critical')\n raise ValidationError('Not a valid name')\n","sub_path":"app/validations.py","file_name":"validations.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"61332966","text":"## Static Imports\nimport os\nimport importlib\nimport gym\nimport gym_everglades\nimport pdb\n\nimport numpy as np\nimport random as r\n\nfrom Stats import Stats\n\nfrom everglades_server import server\n\n## Input Variables\n# Agent files must include a class of the same name with a 'get_action' function\n# Do not include './' in file path\nagent0_file = 'agents/PPO.py'\n#agent1_file = 'agents/same_commands.py'\nagent1_file = 'agents/random_actions.py'\n\nconfig_dir = './config/'\nmap_file = config_dir + 'DemoMap.json'\nsetup_file = config_dir + 'GameSetup.json'\nunit_file = config_dir + 'UnitDefinitions.json'\noutput_dir = './game_telemetry/'\n\n# 0 for no debug / 1 for debug\ndebug = 0\n\nview = 0\n\ncreateOut = 0\n\nnumberOfGames = 500_000\n\n## Specific Imports\nagent0_name, agent0_extension = os.path.splitext(agent0_file)\nagent0_mod = importlib.import_module(agent0_name.replace('/','.'))\nagent0_class = getattr(agent0_mod, os.path.basename(agent0_name))\n\nagent1_name, agent1_extension = os.path.splitext(agent1_file)\nagent1_mod = importlib.import_module(agent1_name.replace('/','.'))\nagent1_class = getattr(agent1_mod, os.path.basename(agent1_name))\n\n## Main Script\nenv = gym.make('everglades-v0')\nplayers = {}\nnames = {}\n\n# Inputs for the dqn agent are:\n# state size, actions, player #, seed\nplayers[0] = agent0_class()\nnames[0] = agent0_class.__name__\n\nplayers[1] = agent1_class(env.num_actions_per_turn, 1)\nnames[1] = agent1_class.__name__\n\n# init stat class\nstats = Stats()\n\n# load model\n# comment if you're starting from the begining\nplayers[0].load_model()\n\nfor game in range(numberOfGames):\n \n # get inital state\n current_state = env.reset(\n players=players,\n config_dir = config_dir,\n map_file = map_file,\n unit_file = unit_file,\n output_dir = output_dir,\n pnames = names,\n debug = debug,\n view = view,\n out = createOut\n )\n new_state = current_state\n \n actions = {}\n Qs = {}\n\n # temp replay buffer\n actions_rp = []\n states_rp = []\n reward_rp = []\n\n # Game Loop\n # assuming only training player 0\n done = False\n \n while not done:\n if debug:\n env.game.debug_state()\n\n if view:\n env.game.view_state()\n \n # last new_state becomes current_state\n current_state = new_state\n \n # get actions\n for pid in players:\n actions[pid], Qs[pid] = players[pid].get_action( current_state[pid] )\n \n new_state, reward, done, _ = env.step(actions)\n \n # append to the temp RP\n actions_rp.append(action_list)\n states_rp.append(current_state[0])\n reward_rp.append(reward[0])\n \n # multi-step learning, applying reward going backwards\n for i in range(len(reward_rp), 1, -1):\n reward_rp[i - 2] = reward_rp[i - 1] * DISCOUNT\n \n \n ### storing tranistions\n for i in range(1, len(reward_rp), 1):\n players[0].update_replay_memory(states_rp[i], states_rp[i], actions_rp[i], reward_rp[i], done)\n \n # updating the stats if needed\n stats.updateStats(reward[0], game+1)\n \n # trains only after game has finsihed\n players[0].train(stats.getWinRate(), game)\n \n # uncomment here to update opposing player here\n # players[1].train()\n\n # print-out for watching training\n print(f\"Game {game}\")\n stats.showWinRate()\n players[0].get_debug()\n print(f\"reward = {reward}\\n\")\n\n# stat.plot\n# finally, save the model\n# model.saveModel()\n","sub_path":"PPO_battle.py","file_name":"PPO_battle.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"455105366","text":"from __future__ import division\nimport os\n\nimport torch\nfrom skimage.io import imsave\nfrom PIL import Image, ImageEnhance \nimport numpy as np\nimport cv2\n\nimport neural_renderer.cuda.create_texture_image as create_texture_image_cuda\n\n\ndef create_texture_image(textures, texture_size_out=16):\n num_faces, texture_size_in = textures.shape[:2]\n tile_width = int((num_faces - 1.) ** 0.5) + 1\n tile_height = int((num_faces - 1.) / tile_width) + 1\n image = torch.zeros(tile_height * texture_size_out, tile_width * texture_size_out, 3, dtype=torch.float32)\n vertices = torch.zeros((num_faces, 3, 2), dtype=torch.float32) # [:, :, XY]\n face_nums = torch.arange(num_faces)\n column = face_nums % tile_width\n row = face_nums / tile_width\n vertices[:, 0, 0] = column * texture_size_out\n vertices[:, 0, 1] = row * texture_size_out\n vertices[:, 1, 0] = column * texture_size_out\n vertices[:, 1, 1] = (row + 1) * texture_size_out - 1\n vertices[:, 2, 0] = (column + 1) * texture_size_out - 1\n vertices[:, 2, 1] = (row + 1) * texture_size_out - 1\n image = image.cuda()\n vertices = vertices.cuda()\n textures = textures.cuda()\n image = create_texture_image_cuda.create_texture_image(vertices, textures, image, 1e-5)\n \n vertices[:, :, 0] /= (image.shape[1] - 1)\n vertices[:, :, 1] /= (image.shape[0] - 1)\n \n image = image.detach().cpu().numpy()\n vertices = vertices.detach().cpu().numpy()\n image = image[::-1, ::1]\n\n return image, vertices\n\ndef do_constrast(img):\n print(do_constrast)\n a=1\n b=80\n rows,cols,channels=img.shape\n dst=img.copy()\n for i in range(rows):\n for j in range(cols):\n for c in range(3):\n color=img[i,j][c]*a+b\n if color>255: # 防止像素值越界(0~255)\n dst[i,j][c]=255\n elif color<0: # 防止像素值越界(0~255)\n dst[i,j][c]=0\n\n return dst\n\ndef do_constrast2(img_original):\n print(do_constrast2)\n \n color_coverted = cv2.cvtColor(img_original, cv2.COLOR_BGR2RGB)\n pil_image=Image.fromarray(np.uint8(color_coverted))\n enhancer = ImageEnhance.Contrast(pil_image)\n new_image = enhancer.enhance(1.8)\n numpy_image=np.array(new_image)\n \n return numpy_image\n\n\ndef save_obj(filename, vertices, faces, textures=None):\n assert vertices.ndimension() == 2\n assert faces.ndimension() == 2\n\n if textures is not None:\n filename_mtl = filename[:-4] + '.mtl'\n filename_texture = filename[:-4] + 'tmp.png'\n material_name = 'material_1'\n texture_image, vertices_textures = create_texture_image(textures)\n imsave(filename_texture, texture_image)\n texture_image = cv2.imread(filename_texture)\n filename_texture = filename[:-4] + '.png'\n texture_image2 = do_constrast2(texture_image)\n imsave(filename_texture, texture_image2)\n\n faces = faces.detach().cpu().numpy()\n\n with open(filename, 'w') as f:\n f.write('# %s\\n' % os.path.basename(filename))\n f.write('#\\n')\n f.write('\\n')\n\n if textures is not None:\n f.write('mtllib %s\\n\\n' % os.path.basename(filename_mtl))\n\n for vertex in vertices:\n f.write('v %.8f %.8f %.8f\\n' % (vertex[0], vertex[1], vertex[2]))\n f.write('\\n')\n\n if textures is not None:\n for vertex in vertices_textures.reshape((-1, 2)):\n f.write('vt %.8f %.8f\\n' % (vertex[0], vertex[1]))\n f.write('\\n')\n\n f.write('usemtl %s\\n' % material_name)\n for i, face in enumerate(faces):\n f.write('f %d/%d %d/%d %d/%d\\n' % (\n face[0] + 1, 3 * i + 1, face[1] + 1, 3 * i + 2, face[2] + 1, 3 * i + 3))\n f.write('\\n')\n else:\n for face in faces:\n f.write('f %d %d %d\\n' % (face[0] + 1, face[1] + 1, face[2] + 1))\n\n if textures is not None:\n with open(filename_mtl, 'w') as f:\n f.write('newmtl %s\\n' % material_name)\n f.write('map_Kd %s\\n' % os.path.basename(filename_texture))\n","sub_path":"neural_renderer_torch/build/lib.linux-x86_64-3.6/neural_renderer/save_obj.py","file_name":"save_obj.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"401557855","text":"graph = []\nvertices = 0 #numero vértices que o grafo terá\nconexoes = 0 #numero de conexoes entre os vértices deste grafo\ncontar_conexoes = 0 #contador para parar a entrada de conexoes\n\nclass grafo:#Criação do grafo\n def __init__(self,vertices,a,c,b):\n #c = peso aresta\n #a = cidade A\n #b = cidade B\n self.a = a\n self.b = b\n self.c = c\n if not graph:#Se a lista graph for vazia \n for adicionar in range(vertices): #adicionando conjuntos vazios no grafo\n graph.append([[],99999999,0])\n \n graph[a-1][0].append([b,c])#inserindo a[ ] --> [b[0],c[1],[2],0]\n graph[c-1][0].append([b,a])\n grafo.dados()\n \n def definir_inicio(self,a):\n graph[a][3] = 1\n \n def dados():#adiciona as adjacências do grafo\n global contar_conexoes\n global vertices\n global conexoes\n if contar_conexoes == conexoes:#para parar a entrada de conexoes\n return True\n a,b,c = input('A,B,C').split() #a,b,c\n construtor = grafo\n contar_conexoes +=1\n return construtor(vertices,int(a),int(b),int(c))\n \n def vertice():#estabelece a quantidade de vértices na lista graph\n global vertices\n global conexoes\n x = input('n,m')\n x1,x2 = x.split()\n vertices= int(x1)\n conexoes = int(x2)\n return grafo.dados() \n \ngrafo.vertice()\n\n\ndef recursivo(graph,u):\n if u[2] == 0:\n u[2] = 1 #marcando o primeiro alvo como ja visitado\n for i in range(len(u[0])):#toda aresta de u ate v\n x = u[0][i][1] #acha o alvo nos vizinhos encontrados\n if graph[x-1][2] == 0: #acha o vizinho de forma hash e verifica se foi visitado\n v = graph[x-1] #classifica-o como v\n recursivo(graph,v)#chamando ele recursivamente\n \nrecursivo(graph,graph[0])\n","sub_path":"search_in_range_rec.py","file_name":"search_in_range_rec.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"525486834","text":"\"\"\"\n연결 리스트로 우선순위 삽입 정렬 : 큐 구현하기\n\"\"\"\n\nfront = rear = None\n\nclass Node:\n def __init__(self, data, n=None, p=None):\n self.data = data\n self.next = n\n self.prev = p\n\ndef isEmpty():\n return front == None\n\ndef enQ(data):\n global front\n # 새로운 노드(객체)생성 & 주소값을 저장한다고 생각\n if isEmpty():\n front = Node(data,None)\n else:\n temp = front\n while temp.next and temp.next.data < data:\n temp = temp.next\n if temp.next:\n temp.next = Node(data,temp.next)\n else:\n temp.next = Node(data,None)\n\ndef deQ():\n global front, rear\n if isEmpty():\n print(\"Empty\")\n return None\n data = front.data\n front = front.next\n if isEmpty():\n rear = None\n return data\n\nenQ(1)\nenQ(5)\nenQ(2)\nenQ(4)\nenQ(3)\n\nprint(deQ())\nprint(deQ())\nprint(deQ())\nprint(deQ())\nprint(deQ())","sub_path":"OnlineJudge/SWExpertAcademy/Example/20190227/example2.py","file_name":"example2.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"462246860","text":"from mantistable.process.data_preparation.normalization.tokenizer import TokenTagEnum, Tokenizer\nfrom nltk.corpus import stopwords\n\nfrom mantistable.process.utils.data_type import DataTypeEnum\nimport dateutil.parser as dateutil\n\n\ndef transformer(text):\n clean_text = get_clean_text(text)\n words = [word.strip() for word in clean_text.split(\" \")]\n tokens = list(filter(lambda item: len(item) > 3 or (len(item) == 3 and item not in stopwords.words('english')), words))\n\n if len(tokens) == 0:\n tokens = words\n text_for_query = f'\"{\" \".join(tokens)}\"'\n else:\n text_for_query = \" AND \".join([f'\"{token}\"'for token in tokens])\n\n if text_for_query == '\"\"':\n text_for_query = \"\"\n\n return clean_text, text_for_query\n\n\ndef convert_to_datatype(text: str, datatype: DataTypeEnum):\n if datatype == DataTypeEnum.NUMERIC:\n return text.replace(\",\", \"\")\n elif datatype == DataTypeEnum.DATE:\n try:\n return dateutil.parse(text).strftime(\"%Y-%d-%m\")\n except:\n return text\n\n return text\n\n\ndef get_clean_text(text):\n def get_token(tokens, idx):\n if len(tokens) <= idx:\n return None\n\n return tokens[idx]\n\n clean_text = \"\"\n tokens = Tokenizer().tokenize(text)\n\n i = 0\n token = get_token(tokens, i)\n \n while token is not None:\n value = token.value\n tag = token.tag\n\n if tag == TokenTagEnum.WORD or tag == TokenTagEnum.NUMBER:\n if \"'\" in value:\n index = value.find(\"'\")\n value = value[0:index]\n \n if value != \"\":\n clean_text += value + \" \"\n elif tag == TokenTagEnum.URL:\n clean_text += value\n elif value == \"(\": # NOTE: skip parenthesis (...)\n j = i + 1\n forward_token = get_token(tokens, j)\n while forward_token is not None and forward_token.value != \")\":\n j += 1\n forward_token = get_token(tokens, j)\n\n i = j\n elif value == \"[\": # NOTE: skip parenthesis [...]\n j = i + 1\n forward_token = get_token(tokens, j)\n while forward_token is not None and forward_token.value != \"]\":\n j += 1\n forward_token = get_token(tokens, j)\n\n i = j\n\n i += 1\n token = get_token(tokens, i)\n\n return clean_text.strip().lower()\n","sub_path":"mantistable/process/data_preparation/normalization/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"84503761","text":"from django.db import models\nfrom datetime import datetime\n\n# Create your models here.\nclass ShowManager(models.Manager):\n def validator(self, postData):\n errors = {}\n if len(postData['title']) == 0 or len(postData['title']) < 3:\n errors['title'] = \"Show Title should be at least 2 characters\"\n if ['title'] == ['title']: \n errors['course_name'] = \"The show tile you enetered is not unique.\"\n if len(postData['network']) == 0 or len(postData['network']) < 3:\n errors['network'] = \"Show Network should be at least 3 characters\"\n if len(postData['description']) != 0 and len(postData['description']) < 10:\n errors['description'] = \"Show Description should be at least 10 characters\"\n if datetime.strptime(postData['release_date'], '%Y-%m-%d') > datetime.now():\n errors['release_date'] = \"Release Dates should be in the past\"\n return errors\n\nclass Show(models.Model):\n title = models.CharField(max_length=255)\n network = models.CharField(max_length=255)\n release_date = models.DateTimeField()\n description = models.CharField(max_length=255)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n objects = ShowManager()","sub_path":"semirestful_tvshows/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"475479946","text":"from flask import Flask, request, jsonify, abort\nfrom flask_cors import CORS\nimport base64\nimport mobileNkust\nimport hashlib\n\napp = Flask(__name__)\nCORS(app)\ntemp_ = {}\n@app.route(\"/getcourseinformation\", methods=['POST'])\ndef getcourseinformation():\n global temp_\n print('step1')\n cookie = request.form.get(\"data\")\n m = hashlib.md5()\n m.update(cookie.encode(\"utf-8\"))\n h = m.hexdigest()\n print('[USER->]', h)\n if h in temp_:\n return jsonify(temp_[h])\n print('step2')\n cookie = base64.b64decode(cookie).decode('utf8').replace('&', ';')\n\n # print(cookie)\n #try:\n user = mobileNkust.NKUST(cookie)\n returnData = user.returnclassificationCourses()\n temp_[h] = returnData\n return jsonify(returnData)\n #except Exception as e:\n # print(e)\n # return abort(501, '請檢查mobile.nkust.edu.tw登入狀態')\n\n\napp.run(host=\"0.0.0.0\", port=5252, debug=True, ssl_context=(\n 'ssl/nginx.crt', 'ssl/nginx.key'))\n","sub_path":"backend/handleapi.py","file_name":"handleapi.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"635817663","text":"# Mail Package\r\nimport smtplib\r\nfrom email.message import EmailMessage\r\n\r\n# google sheet package\r\nfrom gsheets import Sheets\r\n\r\n# Authorizing the api\r\nsheets = Sheets.from_files('FD4GS.json', 'FD4GS_cache.json')\r\n\r\n\r\n# Fetching information from owners database\r\n# Vehicle Information\r\n# Link: https://docs.google.com/spreadsheets/d/1URQBjLmkRkPxI1RGQFpp_ZxUa1xMcoMth3qmWH9DK2Y/edit#gid=972904917\r\nvi1 = sheets.get('1URQBjLmkRkPxI1RGQFpp_ZxUa1xMcoMth3qmWH9DK2Y')\r\n\r\nvi1_form1_ws = vi1.sheets[0]\r\n\r\nentries1 = vi1_form1_ws.values()[1:]\r\n\r\nentries1 = [(i[2], i[6], i[1]) for i in entries1]\r\n\r\n\r\n# Fetching information from search database\r\n# Search Database\r\n# Link: https://docs.google.com/spreadsheets/d/1i2_N7yqcJQQ7cpBJqR8KnxpUOPh3TgNvY8oC1mCSv0U/edit#gid=2035337844\r\nvi2 = sheets.get('1i2_N7yqcJQQ7cpBJqR8KnxpUOPh3TgNvY8oC1mCSv0U')\r\n\r\nvi2_form1_ws = vi2.sheets[0]\r\n\r\nentries2 = vi2_form1_ws.values()[1:]\r\n\r\nentries2 = [(j[1], j[2]) for j in entries2]\r\n\r\n\r\n# Fetching information from helper database\r\n# Helper Database\r\n# Link: https://docs.google.com/spreadsheets/d/1dYaQqMVPEbJuBwHC-nPbu-2NPIcaqwJf8-MqiZswmU4/edit#gid=176906407\r\nvi3 = sheets.get('1dYaQqMVPEbJuBwHC-nPbu-2NPIcaqwJf8-MqiZswmU4')\r\n\r\nvi3_form1_ws = vi3.sheets[0]\r\n\r\nentries3 = vi3_form1_ws.values()[1:]\r\n\r\nentries3 = [(k[2], k[3], k[1], k[4]) for k in entries3]\r\n\r\n# print(entries3)\r\n\r\n\r\n# Fetching common features between all three database\r\n# a[0]is mail, a[1] is color, a[2] is name, b[0] is a mail,b[1]is date, c[0] is location, c[1] is color, c[2] is image link\r\n\r\n\r\nmaaail = 1\r\nfor b in entries2:\r\n for a in entries1:\r\n if b[0] == a[0]: # matching mail\r\n matchess = []\r\n linkk = []\r\n for c in entries3:\r\n\r\n if c[1].casefold() == a[1].casefold(): # matching color\r\n # storing location in list\r\n data_matched = [c[0]]\r\n matchess.append(data_matched)\r\n # storing image links in list\r\n link_matched = [c[2]]\r\n linkk.append(link_matched)\r\n continue\r\n if c[1] == \"null\":\r\n val = c[3].split(\",\")\r\n for v in val:\r\n vs = str(v)\r\n if vs.casefold() == a[1].casefold():\r\n data_matched = [c[0]]\r\n matchess.append(data_matched)\r\n # storing image links in list\r\n link_matched = [c[2]]\r\n linkk.append(link_matched)\r\n\r\n # print(\"Mail:\", b[0], \"Location:\", matchess)\r\n\r\n # Making a mail template\r\n if len(matchess) == 0:\r\n continue\r\n f = open(\"textformat.txt\", \"w\")\r\n sent = \"Hello \" + \\\r\n str(a[2]) + \"!\" + \" \\n \\n \\n \\t \\tWe have collected certain images based on your features and thier locations are: \\n \\n \"\r\n for ii in range(0, len(matchess)):\r\n sent = sent + \"\\t\\t\\t\" + str(ii+1) + \") \" + str(\r\n matchess[ii][0]) + \" and the image link is \" + str(linkk[ii][0]) + \"\\n \\n\"\r\n continue\r\n f.write(sent)\r\n f.close()\r\n\r\n # print(sent)\r\n fii = open(\"textformat.txt\")\r\n final = fii.read()\r\n # print(final)\r\n\r\n # Sending Mail\r\n msg = EmailMessage()\r\n msg['Subject'] = \"Vehicle Matching\"\r\n msg['From'] = \"Vehicle Detector Application\"\r\n msg['to'] = b[0]\r\n\r\n location = \"Your cars are found in \" + str(matchess)\r\n msg.set_content(final)\r\n\r\n server = smtplib.SMTP_SSL('smtp.gmail.com', 465)\r\n server.login(\"vehicledetectorproject@gmail.com\",\r\n \"kumarannaveenpradeish14\")\r\n server.send_message(msg)\r\n server.quit()\r\n print(\"Mail\" + str(maaail)+\" Sent!\")\r\n print(\"************************************\")\r\n maaail = maaail + 1\r\n f.close()\r\n\r\nprint(\"All emails sent!!!\")\r\n","sub_path":"serverr.py","file_name":"serverr.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"540790506","text":"\"\"\"\nmini_qa.py\n~~~~~~~~~~\n\nToy question-answering program.\n\"\"\"\n\n#### Library imports\n\n# standard library\nfrom collections import defaultdict\nimport pickle as pickle\nimport json\nimport re\nimport sys\nfrom xml.etree import ElementTree\n\nfrom google import search\n\n\n#### Config\n\ntry:\n import config\nexcept ImportError:\n print (\"Failed to import config. Enter configuration data into\\n\"\n \"config.py.example, and rename it to config.py.\")\n sys.exit()\n\n#### Parameters used to score results returned from the Google-based\n#### system\nCAPITALIZATION_FACTOR = 2.2\nQUOTED_QUERY_SCORE = 5\nUNQUOTED_QUERY_SCORE = 2\n\n\ndef pretty_qa(question, num=10):\n \"\"\"Wrapper for the `qa` function. `pretty_qa` queries Google to\n answer `question`. Only the top `num` are printed (with scores in\n parentheses).\n\n \"\"\"\n print(\"\\nQ: \"+question)\n for (j, (answer, score)) in enumerate(qa(question)[:num]):\n print(\"%s. %s (%s)\" % (j+1, answer, score))\n\ndef qa(question):\n \"\"\"Return a list of tuples whose first entry is a candidate answer to\n `question`, and whose second entry is the score for that answer.\n The tuples are ordered in decreasing order of score.\n\n \"\"\"\n answer_scores = defaultdict(int)\n for query in rewritten_queries(question):\n for summary in search(query.query):\n for sentence in sentences(summary):\n for ngram in candidate_answers(sentence, query.query):\n answer_scores[ngram] += ngram_score(\n ngram, query.score)\n ngrams_with_scores = sorted(iter(answer_scores.items()), \n key=lambda x: x[1], \n reverse=True)\n return [(\" \".join(ngram), score) \n for (ngram, score) in ngrams_with_scores]\n\ndef rewritten_queries(question):\n \"\"\"Return a list of RewrittenQuery objects, containing the search\n queries (and corresponding weighting score) generated from\n `question`.\n\n \"\"\"\n rewrites = [] \n tq = tokenize(question)\n verb = tq[1] # the simplest assumption, something to improve\n rewrites.append(\n RewrittenQuery(\"\\\"%s %s\\\"\" % (verb, \" \".join(tq[2:])), \n QUOTED_QUERY_SCORE))\n for j in range(2, len(tq)):\n rewrites.append(\n RewrittenQuery(\n \"\\\"%s %s %s\\\"\" % (\n \" \".join(tq[2:j+1]), verb, \" \".join(tq[j+1:])),\n QUOTED_QUERY_SCORE))\n rewrites.append(RewrittenQuery(\" \".join(tq[2:]), UNQUOTED_QUERY_SCORE))\n return rewrites\n\ndef tokenize(question):\n \"\"\"Return a list containing a tokenized form of `question`. Works by\n lowercasing, splitting around whitespace, and stripping all\n non-alphanumeric characters.\n\n \"\"\"\n return [re.sub(r\"\\W\", \"\", x) for x in question.lower().split()]\n\n\nclass RewrittenQuery():\n \"\"\"Given a question we rewrite it as a query to send to Google.\n Instances of the RewrittenQuery class are used to store these\n rewritten queries. Instances have two attributes: the text of the\n rewritten query, which is sent to Google; and a score, indicating\n how much weight to give to the answers. The score is used because\n some queries are much more likely to give highly relevant answers\n than others.\n\n \"\"\"\n\n def __init__(self, query, score):\n self.query = query\n self.score = score\n\n\ndef sentences(summary):\n \"\"\"Return a list whose entries are the sentences in the\n BeautifulSoup.BeautifulSoup object `summary` returned from Google.\n Note that the sentences contain alphabetical and space characters\n only, and all punctuation, numbers and other special characters\n have been removed.\n\n \"\"\"\n text = remove_spurious_words(text_of(summary))\n sentences = [sentence for sentence in text.split(\".\") if sentence]\n return [re.sub(r\"[^a-zA-Z ]\", \"\", sentence) for sentence in sentences]\n\ndef text_of(soup):\n \"\"\"Return the text associated to the BeautifulSoup.BeautifulSoup\n object `soup`.\n\n \"\"\"\n return ''.join([str(x) for x in soup.findAll(text=True)])\n\ndef remove_spurious_words(text):\n \"\"\"Return `text` with spurious words stripped. For example, Google\n includes the word \"Cached\" in many search summaries, and this word\n should therefore mostly be ignored.\n\n \"\"\"\n spurious_words = [\"Cached\", \"Similar\"]\n for word in spurious_words:\n text = text.replace(word, \"\")\n return text\n\ndef candidate_answers(sentence, query):\n \"\"\"Return all the 1-, 2-, and 3-grams in `sentence`. Terms appearing\n in `query` are filtered out. Note that the n-grams are returned\n as a list of tuples. So a 1-gram is a tuple with 1 element, a\n 2-gram is a tuple with 2 elements, and so on.\n\n \"\"\"\n filtered_sentence = [word for word in sentence.split() \n if word.lower() not in query]\n return sum([ngrams(filtered_sentence, j) for j in range(1,4)], [])\n\ndef ngrams(words, n=1):\n \"\"\"Return all the `n`-grams in the list `words`. The n-grams are\n returned as a list of tuples, each tuple containing an n-gram, as\n per the description in `candidate_answers`.\n\n \"\"\"\n return [tuple(words[j:j+n]) for j in range(len(words)-n+1)]\n\ndef ngram_score(ngram, score):\n \"\"\"Return the score associated to `ngram`. The base score is\n `score`, but it's modified by a factor which is\n `CAPITALIZATION_FACTOR` to the power of the number of capitalized\n words. This biases answers toward proper nouns.\n\n \"\"\"\n num_capitalized_words = sum(\n 1 for word in ngram if is_capitalized(word)) \n return score * (CAPITALIZATION_FACTOR**num_capitalized_words)\n\ndef is_capitalized(word):\n \"\"\"Return True or False according to whether `word` is capitalized.\n\n \"\"\"\n return word == word.capitalize()\n\n\nif __name__ == \"__main__\":\n pretty_qa(\"Who ran the first four-minute mile?\")\n pretty_qa(\"Who makes the best pizza in New York?\")\n pretty_qa(\"Who invented the C programming language?\")\n pretty_qa(\"Who wrote the Iliad?\")\n pretty_qa(\"Who caused the financial crash of 2008?\")\n pretty_qa(\"Who caused the Great Depression?\")\n pretty_qa(\"Who is the most evil person in the world?\")\n pretty_qa(\"Who wrote the plays of Wiliam Shakespeare?\")\n pretty_qa(\"Who is the world's best tennis player?\")\n pretty_qa(\"Who is the richest person in the world?\")\n","sub_path":"mini_qa.py","file_name":"mini_qa.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"61102161","text":"#!/usr/bin/python\r\n\r\n'''This module contains the lower-level classes that allow an RTSP pipeline to\r\nbe built and manipulated. Currently, only Axis P1347 cameras have been tested\r\nwith motion jpeg encoding.'''\r\n\r\n__author__ = 'Paul Milliken'\r\n__licence__ = 'GPLv3'\r\n__version__ = 0.1\r\n__maintainer__ = 'Paul Milliken'\r\n__email__ = 'paul.milliken@gmail.com'\r\n__status__ = 'Prototype'\r\n\r\nimport pygst\r\npygst.require('0.10')\r\nimport gst\r\nimport gtk\r\nimport datetime\r\n\r\nclass RtspBaseClass:\r\n '''RtspBaseClass is a base class that provides the building blocks for other\r\n classes that create rtsp pipelines. Commonly used gstreamer pipeline \r\n elements and callback methods are defined within.'''\r\n \r\n def createEmptyPipeline(self):\r\n self.pipeline = gst.Pipeline('mypipeline')\r\n\r\n def createVideobalanceElement(self):\r\n self.videobalance = gst.element_factory_make('videobalance', \\\r\n 'videobalance')\r\n self.videobalance.set_property('brightness', 0.0)\r\n\r\n def createVideoscaleElement(self):\r\n self.videoscale = gst.element_factory_make('videoscale', 'videoscale')\r\n\r\n def createVideorateElement(self):\r\n self.videorate = gst.element_factory_make('videorate', 'videorate')\r\n\r\n def createCapsfilterElement(self):\r\n self.capsfilter = gst.element_factory_make('capsfilter', 'capsfilter')\r\n caps = 'video/x-raw-yuv,framerate=10/1,width=1024,height=768'\r\n self.capsfilter.set_property('caps',gst.caps_from_string(caps))\r\n\r\n def createFfmpegcolorspaceElement(self):\r\n self.ffmpegcolorspace = gst.element_factory_make('ffmpegcolorspace', \\\r\n 'ffmpegcolorspace')\r\n\r\n def createTeeElement(self):\r\n self.tee = gst.element_factory_make('tee', 'tee')\r\n\r\n def createQueueFileElement(self):\r\n self.queueFile = gst.element_factory_make('queue', 'queueFile')\r\n\r\n def createQueueDisplayElement(self):\r\n self.queueDisplay = gst.element_factory_make('queue', 'queueDisplay')\r\n\r\n def createTheoraencElement(self):\r\n self.theoraenc = gst.element_factory_make('theoraenc', 'theoraenc')\r\n\r\n def createJpegencElement(self):\r\n self.jpegenc = gst.element_factory_make('jpegenc', 'jpegenc')\r\n\r\n def createOggmuxElement(self):\r\n self.oggmux = gst.element_factory_make('oggmux', 'oggmux')\r\n\r\n def createAvimuxElement(self):\r\n self.avimux = gst.element_factory_make('avimux', 'avimux')\r\n\r\n def createFilesinkElement(self):\r\n self.filesink = gst.element_factory_make('filesink', 'filesink')\r\n self.assignOutputFilename()\r\n\r\n def assignOutputFilename(self):\r\n '''self.outputFilename is of the form \r\n year_month_day_hour_minute_second.avi'''\r\n now = datetime.datetime.now()\r\n outputFilename = \\\r\n './%s_%s_%s_%s_%s_%s.avi' % (now.year, \\\r\n str(now.month).zfill(2), str(now.day).zfill(2), \\\r\n str(now.hour).zfill(2), str(now.minute).zfill(2), \\\r\n str(now.second).zfill(2))\r\n self.filesink.set_property('location', outputFilename)\r\n\r\n def createRtspsrcElement(self):\r\n '''The name of each rtsp source element is a string representing its\r\n ipaddress'''\r\n self.source = gst.element_factory_make('rtspsrc', 'source')\r\n self.source.set_property('latency', 0)\r\n self.formRtspUri()\r\n self.source.set_property('location', self.rtspUri)\r\n\r\n def resetIPAddress(self, ipAddress):\r\n self.ipAddress = ipAddress\r\n self.formRtspUri()\r\n print('Attempting to change uri to %s' % self.rtspUri)\r\n self.source.set_property('location', self.rtspUri)\r\n print(self.source.get_property('location'))\r\n\r\n def formRtspUri(self):\r\n '''The rtsp stream can be accessed via this string on Axis cameras:'''\r\n self.rtspUri = \\\r\n 'rtsp://%s:554/axis-media/media.amp?videocodec=jpeg&audio=0' %\\\r\n (self.ipAddress)\r\n\r\n def createDepayElement(self):\r\n '''creates jpeg depayer element'''\r\n self.depay = gst.element_factory_make('rtpjpegdepay','mydepay')\r\n \r\n def createDecodeElement(self):\r\n '''creates mjpeg decoder element'''\r\n self.decode = gst.element_factory_make('ffdec_mjpeg','mydecode')\r\n\r\n def createCropElement(self):\r\n self.crop = gst.element_factory_make('videocrop','mycropper')\r\n self.crop.set_property('top', 0)\r\n self.crop.set_property('bottom', 0)\r\n self.crop.set_property('left', 0)\r\n self.crop.set_property('right', 0)\r\n \r\n def createXvimagesinkElement(self):\r\n '''Use an xvimagesink rather than ximagesink to utilise video chip\r\n for scaling etc.'''\r\n self.xvimagesink = gst.element_factory_make('xvimagesink', \\\r\n 'xvimagesink')\r\n self.xvimagesink.set_xwindow_id(self.xid)\r\n \r\n def createPipelineCallbacks(self):\r\n '''Note that source is an rtspsrc element which has a dynamically \r\n created source pad. This means it can only be linked after the pad has\r\n been created. Therefore, the linking is done with the callback function\r\n onPadAddedToRtspsrc(...):'''\r\n self.source.connect('pad-added', self.onPadAddedToRtspsrc)\r\n self.source.connect('pad-removed', self.onPadRemovedFromRtspsrc)\r\n\r\n def onPadAddedToRtspsrc(self, rtspsrc, pad):\r\n '''This callback is required because rtspsrc elements have\r\n dynamically created pads. So linking can only occur after a pad\r\n has been created. Furthermore, only the rtspsrc for the currently\r\n selected camera is linked to the depayer.'''\r\n print('pad added to rtspsrc element.')\r\n self.xvimagesink.set_xwindow_id(self.xid)\r\n depaySinkPad = self.depay.get_pad('sink')\r\n pad.link(depaySinkPad)\r\n\r\n def onPadRemovedFromRtspsrc(self, rtspsrc, pad):\r\n '''Unlinks the rtspsrc element from the depayer'''\r\n print('pad removed from rtspsrc element.')\r\n depaySinkPad = self.depay.get_pad('sink')\r\n pad.unlink(depaySinkPad)\r\n\r\n def pauseOrUnpauseVideo(self):\r\n '''Toggles between the paused and playing states'''\r\n if (self.pipeline.get_state()[1]==gst.STATE_PAUSED):\r\n self.setPipelineStateToPlaying()\r\n else:\r\n self.setPipelineStateToPaused()\r\n \r\n def setPipelineStateToPlaying(self):\r\n self.pipeline.set_state(gst.STATE_PLAYING)\r\n\r\n def setPipelineStateToPaused(self):\r\n self.pipeline.set_state(gst.STATE_PAUSED)\r\n\r\n def setPipelineStateToNull(self):\r\n self.pipeline.set_state(gst.STATE_NULL)\r\n\r\n def setCurrentCropProperties(self, left, right, top, bottom):\r\n '''Sets borders for the videocrop element'''\r\n try:\r\n self.crop.set_property('left', left)\r\n self.crop.set_property('right', right)\r\n self.crop.set_property('top', top)\r\n self.crop.set_property('bottom', bottom)\r\n except:\r\n print('Cannot set crop properties. Check videocrop element exists')\r\n \r\nclass RtspPipelineToDisplay(RtspBaseClass):\r\n '''This class creates and rtsp pipeline that takes displays an rtsp stream\r\n to an xvimagesink that is displayed in a GTK window. Arguments are the ip\r\n address of the camera and the xwindow id where the image will be displayed.\r\n The Gstreamer pipeline elements are inherited from the RtspBaseClass \r\n class.'''\r\n \r\n def __init__(self, ipAddress, xid):\r\n self.ipAddress = ipAddress\r\n # xid is the xwindow I.D. where the video stream will be displayed:\r\n self.xid = xid\r\n self.createGstreamerPipeline()\r\n \r\n def createGstreamerPipeline(self):\r\n '''This pipeline implements something similar to the following bash\r\n equivalent in Python: gst-launch-0.10 -vvv rtspsrc \r\n location='rtsp://192.168.1.60:554/axis-media/\r\n media.amp?videocodec=jpeg&audio=0' ! rtpjpegdepay ! ffdec_mjpeg ! ...\r\n ! xvimagesink'''\r\n self.createEmptyPipeline()\r\n self.createPipelineElements()\r\n self.addElementsToPipeline()\r\n self.linkPipelineElements()\r\n self.createPipelineCallbacks()\r\n\r\n def createPipelineElements(self):\r\n self.createRtspsrcElement()\r\n self.createDepayElement()\r\n self.createDecodeElement()\r\n self.createCropElement()\r\n self.createVideoscaleElement()\r\n self.createVideorateElement()\r\n self.createVideobalanceElement()\r\n self.createCapsfilterElement()\r\n self.createFfmpegcolorspaceElement()\r\n self.createXvimagesinkElement()\r\n\r\n def addElementsToPipeline(self):\r\n '''Add elements to the pipeline'''\r\n self.pipeline.add(self.source)\r\n self.pipeline.add(self.depay)\r\n self.pipeline.add(self.decode)\r\n self.pipeline.add(self.crop)\r\n self.pipeline.add(self.videoscale)\r\n self.pipeline.add(self.videorate)\r\n self.pipeline.add(self.videobalance)\r\n self.pipeline.add(self.capsfilter)\r\n self.pipeline.add(self.ffmpegcolorspace)\r\n self.pipeline.add(self.xvimagesink)\r\n\r\n def linkPipelineElements(self):\r\n '''Link all elements in pipeline except source which has a dynamic\r\n source pad'''\r\n self.depay.link(self.decode)\r\n self.decode.link(self.crop)\r\n self.crop.link(self.videoscale)\r\n self.videoscale.link(self.videorate)\r\n self.videorate.link(self.videobalance)\r\n self.videobalance.link(self.capsfilter)\r\n self.capsfilter.link(self.ffmpegcolorspace)\r\n self.ffmpegcolorspace.link(self.xvimagesink)\r\n\r\nclass RtspPipelineToFileAndDisplay(RtspBaseClass):\r\n '''This class writes an rtsp stream to file and symultaneously displays the\r\n stream to an xvimagesink. It is similar to the RtspPipelineToDisplay class\r\n with the addition of recording to file.'''\r\n \r\n def __init__(self, ipAddress, xid):\r\n self.ipAddress = ipAddress\r\n # xid is the xwindow I.D. where the video stream will be displayed:\r\n self.xid = xid\r\n self.createGstreamerPipeline()\r\n \r\n def createGstreamerPipeline(self):\r\n '''This pipeline implements something similar to the following bash\r\n equivalent in Python: gst-launch-0.10 -vvv rtspsrc \r\n location='rtsp://192.168.1.60:554/axis-media/\r\n media.amp?videocodec=jpeg&audio=0' ! rtpjpegdepay ! ffdec_mjpeg ! ...\r\n ! xvimagesink'''\r\n self.createEmptyPipeline()\r\n self.createPipelineElements()\r\n self.addElementsToPipeline()\r\n self.linkPipelineElements()\r\n self.createPipelineCallbacks()\r\n \r\n def createPipelineElements(self):\r\n '''Create the elements required for the pipeline'''\r\n self.createRtspsrcElement()\r\n self.createDepayElement()\r\n self.createDecodeElement()\r\n self.createCropElement()\r\n self.createVideoscaleElement()\r\n self.createVideorateElement()\r\n self.createVideobalanceElement()\r\n self.createCapsfilterElement()\r\n self.createFfmpegcolorspaceElement()\r\n self.createTeeElement()\r\n self.createQueueFileElement()\r\n self.createQueueDisplayElement()\r\n# self.createTheoraencElement()\r\n# self.createOggmuxElement()\r\n self.createJpegencElement()\r\n self.createAvimuxElement()\r\n self.createFilesinkElement()\r\n self.createXvimagesinkElement()\r\n\r\n def addElementsToPipeline(self):\r\n '''Add the elements to the pipeline'''\r\n self.pipeline.add(self.source)\r\n self.pipeline.add(self.depay)\r\n self.pipeline.add(self.decode)\r\n self.pipeline.add(self.crop)\r\n self.pipeline.add(self.videoscale)\r\n self.pipeline.add(self.videorate)\r\n self.pipeline.add(self.videobalance)\r\n self.pipeline.add(self.capsfilter)\r\n self.pipeline.add(self.ffmpegcolorspace)\r\n self.pipeline.add(self.tee)\r\n self.pipeline.add(self.queueFile)\r\n self.pipeline.add(self.queueDisplay)\r\n# self.pipeline.add(self.theoraenc)\r\n# self.pipeline.add(self.oggmux)\r\n self.pipeline.add(self.jpegenc)\r\n self.pipeline.add(self.avimux)\r\n self.pipeline.add(self.filesink)\r\n self.pipeline.add(self.xvimagesink)\r\n\r\n def linkPipelineElements(self):\r\n '''Link all elements in pipeline except source which has a dynamic\r\n source pad'''\r\n self.depay.link(self.decode)\r\n self.decode.link(self.crop)\r\n self.crop.link(self.videoscale)\r\n self.videoscale.link(self.videorate)\r\n self.videorate.link(self.videobalance)\r\n self.videobalance.link(self.capsfilter)\r\n self.capsfilter.link(self.ffmpegcolorspace)\r\n self.ffmpegcolorspace.link(self.tee)\r\n self.tee.link(self.queueFile)\r\n# self.queueFile.link(self.theoraenc)\r\n# self.theoraenc.link(self.oggmux)\r\n# self.oggmux.link(self.filesink)\r\n self.queueFile.link(self.jpegenc)\r\n self.jpegenc.link(self.avimux)\r\n self.avimux.link(self.filesink)\r\n self.tee.link(self.queueDisplay)\r\n self.queueDisplay.link(self.xvimagesink)\r\n\r\nclass RtspPipelineLightenOnly(RtspBaseClass):\r\n '''This class displays an rtsp stream to the screen with brightness\r\n adjustment and no PTZ functions'''\r\n \r\n def __init__(self, ipAddress, xid):\r\n self.ipAddress = ipAddress\r\n # xid is the xwindow I.D. where the video stream will be displayed:\r\n self.xid = xid\r\n self.createGstreamerPipeline()\r\n \r\n def createGstreamerPipeline(self):\r\n '''This pipeline implements something similar to the following bash\r\n equivalent in Python: gst-launch-0.10 -vvv rtspsrc \r\n location='rtsp://192.168.1.60:554/axis-media/\r\n media.amp?videocodec=jpeg&audio=0' ! rtpjpegdepay ! ffdec_mjpeg ! ...\r\n ! xvimagesink'''\r\n self.createEmptyPipeline()\r\n self.createPipelineElements()\r\n self.addElementsToPipeline()\r\n self.linkPipelineElements()\r\n self.createPipelineCallbacks()\r\n \r\n def createPipelineElements(self):\r\n '''Create the elements required for the pipeline'''\r\n self.createRtspsrcElement()\r\n self.createDepayElement()\r\n self.createDecodeElement()\r\n self.createVideobalanceElement()\r\n self.createXvimagesinkElement()\r\n\r\n def addElementsToPipeline(self):\r\n '''Add the elements to the pipeline'''\r\n self.pipeline.add(self.source)\r\n self.pipeline.add(self.depay)\r\n self.pipeline.add(self.decode)\r\n self.pipeline.add(self.videobalance)\r\n self.pipeline.add(self.xvimagesink)\r\n\r\n def linkPipelineElements(self):\r\n '''Link all elements in pipeline except source which has a dynamic\r\n source pad'''\r\n self.depay.link(self.decode)\r\n self.decode.link(self.videobalance)\r\n self.videobalance.link(self.xvimagesink)\r\n\r\nclass RtspPipelineSimple(RtspBaseClass):\r\n '''This class displays an rtsp stream to the screen with no PTZ or \r\n brightness adjustment'''\r\n \r\n def __init__(self, ipAddress, xid):\r\n self.ipAddress = ipAddress\r\n # xid is the xwindow I.D. where the video stream will be displayed:\r\n self.xid = xid\r\n self.createGstreamerPipeline()\r\n \r\n def createGstreamerPipeline(self):\r\n '''This pipeline implements something similar to the following bash\r\n equivalent in Python: gst-launch-0.10 -vvv rtspsrc \r\n location='rtsp://192.168.1.60:554/axis-media/\r\n media.amp?videocodec=jpeg&audio=0' ! rtpjpegdepay ! ffdec_mjpeg ! ...\r\n ! xvimagesink'''\r\n self.createEmptyPipeline()\r\n self.createPipelineElements()\r\n self.addElementsToPipeline()\r\n self.linkPipelineElements()\r\n self.createPipelineCallbacks()\r\n \r\n def createPipelineElements(self):\r\n '''Create the elements required for the pipeline'''\r\n self.createRtspsrcElement()\r\n self.createDepayElement()\r\n self.createDecodeElement()\r\n self.createXvimagesinkElement()\r\n\r\n def addElementsToPipeline(self):\r\n '''Add the elements to the pipeline'''\r\n self.pipeline.add(self.source)\r\n self.pipeline.add(self.depay)\r\n self.pipeline.add(self.decode)\r\n self.pipeline.add(self.xvimagesink)\r\n\r\n def linkPipelineElements(self):\r\n '''Link all elements in pipeline except source which has a dynamic\r\n source pad'''\r\n self.depay.link(self.decode)\r\n self.decode.link(self.xvimagesink)\r\n","sub_path":"AxisRtsp.py","file_name":"AxisRtsp.py","file_ext":"py","file_size_in_byte":16645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"77996933","text":"from django.db.models import query\nfrom django.shortcuts import render\nfrom django.db.models import Q\nfrom .models import Article, Lesson, Tutorial\nfrom itertools import chain\n\n# Create your views here.\n\ndef index(request):\n if request.method == 'POST':\n query = request.POST.get('search')\n if query is not None:\n lookups = Q(title__icontains = query) | Q(description__icontains=query) | Q(slug__icontains=query)\n\n article_data = Article.objects.filter(lookups).distinct()\n lesson_data = Lesson.objects.filter(lookups).distinct()\n tutorial_data = Tutorial.objects.filter(lookups).distinct()\n\n result = chain(article_data, lesson_data, tutorial_data)\n else:\n return render(request, 'search.html')\n \n context = {\n 'result': result,\n 'query':query\n \n } \n return render(request, 'search.html', context)","sub_path":"MultiSearch/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"49457321","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 findRightInterval(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: List[int]\n \"\"\"\n import bisect\n ref = sorted([(v.start, i) for i, v in enumerate(intervals)])\n result = []\n for x in intervals:\n ind = bisect.bisect_left(ref, (x.end, ))\n if ind != len(intervals):\n result.append(ref[ind][1])\n else:\n result.append(-1)\n return result","sub_path":"436-FindRightInterval/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"490464510","text":"import acm\n\n\ndef SetUp(definitionSetUp):\n import SP_AccumulatorSetup\n SP_AccumulatorSetup.Setup(definitionSetUp)\n\ndef SetUserBlockedDefaultValues(accumulator):\n # Set default values that the user should not be allowed to change\n # These fields are hidden or disbled from the Custom Instrument UI.\n accumulator.Quotation('Per Contract')\n accumulator.PayType('Spot')\n accumulator.ExerciseType('Bermudan')\n accumulator.Digital(False)\n accumulator.StrikeQuotation(None)\n accumulator.Generic(True)\n accumulator.StrikeType('Absolute')\n\ndef SetUserBlockedExoticValues(accumulator):\n # Default values on the exotic record.\n barrierType = 'Up & Out' if accumulator.OptionTypeIsCall() else 'Down & Out'\n accumulator.Exotic().BarrierOptionType(barrierType)\n\ndef SetStrikeEqualUnderlying(accumulator):\n if accumulator.Underlying():\n calcSpace = acm.FCalculationMethods().CreateStandardCalculationsSpaceCollection()\n price = accumulator.Underlying().Calculation().MarketPrice(calcSpace).Value()\n if (price and price.Number() > 0.0):\n accumulator.StrikePrice(price.Number())\n\ndef SetDefaultIfMissing(accumulator):\n if accumulator.StartDate()is None or accumulator.StartDate() == '':\n accumulator.StartDate(acm.Time().DateToday())\n \n monitoring = accumulator.Exotic().BarrierMonitoring()\n if monitoring is None or monitoring not in ('Continuous', 'Discrete'):\n accumulator.Exotic().BarrierMonitoring('Continuous')\n \n if accumulator.Barrier() is None or accumulator.Barrier() == 0.0:\n accumulator.Barrier(accumulator.StrikePrice())\n\ndef SetAdditionalInfoFromDefaultValue(accumulator):\n default = acm.FAdditionalInfoSpec['AccumulatorLeverage'].DefaultValue()\n # Set leverage to 2 if no default value or if defuatl value is 0\n accumulator.AdditionalInfo().AccumulatorLeverage(default if default else 2.0)\n\ndef AccumulatorInstrumentDefaultHook(accumulator):\n # Set the filter criteria\n accumulator.AdditionalInfo().StructureType('Accumulator')\n\n SetAdditionalInfoFromDefaultValue(accumulator)\n\n SetUserBlockedDefaultValues(accumulator)\n\n # Make sure that the instrument is created with \n # an exotic record\n accumulator.CreateExotic()\n \n SetUserBlockedExoticValues(accumulator)\n \n # Set Strike price equal to underlying price\n SetStrikeEqualUnderlying(accumulator)\n\n SetDefaultIfMissing(accumulator)\n\ndef SetUserBlockedFxDefaultValues(accumulator):\n\n # Make sure that the instrument is created with \n # an exotic record\n accumulator.CreateExotic()\n\n # Set default values that the user should not be allowed to change\n # These fields are hidden or disbled from the Custom Instrument UI.\n storeAwayMonitoring = accumulator.Exotic().BarrierMonitoring()\n accumulator.Exotic().BaseType('Barrier')\n accumulator.Exotic().BarrierMonitoring(storeAwayMonitoring)\n\n if accumulator.OptionTypeIsCall():\n accumulator.Exotic().BarrierOptionType('Up & Out')\n else:\n accumulator.Exotic().BarrierOptionType('Down & Out')\n accumulator.ExerciseType('Bermudan')\n accumulator.Quotation('Per Contract')\n accumulator.PayType('Spot')\n accumulator.Generic(True)\n accumulator.Exotic().FxoRebate(0.0)\n\ndef SetFxStrikeEqualUnderlying(accumulator):\n if accumulator.Underlying():\n calcSpace = acm.FCalculationMethods().CreateStandardCalculationsSpaceCollection()\n if accumulator.ForeignCurrency() and accumulator.DomesticCurrency():\n price = accumulator.ForeignCurrency().Calculation().FXRate(calcSpace, accumulator.DomesticCurrency()).Value()\n if (price and price.Number() > 0.0):\n accumulator.StrikeDomesticPerForeign(price.Number())\n\ndef SetFxDefaultIfMissing(accumulator):\n if accumulator.StartDate()is None or accumulator.StartDate() == '':\n accumulator.StartDate(acm.Time().DateToday())\n \n monitoring = accumulator.Exotic().BarrierMonitoring()\n if monitoring is None or monitoring not in ('Continuous', 'Discrete'):\n accumulator.Exotic().BarrierMonitoring('Continuous')\n \n if accumulator.Barrier() is None or accumulator.Barrier() == 0.0:\n accumulator.Exotic().BarrierDomesticPerForeign(accumulator.StrikeDomesticPerForeign())\n\ndef FxAccumulatorInstrumentDefaultHook(accumulator):\n AccDecorator = acm.FBusinessLogicDecorator.WrapObject(accumulator)\n\n # Set the filter criteria\n AccDecorator.AdditionalInfo().StructureType('Accumulator')\n\n SetUserBlockedFxDefaultValues(AccDecorator)\n\n SetAdditionalInfoFromDefaultValue(AccDecorator)\n \n # Add strike and missing default values\n SetFxStrikeEqualUnderlying(AccDecorator)\n\n SetFxDefaultIfMissing(AccDecorator)\n\ndef DataMaint(instrument, dateToday, updateHistorical, updateResult):\n return ['Price Fixing']\n\n","sub_path":"Extensions/StructuredProductsDealPackage/FPythonCode/SP_AccumulatorCustomInsDef.py","file_name":"SP_AccumulatorCustomInsDef.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"465049618","text":"'''\nThis script is to detect faces in a video.\nIt was initally made as a proof of concept to detect the characters in the Avengers movie.\nThe dataset was created by webscraping from google images.\nGoogle colab was used to find embeddings and train the model due to lack of computational power on my laptop.s\n'''\n\n# Import all modules\nimport os\nimport cv2\nfrom imutils import paths\nimport argparse\nimport pickle\nimport face_recognition\nfrom imutils.video import VideoStream\n\n# Extract all faces from the downloaded dataset and save them to a separate folder.\n\n\ndef extract_face():\n p = os.listdir(os.getcwd() + '/data/downloads/')\n face_detector = cv2.CascadeClassifier(\n os.getcwd() + '/casc/haarcascade_frontalface_default.xml')\n\n for direc in p:\n try:\n os.mkdir(os.getcwd() + '/data/faces/{}'.format(direc))\n except:\n pass\n\n images = os.listdir(os.getcwd() + '/data/downloads/' + direc)\n c = 1\n for img in images:\n img = cv2.imread(os.getcwd() + '/data/downloads/' + direc + '/' +\n img)\n faces = face_detector.detectMultiScale(img, 1.3, 5)\n for (x, y, w, h) in faces:\n x1 = x\n y1 = y\n x2 = x + w\n y2 = y + h\n cv2.rectangle(img, (x1, y1), (x2, y2), (255, 255, 255), 2)\n cv2.imwrite(\n os.getcwd() + '/data/faces/{}/{}.jpg'.format(direc, c),\n img[y1:y2, x1:x2])\n c += 1\n\n\n# To make local embeddings of the images\n\n\ndef make_embeddings():\n paths_image = list(paths.list_images(os.getcwd() + '/data/downloads/'))\n kEncodings, kNames = [], []\n for (i, paths_images) in enumerate(paths_image):\n print(\"[INFO] processing image {}/{}\".format(i + 1, len(paths_image)))\n name = paths_images.split(os.path.sep)[-2]\n img = cv2.imread(paths_images)\n rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n boxes = face_recognition.face_locations(rgb, model='cnn')\n encodings = face_recognition.face_encodings(rgb, boxes)\n\n for encoding in encodings:\n kEncodings.append(encoding)\n kNames.append(name)\n data = {'encodings': kEncodings, 'names': kNames}\n f = open(os.getcwd() + '/outputs/encodings.pkl', 'wb')\n f.write(pickle.dumps(data))\n f.close()\n\n\ndef recogIm():\n data = pickle.loads(\n open(os.getcwd() + '/outputs/encodings.pkl', 'rb').read())\n image = cv2.imread('test.jpeg')\n rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n boxes = face_recognition.face_locations(rgb, model='cnn')\n encodings = face_recognition.face_encodings(rgb, boxes)\n names = []\n for encoding in encodings:\n matches = face_recognition.compare_faces(data[\"encodings\"], encoding)\n name = 'Not Found'\n if True in matches:\n matchesId = [i for (i, b) in enumerate(matches) if b]\n counts = {}\n for i in matchesId:\n name = data['names'][i]\n counts[name] = counts.get(name, 0) + 1\n name = max(counts, key=counts.get)\n names.append(name)\n for ((top, right, bottom, left), name) in zip(boxes, names):\n cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)\n y = top - 15 if top - 15 > 15 else top + 15\n cv2.putText(image, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX, 0.75,\n (0, 255, 0), 2)\n\n cv2.imshow(\"Image\", image)\n cv2.waitKey(0)\n\n\ndef recogVid():\n data = pickle.loads(\n open(os.getcwd() + '/outputs/encodings.pkl', 'rb').read())\n cap = cv2.VideoCapture('test.mp4')\n annot = cv2.VideoWriter('annotated.mp4',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))\n while (cap.isOpened()):\n ret, image = cap.read()\n rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n boxes = face_recognition.face_locations(rgb, model='cnn')\n encodings = face_recognition.face_encodings(rgb, boxes)\n names = []\n for encoding in encodings:\n matches = face_recognition.compare_faces(data[\"encodings\"],\n encoding)\n name = 'Not Found'\n if True in matches:\n matchesId = [i for (i, b) in enumerate(matches) if b]\n counts = {}\n for i in matchesId:\n name = data['names'][i]\n counts[name] = counts.get(name, 0) + 1\n name = max(counts, key=counts.get)\n names.append(name)\n for ((top, right, bottom, left), name) in zip(boxes, names):\n cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)\n y = top - 15 if top - 15 > 15 else top + 15\n cv2.putText(image, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX, 0.75,\n (0, 255, 0), 2)\n annot.write(image)\n cap.release()\n annot.release()\n\n\n# extract_face()\nrecogIm()\n# recogVid()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"421947934","text":"import socket\nimport time\n\nip = '0.0.0.0'\nport = 9999\n\nconnection = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\nconnection.bind((ip,port))\nconnection.listen(5)\n\nprint(\"listening on port 9999\")\n\nwhile True:\n client, addr = connection.accept()\n time.sleep(1)\n while True:\n x= str(input(f\"${addr[0]}: \"))\n client.send(x.encode())\n if x == \"exit\":\n client.close()\n break\n result = client.recv(1024)\n print(result.decode())\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"146355300","text":"# Autor: Carlos Alberto Reyes Ortiz\n# Descripcion: Calcula la distancia en km, en un tiempo de 7 hrs, 4.5hrs y la velocidad dada por el usuario. También puede calcular\n# El tiempo que tarda en hrs, en una distancia de 791km, igual por la velocidad dada por el usuario.\n# Escribe tu programa después de esta línea.\ntiempoUno = 7\ntiempoDos = 4.5\ndistanciaTres = 791\nvelocidad = int(input(\"Teclea la velocidad a la que viaja el auto:\"))\n\ndistanciaUno = tiempoUno * velocidad\ndistanciaDos = tiempoDos * velocidad\ntiempoTres = distanciaTres / velocidad\n\nprint(\"Distancia recorrida en 7 hrs:\", \"{:.1f}\" . format(distanciaUno)) # \"{:.1f}\" . format SIRVE PARA MARCAR\n # EL NUMERO DE DECIMALES QUE QUIERES\nprint(\"Distania recorrida en 4.5hrs:\", \"{:.1f}\" . format(distanciaDos))\nprint(\"Tiempo para recorrer 791 km:\", \"{:.1f}\" . format(tiempoTres))\n","sub_path":"auto.py","file_name":"auto.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"614065111","text":"# Your imports go here\nimport logging\nimport os\nimport json\nimport re\nlogger = logging.getLogger(__name__)\n'''\n Given a directory with receipt file and OCR output, this function should extract the amount\n\n Parameters:\n dirpath (str): directory path containing receipt and ocr output\n\n Returns:\n float: returns the extracted amount\n\n'''\ndef extract_amount(dirpath: str) -> float:\n\n logger.info('extract_amount called for dir %s', dirpath)\n # your logic goes here\n ocr_file = os.path.join(dirpath, 'ocr.json')\n text = []\n with open(ocr_file, encoding='utf-8') as json_file:\n data = json.load(json_file)\n for i in range(len(data[\"Blocks\"])):\n if 'Text' in data[\"Blocks\"][i]:\n obj = re.sub('[A-Za-z,]', '', data[\"Blocks\"][i][\"Text\"])\n obj = obj.replace('$', '')\n if re.match(r'\\d+\\.\\d+', obj):\n text.append(float(obj))\n return max(text)\n","sub_path":"extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"251559871","text":"from datetime import datetime\r\n\r\nclass Reservation:\r\n def __init__(self, title: str, number: int, start_time: datetime, end_time: datetime, fixed_price: int, paid_price: int) -> None:\r\n self._title = title\r\n self._number = number\r\n self._start_time = start_time\r\n self._end_time = end_time\r\n self._fixed_price = fixed_price\r\n self._paid_price = paid_price\r\n\r\n def __str__(self):\r\n return \"{} {} {} {} {} {}\".format(\r\n self._title, self._number, self._start_time, self._end_time, self._fixed_price, self._paid_price\r\n )","sub_path":"OBJECTS/MovieReservation/reservation.py","file_name":"reservation.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"417885362","text":"from Crypto.Signature import PKCS1_v1_5\nfrom Crypto.Hash import SHA\nfrom Crypto.PublicKey import RSA\nfrom Crypto import Random\nimport sqlite3\nimport serial\nimport time\nimport RPi.GPIO as GPIO\n\n\nGPIO.setmode(GPIO.BOARD)\n\n#open serial connection\nser = serial.Serial('/dev/ttyUSB0', 9600, write_timeout=10)\n\n#input from the sensor\npadPin = 23\nGPIO.setup(padPin, GPIO.IN)\n\nalreadyPressed = False\n\n#directory to the database\nfile_path = '/var/www/html/database/sensordata.db'\n\nmessage = 'Touch'.encode()\n#path to private key\nkey = RSA.importKey(open('/client/private_key.pem/private_key.pem', 'r').read())\n\n# an SQL script to implement a trigger in the database\nscript = ''' CREATE TRIGGER mytrigger\nBEFORE INSERT ON sensordata\nBEGIN\n SELECT CASE WHEN\n (SELECT COUNT (*) FROM sensordata) >= 3\n THEN\n RAISE(IGNORE)\n END;\nEND;\n'''\n\nwhile True:\n\n padPressed = GPIO.input(padPin)\n if padPressed and not alreadyPressed:\n print(message)\n\t\t#connects to the database and write data\n conn = sqlite3.connect(file_path)\n curs=conn.cursor()\n curs.execute('''DROP TRIGGER IF EXISTS mytrigger''')\n curs.executescript(script)\n curs.execute('''INSERT INTO sensordata VALUES(datetime('now'),(?))''',('pressed',))\n conn.commit()\n \n\n #count the rows in the database\n curs.execute('''SELECT COUNT (*) FROM sensordata''')\n rowcount = curs.fetchone()[0]\n print(rowcount)\n conn.close()\n if rowcount == 3:\n # close the database and sign the data and send it\n\n print('closed')\n digest = SHA.new(message)\n\n print(digest)\n print(message)\n signer = PKCS1_v1_5.new(key)\n sig = signer.sign(digest)\n ser.flushInput()\n ser.write(sig + '\\n'.encode())\n #time.sleep(5)\n alreadyPressed = padPressed\n time.sleep(0.1)\n","sub_path":"final_send.py","file_name":"final_send.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"326138494","text":"from BinaryRandomSigmoidNeuronTest import BinaryRandomSigmoidNeuronTest\n\nclass AndSigmoidNeuronTest(BinaryRandomSigmoidNeuronTest):\n def __init__(self, effectivityIterations, trainInput):\n super(AndSigmoidNeuronTest, self).__init__(effectivityIterations, trainInput)\n\n\n def expectedValue(self, x1Value, x2Value):\n return x1Value and x2Value\n\n\ntrainSet = [[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]]\norSigmoidNeuronTest = AndSigmoidNeuronTest(50, trainSet)\norSigmoidNeuronTest.train(100)\norSigmoidNeuronTest.effectivityGraphic()","sub_path":"Clase4/tests/AndSigmoidNeuron.py","file_name":"AndSigmoidNeuron.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"282267981","text":"import numpy as np\nimport tensorflow as tf\n\nslim = tf.contrib.slim\n\ndef cnn_context(inputs, scope=None, activation_fn=tf.nn.relu):\n\twith tf.variable_scope(None, 'cnn_net', [inputs]):\n\t\twith slim.arg_scope([slim.conv2d], stride=1, padding='SAME'):\n\t\t\tnet1 = slim.conv2d(inputs, 2048, [3,1],rate=1,scope='Conv2d_net1_3x1')\n\t\t\tnet2 = slim.conv2d(net1, 1024, [3,1],rate=1,scope='Conv2d_net2_3x1')\n\t\t\tnet3 = slim.conv2d(net2, 512, [3,1],rate=1,scope='Conv2d_net3_3x1')\n\t\t\tnet4 = slim.conv2d(net3, 256, [3,1],rate=1,scope='Conv2d_net4_3x1')\n\t\t\tnet5 = slim.conv2d(net4, 128, [3,1],rate=2,scope='Conv2d_net5_3x1')\n\t\t\tnet6 = slim.conv2d(net5, 64, [3,1],rate=4,scope='Conv2d_net6_3x1')\n\t\t\tnet7 = slim.conv2d(net6, 32, [3,1],rate=8,scope='Conv2d_net7_3x1')\n\t\t\tnet8 = slim.conv2d(net7, 16, [3,1],rate=16,scope='Conv2d_net8_3x1')\n\t\t\tnet9 = tf.concat(axis=3,values=[net1,net2,net3,net4,net5,net6,net7,net8])\n\t\t\tnet10 = slim.conv2d(net9, 640, [3,1],rate=1,scope='Conv2d_net10_3x1')\n\t\t\tnet11 = slim.conv2d(net10, 8, [3,1],rate=1,scope='Conv2d_net11_3x1')\n\t\t\tnet12 = slim.conv2d(net11, 8, [3,1],rate=1,scope='Conv2d_net12_3x1')\n\t\t\tnet13 = slim.conv2d(net12, 8, [3,1],rate=1,scope='Conv2d_net13_3x1')\n\t\t\tnet14 = slim.conv2d(net13, 8, [3,1],rate=1,scope='Conv2d_net14_3x1')\n\t\t\tnet15 = tf.concat(axis=3,values=[net11,net12,net13,net14])\n\t\t\tnet16 = slim.conv2d(net15, 32, [3,1],rate=1,scope='Conv2d_net16_3x1')\n\t\t\tnet17 = tf.concat(axis=3,values=[inputs,net10,net16])\n\t\t\tnet18 = slim.conv2d(net17, 320, [1,1],rate=1,scope='Conv2d_net18_3x1')\n\t\t\tnetout = slim.conv2d(net18, 3, [1,1],rate=1,activation_fn=None,scope='Conv2d_netout')\n\n\treturn netout\n","sub_path":"context/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"225634841","text":"#-*- coding: utf-8\n\nfrom MovingGrating import MovingGrating\n\nclass SquareMovingGrating(MovingGrating):\n\t'''\n\tОтображает движущуюся прямоугольную решётку\n\t'''\n\tdef __str__(self):\n\t\treturn \"square moving grating C = {0}, sf = {1}, tf = {4}, phase = {2}, orientation = {3}\".\\\n\t\t\tformat(self.getContrast(), self.getSpatialFrequency(), self.getSpatialPhase(), \n\t\t\t\tself.getOrientation(), self.getTemporalFrequency())\n\n\tdef getMovingImage(self, t):\n\t\tA = self._getAmplitude()\n\t\timg = super(SquareMovingGrating, self).getMovingImage(t)\n\t\timg[img>=0.5] = 0.5+A\n\t\timg[img<0.5] = 0.5-A\n\t\treturn img","sub_path":"kozhukhov/Stimulus/SquareMovingGrating.py","file_name":"SquareMovingGrating.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"240730203","text":"from .exceptions import *\nimport random\n\nclass GuessAttempt(object):\n def __init__(self,guess,hit=False,miss=False):\n if hit and miss:\n raise InvalidGuessAttempt\n self.guess = guess\n self.hit = hit\n self.miss = miss\n \n def is_hit(self):\n return self.hit\n \n def is_miss(self):\n return self.miss\n\nclass GuessWord(object):\n def __init__(self,answer):\n if not answer:\n raise InvalidWordException\n self.answer = answer\n self.masked = '*' * len(answer)\n \n \n def perform_attempt(self,guess):\n hit = False\n miss = True\n \n if len(guess) > 1:\n raise InvalidGuessedLetterException\n orig_masked = self.masked\n list_masked = list(self.masked)\n list_answer = list(self.answer)\n \n if guess.lower() in self.answer.lower():\n for i,v in enumerate(self.answer):\n if v.lower() == guess.lower():\n list_masked[i] = guess.lower()\n self.masked = ''.join(list_masked)\n \n if orig_masked != self.masked:\n hit = True\n miss = False\n \n attempt = GuessAttempt(guess,hit,miss)\n return attempt\n\nclass HangmanGame(object):\n WORD_LIST = ['rmotr', 'python', 'awesome']\n \n def __init__(self,word_list=['rmotr', 'python', 'awesome'],number_of_guesses=5):\n self.WORD_LIST = word_list\n self.remaining_misses = number_of_guesses\n self.previous_guesses = []\n self.word = GuessWord(random.choice(word_list))\n \n @classmethod\n def select_random_word(cls, w_list):\n cls.word = cls.get_random(w_list)\n return cls.word.answer\n \n @classmethod\n def get_random(cls, word_list):\n if not word_list:\n raise InvalidListOfWordsException\n word = random.choice(word_list)\n return GuessWord(word)\n\n def guess (self, guess):\n if self.is_lost() or self.is_won():\n raise GameFinishedException()\n attempt = self.word.perform_attempt(guess)\n if attempt.is_miss():\n self.remaining_misses -= 1\n self.previous_guesses.append(attempt.guess.lower())\n if self.is_won():\n raise GameWonException()\n if self.is_lost():\n raise GameLostException()\n return attempt\n \n def is_finished(self):\n return self.is_lost() or self.is_won()\n \n def is_lost(self):\n return self.remaining_misses < 1\n \n def is_won(self):\n return self.word.answer == self.word.masked\n ","sub_path":"hangman/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"593013633","text":"from django.test import TestCase\nfrom django.urls import resolve\nfrom lists.forms import ItemForm, EMPTY_ITEM_ERROR\nfrom lists.views import home_page\nfrom lists.models import Item, List\nfrom django.http import HttpRequest\nfrom django.utils.html import escape\n\n\nclass HomePageTest(TestCase):\n \"\"\"тест домашней страницы\"\"\"\n\n def test_root_url_resolves_to_home_page_view(self):\n \"\"\"тест: корневой url преобразуется в представление домашней страницы\"\"\"\n found = resolve('/')\n self.assertEqual(found.func, home_page)\n\n def test_home_page_returns_correct_html(self):\n \"\"\"тест: домашняя стр. возвращает правильный url\"\"\"\n response = self.client.get('/')\n self.assertTemplateUsed(response, 'home.html')\n\n def home_page_uses_item_form(self):\n \"\"\"тест: домашняя страница использует форму для элемента\"\"\"\n response = self.client.get('/')\n self.assertIsInstance(response.context['form'], ItemForm)\n\n\nclass ListViewTest(TestCase):\n \"\"\"тест представления списка\"\"\"\n\n def test_uses_list_template(self):\n \"\"\"тест: используется шаблон списка\"\"\"\n list_ = List.objects.create()\n response = self.client.get(f'/lists/{list_.id}/')\n self.assertTemplateUsed(response, 'list.html')\n\n def test_displays_all_items(self):\n \"\"\"тест: отображаются элементы только для этого списка\"\"\"\n correct_list = List.objects.create()\n Item.objects.create(text='Item 1', list=correct_list)\n Item.objects.create(text='Item 2', list=correct_list)\n other_list = List.objects.create()\n Item.objects.create(text='другой элемент 1 списка', list=other_list)\n Item.objects.create(text='другой элемент 2 списка', list=other_list)\n\n response = self.client.get(f'/lists/{correct_list.id}/')\n\n self.assertContains(response, 'Item 1')\n self.assertContains(response, 'Item 2')\n self.assertNotContains(response, 'другой элемент 1 списка')\n self.assertNotContains(response, 'другой элемент 2 списка')\n\n def test_passes_correct_list_to_template(self):\n \"\"\"тест: передается правильный шаблон списка\"\"\"\n other_list = List.objects.create()\n correct_list = List.objects.create()\n response = self.client.get(f'/lists/{correct_list.id}/')\n self.assertEqual(response.context['list'], correct_list)\n\n def test_can_save_a_POST_request_to_an_existing_list(self):\n \"\"\"тест: можем сохранить ПОСТ запрос в существующий список\"\"\"\n other_list = List.objects.create()\n correct_list = List.objects.create()\n self.client.post(\n f'/lists/{correct_list.id}/',\n data={'text': 'A new item for an existing list'})\n\n self.assertEqual(Item.objects.count(), 1)\n new_item = Item.objects.first()\n self.assertEqual(new_item.text, \"A new item for an existing list\")\n self.assertEqual(new_item.list, correct_list)\n\n def test_redirect_to_list_view(self):\n \"\"\"тест: переадресуется в представление списка\"\"\"\n other_list = List.objects.create()\n correct_list = List.objects.create()\n response = self.client.post(\n f'/lists/{correct_list.id}/',\n data={'text': 'A new list item in existing list'}\n )\n self.assertRedirects(response, f'/lists/{correct_list.id}/')\n\n def test_for_invalid_input_renders_home_template(self):\n \"\"\"тест на недопустимый ввод: отображает домашний шаблон\"\"\"\n response = self.client.post('/lists/new', data={'text': ''})\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'home.html')\n\n def test_displays_item_form(self):\n \"\"\"тест отображения формы элемента\"\"\"\n list_ = List.objects.create()\n response = self.client.get(f'/lists/{list_.id}/')\n self.assertIsInstance(response.context['form'], ItemForm)\n self.assertContains(response, 'name=\"text\"')\n\n def test_invalid_list_items_arent_saved(self):\n \"\"\"тест: сохраняются недопустимые элементы списка\"\"\"\n self.client.post('/lists/new', data={'text': ''})\n self.assertEqual(List.objects.count(), 0)\n self.assertEqual(Item.objects.count(), 0)\n\n def post_invalid_input(self):\n \"\"\"тест: ошибки валидации оканчиваются на странице списков\"\"\"\n list_ = List.objects.create()\n return self.client.post(\n f'/lists/{list_.id}/',\n data={'text': ''}\n )\n\n def test_for_invalid_input_nothing_saved_to_db(self):\n \"\"\"тест на недопустимый ввод: ничего не сохраняется в БД\"\"\"\n response = self.post_invalid_input()\n self.assertEqual(Item.objects.count(), 0)\n\n def test_for_invalid_input_renders_list_template(self):\n \"\"\"тест на недопустимый ввод: отображается шаблон списка\"\"\"\n response = self.post_invalid_input()\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'list.html')\n\n def test_for_invalid_input_passes_form_to_template(self):\n \"\"\"тест на недопустимый ввод: форма передается в шаблон\"\"\"\n response = self.post_invalid_input()\n self.assertIsInstance(response.context['form'], ItemForm)\n\n","sub_path":"lists/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":5965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"331292713","text":"class Solution(object):\n def interval_intersect(self, p1, p2):\n if p1.start <= p2.start <= p1.end:\n return True\n if p2.start <= p1.start <= p2.end:\n return True\n return False\n\n def insert(self, intervals, p):\n \"\"\"\n :type intervals: List[Interval]\n :type newInterval: Interval\n :rtype: List[Interval]\n \"\"\"\n result = []\n for cur in intervals:\n if p is None:\n result.append(cur)\n elif self.interval_intersect(cur, p):\n p.start = min(p.start, cur.start)\n p.end = max(p.end, cur.end)\n elif p.start < cur.start:\n result.append(p)\n result.append(cur)\n p = None\n else:\n result.append(cur)\n if p is not None:\n result.append(p)\n return result\n","sub_path":"hard/057_Insert_Interval/insert_interval.py","file_name":"insert_interval.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"543988546","text":"from flask_sqlalchemy import SQLAlchemy\nimport bcrypt\nimport re\nimport uuid\nfrom datetime import datetime\n\nfrom sqlalchemy.ext.hybrid import hybrid_property\n\ndb = SQLAlchemy(engine_options={'isolation_level': 'READ COMMITTED'})\n\n\ndef generate_uuid():\n return str(uuid.uuid4())\n\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n oauth_id = db.Column(db.String(50), unique=True)\n first_name = db.Column(db.String(30))\n last_name = db.Column(db.String(30))\n password = db.Column(db.String(60))\n username = db.Column(db.String(30))\n address = db.Column(db.String(100))\n user_type = db.Column(db.String(10))\n oauth = db.Column(db.Boolean(), default=False)\n packages = db.relationship('Package', backref='sender', lazy=True)\n\n def __init__(self, **kwargs):\n if 'password' in kwargs:\n kwargs['password'] = bcrypt.hashpw(kwargs['password'].encode('utf-8'), bcrypt.gensalt())\n super().__init__(**kwargs)\n\n def check_password(self, password):\n return password and bcrypt.checkpw(password.encode('utf-8'), self.password.encode('utf-8'))\n\n def __repr__(self):\n return f'User: {self.username}'\n\n def as_dict(self):\n res = {\n 'id': self.id,\n 'first_name': self.first_name,\n 'last_name': self.last_name,\n 'username': self.username,\n 'address': self.address,\n 'user_type': self.user_type,\n 'packages': []\n }\n for package in self.packages:\n res['packages'].append(package.as_dict())\n return res\n\n @hybrid_property\n def full_name(self):\n return self.first_name + ' ' + self.last_name\n\n @staticmethod\n def authorize(username, password, api=False):\n user = User.query.filter_by(username=username).first()\n if user is None or user.oauth or not user.check_password(password) or api and not user.user_type == 'driver':\n return None\n else:\n return user\n\n @staticmethod\n def check_username(username):\n res = {}\n if User.query.filter_by(username=username).first() is None:\n res[username] = 'available'\n else:\n res[username] = 'unavailable'\n return res\n\n @staticmethod\n def register(**kwargs):\n errors = []\n user_data = {}\n if User.is_valid('username', kwargs.get('username', '')):\n user_data['username'] = kwargs.get('username')\n else:\n errors.append('Błędna nazwa użytkownika')\n if User.is_valid('password', kwargs.get('password', '')) or kwargs.get('oauth', False):\n user_data['password'] = kwargs.get('password', '')\n else:\n errors.append('Błędne hasło')\n if User.is_valid('first_name', kwargs.get('first_name', '')):\n user_data['first_name'] = kwargs.get('first_name')\n else:\n errors.append('Błędne imię')\n if User.is_valid('last_name', kwargs.get('last_name', '')):\n user_data['last_name'] = kwargs.get('last_name')\n else:\n errors.append('Błędne nazwisko')\n if User.is_valid('address', kwargs.get('address', '')):\n user_data['address'] = kwargs.get('address')\n else:\n errors.append('Błędny adres')\n if User.check_username(kwargs.get('username'))[kwargs.get('username')] == 'unavailable':\n errors.append('Nazwa użytkownika zajęta')\n\n user_data['user_type'] = kwargs.get('user_type')\n\n if len(errors) == 0:\n user = User(**user_data)\n db.session.add(user)\n db.session.commit()\n else:\n user = None\n return {'user': user, 'errors': errors}\n\n @staticmethod\n def is_valid(field, value):\n PL = 'ĄĆĘŁŃÓŚŹŻ'\n pl = 'ąćęłńóśźż'\n if field == 'first_name':\n return re.compile(f'[A-Z{PL}][a-z{pl}]+').match(value)\n if field == 'last_name':\n return re.compile(f'[A-Z{PL}][a-z{pl}]+').match(value)\n if field == 'password':\n return re.compile('.{8,}').match(value.strip())\n if field == 'username':\n return re.compile('[a-z]{3,12}').match(value)\n if field == 'address':\n return re.compile(f'[a-zA-Z{pl}{PL}0-9\\-.]').match(value.strip())\n return False\n\n\nclass Package(db.Model):\n id = db.Column(db.String(36), primary_key=True, default=generate_uuid, unique=True, nullable=False)\n sender_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n receiver = db.Column(db.String(100))\n cell = db.Column(db.String(7))\n size = db.Column(db.String(30))\n status = db.Column(db.String(20))\n\n def __init__(self, **kwargs):\n if not kwargs.get('status'):\n self.status = 'Utworzona etykieta'\n super().__init__(**kwargs)\n\n def __repr__(self):\n return f'Package: sender_id: {self.sender_id}, receiver: {self.receiver}'\n\n def as_dict(self):\n return {\n 'id': self.id,\n 'sender_id': self.sender_id,\n 'receiver': self.receiver,\n 'cell': self.cell,\n 'size': self.size,\n 'status': self.status\n }\n \n def delete(self):\n if self.status == 'Utworzona etykieta':\n db.session.delete(self)\n db.session.commit()\n return True\n else:\n return False\n\n def increment_status(self):\n statuses = ['Utworzona etykieta', 'Nadana', 'W drodze', 'Dostarczona', 'Odebrana']\n current_status_idx = statuses.index(self.status)\n if current_status_idx == len(statuses) - 1:\n return False\n else:\n self.status = statuses[current_status_idx + 1]\n db.session.commit()\n return True\n\n @staticmethod\n def register(**kwargs):\n errors = Package.validate(**kwargs)\n if len(errors) == 0:\n p = Package(**kwargs)\n db.session.add(p)\n db.session.commit()\n else:\n p = None\n return {'package': p, 'errors': errors}\n\n @staticmethod\n def validate(**kwargs):\n PL = 'ĄĆĘŁŃÓŚŹŻ'\n pl = 'ąćęłńóśźż'\n errors = []\n if not re.compile(f'[a-zA-Z{pl}{PL}0-9\\-\\.,]').match(kwargs.get('receiver', '')):\n errors.append('Niewłaściwy adres odbiorcy.')\n if not re.compile('^[A-Z]{3}-\\d{2,3}$').match(kwargs.get('cell', '')):\n errors.append('Niewłaściwy numer skrytki.')\n if not re.compile('^\\d{1,10} {0,1}[a-z]{1,10}$').match(kwargs.get('size', '')):\n errors.append('Niewłaściwy rozmiar paczki.')\n if User.query.filter_by(id=kwargs.get('sender_id', -1)).first() is None:\n errors.append('Nie znaleziono nadawcy.')\n return errors\n\n\nclass Session(db.Model):\n id = db.Column(db.String(36), primary_key=True, default=generate_uuid, unique=True, nullable=False)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n user = db.relationship('User')\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n \n @staticmethod\n def register(**kwargs):\n s = Session(**kwargs)\n db.session.add(s)\n db.session.commit()\n return s\n\n\nclass Notification(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n content = db.Column(db.String(500))\n timestamp = db.Column(db.DateTime(), default=datetime.now)\n read = db.Column(db.Boolean, default=False)\n\n user = db.relationship('User')\n\n def mark_as_read(self):\n self.read = True\n db.session.commit()\n\n def as_dict(self):\n return {\n 'id': self.id,\n 'user_id': self.user_id,\n 'content': self.content,\n 'timestamp': self.timestamp,\n 'read': self.read\n }\n\n @staticmethod\n def many_as_dict(notifications):\n res = []\n for notification in notifications:\n res.append(notification.as_dict())\n return {'notifications': res}\n\n @staticmethod\n def register(**kwargs):\n n = Notification(**kwargs)\n db.session.add(n)\n db.session.commit()\n return n\n\n @staticmethod\n def get_unread_notifications_for_user(user_id):\n return Notification.query.filter_by(user_id=user_id, read=False).all()\n\n @staticmethod\n def mark_many_as_read(notifications):\n for notification in notifications:\n notification.read = True\n db.session.commit()\n","sub_path":"pamw_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"343114853","text":"import Utilities.svi_read_data as wind_data\nfrom Utilities.utilities import *\nimport Utilities.svi_prepare_vol_data as svi_data\nimport Utilities.svi_calibration_utility as svi_util\nimport QuantLib as ql\nimport numpy as np\nfrom WindPy import w\nimport datetime\nimport timeit\nimport os\nimport pickle\n'''\n============================================\nCalibrate SVI Params (put call parity)\n============================================\n\nUse put and call option data to calibrate SVI model,\nbased on put call parity adjusted risk free rates\n\n'''\n\nstart = timeit.default_timer()\nnp.random.seed()\nw.start()\n\n#begDate = ql.Date(1, 12, 2016)\nbegDate = ql.Date(1, 6, 2017)\nendDate = ql.Date(20, 7, 2017)\ncalendar = ql.China()\ndaycounter = ql.ActualActual()\n\nevalDate = begDate\ndaily_params = {}\ndaily_option_prices = {}\ndaily_spots = {}\ndaily_svi_dataset = {}\ndates = []\n\nwhile evalDate <= endDate:\n print('Start : ', evalDate)\n evalDate = calendar.advance(evalDate, ql.Period(1, ql.Days))\n ql.Settings.instance().evaluationDate = evalDate\n try:\n #vols, spot, mktData, mktFlds, optionData, optionFlds, optionids = wind_data.get_wind_data(evalDate)\n cal_vols, put_vols, expiration_dates, spot, rf_months = svi_data.get_call_put_impliedVols_moneyness_PCPrate_pcvt(\n evalDate, daycounter, calendar, maxVol=1.0, step=0.0001, precision=0.001, show=False)\n data_months = svi_util.orgnize_data_for_optimization(\n evalDate, daycounter, cal_vols, put_vols, expiration_dates, spot)\n #print(data_months)\n except:\n continue\n key_date = datetime.date(evalDate.year(), evalDate.month(), evalDate.dayOfMonth())\n maturity_dates = to_dt_dates(expiration_dates)\n svi_dataset = cal_vols, put_vols, maturity_dates, spot, rf_months\n daily_svi_dataset.update({key_date:svi_dataset})\n dividend_ts = ql.YieldTermStructureHandle(ql.FlatForward(evalDate, 0.0, daycounter))\n month_indexs = wind_data.get_contract_months(evalDate)\n params_months = []\n for i in range(4):\n nbr_month = month_indexs[i]\n data = data_months.get(i)\n logMoneynesses = data[0]\n totalvariance = data[1]\n expiration_date = data[2]\n ttm = daycounter.yearFraction(evalDate, expiration_date)\n params = svi_util.get_svi_optimal_params(data, ttm, 30)\n params_months.append(params)\n\n daily_params.update({key_date:params_months})\n dates.append(key_date)\n print('Finished : ',evalDate)\n print(params_months[0])\n print(params_months[1])\n print(params_months[2])\n print(params_months[3])\n\n#print(daily_params)\ntimebreak1 = timeit.default_timer()\nprint('calibration time : ',timebreak1-start)\nprint('daily_params = ',daily_params)\nprint('daily_svi_dataset = ',daily_svi_dataset)\nprint('dates = ', dates)\n\nwith open(os.getcwd()+'/intermediate_data/hedging_daily_params_pcprates.pickle','wb') as f:\n pickle.dump([daily_params],f)\nwith open(os.getcwd()+'/intermediate_data/hedging_dates_pcprates.pickle','wb') as f:\n pickle.dump([dates],f)\nwith open(os.getcwd()+'/intermediate_data/hedging_daily_svi_dataset_pcprates.pickle','wb') as f:\n pickle.dump([daily_svi_dataset],f)\n","sub_path":"svi_model/svi_calibration_50etf_pcprates.py","file_name":"svi_calibration_50etf_pcprates.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"61405391","text":"D = {\n 'name': {'first': 'Bob', 'last': 'Smith'},\n 'job': ['dev', 'mgr'],\n 'age': 0.5,\n 'addr': 'Beijing'\n}\nprint(D)\n\nD = {'food': 'spam', 'quality': 4, 'color': 'pink'}\nprint(D['food'])\nD['sex'] = 'gender'\nprint(D)","sub_path":"2018-10-21/Codes/dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"147171136","text":"import sys\nimport os\n\nimport sqlite3\n\n\ndef main():\n connection = sqlite3.connect('database_orig.db')\n connection_new = sqlite3.connect('database_new.db')\n\n c_new = connection_new.cursor()\n c = connection.cursor()\n\n c_new.execute('''SELECT url\n FROM Idol''')\n res = c_new.fetchall()\n\n urls = [url[0] for url in res]\n\n for url in urls:\n c.execute('''SELECT url FROM Idol WHERE url = ?''', (url,))\n old_url = c.fetchone()\n\n if old_url: # Existing idol\n # Only update url of images\n old_url = old_url[0]\n c.execute(''' SELECT id FROM Idol WHERE url = ? ''', (old_url,))\n id_old_idol = c.fetchone()[0]\n c.execute('''DELETE FROM Image\n WHERE id_idol = ? ''', (id_old_idol,))\n\n c_new.execute(''' SELECT I.url \n FROM Image AS I\n JOIN Idol ON Idol.id = I.id_idol\n WHERE Idol.url = ? ''', (url,))\n res = c_new.fetchall()\n image_urls = [g[0] for g in res]\n for img_url in image_urls:\n c.execute(''' INSERT OR IGNORE INTO Image(url, id_idol) VALUES (?, ?) ''', (img_url, id_old_idol,))\n else: # New idol\n c_new.execute(''' SELECT id, name FROM Idol WHERE url = ? ''', (url,))\n id_idol, name = c_new.fetchone()\n\n c_new.execute(''' SELECT G.name \n FROM Groups AS G \n JOIN IdolGroups AS IG ON IG.id_groups = G.id\n WHERE IG.id_idol = ? ''', (id_idol,))\n res = c_new.fetchall()\n name_groups = [g[0] for g in res]\n\n c.execute(''' INSERT INTO Idol(name, url) VALUES (?, ?) ''',\n (name, url,))\n\n c.execute(''' SELECT id FROM Idol WHERE url = ? ''', (url,))\n id_old_idol = c.fetchone()[0]\n\n for group in name_groups:\n c.execute(''' INSERT OR IGNORE INTO Groups(name) VALUES (?) ''', (group,))\n c.execute(''' SELECT id FROM Groups WHERE name = ? ''', (group,))\n id_old_group = c.fetchone()[0]\n\n c.execute(''' INSERT INTO IdolGroups(id_idol, id_groups) VALUES (?, ?) ''',\n (id_old_idol, id_old_group,))\n\n # Images\n c_new.execute(''' SELECT url \n FROM Image\n WHERE id_idol = ? ''', (id_idol,))\n res = c_new.fetchall()\n image_urls = [g[0] for g in res]\n for img_url in image_urls:\n c.execute(''' INSERT OR IGNORE INTO Image(url, id_idol) VALUES (?, ?) ''', (img_url, id_old_idol,))\n\n print(f'New : {url}')\n print(f'Old : {old_url}')\n\n c.execute('''UPDATE Deck SET current_image = 0 ''')\n c_new.close()\n connection.commit()\n c.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"database_creation/transfer_new_data.py","file_name":"transfer_new_data.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"528520862","text":"import numpy as NP\nimport healpy as HP\nfrom astropy.io import fits\nimport glob\n\nrootdir = '/data3/t_nithyanandan/project_HERA/'\nbeams_dir = 'power_patterns/CST/mdl04/'\nprefix = 'X4Y2H_4900_'\nsuffix = '.hmap'\npols = ['X']\n\ncolnum = 0\noutdata = []\nschemes = []\nnsides = []\nnpixs = []\nfrequencies = []\nfor pol in pols:\n fullfnames = glob.glob(rootdir + beams_dir + prefix + '*' + suffix)\n fullfnames = NP.asarray(fullfnames)\n fnames = [fname.split('/')[-1] for fname in fullfnames]\n fnames = NP.asarray(fnames)\n freqs_str = [fname.split('_')[2].split('.')[0] for fname in fnames]\n freqs = NP.asarray(map(float, freqs_str)) * 1e6 # Convert to Hz\n sortind = NP.argsort(freqs)\n fullfnames = fullfnames[sortind]\n fnames = fnames[sortind]\n freqs = freqs[sortind]\n frequencies += [freqs]\n\n beam = None\n for fname in fullfnames:\n inhdulist = fits.open(fname)\n hdu1 = inhdulist[1]\n data = hdu1.data.field(colnum)\n data = data.flatten()\n if not data.dtype.isnative:\n data.dtype = data.dtype.newbyteorder()\n data.byteswap(True)\n scheme = hdu1.header['ORDERING'][:4]\n\n if beam is None:\n beam = data.reshape(-1,1)\n else:\n beam = NP.hstack((beam, data.reshape(-1,1)))\n\n beam = beam / NP.max(beam, axis=0, keepdims=True)\n\n outdata += [beam]\n schemes += [scheme]\n npixs += [beam[:,0].size]\n nsides += [HP.npix2nside(beam[:,0].size)]\n\noutfile = rootdir + beams_dir + '{0[0]}_{0[1]}'.format(fnames[0].split('_')[:2])+suffix\nhdulist = []\nhdulist += [fits.PrimaryHDU()]\nhdulist[0].header['EXTNAME'] = 'PRIMARY'\nhdulist[0].header['NPOL'] = (len(pols), 'Number of polarizations')\nhdulist[0].header['SOURCE'] = ('HERA-CST', 'Source of data')\n\nfor pi,pol in enumerate(pols):\n hdu = fits.ImageHDU(outdata[pi], name='BEAM_{0}'.format(pol))\n hdu.header['PIXTYPE'] = ('HEALPIX', 'Type of pixelization')\n hdu.header['ORDERING'] = (schemes[pi], 'Pixel ordering scheme, either RING or NESTED')\n hdu.header['NSIDE'] = (nsides[pi], 'NSIDE parameter of HEALPIX')\n hdu.header['NPIX'] = (npixs[pi], 'Number of HEALPIX pixels')\n hdu.header['FIRSTPIX'] = (0, 'First pixel # (0 based)')\n hdu.header['LASTPIX'] = (npixs[pi]-1, 'Last pixel # (0 based)')\n hdulist += [hdu]\n hdulist += [fits.ImageHDU(frequencies[pi], name='FREQS_{0}'.format(pol))]\n\nouthdu = fits.HDUList(hdulist)\nouthdu.writeto(outfile, clobber=True)\n","sub_path":"main/consolidate_HERA_CST_beams.py","file_name":"consolidate_HERA_CST_beams.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"197960998","text":"# 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Thomas Quintana \n#\n# Nishad Musthafa \n\n# from lib.esl import Event\n# from lib.server import Dispatcher, WatchEventCommand, UnwatchEventCommand\n# from switchlets.call_utilities.play import PlayCommand, Play\n# from switchlets.call_utilities.utils import StartExecution\nimport mock, time\nfrom switchlets.call_utilities import ActionExecutor, ExecutionComplete, StartExecution\nfrom unittest import TestCase\n\n\n\nclass ActionExecutorTests(TestCase):\n def test_flow(self):\n action_executor = ActionExecutor.start()\n with mock.patch('switchlets.call_utilities.play.Play.on_receive') as mock_play_on_receive:\n mock_sender = mock.Mock()\n execution_params = {\n 'context': [('Play', 'play_url_1'), ('Play', 'play_url_2'), ('Play', 'play_url_3')],\n 'dispatcher': 'mock_dispatcher',\n 'sender': mock_sender,\n 'call_uuid': 'fake_call_uuid'\n }\n # State 'waiting' to 'executing'\n start_execution = StartExecution(**execution_params)\n action_executor.tell({'content': start_execution})\n time.sleep(2)\n\n action_receiver_call_count = mock_play_on_receive.call_count\n action_message = mock_play_on_receive.call_args_list[0][0][0]['content']\n\n self.assertTrue(action_receiver_call_count, 1)\n self.assertTrue(isinstance(action_message, StartExecution))\n self.assertEquals(action_message.get_context(), 'play_url_1')\n self.assertEquals(action_message.get_call_uuid(), 'fake_call_uuid')\n self.assertEquals(action_message.get_dispatcher(), 'mock_dispatcher')\n self.assertEquals(action_message.get_sender().actor_urn, action_executor.actor_urn)\n\n # State 'executing' to 'executing'\n completed_execution = ExecutionComplete()\n action_executor.tell({'content': completed_execution})\n time.sleep(2)\n\n action_receiver_call_count = mock_play_on_receive.call_count\n action_message = mock_play_on_receive.call_args_list[1][0][0]['content']\n \n self.assertTrue(action_receiver_call_count, 2)\n self.assertTrue(isinstance(action_message, StartExecution))\n self.assertEquals(action_message.get_context(), 'play_url_2')\n self.assertEquals(action_message.get_call_uuid(), 'fake_call_uuid')\n self.assertEquals(action_message.get_dispatcher(), 'mock_dispatcher')\n self.assertEquals(action_message.get_sender().actor_urn, action_executor.actor_urn)\n\n # State 'executing' to 'executing'\n completed_execution = ExecutionComplete()\n action_executor.tell({'content': completed_execution})\n time.sleep(2)\n\n action_receiver_call_count = mock_play_on_receive.call_count\n action_message = mock_play_on_receive.call_args_list[2][0][0]['content']\n \n self.assertTrue(action_receiver_call_count, 3)\n self.assertTrue(isinstance(action_message, StartExecution))\n self.assertEquals(action_message.get_context(), 'play_url_3')\n self.assertEquals(action_message.get_call_uuid(), 'fake_call_uuid')\n self.assertEquals(action_message.get_dispatcher(), 'mock_dispatcher')\n self.assertEquals(action_message.get_sender().actor_urn, action_executor.actor_urn)\n\n # State 'executing' to 'complete'\n completed_execution = ExecutionComplete()\n action_executor.tell({'content': completed_execution})\n time.sleep(2)\n\n self.assertEquals(mock_sender.mock_calls[0].call_list()[0][0], 'tell')\n sender_message = mock_sender.mock_calls[0].call_list()[0][1][0]['content']\n self.assertTrue(isinstance(sender_message, ExecutionComplete))\n\n action_executor.stop()\n","sub_path":"tests/switchlets/call_utilities/action_executor.py","file_name":"action_executor.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"37641247","text":"# Copyright (c) 2016 Mellanox Technologies, Ltd\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\n\"\"\"initial migration\n\nRevision ID: 6299ddfd55fb\nRevises: None\nCreate Date: 2016-06-06 14:02:40.249553\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '6299ddfd55fb'\ndown_revision = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table(\n 'allocations',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('resource_provider_id', sa.Integer(), nullable=False),\n sa.Column('consumer_id', sa.String(length=36), nullable=False),\n sa.Column('resource_class_id', sa.Integer(), nullable=False),\n sa.Column('used', sa.Integer(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index('allocations_consumer_id_idx',\n 'allocations',\n ['consumer_id'],\n unique=False)\n op.create_index('allocations_resource_class_id_idx',\n 'allocations',\n ['resource_class_id'],\n unique=False)\n op.create_index('allocations_resource_provider_class_used_idx',\n 'allocations',\n ['resource_provider_id', 'resource_class_id', 'used'],\n unique=False)\n op.create_table(\n 'inventories',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('resource_provider_id', sa.Integer(), nullable=False),\n sa.Column('resource_class_id', sa.Integer(), nullable=False),\n sa.Column('total', sa.Integer(), nullable=False),\n sa.Column('reserved', sa.Integer(), nullable=False),\n sa.Column('min_unit', sa.Integer(), nullable=False),\n sa.Column('max_unit', sa.Integer(), nullable=False),\n sa.Column('step_size', sa.Integer(), nullable=False),\n sa.Column('allocation_ratio', sa.Float(), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint(\n 'resource_provider_id', 'resource_class_id',\n name='uniq_inventories0resource_provider_resource_class')\n )\n op.create_index('inventories_resource_class_id_idx',\n 'inventories',\n ['resource_class_id'],\n unique=False)\n op.create_index('inventories_resource_provider_id_idx',\n 'inventories',\n ['resource_provider_id'],\n unique=False)\n op.create_index('inventories_resource_provider_resource_class_idx',\n 'inventories',\n ['resource_provider_id', 'resource_class_id'],\n unique=False)\n op.create_table(\n 'resource_providers',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('uuid', sa.String(length=36), nullable=False),\n sa.Column('parent_uuid', sa.String(length=36), nullable=True),\n sa.Column('name', sa.Unicode(length=200), nullable=True),\n sa.Column('generation', sa.Integer(), nullable=True),\n sa.Column('can_host', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name', name='uniq_resource_providers0name'),\n sa.UniqueConstraint('uuid', name='uniq_resource_providers0uuid')\n )\n op.create_index('resource_providers_name_idx',\n 'resource_providers',\n ['name'],\n unique=False)\n op.create_index('resource_providers_uuid_idx',\n 'resource_providers',\n ['uuid'],\n unique=False)\n ### end Alembic commands ###\n","sub_path":"nacsa/db/sqlalchemy/alembic/versions/6299ddfd55fb_initial_migration.py","file_name":"6299ddfd55fb_initial_migration.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"429456911","text":"from flask import session\n\ndef add_user_to_session(user, seller=None):\n session['user_id'] = user.id\n session['first_name'] = user.first_name\n session['last_name'] = user.last_name\n session['email'] = user.email\n if seller:\n session['seller_id'] = seller.id\n\ndef remove_user_from_session():\n def pop_if(k):\n if k in session:\n session.pop(k)\n pop_if('user_id')\n pop_if('first_name')\n pop_if('last_name')\n pop_if('seller_id')\n pop_if('email')\n","sub_path":"sessionutils.py","file_name":"sessionutils.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"649286524","text":"import pika\n\n\ndef callback(ch, method, properties, body):\n print(\" [x] %r\" % body)\n\n\n# 与rabbitmq建立连接\nconnection = pika.BlockingConnection(pika.ConnectionParameters('120.77.183.17'))\nchannel = connection.channel()\n\n# 交换机声明\nchannel.exchange_declare(exchange='logs', exchange_type='fanout')\n\n# 让服务器为我们选择一个随机队列名称, 一旦消费者连接关闭,则应删除队列。\nresult = channel.queue_declare(queue='', exclusive=True)\nqueue_name = result.method.queue\n\n# 告诉交换机将消息发送到哪个队列\nchannel.queue_bind(exchange='logs', queue=result.method.queue)\n\nprint(' [*] Waiting for logs. To exit press CTRL+C')\n\nchannel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)\n\nchannel.start_consuming()\n","sub_path":"3. Publish or Subscribe/receive_logs.py","file_name":"receive_logs.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"341388852","text":"i = 0\r\ns = \"вправо\"\r\ndef setup():\r\n size(800,400)\r\n frameRate(160)\r\n \r\ndef draw():\r\n global s\r\n global i\r\n \r\n background(200)\r\n ellipse(i,200,50,50)\r\n if mousePressed == True:\r\n fill(random(0,220),random(0,250),random(0,222))\r\n \r\n if s == \"вправо\":\r\n i = i + 1\r\n if i >= 800:\r\n s = \"влево\"\r\n if s == \"влево\":\r\n i = i - 1\r\n if i <= 0:\r\n s = \"вправо\"\r\n","sub_path":"sketch_210306abcdefgh/sketch_210306abcdefgh.pyde","file_name":"sketch_210306abcdefgh.pyde","file_ext":"pyde","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"47043869","text":"\"\"\"\r\nNAME: info_theory_functions.py\r\nCREATED: 16-JAN-20\r\nLAST EDIT: 23-MAR-20\r\nCREATOR: Author\r\nEMAIL: 62926253+kroot-kaytetye@users.noreply.github.com\r\nPROJECT: kroot\r\nSUMMARY: Contains functions relevant to the information theoretic analysis of Kaytetye syllabified roots.\r\nFUNCTIONS:\r\n _update_dict\r\n _get_max_syl_count\r\n _get_frequency_of_segment_in_list\r\n _split_syllable_into_phonotactic_positions\r\n _get_frequency_of_configurations_in_syllable\r\n _get_phonotactic_entropy\r\n _get_phonotactic_surprisal\r\n _get_surprisal_of_syllable\r\n get_frequency_of_each_config_in_word_position\r\n get_phontactic_entropies\r\n get_surprisals_of_lexicon\r\n get_phonotactic_surprisals\r\n\"\"\"\r\nfrom math import log\r\nimport re\r\n\r\n\r\n##########################################\r\n# Private Functions\r\n##########################################\r\ndef _update_dict(dict_1, dict_2):\r\n \"\"\"\r\n Combines the two provided Dictionaries\r\n \"\"\"\r\n new_dict = {}\r\n for key in dict_1.keys():\r\n new_dict[key] = dict_1[key] + dict_2[key]\r\n return new_dict\r\n\r\n\r\ndef _get_max_syl_count(lexicon):\r\n \"\"\"\r\n Counts the length of all words in the input syllabified lexicon, and returns the longest word (in terms of syllables)\r\n in the lexicon.\r\n \"\"\"\r\n max_syl = 0\r\n for lex in lexicon:\r\n if len(lex.split(\".\")) > max_syl:\r\n max_syl = len(lex.split(\".\"))\r\n return max_syl\r\n\r\n\r\ndef _get_frequency_of_segment_in_list(seg, seg_list):\r\n \"\"\"\r\n Counts the frequency of a given segment or token in a list of segments/tokens.\r\n \"\"\"\r\n return seg_list.count(seg)\r\n\r\n\r\ndef _split_syllable_into_phonotactic_positions(syllable):\r\n \"\"\"\r\n Takes an input syllable, and outputs a three-member list. The first member is the onset. The second member is the\r\n nucleus. The third member is the coda.\r\n \"\"\"\r\n # alternative splitting of syllable into onset and coda, rather than using a syllabic template\r\n vowel_regex = \"[ɐəiu:]\"\r\n p = re.compile(vowel_regex)\r\n vowel_pos = []\r\n for match in p.finditer(syllable):\r\n vowel_pos.append(match.start())\r\n\r\n assert (len(vowel_pos) < 3), \"There must only be one or two vowel phonemes in a single \" \\\r\n \"syllable. \"\r\n assert (len(vowel_pos) > 0), \"There must only be one or two vowel phonemes in a single \" \\\r\n \"syllable. \"\r\n if len(vowel_pos) == 1:\r\n cut_points = [vowel_pos[0], vowel_pos[0] + 1]\r\n else:\r\n cut_points = [vowel_pos[0], vowel_pos[1] + 1]\r\n # Split into positions\r\n onset = syllable[0:cut_points[0]]\r\n nucleus = syllable[cut_points[0]:cut_points[1]]\r\n coda = syllable[cut_points[1]:len(syllable)]\r\n\r\n if len(onset) == 0:\r\n onset = \"0\"\r\n if len(coda) == 0:\r\n coda = \"0\"\r\n return [onset, nucleus, coda]\r\n\r\n\r\ndef _get_frequency_of_configurations_in_syllable(lexicon, seg_list, syllable_number, get_final_syllables):\r\n \"\"\"\r\n Gets the frequency of each segment in seg_list for each phonotactic position in the syllable number for each word\r\n in the lexicon. If syllable_number == 1, the frequency of all the segments in seg_list are retrieved for\r\n the onset, nucleus, and coda of the first syllable in every lexeme.\r\n if get_final_syllables is set to true, this ovverrides the syllable_number variable and simply pulls the final\r\n syllable in each word. The resulting dictionary assigns the onset of these syllables to the corresponding number\r\n (e.g. if a word is three syllables long, onset_2 will receive the the onset. This results in a dictionary which does\r\n not correspond to a single row.\r\n \"\"\"\r\n\r\n if get_final_syllables is False:\r\n\r\n output_dict = {'syllable': [str(syllable_number) + \"_onset\",\r\n str(syllable_number) + \"_nucleus\",\r\n str(syllable_number) + \"_coda\"]}\r\n onset = []\r\n nucleus = []\r\n coda = []\r\n\r\n for lexeme in lexicon:\r\n lex_split = lexeme.split('.')\r\n if syllable_number < len(lex_split):\r\n # special behaviour if it is the final syllable. Only take onset!\r\n if syllable_number == len(lex_split) - 1:\r\n lex_syl = _split_syllable_into_phonotactic_positions(lex_split[syllable_number])\r\n onset.append(lex_syl[0])\r\n else:\r\n lex_syl = _split_syllable_into_phonotactic_positions(lex_split[syllable_number])\r\n\r\n onset.append(lex_syl[0])\r\n nucleus.append(lex_syl[1])\r\n coda.append(lex_syl[2])\r\n for seg in seg_list:\r\n in_list = [_get_frequency_of_segment_in_list(seg, onset),\r\n _get_frequency_of_segment_in_list(seg, nucleus),\r\n _get_frequency_of_segment_in_list(seg, coda)]\r\n output_dict[seg] = in_list\r\n return output_dict\r\n # final syllable behaviour. This ignores the onset and only takes final nucleus and coda (coda is always empty)\r\n else:\r\n output_dict = {'syllable': [\"final_nucleus\",\r\n \"final_coda\"]}\r\n\r\n nucleus = []\r\n coda = []\r\n\r\n for lexeme in lexicon:\r\n lex_split = lexeme.split(\".\")\r\n lex_syl = _split_syllable_into_phonotactic_positions(lex_split[len(lex_split) - 1])\r\n\r\n nucleus.append(lex_syl[1])\r\n coda.append(lex_syl[2])\r\n\r\n # for each set of nucleus and coda, get the frequency of each configuration. Coda is expected to only\r\n # have 0, and this feature can be used for debugging of this function.\r\n for seg in seg_list:\r\n in_list = [_get_frequency_of_segment_in_list(seg, nucleus),\r\n _get_frequency_of_segment_in_list(seg, coda)]\r\n output_dict[seg] = in_list\r\n return output_dict\r\n\r\n\r\ndef _get_phonotactic_entropy(k_row):\r\n \"\"\"\r\n Calculate entropy of a position by summing the probability * positive log probability value of each possible\r\n configuration.\r\n \"\"\"\r\n\r\n # initialise variables\r\n output_row = {\"syl\": k_row['syllable']}\r\n k_keys = []\r\n\r\n # get list of segments from keys\r\n for key in k_row.keys():\r\n if key != \"syllable\":\r\n k_keys.append(key)\r\n\r\n total_count = 0\r\n # because empty cells are represented as 0, there is no need for checking for 'empty' cells\r\n for key in k_keys:\r\n total_count = total_count + int(k_row[key])\r\n\r\n seq_probs = []\r\n # if a row has 0, simply append 0 probabiliy. otherwise, calculate probability\r\n for key in k_keys:\r\n if total_count == 0:\r\n seq_probs.append(0)\r\n else:\r\n seq_probs.append(int(k_row[key]) / total_count)\r\n\r\n entropy = 0\r\n for seq_prob in seq_probs:\r\n # for probabilities greater than zero, add together individual entropy values.\r\n # entropy is equivalent to the sum of each surprisal times the corresponding probability\r\n if seq_prob > 0:\r\n entropy = entropy + (seq_prob * (log(seq_prob, 2) * -1))\r\n\r\n output_row[\"entropy\"] = entropy\r\n return output_row\r\n\r\n\r\ndef _get_phonotactic_surprisal(fq_row):\r\n \"\"\"\r\n Gets surprisals for each segment in row.\r\n \"\"\"\r\n surprisal_row = {}\r\n # get sum\r\n row_sum = 0\r\n for key in fq_row.keys():\r\n if key != \"syllable\":\r\n row_sum = row_sum + int(fq_row[key])\r\n for key in fq_row.keys():\r\n if key == \"syllable\":\r\n surprisal_row[\"syllable\"] = fq_row[\"syllable\"]\r\n else:\r\n if row_sum == 0:\r\n surprisal_row[key] = -1\r\n else:\r\n prob = int(fq_row[key]) / row_sum\r\n if prob == 0:\r\n surprisal_row[key] = -1\r\n else:\r\n surprisal_row[key] = log(int(fq_row[key]) / row_sum, 2) * -1\r\n return surprisal_row\r\n\r\n\r\ndef _get_surprisal_of_syllable(syl, num, word_len, sur_dict_list):\r\n surprisal_in_positions = [0] * 3\r\n syl_poss = _split_syllable_into_phonotactic_positions(syl)\r\n for k_row in sur_dict_list:\r\n # special behaviour if final syllable\r\n if num == word_len - 1:\r\n if k_row[\"syllable\"] == str(num) + \"_onset\":\r\n surprisal_in_positions[0] = float(k_row[syl_poss[0]])\r\n elif k_row[\"syllable\"] == \"final_nucleus\":\r\n surprisal_in_positions[1] = float(k_row[syl_poss[1]])\r\n elif k_row[\"syllable\"] == \"final_coda\":\r\n # final coda will always be 0, and is factored out of calculation\r\n surprisal_in_positions[2] = float(k_row[syl_poss[2]])\r\n else:\r\n if k_row[\"syllable\"] == str(num) + \"_onset\":\r\n surprisal_in_positions[0] = float(k_row[syl_poss[0]])\r\n elif k_row[\"syllable\"] == str(num) + \"_nucleus\":\r\n surprisal_in_positions[1] = float(k_row[syl_poss[1]])\r\n elif k_row[\"syllable\"] == str(num) + \"_coda\":\r\n surprisal_in_positions[2] = float(k_row[syl_poss[2]])\r\n\r\n return sum(surprisal_in_positions)\r\n\r\n\r\n##########################################\r\n# Public Functions\r\n##########################################\r\n\r\ndef get_frequency_of_each_config_in_word_position(lexicon, config_list):\r\n \"\"\"\r\n For the input syllabified lexicon and list of segmental configurations, this function counts the occurrences\r\n of these segments according to phonotactic positions.\r\n \"\"\"\r\n new_dict = None\r\n for syl_num in range(0, _get_max_syl_count(lexicon)):\r\n seg_dict = _get_frequency_of_configurations_in_syllable(lexicon, config_list, syl_num, False)\r\n if syl_num > 0:\r\n new_dict = _update_dict(new_dict, seg_dict)\r\n else:\r\n new_dict = seg_dict\r\n # assign final syllable\r\n final_dict = _get_frequency_of_configurations_in_syllable(lexicon, config_list, -1, True)\r\n new_dict = _update_dict(new_dict, final_dict)\r\n output_dict_list = [dict(zip(new_dict, t)) for t in zip(*new_dict.values())]\r\n return output_dict_list\r\n\r\n\r\ndef get_phontactic_entropies(fq_dict):\r\n \"\"\"\r\n This function retrieves the entropy of each row in the output of get_frequency_of_each_config_in_word_position.\r\n Look at documentation for sub-functions for further details.\r\n \"\"\"\r\n entropys = []\r\n for row in fq_dict:\r\n entropys.append(_get_phonotactic_entropy(row))\r\n return entropys\r\n\r\n\r\ndef get_surprisals_of_lexicon(syl_lex, sur_dict_list):\r\n \"\"\"\r\n Produces the mean surprisal value for each lexeme in syl_lex.\r\n syl_lex: Syllabified lexicon\r\n sur_dict_list: output from get_phonotactic_surprisals.\r\n \"\"\"\r\n out_dict_list = []\r\n for lexeme in syl_lex:\r\n lex_sylab = lexeme.split(\".\")\r\n surprisal_value = 0\r\n out_dict = {}\r\n for i, syl in enumerate(lex_sylab):\r\n surprisal_value = surprisal_value + _get_surprisal_of_syllable(syl, i, len(lex_sylab), sur_dict_list)\r\n out_dict[\"lexeme\"] = lexeme\r\n out_dict[\"mean_surprisal\"] = surprisal_value / (\r\n (len(lex_sylab) * 3) - 1) # three phonotactic positions for each\r\n # syllable excluding final coda\r\n out_dict_list.append(out_dict)\r\n return out_dict_list\r\n\r\n\r\ndef get_phonotactic_surprisals(fq_dict):\r\n \"\"\"\r\n For each row in dict, gets surprisal of each configuration. This is calculated by getting the probability of the\r\n configuration in that position, and then calculating the surprisal based on this (the positive base-2 log of the\r\n probability).\r\n \"\"\"\r\n surprisal_dict = []\r\n for row in fq_dict:\r\n surprisal_dict.append(_get_phonotactic_surprisal(row))\r\n return surprisal_dict\r\n","sub_path":"src/py/info_theory_functions.py","file_name":"info_theory_functions.py","file_ext":"py","file_size_in_byte":11832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"461315865","text":"#\n# @lc app=leetcode.cn id=1 lang=python3\n#\n# [1] 两数之和\n#\n# https://leetcode-cn.com/problems/two-sum/description/\n#\n# algorithms\n# Easy (48.00%)\n# Likes: 8048\n# Dislikes: 0\n# Total Accepted: 980.5K\n# Total Submissions: 2M\n# Testcase Example: '[2,7,11,15]\\n9'\n#\n# 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。\n# \n# 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。\n# \n# \n# \n# 示例:\n# \n# 给定 nums = [2, 7, 11, 15], target = 9\n# \n# 因为 nums[0] + nums[1] = 2 + 7 = 9\n# 所以返回 [0, 1]\n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n res_idx = None\n nums_idx_pair = {}\n for idx, num in enumerate(nums):\n if target - num in nums_idx_pair:\n res_idx = [nums_idx_pair[target-num], idx]\n break\n else:\n nums_idx_pair[num] = idx\n return res_idx\n\n# @lc code=end\n\n","sub_path":"Week_02/1.两数之和.py","file_name":"1.两数之和.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"449540766","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nfrom celluloid import Camera\nimport matplotlib\n\n\ndef activeSwimmers(x, y, fi, n, dt, T0, nOfParticles, ni, v, trans_dif_T, rot_dif_T, gridSize, particle_radius, torque_radius, out=None):\n\n # have the exact same active brownian motions for the particles\n # then super-impose interacting torque effects on top of it\n\n # adjust coefs of active brownian motion to fit eqs\n# gaussCoefs = np.array([[np.sqrt(2*trans_dif_T *dt)],\n# np.sqrt([2*trans_dif_T * dt]),np.sqrt([2*rot_dif_T*dt])])\n\n for step in range(n):\n # generate n samples from a normal distribution for 3 coordinates (x,y,fi)\n #gaussRand_x = norm.rvs(size=(nOfParticles, 3), scale=1) * gaussCoefs\n\n # init rands for torque need (most likely not needed)\n randFactors = (np.random.random((nOfParticles, 1)) - 0.5) * ni\n\n # concatenate x and y so that each particles is a position pair\n pos = np.hstack((x[:, step].reshape((nOfParticles,1)), \n y[:, step].reshape((nOfParticles,1))))\n # also get the speeds for each particle\n # this already is vhat 'cos sin^2(x) + cos^2(x) = 1\n v_hat = np.hstack((np.cos(fi[:, step]) .reshape((nOfParticles,1)), \n np.sin(fi[:, step]).reshape((nOfParticles,1))))\n # init torque\n torque = np.zeros((nOfParticles,1))\n\n # calculate torque for each particle (single torque depends on all other particles) \n for i in range(1, nOfParticles):\n # calculate direction vector to every vector ( r_i,i is not a thing tho)\n r = pos[i] - pos \n # calculate the norm of every direction vector\n rnorms = np.linalg.norm(r, axis=1).reshape((nOfParticles,1))\n # we need rhat\n r_hat = r / rnorms\n r_hat[i] = np.zeros(2)\n # dot 'em. dot does not support axis thing so we do it like this \n dots = np.sum(v_hat[i] * r_hat, axis=1).reshape((nOfParticles,1))\n coefs = dots / rnorms**2 # check whether the shapes are ok here, it works if they are\n coefs[i] = 0\n # crosses v_i with r_i and does so for all i\n crosses = np.cross(v_hat[i], r_hat).reshape((nOfParticles, 1))\n particle_torques = coefs * crosses\n\n if rnorms[i] > torque_radius:\n particle_torques[i] = 0\n\n torque[i] = np.sum(particle_torques) \n# print(torque)\n\n\n torque = T0 * torque\n# print(torque)\n # fi[:, step+1] = fi[:, step] + torque.reshape((nOfParticles,)) \\\n # + randFactors.reshape((nOfParticles,))\n fi[:, step+1] = fi[:, step] + torque.reshape((nOfParticles,)) \\\n + randFactors.reshape((nOfParticles,))\n v_hat = np.hstack((np.cos(fi[:, step+1].reshape((nOfParticles,1))), \n np.sin(fi[:, step+1].reshape((nOfParticles,1)))))\n #x[:, step+1] = (x[:,step] + gaussRand_x[0] + dt * v * v_hat[:,0]) % gridSize\n #y[:, step+1] = (y[:,step] + gaussRand_x[1] + dt * v * v_hat[:,1]) % gridSize\n #x[:, step+1] = (x[:,step] + dt * v * v_hat[:,0]) % gridSize\n #y[:, step+1] = (y[:,step] + dt * v * v_hat[:,1]) % gridSize\n x[:, step+1] = (x[:,step] + v * v_hat[:,0]) % gridSize\n y[:, step+1] = (y[:,step] + v * v_hat[:,1]) % gridSize\n\n pos = np.hstack((x[:, step+1].reshape((nOfParticles,1)), \n y[:, step+1].reshape((nOfParticles,1))))\n\n # now you need to ensure that they do not overlap\n # what if i push it into another particle tho???????????????????\n for p in range(nOfParticles):\n r = pos[p] - pos \n rnorms = np.linalg.norm(r, axis=1).reshape((nOfParticles,1))\n rnorms[p] = 'Inf'\n r_hat = r / rnorms\n for n in range(nOfParticles):\n if rnorms[n] < 2 * particle_radius:\n overlap = 2 * particle_radius - rnorms[n]\n moveVec = r_hat[n] * (overlap / 2)\n# print(moveVec)\n x[p, step+1] += moveVec[0]\n y[p, step+1] += moveVec[1]\n x[n, step+1] -= moveVec[0]\n y[n, step+1] -= moveVec[1]\n\n\n return x, y\n\n\n\n\nnOfParticles = 100\n#rot_dif_T = 0.2\n#trans_dif_T = 0.2\n#v = 1\nnis= [np.pi *2, np.pi * 0.2, np.pi * 0.002]\nni = nis[2] \nv = 0.05\n# Total time.\nT = 50\ngridSize = 100\ntorque0 = 1\nparticle_radius = 1\ntorque_radius = 3 * particle_radius\n\nrot_dif_T = 0.2\ntrans_dif_T = 0.2\n# Number of steps.\nN = 6000\n# Time step size\ndt = T/N\n# Initial values of x.\n# you should init this to sth other than 0\nx = np.zeros((1 * nOfParticles,N+1))\nx[:,0] = np.random.random(nOfParticles) * gridSize\ny = np.zeros((1 * nOfParticles,N+1))\ny[:,0] = np.random.random(nOfParticles) * gridSize\nfi = np.zeros((1 * nOfParticles,N+1))\nfi[:,0] = np.random.random(nOfParticles) * 2*np.pi\n#x[:, 0] = 0.0\n\nx, y = activeSwimmers(x, y, fi, N, dt, torque0, nOfParticles, ni, v, trans_dif_T, rot_dif_T, gridSize, particle_radius, torque_radius)\n\nfig, ax = plt.subplots()\nax.grid()\n# Plot the 2D trajectory.\ncamera = Camera(fig)\ns = (3*(ax.get_window_extent().width / (gridSize+1.) * 72./fig.dpi) ** 2)\n\n\nfor timestep in range(N):\n # for i in range(nOfParticles):\n if timestep % 40 == 0:\n\n clusteredP = set()\n cluster2 = []\n cluster3 = []\n cluster4 = []\n cluster5 = []\n cluster6 = []\n cluster7 = []\n actActNeig = {i:[] for i in range(nOfParticles)}\n\n pos = np.hstack((x[:, timestep].reshape((nOfParticles,1)), \n y[:, timestep].reshape((nOfParticles,1))))\n\n for i in range(nOfParticles):\n\n r = pos[i] - pos \n # calculate the norm of every direction vector\n rnorms = np.linalg.norm(r, axis=1).reshape((nOfParticles,1))\n actActNeig[i] = set([part for part in range(nOfParticles) if rnorms[part] < 4.1 * particle_radius])\n\n #cluster2 = cluster2.union({tuple(pos[j]) for j in range(nOfParticles) if rnorms[j] < 2.1*particle_radius and rnorms[j] > 0})\n clusteredP = clusteredP.union({j for j in range(nOfParticles) if rnorms[j] < 2.1*particle_radius and rnorms[j] > 0})\n\n\n\n\n ax.scatter(x[:, timestep], y[:, timestep], s=s, color='red')\n# cluster2 = np.array(list(cluster2))\n for j in range(nOfParticles):\n cluster = actActNeig[j].intersection(clusteredP)\n if len(cluster) == 2:\n cluster2.append([x[j, timestep], y[j,timestep]])\n if len(cluster) == 3:\n cluster3.append([x[j, timestep], y[j,timestep]])\n if len(cluster) == 4:\n cluster4.append([x[j, timestep], y[j,timestep]])\n if len(cluster) == 5:\n cluster5.append([x[j, timestep], y[j,timestep]])\n if len(cluster) == 6:\n cluster6.append([x[j, timestep], y[j,timestep]])\n if len(cluster) == 7:\n cluster7.append([x[j, timestep], y[j,timestep]])\n\n\n cluster2 =np.array(cluster2) \n cluster3 =np.array(cluster3) \n cluster4 =np.array(cluster4) \n cluster5 =np.array(cluster5) \n cluster6 =np.array(cluster6) \n cluster7 =np.array(cluster7) \n\n if len(cluster2) > 0:\n ax.scatter(cluster2[:, 0], cluster2[:, 1], s=s, color='blue')\n if len(cluster3) > 0:\n ax.scatter(cluster3[:, 0], cluster3[:, 1], s=s, color='green')\n if len(cluster4) > 0:\n ax.scatter(cluster4[:, 0], cluster4[:, 1], s=s, color='cyan')\n if len(cluster5) > 0:\n ax.scatter(cluster5[:, 0], cluster5[:, 1], s=s, color='pink')\n if len(cluster6) > 0:\n ax.scatter(cluster6[:, 0], cluster6[:, 1], s=s, color='gold')\n if len(cluster7) > 0:\n ax.scatter(cluster7[:, 0], cluster7[:, 1], s=s, color='ivory')\n # for p in range(nOfParticles):\n\n# for p in range(nOfParticles):\n #ax.plot(x[p, -10:], y[p, -10:], color='blue')\n#ax.plot(x[2, :], y[2, :], color='blue')\n camera.snap()\n\n#plt.show()\n# Mark the start and end points.\n#ax.plot(x[0,0],x[1,0], 'go')\n#ax.plot(x[0,-1], x[1,-1], 'ro')\n#\n## More plot decorations.\n#ax.set_title('2D Brownian Motion')\n#ax.set_xlabel('x', fontsize=16)\n#ax.set_ylabel('y', fontsize=16)\n#ax.axis('equal')\n#t = np.linspace(0,T,int(T//dt))\n#msd = MSD(x, dt, T)\n#msd = calcMSDAvg(rot_dif_T, trans_dif_T, v, T, N)\n#ax.loglog(t, msd)\nanimation = camera.animate()\nanimation.save('question2colorclustwork_ni=' +str(ni) +'.mp4')\nplt.show()\n","sub_path":"python_code/continuous/sample_code/question2.py","file_name":"question2.py","file_ext":"py","file_size_in_byte":8719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"178713166","text":"from django.db import migrations\n\n\ndef create_iso_list(apps, schema_editor):\n Bearing = apps.get_model('bearing', 'Bearing')\n BearingISO = apps.get_model('bearing', 'BearingISO')\n for name in list(set([item.iso for item in Bearing.objects.all()])):\n iso = BearingISO(name=name)\n iso.save()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('bearing', '0015_bearing_iso_model'),\n ]\n\n operations = [\n migrations.RunPython(create_iso_list),\n ]\n","sub_path":"app/bearing/migrations/0016_create_iso_list.py","file_name":"0016_create_iso_list.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"609439506","text":"# Android Renderer Use No Extra Package\nimport re\nimport os\nimport csv\nimport mimetypes\nfrom datetime import datetime\ntry:\n from html import escape\n from html import unescape\nexcept:\n import html.parser\n parser = html.parser.HTMLParser()\n unescape = parser.unescape\n \nimport templates\nfrom config import log, config\n\nbase_context = {\n 'id_name': 'book_id',\n 'charset': config.epub_charset,\n 'creator_info': '

Download And Compressed By '\n 'AutumnSun.

'\n}\n\nhtml_replaces = [\n (\"[\\r\\n]+\", \"\"),\n (\"\\s+\", \" \"),\n (\"(?i)(<(p|br|hr)[^<>]*>)+\", \"\\n\"),\n (\"(?s)\", \"\"),\n (\"(?i)<(ul|script|style)[^<>]*>[\\w\\W]*?\", \"\"),\n (\"(?i)<[!/]([a-zA-Z][a-zA-Z0-9]*)[^<>]*>\", \"\"),\n (\"(?i)<(?!img)([a-zA-Z][a-zA-Z0-9]*)[^<>]*>\", \"\"),\n (\"(?im)(^(&..sp;)+)|((&..sp;)+$)\", \"\"),\n (\"(?i)(&..sp;)+\", r\"\\1\"),\n (\"(?i)\\s*<(img [^>]+)>\\s*\", r\"\\n<\\1>\\n\"),\n (\"\\n+\", \"\\n\"),\n # (re.compile(\"(&..sp;)\", re.M), \" \"),\n]\ntext_replaces = [\n (\"[\\t  ]+\", \" \"),\n (\"&(?![#a-zA-Z0-9]{1,9};)\", \"&\"),\n # (\"<([a-zA-Z][a-zA-Z0-9]* [^<]+>)\", r\"<\\1\"),\n # (\"(<[a-zA-Z][a-zA-Z0-9]* [^<].+)>\", r\"\\1>\"),\n]\ntitle_reps = [\n ('&(?!#\\d{1,5};)', '&'), \n (']*>', ''),\n ('<', '<'), \n ('>', '>'),\n (r'[/\\\\\"]', '_'),\n (r'\\?', '?'),\n (r':', ':'),\n (r'\\*', '*'),\n (r'\\|', '|'),\n]\n\nhtml_pattern = re.compile(']*>|'\n '&(#?[a-zA-Z\\d]{1,8});')\n# chapter_item: (0 tab, 1 ignore, 2 title, 3 local src, 5 chapter id)\nchapter_item = re.compile('^' + config.chapter_item.format(\n '(\\t*)', '(#? ?)', *['(.*?)'] * 5) + '$', re.M)\n\n\ndef basename(url):\n if not url:\n return ''\n name = os.path.basename(url)\n idx = name.rfind('.')\n if idx > 0:\n name = name[:idx]\n if len(name) == 0:\n return url\n name = re.sub('\\W+', '_', name, re.A)\n if name[0].isalpha():\n return name\n else:\n return 'x' + name\n\n \ndef proper_title(title):\n title = replace_all(title, templates.entities)\n for rep in title_reps:\n title = re.sub(rep[0], rep[1], title)\n return title\n \n \ndef size2str(size):\n units = [\"B\", \"KB\", \"MB\", \"GB\"]\n i = 0\n while size >= 1000 and i < len(units) - 1:\n size /= 1024\n i += 1\n return \"%.2f%s\" % (size, units[i])\n\n\ndef html2text(html):\n if not html_pattern.search(html):\n return html\n lines = unescape(replace_all(html, html_replaces)).splitlines()\n lines = [\"{}\\n\".format(line) for line in lines if line]\n return \"\".join(lines)\n\n\ndef text2xhtml(text, check=False, escape=escape):\n if check and html_pattern.match(text):\n if set(re.findall('<([^>]+)[ \\t]*>', text)) <= {'p', '/p', 'br/', 'img'}:\n return text\n return html2xhtml(text)\n lines = replace_all(text, text_replaces + templates.entities).splitlines()\n log(45, 'text2xhtml: get', len(lines), \"lines\")\n return \"\\n\".join([\"{}
\".format(escape(line)) for line in lines if line])\n\n\ndef html2xhtml(html):\n lines = replace_all(html, html_replaces + text_replaces + templates.entities).splitlines()\n lines = [\"{}
\".format(line) for line in lines if line]\n log(45, 'html2xhtml: get', len(lines), \"lines\")\n return \"\\n\".join(lines)\n\n\ndef replace_all(text, reps=None):\n if reps is None:\n reps = html_replaces + text_replaces\n for each in reps:\n text = re.sub(each[0], each[1], text)\n return text\n\n\ndef load_chapter_list(file_path):\n if os.path.isdir(file_path):\n file_path = os.path.join(file_path, 'Chapters.csv')\n if not os.path.isfile(file_path):\n return []\n with open(file_path, 'r', -1, 'UTF-8') as fl:\n chapters = re.findall(chapter_item, fl.read().replace(' ', '\\t'))\n return chapters\n\n\ndef load_resource_list(file_path):\n if os.path.isdir(file_path):\n file_path = os.path.join(file_path, 'Resources.csv')\n if not os.path.isfile(file_path):\n return []\n with open(file_path, 'r', -1, 'UTF-8') as fl:\n resources = csv.reader([ln for ln in fl.readlines()\n if ln and ln[0] != '#'])\n return [res for res in resources if len(res) == 5]\n\n \ndef catalog_tree(chapters):\n roots = []\n levels = []\n last = -1\n chapters = [ch for ch in chapters if not ch[1]]\n # (0 tab, 1 ignore, 2 title, 3 local src, 5 net link)\n for i, chap in enumerate(chapters):\n level = len(chap[0])\n new_item = {\n 'index': i,\n 'title': proper_title(chap[2]),\n 'href': chap[3],\n 'children': [],\n }\n log(45, level, chap)\n if level > last + 1:\n level = last + 1\n last = level\n log(45, '{}{}: level={}'.format(chap[0], i, level), end=' ')\n if level == 0:\n roots.append(new_item)\n log(45, 'append to root')\n else:\n levels[level - 1]['children'].append(new_item)\n log(45, 'append to', levels[level - 1]['index'])\n\n if level >= len(levels):\n levels.append(new_item)\n else:\n levels[level] = new_item\n return {\n 'nodes': roots,\n 'chapters': chapters,\n 'max_level': len(levels)\n }\n\n\ndef render(template_name, *contexts, **kwargs):\n template_name = template_name.replace('.', '_')\n try:\n func = globals()[template_name]\n except Exception:\n func = templates.__getattribute__(template_name).format\n ctx = base_context.copy()\n for context in contexts:\n ctx.update(context)\n ctx.update(kwargs)\n content = func(**ctx)\n content = re.sub('>(\\s+?)<', '>\\n<', content)\n # if template_name.endswith(('.xhtml', '.ncx', '.opf', '.xml')):\n content = replace_all(content, templates.entities + [['

', '
']])\n return content.encode(config.epub_charset)\n\n\ndef chapter_xhtml(**context):\n context['title'] = replace_all(context['title'], text_replaces)\n return templates.chapter_xhtml.format(**context)\n\n\ndef intro_xhtml(**context):\n return templates.intro_xhtml.format(\n intro_xhtml=text2xhtml(context['intro']), **context)\n\n\n# def cover_xhtml(**context):\n# return templates.cover_xhtml.format(**context)\n\n\n# def container_xml(**context):\n# return templates.container_xml.format(**context)\n\n\ndef nav_xhtml(**context):\n context['nav_lis'] = nav_lis(context['nodes'],\n context['max_level'] - 1)\n return templates.nav_xhtml.format(**context)\n\n\ndef get_type(url):\n return mimetypes.guess_type(url)[0]\n\n\ndef package_opf(**context):\n context['manifest'] = ''\n manifest_srcs = {'nav.xhtml', 'toc.ncx', 'package.opf'}\n context['spine'] = ''\n for chap in context['chapters']:\n chap_id = basename(chap[3])\n if chap[3] not in manifest_srcs:\n context['manifest'] += templates.manifest_item.format(\n chap_id, chap[3], get_type(chap[3]), '')\n manifest_srcs.add(chap[3])\n context['spine'] += templates.spine_item.format(chap_id)\n for item in context['resources']:\n if item[1] not in manifest_srcs:\n res_id = 'res_' + basename(item[1])\n context['manifest'] += templates.manifest_item.format(\n res_id, item[1], get_type(item[1]), item[3])\n manifest_srcs.add(item[1])\n context['now'] = datetime.now().strftime(\"%Y-%m-%dT%H:%m:%SZ\")\n return templates.package_opf.format(**context)\n\n\ndef toc_ncx(**context):\n context['chapter_len'] = len(context['chapters'])\n context['nav_points'] = nav_points(context['nodes'])\n return templates.toc_ncx.format(**context)\n\n\ndef nav_lis(nodes, bold_level=3, level=0):\n if not nodes:\n return ''\n xhtml = '
    \\n'.format(level)\n bold = ' class=\"bold\"' if level < bold_level else ''\n for node in nodes:\n xhtml += '
  1. '\n log(35, 'nav_li:', node['href'], node['title'])\n if 'href' in node and node['href']:\n xhtml += '{1[title]}'.format(bold, node)\n else:\n xhtml += '{1[title]}'.format(bold, node)\n xhtml += nav_lis(node['children'], bold_level, level + 1)\n xhtml += '
  2. \\n'\n xhtml += '
\\n'\n return xhtml\n\n\ndef nav_points(nodes):\n xml = ''\n for node in nodes:\n xml += templates.nav_point.format(node)\n xml += nav_points(node['children'])\n xml += ''\n return xml\n\n# env.filters.update({\n# 'mimetype': lambda u: mimetypes.guess_type(u)[0],\n# 'len': len,\n# 'basename': basename,\n# 'text2xhtml': text2xhtml\n# })\n# env.globals.update({\n# 'charset': config.epub_charset,\n# 'creator_info': creator_info,\n# 'now': lambda: datetime.now().strftime(\"%Y-%m-%dT%H:%m:%SZ\")\n# })\nif __name__ == '__main__':\n\tprint(cgi.escape('&124'))","sub_path":"html_parser.py","file_name":"html_parser.py","file_ext":"py","file_size_in_byte":8933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"267435463","text":"# kelvin du\n# 101152192\nimport random\n\n\ndef placeMines():\n \"\"\"\n placeMines() -> returns a 2d list that represents a game board filled with mines\n \"\"\"\n # initialize a 2d matrix filled with 0s\n grid = [[0 for j in range(GRID_SIZE)] for i in range(GRID_SIZE)]\n # parse through the matrix and give values to cells\n for row in range(0, GRID_SIZE):\n for col in range(0, GRID_SIZE):\n mineHere = random.randint(0, MINE_CHANCE) # 1 in 10 chance for a mine\n if mineHere == 1:\n grid[row][col] = \"X\"\n else:\n grid[row][col] = \"\"\n return grid\n\n\ndef makeBoard():\n \"\"\"\n makeBoard() -> returns a 2d list that represents a game board\n \"\"\"\n grid = [[0 for j in range(GRID_SIZE)] for i in range(GRID_SIZE)]\n for row in range(0, GRID_SIZE):\n for col in range(0, GRID_SIZE):\n grid[row][col] = \"#\"\n return grid\n\n\ndef showBoard(board):\n \"\"\"\n showBoard(board) -> passes in the gameboard and prints the board\n \"\"\"\n numCol = \" |\"\n header = \"--\"\n for i in range(GRID_SIZE):\n numCol += str(i)\n header += \"-\"\n print(numCol)\n print(header)\n for row in range(GRID_SIZE):\n print(row, end = \"\")\n print(\"|\",end = \"\")\n for col in range(GRID_SIZE):\n if board[row][col] == \"\":\n print(\" \", end = \"\")\n print(board[row][col], end = \"\")\n print(\"\")\n\n\ndef countHiddenCells(board):\n \"\"\"\n countHiddenCells(board) -> passes in gameboard and returns number of unrevealed cells\n \"\"\"\n unrevealed = 0\n # parse through game board\n for row in range(len(board)):\n for col in range(len(board)):\n if board[row][col] == \"#\":\n unrevealed += 1 # add to unrevealed count\n return unrevealed\n\n\ndef countAllMines(board):\n \"\"\"\n countAllMines(board) -> passes a gameboard that contains mines and returns the number of mines\n \"\"\"\n mineCount = 0\n # parse through the board to count mines\n for row in range(len(board)):\n for col in range(len(board)):\n if board[row][col] == \"X\":\n mineCount += 1\n return mineCount\n\n\ndef isMineAt(board, row, col):\n \"\"\"\n isMineAt(board, row, col) -> passes in a game board, x,y coordinates and returns a boolean if\n a mine is at the coordinate\n \"\"\"\n if board[row][col] == \"X\":\n return True\n else:\n return False\n\n\ndef countAdjacentMines(board, x, y):\n \"\"\"\n countAdjacentMines(board, x, y) -> passes in a game board and retuns the adjacent number of cells\n \"\"\"\n adjacentMines = 0\n for newX in range(x - 1, x + 2):\n if 0 <= newX < GRID_SIZE:\n for newY in range(y - 1, y + 2):\n # print(newX, newY)\n if 0 <= newY < GRID_SIZE and board[newY][newX] == \"X\":\n # print(\"mines\")\n adjacentMines += 1\n return adjacentMines\n\n\ndef reveal(gameBoard, mineBoard, x, y):\n \"\"\"\n reveal(gameBoard, mineBoard, x, y) -> passes in a player board and game board, and xy coordinates\n reveals empty cells or reveals all bombs when player loses\n \"\"\"\n # if there is an empty cell continue to reveal adjacent empty cells\n if mineBoard[y][x] == \"\":\n mines = countAdjacentMines(mineBoard, x, y)\n if mines != 0:\n # show cell with adjacent mines\n gameBoard[y][x] = mines\n else:\n # make cell a space to keep the scale\n gameBoard[y][x] = \" \"\n # reveals the next cell\n for newX in range(x-1, x+2):\n if 0 <= newX < GRID_SIZE:\n for newY in range(y - 1, y + 2):\n # print(newX, newY)\n if 0 <= newY < GRID_SIZE and gameBoard[newY][newX] == \"#\":\n reveal(gameBoard, mineBoard, newX, newY)\n # gameBoard[x][y] = \" \"\n # if mines == 0:\n # else:\n # gameBoard[x][y] = mines\n else: # if player loses run this block\n # reveals all mines in the board\n for row in range(len(mineBoard)):\n for col in range(len(mineBoard)):\n if mineBoard[row][col] == \"X\":\n gameBoard[row][col] = \"X\"\n\ndef inputValid(text):\n \"\"\"\n inputValid(text) -> passes in a string and does various tests to check for\n input validity, returns a boolean if passes/fails test\n \"\"\"\n # check if has comma\n if \",\" not in text:\n return False\n # if it does split by comma\n temp = text.split(\",\")\n if len(temp) != 2:\n return False\n\n # check if there are only 2 values and both are numbers\n if not (temp[0].isdigit() and temp[1].isdigit()):\n return False\n if not (0 <= int(temp[0]) <= GRID_SIZE and 0 <= int(temp[1]) <= GRID_SIZE):\n return False\n return True\n\ndef main():\n gameLoop = True\n # initialize boards\n mineBoard = placeMines()\n playerBoard = makeBoard()\n # prints the starting board\n showBoard(playerBoard)\n while gameLoop:\n coord = input(\"Select a cell '(row,col)' > \")\n if inputValid(coord):\n coordList = coord.split(\",\")\n # print(countAdjacentMines(mineBoard, int(coordList[1]), int(coordList[0])))\n # check if there is a mine at the coordinate\n if isMineAt(mineBoard, int(coordList[0]), int(coordList[1])):\n # if there is a mine then reveal the board because game over\n reveal(playerBoard, mineBoard, int(coordList[1]), int(coordList[0]))\n # display the board with all mines\n showBoard(playerBoard)\n gameLoop = False\n print(\"GAME OVER!\")\n else:\n # check to reveal the rest of the empty cells\n reveal(playerBoard, mineBoard, int(coordList[1]), int(coordList[0]))\n showBoard(playerBoard)\n # if board is complete then player wins game\n if countHiddenCells(playerBoard) - countAllMines(mineBoard) <= 0:\n gameLoop = False\n print(\"You WIN!\")\n\nGRID_SIZE = 5\nMINE_CHANCE = 10\nmain()\n","sub_path":"minesweeper.py","file_name":"minesweeper.py","file_ext":"py","file_size_in_byte":6204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"377074089","text":"import pytest\nimport docker\nimport requests\nimport json\nimport time\nfrom random import SystemRandom\nfrom docker.types import EndpointSpec\nfrom os.path import dirname, join, realpath\n\n\nHUB_IMAGE_TAG = \"hub:test\"\nMOUNT_IMAGE_TAG = \"nielsbohr/ssh-mount-dummy\"\nNETWORK_NAME = \"jh_test\"\nHUB_SERVICE_NAME = \"jupyterhub\"\nMOUNT_SERVICE_NAME = 'mount_target'\n\nJHUB_URL = \"http://127.0.0.1:8000\"\n\nrand_key = ''.join(SystemRandom().choice(\"0123456789abcdef\") for _ in range(32))\n\n# root dir\nhub_path = dirname(dirname(__file__))\nhub_image = {'path': hub_path, 'tag': HUB_IMAGE_TAG, 'rm': True, 'pull': False}\n\n\nswarm_config = {'advertise_addr': '192.168.99.100'}\nnetwork_config = {'name': NETWORK_NAME, 'driver': 'overlay',\n 'options': {'subnet': '192.168.0.0/20'},\n 'attachable': True}\nhub_config = join(dirname(realpath(__file__)), 'configs', 'jupyterhub_config.py')\nhub_service = {'image': HUB_IMAGE_TAG, 'name': HUB_SERVICE_NAME,\n 'mounts': [\n ':'.join(['/var/run/docker.sock', '/var/run/docker.sock', 'rw']),\n ':'.join([hub_config, '/etc/jupyterhub/jupyterhub_config.py', 'ro'])\n ],\n 'networks': [NETWORK_NAME],\n 'endpoint_spec': EndpointSpec(ports={8000: 8000}),\n 'command': ['jupyterhub', '-f', '/etc/jupyterhub/jupyterhub_config.py']}\n\nremote_hub_config = join(dirname(realpath(__file__)), 'configs',\n 'remote_auth_jupyterhub_config.py')\nremote_hub_service = {'image': HUB_IMAGE_TAG, 'name': HUB_SERVICE_NAME,\n 'mounts': [\n ':'.join(\n ['/var/run/docker.sock', '/var/run/docker.sock', 'rw']),\n ':'.join(\n [remote_hub_config, '/etc/jupyterhub/jupyterhub_config.py',\n 'ro'])\n ],\n 'networks': [NETWORK_NAME],\n 'endpoint_spec': EndpointSpec(ports={8000: 8000}),\n 'env': ['JUPYTERHUB_CRYPT_KEY=' + rand_key],\n 'command': ['jupyterhub', '-f',\n '/etc/jupyterhub/jupyterhub_config.py']}\n\n\n@pytest.mark.parametrize('image', [hub_image], indirect=['image'])\n@pytest.mark.parametrize('swarm', [swarm_config], indirect=['swarm'])\n@pytest.mark.parametrize('network', [network_config], indirect=['network'])\ndef test_remote_auth_hub(image, swarm, network, make_service):\n \"\"\"Test that logging in as a new user creates a new docker service.\"\"\"\n make_service(remote_hub_service)\n client = docker.from_env()\n # Jupyterhub service should be running at this point\n services_before_spawn = client.services.list()\n\n user_cert = '/C=DK/ST=NA/L=NA/O=NBI/OU=NA/CN=Name' \\\n '/emailAddress=mail@sdfsf.com'\n # Auth header\n headers = {'Remote-User': user_cert}\n with requests.Session() as s:\n ready = False\n while not ready:\n try:\n s.get(JHUB_URL)\n if s.get(JHUB_URL + \"/hub/login\").status_code == 401:\n ready = True\n except requests.exceptions.ConnectionError:\n pass\n\n # Login\n login_response = s.post(JHUB_URL + \"/hub/login\", headers=headers)\n assert login_response.status_code == 200\n # Spawn a notebook\n spawn_form_resp = s.get(JHUB_URL + \"/hub/spawn\")\n assert spawn_form_resp.status_code == 200\n assert 'Select a notebook image' in spawn_form_resp.text\n payload = {\n 'dockerimage': 'nielsbohr/base-notebook:latest'\n }\n spawn_resp = s.post(JHUB_URL + \"/hub/spawn\", data=payload)\n assert spawn_resp.status_code == 200\n\n # New services are there\n post_spawn_services = list(set(client.services.list()) - set(\n services_before_spawn))\n assert len(post_spawn_services) > 0\n\n for service in post_spawn_services:\n while service.tasks() and \\\n service.tasks()[0][\"Status\"][\n \"State\"] != \"running\":\n time.sleep(1)\n state = service.tasks()[0][\"Status\"][\"State\"]\n assert state != 'failed'\n\n # Notebook ids\n notebook_services = [service for service in post_spawn_services\n if \"jupyter-\" in service.name]\n\n # Wait for user home\n for notebook_service in notebook_services:\n envs = {}\n for env in notebook_service.attrs['Spec']['TaskTemplate'][\n 'ContainerSpec']['Env']:\n key, value = env.split('=')\n envs[key] = value\n service_prefix = envs['JUPYTERHUB_SERVICE_PREFIX']\n home_resp = s.get(JHUB_URL + service_prefix)\n assert home_resp.status_code == 200\n\n # Write to user home\n hub_api_url = \"{}/api/contents/\".format(service_prefix)\n new_file = 'write_test.ipynb'\n data = json.dumps({'name': new_file})\n notebook_headers = {'X-XSRFToken': s.cookies['_xsrf']}\n resp = s.put(''.join([JHUB_URL, hub_api_url, new_file]), data=data,\n headers=notebook_headers)\n assert resp.status_code == 201\n\n # Remove via the web interface\n jhub_user = envs['JUPYTERHUB_USER']\n resp = s.delete(JHUB_URL + \"/hub/api/users/{}/server\".format(jhub_user),\n headers={'Referer': '127.0.0.1:8000/hub/'})\n assert resp.status_code == 204\n # double check it is gone\n services_after_remove = client.services.list()\n assert len((set(services_before_spawn) - set(services_after_remove))) == 0\n","sub_path":"tests/test_auth_service.py","file_name":"test_auth_service.py","file_ext":"py","file_size_in_byte":5799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"534981850","text":"import fudge\n\nfrom teuthology import config\nfrom teuthology.orchestra import connection\nfrom teuthology.orchestra.test.util import assert_raises\n\n\nclass TestConnection(object):\n def setup(self):\n import time\n time.sleep = lambda s: True\n\n def clear_config(self):\n config.config.teuthology_yaml = ''\n config.config.load()\n\n def test_split_user_just_host(self):\n got = connection.split_user('somehost.example.com')\n assert got == (None, 'somehost.example.com')\n\n def test_split_user_both(self):\n got = connection.split_user('jdoe@somehost.example.com')\n assert got == ('jdoe', 'somehost.example.com')\n\n def test_split_user_empty_user(self):\n s = '@somehost.example.com'\n e = assert_raises(AssertionError, connection.split_user, s)\n assert str(e) == 'Bad input to split_user: {s!r}'.format(s=s)\n\n @fudge.with_fakes\n def test_connect(self):\n self.clear_config()\n config.config.verify_host_keys = True\n fudge.clear_expectations()\n ssh = fudge.Fake('SSHClient')\n ssh.expects_call().with_args().returns(ssh)\n ssh.expects('set_missing_host_key_policy')\n ssh.expects('load_system_host_keys').with_args()\n ssh.expects('connect').with_args(\n hostname='orchestra.test.newdream.net.invalid',\n username='jdoe',\n timeout=60,\n )\n transport = ssh.expects('get_transport').with_args().returns_fake()\n transport.remember_order()\n transport.expects('set_keepalive').with_args(False)\n got = connection.connect(\n 'jdoe@orchestra.test.newdream.net.invalid',\n _SSHClient=ssh,\n )\n assert got is ssh\n\n @fudge.with_fakes\n def test_connect_no_verify_host_keys(self):\n self.clear_config()\n config.config.verify_host_keys = False\n fudge.clear_expectations()\n ssh = fudge.Fake('SSHClient')\n ssh.expects_call().with_args().returns(ssh)\n ssh.expects('set_missing_host_key_policy')\n ssh.expects('connect').with_args(\n hostname='orchestra.test.newdream.net.invalid',\n username='jdoe',\n timeout=60,\n )\n transport = ssh.expects('get_transport').with_args().returns_fake()\n transport.remember_order()\n transport.expects('set_keepalive').with_args(False)\n got = connection.connect(\n 'jdoe@orchestra.test.newdream.net.invalid',\n _SSHClient=ssh,\n )\n assert got is ssh\n\n @fudge.with_fakes\n def test_connect_override_hostkeys(self):\n self.clear_config()\n fudge.clear_expectations()\n sshclient = fudge.Fake('SSHClient')\n ssh = sshclient.expects_call().with_args().returns_fake()\n ssh.remember_order()\n host_keys = fudge.Fake('HostKeys')\n host_keys.expects('add').with_args(\n hostname='orchestra.test.newdream.net.invalid',\n keytype='ssh-rsa',\n key='frobnitz',\n )\n ssh.expects('get_host_keys').with_args().returns(host_keys)\n ssh.expects('connect').with_args(\n hostname='orchestra.test.newdream.net.invalid',\n username='jdoe',\n timeout=60,\n )\n transport = ssh.expects('get_transport').with_args().returns_fake()\n transport.remember_order()\n transport.expects('set_keepalive').with_args(False)\n create_key = fudge.Fake('create_key')\n create_key.expects_call().with_args('ssh-rsa',\n 'testkey').returns('frobnitz')\n got = connection.connect(\n 'jdoe@orchestra.test.newdream.net.invalid',\n host_key='ssh-rsa testkey',\n _SSHClient=sshclient,\n _create_key=create_key,\n )\n assert got is ssh\n","sub_path":"teuthology/orchestra/test/test_connection.py","file_name":"test_connection.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"142317873","text":"import unittest\nimport numpy\nimport dadi\n\n\nclass ParameterSelectionTestCase(unittest.TestCase):\n def test_best_fit(self):\n numpy.random.seed(1398238)\n \n fs = dadi.Spectrum.from_file(\"./tests/test_data/test_1D.fs\")\n \n demo_func = dadi.Numerics.make_anc_state_misid_func(dadi.Demographics1D.two_epoch)\n \n pts = [40,50,60]\n params=[2, 100, 0.5]\n upper_bound = [100, 3, 1]\n lower_bound = [1e-2, 0, 0]\n p_labels = ['nu', 'T', 'misid']\n \n best_params = dadi.ParameterSelection.best_fit(params, fs, \"two_epoch\", \n demo_func, 3, 3, pts=pts, fs_folded=False, param_labels=p_labels,\n func_args=[], upper_bound=upper_bound, lower_bound=lower_bound)\n \n numpy.allclose(best_params, [3.45125289, 0.62949395, 0.15234636])\n \n\nsuite = unittest.TestLoader().loadTestsFromTestCase(ParameterSelectionTestCase)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/test_ParameterSelection.py","file_name":"test_ParameterSelection.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"579962436","text":"#import wsgiref.handlers\n#from google.appengine.ext import webapp\nimport webapp2\nfrom google.appengine.api import urlfetch\nimport urllib\n\n#class MainPage(webapp.RequestHandler):\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n url = 'http://lullar.appspot.com/include/top_menu'\n result = urlfetch.fetch(url)\n if result.status_code == 200:\n self.response.out.write(result.content)\n\napp = webapp2.WSGIApplication([\n ('/include/menu', MainPage),\n], debug=True)\n\n'''\ndef main(): \n application = webapp.WSGIApplication(\n [('/include/menu', MainPage)],\n debug=True) \n wsgiref.handlers.CGIHandler().run(application)\n\nif __name__ == \"__main__\":\n main()\n'''\n\n","sub_path":"com_2/include/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"32430747","text":"# Christopher Larson & Robert Pitts\n# CSCI 238 Lab18, Problem #2\n# person_list.py\n# 11/12/13\n#\n# Create and print a list of Person and Student objects.\n\nimport person\n\ndef main():\n \n friends = []\n robert = person.Student('Robert Pits', 'A001')\n friends.append(robert)\n kyle = person.Person('Kyle Smith')\n friends.append(kyle)\n chris = person.Student('Chris Larson', 'A002')\n friends.append(chris)\n john = person.Person('John Smith')\n friends.append(john)\n nikki = person.Student('Nikki Castillo', 'A003')\n friends.append(nikki)\n adam = person.Person('Adam Smith')\n friends.append(adam)\n\n for friend in friends:\n print(friend)\nmain()\n","sub_path":"python/other/person_list.py","file_name":"person_list.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"370560507","text":"#Constants\nVERSION = 0.1\n\nLOG_FILE = 'asteroid_log.txt'\n\nWINDOW_WIDTH = 640\nWINDOW_HEIGHT = 480\nWINDOW_TITLE = 'Asteroids'\nWINDOW_PERSPECTIVE = 45.0 # degrees\n\nNEAR = 0.1\nFAR = 1000.0\n\n# Time\nmaxDelta = 0.1 # Dt can be a max of 0.1 seconds\n\n# Objects\nobjects = {\n 'MIN_VELOCITY': 1.4,\n 'POSITION': (0.0,30.0,0.0) \n}\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"586268158","text":"'''\ncalculate speedup for the function aggregate examples.\n'''\n\norig = []\nwith open('fa01.txt', 'r') as inFile:\n for line in inFile:\n tokens = line.split(',')\n orig.append((int(tokens[0]), float(tokens[1])))\n\nspedup = []\nwith open('fa04.txt', 'r') as inFile:\n for line in inFile:\n tokens = line.split(',')\n spedup.append((int(tokens[0]), float(tokens[1])))\n\nfor o, s in zip(orig[1:], spedup[1:]):\n speedup = o[1] / s[1]\n print('{0:d},{1:f}'.format(o[0],speedup))\n","sub_path":"src/optimizing-python/function-aggregate/speedup.py","file_name":"speedup.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"594260896","text":"from __future__ import print_function\nimport httplib2\nimport os\n\nfrom apiclient import discovery\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\n\nimport datetime\n\nimport numpy as np\n\ntry:\n import argparse\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\nexcept ImportError:\n flags = None\n\n# If modifying these scopes, delete your previously saved credentials\n# at ~/.credentials/calendar-python-quickstart.json\nSCOPES = 'https://www.googleapis.com/auth/calendar.readonly'\nCLIENT_SECRET_FILE = 'config/client_secret.json'\nAPPLICATION_NAME = 'Google Calendar API Python Quickstart'\n\ntime_table = []\n\nfor h in range(9, 18):\n time1 = datetime.time(h, 15, 0)\n time2 = datetime.time(h, 45, 0)\n time_table.append(time1)\n time_table.append(time2)\n\ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials\n\n\ndef get_upcoming_events(calendar_id='primary', max_results=10):\n credentials = get_credentials()\n http = credentials.authorize(httplib2.Http())\n service = discovery.build('calendar', 'v3', http=http)\n\n now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time\n print('Getting the upcoming {} events'.format(max_results))\n events_result = service.events().list(\n calendarId=calendar_id, timeMin=now, maxResults=max_results, singleEvents=True,\n orderBy='startTime').execute()\n events = events_result.get('items', [])\n\n if not events:\n print('No upcoming events found.')\n return []\n else:\n return events\n\n\ndef extract_datetime(datetime_text):\n ymd, time = datetime_text.split('T')\n year, month, date = ymd.split('-')\n hms, _ = time.split('+')\n hour, minute, second = hms.split(':')\n return year, month, date, hour, minute, second\n\n\ndef events2text(calendar_id, person, max_results=100):\n events = get_upcoming_events(calendar_id, max_results)\n text = '\\n'\n text += person + 'さん\\n'\n\n for event in events:\n start = event['start'].get('dateTime', event['start'].get('date'))\n end = event['end'].get('dateTime', event['end'].get('date'))\n\n summary = event['summary']\n sy, smo, sd, sh, smi, ss = extract_datetime(start)\n ey, emo, ed, eh, emi, es = extract_datetime(end)\n text += '{}/{} {}:{}〜{}:{} {}\\n'.format(smo, sd, sh, smi, eh, emi, summary)\n\n return text\n\ndef events2array(calendar_id='primary', max_results=10):\n events_dic = {}\n all_events = []\n for i in range(len(calendar_id)):\n events = get_upcoming_events(calendar_id[i], max_results)\n all_events.append(events)\n\n for events in all_events:\n for event in events:\n start = event['start'].get('dateTime', event['start'].get('date'))\n end = event['end'].get('dateTime', event['end'].get('date'))\n\n sy, smo, sd, sh, smi, ss = extract_datetime(start)\n ey, emo, ed, eh, emi, es = extract_datetime(end)\n\n stime = datetime.time(int(sh), int(smi), 0)\n etime = datetime.time(int(eh), int(emi), 0)\n\n day = smo + '-' + sd\n\n if day not in events_dic:\n events_dic[day] = time2array(stime, etime)\n else:\n a = events_dic[day]\n b = time2array(stime, etime)\n events_dic[day] = np.logical_and(a, b)\n\n return events_dic\n\ndef time2array(start, end):\n freetime_list = []\n for tt in time_table:\n if start < tt and tt < end:\n freetime_list.append(0)\n else:\n freetime_list.append(1)\n\n freetime_array = np.array(freetime_list, dtype=bool)\n\n return freetime_array\n\ndef array2text(array):\n text = ''\n for i in range(len(array)):\n if array[i] == True:\n if time_table[i].minute == 15:\n text += '{}:{}〜{}:{}\\n'.format(time_table[i].hour, '00',\\\n time_table[i].hour, time_table[i].minute + 15)\n elif time_table[i].minute == 45:\n text += '{}:{}〜{}:{}\\n'.format(time_table[i].hour, time_table[i].minute - 15, \\\n time_table[i].hour + 1, '00')\n\n return text\n\ndef freetime2text(calendar_id):\n text = '\\n'\n\n freetime_dic = events2array(calendar_id)\n\n for k, v in sorted(freetime_dic.items()):\n text += k + '\\n'\n text += array2text(v) + '\\n'\n\n return text\n\ndef score(calendar_id='primary', max_results=10):\n events = get_upcoming_events(calendar_id, max_results)\n events_dic = {}\n scores_dic = {}\n for event in events:\n start = event['start'].get('dateTime', event['start'].get('date'))\n end = event['end'].get('dateTime', event['end'].get('date'))\n\n sy, smo, sd, sh, smi, ss = extract_datetime(start)\n ey, emo, ed, eh, emi, es = extract_datetime(end)\n\n stime = datetime.time(int(sh), int(smi), 0)\n etime = datetime.time(int(eh), int(emi), 0)\n\n day = datetime.datetime(int(sy), int(smo), int(sd))\n\n if day not in events_dic:\n events_dic[day] = time2array(stime, etime)\n else:\n a = events_dic[day]\n b = time2array(stime, etime)\n events_dic[day] = np.logical_and(a, b)\n\n for k, v in sorted(events_dic.items()):\n scores_dic[k] = len(v) - np.count_nonzero(v)\n\n return scores_dic\n\ndef recomend2text(calendar_id):\n text = '\\n'\n\n score_dic = {}\n day_list = []\n for i in range(len(calendar_id)):\n cid = calendar_id[i]\n scores = score(calendar_id=cid)\n for k, v in scores.items():\n if k not in score_dic:\n score_dic[k] = [0, 0, 0]\n score_dic[k][i] = v\n day_list.append(k)\n else:\n score_dic[k][i] = v\n\n sort_day_list = sorted(day_list)\n\n ans_dic1 = {}\n ans_dic2 = {}\n\n for j in range(len(sort_day_list)):\n sd = sort_day_list[j]\n sd_y = sd - datetime.timedelta(days=1)\n sd_t = sd + datetime.timedelta(days=1)\n\n if sd_y in score_dic and sd_t in score_dic:\n score_sum = [x + y + z for (x, y, z) in zip(score_dic[sd_y], score_dic[sd], score_dic[sd_t])]\n # print(sd, 'y:' ,score_dic[sd_y], 'td:', score_dic[sd], 'tm:', score_dic[sd_t], 'sum:', score_sum)\n\n elif sd_y in score_dic and sd_t not in score_dic:\n score_sum = [x + y for (x, y) in zip(score_dic[sd_y], score_dic[sd])]\n # print(sd, 'y:' ,score_dic[sd_y], 'td:', score_dic[sd], 'tm:', [0, 0, 0], 'sum:', score_sum)\n\n elif sd_y not in score_dic and sd_t in score_dic:\n score_sum = [x + y for (x, y) in zip(score_dic[sd], score_dic[sd_t])]\n # print(sd, 'y:' ,[0, 0, 0], 'td:', score_dic[sd], 'tm:', score_dic[sd_t], 'sum:', score_sum)\n\n else:\n score_sum = score_dic[sd]\n # print(sd, 'y:' ,score_dic[sd], 'td:', [0, 0, 0], 'tm:', score_dic[sd], [0, 0, 0], 'sum:', score_sum)\n\n ans_dic1[sd] = max(score_sum)\n ans_dic2[sd] = score_sum\n\n c = 0\n for k, v in sorted(ans_dic1.items(), key=lambda x: x[1]):\n c += 1\n if c < 4:\n strk = str(k)\n text += strk[5:10] + 'を' + str(c) + '番におすすめします!\\n'\n text += '当日および前後二日間の予定時間の合計は・・・'\n text += 'Aさん:' + str(ans_dic2[k][0] / 2)\\\n + '時間 / Bさん:' + str(ans_dic2[k][1] / 2)\\\n + '時間 / Cさん:' + str(ans_dic2[k][2] / 2) + '時間です!\\n'\n text += '---------------------------------------------------------------------------------------------------------------------------------------\\n'\n\n return text\n\ndef search2text(calendar_id, keyword, person, max_results=10):\n events = get_upcoming_events(calendar_id, max_results)\n text = '\\n'\n\n text += person + 'さん\\n'\n\n for event in events:\n start = event['start'].get('dateTime', event['start'].get('date'))\n end = event['end'].get('dateTime', event['end'].get('date'))\n\n summary = event['summary']\n sy, smo, sd, sh, smi, ss = extract_datetime(start)\n ey, emo, ed, eh, emi, es = extract_datetime(end)\n\n if keyword in summary:\n text += '{}/{} {}:{}〜{}:{} {}\\n'.format(smo, sd, sh, smi, eh, emi, summary)\n\n return text\n\nif __name__ == '__main__':\n calendar_id = ['hoge@group.calendar.google.com',\\\n 'hogehoge@group.calendar.google.com',\\\n 'hogehogehoge@group.calendar.google.com']\n\n \"\"\"\n text = ''\n freetime_dic = events2array(calendar_id)\n\n for k, v in sorted(freetime_dic.items()):\n text += k + '\\n'\n text += array2txt(v) + '\\n'\n\n print(text)\n \"\"\"\n\n \"\"\"\n score_dic = {}\n day_list = []\n for i in range(len(calendar_id)):\n cid = calendar_id[i]\n scores = score(calendar_id=cid)\n for k, v in scores.items():\n if k not in score_dic:\n score_dic[k] = [0, 0, 0]\n score_dic[k][i] = v\n day_list.append(k)\n else:\n score_dic[k][i] = v\n\n sort_day_list = sorted(day_list)\n\n ans_dic1 = {}\n ans_dic2 = {}\n\n for j in range(len(sort_day_list)):\n sd = sort_day_list[j]\n sd_y = sd - datetime.timedelta(days=1)\n sd_t = sd + datetime.timedelta(days=1)\n\n if sd_y in score_dic and sd_t in score_dic:\n score_sum = [x + y + z for (x, y, z) in zip(score_dic[sd_y], score_dic[sd], score_dic[sd_t])]\n #print(sd, 'y:' ,score_dic[sd_y], 'td:', score_dic[sd], 'tm:', score_dic[sd_t], 'sum:', score_sum)\n ans_dic1[sd] = max(score_sum)\n ans_dic2[sd] = score_sum\n\n elif sd_y in score_dic and sd_t not in score_dic:\n score_sum = [x + y for (x, y) in zip(score_dic[sd_y], score_dic[sd])]\n #print(sd, 'y:' ,score_dic[sd_y], 'td:', score_dic[sd], 'tm:', [0, 0, 0], 'sum:', score_sum)\n ans_dic1[sd] = max(score_sum)\n ans_dic2[sd] = score_sum\n\n elif sd_y not in score_dic and sd_t in score_dic:\n score_sum = [x + y for (x, y) in zip(score_dic[sd], score_dic[sd_t])]\n #print(sd, 'y:' ,[0, 0, 0], 'td:', score_dic[sd], 'tm:', score_dic[sd_t], 'sum:', score_sum)\n ans_dic1[sd] = max(score_sum)\n ans_dic2[sd] = score_sum\n\n else:\n score_sum = score_dic[sd]\n #print(sd, 'y:' ,score_dic[sd], 'td:', [0, 0, 0], 'tm:', score_dic[sd], [0, 0, 0], 'sum:', score_sum)\n ans_dic1[sd] = max(score_sum)\n ans_dic2[sd] = score_sum\n\n c = 0\n for k, v in sorted(ans_dic1.items(), key=lambda x: x[1]):\n c += 1\n if c < 4:\n strk = str(k)\n print(strk[5:10], 'が', str(c), '番におすすめです!')\n print('Aさん:' ,ans_dic2[k][0] / 2,\\\n '時間 / Bさん:' ,ans_dic2[k][1] / 2,\\\n '時間 / Cさん:' ,ans_dic2[k][2] / 2, '時間')\n \"\"\"","sub_path":"application/google_calendar.py","file_name":"google_calendar.py","file_ext":"py","file_size_in_byte":12119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"64050790","text":"n = list(map(int, input(\"enter the number \")))\ni = 0\nwhile i < len(n)-1:\n n1 = n[i]\n n2 = n[i+1]\n if n1 == n2:\n print(\"YES\")\n break\n i = i + 1\nelse: print(\"NO\")\n","sub_path":"task4f.py","file_name":"task4f.py","file_ext":"py","file_size_in_byte":187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"139060450","text":"#! /usr/bin/env python3\n\"\"\" The Inventory Management Database Integration Test Suite \"\"\"\n\nimport io\nimport os\nimport sys\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\nfrom unittest import TestCase\nfrom unittest.mock import patch\nfrom database_basic import basic_operations\n\nclass TestIntegrationScenario(TestCase):\n \"\"\" Integration Test Class \"\"\"\n @classmethod\n def test_end_to_end(cls):\n \"\"\" Lifecyle End To End Test \"\"\"\n basic_operations.create_database()\n assert os.path.exists(basic_operations.DATABASE_NAME)\n basic_operations.add_customer(0,\n 'jaimes',\n 'hernandez',\n '101 Elliot Ave. SE',\n '205-222-1111',\n 'jh@gmail.com',\n True,\n 2000)\n assert basic_operations.search_customer(1)\n\n assert basic_operations.update_customer_credit(1, 2000)\n results = basic_operations.search_customer_status(1)\n for result in results:\n assert int(result['customer_id']) == 1\n assert result['status']\n assert int(result['credit_limit']) == 2000\n\n assert basic_operations.update_customer_credit(1, 3000)\n results = basic_operations.search_customer_status(1)\n for result in results:\n assert int(result['customer_id']) == 1\n assert result['status']\n assert int(result['credit_limit']) == 3000\n\n assert int(basic_operations.list_active_customers()) > 0\n assert basic_operations.delete_customer(1)\n assert int(basic_operations.list_active_customers()) == 0\n\n basic_operations.delete_database()\n assert not os.path.exists(basic_operations.DATABASE_NAME)","sub_path":"students/JoeNunnelley/lesson03/assignment/tests/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"154457632","text":"from email.parser import Parser as _Parser\n\nimport six\n\n\nif six.PY2:\n from cStringIO import StringIO\n from slimta.util.encoders import utf8only_encode, utf8only_decode\n\n class Parser(_Parser):\n def parsestr(self, text, headersonly=False):\n if isinstance(text, unicode):\n # difference with vanilla is we encode using utf-8, not ascii\n ret = self.parse(StringIO(utf8only_encode(text)),\n headersonly=headersonly)\n else:\n ret = _Parser.parsestr(self, text, headersonly)\n\n # homogeneous return type with py3\n ret._headers = [(utf8only_decode(i), utf8only_decode(j))\n for i, j in ret._headers]\n\n return ret\nelse:\n Parser = _Parser\n","sub_path":"slimta/util/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"427216502","text":"class Solution:\n \"\"\"\n @param height: the height\n @param width: the width\n @param tree: the position of tree\n @param squirrel: the position of squirrel\n @param nuts: the position of nuts\n @return: the minimal distance\n \"\"\"\n\n def minDistance(self, height, width, tree, squirrel, nuts):\n # Write your code here\n def distance(p1, p2):\n return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])\n\n total_distance, saved_distance = 0, -999999\n for nut in nuts:\n total_distance += distance(nut, tree) * 2\n saved_distance = max(saved_distance,\n distance(nut, tree) - distance(nut, squirrel))\n return total_distance - saved_distance\n","sub_path":"lintcode/873-squirrel-simulation.py","file_name":"873-squirrel-simulation.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"395912930","text":"from ..edn import loads, Dict, List, Keyword\nfrom ..query import Edge, Link, Field\nfrom ..compat import text_type\n\n\ndef _extract(values):\n for value in values:\n if isinstance(value, Keyword):\n yield Field(text_type(value))\n elif isinstance(value, Dict):\n for key, val in value.items():\n yield Link(text_type(key), transform(val))\n else:\n raise ValueError('Invalid edge member: {!r}'.format(value))\n\n\ndef transform(value):\n if isinstance(value, List):\n return Edge(list(_extract(value)))\n else:\n raise ValueError('Edge should be defined as vector, '\n '{!r} provided instead'.format(value))\n\n\ndef read(src):\n edn_ast = loads(src)\n return transform(edn_ast)\n","sub_path":"hiku/readers/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"64209239","text":"#!/usr/bin/env python\n\n#############################################################################\n#\n# PyQt5 slack client\n# Copyright (C) 2015 Reza Jelveh\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, see .\n#\n###########################################################################\n\nfrom PyQt5.QtGui import QIcon, QPixmap, QKeySequence\nfrom PyQt5.QtCore import (QFileInfo, QUrl, QSettings, QByteArray,\n QObject, pyqtSlot, pyqtProperty)\nfrom PyQt5.QtWidgets import (QAction, QApplication, QMainWindow,\n QSystemTrayIcon, QMessageBox, QDialog,\n QVBoxLayout, QMenu, QShortcut)\nfrom PyQt5.QtNetwork import QNetworkProxyFactory, QNetworkCookieJar, QNetworkCookie\nfrom PyQt5.QtWebKitWidgets import QWebPage, QWebView, QWebInspector\nfrom PyQt5.QtWebKit import QWebSettings\nfrom gi.repository import Notify\n# from os import startfile\nimport subprocess\n\n# from gi.repository import NM\n\n\nclass cookieJar(QNetworkCookieJar):\n def __init__(self, cookiesKey, parent=None):\n super(cookieJar, self).__init__(parent)\n\n self.mainWindow = parent\n self.cookiesKey = cookiesKey\n cookiesValue = self.mainWindow.settings.value(self.cookiesKey)\n\n if cookiesValue:\n cookiesList = QNetworkCookie.parseCookies(cookiesValue)\n self.setAllCookies(cookiesList)\n\n def setCookiesFromUrl(self, cookieList, url):\n cookiesValue = self.mainWindow.settings.value(self.cookiesKey)\n cookiesArray = cookiesValue if cookiesValue else QByteArray()\n\n for cookie in cookieList:\n cookiesArray.append(cookie.toRawForm() + \"\\n\")\n\n self.mainWindow.settings.setValue(self.cookiesKey, cookiesArray)\n\n return super(cookieJar, self).setCookiesFromUrl(cookieList, url)\n\n\nclass MainWindow(QMainWindow):\n def __init__(self, url):\n super(MainWindow, self).__init__()\n\n QShortcut(QKeySequence(\"Ctrl+Q\"), self, QApplication.instance().quit)\n self.progress = 0\n self.settings = QSettings()\n\n QNetworkProxyFactory.setUseSystemConfiguration(True)\n\n self.view = QWebView(self)\n self.view.load(url)\n self.view.page().setLinkDelegationPolicy(QWebPage.DelegateExternalLinks)\n self.view.linkClicked.connect(self.clickLink)\n self.view.titleChanged.connect(self.adjustTitle)\n self.view.loadProgress.connect(self.setProgress)\n self.view.loadFinished.connect(self.finishLoading)\n cookiesKey = \"cookies\"\n self.cookieJar = cookieJar(cookiesKey, self)\n self.view.page().networkAccessManager().setCookieJar(self.cookieJar)\n\n settings = self.view.settings()\n settings.setAttribute(QWebSettings.NotificationsEnabled, False)\n\n self.setCentralWidget(self.view)\n self.createActions()\n self.createTrayIcon()\n self.trayIcon.activated.connect(self.iconActivated)\n # self.view.setSystemTrayIcon(self.trayIcon)\n\n def showInspector(self):\n dlg = QDialog(self)\n i = QWebInspector(self)\n vbox = QVBoxLayout()\n dlg.setLayout(vbox)\n dlg.setModal(False)\n dlg.show()\n dlg.raise_()\n dlg.activateWindow()\n dlg.resize(800, 400)\n settings = self.view.settings()\n settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)\n i.setPage(self.view.page())\n i.setVisible(True)\n i.setEnabled(True)\n i.raise_()\n i.show()\n # it's important to add the widget after everything has been setup\n # otherwise it won't show up\n vbox.addWidget(i)\n self.view.triggerPageAction(QWebPage.InspectElement)\n\n def clickLink(self, url):\n # if sys.platform.startswith('linux'):\n subprocess.call([\"xdg-open\", url.toString()])\n # else:\n # startfile(file)\n\n def adjustTitle(self):\n if 0 < self.progress < 100:\n self.setWindowTitle(\"%s (%s%%)\" % (self.view.title(), self.progress))\n else:\n self.setWindowTitle(self.view.title())\n\n def setProgress(self, p):\n self.progress = p\n self.adjustTitle()\n\n def setPermissions(self):\n self.view.page().setFeaturePermission(self.view.page().mainFrame(), 0,\n QWebPage.PermissionGrantedByUser);\n\n def finishLoading(self):\n self.progress = 100\n self.adjustTitle()\n self.setPermissions()\n\n def createActions(self):\n self.minimizeAction = QAction(\"Mi&nimize\", self, triggered=self.hide)\n self.restoreAction = QAction(\"&Restore\", self,\n triggered=self.showMaximized)\n self.quitAction = QAction(\"&Quit\", self, shortcut=\"Ctrl+Q\",\n triggered=QApplication.instance().quit)\n\n def createTrayIcon(self):\n self.trayIconMenu = QMenu(self)\n self.trayIconMenu.addAction(self.minimizeAction)\n self.trayIconMenu.addAction(self.restoreAction)\n self.trayIconMenu.addSeparator()\n self.trayIconMenu.addAction(self.quitAction)\n info = QFileInfo(__file__)\n if info.isSymLink():\n _root = QFileInfo(info.symLinkTarget()).absolutePath()\n else:\n _root = info.absolutePath()\n\n icon = QIcon(QPixmap(_root + '/icons/icon_512x512.png'))\n\n self.trayIcon = QSystemTrayIcon(self)\n self.trayIcon.setIcon(icon)\n self.trayIcon.show()\n QApplication.setWindowIcon(icon)\n self.trayIcon.setContextMenu(self.trayIconMenu)\n\n def iconActivated(self, reason):\n if reason in (QSystemTrayIcon.Trigger, QSystemTrayIcon.DoubleClick):\n if self.isVisible():\n self.hide()\n else:\n self.showMaximized()\n\n\nif __name__ == \"__main__\":\n # Notify.init (\"Slack\")\n # create Client object\n # client = NM.Client.new(None)\n\n # # get all connections\n # connections = client.get_connections()\n\n # # print the connections' details\n # for c in connections:\n # print(\"=== %s : %s ===\" % (c.get_id(), c.get_path()))\n # c.for_each_setting_value(print_values, None)\n # print(\"\\n\")\n\n import sys\n\n app = QApplication(sys.argv)\n\n if not QSystemTrayIcon.isSystemTrayAvailable():\n QMessageBox.critical(None, \"Systray\",\n \"I couldn't detect any system tray on this system.\")\n sys.exit(1)\n\n QApplication.setQuitOnLastWindowClosed(False)\n\n url = QUrl('http://saucelabs.slack.com')\n browser = MainWindow(url)\n browser.show()\n\n sys.exit(app.exec_())\n","sub_path":"slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":7138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"99577538","text":"import os\nimport sys\nimport simplejson as json\n\nthis_dir = os.path.dirname(os.path.abspath(__file__))\nroot_dir = os.path.abspath(os.path.join(this_dir, '..', '..'))\nif root_dir not in sys.path:\n sys.path.insert(0, root_dir)\n\nimport torch\n\npred_path = 'datasets/tianchi_xray/predictions.pth'\n\n\ndef main():\n boxlists = torch.load(pred_path)\n for boxlist in boxlists:\n print(boxlist)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/tianchi_xray/stats_3.py","file_name":"stats_3.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"334080470","text":"def max_heapify(A, i): #ヒープ化(ノードの数をHとすると計算量は高さに比例するので(2^nで1段上がるので)(logH))\n l = 2 * i #左は2n\n r = 2 * i + 1 #右は2n+1\n largest = i #親を最大(最小)として仮置き\n if l < len(A) and A[l] > A[i]:\n largest = l\n else:\n largest = i\n if r < len(A) and A[r] > A[largest]:\n largest = r #largestに大きい方を代入して(右か左を)入れ替え\n if largest != i:\n tmp = A[i]\n A[i] = A[largest]\n A[largest] = tmp\n max_heapify(A, largest)\n\ndef build_maxheap(A): #配列の真ん中から左へ徐々にヒープ化していく(その高さごとにその要素数でheapするのでO(H))\n i = len(A) // 2\n while i >= 1:\n max_heapify(A, i)\n i -= 1\n\nif __name__ == \"__main__\":\n num_of_data = int(input())\n A = [int(x) for x in input().split()]\n A.insert(0, 0)\n\n build_maxheap(A)\n A = A[1:]\n print(' {0}'.format(' '.join(map(str, A))))\n\n","sub_path":"basic_2/maximum_heap.py","file_name":"maximum_heap.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"566636113","text":"# 12/30\ndef findNumbers(nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n return sum([len(str(n)) %2 ==0 for n in nums])\n\ntest = findNumbers([12,345,2,6,7896])\nassert(test==2)\nprint(test)","sub_path":"even-digit.py","file_name":"even-digit.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"199535154","text":"\"\"\"\r\nCompute Dice between test ground truth and predictions from groupwise registration.\r\n\r\n\r\n\"\"\"\r\nimport os\r\nimport nibabel as nib\r\nimport glob\r\nimport numpy as np\r\nfrom core import utils_2d\r\nfrom core.metrics_2d import OverlapMetrics\r\n\r\n\r\ndef one_hot_label(label, label_intensity):\r\n gt = np.around(label)\r\n n_class = len(label_intensity)\r\n label = np.zeros((np.hstack((gt.shape, n_class))), dtype=np.float32)\r\n\r\n for k in range(1, n_class):\r\n label[..., k] = (gt == label_intensity[k])\r\n\r\n label[..., 0] = np.logical_not(np.sum(label[..., 1:], axis=-1))\r\n\r\n return label\r\n\r\n\r\ndef load_nifty(name):\r\n img = nib.load(name)\r\n return np.asarray(img.get_fdata(), np.float32)\r\n\r\n\r\nif __name__ == '__main__':\r\n gt_path = '../../../../../../dataset/C0T2LGE/label_center_data/test/*label.nii.gz'\r\n pred_path = '../../../../../../results/MSCMR/test_predictions_1.5mm_group3_fusion15/*label.nii.gz'\r\n\r\n pred_names = utils_2d.strsort(glob.glob(pred_path))\r\n gt_names = utils_2d.strsort([name for name in glob.glob(gt_path) if os.path.basename(name).split('_')[1] == 'DE'])\r\n pred_gt_names = dict(zip(pred_names, gt_names))\r\n print(pred_gt_names)\r\n\r\n average_dice = []\r\n myo_dice = []\r\n LV_dice = []\r\n RV_dice = []\r\n for name in pred_names:\r\n\r\n pred_label = load_nifty(name)\r\n one_hot_pred = one_hot_label(pred_label, (0, 200, 500, 600))\r\n gt_label = load_nifty(pred_gt_names[name])\r\n gt_label = np.concatenate([gt for gt in np.dsplit(gt_label, gt_label.shape[-1])\r\n if np.all([np.sum(gt==i) > 0 for i in [200, 500, 600]])], axis=-1)\r\n one_hot_gt = one_hot_label(gt_label, (0, 200, 500, 600))\r\n\r\n Dice = OverlapMetrics(n_class=4, mode='np')\r\n\r\n dice = Dice.averaged_foreground_dice(one_hot_gt, one_hot_pred)\r\n m_dice = Dice.class_specific_dice(one_hot_gt, one_hot_pred, i=1)\r\n l_dice = Dice.class_specific_dice(one_hot_gt, one_hot_pred, i=2)\r\n r_dice = Dice.class_specific_dice(one_hot_gt, one_hot_pred, i=3)\r\n average_dice.append(dice)\r\n myo_dice.append(m_dice)\r\n LV_dice.append(l_dice)\r\n RV_dice.append(r_dice)\r\n print(\"Average foreground Dice for %s: %.4f\" % (os.path.basename(name), dice))\r\n\r\n print(\"Myocardium Dice for %s: %.4f\" % (os.path.basename(name), m_dice))\r\n\r\n print(\"LV Dice for %s: %.4f\" % (os.path.basename(name), l_dice))\r\n\r\n print(\"RV Dice for %s: %.4f\" % (os.path.basename(name), r_dice))\r\n\r\n print(\"Average prediction Dice: %.4f\" % np.mean(average_dice))\r\n print(\"Average myocardium Dice: %.4f\" % np.mean(myo_dice))\r\n print(\"Average LV Dice: %.4f\" % np.mean(LV_dice))\r\n print(\"Average RV Dice: %.4f\" % np.mean(RV_dice))\r\n\r\n\r\n","sub_path":"src_2d/help/compute_dice.py","file_name":"compute_dice.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"124439301","text":"#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python\n\n#################################################################################################\n# #\n# extract_gyro_data.py: find gyro drift during the grating movements #\n# #\n# author: t. isobe (tisobe@cfa.harvard.edu) #\n# #\n# last update: Mar 09, 2021 #\n# #\n#################################################################################################\n\nimport os\nimport sys\nimport re\nimport string\nimport math\nimport numpy\nimport unittest\nimport time\nimport unittest\nfrom datetime import datetime\nfrom time import gmtime, strftime, localtime\nimport Chandra.Time\nimport Ska.engarchive.fetch as fetch\nimport scipy\nfrom scipy.optimize import curve_fit\n#\n#--- plotting routine\n#\nimport matplotlib as mpl\nif __name__ == '__main__':\n\n mpl.use('Agg')\n\nfrom pylab import *\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as font_manager\nimport matplotlib.lines as lines\n#\n#--- reading directory list\n#\npath = '/data/mta/Script/Gyro/Scripts/house_keeping/dir_list'\n\nwith open(path, 'r') as f:\n data = [line.strip() for line in f.readlines()]\n\nfor ent in data:\n atemp = re.split(':', ent)\n var = atemp[1].strip()\n line = atemp[0].strip()\n exec(\"%s = %s\" %(var, line))\n#\n#--- append pathes to private folders to a python directory\n#\nsys.path.append(bin_dir)\nsys.path.append(mta_dir)\n#\n#--- import several functions\n#\nimport mta_common_functions as mcf #---- contains other functions commonly used in MTA scripts\n#\n#--- temp writing file name\n#\nrtail = int(time.time())\nzspace = '/tmp/zspace' + str(rtail)\n#\n#--- some data\n#\ncatg_list = ['roll', 'pitch', 'yaw']\ngrating_data = \"/data/mta_www/mta_otg/OTG_filtered.rdb\"\n\n#---------------------------------------------------------------------------------------\n#-- extract_gyro_data: find gyro drift during the grating movements --\n#---------------------------------------------------------------------------------------\n\ndef extract_gyro_data():\n \"\"\"\n find gyro drift during the grating movements\n input: none\n output: plots, table, and html \n \"\"\"\n#\n#--- find the last entry date\n#\n l_time = find_last_entry()\n#\n#--- find unprocessed data\n#\n gout = find_grating_insr_retr(l_time)\n#\n#--- go through each data\n#\n for k in range(0, len(gout[0])):\n #for k in range(0, 5):\n action = gout[0][k]\n grating = gout[1][k]\n start = gout[2][k]\n stop = gout[3][k]\n print(action + ' : ' + grating + ' : ' + str(start) + ' : ' + str(stop))\n#\n#--- extract data; fout contains data of roll, pitch, and yaw (time and value)\n#\n fout = extract_each_drift_data(start, stop)\n if len(fout[0][0]) == 0:\n continue\n\n for k in range(0, 3) :\n#\n#--- fit polinomial to the drift data\n#\n dout = fit_polinom_to_center(fout[k], start, stop, action, grating, catg_list[k])\n if dout == False:\n break\n\n [estimates, diff_data, f_time, sec1, sec2, sec3] = dout\n#\n#--- update data table\n#\n update_table(sec1, sec2, sec3, action, grating, catg_list[k], start, stop) \n#\n#--- create drift data plot\n#\n plot_drift(fout[k], f_time, estimates, start, stop, action, grating, catg_list[k])\n#\n#--- create deviation data plot\n#\n plot_dev(f_time, diff_data, action, grating, catg_list[k], start, stop)\n\n#---------------------------------------------------------------------------------------\n#-- find_grating_insr_retr: find time when the grating motion happened --\n#---------------------------------------------------------------------------------------\n\ndef find_grating_insr_retr(l_time):\n \"\"\"\n find time when the grating motion happened\n input: none, but read from /data/mta_www/mta_otg/OTG_filtered.rdb\n output: action --- a list of movement\n grating --- a lit of grating\n tstart --- a list of starting time in seconds from 1998.1.1\n tstop --- a list of stopping time in seconds from 1998.1.1\n \"\"\"\n#\n#--- read grating motion\n#\n gdata = read_data_file(grating_data)\n gdata = gdata[2:]\n \n action = []\n grating = []\n tstart = []\n tstop = []\n for ent in gdata:\n atemp = re.split('\\s+', ent)\n#\n#--- only new observations are kept\n#\n start = convert_to_stime(atemp[2])\n if start < l_time:\n continue\n#\n#--- only the data show the movement are used\n#\n if atemp[0] in ('INSR', 'RETR'):\n\n action.append(atemp[0])\n grating.append(atemp[1])\n tstart.append(start)\n tstop.append(convert_to_stime(atemp[4]))\n\n return [action, grating, tstart, tstop]\n\n#---------------------------------------------------------------------------------------\n#-- extract_each_drift_data: extract roll, pitch, yaw data around movement --\n#---------------------------------------------------------------------------------------\n\ndef extract_each_drift_data(start, stop):\n \"\"\"\n extract roll, pitch, yaw data around movement\n input: start --- starting time in seconds from 1998.1.1\n stop --- ending time in seconds from 1998.1.1\n output: roll --- a list of arrays of time and data; roll\n pitch --- a list of arrays of time and data; pitch\n yaw --- a list of arrays of time and data; yaw\n \"\"\"\n#\n#--- find a mid point and the range\n#\n mid = 0.5 * (stop + start)\n diff = stop - start\n dstart = start - diff\n dstop = stop + diff\n#\n#--- extract data from ska database\n#\n roll = get_data_from_ska('AOGBIAS1', dstart, dstop)\n pitch = get_data_from_ska('AOGBIAS2', dstart, dstop)\n yaw = get_data_from_ska('AOGBIAS3', dstart, dstop)\n\n roll = [roll[0] - mid, roll[1] * 1.0e8]\n pitch = [pitch[0] - mid, pitch[1] * 1.0e8]\n yaw = [yaw[0] - mid, yaw[1] * 1.0e8]\n\n return [roll, pitch, yaw]\n\n#---------------------------------------------------------------------------------------\n#-- fit_polinom_to_center: fitting a 5th degree polinomial to the data and find differences \n#---------------------------------------------------------------------------------------\n\ndef fit_polinom_to_center(fdata, start, stop, action, grating, catg):\n \"\"\"\n fitting a 5th degree polinomial to the data and find differences\n input: fdata --- a list of arrays of time and data\n start --- starting time in seconds from 1998.1.1\n stop --- stopping time in seconds from 1998.1.1\n action --- movement\n grating --- grating\n cag --- catogry (roll/pitch/yaw)\n output: estimates --- a list of model fitted data\n diff_data --- a list of difference between themodel and the data\n f_time --- a list of time for the selected data period\n sec1,sec2,sec3 --- list of [avg, std] of three sections\n \"\"\"\n#\n#--- set fitting range\n#\n tdiff = stop - start\n dstart = -1.5 * tdiff\n dstop = 1.5 * tdiff\n#\n#--- limit data to the fitting range\n#\n t_array = fdata[0]\n v_array = fdata[1]\n index = (t_array > dstart) & (t_array < dstop)\n f_time = t_array[index]\n f_data = v_array[index]\n#\n#--- fit the data\n#\n paraminitial = [0.0 for i in range(0, 5)]\n\n\n try:\n popt, pcov = curve_fit(p_model, f_time, f_data, p0=paraminitial)\n except:\n print(\"Something wrong with curve fitting\")\n return False\n#\n#--- create lists of data of estimated fitting and deviations\n#\n [estimates, diff_data] = compute_difference(f_time, f_data, popt)\n#\n#--- find avg and std of three sections\n#\n [sec1, sec2, sec3] = compute_avg_of_three_sections(f_time, diff_data, start, stop)\n#\n#--- write out the polinomial fitting result\n#\n write_poli_fitting_result(popt, start, stop, action, grating, catg)\n\n return [estimates, diff_data, f_time, sec1, sec2, sec3]\n\n#---------------------------------------------------------------------------------------\n#-- compute_difference: create model fitting results and a list of difference from the data \n#---------------------------------------------------------------------------------------\n\ndef compute_difference(f_time, f_data, popt):\n \"\"\"\n create model fitting results and a list of difference from the data\n input: f_time --- an array of time data\n f_data --- an array of data\n popt --- a list of parameters\n output: estimates --- a list of model fitted data\n diff_data --- a list of difference between themodel and the data\n \"\"\"\n [a0, a1, a2, a3, a4] = popt\n\n estimates = []\n diff_data = []\n for k in range(0, len(f_time)):\n est = p_model(f_time[k], a0, a1, a2, a3, a4)\n diff = f_data[k] - est\n estimates.append(est)\n diff_data.append(diff * 1.0e2)\n\n return [estimates, diff_data]\n\n#---------------------------------------------------------------------------------------\n#-- compute_avg_of_three_sections: compute avg and std of three sctions --\n#---------------------------------------------------------------------------------------\n\ndef compute_avg_of_three_sections(f_time, diff_data, start, stop):\n \"\"\"\n compute avg and std of three sctions\n input: f_time --- an array of time data\n diff_data --- an array of data\n start --- starting time in seconds from 1998.1.1\n stop --- stopping time in seconds from 1998.1.1\n output: [[, ], ...] --- three section avg and std\n \"\"\"\n hdiff = 0.5 * (stop - start)\n dstart = -hdiff\n dstop = hdiff\n\n index = f_time < dstart\n out1 = select_and_avg(index, diff_data)\n\n index = (f_time >= dstart) & (f_time < dstop)\n out2 = select_and_avg(index, diff_data)\n\n index = f_time >= dstop\n out3 = select_and_avg(index, diff_data)\n\n return [out1, out2, out3]\n\n#---------------------------------------------------------------------------------------\n#-- select_and_avg: compute avg and std --\n#---------------------------------------------------------------------------------------\n\ndef select_and_avg(index, idata):\n \"\"\"\n compute avg and std \n input: index --- a list of indices to select data\n idata --- a array of data\n output: avg --- avg\n std --- std\n \"\"\"\n idata = numpy.array(idata)\n selected = idata[index]\n avg = numpy.mean(selected)\n std = numpy.std(selected)\n\n return [avg, std]\n\n#---------------------------------------------------------------------------------------\n#---------------------------------------------------------------------------------------\n#---------------------------------------------------------------------------------------\n\ndef p_model(x, a0, a1, a2, a3, a4):\n\n out = a0 + a1 * x + a2 * x**2 + a3 * x**3 + a4 * x**4\n\n return out\n\n#---------------------------------------------------------------------------------------\n#-- write_poli_fitting_result: printing out polinomial parameters --\n#---------------------------------------------------------------------------------------\n\ndef write_poli_fitting_result(params, start, stop, action, grating, catg):\n \"\"\"\n printing out polinomial parameters\n input: params --- polinomial fitting results (with params to get fitting parameters)\n start --- starting time in seconds from 1998.1.1\n stop --- stopping time in seconds from 1998.1.1\n action --- movement\n grating --- grating\n catg --- category\n output: /Polinomial_results/_/