diff --git "a/2804.jsonl" "b/2804.jsonl" new file mode 100644--- /dev/null +++ "b/2804.jsonl" @@ -0,0 +1,689 @@ +{"seq_id":"419393526","text":"#!/usr/bin/python3\n#\n# fmx_physio_snoop.py Trace off cpu time for Informix threads\n# For Linux, uses BCC, eBPF. Embedded C.\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n#\n# 9-Mar-2019 Nagaraju Inturi Created this.\n#\n# USAGE: \n#./ifmx_offcputime_snoop.py\n#TIME(s) COMM PID OFFCPUTM(us)\n#0.000000000 oninit 14767 990515.68\n#0.000064000 oninit 14767 142.28\n#1.982759000 oninit 14767 1982701.30\n\nfrom __future__ import print_function\nfrom bcc import BPF\nimport ctypes as ct\nfrom os import getpid\nimport sys\nimport os\n\n#\n#if len(sys.argv) < 2:\n# print(\"USAGE: buffgetsnoop PID\")\n# exit()\npid = 0\n#pid = sys.argv[1]\n\n# load BPF program\nbpf_text = \"\"\"\n#include \n#include /* For TASK_COMM_LEN */\n\n// define output data structure in C\nstruct data_t {\n u64 ts;\n u64 delta;\n u32 pid;\n char name[TASK_COMM_LEN];\n};\n\ntypedef struct ifx_thrtime {\n u64 ts;\n} ifx_thrtime_t;\nBPF_HASH(bufmap, u64, ifx_thrtime_t);\nBPF_PERF_OUTPUT(events);\n\nint do_entry(struct pt_regs *ctx) {\n if (!PT_REGS_PARM2(ctx))\n return 0;\n\n u64 bp = PT_REGS_FP(ctx);\n ifx_thrtime_t thrtime = {0};\n u64 paddr = PT_REGS_PARM4(ctx);\n if (!paddr)\n return 0;\n thrtime.ts = bpf_ktime_get_ns();\n bufmap.update(&bp, &thrtime);\n\n return 0;\n}\nint do_return(struct pt_regs *ctx)\n{\n u64 bp = PT_REGS_FP(ctx);\n ifx_thrtime_t *thrtime = bufmap.lookup(&bp);\n\n if (thrtime) {\n u64 ts = bpf_ktime_get_ns();\n struct data_t data = {0};\n data.delta = ts - thrtime->ts;\n data.ts = ts/1000; \n data.pid = bpf_get_current_pid_tgid();\n bpf_get_current_comm(&data.name, sizeof(data.name));\n events.perf_submit(ctx, &data, sizeof(data));\n bufmap.delete(&bp);\n }\n\n return 0;\n};\n\"\"\"\n#bpf_text = bpf_text.replace('PID', pid)\nb = BPF(text=bpf_text)\noninitpath=str(os.environ.get('INFORMIXDIR'))+\"/bin/oninit\"\nfuncname=\"yield_processor_mvp\"\nb.attach_uprobe(name=oninitpath, sym=funcname, fn_name=\"do_entry\")\nb.attach_uretprobe(name=oninitpath, sym=funcname, fn_name=\"do_return\")\nfuncname2=\"yield_processor_svp\"\nb.attach_uprobe(name=oninitpath, sym=funcname2, fn_name=\"do_entry\")\nb.attach_uretprobe(name=oninitpath, sym=funcname2, fn_name=\"do_return\")\n\n\nTASK_COMM_LEN = 16 # linux/sched.h\nclass Data(ct.Structure):\n _fields_ = [(\"ts\", ct.c_ulonglong),\n (\"delta\", ct.c_ulonglong),\n (\"pid\", ct.c_uint),\n (\"name\", ct.c_char * TASK_COMM_LEN)]\n\n\nstart_ts = 0\nprev_ts = 0\ndelta = 0\n\n# header\nprint(\"%-14s %-14s %-6s %7s\" % (\"TIME(s)\", \"COMM\", \"PID\", \"OFFCPUTM(us)\"))\ndef print_event(cpu, data, size):\n event = ct.cast(data, ct.POINTER(Data)).contents\n\n global start_ts\n global prev_ts\n global delta\n\n if start_ts == 0:\n prev_ts = start_ts\n\n if start_ts == 1:\n delta = float(delta) + (event.ts - prev_ts)\n\n print(\"%-14.9f %-16s %-6d %7.2f\" % (delta / 1000000, event.name.decode(), \n event.pid, float(event.delta) / 1000))\n prev_ts = event.ts\n start_ts = 1\n\n# loop with callback to print_event\nb[\"events\"].open_perf_buffer(print_event, page_cnt=64)\nwhile 1:\n b.kprobe_poll()\n","sub_path":"ifmx_offcputime_snoop.py","file_name":"ifmx_offcputime_snoop.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"443265687","text":"##counties = [\"Arapahoe\",\"Denver\",\"Jefferson\"]\n##if counties[1] == 'Denver':\n## print(counties[1])\n\n##temperature = int(input(\"What is the temperature outside?\"))\n\n##if temperature > 80:\n## print(\"Turn on the AC.\")\n##else:\n## print(\"Open the windows.\")\n\n#What is the score?\n##score = int(input(\"What is your test score?\"))\n\n# Determine the grade\n##if score >= 90:\n## print('Your grade is an A.')\n##elif score >= 80:\n## print('Your grade is a B.')\n##elif score >= 70:\n## print('Your grade is a C')\n##elif score >= 60:\n## print('Your grade is a D')\n##else:\n## print('Your grade is an F')\n\n##counties = [\"Arapahoe\", \"Denver\",\"Jefferson\"]\n##if \"Arapahoe\" in counties and \"El Paso\" in counties:\n## print(\"Arapahoe and El Paso are in the list of counties.\")\n##else:\n## print(\"Arapahoe or El Paso is not in the list of counties.\")\n\n##counties = [\"Arapahoe\", \"Denver\",\"Jefferson\"]\n##if \"Arapahoe\" in counties or \"El Paso\" in counties:\n## print(\"Arapahoe or El Paso is in the list of counties.\")\n##else:\n## print(\"Arapahoe and El Paso are not in the list of counties.\")\n\n##x = 0\n#while x <= 5:\n# print(x)\n# x = x + 1\n\n#counties = [\"Arapahoe\", \"Denver\", \"Jefferson\"]\n#for county in counties:\n# print(county)\n\n#numbers = [0, 1, 2, 3, 4]\n#for num in range(5):\n# print(num)\n\n#counties = [\"Arapahoe\", \"Denver\", \"Jefferson\"]\n#for i in range(len(counties)):\n# print(counties[i])\n\n#counties_dict = {\"Arapahoe\": 422829, \"Denver\": 463353, \"Jefferson\": 432438}\n##for county in counties_dict.keys():\n# print(county)\n#for county in counties_dict:\n# print(counties_dict[county])\n\n#for county in counties_dict:\n# print(counties_dict.get(county))\n\n#for county, voters in counties_dict.items():\n# print(county, \"county has\", voters, \"registered voters\")\n\n#voting_data = [{\"county\":\"Arapahoe\", \"registered_voters\": 422829}, {\"county\":\"Denver\", \"registered_voters\": 463353},{\"county\":\"Jefferson\", \"registered_voters\": 432438}]\n#for county_dict in voting_data:\n# print(county_dict)\n\n#for county_dict in voting_data:\n# for value in county_dict.values():\n# print(value)\n\n#for county_dict in voting_data:\n# print(county_dict['county'])\n\n#my_votes = int(input(\"How many votes did you get in the election?\"))\n#total_votes = int(input(\"What is the total votes in the election?\"))\n#print(f\"I received {my_votes / total_votes * 100}% of the total votes.\")\n\n#counties_dict = {\"Arapahoe\": 369237, \"Denver\":413229, \"Jefferson\": 390222}\n#for county, voters in counties_dict.items():\n# print(f\"{county} county county has {voters} registered voters.\")\n\ncandidate_votes = int(input(\"How many votes did the candidate get in the election? \"))\ntotal_votes = int(input(\"What is the total number of votes in the election? \"))\nmessage_to_candidate = (\n f\"You received {candidate_votes:,} number of votes. \"\n f\"The total number of votes in the election was {total_votes:,}. \"\n f\"You received {candidate_votes / total_votes * 100:.2f}% of the total votes.\")\nprint(message_to_candidate)\n","sub_path":"Python_practice.py","file_name":"Python_practice.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"14627163","text":"import asyncio\n\nasync def sumsqr_task(my_id, num_tasks, n):\n total = 0\n for i in range(my_id, n+1, num_tasks):\n total += i * i\n return total\n\nasync def sumsqr(num_tasks, n):\n tasks = [asyncio.create_task(sumsqr_task(i, num_tasks, n)) for i in range(num_tasks)]\n total = 0\n for t in tasks:\n total += await t\n return total\n\n\nasync def sumsqr_task2(my_id, num_tasks, n, total, lock):\n for i in range(my_id, n+1, num_tasks):\n async with lock:\n total[0] += i * i\n\nasync def sumsqr2(num_tasks, n):\n lock = asyncio.Lock()\n total = [0]\n tasks = [asyncio.create_task(sumsqr_task2(i, num_tasks, n, total, lock)) for i in range(num_tasks)]\n await asyncio.gather(*tasks)\n return total[0]\n\nn = 10000\nnum_tasks = 6\nprint(asyncio.run(sumsqr(num_tasks, n)))\nprint(asyncio.run(sumsqr2(num_tasks, n)))\nprint(n * (n+1) * (2*n+1) // 6)\n\n","sub_path":"Asyncio/sumsqr.py","file_name":"sumsqr.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"468311268","text":"import csv\r\nimport glob\r\n\r\nimport pandas\r\n\r\nfrom NeuralEmulator.Utils.Utils import SpiceToFloat\r\n\r\nFOLDER_PATH = r\"C:\\Users\\Avi\\Desktop\\IntelliSpikesLab\\Emulator\\circuits\\PulseFull\"\r\nFILE_PATH = FOLDER_PATH + r'\\*.txt'\r\n\r\nfilesToRead = glob.glob(FILE_PATH)\r\nfor res in filesToRead:\r\n print(res)\r\n\r\n with open(res, 'r') as in_file:\r\n timeVed = []\r\n spikeVout = []\r\n\r\n iinToFreq = {}\r\n firstLine = in_file.readline()\r\n\r\n label = firstLine.split()[1]\r\n label = \"IOUT\"\r\n\r\n firstLine2 = in_file.readline()\r\n splittedLine = firstLine2.split()\r\n splittedLine = splittedLine[2:-2]\r\n\r\n cols = []\r\n vals = []\r\n for c in splittedLine:\r\n c = c.split(\"=\")\r\n cols.append(c[0])\r\n vals.append(SpiceToFloat(c[1]))\r\n\r\n data = {label: []}\r\n\r\n for x in cols:\r\n data[x] = []\r\n\r\n for line in in_file:\r\n splittedLine = line.split()\r\n\r\n if 'Step' in line:\r\n print(line)\r\n splittedLine = splittedLine[2:-2]\r\n\r\n vals = []\r\n for c in splittedLine:\r\n c = c.split(\"=\")\r\n vals.append(SpiceToFloat(c[1]))\r\n\r\n\r\n else:\r\n try:\r\n splittedLine = [SpiceToFloat(x) for x in splittedLine]\r\n\r\n if cols[0] not in data[cols[0]]:\r\n data[cols[0]].append(vals[0])\r\n data[cols[1]].append(vals[1])\r\n data[label].append(splittedLine[-1])\r\n except:\r\n print(\"asd\")\r\n\r\n\r\n df = pandas.DataFrame.from_dict(data)\r\n df = df.drop_duplicates()\r\n cvsFileName = res.replace(\".txt\", \".csv\")\r\n df.to_csv(cvsFileName,index=False)\r\n","sub_path":"Utils/ConvertStepSimulationToCSV.py","file_name":"ConvertStepSimulationToCSV.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439630218","text":"from functools import reduce\r\nfrom multiprocessing import Pool\r\n\r\n\r\nclass Generator:\r\n divisor = 2147483647\r\n\r\n def __init__(self, seed, factor, filter_divisor) -> None:\r\n super().__init__()\r\n self.previous = seed\r\n self.factor = factor\r\n self.filter_divisor = filter_divisor\r\n\r\n def get_next(self):\r\n while True:\r\n self.previous = (self.previous * self.factor) % self.divisor\r\n if self.previous % self.filter_divisor == 0:\r\n return self.previous\r\n\r\ndef get_next(generator):\r\n return generator.get_next()\r\n\r\nclass Generators:\r\n day = 15\r\n test = 2\r\n\r\n def process(self, generator1_seed, generator2_seed):\r\n if self.test == 1:\r\n count = 40000000\r\n generators = [Generator(generator1_seed, 16807, 1),\r\n Generator(generator2_seed, 48271, 1)]\r\n else:\r\n count = 5000000\r\n generators = [Generator(generator1_seed, 16807, 4),\r\n Generator(generator2_seed, 48271, 8)]\r\n\r\n pool = Pool(2)\r\n sum = 0\r\n for i in range(count):\r\n results = None\r\n results = list(map(get_next, generators))\r\n\r\n if reduce(lambda a, b: self.sameBinaryTail(a, b), results):\r\n print(i, results)\r\n sum += 1\r\n\r\n # if i % 100000 == 0:\r\n # print(i)\r\n\r\n print({'count': sum})\r\n\r\n def sameBinaryTail(self, next1, next2):\r\n return self.getBinaryTail(next1) == self.getBinaryTail(next2)\r\n\r\n def getBinaryTail(self, number):\r\n binaryTail = format(number, 'b').zfill(32)[-16:]\r\n return binaryTail\r\n\r\n\r\nif __name__ == \"__main__\":\r\n exercise = Generators()\r\n exercise.process(65, 8921)\r\n exercise.process(679, 771)\r\n","sub_path":"day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"498542564","text":"\n\nfrom xai.brain.wordbase.nouns._rocker import _ROCKER\n\n#calss header\nclass _ROCKERS(_ROCKER, ):\n\tdef __init__(self,): \n\t\t_ROCKER.__init__(self)\n\t\tself.name = \"ROCKERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"rocker\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_rockers.py","file_name":"_rockers.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"362759293","text":"\n#\n# This source file is part of appleseed.\n# Visit http://appleseedhq.net/ for additional information and resources.\n#\n# This software is released under the MIT license.\n#\n# Copyright (c) 2013-2015 Franz Beaune, Joel Daniels, Esteban Tovagliari.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n\nimport bpy\n\nimport functools\n\nimport appleseed as asr\n\n_options_metadata = asr.Configuration.get_metadata()\n\ndef _get_option_metadata(key):\n # todo: this is duplicated in Gaffer too.\n # maybe it's a good candidate to move to appleseed.python?\n return functools.reduce(lambda d, k: d[k], key.split(\".\"), _options_metadata)\n\ndef _create_option_property(cls, **kwargs):\n key = kwargs['key']\n name = key.replace('.', '_')\n\n md = _get_option_metadata(key)\n\n try:\n if 'type' in kwargs:\n opt_type = kwargs['type']\n else:\n opt_type = md['type']\n\n if 'label' in kwargs:\n label = kwargs['label']\n else:\n label = md['label']\n\n if 'help' in kwargs:\n help = kwargs['help']\n else:\n help = md['help']\n\n if 'extra_help' in kwargs:\n extra_help = \".\" + kwargs['extra_help']\n else:\n extra_help = \"\"\n\n help = help + extra_help\n\n prop = None\n\n if opt_type == 'int':\n prop = bpy.props.IntProperty(\n name = label,\n description = help,\n default = kwargs['default'] if 'default' in kwargs else int(md['default']))\n elif opt_type == 'float':\n prop = bpy.props.FloatProperty(\n name = label,\n description = help,\n default = kwargs['default'] if 'default' in kwargs else float(md['default']))\n elif opt_type == 'bool':\n prop = bpy.props.BoolProperty(\n name = label,\n description = help,\n default = kwargs['default'] if 'default' in kwargs else md['default']) \n elif opt_type == 'enum':\n opt_names = md['values'].split(\"|\")\n items = []\n for opt in opt_names:\n opt_md = md['options'][opt]\n items.append((opt, opt_md['label'], opt_md['help']))\n\n prop = bpy.props.EnumProperty(\n name = label,\n description = help,\n items = items,\n default = kwargs['default'] if 'default' in kwargs else md['default'])\n\n setattr(cls, name, prop)\n cls.configuration_property_list[name] = key\n except KeyError as e:\n print(\"Key error for option: \" + key + \" key not found: \" + str(e))\n\nclass AppleseedRenderSettings(bpy.types.PropertyGroup):\n @classmethod\n def register(cls):\n bpy.types.Scene.appleseed = bpy.props.PointerProperty(\n name = \"Appleseed Render Settings\",\n description = \"Appleseed render settings\",\n type = cls)\n\n cls.preview_pause = bpy.props.BoolProperty(\n name = \"Pause Preview\",\n description = \"Pause all viewport preview renders\",\n default = False)\n\n cls.export_project_path = bpy.props.StringProperty(\n description = \"Directory/name to save projects, # characters defines the position and length of frame numbers\",\n subtype = 'FILE_PATH',\n default = \"\")\n\n # render settings\n cls.configuration_property_list = {}\n\n # main\n _create_option_property(\n cls,\n key = \"generic_frame_renderer.passes\",\n label = \"Render Passes\",\n extra_help = \"When using photon mapping this is the number of progressive refinement passes used\")\n\n _create_option_property(cls, key = \"uniform_pixel_renderer.samples\", label=\"Pixel Samples\")\n\n # motion blur\n\n # lighting\n _create_option_property(cls, key = 'pt.dl_light_samples')\n _create_option_property(cls, key = 'pt.enable_caustics')\n _create_option_property(cls, key = 'pt.enable_ibl')\n _create_option_property(cls, key = 'pt.ibl_env_samples')\n\n _create_option_property(\n cls,\n key = 'pt.max_path_length',\n default = 0,\n extra_help = \"0 means unlimited\")\n\n _create_option_property(\n cls,\n key = 'pt.max_ray_intensity',\n default = 0.0,\n extra_help = \"Set to 0 to disable\")\n\n # system\n default_tx_cache_size_mb = _get_option_metadata(\n \"texture_store.max_size\")['default'] / (1024 * 1024)\n print(\"Texture cache size = \", default_tx_cache_size_mb)\n\n _create_option_property(\n cls, \n key = \"texture_store.max_size\",\n type = \"float\",\n default = default_tx_cache_size_mb,\n help = \"Texture cache size in megabytes.\")\n\n _create_option_property(cls, key = \"generic_frame_renderer.tile_ordering\")\n\n @classmethod\n def unregister(cls):\n del bpy.types.Scene.appleseed\n\ndef register():\n bpy.utils.register_class(AppleseedRenderSettings)\n\ndef unregister():\n bpy.utils.unregister_class(AppleseedRenderSettings)\n","sub_path":"appleseed-blender/properties/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":6229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"504921647","text":"\"\"\"\nfinal.py\nAuthor: Adam Glueck\nCredit: Stack oveflow (for eval function), my own bottomless wisdom and creativity\nAssignment: Choice\nI wrote a program to use several calculus estimation technqiues. \nI am most proud of its use of a class based parser,\nallowing it to convert traditional math notation into python math notation the eval function can determine.\n\"\"\"\ngoing='False'\nwhile going=='False':\n i=str(input(\"welcome to the calculus calculator. Would you like to: a, find the area under a curve), b (estimate the center of mass of an area between two functions), c (do basic math), q (quit)\"))\n for j in [\"a\",\"b\",\"c\",\"d\",\"q\"]:\n if i==j:\n going='True'\nfrom math import sin, cos, log, pi, e\nclass parse():\n def __init__(self,j):\n self.j=j\n function=\"\"\n f=list(self.j)\n for i in range (0,len(f)-1):\n if f[i]=='l' and f[i+1]=='n':\n f[i+1]='g'\n f.insert(i+1,'o')\n for i in range (0,len(f)):\n if f[i]=='^':\n f[i]='*'\n f.insert(i+1,'*')\n for i in range (0,len(f)-1):\n for k in ['1','2','3','4','5','6','7','8','9','0']:\n if f[i]==k and f[i+1]=='x':\n f.insert(i+1,'*') \n for i in range (0,len(f)-3):\n for k in ['1','2','3','4','5','6','7','8','9','0']:\n if f[i]==k and f[i+1]=='l' and f[i+2]=='o' and f[i+3]=='g':\n f.insert(i+1,'*')\n equation=\"\"\n for i in range (0,len(f)):\n equation=equation+f[i]\n self.equation=equation\nif i=='a':\n i=str(input(\"this function will approximate the area under a function, please enter your desired function\"))\n c=parse(i)\n f=c.equation\n xmin=float(input(\"x min \"))\n xmax=float(input(\"x max \"))\n numbershapes=float(input(\"number of shapes \"))\n step=(xmax-xmin)/numbershapes\n numbershapes=int(numbershapes)\n a=0\n for i in range (0,numbershapes):\n i=xmin+step*i\n x=i\n a=a+(eval(f))*step\n a=str(a)\n print(\"LRAM is \"+a)\n b=0\n for i in range (1,numbershapes+1):\n i=xmin+step*i\n x=i\n b=b+(eval(f))*step\n b=str(b)\n print(\"RRAM is \"+b)\n c=str((float(a)+float(b))/2)\n print(\"TRAPEZOID is \"+c)\n d=0\n for i in range (0,numbershapes):\n i=(xmin+step/2)+step*i\n x=i\n d=d+(eval(f))*step\n d=str(d)\n print(\"MRAM is \"+d)\n e=str(2*(float(d)+float(c))/3)\n print(\"SIMPSON'S is \"+e)\n i='q'\nif i=='b':\n yone=str(input(\"This program will find the center of mass of the shape between two functions, please input the upper function \"))\n ytwo=str(input(\"please enter the second function \"))\n xmin=float(input(\"please input the minimum x value \"))\n xmax=float(input(\"please input the minimum y value \"))\n one=parse(yone)\n two=parse(ytwo)\n equation=one.equation+'-('+two.equation+')'\n yavg='(('+one.equation+'+'+two.equation+')/2)'\n ytop=yavg+\"*(\"+equation+\")\"\n equation2=\"x*(\"+equation+\")\"\n d=0\n step=(xmax-xmin)/500\n for i in range (0,500):\n i=(xmin+step/2)+step*i\n x=i\n d=d+(eval(equation2))*step\n e=0\n for i in range (0,500):\n i=(xmin+step/2)+step*i\n x=i\n e=e+(eval(equation))*step\n top=0\n for i in range (0,500):\n i=(xmin+step/2)+step*i\n x=i\n top=top+(eval(ytop))*step\n bottom=0\n for i in range (0,500):\n i=(xmin+step/2)+step*i\n x=i\n bottom=bottom+(eval(equation))*step \n xcenter=str(d/e)\n ycenter=str(top/bottom)\n print('the center of mass is about ('+xcenter+', '+ycenter+')')\n i='q'\nif i=='c':\n i=str(input(\"please enter a math problem, there is no need to use weird python notation.\" ))\n problem=parse(i)\n print(eval(problem.equation))\n i='q'\nif i=='q':\n print(\"Goodbye\")\n","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"389921289","text":"import discord\nfrom discord.ext import commands\nimport random, secrets\nimport utils.checks as checks\n\n\nclass Halloween:\n def __init__(self, bot):\n self.bot = bot\n self.bot.waiting = None\n\n def __local_check(self, ctx):\n return ctx.author.id == 287_215_355_137_622_016\n\n @checks.has_char()\n @commands.cooldown(1, 43200, commands.BucketType.user)\n @commands.command(description=\"Trick or Treat!\")\n async def trickortreat(self, ctx):\n # temp\n waiting = self.bot.waiting\n if not waiting:\n self.bot.waiting = ctx.author\n return await ctx.send(\n \"You walk around the houses... Noone is there... *yet*\"\n )\n if secrets.randbelow(2) == 1:\n await ctx.send(\n f\"You walk around the houses and ring at {waiting}'s house! That's a trick or treat bag for you, yay!\"\n )\n await self.bot.pool.execute(\n 'UPDATE profile SET trickortreat=trickortreat+1 WHERE \"user\"=$1;',\n ctx.author.id,\n )\n else:\n await ctx.send(\n f\"You walk around the houses and ring at {waiting}'s house! Sadly they don't have anything for you...\"\n )\n try:\n if secrets.randbelow(2) == 1:\n await waiting.send(\n f\"The waiting was worth it: {ctx.author} rang! That's a trick or treat bag for you, yay!\"\n )\n await self.bot.pool.execute(\n 'UPDATE profile SET trickortreat=trickortreat+1 WHERE \"user\"=$1;',\n waiting.id,\n )\n else:\n await waiting.send(\n f\"{ctx.author} rings at your house, but... Nothing for you!\"\n )\n except discord.Forbidden:\n pass\n finally:\n self.bot.waiting = None\n async with self.bot.pool.acquire() as conn:\n await conn.execute(\n 'UPDATE profile SET money=money+50 WHERE \"user\"=$1', ctx.author.id\n )\n usr = await conn.fetchval(\n 'SELECT \"user\" FROM profile WHERE \"money\">=50 ORDER BY RANDOM() LIMIT 1;'\n )\n await conn.execute(\n 'UPDATE profile SET money=money-50 WHERE \"user\"=$1;', usr\n )\n usr = self.bot.get_user(usr) or \"Unknown User\"\n await ctx.send(f\"{usr} gave you additional $50!\")\n\n @checks.has_char()\n @commands.command(description=\"Open a trick or treat bag!\")\n async def yummy(self, ctx):\n # better name?\n async with self.bot.pool.acquire() as conn:\n bags = await conn.fetchval(\n 'SELECT trickortreat FROM profile WHERE \"user\"=$1;', ctx.author.id\n )\n if bags < 1:\n return await ctx.send(\n \"Seems you haven't got a trick or treat bag yet. Go get some!\"\n )\n mytry = random.randint(1, 6)\n if mytry == 1:\n maximumstat = float(random.randint(20, 30))\n elif mytry == 2 or mytry == 3:\n maximumstat = float(random.randint(10, 19))\n else:\n maximumstat = float(random.randint(1, 9))\n shieldorsword = random.choice([\"Sword\", \"Shield\"])\n names = [\n \"Jack's\",\n \"Spooky\",\n \"Ghostly\",\n \"Skeletal\",\n \"Glowing\",\n \"Moonlight\",\n \"Adrian's really awesome\",\n ]\n itemvalue = random.randint(1, 250)\n if shieldorsword == \"Sword\":\n itemname = f'{random.choice(names)} {random.choice([\"Sword\", \"Blade\", \"Stich\", \"Arm\", \"Bone\"])}'\n item = await conn.fetchrow(\n 'INSERT INTO allitems (\"owner\", \"name\", \"value\", \"type\", \"damage\", \"armor\") VALUES ($1, $2, $3, $4, $5, $6) RETURNING *;',\n ctx.author.id,\n itemname,\n itemvalue,\n \"Sword\",\n maximumstat,\n 0.00,\n )\n elif shieldorsword == \"Shield\":\n itemname = f'{random.choice(names)} {random.choice([\"Shield\", \"Defender\", \"Aegis\", \"Shadow Shield\", \"Giant Ginger\"])}'\n item = await conn.fetchrow(\n 'INSERT INTO allitems (\"owner\", \"name\", \"value\", \"type\", \"damage\", \"armor\") VALUES ($1, $2, $3, $4, $5, $6) RETURNING *;',\n ctx.author.id,\n itemname,\n itemvalue,\n \"Shield\",\n 0.00,\n maximumstat,\n )\n await conn.execute(\n 'INSERT INTO inventory (\"item\", \"equipped\") VALUES ($1, $2);',\n item[0],\n False,\n )\n await conn.execute(\n 'UPDATE profile SET trickortreat=trickortreat-1 WHERE \"user\"=$1;',\n ctx.author.id,\n )\n embed = discord.Embed(\n title=\"You gained an item!\",\n description=\"You found a new item when opening a trick-or-treat bag!\",\n color=0xFF0000,\n )\n embed.set_thumbnail(url=ctx.author.avatar_url)\n embed.add_field(name=\"ID\", value=item[0], inline=False)\n embed.add_field(name=\"Name\", value=itemname, inline=False)\n embed.add_field(name=\"Type\", value=shieldorsword, inline=False)\n if shieldorsword == \"Shield\":\n embed.add_field(name=\"Damage\", value=\"0.00\", inline=True)\n embed.add_field(name=\"Armor\", value=f\"{maximumstat}0\", inline=True)\n else:\n embed.add_field(name=\"Damage\", value=f\"{maximumstat}0\", inline=True)\n embed.add_field(name=\"Armor\", value=\"0.00\", inline=True)\n embed.add_field(name=\"Value\", value=f\"${itemvalue}\", inline=False)\n embed.set_footer(text=f\"Remaining trick-or-treat bags: {bags-1}\")\n await ctx.send(embed=embed)\n\n\ndef setup(bot):\n bot.add_cog(Halloween(bot))\n","sub_path":"cogs/halloween.py","file_name":"halloween.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"652925275","text":"# coding=utf-8\nimport ctypes # Comment this line like this comment for use under Linux or OSX\nimport pygame.locals\n# S I Z E S\n_user32 = ctypes.windll.user32 # Comment this line like this comment for use under Linux or OSX\n# (x,y-Auflösung = ┏━━━━━━━→ x-Achse ┏━━━━━━━→ y-Achse\nSCREENSIZE = _user32.GetSystemMetrics(0), _user32.GetSystemMetrics(1) # under Linux or OSX, if FULLHD type: SCREENSIZE = (1920,1080)\nSCREENTYPE = pygame.locals.RESIZABLE\nLAENGE = 30\nKANTENLAENGE_MINIMUM = 4\nHOEHE = 1\nFENSTER_RAND_ABSTAND = 2\n# C O L O R S\n# (rot-Wert, ↓ , blau-Wert)\n# ┃ grün-Wert ┃ Farbkodierung\n# ┗━ ━┓ ┏━┙┏━━━━━┙\nBLACK = (0, 0, 0) # (rot-Wert, grün-Wert, blau-Wert) Farbkodierung\nBLAUNEON = (100, 200, 255)\nGELBNEON = (255, 255, 0)\nGRUENNEON = (0, 255, 0)\nGRUEN_115 = (0, 115, 0)\nGRUEN_180 = (0, 180, 0)\nGRUEN_75 = (0, 75, 0)\nPINK = (125, 0, 125)\nROT = (255, 0, 0)\nROT_25 = (255, 0, 25)\nROTDUNKEL = (100, 0, 0)\nORANGE = (200, 100, 0)\nROT_100_100= (255, 100, 100)\n\nSOLUTIONPATHCOLOR = GRUEN_180\nBGCOLOR = BLACK\nWALLCOLOR_1 = ROT\nWALLCOLOR_2 = ROTDUNKEL\nPLAYERPATHCOLOR = GRUEN_115\nVALIDMOVECOLOR = GRUENNEON\nINVALIDMOVECOLOR = ROTDUNKEL\nSTARTCOLER = GRUENNEON\nZIELCOLER = ROT_100_100\nGENERATOR_COLOR = GRUEN_75\nBACKTRACKER_COLOR = GRUEN_180\n# M E S S A G E S\n# mazespiel._get_args() Messages:\nAXIS_HELP_MSG = \" Die Integer-Achsenwerte x-Achse und y-Achse jeweils durch 1 Leerzeichen trennen.\"\nGUI_HELP_MSG = \"Direkter Start in die Gui für ein einmaliges Spielen, ohne Konsolenausgabe des \" \\\n \"Labyrinths.\"\n\n# mazespiel.main() Messages:\nPARAM_MSG = \"\\n Parametrisierter Programmstart mit x-Achse = {} und y-Achse = {}.\"\nNO_PARAM_MSG = \"\\n Start des Programms ohne Parameter-Übergabe.\"\nOVER_2_PARAM_ERRMSG = \"\\n ERROR: Zu viele Argumente!\\n Es wird je 1 x-Achse und 1 y-Achse benötigt!\"\nONLY_1_PARAM_ERRMSG = OVER_2_PARAM_ERRMSG.replace(\"viele\",\"wenige\")\n\n# mazespiel.Konsole.setXYachsen() Messages:\nMENU = (\n\"\"\" \n ╻ ╻ Betriebssysteme ╻ ╻ Werkstück A7 ╻ \n Stella Malkogiannidou ┃ Amaal Mohamed ┃ ┃ Samira Hersi \n ┏━━━━┓ ┃ ┃ ━━━━━━━━━━┻━━━━┓ ┃ ┃ ┗━━━━╋━━━━ ┃ ┏━━━━┛ \n ┃ ┃ ┃ ┃ ╔══════════════╩════╩════╩═════════╩═══╗ ┃ ┃ \n ━┛ ┃ ┗━━━━┛ ║ M a z e G a m e M E N Ü ┌╍╍╍╍╍╍╍╫━━━━┫ ╹ ┏━━━━ \n ┃ ╠══════════════════════════════╡Eingabe╣ ┃ ┃ \n ━┓ ┣━━━━━━━━━━━━━━╢ Parametrisierter Start oder ┣╍╍╍╍╍╍╍╢ ┃ ┏━━━━┛ \n ┃ ┃ ║ xy-Achse der vorigen Runde? │ [ v ] ║ ┃ ┃ \n ┃ ╹ ┏━━━━┓ ╠╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┿╌╌╌╌╌╌╌╢ ╹ ╹ ╻ \n ┃ ┃ ┃ ║ xy-Achse zusammen eingeben? ╭│ 35x35 ║ ┃ \n ━┻━━━━━━━━━┛ ┣━━━━╢ TRENNER:'x',' ','*' wie Bsp→╯│[Enter]╠━━━━━━━━━━━━━━╋━━━━ \n ┃ ╠╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┿╌╌╌╌╌╌╌╢ ┃ \n ━┓ ╺━━━━┳━━━━┛ ║ Einzeleingabe der xy-Achse? │[Enter]║ ╺━━━━┓ ┃ \n ┃ ┃ ╠══════════════════════════════╪═══════╣ ┃ ┃ \n ┗━━━━┓ ┃ ╺━━━━╢ Programm beenden mit Taste │ [ q ] ╠━━━━╸ ┃ ┃ \n ┃ ┃ ╠══════════════════════════════╪═══════╣ ┃ ┃ \n ━╸ ┃ ┗━━━━┓ ║ Labyrinth als Daten ausgeben ┕━[ d ]━╢ ┏━━━━┛ ┃ \n ┃ ┃ ║ Info: y = Vertikale, x = Horizontale ║ ┃ ┃ \n ━━━━━━┫ ╺━━━━┛ ╚════╦══════════════╦════╦════════╦════╝ ┗━━━━┓ ┃ \n ┃ Frankfurt University of Applied Sciences 2021 ┃ ┃\n >?> \"\"\")\n\nWRONG_VALUE_ERRMSG = (\n \"\\n ERROR: Falls Option 'Eingabe zusammen' gewählt wurde, dann bitte nur:\\n\"\n \" [y-Achse][x][x-Achse] eingeben\\n\"\n \" OHNE Leerzeichen & als Trenner nur ein kleines 'x' wie z.B.:\\n\"\n \" 50x50\\n\"\n \" Bei EinzelEingabe und für die Achsen bitte NUR GANZE POSITIVE ZAHLEN \"\n \"eingeben!\"\n \"\\n\")\n\nTOO_MANY_VALUE_ERRMSG = \"\\n\\t ERROR! Es wurden mehr als 2 Werte eingegeben!\\n\"\n\n# mazespiel.getValidation_and_config() Messages:\nAXIS_TOO_BIG_ERRMSG = (f\"\\n\\t ERROR! Bei Ihrer Auflösung von {SCREENSIZE[0]}px, \"\n f\"{SCREENSIZE[1]}px können Sie maximal für\\n\\t y-Achse: ^ und für x-Achse: ^\"\n f\" eingeben, sodass das generierte\\n\\t Labyrinth vollständig dargestellt werden\"\n f\" kann!\\n\")\n\nAXIS_SMALLER_10_ERRMSG \\\n = (f\"\\n\\t ERROR! Die Achsenwerte sollten mindestens 10 betragen,\"\n f\"\\n\\t da die Wahrscheinlichkeit steigt, dass zufällig das\"\n f\"\\n\\t Start- und Zielfeld an der selben Koordinate y,x liegen!\"\n f\"\\n\\n\\t Info:{AXIS_TOO_BIG_ERRMSG[9:]}\\n\")\n\nAXIS_SMALLER_0_ERRMSG=\"\\n\\t ERROR! Achsenwerte dürfen nicht kleiner gleich 0 sein!\\n\"\n\nISVALID_MSG = (\"\\n\\n Validierung der Achsenwerte erfolgreich beendet!\\n\\n\" \n \" In kürze ercheint ein Labyrinth in der Konsole und direkt im\\n\"\n \" Anschluss die graphische Ausgabe, die entweder als Fenster oder\\n\"\n \" Vollbild erfolgt.\\n Viel Spaß beim Spielen...\\n\\n\\n\")\n\n# mazespiel.MazeSpiel.do_printGameMetrics() Messages:\nAUSWERTUNG_MSG = \" Auswertung:\\n Das Spiel wurde nach {} Sekunden {} beendet.\\n\" \\\n \" Es wurde {} Mal das Start- und Ziel-Feld neu vergeben.\\n\"\n\nSOLUTION_MSG = \" Spieler Gesamtschrittanzahl: {}\\n \" \\\n \"\\t- valide Schrittanzahl: {} ({} %)\\n\" \\\n \"\\t- invalide Schrittanzahl: {} ({} %)\\n\"\\\n \" Lösungspfadlänge: {}\\n\" \\\n \" Spieler-Effizienz: {} %\\n\\n\"\n","sub_path":"konstanten.py","file_name":"konstanten.py","file_ext":"py","file_size_in_byte":7634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"290162629","text":"from statistics import median\nimport argparse\nfrom pprint import pprint\nimport requests\nfrom bs4 import BeautifulSoup\nfrom ebaysheet import ebaysheet\n\n\ndef accept_title(title):\n if args.exclude is not None:\n for arg in args.exclude:\n if arg.lower() in title.lower():\n return False\n\n if args.required is not None:\n for arg in args.required:\n if arg.lower() not in title.lower():\n return False\n\n return True\n\n\ndef price_in_range(price):\n if args.minprice is not None:\n if price < args.minprice:\n return False\n\n if args.maxprice is not None:\n if price > args.maxprice:\n return False\n\n return True\n\n\ndef get_listings(url_to_scrape):\n r = requests.get(url_to_scrape, headers=headers)\n soup = BeautifulSoup(r.text, \"html.parser\")\n\n # Loop through all li's with \"s-item\" class AKA each listing box\n for li in soup.find_all(\"li\", class_=\"s-item\"):\n\n # Grab Title\n title_element = li.find(\"h3\", class_=\"s-item__title s-item__title--has-tags\")\n if title_element is None:\n continue\n\n title = title_element.text\n title = title.replace(\"New Listing\", \"\")\n\n if accept_title(title) is False:\n continue\n\n titles.append(title)\n\n # Grab Link\n link_element = title_element.find_parent(\"a\")\n link = link_element[\"href\"]\n\n # Grab Price\n price_element = li.find(\"span\", class_=\"s-item__price\")\n if price_element is None:\n continue\n price = price_element.text\n price = price.replace(\"$\", \"\").replace(\",\", \"\")\n\n if \"Tap item to see current price\" in price:\n continue\n\n if \" to \" in price:\n price_range = price.split(\" to \")\n price_midpoint = (float(price_range[0]) + float(price_range[1])) / 2\n price = price_midpoint\n\n price = float(price)\n prices.append(price)\n\n # Grab Shipping\n shipping_element = li.find(\"span\", class_=\"s-item__shipping s-item__logisticsCost\")\n if shipping_element is None:\n continue\n\n shipping = shipping_element.text\n shipping = shipping.replace(\"shipping\", \"\").replace(\"+\", \"\").strip()\n\n if shipping == \"Shipping not specified\" or shipping == \"Freight\":\n continue\n\n if shipping != \"Free\":\n shipping = shipping.replace(\"$\", \"\")\n shipped_price = price + float(shipping)\n shipped_price = round(shipped_price, 2)\n shipping = \"$\" + shipping\n elif shipping == \"Free\":\n shipped_price = price\n\n if price_in_range(shipped_price) is False:\n continue\n\n shipped_prices.append(shipped_price)\n\n # Grab Thumbnail\n thumbnail_element = li.find(\"img\", class_=\"s-item__image-img\")\n if thumbnail_element is None:\n continue\n\n img_url = thumbnail_element.attrs[\"src\"]\n\n listings.append([f'=IMAGE(\"{img_url}\")', f'=HYPERLINK(\"{link}\", \"{title}\")', \"$\" + str(price), shipping, \"$\" + str(shipped_price)])\n\n return listings\n\n\nlistings = []\ntitles = []\nprices = []\nshipped_prices = []\nheaders = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'}\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-search\", \"--keywords\", nargs=\"+\")\nparser.add_argument(\"-req\", \"--required\", nargs=\"+\")\nparser.add_argument(\"-exclude\", \"--exclude\", nargs='+')\nparser.add_argument(\"-pages\", \"--pages\", default=1, type=int)\nparser.add_argument(\"-min\", \"--minprice\", type=float)\nparser.add_argument(\"-max\", \"--maxprice\", type=float)\nargs = parser.parse_args()\n\nkeywords = args.keywords\nif keywords is None:\n keywords = input(\"Search:\")\n\nfor page in range(1, (args.pages + 1)):\n s = \"+\"\n url = f\"https://www.ebay.com/sch/i.html?_from=R40&_nkw={s.join(keywords)}&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1&_ipg=200&_pgn={page}\"\n # print(url)\n get_listings(url)\n\npprint(listings)\nprint(f\"Number of Listings:{len(listings)}\")\nprint(f\"Min:{min(shipped_prices)}\\nMax:{max(shipped_prices)}\\nMedian:{median(shipped_prices)}\")\n\nsh = ebaysheet()\nsh.values_clear(\"Sheet1!A2:M\")\nsh.values_update('Sheet1!A2', params={'valueInputOption': 'USER_ENTERED'}, body={'values': listings})\n","sub_path":"pyBay.py","file_name":"pyBay.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"241773284","text":"import import_all\nimport pathlib\nimport unittest\n\n\nclass PropertiesTest(import_all.ImportAllTest):\n MODULES = True\n PATHS = str(pathlib.Path(__file__).parent / 'edge' / 'edge')\n INCLUDE = 'edge.yes', 'edge.ok', 'edge.maybe', 'edge.sub.*'\n EXCLUDE = 'edge.no', 'edge.maybe', 'edge.sure'\n FAILING = 'edge.ok', 'edge.sub.one'\n\n\nclass ImportAllSubdirectoriesTest(import_all.ImportAllTest):\n FAILING = (\n 'test.edge.edge.maybe',\n 'test.edge.edge.no',\n 'test.edge.edge.ok',\n 'test.edge.edge.sub.one',\n 'test.edge.edge.sub2.one',\n 'test.edge.edge.sub2.sub',\n 'test.edge.edge.sub2.sub.two',\n )\n\n\nclass ModMatcherTest(unittest.TestCase):\n def test_empty(self):\n matches = import_all._ModuleMatcher('')\n self.assertFalse(matches(''))\n self.assertFalse(matches('foo'))\n\n def test_simple(self):\n matches = import_all._ModuleMatcher('foo:bar.*:baz.**')\n self.assertTrue(matches('foo'))\n self.assertFalse(matches('foo.foo'))\n\n self.assertTrue(matches('bar.foo'))\n self.assertFalse(matches('bar'))\n self.assertFalse(matches('bar.foo.bar'))\n\n self.assertTrue(matches('baz.foo'))\n self.assertTrue(matches('baz.foo.baz'))\n self.assertFalse(matches('baz'))\n","sub_path":"test/import_all_test.py","file_name":"import_all_test.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"376805035","text":"vowels = ['a','i','u','e','o']\r\nword = input(\"単語を入力してください。母音を探します。\")\r\n\r\nfound = {}\r\n\r\nfor letter in word:\r\n if letter in vowels:\r\n found[letter] += 1\r\n\r\nfor k,v in sorted(found.items()):\r\n print(k,'の出現回数は', v,'回。')\r\n","sub_path":"head_first_python/vowels5.py","file_name":"vowels5.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"543204268","text":"import requests\nfrom fake_useragent import UserAgent\nfrom scrapy.selector import Selector\nimport json\nimport time\nimport pymysql\n\n\ndef crawl_ip():\n \"\"\"爬取西刺的免费IP\"\"\"\n ip_list = []\n for i in range(1, 1000):\n headers = UserAgent()\n ua = getattr(headers, \"random\")\n ua = {\"User-Agent\": ua}\n url = \"http://www.xicidaili.com/nn/\" + str(i)\n response = requests.get(\"http://www.xicidaili.com/nn/\", headers=ua)\n # time.sleep(3)\n selector = Selector(text=response.text)\n alltr = selector.css(\"#ip_list tr\")\n for tr in alltr[1:]:\n speed_str = tr.css(\".bar::attr(title)\").extract_first()\n if speed_str:\n speed = float(speed_str.split(\"秒\")[0])\n else:\n speed = 0\n all_text = tr.css(\"td ::text\").extract()\n ip = all_text[0]\n port = all_text[1]\n type = all_text[6]\n if not 'HTTP' in type.upper():\n type = \"HTTP\"\n ip_list.append((ip, port, type, speed))\n\n conn = pymysql.connect(host=\"127.0.0.1\", user=\"root\", password=\"root\", db=\"outback\")\n cursor = conn.cursor()\n insert_sql = \"\"\"insert into ip_proxy(ip,port,type,speed) VALUES (%s,%s,%s,%s) \"\"\"\n for i in ip_list:\n try:\n cursor.execute(insert_sql, (i[0], i[1], i[2], i[3]))\n conn.commit()\n except Exception as e:\n print(e)\n conn.rollback()\n\n cursor.close()\n conn.close()\n\n\nprint(crawl_ip())\n\n\nclass GetIp(object):\n conn = pymysql.connect(host=\"127.0.0.1\", user=\"root\", password=\"root\", db=\"outback\")\n cursor = conn.cursor()\n\n def get_random(self):\n select_sql = \"select ip,port,tpye from ip_proxy ORDER by rand() limit 1\"\n\n result = cursor.execute(select_sql)\n for ip_info in cursor.fetchall():\n ip = ip_info[0]\n port = ip_info[1]\n type = ip_info[2].lower()\n judge_result = self.judge_ip(ip, port, )\n if judge_result:\n return \"{0}://{1}:{2}\".format(type, ip, port)\n else:\n self.get_random()\n\n def judge_ip(self, ip, port):\n baidu = \"https://www.baidu.com\"\n proxy_url = \"https://{0}:{1}\".format(ip, port)\n try:\n proxy_dict = {\n \"http\": proxy_url,\n }\n response = requests.get(baidu, proxies=proxy_dict)\n except Exception as e:\n print(\"invalid in or port \")\n self.delete_ip(ip)\n return False\n else:\n code = response.status_code\n if code >= 200 and code < 300:\n print(\"effective ip\")\n return True\n else:\n print(\"invalid in or port \")\n self.delete_ip(ip)\n return False\n\n def delete_ip(self, ip):\n delete_sql = \"\"\"delete form ip_proxy where ip={0}\"\"\", format(ip)\n try:\n cursor.execute(delete_sql)\n conn.commit()\n except Exception as e:\n print(e)\n finally:\n cursor.close()\n conn.close()\n\n\n# if __name__ == \"__main__\":\n# get_ip = GetIP()\n# get_ip.get_random()\n","sub_path":"outback/three_scrapy_project/outback/tools/xichiIP.py","file_name":"xichiIP.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"645925898","text":"__author__ = 'Alexey Nikitin'\nimport unittest\nfrom Friend import Friend\n\n\nclass TestFriend(unittest.TestCase):\n def setUp(self):\n self.friend = Friend()\n\n def reset_friend(self):\n self.friend = Friend()\n\n def test_listenHello1(self):\n self.reset_friend()\n\n sentences = [\"Привет!\", \"Привет\", \"привет\", \"привет.\"]\n expected = \"Привет!\"\n\n cnt = 0\n for sentence in sentences:\n answer = self.friend.listen(sentence)\n if answer == expected:\n cnt += 1\n self.assertEqual(len(sentences), cnt)\n\n def test_listenHello2(self):\n self.reset_friend()\n\n sentence = \"Привет, машина!\"\n answer = self.friend.listen(sentence)\n expected = \"Привет, человек!\"\n self.assertEqual(expected, answer)\n\n def test_listenHello3(self):\n self.reset_friend()\n\n sentence = \"Привет, котенок!\"\n answer = self.friend.listen(sentence)\n expected = \"Муррррр)\"\n self.assertEqual(expected, answer)\n\n def test_listenBuy1(self):\n self.reset_friend()\n\n sentences = [\"Пока!\", \"пока\", \"Пока!\", \"пока.\"]\n expected = \"Рад был пообщаться!\"\n cnt = 0\n for sentence in sentences:\n answer = self.friend.listen(sentence)\n if answer == expected:\n cnt += 1\n self.assertEqual(len(sentences), cnt)\n\n def test_listenAbracadabra1(self):\n self.reset_friend()\n\n sentence = \"пока привет\"\n expected = \"Я тебя не понимаю.\"\n answer = self.friend.listen(sentence)\n self.assertEqual(expected, answer)\n \n def test_listenHow1(self):\n self.reset_friend()\n\n sentence = \"как дела?\"\n expected = [\"Да пойдет.\", \"Нормально.\", \"Очень хорошо!\", \"Очень плохо...\", \"Пока не родила!\",\n \"Я на море! Все отлично!\"]\n answer = self.friend.listen(sentence)\n self.assertTrue(expected.count(answer) > 0)\n\n def test_listenHren1(self):\n self.reset_friend()\n\n sentence = \"Дедушка родил\"\n expected = [\"Идите за миллионом долларов от Чаплина!\", \"Такое бывает?\", \"Да ладно!\", \"Я тоже хочу!\"]\n answer = self.friend.listen(sentence)\n self.assertTrue(expected.count(answer) > 0)\n\n def test_listenBadBehavior(self):\n self.reset_friend()\n\n sentence = \"Пошел ты на...\"\n self.friend.listen(sentence)\n sentence = \"Привет!\"\n answer = self.friend.listen(sentence)\n expected = ['ну привет.']\n self.assertTrue(expected.count(answer) > 0)","sub_path":"tests/testFriend.py","file_name":"testFriend.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"253151526","text":"import numpy as np\n\ndef printMatrix(V):\n m = len(V)\n n = len(V[0])\n for i in range(m):\n for j in range(n):\n print(f'{V[i][j]:10.05f}' , end=\" \")\n print()\n print()\n \ndef matrixInput():\n m = int(input(\"Enter row size :\"))\n n = int(input(\"Enter column size :\"))\n\n A = np.zeros((m,n), dtype=float)\n \n print(\"Enter elements of matrix: \")\n for i in range(m):\n for j in range(n):\n A[i][j] = float(input())\n \n return (A,n)\n\n\ndef Normalize(v):\n sum = 0.0\n for i in v:\n sum+=i**2\n v=v/(sum**0.5)\n return v\n\ndef QRDecomp(A):\n \n n = len(A[0]) # Columns/Vectors\n m = len(A) # Rows/Components\n q = []\n \n q.append(Normalize(A[:,0].reshape(m,1)))\n \n for i in range(1,n):\n \n vec = A[:,i].astype('float64').reshape(m,1)\n temp = np.zeros((m,1),dtype=float)\n\n for j in range(i):\n\n multiplier = (((vec.transpose()).dot((q[j]))))/(q[j].transpose().dot(q[j]))\n temp -= (multiplier)*q[j]\n \n vec = vec + temp\n normalizedvec = Normalize(vec)\n q.append(normalizedvec)\n \n Q = np.array(q).transpose().reshape(m,n) # typecasting python list to numpy array and taking np.array's transpose\n \n # Calculating R\n R = np.zeros((n,n))\n for i in range(n):\n for j in range(n):\n if i<=j:\n R[i][j] = A[:,j].transpose().dot(Q[:,i])\n\n return Q,R\n\n\n\n\n# Default Input\n\nA = np.array(((\n (1, -1, 4),\n (1, 4, -2),\n (1, 4, 2),\n (1, -1, 0)\n)))\n\n# A = np.array([\n# [1,2,4],\n# [0,0,5],\n# [0,3,6]\n# ])\n\nQ,R = QRDecomp(A)\n\nprint(\"Q =\")\nprintMatrix(Q)\n\nprint(\"R =\")\nprintMatrix(R)\n\n# Uncomment following lines for custom input\n\n# A,n = matrixInput()\n","sub_path":"MachineLearning/ML-Programs/QR-DcompFlexible.py","file_name":"QR-DcompFlexible.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"236371750","text":"from flask import Flask, render_template, request, session\nimport sqlite3\nimport csv\n\napp = Flask(__name__)\n\nconn = sqlite3.connect('../ZachSiteDB.db')\nconn.execute('''CREATE TABLE if not exists projects (projid INTEGER PRIMARY KEY, projname TEXT NOT NULL, desc TEXT NOT NULL, link TEXT NOT NULL, img TEXT, editimg TEXT);''')\n\nwith open('app/static/csv/projects.csv') as csvfile:\n curs = conn.cursor()\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for csvrow in reader:\n curs.execute(\n 'SELECT * FROM projects WHERE projname = ? LIMIT 1', (csvrow[0],))\n trow = curs.fetchone()\n\n if trow is None:\n t = (csvrow[0], csvrow[1], csvrow[2], csvrow[3], csvrow[4])\n curs.execute(\n 'INSERT INTO projects (projname, desc, link, img, editimg) VALUES (?,?,?,?,?)', t)\n elif (csvrow[0] != trow[1] or csvrow[1] != trow[2] or csvrow[2] != trow[3] or csvrow[3] != trow[4] or csvrow[4] != trow[5]):\n t = (csvrow[0], csvrow[1], csvrow[2],\n csvrow[3], csvrow[4], trow[0])\n curs.execute(\n 'UPDATE projects SET projname=?, desc=?, link=?, img=?, editimg=? WHERE projid=?', t)\n\nconn.commit()\nconn.close()\n\n\n@app.route('/')\ndef home():\n return render_template('layoutBox.html')\n\n\n@app.route('/', methods=['POST'])\ndef process():\n hashID = request.form['hashID']\n print(hashID)\n if (hashID == \"projects\"):\n return projects()\n elif (hashID == \"resume\"):\n return resume()\n elif (hashID == \"home\"):\n return defaultCont()\n\n\ndef projects():\n con = sqlite3.connect(\"../ZachSiteDB.db\")\n con.row_factory = sqlite3.Row\n\n cur = con.cursor()\n cur.execute(\"SELECT * FROM projects\")\n\n rows = cur.fetchall()\n return render_template(\"projects.html\", rows=rows)\n\n\ndef resume():\n return render_template(\"resume.html\")\n\n\n@app.route('/default')\ndef defaultCont():\n return render_template('contentDefault.html')\n\n\nif __name__ == '__main__':\n app.secret_key = 'oihg49whg7hw4gi'\n app.run(debug=True)\n","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"412549982","text":"import os\nimport glob\nimport shutil\nimport datetime\n\n#destination for the different files\ndest1 = 'E:\\\\Bilder'\ndest2 = 'E:\\\\Video'\ndest3 = 'C:\\\\Users\\\\ukki\\\\Downloads\\\\pdf_files'\ndest4 = 'C:\\\\Users\\\\ukki\\\\Downloads\\\\exe_files'\n\n#list of filetype i want moved\npics = ['jpg', 'jpeg', 'bmp', 'gif', 'png']\nvids = ['webm', 'mpg', 'mp2', 'mpeg', 'mpe', 'mpv', 'ogg', 'mp4', 'm4p', 'm4v', 'flv']\nexe = ['exe']\npdf = ['pdf']\n\n#creating a list of files to move\ndef find_files(args):\n filelist = []\n all_files = glob.glob('C:\\\\Users\\\\ukki\\\\Downloads\\\\*')\n for file in all_files:\n for match in args:\n if file.endswith(match):\n filelist.append(file)\n return filelist\n\n\n#moving the files and adding date+time to the filename (also adding \"X\" at the end if the file already existed in the folder)\ndef move_files(here, there):\n for file in here:\n dest = file.replace('C:\\\\Users\\\\ukki\\\\Downloads', there)\n dest = dest.replace('.', datetime.datetime.fromtimestamp(os.path.getmtime(file)).strftime((\"_%Y-%m-%d_%H%M%S.\")))\n if os.path.exists(dest):\n dest = dest.replace('.', 'X.')\n shutil.move(file, dest)\n\n\npictures_list = find_files(pics)\nmove_files(pictures_list, dest1)\n\nvid_list = find_files(vids)\nmove_files(vid_list, dest2)\n\npdf_files = find_files(pdf)\nmove_files(pdf_files, dest3)\n\nexe_files = find_files(exe)\nmove_files(exe_files, dest4)\n","sub_path":"movefiles.py","file_name":"movefiles.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"546092560","text":"import os\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom datetime import datetime\r\n\r\nfrom shap.common import safe_isinstance\r\n\r\nfrom PyBox.defaults import DefaultValues\r\n\r\n\r\ndef pos_proba2pred_class(pos_proba: np.array, pos_threshold: float, pos_neg_classes: tuple):\r\n pos_str, neg_str = pos_neg_classes\r\n pred_class = pd.DataFrame([neg_str] * len(pos_proba))\r\n pred_class[pos_proba >= pos_threshold] = pos_str\r\n return pred_class\r\n\r\n\r\ndef get_eval_metric(evals_result_: dict):\r\n return list(evals_result_['validation_0'])[0]\r\n\r\n\r\ndef predictors_str_to_list(s: str):\r\n s.strip('[')\r\n s.strip(']')\r\n\r\n\r\ndef generate_unique_timestring():\r\n s = str(datetime.date(datetime.now())) + '-' + str(datetime.now().hour) + '-' + str(\r\n datetime.now().minute) + '-' + str(datetime.now().second)\r\n return s\r\n\r\n\r\ndef generate_dtype_dict(predictors_nomi=None, predictors_metr=None):\r\n d = {}\r\n if predictors_nomi is not None:\r\n d.update(__generate_dtype_dict(predictors_nomi, object))\r\n if predictors_metr is not None:\r\n d.update(__generate_dtype_dict(predictors_metr, float))\r\n return d\r\n\r\n\r\ndef __generate_dtype_dict(col_names: list, t: np.dtype):\r\n d = {}\r\n for i, c in enumerate(col_names):\r\n d[c] = t\r\n return d\r\n\r\n\r\ndef list_add_str_suffix(l: list, s: str) -> list:\r\n for i, c in enumerate(l):\r\n l[i] = c + s\r\n return l\r\n\r\n\r\ndef generate_target_freq_column(target_sev_col: pd.DataFrame) -> pd.DataFrame:\r\n pos_str, neg_str = DefaultValues.pos_neg_class\r\n target_freq_col = pd.DataFrame(pos_str, index=target_sev_col.index, columns=['target_freq'])\r\n idx = target_sev_col == 0\r\n target_freq_col[idx.values] = neg_str\r\n\r\n\r\ndef check_fn(fn: str):\r\n # pre-process of filename fn\r\n if os.path.isfile(fn):\r\n abs_fn = os.path.abspath(fn)\r\n abs_dn = os.path.dirname(abs_fn)\r\n else:\r\n raise ValueError('PyBox cannot find the file with fn = :' + fn)\r\n return abs_fn, abs_dn\r\n\r\n\r\ndef compare_str_array_with_str_scale(str_array, str_scale):\r\n for i, c in enumerate(str_array):\r\n if c == str_scale:\r\n return i\r\n\r\n\r\ndef is_tree_model(model):\r\n if type(model) is dict and \"trees\" in model or \\\r\n safe_isinstance(model,\r\n [\"sklearn.ensemble.RandomForestRegressor\", \"sklearn.ensemble.forest.RandomForestRegressor\"]) \\\r\n or safe_isinstance(model, [\"sklearn.ensemble.IsolationForest\", \"sklearn.ensemble.iforest.IsolationForest\"]) \\\r\n or safe_isinstance(model, \"skopt.learning.forest.RandomForestRegressor\") \\\r\n or safe_isinstance(model,\r\n [\"sklearn.ensemble.ExtraTreesRegressor\", \"sklearn.ensemble.forest.ExtraTreesRegressor\"]) \\\r\n or safe_isinstance(model, \"skopt.learning.forest.ExtraTreesRegressor\") \\\r\n or safe_isinstance(model, [\"sklearn.tree.DecisionTreeRegressor\", \"sklearn.tree.tree.DecisionTreeRegressor\"]) \\\r\n or safe_isinstance(model,\r\n [\"sklearn.tree.DecisionTreeClassifier\", \"sklearn.tree.tree.DecisionTreeClassifier\"]) \\\r\n or safe_isinstance(model, [\"sklearn.ensemble.RandomForestClassifier\",\r\n \"sklearn.ensemble.forest.RandomForestClassifier\"]) \\\r\n or safe_isinstance(model, [\"sklearn.ensemble.ExtraTreesClassifier\",\r\n \"sklearn.ensemble.forest.ExtraTreesClassifier\"]) \\\r\n or safe_isinstance(model, [\"sklearn.ensemble.GradientBoostingRegressor\",\r\n \"sklearn.ensemble.gradient_boosting.GradientBoostingRegressor\"]) \\\r\n or safe_isinstance(model, [\"sklearn.ensemble.GradientBoostingClassifier\",\r\n \"sklearn.ensemble.gradient_boosting.GradientBoostingClassifier\"]) \\\r\n or safe_isinstance(model, \"xgboost.core.Booster\") \\\r\n or safe_isinstance(model, \"xgboost.sklearn.XGBClassifier\") \\\r\n or safe_isinstance(model, \"xgboost.sklearn.XGBRegressor\") \\\r\n or safe_isinstance(model, \"xgboost.sklearn.XGBRanker\") \\\r\n or safe_isinstance(model, \"lightgbm.basic.Booster\") \\\r\n or safe_isinstance(model, \"lightgbm.sklearn.LGBMRegressor\") \\\r\n or safe_isinstance(model, \"lightgbm.sklearn.LGBMRanker\") \\\r\n or safe_isinstance(model, \"lightgbm.sklearn.LGBMClassifier\") \\\r\n or safe_isinstance(model, \"catboost.core.CatBoostRegressor\") \\\r\n or safe_isinstance(model, \"catboost.core.CatBoostClassifier\") \\\r\n or safe_isinstance(model, \"catboost.core.CatBoost\") \\\r\n or safe_isinstance(model, \"imblearn.ensemble._forest.BalancedRandomForestClassifier\"):\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef check_empty(d, errstr ='the input is empty'):\r\n if d is None:\r\n raise ValueError(errstr)\r\n\r\n# binning function\r\ndef bin_me(act, pred, n_bins):\r\n \"bin values in arrays act and pred into (n_bins+1) bins and return aggregated values in a data frame\"\r\n\r\n n = act.size\r\n # combine actual and predicted values in one data frame\r\n xx = pd.DataFrame(act, columns=['act'])\r\n xx['pred'] = pred\r\n # sort by prediction\r\n xx = xx.sort_values(by='pred')\r\n h = np.floor(n / n_bins) # size of each bin\r\n agg_table = pd.DataFrame(data={'act': np.zeros(n_bins + 1), 'pred': np.zeros(n_bins + 1)})\r\n\r\n for i in range(1, n_bins + 1):\r\n # caveat: range(1,n) delivers 1..(n-1)\r\n i_from = int((i - 1) * h)\r\n i_to = int(i * h - 1)\r\n current_values = xx.iloc[i_from:i_to]\r\n m1 = np.mean(current_values.act)\r\n m2 = np.mean(current_values.pred)\r\n agg_table.act[i - 1] = m1\r\n agg_table.pred[i - 1] = m2\r\n\r\n # remaining data\r\n i_from = int(n_bins * h)\r\n i_to = n\r\n tail = xx.iloc[i_from:i_to]\r\n\r\n m1 = np.mean(tail.act)\r\n m2 = np.mean(tail.pred)\r\n agg_table.act[n_bins] = m1\r\n agg_table.pred[n_bins] = m2\r\n\r\n # if remaining data empty one gets a NA row at the end => remove that\r\n agg_table = agg_table.dropna()\r\n\r\n return agg_table\r\n\r\n#### unused\r\n\r\n\r\n# class TargetVecFreq(TVH):\r\n#\r\n# def __init__(self, df: pd.DataFrame, conf: Config):\r\n# y_freq = df[conf.target_freq]\r\n# TVH.__init__(self, y_freq, conf)\r\n\r\n\r\n# class TargetVecSev(TVH):\r\n#\r\n# def __init__(self, df: pd.DataFrame, conf: Config):\r\n# y_sev = df[conf.target_sev]\r\n# TVH.__init__(self, y_sev, conf)\r\n\r\n\r\n# def fm_freq2sev(fm_freq: FreqSevTvhAbt, y_freq: TargetVecFreq):\r\n# fm_sev = FreqSevTvhAbt(fm_freq.df[y_freq.df == 'Y'], fm_freq.conf)\r\n# fm_sev.nomi_encode()\r\n# return fm_sev\r\n\r\n\r\n# def nomi_encode(fm: FreqSevTvhAbt, conf):\r\n# if conf.nomi_encoding == 'Label':\r\n# return label_encode_with_unknowns(fm, conf)\r\n# elif conf.nomi_encoding == 'Ordinal':\r\n# return ordinal_encode_with_unknown(fm, conf)\r\n# elif conf.nomi_encoding == 'OneHot':\r\n# return onehot_encode_with_unknown(fm, conf)\r\n\r\n\r\n# def label_encode_with_unknowns(fm: FreqSevTvhAbt, conf: Config):\r\n# fm_encoder = [LabelEncoder()] * len(conf.predictors_nomi)\r\n# for i in range(len(conf.predictors_nomi)):\r\n# c = conf.predictors_nomi[i]\r\n# enc = LabelEncoder()\r\n# enc.fit(fm.get_fm_freq_train()[c])\r\n# cll = enc.classes_.tolist()\r\n# cll.append(conf.nomi_others)\r\n# enc.classes_ = cll\r\n#\r\n# fm.train[c] = enc.transform(fm.train[c])\r\n#\r\n# def f(s):\r\n# if s not in enc.classes_:\r\n# return conf.nomi_others\r\n# else:\r\n# return s\r\n#\r\n# fm.val[c] = fm.val[c].map(f)\r\n# fm.test[c] = fm.test[c].map(f)\r\n#\r\n# fm.val[c] = enc.transform(fm.val[c])\r\n# fm.test[c] = enc.transform(fm.test[c])\r\n# fm_encoder[i] = enc\r\n# fm.setEncoder(fm_encoder)\r\n# return fm\r\n\r\n# def ordinal_encode_with_unknown(fm: FeatureMatrixFreqSev, conf: Config):\r\n# nomi_encoder = OrdinalEncoder() # TODO: adding further encoders\r\n# nomi_encoder.fit(fm.train[conf.predictors_nomi]) # fit on training data\r\n#\r\n# metr_tmp = fm.train[conf.predictors_metr]\r\n# fm.train = pd.DataFrame(nomi_encoder.transform(fm.train[conf.predictors_nomi]),\r\n# columns=conf.predictors_nomi,\r\n# index=fm.train.index)\r\n# fm.train[conf.predictors_metr] = metr_tmp\r\n#\r\n# metr_tmp = fm.val[conf.predictors_metr]\r\n# fm.val = pd.DataFrame(nomi_encoder.transform(fm.val[conf.predictors_nomi]),\r\n# columns=conf.predictors_nomi,\r\n# index=fm.val.index)\r\n# fm.val[conf.predictors_metr] = metr_tmp\r\n#\r\n# metr_tmp = fm.val[conf.predictors_metr]\r\n# fm.test = pd.DataFrame(nomi_encoder.transform(fm.test[conf.predictors_nomi]),\r\n# columns=conf.predictors_nomi,\r\n# index=fm.test.index)\r\n# fm.test[conf.predictors_metr] = metr_tmp\r\n#\r\n# return fm, nomi_encoder\r\n\r\n\r\n# def onehot_encode_with_unknown(fm: FreqSevTvhAbt, conf: Config):\r\n# fm_encoder = [OneHotEncoder()]\r\n# return fm, fm_encoder\r\n","sub_path":"MR/PyBox/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"637166361","text":"\n#\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\#\n\nfrom copy import deepcopy\nfrom Gaudi.Configuration import *\nfrom GaudiConfUtils.ConfigurableGenerators import CombineParticles\nfrom PhysSelPython.Wrappers import Selection, MergedSelection\nfrom Beauty2Charm_LoKiCuts import LoKiCuts\nfrom Beauty2Charm_Utils import *\n#from Configurables import SubstitutePID\n\n#\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\#\n\nclass Bc2DDBuilder(object):\n '''Makes all Bc->DD decays for the Beauty2Charm module.'''\n\n def __init__(self,d,dst,config):\n \n self.config = config\n self.d = d\n self.dst = dst\n \n self.lines = []\n\n self.d0modes = { }\n self.dpmodes = { }\n self.dstarpmodes = { }\n self.dstar0modes = { }\n\n # Build the merged D selections\n self._createD0Modes()\n self._createDpModes()\n self._createDstarPlusModes()\n self._createDstar0Modes()\n\n # Define the Bc lines\n self._makeBc2DD0()\n self._makeBc2DstarD0()\n self._makeBc2DstarDstar0()\n\n def _buildSel(self,dmodes,name,map):\n if 1 == len(dmodes) :\n map[name] = dmodes[0]\n else :\n map[name] = MergedSelection(\"BC2DD-\"+name+\"-Beauty2Charm\",RequiredSelections=dmodes)\n\n def _createD0Modes(self):\n\n # ( D->hh )\n name = \"D02HH\"\n #dmodes = self.d.hh\n dmodes = self.d.hh_pid\n # With Upstream tracks as well\n #dmodes += self.d.hh_up\n self._buildSel(dmodes,name,self.d0modes)\n\n ## # ( D->hhhh )\n ## name = \"D02HHHH\"\n ## #dmodes = self.d.hhhh\n ## dmodes = self.d.hhhh_pid\n ## # With Upstream tracks as well\n ## #dmodes += self.d.hhhh_up\n ## self._buildSel(dmodes,name,self.d0modes)\n\n # ( D->khhh )\n name = \"D02KHHH\"\n #dmodes = self.d.k3h\n dmodes = self.d.k3h_pid\n self._buildSel(dmodes,name,self.d0modes)\n\n # ( D->Kshh )\n name = \"D02KSHH\"\n #dmodes = self.d.kshh_ll + self.d.kshh_dd\n dmodes = self.d.kshh_ll_pid + self.d.kshh_dd_pid\n # With Upstream tracks as well\n #dmodes += self.d.kshh_ll_up + self.d.kshh_dd_up\n self._buildSel(dmodes,name,self.d0modes)\n\n # ( D->hhpi0 )\n name = \"D02HHPI0\"\n #dmodes = self.d.pi0hh_merged + self.d.pi0hh_resolved\n dmodes = self.d.pi0hh_merged_pid + self.d.pi0hh_resolved_pid\n # With Upstream tracks as well\n #dmodes += self.d.pi0hh_merged_up + self.d.pi0hh_resolved_up\n self._buildSel(dmodes,name,self.d0modes)\n\n ## # ( D->hhhhpi0 )\n ## name = \"D02HHHHPI0\"\n ## dmodes = self.d.pi0hhhh_merged + self.d.pi0hhhh_resolved\n ## # With Upstream tracks as well\n ## #dmodes += self.d.pi0hhhh_merged_up + self.d.pi0hhhh_resolved_up\n ## self._buildSel(dmodes,name,self.d0modes)\n \n # ( D0->Kshhpi0 )\n name = \"D02KSHHPI0\"\n #dmodes = self.d.kspi0hh_ll_merged + self.d.kspi0hh_ll_resolved\n #dmodes += self.d.kspi0hh_dd_merged + self.d.kspi0hh_dd_resolved\n dmodes = self.d.kspi0hh_ll_merged_pid + self.d.kspi0hh_ll_resolved_pid\n dmodes += self.d.kspi0hh_dd_merged_pid + self.d.kspi0hh_dd_resolved_pid\n # With Upstream\n #dmodes += self.d.kspi0hh_ll_merged_up + self.d.kspi0hh_ll_resolved_up\n #dmodes += self.d.kspi0hh_dd_merged_up + self.d.kspi0hh_dd_resolved_up\n self._buildSel(dmodes,name,self.d0modes)\n\n def _createDpModes(self):\n \n ## # ( D->hhh )\n ## name = \"D2HHH\"\n ## dmodes = self.d.hhh\n ## #dmodes = self.d.hhh_pid\n ## # With Upstream tracks as well\n ## #dmodes += self.d.hhh_up\n ## self._buildSel(dmodes,name,self.dpmodes)\n\n # ( D->khh )\n name = \"D2KHH\"\n #dmodes = self.d.k2h\n dmodes = self.d.k2h_pid\n self._buildSel(dmodes,name,self.dpmodes)\n\n # ( D->Ksh )\n name = \"D2KSH\"\n #dmodes = self.d.ksh_ll + self.d.ksh_dd\n dmodes = self.d.ksh_ll_pid + self.d.ksh_dd_pid\n # With Upstream tracks as well\n #dmodes += self.d.ksh_ll_up + self.d.ksh_dd_up\n self._buildSel(dmodes,name,self.dpmodes)\n\n # ( D->Kshhh )\n name = \"D2KSHHH\"\n #dmodes = self.d.kshhh_ll + self.d.kshhh_dd\n dmodes = self.d.kshhh_ll_pid + self.d.kshhh_dd_pid\n # With Upstream tracks as well\n #dmodes += self.d.kshhh_ll_up + self.d.kshhh_dd_up\n self._buildSel(dmodes,name,self.dpmodes)\n\n ## # ( D->KsKhh )\n ## name = \"D2KSKHH\"\n ## dmodes = self.d.kskhh_ll_pid + self.d.kskhh_dd_pid\n ## self._buildSel(dmodes,name,self.dpmodes)\n\n ## # ( D->hhhpi0 )\n ## name = \"D2HHHPI0\"\n ## #dmodes = self.d.pi0hhh_merged + self.d.pi0hhh_resolved\n ## dmodes = self.d.pi0hhh_merged_pid + self.d.pi0hhh_resolved_pid\n ## # With Upstream tracks as well\n ## #dmodes += self.d.pi0hhh_merged_up + self.d.pi0hhh_resolved_up\n ## self._buildSel(dmodes,name,self.dpmodes)\n\n # ( D->Khhpi0 )\n name = \"D2KHHPI0\"\n dmodes = self.d.pi0khh_merged_pid + self.d.pi0khh_resolved_pid \n self._buildSel(dmodes,name,self.dpmodes)\n\n # ( D->Kshpi0 )\n name = \"D2KSHPI0\"\n dmodes = self.d.kspi0h_ll_merged + self.d.kspi0h_ll_resolved\n dmodes += self.d.kspi0h_dd_merged + self.d.kspi0h_dd_resolved\n # With Upstream\n #dmodes += self.d.kspi0h_ll_merged_up + self.d.kspi0h_ll_resolved_up\n #dmodes += self.d.kspi0h_dd_merged_up + self.d.kspi0h_dd_resolved_up\n self._buildSel(dmodes,name,self.dpmodes)\n\n # ( D -> K*+hh )\n name = \"D2KstHH\"\n dmodes = self.d.kstarhh\n self._buildSel(dmodes,name,self.dpmodes)\n\n # ( D -> K*+K*0 )\n name = \"D2KstKst0\"\n dmodes = self.d.kstarkstar0\n self._buildSel(dmodes,name,self.dpmodes)\n\n # ( D -> K*+Ks )\n name = \"D2KstKS\"\n dmodes = self.d.kstarks_ll + self.d.kstarks_dd\n self._buildSel(dmodes,name,self.dpmodes)\n \n def _createDstarPlusModes(self):\n\n # D*+ modes ( D0 -> hh )\n name = \"Dst2D0PID02HH\"\n #dmodes = self.dst.d0pi\n dmodes = self.dst.d0pi_pid\n #dmodes += self.dst.d0pi_dup + self.dst.d0pi_hup + self.dst.d0pi_dup_hup\n self._buildSel(dmodes,name,self.dstarpmodes)\n\n ## # D*+ modes ( D0 -> hhhh )\n ## name = \"Dst2D0PID02HHHH\"\n ## #dmodes = self.dst.d0pi_hhhh\n ## dmodes = self.dst.d0pi_hhhh_pid\n ## #dmodes += self.dst.d0pi_hhhh_dup + self.dst.d0pi_hhhh_hup + self.dst.d0pi_hhhh_dup_hup\n ## self._buildSel(dmodes,name,self.dstarpmodes)\n\n # D*+ modes ( D0 -> Khhh )\n name = \"Dst2D0PID02KHHH\"\n dmodes = self.dst.d0pi_k3h_pid\n self._buildSel(dmodes,name,self.dstarpmodes)\n\n # D*+ modes ( D0 -> Kshh )\n name = \"Dst2D0PID02KSHH\"\n #dmodes = self.dst.d0pi_kshh_ll + self.dst.d0pi_kshh_dd\n dmodes = self.dst.d0pi_kshh_ll_pid + self.dst.d0pi_kshh_dd_pid\n #dmodes += self.dst.d0pi_kshh_ll_dup + self.dst.d0pi_kshh_dd_dup\n #dmodes += self.dst.d0pi_kshh_ll_hup + self.dst.d0pi_kshh_dd_hup\n self._buildSel(dmodes,name,self.dstarpmodes)\n\n # D*+ modes ( D0 -> KsPi0hh )\n name = \"Dst2D0PID02KSPI0HH\"\n #dmodes = self.dst.d0pi_kspi0hh_ll_merged + self.dst.d0pi_kspi0hh_dd_merged\n #dmodes += self.dst.d0pi_kspi0hh_ll_resolved + self.dst.d0pi_kspi0hh_dd_resolved\n dmodes = self.dst.d0pi_kspi0hh_ll_merged_pid + self.dst.d0pi_kspi0hh_dd_merged_pid\n dmodes += self.dst.d0pi_kspi0hh_ll_resolved_pid + self.dst.d0pi_kspi0hh_dd_resolved_pid\n #dmodes += self.dst.d0pi_kspi0hh_ll_merged_dup + self.dst.d0pi_kspi0hh_dd_merged_dup\n #dmodes += self.dst.d0pi_kspi0hh_ll_resolved_dup + self.dst.d0pi_kspi0hh_dd_resolved_dup\n #dmodes += self.dst.d0pi_kspi0hh_ll_merged_hup + self.dst.d0pi_kspi0hh_dd_merged_hup\n #dmodes += self.dst.d0pi_kspi0hh_ll_resolved_hup + self.dst.d0pi_kspi0hh_dd_resolved_hup\n self._buildSel(dmodes,name,self.dstarpmodes)\n\n ## # Ds*+ pi0 modes ( Ds+ -> hhh )\n ## name = \"Dst2DPI0D2HHH\"\n ## #dmodes = self.dst.dpi0_merged + self.dst.dpi0_resolved\n ## dmodes = self.dst.dpi0_merged_pid + self.dst.dpi0_resolved_pid\n ## #dmodes += self.dst.dpi0_merged_dup + self.dst.dpi0_resolved_dup\n ## self._buildSel(dmodes,name,self.dstarpmodes)\n\n # Ds*+ pi0 modes ( Ds+ -> khh )\n name = \"Dst2DPI0D2KHH\"\n dmodes = self.dst.dpi0_khh_merged_pid + self.dst.dpi0_khh_resolved_pid\n self._buildSel(dmodes,name,self.dstarpmodes)\n \n # Ds*+ pi0 modes ( Ds+ -> Ksh )\n name = \"Dst2DPI0D2KSH\"\n dmodes = self.dst.dpi0_merged_ksh_ll + self.dst.dpi0_resolved_ksh_ll\n dmodes += self.dst.dpi0_merged_ksh_dd + self.dst.dpi0_resolved_ksh_dd\n #dmodes += self.dst.dpi0_merged_ksh_ll_dup + self.dst.dpi0_resolved_ksh_ll_dup\n #dmodes += self.dst.dpi0_merged_ksh_dd_dup + self.dst.dpi0_resolved_ksh_dd_dup\n self._buildSel(dmodes,name,self.dstarpmodes)\n\n # Ds*+ pi0 modes ( Ds+ -> Kshhh )\n name = \"Dst2DPI0D2KSHHH\"\n #dmodes = self.dst.dpi0_merged_kshhh_ll + self.dst.dpi0_resolved_kshhh_ll\n #dmodes += self.dst.dpi0_merged_kshhh_dd + self.dst.dpi0_resolved_kshhh_dd\n dmodes = self.dst.dpi0_merged_kshhh_ll_pid + self.dst.dpi0_resolved_kshhh_ll_pid\n dmodes += self.dst.dpi0_merged_kshhh_dd_pid + self.dst.dpi0_resolved_kshhh_dd_pid\n #dmodes += self.dst.dpi0_merged_kshhh_ll_dup + self.dst.dpi0_resolved_kshhh_ll_dup\n #dmodes += self.dst.dpi0_merged_kshhh_dd_dup + self.dst.dpi0_resolved_kshhh_dd_dup\n self._buildSel(dmodes,name,self.dstarpmodes)\n\n ## # Ds*+ pi0 modes ( Ds+ -> KsKhh )\n ## name = \"Dst2DPI0D2KSHHH\"\n ## dmodes = self.dst.dpi0_merged_kskhh_ll_pid + self.dst.dpi0_resolved_kskhh_ll_pid\n ## dmodes += self.dst.dpi0_merged_kskhh_dd_pid + self.dst.dpi0_resolved_kskhh_dd_pid\n ## self._buildSel(dmodes,name,self.dstarpmodes)\n\n # Ds*+ pi0 modes ( Ds+ -> KsPi0h )\n name = \"Dst2DPI0D2KSPI0H\"\n dmodes = self.dst.dpi0_merged_kspi0h_ll + self.dst.dpi0_merged_kspi0h_dd\n dmodes += self.dst.dpi0_resolved_kspi0h_ll + self.dst.dpi0_resolved_kspi0h_dd\n #dmodes += self.dst.dpi0_merged_kspi0h_ll_dup + self.dst.dpi0_merged_kspi0h_dd_dup\n #dmodes += self.dst.dpi0_resolved_kspi0h_ll_dup + self.dst.dpi0_resolved_kspi0h_dd_dup\n self._buildSel(dmodes,name,self.dstarpmodes)\n\n ## # Ds*+ gamma modes ( Ds+ -> hhh )\n ## name = \"DStar2DGammaD2HHH\"\n ## #dmodes = self.dst.dgamma_hhh\n ## dmodes = self.dst.dgamma_hhh_pid\n ## #dmodes += self.dst.dgamma_hhh_dup\n ## self._buildSel(dmodes,name,self.dstarpmodes)\n\n # Ds*+ gamma modes ( Ds+ -> Khh )\n name = \"Dst2DGammaD2KHH\"\n dmodes = self.dst.dgamma_khh_pid\n self._buildSel(dmodes,name,self.dstarpmodes)\n\n # Ds*+ gamma modes ( Ds+ -> Ksh )\n name = \"Dst2DGammaD2KSH\"\n dmodes = self.dst.dgamma_ksh_ll + self.dst.dgamma_ksh_dd\n #dmodes += self.dst.dgamma_ksh_ll_dup + self.dst.dgamma_ksh_dd_dup\n self._buildSel(dmodes,name,self.dstarpmodes)\n\n # Ds*+ gamma modes ( Ds+ -> Kshhh )\n name = \"Dst2DGammaD2KSHHH\"\n #dmodes = self.dst.dgamma_kshhh_ll + self.dst.dgamma_kshhh_dd\n dmodes = self.dst.dgamma_kshhh_ll_pid + self.dst.dgamma_kshhh_dd_pid\n #dmodes = self.dst.dgamma_kskhh_ll_pid + self.dst.dgamma_kskhh_dd_pid\n #dmodes += self.dst.dgamma_kshhh_ll_dup + self.dst.dgamma_kshhh_dd_dup\n self._buildSel(dmodes,name,self.dstarpmodes)\n\n # Ds*+ gamma modes ( Ds+ -> KsPi0h )\n name = \"Dst2DGammaD2KSPI0H\"\n dmodes = self.dst.dgamma_kspi0h_ll + self.dst.dgamma_kspi0h_dd\n #dmodes += self.dst.dgamma_kspi0h_ll_dup + self.dst.dgamma_kspi0h_dd_dup\n self._buildSel(dmodes,name,self.dstarpmodes)\n\n def _createDstar0Modes(self):\n\n # D0* pi0 ( D0 -> hh )\n name = \"Dst02D0PI0D02HH\"\n #dmodes = self.dst.d0pi0_merged + self.dst.d0pi0_resolved\n dmodes = self.dst.d0pi0_merged_pid + self.dst.d0pi0_resolved_pid\n #dmodes += self.dst.d0pi0_merged_dup + self.dst.d0pi0_resolved_dup\n self._buildSel(dmodes,name,self.dstar0modes)\n\n ## # D0* pi0 ( D0 -> hhhh )\n ## name = \"Dst02D0PI0D02HHHH\"\n ## #dmodes = self.dst.d0pi0_hhhh_merged + self.dst.d0pi0_hhhh_resolved\n ## dmodes = self.dst.d0pi0_hhhh_merged_pid + self.dst.d0pi0_hhhh_resolved_pid\n ## #dmodes += self.dst.d0pi0_hhhh_merged_dup + self.dst.d0pi0_hhhh_resolved_dup\n ## self._buildSel(dmodes,name,self.dstar0modes)\n\n # D0* pi0 ( D0 -> Khhh )\n name = \"Dst02D0PI0D02KHHH\"\n dmodes = self.dst.d0pi0_k3h_merged_pid + self.dst.d0pi0_k3h_resolved_pid\n self._buildSel(dmodes,name,self.dstar0modes)\n\n # D0* pi0 ( D0 -> Kshh )\n name = \"Dst02D0PI0D02KSHH\"\n #dmodes = self.dst.d0pi0_kshh_ll + self.dst.d0pi0_kshh_dd\n dmodes = self.dst.d0pi0_kshh_ll_pid + self.dst.d0pi0_kshh_dd_pid\n #dmodes += self.dst.d0pi0_kshh_ll_dup + self.dst.d0pi0_kshh_dd_dup\n self._buildSel(dmodes,name,self.dstar0modes)\n\n # D0* gamma ( D0 -> hh )\n name = \"Dst02D0GammaD02HH\"\n dmodes = self.dst.d0gamma_hh_pid\n self._buildSel(dmodes,name,self.dstar0modes)\n\n # D0* gamma ( D0 -> khhh )\n name = \"Dst02D0GammaD02KHHH\"\n dmodes = self.dst.d0gamma_k3h_pid\n self._buildSel(dmodes,name,self.dstar0modes)\n\n # D0* gamma ( D0 -> Kshh )\n name = \"Dst02D0GammaD02KSHH\"\n #dmodes = self.dst.d0gamma_kshh_ll + self.dst.d0gamma_kshh_dd\n dmodes = self.dst.d0gamma_kshh_ll_pid + self.dst.d0gamma_kshh_dd_pid\n #dmodes += self.dst.d0gamma_kshh_ll_dup + self.dst.d0gamma_kshh_dd_dup\n self._buildSel(dmodes,name,self.dstar0modes)\n\n\n def _createLines(self,name,modes0,modes1,descr,prescale=1.0):\n\n # Loop over all combinations and build the lines\n for d0name,d0mode in modes0.iteritems():\n for d1name,d1mode in modes1.iteritems():\n tag = d0name + d1name\n #print \"'Stripping\" + name + tag + \"Beauty2CharmLine',\"\n decays = { name : descr }\n inputs = { name : [ d0mode, d1mode ] }\n bc2dd = makeB2XSels( decays, tag, inputs, self.config )\n self.lines.append( ProtoLine(bc2dd,prescale) )\n\n \n def _makeBc2DD0(self):\n '''Makes Bc+ -> D+ D0 + c.c.'''\n self._createLines( 'Bc2DD0', self.dpmodes, self.d0modes, \n [\"B_c+ -> D+ D0\",\"B_c- -> D- D0\"] )\n \n\n def _makeBc2DstarD0(self):\n '''Makes Bc+ -> D*+ D0 + c.c.'''\n self._createLines( \"Bc2DstD0\", self.dstarpmodes, self.d0modes,\n [\"B_c+ -> D*(2010)+ D0\",\n \"B_c- -> D*(2010)- D0\",\n \"B_c+ -> D*_s+ D0\",\n \"B_c- -> D*_s- D0\"] )\n\n def _makeBc2DstarDstar0(self):\n '''Makes Bc+ -> D*+ D*0 + c.c.'''\n self._createLines( \"Bc2DstDst0\", self.dstarpmodes, self.dstar0modes,\n [\"B_c+ -> D*(2010)+ D*(2007)0\",\n \"B_c- -> D*(2010)- D*(2007)0\",\n \"B_c+ -> D*_s+ D*(2007)0\",\n \"B_c- -> D*_s- D*(2007)0\"] )\n","sub_path":"DaVinciDev_v38r1p1/InstallArea/x86_64-slc6-gcc49-opt/python/StrippingArchive/Stripping23r1/StrippingB2OC/Beauty2Charm_Bc2DDBuilder.py","file_name":"Beauty2Charm_Bc2DDBuilder.py","file_ext":"py","file_size_in_byte":15642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"362519857","text":"# Copyright 2016 Comcast Inc.\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\nimport sys\n\nfrom neutronclient.common import exceptions\nfrom neutronclient.neutron.v2_0.qos import dscp_marking_rule as dscp_rule\nfrom neutronclient.tests.unit import test_cli20\n\n\nclass CLITestV20QoSDscpMarkingRuleJSON(test_cli20.CLITestV20Base):\n\n non_admin_status_resources = ['dscp_marking_rule']\n\n def setUp(self):\n super(CLITestV20QoSDscpMarkingRuleJSON, self).setUp()\n self.dscp_res = 'dscp_marking_rule'\n self.dscp_cmd_res = 'qos_dscp_marking_rule'\n self.dscp_ress = self.dscp_res + 's'\n self.dscp_cmd_ress = self.dscp_cmd_res + 's'\n\n def test_create_dscp_marking_rule_with_dscp_mark(self):\n cmd = dscp_rule.CreateQoSDscpMarkingRule(test_cli20.MyApp(sys.stdout),\n None)\n my_id = 'my-id'\n policy_id = 'policy_id'\n position_names = ['dscp_mark']\n valid_dscp_marks = ['0', '56']\n invalid_dscp_marks = ['-1', '19', '42', '44', '57', '58']\n for dscp_mark in valid_dscp_marks:\n args = ['--dscp-mark', dscp_mark, policy_id]\n position_values = [dscp_mark]\n self._test_create_resource(self.dscp_res, cmd, '', my_id, args,\n position_names, position_values,\n cmd_resource=self.dscp_cmd_res,\n parent_id=policy_id)\n for dscp_mark in invalid_dscp_marks:\n args = ['--dscp-mark', dscp_mark, policy_id]\n position_values = [dscp_mark]\n self._test_create_resource(\n self.dscp_res, cmd, '', my_id, args,\n position_names, position_values,\n cmd_resource=self.dscp_cmd_res,\n parent_id=policy_id,\n no_api_call=True,\n expected_exception=exceptions.CommandError)\n\n def test_update_dscp_marking_rule_with_dscp_mark(self):\n cmd = dscp_rule.UpdateQoSDscpMarkingRule(test_cli20.MyApp(sys.stdout),\n None)\n my_id = 'my-id'\n dscp_mark = '56'\n policy_id = 'policy_id'\n args = ['--dscp-mark', dscp_mark,\n my_id, policy_id]\n self._test_update_resource(self.dscp_res, cmd, my_id, args,\n {'dscp_mark': dscp_mark},\n cmd_resource=self.dscp_cmd_res,\n parent_id=policy_id)\n\n def test_delete_dscp_marking_rule(self):\n cmd = dscp_rule.DeleteQoSDscpMarkingRule(test_cli20.MyApp(sys.stdout),\n None)\n my_id = 'my-id'\n policy_id = 'policy_id'\n args = [my_id, policy_id]\n self._test_delete_resource(self.dscp_res, cmd, my_id, args,\n cmd_resource=self.dscp_cmd_res,\n parent_id=policy_id)\n\n def test_show_dscp_marking_rule(self):\n cmd = dscp_rule.ShowQoSDscpMarkingRule(test_cli20.MyApp(sys.stdout),\n None)\n policy_id = 'policy_id'\n args = [self.test_id, policy_id]\n self._test_show_resource(self.dscp_res, cmd, self.test_id, args,\n [], cmd_resource=self.dscp_cmd_res,\n parent_id=policy_id)\n","sub_path":"neutronclient/tests/unit/qos/test_cli20_dscp_marking_rule.py","file_name":"test_cli20_dscp_marking_rule.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"502481627","text":"from config.Configs import ModelConfig\nfrom model.vgg16_standard import get_vgg16_standard_rpn, get_vgg16_standard_classifier, vgg16_base\nfrom model.vgg16 import get_vgg16_rpn, get_vgg16_classifier\nfrom model.vgg16 import vgg16_base as vg16_base\nfrom model.resnet50 import resnet50_base, get_resnet50_rpn, get_resnet50_classifier\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.layers import Flatten, Dense, Input, Conv2D, MaxPooling2D\nimport tensorflow as tf\nimport os\n\n\ndef init_session(run_on_laptop=False, use_bfc=False):\n if run_on_laptop:\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n os.environ['CUDA_VISIBLE_DEVICES'] = '1'\n config = tf.ConfigProto()\n if use_bfc:\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n K.set_session(sess)\n\n\ndef get_classifier_model(model_name):\n \"\"\"\n Return the classifier model\n :param model_name: ModelConfig object\n :return: classifier model\n \"\"\"\n models = model_name.value\n input_dim = models.input_dim\n num_roi = models.classifier_train_batch\n inputs = Input(shape=(input_dim, input_dim, 3))\n roi_input = Input(shape=(num_roi, 4))\n\n if model_name == ModelConfig.ResNet50:\n base_f = resnet50_base\n classifier_f = get_resnet50_classifier\n elif model_name == ModelConfig.VGG16_standard:\n base_f = vgg16_base\n classifier_f = get_vgg16_standard_classifier\n elif model_name == ModelConfig.VGG16:\n base_f = vg16_base\n classifier_f = get_vgg16_classifier\n else:\n raise RuntimeError(\"No model selected.\")\n base_layers = base_f(inputs)\n\n classifier = classifier_f(base_layers, roi_input, num_roi)\n model_classifier = Model([inputs, roi_input], classifier)\n\n return model_classifier\n\n\ndef get_rpn_model(model_name):\n \"\"\"\n Return the rpn model\n :param model_name: ModelConfig object\n :return: rpn model\n \"\"\"\n models = model_name.value\n input_dim = models.input_dim\n inputs = Input(shape=(input_dim, input_dim, 3))\n num_anchors = len(models.anchor_box_scales) * len(models.anchor_box_ratios)\n\n if model_name == ModelConfig.ResNet50:\n base_f = resnet50_base\n rpn_f = get_resnet50_rpn\n elif model_name == ModelConfig.VGG16_standard:\n base_f = vgg16_base\n rpn_f = get_vgg16_standard_rpn\n elif model_name == ModelConfig.VGG16:\n base_f = vg16_base\n rpn_f = get_vgg16_rpn\n else:\n raise RuntimeError(\"No model selected.\")\n base_layers = base_f(inputs)\n\n rpn = rpn_f(base_layers, num_anchors)\n model_rpn = Model(inputs, rpn[:2])\n\n return model_rpn\n\n\ndef get_predict_model(model_name):\n \"\"\"\n Return the models for prediction\n :param model_name: ModelConfig object\n :return: rpn model, classifier model\n \"\"\"\n models = model_name.value\n input_dim = models.input_dim\n num_roi = models.classifier_train_batch\n feature_map_filters = models.feature_map_filters\n num_anchors = len(models.anchor_box_scales) * len(models.anchor_box_ratios)\n\n inputs = Input(shape=(input_dim, input_dim, 3))\n roi_input = Input(shape=(num_roi, 4))\n feature_map_input = Input(shape=(None, None, feature_map_filters))\n\n if model_name == ModelConfig.VGG16_standard:\n base_f = vgg16_base\n rpn_f = get_vgg16_standard_rpn\n classifier_f = get_vgg16_standard_classifier\n elif model_name == ModelConfig.ResNet50:\n base_f = resnet50_base\n rpn_f = get_resnet50_rpn\n classifier_f = get_resnet50_classifier\n elif model_name == ModelConfig.VGG16:\n base_f = vg16_base\n rpn_f = get_vgg16_rpn\n classifier_f = get_vgg16_classifier\n else:\n raise RuntimeError(\"No model selected.\")\n\n base_layers = base_f(inputs)\n\n rpn = rpn_f(base_layers, num_anchors)\n model_rpn = Model(inputs, rpn)\n\n classifier = classifier_f(feature_map_input, roi_input, num_roi)\n model_classifier_only = Model([feature_map_input, roi_input], classifier)\n\n return model_rpn, model_classifier_only\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"654534363","text":"from typing import List\n\n\nclass Solution:\n def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:\n S = sum(x for x in A if x % 2 == 0)\n ans = []\n\n for x, k in queries:\n if A[k] % 2 == 0: S -= A[k]\n A[k] += x\n if A[k] % 2 == 0: S += A[k]\n ans.append(S)\n\n return ans\n\n\n\nA = [1,2,3,4]\nqueries = [[1,0],[-3,1],[-4,0],[2,3]]\nres = Solution().sumEvenAfterQueries(A, queries)\nprint(res)","sub_path":"array/0985_sum_of_even_numbers_after_queries/0985_sum_of_even_numbers_after_queries.py","file_name":"0985_sum_of_even_numbers_after_queries.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"456539198","text":"my_list=[1,2,3,4,5,6,7,8,9]\nfor item in my_list:\n print(item)\n\nfor item in range(0,10):\n print(item)\n\n\nevens=[x for x in range(0,21,2)]\nprint(evens)\n\ns='Something'\nfor letter in list(enumerate(s)):\n print(list(letter))\n\n\n# For loops in tuples\ntuples=[(1,2),(2,3),(3,4)]\nfor (item1,item2) in tuples:\n print(item1,item2)\n\n# List zipping \n\n\nmy_list=[1,2,3,4,5,6,7,8,9]\nmy_list2=[1,2,3,4,5,6,7,8,9]\nfor item in zip(my_list,my_list2):\n print(item)\n","sub_path":"Chapter2/For_Loop_C2.py","file_name":"For_Loop_C2.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"649698712","text":"lst=list()\nn=int(input(\"Enter the number of elements you want in a list:\"))\nprint(\"Enter the numbers:\")\nfor i in range(n):\n numbers=int(input())\n lst.append(numbers)\n\ndef max(lst):\n max=0\n for i in lst:\n if i > max:\n max=i\n\n return max\nprint(\"The greatest number among the list is:\",max(lst))\n\ndef min(lst):\n for i in lst:\n min=i\n if i>>>>>')\n for s in rs1:\n print(s)\n print('随机近义词替换>>>>>>')\n for s in rs2:\n print(s)\n print('随机近义字替换>>>>>>')\n for s in rs3:\n print(s)\n\n print('随机字删除>>>>>>')\n for s in rs4:\n print(s)\n\n\n# if __name__ == '__main__':\n # quick_start()\n # test_ner()\n","sub_path":"nlpcda/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"331604942","text":"# Simple GPA Calculator ran through terminal\n# Made by: Rutvik Patel\n\ndebug = False\nscale = {\"CR\": 0, \"A+\": 4.0, \"A\": 4.0, \"A-\": 3.7, \"B+\": 3.3, \"B\": 3.0, \"B-\": 2.7, \"C+\": 2.3, \"C\": 2.0, \"C-\": 1.7, \"D+\": 1.3, \"D\": 1.0}\n\ntry:\n # get input\n num_classes = int(input(\"Number of classes taken: \"))\n grades = []\n weight = []\n for i in range(0, num_classes):\n user_in = input(\"Class grade and credit weight (separated by a space): \").split()\n grades.append(user_in[0])\n weight.append(float(user_in[1]))\n\n # calculate\n total_credits = 0\n for i in range(0, num_classes):\n total_credits += weight[i]\n if debug:\n print(\"The total credits taken are: \", total_credits)\n\n gpa = 0\n weighted_grades = 0\n for i in range(0, num_classes):\n weighted_grades += scale[grades[i]] * weight[i]\n if debug:\n print(\"Your weighted grades achieved is: \", weighted_grades)\n gpa = weighted_grades / total_credits\n # display answer\n print(\"Your GPA is: \", gpa)\nexcept ValueError:\n print(\"Please check your input and try again.\")","sub_path":"gpa-calculator.py","file_name":"gpa-calculator.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"7366822","text":"#!/usr/bin/env python3\n# ============================================================================\n# File: websitebuilder.py\n# Author: Erik Johannes Husom\n# Created: 2019-11-04\n# ----------------------------------------------------------------------------\n# Description:\n# Building a website from Markdown files with Python.\n# ============================================================================\nimport glob\nimport os\nimport sys\n\n\nclass WebsiteBuilder():\n \"\"\"Building a website from Markdown files.\n\n Directory structure:\n\n website/\n | _config.yml\n | _includes/\n | | footer.html\n | | head.html\n | | header.html\n | _layouts/\n | | default.html\n | _posts/\n | _sass/\n | | style.css\n\n\n Frontmatter of Markdown files:\n\n ---\n title: Page title\n author: John Doe\n layout: default\n ---\n\n\n Parameters\n ----------\n parameter : float\n Description.\n\n\n\n Attributes\n ----------\n attribute : float\n Description.\n\n array[float]\n Description.\n\n\n Notes\n -----\n\n \n References\n ----------\n\n\n Example\n -------\n >>>\n\n \"\"\"\n\n\n def __init__(self):\n\n\n # Register all necessary directories and files\n self.wd = os.path.dirname(os.path.realpath(__file__))\n\n self.config = '_config.yml'\n self.index = 'index.md'\n\n self.includes_dir = '_includes/'\n self.layout_dir = '_layouts/'\n self.posts_dir = '_posts/'\n self.sass_dir = '_sass/'\n self.site_dir = '_site/'\n\n self.dirs = []\n self.dirs.append(self.includes_dir)\n self.dirs.append(self.layout_dir)\n self.dirs.append(self.posts_dir)\n self.dirs.append(self.sass_dir)\n self.dirs.append(self.site_dir)\n\n # Create necessary directories if not already present\n for dir_ in self.dirs:\n self.create_dir(directory=dir_)\n\n # Find Markdown files in top directory\n # file_list = os.listdir(self.wd)\n # print(file_list)\n\n markdown_list = glob.glob('*.md')\n print(markdown_list)\n\n\n\n\n def create_dir(self, directory='_site'):\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n\n\n def markdown2html(self, file_):\n \"\"\"Convert Markdown file to html.\n\n Parameters\n ----------\n filename : str\n Filename of the Markdown file to be converted.\n\n\n Notes\n -----\n\n\n Example\n -------\n >>>\n\n\n \"\"\"\n \n if file_.endswith('.md') or file_.endswith('.markdown'):\n\n filename, md_ext = os.path.splitext(file_)\n html_file = filename + '.html'\n\n os.system('pandoc -f markdown -t html '\n + file_\n + ' -o '\n + html_file)\n\n\n\n \n def assemble_html(self):\n \"\"\"Oneliner.\n\n Parameters\n ----------\n parameter : float\n Description.\n\n\n Returns\n -------\n array[float]\n Description.\n\n\n Notes\n -----\n\n\n Example\n -------\n >>>\n\n\n \"\"\"\n\n\nif __name__ == '__main__':\n website = WebsiteBuilder()\n # website.markdown2html('index.md')\n","sub_path":"websitebuilder.py","file_name":"websitebuilder.py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"408918769","text":"import netCDF4 as nc\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nimport time\nimport datetime\nimport sys\n\ndef resolve_data(filepath, savedir):\n # filepath = r'D:/Data/20180516_210000.opflow.nc'\n # savedir = r'D:/Data/weatherRadarExtrapolation_parse/'\n # 获得源文件的文件名\n orginal_filename = filepath.split('\\\\')[-1]\n # 获得文件的日期\n time_str = orginal_filename[0 : 15]\n timeArray = time.strptime(time_str, '%Y%m%d_%H%M%S')\n # timeArray可以调用tm_year等\n timeStamp = int(time.mktime(timeArray))\n timeStamp += 8 * 3600\n dateArray = datetime.datetime.fromtimestamp(timeStamp)\n yyyyMMddHHmmss = dateArray.strftime('%Y%m%d%H%M%S')\n yyyyMMdd = yyyyMMddHHmmss[0:8]\n HHmmss = yyyyMMddHHmmss[8:14]\n # 获得文件的雷达\n create_radar = orginal_filename.split('.')[1]\n if create_radar == 'SA':\n create_radar = 'Z9280'\n elif create_radar == 'XPAR':\n create_radar = 'Multistation'\n # 获得文件的方法\n create_method = orginal_filename.split('.')[2]\n # 产品类型\n product_type = 'MAXREF'\n dataset = nc.Dataset(filepath, 'r')\n orginal_lon = dataset.variables['lon'][:]\n orginal_lat = dataset.variables['lat'][:]\n cr = dataset.variables['cr'][:]\n lon_min = 101\n lon_max = 106\n lat_min = 28\n lat_max = 33\n # 对原始经纬度进行截取\n lon_idx = np.where((orginal_lon >= float(lon_min)) & (orginal_lon <= float(lon_max)))\n after_lon = orginal_lon[lon_idx]\n lat_idx = np.where((orginal_lat >= float(lat_min)) & (orginal_lat <= float(lat_max)))\n after_lat = orginal_lat[lat_idx]\n lon_min_ind = lon_idx[0][0]\n lon_max_ind = lon_idx[0][-1]\n lat_min_ind = lat_idx[0][0]\n lat_max_ind = lat_idx[0][-1]\n timestep = dataset.variables['timestep'][:]\n cr_after = cr[0:len(timestep) + 1, lat_min_ind:lat_max_ind + 1, lon_min_ind: lon_max_ind + 1]\n\n # 获取cr数组的维度\n cr_d_count = cr.ndim\n # 获取cr数组的每个维度的长度\n cr_shape = cr.shape\n # 将cr_after 里的--转化为None\n cr_after = cr_after.flatten().tolist()\n cr_after = np.array(cr_after).reshape(cr_shape[0], len(after_lat), len(after_lon))\n # 找到无效值\n invalid_dic = {}\n for i in cr_after[0][0]:\n if i in invalid_dic:\n invalid_dic[i] += 1\n else:\n invalid_dic[i] = 1\n value_max = 0\n key_max = 0\n for key, value in invalid_dic.items():\n if value > value_max:\n if key == None:\n continue\n value_max = value\n key_max = key\n invalid_value = key_max\n if cr_d_count == 3:\n for d in range(20):\n # 取每个时刻的二维数组值\n cr_data = cr_after[d]\n # 消除其中的无效值\n cr_data[cr_data == invalid_value] = np.nan\n cr_data[cr_data == None] = np.nan\n # 获得预报的时间\n forecast_time = timestep[d] + 6\n # xx, yy = np.meshgrid(x, y)\n new_save_dir = '{}{}{}{}{}{}{}'.format(savedir, create_radar, '/', yyyyMMdd, '/', product_type, '/')\n filename = '{}{}{}{}{}{}{}{}'.format(yyyyMMdd, HHmmss, '_', forecast_time, '_', create_method, '_', product_type.lower())\n draw_img(lat_min, lat_max, lon_min, lon_max, after_lon, after_lat, cr_data, new_save_dir, filename)\n\n\n\ndef draw_img(*args):\n lat_min = args[0]\n lat_max = args[1]\n lon_min = args[2]\n lon_max = args[3]\n xx = args[4]\n yy = args[5]\n data = args[6]\n savedir = args[7]\n filename = args[8]\n xx, yy = np.meshgrid(xx, yy)\n m = Basemap(projection='merc', llcrnrlat=lat_min, urcrnrlat=lat_max, \\\n llcrnrlon=lon_min, urcrnrlon=lon_max, lat_ts=5, resolution='c')\n # ax = plt.subplot(1, 1, 1) # 绘图区\n # 将数据中的无效值的颜色设为透明\n alpha = np.nan\n fig = plt.figure(figsize=(5,5))\n fig.patch.set_alpha(alpha)\n plt.axis('off')\n plt.contourf(xx, yy, data)\n if os.path.exists(savedir) == False:\n os.makedirs(savedir)\n savepath = savedir + '/' + filename\n plt.savefig(savepath, transparent=True, bbox_inches='tight', pad_inches=0)\n plt.close(\"all\")\n\nif __name__ == '__main__':\n # filepath = 'D:\\\\Data\\\\20210202_123600.SA.dnn.nc'\n # savedir = r'D:/Data/weatherRadarExtrapolation_parse/'\n filepath = sys.argv[1]\n savedir = sys.argv[2]\n resolve_data(filepath, savedir)","sub_path":"swsw-data/src/main/resources/python/radar_extraplation/radarextra_maxref.py","file_name":"radarextra_maxref.py","file_ext":"py","file_size_in_byte":4497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"552047","text":"from line import Line\n\nclass TreeNode(object): \n def __init__(self, point, line): \n self.point = point \n self.left = None\n self.right = None\n self.height = 1\n if line is None:\n self.lines = []\n else:\n self.lines = [line]\n \ndef compare(p, q):\n px, py = p\n qx, qy = q\n if py != qy:\n return py - qy\n return qx - px\n\nclass EventQueue(object): \n def __init__(self):\n self.root = None\n \n def _insert(self, root, point, line=None): \n if not root: \n return TreeNode(point, line) \n elif compare(point, root.point) < 0: \n root.left = self._insert(root.left, point, line) \n elif compare(point, root.point) > 0:\n root.right = self._insert(root.right, point, line) \n else:\n if line is not None:\n root.lines.append(line)\n return root\n root.height = 1 + max(self.getHeight(root.left), \n self.getHeight(root.right)) \n balance = self.getBalance(root) \n if balance > 1 and compare(point, root.point) < 0: \n return self.rightRotate(root) \n if balance < -1 and compare(point, root.point) > 0: \n return self.leftRotate(root) \n if balance > 1 and compare(point, root.point) > 0: \n root.left = self.leftRotate(root.left) \n return self.rightRotate(root) \n if balance < -1 and compare(point, root.point) < 0: \n root.right = self.rightRotate(root.right) \n return self.leftRotate(root) \n return root \n \n def insert_line(self, line):\n upper_end = line.upper_endpoint\n lower_end = line.lower_endpoint\n self.root = self._insert(self.root, upper_end, line)\n self.root = self._insert(self.root, lower_end, None)\n \n def insert(self, point):\n self.root = self._insert(self.root, point, None)\n \n def leftRotate(self, z): \n y = z.right \n T2 = y.left \n y.left = z \n z.right = T2 \n z.height = 1 + max(self.getHeight(z.left), \n self.getHeight(z.right)) \n y.height = 1 + max(self.getHeight(y.left), \n self.getHeight(y.right)) \n return y \n \n def rightRotate(self, z): \n \n y = z.left \n T3 = y.right \n y.right = z \n z.left = T3 \n z.height = 1 + max(self.getHeight(z.left), \n self.getHeight(z.right)) \n y.height = 1 + max(self.getHeight(y.left), \n self.getHeight(y.right)) \n return y \n \n def getHeight(self, root): \n if not root: \n return 0\n return root.height \n \n def getBalance(self, root): \n if not root: \n return 0\n return self.getHeight(root.left) - self.getHeight(root.right) \n \n def _inOrder(self, root, result): \n if not root: \n return\n \n self._inOrder(root.left, result) \n result.append(root)\n self._inOrder(root.right, result)\n \n def inOrder(self):\n result = []\n self._inOrder(self.root, result)\n return result\n \n def delete(self, point):\n self.root = self._delete(self.root, point)\n \n def get_max(self):\n current = self.root\n while (current.right != None):\n current = current.right\n return current\n \n def pop_next_event(self):\n current = self.get_max()\n self.delete(current.point)\n return current\n \n def _delete(self, root, key): \n if not root: \n return root \n elif compare(key, root.point) < 0: \n root.left = self._delete(root.left, key) \n elif compare(key, root.point) > 0: \n root.right = self._delete(root.right, key) \n else: \n if root.left is None: \n temp = root.right \n root = None\n return temp \n elif root.right is None: \n temp = root.left \n root = None\n return temp \n temp = self.getMinValueNode(root.right) \n root.point = temp.point \n root.lines = temp.lines\n root.right = self._delete(root.right, \n temp.point) \n if root is None: \n return root \n root.height = 1 + max(self.getHeight(root.left), \n self.getHeight(root.right)) \n balance = self.getBalance(root) \n if balance > 1 and self.getBalance(root.left) >= 0: \n return self.rightRotate(root) \n if balance < -1 and self.getBalance(root.right) <= 0: \n return self.leftRotate(root) \n if balance > 1 and self.getBalance(root.left) < 0: \n root.left = self.leftRotate(root.left) \n return self.rightRotate(root) \n if balance < -1 and self.getBalance(root.right) > 0: \n root.right = self.rightRotate(root.right) \n return self.leftRotate(root) \n return root \n\n def getMinValueNode(self, root): \n if root is None or root.left is None: \n return root \n \n return self.getMinValueNode(root.left) \n \n def is_empty(self):\n return self.root is None\n \nif __name__ == '__main__':\n line_1 = Line((1, 8), (0, 6))\n line_2 = Line((1, 8), (2, 6))\n line_3 = Line((2, 6), (1, 4))\n line_4 = Line((3, 7), (4, 5))\n line_5 = Line((3, 3), (6, 5))\n line_6 = Line((5, 6), (7, 4))\n line_7 = Line((5, 4), (7, 6))\n lines = [line_1, line_2, line_3, line_4, line_5, line_6, line_7]\n i = 1\n for line in lines:\n line.name = 'line_'+str(i)\n i += 1\n Q = EventQueue()\n for line in lines:\n Q.insert_line(line)\n def print_q(Q):\n lul = []\n for node in Q.inOrder():\n lul.append(node.point)\n print(lul)","sub_path":"line_intersecting/omegalul/eventQueue.py","file_name":"eventQueue.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"382852006","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams['figure.figsize'] = 12, 12\n\n\ndef attraction(position, goal, alpha):\n x = alpha * (position[0] - goal[0])\n y = alpha * (position[1] - goal[1])\n return [x, y]\n\n\ndef repulsion(position, obstacle, beta, q_max):\n distance_x = position[0] - obstacle[0]\n x = beta * (1/q_max - 1/distance_x) * 1/distance_x**2\n distance_y = position[1] - obstacle[1]\n y = beta * (1/q_max - 1/distance_y) * 1/distance_y**2\n if x < q_max and y < q_max: return [x, y]\n else: return [0, 0]\n\n\ndef potential_field(grid, goal, alpha, beta, q_max):\n x = []\n y = []\n fx = []\n fy = []\n\n obs_i, obs_j = np.where(grid == 1)\n\n for i in range(grid.shape[0]):\n for j in range(grid.shape[1]):\n if grid[i, j] == 0:\n # add attraction force\n force = attraction([i, j], goal, alpha)\n\n for (oi, oj) in zip(obs_i, obs_j):\n if np.linalg.norm(np.array([i, j]) - np.array([oi, oj])) < q_max:\n # add replusion force\n force += repulsion([i, j], [oi, oj], beta, q_max)\n\n x.append(i)\n y.append(j)\n fx.append(force[0])\n fy.append(force[1])\n return x, y, fx, fy\n\n\nif __name__ == '__main__':\n grid = np.zeros((30, 30))\n grid[10:15,10:15] = 1.0\n grid[17:25,10:17] = 1.0\n\n goal = [5, 5]\n # constsants\n alpha = 1.0\n beta = 2.0\n q_max = 10\n\n x, y, fx, fy = potential_field(grid, goal, alpha, beta, q_max)\n\n plt.imshow(grid, cmap = 'Greys', origin='lower')\n plt.plot(goal[1], goal[0], 'ro')\n plt.quiver(y, x, fy, fx)\n plt.xlabel('X')\n plt.ylabel('Y')\n plt.show()\n","sub_path":"planning/localplaning/potential_field.py","file_name":"potential_field.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"508992253","text":"class Win_Door:\r\n def __init__(self, x, y):\r\n self.square = x * y\r\nclass Room:\r\n def __init__(self, x, y, z):\r\n self.width = x\r\n self.height = y\r\n self.lenght = z \r\n self.wd = []\r\n def square(self):\r\n return 2 * self.lenght * (self.width + self.height)\r\n def addWD(self, w, h):\r\n self.wd.append(Win_Door(w, h))\r\n def workSurface(self):\r\n new_square = self.square()\r\n for i in self.wd:\r\n new_square -= i.square\r\n return new_square\r\n def roll(self, wr, hr):\r\n return self.workSurface()/(wr*hr)\r\nclass Interface:\r\n def __init__(self):\r\n self.parametersRoom = []\r\n self.parametersWindow = []\r\n self.parametersDoors = []\r\n self.parametersRoll = []\r\n\r\n self.parametersRoom.append(float(input(\"Введите ширину комнаты: \")))\r\n self.parametersRoom.append(float(input(\"Введите высоту комнаты: \")))\r\n self.parametersRoom.append(float(input(\"Введите длину комнаты: \")))\r\n countWindow = int(input(\"Введите количество окон: \"))\r\n for i in range(countWindow):\r\n self.parametersWindow.append(float(input(f'Введите высоту {i+1} - го окна: ')))\r\n self.parametersWindow.append(float(input(f'Введите ширину {i+1} - го окна: ')))\r\n countDoors = int(input(\"Введите количество дверей: \"))\r\n for i in range(countDoors):\r\n self.parametersDoors.append(float(input(f'Введите высоту {i+1} - й двери: ')))\r\n self.parametersDoors.append(float(input(f'Введите ширину {i+1} - й двери: ')))\r\n self.parametersRoll.append(float(input('Введите ширину рулона: ')))\r\n self.parametersRoll.append(float(input('Введите длину рулона: ')))\r\n\r\n\r\n\r\ni1 = Interface()\r\nr1 = Room(i1.parametersRoom[0], i1.parametersRoom[1], i1.parametersRoom[2]) \r\nprint(f' Oбщая площадь квартиры: {r1.square()}')\r\nfor i,j in enumerate(range(0,len(i1.parametersWindow),2)):\r\n r1.addWD(i1.parametersWindow[i], i1.parametersWindow[i+1]) #площадь окон\r\nfor i,j in enumerate(range(0,len(i1.parametersDoors),2)):\r\n r1.addWD(i1.parametersDoors[i], i1.parametersDoors[i+1]) #площадь дверей\r\nprint(f'Oбклеиваемая площадь: {r1.workSurface()}') \r\nprint(f'Количество рулонов обой: {r1.roll(i1.parametersRoll[0], i1.parametersRoll[1])}')\r\n\r\n","sub_path":"OOAP__PR_5.py","file_name":"OOAP__PR_5.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"54668691","text":"import numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\n\nclass RandomProjector(object):\n def __init__(self, X, y, frames=200):\n self.X = X\n self.y = y\n self.frames = frames\n\n if y is not None:\n # Spectral has 255 colors (I think)\n num_classes = len(np.unique(y))\n colors = plt.cm.Spectral(np.arange(num_classes)\n * 255 / num_classes)\n else:\n num_classes = 1\n colors = 'b'\n\n self.points = [plt.plot([], [], 'o', color=colors[i])[0]\n for i in range(num_classes)]\n\n n_features = X.shape[1]\n\n # initialize projection matrix\n self.projection = np.zeros((n_features, 2))\n\n # rest is n_features - 2 large\n size = n_features - 2\n self.frequencies = 10 + np.random.randint(10, size=(size, 2))\n self.phases = np.random.uniform(size=(size, 2))\n\n def init_figure(self):\n for p in self.points:\n p.set_data([], [])\n plt.xlim((-2, 2))\n plt.ylim((-2, 2))\n plt.xticks(())\n plt.yticks(())\n return self.points\n\n def animate(self, i):\n # set top 2x2 to identity\n self.projection[0, 0] = 1\n self.projection[1, 1] = 1\n # set \"free entries\" of projection matrix\n # gives them a \"rotation\" feel and makes the whole thing seamless.\n scale = 2 * np.pi * i / self.frames\n self.projection[2:, :] = np.sin(self.frequencies * scale + self.phases)\n interpolation = np.dot(X, self.projection)\n interpolation /= interpolation.max(axis=0)\n for p, c in zip(self.points, np.unique(y)):\n p.set_data(interpolation[y == c, 0], interpolation[y == c, 1])\n return self.points\n\n\ndef make_video(X, y=None, frames=500, filename=\"video.mp4\"):\n fig = plt.figure()\n projector = RandomProjector(X, y, frames)\n anim = FuncAnimation(fig, projector.animate, frames=frames, interval=100,\n blit=True, init_func=projector.init_figure)\n\n #anim.save(filename, fps=20, extra_args=['-vcodec', 'libx264'])\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n iris = load_iris()\n #iris = load_digits()\n X, y = iris.data, iris.target\n\n mask = (y == 1) + (y == 2) + (y == 7)\n y = y[mask]\n X = X[mask]\n\n # we should at least remove the mean\n X = StandardScaler(with_std=False).fit_transform(X)\n\n # make boring PCA visualization for comparison\n num_classes = len(np.unique(y))\n colors = plt.cm.Spectral(np.arange(num_classes) * 255 / num_classes)\n X_pca = PCA(n_components=2).fit_transform(X)\n for i, c in enumerate(np.unique(y)):\n plt.plot(X_pca[y == c, 0], X_pca[y == c, 1], 'o', color=colors[i],\n label=c)\n plt.legend()\n plt.savefig(\"digits_pca.png\", bbox_inches=\"tight\")\n # PCA here optional. Also try without.\n X = PCA().fit_transform(X)\n make_video(X, y, filename='digits_two_classes.mp4', frames=1000)\n# import numpy as np\n\n# import matplotlib.pyplot as plt\n# from matplotlib.animation import FuncAnimation\n\n# from sklearn.datasets import load_iris\n# from sklearn.preprocessing import StandardScaler\n\n# iris = load_iris()\n# X, y = iris.data, iris.target\n\n# X_pca = StandardScaler().fit_transform(X)\n\n# fig = plt.figure()\n# colors = plt.cm.Spectral(y * 255 / y.max())\n\n# n_iter = 200\n\n# points = [plt.plot([], [], 'o', color=['r', 'g', 'b'][i])[0]\n# for i in np.unique(y)]\n\n\n# def init():\n# global points\n# for p in points:\n# p.set_data([], [])\n# plt.xlim((-4, 4))\n# plt.ylim((-3, 3))\n# plt.xticks(())\n# plt.yticks(())\n# return points\n\n\n# def animate(i):\n# global points\n# alpha = 2 * np.pi * i / n_iter\n# beta = 4 * np.pi * i / n_iter\n# interpolation1 = np.cos(alpha) * X_pca[:, 1] + np.sin(alpha) * X_pca[:, 2]\n# interpolation2 = np.cos(beta) * X_pca[:, 0] + np.sin(beta) * X_pca[:, 3]\n# for p, c in zip(points, np.unique(y)):\n# p.set_data(interpolation1[y == c], interpolation2[y == c])\n# return points\n\n# anim = FuncAnimation(fig, animate, frames=n_iter, interval=100, blit=True,init_func=init)\n# #anim.save(\"iris.mp4\", fps=20, extra_args=['-vcodec', 'libx264'])\n# plt.show()","sub_path":"Unsupervised_Learning/RandomProj/RP_Iris.py","file_name":"RP_Iris.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"191536286","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport csv\r\n\r\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\r\nurl = 'https://www.quikr.com/bikes-scooters/used+Royal-Enfield+bikes-scooters+karnataka+x1146899?from=auto'\r\nr = requests.get(url, headers=headers)\r\nsoup = BeautifulSoup(r.content, 'html.parser')\r\nresult = []\r\nkeys = [\"name\",\"price\",\"prime_features\"]\r\nfor i in soup.find_all(\"div\", {\"class\": \"qc-ads__card--body\"}):\r\n temp={}\r\n name = i.find(\"h2\").text\r\n price = i.find(\"div\",{\"class\": \"price\"}).text\r\n prime_features = i.find(\"div\",{\"class\": \"prime-features\"}).text\r\n temp.update({keys[0]:name,keys[1]:price,keys[2]:prime_features})\r\n result.append(temp)\r\n\r\nwith open('details_result.csv', 'wb') as output_file:\r\n dict_writer = csv.DictWriter(output_file, keys)\r\n dict_writer.writeheader()\r\n dict_writer.writerows(result)\r\n","sub_path":"automation.py","file_name":"automation.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"622056375","text":"from dbco import *\nfrom nltk.tokenize import sent_tokenize\nimport re\n\ndef create_sentences(content):\n\t'''Divide content into sentences'''\n\tsentences = sent_tokenize(content)\n\t# Remove newline character from sentences, along with preceding or trailing whitespaces\n\tsentences = [re.sub('\\n', '', sentence).strip() for sentence in sentences]\n\treturn sentences\n\ndef get_highlighted_sentences(sentences, entities):\n\t'''Takes in paragraphs of text and a list of entities, returns a list of the sentences in content in which any number of words in entitites shows'''\n\n\thighlights = []\n\n\tfor sentence in sentences:\n\t\tmatching_entities = []\n\t\tfound_match = False\n\n\t\tfor entity in entities:\n\t\t\tif entity.lower() in sentence.lower():\n\t\t\t\tmatching_entities.append(entity)\n\t\t\t\tfound_match = True\n\n\t\tif found_match:\n\t\t\thighlight = {\n\t\t\t'sentence': sentence,\n\t\t\t'entitites': matching_entities\n\t\t\t}\n\t\t\thighlights.append(highlight)\n\n\treturn highlights\n\ndef save_to_db(article, highlights):\n\t'''Updates an article in the db to include the highlights'''\n\tdoc_id = article[\"_id\"]\n\tdb.qdoc.update( { \"_id\": doc_id },{\"$set\": {\"highlights\": highlights} } )\n\n\ndef main(limit=10):\n\t'''Fetches some number of articles, and saves to the databases the sentences that have a match with one of our entitites for the given article'''\n\n\t# Gets articles where we have entities and content, sort by how recent article is\n\tarticles = db.qdoc.find({ \"$query\": { \"entities\": { \"$exists\": True }, \"content\": { \"$exists\": True } },\n\t\t\"$orderby\": { '_id' : -1 } },\n\t\t{ \"content\": 1, \"entities\": 1}).limit(limit)\n\n\t# Processes each article one at a time\n\tfor article in articles:\n\n\t\t# Converts key names to python strings so lookup is convenient\n\t\tarticle = dict([(k.encode('utf-8'), v) for k, v in article.iteritems()])\n\t\tcontent = article['content']\n\t\tentities = article['entities']\n\n\t\tsentences = create_sentences(content)\n\t\thighlights = get_highlighted_sentences(sentences, entities)\n\n\t\tsave_to_db(article, highlights)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"entity_highlights.py","file_name":"entity_highlights.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"509259751","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport json\nimport sys\n\ntimes = []\nrewards = []\nt = []\nr = []\n\ntrials = [\"Reacher-v1-none-20000.000000-0.001000-0.000000-0.000000\",\"Reacher-v1-none-10000.000000-0.001000-0.000000-0.000000\",\"Reacher-v1-none-5000.000000-0.001000-0.000000-0.000000\",\"Reacher-v1-none-1500.000000-0.001000-0.000000-0.000000\"]\nnames = [\"Fixed 20,000 steps\", \"Fixed 10,000 steps\", \"Fixed 5,000 steps\", \"Fixed 1,500 steps\"]\n\nfor i in xrange(len(trials)):\n with open(trials[i]) as data_file:\n data = json.load(data_file)\n\n times.append([])\n rewards.append([])\n totaltime = 0\n\n time_since = 0\n avg = 0\n avgcount = 0\n\n for e in xrange(len(data[\"mean_reward\"])):\n totaltime += data[\"timesteps\"][e]\n\n time_since += data[\"timesteps\"][e]\n avg += data[\"mean_reward\"][e]\n avgcount += 1\n\n if time_since > 10000:\n time_since = 0\n # totaltime += 1\n if i == 0:\n times[i].append(totaltime)\n else:\n times[i].append(totaltime)\n rewards[i].append(data[\"mean_reward\"][e])\n\n avg = 0\n avgcount = 0\n\n t.append(np.array(times[i]))\n r.append(np.array(rewards[i]))\n\n plt.plot(t[i],r[i],color=(1 - (i/5.0),i/5.0,1.0),label=names[i])\n\nplt.xlabel(\"Environment Steps Seen\")\nplt.ylabel(\"Average return\")\nplt.legend(loc=4)\nplt.title(\"Reacher-v1\")\nplt.show()\n","sub_path":"results/vs_fixed/reacher/fixed_steps.py","file_name":"fixed_steps.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"435388207","text":"import csv\nimport mysql.connector\nfrom Connection import DBCon\n\ncaminho = '/home/homelist/Documentos/Tabela de Preço.csv'\ncont = 0\n\n# Leitura da tabela de preços\nwith open(caminho, 'r') as ler:\n produtos = csv.reader(ler, delimiter=';')\n for produto in produtos:\n price = produto[3].replace(',', '.')\n cod_barra = produto[1]\n id_produto = DBCon.codBarra(cod_barra)\n if id_produto is not None:\n with open('files/update_price2.txt', 'a') as f:\n f.write(\"update products set price=%s where id=%s;\" % (price, id_produto))\n f.write('\\n')","sub_path":"Update/generateInsertPrice.py","file_name":"generateInsertPrice.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"549170668","text":"from conans import ConanFile, AutoToolsBuildEnvironment, CMake, tools\nfrom conans.errors import ConanException\nimport os, glob, shutil, ntpath\n\nclass ApacheaprutilConan(ConanFile):\n name = \"apache-apr-util\"\n version = \"1.6.1\"\n license = \"Apache-2.0\"\n url = \"https://github.com/malwoden/conan-apache-apr-util\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n requires = \"apache-apr/1.6.3@neewill/testing\", \"expat/2.2.5@bincrafters/stable\"\n options = {\"shared\": [True, False]}\n default_options = \"shared=False\"\n exports_sources = [\"CMakeLists.patch.txt\"]\n source_subfolder = \"source_subfolder\"\n generators = \"cmake\"\n\n def requirements(self):\n # make option?\n self.requires(\"OpenSSL/1.0.2n@conan/stable\")\n\n # cmake file requires patching to support anything other than these settings\n if self.settings.os == \"Windows\":\n self.options[\"apache-apr\"].shared = self.options.shared\n self.options[\"expat\"].shared = False\n\n if self.settings.os != \"Windows\" and self.options.shared:\n raise ConanException(\"Cannot build shared libs on non-windows platforms\")\n\n def source(self):\n file_ext = \".tar.gz\" if not self.settings.os == \"Windows\" else \"-win32-src.zip\"\n tools.get(\"http://archive.apache.org/dist/apr/apr-util-\" + self.version + file_ext)\n os.rename(\"apr-util-\" + self.version, self.source_subfolder)\n\n if self.settings.os == \"Windows\":\n tools.patch(self.source_subfolder, \"CMakeLists.patch.txt\")\n\n def build_unix(self):\n env_build = AutoToolsBuildEnvironment(self)\n env_build.fpic = self.options.shared\n\n with tools.environment_append(env_build.vars):\n configure_command = \"./configure\"\n configure_command += \" --prefix=\" + self.build_folder + \"/buildinstall\"\n configure_command += \" --with-apr=\" + self.deps_cpp_info[\"apache-apr\"].rootpath\n configure_command += \" --with-expat=\" + self.deps_cpp_info[\"expat\"].rootpath\n # How to enable shared util builds\n # configure_command += \" --enable-shared=\" + (\"yes\" if self.options.shared else \"no\")\n # configure_command += \" --enable-static=\" + (\"yes\" if not self.options.shared else \"no\")\n\n # add with-ssl flag?\n\n with tools.chdir(self.source_subfolder):\n self.run(configure_command)\n self.run(\"find ./\")\n self.run(\"make -j \" + str(max(tools.cpu_count() - 1, 1)))\n self.run(\"make install\")\n\n def build_windows(self):\n cmake = CMake(self)\n build_target = \"libaprutil-1\" if self.options.shared == True else \"aprutil-1\"\n\n install_folder = self.build_folder + \"/buildinstall\"\n os.makedirs(install_folder + \"/include\", exist_ok=True)\n\n # copy and copy2 will not work due to the permissions issues\n for filename in glob.iglob(self.deps_cpp_info[\"apache-apr\"].include_paths[0] + \"/*.h\"):\n shutil.copyfile(filename, install_folder + \"/include/\" + ntpath.basename(filename))\n\n apr_lib_name = \"libapr-1.lib\" if self.options[\"apache-apr\"].shared == True else \"apr-1.lib\"\n os.makedirs(install_folder + \"/lib/\", exist_ok=True)\n shutil.copyfile(self.deps_cpp_info[\"apache-apr\"].lib_paths[0] + \"/\" + apr_lib_name,\n install_folder + \"/lib/\" + apr_lib_name)\n\n if self.options.shared:\n cmake.definitions[\"APU_BUILD_SHARED\"] = \"TRUE\"\n\n cmake.definitions[\"CMAKE_INSTALL_PREFIX\"] = install_folder\n\n # Cmake file will require patching if these are enabled\n cmake.definitions[\"APU_HAVE_ODBC\"] = \"FALSE\"\n cmake.definitions[\"APR_HAS_LDAP\"] = \"FALSE\"\n\n cmake.configure(source_folder=self.source_subfolder)\n cmake.build(target=build_target)\n cmake.install()\n\n def build(self):\n if self.settings.os == \"Windows\":\n self.build_windows()\n else:\n self.build_unix()\n\n def package(self):\n base_path = self.build_folder + \"/buildinstall/\"\n\n if self.options.shared == True:\n self.copy(\"*.so*\", dst=\"lib\", src=base_path + \"lib\", keep_path=False)\n self.copy(\"*.dylib*\", dst=\"lib\", src=base_path + \"lib\", keep_path=False)\n self.copy(\"libaprutil-1.lib\", dst=\"lib\", src=base_path + \"lib\", keep_path=False)\n self.copy(\"libaprutil-1.dll\", dst=\"bin\", src=base_path + \"bin\", keep_path=False)\n else:\n self.copy(\"aprutil-1.a\", dst=\"lib\", src=base_path + \"lib\", keep_path=False)\n self.copy(\"aprutil-1.lib\", dst=\"lib\", src=base_path + \"lib\", keep_path=False)\n self.copy(\"libaprutil-1.a\", dst=\"lib\", src=base_path + \"lib\", keep_path=False)\n\n self.copy(\"apu-1-config\", dst=\"bin\", src=base_path + \"bin\", keep_path=False)\n self.copy(\"*.h\", dst=\"include\", src=base_path + \"include\", keep_path=True)\n\n def package_info(self):\n self.cpp_info.libs = tools.collect_libs(self)\n if self.settings.os != \"Windows\":\n self.cpp_info.includedirs = [\"include/apr-1\"]\n\n if self.settings.os == \"Windows\":\n if not self.options.shared:\n self.cpp_info.defines = [\"APU_DECLARE_STATIC\"]\n else:\n self.cpp_info.defines = [\"APU_DECLARE_EXPORT\"]\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":5334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"48178766","text":"\"\"\"\nDjango settings for mysite project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '5jvfazg&8h$)u(t7az6a+50u2%(v0%w@-1x3lq1f&kn!_#bjgd'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'ckeditor', # App for adding markdown preview to the admin page\n 'blog', #Blog app\n 'autoslug', # slug field generator app\n\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'mysite.urls'\n\nWSGI_APPLICATION = 'mysite.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nMEDIA_URL = '/media/'\n\n\nCKEDITOR_UPLOAD_PATH = \"uploads/\"\nCKEDITOR_IMAGE_BACKEND = 'pillow'\nCKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'\nCKEDITOR_CONFIGS = {\n 'default': {\n 'toolbar': 'UltraFull',\n 'height': 300,\n 'toolbar_UltraFull': [\n ['Font', 'FontSize', 'Format'],\n ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'],\n [\n 'NumberedList', 'BulletedList', '-',\n 'Outdent', 'Indent', '-',\n 'Blockquote', '-',\n 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'\n ],\n ['Link', 'Unlink', 'Anchor'],\n ['Image', 'Flash', 'Table', 'HorizontalRule', 'PageBreak', 'Smiley', 'SpecialChar'],\n ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'],\n ['TextColor', 'BGColor'],\n ['Maximize', 'Source'],\n ],\n 'language': 'en',\n 'forcePasteAsPlainText': True,\n },\n}\n","sub_path":"mysite/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"174471277","text":"# coding=utf-8\nimport pymysql\nimport logging\nimport os\nimport json\nimport copy\nimport subprocess\n\nfrom error import Error\nfrom common import Common\n\n\nclass ModTemplate(object):\n \"\"\"Project Database access class\n\n\t执行项目(站点)的增删改查等数据操作\n\t\"\"\"\n\n db = None\n conf = None\n\n def __init__(self, webapp):\n \"\"\"Init ModTemplate Class\n\t\t\"\"\"\n self.__class__.db = webapp.db\n self.__class__.conf = webapp.cfg\n self.__class__.webapp = webapp\n\n def update(self, action, pid, **template):\n \"\"\"Add template\n\n\t\t添加/修改一个站点模板(数据表)\n\n\t\tArgs:\n\t\t\ttemplate:\n\t\t\ttemplate_name:项目名称\n\t\t\tenable:是否启用 True/False\n\t\tReturns:\n\t\t\tError json\n\t\t\"\"\"\n pass\n\n pid = str(pid)\n if 'template_name' not in template:\n return Error.MODPARAMERR\n expression = \"`project_id`=\" + pid + \",`template_name`='\" + template['template_name'] + \"'\"\n _enable = '1' if 'enable' not in template else str(template['enable'])\n _template_view = '' if 'template_view' not in template else template['template_view']\n _template_summary = '' if 'template_summary' not in template else template['template_summary']\n _template_config = '' if 'template_config' not in template else template['template_config']\n _callback = '' if 'callback' not in template else template['callback']\n _publish_url = self.conf['default_publish_url'] if 'publish_url' not in template else template[\n 'publish_url']\n expression = expression + \",`enable`=\" + _enable + \",`template_view`='\" + pymysql.escape_string(\n _template_view) + \"',`template_summary`='\" + pymysql.escape_string(\n _template_summary) + \"',`publish_callback`='\" + pymysql.escape_string(\n _callback) + \"',`publish_url`='\" + _publish_url + \"',`template_config`='\"+pymysql.escape_string(\n\t\t\t_template_config)+\"'\"\n if action == 'update':\n if 'template_id' not in template:\n return Error.MODPARAMERR\n # 判断callback设置是否修改\n sql = \"select `publish_callback` from `cms_template` where `template_id`=\" + str(template['template_id'])\n _n, _data = self.db.executeQuery(pid, sql)\n if _n < 1:\n return _data\n else:\n _old_callback = _data[0][0]\n # 更新模板信息\n sql = \"update `cms_template` set \" + expression + \" where template_id=\" + str(template['template_id'])\n else:\n sql = \"insert into `cms_template` set \" + expression + \",`allow`=''\"\n logging.info('Template update SQL:' + sql)\n n, data = self.db.execute(pid, sql)\n # 获取project信息\n if data['code'] != 0:\n return data\n # 更新记录\n if action == 'update':\n if _old_callback != _callback:\n self.webapp.schema.load_schema()\n return data\n\n # 添加记录\n sql = \"select template_id from cms_template where project_id='\" + pid + \"' and template_name='\" + template[\n 'template_name'] + \"' order by template_id desc limit 1\"\n n, data = self.db.executeQuery(pid, sql)\n if n < 1:\n return data\n _template_id = data[0][0]\n logging.info(str(data))\n # 创建模板表cms_tbl_{$tid}\n _tblname = 'cms_tbl_' + str(_template_id)\n sql = Common.loadSql('template_create.sql')\n sql = sql.replace('{$tblname}', _tblname)\n n, data = self.db.execute(pid, sql, mutiline=True)\n if data['code'] != 0:\n return data\n recode = copy.deepcopy(data)\n recode['tid'] = _template_id\n return data\n\n def get_template_list(cls, pid, pagesize=-1, pageindex=1, strfilter='', order=''):\n \"\"\"get template list by case,support page\n\n\t\t获取模板列表,支持分页\n\n\t\tArgs:\n\t\t\tpid:项目id\n\t\t\tpagesize:页长度\n\t\t\tpageindex:页码\n\t\t\tstrfilter:查找条件\n\t\t\torder:排序规则\n\n\t\tReturns:\n\t\t\tList\n\t\t\"\"\"\n pass\n\n pid = str(pid)\n strfilter = '1' if strfilter == '' else strfilter\n order = 'template_id desc' if order == '' else order\n sql = 'select count(*) from cms_template where ' + strfilter\n n, data = cls.db.executeQuery(pid, sql)\n if n == -1:\n return n, data\n count = data[0][0]\n # 处理strfilter和order\n strfilter = strfilter.replace('`', '').replace('template_id', 'a.template_id')\n order = order.replace('`', '').replace('template_id', 'a.template_id')\n sql = \"select a.template_id,a.project_id,a.template_name,a.`enable`,a.`template_summary`,ifnull(b.`document_count`,0) from cms_template a left outer join `cms_template_statistics` b on a.template_id=b.template_id where \" + strfilter + ' order by ' + order\n if pagesize > 0:\n sql = sql + ' limit ' + str((pageindex - 1) * pagesize) + ',' + str(pagesize)\n n, data = cls.db.executeQuery(pid, sql)\n if n >= 0:\n return count, data\n return n, data\n\n def get_template_one(cls, pid, tid):\n \"\"\"get template detail\n\n\t\t获取模板详细信息\n\t\t\n\t\tArgs:\n\t\t\tpid:项目id\n\t\t\ttid:模板id\n\t\t\n\t\tReturns:\n\t\t\tDict\n\t\t\"\"\"\n pass\n sql = \"select `template_id`,`project_id`,`template_name`,`template_view`,`publish_callback`,`publish_url`,`enable`,`template_summary` from `cms_template` where `project_id`=\" + str(\n pid) + \" and `template_id`=\" + str(tid)\n n, data = cls.db.executeQuery(pid, sql)\n if n > 0:\n result = {'template_id': data[0][0], 'project_id': data[0][1], 'template_name': data[0][2].rstrip(),\n 'template_summary': data[0][7].strip(), 'template_view': data[0][3].rstrip(),\n 'publish_callback': data[0][4], 'publish_url': data[0][5], 'enable': data[0][6]}\n return result\n return Error.DBEMPTYERR\n\n def create_empty(self, pid=0):\n \"\"\" make a empty instance\n\t\t\"\"\"\n return {'template_id': 0, 'project_id': pid, 'template_name': '', 'template_view': '', 'template_summary': '',\n 'publish_callback': '', 'publish_url': self.conf['default_publish_format'], 'enable': 1}\n\n def update_template_allow(self, pid, user, tids):\n \"\"\"update template allow users\n\t\t修改模板归属\n\n\t\tArgs:\n\t\t\tpid:\n\t\t\tuser:\n\t\t\ttids:模板id集合 List[]\n\t\tReturns:\n\t\t\"\"\"\n sql = \"select template_id,IFNULL(allow,'') from cms_template\"\n n, data = self.db.executeQuery(pid, sql)\n if n < 0:\n return data\n sql = \"\"\n for row in data:\n tid = str(row[0])\n allow = [] if row[1] == '' else json.loads(row[1])\n is_change = False\n # 清理\n if user in allow and tid not in tids:\n allow.remove(user)\n is_change = True\n # 追加\n if user not in allow and tid in tids:\n allow.append(user)\n is_change = True\n # 生成sql\n if is_change:\n sql = sql + \"update `cms_template` set allow='\" + pymysql.escape_string(\n json.dumps(allow, ensure_ascii=False)) + \"' where `template_id`=\" + tid + \";\\n\"\n pass\n n, data = self.db.execute(pid, sql, mutiline=True)\n if n < 0:\n return data\n return Error.SUCC\n\n def remove_template(self, pid, tid):\n \"\"\"\n\t\tremove template\n\t\t删除模板,删除前会备份至安全区目录./safearea\n\n\t\tArgs:\n\t\t\tpid:\n\t\t\ttid:\n\n\t\tReturns:\n\t\t\t\n\t\t\"\"\"\n _cfg = Common.collection_find(self.conf['db'], lambda s: s['pid'] == int(pid))\n if _cfg is None:\n return Error.DATANOTEXISTED\n _cfg['tid'] = tid\n cmd = \"mysqldump -h \" + _cfg['host'] + \" -u \" + _cfg['user'] + \" -p\" + _cfg['passwd'] + \" cms_site_\" + str(\n pid) + \" cms_tbl_\" + str(tid) + \" >./safearea/\" + str(pid) + \"_\" + str(tid) + \".sql\"\n child = subprocess.Popen([cmd], shell=True)\n child.wait()\n cmd = 'mysql -h{$host} -P{$port} -u {$user} -p{$passwd} --execute=\"select * from cms_template where template_id={$tid}\" cms_site_{$pid} >./safearea/template_cfg_{$pid}_{$tid}.bak'\n cmd = Common.exp_render(cmd, _cfg)\n child = subprocess.Popen([cmd], shell=True)\n child.wait()\n cmd = 'mysql -h{$host} -P{$port} -u {$user} -p{$passwd} --execute=\"select * from cms_template_field where template_id={$tid}\" cms_site_{$pid} >./safearea/template_field_{$pid}_{$tid}.bak'\n cmd = Common.exp_render(cmd, _cfg)\n child = subprocess.Popen([cmd], shell=True)\n child.wait()\n sql = \"DROP TABLE IF EXISTS `cms_tbl_\" + str(tid) + \"`;\\n\"\n sql = sql + \"delete from `cms_template_field` where template_id=\" + str(tid) + \";\\n\"\n sql = sql + \"delete from `cms_template` where template_id=\" + str(tid) + \";\"\n n, data = self.db.execute(pid, sql, mutiline=True)\n\n if n < 0:\n return data\n return Error.SUCC\n","sub_path":"modtemplate.py","file_name":"modtemplate.py","file_ext":"py","file_size_in_byte":9083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"45377159","text":"'''\n画像を判定する(1 = dog, 0 = cat)\n提出用csvを作成\n$ python test.py ./images/test1/*.jpg\n'''\n\nimport train\nimport sys, os\nfrom PIL import Image\nimport numpy as np\nimport csv\n\n\n# コマンドラインからファイル名を得る、引数がなければ終了\nif len(sys.argv) <= 1:\n print(\"test.py (ファイル名)\")\n quit()\n\nimage_size = 50\ncategories = [\n 'dog',\n 'cat',\n]\n\n# 入力画像をNumpyに変換 --- (※2)\nX = []\nfiles = []\nfor fname in sys.argv[1:]:\n img = Image.open(fname)\n img = img.convert(\"RGB\")\n img = img.resize((image_size, image_size))\n in_data = np.asarray(img)\n X.append(in_data)\n files.append(fname)\nX = np.array(X)\n\n# CNNのモデルを構築 --- (※3)\nmodel = train.build_model(X.shape[1:])\nmodel.load_weights(\"./models/dogcat-cnn-model.hdf5\")\n\n# CSVに保存\nheader = ['id', 'label']\ndata = []\npre = model.predict(X)\nfor i, p in enumerate(pre):\n y = p.argmax()\n print(\"input:\", files[i])\n print(\"sp:\", categories[y])\n # 反対だった。。。\n if y == 0:\n y = 1\n elif y == 1:\n y = 0\n data.append([i+1, y])\n\nwith open('result.csv', 'w') as f:\n writer = csv.writer(f, lineterminator='\\n')\n writer.writerow(header)\n writer.writerows(data)\n","sub_path":"test_csv.py","file_name":"test_csv.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"125225910","text":"from pixivpy3 import *\r\nimport json\r\nfrom time import sleep\r\nimport os\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# フォローユーザのpixiv_idをcsvファイルから取得しidをリストで返す\r\ndef follow_user_pixiv_id_lists():\r\n file_name = input(\"Type illustrator pixiv_id number list(csv):\\n>>>\")\r\n df = pd.read_csv(file_name, encoding='utf-8')\r\n following_user_id = []\r\n following_user_id = df['user_id']\r\n return following_user_id\r\n\r\n\r\n# ログイン処理\r\ndef login():\r\n api = PixivAPI()\r\n f = open(\"client.json\", \"r\")\r\n client_info = json.load(f)\r\n f.close()\r\n api.login(client_info[\"pixiv_id\"], client_info[\"password\"])\r\n return api\r\n\r\n\r\n# 入力されたpixiv_idから絵師情報を取得しダウンロード\r\ndef getinfo_and_download(user_id):\r\n api = login()\r\n json_result = api.users_works(int(user_id), per_page=1000) # とりあえずmax1000作品と定義\r\n total_works = json_result.pagination.total\r\n illust = json_result.response[0]\r\n\r\n # ファイル名規則チェック(抵触するものは0で置換)\r\n illust.user.name = illust.user.name.translate(str.maketrans({'\\\\': '0', '/': '0', ':': '0', ';': '0', ',': '0', '*': '0', \\\r\n '?': '0', '\\\"': '0', '<': '0', '>': '0', '|': '0', '.': '0'}))\r\n\r\n # ユーザーネーム@hogeを除去\r\n illust.user.name = illust.user.name[0:((illust.user.name + '@').index('@'))] # 半角の@以降を削除\r\n illust.user.name = illust.user.name[0:((illust.user.name + '@').index('@'))] # 全角の@以降を削除\r\n # ユーザーネーム(hoge)を除去\r\n illust.user.name = illust.user.name[0:((illust.user.name + '(').index('('))] # 半角の(以降を削除\r\n illust.user.name = illust.user.name[0:((illust.user.name + '(').index('('))] # 全角の(以降を削除\r\n illust.user.name = illust.user.name[0:((illust.user.name + '[').index('['))] # 半角の[以降を削除\r\n illust.user.name = illust.user.name[0:((illust.user.name + '「').index('「'))] # 全角の「以降を削除\r\n\r\n # 文字列がなくなったとき\r\n if len(illust.user.name) == 0:\r\n illust.user.name = user_id + '(name_error)'\r\n\r\n if not os.path.exists(\"./pixiv_images\"): # 保存用フォルダがない場合は生成\r\n os.mkdir(\"./pixiv_images\")\r\n saving_direcory_path = \"./pixiv_images/\" + illust.user.name + \"/\"\r\n aapi = AppPixivAPI()\r\n separator = \"------------------------------------------------------------\"\r\n\r\n # ダウンロード\r\n print(\"Artist: %s\" % illust.user.name)\r\n print(\"Works: %d\" % total_works)\r\n print(separator)\r\n if not os.path.exists(saving_direcory_path):\r\n os.mkdir(saving_direcory_path)\r\n for work_no in range(0, total_works):\r\n\r\n illust = json_result.response[work_no]\r\n print(\"Procedure: %d/%d\" % (work_no + 1, total_works))\r\n print(\"Title: %s\" % illust.title)\r\n print(\"URL: %s\" % illust.image_urls[\"large\"])\r\n print(\"Caption: %s\" % illust.caption)\r\n\r\n # イラストがすでにダウンロードされている場合\r\n if os.path.exists(saving_direcory_path + str(illust.id) + \"_p0.png\") or os.path.exists(\r\n saving_direcory_path + str(illust.id) + \"_p0.jpg\"):\r\n print(\"Title:\" + str(illust.title) + \" has already downloaded.\")\r\n print(separator)\r\n sleep(2)\r\n\r\n continue\r\n\r\n # 漫画の場合\r\n if illust.is_manga:\r\n work_info = api.works(illust.id)\r\n for page_no in range(0, work_info.response[0].page_count):\r\n page_info = work_info.response[0].metadata.pages[page_no]\r\n aapi.download(page_info.image_urls.large, saving_direcory_path)\r\n sleep(3)\r\n # イラストの場合\r\n else:\r\n aapi.download(illust.image_urls.large, saving_direcory_path)\r\n sleep(3)\r\n print(separator)\r\n\r\n\r\nuser_id_list = follow_user_pixiv_id_lists()\r\n\r\nfor i in user_id_list:\r\n getinfo_and_download(i)\r\n sleep(4)\r\n\r\nprint(\"\\nThat\\'s all.\")","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90080215","text":"import urllib.request\nimport re\n\nurl = \"http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=\"\nval = \"82682\"\nr = range(400)\nfor i in r:\n text = urllib.request.urlopen(url+val).read()\n try:\n val = (re.findall(\"nothing is (\\d+)\",str(text)))[0]\n print('the next is snothing: ', val)\n except:\n print('Last: ', text)\n break\n","sub_path":"task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"138346469","text":"from Players import player\nimport deck\nfrom random import choice\n\nclass Game():\n \"\"\"\n Handles the primary gameplay.\n \"\"\"\n playerList = []\n \n def __init__(self, size):\n self.players(size)\n self.round = 0\n self.deck = deck.Deck()\n self.deck.shufflecards()\n self.firstPlayer = choice(self.playerList)\n \n def players(self, size):\n \"\"\"\n Generates the required number of player instances, currently with automatic names.\n \"\"\"\n playernumber = 0\n while len(self.playerList) < size:\n playernumber += 1\n playername = \"Player \" + str(playernumber)\n newPlayer = player.Player(playername)\n self.playerList.append(newPlayer)\n \n def print_game_status(self):\n \"\"\"\n Prints the current status of the game, the deck, and all the players\n \"\"\"\n self.deck.print_deck()\n self.deck.print_sideboard()\n for i in self.playerList:\n i.print_player()\n ","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"259090466","text":"import math\r\nportfolioDeviationReturn = dict(a92 = -7.14, a93 = 1.62, a94 = 2.48, a95 = -2.59, a96 = 9.37, a97 = -0.55, a98 = -0.89, a99 = -9.19, a00 = -5.11, a01 = -0.49, a02 = 6.84, a03 = 3.04)\r\ndef mean_1():\r\n sum = 0\r\n for key,val in portfolioDeviationReturn.items():\r\n sum += val\r\n return sum / len(portfolioDeviationReturn)\r\n\r\ndef TrackingRisk():\r\n mn = mean()\r\n sum = 0\r\n for key,val in portfolioDeviationReturn.items():\r\n sum += math.pow((val - mn),2)\r\n return math.sqrt(sum / (len(portfolioDeviationReturn) - 1))\r\n\r\nMSCIGermanIndexTotalReturn = dict(b93 = 46.21, b94 = -6.18, b95 = 8.04, b96 = 22.87, b97 = 45.90, b98 = 20.32, b99 = 41.20, b00 = -9.53, b01 = -17.75, b02 = -43.06)\r\ndef geometricMeanReturn():\r\n sum = 1\r\n for key,val in MSCIGermanIndexTotalReturn.items():\r\n sum *= math.pow(((val/100)+1),1/10)\r\n return sum-1\r\n\r\ndef percentile(x):\r\n percent = int((len(MSCIGermanIndexTotalReturn) + 1) * x / 100)\r\n srt = list(sorted(MSCIGermanIndexTotalReturn.values()))\r\n Px = srt[percent-1] + x / 100 * (srt[percent] - srt[percent-1])\r\n return Px\r\n\r\ndef mean_2():\r\n sum = 0\r\n for key,val in MSCIGermanIndexTotalReturn.items():\r\n sum += val\r\n return sum / len(MSCIGermanIndexTotalReturn)\r\n\r\ndef MAD():\r\n sum = 0\r\n for key,val in MSCIGermanIndexTotalReturn.items():\r\n sum += abs(val - mean_2())\r\n return sum / len(MSCIGermanIndexTotalReturn)\r\n\r\ndef variance():\r\n sum = 0\r\n for key,val in MSCIGermanIndexTotalReturn.items():\r\n sum += math.pow(val - mean_2(),2)\r\n return sum / (len(MSCIGermanIndexTotalReturn) - 1)\r\n\r\nprint(math.sqrt(variance()))\r\n\r\ndef semiVariance():\r\n sum = 0\r\n count = 0\r\n for val in MSCIGermanIndexTotalReturn.values():\r\n if val < mean_2():\r\n sum += math.pow((val - mean_2()),2)\r\n count += 1\r\n return sum / (count-1)\r\nprint(math.sqrt(semiVariance()))\r\n\r\ndef sampleSkewness():\r\n n = len(MSCIGermanIndexTotalReturn)\r\n Sk = 0\r\n for val in MSCIGermanIndexTotalReturn.values():\r\n Sk += math.pow(val-mean_2(),3)\r\n return (Sk * n) / ((n-1)*(n-2) * math.sqrt(variance())**3)\r\n\r\ndef excessKurtosis():\r\n n = len(MSCIGermanIndexTotalReturn)\r\n Ke = 0\r\n for val in MSCIGermanIndexTotalReturn.values():\r\n Ke += math.pow(val - mean_2(),4)\r\n Ke /= math.sqrt(variance()) ** 4\r\n Ke *= n * (n+1) / ((n-1)*(n-2)*(n-3))\r\n return Ke - ((3 * math.pow((n-1),2)) / ((n -2) * (n-3)))\r\n\r\nJPMGermany57YearGBI = dict(c93 = 15.74, c94 = -3.4, c95 = 18.3, c96 = 8.35, c97 = 6.65, c98 = 12.45, c99 = -2.19, c00 = 7.44, c01 = 5.55, c02 = 10.27)\r\ndef annualReturn():\r\n sum = 0\r\n for val in JPMGermany57YearGBI.values():\r\n sum += val * 0.4\r\n for val in MSCIGermanIndexTotalReturn.values():\r\n sum += val * 0.6\r\n return sum/len(JPMGermany57YearGBI)\r\n\r\ndef mean_3():\r\n sum = 0\r\n for val in JPMGermany57YearGBI.values():\r\n sum += val\r\n return sum / len(JPMGermany57YearGBI)\r\n\r\ndef stdJPM():\r\n sum = 0\r\n for val in JPMGermany57YearGBI.values():\r\n sum += math.pow((val - mean_3()),2)\r\n sum /= len(JPMGermany57YearGBI) - 1\r\n return math.sqrt(sum)\r\n\r\ndef bondPortfolio():\r\n sum = 0\r\n valsOfMSCI = list(MSCIGermanIndexTotalReturn.values())\r\n valsofJPM = list(JPMGermany57YearGBI.values())\r\n for i in range(len(valsofJPM)):\r\n sum += (((valsOfMSCI[i]*0.6)+(valsofJPM[i]*0.4) - annualReturn())**2)\r\n return math.sqrt(sum / (len(valsofJPM)-1))\r\n","sub_path":"Assignment_1.py","file_name":"Assignment_1.py","file_ext":"py","file_size_in_byte":3505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"425468101","text":"import numpy as np\n\ndef slow_fft(signal, nfft=None):\n r\"\"\"\n For the purpose of study, for a faster method to use cache or more optimized \n methods such as radix-2 FFT.\n\n Parameters\n ----------\n signal : tuple or array_like\n Time series of measurement values\n\n Returns\n -------\n s : ndarray\n Frequencies strength\n \"\"\"\n signal = np.asarray(signal, dtype=float)\n if nfft is None:\n nfft = signal.shape[0]\n\n # Adjust\n # according to nyquist theorem, to get frequencies bigger than signal size\n # need to extend the fs (or in other words extend signal) \n if nfft > signal.shape[0]:\n signal = np.append(signal, np.zeros(nfft - signal.shape[0]))\n signal = signal[:nfft]\n\n # Freq segments\n time = np.arange(nfft)\n output = np.zeros(nfft//2 + 1, np.complex)\n\n for f in range(nfft//2 + 1):\n # pi*-2j -> complete rotation\n # f -> frequency 1=one rotation\n # time/n -> transform time to 1 second range\n output[f] = sum(signal * np.exp(-2j * np.pi * f * time / nfft))\n #\n return output\n\n\ndef reduced_slow_fft(signal, nfft=None):\n r\"\"\"\n For the purpose of study, for a faster method to use cache or more optimized \n methods such as radix-2 FFT.\n\n Parameters\n ----------\n signal : tuple or array_like\n Time series of measurement values\n\n Returns\n -------\n s : ndarray\n Frequencies strength\n \"\"\"\n signal = np.asarray(signal, dtype=float)\n if nfft is None:\n nfft = signal.shape[0]\n\n # Adjust\n if nfft > signal.shape[0]:\n signal = np.append(signal, np.zeros(nfft - signal.shape[0]))\n signal = signal[:nfft]\n\n a = np.exp(-2j * np.pi * np.arange(nfft//2 + 1).reshape((nfft//2+1, 1)) * np.arange(nfft) / nfft)\n\n return abs(np.dot(a, signal)) / nfft\n\ndef radix2_fft(x):\n r\"\"\"\n This function computes the one-dimensional discrete Fourier\n Transform (DFT) using Cooley–Tukey FFT Method (radix-2 FFT).\n\n Parameters\n ----------\n signal : tuple or array_like\n Time series of measurement values\n\n Returns\n -------\n s : ndarray\n Frequencies strength\n \"\"\"\n N = len(x)\n if N <= 1: return x\n even = radix2_fft(x[0::2])\n odd = radix2_fft(x[1::2])\n T = [np.exp(-2j*np.pi*k/N)*odd[k] for k in range(N//2)]\n R = [even[k] + T[k] for k in range(N//2)] + [even[k] - T[k] for k in range(N//2)]\n return np.asarray(R, np.float)\n\n\ndef powfft(frames, nfft):\n return 1.0 / nfft * np.square(reduced_slow_fft(frames, nfft))","sub_path":"src/signal_processing/fft.py","file_name":"fft.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"595532708","text":"import statistics as st\r\nimport pandas as pd\r\nimport plotly.express as pe\r\nimport plotly.figure_factory as pf\r\nimport numpy as np\r\n\r\ndata = pd.read_csv(\"college.csv\")\r\nenglishscore = data[\"TOEFL Score\"].tolist()\r\nchanceofadmit = data[\"Chance of Admit \"].tolist()\r\ngraph = pe.scatter(x=englishscore,y=chanceofadmit)\r\ngraph.show()\r\narrayenglish = np.array(englishscore)\r\nadmit= np.array(chanceofadmit)\r\n\r\nm,c = np.polyfit(englishscore, chanceofadmit, 1)\r\ny=[]\r\n\r\nfor x in arrayenglish:\r\n newy=m*x+c\r\n y.append(newy)\r\ngraph1 = pe.scatter(x=arrayenglish, y=admit)\r\ngraph1.update_layout(shapes=[dict(type=\"line\", y0=min(y), y1=max(y), x0=min(englishscore), x1=max(englishscore))])\r\ngraph1.show()\r\n","sub_path":"hw.py","file_name":"hw.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"279292848","text":"# -*- coding:utf8 -*-\nimport pdb\nimport itertools \n\nfrom django.shortcuts import render\nfrom django.http import Http404\nfrom django.http import HttpResponse\nfrom django.conf import settings\nfrom django.db.models import Q\n\nfrom mobile.detectmobilebrowsermiddleware import DetectMobileBrowser\nfrom area.models import Area\nfrom kb.models import Article, FoodLocation\nfrom .models import Words\nfrom basedatas.bd_comm import Common\n\n\ndmb = DetectMobileBrowser()\ncomm = Common()\n\ndef inplace(request ):\n kwargs = {}\n content = {}\n isMobile = dmb.process_request(request)\n if 'homepage_province' in request.GET:\n homepage_province = int(request.GET['homepage_province'].strip())\n # 搜索某地的美食\n if homepage_province -1:\n placeid = homepage_province\n\n if 'homepage_city' in request.GET: \n homepage_city = int(request.GET['homepage_city'].strip())\n \n if homepage_city > -1:\n placeid = homepage_city\n \n if 'homepage_county' in request.GET: \n homepage_county = int(request.GET['homepage_county'].strip()) \n if homepage_county > -1:\n placeid = homepage_county\n\n if 'placeid' in request.GET :\n placeid = int(request.GET['placeid'].strip())\n \n # 用户搜索的时候没有输入关键字,此时应该给出一些默认的推荐的美食\n # return render(request, 'search/inplace.html', content)\n \n content = foods_inplace(placeid, request)\n\n provinces = Area.objects.filter(level = 1)\n content['provinces'] = provinces\n content['rootmedia'] = settings.MEDIA_URL\n content['page_title'] = u'搜索美食'\n if isMobile:\n return render(request, 'search/m_inplace.html', content)\n else:\n return render(request, 'search/inplace.html', content)\n \n \ndef foods_inplace(placeid, request):\n \"\"\"\n 根据地名搜索各地的美食,\n 如果搜索的是县级,且县级没有搜到,则搜索上一级的市级\n 如果搜索的是市级,且市级没有搜到,则搜索上一级的省级\n \"\"\"\n content = {}\n try:\n area = Area.objects.get(pk = placeid)\n\n comm = Common()\n ip = comm.get_client_ip(request)\n if request.user.is_anonymous():\n words = Words.objects.create(area=area,ip=ip)\n else:\n words = Words.objects.create(area=area,ip=ip, user= request.user)\n \n words.save()\n\n content['area'] = area\n if area.level == 2: # 市:搜索该市的所有美食,包括县。\n foodslocation = FoodLocation.objects.filter(Q(area = area) | Q(area__parent_id=area.id))\n elif area.level == 3:\n foodslocation = FoodLocation.objects.filter(area = area) \n elif area.level == 1:\n cities_under = Area.objects.filter(parent_id = area.id)\n foodslocation = []\n for city_under in cities_under:\n foodslocation_item = FoodLocation.objects.filter(Q(area = city_under) | Q(area__parent_id=city_under.id))\n if len(foodslocation_item) > 0:\n foodslocation += foodslocation_item \n \n if area.level == 2 or area.level == 1: \n kbids = []\n new_foodslocation = []\n for foodlocation in foodslocation:\n if foodlocation.kb.id not in kbids:\n kbids.append(foodlocation.kb.id )\n new_foodslocation.append(foodlocation)\n foodslocation = new_foodslocation\n\n content['foodslocation'] = foodslocation\n\n if len(foodslocation ) == 0:\n # 在当地没有搜索出来记录,应该提示给用户,并搜索上一级地方的美食\n # 如县级没有搜出来,就搜市级; 市级没有搜出来,就搜省级\n content['status'] = 1 # 1 代表原来的搜索条件没有搜到记录\n \n elif len(foodslocation) < 13:\n # 搜索出来不到13个记录,为了丰富内容,还应该继续搜索推荐内容\n content['status'] = 2 # 2 代表搜到了记录,但是但是记录比较少\n\n if area.level == 3: # 当前为县级\n # 查找了市级的记录\n city_locations = FoodLocation.objects.filter(area__id = area.parent_id)\n \n # 查找了省级级的记录\n city = Area.objects.get(pk = area.parent_id) # 市\n province = Area.objects.get(pk = city.parent_id) # 省\n province_locations = FoodLocation.objects.filter(area__id = city.parent_id)\n \n cities = Area.objects.filter(parent_id = city.parent_id) # 同级市\n counties = Area.objects.filter(parent_id = area.parent_id) # 同级县\n\n content['city'] = city\n content['cities'] = cities\n content['counties'] = counties\n content['province'] = province\n content['city_locations'] = city_locations\n content['province_locations'] = province_locations\n elif area.level == 2: # 当前为市级\n # 查找了市级的记录\n province = Area.objects.get(pk = area.parent_id) # 省\n # province_locations = FoodLocation.objects.filter(area__id = province.id)\n cities_under = Area.objects.filter(parent_id = area.parent_id)\n province_locations = []\n for city_under in cities_under:\n foodslocation_item = FoodLocation.objects.filter(Q(area = city_under) | Q(area__parent_id=city_under.id))\n if len(foodslocation_item) > 0:\n province_locations += foodslocation_item \n \n kbids = []\n new_foodslocation = []\n for foodlocation in province_locations:\n if foodlocation.kb.id not in kbids:\n kbids.append(foodlocation.kb.id )\n new_foodslocation.append(foodlocation)\n \n province_locations = new_foodslocation\n cities = Area.objects.filter(parent_id = area.parent_id) # 同级县\n content['city'] = area\n content['cities'] = cities\n content['province'] = province\n content['province_locations'] = province_locations\n else: # 省级\n cities = Area.objects.filter(parent_id = area.id) # 该省级所有的市\n content['province'] = area\n content['cities'] = cities\n return content\n\n except Area.DoesNotExist:\n raise Http404\n\n\ndef search_all(request ):\n # 根据关键词搜索地方美食\n content = {}\n isMobile = dmb.process_request(request)\n keywords = ''\n if 'keywords' in request.GET:\n keywords = request.GET['keywords'].strip()\n content['keywords'] = keywords\n\n comm = Common()\n ip = comm.get_client_ip(request)\n \n if request.user.is_anonymous():\n words = Words.objects.create(keywords=keywords,ip=ip)\n else:\n words = Words.objects.create(keywords=keywords,ip=ip, user= request.user)\n \n words.save()\n if keywords:\n kbs = Article.objects.filter(title__contains = keywords) \n #kbs = Article.objects.all()\n kbs.extra(\n select={'strength':'count_read+count_good+count_reply+count_confirm'},\n order_by=('strength')\n )\n else:\n kbs = ''\n content['kbs'] = kbs\n content['rootmedia'] = settings.MEDIA_URL\n provinces = Area.objects.filter(level = 1)\n content['provinces'] = provinces\n content['page_title'] = u'搜索美食'\n if isMobile:\n return render(request, 'search/m_search.html', content)\n else:\n return render(request, 'search/search.html', content)\n \n\ndef test_search(request):\n return render(request, 'search/search.1.html', {})\n\n\n\ndef search_records(request):\n \"\"\"\n 查看用户的搜索记录\n \"\"\"\n isMobile = dmb.process_request(request)\n user = request.user\n if user.is_anonymous():\n return comm.redirect_login_path(isMobile, request)\n \n if not user.is_superuser:\n return HttpResponse('not u')\n \n words = Words.objects.all()\n content = {\n 'words' :words,\n 'page_title': u'搜索记录'\n }\n if isMobile:\n return render(request, 'search/m_searchrecords.html', content)\n else:\n return render(request, 'search/searchrecords.html', content)","sub_path":"wedding/search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"220195687","text":"#Desafio 1\n\ndef format_string(string1):\n string1 = string1.replace(\" \", \"\")\n string1 = string1.lower()\n return string1\n\ndef eh_subsequencia(string1,string2):\n string_test1 = format_string(string1)\n string_test2 = format_string(string2)\n list1 = list(string_test1)\n list2 = list(string_test2)\n \n dict1 = dict()\n dict2 = dict()\n \n for i in range(0, len(list1)):\n dict1[list1[i]] = 0\n \n for i in range(0, len(list2)):\n dict2[list2[i]] = 0\n \n for i in range(0, len(list1)):\n dict1[list1[i]] += 1\n \n for i in range(0, len(list2)):\n dict2[list2[i]] += 1\n \n if(dict1 == dict2):\n return True\n \n keys1 = list(dict1.keys())\n keys2 = list(dict2.keys())\n \n if(set(keys1) < set(keys2) or len(keys2) > len(keys1)):\n return False\n \n for i in range(0, len(keys2)):\n j = keys2[i]\n if dict2[j] > dict1[j]:\n return False\n \n return True\n \nstring1 = str(input())\nstring2 = str(input())\n\nprint(eh_subsequencia(string1,string2))\n","sub_path":"AulasPython/Aula 6/Q5/q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"128276493","text":"#!/usr/bin/python3\n\nfrom PIL import Image, ImageColor\nimport math\n\nf = open('data.dat', 'rb')\nbyte = f.read(2)\ncount = 0\n# im = Image.new('1', (4096,500))\nim = Image.new('1', (4096,500))\ncolor = ImageColor.getcolor('white', '1')\nmin = 99999\nmax = 0\nwhile count<4096:\n y = math.floor(int.from_bytes(byte, \"little\")/1024*500)\n if (y>=500):\n y = 499\n print(\"({}, {})\".format(count, y))\n im.putpixel((count, y), color)\n if (y < min):\n min = y\n if (y > max):\n max = y\n byte = f.read(10)\n byte = f.read(2)\n count += 1\n\n\nprint(\"min {} max {}\".format(min, max))\nim.show()","sub_path":"create_image.py","file_name":"create_image.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"73630889","text":"# Strings in Python can be formatted in a number of different ways.\n# First of all, characters prefixed with a backslash (“\\”) inside a string indicate so-called “escape characters” and represent special formatting instructions.\n# In the example above, for instance, “\\n” indicates a line break. “\\t” on the other hand represents a tab, and “\\\\” is simply the backslash character itself.\n# Next, it is possible to format strings by means of the format function:\nprint(\"{} : {}\".format(\"A\", \"B\"))\nprint(\"{0}, {0}, {1}\".format(\"A\", \"B\"))\nprint(\"{name} wants to eat {food}\".format(name=\"Seppe\", food=\"lasagna\"))\n\n\n# Python provides a way to formatted-output string.\n# Steps:\n# 1. Create a format specification string that includes print fields denoted with the characters {}.\n# 2. App the format method to this format-specification string, specifying the values to be printed as arguments.\n# 3. Print the resulting output string.\nformatStr='The numbers are {} and {}'\nprint(formatStr.format(10,20))\n\n# an example\ndata = [\n (1000, 10),\n (2000, 17),\n (2500, 170),\n (2500, -170),\n]\n# Print the header for reference\nprint('REVENUE | PROFIT | PERCENT')\n\n# This template aligns and displays the data in the proper format\nTEMPLATE = '{revenue:>7,} | {profit:>+7} | {percent:>7.2%}'\n# Print the data rows\nfor revenue, profit in data:\n row = TEMPLATE.format(revenue=revenue, profit=profit, percent=profit / revenue)\n print(row)\n# After the name of the parameter, there's a colon that separates the format definition. Note that all inside the curly brackets.\n# In all columns, the format specification sets the width to seven characters and aligns the values to the right with the > symbol\n\n\n\n# Apart from using the format function illustrated here, python also allows us to format strings using the “%” operator\nprint(\"%s is %s\" % (\"Seppe\", \"happy\"))\n\n\n\n# python 3.6 also added “f-strings” to format strings in a more concise way:\nname='qiaolin'\nage=29\nprint(f'Her name is {name} and she is {age} years old.')","sub_path":"src/basicKB/dev/basics/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"606833069","text":"try:\n import awkward1 as ak\nexcept ImportError:\n import awkward as ak\n\nfrom coffea import processor, hist\nfrom coffea.nanoevents import NanoEventsFactory, NanoAODSchema\nfrom coffea.analysis_tools import Weights, PackedSelection\n\nimport numpy as np\n\n\nclass meta_processor(processor.ProcessorABC):\n def __init__(self, accumulator={}):\n self._accumulator = processor.dict_accumulator( accumulator )\n\n @property\n def accumulator(self):\n return self._accumulator\n\n # we will receive a NanoEvents instead of a coffea DataFrame\n def process(self, events):\n \n output = self.accumulator.identity()\n\n dataset = events.metadata['dataset']\n\n try:\n sumw = sum(events['genEventSumw'])\n sumw2 = sum(events['genEventSumw2'])\n nevents = sum(events['genEventCount'])\n except ValueError:\n # this happens for data\n sumw = 0\n sumw2 = 0\n nevents = 0\n\n\n output[events.metadata['filename']]['sumWeight'] += sumw # naming for consistency...\n output[events.metadata['filename']]['sumWeight2'] += sumw2 # naming for consistency...\n output[events.metadata['filename']]['nevents'] += nevents\n output[events.metadata['filename']]['nChunk'] += 1\n\n output[dataset]['sumWeight'] += sumw\n output[dataset]['sumWeight2'] += sumw2\n output[dataset]['nevents'] += nevents\n output[dataset]['nChunk'] += 1\n \n return output\n\n def postprocess(self, accumulator):\n return accumulator\n\n\ndef get_sample_meta(fileset, samples, workers=10, skipbadfiles=True):\n \n from processor.default_accumulators import add_processes_to_output, add_files_to_output\n\n meta_accumulator = {}\n add_files_to_output(fileset, meta_accumulator)\n add_processes_to_output(fileset, meta_accumulator)\n\n meta_output = processor.run_uproot_job(\n fileset,\n \"Runs\",\n meta_processor(accumulator=meta_accumulator),\n processor.futures_executor,\n {'workers': workers, \"skipbadfiles\":skipbadfiles ,},\n chunksize=100000,\n )\n\n # now clean up the output, get skipped files per data set\n meta = {}\n\n for sample in fileset:\n meta[sample] = meta_output[sample]\n good_files = []\n skipped_files = []\n for rootfile in fileset[sample]:\n if meta_output[rootfile]:\n good_files.append(rootfile)\n else:\n skipped_files.append(rootfile)\n meta[sample]['good_files'] = good_files\n meta[sample]['n_good'] = len(good_files)\n meta[sample]['bad_files'] = skipped_files\n meta[sample]['n_bad'] = len(skipped_files)\n meta[sample]['xsec'] = samples[sample]['xsec']\n\n return meta\n\n\nif __name__ == '__main__':\n\n from Tools.helpers import get_samples\n from Tools.config_helpers import redirector_ucsd, redirector_fnal\n from Tools.nano_mapping import make_fileset, nano_mapping\n\n \n samples = get_samples()\n\n fileset = make_fileset(['QCD'], samples, redirector=redirector_ucsd, small=False)\n\n meta = get_sample_meta(fileset)\n\n import pandas as pd\n df = pd.DataFrame(meta)\n print (df.transpose())\n","sub_path":"processor/meta_processor.py","file_name":"meta_processor.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"124605837","text":"\n\nfrom xai.brain.wordbase.nouns._gibe import _GIBE\n\n#calss header\nclass _GIBED(_GIBE, ):\n\tdef __init__(self,): \n\t\t_GIBE.__init__(self)\n\t\tself.name = \"GIBED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"gibe\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_gibed.py","file_name":"_gibed.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"101619555","text":"# Escreva um programa que resolva uma equação de segundo grau.\n\n# x=-b+- raiz quadra de delta dividido por 2xA\n# delta = b ao quadrado - 4xAxC\n\nfrom math import sqrt\n\na = input(\"Valor de A: \")\nb = input(\"Valor de B: \")\nc = input(\"Valor de C: \")\n\na = int(a)\nb = int(b)\nc = int(c)\n\ndelta = b ** 2 - 4 * a * c\nraiz_delta = sqrt(delta)\n\nx1 = (-b + raiz_delta) / (2 * a)\nx2 = (-b - raiz_delta) / (2 * a)\n\nprint(\"x +: \", float(x1))\nprint(\"x -: \", float(x2))","sub_path":"Python básico e intermediário/SegundoGrau.py","file_name":"SegundoGrau.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"26177235","text":"import os\nimport schedule\nimport serial\nimport time\nfrom signalrcore.hub_connection_builder import HubConnectionBuilder\n\nhub_connection = HubConnectionBuilder().with_url(\"ws://localhost:5000/gpshub\").build()\n\n# Now consider only type 'GPRMC'\ndef getGpsData():\n if os.path.exists('/dev/ttyACM0') == True:\n ser = serial.Serial('/dev/ttyACM0', 4800, timeout = 10)\n gps = ser.readline()\n return gps\n return \"Invalid Data\"\n\ndef sendData():\n data = getGpsData()\n dataString = str(data, 'utf-8')\n if (dataString.startswith('$GPRMC')):\n hub_connection.send(\"SendDataAsync\", [\"8\", dataString])\n\ndef main():\n schedule.every(2).seconds.do(sendData)\n\n hub_connection.build()\n hub_connection.on(\"ReceivedData\", print)\n hub_connection.start()\n\n while True:\n schedule.run_pending()\n time.sleep(1)\n \nif __name__ == \"__main__\":\n main()","sub_path":"SmartHelmet-Pi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"282730156","text":"from django.conf.urls import url\nfrom django.contrib import admin\n\nfrom .views import (\n get_home_page,\n get_nav,\n BlogDetailAPIView,\n BlogListAPIView,\n PageHtmlAPIView,\n CategoryListAPIView,\n NavbarAPIView,\n )\n\nurlpatterns = [\n url(r'^home/$', get_home_page, name='home'),\n url(r'^nav/$', get_nav, name='nav'),\n url(r'^blog/$', BlogListAPIView.as_view(), name='list'),\n url(r'^blog/(?P[\\w-]+)/$', BlogDetailAPIView.as_view(), name='detail'),\n url(r'^category/$', CategoryListAPIView.as_view(), name='list'),\n url(r'^page/(?P[\\w-]+)/$', PageHtmlAPIView.as_view(), name='detail'),\n]\n","sub_path":"backend/src/profiles/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306555738","text":"from const import *\n\ndef formatTime(timeString):\n baseString = \"%%{B%s}%%{U%s}%%{+u}%%{A:zenity --calendar &:} %s %%{A}%%{-u}%%{U-}%%{B-}\"\n return baseString % (BLUE_BG, BLUE, timeString)\n\n\ndef formatVolume(volString):\n baseString = \"%%{B%s}%%{U%s}%%{+u}%%{A:cinnamon-settings sound &:} %s %%{A}%%{-u}%%{U-}%%{B-}\"\n result = \"\"\n\n if volString == \"mute\":\n result = \"\\uf224\"\n volume = \"\"\n else:\n volume = int(volString)\n if volume == 0:\n result = \"\\uf026\"\n elif volume < 20:\n result = \"\\uf223\"\n elif volume < 50:\n result = \"\\uf1f9\"\n else:\n result = \"\\uf225\"\n\n result += \" \" + volString\n\n return baseString % (GREEN_BG, GREEN, result)\n\n\ndef formatMusic(musicData):\n if musicData[\"artist\"] is None:\n return \"\"\n \n artist = musicData[\"artist\"]\n title = musicData[\"title\"]\n\n if len(artist) > 15:\n artist = artist[:15] + \"...\"\n if len(title) > 15:\n title = title[:15] + \"...\"\n\n songString = artist + \" - \" + title\n \n if musicData[\"playing\"]:\n songString = \"%{T2}\\uf1c7%{T-} \" + songString\n else:\n songString = \"%{T2}\\uf1b9%{T-} \" + songString\n\n baseString = \"%%{B%s}%%{U%s}%%{+u} %s %%{-u}%%{U-}%%{B-}\"\n return baseString % (RED_BG, RED, songString)\n\n\ndef formatDesktops(desktopData):\n results = {}\n baseString = \"%%{F%s} %s %%{F-}\"\n\n for monitor in MONITORS:\n formattedMonitor = \"\"\n deskNames = sorted(desktopData[monitor], key = lambda x: int(x) if x != '0' else 10)\n\n for name in deskNames:\n desk = desktopData[monitor][name]\n formattedDesk = \"\"\n if desk in \"Oo\": # Occupied (add close command)\n command = \"bspc node @{}\\:.focused -c\".format(name)\n formattedDesk = \"%%{A2:%s:}%%{T4}\\u25CF%%{T-}%%{A}\" % command\n else:\n formattedDesk = \"%{T4}\\u25CB%{T-}\"\n\n # Add focus command regardless of whether it's already focused\n command = \"bspc desktop -f {}\".format(name)\n formattedDesk = \"%%{A:%s:}%s%%{A}\" % (command, formattedDesk)\n\n fgColour = \"\"\n if monitor == desktopData[\"active\"]:\n if desk in \"OF\":\n fgColour = ACTIVE_MON_ACTIVE\n else:\n fgColour = ACTIVE_MON_INACTIVE\n else:\n if desk in \"OF\":\n fgColour = INACTIVE_MON_ACTIVE\n else:\n fgColour = INACTIVE_MON_INACTIVE\n\n formattedMonitor += baseString % (fgColour, formattedDesk)\n\n results[monitor] = formattedMonitor\n\n return results\n\n\ndef formatPanel(volume, time, music, desktops):\n baseString = \"%%{c}%s%%{r} %s %s %s \"\n\n dvi = baseString % (desktops[\"DVI-D-0\"], music, volume, time)\n hdmi = baseString % (desktops[\"HDMI-0\"], music, volume, time)\n\n return \"%%{Sf}%s%%{Sl}%s\" % (dvi, hdmi)\n","sub_path":"formatter.py","file_name":"formatter.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"525285216","text":"def fizzbuzz(n):\n numbers = range(1, n + 1)\n out = [str(i) for i in numbers]\n\n for i in numbers:\n if i % 15 == 0:\n out[i - 1] = 'fizzbuzz'\n elif i % 5 == 0:\n out[i - 1] = 'buzz'\n elif i % 3 == 0:\n out[i - 1] = 'fizz'\n\n return out\n","sub_path":"kata20190128/fizzbuzz.py","file_name":"fizzbuzz.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"567893355","text":"import argparse\nimport datetime\nimport unittest\nimport string\nimport random\nimport logging\n\nimport apache_beam as beam\nfrom apache_beam.options.pipeline_options import PipelineOptions\nfrom apache_beam.options.pipeline_options import SetupOptions\n#from apache_beam.runners.PipelineRunner import PipelineRunner\n\nfrom google.cloud.bigtable.client import Client\nfrom google.cloud.bigtable import row\nfrom google.cloud.bigtable.row_set import RowSet\nfrom beam_bigtable.bigtable import (BigtableConfiguration, BigtableReadConfiguration)\n\n\ndef _generate_mutation_data(row_index):\n row_contents = []\n value = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(100))\n logging.info('Random',value)\n column_family_id = 'cf1'\n start_index = 0\n end_index = row_index\n while start_index < end_index:\n row_values = {}\n start_index += 1\n key = \"beam_key%s\" % ('{0:07}'.format(start_index))\n logging.info(\"key = \",key)\n row_values[\"row_key\"] = key\n #row_values[\"table\"] = \"projects/grass-clump-479/instances/test-sangram-beam/tables/test-beam1\" #'test-beam1' # remove this\n #print row_values[\"table\"], \"____________________________-\"\n row_values[\"row_content\"] = []\n for column_id in range(10):\n row_content = {\n \"column_family_id\": column_family_id,\n \"column_id\": ('field%s' % column_id).encode('utf-8'),\n \"value\": value\n }\n row_values[\"row_content\"].append(row_content)\n #print \"\\n\",row_values[\"row_content\"],\"\\n\"\n #row_values[\"table\"] = \"projects/grass-clump-479/instances/test-sangram-beam/tables/test-beam1\" #'test-beam1' # remove this\n row_values[\"table\"] = \"projects/grass-clump-479/instances/quickstart-instance-php/tables/bigtable-php-table\"\n row_contents.append(row_values)\n logging.info(\"\\n\",row_contents,\"\\n\")\n\n return row_contents\n\n\ndef _generate_max_mutation_value(row_index):\n row_contents = []\n number_of_bytes = 2 * 1024 * 1024\n value = b'1' * number_of_bytes # 2MB of 1's.\n column_family_id = 'cf'\n start_index = 0\n end_index = row_index\n while start_index < end_index:\n row_values = {}\n start_index += 1\n key = \"beam_key%s\" % ('{0:07}'.format(start_index))\n row_values[\"row_key\"] = key\n row_values[\"row_content\"] = []\n for column_id in range(1):\n row_content = {\n \"column_family_id\": column_family_id,\n \"column_id\": ('field%s' % column_id).encode('utf-8'),\n \"value\": value\n }\n row_values[\"row_content\"].append(row_content)\n\n row_contents.append(row_values)\n\n return row_contents\n\n\ndef _get_row_range_with_row_keys(row_index):\n row_set = RowSet()\n start_index = 0\n end_index = row_index\n while start_index < end_index:\n start_index += 1\n key = \"beam_key%s\" % ('{0:07}'.format(start_index))\n row_set.add_row_key(key)\n\n return row_set\n\n\nclass GenerateDirectRows(beam.DoFn):\n \"\"\" Generates an iterator of DirectRow object to process on beam pipeline.\n\n \"\"\"\n def process(self, row_values):\n \"\"\" Process beam pipeline using an element.\n\n :type row_value: dict\n :param row_value: dict: dict values with row_key and row_content having\n family, column_id and value of row.\n \"\"\"\n direct_row = row.DirectRow(row_key=row_values[\"row_key\"])\n\n for row_value in row_values[\"row_content\"]:\n direct_row.set_cell(\n row_value[\"column_family_id\"],\n row_value[\"column_id\"],\n row_value[\"value\"],\n datetime.datetime.now())\n\n yield direct_row\n\n\nclass PrintKeys(beam.DoFn):\n def process(self, row):\n return [row.row_key]\n\nclass BigtableBeamProcess():\n\n def __init__(self, PROJECT_ID, INSTANCE_ID, TABLE_ID):\n self.project_id = PROJECT_ID\n self.instance_id = INSTANCE_ID\n self.table_id = TABLE_ID\n\n client = Client(project=PROJECT_ID, admin=True)\n instance = client.instance(INSTANCE_ID)\n table = instance.table(TABLE_ID)\n\n def setUp(self):\n self.rows_to_delete = []\n\n def tearDown(self):\n for row in self.rows_to_delete:\n row.clear()\n row.delete()\n row.commit()\n\n def write_to_table(self, row_count):\n from beam_bigtable.bigtable import WriteToBigtable\n\n beam_options = BigtableConfiguration(self.project_id, self.instance_id, self.table_id)\n\n row_values = _generate_mutation_data(row_count)\n pipeline_options = PipelineOptions()\n with beam.Pipeline(options=pipeline_options) as p:\n (p\n | 'Generate Row Values' >> beam.Create(row_values)\n | 'Generate Direct Rows' >> beam.ParDo(GenerateDirectRows())\n | 'Write to BT' >> beam.ParDo(WriteToBigtable(beam_options)))\n \n result = p.run()\n result.wait_until_finish()\n\n\n def write_to_table_max_mutations(self):\n from beam_bigtable.bigtable import WriteToBigtable\n\n beam_options = BigtableConfiguration(self.project_id, self.instance_id, self.table_id)\n\n row_values = _generate_mutation_data(10000000000)\n pipeline_options = PipelineOptions()\n with beam.Pipeline(options=pipeline_options) as p:\n (p\n | 'Generate Row Values' >> beam.Create(row_values)\n | 'Generate Direct Rows' >> beam.ParDo(GenerateDirectRows())\n | 'Write to BT' >> beam.ParDo(WriteToBigtable(beam_options)))\n\n\n def write_to_table_max_mutation_value(self):\n from beam_bigtable.bigtable import WriteToBigtable\n\n beam_options = BigtableConfiguration(self.project_id, self.instance_id, self.table_id)\n\n row_values = _generate_max_mutation_value(10000)\n pipeline_options = PipelineOptions()\n with beam.Pipeline(options=pipeline_options) as p:\n (p\n | 'Generate Row Values' >> beam.Create(row_values)\n | 'Generate Direct Rows' >> beam.ParDo(GenerateDirectRows())\n | 'Write to BT' >> beam.ParDo(WriteToBigtable(beam_options)))\n\n def read_rows(self, argv=[]):\n from beam_bigtable.bigtable import ReadFromBigtable\n from apache_beam.options.pipeline_options import DebugOptions\n \n argv.extend([\n '--experiments=beam_fn_api',\n # '--runner=direct',\n '--project=grass-clump-479',\n '--requirements_file=requirements.txt',\n '--runner=dataflow',\n '--staging_location=gs://juantest/stage',\n '--temp_location=gs://juantest/temp',\n \"--setup_file=./beam_bigtable/setup.py\",\n \"--extra_package=./beam_bigtable/dist/beam_bigtable-0.1.2.tar.gz\"\n ])\n \n parser = argparse.ArgumentParser()\n known_args, pipeline_args = parser.parse_known_args(argv)\n\n config = BigtableReadConfiguration(self.project_id, self.instance_id, self.table_id)\n read_from_bigtable = ReadFromBigtable(config)\n pipeline_options = PipelineOptions(pipeline_args)\n # pipeline_options.view_as(SetupOptions).save_main_session = True\n debug_options = pipeline_options.view_as(DebugOptions)\n \n logging.info(debug_options)\n\n arg_output = 'gs://juantest/results/one_output'\n with beam.Pipeline(options=pipeline_options) as p:\n get_data = (p \n | 'Read Rows' >> beam.io.Read(read_from_bigtable)\n | 'Print keys' >> beam.ParDo( PrintKeys() )\n )\n get_data | 'write' >> beam.io.WriteToText( arg_output )\n\n result = p.run()\n result.wait_until_finish()\n\n\n def read_rows_with_row_set(self):\n from beam_bigtable.bigtable import ReadFromBigtable\n beam_options = BigtableConfiguration(self.project_id, self.instance_id, self.table_id)\n bigtable_read_configuration = BigtableReadConfiguration(\n beam_options,\n row_set=_get_row_range_with_row_keys\n )\n pipeline_options = PipelineOptions()\n with beam.Pipeline(options=pipeline_options) as p:\n rows = (p | 'Read Rows' >> beam.io.Read(ReadFromBigtable(\n bigtable_read_configuration)))\n\n\n\ndef main(args):\n project_id = args.project\n instance_id=args.instance\n table_id = args.table\n\n my_beam = BigtableBeamProcess(project_id, instance_id, table_id)\n \n \n my_beam.write_to_table(5)\n my_beam.read_rows()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n '--project',\n help='Your Cloud Platform project ID.'\n )\n parser.add_argument(\n '--instance',\n help='ID of the Cloud Bigtable instance to connect to.'\n )\n parser.add_argument(\n '--table',\n help='Table to create and destroy.'\n )\n\n args = parser.parse_args()\n main(args)","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":9124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"428996443","text":"# https://www.filmalcinema.com/lista-completa/\nimport re\nfrom collections import defaultdict\nfrom justwatch import JustWatch\nimport json\nimport logging\nimport sys\nfrom datetime import datetime\n\nlogging.basicConfig(\n level=logging.INFO,\n format='%(message)s',\n filename=datetime.now().isoformat(timespec='hours'),\n filemode='w')\n\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\nformatter = logging.Formatter('%(message)s')\nconsole.setFormatter(formatter)\nlogging.getLogger('').addHandler(console)\n\nRELEASE_YEAR = 'original_release_year'\nPROVIDER_ID = 'provider_id'\nOFFERS = 'offers'\nTITLE = 'title'\nURLS = 'urls'\nSTANDARD_WEB = 'standard_web'\n\n# provider id as returned by the JustWatch api\nPRIMEVIDEO = 119\nNETFLIX = 8\n\nMY_TARGET_PROVIDERS = [PRIMEVIDEO, NETFLIX]\n\njust_watch = JustWatch(country='IT')\n\n\ndef parse_movies_textfile():\n year_regex = re.compile(r'^[0-9]{4}$')\n year_movies = defaultdict(list)\n current_year = None\n with open('lista.txt', 'r') as lista_file:\n for content in lista_file.readlines():\n content = content.strip()\n if year_regex.match(content):\n current_year = int(content)\n else:\n year_movies[current_year].append(content)\n return year_movies\n\n\ndef filter_by_available_for_target_providers(year, movies):\n year = int(year)\n good_results = defaultdict(set)\n for movie in movies:\n results = just_watch.search_for_item(query=movie)\n for item in results.get('items'):\n if item.get(RELEASE_YEAR) == year and item.get(\n TITLE).strip().lower() == movie.strip().lower():\n for offer in item.get(OFFERS, []):\n if offer.get(PROVIDER_ID) in MY_TARGET_PROVIDERS:\n good_results[movie].add(\n offer.get(URLS, {}).get(STANDARD_WEB))\n return good_results\n\n\ndef md_format(year, offers):\n result = f\"\\n\\n### {year}\\n\"\n for movie, providers in offers.items():\n for provider in providers:\n provider_name = provider.split('/')[2]\n result += f\"\\n- {movie} [{provider_name}]({provider})\\n\"\n return result\n\n\nif __name__ == '__main__':\n results = {}\n movies = parse_movies_textfile()\n for year in movies.keys():\n results[year] = filter_by_available_for_target_providers(\n year, movies.get(year, []))\n logging.info(md_format(year, results[year]))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"130576792","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport random\r\n\r\ndef bubbleSort(elements):\r\n for i in range(0,len(elements)-1):\r\n count=0\r\n for j in range(0,len(elements)-1):\r\n if(elements[j]>elements[j+1]):\r\n count=elements[j]\r\n elements[j]=elements[j+1]\r\n elements[j+1]=count\r\n else:\r\n continue\r\n return elements\r\ndef avarageValue(elements):\r\n\r\n\treturn sum(elements) / len(elements)\r\n\r\n\r\ndef median(elements):\r\n\r\n\tif (len(elements) % 2 == 0):\r\n\t\treturn (elements[int(len(elements) / 2)] + elements[int(len(elements) / 2) - 1]) / 2\r\n\telse:\r\n\t\treturn elements[int(len(elements) / 2)]\r\n\r\n\r\n\r\n\r\nlength = int(input(\"\\nEnter length of list: \"))\r\n\r\nelements = [random.randint(0, 100) for i in range(length)]\r\n\r\nprint('\\nGenerated list : {}'.format(elements))\r\n\r\nprint('\\nSorted list : {}'.format(elements))\r\n\r\nprint('\\nAvarage value : {}'.format(avarageValue(elements)))\r\n\r\nprint('\\nMedian : {}'.format(median(elements)))\r\n","sub_path":"lab8.3.py","file_name":"lab8.3.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"414953897","text":"from xbmcswift2 import Plugin, xbmcgui\nfrom resources.lib import buzzfeedscraper\n\nPLUGIN_URL = 'plugin://plugin.video.youtube/?action=play_video&videoid'\n\nplugin = Plugin()\n\n\n@plugin.route('/')\ndef main_menu():\n\n items = [\n {\n # AJ+ EN\n 'label': plugin.get_string(30000),\n 'path': plugin.url_for('get_content', url='https://www.youtube.com/channel/UCV3Nm3T-XAgVhKH9jT0ViRg/videos'),\n 'thumbnail': 'https://yt3.ggpht.com/-ZdkPN_aFeYY/AAAAAAAAAAI/AAAAAAAAAAA/Gf2XBEqFddI/s100-c-k-no-rj-c0xffffff/photo.jpg',\n },\n {\n # AJ+ ES\n 'label': plugin.get_string(30001),\n 'path': plugin.url_for('get_content', url='https://www.youtube.com/channel/UCS0lmlVIYVz2qeWlZ_ynIWg/videos'),\n 'thumbnail': 'https://yt3.ggpht.com/-dIY2yXt4g6E/AAAAAAAAAAI/AAAAAAAAAAA/HfkzxVUID2c/s100-c-k-no-rj-c0xffffff/photo.jpg',\n },\n {\n # AJ+ AR\n 'label': plugin.get_string(30002),\n 'path': plugin.url_for('get_content', url='https://www.youtube.com/channel/UC-4KnPMmZzwAzW7SbVATUZQ/videos'),\n 'thumbnail': 'https://yt3.ggpht.com/-Gp4qJ1iZHH4/AAAAAAAAAAI/AAAAAAAAAAA/EO7AVgoVh4Y/s100-c-k-no-rj-c0xffffff/photo.jpg',\n }\n ]\n \n return items\n\n\n@plugin.route('/content/')\ndef get_content(url):\n \n content = buzzfeedscraper.get_latest(url)\n items = []\n\n for i in content:\n items.append({\n 'label': i['label'],\n 'path': PLUGIN_URL + i['path'],\n 'thumbnail': i['thumbnail'],\n 'is_playable': True,\n })\n\n return items\n\n\nif __name__ == '__main__':\n plugin.run()\n","sub_path":"addon.py","file_name":"addon.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"548313713","text":"# -*- coding: utf-8 -*-\nimport io\nimport logging\nimport re\n\nimport boto3\nfrom botocore.exceptions import ClientError\nfrom botocore.client import Config\n\nfrom dask.base import tokenize\nfrom .utils import read_block\n\nlogger = logging.getLogger(__name__)\n\nlogging.getLogger('boto3').setLevel(logging.WARNING)\nlogging.getLogger('botocore').setLevel(logging.WARNING)\n\ndef split_path(path):\n \"\"\"\n Normalise S3 path string into bucket and key.\n\n Parameters\n ----------\n path : string\n Input path, like `s3://mybucket/path/to/file`\n\n Examples\n --------\n >>> split_path(\"s3://mybucket/path/to/file\")\n (\"mybucket\", \"path/to/file\")\n \"\"\"\n if path.startswith('s3://'):\n path = path[5:]\n if '/' not in path:\n return path, \"\"\n else:\n return path.split('/', 1)\n\n\nclass S3FileSystem(object):\n \"\"\"\n Access S3 data as if it were a file system.\n \"\"\"\n _conn = {}\n connect_timeout=5\n read_timeout=15\n\n def __init__(self, anon=True, key=None, secret=None, **kwargs):\n \"\"\"\n Create connection object to S3\n\n Will use configured key/secret (typically in ~/.aws, see the\n boto3 documentation) unless specified\n\n Parameters\n ----------\n anon : bool (True)\n whether to use anonymous connection (public buckets only)\n key : string (None)\n if not anonymouns, use this key, if specified\n secret : string (None)\n if not anonymous, use this password, if specified\n kwargs : other parameters for boto3 session\n \"\"\"\n self.anon = anon\n self.key = key\n self.secret = secret\n self.kwargs = kwargs\n self.connect(anon, key, secret, kwargs)\n self.dirs = {}\n self.s3 = self.connect(anon, key, secret, kwargs)\n\n def connect(self, anon, key, secret, kwargs):\n tok = tokenize(anon, key, secret, kwargs)\n if tok not in self._conn:\n logger.debug(\"Open S3 connection. Anonymous: %s\",\n self.anon)\n if self.anon:\n from botocore import UNSIGNED\n conf = Config(connect_timeout=self.connect_timeout,\n read_timeout=self.read_timeout,\n signature_version=UNSIGNED)\n s3 = boto3.Session().client('s3', config=conf)\n else:\n conf = Config(connect_timeout=self.connect_timeout,\n read_timeout=self.read_timeout)\n s3 = boto3.Session(self.key, self.secret,\n **self.kwargs).client('s3', config=conf)\n self._conn[tok] = s3\n return self._conn[tok]\n\n def __getstate__(self):\n d = self.__dict__.copy()\n del d['s3']\n logger.debug(\"Serialize with state: %s\", d)\n return d\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n self.s3 = self.connect(self.anon, self.key, self.secret, self.kwargs)\n\n def open(self, path, mode='rb', block_size=4*1024**2):\n \"\"\" Open a file for reading or writing\n\n Parameters\n ----------\n path: string\n Path of file on S3\n mode: string\n One of 'rb' or 'wb'\n block_size: int\n Size of data-node blocks if reading\n \"\"\"\n if 'b' not in mode:\n raise NotImplementedError(\"Text mode not supported, use mode='%s'\"\n \" and manage bytes\" % (mode[0] + 'b'))\n return S3File(self, path, mode, block_size=block_size)\n\n def _ls(self, path, refresh=False):\n \"\"\" List files below path\n\n Parameters\n ----------\n path : string/bytes\n location at which to list files\n detail : bool (=True)\n if True, each list item is a dict of file properties;\n otherwise, returns list of filenames\n refresh : bool (=False)\n if False, look in local cache for file details first\n \"\"\"\n path = path.lstrip('s3://').lstrip('/')\n bucket, key = split_path(path)\n if bucket not in self.dirs or refresh:\n if bucket == '':\n # list of buckets\n if self.anon:\n # cannot list buckets if not logged in\n return []\n files = self.s3.list_buckets()['Buckets']\n for f in files:\n f['Key'] = f['Name']\n f['Size'] = 0\n del f['Name']\n else:\n files = self.s3.list_objects(Bucket=bucket).get('Contents', [])\n for f in files:\n f['Key'] = \"/\".join([bucket, f['Key']])\n self.dirs[bucket] = list(sorted(files, key=lambda x: x['Key']))\n files = self.dirs[bucket]\n return files\n\n def ls(self, path, detail=False):\n path = path.lstrip('s3://').rstrip('/')\n try:\n files = self._ls(path)\n except ClientError:\n files = []\n if path:\n pattern = re.compile(path + '/[^/]*.$')\n files = [f for f in files if pattern.match(f['Key']) is not None]\n if not files:\n try:\n files = [self.info(path)]\n except (OSError, IOError):\n files = []\n if detail:\n return files\n else:\n return [f['Key'] for f in files]\n\n def info(self, path):\n if path.startswith('s3://'):\n path = path[len('s3://'):]\n path = path.rstrip('/')\n files = self._ls(path)\n files = [f for f in files if f['Key'].rstrip('/') == path]\n if len(files) == 1:\n return files[0]\n else:\n raise IOError(\"File not found: %s\" %path)\n\n def walk(self, path):\n return [f['Key'] for f in self._ls(path) if f['Key'].rstrip('/'\n ).startswith(path.rstrip('/') + '/')]\n\n def glob(self, path):\n \"\"\"\n Find files by glob-matching.\n\n Note that the bucket part of the path must not contain a \"*\"\n \"\"\"\n path0 = path\n path = path.lstrip('s3://').lstrip('/')\n bucket, key = split_path(path)\n if \"*\" in bucket:\n raise ValueError('Bucket cannot contain a \"*\"')\n if '*' not in path:\n path = path.rstrip('/') + '/*'\n if '/' in path[:path.index('*')]:\n ind = path[:path.index('*')].rindex('/')\n root = path[:ind+1]\n else:\n root = '/'\n allfiles = self.walk(root)\n pattern = re.compile(\"^\" + path.replace('//', '/')\n .rstrip('/')\n .replace('*', '[^/]*')\n .replace('?', '.') + \"$\")\n out = [f for f in allfiles if re.match(pattern,\n f.replace('//', '/').rstrip('/'))]\n if not out:\n out = self.ls(path0)\n return out\n\n def du(self, path, total=False, deep=False):\n if deep:\n files = self.walk(path)\n files = [self.info(f) for f in files]\n else:\n files = self.ls(path, detail=True)\n if total:\n return sum(f.get('Size', 0) for f in files)\n else:\n return {p['Key']: p['Size'] for p in files}\n\n def exists(self, path):\n return bool(self.ls(path))\n\n def cat(self, path):\n with self.open(path, 'rb') as f:\n return f.read()\n\n def tail(self, path, size=1024):\n \"\"\" Return last bytes of file \"\"\"\n length = self.info(path)['Size']\n if size > length:\n return self.cat(path)\n with self.open(path, 'rb') as f:\n f.seek(length - size)\n return f.read(size)\n\n def head(self, path, size=1024):\n \"\"\" Return first bytes of file \"\"\"\n with self.open(path, 'rb', block_size=size) as f:\n return f.read(size)\n\n def read_block(self, fn, offset, length, delimiter=None):\n \"\"\" Read a block of bytes from an S3 file\n\n Starting at ``offset`` of the file, read ``length`` bytes. If\n ``delimiter`` is set then we ensure that the read starts and stops at\n delimiter boundaries that follow the locations ``offset`` and ``offset\n + length``. If ``offset`` is zero then we start at zero. The\n bytestring returned WILL include the end delimiter string.\n\n If offset+length is beyond the eof, reads to eof.\n\n Parameters\n ----------\n fn: string\n Path to filename on S3\n offset: int\n Byte offset to start read\n length: int\n Number of bytes to read\n delimiter: bytes (optional)\n Ensure reading starts and stops at delimiter bytestring\n\n Examples\n --------\n >>> s3.read_block('data/file.csv', 0, 13) # doctest: +SKIP\n b'Alice, 100\\\\nBo'\n >>> s3.read_block('data/file.csv', 0, 13, delimiter=b'\\\\n') # doctest: +SKIP\n b'Alice, 100\\\\nBob, 200\\\\n'\n\n Use ``length=None`` to read to the end of the file.\n >>> s3.read_block('data/file.csv', 0, None, delimiter=b'\\\\n') # doctest: +SKIP\n b'Alice, 100\\\\nBob, 200\\\\nCharlie, 300'\n\n See Also\n --------\n distributed.utils.read_block\n \"\"\"\n with self.open(fn, 'rb') as f:\n size = f.info()['Size']\n if length is None:\n length = size\n if offset + length > size:\n length = size - offset\n bytes = read_block(f, offset, length, delimiter)\n return bytes\n\n\nclass S3File(object):\n \"\"\"\n Cached read-only interface to a key in S3, behaving like a seekable file.\n\n Optimized for a single continguous block.\n \"\"\"\n\n def __init__(self, s3, path, mode='rb', block_size=4*2**20):\n \"\"\"\n Open S3 as a file. Data is only loaded and cached on demand.\n\n Parameters\n ----------\n s3 : boto3 connection\n bucket : string\n S3 bucket to access\n key : string\n S3 key to access\n blocksize : int\n read-ahead size for finding delimiters\n \"\"\"\n self.mode = mode\n if mode != 'rb':\n raise NotImplementedError(\"File mode must be 'rb', not %s\" % mode)\n self.path = path\n bucket, key = split_path(path)\n self.s3 = s3\n self.size = self.info()['Size']\n self.bucket = bucket\n self.key = key\n self.blocksize = block_size\n self.cache = b\"\"\n self.loc = 0\n self.start = None\n self.end = None\n self.closed = False\n\n def info(self):\n return self.s3.info(self.path)\n\n def tell(self):\n return self.loc\n\n def seek(self, loc, whence=0):\n if whence == 0:\n self.loc = loc\n elif whence == 1:\n self.loc += loc\n elif whence == 2:\n self.loc = self.size + loc\n else:\n raise ValueError(\"invalid whence (%s, should be 0, 1 or 2)\" % whence)\n if self.loc < 0:\n self.loc = 0\n return self.loc\n\n def _fetch(self, start, end):\n if self.start is None and self.end is None:\n # First read\n self.start = start\n self.end = end + self.blocksize\n self.cache = _fetch_range(self.s3.s3, self.bucket, self.key,\n start, self.end)\n if start < self.start:\n new = _fetch_range(self.s3.s3, self.bucket, self.key,\n start, self.start)\n self.start = start\n self.cache = new + self.cache\n if end > self.end:\n if end > self.size:\n return\n new = _fetch_range(self.s3.s3, self.bucket, self.key,\n self.end, end + self.blocksize)\n self.end = end + self.blocksize\n self.cache = self.cache + new\n\n def read(self, length=-1):\n \"\"\"\n Return data from cache, or fetch pieces as necessary\n \"\"\"\n if self.mode != 'rb':\n raise ValueError('File not in read mode')\n if length < 0:\n length = self.size\n if self.closed:\n raise ValueError('I/O operation on closed file.')\n self._fetch(self.loc, self.loc + length)\n out = self.cache[self.loc - self.start:\n self.loc - self.start + length]\n self.loc += len(out)\n return out\n\n def flush(self):\n pass\n\n def close(self):\n self.flush()\n self.cache = None\n self.closed = True\n\n def __str__(self):\n return \"\" % (self.bucket, self.key)\n\n __repr__ = __str__\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n self.close()\n\n\n\ndef _fetch_range(client, bucket, key, start, end, max_attempts=10):\n logger.debug(\"Fetch: %s/%s, %s-%s\", bucket, key, start, end)\n for i in range(max_attempts):\n try:\n resp = client.get_object(Bucket=bucket, Key=key,\n Range='bytes=%i-%i' % (start, end - 1))\n return resp['Body'].read()\n except boto3.s3.transfer.S3_RETRYABLE_ERRORS as e:\n logger.debug('Exception %e on S3 download, retrying',\n exc_info=True)\n continue\n except ClientError as e:\n if e.response['Error'].get('Code', 'Unknown') in ['416', 'InvalidRange']:\n return b''\n else:\n raise\n raise RuntimeError(\"Max number of S3 retries exceeded\")\n","sub_path":"distributed/s3fs.py","file_name":"s3fs.py","file_ext":"py","file_size_in_byte":13690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"123606812","text":"\"\"\" A. Арбуз \"\"\"\n\nweight = int(input())\ni = 1\ncount = 0\nwhile i < weight:\n half_1 = weight - i\n half_2 = i\n if (half_1%2 == 0) & (half_2%2 == 0):\n print('YES')\n count += 1\n break\n i += 1\nif (count == 0):\n print('NO')\n\n\n","sub_path":"CodeForsecTasks/Completed/task_4a.py","file_name":"task_4a.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90696030","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='VideoSetting',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('format', models.CharField(help_text='The format the video will be encoded to.', max_length=8, verbose_name='format', choices=[(b'flv', 'Flash'), (b'mp4', 'H264'), (b'ogv', 'Ogg Theora'), (b'webm', 'VP8/WebM')])),\n ('size', models.CharField(help_text='The size the video will be encoded to.', max_length=16, verbose_name='format', choices=[(b'426x240', '240p (426x240)'), (b'640x360', '360p (640x360)'), (b'854x480', '480p (854x480)'), (b'1280x720', '720p (1280x720)'), (b'1920x1080', '1080p (1920x1080)')])),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AlterUniqueTogether(\n name='videosetting',\n unique_together=set([('format', 'size')]),\n ),\n ]\n","sub_path":"osso/videmus/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"599822475","text":"'''\nCreated on Mar 29, 2013\n\n@author: perezrafael\n'''\nimport pandas as pd\nimport numpy as np\nimport matplotlib\n#matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport os.path\nimport sklearn\n\ndef reformat_types(df):\n for column in df.columns:\n if type(df[column][0]) is str:\n new_column = df[[column]].drop_duplicates().reset_index()[[column]]\n new_column = new_column.reset_index()\n if column != 'index':\n new_column.rename(columns={'index' : 'level_0'}, inplace=True) \n df = df.merge(new_column, on=column)\n df = df.drop(column, axis=1)\n df.rename(columns={'level_0' : column}, inplace=True)\n return df\n\ndef _listdir_with_fullpath(d):\n return [os.path.join(d, i) for i in os.listdir(d)]\n\n\n\nif __name__ == '__main__':\n COUNTRY = 143441\n input_dirs = _listdir_with_fullpath('/Users/perezrafael/appannie/data_science/evaluation/data/ios/2013-02/estreal_daily_raw')\n dfs = map(pd.read_csv, input_dirs)\n df = pd.concat(dfs)\n df = df[(df['feed_id']==0) | (df['feed_id']==101)]\n df = reformat_types(df)\n gdf = df.groupby(['category_id', 'date', 'app_id'])\n gdf = gdf.size().reset_index()\n gdf.rename(columns={0:'count'}, inplace=True)\n universals = gdf[gdf['count']>1][['app_id']].drop_duplicates()\n universals['universal'] = 1\n gdf = gdf.merge(universals, on='app_id', how='inner')\n gdf['ratio'] = -1\n gdf['ratio'][(gdf['universal']==1) & (gdf['count']==1)] = 1\n universals = df.merge(gdf, on=['category_id', 'app_id', 'date'], how='inner')\n universals = universals.sort('units', ascending=False)\n #universals = universals[:100000]\n concatenated = pd.DataFrame()\n ugdf = universals[['category_id', 'rank', 'app_id', 'estimate', 'feed_id', 'units', 'date', 'ratio']].groupby('feed_id')\n first_pass = True\n prev_name = ''\n units_first_name = ''\n for name, group in ugdf:\n if first_pass:\n concatenated = group\n first_pass=False\n units_first_name = 'units_%s'%name\n else:\n concatenated = concatenated.merge(group, on=['category_id', 'app_id', 'date'], how='outer', suffixes=['_%s'%prev_name, '_%s'%name])\n concatenated['ratio_%s'%name][np.isnan(concatenated['ratio_%s'%name])] = 0\n concatenated['ratio_%s'%prev_name][np.isnan(concatenated['ratio_%s'%prev_name])] = 0\n #concatenated['ratio_%s'%name][concatenated['ratio_%s'%name]<0] = concatenated['estimate_%s'%name]/(concatenated['estimate_%s'%name] + concatenated['estimate_%s'%prev_name])\n #concatenated['ratio_%s'%prev_name][concatenated['ratio_%s'%prev_name]<0] = concatenated['estimate_%s'%prev_name]/(concatenated['estimate_%s'%name] + concatenated['estimate_%s'%prev_name])\n concatenated['ratio_%s'%name][concatenated['ratio_%s'%name]<0] = concatenated['estimate_%s'%name]/concatenated[units_first_name]\n concatenated['ratio_%s'%prev_name][concatenated['ratio_%s'%prev_name]<0] = concatenated['estimate_%s'%prev_name]/concatenated[units_first_name]\n concatenated['ratio_%s'%name][concatenated['ratio_%s'%name]>1] = 1\n concatenated['ratio_%s'%prev_name][concatenated['ratio_%s'%prev_name]>1] = 1\n concatenated[units_first_name][np.isnan(concatenated[units_first_name])]=concatenated['units_%s'%name][np.isnan(concatenated[units_first_name])]\n concatenated = concatenated.drop('units_%s'%name, axis=1)\n prev_name = name\n concatenated['sbe'] = concatenated['estimate_0'].fillna(0) + concatenated['estimate_101'].fillna(0)\n concatenated['rel_diff'] = ((concatenated['units_0'] - concatenated['sbe']) / concatenated['units_0']).abs() \n concatenated = concatenated[concatenated['rel_diff']<0.01]\n #concatenated['store_id'] = COUNTRY\n concatenated.to_csv('/Users/perezrafael/appannie/data/%s_universal_test.csv'%COUNTRY, index=False)\n universals = universals.drop(['universal', 'estimate'], axis=1)\n gdf = universals.groupby(['app_id', 'category_id'])\n plotting = False\n for name, group in gdf:\n title_str = '%s_%s'%name\n single_feed = group[group['ratio']>0]\n single_feed_size = single_feed.shape[0]\n dual_feed_size = group[group['ratio']<0].shape[0]\n if single_feed_size>0 and dual_feed_size>0 and plotting:\n plt.clf()\n #ax = plt.subplot(111)\n plt.plot(group[group['feed_id']==0]['rank'], group[group['feed_id']==0]['units'], 'b^', alpha=0.9)\n plt.plot(group[group['feed_id']==101]['rank'], group[group['feed_id']==101]['units'], 'bs', alpha=0.9)\n plt.plot(single_feed[single_feed['feed_id']==0]['rank'], single_feed[single_feed['feed_id']==0]['units'], 'r^', alpha=0.9)\n plt.plot(single_feed[single_feed['feed_id']==101]['rank'], single_feed[single_feed['feed_id']==101]['units'], 'rs', alpha=0.9) \n \n #plt.plot(group['date'].median(), group['units'].median(), 'b^', ms=20)\n #plt.plot(group['date'].median(), single_feed['units'].median(), 'r^', ms=20)\n plt.title(title_str)\n #ax.set_xscale('log')\n #ax.set_yscale('log')\n plt.show()\n \n \n","sub_path":"universals/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"239192834","text":"\n\ndef rotate_image_90_degrees(matrix: [[int]]) -> [[int]]:\n size = len(matrix)\n layer_count = int(size / 2)\n\n for layer in range(0, layer_count):\n last = size - layer - 1\n\n for element in range(layer, last):\n offset = element - layer\n\n top = matrix[layer][element]\n right_side = matrix[element][last]\n bottom = matrix[last][last - offset]\n left_side = matrix[last - offset][layer]\n\n matrix[layer][element] = left_side\n matrix[element][last] = top\n matrix[last][last - offset] = right_side\n matrix[last - offset][layer] = bottom\n return matrix\n","sub_path":"multi_dimensional_arrays/rotate_image.py","file_name":"rotate_image.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"553317366","text":"import torch\nimport torch.optim as optim\nimport numpy as np\nfrom functools import reduce\nfrom operator import add\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nfrom tensorboardX import SummaryWriter\n\nwriter = SummaryWriter()\n\ncoefficients = [0, 0, -3, 1, 1]\npoly = lambda x: reduce(add, [c * x ** i for i, c in enumerate(coefficients)])\n\nX = np.linspace(-2, 2, 100)\nY = poly(X)\n\nymean = np.mean(Y)\nystd = np.std(Y)\nY = (Y - ymean) / ystd\n\nxmean = np.mean(X)\nxstd = np.std(X)\nX = (X - xmean) / xstd\n\n\n# plt.plot(X, y)\n# plt.show()\n\nclass FullyConnectedNet(nn.Module):\n def __init__(self):\n super(FullyConnectedNet, self).__init__()\n self.fc1 = nn.Linear(4, 1)\n\n def forward(self, x):\n x = self.fc1(x)\n return x\n\n\nif __name__ == '__main__':\n\n net = FullyConnectedNet()\n optimizer = optim.Adam(net.parameters(), lr=0.001)\n criterion = nn.MSELoss()\n n_epoch = 1000\n\n for epoch in range(n_epoch):\n epoch_loss = 0.0\n for i in range(X.shape[0]):\n x = torch.tensor([X[i] ** j for j in range(1, 5)])\n y = torch.tensor(Y[i])\n\n output = net(x)\n loss = criterion(output, y)\n epoch_loss += loss.item()\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n print(f\"epoch:{epoch + 1},loss:{epoch_loss}\")\n writer.add_scalar('data/epoch_loss', epoch_loss, epoch + 1)\n\n torch.save(net, \"model\")\n\n writer.close()\n","sub_path":"regression/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"623354155","text":"# Copyright (c) 2021 Red Hat\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.\nfrom __future__ import absolute_import\n\nimport collections\nimport typing\n\nfrom oslo_log import log\n\nimport tobiko\nfrom tobiko.openstack import octavia\nfrom tobiko.shell import curl\nfrom tobiko.shell import ssh\nfrom tobiko.shell import sh\n\n\nLOG = log.getLogger(__name__)\n\n\ndef check_members_balanced(ip_address: str,\n protocol: str,\n port: int,\n pool_id: str = None,\n members_count: int = None,\n lb_algorithm: str = None,\n requests_count: int = 10,\n connect_timeout: tobiko.Seconds = 10.,\n interval: tobiko.Seconds = 1,\n ssh_client: ssh.SSHClientFixture = None) -> (\n typing.Dict[str, int]):\n\n \"\"\"Check if traffic is properly balanced between members.\"\"\"\n\n test_case = tobiko.get_test_case()\n\n # Getting the members count\n if members_count is None:\n if pool_id is None:\n raise ValueError('Either members_count or pool_id has to be passed'\n ' to the function.')\n\n else: # members_count is None and pool_id is not None\n members_count = len(octavia.list_members(pool_id=pool_id))\n\n last_content = None\n replies: typing.Dict[str, int] = collections.defaultdict(lambda: 0)\n for attempt in tobiko.retry(count=members_count * requests_count,\n interval=interval):\n try:\n content = curl.execute_curl(hostname=ip_address,\n scheme=protocol,\n port=port,\n path='id',\n connect_timeout=connect_timeout,\n ssh_client=ssh_client).strip()\n except sh.ShellCommandFailed as ex:\n if ex.exit_status == 28:\n raise octavia.TrafficTimeoutError(\n reason=str(ex.stderr)) from ex\n else:\n raise ex\n\n replies[content] += 1\n\n if last_content is not None and lb_algorithm == 'ROUND_ROBIN':\n if members_count > 1 and last_content == content:\n raise octavia.RoundRobinException(\n 'Request was forwarded two times to the same host:\\n'\n f'members_count: {members_count}\\n'\n f'expected: {last_content}\\n'\n f'actual: {content}\\n')\n\n last_content = content\n\n if attempt.is_last:\n break\n else:\n raise RuntimeError('Broken retry loop')\n\n LOG.debug(f\"Replies counts from load balancer: {replies}\")\n\n # assert that 'members_count' servers replied\n missing_members_count = members_count - len(replies)\n test_case.assertEqual(0, missing_members_count,\n f'Missing replies from {missing_members_count} \"'\n '\"members.')\n\n return replies\n","sub_path":"tobiko/openstack/octavia/_validators.py","file_name":"_validators.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"420834771","text":"\"\"\"\n给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。\n\n示例:\n\n输入: n = 4, k = 2\n输出:\n[\n [2,4],\n [3,4],\n [2,3],\n [1,2],\n [1,3],\n [1,4],\n]\n通过次数110,672提交次数145,990\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/combinations\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\n深度优先搜索,这里不用copy mark向量,因为我把置零的操作放在后面,\n每次更新返回的时候,当前位后面的位都是0.\n\"\"\"\n\n\nfrom typing import *\n\n\nclass Solution:\n def dfs(self, mark: List[int], count: int, k: int, index: int) -> List[List[int]]:\n rtn = []\n if count == k:\n tmp = [i+1 for i in range(len(mark)) if mark[i] == 1]\n rtn.append(tmp)\n return rtn\n if index == len(mark):\n return rtn\n\n mark[index] = 1\n rtn.extend(self.dfs(mark, count + 1, k, index + 1))\n mark[index] = 0\n rtn.extend(self.dfs(mark, count, k, index + 1))\n return rtn\n\n def combine(self, n: int, k: int) -> List[List[int]]:\n mark, count, index = [0 for _ in range(n)], 0, 0\n return self.dfs(mark, count, k, index)\n\n\nif __name__=='__main__':\n s = Solution()\n print(s.combine(4, 2))\n","sub_path":"77_combination.py","file_name":"77_combination.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"570930405","text":"import numpy\nimport os\nimport argparse\n\n\nparser = argparse.ArgumentParser(description=\"Read matrix from a text file, round its values and print to output file\")\nparser.add_argument('--folderOriginalWavs', help='', required=True)\nparser.add_argument('--jsonFile', help='', required=False)\nparser.add_argument('--outputFolder', help='Output file.', required=True)\nargs = parser.parse_args()\n\nif not os.path.exists(args.inputFile):\n print('Input file is invalid.')\n\n\nif args.skipLines != \"\":\n skipLines = int(args.skipLines)\nelse:\n skipLines = 0\n\nmatrix = numpy.loadtxt(args.inputFile,skiprows=skipLines)\nnumpy.around(matrix, decimals=1)\nnumpy.savetxt(args.outputFile, matrix, fmt=\"%0.5f\")\n","sub_path":"round_matrix.py","file_name":"round_matrix.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"501662238","text":"# libraries\nimport utils.file\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n# Variables\nmodel_name = '180914-lstm-128-presumption-test-results'\njson_path = f'../results/{model_name}.json'\n\n# Data\ndata = utils.file.read_json(json_path)\ndf = pd.DataFrame(data)\n\n# multiple line plot\nplt.title(model_name)\nplt.plot('losses', data=df, color='#FF9E9D', linewidth=2)\nplt.plot('accuracies', data=df, color='#7FC7AF', linewidth=2)\nplt.plot('val_losses', data=df, color='#FF3D7F', linewidth=2)\nplt.plot('val_accuracies', data=df, color='#3FB8AF', linewidth=2)\nplt.plot('val_f1s', data=df, color='#F8CA00', linewidth=2)\n\nplt.legend()\nplt.show()\n","sub_path":"bin/keras-plot.py","file_name":"keras-plot.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"489322628","text":"import json\nfrom unittest.mock import patch\n\nfrom django.test import TestCase\n\nfrom orchestra.tests.helpers.notifications import MockMail\nfrom orchestra.tests.helpers.slack import MockSlacker\n\n\nclass OrchestraTestCase(TestCase):\n\n def setUp(self): # noqa\n super(OrchestraTestCase, self).setUp()\n # maxDiff prevents the test runner from suppressing the diffs on\n # assertEquals, which is nice when you have large string comparisons as\n # we do in this test to assert the expected JSON blob responses.\n self.maxDiff = None\n\n # Without patching the slack API calls, the tests hang indefinitely\n # and you'll need to restart your boot2docker.\n self.slack = MockSlacker()\n patcher = patch('orchestra.slack.slacker.Slacker',\n return_value=self.slack)\n patcher.start()\n self.addCleanup(patcher.stop)\n self.addCleanup(self.slack.clear)\n\n # Though mail isn't sent in django tests, we mock out send_mail here to\n # have access to sent messages for testing.\n self.mail = MockMail()\n patcher = patch('orchestra.utils.notifications.send_mail',\n side_effect=self.mail.send_mail)\n patcher.start()\n self.addCleanup(patcher.stop)\n self.addCleanup(self.mail.clear)\n\n def ensure_response(self,\n response,\n expected_json_payload,\n expected_status_code):\n self.assertEquals(response.status_code, expected_status_code)\n returned = json.loads(response.content.decode('utf-8'))\n self.assertEquals(returned,\n expected_json_payload)\n\n def _submit_assignment(self, client, task_id, data=None,\n seconds=1, command='submit'):\n if data is None:\n data = {'test': 'test'}\n request = json.dumps(\n {'task_id': task_id, 'task_data': data, 'command_type': command,\n 'work_time_seconds': seconds})\n\n return client.post(\n '/orchestra/api/interface/submit_task_assignment/',\n request,\n content_type='application/json')\n\n def assertModelInstanceExists(self,\n model_class,\n lookup_attributes,\n check_attributes={}):\n try:\n model_instance = model_class.objects.get(**lookup_attributes)\n except model_class.DoesNotExist:\n self.fail('{} instance not created in database.'\n .format(str(model_class)))\n for attribute_name, expected_value in check_attributes.items():\n self.assertEqual(getattr(model_instance, attribute_name),\n expected_value)\n return model_instance\n\n def assertModelInstanceNotExists(self, model_class, lookup_attributes):\n with self.assertRaises(model_class.DoesNotExist):\n model_class.objects.get(**lookup_attributes)\n","sub_path":"orchestra/tests/helpers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"644604926","text":"\"\"\"\n Finished implementing the function to extract words from a text.\n\"\"\"\nimport re\n\n# Input a text\ncontext = input()\n# Evict \",\", \".\" and so on using ASCII codes\nfor i in range(33, 64):\n context = context.replace(str(chr(i)), '')\nfor i in range(91, 96):\n context = context.replace(str(chr(i)), '')\nfor i in range(123, 127):\n context = context.replace(str(chr(i)), '')\n\n# Replace uppercase letters to lowercase letters.\nfor i in range(65,90):\n context = context.replace(str(chr(i)), str(chr(i+32)))\n\n# Devide context to words\nwords = list(context.split())\nprint(words)\n\n","sub_path":"word_counter.py","file_name":"word_counter.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"195205478","text":"# 파이썬 말뭉치(corpus) 다루기\r\n# 말뭉치 - 자연어 처리를 위한 분류된 언어의 표본집합\r\n# pip install konlpy - 한국어 말뭉치 처리를 위한 패키지 모음\r\n\r\n# Okt (open korean text) 주요 메소드\r\n# pos (문자열, 품사)를 튜플로 반환\r\n# nouns 문자열의 명사 리스트로 반환\r\n\r\nfrom konlpy.tag import Okt\r\n\r\nok = Okt()\r\n# test = \"안녕하세요. 저는 한현진입니다. #패스트 캠퍼스 #패캠 #인강\"\r\n\r\n# # for i in ok.pos(test, norm=True):\r\n# # print(i)\r\n\r\n# for i in ok.pos(test):\r\n# if i[1] == 'Hashtag':\r\n# print(i)\r\n\r\n# 리스트로 반환\r\ntest = \"패스트캠퍼스 패캠 문성재 코딩 프로그래밍\"\r\nfor i in ok.nouns(test):\r\n print(i)","sub_path":"python/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"236460196","text":"# -*- coding: utf-8 -*-\nimport sqlite3\nimport time\nimport os\nimport xlrd\n\nimport configparser\ndef conf(msini):\n confbj=[]\n conf = configparser.ConfigParser()\n conf.read(os.getcwd() + '\\\\db\\\\'+msini, encoding=\"utf-8\")\n in_file = conf.get('filename', 'in')\n out_file = conf.get('filename', 'in')\n sfbj= conf.get('filename', '是否插入')\n confbj.append(in_file)\n confbj.append(out_file)\n confbj.append(sfbj)\n return confbj\n\n\ndef wf_main(msfile):\n mssheets = []\n msfile = os.getcwd() + '\\\\in\\\\' + msfile\n if not os.path.exists(msfile):\n print(\"★★★★★★不存在\" + msfile)\n time.sleep(15)\n return\n wb = xlrd.open_workbook(filename=msfile)\n # 跑表\n mssheets = wb.sheet_names()\n for mssheet in mssheets:\n msfileds = [] # 跑表\n print(mssheet)\n sheet = wb.sheet_by_name(mssheet)\n # 跑字段,建表\n if sheet.ncols > 1:\n sql1 = ''\n sql2 = ''\n bl = []\n for x in range(0, sheet.ncols):\n print(sheet.cell(0, x).value)\n msfileds.append(sheet.cell(0, x).value + str(x))\n bl.append(\"?\")\n # print(msfileds)\n bl = ','.join(bl)\n msfileds = ','.join(msfileds)\n sql1 = \"CREATE TABLE IF NOT EXISTS \" + mssheet + \" ( \" + msfileds + \" ); \"\n sql2 = \"INSERT INTO \" + mssheet + \" VALUES ( \" + bl + \" )\"\n print(sql1)\n cur.execute(sql1)\n for y in range(1, sheet.nrows):\n cur.execute(sql2, tuple(sheet.row_values(y)))\n print(sheet.row_values(y))\n conn.commit()\n\nif __name__ == '__main__':\n start = time.time()\n\n msini = \"config.ini\"\n confh=conf(msini)\n print(confh)\n msfile =confh[0]\n if confh[2]=='否':\n if os.path.exists(os.getcwd() + '\\\\db\\\\myanswer.db'):\n os.remove(os.getcwd() + '\\\\db\\\\myanswer.db')\n\n print('开始时间:' + time.strftime(\"%Y_%m-%d %H:%M:%S\", time.localtime()))\n ldb = os.getcwd() + '\\\\db\\\\myanswer.db'\n conn = sqlite3.connect(ldb)\n cur = conn.cursor()\n wf_main(msfile)\n conn.close()\n end = time.time()\n print('完成时间:' + time.strftime(\"%Y_%m-%d %H:%M:%S\", time.localtime()))\n lasttime = int((end - start))\n print('耗时' + str(lasttime) + '秒')\n\n\n\n\n\n\n","sub_path":"EXCEL导入sql.py","file_name":"EXCEL导入sql.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"65123007","text":"#!/usr/bin/python3\r\n#By Steven Feng and Ayush Ghosh\r\nfrom state import State\r\nfrom airplane_objects import radio, motors, i2c_sensors\r\nimport time\r\nimport sys\r\nimport os\r\nimport logging\r\n#TODO: Implement autonomous states\r\n#Joystick button indexes\r\nLB = 7\r\nRB = 6\r\nmotorDisable = 5\r\nmotorEnable = 4\r\nX = 3\r\nY = 2\r\nA = 1\r\nB = 0\r\n\r\nARM_TIME_OUT = 12 # Number of messages before arm sequence resets\r\n\r\n#bit8 bit7 bit6 bit5 bit4 bit3 bit2 bit1\r\n#LB RB view selec X Y A B\r\n\r\n\r\n# 1 idle\r\n# 2 standby\r\n# 3 cruise\r\n# 4 emergency\r\n# 5 level flight\r\n# 6 autonomous takeoff\r\n# 7 autonomous land\r\nclass IdleState (State):\r\n def on_event(self, event):\r\n if (event == \"EngOnBtn\"):\r\n i2c_sensors.calibrate()\r\n time.sleep(6) # wait for madgwick to settle\r\n return StandbyState()\r\n return self\r\n \r\n def run(self):\r\n #filename_time = time.strftime(\"%Y%m%d-%H_%M_%S\")\r\n #log_filename = \"/home/pi/Remote-Controlled-Airplane/logs/\" + filename_time + \".log\"\r\n #os.makedirs(os.path.dirname(log_filename), exist_ok=True)\r\n #logging.basicConfig(filename=log_filename, filemode='a', level=logging.DEBUG)\r\n\r\n print(\"Running IdleState\")\r\n \r\n #localtime = time.asctime( time.localtime(time.time()) )\r\n #logging.debug('%s: Running IdleState', localtime)\r\n \r\n radio.start_radio()\r\n idle = 1\r\n looping = True\r\n while looping:\r\n #btn_num = int(input(\"Enter num: \"))\r\n #radio.receivedMessage = [10, 100, 110, 90, btn_num, 80]\r\n\r\n \r\n t = radio.read_from_radio()\r\n [radio_valid, x] = radio.decode_message()\r\n \r\n if (radio_valid):\r\n print (radio.button_event_state)\r\n if (radio.button_event_state[motorEnable]):\r\n looping = False\r\n return \"EngOnBtn\"\r\n sensor_data = [0.0, 0.0, 0.0, 0.0, 0.0]\r\n try:\r\n sensor_data = i2c_sensors.read_shared_data()\r\n except:\r\n pass\r\n \r\n radio.send_message(idle, sensor_data)\r\n \r\n print (\"Its whack that you are here in this spot in IdleState. Something terribly wrong\")\r\n\r\n localtime = time.asctime( time.localtime(time.time()) )\r\n logging.debug('%s: Its whack that you are here in this spot in IdleState. Something terribly wrong', localtime)\r\n \r\n return \"Error\"\r\n\r\n\r\nclass StandbyState(State):\r\n def on_event(self, event):\r\n if (event == \"Cruise\"):\r\n i2c_sensors.write_sensor_log_status(True)\r\n return CruiseState()\r\n if (event == \"EngOffBtn\"):\r\n return IdleState()\r\n return self\r\n\r\n def reset_arm_sequence(self):\r\n radio.neg_throttle_flag_1 = False\r\n radio.pos_throttle_flag_2 = False\r\n radio.cen_throttle_flag_3 = False\r\n\r\n def run(self):\r\n print(\"Running StandbyState\")\r\n standby = 2\r\n\r\n self.reset_arm_sequence()\r\n time_out_counter = 0\r\n \r\n while (not radio.cen_throttle_flag_3):\r\n try:\r\n #print (radio.neg_throttle_flag_1)\r\n #print (radio.pos_throttle_flag_2)\r\n #print (radio.cen_throttle_flag_3)\r\n\r\n #btn_num = 0 #int(input(\"Enter num: \"))\r\n #throt_num = int(input(\"Enter throttle: \"))\r\n #radio.receivedMessage = [10, 100, throt_num, 90, btn_num, 80]\r\n t = radio.read_from_radio()\r\n\r\n #return aileron, rudder, elevator, escValue, trimoffset\r\n [success, msg_decode] = radio.decode_message()\r\n \r\n if (success):\r\n if (msg_decode != []):\r\n #Write The Motors in order: (aileronValue_, rudderAngle_, elevatorAngle_, escValue_=0, trimoffset)\r\n print(msg_decode[0], msg_decode[1], msg_decode[2], 0, msg_decode[4])\r\n motors.write_motor(msg_decode[0], msg_decode[1], msg_decode[2], 0, msg_decode[4])\r\n\r\n time_out_counter += 1\r\n if (radio.button_event_state[motorDisable]):\r\n return \"EngOffBtn\"\r\n \r\n if time_out_counter >= ARM_TIME_OUT:\r\n self.reset_arm_sequence()\r\n time_out_counter = 0\r\n\r\n if (not radio.neg_throttle_flag_1):\r\n if (msg_decode[3] < 10):\r\n radio.neg_throttle_flag_1 = True\r\n time_out_counter = 0\r\n if (radio.neg_throttle_flag_1):\r\n if (msg_decode[3] < 10):\r\n time_out_counter = 0\r\n \r\n if (msg_decode[3] > 230):\r\n radio.pos_throttle_flag_2 = True\r\n time_out_counter = 0\r\n if (radio.neg_throttle_flag_1 and radio.pos_throttle_flag_2):\r\n if (msg_decode[3] < 10):\r\n radio.cen_throttle_flag_3 = True\r\n time_out_counter = 0\r\n return \"Cruise\"\r\n \r\n sensor_data = [0.0, 0.0, 0.0, 0.0, 0.0]\r\n try:\r\n sensor_data = i2c_sensors.read_shared_data()\r\n except:\r\n pass\r\n \r\n radio.send_message(standby, sensor_data)\r\n\r\n except KeyboardInterrupt:\r\n # quit\r\n sys.exit()\r\n except IndexError:\r\n print (\"Error occured in Standby State, index error\") #log this later, but not print\r\n return \"Error\"\r\n \r\n \r\n \r\n \r\nclass CruiseState (State):\r\n def on_event(self, event):\r\n if (event == \"Lost\"):\r\n motors.write_motor(1, 1, 1, 0, 0)\r\n return EmergencyState()\r\n elif(event == \"EngOffBtn\"):\r\n i2c_sensors.write_sensor_log_status(False)\r\n return StandbyState()\r\n \r\n return self\r\n def run(self):\r\n cruise = 3\r\n try:\r\n print(\"Running CruiseState\")\r\n motors.ESC.arm()\r\n \r\n radio_valid = True\r\n while (radio_valid):\r\n \r\n t = radio.read_from_radio()\r\n \r\n #btn_num = int(input(\"Enter btn num. Entering 400 will eventually start emergency: \"))\r\n #if btn_num == 400:\r\n # radio.receivedMessage = []\r\n #else:\r\n # radio.receivedMessage = [10, 100, 150, 90, btn_num, 80]\r\n\r\n [radio_valid, msg_decode] = radio.decode_message()\r\n \r\n if (radio_valid):\r\n if (radio.button_event_state[motorDisable] and msg_decode[3] < 10):\r\n return \"EngOffBtn\"\r\n \r\n if (msg_decode != []):\r\n #Write The Motors in order: (aileronValue_, rudderAngle_, elevatorAngle_, escValue_, trimoffset)\r\n print (\"Writing to Motors: Ailerons =\", msg_decode[0], \"Rudder =\", msg_decode[1], \"Elevator = \", msg_decode[2], \"ESC = \", msg_decode[3], \"TrimOffset = \", msg_decode[4])\r\n motors.write_motor(msg_decode[0], msg_decode[1], msg_decode[2], msg_decode[3], msg_decode[4])\r\n\r\n else:\r\n return \"Lost\"\r\n \r\n sensor_data = [0.0, 0.0, 0.0, 0.0, 0.0]\r\n try:\r\n sensor_data = i2c_sensors.read_shared_data()\r\n except:\r\n pass\r\n \r\n radio.send_message(cruise, sensor_data)\r\n \r\n except KeyboardInterrupt:\r\n # quit\r\n sys.exit()\r\n\r\n except: \r\n print (\"MAYDAY-MAYDAY, Error occured in Cruise, restarting state\")\r\n return \"Error\"\r\n \r\nclass EmergencyState (State):\r\n\r\n def on_event(self, event):\r\n if (event == \"Signal\"):\r\n return CruiseState()\r\n return self\r\n def run(self):\r\n print(\"Running EmergencyState\")\r\n \r\n emergency = 4\r\n radio_valid = False\r\n motors.write_motor(0, 0, 0, 0, 0)\r\n motors.ESC.stop()\r\n while (not radio_valid):\r\n #WRITE MOTOR ANGLES AND HOPE FOR THE BEST\r\n radio.soft_reset()\r\n \r\n t = radio.read_from_radio()\r\n [radio_valid, msg_decode] = radio.decode_message()\r\n if (radio_valid and msg_decode != []):\r\n return \"Signal\"\r\n\r\n\r\n sensor_data = [0.0, 0.0, 0.0, 0.0, 0.0]\r\n try:\r\n sensor_data = i2c_sensors.read_shared_data()\r\n except:\r\n pass\r\n\r\n radio.send_message(emergency, sensor_data)\r\n \r\n print (\"Its whack that you are here in this spot in EmergencyState. Something terribly wrong\")\r\n return \"Error\"\r\n","sub_path":"State_Machine/statemachine.py","file_name":"statemachine.py","file_ext":"py","file_size_in_byte":9216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"268635678","text":"# ====== Legal notices\n#\n# Copyright (C) 2013 - 2020 GEATEC engineering\n#\n# This program is free software.\n# You can use, redistribute and/or modify it, but only under the terms stated in the QQuickLicense.\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.\n# See the QQuickLicense for details.\n#\n# The QQuickLicense can be accessed at: http://www.qquick.org/license.html\n#\n# __________________________________________________________________________\n#\n#\n# THIS PROGRAM IS FUNDAMENTALLY UNSUITABLE FOR CONTROLLING REAL SYSTEMS !!\n#\n# __________________________________________________________________________\n#\n# It is meant for training purposes only.\n#\n# Removing this header ends your license.\n#\n\nimport argparse as ap\nimport distutils.dir_util as du\nimport os\nimport webbrowser as wb\n\nsimulationsSubdirName = 'simulations'\naccessoriesSubdirName = 'accessories'\nhowtoFileName = 'simpylc_howto.pdf'\n\nclass CommandArgs :\n def __init__ (self):\n self.argParser = ap.ArgumentParser ()\n self.argParser.add_argument ('-a', '--acc', help = \"Copy accessories to current directory\", action = 'store_true')\n self.argParser.add_argument ('-d', '--doc', help = \"Show documentation in default browser\", action = 'store_true')\n self.argParser.add_argument ('-s', '--sim', help = \"Copy example simulations to directory\", action = 'store_true')\n self.__dict__.update (self.argParser.parse_args () .__dict__)\n \n \ncommandArgs = CommandArgs ()\n\nsimulatorDir = os.path.dirname (os.path.realpath (__file__))\ncurrentDir = os.getcwd ()\n\nif commandArgs.acc:\n du.copy_tree (simulatorDir + '/' + accessoriesSubdirName, currentDir + '/' + accessoriesSubdirName)\nelif commandArgs.sim:\n du.copy_tree (simulatorDir + '/' + simulationsSubdirName, currentDir + '/' + simulationsSubdirName)\nelif commandArgs.doc:\n wb.open (simulatorDir + '/' + howtoFileName)\nelse:\n commandArgs.argParser.print_help ()\n \n","sub_path":"simpylc/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"149350084","text":"from ScenarioType import *\n\nclass ScenarioInfoPort(ScenarioInfo):\n def __init__(self):\n super().__init__()\n\n self.fs = None\n self.Labels = [] # list of LabelEntry\n\nscena = ScenarioInfoPort()\n\n'''\n\n\n self.MapName = ''\n self.Location = ''\n self.Unknown_14 = 0\n self.Flags = 0\n self.IncludedScenario = []\n self.NpcNameOffset = 0\n self.ScnInfoOffset = []\n self.ScenaFunctionTable = ScenarioEntry()\n self.UnknownEntry_46 = ScenarioEntry()\n self.Unknown_4A = 0\n self.PreInitSectionIndex = 0\n self.ScnInfoNumber = []\n self.Unknown_51 = b''\n self.Information = b''\n\n'''\n\ndef CreateScenaFile(MapName, Location, Unknown_14, Flags, IncludeList, Unknown_4A, PreInitSectionIndex, Unknown_51, Information):\n scena.MapName = MapName\n scena.Location = Location\n scena.Unknown_14 = Unknown_14\n scena.Flags = Flags\n scena.IncludedScenario = IncludeList\n scena.Unknown_4A = Unknown_4A\n scena.PreInitSectionIndex = PreInitSectionIndex\n scena.Unknown_51 = Unknown_51\n scena.Information = Information\n\n scena.fs = open(MapName + '.bin2', 'wb+')\n scena.fs.seek(0x94)\n\n\ndef Npc(X, Y, Z, Unknown1, Unknown2, Unknown, InitScenaIndex, InitSectionIndex, TalkScenaIndex, TalkSectionIndex, Unknown4, Unknown5):\n\n chrinfo = ScenarioCharInformation()\n\n chrinfo.X = X\n chrinfo.Y = Y\n chrinfo.Z = Z\n chrinfo.Unknown1 = Unknown1\n chrinfo.Unknown2 = Unknown2\n chrinfo.Unknown = Unknown\n chrinfo.InitScenaIndex = InitScenaIndex\n chrinfo.InitSectionIndex = InitSectionIndex\n chrinfo.TalkScenaIndex = TalkScenaIndex\n chrinfo.TalkSectionIndex = TalkSectionIndex\n chrinfo.Unknown4 = Unknown4\n chrinfo.Unknown5 = Unknown5\n\n if len(scena.ScnInfo[SCN_INFO_NPC_POSITION]) == 0:\n scena.ScnInfoOffset[SCN_INFO_NPC_POSITION] = scena.fs.tell()\n\n scena.ScnInfo[SCN_INFO_NPC_POSITION].append(chrinfo)\n\n scena.fs.write(chrinfo.binary())\n\ndef ScpFunction(FunctionLabel):\n scena.ScenaFunctions.append(FunctionLabel)\n scena.fs.write(struct.pack('0:\n facebox[0]=facebox[0]-15\n if (facebox[1]-10)>0:\n facebox[1]=facebox[1]-15\n # if (facebox[1]+facebox[2]+50)0:\n # x1=x1-50\n \n # if x1<0:\n # x1=0\n y1=facebox[1]\n # if (y1-5)>0:\n # y1=y1-50\n # if x1<0:\n # y1=0\n x2=facebox[0]+facebox[2]\n # if (x2+5) vcap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH):\n # x2= vcap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)\n y2=facebox[1]+facebox[3]\n # if ((y2+5) vcap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT):\n # y2= vcap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)\n face_img = frame[y1:y2, x1:x2]\n # box = detector.extract_cnn_facebox(face_img)\n # if box is not None:\n # # Detect landmarks from image of 128x128.\n # face_img = frame[box[1]: box[3],\n # box[0]: box[2]]\n face_img = cv2.resize(face_img, (CNN_INPUT_SIZE, CNN_INPUT_SIZE))\n face_img = cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB)\n # cv2.imshow(\"Preview1\", face_img)\n tm.start()\n marks = mark_detector.detect_marks([face_img])\n tm.stop()\n # cv2.imshow(\"Preview1\", face)\n # Convert the marks locations from local CNN to global image.\n marks *= (facebox[2])\n marks[:, 0] += facebox[0]\n marks[:, 1] += facebox[1]\n\n # Uncomment following line to show raw marks.\n # mark_detecamarks, color=(0, 255, 0))\n\n # Uncomment following line to show facebox.\n # mark_detector.draw_box(frame, [facebox])\n\n # Try pose estimation with 68 points.\n pose = pose_estimator.solve_pose_by_68_points(marks)\n\n # Stabilize the pose.\n # steady_pose = []\n # pose_np = np.array(pose).flatten()\n # for value, ps_stb in zip(pose_np, pose_stabilizers):\n # ps_stb.update([value])\n # steady_pose.append(ps_stb.state[0])\n # steady_pose = np.reshape(steady_pose, (-1, 3))\n # pose_np = np.array(pose).flatten()\n # pose = np.reshape(pose, (-1, 3))\n\n # Uncomment following line to draw pose annotation on frame.\n # print (pose[1])\n # print(pose[1][2]/3.14)\n pose_estimator.draw_annotation_box(\n frame, pose[0], pose[1], color=(255, 128, 128))\n\n # Uncomment following line to draw stabile pose annotation on frame.\n # pose_estimator.draw_annotation_box(\n # frame, steady_pose[0], steady_pose[1], color=(128, 255, 128))\n # break\n\n # Uncomment following line to draw head axes on frame.\n # print(ste)\n pose_estimator.draw_axes(frame, pose[0], pose[1])\n ratio =pose_estimator.cal_eye_index(marks)\n\n side.append((ratio[0]-0.2)/(0.8-0.2)*100-50)\n up.append((pose[1][1]+60)/(100+60)*100-50)\n print(pose[1][1])\n # up.append(pose[1][1])\n # print((pose[1][1]+60)/(-200+60)*100)\n print(pose[1][1])\n\n # image_points=marks\n\n # # (success, rotation_vector, translation_vector) = cv2.solvePnP(model_points, image_points, camera_matrix, dist_coeffs, flags=cv2.CV_ITERATIVE)\n\n # (nose_end_point2D, jacobian) = cv2.projectPoints(np.array([(0.0, 0.0, 1000.0)]), pose[1], pose[0], pose_estimator.ret()[1],pose_estimator.ret()[0])\n # vec,\n # tvec=self.t_vec[0]), int(nose_end_point2D[0][0][1]))\n # print('sdf')\n # cv2.line(frame, p1, p2, (255,0,0), 2)\n except:\n print(\"NONE\")\n # Show preview.\n cv2.imshow(\"Preview\", frame)\n if cv2.waitKey(10) == 27:\n plt.scatter(side, up, s=np.pi*3, c=(0,0,0), alpha=0.5)\n plt.title('Scatter plot')\n plt.xlabel('x')\n plt.ylabel('y')\n plt.show()\n break\n \n # Clean up the multiprocessing process.\n # box_process.terminate()\n # box_process.join()\n \n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Merged.py","file_name":"Merged.py","file_ext":"py","file_size_in_byte":8483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"602466541","text":"packet_flow_files_dir=\"/Users/jubong/git/Tensorflow/deploy/packet_flow_files_dir/\"\n\nprocess_definition_policy = {\n \"web\" : [\"google chrome\",\"chrome.exe\", \"iexplore.exe\", \"firefox\", \"microsoftedge.exe\", \"microsoftedgecp.exe\", False],\n \"dropbox\" : [\"dropbox\", \"dropbox.exe\", False],\n \"kakaotalk\" : [\"kakaotalk\", \"kakaotalk.exe\", False],\n \"slack\" : [\"slack\", \"slack.exe\", False],\n \"mysqlworkbench\" : [\"mysqlworkbench\", \"mysqlworkbench.exe\", False],\n \"teamviewer\" : [\"teamviewer\", \"teamviewer.exe\", \"teamviewer_desktop\", \"teamviewer_service\", \"teamviewer_service.exe\", \"teamviewerd\", False],\n \"com.apple\" : [\"com.apple.geod\", \"com.apple.photomoments\", \"com.apple.safari.safebrowsing.service\", \"com.apple.webkit.networking\", False],\n \"onedrive\" : [\"onedrive\", \"onedrive.exe\", False],\n \"python\" : [\"python\", \"python3.6\", \"python.exe\", False],\n \"skype\" : [\"skype\", \"skype.exe\", \"skypebrowserhost.exe\", \"skypehost.exe\", False],\n \"utorrent\" : [\"utorrent', 'utorrentie.exe\", False],\n \"vnc\" : [\"vncserver\", \"vncviewer\", False],\n \"git\" : [\"git\", \"git-remote-https.exe\", False],\n \"leagueoflegends\" : [\"leagueclient.exe\", \"leagueclientux.exe\", False],\n \"wunderlist\" : [\"wunderlist\", \"wunderlisthelper\", False]\n}\n\n#DB information\nhost = \"218.150.181.120\"\nport = 33060\nuser = \"etri\"\npassword = \"linketri\"\ndb = \"network\"\ncharset = \"utf8\"","sub_path":"deploy/config2.py","file_name":"config2.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"412801845","text":"\"\"\"Entry point for serverside portion of Resonant Lab plugin.\"\"\"\n\nimport os\n\nimport yaml\n\nfrom girder.api import access\nfrom girder.api.describe import Description, describeRoute\nfrom girder.api.rest import Resource\nfrom girder.utility.plugin_utilities import registerPluginWebroot\n\n\nclass ResonantLab(Resource):\n \"\"\"Girder resource definition for Resonant Lab.\"\"\"\n\n _cp_config = {'tools.staticdir.on': True,\n 'tools.staticdir.index': 'index.html'}\n\n def __init__(self, version=None, sha=None):\n \"\"\"Initialize.\"\"\"\n super(ResonantLab, self).__init__()\n\n self.version = version\n self.sha = sha\n\n self.resourceName = 'resonantlab'\n\n self.route('GET', ('build', 'version'), self.get_version)\n self.route('GET', ('build', 'hash'), self.get_hash)\n\n @access.public\n @describeRoute(\n Description('''Get Resonant Lab's current version number.''')\n )\n def get_version(self, params):\n \"\"\"Return Resonant Lab version number.\"\"\"\n return self.version\n\n @access.public\n @describeRoute(\n Description('''Get Resonant Lab's build hash.''')\n )\n def get_hash(self, params):\n \"\"\"Return Resonant Lab git build hash.\"\"\"\n return self.sha\n\n\ndef load(info):\n \"\"\"Girder plugin loading hook for Resonant Lab.\"\"\"\n # Compute full path to plugin's index.html file.\n ResonantLab._cp_config['tools.staticdir.dir'] = os.path.join(info['pluginRootDir'], 'web_external')\n\n # Read the version number from the plugin specification file.\n config_file = os.path.join(info['pluginRootDir'], 'plugin.yml')\n with open(config_file) as f:\n config = yaml.safe_load(f)\n\n # Read the git hash from the hash file.\n git_sha_file = os.path.join(info['pluginRootDir'], 'git-sha')\n with open(git_sha_file) as f:\n git_sha = f.read().strip()\n\n # Instantiate ResonantLab resource and register the plugin with Girder.\n app = info['apiRoot'].resonantlab = ResonantLab(version=config.get('version'), sha=git_sha)\n registerPluginWebroot(app, info['name'])\n","sub_path":"server/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"201551364","text":"from django.shortcuts import render, redirect\nfrom article.preload import *\nfrom django.http import HttpResponse, HttpRequest, HttpResponseRedirect\nfrom article.models import Article, Serverlog, Document,Photos\nfrom article.uploadform import DocumentForm, uploadtoupyun\nfrom datetime import datetime\nfrom django.contrib.syndication.views import Feed\nfrom django.http import Http404\nfrom article.comment import *\n\n\n# Create your views here.\n\ndef showlog(request):\n log_list = Serverlog.objects.all().order_by('-date_time')\n\n paginator = Paginator(log_list, 9)\n page = request.GET.get('page')\n try:\n log_list = paginator.page(page)\n except PageNotAnInteger:\n log_list = paginator.page(1)\n except EmptyPage:\n log_list = paginator.paginator(paginator.num_pages)\n # return render(request,'home.html',{'post_list':post_list})\n return render(request, \"log.html\", {'log_list': log_list})\n\n\ndef upload(request):\n ipAddress = str(request.META.get('REMOTE_ADDR', ''))\n userAgent = str(request.META.get('HTTP_USER_AGENT'))\n log = Serverlog.objects.create(ipAddress=ipAddress, browser=userAgent, source='upload')\n log.save()\n upyunpath=False\n if request.method == 'POST':\n form = DocumentForm(request.POST, request.FILES)\n if form.is_valid():\n if request.session.get('has_updated',False):\n return HttpResponse('You have Updated a file.')\n f = request.FILES['docfile']\n name = f.name\n if request.POST['photo']== '1':\n desc=request.POST['desc']\n #Photos.objects.create(url='https://patrickhao.b0.upaiyun.com/photo/%s' % name,title=name,desc=desc)\n res=uploadtoupyun(f,name,True)\n Photos.objects.create(url='https://patrickhao.b0.upaiyun.com/photo/%s' % name,title=name,desc=desc)\n return HttpResponseRedirect('/photos/')\n upyun = request.POST['upyun']\n if upyun == 'on':\n upyunpath = 'https://patrickhao.b0.upaiyun.com/myblog/%s' % name\n res = uploadtoupyun(f, name,False)\n newdoc = Document(docfile=f,upyunpath=str(upyunpath),ipAddress=ipAddress,userAgent=userAgent)\n newdoc.save()\n\n request.session['has_updated']=True\n else:\n form = DocumentForm()\n documents = Document.objects.all()\n return render(request, 'Box.html', {'documents': documents, 'form': form,'upyunpath':upyunpath})\n\n\ndef Uphoto(request):\n return render(request, 'Box.html')\n\n\nclass RSSFeed(Feed):\n title = \"RSS feed - article\"\n link = \"feeds/posts/\"\n description = \"RSS feed - blog posts\"\n\n def items(self):\n return Article.objects.order_by('-date_time')\n\n def item_title(self, item):\n return item.title\n\n def item_description(self, item):\n return item.content\n\n\ndef detail(request, id):\n if 'maction' in request.POST:\n if request.session.get('has_upvoke%s'%id,False):\n return HttpResponse('Failed')\n p=Article.objects.get(id=request.POST['mid'])\n p.upvoke+=1\n p.save()\n request.session['has_upvoke%s'%id]=True\n return HttpResponse(p.upvoke)\n\n\n id = int(id)\n try:\n post = Article.objects.get(id=str(id))\n post.view += 1\n post.save()\n comment_list = post.comment_set.all()\n\n if id < Article.objects.latest(\"id\").id:\n pre_post = Article.objects.get(id=str(id + 1))\n else:\n pre_post = False\n if id > 1:\n nex_post = Article.objects.get(id=str(id - 1))\n else:\n nex_post = False\n except Article.DoesNotExist:\n raise Http404\n return render(request, 'post.html', {'post': post,\n 'pre_post': pre_post,\n 'nex_post': nex_post,\n 'comment_list': comment_list,\n 'upvoke':post.upvoke})\n\n\ndef archives(request):\n try:\n if 'year' in request.GET:\n year = request.GET['year']\n post_list = Article.objects.filter(date_time__year=year)\n archive_type = 'year'\n elif 'month' in request.GET:\n month = request.GET['month']\n post_list = Article.objects.filter(date_time__month=month)\n archive_type = 'month'\n elif 'day' in request.GET:\n day = request.GET['day']\n post_list = Article.objects.filter(date_time__day=day)\n archive_type = 'day'\n else:\n post_list = Article.objects.all()\n archive_type = 'all'\n except Article.DoesNotExist:\n raise Http404\n return render(request, 'archives.html', {'post_list': post_list,\n 'error': False, 'archive_type': archive_type})\n\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\n\ndef home(request):\n # post_list=Article.objects.all()\n # return render(request,'home.html',{'post_list':post_list})\n ipAddress = str(request.META.get('REMOTE_ADDR', ''))\n userAgent = str(request.META.get('HTTP_USER_AGENT'))\n log = Serverlog.objects.create(ipAddress=ipAddress, browser=userAgent, source='home')\n log.save()\n posts = Article.objects.all()\n for post in posts:\n post.content = preloadMarkdown(post.content)\n paginator = Paginator(posts, 6)\n page = request.GET.get('page')\n try:\n post_list = paginator.page(page)\n except PageNotAnInteger:\n post_list = paginator.page(1)\n except EmptyPage:\n post_list = paginator.paginator(paginator.num_pages)\n return render(request, 'home.html', {'post_list': post_list})\n\n\ndef about_me(request):\n return render(request, 'aboutme.html')\n\n\ndef tag(request, tag):\n try:\n post_list = Article.objects.filter(category__iexact=tag)\n except Article.DoesNotExist:\n raise Http404\n return render(request, 'archives.html', {'post_list': post_list, 'error': False})\n\n\ndef blog_search(request):\n ct = False\n if 'ct' in request.POST:\n ct = request.POST['ct']\n if 's' in request.POST:\n s = request.POST['s']\n if not s:\n return render(request, 'home.html')\n else:\n post_list = Article.objects.filter(title__icontains=s)\n if not ct:\n if len(post_list) == 0:\n return render(request, 'archives.html',\n {'post_list': post_list, 'error': True, 'archive_search': True})\n else:\n return render(request, 'archives.html',\n {'post_list': post_list, 'error': False, 'archive_search': True})\n else:\n post_list2 = Article.objects.filter(content__icontains=s)\n post_list = list(post_list)\n post_list2 = list(post_list2)\n post_list += post_list2\n if len(post_list) == 0:\n return render(request, 'archives.html', {'post_list': post_list, 'error': True})\n else:\n return render(request, 'archives.html', {'post_list': post_list, 'archive_search': True})\n return redirect('/')\n\n\ndef edit(request):\n post = []\n print(request.body)\n #return HttpResponse(str(request.META.get('HTTP_USER_AGENT', '')))\n return render(request,'edit.html',{'post':post,'edit':False})\n\n\ndef editpost(request, id):\n try:\n post = Article.objects.get(id=str(id))\n except DoesNotExist:\n raise Http404\n return render(request, 'edit.html', {'post': post, 'edit': True})\n\n\ndef commitpost(request, id):\n post = Article.objects.get(id=str(id))\n if 'title' in request.POST:\n title = request.POST['title']\n category = request.POST['category']\n content = request.POST['content']\n post.title = title\n post.category = category\n post.content = content\n post.save()\n return HttpResponseRedirect('/%s/' % post.id)\n # return render(request,'post.html',{'post':post})\n else:\n return render(request, 'home.html')\n\n\ndef addpost(request):\n if 'title' in request.POST:\n title = request.POST['title']\n category = request.POST['category']\n content = request.POST['content']\n Article.objects.create(title=title, category=category, content=content).save()\n post = Article.objects.latest(\"id\")\n return HttpResponseRedirect('/%s/' % post.id)\n # return render(request,\"post.html\",{'post':post})\n return render(request, \"home.html\")\n","sub_path":"article/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"498522253","text":"# -*- coding: utf-8 -*-\n\"\"\"config classes and methods for zazu\"\"\"\nimport os\nimport click\nimport git\nimport straight.plugin\nimport yaml\nimport zazu.build_server\nimport zazu.issue_tracker\n\n__author__ = \"Nicholas Wiles\"\n__copyright__ = \"Copyright 2016\"\n\nPROJECT_FILE_NAMES = ['zazu.yaml', '.zazu.yaml']\n\n\ndef issue_tracker_factory(config):\n \"\"\"A factory function that makes and initializes a IssueTracker object from a config\"\"\"\n plugins = straight.plugin.load('zazu.plugins', subclasses=zazu.issue_tracker.IssueTracker)\n known_types = {p.type().lower(): p.from_config for p in plugins}\n if 'type' in config:\n type = config['type']\n type = type.lower()\n if type in known_types:\n return known_types[type](config)\n else:\n raise zazu.ZazuException('{} is not a known issueTracker, please choose from {}'.format(type,\n known_types.keys()))\n else:\n raise zazu.ZazuException('IssueTracker config requires a \"type\" field')\n\n\ndef continuous_integration_factory(config):\n \"\"\"A factory function that makes and initializes a CI object from a config\"\"\"\n plugins = straight.plugin.load('zazu.plugins', subclasses=zazu.build_server.BuildServer)\n known_types = {p.type().lower(): p.from_config for p in plugins}\n if 'type' in config:\n type = config['type']\n type = type.lower()\n if type in known_types:\n return known_types[type](config)\n else:\n raise zazu.ZazuException('{} is not a known CI service, please choose from {}'.format(type,\n known_types.keys()))\n else:\n raise zazu.ZazuException('CI config requires a \"type\" field')\n\n\ndef path_gen(search_paths, file_names):\n \"\"\"Generates full paths given a list of directories and list of file names\"\"\"\n for p in search_paths:\n for f in file_names:\n yield os.path.join(p, f)\n\n\ndef load_yaml_file(search_paths, file_names):\n \"\"\"Load a project yaml file\"\"\"\n searched = path_gen(search_paths, file_names)\n for file in searched:\n try:\n with open(file) as f:\n return yaml.load(f)\n except IOError:\n pass\n searched = path_gen(search_paths, file_names)\n raise click.ClickException('no yaml file found, searched:{}'.format(zazu.util.pprint_list(searched)))\n\n\nclass Config(object):\n\n \"\"\"Holds all zazu configuration info\"\"\"\n\n def __init__(self, repo_root):\n self.repo_root = repo_root\n if self.repo_root:\n self.repo = git.Repo(self.repo_root)\n else:\n self.repo = None\n self._issue_tracker = None\n self._continuous_integration = None\n self._project_config = None\n self._tc = None\n\n def issue_tracker(self):\n if self._issue_tracker is None:\n try:\n self._issue_tracker = issue_tracker_factory(self.issue_tracker_config())\n except zazu.ZazuException as e:\n raise click.ClickException(str(e))\n return self._issue_tracker\n\n def issue_tracker_config(self):\n try:\n return self.project_config()['issueTracker']\n except KeyError:\n raise zazu.ZazuException(\"no issueTracker config found\")\n\n def continuous_integration(self):\n if self._continuous_integration is None:\n try:\n self._continuous_integration = continuous_integration_factory(self.ci_config())\n except zazu.ZazuException as e:\n raise click.ClickException(str(e))\n return self._continuous_integration\n\n def ci_config(self):\n return self.project_config().get('ci', {})\n\n def project_config(self):\n if self._project_config is None:\n self._project_config = load_yaml_file([self.repo_root], PROJECT_FILE_NAMES)\n required_zazu_version = self.zazu_version_required()\n if required_zazu_version and required_zazu_version != zazu.__version__:\n click.secho('Warning: this repo has requested zazu {}, which doesn\\'t match the installed version ({}). '\n 'Use \"zazu upgrade\" to fix this'.format(required_zazu_version, zazu.__version__), fg='red')\n return self._project_config\n\n def style_config(self):\n return self.project_config().get('style', {})\n\n def zazu_version_required(self):\n return self.project_config().get('zazu', '')\n\n def check_repo(self):\n \"\"\"Checks that the config has a valid repo set\"\"\"\n if self.repo_root is None or self.repo is None:\n raise click.UsageError('The current working directory is not in a git repo')\n","sub_path":"zazu/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"547176532","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\ndef error(y, x, t, solution):\n x, t = np.meshgrid(x, t, indexing='ij')\n u = solution(x, t)\n\n return np.max(np.abs(y - u))\n\n\ndef plot(x, t, y):\n fig = plt.figure()\n ax = fig.add_subplot(projection='3d')\n\n x, t = np.meshgrid(x, t, indexing='ij')\n\n ax.plot_surface(x, t, y, cmap='viridis')\n\n ax.set_xlabel('x')\n ax.set_ylabel('t')\n ax.set_zlabel('u')\n ax.view_init(35, 65)\n\n plt.show()\n","sub_path":"Numerical Analysis/term5/lab3/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"202316461","text":"import chainer\nimport chainer.functions as F\nimport chainer.links as L\n\n\nclass Alex(chainer.Chain):\n\n \"\"\"Single-GPU AlexNet without partition toward the channel axis.\"\"\"\n\n insize = 227\n\n def __init__(self):\n super(Alex, self).__init__(\n conv1=L.Convolution2D(3, 96, 11, stride=4),\n conv2=L.Convolution2D(96, 256, 5, pad=2),\n conv3=L.Convolution2D(256, 384, 3, pad=1),\n conv4=L.Convolution2D(384, 384, 3, pad=1),\n conv5=L.Convolution2D(384, 256, 3, pad=1),\n fc6=L.Linear(9216, 4096),\n fc7=L.Linear(4096, 4096),\n fc8=L.Linear(4096, 2),\n )\n self.train = True\n\n def clear(self):\n self.loss = None\n self.accuracy = None\n\n def __call__(self, x, t):\n self.clear()\n h1 = F.max_pooling_2d(F.relu(\n F.local_response_normalization(self.conv1(x))), 3, stride=2)\n h2 = F.max_pooling_2d(F.relu(\n F.local_response_normalization(self.conv2(h1))), 3, stride=2)\n h3 = F.relu(self.conv3(h2))\n h4 = F.relu(self.conv4(h3))\n h5 = F.max_pooling_2d(F.relu(self.conv5(h4)), 3, stride=2)\n h6 = F.dropout(F.relu(self.fc6(h5)), train=self.train)\n h7 = F.dropout(F.relu(self.fc7(h6)), train=self.train)\n h8 = self.fc8(h7)\n \n self.h7 = h7\n self.h8 = h8\n \n self.soft = F.softmax(h8)\n\n self.loss = F.softmax_cross_entropy(h8, t)\n self.accuracy = F.accuracy(h8, t)\n return self.loss\n","sub_path":"program/alex_model_for_classification.py","file_name":"alex_model_for_classification.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"270301590","text":"import wx\n\n ###############################################################################\n ###############################################################################\n\n\nstats = (\n (\"Score\", \"{:.1f}\", lambda team: team[\"score\"]),\n (\"Total Yards\", \"{:.2f}\", lambda team: team[\"totalYds\"]),\n (\"Passing\", \"{:.2f}\", lambda team: team[\"passingYds\"]),\n (\"Rushing\", \"{:.2f}\", lambda team: team[\"rushingYds\"]),\n (\"1st Downs\", \"{:.1f}\", lambda team: team[\"firstDowns\"]),\n (\"3rd %\", \"{}%\", lambda team: int((team[\"thirdDownConv\"] / team[\"thirdDownAtt\"])*100)),\n (\"4th %\", \"{}%\", lambda team: int((team[\"fourthDownConv\"] / team[\"fourthDownAtt\"])*100)),\n (\"Penalties\", \"{:.0f} - {:.0f}\", lambda team: (team[\"penalties\"], team[\"penaltyYds\"])),\n (\"Turnovers\", \"{:.1f}\", lambda team: team[\"turnovers\"]),\n (\"Possession\", \"{}:{}\", lambda team: team[\"possTime\"].split(\":\"))\n )\n\ndef newLabel(parent, font, text=None):\n\n label = wx.StaticText(parent)\n label.SetFont(font)\n if text:\n label.SetLabel(text)\n return label\n\n\n###############################################################################\n###############################################################################\n\n\nclass TeamStatsPanel(wx.Panel):\n\n def __init__(self, parent):\n super().__init__(parent)\n\n labelFont = wx.Font(15, wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)\n\n self.teamLabel = newLabel(self, labelFont)\n self.oppLabel = newLabel(self, labelFont, \"Opponents\")\n\n self.teamStatLabels = []\n self.oppStatLabels = []\n\n mainSizer = wx.BoxSizer(wx.VERTICAL)\n nameSizer = wx.BoxSizer(wx.HORIZONTAL)\n statsSizer = wx.BoxSizer(wx.HORIZONTAL)\n self.teamSizer = wx.GridSizer(len(stats), 2, 5, 5)\n self.oppSizer = wx.GridSizer(len(stats), 2, 5, 5)\n\n nameSizer.Add((0,0), 1, wx.EXPAND)\n nameSizer.Add(self.teamLabel, 1, wx.ALIGN_CENTER)\n nameSizer.Add((0,0), 1, wx.EXPAND)\n nameSizer.Add(self.oppLabel, 1, wx.ALIGN_CENTER)\n nameSizer.Add((0,0), 1, wx.EXPAND)\n statsSizer.Add(self.teamSizer, 1, wx.EXPAND)\n statsSizer.Add(self.oppSizer, 1, wx.EXPAND)\n\n mainSizer.Add(nameSizer, 0, wx.EXPAND | wx.TOP, 10)\n mainSizer.Add(statsSizer, 1, wx.EXPAND | wx.TOP, 30)\n\n self.panel.SetSizer(mainSizer)\n\n self.addLabels()\n\n\n def addLabels(self):\n\n statFont = wx.Font(10, wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)\n\n for stat in [s[label] for s in stats]:\n teamLabel = newLabel(self, statFont, stat)\n oppLabel = newLabel(self, statFont, stat)\n teamStatLabel = newLabel(self, statFont)\n oppStatLabel = newLabel(self, statFont)\n self.teamSizer.Add(teamLabel, wx.ALIGN_CENTER_HORIZONTAL)\n self.teamSizer.Add(teamStatLabel, wx.ALIGN_CENTER_HORIZONTAL)\n self.oppSizer.Add(oppLabel, wx.ALIGN_CENTER_HORIZONTAL)\n self.oppSizer.Add(oppStatLabel, wx.ALIGN_CENTER_HORIZONTAL)\n self.teamStatLabels.append(teamStatLabel)\n self.oppStatLabels.append(oppStatLabel)\n\n\n def setTeamStats(self, teamName, teamStats, oppStats):\n self.teamLabel.SetLabel(teamName)\n for i,stat in enumerate(stats):\n try:\n self.teamStatLabels[i].SetLabel(stat[strFormat].format(*stat[func](teamStats)))\n self.oppStatLabels[i].SetLabel(stat[strFormat].format(*stat[func](oppStats)))\n except TypeError:\n self.teamStatLabels[i].SetLabel(stat[strFormat].format(stat[func](teamStats)))\n self.oppStatLabels[i].SetLabel(stat[strFormat].format(stat[func](oppStats)))\n","sub_path":"Views/Handicapper/TeamStats.py","file_name":"TeamStats.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"251375228","text":"from heapq import heapify, heappushpop, nlargest, nsmallest\n\n\ndef my_nlargest(arr, k):\n kheap = arr[:k]\n heapify(kheap)\n for j in range(k, len(arr)):\n heappushpop(kheap, arr[j])\n kheap.sort()\n\n return kheap[0]\n\ndef my_nsmallest(arr, k):\n for j in range(len(arr)):\n arr[j] *= -1\n\n negkheap = my_nlargest(arr,k)\n for j in range(len(arr)):\n arr[j] *= -1\n return negkheap * -1\n\n\nl = [4,1,6,8,2,10,15,3,6]\nk = 2\n\nprint(my_nlargest(l, k))\nprint(my_nsmallest(l, k))\n\nprint(nlargest(k, l)[-1] == my_nlargest(l, k))\nprint(nsmallest(k, l)[-1] == my_nsmallest(l, k))\n\n\n\n\n\n\n\n\n\n","sub_path":"Trees/Heap/NLargest-NSmallest.py","file_name":"NLargest-NSmallest.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"309273724","text":"import PySimpleGUI as sg\r\n\r\nfrom JsonFiles.JsonFuncs import JsonFuncs\r\nfrom Sounds.SoundFuncs import SoundFuncs\r\n\r\n\r\nclass SettingsPage:\r\n def openSettingsPage(user):\r\n \r\n settingsPageLayout = [[sg.Checkbox(text='Collision Detection', \r\n default= user['collisionDetectionToggle'],\r\n key='-COLLISION DETECTION-', enable_events= True)], \r\n [sg.Checkbox(text= 'Voice Alerts', default= user['voiceToggle'],\r\n key = '-VOICE TOGGLE-', enable_events= True)],\r\n [sg.Button('OK')]]\r\n\r\n settingsPageWindow = sg.Window('Settings', settingsPageLayout,\r\n no_titlebar= False, location=(0,0),\r\n size=(800, 480), finalize= True)\r\n\r\n while True:\r\n event, values = settingsPageWindow.read()\r\n if event == sg.WINDOW_CLOSED or event == 'OK': #if window is closed or if user clickes OK button\r\n SoundFuncs.playSound('Sounds/menuButtonClick.mp3')\r\n JsonFuncs.writeUserData(user) #write updated user data to json\r\n settingsPageWindow.Close()\r\n return user\r\n break\r\n\r\n if event == '-VOICE TOGGLE-': #if user toggles the voice checkbox\r\n SoundFuncs.playSound('Sounds/menuButtonClick.mp3')\r\n user['voiceToggle'] = not user['voiceToggle'] #changes preference in user object\r\n \r\n if event == '-COLLISION DETECTION-': #if user toggles the collision detection checkbox\r\n SoundFuncs.playSound('Sounds/menuButtonClick.mp3')\r\n user['collisionDetectionToggle'] = not user['collisionDetectionToggle'] #changes preference in user object\r\n \r\n\r\n \r\n\r\n\r\n ","sub_path":"SettingsPage.py","file_name":"SettingsPage.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"423866876","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 5 20:57:30 2017\n\n@author: wrm\n\"\"\"\n\nfrom sklearn.linear_model import LogisticRegression\nimport xgboost as xgb\nimport pandas as pd\nimport time \nimport numpy as np\n\nnow = time.time()\ntraincsv = pd.read_csv(\"./pre/train.csv\") # 注意自己数据路径\nadcsv = pd.read_csv(\"./pre/ad.csv\")\nusercsv = pd.read_csv(\"./pre/user.csv\")\npositioncsv = pd.read_csv(\"./pre/position.csv\")\ncategorycsv = pd.read_csv(\"./pre/app_categories.csv\")\nusercatecsv = pd.read_csv(\"./pre/new/usercate.csv\")\nusercatecsv = usercatecsv.drop(['Unnamed: 0'],axis=1)\n \n\ndataset = pd.merge(traincsv, adcsv, how='inner', on='creativeID',sort=False, \n suffixes=('_x', '_y'), copy=True, indicator=False) \ndataset = pd.merge(dataset, usercsv, how='inner', on='userID',sort=False, \n suffixes=('_x', '_y'), copy=True, indicator=False) \ndataset = pd.merge(dataset, positioncsv, how='inner', on='positionID',sort=False, \n suffixes=('_x', '_y'), copy=True, indicator=False) \ndataset = pd.merge(dataset, categorycsv, how='inner', on='appID',sort=False, \n suffixes=('_x', '_y'), copy=True, indicator=False) \ndataset = pd.merge(dataset, usercatecsv, how='inner', on='userID',sort=False, \n suffixes=('_x', '_y'), copy=True, indicator=False) \ndataset = dataset.drop(['conversionTime'],axis=1) \n\ntrain = dataset.iloc[::3,1:]\nlabels = dataset.iloc[::3,0].values\n\n\ntestcsv = pd.read_csv(\"./pre/test.csv\") # 注意自己数据路径\ntests = pd.merge(testcsv, adcsv, how='inner', on='creativeID',sort=False, \n suffixes=('_x', '_y'), copy=True, indicator=False) \ntests = pd.merge(tests, usercsv, how='inner', on='userID',sort=False, \n suffixes=('_x', '_y'), copy=True, indicator=False) \ntests = pd.merge(tests, positioncsv, how='inner', on='positionID',sort=False, \n suffixes=('_x', '_y'), copy=True, indicator=False) \ntests = pd.merge(tests, categorycsv, how='inner', on='appID',sort=False, \n suffixes=('_x', '_y'), copy=True, indicator=False) \ntests = pd.merge(tests, usercatecsv, how='inner', on='userID',sort=False, \n suffixes=('_x', '_y'), copy=True, indicator=False) \n#%%\ndel(traincsv)\ndel(adcsv)\ndel(usercsv)\ndel(positioncsv)\ndel(categorycsv)\ndel(dataset)\ndel(testcsv)\ndel(usercatecsv)\n#test_id = range(len(tests))\ntest = tests.iloc[:,2:]\ntests = tests[['instanceID','label']]\n\ntrain.iloc[:,0] = train.iloc[:,0].values%10000/100*60+train.iloc[:,0]%100 #clickTime中将点击时间在每天的分钟数作为特征\ntest.iloc[:,0] = test.iloc[:,0].values%10000/100*60+test.iloc[:,0]%100\n\n#from collections import Counter\n#cnt = Counter(train.iloc[:,3])\n#indice3 = np.array([2579,3322,2150,4867,3688,675,3347,6086,3150,4250,4657,2426,7619,2831,4455,3789,1400,7149,2891,4292])\n#for i in range(a.shape[0]):\n# if i not in indice3:\n# i = 0\n \nfrom sklearn.preprocessing import OneHotEncoder\nohe = OneHotEncoder()\ncat_train = train.iloc[:,[4,5,10,12,13,14,15,19,20]]\ncat_train_matrix = ohe.fit_transform(cat_train).toarray()\ndel(cat_train)\n\n#from sklearn.feature_extraction import DictVectorizer\n#train.iloc[:,4] = ','.join(str(i) for i in train.iloc[:,4]).split(',')\n#train.iloc[:,5] = ','.join(str(i) for i in train.iloc[:,5]).split(',')\n#train.iloc[:,10] = ','.join(str(i) for i in train.iloc[:,10]).split(',')\n#train.iloc[:,12] = ','.join(str(i) for i in train.iloc[:,12]).split(',')\n#train.iloc[:,13] = ','.join(str(i) for i in train.iloc[:,13]).split(',')\n#train.iloc[:,14] = ','.join(str(i) for i in train.iloc[:,14]).split(',')\n#train.iloc[:,15] = ','.join(str(i) for i in train.iloc[:,15]).split(',')\n#train.iloc[:,19] = ','.join(str(i) for i in train.iloc[:,19]).split(',')\n#train.iloc[:,20] = ','.join(str(i) for i in train.iloc[:,20]).split(',')\n#cat_train = train.iloc[:,[4,5,10,12,13,14,15,19,20]]\n#dict_vec = DictVectorizer(sparse=False)\n#cat_train_matrix = dict_vec.fit_transform(cat_train.to_dict(orient='record'))\n#del(cat_train)\ntrain = np.hstack((train.iloc[:,[0,1,2,3,6,7,8,9,11,16,17,18,21,22,23,24,25,26,\n 27,28,29,30,31,32,33,34]].values,cat_train_matrix))\ndel(cat_train_matrix)\n#train[(train[:,1]==0),1] = np.nan\n\n#test.iloc[:,4] = ','.join(str(i) for i in test.iloc[:,4]).split(',')\n#test.iloc[:,5] = ','.join(str(i) for i in test.iloc[:,5]).split(',')\n#test.iloc[:,10] = ','.join(str(i) for i in test.iloc[:,10]).split(',')\n#test.iloc[:,12] = ','.join(str(i) for i in test.iloc[:,12]).split(',')\n#test.iloc[:,13] = ','.join(str(i) for i in test.iloc[:,13]).split(',')\n#test.iloc[:,14] = ','.join(str(i) for i in test.iloc[:,14]).split(',')\n#test.iloc[:,15] = ','.join(str(i) for i in test.iloc[:,15]).split(',')\n#test.iloc[:,19] = ','.join(str(i) for i in test.iloc[:,19]).split(',')\n#test.iloc[:,20] = ','.join(str(i) for i in test.iloc[:,20]).split(',')\ncat_test = test.iloc[:,[4,5,10,12,13,14,15,19,20]]\ncat_test_matrix = ohe.transform(cat_test).toarray()\n#cat_test_matrix = ohe.transform(cat_test).toarray()\ndel(cat_test)\ntest = np.hstack((test.iloc[:,[0,1,2,3,6,7,8,9,11,16,17,18,21,22,23,24,25,26,\n 27,28,29,30,31,32,33,34]].values,cat_test_matrix))\ndel(cat_test_matrix)\n#%%\ngrd_lm = LogisticRegression()\ngrd_lm.fit(train,labels)\npred = grd_lm.predict_proba(test)[:, 1]\n","sub_path":"腾讯算法大赛_2017_6/lr.py","file_name":"lr.py","file_ext":"py","file_size_in_byte":5305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"108070315","text":"# coding: utf-8\n\nimport xlrd\nimport numpy as np\n\nbook = xlrd.open_workbook('sample.xlsx')\nsheet = book.sheet_by_index(0)\n\ndata = []\nfor row in range(sheet.nrows):\n rows = []\n for col in range(sheet.ncols):\n rows.append(sheet.cell(row,col).value)\n data.append(rows)\n\nmat = np.matrix(data)\nprint(mat)\n","sub_path":"python/xlrd/mat.py","file_name":"mat.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"289731422","text":"#\n# Copyright (c) 2023 Airbyte, Inc., all rights reserved.\n#\n\n\nfrom unittest.mock import MagicMock\n\nfrom airbyte_cdk.sources.streams.http.auth.core import NoAuth\nfrom pytest import fixture\nfrom source_trello.source import Boards, Cards, TrelloStream\n\nfrom .helpers import NO_SLEEP_HEADERS, read_all_records\n\n\n@fixture\ndef patch_base_class(mocker):\n # Mock abstract methods to enable instantiating abstract class\n mocker.patch.object(TrelloStream, \"path\", \"v0/example_endpoint\")\n mocker.patch.object(TrelloStream, \"primary_key\", \"test_primary_key\")\n mocker.patch.object(TrelloStream, \"__abstractmethods__\", set())\n\n\ndef test_request_params(patch_base_class, config):\n stream = TrelloStream(config)\n inputs = {\"stream_slice\": None, \"stream_state\": None, \"next_page_token\": {\"before\": \"id\"}}\n expected_params = {\"limit\": None, \"since\": \"start_date\", \"before\": \"id\"}\n assert stream.request_params(**inputs) == expected_params\n\n\ndef test_next_page_token(patch_base_class, config):\n stream = TrelloStream(config)\n inputs = {\"response\": MagicMock()}\n expected_token = None\n assert stream.next_page_token(**inputs) == expected_token\n\n\ndef test_boards_stream(requests_mock):\n mock_boards_request = requests_mock.get(\n \"https://api.trello.com/1/members/me/boards\",\n headers=NO_SLEEP_HEADERS,\n json=[{\"id\": \"b11111111111111111111111\", \"name\": \"board_1\"}, {\"id\": \"b22222222222222222222222\", \"name\": \"board_2\"}],\n )\n\n config = {\"authenticator\": NoAuth(), \"start_date\": \"2021-02-11T08:35:49.540Z\"}\n stream1 = Boards(config=config)\n records = read_all_records(stream1)\n assert records == [{\"id\": \"b11111111111111111111111\", \"name\": \"board_1\"}, {\"id\": \"b22222222222222222222222\", \"name\": \"board_2\"}]\n\n stream2 = Boards(config={**config, \"board_ids\": [\"b22222222222222222222222\"]})\n records = read_all_records(stream2)\n assert records == [{\"id\": \"b22222222222222222222222\", \"name\": \"board_2\"}]\n\n stream3 = Boards(config={**config, \"board_ids\": [\"not-found\"]})\n records = read_all_records(stream3)\n assert records == []\n\n assert mock_boards_request.call_count == 3\n\n\ndef test_cards_stream(requests_mock):\n mock_boards_request = requests_mock.get(\n \"https://api.trello.com/1/members/me/boards\",\n headers=NO_SLEEP_HEADERS,\n json=[{\"id\": \"b11111111111111111111111\", \"name\": \"board_1\"}, {\"id\": \"b22222222222222222222222\", \"name\": \"board_2\"}],\n )\n\n mock_cards_request_1 = requests_mock.get(\n \"https://api.trello.com/1/boards/b11111111111111111111111/cards/all\",\n headers=NO_SLEEP_HEADERS,\n json=[{\"id\": \"c11111111111111111111111\", \"name\": \"card_1\"}, {\"id\": \"c22222222222222222222222\", \"name\": \"card_2\"}],\n )\n\n mock_cards_request_2 = requests_mock.get(\n \"https://api.trello.com/1/boards/b22222222222222222222222/cards/all\",\n headers=NO_SLEEP_HEADERS,\n json=[{\"id\": \"c33333333333333333333333\", \"name\": \"card_3\"}, {\"id\": \"c44444444444444444444444\", \"name\": \"card_4\"}],\n )\n\n config = {\"authenticator\": NoAuth(), \"start_date\": \"2021-02-11T08:35:49.540Z\"}\n stream1 = Cards(config=config)\n records = read_all_records(stream1)\n assert records == [\n {\"id\": \"c11111111111111111111111\", \"name\": \"card_1\"},\n {\"id\": \"c22222222222222222222222\", \"name\": \"card_2\"},\n {\"id\": \"c33333333333333333333333\", \"name\": \"card_3\"},\n {\"id\": \"c44444444444444444444444\", \"name\": \"card_4\"},\n ]\n\n stream2 = Cards(config={**config, \"board_ids\": [\"b22222222222222222222222\"]})\n records = read_all_records(stream2)\n assert records == [{\"id\": \"c33333333333333333333333\", \"name\": \"card_3\"}, {\"id\": \"c44444444444444444444444\", \"name\": \"card_4\"}]\n\n stream3 = Cards(config={**config, \"board_ids\": [\"not-found\"]})\n records = read_all_records(stream3)\n assert records == []\n\n assert mock_boards_request.call_count == 3\n assert mock_cards_request_1.call_count == 1\n assert mock_cards_request_2.call_count == 2\n","sub_path":"dts/airbyte/airbyte-integrations/connectors/source-trello/unit_tests/test_streams.py","file_name":"test_streams.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"392312359","text":"#!/usr/bin/env python3\n\n\"\"\"\nAggregates images extracted from runs from logs (see analzye_logs package) and sorts them after colors into fixed size\ndatasets.\n\"\"\"\n\nimport pathlib\nimport argparse\nimport shutil\n\n\nclass FidDirectory:\n\n def __init__(self, path: pathlib.Path, restrict_size=-1):\n self.path = path\n self.path.mkdir(parents=True, exist_ok=True)\n self.restrict_size = restrict_size\n\n tmp_path = \"-1\"\n for img_path in self.path.iterdir():\n if not img_path.suffix == \".jpg\":\n continue\n if img_path.stem > tmp_path:\n tmp_path = img_path.stem\n self.counter = int(tmp_path) + 1\n\n if self.full():\n print(\"FidDirectory: already full at {}: {}\".format(self.restrict_size, self.path))\n\n def full(self):\n return 0 < self.restrict_size <= self.counter\n\n def add(self, source_file: pathlib.Path):\n if source_file.suffix != \".jpg\":\n return\n if self.full():\n return\n\n new_file = self.path / \"{0:06d}.jpg\".format(self.counter)\n shutil.copy(source_file.as_posix(), new_file.as_posix())\n self.counter += 1\n\n if self.full():\n print(\"FidDirectory: reached maximum size at {}: {}\".format(self.restrict_size, self.path))\n\n def clear(self):\n for path in self.path.iterdir():\n path.unlink()\n self.counter = 0\n\n\ndef translate_source_dir(name: str) -> str:\n source_encoding = name.split(\"-\")[0]\n return {\n \"b_b\": \"blue\",\n \"b_r\": \"red\",\n \"b_g\": \"green\",\n \"b_w\": \"b_white\",\n \"m_w\": \"m_white\",\n \"l_w\": \"l_white\",\n }[source_encoding]\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--src\", required=True, help=\"source directory containing runs\")\n parser.add_argument(\"--tgt\", required=True, help=\"target directory to store datasets\")\n parser.add_argument(\"--reset\", action=\"store_true\", help=\"reset all directories before copying new files\")\n\n args = parser.parse_args()\n\n src_dir = pathlib.Path(args.src)\n assert src_dir.is_dir()\n tgt_dir = pathlib.Path(args.tgt)\n\n fid_dirs = {\n \"blue\": FidDirectory(tgt_dir / \"blue\", 2048),\n \"red\": FidDirectory(tgt_dir / \"red\", 2048),\n \"green\": FidDirectory(tgt_dir / \"green\", 2048),\n \"m_white\": FidDirectory(tgt_dir / \"m_white\", 2048),\n \"l_white\": FidDirectory(tgt_dir / \"l_white\", 2048),\n \"b_white\": FidDirectory(tgt_dir / \"b_white\", 2048),\n }\n\n if args.reset:\n for fid_dir in fid_dirs.values():\n fid_dir.clear()\n\n for path in src_dir.iterdir():\n tgt_dir_name = translate_source_dir(path.stem)\n for img_path in (path / \"original\").iterdir():\n fid_dirs[tgt_dir_name].add(img_path)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/create_fid_datasets.py","file_name":"create_fid_datasets.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"15859037","text":"import cv2\nimport numpy as np\nimport show_imgs as si\nIMG_PATH = \"../sample_imgs\"\nSKY_LABEL = 1\nGOOSE_LABEL = 2\n\ndef watershed():\n srcimg = cv2.imread(IMG_PATH + \"/wildgoose.jpg\", cv2.IMREAD_COLOR)\n images = {\"original\": srcimg}\n # find apprent background(sky) and wild goose region\n gray = cv2.cvtColor(srcimg, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (3, 3), 0)\n ret, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n images[\"threshold\"] = binary\n app_sky = cv2.erode(binary, kernel, iterations=3)\n images[\"apparent sky\"] = app_sky\n app_goose = cv2.dilate(binary, kernel, iterations=1)\n images[\"apparent wildgoose\"] = app_goose\n images[\"undetermined\"] = cv2.subtract(app_goose, app_sky)\n # create markers and watershed\n markers = np.zeros(gray.shape, dtype=np.int32)\n markers[app_sky > 0] = SKY_LABEL\n markers[app_goose == 0] = GOOSE_LABEL\n markers = cv2.watershed(srcimg, markers)\n # show contours of wild gooses\n labelimg = np.zeros_like(srcimg)\n labelimg[markers == -1, :] = (0, 0, 255) # draw contours\n labelimg[markers == SKY_LABEL, :] = (200, 150, 100)\n labelimg[markers == GOOSE_LABEL, :] = srcimg[markers == GOOSE_LABEL, :]\n images[\"label\"] = labelimg\n result_img = si.show_imgs(images, \"watershed\", 3)\n print((markers == GOOSE_LABEL)[150:160, 120:130])\n\nif __name__ == \"__main__\":\n watershed()\n\n #","sub_path":"opencv-class/segmentation/watershed.py","file_name":"watershed.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"207592771","text":"class Delayed:\n '''\n Creates decorators,\n\n The decorated function should return True/False depending on whether or not it has been activated,\n if true, creates a delay in order to be spammed.\n '''\n wait = 0\n delayed = False\n def __init__(self, delay):\n self.delay = delay\n \n def __call__(self, func):\n def inner(*args, **kwargs):\n if self.delayed:\n self.wait += 1\n if self.wait == self.delay:\n self.delayed = False\n self.wait = 0\n else:\n # first argument if a boolean value of if the tested key was pressed\n executed = func(*args, **kwargs)\n if executed:\n self.delayed = True\n return executed\n return inner\n\nfrom time import time\nimport math\n\ndef cal_angle(p1, p2):\n angle = -math.atan2(p1[1]-p2[1], p1[0]-p2[0])\n angle = 180/3.14 * angle\n return angle\n\ndef mean(array):\n total = 0\n for v in array:\n total += v\n return total/len(array)\n\nclass Counter:\n funcs = {'names':[], 'iterations':[],'time':[]}\n @classmethod\n def call(cls,func):\n cls.funcs['names'].append(func.__name__)\n cls.funcs['iterations'].append(0)\n cls.funcs['time'].append(0)\n index = len(cls.funcs['names'])-1\n \n def inner(*args, **kwargs):\n cls.funcs['iterations'][index] += 1\n st = time()\n r = func(*args, **kwargs)\n cls.funcs['time'][index] += time() - st\n return r\n \n return inner\n @classmethod\n def result(cls):\n print('Result:')\n for i in range(len(cls.funcs['names'])):\n name = cls.funcs['names'][i]\n iteration = cls.funcs['iterations'][i]\n time = cls.funcs['time'][i]\n try:\n performance = time/iteration\n except:\n performance = 0\n \n print(f'{name}: {iteration} mean: {performance:.4f} total:{time:.3f}')\n @classmethod\n def reset(cls):\n cls.funcs['time'] = [0 for _ in cls.funcs['names']]\n cls.funcs['iterations'] = [0 for _ in cls.funcs['names']]\n\n","sub_path":"game/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"556387525","text":"# Copyright (C) 2012 Brian Wesley Baugh\n#\n# This work is licensed under the Creative Commons\n# Attribution-NonCommercial-ShareAlike 3.0 Unported License.\n# To view a copy of this license, visit:\n# http://creativecommons.org/licenses/by-nc-sa/3.0/\nimport ast\nimport datetime\nimport errno\nimport fnmatch\nimport locale\nimport logging\nimport os\nimport pprint\nimport re\nimport sys\nimport time\nimport urllib2\n\ntry:\n from uploader import mail\nexcept ImportError:\n print('Unable to load gmail library. Disabling submitting to TwitPic.')\n mail = None\n\n\nTWITPIC_EMAIL_ADDRESS = '' \nSAVE_LOCATION = '/var/scripts/teen_arrests/generated/' #replace this with whatever directory you want to store the generated data in\n\n# How often to check the City Jail Custody Report webpage\nSECONDS_BETWEEN_CHECKS = 60\n\n# Logging level\nlogging.basicConfig(level=logging.INFO)\n\n\nclass Inmate(object):\n \"\"\"Storage class to hold name, DOB, charge, etc.\n\n The class __init__ will accept all keyword arguments and set them as\n class attributes. In the future it would be a good idea to switch from\n this method to actually specifying each class attribute explicitly.\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"Inits Inmate with all keyword arguments as class attributes.\"\"\"\n setattr(self, 'mug', None)\n for dictionary in args:\n for key in dictionary:\n setattr(self, key, dictionary[key])\n for key in kwargs:\n setattr(self, key, kwargs[key])\n def get_age(self):\n t1 = datetime.datetime.strptime(self.DOB, '%m/%d/%Y')\n t2 = datetime.datetime.strptime(self.arrest, '%m/%d/%Y %H:%M:%S')\n age = int((t2 - t1).days / 365.2425)\n return age\n def get_twitter_message(self):\n \"\"\"Constructs a mug shot caption \"\"\"\n parts = []\n # Append age\n t1 = datetime.datetime.strptime(self.DOB, '%m/%d/%Y')\n t2 = datetime.datetime.strptime(self.arrest, '%m/%d/%Y %H:%M:%S')\n age = int((t2 - t1).days / 365.2425)\n parts.append(str(age) + \" yrs old\")\n # Append bond (if there is data)\n if self.charges:\n bond = 0\n for charge in self.charges:\n if charge['amount']:\n bond += int(float(charge['amount'][1:]))\n if bond:\n locale.setlocale(locale.LC_ALL, '')\n bond = locale.currency(bond, grouping=True)[:-3]\n #parts.append(\"Bond: \" + bond)\n # Append list of charges\n # But first shorten the charge text\n cities = (r'(?:DPD|Denton|Lake Dallas|Frisco|'\n r'Dallas|Corinth|Richardson)*')\n #extras = r'\\s*(?:CO)?\\s*(?:SO)?\\s*(?:PD)?\\s*(?:Warrant)?(?:S)?\\s*/\\s*'\n for charge in self.charges:\n \"\"\"charge['charge'] = re.sub(r'\\A' + cities, # used to be cities + extras,\n '',\n charge['charge'])\"\"\"\n # pad certain characters with spaces to fix TwitPic display\n charge['charge'] = re.sub(r'([<>])', r' \\1 ', charge['charge'])\n # collapse multiple spaces\n charge['charge'] = re.sub(r'\\s{2,}', r' ', charge['charge'])\n parts.append(charge['charge'].lower())\n return ' | '.join(parts)\n\n def __str__(self):\n \"\"\"String representation of the Inmate formatted with pprint.\"\"\"\n return pprint.pformat(dict((k, v) for (k, v) in vars(self).items()\n if k != 'mug'))\n\n def __repr__(self):\n \"\"\"Represent the Inmate as a dictionary, not including the mug shot.\"\"\"\n return str(dict((k, v) for (k, v) in vars(self).items() if k != 'mug'))\n\n\ndef get_jail_report():\n \"\"\"Retrieves the Denton City Jail Custody Report webpage.\"\"\"\n logger = logging.getLogger('JailReport')\n logger.debug(\"Getting Jail Report\")\n # Uncomment to read from file instead of LIVE web page\n## with open('dentonpolice_recent.html') as f:\n## return f.read()\n logger.debug(\"Opening URL\")\n response = urllib2.urlopen('http://dpdjailview.cityofdenton.com/')\n logger.debug(\"Reading page\")\n html = response.read().decode('utf-8')\n with open(SAVE_LOCATION + 'recent.html', mode='w') as f:\n f.write(html)\n return html\n\n\ndef get_mug_shots(inmates):\n \"\"\"Retrieves the mug shot for each Inmate and stores it in the Inmate.\"\"\"\n logger = logging.getLogger('get_mug_shots')\n logger.debug(\"Getting mug shots\")\n for inmate in inmates:\n try:\n logger.debug(\"Opening mug shot URL (ID: {})\".format(inmate.id))\n response = urllib2.urlopen(\"http://dpdjailview.cityofdenton.com/ImageHandler.ashx?type=image&imageID=\" + inmate.id)\n inmate.mug = response.read()\n except urllib.error.HTTPError as e:\n if e.code == 500:\n logger.warning('Unable to retrieve: Internal Server Error '\n '(ID: %s)', inmate.id)\n inmate.mug = None\n\n\ndef save_mug_shots(inmates):\n \"\"\"Saves the mug shot image data to a file for each Inmate.\n\n Mug shots are saved by the Inmate's ID.\n If an image file with the same ID already exists and the new mug shot\n is different, the new mug shot is saved with the current date / time\n appended to the filename.\n\n Args:\n inmates: List of Inmate objects to be processed.\n \"\"\"\n logger = logging.getLogger('save_mug_shots')\n path = SAVE_LOCATION + \"mugs/\"\n # Make mugs/ folder\n try:\n os.makedirs(path)\n except OSError as e:\n # File/Directory already exists\n if e.errno == errno.EEXIST:\n pass\n else:\n raise\n # Save each inmate's mug shot\n for inmate in inmates:\n # Skip inmates with no mug shot\n if inmate.mug is None:\n continue\n # Check if there is already a mug shot for this inmate\n try:\n old_size = os.path.getsize(path + inmate.id + '.jpg')\n if old_size == len(inmate.mug):\n logger.debug(\"Skipping save of mug shot (ID: %s)\", inmate.id)\n continue\n else:\n for filename in os.listdir(path):\n if (fnmatch.fnmatch(filename, '{}_*.jpg'.format(inmate.id))\n and os.path.getsize(filename) == len(inmate.mug)):\n logger.debug(\"Skipping save of mug shot (ID: %s)\",\n inmate.id)\n continue\n logger.debug(\"Saving mug shot under alternate filename \"\n \"(ID: {})\".format(inmate.id))\n location = (path + inmate.id + '_' +\n datetime.datetime.now().strftime(\"%y%m%d%H%M%S\") +\n '.jpg')\n except OSError as e:\n # No such file\n if e.errno == errno.ENOENT:\n old_size = None\n location = path + inmate.id + '.jpg'\n else:\n raise\n # Save the mug shot\n with open(location, mode='wb') as f:\n f.write(inmate.mug)\n\n\ndef log_inmates(inmates, recent=False, mode='a'):\n \"\"\"Log to file all Inmate information excluding mug shot image data.\n\n Args:\n inmates: List of Inmate objects to be processed.\n recent: Default of False will append to the main log file.\n Specifying True will overwrite the separate recent log, which\n is representative of the inmates seen during the last check.\n \"\"\"\n logger = logging.getLogger('log_inmates')\n if recent:\n location = SAVE_LOCATION + 'recent.txt'\n mode = 'w'\n else:\n location = SAVE_LOCATION + 'log.txt'\n logger.debug(\"Saving inmates to {} log\".format(\"recent\" if recent\n else \"standard\"))\n with open(location, mode=mode) as f:\n for inmate in inmates:\n if not recent:\n logger.info(\"Recording Inmate:\\n%s\", inmate)\n f.write(repr(inmate) + '\\n')\n\n\ndef read_log(recent=False):\n \"\"\"Loads Inmate information from log to re-create Inmate objects.\n\n Mug shot data is not retrieved, neither from file nor server.\n\n Args:\n recent: Default of False will read from the main log file.\n Specifying True will read the separate recent log, which\n is representative of the inmates seen during the last check.\n While this is not the default, it is the option most used.\n \"\"\"\n logger = logging.getLogger('read_log')\n if recent:\n location = SAVE_LOCATION + 'recent.txt'\n else:\n location = SAVE_LOCATION + 'log.txt'\n logger.debug(\"Reading inmates from {} log\".format(\"recent\" if recent else\n \"standard\"))\n inmates = []\n try:\n with open(location) as f:\n for line in f:\n inmates.append(Inmate(ast.literal_eval(line)))\n except IOError as e:\n # No such file\n if e.errno == errno.ENOENT:\n pass\n else:\n raise\n return inmates\n\n\ndef most_recent_mug(inmate):\n \"\"\"Returns the filename of the most recent mug shot for the Inmate.\n\n Args:\n inmates: List of Inmate objects to be processed.\n \"\"\"\n best = ''\n for filename in os.listdir(SAVE_LOCATION + 'mugs/'):\n if fnmatch.fnmatch(filename, '{}*.jpg'.format(inmate.id)):\n if filename > best:\n best = filename\n return best\n\ndef post_twitpic(inmates):\n \"\"\"Posts to TwitPic each inmate using their mug shot and caption.\n\n Args:\n inmates: List of Inmate objects to be processed.\n \"\"\"\n logger = logging.getLogger('post_twitpic')\n for inmate in inmates:\n if inmate.get_age() < 20:\n message = inmate.get_twitter_message()\n logger.info('Posting to TwitPic (ID: %s)', inmate.id)\n mail(to=TWITPIC_EMAIL_ADDRESS,\n subject=message, # Caption\n text=repr(inmate), # Serves as a log that can later be loaded in.\n attach= SAVE_LOCATION + \"mugs/{}\".format(most_recent_mug(inmate)))\n\ndef parse_inmates(html):\n inmate_pattern = re.compile(r\"\"\"\n _dlInmates_lblName_\\d+\">(?P.*?).*?\n _dlInmates_lblDOB_\\d+\">(?P.*?).*?\n _dlInmates_Label2_\\d*\">(?P.*?).*?\n ImageHandler\\.ashx\\?imageId=(?P\\d+)&type=thumb\n \"\"\", re.DOTALL | re.X)\n charges_pattern = re.compile(r\"\"\"\n _dlInmates_Charges_\\d+_lblCharge_\\d+\">(?P.*?).*?\n _dlInmates_Charges_\\d+_lblBondOrFine_\\d+\">(?P.*?).*?\n _dlInmates_Charges_\\d+_lblAmount_\\d+\">(?P.*?)\n \"\"\", re.DOTALL | re.X)\n inmates = []\n for inmate in inmate_pattern.finditer(html):\n data = inmate.groupdict()\n # Parse charges for inmate\n charges = []\n # Find end location\n next_inmate = inmate_pattern.search(html, inmate.end())\n try:\n next_inmate = next_inmate.start()\n except:\n next_inmate = len(html)\n for charge in charges_pattern.finditer(html, inmate.end(),\n next_inmate):\n charges.append(charge.groupdict())\n data['charges'] = charges\n # Store the current time as when seen\n data['seen'] = str(datetime.datetime.now())\n # Store complete Inmate object\n inmates.append(Inmate(data))\n return inmates\n\n\ndef find_missing(inmates, recent_inmates):\n \"\"\"Find inmates that no longer appear on the page that may not be logged.\n\n Args:\n inmates: Current list of Inmates.\n recent_inmates: List of Inmates seen during the previous page check.\n\n Returns:\n A list of inmates that appear to be missing and that were likely\n not logged during previous page checks.\n \"\"\"\n logger = logging.getLogger('find_missing')\n # Since we try not to log inmates that don't have charges listed,\n # make sure that any inmate on the recent list that doesn't appear\n # on the current page get logged even if they don't have charges.\n # Same goes for inmates without saved mug shots, as well as for\n # inmates with the only charge reason being 'LOCAL MUNICIPAL WARRANT'\n missing = []\n for recent in recent_inmates:\n potential = False\n if not recent.charges or not most_recent_mug(recent):\n potential = True\n elif (len(recent.charges) == 1 and\n re.search(r'WARRANT(?:S)?\\Z', recent.charges[0]['charge'])):\n potential = True\n # add if the inmate is missing from the current report or if the\n # inmate has had their charge updated\n if potential:\n found = False\n for inmate in inmates:\n if recent.id == inmate.id:\n found = True\n if not recent.charges and not inmate.charges:\n break\n if (inmate.charges and\n re.search(r'WARRANT(?:S)?\\Z',\n inmate.charges[0]['charge']) is None):\n missing.append(inmate)\n break\n if not found:\n missing.append(recent)\n # if couldn't download the mug before and missing now,\n # go ahead and log it for future reference\n if not most_recent_mug(recent):\n log_inmates([recent])\n if len(missing) > 0:\n logger.info(\"Found %s inmates without charges that are now missing\",\n len(missing))\n return missing\n\n\ndef main():\n \"\"\"Main function\n\n Used to scrape the Jail Custody Report, download mug shots, save a log,\n and upload to Twitter.\n \"\"\"\n logging.info(\"main() starting\")\n logger = logging.getLogger('main')\n # Get the Jail Report webpage\n html = get_jail_report()\n # Parse list of inmates from webpage\n inmates = parse_inmates(html)\n # Load the list of inmates seen last time we got the page\n recent_inmates = read_log(recent=True)\n # Find inmates that no longer appear on the page that may not be logged.\n missing = find_missing(inmates, recent_inmates)\n # Make a copy of the current parsed inmates to use later\n inmates_original = inmates[:]\n # Discard recent inmates with no charges listed\n recent_inmates = [recent for recent in recent_inmates if recent.charges]\n # Compare the current list with the list read last time (recent) and\n # get rid of duplicates (already logged inmates). Also discard inmates\n # that have no charges listed, or if the only charge is\n # 'LOCAL MUNICIPAL WARRANT'.\n # TODO(bwbaugh): Make this readable by converting to proper for-loopps.\n inmates = [inmate for inmate in inmates\n if inmate.charges and\n not (len(inmate.charges) == 1 and\n re.search(r'WARRANT(?:S)?\\Z', inmate.charges[0]['charge']))\n and not any((recent.id == inmate.id) and\n (len(recent.charges) <= len(inmate.charges))\n for recent in recent_inmates)]\n # Add to the current list those missing ones without charges that\n # also need to be logged.\n inmates.extend(missing)\n # Double check that there are no duplicates.\n # Note: this is needed due to programming logic error, but the code\n # is getting complicated so in case I don't find the bug better to check.\n for i in range(len(inmates)):\n for j in range(i + 1, len(inmates)):\n if inmates[i] and inmates[j] and inmates[i].id == inmates[j].id:\n logger.warning('Removing duplicate found in inmates (ID: %s)',\n inmates[i].id)\n inmates[i] = None\n inmates = [inmate for inmate in inmates if inmate]\n # We now have our final list of inmates, so let's process them.\n if inmates:\n try:\n get_mug_shots(inmates)\n except urllib.error.HTTPError as e:\n # Service Unavailable\n if e.code == 503:\n reason = \"HTTP Error 503: Service Unavailable\"\n else:\n reason = e\n logger.warning(\"get_mug_shots: %s\", reason)\n return\n except http.client.HTTPException as e:\n logger.warning(\"get_mug_shots: %s\", e)\n return\n save_mug_shots(inmates)\n # Discard inmates that we couldn't save a mug shot for.\n inmates = [inmate for inmate in inmates if inmate.mug]\n # Log and post to TwitPic\n log_inmates(inmates)\n if TWITPIC_EMAIL_ADDRESS and mail is not None:\n post_twitpic(inmates)\n # Save the most recent list of inmates to the log for next time\n log_inmates(inmates_original, recent=True)\n\nif __name__ == '__main__':\n # Continuously checks the custody report page every SECONDS_BETWEEN_CHECKS.\n logging.info(\"__main__ starting\")\n while True:\n try:\n main()\n logging.info(\"Main loop: going to sleep for %s seconds\",\n SECONDS_BETWEEN_CHECKS)\n time.sleep(SECONDS_BETWEEN_CHECKS)\n except KeyboardInterrupt:\n print(\"Stopping\")\n logging.shutdown()\n break\n","sub_path":"scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":17395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"604182081","text":"import numpy as np\nimport string\nimport proc\n\n\n# We process line by line\ndef break_caesar_cipher(line):\n max_rot = 26\n freqz = []\n word = merge_words(line.split())\n for k in range(max_rot):\n # rotate the words by k\n sword = shift_string(list(word), k)\n freqs = compute_letter_frequency(sword)\n freqz.append(freqs)\n # compare all frequency statistics then select the best one\n # from the closeness with english letter_statistics\n true_freq = english_letter_statistic()\n sims = [compute_letter_statistic_similarity(freqz[i], true_freq) for i in range(len(freqz))]\n # among the sims choose one with the most minimum value\n rot_estimate = np.array(sims).argmin()\n rot_estimate = 26 - rot_estimate\n plain_text = proc.caesar_cipher_decrypt(line, rot_estimate)\n # only return the first three words\n\n return getFirstThreeWords(plain_text) + ' ' + str(rot_estimate)\n\n\ndef getFirstThreeWords(line):\n word = line.split()\n return \" \".join(word[:3])\n\n\ndef compute_letter_statistic_similarity(fact_stats, stats):\n similarity = 0\n for key in stats.iterkeys():\n similarity += (fact_stats[key] - stats[key]) ** 2\n return similarity / float(len(stats))\n\n\ndef merge_words(words):\n z = reduce(lambda x, y: x + y, words)\n return z\n\n\ndef english_letter_statistic():\n letter = np.array(list(string.uppercase))\n # average letter frequencies in English\n stats = [8.1, 1.5, 2.8, 4.3, 13.0, 2.2, 2.0, 6.1, 7.0, 0.15, 0.77, 7.0, 2.4,\n 6.8, 7.5, 1.9, 0.095, 6.0, 6.3, 9.1, 2.8, 0.98, 2.4, 0.15, 2.0, 0.074]\n table = dict(zip(letter, stats))\n return table\n\n\ndef compute_letter_frequency(word):\n # prepare empty stats\n letter = list(string.uppercase)\n stats = [0] * 26\n table = dict(zip(letter, stats))\n wc = len(word)\n for c in word:\n if (not (c.isspace())):\n table[c] = table[c] + 1\n # iterate again to divide by word length\n key = map(lambda x: x, table)\n ratio = map(lambda x: table[x] * 100 / float(wc), table)\n freq_stats = dict(zip(key, ratio))\n return freq_stats\n\n\n# only uppercase capable\ndef shift_string(string, k):\n strcopy = list(string)\n for i in range(len(strcopy)):\n if (not (strcopy[i].isspace())):\n strcopy[i] = shift_letter(strcopy[i], k)\n return \"\".join(strcopy)\n\n\n# shift a letter by k position to the right according to alphabet sequence\n# basic version only able to rotate UPPERCASE letters\ndef shift_letter(c, k):\n offset_A = 0x41\n ascii_rotated = ((ord(c) - offset_A + k) % 26)\n char_rotated = chr(ascii_rotated + offset_A)\n return char_rotated\n","sub_path":"crypto.py","file_name":"crypto.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"446289504","text":"\n\nfrom xai.brain.wordbase.nouns._electorate import _ELECTORATE\n\n#calss header\nclass _ELECTORATES(_ELECTORATE, ):\n\tdef __init__(self,): \n\t\t_ELECTORATE.__init__(self)\n\t\tself.name = \"ELECTORATES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"electorate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_electorates.py","file_name":"_electorates.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"400230104","text":"#!/usr/bin/env python\nimport os\nimport select\nimport base\n\nfrom base import Event_base, Epoll_loop, Event_epoll, Event, Eventop\n\n\nEPOLL_CTL_ADD = 0X01\nEPOLL_CTL_MOD = 0X02\nEPOLL_CTL_DEL = 0X03\n\n\ndef epoll_init(base):\n\tepfd = select.epoll()\n\tloop = Epoll_loop()\n\tloop.epfd = epfd\n\tloop.events = [] * 1024\n\tloop.nevents = 1024\n\tloop.nfds = 1024\n\treturn loop\n\n\ndef epoll_add(loop, ev):\n\tfd = -1\n\tevents = 0\n\top = -1;\n\n\tfd = ev.ev_fd\n\tif not fd.fileno() in loop.fds:\n\t\tloop.fds[fd.fileno()] = Event_epoll()\n\n\tevent_epoll = loop.fds[fd.fileno()]\n\n\top = EPOLL_CTL_ADD\n\n\tif isinstance(event_epoll.read, Event):\n\t\tevents |= select.EPOLLIN\n\t\top = EPOLL_CTL_MOD\n\n\tif isinstance(event_epoll.write, Event):\n\t\tevents |= sekect.EPOLLOUT\n\t\top = EPOLL_CTL_MOD\n\n\tif ev.ev_events & base.EV_READ:\n\t\tevents |= select.EPOLLIN\n\n\tif ev.ev_events & base.EV_WRITE:\n\t\tevents |= select.EPOLLOUT\n\n\tif op == EPOLL_CTL_ADD:\n\t\tloop.epfd.register(fd.fileno(), events)\n\telif op == EPOLL_CTL_MOD:\n\t\tloop.epfd.modify(fd.fileno(), events)\n\n\tif ev.ev_events & base.EV_READ:\n\t\tevent_epoll.read = ev\n\n\tif ev.ev_events & base.EV_WRITE:\n\t\tevent_epoll.write = ev\n\n\ndef epoll_del(loop, ev):\n\tfd = -1\n\tevents = 0\n\tneedwritedelete = 1\n\tneedreaddelete = 1\n\n\tfd = ev.ev_fd\n\n\tif fd.fileno() not in loop.fds:\n\t\treturn 1\n\n\tevent_epoll = loop.fds[fd.fileno()]\n\n\top = EPOLL_CTL_DEL\n\n\tif ev.ev_events & base.EV_READ:\n\t\tevents |= select.EPOLLIN\n\n\tif ev.ev_events & base.EV_WRITE:\n\t\tevents |= select.EPOLLOUT\n\n\tif (events & (select.EPOLLIN | select.EPOLLOUT)) != (select.EPOLLIN | select.EPOLLOUT) :\n\t\tif (events & select.EPOLLIN) and (event_epoll.write != None) :\n\t\t\tneedwritedelete = 0\n\t\t\tevents = select.EPOLLOUT\n\t\t\top = EPOLL_CTL_MOD\n\n\t\telif (events & select.EPOLLOUT) and (event_epoll.read != None) :\n\t\t\tneedreaddelete = 0\n\t\t\tevents = select.EPOLLIN\n\t\t\top = EPOLL_CTL_MOD\n\n\n\tif needreaddelete:\n\t\tevent_epoll.read = None\n\n\tif needwritedelete:\n\t\tevent_epoll.write = None\n\n\n\tif op == EPOLL_CTL_MOD:\n\t\tloop.epfd.modify(fd.fileno(), events)\n\telif op == EPOLL_CTL_DEL:\n\t\tloop.epfd.unregister(fd.fileno())\n\n\ndef epoll_dispatch(loop, tv):\n\tret = loop.epfd.poll(1)\n\n\n\tfor fd, event in ret:\n\t\tevent_read = None\n\t\tevent_write = None\n\n\t\tif fd < 0:\n\t\t\tcontinue\n\n\t\tevent_epoll = loop.fds[fd]\n\n\t\tif event & (select.EPOLLHUP | select.EPOLLERR) :\n\t\t\tevent_read = event_epoll.read\n\t\t\tevent_write = event_epoll.write\n\n\t\telse :\n\t\t\tif event & select.EPOLLIN :\n\t\t\t\tevent_read = event_epoll.read\n\n\t\t\tif event & select.EPOLLOUT :\n\t\t\t\tevent_write = event_epoll.write\n\n\t\tif not (event_read or event_write) :\n\t\t\tcontinue\n\n\t\tif event_read is not None :\n\t\t\tfrom event import event_active\n\t\t\tevent_active(event_read, base.EV_READ, 1)\n\n\t\tif event_write is not None :\n\t\t\tfrom event import event_active\n\t\t\tevent_active(event_write, base.EV_WRITE, 1)\n\n","sub_path":"Reactor/v0.1/epoll.py","file_name":"epoll.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"561011722","text":"#! /usr/bin/env python3\n# -*- encoding: utf-8 -*-\n\nimport sys\n\nclass CSVReader:\n \"\"\"\n Класс чтения .csv-файлов.\n В качестве аргумента передается путь к файлу в виде строки.\n \"\"\"\n def __init__(self, infile):\n self.read_lines(infile)\n\n def read_lines(self, infile):\n \"\"\"\n Функция создает двумерный список.\n \"\"\"\n self.content = []\n try:\n csv = open(infile, 'r')\n for line in csv:\n self.content.append(line.rstrip().split(','))\n except IOError as err:\n print(err)\n finally:\n csv.close()\n\n def get_content(self):\n return self.content\n\nclass CSVWriter:\n \"\"\"\n Класс записи .csv-файлов.\n В качестве аргумента передается двумерное множество,\n и путь к файлу для записи.\n \"\"\"\n def __init__(self, inset, outfile):\n self.write_csv(inset, outfile)\n\n def write_csv(self, inset, outfile):\n try:\n csv = open(outfile, 'a')\n for row in inset:\n s = ''\n for col in row:\n s += str(col) + ', '\n csv.write(s[:-2] + '\\n')\n\n except IOError as err:\n print(err)\n finally:\n csv.close()\n\ndef main(argv=sys.argv):\n csv = CSVReader('short.csv')\n rows = csv.get_content()\n for row in rows:\n print(row)\n new_csv = CSVWriter(rows, 'new.csv')\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"csvrw.py","file_name":"csvrw.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"327292366","text":"import typing\nfrom enum import IntEnum\n\n\nclass SessionStatus(IntEnum):\n \"\"\" Статусы SBD сессий \"\"\"\n\n SUCESS = 0\n \"\"\" The SBD session completed successfully. \"\"\"\n\n MO_OK_MT_TOO_LARGE = 1\n \"\"\" The MO message transfer, if any, was successful. The MT\n message queued at the Iridium Gateway is too large to be\n transferred within a single SBD session \"\"\"\n\n MO_OK_BAD_LOC = 2\n \"\"\" The MO message transfer, if any, was successful. The reported\n location was determined to be of unacceptable quality. This\n value is only applicable to IMEIs using SBD protocol revision 1. \"\"\"\n\n TIMEOUT = 10\n \"\"\" The SBD session timed out before session completion. \"\"\"\n\n MO_TOO_LARGE = 12\n \"\"\" The MO message being transferred by the IMEI is too large to\n be transferred within a single SBD session. \"\"\"\n\n RF_LINK_LOSS = 13\n \"\"\" An RF link loss occurred during the SBD session \"\"\"\n\n IMEI_ANOMALY = 14\n \"\"\" An IMEI protocol anomaly occurred during SBD session \"\"\"\n\n IMEI_PROHIBITED = 15\n \"\"\" The IMEI is prohibited from accessing the Iridium Gateway \"\"\"\n\n\nclass IEI(IntEnum):\n \"\"\" Идентификаторы Information Element-ов \"\"\"\n MO_HEADER = 0x01\n MO_PAYLOAD = 0x02\n MO_LOCATION_INFORMATION = 0x03\n M0_CONFIRMATION = 0x05\n\n MT_HEADER = 0x41\n MT_PAYLOAD = 0x42\n MT_CONFIRMATION = 0x44\n MT_MESSAGE_PRIORITY = 0x46\n\n\nclass ConfirmationStatus(IntEnum):\n \"\"\" Очевидно... \"\"\"\n SUCCESS = 1\n FAILURE = 0\n\n\nclass MTDispositionFlags(IntEnum):\n \"\"\" дополнительные флаги для mobile terminated сообщений \"\"\"\n\n FLUSH_MT_QUEUE = 1\n \"\"\" Delete all MT payloads in the SSD’s MT queue \"\"\"\n\n SEND_RING_ALERT = 2\n \"\"\" Send ring alert with no associated MT payload (normal ring alert rules apply) \"\"\"\n\n UPDATE_SSD_LOC = 8\n \"\"\" Update SSD location with given lat/lon values \"\"\"\n\n HIGH_PRIO = 16\n \"\"\" Place the associated MT payload in queue based on priority level \"\"\"\n\n ASSIGN_MTMSN = 32\n \"\"\" Use the value in the Unique ID field as the MTMSN \"\"\"\n\n\nclass MTMessageStatus(IntEnum):\n \"\"\" Статус обработки MT сообщения терминалом\n Значения от 1 до 50 обозначают успешное постановление сообщения в очередь\n и означают номер сообщения в MT очереди, поэтому этот енум их не покрывает\n \"\"\"\n\n @classmethod\n def parse(cls, value: int):\n \"\"\" Специальный метод для парсинга значений с учетом валидных значений от 1 до 50 \"\"\"\n if 0 <= value <= 50:\n return value\n else:\n return cls(value)\n\n SUCCESS_NO_PAYLOAD = 0\n \"\"\" Successful, no payload in message \"\"\"\n\n IMEI_INVALID = -1\n \"\"\" Invalid IMEI – too few characters, non-numeric characters \"\"\"\n\n IMEI_UNKNOWN = -2\n \"\"\" Unknown IMEI – not provisioned on the Iridium Gateway \"\"\"\n\n PAYLOAD_SIZE_EXCEEDED = -3\n \"\"\" Payload size exceeded maximum allowed \"\"\"\n\n PAYLOAD_EXPECTED = -4\n \"\"\" Payload expected, but none received \"\"\"\n\n QUEUE_IS_FULL = -5\n \"\"\" MT message queue full (max of 50) \"\"\"\n\n MT_UNAVAILABLE = -6\n \"\"\" MT resources unavailable \"\"\"\n\n PROTOCOL_ERROR = -7\n \"\"\" Violation of MT DirectIP protocol error \"\"\"\n\n RING_ALERTS_DISABLED = -8\n \"\"\" Ring alerts to the given IMEI are disabled \"\"\"\n\n IMEI_NOT_ATTACHED = -9\n \"\"\" The given IMEI is not attached (not set to receive ring alerts) \"\"\"\n\n IP_REJECTED = -10\n \"\"\" Source IP address rejected by MT filter \"\"\"\n\n MTMSN_OUT_OF_RANGE = -11\n \"\"\" MTMSN value is out of range (valid range is 1 – 65,535)s \"\"\"\n\n\nclass MTMessagePriority:\n \"\"\" Приоритет отправляемого сообщения\n 1 - наивысший приоритет. 5 - низший\n Любое значение не из диапазона 1-5 считается как 5\n \"\"\"\n\n PRIO_1 = 1\n PRIO_2 = 2\n PRIO_3 = 3\n PRIO_4 = 4\n PRIO_5 = 5\n","sub_path":"src/ground/grain-server.backup/mcc/iridium/messages/enum.py","file_name":"enum.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"118596046","text":"import base64\nimport binascii\nimport os\nimport platform\nfrom io import BytesIO, BufferedIOBase, TextIOBase\n\nfrom PIL import Image\n\nis_screen = os.environ.get('TERM').startswith('screen')\nosc = b'\\033Ptmux;\\033\\033]' if is_screen else b'\\033]'\nst = b'\\a\\033\\\\' if is_screen else b'\\a'\n\n\ndef get_content(content) -> bytes:\n # bytes\n if isinstance(content, bytes):\n return content\n\n # file-like object\n if isinstance(content, (BufferedIOBase, TextIOBase)):\n return content.read()\n\n # str\n try:\n # base64 string\n return base64.b64decode(content, validate=True)\n except binascii.Error:\n # filename\n with open(content, 'rb') as f:\n raw_content = f.read()\n return raw_content\n\n\ndef get_clipboard_image() -> bytes:\n if platform.system() == 'Darwin':\n import AppKit\n pb = AppKit.NSPasteboard.generalPasteboard()\n pb_buf = pb.dataForType_(AppKit.NSPasteboardTypePNG)\n if pb_buf:\n return pb_buf.base64Encoding()\n return b''\n\n\ndef buffer_resize(raw_content, resize) -> bytes:\n try:\n with Image.open(BytesIO(get_content(raw_content))) as origin:\n fmt = origin.format\n resized = origin.resize(resize)\n except OSError:\n return b''\n else:\n with BytesIO() as buf:\n resized.save(buf, format=fmt)\n resized_content = buf.getvalue()\n\n return resized_content\n\n\ndef iterm2_img_format(content, inline=1, preserve=1,\n width=None, height=None) -> str:\n raw_content = get_content(content)\n size = len(raw_content)\n try:\n b64content = base64.b64encode(raw_content)\n except TypeError:\n b64content = raw_content.encode('utf-8')\n\n result = osc\n result += b'1337;File='\n result += b'size=%s;' % bytes(str(size).encode())\n result += b'inline=%s;' % bytes(str(inline).encode())\n if width is not None:\n result += b'width=%s;' % bytes(str(width).encode())\n if height is not None:\n result += b'height=%s;' % bytes(str(height).encode())\n result += b'preserveAspectRatio=%s;' % bytes(str(preserve).encode())\n result += b':'\n result += b'%s' % b64content\n result += st\n result += b'\\n'\n\n return result.decode()\n\n","sub_path":"imgcat/img.py","file_name":"img.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"160900899","text":"#!/usr/bin/env python\n\"\"\"Test point cloud part segmentation models\"\"\"\n\nfrom __future__ import division\nimport argparse\nimport os.path as osp\nimport logging\nimport time\n\nimport numpy as np\nimport torch\nfrom torch import nn\n\nfrom shaper.config.part_segmentation import cfg\nfrom shaper.config import purge_cfg\nfrom shaper.models.build import build_model\nfrom shaper.data.build import build_dataloader, build_transform\nfrom shaper.data import transforms as T\nfrom shaper.data.datasets.evaluator import evaluate_part_segmentation\nfrom shaper.utils.checkpoint import Checkpointer\nfrom shaper.utils.metric_logger import MetricLogger\nfrom shaper.utils.io import mkdir\nfrom shaper.utils.logger import setup_logger\nfrom shaper.utils.torch_util import set_random_seed\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"PyTorch 3D Deep Learning Training\")\n parser.add_argument(\n \"--cfg\",\n dest=\"config_file\",\n default=\"\",\n metavar=\"FILE\",\n help=\"path to config file\",\n type=str,\n )\n parser.add_argument(\n \"opts\",\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER,\n )\n\n args = parser.parse_args()\n return args\n\n\ndef test(cfg, output_dir=\"\"):\n logger = logging.getLogger(\"shaper.tester\")\n\n # Build model\n model, loss_fn, metric_fn = build_model(cfg)\n model = nn.DataParallel(model).cuda()\n\n # Build checkpointer\n checkpointer = Checkpointer(model, save_dir=output_dir)\n\n if cfg.TEST.WEIGHT:\n # Load weight if specified\n weight_path = cfg.TEST.WEIGHT.replace(\"@\", output_dir)\n checkpointer.load(weight_path, resume=False)\n else:\n # Load last checkpoint\n checkpointer.load(None, resume=True)\n\n # Build data loader\n test_data_loader = build_dataloader(cfg, mode=\"test\")\n test_dataset = test_data_loader.dataset\n\n # Prepare visualization\n vis_dir = cfg.TEST.VIS_DIR.replace(\"@\", output_dir)\n if vis_dir:\n mkdir(vis_dir)\n\n # ---------------------------------------------------------------------------- #\n # Test\n # ---------------------------------------------------------------------------- #\n seg_logit_all = []\n model.eval()\n loss_fn.eval()\n metric_fn.eval()\n set_random_seed(cfg.RNG_SEED)\n\n if cfg.TEST.VOTE.NUM_VOTE > 1:\n # Disable inherent shuffle\n test_dataset.shuffle_points = False\n # Remove old transform\n test_dataset.transform = None\n\n if cfg.TEST.VOTE.TYPE == \"AUGMENTATION\":\n tmp_cfg = cfg.clone()\n tmp_cfg.defrost()\n tmp_cfg.TEST.AUGMENTATION = tmp_cfg.TEST.VOTE.AUGMENTATION\n transform_list = [build_transform(tmp_cfg, False)] * cfg.TEST.VOTE.NUM_VOTE\n elif cfg.TEST.VOTE.TYPE == \"MULTI_VIEW\":\n # Build new transform\n transform_list = []\n for view_ind in range(cfg.TEST.VOTE.NUM_VOTE):\n t = [T.PointCloudToTensor(),\n T.PointCloudRotateByAngle(cfg.TEST.VOTE.MULTI_VIEW.AXIS,\n 2 * np.pi * view_ind / cfg.TEST.VOTE.NUM_VOTE)]\n transform_list.append(T.Compose(t))\n else:\n raise NotImplementedError(\"Unsupported voting method.\")\n\n with torch.no_grad():\n start_time = time.time()\n end = start_time\n for ind in range(len(test_dataset)):\n data = test_dataset[ind]\n data_time = time.time() - end\n points = data[\"points\"]\n cls_label = data[\"cls_label\"]\n num_points = points.shape[0]\n\n # Convert points into tensor\n points_batch = [t(points) for t in transform_list]\n if cfg.TEST.VOTE.SHUFFLE:\n index_batch = [torch.randperm(num_points) for _ in points_batch]\n points_batch = [points[index] for points, index in zip(points_batch, index_batch)]\n points_batch = torch.stack(points_batch, dim=0).transpose_(1, 2).contiguous()\n points_batch = points_batch.cuda(non_blocking=True)\n cls_label_batch = torch.tensor([cls_label] * cfg.TEST.VOTE.NUM_VOTE).cuda()\n\n preds = model({\"points\": points_batch, \"cls_label\": cls_label_batch})\n seg_logit_batch = preds[\"seg_logit\"].cpu().numpy()\n\n if cfg.TEST.VOTE.SHUFFLE:\n seg_logit_ensemble = np.zeros(seg_logit_batch.shape[1:], dtype=seg_logit_batch.dtype)\n for i, index in enumerate(index_batch):\n index = index.numpy()\n seg_logit_ensemble[:, index] += seg_logit_batch[i]\n else:\n seg_logit_ensemble = np.mean(seg_logit_batch, axis=0)\n\n seg_logit_all.append(seg_logit_ensemble)\n\n batch_time = time.time() - end\n end = time.time()\n\n if ind % cfg.TEST.LOG_PERIOD == 0:\n logger.info(\"iter: {:4d} time:{:.4f} data:{:.4f}\".format(ind, batch_time, data_time))\n seg_logit_all = np.stack(seg_logit_all, axis=0)\n else:\n test_meters = MetricLogger(delimiter=\" \")\n with torch.no_grad():\n start_time = time.time()\n end = start_time\n for iteration, data_batch in enumerate(test_data_loader):\n data_time = time.time() - end\n\n data_batch = {k: v.cuda(non_blocking=True) for k, v in data_batch.items()}\n\n preds = model(data_batch)\n\n seg_logit_all.append(preds[\"seg_logit\"].cpu().numpy())\n loss_dict = loss_fn(preds, data_batch)\n metric_dict = metric_fn(preds, data_batch)\n losses = sum(loss_dict.values())\n test_meters.update(loss=losses, **loss_dict, **metric_dict)\n\n batch_time = time.time() - end\n end = time.time()\n test_meters.update(time=batch_time, data=data_time)\n\n if iteration % cfg.TEST.LOG_PERIOD == 0:\n logger.info(\n test_meters.delimiter.join(\n [\n \"iter: {iter:4d}\",\n \"{meters}\",\n ]\n ).format(\n iter=iteration,\n meters=str(test_meters),\n )\n )\n test_time = time.time() - start_time\n logger.info(\"Test {} forward time: {:.2f}s\".format(test_meters.summary_str, test_time))\n seg_logit_all = np.concatenate(seg_logit_all, axis=0)\n\n evaluate_part_segmentation(test_dataset, seg_logit_all, output_dir=output_dir, vis_dir=vis_dir)\n\n\ndef main():\n args = parse_args()\n\n # Load the configuration\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n purge_cfg(cfg)\n cfg.freeze()\n\n output_dir = cfg.OUTPUT_DIR\n # Replace '@' with config path\n if output_dir:\n config_path = osp.splitext(args.config_file)[0]\n config_path = config_path.replace(\"configs\", \"outputs\")\n output_dir = output_dir.replace('@', config_path)\n mkdir(output_dir)\n\n logger = setup_logger(\"shaper\", output_dir, prefix=\"test\")\n logger.info(\"Using {} GPUs\".format(torch.cuda.device_count()))\n logger.info(args)\n\n logger.info(\"Loaded configuration file {}\".format(args.config_file))\n logger.info(\"Running with config:\\n{}\".format(cfg))\n\n assert cfg.TASK == \"part_segmentation\"\n test(cfg, output_dir)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tools/test_part_seg.py","file_name":"test_part_seg.py","file_ext":"py","file_size_in_byte":7730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"222944686","text":"\"\"\"\nFind kth data from last index of linked list\n\nExpected result:\n\n1. result: 4 <- k: 2 from list[1, 2, 3, 4, 5]\n2. result: 8 <- k: 3 from list[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n\"\"\"\n\nclass Node(object):\n def __init__(self, data=None, next=None):\n self.data = data\n self.next = next\n\nclass LinkedList(object):\n def __init__(self):\n self.head = None\n self.tail = None\n\n def add(self, data):\n if self.head is None:\n self.head = self.tail = Node(data)\n else:\n node = Node(data)\n self.tail.next = node\n self.tail = node\n\n\nclass KthFromLast(LinkedList):\n def find_kth_to_last(self, k):\n p1 = p2 = self.head\n i, j = 0, k-1\n while p1:\n if i > j:\n try:\n p2 = p2.next\n except:\n break\n p1 = p1.next\n i += 1\n return p2.data\n\n\ndef test():\n test_cases = [\n {\"list\": [1, 2, 3, 4, 5] , \"k\": 2},\n {\"list\": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], \"k\": 3}\n ]\n for i, test_case in enumerate(test_cases, 1):\n l1, k = test_case['list'], test_case['k']\n ll = KthFromLast()\n for data in l1:\n ll.add(data)\n res = ll.find_kth_to_last(k)\n print(f\"{i}. result: {res} <- k: {k} from list{l1}\")\n\n\nif __name__ == '__main__':\n test()\n\n","sub_path":"algo/07-02-abstract-data-type-excercise/05-linked-list/01_find_kth_from_the_end.py","file_name":"01_find_kth_from_the_end.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"563642003","text":"import gym\nimport matplotlib.pyplot as plt\nfrom Exercise4.NeuralNetwork import NeuralNetwork\nfrom Exercise4.Agent import Agent\n\n# Parameters\nnum_games = int(1e4)\nlearning_rate = 0.0001\ndiscount_factor = 0.99\nepsilon_max = 1\nepsilon_min = 0.01\nepsilon_dec = 1e-5\nnum_observations = 4\nnum_actions = 2\nnum_games_to_avg = 100\nnum_hidden_layer_neurons = 128\n\n# Creates environment, neural network, and agent\nenv = gym.make('CartPole-v1')\nnetwork = NeuralNetwork([num_observations, num_hidden_layer_neurons, num_actions], learning_rate)\nagent = Agent(network, num_actions, discount_factor, epsilon_max, epsilon_min, epsilon_dec)\n\n\n# Simulates a neural Q-learning agent in the Cart-pole environment and plots results\ndef main():\n rewards = []\n avg_rewards = []\n epsilons = []\n for i in range(num_games):\n if len(rewards) == num_games_to_avg:\n rewards = rewards[1:]\n rewards.append(run_game())\n avg_rewards.append(sum(rewards) / len(rewards))\n epsilons.append(agent.epsilon)\n env.close()\n plot(avg_rewards, epsilons)\n\n\n# Plots the reward and decreasing epsilon in one graph\ndef plot(avg_rewards, epsilons):\n color = 'tab:blue'\n fig, reward_axis = plt.subplots()\n reward_axis.set_xlabel('Number of Games')\n reward_axis.set_ylabel('Avg. Reward', color=color)\n reward_axis.plot(range(num_games), avg_rewards, color=color)\n\n color = 'tab:orange'\n epsilon_axis = reward_axis.twinx()\n epsilon_axis.set_ylabel('Epsilon', color=color)\n epsilon_axis.plot(range(num_games), epsilons, color=color)\n\n fig.tight_layout()\n plt.show()\n\n\n# Runs a single game in the environment and returns the final reward\ndef run_game():\n state = env.reset()\n total_reward = 0\n done = False\n while not done:\n action = agent.action(state)\n new_state, reward, done = env.step(action)[0:3]\n agent.update(state, action, reward, new_state)\n total_reward += reward\n state = new_state\n return total_reward\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"env/Exercise4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"369825223","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'fillForm'\nurlpatterns = [\n url(r'^$', views.fill_form, name='index'),\n url(r'^forms/$', views.get_forms, name='allforms'),\n url(r'^form/(?P\\d{0,10})/$', views.get_form, name='singleform'),\n url(r'^form/(?P\\d{0,10})/pdf$', views.get_pdf, name='singleformpdf'),\n]\n","sub_path":"fillForm/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"581529309","text":"import numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport classifier_nn\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport pandas as pd\nfrom scipy.io import loadmat\nfrom sklearn.preprocessing import OneHotEncoder\n\ndef main():\n \"\"\"\n\n :return:\n \"\"\"\n\n data = loadmat('./20by20 Data/ex4data1.mat')\n X = data[\"X\"]\n y = data[\"y\"]\n encoder = OneHotEncoder(sparse=False)\n y_matrix = encoder.fit_transform(y)\n train_data= (X,y_matrix)\n test_data = ()\n\n # # Loading and reading data\n # # The data is in such a way that \"0\" digit is labeled as \"10\", while\n # # the digits \"1\" to \"9\" are labeled as \"1\" to \"9\" in their natural order.\n # mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n #\n # # We will perform some checks to ascertain number of training, test and cross validation examples\n # # in this data set.\n # print()\n # print(\"Number of training examples : \" + str(mnist.train.num_examples))\n # print(\"Number of test examples : \" + str(mnist.test.num_examples))\n # print(\"Number of cross validation examples : \" + str(mnist.validation.num_examples))\n # print(\"Number of pixel values in a single example : \" + str(mnist.train.images[1].shape[0])),print()\n\n #Visualizing data\n for i in range(1,6):\n plt.figure(num=i)\n # #plt.imshow(mnist.train.images[random.randint(1,int(mnist.train.num_examples))].reshape(28,28),cmap=\"gist_gray\")\n plt.imshow(np.matrix(X[random.randint(1, 5000)]).reshape(20, 20),\n cmap=\"gist_gray\")\n plt.show()\n\n # Specifying X and y matrices for train and test data\n # train_data = mnist.train.next_batch(10000)\n X_train = train_data[0]\n y_train = train_data[1]\n print(\"Shape of X_train : \" + str(X_train.shape))\n print(\"Shape of y_train : \" + str(y_train.shape)),print()\n\n # test_data = mnist.test.next_batch(1000)\n # X_test = test_data[0]\n # y_test = test_data[1]\n # print(\"Shape of X_test : \" + str(X_test.shape))\n # print(\"Shape of y_test : \" + str(y_test.shape)),print()\n\n # Calling neural network model\n layers = [400,25,10]\n classifier_nn.model_nn(train_data,test_data,layers,y)\n\nmain()\n\n\n","sub_path":"driver_file.py","file_name":"driver_file.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"153086451","text":"\"\"\"Test RFlink serial low level and packet parsing protocol.\"\"\"\n\nfrom unittest.mock import Mock\n\nimport pytest\n\nfrom rflink.protocol import PacketHandling\n\nCOMPLETE_PACKET = b'20;E0;NewKaku;ID=cac142;SWITCH=1;CMD=ALLOFF;\\r\\n'\nINCOMPLETE_PART1 = b'20;E0;NewKaku;ID=cac'\nINCOMPLETE_PART2 = b'142;SWITCH=1;CMD=ALLOFF;\\r\\n'\n\n# Testing parsing of 4 structures\n\"\"\"\nCOMMAND_TEMPLATES = {\n'minimal': '{node};{};{};',\n'command': '{node};{};{};{};',\n'switch_command': '{node};{};{};{};{};',\n'switch_value_command': '{node};{};{};{};{};{};'\n}\n\"\"\"\n\n\nCOMPLETE_PACKET_DICT = {\n 'id': 'cac142',\n 'node': 'gateway',\n 'protocol': 'newkaku',\n 'command': 'alloff',\n 'switch': '1',\n}\n\n\nPACKET_MINIMAL=b'10;DELTRONIC;001c33;\\r\\n'\nPACKET_COMMAND=b'10;MERTIK;64;UP;\\r\\n'\nPACKET_SWITCH_COMMAND=b'10;NewKaku;0cac142;3;ON;\\r\\n'\nPACKET_SWITCH_VALUE_COMMAND=b'10;MiLightv1;F746;00;3c00;ON;\\r\\n'\n\nPACKET_MINIMAL_DICT = {\n 'id': '001c33',\n 'node': 'gateway',\n 'protocol': 'deltronic',\n}\n\n\nPACKET_COMMAND_DICT = {\n 'id': '64',\n 'node': 'gateway',\n 'protocol': 'mertik',\n 'command': 'up',\n}\n\nPACKET_SWITCH_COMMAND_DICT = {\n 'id': '0cac142',\n 'node': 'gateway',\n 'protocol': 'newkaku',\n 'command': 'on',\n 'switch': '3',\n}\n\nPACKET_SWITCH_VALUE_COMMAND_DICT = {\n 'id': 'F746',\n 'node': 'gateway',\n 'protocol': 'milightv1',\n 'command': 'on',\n 'switch': '00',\n 'value': '3c00',\n}\n\n@pytest.fixture\ndef protocol(monkeypatch):\n \"\"\"Rflinkprotocol instance with mocked handle_packet.\"\"\"\n monkeypatch.setattr(PacketHandling, 'handle_packet', Mock())\n return PacketHandling(None)\n\n\ndef test_complete_packet(protocol):\n \"\"\"Protocol should parse and output complete incoming packets.\"\"\"\n protocol.data_received(COMPLETE_PACKET)\n\n protocol.handle_packet.assert_called_once_with(COMPLETE_PACKET_DICT)\n\ndef test_p1(protocol):\n protocol.data_received(PACKET_MINIMAL)\n protocol.handle_packet.assert_called_once_with(PACKET_MINIMAL_DICT)\n\ndef test_p2(protocol):\n protocol.data_received(PACKET_COMMAND)\n protocol.handle_packet.assert_called_once_with(PACKET_COMMAND_DICT)\n\ndef test_p3(protocol):\n protocol.data_received(PACKET_SWITCH_COMMAND)\n protocol.handle_packet.assert_called_once_with(PACKET_SWITCH_COMMAND_DICT)\n\ndef test_p4(protocol):\n protocol.data_received(PACKET_SWITCH_VALUE_COMMAND)\n protocol.handle_packet.assert_called_once_with(PACKET_SWITCH_VALUE_COMMAND_DICT)\n\n\ndef test_split_packet(protocol):\n \"\"\"Packet should be allowed to arrive in pieces.\"\"\"\n protocol.data_received(INCOMPLETE_PART1)\n protocol.data_received(INCOMPLETE_PART2)\n\n protocol.handle_packet.assert_called_once_with(COMPLETE_PACKET_DICT)\n\n\ndef test_starting_incomplete(protocol):\n \"\"\"An initial incomplete packet should be discarded.\"\"\"\n protocol.data_received(INCOMPLETE_PART2)\n protocol.data_received(INCOMPLETE_PART1)\n protocol.data_received(INCOMPLETE_PART2)\n\n protocol.handle_packet.assert_called_once_with(COMPLETE_PACKET_DICT)\n\n\ndef test_multiple_packets(protocol):\n \"\"\"Multiple packets should be parsed.\"\"\"\n protocol.data_received(COMPLETE_PACKET)\n protocol.data_received(COMPLETE_PACKET)\n\n assert protocol.handle_packet.call_count == 2\n protocol.handle_packet.assert_called_with(COMPLETE_PACKET_DICT)\n","sub_path":"tests/test_protocol.py","file_name":"test_protocol.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"133540632","text":"__author__ = 'noe'\n\nfrom pyemma.msm.models.msm import MSM as _MSM\nfrom pyemma.msm.estimators.maximum_likelihood_msm import MaximumLikelihoodMSM as _MLMSM\nfrom pyemma.msm.models.msm_sampled import SampledMSM as _SampledMSM\nfrom pyemma.util.types import ensure_dtraj_list\nfrom pyemma._base.progress import ProgressReporter\nfrom pyemma._ext.six.moves import range\n\n\nclass BayesianMSM(_MLMSM, _SampledMSM, ProgressReporter):\n \"\"\" Bayesian estimator for MSMs given discrete trajectory statistics\n\n Parameters\n ----------\n lag : int, optional, default=1\n lagtime to estimate the HMSM at\n\n nsamples : int, optional, default=100\n number of sampled transition matrices used\n\n nsteps : int, optional, default=None\n number of Gibbs sampling steps for each transition matrix used.\n If None, nstep will be determined automatically\n\n msm : :class:`MSM `\n Single-point estimate of MSM object around which errors will be\n evaluated\n\n reversible : bool, optional, default = True\n If true compute reversible MSM, else non-reversible MSM\n\n count_mode : str, optional, default='effective'\n mode to obtain count matrices from discrete trajectories. Should be one of:\n\n * 'sliding' : A trajectory of length T will have :math:`T-tau` counts\n at time indexes\n .. math:\n (0 \\rightarray \\tau), (1 \\rightarray \\tau+1), ..., (T-\\tau-1 \\rightarray T-1)\n\n * 'effective' : Uses an estimate of the transition counts that are\n statistically uncorrelated. Recommended when used with a\n Bayesian MSM.\n\n * 'sample' : A trajectory of length T will have :math:`T/tau` counts\n at time indexes\n .. math:\n (0 \\rightarray \\tau), (\\tau \\rightarray 2 \\tau), ..., (((T/tau)-1) \\tau \\rightarray T)\n\n sparse : bool, optional, default = False\n If true compute count matrix, transition matrix and all derived\n quantities using sparse matrix algebra. In this case python sparse\n matrices will be returned by the corresponding functions instead of\n numpy arrays. This behavior is suggested for very large numbers of\n states (e.g. > 4000) because it is likely to be much more efficient.\n\n connectivity : str, optional, default = 'largest'\n Connectivity mode. Three methods are intended (currently only\n 'largest' is implemented)\n 'largest' : The active set is the largest reversibly connected set.\n All estimation will be done on this subset and all quantities\n (transition matrix, stationary distribution, etc) are only defined\n on this subset and are correspondingly smaller than the full set\n of states\n 'all' : The active set is the full set of states. Estimation will be\n conducted on each reversibly connected set separately. That means\n the transition matrix will decompose into disconnected submatrices,\n the stationary vector is only defined within subsets, etc.\n Currently not implemented.\n 'none' : The active set is the full set of states. Estimation will be\n conducted on the full set of states without ensuring connectivity.\n This only permits nonreversible estimation.\n Currently not implemented.\n\n dt_traj : str, optional, default='1 step'\n Description of the physical time corresponding to the trajectory time\n step. May be used by analysis algorithms such as plotting tools to\n pretty-print the axes. By default '1 step', i.e. there is no physical\n time unit. Specify by a number, whitespace and unit. Permitted units\n are (* is an arbitrary string):\n\n | 'fs', 'femtosecond*'\n | 'ps', 'picosecond*'\n | 'ns', 'nanosecond*'\n | 'us', 'microsecond*'\n | 'ms', 'millisecond*'\n | 's', 'second*'\n\n conf : float, optional, default=0.95\n Confidence interval. By default one-sigma (68.3%) is used. Use 95.4%\n for two sigma or 99.7% for three sigma.\n\n \"\"\"\n def __init__(self, lag=1, nsamples=100, nsteps=None, reversible=True, count_mode='effective', sparse=False,\n connectivity='largest', dt_traj='1 step', conf=0.95):\n _MLMSM.__init__(self, lag=lag, reversible=reversible, count_mode=count_mode, sparse=sparse,\n connectivity=connectivity, dt_traj=dt_traj)\n self.nsamples = nsamples\n self.nsteps = nsteps\n self.conf = conf\n\n def _estimate(self, dtrajs):\n \"\"\"\n\n Parameters\n ----------\n dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int)\n discrete trajectories, stored as integer ndarrays (arbitrary size)\n or a single ndarray for only one trajectory.\n\n Return\n ------\n hmsm : :class:`EstimatedHMSM `\n Estimated Hidden Markov state model\n\n \"\"\"\n # ensure right format\n dtrajs = ensure_dtraj_list(dtrajs)\n # conduct MLE estimation (superclass) first\n _MLMSM._estimate(self, dtrajs)\n\n # transition matrix sampler\n from msmtools.estimation import tmatrix_sampler\n from math import sqrt\n if self.nsteps is None:\n self.nsteps = int(sqrt(self.nstates)) # heuristic for number of steps to decorrelate\n # use the same count matrix as the MLE. This is why we have effective as a default\n tsampler = tmatrix_sampler(self.count_matrix_active, reversible=self.reversible, T0=self.transition_matrix,\n nsteps=self.nsteps)\n\n self._progress_register(self.nsamples, description=\"Sampling models\", stage=0)\n\n def call_back():\n self._progress_update(1, stage=0)\n\n sample_Ps, sample_mus = tsampler.sample(nsamples=self.nsamples,\n return_statdist=True,\n call_back=call_back)\n self._progress_force_finish(0)\n\n # construct sampled MSMs\n samples = []\n for i in range(self.nsamples):\n samples.append(_MSM(sample_Ps[i], pi=sample_mus[i], reversible=self.reversible, dt_model=self.dt_model))\n\n # update self model\n self.update_model_params(samples=samples)\n\n # done\n return self\n","sub_path":"pyemma/msm/estimators/bayesian_msm.py","file_name":"bayesian_msm.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"214784015","text":"import pandas as pd\r\nimport numpy\r\nimport math\r\n\r\n\"\"\"\r\nIndoors is a class which represents the model calculation. A detailed description of\r\nthe mathematical model can be found at: Martin Z. Bazant and John W. M. Bush, medRxiv preprint (2020): \r\n\"Beyond Six Feet: A Guideline to Limit Indoor Airborne Transmission of COVID-19\"\r\n\r\nhttp://web.mit.edu/bazant/www/COVID-19/\r\n\r\nProperties:\r\nModel Parameters\r\nCalculated Variables\r\nmerv_dict: MERV values to aerosol filtration efficiency conversion\r\n\r\nMethods:\r\ndef __init__: Constructor\r\ndef calc_vars: Calculates and stores all variables used in the model, based on the model parameters.\r\ndef calc_n_max: Calculate maximum people allowed in the room given an exposure time (hours), using the transient\r\n model.\r\ndef calc_n_max_ss: Calculate maximum people allowed in the room given an exposure time (hours), using the steady-state\r\n model.\r\ndef calc_max_time: Calculate maximum exposure time allowed given a capacity (# people, transient)\r\ndef calc_n_max_series: Calculate maximum people allowed in the room across a range of exposure times\r\ndef get_six_ft_n: Get the maximum number of people allowed in the room, based on the six-foot rule.\r\ndef set_default_params: Sets default parameters.\r\ndef merv_to_eff: Converts a MERV rating to an aerosol filtration efficiency. \r\ndef clamp: Clamps a value within a given range.\r\n\"\"\"\r\n\r\n\r\nclass Indoors:\r\n # Model Parameters\r\n physical_params = []\r\n physio_params = []\r\n disease_params = []\r\n prec_params = []\r\n\r\n # Calculated Variables\r\n room_vol = 0 # ft3\r\n fresh_rate = 0 # ft3/min\r\n recirc_rate = 0 # ft3/min\r\n air_filt_rate = 0 # /hr\r\n sett_speed = 0 # m/hr\r\n conc_relax_rate = 0 # /hr\r\n airb_trans_rate = 0 # /hr\r\n viral_deact_rate = 0 # /hr\r\n eff_aerosol_radius = 0 # um\r\n\r\n # Source: https://www.ashrae.org/technical-resources/filtration-disinfection\r\n # Table of MERV values corresponding to aerosol filtration efficiency, by different particle sizes (in microns)\r\n merv_dict = [\r\n {'merv': 1, '0.3-1': 0.01, '1-3': 0.01, '3-10': 0.01},\r\n {'merv': 2, '0.3-1': 0.01, '1-3': 0.01, '3-10': 0.01},\r\n {'merv': 3, '0.3-1': 0.01, '1-3': 0.01, '3-10': 0.01},\r\n {'merv': 4, '0.3-1': 0.01, '1-3': 0.01, '3-10': 0.01},\r\n {'merv': 5, '0.3-1': 0.01, '1-3': 0.01, '3-10': 0.2},\r\n {'merv': 6, '0.3-1': 0.01, '1-3': 0.01, '3-10': 0.35},\r\n {'merv': 7, '0.3-1': 0.01, '1-3': 0.01, '3-10': 0.50},\r\n {'merv': 8, '0.3-1': 0.01, '1-3': 0.20, '3-10': 0.70},\r\n {'merv': 9, '0.3-1': 0.01, '1-3': 0.35, '3-10': 0.75},\r\n {'merv': 10, '0.3-1': 0.01, '1-3': 0.50, '3-10': 0.80},\r\n {'merv': 11, '0.3-1': 0.2, '1-3': 0.65, '3-10': 0.85},\r\n {'merv': 12, '0.3-1': 0.35, '1-3': 0.80, '3-10': 0.90},\r\n {'merv': 13, '0.3-1': 0.50, '1-3': 0.85, '3-10': 0.90},\r\n {'merv': 14, '0.3-1': 0.75, '1-3': 0.90, '3-10': 0.95},\r\n {'merv': 15, '0.3-1': 0.85, '1-3': 0.90, '3-10': 0.95},\r\n {'merv': 16, '0.3-1': 0.95, '1-3': 0.95, '3-10': 0.95},\r\n {'merv': 17, '0.3-1': 0.9997, '1-3': 0.9997, '3-10': 0.9997},\r\n {'merv': 18, '0.3-1': 0.99997, '1-3': 0.99997, '3-10': 0.99997},\r\n {'merv': 19, '0.3-1': 0.999997, '1-3': 0.999997, '3-10': 0.999997},\r\n {'merv': 20, '0.3-1': 0.9999997, '1-3': 0.9999997, '3-10': 0.9999997},\r\n ]\r\n\r\n def __init__(self):\r\n self.set_default_params()\r\n self.calc_vars()\r\n\r\n # Calculate all calculated variables\r\n def calc_vars(self):\r\n # Physical Parameters\r\n floor_area = self.physical_params[0] # ft2\r\n mean_ceiling_height = self.physical_params[1] # ft\r\n air_exch_rate = self.physical_params[2] # /hr\r\n primary_outdoor_air_fraction = self.physical_params[3] # no units\r\n aerosol_filtration_eff = self.physical_params[4] # no units\r\n relative_humidity = self.physical_params[5] # no units\r\n\r\n # Physiological Parameters\r\n breathing_flow_rate = self.physio_params[0] # m3 / hr\r\n max_aerosol_radius = self.physio_params[1]\r\n\r\n # Disease Parameters\r\n exhaled_air_inf = self.disease_params[0] # infection quanta/m3\r\n max_viral_deact_rate = self.disease_params[1] # /hr\r\n\r\n # Precautionary Parameters\r\n mask_passage_prob = self.prec_params[0] # no units\r\n\r\n # Calculation\r\n mean_ceiling_height_m = mean_ceiling_height * 0.3048\r\n self.room_vol = floor_area * mean_ceiling_height # ft3\r\n room_vol_m = 0.0283168 * self.room_vol # m3\r\n\r\n self.fresh_rate = self.room_vol * air_exch_rate / 60 # ft3/min\r\n\r\n self.recirc_rate = self.fresh_rate * (1/primary_outdoor_air_fraction - 1) # ft3/min\r\n\r\n self.air_filt_rate = aerosol_filtration_eff * self.recirc_rate * 60 / self.room_vol # /hr\r\n\r\n self.eff_aerosol_radius = ((0.4 / (1 - relative_humidity)) ** (1 / 3)) * max_aerosol_radius\r\n\r\n self.viral_deact_rate = max_viral_deact_rate * relative_humidity\r\n\r\n self.sett_speed = 3 * (self.eff_aerosol_radius / 5) ** 2 # mm/s\r\n self.sett_speed = self.sett_speed * 60 * 60 / 1000 # m/hr\r\n\r\n self.conc_relax_rate = air_exch_rate + self.air_filt_rate + self.viral_deact_rate + self.sett_speed / mean_ceiling_height_m # /hr\r\n\r\n self.airb_trans_rate = ((breathing_flow_rate * mask_passage_prob) ** 2) * exhaled_air_inf / (room_vol_m * self.conc_relax_rate)\r\n\r\n # Calculate maximum people allowed in the room given an exposure time (hours), using the\r\n # transient model\r\n def calc_n_max(self, exp_time):\r\n risk_tolerance = self.prec_params[1] # no units\r\n n_max = 1 + (risk_tolerance * (1 + 1/(self.conc_relax_rate * exp_time)) / (self.airb_trans_rate * exp_time))\r\n return n_max\r\n\r\n # Calculate maximum people allowed in the room given an exposure time (hours), using the\r\n # steady-state model\r\n def calc_n_max_ss(self, exp_time):\r\n risk_tolerance = self.prec_params[1] # no units\r\n n_max = 1 + risk_tolerance / (self.airb_trans_rate * exp_time)\r\n return n_max\r\n\r\n # Calculate maximum exposure time allowed given a capacity (# people), transient\r\n def calc_max_time(self, n_max):\r\n risk_tolerance = self.prec_params[1] # no units\r\n\r\n exp_time_ss = risk_tolerance / ((n_max - 1) * self.airb_trans_rate) # hrs, steady-state\r\n exp_time_trans = exp_time_ss * (1 + (1 + 4 / (self.conc_relax_rate * exp_time_ss)) ** 0.5) / 2 # hrs, transient\r\n return exp_time_trans\r\n\r\n # Calculate maximum people allowed in the room across a range of exposure times, returning both transient\r\n # and steady-state outputs\r\n def calc_n_max_series(self, t_min, t_max, t_step):\r\n df = pd.DataFrame(columns=['exposure_time', 'occupancy_trans', 'occupancy_ss'])\r\n for exp_time in numpy.arange(t_min, t_max, t_step):\r\n n_max_trans = self.calc_n_max(exp_time)\r\n n_max_ss = self.calc_n_max_ss(exp_time)\r\n df = df.append(pd.DataFrame({'exposure_time': [exp_time], 'occupancy_trans': [n_max_trans],\r\n 'occupancy_ss': [n_max_ss]}))\r\n\r\n return df\r\n\r\n # Get the maximum number of people allowed in the room, based on the six-foot rule.\r\n def get_six_ft_n(self):\r\n floor_area = self.physical_params[0] # ft2\r\n return math.floor(floor_area / 36)\r\n\r\n # Get the maximum number of people this room can physically have (based on floor area)\r\n def get_n_max(self):\r\n floor_area = self.physical_params[0] # ft2\r\n flr_rad = 3 # ft\r\n return math.floor(floor_area / flr_rad ** 2)\r\n\r\n # Sets default parameters.\r\n def set_default_params(self):\r\n # Physical Parameters\r\n floor_area = 900 # ft2\r\n mean_ceiling_height = 12 # ft\r\n air_exchange_rate = 3 # /hr (air changes per hour (ACH))\r\n primary_outdoor_air_fraction = 0.2 # 1.0 = natural ventilation\r\n aerosol_filtration_eff = 0 # >0.9997 HEPA, =0.2-0.9 MERVs, =0 no filter\r\n relative_humidity = 0.6\r\n self.physical_params = [floor_area, mean_ceiling_height, air_exchange_rate, primary_outdoor_air_fraction,\r\n aerosol_filtration_eff, relative_humidity]\r\n\r\n # Physiological Parameters\r\n breathing_flow_rate = 0.5 # m3/hr\r\n max_aerosol_radius = 2 # micrometers\r\n self.physio_params = [breathing_flow_rate, max_aerosol_radius]\r\n\r\n # Disease Parameters\r\n exhaled_air_inf = 30 # infection quanta/m3\r\n max_viral_deact_rate = 0.3 # /hr\r\n self.disease_params = [exhaled_air_inf, max_viral_deact_rate]\r\n\r\n # Precautionary Parameters\r\n mask_passage_prob = 0.1 # 1 = no masks, ~0.1 cloth, <0.05 N95\r\n risk_tolerance = 0.1 # expected transmissions per infector\r\n self.prec_params = [mask_passage_prob, risk_tolerance]\r\n\r\n # Convert MERV rating to aerosol filtration efficiency\r\n # merv: if not integer, floor it\r\n # aerosol_radius: must be <= 10\r\n @staticmethod\r\n def merv_to_eff(merv, aerosol_radius):\r\n if merv == 0:\r\n return 0\r\n eff = 0\r\n merv = numpy.floor(Indoors.clamp(merv, 1, 20))\r\n merv_dict = Indoors.merv_dict\r\n for item in merv_dict:\r\n if item['merv'] == merv:\r\n if aerosol_radius < 1:\r\n eff = item['0.3-1']\r\n elif aerosol_radius < 3:\r\n eff = item['1-3']\r\n else:\r\n eff = item['3-10']\r\n\r\n return eff\r\n\r\n # Clamp value within range\r\n @staticmethod\r\n def clamp(n, smallest, largest):\r\n return max(smallest, min(n, largest))\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"indoors.py","file_name":"indoors.py","file_ext":"py","file_size_in_byte":9800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"356094556","text":"from bootstrap_datepicker_plus import DatePickerInput\nfrom django import forms\nfrom declaracion.models import (SueldosPublicos,IngresosVarios)\n\n\nclass SueldosPublicosForm(forms.ModelForm):\n class Meta:\n model = SueldosPublicos\n fields = '__all__'\n exclude = ['declaraciones', 'domicilios', 'observaciones']\n widgets = {'fecha_transaccion': DatePickerInput(options={\n \"format\": 'YYYY-MM-DD',\n \"locale\": \"es\",\n \"ignoreReadonly\": True,\n \"maxDate\": 'now'\n })}\nclass IngresosVariosForm(forms.ModelForm):\n class Meta:\n model = IngresosVarios\n fields = '__all__'\n exclude = ['declaraciones', 'domicilios', 'observaciones',\n 'cat_tipos_ingresos_varios', 'info_personal_var']\n widgets = {'es_transaccion': DatePickerInput(options={\n \"format\": 'YYYY-MM-DD',\n \"locale\": \"es\",\n \"ignoreReadonly\": True,\n \"maxDate\": 'now'\n })}\n\n","sub_path":"declaraciones/declaracion/forms/ingresos.py","file_name":"ingresos.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"68603665","text":"import uuid\n\nfrom django.contrib.sitemaps import ping_google\nfrom django.utils.text import slugify\nfrom django.core.validators import FileExtensionValidator\nfrom django.db import models\n\nfrom tinymce.models import HTMLField\n\nfrom .user import User\n\n\nclass Event(models.Model):\n \"\"\"\n This model contains the events data.\n \"\"\"\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n\n # Identity\n title = models.CharField(max_length=100, verbose_name=\"Título\")\n resume = models.CharField(max_length=250, verbose_name=\"Resumo\")\n description = HTMLField(verbose_name=\"Descrição\")\n\n slug = models.SlugField(\n max_length=500,\n unique=True,\n verbose_name=\"Slogan da página\",\n help_text=\"Utilizado para que o link da página torne-se fácil de ler por um humano\",\n )\n\n slideshow = models.BooleanField(\n default=False,\n verbose_name=\"Slideshow\",\n help_text=\"Selecione essa opção se deseja que o evento apareça na HomePage.\",\n )\n\n # Content\n image = models.ImageField(\n verbose_name=\"Imagem\",\n upload_to=\"events/\",\n validators=[\n FileExtensionValidator(\n [\"png\", \"jpg\", \"jpeg\"], \"Formato de imagem inválido (.png, .jpg, jpeg)\"\n )\n ],\n )\n\n icon = models.ImageField(\n verbose_name=\"Ícone\",\n upload_to=\"events/\",\n validators=[\n FileExtensionValidator(\n [\"png\", \"jpg\", \"jpeg\"], \"Formato de ícone inválido (.png, .jpg, jpeg)\"\n )\n ],\n )\n\n apresentation = models.FileField(\n verbose_name=\"Apresentação\",\n null=True,\n blank=True,\n upload_to=\"events/\",\n validators=[\n FileExtensionValidator(\n [\"pdf\", \"ppt\", \"pptx\"],\n \"Formato de apresentação inválido (.pdf, .ppt, .pptx)\",\n )\n ],\n )\n\n # Activity period\n starts_at = models.DateTimeField(verbose_name=\"Data de início\")\n ends_at = models.DateTimeField(verbose_name=\"Data de término\")\n\n # Monitoring\n created_at = models.DateTimeField(auto_now_add=True, verbose_name=\"Data de criação\")\n updated_at = models.DateTimeField(auto_now=True, verbose_name=\"Ultima atualização\")\n\n # Associations\n created_by = models.ForeignKey(\n User,\n blank=True,\n null=True,\n help_text=\"Usuário responsável pela criação do registro (evento).\",\n related_name=\"event_creator_set\",\n verbose_name=\"Criador\",\n on_delete=models.SET_NULL,\n )\n\n updated_by = models.ForeignKey(\n User,\n blank=True,\n null=True,\n help_text=\"Usuário responsável pela ultima atualização do registro (evento).\",\n related_name=\"event_updater_set\",\n verbose_name=\"Atualizador\",\n on_delete=models.SET_NULL,\n )\n\n class Meta:\n verbose_name = \"Evento\"\n verbose_name_plural = \"Eventos\"\n\n def __str__(self):\n return self.title\n\n def save(self, *args, **kwargs):\n self.slug = slugify(self.title)\n super(Event, self).save(*args, **kwargs)\n\n try:\n ping_google()\n except Exception:\n pass\n","sub_path":"apps/core/models/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"136837096","text":"import starganlib as sg\nfrom datasets.CelebA import CelebA\nfrom datasets.HotOneWrapper import HotOneWrapper\nimport os\nimport torch\nfrom torch.utils import data\n\nimport torchvision.datasets as datasets\n\nfrom torchvision import transforms as T\n\nif __name__ == '__main__':\n\n dirname = os.path.dirname(__file__)\n dataset1Path = os.path.join(dirname, './data/dataset1/train')\n\n crop_size=178\n image_size=128\n transform = []\n transform.append(T.RandomHorizontalFlip())\n transform.append(T.CenterCrop(crop_size))\n transform.append(T.Resize(image_size))\n transform.append(T.ToTensor())\n transform.append(T.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)))\n transform = T.Compose(transform)\n\n dataset1 = HotOneWrapper(datasets.ImageFolder(dataset1Path, transform=transform), 2)\n dataset2 = HotOneWrapper(datasets.ImageFolder(dataset1Path, transform=transform), 2)\n dataset3 = HotOneWrapper(datasets.ImageFolder(dataset1Path, transform=transform), 2)\n\n image_dir = \"E:/AlexU/master/Computer Vision - Marwan/project/stargan/data/CelebA_nocrop/images\"\n attr_path = \"E:/AlexU/master/Computer Vision - Marwan/project/stargan/data/list_attr_celeba.txt\"\n chosen_attributes = ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Male', 'Young']\n celeba = CelebA(image_dir, attr_path, chosen_attributes, transform=transform)\n\n hyper_parameters = sg.HyperParamters()\n stargan = sg.StarGAN(hyper_parameters)\n stargan.addDataset(dataset1, 2)\n stargan.addDataset(dataset2, 2)\n stargan.addDataset(dataset3, 2)\n stargan.addDataset(celeba, 5)\n \n training_parameters = sg.TrainingParams(\n num_iters=1\n )\n stargan.train(training_parameters)\n\n print(\"DONE ........\")\n print(torch.__path__)","sub_path":"example1.py","file_name":"example1.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"256155406","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n# Copyright 2006-2007 (C) Raster Software Vigo (Sergio Costas)\n# Copyright 2006-2007 (C) Peter Gill - win32 parts\n\n# This file is part of DeVeDe\n#\n# DeVeDe 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# DeVeDe 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\nfrom gi.repository import Gtk\nimport devede_other\n\nclass show_error:\n\t\n\tdef __init__(self,gladefile,message):\n\t\t\n\t\t\"\"\" Shows a window with an error \"\"\"\n\t\t\n\t\tself.newtree=devede_other.create_tree(self,\"werror_dialog\",gladefile,False)\n\t\tlabel=self.newtree.get_object(\"label_error_dialog\")\n\t\tlabel.set_text(message)\n\t\twindow=self.newtree.get_object(\"werror_dialog\")\n\t\twindow.show()\n\t\twindow.run()\n\t\twindow.hide()\n\t\twindow.destroy()\n\t\twindow=None\n\n\nclass show_warning:\n\t\n\tdef __init__(self,gladefile,message):\n\t\t\n\t\t\"\"\" Shows a window with an error \"\"\"\n\t\t\n\t\tself.newtree=devede_other.create_tree(self,\"wwarning_dialog\",gladefile,False)\n\t\tlabel=self.newtree.get_object(\"wwarning_dialog_text\")\n\t\tlabel.set_text(message)\n\t\twindow=self.newtree.get_object(\"wwarning_dialog\")\n\t\twindow.show()\n\t\twindow.run()\n\t\twindow.hide()\n\t\twindow.destroy()\n\t\twindow=None\n\n\nclass ask_exit:\n\t\n\tdef __init__(self,gladefile):\n\t\n\t\tself.newtree=devede_other.create_tree(self,\"wcancel_dialog\",gladefile,False)\n\t\tself.window=self.newtree.get_object(\"wcancel_dialog\")\n\t\t\n\tdef run(self):\n\t\tself.window.show()\n\t\tretval=self.window.run()\n\t\tself.window.hide()\n\t\tself.window.destroy()\n\t\tself.window=None\n\t\treturn retval\n\n\nclass ask_overwrite_onload:\n\t\n\tdef __init__(self,gladefile):\n\t\n\t\tself.newtree=devede_other.create_tree(self,\"wloosecurrent\",gladefile,False)\n\t\tself.window=self.newtree.get_object(\"wloosecurrent\")\n\t\t\n\tdef run(self):\n\t\tself.window.show()\n\t\tretval=self.window.run()\n\t\tself.window.hide()\n\t\tself.window.destroy()\n\t\tself.window=None\n\t\treturn retval\n\n\nclass ask_delete_title:\n\t\n\tdef __init__(self,titlename,gladefile):\n\t\t\n\t\tself.newtree=devede_other.create_tree(self,\"wdel_title_dialog\",gladefile,False)\n\t\tself.window=self.newtree.get_object(\"wdel_title_dialog\")\n\t\tlabel=self.newtree.get_object(\"what_title\")\n\t\tlabel.set_text(titlename)\n\t\n\tdef run(self):\n\t\tself.window.show()\n\t\tretval=self.window.run()\n\t\tself.window.hide()\n\t\tself.window.destroy()\n\t\tself.window=None\n\t\treturn retval\n\n\nclass ask_delete_chapter:\n\t\n\tdef __init__(self,titlename,gladefile):\n\t\t\n\t\tself.newtree=devede_other.create_tree(self,\"wdel_chapter_dialog\",gladefile,False)\n\t\tself.window=self.newtree.get_object(\"wdel_chapter_dialog\")\n\t\tlabel=self.newtree.get_object(\"labelchapter\")\n\t\tlabel.set_text(titlename)\n\t\n\tdef run(self):\n\t\tself.window.show()\n\t\tretval=self.window.run()\n\t\tself.window.hide()\n\t\tself.window.destroy()\n\t\tself.window=None\n\t\treturn retval\n\n\nclass ask_erase_all:\n\t\n\tdef __init__(self,gladefile):\n\t\t\n\t\tself.newtree=devede_other.create_tree(self,\"werase_dialog\",gladefile,False)\n\t\tself.window=self.newtree.get_object(\"werase_dialog\")\n\n\tdef run(self):\n\t\tself.window.show()\n\t\tretval=self.window.run()\n\t\tself.window.hide()\n\t\tself.window.destroy()\n\t\tself.window=None\n\t\treturn retval\n\n\nclass show_about:\n\n\tdef __init__(self,parent):\n\n\t\t\"\"\" Shows the About dialog \"\"\"\n\t\twindow=Gtk.AboutDialog.new()\n\t\twindow.set_transient_for(parent)\n\t\twindow.set_destroy_with_parent(True)\n\t\twindow.set_logo_icon_name(\"devede\")\n\t\twindow.set_program_name(\"DeVeDe\")\n\t\twindow.set_version(\"3.22.0beta1\")\n\t\twindow.set_website(\"http://www.rastersoft.com/programas/devede.html\")\n\t\twindow.set_license_type(Gtk.License.GPL_3_0)\n\t\twindow.set_authors([\n\t\t\t\"Sergio Costas \",\n\t\t\t\"Peter Gill (Win32 parts)\",\n\t\t\t\"Gustavo Sanchez \"])\n\t\twindow.set_copyright(\"(C) 2006-2012 Raster Software Vigo, Peter Gill and Gustavo Sanchez\")\n\t\twindow.set_translator_credits(\"\"\"Alex\nArnaud Leroy\nDaniel Nylander\nHagen Hoepfner\nHenrik Kristiansen\nHolger Wansing\nJoan Farrerons\nJoel Calado\nJose Sun\nJozef Riha\nLars-Erik Aunevik Labori\nLaszlo Csordas\nMarco de Freitas\nMartin Šín\nMaurizio Daniele\nMaxim Winckelmans\nMiguel Bouzada\nPatrick Monnerat\nQla\nV. Fotiadis\n大宝\"\"\")\n\t\twindow.run()\n\t\twindow.destroy()\n","sub_path":"devede_dialogs.py","file_name":"devede_dialogs.py","file_ext":"py","file_size_in_byte":4615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"136310670","text":"#!/usr/bin/python\n\nimport sys\nsys.path.append('..')\nimport common\n\ndef install(cfg, ttyid):\n\n\tif len(cfg) == 0:\n\t\treturn\n\tcfg1 = cfg[0]\n\n\tmysqlpwd = cfg1.get('mysqlpwd', '')\n\tif mysqlpwd is None or len(mysqlpwd) == 0:\n\t\tmysqlpwd = '123456'\t\n\n\tssh = common.SSH(cfg, ttyid)\n\tssh.upload(common.join(__file__, 'lamp-install.sh'), '/tmp/lamp-install.sh')\n\tssh.cmd('chmod u+x /tmp/lamp-install.sh', True)\n\tssh.cmd('/tmp/lamp-install.sh -p %s' % mysqlpwd, True)\n\tssh.close()\n\n\n","sub_path":"web/modules/lamp/lamp.py","file_name":"lamp.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"119590927","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\n\nVERSION=\"0.1\"\n\nsetup(\n name=\"aletools\",\n version=VERSION,\n description=\"Wren Lab GEO automated label extraction and validation tools\",\n author=\"Cory Giles, Chris Reighard, Xiavan Roopnarinesingh, Aleksandra Perz, Chase Brown, Hunter Porter\",\n author_email=\"xiavan_roopnarinesingh@ouhsc.edu\",\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)\",\n \"Natural Language :: English\",\n \"Operating System :: POSIX\",\n \"Programming Language :: Python :: 3.6\",\n \"Topic :: Scientific/Engineering :: Bio-Informatics\"\n ],\n license=\"AGPLv3+\",\n #packages=find_packages(),\n packages=[\"mle\"],\n package_dir={\"mle\": \"mle\"},\n #package_data={\"mle\": ['data/*.tsv']},\n include_package_data=True,\n scripts=[\"bin/ale\",\"bin/ale-validation\"],\n dependency_links=[\"https://gitlab.com/wrenlab/wrenlab.git\"]\n )\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"649245511","text":"# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack.package import *\n\n\nclass PySpglib(PythonPackage):\n \"\"\"Python bindings for C library for finding and handling\n crystal symmetries.\"\"\"\n\n homepage = \"https://atztogo.github.io/spglib/\"\n pypi = \"spglib/spglib-1.9.9.18.tar.gz\"\n\n version(\"1.16.1\", sha256=\"9fd2fefbd83993b135877a69c498d8ddcf20a9980562b65b800cfb4cdadad003\")\n version(\"1.9.9.18\", sha256=\"cbbb8383320b500dc6100b83d5e914a26a97ef8fc97c82d8921b10220e4126cd\")\n\n # Most Python packages only require setuptools as a build dependency.\n # However, spglib requires setuptools during runtime as well.\n depends_on(\"py-setuptools@18.0:\", type=(\"build\", \"run\"))\n depends_on(\"py-numpy\", type=(\"build\", \"run\"))\n","sub_path":"var/spack/repos/builtin/packages/py-spglib/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"622301417","text":"# -*- coding: Utf-8 -*-\nfrom PyQt5.QtCore import pyqtSignal, QObject\n\n\ndef BaseSignals(QObject):\n signalSetted = pyqtSignal(name='setted')\n signalUnSetted = pyqtSignal(name='unSetted')\n signalAddTask = pyqtSignal('PyQt_PyObject,PyQt_PyObject', name='addTask')\n signalTaskAdded = pyqtSignal('PyQt_PyObject', name='taskAdded')\n\n\n","sub_path":"common_blocks/interface_imitator/signals_mixin.py","file_name":"signals_mixin.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"76668018","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/khan/tests/test_schema.py\n# Compiled at: 2010-05-12 10:25:54\nfrom khan.schema import *\nfrom khan.utils.testing import *\n\nclass SchemaEntity(Schema):\n a = String()\n a_ = String(default='b_value')\n b = Int()\n b_ = Int(default=1)\n c = Unicode()\n c_ = Unicode(default='d_value')\n d = Boolean()\n d_ = Boolean(default=True)\n e = SBoolean()\n e_ = SBoolean(default='on')\n f = Float()\n f_ = Float(default=0.1)\n g = Double()\n g_ = Double(default=0.2)\n h = Choice(range(0, 100))\n j = DateTime()\n j_ = DateTime(default='2009-12-12 12:12:12')\n k = List(Int())\n k_ = List(Int(), default=range(20, 30))\n l = Set(Int())\n l_ = Set(Int(), default=set(range(40, 50)))\n m = PlainText()\n m_ = PlainText(default='abcd1234')\n n = Email()\n n_ = Email(default='test@test.com')\n o = URL()\n o_ = URL(default='http://test.com')\n\n\nclass TestSchema(TestCase):\n\n def setUp(self):\n self.schema = SchemaEntity()\n\n def test_string(self):\n self.assertEqual('base string', String().convert('base string'), 'string convert failed')\n self.assertEqual('unicode string', String().convert('unicode string'), 'string convert unicode failed')\n self.assertEqual('中文', String().convert('中文'), 'string convert unicode failed')\n self.assertEqual('中文', String(default='中文').convert(None), 'string convert failed')\n self.assertEqual('1', String().convert(1), 'string convert failed')\n self.assertEqual('True', String().convert(True), 'string convert failed')\n self.assertRaises(ValidationError, lambda x: String(required=True).convert(None), 'string convert failed')\n self.assertRaises(ValidationError, lambda x: String(min=2).convert('1'), 'string convert failed')\n self.assertRaises(ValidationError, lambda x: String(max=2).convert('123'), 'string convert failed')\n self.assertRaises(ValidationError, lambda x: String(min=1, max=3).convert('1234'), 'string convert failed')\n return\n\n def test_unicode(self):\n self.assertEqual('base string', Unicode().convert('base string'), 'unicode convert failed')\n self.assertEqual('unicode string', Unicode().convert('unicode string'), 'unicode convert unicode failed')\n self.assertEqual('中文', Unicode().convert('中文'), 'unicode convert unicode failed')\n self.assertEqual('中文', Unicode(default='中文').convert(None), 'unicode convert failed')\n self.assertEqual('中文', Unicode(default='中文').convert(None), 'unicode convert failed')\n self.assertEqual('中文', Unicode(default='中文').convert(None), 'default not encode')\n self.assertEqual('1', Unicode().convert(1), 'unicode convert failed')\n self.assertEqual('1', Unicode().convert(1), 'unicode convert failed')\n self.assertEqual('True', Unicode().convert(True), 'unicode convert failed')\n self.assertEqual('True', Unicode().convert(True), 'unicode convert failed')\n self.assertRaises(ValidationError, lambda x: Unicode(required=True).convert(None), 'unicode convert failed')\n return\n\n def test_int(self):\n self.assertEqual(1, Int().convert(1), 'int convert failed')\n self.assertEqual(1, Int(default=1).convert(None), 'int convert failed')\n return\n\n def test_boolean(self):\n self.assertEqual(True, Boolean().convert(True), 'boolean convert failed')\n self.assertNotEqual(True, Boolean().convert(False), 'boolean convert failed')\n self.assertNotEqual(True, Boolean(default=True).convert(None), 'boolean convert failed')\n return\n\n def test_sbool(self):\n for i in ['on', 'true', 'True', 'tRuE', -1, 0.1, True]:\n self.assertEqual(True, SBool().convert(i), 'boolean convert failed')\n\n for i in ['off', 'false', 'False', 'fAlSe', '', None]:\n self.assertEqual(False, SBool().convert(i), 'boolean convert failed')\n\n for i in ['other str', 'base string']:\n self.assertRaises(ValidationError, lambda x: SBool().convert(i), 'boolean convert failed')\n\n return\n\n def test_float(self):\n self.assertEqual(0.1, Float().convert(0.1), 'float convert failed')\n self.assertEqual(1.0, Float().convert(1), 'float convert failed')\n self.assertRaises(ValidationError, lambda x: Float().convert('str'), 'float convert failed')\n\n def test_double(self):\n self.assertEqual(0.1, Double().convert(0.1), 'float convert failed')\n self.assertEqual(1.0, Double().convert(1), 'float convert failed')\n self.assertEqual(1.0, Double(default=1.0).convert(None), 'float convert failed')\n self.assertRaises(ValidationError, lambda x: Double().convert('str'), 'float convert failed')\n return\n\n def test_choice(self):\n self.assertEqual(1, Choice(range(0, 100)).convert(1), 'choice convert failed')\n self.assertRaises(ValidationError, lambda x: Choice(range(0, 10)).convert(100), 'choice convert failed')\n\n def test_datetime(self):\n import datetime\n self.assertEqual(datetime.datetime(2009, 12, 12, 12, 12, 12), DateTime().convert('2009-12-12 12:12:12'), 'datetime convert failed')\n self.assertEqual(datetime.datetime(2009, 12, 12), DateTime(fmt='%Y-%m-%d').convert('2009-12-12'), 'datetime convert failed')\n self.assertRaises(ValidationError, lambda x: DateTime().convert('2009-12-12 12:12'), 'datetime convert failed')\n\n def test_list(self):\n self.assertEqual(range(0, 100), List(Int()).convert(range(0, 100)), 'list convert failed')\n self.assertEqual(['str', 'other'], List(String()).convert(['str', 'other']), 'list convert failed')\n self.assertRaises(ValidationError, lambda x: List(Int()).convert(['str', 'other']), 'list convert with type')\n self.assertEqual(['1', '2'], List(String()).convert(range(1, 3)), 'list convert with type')\n self.assertEqual(['', '1'], List(String()).convert(range(0, 2)), 'list convert with type')\n\n def test_set(self):\n self.assertEqual(set(range(0, 100)), Set(Int()).convert(range(0, 100)), 'list convert failed')\n self.assertEqual(set(['str', 'other']), Set(String()).convert(['str', 'other']), 'list convert failed')\n self.assertRaises(ValidationError, lambda x: Set(Int()).convert(['str', 'other']), 'list convert with type')\n self.assertEqual(set(['1', '2']), Set(String()).convert(range(1, 3)), 'list convert with type')\n self.assertEqual(set(['', '1']), Set(String()).convert(range(0, 2)), 'list convert with type')\n self.assertEqual(set(range(0, 3)), Set(Int()).convert([0, 1, 2, 2]), 'list convert failed')\n self.assertEqual(set(['str', 'other']), Set(String()).convert(['str', 'str', 'other']), 'list convert failed')\n\n def test_email(self):\n self.assertEqual('test@test.com', Email().convert('test@test.com'), 'email convert failed')\n self.assertEqual('test@default.com', Email(default='test@default.com').convert(None), 'email convert failed')\n return\n\n def test_url(self):\n self.assertEqual('http://www.khan.com', URL().convert('http://www.khan.com'), 'url convert failed')\n self.assertRaises(ValidationError, lambda x: URL().convert('http://'), 'url convert failed')\n\n def test_plain_text(self):\n self.assertEqual('abcd1234_-', PlainText().convert('abcd1234_-'), 'plaintext convert failed')\n\n def test_Schema(self):\n import datetime\n obj = dict(a='a', b=1, c='中文', d=True, e='on', f=0.1, g=0.2, h=1, j='2009-12-12 12:12:12', k=range(20, 30), l=set(range(40, 50)), m='abcd', n='test@test.com', o='http://test.com')\n self.assertEqual({'n_': 'test@test.com', \n 'l_': set([40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), \n 'f_': 0.1, \n 'g_': 0.2, 'e_': False, \n 'c_': 'd_value', \n 'a_': 'b_value', \n 'o_': 'http://test.com', \n 'b': 1, \n 'm_': 'abcd1234', \n 'k_': [\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29], \n 'a': 'a', \n 'c': '中文', \n 'j_': '2009-12-12 12:12:12', \n 'e': True, \n 'd': True, \n 'g': 0.2, \n 'f': 0.1, \n 'h': 1, \n 'k': [\n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29], \n 'j': datetime.datetime(2009, 12, 12, 12, 12, 12), \n 'm': 'abcd', \n 'l': set([40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), \n 'o': 'http://test.com', \n 'n': 'test@test.com', \n 'd_': False, \n 'b_': 1}, self.schema.convert(obj), 'Schema convert failed')\n\n class MySchema(Schema):\n s = String()\n b = Bool()\n\n myschema = MySchema()\n result = myschema.convert({'s': 1, 'b': 'b', 'd': 'extra'})\n self.assertTrue(result == {'s': '1', 'b': True, 'd': 'extra'})\n myschema = MySchema(allow_extra_fields=False)\n cb = lambda : myschema.convert({'s': 1, 'b': 'b', 'd': 'extra'})\n self.assertRaises(SchemaError, cb)\n myschema = MySchema(allow_extra_fields=True, filter_extra_fields=True)\n result = myschema.convert({'s': 1, 'b': 'b', 'd': 'extra'})\n self.assertTrue(result == {'s': '1', 'b': True})\n myschema = MySchema(default={'default': 1})\n result = myschema.convert(123)\n self.assertTrue(result == {'default': 1})","sub_path":"pycfiles/Khan-0.1.6dev-py2.6/test_schema.py","file_name":"test_schema.py","file_ext":"py","file_size_in_byte":9589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"332895024","text":"import asyncio, discord\r\nfrom operator import itemgetter\r\nfrom discord.ext import commands\r\nfrom Cogs import Utils, DisplayName\r\n\r\ndef setup(bot):\r\n\t# Add the bot and deps\r\n\tsettings = bot.get_cog(\"Settings\")\r\n\tbot.add_cog(DJRoles(bot, settings))\r\n\r\nclass DJRoles(commands.Cog):\r\n\r\n\t# Init with the bot reference, and a reference to the settings var and xp var\r\n\tdef __init__(self, bot, settings):\r\n\t\tself.bot = bot\r\n\t\tself.settings = settings\r\n\t\tglobal Utils, DisplayName\r\n\t\tUtils = self.bot.get_cog(\"Utils\")\r\n\t\tDisplayName = self.bot.get_cog(\"DisplayName\")\r\n\r\n\t@commands.command(pass_context=True)\r\n\tasync def adddj(self, ctx, *, role : str = None):\r\n\t\t\"\"\"Adds a new role to the dj list (bot-admin only).\"\"\"\r\n\t\tusage = 'Usage: `{}adddj [role]`'.format(ctx.prefix)\r\n\t\tif not await Utils.is_bot_admin_reply(ctx): return\r\n\r\n\t\tif role == None:\r\n\t\t\treturn await ctx.send(usage)\r\n\r\n\t\troleName = role\r\n\t\tif type(role) is str:\r\n\t\t\tif role.lower() == \"everyone\" or role.lower() == \"@everyone\":\r\n\t\t\t\trole = ctx.guild.default_role\r\n\t\t\telse:\r\n\t\t\t\trole = DisplayName.roleForName(roleName, ctx.guild)\r\n\t\t\tif not role:\r\n\t\t\t\tmsg = 'I couldn\\'t find *{}*...'.format(roleName)\r\n\t\t\t\treturn await ctx.send(Utils.suppressed(ctx,msg))\r\n\r\n\t\t# Now we see if we already have that role in our list\r\n\t\tpromoArray = self.settings.getServerStat(ctx.guild, \"DJArray\")\r\n\t\tif next((x for x in promoArray if str(x[\"ID\"])==str(role.id)),False):\r\n\t\t\tmsg = '**{}** is already in the list.'.format(role.name)\r\n\t\t\treturn await ctx.send(Utils.suppressed(ctx,msg))\r\n\r\n\t\t# If we made it this far - then we can add it\r\n\t\tpromoArray.append({ 'ID' : role.id, 'Name' : role.name })\r\n\t\tself.settings.setServerStat(ctx.guild, \"DJArray\", promoArray)\r\n\r\n\t\tmsg = '**{}** added to list.'.format(role.name)\r\n\t\tawait ctx.send(Utils.suppressed(ctx,msg))\r\n\t\t\r\n\t\t\r\n\t@commands.command(pass_context=True)\r\n\tasync def removedj(self, ctx, *, role : str = None):\r\n\t\t\"\"\"Removes a role from the dj list (bot-admin only).\"\"\"\r\n\t\tusage = 'Usage: `{}removedj [role]`'.format(ctx.prefix)\r\n\t\tif not await Utils.is_bot_admin_reply(ctx): return\r\n\t\tif role == None:\r\n\t\t\treturn await ctx.send(usage)\r\n\t\t# Name placeholder\r\n\t\troleName = role\r\n\t\tif type(role) is str:\r\n\t\t\tif role.lower() == \"everyone\" or role.lower() == \"@everyone\":\r\n\t\t\t\trole = ctx.guild.default_role\r\n\t\t\telse:\r\n\t\t\t\trole = DisplayName.roleForName(role, ctx.guild)\r\n\t\t# If we're here - then the role is a real one\r\n\t\tpromoArray = self.settings.getServerStat(ctx.guild, \"DJArray\")\r\n\t\t# Check by id first, then by name\r\n\t\tfound_role = next((x for x in promoArray if str(x[\"ID\"])==str(role.id)),False)\r\n\t\tif not found_role:\r\n\t\t\tfound_role = next((x for x in promoArray if x[\"Name\"].lower()==role.name.lower()),False)\r\n\t\tif found_role:\r\n\t\t\tpromoArray.remove(found_role)\r\n\t\t\tself.settings.setServerStat(ctx.guild, \"DJArray\", promoArray)\r\n\t\t\tmsg = '**{}** removed successfully.'.format(found_role['Name'])\r\n\t\t\treturn await ctx.send(Utils.suppressed(ctx,msg))\r\n\t\t# If we made it this far - then we didn't find it\r\n\t\tmsg = '**{}** not found in list.'.format(role)\r\n\t\tawait ctx.send(Utils.suppressed(ctx,msg))\r\n\r\n\r\n\t@commands.command(pass_context=True)\r\n\tasync def listdj(self, ctx):\r\n\t\t\"\"\"Lists dj roles and id's.\"\"\"\r\n\t\tpromoArray = self.settings.getServerStat(ctx.guild, \"DJArray\")\r\n\t\tpromoSorted = sorted(promoArray, key=itemgetter('Name'))\r\n\t\tif not len(promoSorted):\r\n\t\t\troleText = \"There are no dj roles set yet. Use `{}adddj [role]` to add some.\".format(ctx.prefix)\r\n\t\t\treturn await ctx.channel.send(roleText)\r\n\t\troleText = \"__**Current DJ Roles:**__\\n\\n\"\r\n\t\tfor arole in promoSorted:\r\n\t\t\trole = ctx.guild.get_role(int(arole[\"ID\"]))\r\n\t\t\troleText += \"**{}** (removed from server)\\n\".format(arole[\"Name\"]) if role is None else \"**{}** (ID : `{}`)\\n\".format(role.name, arole[\"ID\"])\r\n\t\tawait ctx.send(Utils.suppressed(ctx,roleText))","sub_path":"Cogs/DJRoles.py","file_name":"DJRoles.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"55297367","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n\nimport random\nfrom contextlib import contextmanager\n\nimport numpy as np\nimport timeit\nimport torch\nimport operator\nfrom functools import reduce\n\n\nprod = lambda l: reduce(operator.mul, l, 1)\ntorch.set_default_tensor_type(torch.DoubleTensor)\n\ndef cross_product(vec3a, vec3b):\n vec3a = convert_into_at_least_2d_pytorch_tensor(vec3a)\n vec3b = convert_into_at_least_2d_pytorch_tensor(vec3b)\n skew_symm_mat_a = vector3_to_skew_symm_matrix(vec3a)\n return (skew_symm_mat_a @ vec3b.unsqueeze(2)).squeeze(2)\n\n\ndef bfill_lowertriangle(A: torch.Tensor, vec: torch.Tensor):\n ii, jj = np.tril_indices(A.size(-2), k=-1, m=A.size(-1))\n A[..., ii, jj] = vec\n return A\n\n\ndef bfill_diagonal(A: torch.Tensor, vec: torch.Tensor):\n ii, jj = np.diag_indices(min(A.size(-2), A.size(-1)))\n A[..., ii, jj] = vec\n return A\n\n\ndef vector3_to_skew_symm_matrix(vec3):\n vec3 = convert_into_at_least_2d_pytorch_tensor(vec3)\n batch_size = vec3.shape[0]\n skew_symm_mat = vec3.new_zeros((batch_size, 3, 3))\n skew_symm_mat[:, 0, 1] = -vec3[:, 2]\n skew_symm_mat[:, 0, 2] = vec3[:, 1]\n skew_symm_mat[:, 1, 0] = vec3[:, 2]\n skew_symm_mat[:, 1, 2] = -vec3[:, 0]\n skew_symm_mat[:, 2, 0] = -vec3[:, 1]\n skew_symm_mat[:, 2, 1] = vec3[:, 0]\n return skew_symm_mat\n\n\ndef torch_square(x):\n return x * x\n\n\ndef exp_map_so3(omega, epsilon=1.0e-14):\n omegahat = vector3_to_skew_symm_matrix(omega).squeeze()\n\n norm_omega = torch.norm(omega, p=2)\n exp_omegahat = (torch.eye(3) +\n ((torch.sin(norm_omega) / (norm_omega + epsilon)) * omegahat) +\n (((1.0 - torch.cos(norm_omega)) / (torch_square(norm_omega + epsilon))) *\n (omegahat @ omegahat))\n )\n return exp_omegahat\n\n\ndef set_rng_seed(rng_seed: int) -> None:\n random.seed(rng_seed)\n torch.manual_seed(rng_seed)\n np.random.seed(rng_seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(rng_seed)\n\n\ndef move_optimizer_to_gpu(optimizer):\n \"\"\"\n Move the optimizer state to GPU, if necessary.\n After calling, any parameter specific state in the optimizer\n will be located on the same device as the parameter.\n \"\"\"\n for param_group in optimizer.param_groups:\n for param in param_group['params']:\n if param.is_cuda:\n param_state = optimizer.state[param]\n for k in param_state.keys():\n if isinstance(param_state[k], torch.Tensor):\n param_state[k] = param_state[k].cuda(device=param.get_device())\n\n\ndef require_and_zero_grads(vs):\n for v in vs:\n v.requires_grad_(True)\n try:\n v.grad.zero_()\n except AttributeError:\n pass\n\n\ndef compute_mse_per_dim(prediction, ground_truth, data_axis=0):\n mse_per_dim = ((prediction - ground_truth) ** 2).mean(axis=data_axis)\n return mse_per_dim\n\n\ndef compute_mse_loss(prediction, ground_truth, data_axis=0):\n mse_per_dim = compute_mse_per_dim(prediction, ground_truth, data_axis)\n return mse_per_dim.mean()\n\n\ndef compute_mse_var_nmse_per_dim(prediction, ground_truth, data_axis=0, is_adding_regularizer=True, save_filepath=None):\n mse_per_dim = compute_mse_per_dim(prediction, ground_truth, data_axis)\n var_ground_truth_per_dim = ground_truth.var(axis=data_axis)\n if (is_adding_regularizer):\n reg = 1.0e-14\n else:\n reg = 0.0\n nmse_per_dim = mse_per_dim / (var_ground_truth_per_dim + reg)\n if save_filepath is not None:\n from fair_robot_envs.env.utils.pyplot_util import subplot_ND\n\n traj_list = [prediction, ground_truth]\n subplot_ND(NDtraj_list=traj_list,\n title='prediction_vs_ground_truth',\n Y_label_list=['dim %d' % i for i in range(prediction.shape[1])],\n fig_num=0,\n label_list=['prediction', 'ground_truth'],\n is_auto_line_coloring_and_styling=True,\n save_filepath=save_filepath,\n X_label='time index')\n return mse_per_dim, var_ground_truth_per_dim, nmse_per_dim\n\n\ndef compute_nmse_per_dim(prediction, ground_truth, data_axis=0, is_adding_regularizer=True, save_filepath=None):\n [_, _, nmse_per_dim] = compute_mse_var_nmse_per_dim(prediction, ground_truth,\n data_axis, is_adding_regularizer, save_filepath)\n return nmse_per_dim\n\n\ndef compute_nmse_loss(prediction, ground_truth, data_axis=0, is_adding_regularizer=True):\n nmse_per_dim = compute_nmse_per_dim(prediction, ground_truth, data_axis, is_adding_regularizer)\n return nmse_per_dim.mean()\n\n\ndef convert_into_pytorch_tensor(variable):\n if isinstance(variable, torch.Tensor):\n return variable\n elif isinstance(variable, np.ndarray):\n return torch.Tensor(variable)\n else:\n return torch.Tensor(variable)\n\n\ndef convert_into_at_least_2d_pytorch_tensor(variable):\n tensor_var = convert_into_pytorch_tensor(variable)\n if len(tensor_var.shape) == 1:\n return tensor_var.unsqueeze(0)\n else:\n return tensor_var\n\n\ndef list2dict(list_dict):\n dict_list = {key: [] for key in list_dict[0]}\n for element in list_dict:\n for key in element.keys():\n dict_list[key].append(element[key])\n return dict_list\n\n\ndef extract_inv_dyn_dataset(dataset):\n inv_dyn_dataset = dict()\n T = dataset['joint_vel'].shape[0]\n inv_dyn_dataset['N_data'] = T-1\n\n keys = ['joint_pos', 'joint_vel', 'joint_acc', 'torque_applied']\n for key in keys:\n inv_dyn_dataset[key] = dataset[key][:(T-1), :]\n assert(inv_dyn_dataset[key].shape[0] == T-1)\n\n next_keys = ['joint_pos', 'joint_vel', 'joint_acc']\n for key in next_keys:\n inv_dyn_dataset['next_' + key] = dataset[key][1:, :]\n assert(inv_dyn_dataset['next_' + key].shape[0] == T-1)\n return inv_dyn_dataset\n\n\ndef combine_datasets(dataset_list):\n combined_dataset = dict()\n N_data = 0\n dt = None\n keys = dataset_list[0].keys()\n for dataset in dataset_list:\n for key in keys:\n if key == 'N_data':\n N_data += dataset['N_data']\n elif key == 'dt':\n if dt is None:\n dt = dataset['dt']\n else:\n assert (dt == dataset['dt'])\n else:\n if key not in combined_dataset.keys():\n combined_dataset[key] = list()\n combined_dataset[key].append(dataset[key])\n for key in keys:\n if key == 'N_data':\n combined_dataset['N_data'] = N_data\n elif key == 'dt':\n combined_dataset['dt'] = dt\n else:\n combined_dataset[key] = np.concatenate(combined_dataset[key])\n if 'N_data' in keys:\n assert combined_dataset[key].shape[0] == N_data\n return combined_dataset\n\n\ndef plot_grad_flow(viz, env, named_parameters, window_name=\"grad_bar\"):\n '''Plots the gradients flowing through different layers in the net during training.\n Can be used for checking for possible gradient vanishing / exploding problems.\n Usage: Plug this function in Trainer class after loss.backwards() as\n \"plot_grad_flow(self.model.named_parameters())\" to visualize the gradient flow'''\n ave_grads = []\n max_grads = []\n num_nan_grads = []\n layers = []\n for n, p in named_parameters:\n if (p.requires_grad) and (\"bias\" not in n):\n if p.grad is not None:\n assert p.grad is not None, \"Layer \" + str(n) + \" does not have any gradients!!!\"\n layers.append(n)\n ave_grads.append(p.grad.abs().mean())\n max_grads.append(p.grad.abs().max())\n num_nan_grads.append(torch.sum(torch.isnan(p.grad.abs()) | torch.isinf(p.grad.abs()))/prod(list(p.grad.abs().shape)))\n if len(layers) < 2:\n dictionary = dict(\n stacked=False,\n legend=['max-gradient', 'mean-gradient']\n )\n else:\n dictionary = dict(\n stacked=False,\n legend=['max-gradient', 'mean-gradient'],\n rownames=layers,\n title=window_name\n )\n viz.bar(\n X=np.array([max_grads, ave_grads]).transpose([1, 0]),\n env=env,\n win=window_name,\n opts=dictionary\n )\n return torch.stack(max_grads), torch.stack(ave_grads), torch.stack(num_nan_grads), layers\n\n\n@contextmanager\ndef temp_require_grad(vs):\n prev_grad_status = [v.requires_grad for v in vs]\n require_and_zero_grads(vs)\n yield\n for v, status in zip(vs, prev_grad_status):\n v.requires_grad_(status)\n\n\nclass Timer(object):\n\n def __enter__(self):\n self.t_start = timeit.default_timer()\n return self\n\n def __exit__(self, _1, _2, _3):\n self.t_end = timeit.default_timer()\n self.dt = self.t_end - self.t_start\n","sub_path":"differentiable_robot_model/rigid_body/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"158259034","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 21 13:45:05 2019\r\n\r\n@author: Arthur\r\n\"\"\"\r\nimport sys\r\nsys.path.insert(1, \"C:\\\\Users\\\\Arthur\\\\Documents\\\\Study\\\\Internship VanBoven\\\\Project - Identifying Broccoli Heads\\\\Code\\\\Modules\")\r\nimport image_processing as ip\r\nimport detect_plants as dp\r\n\r\nimport numpy as np\r\nimport cv2\r\nimport time\r\n\r\ntime_begin = time.time()\r\n\r\ndir = \"C:\\\\Users\\\\Arthur\\\\Documents\\\\Study\\\\Internship VanBoven\\\\\"\r\nimg_path = \"Operational Tasks\\\\Schol\\\\c08_biobrass-Schol-201907261210-GR_cropped.tif\"\r\n#img_path = \"Operational Tasks\\\\Wever west\\\\c01_verdonk-Wever west-201907170749-GR.tif\"\r\nimg_path = dir + img_path\r\n#img_path = dir + \"Data\\\\190723_Demo_Hendrik_de_Heer\\\\clipped_imagery\\\\20190513_clip.tif\"\r\n\r\n# Determine factor for scaling parameters\r\nxpix,ypix = ip.PixelSize(img_path)\r\npar_fact = 7.68e-5/(xpix*ypix)\r\n\r\nsigma = 8.0*par_fact\r\nsigma_grass = 2.0*par_fact\r\nneighborhood_size = 30*par_fact\r\nthreshold = 2.0\r\n\r\nblock_size = 3000\r\n\r\n# Get information of image partition\r\ndiv_shape = ip.divide_image(img_path, block_size, remove_size=block_size)\r\nds, ysize, xsize, yblocks, xblocks, block_size = div_shape\r\n\r\n# Detect center of plants using local minima\r\nxcoord, ycoord = dp.DetectLargeImage(img_path, div_shape, sigma, neighborhood_size, threshold, sigma_grass)\r\n# Write to shapefile\r\ndp.WriteShapefilePoints(ds, xcoord, ycoord)\r\n\r\n# Create array with the positions of the coordinates\r\narr_points = np.zeros([yblocks*block_size//10,xblocks*block_size//10], dtype='uint8')\r\narr_points[(ycoord/10).astype(int),(xcoord/10).astype(int)] = 1\r\narr_points = cv2.dilate(arr_points,np.ones((3,3),np.uint8),iterations = 1)\r\n\r\n# Detect lines using Hough Lines Transform\r\nlines = dp.HoughLinesP(arr_points, par_fact)\r\n# Write to shapefile\r\nlines = lines.reshape(lines.shape[0],4) * 10\r\ndp.WriteShapefileLines(ds, lines[:,0], lines[:,1], lines[:,2], lines[:,3])\r\n\r\ntime_end = time.time()\r\nprint('Total time: {}'.format(time_end-time_begin))\r\n","sub_path":"Detect.py","file_name":"Detect.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"569864540","text":"import numpy as np\nfrom PIL import ImageGrab\nimport cv2\nimport time\n\ndef screen_record(): \n probes = [cv2.imread(\"units/probe1.png\",0),cv2.imread(\"units/probe2.png\",0),cv2.imread(\"units/probe1.png\",0)]\n probes_wh = [ i.shape[::-1] for i in probes]\n print(probes_wh)\n\n #KAZEKAZEKAZEKAZE\n #cv2.imshow('probe', probes[0])\n #for i in probes:\n\n # sift = cv2.KAZE_create()\n # (kps, descs) = sift.detectAndCompute(i, None)\n # print(\"# kps: {}, descriptors: {}\".format(len(kps), descs.shape))\n last_time = time.time()\n while(True):\n # 800x600 windowed mode\n printscreen = np.array(ImageGrab.grab(bbox=(8,40,1032,744)))\n print('loop took {} seconds'.format(time.time()-last_time))\n last_time = time.time()\n gray_image = cv2.cvtColor(printscreen, cv2.COLOR_BGR2GRAY)\n #KAZEKAZEKAZEKAZE\n #ret = sift.detect(printscreen)\n #print(ret)\n for probe,probe_wh in zip(probes,probes_wh):\n r = cv2.matchTemplate(probe,gray_image, cv2.TM_CCORR_NORMED)\n print(r)\n threshold = 0.87\n loc = np.where( r >= threshold)\n for pt in zip(*loc[::-1]):\n cv2.rectangle(printscreen,\n pt,(pt[0]+probe_wh[0],pt[1]+probe_wh[1]),(0,0,255),2)\n \n cv2.imshow('window',cv2.cvtColor(printscreen, cv2.COLOR_BGR2RGB))\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n\nscreen_record()\n","sub_path":"screen_grab.py","file_name":"screen_grab.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"43308697","text":"from django.views import View\nfrom onlineapp.models import *\nfrom onlineapp.forms import *\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\n\nclass AddStudentView(LoginRequiredMixin, View):\n login_url = '/login/'\n\n def get(self, request, *args, **kwargs):\n form1 = AddStudent()\n form2 = AddMockTest1()\n if kwargs.get('student_id'):\n student = Student.objects.get(id=kwargs.get('student_id'))\n mocktest1 = MockTest1.objects.get(student_id=kwargs.get('student_id'))\n form1 = AddStudent(instance=student)\n form2 = AddMockTest1(instance=mocktest1)\n return render(\n request,\n 'add_student.html',\n {'form1': form1, 'form2': form2, 'title': \"Add student\", 'logged_in': request.user.is_authenticated})\n\n def post(self, request, *args, **kwargs):\n form1 = AddStudent(request.POST)\n form2 = AddMockTest1(request.POST)\n if kwargs.get('student_id'):\n student = Student.objects.get(id=kwargs.get('student_id'))\n mocktest1 = MockTest1.objects.get(student_id=kwargs.get('student_id'))\n form1 = AddStudent(request.POST, instance=student)\n form2 = AddMockTest1(request.POST, instance=mocktest1)\n college = get_object_or_404(College, id=kwargs.get('college_id'))\n else:\n form1 = AddStudent(request.POST)\n form2 = AddMockTest1(request.POST)\n college = get_object_or_404(College, id=kwargs.get('college_id'))\n if form1.is_valid() and form2.is_valid():\n student = form1.save(commit=False)\n student.college = college\n student.save()\n mocktest1 = form2.save(commit=False)\n mocktest1.student = student\n mocktest1.total = str(mocktest1.problem1+mocktest1.problem2+mocktest1.problem3+mocktest1.problem4)\n mocktest1.save()\n return redirect('colleges_html')\n\n\nclass DeleteStudentView(LoginRequiredMixin, View):\n login_url = '/login/'\n def get(self, request, *args, **kwargs):\n if kwargs.get('student_id'):\n mocktest1 = get_object_or_404(MockTest1, student_id=kwargs.get('student_id'))\n mocktest1.delete()\n student = get_object_or_404(Student, id=kwargs.get('student_id'))\n student.delete()\n return redirect('colleges_html')","sub_path":"classproject/onlineapp/views/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"504478476","text":"import matplotlib.pyplot as plt\n\ndef plot_nestedcv(full_train_mse, test_mse, alphas, title=\"\", regr_name=\"regr\"):\n\n plt.plot(full_train_mse * 100, label='Full Train MSE')\n plt.plot(test_mse * 100, label='Test MSE')\n plt.title(title)\n plt.ylabel(\"Mean Squared Errror (x100)\")\n plt.xlabel('Fold Index')\n plt.legend()\n plt.ylim((0,0.04))\n plt.savefig(f\"{regr_name}_cv_plot.png\", dpi=196)\n #plt.show()\n\n # Show alphas.\n plt.plot(alphas, '--', label='Alpha')\n #plt.show()\n\ndef plot_pred_v_reality(real, pred, base=None, title=\"\", regr_name=\"regr\"):\n \"\"\"Plots a scatter plot with matching residual lines for both predictions\n and the true data.\n\n Args:\n times (np.ndarray):\n real (np.ndarray):\n pred (np.ndarray):\n \"\"\"\n times = list(range(len(real)))\n plt.vlines(times, real, pred, linestyle='dashed', alpha=0.5, zorder=-2)\n plt.scatter(times, real, s=30, marker='.', label=\"True\")\n plt.scatter(times, pred, s=30, marker='x', label=\"Prediction\")\n if base is not None:\n plt.plot(times, base, label='Baseline', zorder=-1, color='k')\n plt.title(title)\n plt.xlabel(\"Test Sample Index\")\n plt.ylabel('Peak Ozone, Parts Per Million')\n #plt.grid()\n plt.legend()\n plt.savefig(f\"{regr_name}_pred_true.png\", dpi=196)\n plt.show()\n\n","sub_path":"plotting/timecv.py","file_name":"timecv.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"554471593","text":"codVertice = 1\ncodSet = 1\nclass Vertice:\n\tdef __init__(self, latitude, longitude):\n\t\tglobal codVertice\n\t\tself.cod = codVertice\n\t\tself.latitude = latitude\n\t\tself.longitude = longitude\n\t\tcodVertice += 1\n\tdef calcularDistancia(self, vertice2):\n\t\tauxLat = self.latitude - vertice2.latitude\n\t\tauxLong = self.longitude - vertice2.longitude\n\t\t\n\t\tdistancia = (auxLat*auxLat)+(auxLong*auxLong)\n\t\tdistancia = distancia ** (1/2)\n\t\treturn distancia\n\nclass Set:\n\tdef __init__(self, arrVertices):\n\t\tglobal codSet\n\t\tself.arrVertices = arrVertices\n\t\tcodSet += 1\n\t\t\nvertices = [Vertice(82, 76), Vertice(96, 44), Vertice(50, 5), Vertice(49, 8), Vertice(13, 7), Vertice(29, 89), Vertice(58, 30), Vertice(84, 39), Vertice(14, 24), Vertice(2, 39), Vertice(3, 82), Vertice(5, 10), Vertice(98, 52), Vertice(84, 25), Vertice(61, 59), Vertice(1, 65), Vertice(88, 51), Vertice(91, 2), Vertice(19, 32), Vertice(93, 3), Vertice(50, 93), Vertice(98, 14), Vertice(5, 42), Vertice(42, 9), Vertice(61, 62), Vertice(9, 97), Vertice(80, 55), Vertice(57, 69), Vertice(23, 15), Vertice(20, 70), Vertice(85, 60), Vertice(98, 5)]\n\nsets = [Set([12, 5]), Set([13, 2]), Set([26, 11]), Set([18, 20, 22, 32]), Set([28, 15, 25]), Set([4, 3, 24]), Set([16]), Set([10, 23]), Set([21]), Set([7]), Set([14, 8]), Set([6]), Set([30]), Set([29]), Set([27, 17, 31]), Set([19, 9])]\n\nprint (\"Arr vertices: \" + str(sets[0].arrVertices))\n\nmenorDistancia = 999\ntuplaMenorDistancia = None\n\nfor i in range(0, 32):\n\tfor j in range(0 ,32):\n\t\tauxDistancia = vertices[i].calcularDistancia(vertices[j])\n\t\tif i != j and auxDistancia < menorDistancia:\n\t\t\tmenorDistancia = auxDistancia\n\t\t\ttuplaMenorDistancia = (i, j)\nprint (menorDistancia)\nprint (tuplaMenorDistancia)\nprint (\"Lat: \" + str(vertices[tuplaMenorDistancia[0]].latitude))\nprint (\"Long: \" + str(vertices[tuplaMenorDistancia[0]].longitude))\nprint (\"Lat2: \" + str(vertices[tuplaMenorDistancia[1]].latitude))\nprint (\"Long2: \" + str(vertices[tuplaMenorDistancia[1]].longitude))\n","sub_path":"lixo/trabalho1.py","file_name":"trabalho1.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"614314946","text":"import requests\nimport json\n\ndef getOrcidId(givenName,familyName):\n headers = {\"Accept\": \"application/json\"}\n\n #parameters= given-names, family-name\n #searching with the parameters and adding boolean operators to get the best result\n api = \"https://pub.orcid.org/v3.0/search/?q=given-names:\"+givenName+\"+AND+family-name:\"+familyName+\"+AND+(('TU+Chemnitz'+OR+'Technical+University+of+Chemnitz'+OR+'Technische+Universität+Chemnitz')+OR+email:*tu-chemnitz*)\"\n \n resp = requests.get(api,headers=headers)\n \n try:\n parsejson = resp.json()[\"result\"][0][\"orcid-identifier\"]\n return parsejson[\"uri\"]\n except:\n parsejson = \"\" #returns empty result if no orcidid found\n return parsejson\n \n \n\n","sub_path":"researchee/orcidId.py","file_name":"orcidId.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"112970605","text":"import pymysql\n\nDB_CONFIG = { # 数据库配置\n 'host': '172.17.146.238',\n 'port': 3306,\n 'user': 'root',\n 'passwd': 'Sui@911120',\n 'db': 'du_alarm_app',\n 'charset': 'utf8',\n}\nid = 'chemin'\nlevel = 4\n\ntry:\n conn_db = pymysql.connect(**DB_CONFIG)\n cursor = conn_db.cursor(cursor=pymysql.cursors.DictCursor)\nexcept Exception as error:\n # write_logs(\"alarm.err\", RECORD_LOG_STATUS, error, LOG_FILE_PATH)\n # return 3000\n print(error)\nelse:\n cursor.execute(\"select id,ding_user,email_user,wechat_user,chat_name,title,ding_chat_id from \\\n alarm_info where owner=%s and level=%s;\", (id, level))\n alarm_session = cursor.fetchall()\n print(alarm_session)","sub_path":"osa/alarm_v2/test_/db_test.py","file_name":"db_test.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306034459","text":"import random\nimport gensafeprime\nfrom Crypto.Util import number\nfrom math import gcd\nfrom time import sleep\n\nglobal first_primes_list\nglobal encrypt_key\nglobal ciphertext\nglobal n\n\nclass sender:\n\n def __init__(self):\n self.plaintext = None\n self.set_message()\n self.encrypt()\n\n def set_message(self):\n print(\"Plaintext:\",end=\"\")\n inp = int(input())\n self.plaintext = inp\n\n def encrypt(self):\n global ciphertext\n global encrypt_key\n \n ciphertext = pow(self.plaintext,encrypt_key,n)\n print(\"\\nCiphertext:\",ciphertext,'\\n')\n\nclass receiver: #Receiver Class Described\n\n def __init__(self): #Constructor\n global n\n global encrypt_key\n \n self.p, self.q = None, None #The two prime numbers chosen (Hide somehow)\n n = None #n = pq\n self.decrypt_key = None #d is the private decryption key\n self.toit_n = None #represents Euler toitent function for n\n self.plaintext = None #Stores decrypted message\n \n self.generate_prime_pair()\n self.gen_encrypt_key()\n self.gen_decrypt_key()\n\n def generate_prime_pair(self,b=512):\n '''n = number of bits used for the prime generation'''\n global n\n \n self.p = gen_prime_2(b) \n self.q = gen_prime_2(b)\n n = self.p * self.q\n self.toit_n = (self.p-1)*(self.q-1) #Calculate Euler Toitent of n\n\n def gen_decrypt_key(self):\n global encrypt_key\n \n self.decrypt_key = modular_inverse(encrypt_key,self.toit_n) % self.toit_n\n\n def decrypt(self):\n global ciphertext\n global n\n\n self.plaintext = pow(ciphertext,self.decrypt_key,n)\n print(\"Plaintext:\",self.plaintext)\n\n def gen_encrypt_key(self): #generate random coprimes wrt toit_n\n global encrypt_key\n\n encrypt_key = find_coprime(self.toit_n)\n \n \n \n#########################UNDERSTAND##############################\n\ndef modular_inverse(a, m): \n m0 = m \n y = 0\n x = 1\n \n if (m == 1) : \n return 0\n \n while (a > 1) : \n q = a // m \n t = m \n m = a % m \n a = t \n t = y \n y = x - q * y \n x = t \n \n if (x < 0) : \n x = x + m0 \n \n return x\n\n\ndef eval_mod_exponent(x, y, p) : \n res = 1 \n x = x % p \n \n while (y > 0) : \n if ((y & 1) == 1) : \n res = (res * x) % p \n \n y = y >> 1\n x = (x * x) % p \n return res \n \n#################################################################\n\ndef find_coprime(a):\n '''Find a random coprime of a which is < a'''\n\n r = random.randrange(2,a-1)\n while True:\n if gcd(r,a) == 1:\n return r\n elif r == a-1:\n r = random.randrange(2,a-1)\n else:\n r += 1\n\ndef crypto_prime(n):\n return number.getPrime(n)\n\ndef erik_tews_SSL_prime(n):\n return gensafeprime.generate(n)\n\ndef first_primes(t):\n '''Generate the first prime numbers upto t using Eratosthenes'''\n global first_primes_list\n first_primes_list = []\n \n test_lis = [i for i in range(2,t+1)]\n\n for i in test_lis:\n first_primes_list.append(i)\n\n for x in range(2,(t+1)//i+1):\n if x*i in test_lis:\n test_lis.remove(x*i)\n\ndef gen_prime_1(n):\n\n while True:\n sample = random_n(n) #Randomly choose n bit number\n \n for i in first_primes_list:\n if sample%i == 0:\n break\n if sample < 4000000:\n if i > sample**(1/2):\n return sample\n else: return sample\n\ndef miller_rabin_test(n):\n \"\"\" Miller-Rabin primality test. \"\"\"\n \n if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:\n return False\n if n==2 or n==3 or n==5 or n==7:\n return True\n \n s = 0\n d = n-1\n while d%2==0:\n d >>= 1 #Bitwise Right Shift. Same as dividing d by 2\n s+=1\n assert(2**s * d == n-1)\n \n def trial_composite(a):\n if pow(a, d, n) == 1:\n return False\n for i in range(s):\n if pow(a, 2**i * d, n) == n-1:\n return False\n return True \n \n for i in range(20): #number of trials\n a = random.randrange(2, n)\n if trial_composite(a):\n return False\n \n return True \n \ndef gen_prime_2(n):\n '''Incorporates all tests to generate prime'''\n \n while True:\n sample = gen_prime_1(n) #Generate Random No. based on small prime division\n\n #print(\"TESTING:\",sample)\n\n #Fermat Takes too long, thus disabled. Enable to add Fermat Test\n '''\n if fermat_test(sample) == False: #Apply Fermat Test\n print(\" FERMAT FAILED \") \n continue\n '''\n \n if miller_rabin_test(sample) == False: #Apply Miller Rabin Test\n #print(\" RABIN FAILED \")\n continue\n \n #print(\" PASSED \")\n return sample\n\ndef fermat_test(p,a=2):\n '''Using base (a) = 2'''\n if a**(p-1) % p == 1 % p:\n return True\n else:\n return False\n\ndef random_n(n):\n return(random.randrange(2**(n-1)+1,2**n-1))\n\n\nfirst_primes(2000) #Generate primes upto 2000. Increase for more filtered values\n\n##print(\"RSA Encryption/Decryption\")\n##sleep(1)\n##\n##r = receiver()\n##s = sender()\n##r.decrypt()\n## \n","sub_path":"proactive_scripts/RSA.py","file_name":"RSA.py","file_ext":"py","file_size_in_byte":5422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"646006802","text":"#encoding=utf8\r\n# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\nimport os\r\nfrom os.path import join\r\nimport paddle\r\nfrom enum import Enum\r\nimport multiprocessing\r\nimport argparse\r\n\r\nclass parameters():\r\n bpr_batch = 2048\r\n recdim = 64\r\n layer = 3\r\n lr = 0.001\r\n decay = 1e-4\r\n dropout = 0\r\n keepprob = 0.6\r\n a_fold = 100\r\n testbatch = 100\r\n dataset = 'my_data'\r\n path = \"./checkpoints\"\r\n tensorboard = 1\r\n comment = 'lgn'\r\n load = 0\r\n epochs = 1000\r\n multicore = 0\r\n pretrain = 0\r\n seed = 2020\r\n model = 'lgn'\r\n topks = \"[20]\"\r\n\r\n\r\ndef parse_args():\r\n parser = argparse.ArgumentParser(description=\"Go lightGCN\")\r\n parser.add_argument('--bpr_batch', type=int,default=2048,\r\n help=\"the batch size for bpr loss training procedure\")\r\n parser.add_argument('--recdim', type=int,default=64,\r\n help=\"the embedding size of lightGCN\")\r\n parser.add_argument('--layer', type=int,default=3,\r\n help=\"the layer num of lightGCN\")\r\n parser.add_argument('--lr', type=float,default=0.001,\r\n help=\"the learning rate\")\r\n parser.add_argument('--decay', type=float,default=1e-4,\r\n help=\"the weight decay for l2 normalizaton\")\r\n parser.add_argument('--dropout', type=int,default=0,\r\n help=\"using the dropout or not\")\r\n parser.add_argument('--keepprob', type=float,default=0.6,\r\n help=\"the batch size for bpr loss training procedure\")\r\n parser.add_argument('--testbatch', type=int,default=100,\r\n help=\"the batch size of users for testing\")\r\n parser.add_argument('--dataset', type=str,default='gowalla',\r\n help=\"available datasets: [lastfm, gowalla, yelp2018, amazon-book]\")\r\n parser.add_argument('--path', type=str,default=\"./checkpoints\",\r\n help=\"path to save weights\")\r\n parser.add_argument('--topks', nargs='?',default=\"[20]\",\r\n help=\"@k test list\")\r\n parser.add_argument('--comment', type=str,default=\"lgn\")\r\n parser.add_argument('--load', type=int,default=0)\r\n parser.add_argument('--epochs', type=int,default=1000)\r\n parser.add_argument('--multicore', type=int, default=0, help='whether we use multiprocessing or not in test')\r\n parser.add_argument('--pretrain', type=int, default=0, help='whether we use pretrained weight or not')\r\n parser.add_argument('--seed', type=int, default=2020, help='random seed')\r\n parser.add_argument('--model', type=str, default='lgn', help='rec-model, support [mf, lgn]')\r\n parser.add_argument('--multigpu', type=bool, default=False)\r\n parser.add_argument('--multicpu', type=bool, default=False)\r\n return parser.parse_args()\r\n\r\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\r\nargs = parse_args()\r\n\r\nROOT_PATH = \"./\"\r\nCODE_PATH = join(ROOT_PATH, 'code')\r\nDATA_PATH = join(ROOT_PATH, 'data')\r\nBOARD_PATH = join(CODE_PATH, 'runs')\r\nFILE_PATH = join(CODE_PATH, 'checkpoints')\r\nimport sys\r\nsys.path.append(join(CODE_PATH, 'sources'))\r\n\r\nconfig = {}\r\nall_dataset = ['lastfm', 'gowalla', 'yelp2018', 'amazon-book']\r\nall_models = ['mf', 'lgn']\r\nconfig['bpr_batch_size'] = args.bpr_batch\r\nconfig['latent_dim_rec'] = args.recdim\r\nconfig['lightGCN_n_layers']= args.layer\r\nconfig['dropout'] = args.dropout\r\nconfig['keep_prob'] = args.keepprob\r\nconfig['test_u_batch_size'] = args.testbatch\r\nconfig['multicore'] = args.multicore\r\nconfig['lr'] = args.lr\r\nconfig['decay'] = args.decay\r\nconfig['pretrain'] = args.pretrain\r\n\r\nconfig['multigpu'] = args.multigpu\r\n\r\nconfig['multicpu'] = args.multicpu\r\nCORES = multiprocessing.cpu_count() // 2\r\nseed = args.seed\r\n\r\nmodel_name = args.model\r\n\r\ndataset = join(DATA_PATH, args.dataset)\r\n\r\n\r\nTRAIN_epochs = args.epochs\r\nLOAD = args.load\r\nPATH = args.path\r\ntopks = eval(args.topks)\r\ncomment = args.comment\r\n# let pandas shut up\r\nfrom warnings import simplefilter\r\nsimplefilter(action=\"ignore\", category=FutureWarning)\r\n\r\ndef cprint(words : str):\r\n print(f\"\\033[0;30;43m{words}\\033[0m\")\r\n","sub_path":"NGCF/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"269780368","text":"from msizenko_42cc.apps.assignment.models import RequestLog\n\n\nclass RequestLoggerMiddleware:\n \n def process_request(self, request):\n log = RequestLog()\n log.method = request.method\n log.path = request.path\n if request.user.is_authenticated():\n log.user = request.user\n log.user_agent = request.META.get('HTTP_USER_AGENT', '--')\n log.save()\n ","sub_path":"msizenko_42cc/apps/assignment/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"342556761","text":"#!/usr/bin/python\n#\n# Copyright 2020 Google LLC\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 google.datacatalog_connectors.rdbms.scrape import \\\n config_constants, metadata_enricher\n\n\nclass MetadataEnricher(metadata_enricher.MetadataEnricher):\n\n def enrich(self, scraped_dataframe):\n asset_prefix = self._enrich_metadata_dict.get(\n config_constants.METADATA_ENRICH_ENTRY_PREFIX)\n\n if asset_prefix:\n table_container_name = self._metadata_definition[\n config_constants.TABLE_CONTAINER_DEF_KEY][\n config_constants.ASSET_NAME_KEY]\n table_name = self._metadata_definition[\n config_constants.TABLE_DEF_KEY][\n config_constants.ASSET_NAME_KEY]\n # Update Assets' name with user configured prefix\n scraped_dataframe[\n table_name] = asset_prefix + scraped_dataframe[table_name]\n scraped_dataframe[\n table_container_name] = asset_prefix + scraped_dataframe[\n table_container_name]\n\n return scraped_dataframe\n","sub_path":"google-datacatalog-sqlserver-connector/src/google/datacatalog_connectors/sqlserver/scrape/metadata_enricher.py","file_name":"metadata_enricher.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466994567","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 9 20:46:22 2015\n\n@author: robot\n\"\"\"\nimport random\nimport pylab\nimport numpy as np\n\ndef drawing_without_replacement_sim(numTrials):\n '''\n Runs numTrials trials of a Monte Carlo simulation\n of drawing 3 balls out of a bucket containing\n 3 red and 3 green balls. Balls are not replaced once\n drawn. Returns a decimal - the fraction of times 3 \n balls of the same color were drawn.\n '''\n \n\n def allthesame(numberRed, numberGreen, numberDrawn):\n \n bucket = []\n draw = []\n for i in range(numberRed):\n bucket.append('r')\n for i in range(numberGreen):\n bucket.append('g')\n\n for i in range(numberDrawn):\n draw.append(bucket.pop(random.randint(0,len(bucket)-1)))\n\n #print(draw) \n try:\n for i in range(len(draw)):\n if draw[i] != draw[i+1]:\n return False\n except: \n return True\n \n numberTheSame = 0\n for i in range(numTrials):\n if allthesame(4,4,3) == True:\n numberTheSame +=1\n\n #print(numberTheSame,numTrials)\n return (float(numberTheSame)/float(numTrials)) \n\n###########################\nans =[]\nfor i in range (250):\n ans.append(drawing_without_replacement_sim(20000))\n print(i)\n\nprint (np.average(ans))\npylab.hist(ans)","sub_path":"stanford_cs106b/noReplacementSim.py","file_name":"noReplacementSim.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"121808274","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2017, Frappe Technologies and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nimport json, requests\nfrom frappe import _\nfrom frappe.model.document import Document\nfrom six.moves.urllib.parse import urlparse\nfrom time import sleep\n\nclass Webhook(Document):\n\tdef autoname(self):\n\t\tself.name = self.webhook_doctype + \"-\" + self.webhook_docevent\n\tdef validate(self):\n\t\tself.validate_docevent()\n\t\tself.validate_request_url()\n\t\tself.validate_repeating_fields()\n\tdef validate_docevent(self):\n\t\tif self.webhook_doctype:\n\t\t\tis_submittable = frappe.get_value(\"DocType\", self.webhook_doctype, \"is_submittable\")\n\t\t\tif not is_submittable and self.webhook_docevent in [\"on_submit\", \"on_cancel\", \"on_update_after_submit\"]:\n\t\t\t\tfrappe.throw(_(\"DocType must be Submittable for the selected Doc Event\"))\n\tdef validate_request_url(self):\n\t\ttry:\n\t\t\trequest_url = urlparse(self.request_url).netloc\n\t\t\tif not request_url:\n\t\t\t\traise frappe.ValidationError\n\t\texcept Exception as e:\n\t\t\tfrappe.throw(_(\"Check Request URL\"), exc=e)\n\tdef validate_repeating_fields(self):\n\t\t\"\"\"Error when Same Field is entered multiple times in webhook_data\"\"\"\n\t\twebhook_data = []\n\t\tfor entry in self.webhook_data:\n\t\t\twebhook_data.append(entry.fieldname)\n\n\t\tif len(webhook_data)!= len(set(webhook_data)):\n\t\t\tfrappe.throw(_(\"Same Field is entered more than once\"))\n\ndef enqueue_webhook(doc, webhook):\n\twebhook = frappe.get_doc(\"Webhook\", webhook.get(\"name\"))\n\theaders = {}\n\tdata = {}\n\tif webhook.webhook_headers:\n\t\tfor h in webhook.webhook_headers:\n\t\t\tif h.get(\"key\") and h.get(\"value\"):\n\t\t\t\theaders[h.get(\"key\")] = h.get(\"value\")\n\tif webhook.webhook_data:\n\t\tfor w in webhook.webhook_data:\n\t\t\tfor k, v in doc.as_dict().items():\n\t\t\t\tif k == w.fieldname:\n\t\t\t\t\tdata[w.key] = v\n\tfor i in range(3):\n\t\ttry:\n\t\t\tr = requests.post(webhook.request_url, data=json.dumps(data), headers=headers, timeout=5)\n\t\t\tr.raise_for_status()\n\t\t\tfrappe.logger().debug({\"webhook_success\":r.text})\n\t\t\tbreak\n\t\texcept Exception as e:\n\t\t\tfrappe.logger().debug({\"webhook_error\":e, \"try\": i+1})\n\t\t\tsleep(3*i + 1)\n\t\t\tif i !=2:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\traise e\n\ndef run_webhooks(doc, method):\n\t'''Run webhooks for this method'''\n\tif frappe.flags.in_import or frappe.flags.in_patch or frappe.flags.in_install:\n\t\treturn\n\n\tif not getattr(frappe.local, 'webhooks_executed', None):\n\t\tfrappe.local.webhooks_executed = []\n\n\tif doc.flags.webhooks == None:\n\t\twebhooks = frappe.cache().hget('webhooks', doc.doctype)\n\t\tif webhooks==None:\n\t\t\twebhooks = frappe.get_all('Webhook',\n\t\t\t\tfields=[\"name\", \"webhook_docevent\", \"webhook_doctype\"])\n\t\t\tfrappe.cache().hset('webhooks', doc.doctype, webhooks)\n\t\tdoc.flags.webhooks = webhooks\n\n\tif not doc.flags.webhooks:\n\t\treturn\n\n\tdef _webhook_request(webhook):\n\t\tif not webhook.name in frappe.local.webhooks_executed:\n\t\t\tfrappe.enqueue(\"frappe.integrations.doctype.webhook.webhook.enqueue_webhook\", doc=doc, webhook=webhook)\n\t\t\tfrappe.local.webhooks_executed.append(webhook.name)\n\n\tevent_list = [\"on_update\", \"after_insert\", \"on_submit\", \"on_cancel\", \"on_trash\"]\n\n\tif not doc.flags.in_insert:\n\t\t# value change is not applicable in insert\n\t\tevent_list.append('on_change')\n\t\tevent_list.append('before_update_after_submit')\n\n\tfor webhook in doc.flags.webhooks:\n\t\tevent = method if method in event_list else None\n\t\tif event and webhook.webhook_docevent == event and webhook.webhook_doctype == doc.doctype:\n\t\t\t_webhook_request(webhook)\n","sub_path":"frappe/integrations/doctype/webhook/webhook.py","file_name":"webhook.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"506842191","text":"import MySQLdb\nimport networkx as nx\nimport igraph as ig\nimport MySQLdb.cursors\nimport traceback\nimport json\n# import pickle\n# from numpy import *\nfrom datetime import datetime\n# import generators\n\ndef ResultIter(cursor, arraysize=100):\n while True:\n results = cursor.fetchmany(arraysize)\n if not results:\n break\n for result in results:\n yield result\n\ndb = MySQLdb.connect(\"localhost\",\"root\",\"arun\",\"btp\",cursorclass=MySQLdb.cursors.DictCursor )\ncursor = db.cursor()\n\nsql = \"select src,dest,weight from citation_weighted \"\npaper_list = []\ns = []\nresults= []\nprint(\"sql\")\nprint(str(datetime.now()))\nG=nx.DiGraph()\ncount =0 \nfout=open('pop.txt','w')\ntry:\n cursor.execute(sql)\n # results = cursor.fetchall()\n result = cursor.fetchmany(1000)\n while result:\n for row in result:\n fout.write(str(row['src'])+\",\"+str(row['dest'])+\",\"+str(row['weight']))\n paper_list=[(row['src'],row['dest'],row['weight'])]\n G.add_weighted_edges_from(paper_list)\n print (G.number_of_nodes())\n print (\"count\"+str(count))\n count+=1\n result = cursor.fetchmany(1000)\n\n # for row in ResultIter(cursor):\n # # count+=1\n # # print (\"Results\"+str(count))\n # # for row in results:\n # paper_list=[(row['src'],row['dest'],row['weight'])]\n # G.add_weighted_edges_from(paper_list)\n # print (G.number_of_nodes())\n # # del paper_list[:]\n # print (\"Rows Fetched\")\n # for row in results:\n # paper_list.append((row['src'],row['dest'],row['weight']))\n # if len(paper_list) >=1000000:\n # G.add_weighted_edges_from(paper_list)\n # del paper_list[:]\n # G.add_weighted_edges_from(paper_list)\n # del results[:]\nexcept Exception as e:\n print (\"EXIT\")\n print (e)\n traceback.print_exc()\n exit()\n\nprint (\"add_weighted_edges_from\")\nprint(str(datetime.now()))\n\n###########################\ndel paper_list[:]\nprint (\"centrality\")\nprint(str(datetime.now()))\ncentrality=nx.eigenvector_centrality(G)\nprint (\"FILE DUMP\")\nprint(str(datetime.now()))\nwith open('citation.txt', 'w') as f:\n for node in centrality:\n f.write(str(node)+\",\"+str(centrality[node])+\"\\n\")\nprint(\"EXIT\")\nprint(str(datetime.now()))\nexit()","sub_path":"centr/citcen.py","file_name":"citcen.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"553022617","text":"import base64\nimport hashlib\n\nfrom django.contrib.auth.models import User\n\n\ndef create_user(handle, use_hash=False, with_profile=False):\n \"\"\"Helper to create Users\"\"\"\n email = '%s@%s.com' % (handle, handle)\n if use_hash:\n username = base64.urlsafe_b64encode(\n hashlib.sha1(email).digest()).rstrip('=')\n else:\n username = handle\n user = User.objects.create_user(username, email, handle)\n if with_profile:\n profile = user.get_profile()\n profile.name = handle.title()\n profile.save()\n return user\n","sub_path":"popcorn_gallery/users/tests/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"646341603","text":"\"\"\"979. Distribute Coins in Binary Tree\nhttps://leetcode.com/problems/distribute-coins-in-binary-tree/\n\nGiven the root of a binary tree with N nodes, each node in the tree has \nnode.val coins, and there are N coins total.\n\nIn one move, we may choose two adjacent nodes and move one coin from one node \nto another. (The move may be from parent to child, or from child to parent.)\n\nReturn the number of moves required to make every node have exactly one coin.\n\nNote:\n 1<= N <= 100\n 0 <= node.val <= N\n\"\"\"\nfrom common.tree_node import TreeNode\n\n\nclass Solution:\n def distribute_coins(self, root: 'TreeNode') -> 'int':\n count = 0\n\n def recursive_count(node: 'TreeNode') -> 'int':\n nonlocal count\n if node is None:\n return 0\n if node.left is None and node.right is None:\n count += abs(node.val - 1)\n return node.val - 1\n node.val += recursive_count(node.left)\n node.val += recursive_count(node.right)\n count += abs(node.val - 1)\n return node.val - 1\n\n recursive_count(root)\n return count\n","sub_path":"python-algorithm/leetcode/problem_979.py","file_name":"problem_979.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439812684","text":"\"\"\"Add newsletter models.\n\nRevision ID: d3e9983f8366\nRevises: 8fc09a727a5c\nCreate Date: 2017-06-15 22:44:02.778366\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd3e9983f8366'\ndown_revision = '8fc09a727a5c'\n\n\ndef upgrade():\n op.create_table(\n 'newsletter',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('created', sa.DateTime(), nullable=True),\n sa.Column('modified', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id', name=op.f('pk_newsletter')),\n sqlite_autoincrement=True\n )\n op.create_table(\n 'newsletter_news',\n sa.Column('newsletter_id', sa.Integer(), nullable=True),\n sa.Column('news_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(\n ['news_id'], ['news.id'],\n name=op.f('fk_newsletter_news_news_id_news')),\n sa.ForeignKeyConstraint(\n ['newsletter_id'], ['newsletter.id'],\n name=op.f('fk_newsletter_news_newsletter_id_newsletter'))\n )\n op.create_table(\n 'newsletter_activities',\n sa.Column('newsletter_id', sa.Integer(), nullable=True),\n sa.Column('activity_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(\n ['activity_id'], ['activity.id'],\n name=op.f('fk_newsletter_activities_activity_id_activity')),\n sa.ForeignKeyConstraint(\n ['newsletter_id'], ['newsletter.id'],\n name=op.f('fk_newsletter_activities_newsletter_id_newsletter'))\n )\n\n\ndef downgrade():\n op.drop_table('newsletter_activities')\n op.drop_table('newsletter_news')\n op.drop_table('newsletter')\n","sub_path":"migrations/versions/2017_06_15_d3e9983f8366_add_newsletter_models.py","file_name":"2017_06_15_d3e9983f8366_add_newsletter_models.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"353583604","text":"class Solution:\n def racecar(self, target: int) -> int:\n # 1. Initialize double ended queue as 0 moves, 0 position, +1 velocity\n queue = collections.deque([(0, 0, 1)])\n while queue:\n # (moves) moves, (pos) position, (vel) velocity)\n moves, pos, vel = queue.popleft()\n if pos == target:\n return moves\n # 2. Always consider moving the car in the direction it is already going\n queue.append((moves + 1, pos + vel, 2 * vel))\n # 3. Only consider changing the direction of the car if one of the following conditions is true\n # i. The car is driving away from the target.\n # ii. The car will pass the target in the next move.\n if (pos + vel > target and vel > 0) or (pos + vel < target and vel < 0):\n queue.append((moves + 1, pos, -vel / abs(vel)))\n","sub_path":"Leetcode/0818-Race-Car.py","file_name":"0818-Race-Car.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"543924577","text":"# -*- coding: UTF-8 -*-\r\n\r\n#enter the path to your corpus that you want to tag\r\n#e.g. r\"F:\\AllTag\\chn_eng_train.zh.txt\"\r\n#r\"F:\\AllTag\\chn_eng_train.en.txt\"\r\n\r\nwith open (r\"path to chinese corpus\",\"r\",encoding=\"utf-8_sig\") as ChnReader,open (r\"path to english corpus\",\"r\",encoding=\"utf-8_sig\") as EngReader:\r\n ChnWord = []\r\n EngWord = []\r\n for index,line in enumerate(ChnReader):\r\n list1 = line.split()\r\n for word in list1:\r\n if word not in ChnWord:\r\n ChnWord.append(word)\r\n for index,line in enumerate(EngReader):\r\n list2 = line.split()\r\n for word in list2:\r\n if word not in EngWord:\r\n EngWord.append(word)\r\n \r\nprint(ChnWord)\r\nprint(EngWord)\r\n","sub_path":"GetWord.py","file_name":"GetWord.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"282167740","text":"import pandas as pd\nimport pyodbc\n\nfrom copy import deepcopy\n\ndef export_data_to_db(server: str,\n database: str,\n table_to_append: pd.DataFrame,\n temp_table_name: str,\n final_table_name: str):\n cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server}; \\\n SERVER=' + server + '; \\\n DATABASE=' + database + ';\\\n Trusted_Connection=yes;')\n\n cursor = cnxn.cursor()\n # read data from sql table\n data_backlog = pd.read_sql(\"SELECT * FROM\" + final_table_name, cnxn)\n cols = list(data_backlog)\n if final_table_name == '[dbo].[reports_backlog]':\n dedup_cols = deepcopy(cols)\n dedup_cols.remove('ScoreTimestamp')\n elif final_table_name == '[dbo].[scored_cases_backlog]':\n dedup_cols = deepcopy(cols)\n dedup_cols.remove('pqc_timestamp')\n else:\n dedup_cols = cols\n\n data_all = pd.concat([data_backlog, table_to_append], ignore_index=True)\n data_dedup = data_all.drop_duplicates(subset=dedup_cols,\n keep='last',\n ignore_index=True)\n\n insert_values_list = []\n for num, a in data_dedup.iterrows():\n single_insert_list = [x for x in data_dedup.loc[num]]\n list_to_str = \"', '\".join(str(elem) for elem in single_insert_list)\n single_values = \"('{}')\".format(list_to_str)\n single_values = single_values.replace(\", 'nan'\", \", NULL\")\n insert_values_list.append(single_values)\n\n insert_values = \", \\n\".join(str(val) for val in insert_values_list)\n all_cols = \", \".join('[' + str(header) + ']' for header in cols)\n insert_statement = \"INSERT INTO {} ({}) VALUES {}\".format(temp_table_name,\n all_cols,\n insert_values)\n try:\n cursor.execute(insert_statement)\n print(\"Data sucessfully exported into %s .\" % temp_table_name)\n\n except pyodbc.ProgrammingError:\n print(\"Could not insert values into {} table.\" % temp_table_name)\n\n insert_temp_to_final = \"INSERT INTO {} \\\n SELECT * FROM {} t \\\n WHERE NOT EXISTS \\\n (SELECT 1 FROM {} f \\\n WHERE t.GRID = f.GRID AND t.Score = f.Score)\".format(\n final_table_name,\n temp_table_name,\n final_table_name)\n\n try:\n cursor.execute(insert_temp_to_final)\n print(\"Data sucessfully exported into %s .\" % final_table_name)\n except pyodbc.ProgrammingError:\n print(\"Could not insert values into %s table.\" % final_table_name)\n cursor.commit()\n cursor.close()\n cnxn.close()\n return data_dedup\n","sub_path":"SKRYPTY/MODELING/scripts/fcu/scripts/export_monitoring_data_to_db.py","file_name":"export_monitoring_data_to_db.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"418584700","text":"import sys\nimport argparse\nimport os\nimport random\nimport torch\nimport torch.nn as nn\n#import torch.nn.parallel\n#import torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torchvision.utils as vutils\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfrom Utils import Utils\nfrom config import parse_args\n\nfrom models.gan import GAN\n#from models.dcgan import DCGAN_MODEL\n#from models.wgan_clipping import WGAN_CP\n#from models.wgan_gradient_penalty import WGAN_GP\n\n# Reference: https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html\n# Set random seed for reproducibility\nmanualSeed = 999\n# manualSeed = random.randint(1, 10000) # to produce different results each time\nprint(\"Random Seed: \", manualSeed)\nrandom.seed(manualSeed)\ntorch.manual_seed(manualSeed)\n\n\n\ndef main(args):\n #--------------prepare data------------------------\n dataset = args.dataset\n dataroot = args.dataroot\n if not os.path.exists(dataroot):\n os.makedirs(dataroot)\n batch_size = args.batch_size \n epochs = args.epochs\n channels = args.channels\n model = None\n model_name = args.model\n if args.model == 'GAN':\n model = GAN(epochs, batch_size)\n elif args.model == 'DCGAN':\n model = DCGAN_MODEL(args)\n elif args.model == 'WGAN-CP':\n model = WGAN_CP(args)\n elif args.model == 'WGAN-GP':\n model = WGAN_GP(args)\n else:\n print(\"Model type non-existing. Try again.\")\n exit(-1)\n workers = 0 # number of workers for dataloader, 2 creates problems\n utils = Utils()\n train_loader, test_loader = utils.prepare_data(dataroot, batch_size, workers, dataset, model_name, channels)\n # Start model training\n resume_training = False\n if args.resume_training == 'True':\n resume_training = True\n if args.is_train == 'True':\n model.train(train_loader, resume_training)\n\n # start evaluating on test data\n else:\n model.evaluate(test_loader, args.load_D, args.load_G)\n # for i in range(50):\n # model.generate_latent_walk(i)\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n sys.exit(int(main(args) or 0))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"34145214","text":"import pygame\nfrom pygame.locals import *\nfrom pygame.color import THECOLORS\npygame.init()\nBrack=[0,0,0]\nWhite=[255,255,255]\nnumber=[\"A0\",\"A1\",\"A2\",\"A3\",\"A4\",\"B0\",\"B1\",\"B2\",\"B3\"]\nicon=[\"mz.png\",\"mz.png\",\"mz.png\",\"mz.png\",\"kz.png\",\"bz.png\",\"bz.png\",\"bz.png\",\"bz.png\"]\nscreen = pygame.display.set_mode((1240,768),0,32)#FULLSCREEN\nscreen.fill(Brack)\nclass Bottles(object):\n def Icon(num,x,y):\n img0=pygame.image.load(icon[num])\n screen.blit(img0,(x,y))\n text=pygame.font.Font(\"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc\",46)\n text_fmt0=text.render(number[num],3,White)\n screen.blit(text_fmt0,(x-80,y+50))\n pygame.display.update()\nif __name__ == '__main__':\n Bottles.Icon(0,160,50)\n Bottles.Icon(1,530,50)\n Bottles.Icon(2,890,50)\n Bottles.Icon(3,160,290)\n Bottles.Icon(4,530,290)\n Bottles.Icon(5,890,290)\n Bottles.Icon(6,160,530)\n Bottles.Icon(7,530,530)\n Bottles.Icon(8,890,530)\n while True:\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n exit()\n elif event.type == QUIT:\n exit()\n","sub_path":"bottles.py","file_name":"bottles.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463206503","text":"import turtle\n\ns = turtle.Screen() \n\nt = turtle.Turtle()\ni=0\n\ndef left(x,y,a,l):\n t.up()\n t.goto(x,y)\n t.down()\n t.rt(a)\n t.fd(l)\n return [t.position(),a,l]\n\n\ndef right(x,y,a,l):\n t.up()\n t.goto(x,y)\n t.down()\n t.rt(-2*a)\n t.fd(l)\n return [t.position(),a,l]\n\n#t.rt(-90)\n#t.setheading(90)\n#left(0,0,60,60)\n#right(0,0,60,60)\n#t.setheading(90)\n\nxind=0\nyind=0\nL=100\ndef recursive(x,y):\n t.setheading(90)\n global L\n L=0.6*L\n global i\n if i >10:\n #exit()\n return 1\n else:\n i+=1\n Lef=left(x,y,60,30)\n Rig=right(x,y,60,30)\n recursive(Rig[0][0],Rig[0][1])\n recursive(Lef[0][0],Lef[0][1])\n #return recursive(Rig[0][0],Rig[0][1]) + recursive(Lef[0][0],Lef[0][1]) \n\nrecursive(0,0)\n#print(t.position())\n'''\nt.rt(360-90)\nt.fd(100)\nt.rt(30)\nt.fd(50)\n'''\n#print(t.position())\nturtle.done()","sub_path":"week1 and extra/branches.py","file_name":"branches.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"218643467","text":"import os.path\nfrom django.conf.urls import *\nfrom bookmark.views import *\nsite_media = os.path.join(\n os.path.dirname(__file__), 'site_media')\n\n\nurlpatterns = patterns('',\n (r'^$', main_page),\n (r'^user/(\\w+)/$', user_page),\n (r'^login/$', 'django.contrib.auth.views.login'),\n (r'^logout/$', logout_page),\n (r'^site_media/(?P.*)$', 'django.views.static.serve',\n { 'document_root': site_media }),\n (r'^register/$', register_page),\n)\n","sub_path":"django_bookmarks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"373081748","text":"import requests\n\nfrom .errors import AuthenticationException, GaugesException\n\nMETHODS = ['get', 'put', 'post', 'delete']\n\nclass Singleton(type):\n __instance = None\n def __call__(self, *args, **kwargs):\n if self.__instance is None:\n self.__instance = super(Singleton, self).__call__(*args, **kwargs)\n return self.__instance\n \n\nclass API(object):\n __metaclass__ = Singleton\n \n def __init__(self):\n self.headers = {}\n \n def set_api_key(self, api_key):\n self.headers['X-Gauges-Token'] = api_key \n \n def make_request(self, url, method='get', **params):\n method = method.lower()\n if method in METHODS and hasattr(requests, method):\n method_function = getattr(requests, method)\n \n if params:\n response = method_function(url, params=params, headers=self.headers)\n else:\n response = method_function(url, headers=self.headers)\n \n if response.status_code == 401:\n raise AuthenticationException('api authentication failed.')\n elif response.status_code != 200:\n raise GaugesException('request failed.')\n \n return response.json()\n else:\n raise GaugesException('request method does not exists.')\n \n\n","sub_path":"gauges/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"467312121","text":"# This is a personal secretary program whose name is Hana.\n\nimport datetime\n\ndef age(today, birth):\n today = datetime.date.today()\n age = datetime.timedelta.total_seconds(today - birth) / 365.2422 / 24 / 3600\n return age\n\ndef modify_userdata():\n with open(\"userdata.txt\", 'w') as userdata:\n user = str(input(\"please enter your name. \\n\"))\n birth_raw = str(input(\"enter your birthday by 8 digits. \\n\"))\n print(\"User data has been successfully saved\")\n userdata.write(user + '\\n')\n userdata.write(birth_raw + '\\n')\n\ndef dateinfo():\n print('Hello ' + user + ', today is ' + today.strftime('%A %d, %B %Y'))\n print('Your age is %.4f' % age(today, birth))\n\n#read user information or require input data\ntry:\n with open(\"userdata.txt\", 'r') as userdata:\n userdata_list = userdata.readlines()\n user = userdata_list[0][:-2]\n birth_raw = userdata_list[1][:-2]\nexcept FileNotFoundError:\n modify_userdata()\n\n#convert birth data to datetime.date object\nbirth = datetime.date(int(birth_raw[:4]), int(birth_raw[4:6]), int(birth_raw[6:]))\ntoday = datetime.date.today()\n\nmenu = \"\"\"\n\n\n==============Select Menu===============\n1. Reenter user data\n2. What's my age?\n========================================\n\"\"\"\ndateinfo()\nwhile True:\n menu_sel = input(menu)\n if menu_sel == '1':\n modify_userdata()\n dateinfo()\n elif menu_sel == '2':\n dateinfo()","sub_path":"SecretaryHana.py","file_name":"SecretaryHana.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583499465","text":"# coding: utf-8\n\nnow = input().split()\n\nn = int(input())\n\ns = [input().split() for i in range(n)]\n\nresult_list = []\ncheck_number = 0\n\nfor j in s:\n if int(j[1]) <= int(now[0]) and int(j[2]) >= int(now[0]) and int(j[3]) <= int(now[1]) and int(j[4]) >= int(now[1]) and int(j[5]) <= int(now[2]) and int(j[6]) >= int(now[2]):\n result_list.append(j[0])\n else:\n result_list.append(False)\n\nfor k in result_list:\n if k != False:\n print(k)\n check_number += 1\n\nif check_number == 0:\n print(\"no evolution\")\n","sub_path":"practice/evolution.py","file_name":"evolution.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"98662665","text":"def uniquePathsWithObstacles(self, obstacleGrid):\n if not obstacleGrid:\n return 0\n m, n = len(obstacleGrid), len(obstacleGrid[0])\n firstCol = [0 for i in range(m)]\n firstCol[0] = 1 if obstacleGrid[0][0] == 0 else 0\n \n for i in range(1, m):\n firstCol[i] = 0 if obstacleGrid[i][0] == 1 else firstCol[i-1]\n\n for j in range(1, n):\n secondCol = [0 for k in range(m)]\n secondCol[0] = firstCol[0] if obstacleGrid[0][j] == 0 else 0\n for i in range(1, m):\n secondCol[i] = 0 if obstacleGrid[i][j] == 1 else secondCol[i - 1] + firstCol[i]\n firstCol = secondCol\n return firstCol[-1]","sub_path":"LC/063_Unique_Paths_II.py","file_name":"063_Unique_Paths_II.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"252460017","text":"#coding=utf-8\nimport requests\nfrom bs4 import BeautifulSoup \nimport os\nimport re\nheaders = {'User-Agent':\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1\"}\n\nlist1=[] #存储链接\n\ndef getUrl(url):#获得简书用户的文章链接\n start_html = requests.get(url, headers=headers) #获得网页\n Soup=BeautifulSoup(start_html.text,'lxml') #调用bs4\n p_list=Soup.find_all(\"h4\")# 找出所有h4标签里面的内容\n \n Title=str(Soup.find('title'))#得到标题\n #Tlen=len(Title) \n Title=Title[7:len(Title)-8]#去掉标签等乱七八找的东西\n #写入txt\n for p in p_list:\n pstr=str(p)\n ple=len(pstr)\n pos=pstr.find('href')+6;\n list1.append('http://www.jianshu.com'+pstr[pos:pos+15])\n return Title\n\ndef getTxt(url): #获得链接里面的文本\n start_html = requests.get(url, headers=headers) #获得网页\n Soup=BeautifulSoup(start_html.text,'lxml') #调用bs4\n p_list=Soup.find_all('p')# 找出所有p标签里面的内容\n Title=str(Soup.body.h1)#把得到标题\n #Tlen=len(Title)\n\n Title=Title[18:len(Title)-5]#去掉标签等乱七八找的东西\n #写入txt\n with open(Title+'.txt','w') as f:\n for p in p_list:\n pstr=str(p)\n plen=len(pstr)\n if pstr.find('class')>0:\n continue;\n s=pstr[3:plen-4];\n tmp=''\n mark=0\n for sub_s in s:#去掉里面 乱七八糟的标签\n if sub_s=='<':\n mark=1\n if sub_s=='>':\n mark=0\n if mark==1:\n continue\n elif sub_s!='>':\n tmp=tmp+sub_s\n f.write(tmp+'\\n')\nif __name__=='__main__':\n name=getUrl('http://www.jianshu.com/users/d699edde9c0e/latest_articles')\n \n pat=str(name[0:len(name)-8])\n print(pat)\n os.makedirs(os.path.join(\"/home/guanjun/桌面/Read\",pat))\n s='/home/guanjun/桌面/Read/'+pat\n os.chdir(s)\n#print(s) \n for url in list1:\n print(\"文章链接:\"+url)\n if len(list1)==0:\n print('该网页下没有要爬去的链接')\n else:\n for url in list1:\n getTxt(url)\n print('爬取完成!!')\n","sub_path":"craw.py","file_name":"craw.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"484755376","text":"import argparse\nimport sys\nimport os\n\nclass EnableGPIO:\n\n GPIO_PATH = '/sys/class/gpio/'\n gpio_number = 0\n\n def __init__(self, gpio_number):\n self.gpio_number = gpio_number\n print('Enable: gpio{}'.format(self.gpio_number))\n\n def gpio(self):\n if not os.path.exists(self.GPIO_PATH + 'gpio' + str(self.gpio_number)):\n try:\n file = open(self.GPIO_PATH + 'export', 'w')\n file.write(str(self.gpio_number))\n file.close()\n print('GPIO {} enabled'.format(self.GPIO_PATH + 'gpio' + str(self.gpio_number)))\n except IOError as err:\n print('Can\\'t write to file (gpio) {}'.format(err))\n else:\n print('File {} already exists'.format(self.GPIO_PATH + 'gpio' + self.gpio_number))\n\n def set_direction(self, direction):\n try:\n file = open(self.GPIO_PATH + 'gpio' + str(self.gpio_number) + '/direction', 'w')\n file.write(str(direction))\n file.close()\n print('File {} created'.format(file))\n except IOError as err:\n print('Can\\'t set direction {}'.format(err))\n\n\ndef main():\n parser = argparse.ArgumentParser('SET GPIO')\n parser.add_argument('-g', '--gpio', help='Enter gpio number to set', type=str)\n parser.add_argument('-d', '--direction', help='Set gpio direction, in/out', type=str)\n args = parser.parse_args()\n print(args)\n enable_gpio = EnableGPIO(args.gpio)\n enable_gpio.gpio()\n enable_gpio.set_direction(args.direction)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"Python_Projects/EnableGPIO/EnableGPIO.py","file_name":"EnableGPIO.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"137782129","text":"\nimport pytest\nfrom typing import Optional\nimport ring\n\n\n@pytest.mark.asyncio\nasync def test_async_def_vanilla_function(aiomcache_client):\n storage, storage_ring = aiomcache_client\n\n with pytest.raises(TypeError):\n @storage_ring(storage)\n def vanilla_function():\n pass\n\n\n@pytest.mark.asyncio\nasync def test_async_def_func_method():\n cache = {}\n\n async def async_func(n):\n return n\n\n class A(object):\n def __str__(self):\n return 'A'\n\n @ring.dict(cache)\n async def method(self, a, b):\n x = await async_func(100)\n return base + a * x + b\n\n @ring.dict(cache)\n @classmethod\n async def cmethod(cls, a, b):\n x = await async_func(200)\n return base + a * x + b\n\n obj = A()\n\n base = 10000\n await obj.method.delete(1, 2)\n value = await obj.method(1, 2)\n assert value == 10102, value\n\n await obj.cmethod.delete(1, 2)\n value = await obj.cmethod(1, 2)\n assert value == 10202, value\n\n\n@pytest.mark.parametrize('field,expected', [\n (None, {'a': int, 'b': str, 'return': float}),\n ('__call__', {'a': int, 'b': str, 'return': float}),\n ('execute', {'a': int, 'b': str, 'return': float}),\n ('get', {'a': int, 'b': str, 'return': Optional[float]}),\n ('get_or_update', {'a': int, 'b': str, 'return': float}),\n ('update', {'a': int, 'b': str, 'return': float}),\n ('key', {'a': int, 'b': str, 'return': str}),\n ('set', {'a': int, 'b': str, 'return': None}),\n ('delete', {'a': int, 'b': str, 'return': None}),\n ('touch', {'a': int, 'b': str, 'return': None}),\n\n])\n@pytest.mark.asyncio\nasync def test_annotation(field, expected):\n\n @ring.dict({})\n def f(a: int, b: str) -> float:\n pass\n\n @ring.dict({})\n async def g(a: int, b: str) -> float:\n pass\n\n if field is not None:\n owner = getattr(f, field)\n else:\n owner = f\n\n print('actual:', owner.__annotations__)\n print('expected:', expected)\n assert owner.__annotations__ == expected\n\n if field is not None:\n owner = getattr(g, field)\n else:\n owner = g\n\n print('actual:', owner.__annotations__)\n print('expected:', expected)\n assert owner.__annotations__ == expected\n","sub_path":"tests/_test_func_async_def.py","file_name":"_test_func_async_def.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583346869","text":"from copy import deepcopy\nfrom datetime import datetime\nimport os\nimport json\nfrom time import sleep, time\nfrom typing import Tuple\n\nimport requests\nfrom pathlib import Path\n\nfrom models import Unit, Semester\n\n\nCACHE = Path(\"./cache\")\nCACHE.mkdir(exist_ok=True)\n\nimport requests\n\ncookies = {\n \"sitevisitscookie\": \"4\",\n \"dmid\": \"34d15443-3ab7-49d8-9dfc-daff6dfc7753\",\n \"AWSALB\": \"qHgJxcCXCyIUvio69i0EkW9F06aJJXLO7kxb3mTnQTJkEBQ9MRKbnhcHJ7KYT7CS5GS0tyAQ3BbyXMFRgA+tEFOIxSpSUjAHFDOf7qJRGBfNLDjrKihEmIjv/7km\",\n \"AWSALBCORS\": \"qHgJxcCXCyIUvio69i0EkW9F06aJJXLO7kxb3mTnQTJkEBQ9MRKbnhcHJ7KYT7CS5GS0tyAQ3BbyXMFRgA+tEFOIxSpSUjAHFDOf7qJRGBfNLDjrKihEmIjv/7km\",\n \"JSESSIONID\": \"EE61CBC5C6586FC14B3A1CDC6EC9E1DD\",\n \"opvc\": \"307a11cd-0f24-46fb-86b2-d3c7481b1dec\",\n}\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:105.0) Gecko/20100101 Firefox/105.0\",\n \"Accept\": \"application/json, text/plain, */*\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Content-Type\": \"application/json;charset=utf-8\",\n \"Origin\": \"https://handbook.monash.edu\",\n \"DNT\": \"1\",\n \"Connection\": \"keep-alive\",\n \"Referer\": \"https://handbook.monash.edu/2023/units/FIT1013\",\n \"Sec-Fetch-Dest\": \"empty\",\n \"Sec-Fetch-Mode\": \"cors\",\n \"Sec-Fetch-Site\": \"same-origin\",\n \"Sec-GPC\": \"1\",\n}\n\njson_data = lambda code: {\n \"query\": {\n \"bool\": {\n \"must\": [\n {\n \"query_string\": {\n \"query\": f\"monash2_psubject.code: {code}\",\n },\n },\n {\n \"term\": {\n \"live\": True,\n },\n },\n ]\n },\n },\n \"aggs\": {\n \"implementationYear\": {\n \"terms\": {\n \"field\": \"monash2_psubject.implementationYear_dotraw\",\n \"size\": 100,\n },\n },\n \"availableInYears\": {\n \"terms\": {\n \"field\": \"monash2_psubject.availableInYears_dotraw\",\n \"size\": 100,\n },\n },\n },\n \"size\": 100,\n \"_source\": {\n \"includes\": [\n \"versionNumber\",\n \"availableInYears\",\n \"implementationYear\",\n ],\n },\n}\n\nCOLLECT = True\n\n\ndef get_unit(unit_code: str) -> Tuple[dict, bool]:\n unit_code = unit_code.upper()\n # check cache\n cache_file = CACHE / f\"{unit_code}.json\"\n if cache_file.exists():\n print(f\"use cache {unit_code}\")\n return json.loads(cache_file.read_text()), True\n\n if COLLECT:\n return None, True\n print(f\"requesting {unit_code}\")\n response = requests.post(\n \"https://handbook.monash.edu/api/es/search\",\n cookies=cookies,\n headers=headers,\n json=json_data(unit_code),\n )\n if response.status_code == 200:\n # cache response\n with open(cache_file, \"w\") as f:\n f.write(response.text)\n\n return response.json(), False\n\n\ndef get_semester(resp) -> Semester:\n offering = map(\n lambda x: x[\"name\"],\n filter(lambda x: x[\"location\"][\"value\"] != \"Malaysia\", resp[\"unit_offering\"]),\n )\n semester = Semester.Non.value\n for sem in offering:\n if \"S1\" in sem:\n semester = semester | Semester.One.value\n elif \"S2\" in sem:\n semester = semester | Semester.Two.value\n return semester\n\n\ndef resp_to_unit(code, resp) -> Unit:\n arr = sorted(\n resp[\"contentlets\"],\n key=lambda x: datetime.strptime(x[\"modDate\"], \"%Y-%m-%d %H:%M:%S.%f\"),\n )\n resp = json.loads(arr[len(arr) - 1][\"data\"])\n\n exam = list(\n map(\n lambda x: x[\"weight\"],\n filter(\n lambda x: x[\"assessment_type\"][\"value\"] == \"exam\" or \"final\" in x[\"assessment_name\"], resp[\"assessments\"]\n ),\n )\n )\n return Unit(\n code,\n resp[\"title\"],\n resp[\"school\"][\"value\"],\n int(exam[0]) if exam else 0,\n get_semester(resp),\n )\n\n\ndef main():\n codes = []\n with open(\"./codes.txt\", \"r\") as f:\n # arr = json.load(f)\n codes += list(map(lambda x: x.strip(), f.readlines()))\n\n with open(\"../data.old.json\", \"r\") as f:\n arr = json.load(f)\n codes += list(map(lambda x: x[\"code\"], arr))\n new_output = []\n\n for code in set(map(lambda x:x.upper(), codes)):\n resp, ret = get_unit(code)\n if resp is None:\n continue\n unit = resp_to_unit(code, resp)\n new_output.append(unit.__dict__)\n if not ret:\n sleep(1)\n with open(\"../data.json\", \"w\") as f:\n json.dump(new_output, f)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"spider/collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"553913522","text":"import serial\nimport binascii\nimport time\n\n\ndef scan_COM():\n ser = serial.Serial()\n port_name = []\n i = 1\n while i < 100:\n name = 'COM' + str(i)\n #ser.open\n try:\n ser.is_open\n ser = serial.Serial(name)\n port_name.append(name)\n except serial.serialutil.SerialException as e:\n pass\n i += 1\n return port_name\n\n\ndef select_port(port, baudrate, bytesize, parity, stopbits, timeout):\n # serparity 检验位\n serparity = serial.PARITY_NONE\n if parity == 'Even':\n serparity = serial.PARITY_EVEN\n elif parity == 'Mark':\n serparity = serial.PARITY_MARK\n elif parity == 'Odd':\n serparity = serial.PARITY_ODD\n # serstop停止位\n serstop = serial.STOPBITS_ONE\n if stopbits == 'OnePointFive':\n serstop = serial.STOPBITS_ONE_POINT_FIVE\n elif stopbits == 'Two':\n serstop = serial.STOPBITS_TWO\n # ser 代表打开的串口信息\n try:\n ser = serial.Serial(port, baudrate, bytesize, serparity, serstop, timeout)\n except serial.serialutil.SerialException:\n ser.close()\n ser = serial.Serial(port, baudrate, bytesize, serparity, serstop, timeout)\n return ser\n\n\n# while死循环接收信息\ndef recv(ser):\n data = ser.read_all()\n return data\n\n\ndef send_message(data):\n serial.write(data.encode('utf-8'))\n\n\n# 转成字符串\ndef distinguish_data_to_Str(data):\n # 字符串码解码转字符串\n print(data)\n data = bytes(data).decode('utf-8')\n return data\n\n\n# 转成HEX\ndef distinguish_data_to_hex(data):\n # 字符串转16进制\n senorlist = []\n # [2:-1]截取掉这个字符串的前两位和最后一位\n data = str(binascii.b2a_hex(data))[2:-1]\n\n # 如果len<28说明信息不完整\n if len(data) < 28:\n senorlist.append(\"ERROR\")\n else:\n # 完整信息\n senorlist.append(data)\n # 传感器种类\n senorlist.append(data[4]+data[5])\n # 传送的数据\n senorlist.append(data[10: -6])\n # 返回一个列表\n return senorlist\n\n\ndef hex_to_str(s):\n return ''.join([chr(i) for i in [int(b, 16) for b in s.split(' ')]])\n\n\ndef str_to_hex(s):\n return ' '.join([hex(ord(c)).replace('0x', '') for c in s])\n\n\ndef str_to_hexStr(string):\n str_bin = string.encode('utf-8')\n print(str_bin)\n return binascii.hexlify(str_bin).decode('utf-8')\n\n\ndef hexStr_to_str(hex_str):\n hexadecimal = hex_str.encode('utf-8')\n str_bin = binascii.unhexlify(hexadecimal)\n return str_bin.decode('utf-8')\n\"\"\"\nstr = \"中\"\nencode_str = str.encode('utf-8')\ndecode_str = encode_str.decode('utf-8')\n\nprint(str)\nprint(encode_str)\nprint(decode_str)\"\"\"\n\n'''\n发送端, Hex和字符都转成16进制b''\n\n\n\n'''","sub_path":"Serial_Operation.py","file_name":"Serial_Operation.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"417670290","text":"import sys\nfrom collections import defaultdict\n\n###############################################################################\n#usage:\n#python variants_within_peaks | sort -k 1,1 -k2,2n > out\n###############################################################################\n\n#get gwas data file, atac seq peak file:\ngwas_file = str(sys.argv[1])\natac_file = str(sys.argv[2])\nthreshold = float(sys.argv[3])\n\n#get lines in gwas file where pval is above the threshold\ndef filter_pvals(thresh):\n\n #list of gwas info for output:\n gwas_info = []\n i = 0\n\n #get all lines in gwas_file where the pval is above the threshold\n for line in open(gwas_file, 'r'):\n if i > 0:\n l = line.split('\\t')\n if float(l[5]) >= thresh:\n gwas_info.append(l)\n i += 1\n return gwas_info\n\n#function to get variants within peaks only:\ndef variants_within_peaks():\n\n #get all variants above the pval threshold\n gwas_info = filter_pvals(threshold)\n\n #make a dict where key = rsid, val = [chr, locus]\n gwas_dict = defaultdict(list)\n for l in gwas_info:\n gwas_dict[l[0]] = [l[1], l[2], l[5]]\n\n #make a dict where key = chr#, val = list of atac seq peaks\n peak_dict = defaultdict(list)\n for line in open(atac_file, 'r'):\n if line[0] != '#':\n l = line.split('\\t')\n peak_dict[l[0][3:]].append([item for item in l])\n\n #look for variants that fall within atac peaks:\n peak_variants = []\n for snp, loc in gwas_dict.items():\n for peak in peak_dict[loc[0]]:\n #check if the locus of this snp is within the current atac peak\n if int(peak[1]) <= int(loc[1]) and int(loc[1]) <= int(peak[2]):\n item = loc[0] + '\\t' + loc[1] + '\\t' + loc[1] + '\\t' + snp + '\\t' + loc[2]\n print(item)\n break\n\nvariants_within_peaks()","sub_path":"python_scripts/variants_within_peaks.py","file_name":"variants_within_peaks.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"609740727","text":"#!/usr/bin/python\nimport tornado\nimport tornado.ioloop\nimport tornado.web\nimport tornado.gen\nimport datetime\nimport time\nimport tornadotiming\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\nclass MainHandler(tornadotiming.TimingRequestHandler):\n @tornadotiming.coroutine\n def get(self):\n for i in xrange(0, 10):\n yield tornado.gen.Task(tornado.ioloop.IOLoop.instance().add_timeout, datetime.timedelta(milliseconds=1000))\n if i == 5:\n time.sleep(2)\n self.write(\"Hello, world\\r\\n\")\n self.flush()\n\n def post(self):\n for i in xrange(0, 10):\n self.write(\"Hello, world\\r\\n\")\n self.flush()\n time.sleep(1)\n\napplication = tornado.web.Application([\n (r\"/\", MainHandler),\n])\n\nif __name__ == \"__main__\":\n application.listen(8888)\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"non_monkeypatched.py","file_name":"non_monkeypatched.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"358696567","text":"import http.cookiejar,urllib.request\n\nfilename = 'cookies.txt'\n# cookie = http.cookiejar.CookieJar()\n# cookie = http.cookiejar.MozillaCookieJar(filename)\ncookie = http.cookiejar.LWPCookieJar(filename)\nhandler = urllib.request.HTTPCookieProcessor(cookie)\nopener = urllib.request.build_opener(handler)\nresponse = opener.open('http://www.dyyy120.com')\ncookie.save(ignore_discard=True,ignore_expires=True)\n\n# for item in cookie:\n# print(item.name + \"=\" + item.value)","sub_path":"urllib/cookies.py","file_name":"cookies.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"18224121","text":"# Download the Python helper library from twilio.com/docs/python/install\nfrom twilio.rest import TwilioRestClient\n\n# Your Account Sid and Auth Token from twilio.com/user/account\naccount_sid = \"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"\nauth_token = \"your_auth_token\"\nclient = TwilioRestClient(account_sid, auth_token)\n\nip_address = client.sip.ip_addresses(\"AL32a3c49700934481addd5ce1659f04d2\").update(\"IP32a3c49700934481addd5ce1659f04d2\", friendly_name=\"Orlandos Nightclub\")\nprint(ip_address.friendly_name)\n","sub_path":"rest/sip-in/update-address-instance/update-address-instance.py","file_name":"update-address-instance.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"93982268","text":"#-*- coding: utf-8 -*-\nfrom xmlbook import *\nfrom http.client import HTTPConnection\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom xmlbook import *\nfrom http.client import HTTPConnection\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom tkinter import *\nfrom tkinter import font\nimport tkinter.messagebox\n\n\n##global\nconn = None\nCrimeDoc = None\nCSelect = None\nuri = None\nURI = None\n\ng_Tk = Tk()\ng_Tk.geometry(\"1000x600+750+200\")\nDataList = []\nuri = URI\n# regKey = '73ee2bc65b*******8b927fc6cd79a97'\nregKey = 'PGM0C0ZXEQ3U3XV0CURV'\n\nprint(\"\\n\")\n# 네이버 OpenAPI 접속 정보 information\nserver = \"openapi.crimestats.or.kr:8080\"\n\n# smtp 정보\nhost = \"smtp.gmail.com\" # Gmail SMTP 서버 주소.\nport = \"587\"\n\n\ndef returnURI():\n return URI\n\ndef userURIBuilder(server, **user):\n # str = \"http://\" + server + \"/search\" + \"?\"\n str = \"https://\" + server + \"/WiseOpen/ArcData\" + \"/\" + regKey + \"/xml\"\n #for key in user.keys():\n # str += \"/\" + user[key] # 어떻게 고치지\n return str\n\n\ndef connectOpenAPIServer():\n global conn, server\n conn = HTTPConnection(server)\n\ndef PrintAYearMenu(year):\n print(\"========\", year, \"년도==========\")\n print(\"피해자 성별과 연령: s\")\n print(\"범죄발생 월: m\")\n print(\"범죄발생시간: t\")\n print(\"범죄발생지역: a\")\n print(\"범죄자 범행 동기: mot\")\n print(\"범죄자 정신 상태: men\")\n print(\"범죄자와 피해자와의 관계: r\")\n print(\"범죄도구 및 입수방법: too\")\n print(\"범죄자 검거단서: c\")\n print(\"========Menu==========\")\n\n\ndef getSexData(year, crime):\n global server, regKey, conn, uri, URI\n if conn == None:\n connectOpenAPIServer()\n\n if year != \"2014\" and year != \"2015\":\n if crime == '1': itemcode = \"7\"\n else: itemcode = \"10\"\n for i in range(5, 25):\n uri = userURIBuilder(server, start=\"1\", end=\"10\", BASE_YEAR=year, STAT_CODE=\"15\", ITEM_CODE1=itemcode,\n ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/10/\" + year + \"/15/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n else:\n if crime == '1': itemcode = \"10208\"\n else: itemcode = \"10211\"\n for i in range(5, 25):\n uri = userURIBuilder(server, start=\"1\", end=\"10\", BASE_YEAR=year, STAT_CODE=\"227\", ITEM_CODE1=itemcode,\n ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/10/\" + year + \"/227/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n\ndef getMonthData(year, crime):\n global server, regKey, conn, uri, URI\n if conn == None:\n connectOpenAPIServer()\n\n if year != \"2014\" and year != \"2015\":\n print(\"해당 년도의 데이터가 없습니다.\")\n else:\n if crime == \"1\": itemcode = \"10208\"\n else: itemcode = \"10211\"\n for i in range(5, 17):\n uri = userURIBuilder(server, start=\"1\", end=\"10\", BASE_YEAR=year, STAT_CODE=\"180\", ITEM_CODE1=itemcode,\n ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/10/\" + year + \"/180/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n\ndef getTimeData(year, crime):\n global server, regKey, conn, uri, URI\n if conn == None:\n connectOpenAPIServer()\n\n if year != \"2014\" and year != \"2015\":\n if crime == '1': itemcode = \"7\"\n else: itemcode = \"10\"\n for i in range(5, 13):\n uri = userURIBuilder(server, start=\"1\", end=\"10\", BASE_YEAR=year, STAT_CODE=\"6\", ITEM_CODE1=itemcode,\n ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/10/\" + year + \"/6/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n else:\n if crime == '1': itemcode = \"10208\"\n else: itemcode = \"10211\"\n for i in range(5, 14):\n uri = userURIBuilder(server, start=\"1\", end=\"10\", BASE_YEAR=year, STAT_CODE=\"182\", ITEM_CODE1=itemcode,\n ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/10/\" + year + \"/182/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n\ndef getAreaData(year, crime):\n global server, regKey, conn, uri, URI\n if conn == None:\n connectOpenAPIServer()\n\n if year != \"2014\" and year != \"2015\":\n print(\"해당 년도의 데이터가 없습니다.\")\n else:\n if crime == '1': itemcode = \"10208\"\n else: itemcode = \"10211\"\n for i in range(5, 22):\n uri = userURIBuilder(server, start=\"1\", end=\"10\", BASE_YEAR=year, STAT_CODE=\"185\", ITEM_CODE1=itemcode,\n ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/10/\" + year + \"/185/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n\ndef getMotivData(year, crime):\n global server, regKey, conn, uri, URI\n if conn == None:\n connectOpenAPIServer()\n\n if year != \"2014\" and year != \"2015\":\n if crime == '1': itemcode = \"7\"\n else: itemcode = \"10\"\n for i in range(5, 22):\n uri = userURIBuilder(server, start=\"1\", end=\"10\", BASE_YEAR=year, STAT_CODE=\"57\", ITEM_CODE1=itemcode,\n ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/10/\" + year + \"/57/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n else:\n if crime == '1': itemcode = \"10208\"\n else: itemcode = \"10211\"\n for i in range(5, 26):\n uri = userURIBuilder(server, start=\"1\", end=\"10\", BASE_YEAR=year, STAT_CODE=\"224\", ITEM_CODE1=itemcode,\n ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/10/\" + year + \"/224/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n\ndef getMENTALData(year, crime):\n global server, regKey, conn, uri, URI\n if conn == None:\n connectOpenAPIServer()\n\n if year != \"2014\" and year != \"2015\":\n if (crime == \"1\"): itemcode = \"7\"\n else: itemcode = \"10\"\n for i in range(7, 25):\n uri = userURIBuilder(server, start=\"1\", end=\"500\", BASE_YEAR=year,\n STAT_CODE=\"56\", ITEM_CODE1=itemcode, ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/500/\" + year + \"/500/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n else:\n if (crime == \"1\"): itemcode = \"10208\"\n else: itemcode = \"10211\"\n for i in range(7, 25):\n uri = userURIBuilder(server, start=\"1\", end=\"500\", BASE_YEAR=year,\n STAT_CODE=\"208\", ITEM_CODE1=itemcode, ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/500/\" + year + \"/208/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n\ndef getRELATIONData(year, crime):\n global server, regKey, conn, uri, URI\n if conn == None:\n connectOpenAPIServer()\n\n if year != \"2014\" and year != \"2015\":\n if (crime == '1'): itemcode = \"7\"\n else: itemcode = \"10\"\n for i in range(5, 19):\n uri = userURIBuilder(server, start=\"1\", end=\"500\", BASE_YEAR=year,\n STAT_CODE=\"53\", ITEM_CODE1=itemcode, ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/500/\" + year + \"/53/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n else:\n if (crime == '1'): itemcode = \"10208\"\n else: itemcode = \"10211\"\n for i in range(5, 19):\n uri = userURIBuilder(server, start=\"1\", end=\"500\", BASE_YEAR=year,\n STAT_CODE=\"229\", ITEM_CODE1=itemcode, ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/500/\" + year + \"/229/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n\ndef getTOOLData(year, crime):\n global server, regKey, conn, uri, URI\n if conn == None:\n connectOpenAPIServer()\n\n if year != \"2014\" and year != \"2015\":\n for r in range(420, 427):\n for i in range(5, 19):\n uri = userURIBuilder(server, start=\"1\", end=\"500\", BASE_YEAR=year,\n STAT_CODE=\"36\", ITEM_CODE1=str(r), ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/500/\" + year + \"/36/\" + str(r) +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n else:\n for r in range(420, 427):\n for i in range(5, 19):\n uri = userURIBuilder(server, start=\"1\", end=\"500\", BASE_YEAR=year,\n STAT_CODE=\"190\", ITEM_CODE1=str(r), ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/500/\" + year + \"/190/\" + str(r) +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n\ndef getCLUEData(year, crime):\n global server, regKey, conn, uri, URI\n if conn == None:\n connectOpenAPIServer()\n\n if year != \"2014\" and year != \"2015\":\n if(crime == \"1\"): itemcode = \"7\"\n else: itemcode = \"10\"\n for i in range(5, 27):\n uri = userURIBuilder(server, start=\"1\", end=\"500\", BASE_YEAR=year,\n STAT_CODE=\"40\", ITEM_CODE1=itemcode, ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/500/\" + year + \"/40/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n else:\n if(crime == \"1\"): itemcode = \"10208\"\n else: itemcode = \"10211\"\n for i in range(5, 27):\n uri = userURIBuilder(server, start=\"1\", end=\"500\", BASE_YEAR=year,\n STAT_CODE=\"172\", ITEM_CODE1=itemcode, ITEM_CODE2=str(i))\n URI = uri + \"/1\" + \"/500/\" + year + \"/172/\" + itemcode +\"/\" + str(i)\n conn.request(\"GET\", uri)\n getData(year)\n\n\ndef getData(year):\n global CrimeDoc\n req = conn.getresponse()\n #print(req.status)\n if int(req.status) == 200:\n CrimeDoc = req.read().decode('utf-8')\n SearchLibrary()\n #PrintSearchData()\n #return extractBookData(req.read().decode('utf-8'))\n else:\n print(\"OpenAPI request has been failed!! please retry\")\n return None\n\n\ndef InitTopText():\n TempFont = font.Font(g_Tk, size=20, weight='bold', family = 'Consolas')\n MainText = Label(g_Tk, font = TempFont, text=\"[범죄 분석 App]\")\n MainText.pack()\n MainText.place(x=20)\n\n\ndef InitSearchListBox():\n # 데이터조회\n global SearchListBox\n ListBoxScrollbar = Scrollbar(g_Tk)\n ListBoxScrollbar.pack()\n ListBoxScrollbar.place(x=445, y=175)\n TempFont = font.Font(g_Tk, size=15, weight='bold', family='Consolas')\n SearchListBox = Listbox(g_Tk, font=TempFont, activestyle='none',\n width=30, height=1, borderwidth=12, relief='ridge',\n yscrollcommand=ListBoxScrollbar.set)\n SearchListBox.insert(0, \"피해자 성별과 연령(1964~2015)\")\n SearchListBox.insert(1, \"범죄발생 월(2014~2015)\")\n SearchListBox.insert(2, \"범죄발생시간(1964~2015)\")\n SearchListBox.insert(3, \"범죄발생지역(2014~2015)\")\n SearchListBox.insert(4, \"범죄자 범행 동기(1972~2015)\")\n SearchListBox.insert(5, \"범죄자 정신상태(1972~2015\")\n SearchListBox.insert(6, \"범죄자와 피해자와의 관계\")\n SearchListBox.insert(7, \"범죄도구 및 입수방법\")\n SearchListBox.insert(8, \"범죄자 검거단서\")\n SearchListBox.pack()\n SearchListBox.place(x=90, y=175)\n ListBoxScrollbar.config(command=SearchListBox.yview)\n\n # 차트조회\n global SearchListBox2\n ListBoxScrollbar2 = Scrollbar(g_Tk)\n ListBoxScrollbar2.pack()\n ListBoxScrollbar2.place(x=445, y=450)\n #TempFont = font.Font(g_Tk, size=15, weight='bold', family='Consolas')\n SearchListBox2 = Listbox(g_Tk, font=TempFont, activestyle='none',\n width=30, height=1, borderwidth=12, relief='ridge',\n yscrollcommand=ListBoxScrollbar2.set)\n\n SearchListBox2.insert(0, \"범죄발생 월(2014~2015)\")\n SearchListBox2.insert(1, \"범죄발생시간(2014~2015)\")\n SearchListBox2.insert(2, \"범죄발생지역(2014~2015)\")\n SearchListBox2.pack()\n SearchListBox2.place(x=90, y=450)\n ListBoxScrollbar2.config(command=SearchListBox2.yview)\n\n\ndef InitInputLabel():\n global InputLabel, InputLabel2, InputLabel3, InputLabel4, v1, v2, v3, v4\n TempFont = font.Font(g_Tk, size=15, weight='bold', family = 'Consolas')\n\n # 데이터 조회\n # 년도\n v1 = StringVar()\n InputLabel = Entry(g_Tk, font = TempFont, width = 30, borderwidth = 12, relief = 'ridge', textvariable=v1)\n InputLabel.pack()\n InputLabel.place(x=90, y=75)\n #사건\n v2 = StringVar()\n InputLabel2 = Entry(g_Tk, font=TempFont, width=30, borderwidth=12, relief='ridge', textvariable=v2)\n InputLabel2.pack()\n InputLabel2.place(x=90, y=125)\n\n # 차트 조회\n # 년도\n v3 = StringVar()\n InputLabel3 = Entry(g_Tk, font=TempFont, width=30, borderwidth=12, relief='ridge', textvariable=v3)\n InputLabel3.pack()\n InputLabel3.place(x=90, y=350)\n # 사건\n v4 = StringVar()\n InputLabel4 = Entry(g_Tk, font=TempFont, width=30, borderwidth=12, relief='ridge', textvariable=v4)\n InputLabel4.pack()\n InputLabel4.place(x=90, y=400)\n\n l1 = Label(g_Tk, text=\"년도\")\n l2 = Label(g_Tk, text=\"사건\")\n l3 = Label(g_Tk, text=\"세부사항\")\n l4 = Label(g_Tk, text=\"< 데이터 조회 >\")\n l5 = Label(g_Tk, text=\"< 차트 조회 >\")\n l6 = Label(g_Tk, text=\"년도\")\n l7 = Label(g_Tk, text=\"사건\")\n l8 = Label(g_Tk, text=\"세부사항\")\n l1.pack(); l2.pack(); l3.pack(); l4.pack();\n l5.pack(); l6.pack(); l7.pack(); l8.pack();\n l1.place(x=35, y=90); l2.place(x=35, y=140); l3.place(x=25, y=190); l4.place(x=10, y=50);\n l5.place(x=10, y=320); l6.place(x=35, y=370); l7.place(x=35, y=420); l8.place(x=25, y=470);\n\n\ndef InitSearchButton():\n TempFont = font.Font(g_Tk, size=12, weight='bold', family = 'Consolas')\n\n #데이터 조회\n SearchButton = Button(g_Tk, font = TempFont, text=\"검색\", command=SearchButtonAction)\n SearchButton.pack()\n SearchButton.place(x=240, y=235)\n\n # 차트 조회\n SearchButton2 = Button(g_Tk, font=TempFont, text=\"검색\", command=SearchButtonAction2)\n SearchButton2.pack()\n SearchButton2.place(x=240, y=505)\n\ndef SearchButtonAction():\n global SearchListBox, CSelect\n global InputLabel, InputLabel2, v1, v2\n RenderText.configure(state='normal')\n RenderText.delete(0.0, END)\n\n #ret = getCrimeDataFromYear(InputLabel)\n #AddBook(ret)\n\n if (v2.get() == \"살인\"):\n CSelect = '1';\n else:\n CSelect = '2';\n\n RenderText.configure(state='normal')\n RenderText.delete(0.0, END)\n\n # 데이터 조회\n iSearchIndex = SearchListBox.curselection()[0]\n if iSearchIndex == 0:\n getSexData(v1.get(), CSelect)\n elif iSearchIndex == 1:\n getMonthData(v1.get(), CSelect)\n elif iSearchIndex == 2:\n getTimeData(v1.get(), CSelect)\n elif iSearchIndex == 3:\n getAreaData(v1.get(), CSelect)\n elif iSearchIndex == 4:\n getMotivData(v1.get(), CSelect)\n elif iSearchIndex == 5:\n getMENTALData(v1.get(), CSelect)\n elif iSearchIndex == 6:\n getRELATIONData(v1.get(), CSelect)\n elif iSearchIndex == 7:\n getTOOLData(v1.get(), CSelect)\n elif iSearchIndex == 8:\n getCLUEData(v1.get(), CSelect)\n\n SearchLibrary()\n\n RenderText.configure(state='disabled')\n\ndef SearchButtonAction2():\n global SearchListBox2\n global InputLabel3, InputLabel4, v3, v4\n\n # 차트 조회\n iSearchIndex2 = SearchListBox2.curselection()[0]\n if iSearchIndex2 == 0:\n if (v4.get() == \"살인\"):\n if (v3.get() == \"2014\"):\n img = PhotoImage(file='2014_murder_month.gif')\n else:\n img = PhotoImage(file='2015_murder_month.gif')\n else:\n if (v3.get() == \"2014\"):\n img = PhotoImage(file='2014_violence_month.gif')\n else:\n img = PhotoImage(file='2015_violence_month.gif')\n elif iSearchIndex2 == 1:\n if (v4.get() == \"살인\"):\n if (v3.get() == \"2014\"):\n img = PhotoImage(file='2014_murder_time.gif')\n else:\n img = PhotoImage(file='2015_murder_time.gif')\n else:\n if (v3.get() == \"2014\"):\n img = PhotoImage(file='2014_violence_time.gif')\n else:\n img = PhotoImage(file='2015_violence_time.gif')\n elif iSearchIndex2 == 2:\n if (v4.get() == \"살인\"):\n if (v3.get() == \"2014\"):\n img = PhotoImage(file='2014_murder_region.gif')\n else:\n img = PhotoImage(file='2015_murder_region.gif')\n else:\n if (v3.get() == \"2014\"):\n img = PhotoImage(file='2014_violence_region.gif')\n else:\n img = PhotoImage(file='2015_violence_region.gif')\n\n lbl = Label(image=img)\n lbl.image = img\n lbl.pack(side=RIGHT)\n lbl.place(x=490, y=150)\n\ndef SearchLibrary():\n global CSelect, DataList\n import http.client\n from xml.dom.minidom import parse, parseString\n conn = http.client.HTTPConnection(\"openapi.crimestats.or.kr:8080\")\n conn.request(\"GET\", returnURI())\n req = conn.getresponse()\n DataList.clear()\n\n if req.status == 200:\n BooksDoc = req.read().decode('utf-8')\n if BooksDoc == None:\n print(\"에러\")\n else:\n parseData = parseString(BooksDoc)\n GeoInfoLibrary = parseData.childNodes\n row = GeoInfoLibrary[0].childNodes\n\n for item in row:\n if item.nodeName == \"row\":\n subitems = item.childNodes\n\n if subitems[1].firstChild is not None:\n RenderText.insert(INSERT, \"<\")\n RenderText.insert(INSERT, subitems[1].firstChild.nodeValue)\n RenderText.insert(INSERT, \"년도> \")\n if CSelect == '1':\n RenderText.insert(INSERT, \"<살인>\")\n else:\n RenderText.insert(INSERT, \"<성폭행>\")\n RenderText.insert(INSERT, \"\\n\"),\n if subitems[5].firstChild is not None:\n RenderText.insert(INSERT, subitems[5].firstChild.nodeValue)\n RenderText.insert(INSERT, \" - \")\n if subitems[13].firstChild is not None:\n RenderText.insert(INSERT, subitems[13].firstChild.nodeValue)\n RenderText.insert(INSERT, \", \")\n if subitems[15].firstChild is not None:\n RenderText.insert(INSERT, \"계: \")\n RenderText.insert(INSERT, subitems[15].firstChild.nodeValue)\n RenderText.insert(INSERT, \", \")\n RenderText.insert(INSERT, \"\\n\")\n RenderText.insert(INSERT, \"==========================================\")\n RenderText.insert(INSERT, \"\\n\\n\\n\\n\\n\")\n\n\ndef InitRenderText():\n global RenderText\n\n RenderTextScrollbar = Scrollbar(g_Tk)\n RenderTextScrollbar.pack()\n RenderTextScrollbar.place(x=375, y=200)\n\n TempFont = font.Font(g_Tk, size=10, family='Consolas')\n RenderText = Text(g_Tk, width=49, height=27, borderwidth=12, relief='ridge', yscrollcommand=RenderTextScrollbar.set)\n RenderText.pack()\n RenderText.place(x=540, y=115)\n RenderTextScrollbar.config(command=RenderText.yview)\n RenderTextScrollbar.pack(side=RIGHT, fill=BOTH)\n\n RenderText.configure(state='disabled')\n\n\n\n\nInitTopText()\nInitSearchListBox()\nInitInputLabel()\nInitSearchButton()\nInitRenderText()\n#InitSendEmailButton()\n#InitSortListBox()\n#InitSortButton()\n\ng_Tk.mainloop()\n","sub_path":"Term_Project/build/lib/internetbook.py","file_name":"internetbook.py","file_ext":"py","file_size_in_byte":20125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"654099495","text":"__author__ = 'linweizhong'\n\"\"\"\nTrapping Rain Water\n Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.\n https://leetcode.com/problems/trapping-rain-water/\n\"\"\"\nclass Solution:\n def findMax(self,arr,start,v):\n\n maxindex = start+1\n for i in xrange(start+1,len(arr),1) :\n if arr[i] >= v :\n return i\n if arr[i] >= arr[maxindex] :\n max_value = arr[i]\n maxindex = i\n return maxindex\n\n def calCapacity(self,arr,shortboard,start,end):\n capacity = 0\n #print start,end,shortboard\n for idx in xrange(start,end+1,1):\n v = shortboard -arr[idx]\n if v > 0 :\n capacity += v\n return capacity\n\n\n # @param {integer[]} height\n # @return {integer}\n def trap(self, height):\n if len(height) == 0 : return 0\n start = 0\n capacity = 0\n nextstart = 0\n while start < len(height):\n nextstart = self.findMax(height,start,height[start])\n if nextstart == (start +1) :\n start +=1\n continue\n\n shortboard = height[start]\n #print height[start],height[nextstart],start,nextstart\n if shortboard > height[nextstart] :\n shortboard = height[nextstart]\n #print \"capacity is :\",self.calCapacity(height,shortboard,start,nextstart)\n capacity += self.calCapacity(height,shortboard,start,nextstart)\n start = nextstart\n\n return capacity\n\n\n\n\n\n","sub_path":"leetcode/trapping_Rain_Water.py","file_name":"trapping_Rain_Water.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"143349015","text":"import requests\nimport json\nimport xlwt\nfrom bs4 import BeautifulSoup\n \ndef getData(page, news):\n headers = {\n \"Host\": \"interface.sina.cn\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0\",\n \"Accept\": \"*/*\",\n \"Accept-Language\": \"zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Connection\": \"keep-alive\",\n \"Referer\": r\"https://search.sina.com.cn/?q=%E9%87%91%E8%9E%8D%E8%B4%A2%E6%8A%A5&c=news&from=channel&ie=utf-8\",\n \"Cookie\": \"ustat=__172.16.93.31_1580710312_0.68442000; genTime=1580710312; vt=99; Apache=9855012519393.69.1585552043971; SINAGLOBAL=9855012519393.69.1585552043971; ULV=1585552043972:1:1:1:9855012519393.69.1585552043971:; historyRecord={'href':'https://news.sina.cn/','refer':'https://sina.cn/'}; SMART=0; dfz_loc=gd-default\",\n \"TE\": \"Trailers\"\n }\n \n params = {\n \"t\":\"\",\n \"q\":\"金融财报\",\n \"pf\":\"0\",\n \"ps\":\"0\",\n \"page\":\"1\",\n \"stime\":\"2019-03-30\",\n \"etime\":\"2020-03-31\",\n \"sort\":\"rel\",\n \"highlight\":page,\n \"num\":\"10\",\n \"ie\":\"utf-8\"\n }\n \n response = requests.get(\"https://interface.sina.cn/homepage/search.d.json?\", params=params, headers=headers)\n dic = json.loads(response.text)\n news += dic[\"result\"][\"list\"]\n \n return news\n \n \ndef writeData(news):\n workbook = xlwt.Workbook(encoding = 'utf-8')\n worksheet = workbook.add_sheet('MySheet')\n \n worksheet.write(0, 0, \"标题\")\n worksheet.write(0, 1, \"时间\")\n worksheet.write(0, 2, \"媒体\")\n worksheet.write(0, 3, \"网址\")\n worksheet.write(0, 4, \"正文\")\n \n for i in range(len(news)):\n #print(news[i])\n worksheet.write(i+1, 0, news[i][\"origin_title\"])\n worksheet.write(i+1, 1, news[i][\"datetime\"])\n worksheet.write(i+1, 2, news[i][\"media\"])\n worksheet.write(i+1, 3, news[i][\"url\"])\n html = requests.get(news[i][\"url\"]).content\n soup = BeautifulSoup(html,'xlml')\n worksheet.write(i + 1,\t4,\tsoup.text)\n \n workbook.save('D:/test/data.xls')\n \n \ndef main():\n news = []\n for i in range(1,501):\n news = getData(i, news)\n writeData(news)\n \nif __name__ == '__main__':\n main()","sub_path":"pingpang.py","file_name":"pingpang.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"57256854","text":"# -*- coding: utf-8 -*-\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.keys import Keys\nfrom pandas import ExcelWriter\nimport pandas as pd\n\noption = webdriver.ChromeOptions()\noption.add_argument(' - incognito')\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://www.jobstreet.vn/j?q=data&l=&sp=homepage\")\n\n#elem = driver.find_element_by_xpath('//*[@id=\"job-mail-subscribe-modal\"]/div/div/div/button/span')\n#elem.click()\n#timeout=20\n\nten = []\ntheloai=[]\ndiachi = []\nmotacongviec = []\nyeucaukinhnghiem =[]\nloiich=[]\ncount = 0\nlink = driver.find_elements_by_class_name('jobtitle')\n\n#form1\nwhile count <10:\n for i in link:\n j = i.get_attribute('href')\n driver.get(j)\n name = driver.find_element_by_id('company_name').text\n title = driver.find_element_by_('position_title').text\n address = driver.find_element_by_id('address').text\n mota = driver.find_element_by_class_name('job_description').text\n experience = driver.find_element_by_id('years_of_experience').text\n lido = driver.find_element_by_class_name('why_join_us_all').text\n \n ten.append(name)\n theloai.append(title)\n diachi.append(address)\n motacongviec.append(mota)\n yeucaukinhnghiem.append(experience)\n loiich.append(lido)\n count = count+1\n\n\n#form2 \n# while count <10:\n for i in link:\n j = i.get_attribute('href')\n driver.get(j)\n name = driver.find_element_by_class_name ('company').text\n title = driver.find_element_by_tag_name('h1').text\n address = driver.find_element_by_class_name('location').text\n mota = driver.find_element_by_class_name('summary').text\n thoigian = driver.find_element_by_class_name('date').text\n #lido = driver.find_element_by_class_name('why_join_us_all').text\n \n ten.append(name)\n theloai.append(title)\n diachi.append(address)\n motacongviec.append(mota)\n yeucaukinhnghiem.append(thoigian)\n #loiich.append(lido)\n count = count+1\n \n\ndf = pd.DataFrame({'Name':ten,\n 'Title':theloai,\n 'Address':diachi,\n 'Job':motacongviec,\n 'Year-Experience':yeucaukinhnghiem,\n 'benifit':loiich\n })\n\nwriter = ExcelWriter(\"jobstreet.xlsx\")\ndf.to_excel(writer)\nwriter.save() \n","sub_path":"Source/Final/Page/jobstreet.py","file_name":"jobstreet.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"382781243","text":"#!/usr/bin/python3\n\n#Author: Fredrik Hagen Fasteraune (freddahf@outlook.com)\n\ndef swap(data, i, j):\n tmp = data[i]\n data[i] = data[j]\n data[j] = tmp \n \ndef leftchild(x):\n return ((2 * x) + 1)\n\ndef rightchild(x):\n return ((2 * x) + 2)\n\ndef parent(x):\n return int((x-1) / 2)\n\ndef heapify(data, size, drawfn):\n i = parent(size-1)\n while i >= 0:\n siftdown(data, i, size-1, drawfn)\n i -=1\n\ndef siftdown(data, i, n, drawfn):\n root = data[i]\n\n while leftchild(i) < n:\n drawfn(data)\n hi = leftchild(i)\n if rightchild(i) < n and data[leftchild(i)] < data[rightchild(i)]:\n hi = rightchild(i) \n if data[hi] <= root:\n break\n\n data[i] = data[hi]\n i = hi\n data[i] = root\n\n\ndef heapsort_2(data, drawfn):\n heapify(data, len(data), drawfn)\n\n kake = input()\n\n i = len(data) - 1\n while i >= 0:\n swap(data, 0, i)\n siftdown(data, 0, i, drawfn)\n i -= 1\n\n","sub_path":"heapsort_2.py","file_name":"heapsort_2.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"633472105","text":"#-------------------------------------------------------------------------------\r\n# Name: Knight Board (Cruise Automation)\r\n# Purpose: Cruise Automation\r\n#\r\n# Author: Francis\r\n#\r\n# Created: 14-Jan-2017\r\n#-------------------------------------------------------------------------------\r\n\r\nfrom collections import deque\r\ntry:\r\n import Queue as Q # ver. < 3.0\r\nexcept ImportError:\r\n import queue as Q\r\n# All inputs are given as points and thus the point object is created\r\n# which has the x and y location of each point on the board\r\nclass Point:\r\n def __init__(self,x_init,y_init):\r\n self.x = x_init\r\n self.y = y_init\r\n\r\n#self.adjList = [] (an adjacency list of all the knight positions a knight can move to from that given vertex point)\r\n#self.visit = 0 (a variable to know whether a vertex has been visited or not)\r\n#self.parent = Point(-1,-1) ( a variable which tells the parent vertex of the given vertex)\r\n#self.special = Point(-1,-1) (a teleportation point for the given vertex)\r\n#self.cost = 1 (cost of moving to that vertex)\r\n#self.tCost = 0 (cost to travel to this vertex from the given start vertex)\r\n#self.type = 0 (type of vertex Eg: barrier, water, lava, etc)\r\n#self.parent1 = Point(-1,-1) ( a variable which tells the parent vertex for a loop from that vertex)\r\n#self.loopCost = 0 (Stores the cost of a loop if one exist from that vertex)\r\n#self.land = 0 (variable to print the vertex as a grid for viewing path of knight)\r\n\r\nclass Vertex(Point):\r\n def __init__(self, x_init,y_init):\r\n Point.__init__(self, x_init,y_init)\r\n self.adjList = []\r\n self.visit = 0\r\n self.parent = Point(-1,-1)\r\n self.special = Point(-1,-1)\r\n self.cost = 1\r\n self.tCost = 0\r\n self.type = 0\r\n self.parent1 = Point(-1,-1)\r\n self.loopCost = 0\r\n self.land = 0\r\n\r\n def setParent(self, pt):\r\n self.parent = pt\r\n\r\n def setParent1(self, pt):\r\n self.parent1 = pt\r\n\r\nglobal pointList, grid\r\npointList = []\r\n\r\ndef initializeGrid(grid):\r\n for i in range(grid):\r\n for j in range(grid):\r\n pt1 = Vertex(i,j)\r\n pointList.append(pt1)\r\n#points for the 32*32 grid with special properites the properties are mentioned below\r\nwater = [(8,8), (9,8), (9,9), (10,8), (10,9), (11,8), (11,9), (12,3), (12,4), (12,5),\r\n (12,6), (12,7), (12,8), (12,9), (13,3), (13,4), (13,5), (13,6), (13,7), (13,8),\r\n (13,9), (14,3), (14,3), (14,3), (14,4), (15,3), (15,4), (16,0), (16,1), (16,2),\r\n (16,3), (17,3), (17,4), (17,5), (17,6), (17,7), (17,8), (17,9), (18,3), (18,4),\r\n (18,5), (18,6), (18,7), (18,8), (18,9), (19,3), (19,4), (19,5), (19,6), (19,7),\r\n (19,8), (19,9), (20,3), (20,4), (20,5), (20,6), (20,7), (20,8), (20,9), (14,25),\r\n (14,26), (14,27), (14,28), (14,29), (14,30), (14,31), (14,29), (15,25), (16,19),\r\n (16,20), (16,21), (16,22), (16,23), (16,24), (16,25), (19,18), (19,19), (19,20),\r\n (19,21), (19,22), (19,23), (20,18), (20,19), (20,20), (20,21), (20,22), (20,23)]\r\nteleport = [(11,26), (23,27)]\r\nlava = [(0,12), (0,13), (0,14), (1,12), (1,13), (1,14), (2,12), (2,13), (2,14), (3,12),\r\n (3,13), (3,14), (4,12), (4,13), (4,14), (5,12), (5,13), (5,14), (2,18), (2,19),\r\n (2,20), (3,17), (3,18), (3,19), (4,15), (4,16), (4,17), (4,18), (4,19), (5,15),\r\n (5,16), (5,17)]\r\nrock = [(3,23), (3,24), (4,23), (4,24), (6,21), (6,22), (7,21), (7,22), (9,3), (9,4),\r\n (10,3), (10,4), (13,22), (13,23), (14,22), (14,23), (22,5), (22,6), (23,5), (23,6),\r\n (24,17), (24,18), (25,17), (25,18), (26,22), (26,23), (27,22), (27,23), (28,22),\r\n (28,23), (29,22), (29,23), (30,22), (30,23), (31,22), (31,23)]\r\nbarrier = [(0,8), (1,8), (2,8), (3,8), (4,8), (5,8), (6,8), (7,8), (7,9), (8,9), (8,10),\r\n (9,10), (9,11), (9,12), (9,13), (9,14), (9,15), (9,16), (9,17), (9,18), (9,19), (10,19),\r\n (11,19), (12,19), (13,19), (14,19), (14,18), (14,17), (14,16), (14,15), (15,15), (16,15),\r\n (17,15), (18,15), (18,16), (18,17), (19,17), (20,17), (17,31), (17,30), (17,29), (17,28),\r\n (18,28), (19,28), (19,27), (19,26), (19,25), (19,24), (20,24), (21,24), (21,25), (22,25),\r\n (23,25), (24,25), (31,11), (30,11), (29,11), (28,11), (27,11), (26,11), (25,11), (24,11),\r\n (23,11), (22,11), (21,11), (21,12), (21,13)]\r\n\r\n#find point in the global vertex list\r\ndef findPoint(pt):\r\n tLen = len(pointList)\r\n for i in range(tLen):\r\n if pt.x == pointList[i].x and pt.y == pointList[i].y:\r\n return i\r\n return -1\r\n\r\n# 0 normal cost = 1 move\r\n# 1 water cost = 2 moves\r\n# 2 Teleport cost = 0\r\n# 3 Lava cost = 5 moves\r\n# 4 rock cost = 1 move (cannot land on rock)\r\n# 5 barrier cost = cannot pass through barrier\r\ndef assignType(points, iType):\r\n for point in points:\r\n ind = findPoint(Point(point[0],point[1]))\r\n pointList[ind].type = iType\r\n\r\n#assign type property to each vertex in the global vertex list.\r\ndef assignAllType():\r\n assignType(water, 1)\r\n assignType(teleport, 2)\r\n assignType(lava, 3)\r\n assignType(rock, 4)\r\n assignType(barrier, 5)\r\n\r\n#printing the final grid with value K intermediate landing spots (just for visualization)\r\ndef printGrid():\r\n lGrid = len(pointList)\r\n row = abs(lGrid**(0.5))\r\n for i in range(lGrid):\r\n if i % row == 0:\r\n print('')\r\n if (pointList[i].type == 2):\r\n print('T',end = \" \")\r\n elif (pointList[i].land == 0):\r\n print(pointList[i].type, end = \" \")\r\n elif (pointList[i].land == 1):\r\n print('S',end = \" \" )\r\n elif (pointList[i].land == 2):\r\n print('K',end = \" \" )\r\n elif (pointList[i].land == 3):\r\n print('E',end = \" \" )\r\n print('')\r\n\r\n# assigning cost based on the type of the vertex which was earlier set\r\n# teleportation vertices have the point to which teleportation is possible stored\r\n# in the matrix\r\ndef assignCost():\r\n noPoint = len(pointList)\r\n for i in range(noPoint):\r\n temp = pointList[i].type\r\n if temp == 0 or temp == 4 :\r\n pointList[i].cost = 1\r\n elif temp == 1:\r\n pointList[i].cost = 2\r\n elif temp == 2:\r\n pointList[i].cost = 1\r\n if pointList[i].x == 11:\r\n pointList[i].special = Point(23,27)\r\n else:\r\n pointList[i].special = Point(11,26)\r\n elif temp == 3:\r\n pointList[i].cost = 5\r\n\r\n# finds all the moves which are possible for a knight from a particular point\r\ndef getValidMoves(pt):\r\n ind = findPoint(pt)\r\n moves = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]\r\n tList = []\r\n p = 1\r\n if pointList[ind].type == 2:\r\n p = 2\r\n for i in range(p):\r\n if i == 1:\r\n pt = pointList[ind].special\r\n for move in moves:\r\n temp = Point(pt.x+move[0],pt.y+move[1])\r\n ret = checkIfInGrid(temp)\r\n if ret == 1:\r\n ret = checkifPass(pt, temp)\r\n if ret == 1:\r\n tList.append(temp)\r\n pointList[ind].adjList.append(tList)\r\n return tList\r\n\r\n# check if the knight can pass as barrier is not allowed to be passed\r\ndef checkifPass(st, end):\r\n ind = findPoint(end)\r\n if pointList[ind].type >= 4:\r\n return 0\r\n move = 1\r\n # check whether if the knight has a valid way to move to the end point\r\n # without going through a barrier. The knight has two ways to travel to\r\n # the end point, both of which is checked here.\r\n for i in range(min(st.x, end.x+1), max(st.x, end.x+1)):\r\n ind = findPoint(Point(i,st.y))\r\n if pointList[ind].type > 4:\r\n move = 0\r\n break\r\n if move == 1:\r\n for j in range(min(st.y, end.y+1), max(st.y, end.y+1)):\r\n ind = findPoint(Point(end.x,j))\r\n if pointList[ind].type > 4:\r\n move = 0\r\n break\r\n\r\n if move == 0:\r\n for j in range(min(st.y, end.y+1), max(st.y, end.y+1)):\r\n ind = findPoint(Point(st.x,j))\r\n if pointList[ind].type > 4:\r\n return 0\r\n for i in range(min(st.x, end.x+1), max(st.x, end.x+1)):\r\n ind = findPoint(Point(i,end.y))\r\n if pointList[ind].type > 4:\r\n return 0\r\n return 1\r\n\r\n# checks if the point is in the 8x8 grid\r\ndef checkIfInGrid(pt):\r\n nPt = len(pointList)\r\n row = abs(nPt**0.5)\r\n if pt.x < row and pt.x >= 0 and pt.y < row and pt.y >= 0:\r\n return 1\r\n return 0\r\n\r\n# calculate the square of the distance between two points\r\ndef distanceSq(a, b):\r\n return ((a.x-b.x)**2+(a.y-b.y)**2)\r\n\r\n#check whether the sequence of moves are valid for a knight\r\ndef validateMoves(moves):\r\n for i, move in enumerate(moves):\r\n if i == 0:\r\n stP = move\r\n else:\r\n dSq = distanceSq(stP, move)\r\n if (dSq != 5):\r\n # print('Not a valid move')\r\n return 0\r\n elif (checkIfInGrid(move) == 0):\r\n return 0\r\n elif (checkifPass(stP, move) == 0):\r\n return 0\r\n stP = move\r\n # print('All valid moves')\r\n return 1\r\n\r\n# find the sequence of fewest moves from start \"st\" to end \"end\"\r\ndef computeMoveSeq(st, end):\r\n if st.x == end.x and st.y == end.y:\r\n return\r\n q = Q.PriorityQueue()\r\n count = 0\r\n q.put((0, count, st))\r\n while not q.empty():\r\n pt1 = q.get()[2]\r\n if pt1.x == end.x and pt1.y == end.y:\r\n break\r\n tempList = getValidMoves(pt1)\r\n ind = findPoint(pt1)\r\n tempCost = pointList[ind].tCost\r\n pointList[ind].visit = 1\r\n for m in range(len(tempList)):\r\n ind = findPoint(tempList[m])\r\n if pointList[ind].visit == 0:\r\n pointList[ind].setParent(pt1)\r\n pointList[ind].tCost = pointList[ind].cost + tempCost\r\n pointList[ind].visit = 1\r\n count += 1\r\n q.put((pointList[ind].tCost, count, tempList[m]))\r\n else:\r\n tCost = pointList[ind].cost + tempCost\r\n if tCost < pointList[ind].tCost:\r\n pointList[ind].setParent(pt1)\r\n count += 1\r\n q.put((pointList[ind].tCost, count, tempList[m]))\r\n path = computePath(st,end)\r\n return path\r\n\r\n# find the path given the start and end after the parent pointers are set\r\n# this function should be only called after the parent pointers are set\r\ndef computePath(st, end):\r\n ind = findPoint(end)\r\n pt1 = pointList[ind]\r\n path = []\r\n pathList = []\r\n while pt1.x != st.x or pt1.y != st.y:\r\n pathList.append(pt1)\r\n ind = findPoint(pt1)\r\n pt1 = pointList[ind].parent\r\n # done so that we know where to print K (Knight moves) in the grid\r\n pointList[ind].land = 2\r\n pathList.append(pt1)\r\n ind = findPoint(pathList[0])\r\n pointList[ind].land = 3\r\n ind = findPoint(pathList[len(pathList)-1])\r\n pointList[ind].land = 1\r\n while len(pathList):\r\n pt2 = pathList.pop()\r\n path.append(pt2)\r\n return path\r\n\r\n#compute the longest path sequence after the two parent pointers are set.\r\n# the loop parent pointer and the farthest distance pointer.\r\ndef computeLongPath(st, end):\r\n # path traversed by following the pointers from end to start\r\n pt1 = Point(end.x,end.y)\r\n path = []\r\n pathList = []\r\n while pt1.x != st.x or pt1.y != st.y:\r\n ind = findPoint(pt1)\r\n if pointList[ind].visit == 2:\r\n pathList.append(pt1)\r\n pointList[ind].visit = 1\r\n pointList[ind].land = 2\r\n pt1 = pointList[ind].parent1\r\n ind = findPoint(pt1)\r\n elif pointList[ind].visit == 1:\r\n pathList.append(pt1)\r\n pointList[ind].visit = 0\r\n pointList[ind].land = 2\r\n pt1 = pointList[ind].parent\r\n # if the 2nd parent points to a path which is already used twice then\r\n # the 1st parent is used to move towards the start\r\n else:\r\n pt1 = pathList.pop()\r\n ind = findPoint(pt1)\r\n pointList[ind].visit = 1\r\n pathList.append(pt1)\r\n ind = findPoint(pathList[0])\r\n pointList[ind].land = 3\r\n ind = findPoint(pathList[len(pathList)-1])\r\n pointList[ind].land = 1\r\n while len(pathList):\r\n pt2 = pathList.pop()\r\n path.append(pt2)\r\n return path\r\n\r\n# Negative of the previous method such that the cost 5 become -5 and thus now\r\n# is the highest priority. At the same time the largest loop is computed at a given\r\n# vertex and the loop cost is stored and the final parent pointer is set for the\r\n# loop which has the highest\r\ndef computeLongestMoveSeq(st, end):\r\n if st.x == end.x and st.y == end.y:\r\n return\r\n ind = findPoint(end)\r\n pointList[ind].cost = -10\r\n pointList[ind].visit = 1\r\n q = Q.PriorityQueue()\r\n ind = findPoint(st)\r\n pointList[ind].visit = 1\r\n count = 0\r\n q.put((0, count, st))\r\n while not q.empty():\r\n pt1 = q.get()[2]\r\n if pt1.x == end.x and pt1.y == end.y:\r\n break\r\n tempList = getValidMoves(pt1)\r\n ind = findPoint(pt1)\r\n tempCost = pointList[ind].tCost\r\n for m in range(len(tempList)):\r\n ind = findPoint(tempList[m])\r\n if pointList[ind].visit == 0:\r\n pointList[ind].setParent(pt1)\r\n pointList[ind].tCost = - pointList[ind].cost + tempCost\r\n pointList[ind].visit += 1\r\n count += 1\r\n q.put((pointList[ind].tCost, count, tempList[m]))\r\n elif pointList[ind].visit == 1:\r\n pointList[ind].loopCost = - pointList[ind].cost + tempCost - pointList[ind].tCost\r\n pointList[ind].setParent1(pt1)\r\n pointList[ind].visit += 1\r\n count += 1\r\n q.put((pointList[ind].tCost+pointList[ind].loopCost, count, tempList[m]))\r\n elif pointList[ind].visit == 2:\r\n tLoopCost = - pointList[ind].cost + tempCost - pointList[ind].tCost\r\n if tLoopCost < pointList[ind].loopCost:\r\n pointList[ind].loopCost = tLoopCost\r\n pointList[ind].setParent1(pt1)\r\n count += 1\r\n q.put((pointList[ind].tCost+pointList[ind].loopCost, count, tempList[m]))\r\n path = computeLongPath(st,end)\r\n return path\r\n\r\nif __name__ == '__main__':\r\n initializeGrid(8)\r\n #Level 1\r\n #definition of start and end point\r\n S = Point(0,0)\r\n ind = findPoint(S)\r\n pointList[ind].land = 1\r\n E = Point(3,1)\r\n ind = findPoint(E)\r\n pointList[ind].land = 3\r\n # definition of an intermediate position\r\n K = Point (1,2)\r\n ind = findPoint(K)\r\n pointList[ind].land = 2\r\n moves = [S,K,E]\r\n ret = validateMoves(moves)\r\n print('\\nLevel 1: Validate sequence of moves\\n')\r\n print('Start Pt:', S.x,S.y)\r\n print('Intermediate Pt: K', K.x, K.y)\r\n print('End Pt:', E.x,E.y)\r\n print('ret = ',ret)\r\n printGrid()\r\n #Level 2 and level 3\r\n path1 = computeMoveSeq(S,E)\r\n print('\\nLevel 2 and 3: Fewest sequence of moves for a normal 8*8 board\\n')\r\n print('Start Pt:', S.x,S.y)\r\n print('End Pt:', E.x,E.y)\r\n for i in range(len(path1)):\r\n print(path1[i].x, path1[i].y)\r\n #Level 4\r\n pointList = []\r\n initializeGrid(32)\r\n assignAllType()\r\n assignCost()\r\n #definition of start and end point\r\n S = Point(0,0)\r\n E = Point(10, 30)\r\n path2 = computeMoveSeq(S,E)\r\n print('\\nLevel 4: Fewest sequence of moves for 32*32 special board\\n')\r\n print('Start Pt:', S.x,S.y)\r\n print('End Pt:', E.x,E.y)\r\n for i in range(len(path2)):\r\n print(path2[i].x, path2[i].y)\r\n printGrid()\r\n #level 5\r\n pointList = []\r\n initializeGrid(32)\r\n assignAllType()\r\n assignCost()\r\n #definition of start and end point\r\n S = Point(0,0)\r\n E = Point(1,2)\r\n path3 = computeLongestMoveSeq(S,E)\r\n print('\\nLevel 5: Longest sequence of Moves\\n')\r\n print('Start Pt:', S.x,S.y)\r\n print('End Pt:', E.x,E.y)\r\n for i in range(len(path3)):\r\n print(path3[i].x, path3[i].y)\r\n printGrid()\r\n\r\n","sub_path":"KnightMoveProb.py","file_name":"KnightMoveProb.py","file_ext":"py","file_size_in_byte":16276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"8917799","text":"\"\"\"myapp.py\n\nUsage:\n\n (window1)$ python myapp.py -l info\n\n (window2)$ python\n >>> from myapp import add\n >>> add.delay(16, 16).get()\n 32\n\n\"\"\"\nfrom celery import Celery\n\n\ncelery = Celery(\"myapp\")\ncelery.conf.update(BROKER_HOST=\"localhost\")\n\n@celery.task(accept_magic_kwargs=False)\ndef add(x, y, **kwargs):\n print(\"add id: %r %r %r\" % (add.request.id, add.request.args,\n add.request.kwargs))\n print(\"kwargs: %r\" % (kwargs, ))\n return x + y\n\nif __name__ == \"__main__\":\n celery.worker_main()\n","sub_path":"examples/app/myapp.py","file_name":"myapp.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"551389860","text":"import operate\n\nclass Route:\n\n\n def __init__(self):\n self.MAX_ROUTE_SIZE = 42\n self.evalNum = 0\n self.ope = operate.Operator()\n self.bit1 = 1\n self.bit2 = 1\n\n def __gt__(self, other):\n return self.evalNum > other.evalNum\n\n def duplicate(self):\n tmp = Route()\n tmp.bit1 = self.bit1\n tmp.bit2 = self.bit2\n return tmp\n\n\n def push_back(self, nextRoute):\n if self.bit1 >> 63:\n self.bit2 = (self.bit2 << 3) | (nextRoute & ((1 << 3) - 1))\n else:\n self.bit1 = (self.bit1 << 3) | (nextRoute & ((1 << 3) - 1))\n\n\n def push_back_length(self, nextRoute, length):\n msb = 0\n msb = self.MSB64bit(self.bit1, msb)\n if(length <= 0):\n return\n if msb == 63:\n self.bit2 = (self.bit2 << 3 * length) | nextRoute\n elif msb + length * 3 < 64:\n self.bit1 = (self.bit1 << 3 * length) | nextRoute\n else:\n firstLength = length - (63 - msb) / 3\n self.bit1 = (self.bit1 << (3*firstLength)) | (nextRoute & ((1 << ((firstLength*3) - 1))))\n self.bit2 = (self.bit2 << (3 * (length - firstLength))) | (nextRoute >> (firstLength*3))\n\n\n def push_back_route(self, route):\n argMsb1 = argMsb2 = 0\n argMsb1 = self.MSB64bit(route.bit1, argMsb1)\n argMsb2 = self.MSB64bit(route.bit2, argMsb2)\n \n self.push_back_length(route.bit1 & ~(1 << argMsb1), int(argMsb1/3))\n self.push_back_length(route.bit2 & ~(1 << argMsb2), int(argMsb2/3))\n\n\n def top(self):\n if self.bit1 == 1:\n return -1\n if self.bit2 != 1:\n return self.bit2 & ((1 << 3) - 1)\n return self.bit1 & ((1 << 3) - 1)\n\n\n def getBits(self, index):\n if index >= self.MAX_ROUTE_SIZE:\n return -1\n if index < 21:\n msb = 0\n msb = self.MSB64bit(self.bit1, msb)\n if msb < index * 3:\n return -1\n return (self.bit1 >> ((msb/3 -index-1)*3)) & ((1 << 3) - 1)\n else:\n msb = 0\n msb = self.MSB64bit(self.bit2, msb)\n index -= 21\n if msb < index * 3:\n return -1\n return (self.bit2 >> ((msb/3 -index-1)*3)) & ((1 << 3) - 1)\n\n\n def shift(self):\n if self.bit1 == 1:\n return\n if self.bit2 == 1:\n self.bit1 = self.bit1 >> 3\n else:\n self.bit1 = (self.bit1 >> 3) | (self.bit2 & ((1 << 3) - 1))\n self.bit2\n\n\n def pop_back(self):\n if self.bit1 == 1:\n return\n if self.bit2 != 1:\n self.bit2 = self.bit2 >> 3\n else:\n self.bit1 = self.bit1 >> 3\n self.bit1 = max(1, self.bit1)\n self.bit2 = max(1, self.bit2)\n\n\n def pop_back_length(self, length):\n if self.bit2 == 1:\n self.bit1 = (self.bit1 >> length * 3)\n msb = 0\n msb = self.MSB64bit(self.bit2, msb)\n \n secondLength = length - msb / 3\n if secondLength <= 0:\n self.bit2 = (self.bit2 >> length * 3)\n else:\n self.bit2 = 1\n self.bit1 = (self.bit1 >> secondLength * 3)\n self.bit1 = max(1, self.bit1)\n self.bit2 = max(1, self.bit2)\n\n\n def size(self):\n bit1Size = bit2Size = 0\n bit1Size = self.MSB64bit(self.bit1, bit1Size)\n bit2Size = self.MSB64bit(self.bit2, bit2Size)\n return (bit1Size + bit2Size) / 3\n\n\n def clear(self):\n self.bit1 = 1\n self.bit2 = 1\n\n# here is operator\n\n def count64bit(self, v):\n count = (v&0x5555555555555555)+((v>>1)&0x5555555555555555)\n count = (count&0x3333333333333333)+((count>>2)&0x3333333333333333)\n count = (count&0x0f0f0f0f0f0f0f0f)+((count>>4)&0x0f0f0f0f0f0f0f0f)\n count = (count&0x00ff00ff00ff00ff)+((count>>8)&0x00ff00ff00ff00ff)\n count = (count&0x0000ffff0000ffff)+((count>>16)&0x0000ffff0000ffff)\n return (int)((count&0x00000000ffffffff)+((count>>32)&0x00000000ffffffff))\n def MSB64bit(self, v, out):\n if v == 0:\n return\n v |= (v >> 1)\n v |= (v >> 2)\n v |= (v >> 4)\n v |= (v >> 8)\n v |= (v >> 16)\n v |= (v >> 32)\n out = self.count64bit(v) - 1\n return out\n\n","sub_path":"ロボット創造実習/program/mac/route.py","file_name":"route.py","file_ext":"py","file_size_in_byte":4318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"408185912","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport autoslug.fields\nimport ckeditor_uploader.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('translation', '__first__'),\n ('channel', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Contact',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('email', models.EmailField(max_length=100)),\n ('state', models.CharField(default=b'S', max_length=1, choices=[(b'A', 'All'), (b'S', 'Subscribed'), (b'U', 'Unsubscribed')])),\n ('creation_date', models.DateTimeField(auto_now_add=True, null=True)),\n ('subscription_date', models.DateTimeField(null=True, blank=True)),\n ('unsubscription_date', models.DateTimeField(null=True, blank=True)),\n ('channel', models.ForeignKey(to='channel.Channel')),\n ],\n options={\n 'db_table': 'contact',\n },\n ),\n migrations.CreateModel(\n name='Newsletter',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('channel', models.ForeignKey(to='channel.Channel')),\n ],\n options={\n 'db_table': 'newsletter',\n },\n ),\n migrations.CreateModel(\n name='NewsletterAuthor',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('first_name', models.CharField(max_length=100, blank=True)),\n ('last_name', models.CharField(max_length=100, blank=True)),\n ('url', models.URLField(null=True, blank=True)),\n ],\n options={\n 'db_table': 'newsletter_author',\n },\n ),\n migrations.CreateModel(\n name='NewsletterTranslation',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=69)),\n ('slug', autoslug.fields.AutoSlugField(unique=True, editable=False)),\n ('subtitle', ckeditor_uploader.fields.RichTextUploadingField()),\n ('state', models.SmallIntegerField(default=1, choices=[(1, b'Cr\\xc3\\xa9\\xc3\\xa9'), (2, b'Publi\\xc3\\xa9e'), (3, b'Corbeille'), (4, b'BDD')])),\n ('lang', models.CharField(max_length=2, choices=[(b'fr', b'French'), (b'en', b'English')])),\n ('creation_date', models.DateTimeField(auto_now_add=True)),\n ('last_modification_date', models.DateTimeField(auto_now=True)),\n ('publish_date', models.DateTimeField(db_index=True, null=True, blank=True)),\n ('trash_date', models.DateTimeField(null=True, blank=True)),\n ('delete_date', models.DateTimeField(null=True, blank=True)),\n ('newsletter', models.ForeignKey(related_name='newsletter_translation', to='newsletter.Newsletter')),\n ],\n options={\n 'db_table': 'newsletter_translation',\n },\n ),\n migrations.CreateModel(\n name='NewsletterTranslationsOrder',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('order', models.IntegerField(null=True, blank=True)),\n ('newsletter_translation', models.ForeignKey(related_name='n_t', to='newsletter.NewsletterTranslation')),\n ('translation', models.ForeignKey(related_name='newsletter_translations_order', to='translation.Translation')),\n ],\n options={\n 'ordering': ('order',),\n 'db_table': 'newsletter_translations_order',\n },\n ),\n migrations.AddField(\n model_name='newslettertranslation',\n name='translations',\n field=models.ManyToManyField(related_name='translations', through='newsletter.NewsletterTranslationsOrder', to='translation.Translation', blank=True),\n ),\n migrations.AddField(\n model_name='newsletterauthor',\n name='newsletter_translation',\n field=models.ForeignKey(to='newsletter.NewsletterTranslation'),\n ),\n migrations.AlterUniqueTogether(\n name='contact',\n unique_together=set([('email', 'channel')]),\n ),\n ]\n","sub_path":"src/newsletter/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"311537480","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom tqdm import tqdm\nimport wandb\nimport time\nimport os\n\nfrom SysDLNet import Net\n\n\ndef run(config=None):\n if config:\n wandb.init(config=config, project=\"SysDL Assignment 3\")\n else:\n wandb.init(project=\"SysDL Assignment 3\")\n config = wandb.config\n device = \"cuda\"\n\n transform_train = transforms.Compose(\n [\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ]\n )\n transform_test = transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ]\n )\n\n trainset = torchvision.datasets.CIFAR100(\n root=\"/data\", train=True, download=True, transform=transform_train\n )\n trainloader = torch.utils.data.DataLoader(\n trainset, batch_size=config[\"batch_size\"], shuffle=True, num_workers=4\n )\n\n testset = torchvision.datasets.CIFAR100(\n root=\"/data\", train=False, download=True, transform=transform_test\n )\n testloader = torch.utils.data.DataLoader(\n testset, batch_size=config[\"batch_size\"], shuffle=False, num_workers=4\n )\n\n net = Net()\n net.to(device)\n\n loss_fn = torch.nn.CrossEntropyLoss()\n\n if config[\"optimizer\"] == \"adam\":\n optimizer = torch.optim.Adam(\n net.parameters(), lr=config[\"lr\"], weight_decay=config[\"weight_decay\"]\n )\n elif config[\"optimizer\"] == \"sgd\":\n optimizer = torch.optim.SGD(\n net.parameters(),\n lr=config[\"lr\"],\n weight_decay=config[\"weight_decay\"],\n momentum=config[\"momentum\"],\n )\n\n if config[\"schedule\"]:\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\n optimizer, len(trainloader) * config[\"epochs\"]\n )\n\n print(\"Starting training...\\n\")\n num_examples = 0\n\n wandb.watch(net)\n\n for epoch in range(config[\"epochs\"]):\n start_time = time.time()\n pbar = tqdm(desc=\"Training epoch: {}\".format(epoch), total=len(trainloader))\n correct = 0\n total = 0\n\n net.train()\n for i, data in enumerate(trainloader, 0):\n inputs, labels = data\n inputs, labels = inputs.to(device), labels.to(device)\n optimizer.zero_grad()\n outputs = net(inputs)\n loss = loss_fn(outputs, labels)\n loss.backward()\n optimizer.step()\n if config[\"schedule\"]:\n scheduler.step()\n\n num_examples += labels.shape[0]\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n wandb.log({\"train_loss\": loss.item(), \"examples_seen\": num_examples})\n pbar.update()\n\n train_accuracy = 100 * correct / total\n pbar.close()\n\n pbar = tqdm(desc=\"Testing\", total=len(testloader))\n running_loss = 0.0\n correct = 0\n total = 0\n\n net.eval()\n with torch.no_grad():\n for data in testloader:\n images, labels = data\n images, labels = images.to(device), labels.to(device)\n outputs = net(images)\n _, predicted = torch.max(outputs.data, 1)\n\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n running_loss += loss_fn(outputs, labels).item() * labels.shape[0]\n pbar.update()\n\n test_loss = running_loss / len(testset)\n test_accuracy = 100 * correct / total\n print(\"Accuracy on testset: {}\\n\".format(test_accuracy))\n pbar.close()\n\n wandb.log(\n {\n \"epoch\": epoch,\n \"train_acc\": train_accuracy,\n \"test_loss\": test_loss,\n \"test_acc\": test_accuracy,\n \"epoch_time\": time.time() - start_time,\n },\n )\n\n if (epoch + 1) % 5 == 0:\n torch.save(\n net.state_dict(),\n os.path.join(wandb.run.dir, \"SysDLNet_{}.pt\".format(epoch)),\n )\n\n\nif __name__ == \"__main__\":\n wandb.login(key=\"df416cf0e6b9361efc64aa08d4715af979c8d070\")\n\n run(\n {\n \"epochs\": 150,\n \"optimizer\": \"adam\",\n \"lr\": 0.0025,\n \"weight_decay\": 0.00001,\n \"batch_size\": 512,\n \"momentum\": 0.95,\n \"schedule\": True,\n }\n )\n\n # sweep_config = {\"method\": \"random\"}\n # metric = {\"name\": \"loss\", \"goal\": \"minimize\"}\n # sweep_config[\"metric\"] = metric\n # parameters_dict = {\n # \"epochs\": {\"value\": 20},\n # \"optimizer\": {\"values\": [\"adam\", \"sgd\"]},\n # \"lr\": {\"values\": [0.0001, 0.0025, 0.0075, 0.001, 0.003]},\n # \"weight_decay\": {\"values\": [0, 1e-5, 3e-5, 1e-4, 3e-4, 1e-3]},\n # \"batch_size\": {\"values\": [64, 256, 512]},\n # \"momentum\": {\"values\": [0, 0.1, 0.3, 0.6, 0.8, 0.9, 0.95]},\n # \"schedule\": {\"values\": [True, False]},\n # }\n # sweep_config[\"parameters\"] = parameters_dict\n\n # sweep_id = wandb.sweep(sweep_config, project=\"SysDL Assignment 3\")\n # wandb.agent(sweep_id, run, count=25)\n","sub_path":"assignment3/fuse.py","file_name":"fuse.py","file_ext":"py","file_size_in_byte":5409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"10475239","text":"# Dictionary\nalien_0 = {'color': 'green', 'points': 5}\n\nprint(alien_0['color'])\nprint(alien_0['points'])\n\nnew_points = alien_0['points']\nprint(f\"\\nYou earned {new_points} points!\")\n\n# Adding dictionary values\nalien_0['x_position'] = 0\nalien_0['y_position'] = 25\nprint(alien_0)\n\nalien_1 = {}\nalien_1['color'] = 'red'\nalien_1['points'] = 10\nprint(alien_1)\n\n# Modifying values\nalien_2 = {'color':'blue'}\nprint(f\"\\nThe alien is {alien_2['color']}.\")\nalien_2['color'] = 'yellow'\nprint(f\"The alien color is now {alien_2['color']}.\")\n\nalien_3 = {'x_position': 0, 'y_position': 25, 'speed': 'medium', 'points': 25}\nprint(f\"\\nOriginal position: {alien_3['x_position']}\")\n\n# Move the alien to the right\n# Determine how far to move the alien based on its current speed.\nif alien_3['speed'] == \"slow\":\n x_increment = 1\nelif alien_3['speed'] == 'medium':\n x_increment = 2\nelse:\n # This must be a fast alien\n x_increment = 3\n\n#The new position of the alien is:\nalien_3['x_position'] = alien_3['x_position'] + x_increment\nprint(f\"New position: {alien_3['x_position']}\")\n\nprint(f\"\\n{alien_3}\")\ndel alien_3['points']\nprint(alien_3)","sub_path":"alien.py","file_name":"alien.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"438087656","text":"import sys\nfrom Bio import SeqIO\n\n\n\nworking_dir = \"/mnt/lustre/hcgs/joseph7e/program_PrimerRegionExtractor/extract_regions_from_CLC/\"\nfasta_file = working_dir + \"../99_otus_18S.fasta\"\n#forward_primer = sys.argv[2]\n#reverse_primer = sys.argv[3]\ntaxonomy_file = working_dir + \"../majority_taxonomy_all_levels.txt\"\n# blast_results = working_dir + \"V9.blast\"\n\ntax_dict = {}\nfor line in open(taxonomy_file):\n elements = line.rstrip().split('\\t')\n seq = elements[0]\n phylum = elements[1].split(';')[5]\n if \"Metazoa\" in elements[1]:\n tax_dict[seq] = phylum\n\nsequence_dict = SeqIO.to_dict(SeqIO.parse(fasta_file, \"fasta\"))\n\nfor k, v in tax_dict.items():\n print ('>' + k +'\\n' + sequence_dict[k].seq)\n","sub_path":"Primer-Extract/extract_metazoa.py","file_name":"extract_metazoa.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"43504932","text":"from backend import non_edge_blurring\nfrom rapport_snippets.figs import *\n\n\ndef compile(output_dir=\"./rapport_snippets/output/\"):\n \"\"\"\n Compiles a .tex file for the non edge blurring function\n\n Parameters\n ----------\n output_dir : str\n the location to store the .tex with images\n \"\"\"\n for color in [True, False]:\n name = (\"color\" if color else \"gray\")\n output_dir_path = output_dir + name\n make_dir(output_dir_path)\n\n blurring_obj = non_edge_blurring.NonEdgeBlur(\"./files/test_images/lena.png\", color)\n epoch_count = {\n 0.25: [1, 10, 100],\n 0.5: [1, 10, 100],\n 0.75: [1, 10, 100]\n }\n results_doc = compile_doc(blurring_obj, epoch_count, \"{}/\".format(output_dir_path),\n \"glatting/non_edge_blur/{}/\".format(name))\n results_doc.add_caption(\"Resultat med ulike verdier av $\\\\alpha$ og iterasjoner. $K={}$ på alle bildene.\".format(blurring_obj.k))\n results_doc.add_ref(\"nonEdgeBlur\" + name)\n results_doc.save(\"{}/results.tex\".format(output_dir_path))\n","sub_path":"src/rapport_snippets/non_edge_blurring.py","file_name":"non_edge_blurring.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"266560811","text":"import numpy as np\nimport cv2\nfrom EssentialMatrixFromFundamentalMatrix import *\nfrom GetInlierRANSANC import * \nfrom GetIntrinsic import *\n\n\ndef ExtractCameraPose(E):\n print(\"*** ExtractCameraPose process:\")\n u, s, vh = np.linalg.svd(E, full_matrices=True)\n print(np.linalg.det(u))\n print(np.linalg.det(vh))\n # print(\"singular value: \", s) \n w = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]])\n R1 = np.matmul(u, np.matmul(w,vh))\n R2 = np.matmul(u, np.matmul(w.T, vh))\n # print(\"R1: \", np.linalg.det(R1))\n # print(\"R2: \", np.linalg.det(R2))\n U = u[:, 2]\n if np.linalg.det(R1) < 0: R1 = -R1\n if np.linalg.det(R2) < 0: R2 = -R2\n pose = [(U, R1), (-U, R1), (U, R2), (-U, R2)]\n\n for i, p in enumerate(pose):\n print(\"C\"+str(i+1))\n print(p[0])\n print(\"R\"+str(i+1))\n print(p[1])\n print(\"==========\")\n return pose\n\n\nif __name__ == \"__main__\":\n # img1 = cv2.imread('frame_gray/frame100.jpg', 0) # queryImage\n # img2 = cv2.imread('frame_gray/frame101.jpg', 0) # trainImage\n # pt = GetSiftCorrespondence(img1, img2, 0.7)\n # F, _ = GetInlierRANSANC(pt, 20, 0.001)\n # K = GetIntrinsic(\"Oxford_dataset/model\")\n # E = EssentialMatrixFromFundamentalMatrix(F, K)\n # pose = ExtractCameraPose(E)\n # print(pose)\n K = np.array([[568.996140852, 0, 643.21055941],\n [0, 568.988362396, 477.982801038],\n [0, 0, 1]])\n\n filePath = \"../Data/Imgs/\"\n corDict = readMatches(filePath)\n curDict = corDict['12']\n F, matchPts_inlier = GetInlierRANSAC(curDict, 20000, 0.0025)\n E = EssentialMatrixFromFundamentalMatrix(F, K)\n pose = ExtractCameraPose(E)\n\n","sub_path":"StructureFromMotion/Utils/ExtractCameraPose.py","file_name":"ExtractCameraPose.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"167341802","text":"from matplotlib import pyplot as plt\nimport numpy as np\nimport random\nimport tensorflow as tf\n\n\ndef visualize_losses(train_loss, test_loss):\n plt.figure(1)\n plt.plot(train_loss, 'r-')\n plt.plot(test_loss, 'b-')\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.show()\n\n\ndef visualize_tensor(tensor):\n plt.subplot()\n plt.imshow(tensor)\n plt.show()\n\n\nif __name__ == '__main__':\n print('A suite of visualizing stuff (activations, weights, loss, etc.)')\n img = np.zeros([5, 5], dtype=np.float32)\n for i in range(img.shape[0]):\n for j in range(img.shape[1]):\n img[i][j] = random.random()\n\n visualize_tensor(img)\n\n","sub_path":"visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"181039967","text":"# -*- coding: utf-8 -*-\n\nfrom bse import path as _p\n\nNETRC = _p.expanduser(\"~/.netrc\")\n\nLOG = _p.join(_p.here(__file__), \"..\", \"bse.log\")\n\n# Environment variables\n\nENV_NETRC = \"BSE_NETRC\"\n\n# Dict keys to mask when debugging\n\nMASK_KEYS = (\"CB-ACCESS-SIGN\", \"CB-ACCESS-KEY\")\n\n# Script paths\n\nSCRIPT_PATHS = (_p.join(_p.here(__file__), \"scripts\"),)\n","sub_path":"bse/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"356326748","text":"from bs4 import BeautifulSoup\nfrom cybersource.constants import CHECKOUT_BASKET_ID, CHECKOUT_ORDER_NUM, CHECKOUT_SHIPPING_CODE, CHECKOUT_ORDER_ID\nfrom cybersource.tests import factories as cs_factories\nfrom decimal import Decimal as D\nfrom django.core import mail\nfrom django.core.urlresolvers import reverse\nfrom mock import patch\nfrom oscar.core.loading import get_class, get_model\nfrom oscar.test import factories\nfrom random import randrange\nfrom rest_framework.test import APITestCase\nimport datetime\nimport requests # Needed for external calls!\n\nBasket = get_model('basket', 'Basket')\nProduct = get_model('catalogue', 'Product')\nOrder = get_model('order', 'Order')\n\n\nclass BaseCheckoutTest(APITestCase):\n fixtures = ['cybersource-test.yaml']\n\n def create_product(self, price=D('10.00')):\n product = factories.create_product(\n title='My Product',\n product_class='My Product Class')\n record = factories.create_stockrecord(\n currency='USD',\n product=product,\n num_in_stock=10,\n price_excl_tax=price)\n factories.create_purchase_info(record)\n return product\n\n def do_add_to_basket(self, product_id, quantity=1):\n url = reverse('api-basket-add-product')\n data = {\n \"url\": reverse('product-detail', args=[product_id]),\n \"quantity\": quantity\n }\n return self.client.post(url, data)\n\n def do_get_basket(self):\n url = reverse('api-basket')\n return self.client.get(url)\n\n def do_sign_auth_request(self, basket_id=None, data=None):\n if data is None:\n data = {\n \"guest_email\": \"herp@example.com\",\n \"basket\": reverse('basket-detail', args=[basket_id]),\n \"shipping_address\": {\n \"first_name\": \"fadsf\",\n \"last_name\": \"fad\",\n \"line1\": \"234 5th Ave\",\n \"line4\": \"Manhattan\",\n \"postcode\": \"10001\",\n \"state\": \"NY\",\n \"country\": reverse('country-detail', args=['US']),\n \"phone_number\": \"+1 (717) 467-1111\",\n }\n }\n url = reverse('cybersource-sign-auth-request')\n res = self.client.post(url, data, format='json')\n self.assertEqual(res.status_code, 200)\n\n next_year = datetime.date.today().year + 1\n cs_data = {\n 'card_type': '001',\n 'card_number': '4111111111111111',\n 'card_cvn': '123',\n 'card_expiry_date': '12-{}'.format(next_year),\n 'bill_to_forename': 'Testy',\n 'bill_to_surname': 'McUnitTest',\n 'bill_to_address_line1': '234 5th Ave',\n 'bill_to_address_line2': 'apt 5',\n 'bill_to_address_city': 'Manhattan',\n 'bill_to_address_state': 'NY',\n 'bill_to_address_postal_code': '10001',\n 'bill_to_address_country': 'US',\n 'bill_to_phone': '17174671111',\n }\n for field in res.data['fields']:\n if not field['editable'] or field['key'] not in cs_data:\n cs_data[field['key']] = field['value']\n cs_url = res.data['url']\n return cs_url, cs_data\n\n def do_cybersource_post(self, cs_url, cs_data):\n res = requests.post(cs_url, cs_data)\n self.assertEqual(res.status_code, 200)\n\n soup = BeautifulSoup(res.content, 'html.parser')\n form_data = {}\n for element in soup.find_all('input'):\n form_data[element['name']] = element['value']\n\n # We have the data from cybersource, send it to our cybersource callback\n url = reverse('cybersource-reply')\n return self.client.post(url, form_data)\n\n def check_finished_order(self, number, product_id, quantity=1):\n # Order exists and was paid for\n self.assertEqual(Order.objects.all().count(), 1)\n order = Order.objects.get()\n self.assertEqual(order.number, number)\n\n lines = order.lines.all()\n self.assertEqual(lines.count(), 1)\n line = lines[0]\n self.assertEqual(line.quantity, quantity)\n self.assertEqual(line.product_id, product_id)\n\n payment_events = order.payment_events.filter(event_type__name=\"Authorise\")\n self.assertEqual(payment_events.count(), 1)\n self.assertEqual(payment_events[0].amount, order.total_incl_tax)\n\n payment_sources = order.sources.all()\n self.assertEqual(payment_sources.count(), 1)\n self.assertEqual(payment_sources[0].currency, order.currency)\n self.assertEqual(payment_sources[0].amount_allocated, order.total_incl_tax)\n self.assertEqual(payment_sources[0].amount_debited, D('0.00'))\n self.assertEqual(payment_sources[0].amount_refunded, D('0.00'))\n\n transactions = payment_sources[0].transactions.all()\n self.assertEqual(transactions.count(), 1)\n self.assertEqual(transactions[0].txn_type, 'Authorise')\n self.assertEqual(transactions[0].amount, order.total_incl_tax)\n self.assertEqual(transactions[0].status, 'ACCEPT')\n\n self.assertEqual(transactions[0].log_field('req_reference_number'), order.number)\n self.assertEqual(transactions[0].token.card_last4, '1111')\n\n self.assertEqual(len(mail.outbox), 1)\n\n\n\n\nclass CheckoutIntegrationTest(BaseCheckoutTest):\n \"\"\"Full Integration Test of Checkout\"\"\"\n\n def test_checkout_process(self):\n \"\"\"Full checkout process using minimal api calls\"\"\"\n product = self.create_product()\n\n res = self.do_get_basket()\n self.assertEqual(res.status_code, 200)\n basket_id = res.data['id']\n\n res = self.do_add_to_basket(product.id)\n self.assertEqual(res.status_code, 200)\n\n cs_url, cs_data = self.do_sign_auth_request(basket_id)\n\n res = self.do_cybersource_post(cs_url, cs_data)\n self.assertEqual(res.status_code, 302)\n self.check_finished_order(cs_data['reference_number'], product.id)\n\n\n def test_add_product_during_auth(self):\n \"\"\"Test attempting to add a product during the authorize flow\"\"\"\n product = self.create_product()\n\n res = self.do_get_basket()\n self.assertEqual(res.status_code, 200)\n basket_id = res.data['id']\n\n # Adding a product here should succeed\n res = self.do_add_to_basket(product.id)\n basket1 = res.data['id']\n self.assertEqual(res.status_code, 200)\n\n cs_url, cs_data = self.do_sign_auth_request(basket_id)\n\n # Adding a product here should go to a new basket, not the one we're auth'ing\n res = self.do_add_to_basket(product.id)\n self.assertEqual(res.status_code, 200)\n basket2 = res.data['id']\n self.assertNotEqual(basket1, basket2)\n\n res = self.do_cybersource_post(cs_url, cs_data)\n self.assertEqual(res.status_code, 302)\n self.check_finished_order(cs_data['reference_number'], product.id)\n\n # Adding a product here should go to basket2, not basket1\n res = self.do_add_to_basket(product.id)\n self.assertEqual(res.status_code, 200)\n basket3 = res.data['id']\n self.assertEqual(basket2, basket3)\n\n\n def test_pay_for_nothing(self):\n \"\"\"Test attempting to pay for an empty basket\"\"\"\n res = self.do_get_basket()\n self.assertEqual(res.status_code, 200)\n basket_id = res.data['id']\n\n data = {\n \"guest_email\": \"herp@example.com\",\n \"basket\": reverse('basket-detail', args=[basket_id]),\n \"shipping_address\": {\n \"first_name\": \"fadsf\",\n \"last_name\": \"fad\",\n \"line1\": \"234 5th Ave\",\n \"line4\": \"Manhattan\",\n \"postcode\": \"10001\",\n \"state\": \"NY\",\n \"country\": reverse('country-detail', args=['US']),\n \"phone_number\": \"+1 (717) 467-1111\",\n }\n }\n url = reverse('cybersource-sign-auth-request')\n res = self.client.post(url, data, format='json')\n self.assertEqual(res.status_code, 406)\n\n\n def test_manipulate_total_pre_auth(self):\n \"\"\"Test attempting to manipulate basket price when requesting an auth form\"\"\"\n product = self.create_product()\n\n res = self.do_get_basket()\n self.assertEqual(res.status_code, 200)\n basket_id = res.data['id']\n\n res = self.do_add_to_basket(product.id)\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data['total_incl_tax'], '10.00')\n\n url = reverse('cybersource-sign-auth-request')\n data = {\n \"guest_email\": \"herp@example.com\",\n \"basket\": reverse('basket-detail', args=[basket_id]),\n \"total\": \"2.00\", # Try and get $10 of product for only $2\n \"shipping_address\": {\n \"first_name\": \"fadsf\",\n \"last_name\": \"fad\",\n \"line1\": \"234 5th Ave\",\n \"line4\": \"Manhattan\",\n \"postcode\": \"10001\",\n \"state\": \"NY\",\n \"country\": reverse('country-detail', args=['US']),\n \"phone_number\": \"+1 (717) 467-1111\",\n }\n }\n res = self.client.post(url, data, format='json')\n self.assertEqual(res.status_code, 406)\n\n\n def test_manipulate_total_during_auth(self):\n \"\"\"Test attempting to manipulate basket price when requesting auth from CyberSource\"\"\"\n product = self.create_product()\n\n res = self.do_get_basket()\n self.assertEqual(res.status_code, 200)\n basket_id = res.data['id']\n\n res = self.do_add_to_basket(product.id)\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res.data['total_incl_tax'], '10.00')\n\n cs_url, cs_data = self.do_sign_auth_request(basket_id)\n\n cs_data['amount'] = '2.00'\n res = requests.post(cs_url, cs_data)\n self.assertEqual(res.status_code, 403)\n\n\n def test_free_product(self):\n \"\"\"Full checkout process using minimal api calls\"\"\"\n product = self.create_product(price=D('0.00'))\n\n res = self.do_get_basket()\n self.assertEqual(res.status_code, 200)\n basket_id = res.data['id']\n\n res = self.do_add_to_basket(product.id)\n self.assertEqual(res.status_code, 200)\n\n cs_url, cs_data = self.do_sign_auth_request(basket_id)\n\n self.assertEqual(cs_data['amount'], '0.00')\n\n res = self.do_cybersource_post(cs_url, cs_data)\n self.assertEqual(res.status_code, 302)\n self.check_finished_order(cs_data['reference_number'], product.id)\n\n\n\nclass CSReplyViewTest(BaseCheckoutTest):\n \"\"\"Test the CybersourceReplyView with fixtured requests\"\"\"\n\n def prepare_basket(self):\n \"\"\"Setup a basket and session like SignAuthorizePaymentFormView would normally\"\"\"\n product = self.create_product()\n\n res = self.do_get_basket()\n self.assertEqual(res.status_code, 200)\n basket_id = res.data['id']\n\n res = self.do_add_to_basket(product.id)\n self.assertEqual(res.status_code, 200)\n\n session = self.client.session\n session[CHECKOUT_BASKET_ID] = basket_id\n session[CHECKOUT_ORDER_NUM] = str(randrange(1000000, 9999999))\n session[CHECKOUT_SHIPPING_CODE] = 'free-shipping'\n session.save()\n return session, basket_id, session[CHECKOUT_ORDER_NUM]\n\n\n @patch('cybersource.signals.order_placed.send')\n def test_invalid_signature(self, order_placed):\n \"\"\"Invalid signature should result in 400 Bad Request\"\"\"\n session, basket_id, order_number = self.prepare_basket()\n data = cs_factories.build_declined_reply_data(order_number)\n data = cs_factories.sign_reply_data(data)\n\n data['signature'] = 'abcdef'\n\n url = reverse('cybersource-reply')\n resp = self.client.post(url, data)\n self.assertEqual(resp.status_code, 400)\n self.assertEqual(len(mail.outbox), 0, 'Should not send email')\n self.assertEqual(order_placed.call_count, 0, 'Should not trigger signal')\n self.assertEqual(Order.objects.count(), 0, 'Should not make order')\n\n\n @patch('cybersource.signals.order_placed.send')\n def test_invalid_request_type(self, order_placed):\n \"\"\"Bad request type should result in 400 Bad Request\"\"\"\n session, basket_id, order_number = self.prepare_basket()\n data = cs_factories.build_declined_reply_data(order_number)\n\n data[\"req_transaction_type\"] = \"payment\",\n\n data = cs_factories.sign_reply_data(data)\n url = reverse('cybersource-reply')\n resp = self.client.post(url, data)\n self.assertEqual(resp.status_code, 400)\n self.assertEqual(len(mail.outbox), 0, 'Should not send email')\n self.assertEqual(order_placed.call_count, 0, 'Should not trigger signal')\n self.assertEqual(Order.objects.count(), 0, 'Should not make order')\n\n\n @patch('cybersource.signals.order_placed.send')\n def test_duplicate_transaction_id(self, order_placed):\n \"\"\"Duplicate Transaction ID should result in redirect to the success page\"\"\"\n session, basket_id, order_number = self.prepare_basket()\n data = cs_factories.build_accepted_reply_data(order_number)\n data = cs_factories.sign_reply_data(data)\n url = reverse('cybersource-reply')\n self.assertEqual(order_placed.call_count, 0)\n self.assertEqual(Order.objects.count(), 0)\n\n resp = self.client.post(url, data)\n self.assertRedirects(resp, reverse('checkout:thank-you'))\n self.assertEqual(order_placed.call_count, 1)\n self.assertEqual(Order.objects.count(), 1)\n\n resp = self.client.post(url, data)\n self.assertRedirects(resp, reverse('checkout:thank-you'))\n self.assertEqual(order_placed.call_count, 1)\n self.assertEqual(Order.objects.count(), 1)\n\n\n @patch('cybersource.signals.order_placed.send')\n def test_invalid_reference_number(self, order_placed):\n \"\"\"Mismatched reference number should result in 400 Bad Request\"\"\"\n session, basket_id, order_number = self.prepare_basket()\n data = cs_factories.build_accepted_reply_data(order_number + 'ABC')\n data = cs_factories.sign_reply_data(data)\n url = reverse('cybersource-reply')\n resp = self.client.post(url, data)\n self.assertEqual(resp.status_code, 400)\n self.assertEqual(order_placed.call_count, 0)\n self.assertEqual(Order.objects.count(), 0)\n\n\n @patch('cybersource.signals.order_placed.send')\n def test_missing_basket(self, order_placed):\n \"\"\"Missing basket should result in 400 Bad Request\"\"\"\n session, basket_id, order_number = self.prepare_basket()\n del session[CHECKOUT_BASKET_ID]\n session.save()\n data = cs_factories.build_accepted_reply_data(order_number)\n data = cs_factories.sign_reply_data(data)\n url = reverse('cybersource-reply')\n resp = self.client.post(url, data)\n self.assertEqual(resp.status_code, 400)\n self.assertEqual(order_placed.call_count, 0)\n self.assertEqual(Order.objects.count(), 0)\n\n\n @patch('cybersource.signals.order_placed.send')\n def test_declined_card(self, order_placed):\n \"\"\"Declined card should should result in redirect to failure page\"\"\"\n session, basket_id, order_number = self.prepare_basket()\n data = cs_factories.build_declined_reply_data(order_number)\n data = cs_factories.sign_reply_data(data)\n url = reverse('cybersource-reply')\n\n resp = self.client.post(url, data)\n self.assertRedirects(resp, reverse('checkout:index'), fetch_redirect_response=False)\n\n self.assertEqual(len(mail.outbox), 0, 'Should not send email')\n self.assertEqual(order_placed.call_count, 0, 'Should not trigger signal')\n self.assertEqual(Order.objects.count(), 0, 'Should not make order')\n\n\n @patch('cybersource.signals.order_placed.send')\n def test_success(self, order_placed):\n \"\"\"Successful authorization should create an order and redirect to the success page\"\"\"\n session, basket_id, order_number = self.prepare_basket()\n data = cs_factories.build_accepted_reply_data(order_number)\n data = cs_factories.sign_reply_data(data)\n url = reverse('cybersource-reply')\n self.assertEqual(order_placed.call_count, 0)\n resp = self.client.post(url, data)\n\n self.assertRedirects(resp, reverse('checkout:thank-you'))\n\n self.assertEqual(len(mail.outbox), 1, 'Should send email')\n self.assertEqual(order_placed.call_count, 1, 'Should trigger order_placed signal')\n\n order = order_placed.call_args[1]['order']\n self.assertEqual(order.status, 'Authorized', 'Should set order status')\n self.assertEqual(order.basket.id, basket_id, 'Should use basket from session')\n self.assertEqual(order.number, order_number, 'Should use order number from CS request')\n\n session = self.client.session\n self.assertEquals(session[CHECKOUT_ORDER_ID], order.id, 'Should save order_id in session')\n\n self.assertEqual(order.sources.count(), 1, 'Should save pPaymentSource')\n source = order.sources.first()\n self.assertEqual(source.currency, 'USD')\n self.assertEqual(source.amount_allocated, D('99.99'))\n self.assertEqual(source.amount_refunded, D('0.00'))\n self.assertEqual(source.amount_debited, D('0.00'))\n\n self.assertEqual(source.transactions.count(), 1, 'Should save Transaction')\n transaction = source.transactions.first()\n self.assertEqual(transaction.log.data, data)\n self.assertEqual(transaction.token.log, transaction.log)\n self.assertEqual(transaction.token.masked_card_number, 'xxxxxxxxxxxx1111')\n self.assertEqual(transaction.token.card_type, '001')\n self.assertEqual(transaction.txn_type, 'Authorise')\n self.assertEqual(transaction.amount, D('99.99'))\n self.assertEqual(transaction.reference, data['transaction_id'])\n self.assertEqual(transaction.status, 'ACCEPT')\n self.assertEqual(transaction.request_token, data['request_token'])\n\n self.assertEqual(order.payment_events.count(), 1, 'Should save PaymentEvent')\n event = order.payment_events.first()\n self.assertEqual(event.amount, D('99.99'))\n self.assertEqual(event.reference, data['transaction_id'])\n self.assertEqual(event.event_type.name, 'Authorise')\n\n self.assertEqual(event.line_quantities.count(), 1, 'Should save PaymentEventQuantity')\n lq = event.line_quantities.first()\n self.assertEqual(lq.line, order.lines.first())\n self.assertEqual(lq.quantity, 1)\n\n\n\nclass AuthPaymentFormViewTest(BaseCheckoutTest):\n \"\"\"Test the SignAuthorizePaymentFormView\"\"\"\n\n def prepare_basket(self):\n \"\"\"Setup a basket so that we can pay for it\"\"\"\n product = self.create_product()\n\n res = self.do_get_basket()\n self.assertEqual(res.status_code, 200)\n basket_id = res.data['id']\n\n res = self.do_add_to_basket(product.id)\n self.assertEqual(res.status_code, 200)\n\n return basket_id\n\n\n @patch('cybersource.signals.pre_build_auth_request.send')\n @patch('cybersource.signals.pre_calculate_auth_total.send')\n def test_request_auth_form_success(self, pre_calculate_auth_total, pre_build_auth_request):\n basket_id = self.prepare_basket()\n\n # Add some taxes to the basket\n def add_taxes(sender, basket, shipping_address, **kwargs):\n for line in basket.all_lines():\n line.purchase_info.price.tax = D('0.42')\n pre_calculate_auth_total.side_effect = add_taxes\n\n # Add an extra field into the request\n def add_a_field(sender, extra_fields, request, basket, **kwargs):\n extra_fields['my_custom_field'] = 'ABC'\n pre_build_auth_request.side_effect = add_a_field\n\n # Pregenerate the order number\n session = self.client.session\n session[CHECKOUT_ORDER_NUM] = '10000042'\n session.save()\n\n cs_url, data = self.do_sign_auth_request(basket_id=basket_id)\n\n # CS URL should be correct\n self.assertEqual(cs_url, 'https://testsecureacceptance.cybersource.com/silent/pay')\n\n # Basket ID should be stored in the session\n session = self.client.session\n self.assertEqual(session[CHECKOUT_BASKET_ID], basket_id)\n\n # Basket must be frozen\n basket = Basket.objects.get(id=basket_id)\n self.assertFalse(basket.can_be_edited)\n\n # Make sure each signal got called\n self.assertEqual(pre_calculate_auth_total.call_count, 1)\n self.assertEqual(pre_build_auth_request.call_count, 1)\n\n # Check response fields\n self.assertEquals(data['amount'], '10.42')\n self.assertEquals(data['bill_to_address_city'], 'Manhattan')\n self.assertEquals(data['bill_to_address_country'], 'US')\n self.assertEquals(data['bill_to_address_line1'], '234 5th Ave')\n self.assertEquals(data['bill_to_address_line2'], 'apt 5')\n self.assertEquals(data['bill_to_address_postal_code'], '10001')\n self.assertEquals(data['bill_to_address_state'], 'NY')\n self.assertEquals(data['bill_to_email'], 'herp@example.com')\n self.assertEquals(data['bill_to_forename'], 'Testy')\n self.assertEquals(data['bill_to_phone'], '17174671111')\n self.assertEquals(data['bill_to_surname'], 'McUnitTest')\n self.assertEquals(data['card_cvn'], '123')\n self.assertEquals(data['card_expiry_date'], '12-2017')\n self.assertEquals(data['card_number'], '4111111111111111')\n self.assertEquals(data['card_type'], '001')\n self.assertEquals(data['currency'], 'USD')\n self.assertEquals(data['customer_ip_address'], '127.0.0.1')\n self.assertEquals(data['device_fingerprint_id'], '')\n self.assertEquals(data['item_0_name'], 'My Product')\n self.assertEquals(data['item_0_quantity'], '1')\n self.assertEquals(data['item_0_sku'], basket.all_lines()[0].stockrecord.partner_sku)\n self.assertEquals(data['item_0_unit_price'], '10.42')\n self.assertEquals(data['line_item_count'], '1')\n self.assertEquals(data['locale'], 'en')\n self.assertEquals(data['my_custom_field'], 'ABC')\n self.assertEquals(data['payment_method'], 'card')\n self.assertEquals(data['reference_number'], '10000042')\n self.assertEquals(data['ship_to_address_city'], 'Manhattan')\n self.assertEquals(data['ship_to_address_country'], 'US')\n self.assertEquals(data['ship_to_address_line1'], '234 5th Ave')\n self.assertEquals(data['ship_to_address_line2'], '')\n self.assertEquals(data['ship_to_address_postal_code'], '10001')\n self.assertEquals(data['ship_to_address_state'], 'NY')\n self.assertEquals(data['ship_to_forename'], 'fadsf')\n self.assertEquals(data['ship_to_phone'], '17174671111')\n self.assertEquals(data['ship_to_surname'], 'fad')\n self.assertEquals(data['transaction_type'], 'authorization,create_payment_token')\n","sub_path":"sandbox/tests/test_checkout.py","file_name":"test_checkout.py","file_ext":"py","file_size_in_byte":23188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"152039039","text":"from django.db import models\nfrom account.models import User\nclass Question(models.Model):\n user=models.ForeignKey(User,on_delete=models.DO_NOTHING)\n question_type=models.CharField(max_length=50)\n question_text=models.CharField(max_length=200)\n question_date=models.DateTimeField(auto_now_add=True)\n question_img=models.ImageField(upload_to='question_img',null=True)\n reward_integral = models.IntegerField(default=0)\nclass Like_record(models.Model):\n from_user=models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name=\"from_user\")\n to_user=models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name=\"to_user\")\n likes=models.IntegerField(default=0)\nclass Comment(models.Model):\n is_read=models.IntegerField(default=0)\n comment_question=models.ForeignKey(Question,on_delete=models.DO_NOTHING,null=True)\n comment_type=models.IntegerField(default=0)\n comment_user=models.ForeignKey(User,related_name=\"comment\",on_delete=models.DO_NOTHING)\n reply_user=models.ForeignKey(User,related_name=\"reply\",on_delete=models.DO_NOTHING)\n comment_text=models.TextField()\n comment_time=models.DateTimeField(auto_now_add=True)\n parent_comment=models.ForeignKey('self',null=True,on_delete=models.DO_NOTHING,related_name=\"parent\")\n root_comment=models.ForeignKey('self',null=True,on_delete=models.DO_NOTHING,related_name=\"root\")\n comment_img=models.ImageField(upload_to='answer_img',null=True)\n class Meta:\n ordering=['comment_time']\nclass History_record(models.Model):\n user=models.ForeignKey(User,on_delete=models.DO_NOTHING)\n viewed_question=models.ForeignKey(Question,on_delete=models.DO_NOTHING)\n view_time=models.DateTimeField(auto_now_add=True)\n class Meta:\n ordering=['-view_time']\nclass Admire_record(models.Model):\n user=models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name='who_admire')\n question=models.ForeignKey(Question,on_delete=models.DO_NOTHING)\n admire_comment=models.ForeignKey(Comment,on_delete=models.DO_NOTHING)\n admire_user=models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name='admire_who')\n admire_time=models.DateTimeField(auto_now_add=True)\n is_admired=models.IntegerField(default=0)\n is_read=models.IntegerField(default=0)\nclass Initial_integral(models.Model):\n user=models.ForeignKey(User,on_delete=models.DO_NOTHING)\n is_aquired=models.IntegerField(default=0)\n# Create your models here.\n","sub_path":"comment/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"278583554","text":"import copy # for using deep copy.\n# initial 2D array at time t=0\narr = [[0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 1], [0, 1, 0, 0, 1],\n [0, 0, 0, 0, 0]]\n\n# this 2D array will keep the updated values\nupdate_arr = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]]\n\nr = len(arr) - 1 # length of row\nc = len(arr[1]) - 1 # length of column\n\n\ndef check_neighbours(x, y, a1, a2, b1, b2):\n value = arr[x][y]\n count_alive = 0\n for k in range(a1, a2):\n for L in range(b1, b2):\n if k != x or L != y:\n if arr[k][L] == 1:\n count_alive = count_alive + 1\n if value == 1:\n if count_alive == 2:\n return 1\n else:\n return 0\n else:\n if count_alive == 2 or count_alive == 3:\n return 1\n else:\n return 0\n\n\nfor t in range(21):\n print(\"time:\", t)\n\n for i in range(len(arr)):\n for j in range(len(arr[i])):\n print(arr[i][j], end=' ')\n print()\n print()\n\n for i in range(len(arr)):\n for j in range(len(arr[i])):\n if i != 0 and i != r and j != 0 and j != c: #this one is for middle part\n update_arr[i][j] = check_neighbours(i, j, i-1, i+2, j-1, j+2)\n\n elif i == 0 and j == 0: # top left corner\n update_arr[i][j] = check_neighbours(i, j, i, i+2, j, j+2)\n\n elif i == r and j == 0: # bottom left corner\n update_arr[i][j] = check_neighbours(i, j, i-1, i+1, j, j+2)\n\n elif j == 0: # left side\n update_arr[i][j] = check_neighbours(i, j, i-1, i+2, j, j+2)\n\n elif i == 0 and j == c: # top right corner\n update_arr[i][j] = check_neighbours(i, j, i, i + 2, j-1, j+1)\n\n elif i == r and j == c: # bottom right corner\n update_arr[i][j] = check_neighbours(i, j, i-1, i, j-1, j+1)\n\n elif j == c: # right side\n update_arr[i][j] = check_neighbours(i, j, i-1, i+2, j-1, j+1)\n\n elif i == 0: # top corner\n update_arr[i][j] = check_neighbours(i, j, i, i+2, j-1, j+2)\n\n elif i == r: # bottom corner\n update_arr[i][j] = check_neighbours(i, j, i-1, i+1, j-1, j+2)\n\n arr = copy.deepcopy(update_arr) # copy the updated array to the main array\n","sub_path":"Lab_6_assignment_even_id/ques1.py","file_name":"ques1.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"185914384","text":"# drugs.py\n# \n# Rob Churchill\n# rjc111@georgetown.edu\n#\n# Automated Reasoning\n# \tMark Maloof\n#\tSpring 2016\n#\n# implements the drug bayes network, and infers D given C\n\nfrom factor import Factor, Variable\nfrom eliminate import eliminate, sum_out\nfrom net import BayesNetwork\n\n# declare all variables in the bn\nd = Variable('d', 2) # alarm goes off\nc = Variable('c', 2) # burglary\n\n# set evidence variable to unhidden and give it a value\nc.hidden = False\nc.value = 1\nevidence = [c]\n\n# set query variable to be unhidden\nd.hidden = False\n\nf_d = Factor('d', [d])\nf_d.phi = [0.9, 0.1]\n\nf_c = Factor('c', [c, d])\nf_c.phi = [0.5, 0.5, 0.25, 0.75]\n\nbn = BayesNetwork([d,c], [f_c, f_d])\n\neliminate(d, evidence, bn)","sub_path":"mark/bayes/drugs.py","file_name":"drugs.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"453730991","text":"#!/usr/bin/env python3\n\n# Python Stream Deck Library\n# Released under the MIT license\n#\n# dean [at] fourwalledcubicle [dot] com\n# www.fourwalledcubicle.com\n#\n\nimport StreamDeck.StreamDeck as StreamDeck\nimport threading\nfrom PIL import Image, ImageDraw, ImageFont\n\n\n# Generates a custom tile with run-time generated text and custom image via the\n# PIL module.\ndef render_key_image(width, height, rgb_order, icon_filename, label_text):\n # Create new key image of the correct dimensions, black background\n image = Image.new(\"RGB\", (width, height), 'black')\n\n # Add image overlay, rescaling the image asset if it is too large to fit the\n # requested dimensions via a high quality Lanczos scaling algorithm\n icon = Image.open(icon_filename).convert(\"RGBA\")\n icon.thumbnail((width, height - 20), Image.LANCZOS)\n image.paste(icon, (0, 0), icon)\n\n # Load a custom TrueType font and use it to overlay the key index, draw key\n # number onto the image\n font = ImageFont.truetype(\"Assets/Roboto-Regular.ttf\", 14)\n draw = ImageDraw.Draw(image)\n draw.text((10, height - 20), text=label_text, font=font, fill=(255, 255, 255, 128))\n\n # Get the raw r, g and b components of the generated image (note we need to\n # flip it horizontally to match the format the StreamDeck expects)\n r, g, b = image.transpose(Image.FLIP_LEFT_RIGHT).split()\n\n # Recombine the B, G and R elements in the order the display expects them,\n # and convert the resulting image to a sequence of bytes\n rgb = {\"R\": r, \"G\": g, \"B\": b}\n return Image.merge(\"RGB\", (rgb[rgb_order[0]], rgb[rgb_order[1]], rgb[rgb_order[2]])).tobytes()\n\n\n# Returns styling information for a key based on its position and state.\ndef get_key_style(deck, key, state):\n # Last button in the example application is the exit button\n exit_key_index = deck.key_count() - 1\n\n if key == exit_key_index:\n name = \"exit\"\n icon = \"Assets/Exit.png\"\n text = \"Exit\"\n else:\n name = \"emoji\"\n icon = \"Assets/{}.png\".format(\"Pressed\" if state else \"Released\")\n text = \"Pressed!\" if state else \"Key {}\".format(key)\n\n return {\"name\": name, \"icon\": icon, \"label\": text}\n\n\n# Creates a new key image based on the key index, style and current key state\n# and updates the image on the StreamDeck.\ndef update_key_image(deck, key, state):\n # Get the required key image dimensions\n image_format = deck.key_image_format()\n width = image_format['width']\n height = image_format['height']\n rgb_order = image_format['order']\n\n # Determine what icon and label to use on the generated key\n style = get_key_style(deck, key, state)\n\n # Generate the custom key with the requested image and label\n image = render_key_image(width, height, rgb_order, style[\"icon\"], style[\"label\"])\n\n # Update requested key with the generated image\n deck.set_key_image(key, image)\n\n\n# Prints key state change information, updates rhe key image and performs any\n# associated actions when a key is pressed.\ndef key_change_callback(deck, key, state):\n # Print new key state\n print(\"Deck {} Key {} = {}\".format(deck.id(), key, state), flush=True)\n\n # Update the key image based on the new key state\n update_key_image(deck, key, state)\n\n # Check if the key is changing to the pressed state\n if state:\n key_style_name = get_key_style(deck, key, state)[\"name\"]\n\n # When an exit button is pressed, close the application\n if key_style_name == \"exit\" and state:\n # Reset deck, clearing all button images\n deck.reset()\n\n # Close deck handle, terminating internal worker threads\n deck.close()\n\n\nif __name__ == \"__main__\":\n manager = StreamDeck.DeviceManager()\n decks = manager.enumerate()\n\n print(\"Found {} Stream Decks.\".format(len(decks)), flush=True)\n\n for deck in decks:\n deck.open()\n deck.reset()\n\n deck.set_brightness(30)\n\n # Set initial key images\n for key in range(deck.key_count()):\n update_key_image(deck, key, False)\n\n # Register callback function for when a key state changes\n deck.set_key_callback(key_change_callback)\n\n # Wait until all application threads have terminated (for this example,\n # this is when all deck handles are closed)\n for t in threading.enumerate():\n if t is threading.currentThread():\n continue\n\n if t.is_alive():\n t.join()\n","sub_path":"src/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":4514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"497021871","text":"from tkinter import Checkbutton\n\nfrom ..utils import load_color\n\ndef Checkbox(root, style = \"\", **options):\n\n props = {\n 'activeforeground': load_color(style)['color'],\n 'activebackground': load_color(style)['acColor']\n }\n\n props.update(**options)\n\n C = Checkbutton(\n root\n )\n\n C.config(props)\n\n C.pack()","sub_path":"src/Checkbox/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"380419066","text":"import argparse\nimport delfi.distribution as dd\nimport logging\nimport dill as pickle\nimport numpy as np\nimport os\nimport time\nimport shutil\n\nfrom model.ChannelOmni import ChannelOmni\nfrom model.ChannelOmniStats import ChannelOmniStats as ChannelStats\nfrom delfi.generator import Default, MPGenerator\nfrom delfi.summarystats import Identity\nfrom tqdm import tqdm\n\n\ndef args_parse():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--disable_debug\",\n dest=\"disable_debug\",\n action=\"store_true\",\n help=\"Disable debug mode\",\n )\n parser.add_argument(\n \"--n_samples\",\n type=int,\n default=1000,\n help=\"Number of samples (theta, stats) to generate from the prior.\",\n )\n parser.add_argument(\n \"--name\",\n type=str,\n default=\"default\",\n help=\"Sets the name of the data folder for storage.\",\n )\n parser.add_argument(\n \"--overwrite\",\n dest=\"overwrite\",\n action=\"store_true\",\n help=\"Overwrite files that exist.\",\n )\n parser.add_argument(\n \"--seed\",\n type=int,\n default=0,\n help=\"Seed, if set to zero a seed will be generated randomly.\",\n )\n parser.add_argument(\n \"--verbose\",\n dest=\"verbose\",\n action=\"store_false\",\n help=\"Verbose output, defaults to True.\",\n )\n args = parser.parse_args()\n\n # seed\n if args.seed == 0:\n args.seed = np.random.randint(2 ** 32 - 1)\n\n # directory setup\n args.bp = \"data/{}\".format(args.name)\n if os.path.exists(args.bp) and os.path.isdir(args.bp):\n if args.overwrite:\n shutil.rmtree(args.bp)\n os.makedirs(args.bp)\n else:\n os.makedirs(args.bp)\n\n return args\n\n\ndef prep_log(args):\n logger = logging.getLogger(\"generate.py\")\n logger.setLevel(logging.DEBUG)\n\n # create file handler which logs even debug messages\n fh = logging.FileHandler(\"{}/run.log\".format(args.bp))\n fh.setLevel(logging.DEBUG)\n\n # create console handler with a higher log level\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n\n # create formatter and add it to the handlers\n formatter = logging.Formatter(\n \"%(asctime)s [%(levelname)s]: %(message)s\", \"%m-%d %H:%M:%S\"\n )\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n logger.addHandler(fh)\n logger.addHandler(ch)\n\n return logger\n\n\ndef main(args):\n log = prep_log(args)\n\n log.info(\"Running {}.\".format(args.name))\n if args.verbose:\n log.info(args)\n\n prior_lims = np.array([\n [0, 1],\n [-10., 10.],\n [-120., 120.],\n [0., 2000],\n [0., 0.5],\n [0, 0.05],\n [0., 0.5],\n [0, 0.05]\n ])\n\n if args.verbose:\n log.info('prior')\n log.info(prior_lims)\n\n m = ChannelOmni(third_exp_model=False, seed=args.seed)\n p = dd.Uniform(lower=prior_lims[:,0], upper=prior_lims[:,1])\n s = ChannelStats()\n g = Default(model=m, prior=p, summary=s)\n\n tic = time.time()\n dats = g.gen(args.n_samples)\n toc = time.time()\n log.info('Generation took {}s.'.format(toc-tic))\n\n np.save('{}/theta.npy'.format(args.bp), dats[0])\n np.save('{}/stats.npy'.format(args.bp), dats[1])\n\n\nif __name__ == \"__main__\":\n try:\n args = args_parse()\n main(args)\n except:\n if args.disable_debug:\n pass\n else:\n import traceback, pdb, sys\n\n traceback.print_exc()\n pdb.post_mortem()\n sys.exit(1)\n","sub_path":"4_channelomics/support_files/data_generate.py","file_name":"data_generate.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"379282649","text":"import math\n\ndef math_func1(x, y):\n one = x ** 2\n # one = x * x\n two = y * y\n top = one + two\n\n three = 3 * x\n bottom = three + 5\n result = top / bottom\n return result\n\ndef math_func2(a, b, c):\n one = -b\n two = math.sqrt((b**2) - 4 * a * c)\n top = one + two\n\n three = 2 * a\n bottom = three\n result = top / bottom\n return result\n\ndef math_func_d(x1, y1, x2, y2):\n return math.sqrt(((x1-x2)**2)+((y1-y2)**2))\n\ndef math_func_is_negative (x):\n return x < 0","sub_path":"pycharm-2/lab2_funcs_tests.py","file_name":"lab2_funcs_tests.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"559690933","text":"print(__doc__)\n\n\n# Code source: Gaël Varoquaux\n# License: BSD 3 clause\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn import svm\n\ndata = pd.read_csv('crop_tsc_balanced_imputed_2015.csv', index_col=None, header=None)\nX = data.iloc[:,0:8]\nY = data.iloc[:,9]\n\n\n\n# figure number\nfignum = 1\n\n# fit the model\nfor kernel in ('linear', 'poly', 'rbf'):\n clf = svm.SVC(kernel=kernel, gamma=2)\n clf.fit(X, Y)\n\n # plot the line, the points, and the nearest vectors to the plane\n plt.figure(fignum, figsize=(4, 3))\n plt.clf()\n \n plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80,\n facecolors='none', zorder=10, edgecolors='k')\n print(\"svm created for kernel type %s\"%(kernel))\n print(clf.support_vectors_.shape)\n #plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired,\n # edgecolors='k')\n\n# plt.savefig('SVM-comparison.png')\nprint(\"done\")\n","sub_path":"svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"159802491","text":"# python3\nimport sys\n\n\ndef compute_min_refills(distance, tank, stops):\n stops.append(distance)\n stops.insert(0,0)\n next_tank = tank\n count = 0\n for i in range(0,len(stops)-1):\n current_station, next_station = stops[i], stops[i+1]\n if (next_station - current_station > tank):\n return -1\n else:\n if(next_station>next_tank): \n next_tank = current_station + tank\n count = count + 1 \n return count\n\nif __name__ == '__main__':\n d, m, _, *stops = map(int, sys.stdin.read().split())\n print(compute_min_refills(d, m, stops))\n","sub_path":"Algorithms/car_fueling.py","file_name":"car_fueling.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"648529690","text":" # -*- coding: utf-8 -*-\nfrom __future__ import division\n\nimport json\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\n\nfrom dateutil import parser\nfrom dateutil.relativedelta import relativedelta\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.db import connection\nfrom django.db.models import Sum, Count, Q, F, FloatField\nfrom django.db.models.functions import Coalesce\nfrom django.http.response import HttpResponse\nfrom django.shortcuts import render\nfrom rest_framework import status as http_status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom webapp.apps.customer.assets.utils import AssetsUtil\nfrom webapp.apps.customer.safety.utils import convert_none_or_empty_to_0\n\n\nclass AssetsView(APIView):\n tpl = 'customer/assets/account_assets.html'\n __row_per_page = 20\n\n def get(self, request, *args, **kwargs):\n user = request.user\n data = request.GET\n\n period_type = data.get('period_type')\n flag = data.get('flag')\n flag = 1 if flag != '2' else 2\n ctx = {'flag': flag, 'period_type': period_type}\n\n start_time, end_time = self.get_date_range(period_type)\n\n period_cond = 'period_type={}'.format(period_type) if period_type else ''\n if period_type == 'start-end':\n if start_time:\n period_cond += '&start_date={}'.format(start_time)\n if end_time:\n period_cond += '&end_date={}'.format(end_time)\n if period_cond.startswith('&'):\n period_cond =period_cond[1:]\n ctx['start_date'] = start_time\n ctx['end_date'] = end_time\n ctx['period_cond'] = period_cond\n # ctx = {'flag': flag, 'period_type': period_type, 'start_date': start_time, 'end_date': end_time, 'period_cond': period_cond}\n\n try:\n page_idx = data.get('page')\n if not page_idx:\n page_idx = 1\n else:\n page_idx = int(page_idx)\n except ValueError:\n return Response(status=http_status.HTTP_400_BAD_REQUEST)\n\n is_verified = True if hasattr(user, 'userprofile') and user.userprofile.audit_status else False\n\n ctx['user'] = {'is_verified': is_verified, 'name': user.username, 'fund_acc_id': user.userprofile.uid}\n\n if end_time and period_type == 'start-end':\n end_time = (parser.parse(end_time) + timedelta(days=1)).strftime('%Y-%m-%d')\n\n ctx['frame_id'] = 'assets'\n\n return render(request,self.tpl, ctx)\n\n def get_date_range(self, period_type):\n start_time, end_time = None, None\n if period_type == 'start-end':\n start_time, end_time = self.request.GET.get('start_date'), self.request.GET.get('end_date')\n\n elif period_type == '1_month':\n start_time, end_time = datetime.today() - relativedelta(months=1), datetime.today()\n elif period_type == '3_month':\n start_time, end_time = datetime.today() - relativedelta(months=3), datetime.today()\n elif period_type == '1_year':\n start_time, end_time = datetime.today() - relativedelta(years=1), datetime.today()\n return start_time, end_time\n\n\n@login_required\ndef get_user_income(request):\n user = request.user\n result = {}\n \n try :\n #=======================================================================\n # #昨日收益\n # today = datetime.today().date()\n # yesterday = today - timedelta(days=1)\n # yesterday_icome = UserAssetDailyReport.objects.filter(target_date=yesterday, user=user).values('income')\n # if yesterday_icome :\n # yesterday_icome = str(yesterday_icome[0]['income'])\n # else :\n # yesterday_icome = \"0.0\"\n # #累计收益\n # total_icome = UserAssetDailyReport.objects.filter(user=user).aggregate(Sum('income')).values()\n # if total_icome :\n # total_icome = str(total_icome[0])\n # else :\n # total_icome = \"0.0\"\n #=======================================================================\n #昨日收益\n yesterday_icome = AssetsUtil.get_profit(user.id)[1]\n if yesterday_icome:\n yesterday_icome = yesterday_icome\n else :\n yesterday_icome =0.00\n #累计收益\n total_icome = AssetsUtil.get_profit(user.id)[0]\n if total_icome :\n total_icome = total_icome\n else:\n total_icome = 0.00\n \n except :\n pass\n \n result = {'yesterday_icome':yesterday_icome,\n 'total_icome' :total_icome,\n }\n \n return HttpResponse(json.dumps(result),content_type=\"application/json\")","sub_path":"webapp/apps/customer/assets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"454769752","text":"#Made by BcMaster12\n\nfrom wand.image import Image\nimport random\nimport glob\n\nBGpath = 'Sources/ClassicMemes/Backgrounds/'\nFGpath = 'Sources/ClassicMemes/Foregrounds/'\n\n#Top text list\nTTran=[\n#\"Eating spicy goodness\",\n\"OMG!\",\n\"*sniff* *sniff*\",\n\"Dear Liberals\",\n\"*breaths in...*\",\n\"TOP TEXT\",\n\"*notices bulge*\",\n\"Number 15...\",\n\"Sample Text\",\n\"MFW WHEN\",\n\"BREAKING NEWS!\",\n\"Hello i'm a mac...\",\n\"i'm not gonna lie\",\n\"*burp*\",\n\"Uh oh!\"\n]\nTText = random.choice(TTran)\n#TTsize = len(TText)\n#print(TTsize)\nprint(\"Top Text Chosen: \" + TText)\n\n#Bottom text list\nBTran=[\n\"LIKE A BOSS\",\n\"*dies inside*\",\n#\"Mommy find's the poop sock\",\n\"BOTTOM TEXT\",\n\"Sample Text\",\n#\"BUT THAT'S JUST A THEORY!\",\n\"I farted in class...\",\n\"*burns building on fire*\",\n\"OWO what's this?\",\n#\"i'm gay!\",\n#\"This is pretty gay.\",\n\"and this is my fetish\",\n\"THIS IS SO EPIC!\",\n\"WEED EATER!\",\n\"i'm a robot.\",\n\"oh wait...\"\n]\nBText = random.choice(BTran)\n#BTsize = len(BText)\n#print(BTsize)\nprint(\"Bottom Text Chosen: \" + BText)\n\n#Background image Scan\nFIscan=[f for f in glob.glob(BGpath + \"**\" , recursive=True)]\n\nBchoice = random.choice(FIscan)\nprint(\"Background Chosen: \" + Bchoice)\n\n#Foreground image Scan\nFIscan=[f for f in glob.glob(FGpath + \"**\", recursive=True)]\n\nFchoice = random.choice(FIscan)\nprint(\"Foreground Chosen: \" + Fchoice)\n\n\n#Assign the image files to the meme\nBGimg = Image(filename=(Bchoice))\nFGimg = Image(filename=(Fchoice))\n","sub_path":"meme0assets.py","file_name":"meme0assets.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"27954163","text":"from django.test import TestCase\r\nfrom ourapp.models import Game, Category, Thread, Comment, Page, UserProfile\r\nfrom django.core.urlresolvers import reverse\r\n\r\ndef add_cat(name):\r\n c = Category.objects.get_or_create(name=name)[0]\r\n return c\r\n\r\ndef add_game(cat,gameID,name, views=0, server=\"World\", platform= \"PC\"):\r\n g = Game.objects.get_or_create(category=cat,gameID=gameID, name=name, server=server, platform=platform)[0]\r\n g.views=views\r\n g.save()\r\n return g\r\n \r\ndef add_thread(game, title, body):\r\n t = Thread.objects.get_or_create(game=game,title=title, body=body)[0]\r\n return t\r\n \r\ndef add_comment(thread, title):\r\n comment = Comment.objects.get_or_create(thread=thread,title=title)[0]\r\n return comment\r\n \r\n \r\nclass CategoryMethodTests(TestCase):\r\n\r\n def test_slug_line_creation(self):\r\n cat = add_cat('Random Category String')\r\n cat.save()\r\n self.assertEqual(cat.slug, 'random-category-string')\r\n\r\nclass GameMethodTests(TestCase):\r\n\r\n def test_slug_line_creation(self):\r\n cat = add_cat('Random Category String')\r\n cat.save()\r\n game = add_game(cat, 1, \"LoL\")\r\n game.save()\r\n self.assertEqual(game.slug, '1')\r\n\r\nclass ThreadMethodTests(TestCase):\r\n\r\n def test_slug_line_creation(self):\r\n cat = add_cat('Random Category String')\r\n cat.save()\r\n game = add_game(cat, 1, \"LoL\")\r\n game.save()\r\n thread = add_thread(game, \"new thread\", \"thread body\")\r\n self.assertEqual(thread.slug, 'new-thread')\r\n\r\nclass ViewTests(TestCase):\r\n\r\n def test_main_page(self):\r\n # create 3 categories\r\n cat1 = add_cat('category 1')\r\n cat1.views = 5\r\n cat1.save()\r\n cat2 = add_cat('category 2')\r\n cat2.views = 10\r\n cat2.save()\r\n cat3 = add_cat('category 3')\r\n cat3.views = 2\r\n cat3.save()\r\n\r\n # create 2 games\r\n game1 = add_game(cat1, 1, \"LoL\")\r\n game1.views = 100\r\n game2 = add_game(cat1, 2, \"DotA\")\r\n game2.views = 7242\r\n game1.save()\r\n game2.save()\r\n \r\n # get main page\r\n response = self.client.get('/gamecrew/')\r\n\r\n categories = response.context['categories']\r\n self.assertEqual(len(categories), 3)\r\n\r\n # check that categories are sorted by views\r\n self.assertEqual(categories[0], cat2)\r\n self.assertEqual(categories[1], cat1)\r\n self.assertEqual(categories[2], cat3)\r\n\r\n games = response.context['games']\r\n self.assertEqual(len(games), 2)\r\n\r\n # check that games are sorted by views\r\n self.assertEqual(games[0], game2)\r\n self.assertEqual(games[1], game1)\r\n\r\n def test_category(self):\r\n cat = add_cat('category 1')\r\n cat2 = add_cat('category 2')\r\n\r\n game1 = add_game(cat, 1, \"LoL\")\r\n game1.views = 10\r\n game2 = add_game(cat2, 2, \"DotA\")\r\n game3 = add_game(cat, 3, \"CoD\")\r\n game3.views = 11\r\n game1.save()\r\n game3.save()\r\n\r\n response = self.client.get('/gamecrew/category/category-1/')\r\n self.assertEqual(response.context['category'], cat)\r\n self.assertEqual(response.context['category_name'], 'category 1')\r\n\r\n category_games = response.context['all_games']\r\n self.assertEquals(len(category_games), 2)\r\n\r\n def test_game(self):\r\n cat = add_cat('category')\r\n game1 = add_game(cat, 1, \"LoL\")\r\n game2 = add_game(cat, 2, \"DotA\")\r\n\r\n thread1 = add_thread(game1, \"thread1\", \"text\")\r\n thread2 = add_thread(game2, \"thread2\", \"text\")\r\n thread3 = add_thread(game1, \"thread3\", \"text\")\r\n \r\n response = self.client.get('/gamecrew/category/category/1/')\r\n threads = response.context['threads']\r\n self.assertEquals(len(threads), 2)\r\n \r\n","sub_path":"Gamecrew_ColorScheme/ourapp/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"71266550","text":"import bpy\nfrom mathutils import Vector\n\n\ndef get_face_pixel_step(context, face):\n \"\"\"\n Finds the UV space amount for one pixel of a face, if it is textured\n :param context:\n :param face:\n :return: Vector of the pixel translation, None if face is not textured\n \"\"\"\n # Try to get the material being applied to the face\n slot_len = len(context.object.material_slots)\n if face.material_index < 0 or face.material_index >= slot_len:\n return None\n material = context.object.material_slots[face.material_index].material\n if material is None:\n return None\n # Try to get the texture the material is using\n target_img = None\n for texture_slot in material.texture_slots:\n if texture_slot is None:\n continue\n if texture_slot.texture is None:\n continue\n if texture_slot.texture.type == 'NONE':\n continue\n if texture_slot.texture.image is None:\n continue\n if texture_slot.texture.type == 'IMAGE':\n target_img = texture_slot.texture.image\n break\n if target_img is None:\n return None\n # With the texture in hand, save the UV step for one pixel movement\n pixel_step = Vector((1 / target_img.size[0], 1 / target_img.size[1]))\n return pixel_step\n","sub_path":"BRM_Utils.py","file_name":"BRM_Utils.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"502406547","text":"arr = [5, 12, 12, 8, 9, 17, 25, 13, 25, 1, 1]\n\nlarge = min(arr[0],arr[1])\nlargest = max(arr[0], arr[1])\n\nfor x in arr:\n if x > large:\n if x > largest:\n large = largest\n largest = x\n elif x < largest:\n large = x\n\nprint(large)","sub_path":"Array/2_secondLargest.py","file_name":"2_secondLargest.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608376602","text":"def classifica_lista(lista):\n lista_crescente = sorted(lista, key=int)\n lista_decrescente = sorted(lista, key = int, reverse = True)\n if len(lista) < 2:\n return 'nenhum'\n elif lista == lista_crescente:\n return 'crescente'\n elif lista == lista_decrescente:\n return 'decrescente'\n else:\n return 'nenhum'","sub_path":"backup/user_018/ch151_2020_04_13_20_30_07_740575.py","file_name":"ch151_2020_04_13_20_30_07_740575.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"356559530","text":"from .settings import *\n\nDEBUG=True\n\nBLACKLIST = ['debug_toolbar', 'django_extensions']\nINSTALLED_APPS = tuple([app for app in INSTALLED_APPS if app not in BLACKLIST])\n\nimport dj_database_url\nDATABASES['default'] = dj_database_url.config()\n\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\nALLOWED_HOSTS = ['*']\n\nimport os\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n# STATIC_ROOT = 'staticfiles'\n# STATIC_URL = '/static/'\n\n\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.9/howto/static-files/\n# STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')\n# STATIC_URL = '/static/'\n#\n# # Extra places for collectstatic to find static files.\n# STATICFILES_DIRS = (\n# os.path.join(PROJECT_ROOT, 'static'),\n# )\n\n\n# STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')\n# STATIC_URL = '/static/'\n#\n# # Extra places for collectstatic to find static files.\n# # STATICFILES_DIRS = (\n# # os.path.join(PROJECT_ROOT, 'static'),\n# # )\n#\n# # Simplified static file serving.\n# # https://warehouse.python.org/project/whitenoise/\n# STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'\n\nSTATIC_ROOT = 'staticfiles'\nSTATIC_URL = '/static/'\n","sub_path":"freelance_app/heroku-settings.py","file_name":"heroku-settings.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"136326164","text":"import RPi.GPIO as GPIO\nimport time\n\n#TRIG = 23 # black for rh sensor\n#ECHO = 24 # white for rh sensor\n\n#TRIG = 14\n#ECHO = 15\n\nSCAN_SERVO = 2\nSTEP_TIME = 0.00\nSTEP_INCREMENT = 10\nHOME_HEADING = 65\nACTIVE_HEADING = 30\n\n\nSCAN_R_TO_L = 1\nSCAN_L_TO_R = 2\n\nclass Measurer(object):\n\n def __init__ (self, pp, trigger_pin, echo_pin):\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(trigger_pin,GPIO.OUT)\n GPIO.setup(echo_pin,GPIO.IN)\n self.__last_scan_direction = SCAN_R_TO_L\n self.__pivotpi = pp\n self.__trigger_pin = trigger_pin\n self.__echo_pin = echo_pin\n\n def goto_home_position(self):\n self.__pivotpi.angle(SCAN_SERVO, HOME_HEADING)\n\n def goto_active_position(self):\n self.__pivotpi.angle(SCAN_SERVO, HOME_HEADING)\n\n def measure_cm(self):\n GPIO.output(self.__trigger_pin, False)\n time.sleep(0.1)\n GPIO.output(self.__trigger_pin, True)\n time.sleep(0.00001)\n GPIO.output(self.__trigger_pin, False)\n\n try:\n\n while GPIO.input(self.__echo_pin) == 0:\n pulse_start = time.time()\n\n while GPIO.input(self.__echo_pin) == 1:\n pulse_end = time.time()\n\n pulse_duration = pulse_end - pulse_start\n distance = pulse_duration * 17150\n pulse_duration = None\n distance = round(distance, 2)\n except Exception as ex:\n print('Measurer::measure_cm Exception: ', ex)\n distance = 50000\n\n return distance\n\n def heading_to_target(self):\n heading_to_target = None\n closest_distance = 50000\n\n if self.__last_scan_direction == SCAN_L_TO_R:\n scan_range = range(120, 10, 0-STEP_INCREMENT)\n self.__last_scan_direction = SCAN_R_TO_L\n else:\n scan_range = range(20, 120, STEP_INCREMENT)\n self.__last_scan_direction = SCAN_L_TO_R\n\n for theta in scan_range:\n time.sleep(STEP_TIME)\n self.__pivotpi.angle(SCAN_SERVO, theta)\n distance = self.measure_cm()\n if distance < closest_distance:\n closest_distance = distance\n heading_to_target = theta\n return (heading_to_target, closest_distance)\n\n\n","sub_path":"measurer.py","file_name":"measurer.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"429378948","text":"# Matthew Holman 5-12-2020\n# Agent Communication\n#\n# Final Metrics Plotter\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Labels\nxLabel = \"Relative Rankings\"\nyLabel = \"Averaged #'s of Rankings Over All Tests\"\nsaveTitle = \"Final_Metrics-Mean_Non_Productive_Time\"\ngraphTitle = \"Mean Non-Productive Time\"\n\n# Read in data\ndata_csv = pd.read_csv(\"Mean_Non_Productive_Time_Comparison.csv\", index_col=\"Strategy\")\ndataT = data_csv.transpose()\n\n# Create subplot\nfmfig, fm = plt.subplots() # Random Crystals, Random Start\n\n# Plot data\nindex = np.arange(4)\nbar_width = 0.15\nfm.bar(index, dataT[\"Communication\"], bar_width, color=\"blue\", label=\"Communication\")\nfm.bar(index+bar_width, dataT[\"Non-Communication\"], bar_width, color=\"green\", label=\"Non-Communication\")\nfm.bar(index+bar_width*2, dataT[\"Brute Force Detecting\"], bar_width, color=\"orange\", label=\"Brute Force Detecting\")\nfm.bar(index+bar_width*3, dataT[\"Brute Force Non-Detecting\"], bar_width, color=\"red\", label=\"Brute Force Non-Detecting\")\n\n# Change plot size\nbox = fm.get_position()\nfm.set_position([box.x0, box.y0 + box.height * 0.2, box.width, box.height * 0.8])\nplt.ylim([0, 11])\nplt.yticks(np.arange(0, 12, step=1))\n\n# Place the legend\nfm.legend(loc='upper center', bbox_to_anchor=(0.5, -0.18), fancybox=True, shadow=True, ncol=2)\n\n# Set the title\nfm.set_title(graphTitle)\n\n# Set the axis labels\nfm.set_xticks(index + bar_width + bar_width / 2)\nfm.set_xticklabels([\"# Best\", \"# 2nd\", \"# 3rd\", \"# Worst\"])\nfm.set_xlabel(xLabel)\nfm.set_ylabel(yLabel)\n\n# Show the graph\n#plt.show()\n\n# Save the graph\nfmfig.savefig(saveTitle + \".png\")","sub_path":"Data/Graphs_And_Collated_Data/mean_non_productive_time/plotFinalMetrics.py","file_name":"plotFinalMetrics.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"189570196","text":"\r\nimport numpy as np\r\nimport cv2 as cv\r\n\r\ndef draw_flow(img, flow, step=16):\r\n h, w = img.shape[:2]\r\n y, x = np.mgrid[step / 2:h:step, step / 2:w:step].reshape(2, -1).astype(int)\r\n fx, fy = flow[y, x].T\r\n lines = np.vstack([x, y, x + fx, y + fy]).T.reshape(-1, 2, 2)\r\n lines = np.int32(lines + 0.5)\r\n vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)\r\n cv.polylines(vis, lines, 0, (0, 255, 0))\r\n for (x1, y1), (x2, y2) in lines:\r\n cv.circle(vis, (x1, y1), 1, (0, 255, 0), -1)\r\n return vis\r\n\r\ndef warp_flow(img, flow):\r\n h, w = flow.shape[:2]\r\n #flow = -flow\r\n flow[:, :, 0] += np.arange(w)\r\n flow[:, :, 1] += np.arange(h)[:, np.newaxis]\r\n res = cv.remap(img, flow, None, cv.INTER_LINEAR)\r\n return res\r\n\r\ndef run_opical_flow():\r\n #이미지 불러오기\r\n prev_img = cv.imread(\"prev.tiff\", cv.IMREAD_ANYDEPTH)\r\n next_img = cv.imread(\"next.tiff\", cv.IMREAD_ANYDEPTH)\r\n # assert (prev_img != None and next_img != None)\r\n\r\n #테스트를 위한 x로 10 이동한 이미지 생성\r\n # h, w = prev_img.shape[:2]\r\n # M = np.float_([[1, 0, 10], [0, 1, 0]])\r\n # test_next_img = cv.warpAffine(prev_img, M, (w, h))\r\n # cv.imshow(\"img\", test_next_img)\r\n\r\n # optical flow 계산\r\n win_size = 5\r\n iteration = 5\r\n flow = cv.calcOpticalFlowFarneback(prev_img, next_img, None, 0.5, 3, win_size, iteration, 5, 1.2, 0)\r\n\r\n #���로우 그리기\r\n # vis = draw_flow(prev_img, flow, 15)\r\n cv.imshow(\"prev_img\", prev_img)\r\n cv.imshow(\"next_img\", next_img)\r\n\r\n # calculated_prev_img 계산\r\n interpolation = True\r\n calculated_prev_img = np.zeros_like(next_img)\r\n if interpolation == True:\r\n calculated_prev_img = warp_flow(next_img, flow)\r\n else:\r\n calculated_prev_img = calculated_prev_img + 0.5\r\n for xx in range(next_img.shape[1]):\r\n for yy in range(next_img.shape[0]):\r\n flowed_xx = int(xx - flow[yy, xx, 0])\r\n flowed_yy = int(yy - flow[yy, xx, 1])\r\n # next이미지의 픽셀값을 calculated prev 이미지에다가 넣음(중복된 픽셀이동에 걍 겹처버림)\r\n if 0 < flowed_xx < next_img.shape[1] and 0 < flowed_yy < next_img.shape[0]:\r\n calculated_prev_img[flowed_yy, flowed_xx] = next_img[yy, xx]\r\n\r\n #결과 display\r\n cv.imshow(\"cal_prev_img\", calculated_prev_img)\r\n cv.imwrite(\"cal_prev_img.tiff\", calculated_prev_img)\r\n cv.waitKey(0)\r\n\r\n #save\r\n cv.imwrite(\"result_img.tiff\", calculated_prev_img)\r\n \r\n\r\n\r\n\r\n# #op.run_opical_flow()\r\n\r\n# img_prev = cv.imread(\"prev.tiff\", cv.IMREAD_ANYDEPTH)\r\n# img_next = cv.imread(\"next.tiff\", cv.IMREAD_ANYDEPTH)\r\n\r\n# map_x = cv.imread(\"displacement_x.tif\", cv.IMREAD_ANYDEPTH)\r\n# map_y = cv.imread(\"displacement_y.tif\", cv.IMREAD_ANYDEPTH)\r\n\r\n# for i in range(map_x.shape[1]):\r\n# map_x[:, i] += i\r\n\r\n# for j in range(map_y.shape[0]):\r\n# map_y[j, :] += j\r\n\r\n# cv.imshow(\"prev img\", img_prev)\r\n# cv.imshow(\"next img\", img_next)\r\n\r\n# img_result = cv.remap(img_next, map_x, map_y, cv.INTER_LINEAR)\r\n# cv.imshow(\"result.tiff\", img_result)\r\n# cv.imwrite(\"result.tiff\", img_result)\r\n\r\n# cv.waitKey(0)\r\n\r\n\r\n# # img_one_partical = cv.imread(\"test_oneParticle.tif\", cv.IMREAD_ANYDEPTH)\r\n# #\r\n# # map_x = np.zeros((img_one_partical.shape[0], img_one_partical.shape[1]), dtype=np.float32)\r\n# # map_y = np.zeros((img_one_partical.shape[0], img_one_partical.shape[1]), dtype=np.float32)\r\n# #\r\n# # for i in range(map_x.shape[1]):\r\n# # map_x[:, i] = i\r\n# # for j in range(map_y.shape[0]):\r\n# # map_y[j, :] = j\r\n# #\r\n# #\r\n# # img_result = cv.remap(img_one_partical, map_x, map_y, cv.INTER_LINEAR)\r\n# #\r\n# # cv.imshow(\"img_one_partical_rs\", img_one_partical)\r\n# # cv.imshow(\"img_one_result_rs\", img_result)\r\n# #\r\n# # cv.imwrite(\"img_result.tiff\", img_result)\r\n# #\r\n# # cv.waitKey(0)","sub_path":"ImgCtrl_optical_flow_test.py","file_name":"ImgCtrl_optical_flow_test.py","file_ext":"py","file_size_in_byte":3852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"210443006","text":"#\n# @lc app=leetcode.cn id=154 lang=python3\n#\n# [154] 寻找旋转排序数组中的最小值 II\n#\n# https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/description/\n#\n# algorithms\n# Hard (48.70%)\n# Likes: 135\n# Dislikes: 0\n# Total Accepted: 27.9K\n# Total Submissions: 57.1K\n# Testcase Example: '[1,3,5]'\n#\n# 假设按照升序排序的数组在预先未知的某个点上进行了旋转。\n# \n# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。\n# \n# 请找出其中最小的元素。\n# \n# 注意数组中可能存在重复的元素。\n# \n# 示例 1:\n# \n# 输入: [1,3,5]\n# 输出: 1\n# \n# 示例 2:\n# \n# 输入: [2,2,2,0,1]\n# 输出: 0\n# \n# 说明:\n# \n# \n# 这道题是 寻找旋转排序数组中的最小值 的延伸题目。\n# 允许重复会影响算法的时间复杂度吗?会如何影响,为什么?\n# \n# \n#\n\n# @lc code=start\nfrom typing import List\n\n\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n l, h = 0, len(nums) - 1\n\n while h > l:\n pivot = l + (h - l) // 2\n if nums[pivot] < nums[h]:\n h = pivot\n elif nums[pivot] > nums[h]:\n l = pivot + 1\n else:\n h -= 1\n\n return nums[l]\n\n# @lc code=end\n","sub_path":"hard/154.寻找旋转排序数组中的最小值-ii.py","file_name":"154.寻找旋转排序数组中的最小值-ii.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"206851771","text":"from rest_framework import serializers\nfrom hentai.models import *\nfrom accounts.models import CustomUser\n\n# Classes needed to use the API\n\nclass TagSerializer(serializers.ModelSerializer):\n class Meta:\n model = VideoTag\n fields = ('id', 'tag_name')\n\nclass VideoSerializer(serializers.ModelSerializer):\n class Meta:\n model = Video\n fields = ('id', 'episode', 'upload_date', 'file_path', 'tags')\n\nclass VideoDetailSerializer(serializers.ModelSerializer):\n tags = TagSerializer(many = True, read_only = True)\n\n class Meta:\n model = Video\n fields = ('id', 'episode', 'upload_date', 'file_path', 'tags')\n\nclass LanguageSerializer(serializers.ModelSerializer):\n class Meta:\n model = Language\n fields = ('id', 'name')\n\nclass DescriptionSerializer(serializers.ModelSerializer):\n language = LanguageSerializer(read_only = True)\n\n class Meta:\n model = Description\n fields = ('title', 'description', 'language')\n\nclass SeriesDetailSerializer(serializers.ModelSerializer):\n videos = VideoSerializer(many = True, read_only = True)\n description = DescriptionSerializer(many = True, read_only = True)\n\n class Meta:\n model = Series\n fields = ('id', 'series_name', 'description', 'videos')\n\nclass SeriesSerializer(serializers.ModelSerializer):\n videos = VideoSerializer(many = True, read_only = True)\n\n class Meta:\n model = Series\n fields = ('id', 'series_name', 'videos')\n\nclass LikesSerializer(serializers.ModelSerializer):\n class Meta:\n model = CustomUser\n fields = ('username', 'email', 'likes')\n\nclass FavouritesSerializer(serializers.ModelSerializer):\n class Meta:\n model = CustomUser\n fields = ('username', 'email', 'favourites')","sub_path":"source/hentai/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"561483709","text":"\n# coding: utf-8\n\n# In[22]:\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom scipy import misc \nfrom scipy import ndimage\nfrom scipy import signal\nimport re \nimport os\nfrom skimage import transform as tf\nimport numpy as np\nimport Image\nimport pickle\nimport sys\nimport generalFunctions as gef\nimport copy as cp\nfrom pandas import DataFrame as dataFrame\nimport pandas as pd\nimport copy as cp\nimport scipy\nfrom analysis_reachExtractionToolbox import reachExtractor2, chansPreprocessor, runReachExtractorFully\n################################################## Key configs\ncurrDirec = os.getcwd()\n\nscriptConfig = {}\nscriptConfig['divScale'] = 10 #####Divide ms score/10 to get the relevant timescale. 10 is for 100Hz, 100 is for 10Hz etc.\n\nscriptConfig['excludeTrials'] = 0 #off for now\n\n\n# In[23]:\n\n\ndataFolder = 'data'\nprojectToProcess = 'proxDist'\nprojectFolder = projectToProcess\n\nloadPath = currDirec + '/' + dataFolder + '/' + projectToProcess + '/'\n#this part will need tweaking\nmouseToProcess = 'MTHL059' #033\nsessionName = 'S091' #994\nfovName = 'F091'\n\n##################################Here we check whether we are indeed in ipython. Essentially a 'cluster' check.\nargvName = sys.argv[0]\nmatchPattern = '/Users/phillipsj10/anaconda/lib/python2.7/site-packages/ipykernel/__main__.py' ##the outline for acceptable files [A-D]{1-4}_\ninPynb = re.match(matchPattern, argvName)\nif (inPynb == None):\n print('We are not in ipython')\n inIpython = 0\nelse:\n inIpython = 1\n get_ipython().magic(u'pylab inline')\n\n######################################################Now we process as required\n\nif (inIpython == 0): ###ie, we were called by the command line.\n loadPath = sys.argv[1]\n #######now need to overwrite the mouseToProcess, project folder etc using regex.\n fileName = gef.fileNamePuller(loadPath)\n mouseDetails = gef.sessionNameReader(fileName)\n mouseToProcess = mouseDetails['mouse']\n sessionName = mouseDetails['session']\n fovName = mouseDetails['fov']\n folderToProcess = mouseToProcess + '_' + sessionName + '_' + fovName\n projectToProcess = sys.argv[2]\n projectFolder = projectToProcess\n loadPath = currDirec + '/' + dataFolder + '/' + projectFolder + '/' + mouseToProcess + '/' + mouseToProcess + '_' + sessionName + '_' + fovName + '/' + 'registeredDirectory/'\n\n\nelse:\n folderToProcess = mouseToProcess + '_' + sessionName + '_' + fovName\n loadPath = currDirec + '/' + dataFolder + '/' + projectFolder + '/' + mouseToProcess + '/' + folderToProcess + '/' + 'registeredDirectory/'\n \n\noutputDirectory = loadPath #Storage site for the registered images.\n\n\n# In[24]:\n\nprint('We are working on mouse ' + mouseToProcess + ' looking at session' + sessionName + ' on fov ' + fovName)\n\n\n# In[ ]:\n\n\n\n\n# In[25]:\n\n##################################################Load data\n\n####Here we load the relevant datafiles:\n###CREATE A REGEX TO LOAD THE PCKL.\n#EXAMPLE PKL NAME: ['ITPT043_F001_dataFile.pkl']\npklSearchName = '[A-Z]{1,4}[0-9]{1,3}_S[0-9]{1,3}_F[0-9]{1,3}_sessionOutput\\.pkl'\npklFiles = os.listdir(loadPath) \npklFiles = [elem for elem in pklFiles if re.search(pklSearchName, elem) != None]\nif (len(pklFiles) != 1):\n ###GIVE ERROR\n #sys.exit(\"Incorrect number of pkl files\")\n \n print('Incorrect pkl number')\n\n \n#code commented out is legacy code that the new pandas has rendered irrelevant.\n#dataFilesPkl = open(loadPath + pklFiles[0], 'rb')\n#sessionData = pickle.load(dataFilesPkl)\n\nsessionDataTemp = pd.read_pickle(loadPath + pklFiles[0])\n#dataFilesPkl.close()\nsessionData = sessionDataTemp['data']\n\n#sessionMeta = sessionDataTemp['meta'] < readd\n\n\n# In[26]:\n\nsessionData2 = cp.deepcopy(sessionData)\n\n\n# In[27]:\n\nreachDataDF,sessionData = runReachExtractorFully(sessionData)\n\n\n# In[28]:\n\n\n\n####Some code pillaged from stackoverflow because I iz a code pirate\ndef movingAverage(a, windowLength) :\n n=windowLength\n ret = np.cumsum(a, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n\n\n\n# In[ ]:\n\n\n\n\n# In[29]:\n\n#reachDataDF = pd.DataFrame(reachData).T\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[30]:\n\n##########ADDITIONAL REACH EXTRACTION WORK:\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[31]:\n\n################################################Now we do trial extraction\n#reaches\n\n\n# In[32]:\n\n\nnumOfTrials = max(sessionData['chanTrialNum']) +1\nnumOfTrials = int(numOfTrials)\n\ntrials= {} #a dict of the relevant trials\n\nfor trialNum in range(numOfTrials): ###get an integer of all the trials\n print('Working on trial number ', str(trialNum))\n trialTemp = {}\n relevantTimepoints = sessionData['chanTrialNum'][sessionData['chanTrialNum'] ==trialNum]\n trialDuration= len(relevantTimepoints)\n \n \n trialTemp['trialDuration'] = trialDuration\n trialTemp['startTime'] = min(relevantTimepoints.index)\n trialTemp['endTime'] = max(relevantTimepoints.index)\n \n if (inIpython==1):\n print('--------Trial duration is ', trialTemp['trialDuration'])\n print('--------Min time is ', trialTemp['startTime'])\n print('--------Max time is ', trialTemp['endTime'])\n trials[trialNum] = trialTemp\n\n\n# In[33]:\n\n#################################################ROI EVENT EXTRACTION\n\n##############################################pulling out events from the roiData.\nfrom scipy.signal import savgol_filter as savgol_filter\ntestOn=0\nif (testOn==1):\n\n roiExample = sessionData['roi6']\n\n roiExample = np.array(roiExample)\n roiExampleBaseCorrect = roiExample - min(roiExample)\n\n\n #ButterFilter\n N=2\n Wn = 0.01 #making this smaller makes it blurrier. 0.01 is good, 0.05 also. Order doesn't seem to change much\n b, a = signal.butter(N, Wn, 'low')\n output_signal = signal.filtfilt(b, a, roiExampleBaseCorrect)\n\n\n roiExampleSmooth = savgol_filter(roiExample, 101,1)\n roiChange = np.diff(output_signal)\n roiChange = np.square(roiChange)\n roiChange = np.sqrt(roiChange)\n\n\n\n stanDevRoi = ((roiExampleSmooth - np.mean(roiExampleSmooth))/np.std(roiExampleSmooth))\n\n ###ISSUE DY AND DX ARE ONE INDEX SHORTER DUE TO THE WAY THE DIFFERENTIAL WORKS. THEREFORE INSERTING 'FAKEVAL' OF ZERO AT THE VERY END.\n roiChangeSmooth = savgol_filter(roiChange, 61,1)\n\n\n stanDevRoi = stanDevRoi\n\n\n ################################################\n\n\n# In[ ]:\n\n\n\n\n# In[34]:\n\nonon=0\nif (onon==1):\n startTime = 0\n endTime= 300000\n plotRange=range(startTime, endTime)\n #plot(roiChangeSmooth[plotRange]*100)\n #plot(roiChange[plotRange]*100)\n plot(roiExampleSmooth[plotRange])\n plot(filteredThresholdCrossings[plotRange])\n #plot(sessionData['chanRewardBinary'][plotRange])\n\n\n\n #plot(stanDevRoi[plotRange])\n\n\n fig = plt.gcf()\n fig.set_size_inches(20,15)\n\n\n\n# In[35]:\n\n#####################################FIND TRIAL TIME DEMARKERS:\n###FIND TIME POINT of first and last relevant point, exclude all values above and below this.\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[36]:\n\n######################################BINARY EVENT TIME EXTRACTIONS\nif (scriptConfig['excludeTrials'] == 1): ###44553311\n earlyTimepoint = (sessionData[sessionData['chanTrialNum']==5].index[0])-2\n latestTimepoint = sessionData[sessionData['chanTrialNum']==(max(sessionData['chanTrialNum']))].index[0]\n#print(earlyTimepoint)\n#print(latestTimepoint)\n\neventsTemp= {}\n\nsessionDataKeys = sessionData.keys()\nbinaryRegex = 'Binary'\nbinaryKeys = [elem for elem in sessionDataKeys if re.search(binaryRegex, elem) != None]\n#####Looop this for the relevant binary values:\nfor binaryKey in range(len(binaryKeys)):\n \n binaryName = binaryKeys[binaryKey]\n indexes = sessionData.loc[sessionData[binaryName] == 1].index\n if (scriptConfig['excludeTrials'] == 1):\n #for indexId in range(len(indexes)):\n indexes = list(indexes)\n \n firstIndex=0\n lastIndex=0 \n del lastIndex\n del firstIndex \n \n foundLast = 0\n foundFirst=0\n for indexTP in range(len(indexes)):\n if (foundFirst==0):\n if (indexes[indexTP]>earlyTimepoint):\n firstIndex=indexTP #we found the first index!\n foundFirst=1\n if (foundLast==0):\n if (indexes[indexTP]>latestTimepoint):\n foundLast=1\n lastIndex = indexTP\n \n \n \n \n\n \n if 'lastIndex' in locals():\n if (binaryName == 'chanTrialStartBinary'):\n lastIndex = lastIndex-(3000/scriptConfig['divScale']) #necessary because gets closer to end\n \n del indexes[lastIndex:]\n \n if 'firstIndex' in locals():\n \n \n del indexes[0:firstIndex]\n\n \n \n \n \n ####find first and last index under these timepoints\n \n eventsTemp[binaryName] = indexes\n \n\n\n#sessionData.ix[e.index]\n\n\n# In[ ]:\n\n\n\n\n# In[38]:\n\nsession = {}\nsession['trials'] = trials\nsession['trials'] = pd.DataFrame(session['trials']).transpose()\nsession['data'] = sessionData\nsession['reaches'] = reachDataDF\n#session['reaches'] = pd.DataFrame(session['reaches']).transpose()\n#session['slowReaches'] = slowReaches\nsession['meta'] = sessionDataTemp['meta']\nsession['events'] = eventsTemp\n\n\n\n# In[39]:\n\n#############CONVERT EVENTS INTO EVENTSDF <<< This should be relatively easy to pull off.\n\n\n# In[40]:\n\n##############################################SIMPLIFYING:\n\nfor roiId in range(len(session['meta']['roiMeta'])):\n del session['meta']['roiMeta'][roiId]['mask']\n\n\n# In[41]:\n\ndef subselectRoiKeys(keys):\n \n \n matchPattern = 'roi'\n roiKeys = [elem for elem in keys if re.search(matchPattern, elem) != None]\n \n \n return roiKeys\ndef subselectSpikesKeys(keys):\n \n \n matchPattern = 'spikes'\n roiKeys = [elem for elem in keys if re.search(matchPattern, elem) != None]\n \n \n return roiKeys\ndef subselectBinaryKeys(keys):\n \n \n matchPattern = 'Binary'\n binaryKeys = [elem for elem in keys if re.search(matchPattern, elem) != None]\n \n \n return binaryKeys\n\n\n\n# In[43]:\n\nsession['data'].keys()\n\n\n# In[42]:\n\n###########################################Here we delete certain files\notherKeys = ['chanCurrFrame','chanCurrVid','chanLickPortPiezo','chanESV','chanEP','chanTranslateEuclidean','chanJoystickX','chanJoystickY','chanEPSmoothForVel']\nroiKeys = subselectRoiKeys(session['data'])\nbinaryKeys = subselectBinaryKeys(session['data'])\nspikesKeys = subselectSpikesKeys(session['data'])\nkeysToKeep = roiKeys+binaryKeys+otherKeys+spikesKeys\n\nsession['data'] = cp.deepcopy(session['data'][keysToKeep])\n\n\n# In[ ]:\n\nsession['data'][binaryKeys] = session['data'][binaryKeys].astype('bool')\n\n\n# In[ ]:\n\ndownConvert=0\nif (downConvert==1):\n for roiId in range(len(roiKeys)):\n #session['data'][roiKeys[roiId]] = session['data'][roiKeys[roiId]]*10000\n session['data'][roiKeys[roiId]] = session['data'][roiKeys[roiId]].astype('int16')\n\n\n# In[ ]:\n\n\npklSaveName = session['meta']['mouseGroup'] + session['meta']['mId'] + '_S' + session['meta']['sId'] + '_F' + session['meta']['fov'] + '_fullExtract.pkl'\n\n#pklSaveName = 'MTHL015_S003_F003_fullExtract.pkl'\nsavePathName = loadPath + pklSaveName\noutput = open(savePathName, 'wb')\npickle.dump(session, output) #newDF\noutput.close()\npklSaveName\n\nprint('Seems to be working fine, saved')\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\ndef reachPlotter(reachData, sessionData, zScoreOfEuclidVelocity, filteredThresholdCrossings, numToPlot):\n \n startTime = reachData[numToPlot]['startTime']\n endTime = reachData[numToPlot]['endTime']\n \n startTime = startTime - 100\n endTime = endTime+200\n \n plotRange=range(startTime, endTime)\n plot(sessionData['chanJoystickX'][plotRange]/np.mean(sessionData['chanJoystickX']))\n plot(sessionData['chanEuclidVelocity'][plotRange]/5)\n #plot(sessionData['chanLickportBinary'][plotRange]*30)\n plot(sessionData['chanRewardBinary'][plotRange]*15)\n #plot(sessionData['chanLickPortPiezo'][plotRange]/700)\n #plot(zScoreOfEuclidVelocity[plotRange])\n #plot(filteredThresholdCrossings[plotRange]*25)\n fig = plt.gcf()\n fig.set_size_inches(20,15)\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n#reachPlotter(reachData,sessionData, zScoreOfEuclidVelocity, filteredThresholdCrossings,23)\n\n","sub_path":"_DISTILL/3_featureExtractor.py","file_name":"3_featureExtractor.py","file_ext":"py","file_size_in_byte":12339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"203070621","text":"from base_filter import BaseFilter\n\nclass SlowFilter(BaseFilter):\n \"\"\" accepts only lines that have a duration that is longer than the specified \n parameter in ms (default 1000).\n \"\"\"\n filterArgs = [\n ('--slow', {'action':'store', 'nargs':'?', 'default':False, 'type':int, 'help':'only output lines with query times longer than SLOW ms (default 1000)'})\n ]\n\n def __init__(self, mlogfilter):\n BaseFilter.__init__(self, mlogfilter)\n \n if 'slow' in self.mlogfilter.args and self.mlogfilter.args['slow'] != False:\n self.active = True\n if self.mlogfilter.args['slow'] == None:\n self.slowms = 1000\n else:\n self.slowms = self.mlogfilter.args['slow']\n\n def accept(self, logevent):\n if logevent.duration != None:\n return logevent.duration >= self.slowms\n return False","sub_path":"mtools/mlogfilter/filters/slow_filter.py","file_name":"slow_filter.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"55703757","text":"from gensim import corpora,models,similarities\nimport jieba\nimport re\nimport os\nimport datetime\nimport numpy as np\nimport SVMDemo\n\n\n\n\nlabel = []\ntrainDataDir = '../lib/'\n#加载分类劳动合同标签库\ndef load_label():\n path = '%s/标签库.txt'%trainDataDir\n with open(path,'r',encoding='utf-8') as f:\n for line in f:\n label.append(np.float32(line.split('\\t')[1][0]))\n return label\n\n#加载分类实习合同标签库\ndef load_label_internships():\n path = '%s/标签库_实习.txt'%trainDataDir\n with open(path, 'r', encoding='utf-8') as f:\n for line in f:\n label.append(float(line.split('\\t')[1][0]))\n return label\n#加载stopword\ndef loadstopword(path):\n stop_word = []\n with open(path,'r',encoding='utf-8') as f:\n for line in f:\n line = line.replace('\\n','')\n stop_word.append(line)\n return stop_word\n\ndef jiebacut(path):\n jieba.load_userdict(r'%s/my_dict.txt'%trainDataDir)\n pattern = re.compile( '[\\ue80b└└┌┐│┬\\\\t\\\\n\\\\s,.<>/?:;\\'\\\"[\\\\]{}()\\\\|~!@#$%^&*\\\\-_=+a-zA-Z,。《》、?:;“”‘’{}【】()…¥!—┄-\\\\d.._─]+')\n with open(path, 'r', encoding='utf-8') as f:\n strline = re.sub(pattern, '', f.read())\n words = jieba.lcut(strline)\n stopword = loadstopword(r'%s/stop_words.txt'%trainDataDir)\n words2 = [word for word in words if word not in stopword]\n return words2\n\nclass ClassifyContract(object):\n def __init__(self,filepath,pathdir):\n self.filepath = filepath\n self.pathdir = pathdir\n self.wordappend = []\n\n#classification等于1:劳动合同分类;2:实习合同分类,默认为1\n\n def classifyBatch(self,classification=1):\n if classification==1:\n label = load_label()\n if classification==2:\n label = load_label_internships()\n dictionary = corpora.Dictionary.load(r'./%s/contract.dict'%trainDataDir)\n lsi = models.LsiModel.load(r'./%s/model.lsi'%trainDataDir)\n L = self.listAll(self.pathdir)\n if len(L)>500:\n L = L[:500]\n batchVec = []\n for l in L:\n word = jiebacut(l)\n vec = dictionary.doc2bow(word)\n word_vec = lsi[vec]\n vec = []\n self.wordappend.append(word_vec)\n for a in word_vec:\n vec.append(a[1])\n batchVec.append(vec)\n return batchVec\n\n def listAll(self, file_dir):\n L = []\n add = 0\n for root, dirs,files in os.walk(file_dir):\n pass\n L = [root+file for file in files]\n return L\n\n\nif __name__=='__main__':\n\n # a = xgboostDemo.xgbpredictBatch(tem)\n\n i = 0\n classification = 1\n path = r'../test_data/测试_劳动合同/'\n allnum = 0\n positive = 0\n label = []\n # starttime = datetime.datetime.now()\n cc = ClassifyContract(None, path)\n tem = np.array(cc.classifyBatch())\n a = SVMDemo.SVM().loadModelPredict(tem)\n for t in a:\n if t == 1:\n positive += 1\n allnum += 1\n print(positive / allnum)\n # endtime = datetime.datetime.now?()\n # print((endtime - starttime).seconds)\n path = r'../test_data/测试_非劳动合同/'\n allnum = 0\n negative = 0\n label = []\n # starttime = datetime.datetime.now()\n c0 = ClassifyContract(None, path)\n tem = np.array(c0.classifyBatch())\n a = SVMDemo.SVM().loadModelPredict(tem)\n for t in a:\n if t == 0:\n negative += 1\n allnum += 1\n print(negative / allnum)\n\n\n\n\n\n","sub_path":"SVM/testSVM.py","file_name":"testSVM.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"545925926","text":"# coding:utf-8\n\nimport socket\n\n\ndef convert_integer():\n \"\"\"\n 网络字节序和本地设备字节序之间转换\n ps 网络是大端子节序 x86架构是小端\n\n ntohl (convert 32-bit integer from network to host)\n ntohs (convert 16-bit integer from network to host)\n htonl (convert 32-bit integer from host to network)\n htons (convert 16-bit integer from host to network)\n :return:\n \"\"\"\n data = 1234\n # 32-bit\n print(\"Original: %s => Long host byte order: %s ,Network byte order: %s\" % (data, socket.ntohl(data), socket.htonl(data)))\n print(\"Original: %s => Short host byte order: %s ,Network byte order: %s\" % (data, socket.ntohs(data), socket.htons(data)))\nif __name__ == '__main__':\n convert_integer()\n","sub_path":"ch1/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"378516408","text":"import numpy as np\nimport cv2\nimport StationMap\nfrom Detector import Detector\nimport HandrailLocator\nfrom CameraController import CameraController\nfrom breezyslam.algorithms import RMHC_SLAM\nfrom breezyslam.sensors import RPLidarA1 as LaserModel\nfrom rplidar import RPLidar as Lidar\nfrom roboviz import MapVisualizer\nimport pybreezyslam\n\n\nclass SlamFactory:\n def build(self, laserModel, map_size_pix, map_size_m, initial_position=(-1, -1)):\n slam = RMHC_SLAM(LaserModel(), self.MAP_SIZE_PIXELS, self.MAP_SIZE_METERS)\n if not initial_position == (-1, -1):\n slam.position = pybreezyslam.Position(initial_position[0] * 10, initial_position[0] * 10, 0)\n return slam\n\n\nclass RobotPosition:\n def __init__(self, plane, robot_pos, robot_dir):\n self.plane = plane\n self.pos = robot_pos\n self.dir = robot_dir\n\n\nclass MapManager:\n\n def __init__(self, station, robot_pos):\n self.station = station\n self.robot_pos = robot_pos\n\n # SLAM\n self.MAP_SIZE_PIXELS = 500\n self.MAP_SIZE_METERS = 10\n self.MIN_SAMPLES = 200\n\n self.lidar = Lidar('/dev/ttyUSB0')\n self.initial_pos_cm = (0, 0)\n self.slam = SlamFactory.build(LaserModel(), self.MAP_SIZE_PIXELS, self.MAP_SIZE_METERS, initial_pos_cm)\n self.mapbytes = bytearray(self.MAP_SIZE_PIXELS * self.MAP_SIZE_PIXELS)\n self.iterator = self.lidar.iter_scans()\n self.previous_distances = None\n self.previous_angles = None\n next(self.iterator)\n\n def assign_id_and_conf_to_handrail_detection(self, robot_to_handrail_vector):\n x, y = self.get_handrail_coordinates(robot_to_handrail_vector)\n print(x, y)\n inv_dist_list = []\n for handrail in self.robot_pos.plane.handrails_on_plane:\n inv_dist_list.append(1 / self.get_distance(x, y, handrail.x, handrail.y))\n norm_confidence = [float(i)/sum(inv_dist_list) for i in inv_dist_list]\n max_confidence = max(norm_confidence)\n id = norm_confidence.index(max_confidence)\n handrail_id = self.robot_pos.plane.handrails_on_plane[id].handrail_id\n ######################################################################################## update handrail location\n return handrail_id, max_confidence\n\n def get_handrail_coordinates(self, distance_in_dir, distance_orth_dir):\n # Find orthogonal vector based on position of handrail in picture\n if distance_orth_dir < 0:\n orthogonal_matrix = np.array([[0, -1], [1, 0]])\n else:\n orthogonal_matrix = np.array([[0, 1], [-1, 0]])\n orthogonal_vector = np.matmul(self.robot_pos.dir, orthogonal_matrix)\n\n # Calculate handrail location in global coordinates\n handrail_location = self.robot_pos.dir * distance_in_dir + orthogonal_vector * distance_orth_dir\n return handrail_location\n\n def get_distance(self, x1, y1, x2, y2):\n dist_squared = pow((x2 - x1), 2) + pow((y2 - y1), 2)\n return pow(dist_squared, 1/2)\n\n def update(self):\n # Extract (quality, angle, distance) triples from current scan\n items = [item for item in next(self.iterator)]\n\n # Extract distances and angles from triples\n distances = [item[2] for item in items]\n angles = [item[1] for item in items]\n\n # Update SLAM with current Lidar scan and scan angles if adequate\n if len(distances) > self.MIN_SAMPLES:\n self.slam.update(distances, scan_angles_degrees=angles)\n previous_distances = distances.copy()\n previous_angles = angles.copy()\n\n # If not adequate, use previous\n elif self.previous_distances is not None:\n self.slam.update(self.previous_distances, scan_angles_degrees=self.previous_angles)\n\n # Get current robot position\n x, y, theta = self.slam.getpos()\n\n self.robot_pos.pos = (x / 10, y / 10) # convert from mm to cm\n # self.robot_pos.dir = theta ####################################################### Convert theta to unit vector\n\n # Get current map bytes as grayscale\n self.slam.getmap(self.mapbytes)\n\n\ndef create_sample_map_manager():\n handrail1 = StationMap.Handrail(1, 0, (100, 100))\n handrail2 = StationMap.Handrail(2, 0, (-100, -100))\n # handrail3 = StationMap.Handrail(3, 0, (-100, 50))\n # handrail4 = StationMap.Handrail(4, 0, (-200, 100))\n floor_plane = StationMap.Plane(1, (300, 300), (-300, -300), (100, 300), [handrail1, handrail2])\n # leftw_plane = StationMap.Plane(2, (0, 300), (-300, 0), (-150, 100), [handrail3, handrail4])\n JEM_node = StationMap.Node(\"JEM\", [floor_plane])\n ISS = StationMap.InternationalSpaceStation([JEM_node])\n\n robot_pos = RobotPosition(floor_plane, (0, 0), (0.707, 0.707))\n\n return MapManager(ISS, robot_pos)\n\n\ndef test_id_assignment_easy():\n map_manager = create_sample_map_manager()\n print(map_manager.assign_id_and_conf_to_handrail_detection((100, 50)))\n\n\ndef test_id_assignment_camera():\n handrail_filter = HandrailLocator.calibrate_from_package_return_handrail_filter()\n map_manager = create_sample_map_manager()\n\n cam = CameraController()\n test_img = cam.get_image()\n vectors = handrail_filter.get_handrail_vectors(test_img)\n for vect in vectors:\n print(map_manager.assign_id_and_conf_to_handrail_detection(vect))\n\n\ndef test_lidar():\n map_manager = create_sample_map_manager()\n while True:\n map_manager.update()\n\n\nif __name__==\"__main__\":\n test_id_assignment_camera()","sub_path":"MapManager.py","file_name":"MapManager.py","file_ext":"py","file_size_in_byte":5549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"611072906","text":"import library as lib\n\ndef run(label_id_list, model_id):\n lines=open('create_hyper_py_source_string.py', 'r').readlines()\n lines=[i.replace(' ', '\\t') for i in lines]\n script=\"\"\n for i in lines:\n script+=i\n label=''\n for i in label_id_list:\n label+=\"'\"+i+\"'\"+','\n label=label[:-1]\n script=script.replace('LABEL_ID_CONCAT_WITH_COMMA_STRING',label, 1)\n label=''\n for i in label_id_list:\n label+=\"\\\\'\"+i+\"\\\\'\"+','\n label=label[:-1]\n script=script.replace('LABEL_ID_CONCAT_WITH_COMMA_STRING_2',label)\n script=script.replace('MODEL_ID',model_id)\n open('hyper_space/'+model_id+'.py', 'w').write(script)\n hyper=lib.subp.Popen('start /wait cmd /c '+'python hyper_space/'+model_id+'.py', shell=True)\n lib.db_operate.optim_progress(model_id, hyper.pid)\n hyper.wait()\n #hyper=subp.Popen('python hyper_space/'+model_id+'.py', shell=False)\n #hyper=subp.Popen('start /wait cmd /c '+'python hyper_space/'+'test3'+'.py', shell=True)\n","sub_path":"PythonServer/create_hyper_py.py","file_name":"create_hyper_py.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"310880621","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# NCTR, Nile Center for Technology Research\n# Copyright (C) 2011-2012 NCTR ().\n#\n##############################################################################\n\nfrom openerp.osv import fields, osv,orm\nfrom openerp.tools.translate import _\nimport decimal_precision as dp\n\n\nclass stock_partial_picking_line(osv.TransientModel):\n\n#FIXME: Depend on stock\n#TODO : add new column (real_qty)\n\n _inherit = \"stock.partial.picking.line\"\n _columns = {\n 'real_qty' : fields.float(\"Real Stock\", digits_compute=dp.get_precision('Product UoM')), \n }\n\nclass stock_partial_picking(osv.osv_memory):\n _inherit = \"stock.partial.picking\"\n\n def _partial_move_for(self, cr, uid, move):\n \"\"\"\n Inherit to add real stock quantity in partial move dict\n @param move: id of picking move\n @return: id\n \"\"\"\n context = {}\n context['uom']=move.product_uom.id\n context['location'] = move.location_id.id\n product = self.pool.get('product.product').browse(cr, uid, move.product_id.id, context=context)\n partial_move= super(stock_partial_picking,self)._partial_move_for(cr, uid, move)\n partial_move.update( {\n 'real_qty': product.qty_available \n })\n return partial_move\n\n def do_partial(self, cr, uid, ids, context=None):\n \"\"\"\n Inherit fuction to add constrains in picking \n @return: super function of stock_partial_move\n \"\"\"\n assert len(ids) == 1, 'Partial picking processing may only be done one at a time'\n uom_obj = self.pool.get('product.uom')\n partial = self.browse(cr, uid, ids[0], context=context)\n picking_type = partial.picking_id.type\n for wizard_line in partial.move_ids:\n line_uom = wizard_line.product_uom\n\n #Adding a check whether any move line contains exceeding real location qty to original moveline\n qty_in_line_uom = uom_obj._compute_qty(cr, uid, line_uom.id, wizard_line.quantity, wizard_line.move_id.product_uom.id)\n\n if qty_in_line_uom > wizard_line.move_id.product_qty:\n raise osv.except_osv(_('Processing Error'), _('Processing quantity for is larger than the available quantity !'))\n \n\n if (picking_type in ['out','internal']) and (qty_in_line_uom > wizard_line.real_qty ):\n raise osv.except_osv(_('Warning'), _('Processing quantity is larger than the available quantity in is location!'))\n \n return super(stock_partial_picking, self).do_partial(cr, uid, ids, context=context)\n\nclass stock_return_picking(osv.osv_memory):\n _name = 'stock.return.picking'\n _inherit = 'stock.return.picking'\n\n def create_returns(self, cr, uid, ids, context=None):\n \"\"\" \n Creates return picking.\n @param self: The object pointer.\n @param cr: A database cursor\n @param uid: ID of the user currently logged in\n @param ids: List of ids selected\n @param context: A standard dictionary\n @return: A dictionary which of fields with values.\n \"\"\"\n move_obj = self.pool.get('stock.move')\n data_obj = self.pool.get('stock.return.picking.memory')\n data = self.read(cr, uid, ids[0], context=context)\n record_id = context and context.get('active_id', False) or False\n val_id = data['product_return_moves']\n for v in val_id:\n data_get = data_obj.browse(cr, uid, v, context=context)\n mov_id = data_get.move_id.id\n if not mov_id:\n raise osv.except_osv(_('Warning !'), _(\"You have manually created product lines, please delete them to proceed\"))\n new_qty = data_get.quantity\n move = move_obj.browse(cr, uid, mov_id, context=context)\n return_history = self.get_return_history(cr, uid, record_id, context) \n qty = move.product_qty - return_history.get(move.id, 0)\n returned_qty = move.product_qty\n if new_qty > qty:\n raise osv.except_osv(_('Warning !'), _(\"The return quantity greater than move quantity\"))\n if new_qty < 0.0:\n raise osv.except_osv(_('Warning !'), _(\"The return quantity less than zero.\"))\n return super(stock_return_picking, self).create_returns(cr, uid, ids, context=context)\n \n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"v_7/GDS/common_shamil_v3/stock_negative/wizard/stock_partial_picking.py","file_name":"stock_partial_picking.py","file_ext":"py","file_size_in_byte":4543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"459461095","text":"import BirdSongToolbox.GetBirdData as gbd\n\nimport BirdSongToolbox.epoch_raw_data as erd\n\nfrom BirdSongToolbox.file_utility_functions import _save_pckl_data\n\nimport h5py\nimport os\nfrom src.sanity_checks.data_check_first_pass import _get_true_starts\n\n\ndef main_for_1day_raw(bird_id, session, neural_chans: list, audio_chan: list, verbose=False):\n \"\"\" Epoch (Chunk) Raw Chronic Data\n\n Parameters\n ----------\n bird_id : str\n subject id\n session : str\n the date of the recording\n neural_chans : list\n list of the channels(columns) of the .kwd file are neural channels\n audio_chan : list\n list of the channel(s)[column(s)] of the .kwd file that are audio channels\n verbose : bool\n If True the Function prints out useful statements, defaults to False\n\n Returns\n -------\n buff_chunks_neural : list, shape = [Chunk]->(channels, Samples)\n Neural Data that is Low-Pass Filter at 400 Hz and Downsampled to 1 KHz, list of 2darrays\n chunk_index_test : list, shape = [Chunk]->(absolute start, absolute end)\n List of the Absolute Start and End of Each Chunk for that Recordings Day\n chunk_ledger : list, shape = [Chunk]->(first epoch, ..., last epoch)\n Ledger of which epochs occur in each Chunk, Chunks that only contain one Epoch have a length of 1\n buff_chunks_audio : list, shape = [Chunk]->(Samples)\n Audio Data that is Band-Pass Filtered between\n\n Saves\n -----\n buff_chunks_neural : pckl\n Large_Epochs_Neural.pckl\n chunk_index_test : pckl\n Large_Epochs_Times.pckl\n chunk_ledger : pckl\n Epochs_Ledger.pckl\n buff_chunks_audio : pckl\n Large_Epochs_Audio.pckl\n\n \"\"\"\n # Folder where birds are\n experiment_folder_path = '/net/expData/birdSong/ss_data'\n\n bird_folder_path = os.path.join(experiment_folder_path, bird_id) # Folder for the bird\n\n day_folder = os.path.join(bird_folder_path, session) # Folder for Session\n\n # [3] Select Kwik File and get its Data\n kwik_file = gbd.get_data_path(day_folder=day_folder, file_type='.kwik') # Ask User to select Kwik File\n kwik_file_path = os.path.join(day_folder, kwik_file) # Get Path to Selected Kwik File\n kwik_data = gbd.read_kwik_data(kwik_path=kwik_file_path, verbose=True) # Make Dict of Data from Kwik File\n\n # [4] Select the Kwe file\n kwe = gbd.get_data_path(day_folder=day_folder, file_type='.kwe') # Select KWE File\n kwe_file_path = os.path.join(day_folder, kwe) # Get Path to Selected KWE File\n kwe_data = gbd.read_kwe_file(kwe_path=kwe_file_path, verbose=False) # Read KWE Data into Dict\n\n # [5] Select the Kwd file\n kwd = gbd.get_data_path(day_folder=day_folder, file_type='.kwd') # Select Kwd File\n kwd_file = h5py.File(os.path.join(day_folder, kwd), 'r') # Read Kwd Data into Dict\n\n # Showing where data is coming from\n print('Getting Data from ', kwd)\n\n # TODO: Clean Up Documentation Below\n\n # [6] Get the Absolute Start Times for the Automated Labels\n times = _get_true_starts(kwe_data=kwe_data, kwik_data=kwik_data)\n\n # [7] Determine How to Chunk (Epoch) the Data using the Automated Labels\n chunks, chunk_ledger = erd.determine_chunks_for_epochs(times)\n\n # [8.1] Chunk the Neural data with a buffer, low pass filter then Downsample\n buff_chunks_neural, chunk_index_test = erd.epoch_neural_raw(kwd_file=kwd_file, kwe_data=kwe_data, chunks=chunks,\n neural_chans=neural_chans, verbose=verbose)\n\n # [8.2] Save the Neural Epochs(Chunks) to pickle\n _save_pckl_data(data=buff_chunks_neural, data_name='Large_Epochs_Neural_Raw', bird_id=bird_id, session=session,\n make_parents=True, verbose=True)\n\n # # [8.3] Save the Register of the Absolute Start and End of Each Chunk\n # _save_pckl_data(data=chunk_index_test, data_name=\"Large_Epochs_Times\", bird_id=bird_id, session=session,\n # make_parents=True)\n\n # # [8.4] Save the Ledger of which Labels occur in which Epochs\n # _save_pckl_data(data=chunk_ledger, data_name=\"Epochs_Ledger\", bird_id=bird_id, session=session, make_parents=True)\n\n # [8.5] Save the Neural Epochs to .mat\n # TODO: Use info from https://docs.scipy.org/doc/scipy/reference/tutorial/io.html\n\n # [9.1] Chunk the Audio data with a buffer, and Band Pass Filter noise\n buff_chunks_audio = erd.epoch_audio_raw(kwd_file=kwd_file, kwe_data=kwe_data, chunks=chunks, audio_chan=audio_chan,\n verbose=verbose)\n # [9.2] Save the Chunk Audio\n _save_pckl_data(data=buff_chunks_audio, data_name=\"Large_Epochs_Audio_Raw\", bird_id=bird_id, session=session,\n verbose=True)\n\n","sub_path":"src/epoch/large_epochs_raw.py","file_name":"large_epochs_raw.py","file_ext":"py","file_size_in_byte":4750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"465349754","text":"integer_list=[1,2,3]\nheterogeneous_list=[\"string\",0.1,True]\nlist_of_lists=[integer_list,heterogeneous_list,[]]\n\nlist_length=len(integer_list)\nlist_sum=sum(integer_list)\nprint(list_length)\nprint(list_sum)\n\n#리스트의 n번째 값 불러오기\nx=[0,1,2,3,4,5,6,7,8,9]\nzero=x[0]\none=x[1]\nnine=x[-1]\neight=x[-2]\nx[0]=-1 #--->대체\n\nprint(x) #[-1,1,2,3,4,6,7,8,9]\n\n#슬라이싱\nfirst_three=x[:3] #[-1,1,2]\nthree_to_end=x[3:] #[3,4,5,6,7,8,9]\none_to_four=x[1:5] #[1,2,3,4]\nlast_three=x[-3:] #[7,8,9]\nwithout_first_and_last=x[1:-1] #[1,2,3,4,5,6,7,8]\ncopy_of_x=x[:] #[-1,1,2,3,4,5,6,7,8,9]\n\n#간격 설정하여 분리\nevery_third=x[::3]\nfive_to_three=x[5:2:-1] #[a:b:c]--->range(a,b) 간격 c\nprint(five_to_three)\n\n#in연산자\na=1 in [1,2,3] #True\nb=0 in [1,2,3] #False\n\nprint(a)\nprint(b)\n\n#리스트 추가\nx=[1,2,3]\nx.extend([4,5,6])\nprint(x) #[1,2,3,4,5,6]\n\n#리스트에 항목 추가\nx=[1,2,3]\nx.append(0) #[1,2,3,0]\ny=x[-1] #0\nz=len(x) #4\n\n#리스트 풀기\nx,y=[1,2]\nprint(x)\nprint(y)\n\n#버릴 항목은 밑줄(under_bar)로 표시\n_,y=[1,2]\nprint(y)\n\n\n","sub_path":"homework/p023_list.py","file_name":"p023_list.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"315632633","text":"\ndef bairro_mais_custoso(dicionario):\n dic = {}\n for bairro in dicionario:\n gasto = 0\n lista = dicionario[bairro]\n for valor in lista[6:12]:\n gasto += valor\n dic[bairro] = gasto\n b = 0\n for i in dic:\n if dic[i]>b:\n x = i\n return x","sub_path":"backup/user_337/ch167_2020_06_21_16_30_53_491486.py","file_name":"ch167_2020_06_21_16_30_53_491486.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"106291873","text":"class Node:\n def __init__(self, val=None):\n self.val = val\n self.next = None\n\n\nclass SingleLinkList:\n def __init__(self, head=None):\n \"\"\"链表的头部\"\"\"\n self._head = head\n\n def add(self, val: int):\n\n \"\"\"\n 给链表添加元素\n :param val: 传过来的数字\n :return:\n \"\"\"\n # 创建一个节点\n node = Node(val)\n if self._head is None:\n self._head = node\n else:\n cur = self._head\n while cur.next is not None:\n cur = cur.next # 移动游标\n cur.next = node # 如果 next 后面没了证明以及到最后一个节点了\n\n def traversal(self):\n if self._head is None:\n return\n else:\n cur = self._head\n while cur is not None:\n print(cur.val)\n cur = cur.next\n\n def size(self):\n \"\"\"\n 获取链表的大小\n :return:\n \"\"\"\n count = 0\n if self._head is None:\n return count\n else:\n cur = self._head\n while cur is not None:\n count += 1\n cur = cur.next\n return count\n\n def reverse(self):\n \"\"\"\n 单链表反转\n 思路:\n 让 cur.next 先断开即指向 none,指向设定 pre 游标指向断开的元素,然后\n cur.next 指向断开的元素,再把开始 self._head 再最后一个元素的时候.\n :return:\n \"\"\"\n if self._head is None or self.size() == 1:\n return\n else:\n pre = None\n cur = self._head\n while cur is not None:\n post = cur.next\n cur.next = pre\n pre = cur\n cur = post\n self._head = pre # 逆向后的头节点\n\n\nif __name__ == '__main__':\n single_link = SingleLinkList()\n single_link.add(3)\n single_link.add(5)\n # single_link.add(6)\n # single_link.add(7)\n # single_link.add(8)\n # print(\"对链表进行遍历\")\n # single_link.traversal()\n # print(f\"size:{single_link.size()}\")\n # print(\"对链表进行逆向操作之后\")\n # single_link.reverse()\n # single_link.traversal()\n","sub_path":"Ellie/suanfa/链表.py","file_name":"链表.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"330566708","text":"class Solution:\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n d, convert_d, res = {}, [], []\n for n in nums:\n if n in d: # use in to detect undefined key\n d[n]+=1\n else:\n d[n]=1\n \n for key in d.keys():\n convert_d.append((-d[key],key))\n \n heapq.heapify(convert_d)\n\n for i in range(0, k):\n res.append(heapq.heappop(convert_d)[1])\n return res\n\n\n\n\n \"\"\"\n origin:\n from collections import Counter\n c=Counter(nums)\n return list(dict(c.most_common(k)).keys()) \n \n brilliant one:\n return zip(*collections.Counter(nums).most_common(k))[0]\n\n by heapq:\n num_count = collections.Counter(nums)\n return heapq.nlargest(k, num_count, key=lambda x: num_count[x])\n key describes how can we decide our results. it is a function.\n \"\"\"","sub_path":"python/topKFreq.py","file_name":"topKFreq.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"292955350","text":"from __future__ import print_function, division\n\nimport numpy as np\nfrom pandas import core\nfrom ajustador import nrd_output,xml\nimport os\n\nimport logging \nfrom ajustador.helpers.loggingsystem import getlogger \nlogger = getlogger(__name__) \nlogger.setLevel(logging.INFO)\n\nAVOGADRO = 6.02214179\n\"\"\"Avogadro constant from CODATA 2006\"\"\"\nPUVC = AVOGADRO / 10\n\"\"\"Converts concentrations to particle numbers\"\"\"\nms_to_sec=1000\n\n''' to do: \n1. Turn this into class, which has attribute norm? and various features? Then, can use that attribute in plot_neurord_tog to plot %\n2. align experiments and simulations so that simulations can be shorter than experiments\nc. use stim start in wave and sim to align data\nd. align the simulation with experiment in fitness function based on filename param, not just sorted\n'''\n\ndef nrd_output_percent(sim_output,specie,stim_time,scale=1):\n pop1=nrd_output.nrd_output_conc(sim_output,specie)\n wave1y=pop1.values[:,0]\n wave1x=pop1.index\n start_index,wave1y_basal=basal(wave1x,wave1y,stim_time)\n if scale==1:\n wave1y=wave1y/wave1y_basal\n else:\n #kluge just for FRET percent change optimization, because model peak to basal Epac1cAMP ratio ~4.0 (not 0.4 as in fret)\n #perhaps should add ability to parse and execute arbitrary equation. Invert this for data in drawing.plot_neurord_tog\n wave1y=1+(wave1y/wave1y_basal-1)/scale\n #wave1y=1.0+wave1y/scale\n return wave1y,wave1x\n\ndef yvalues(y):\n if isinstance(y, np.ndarray):\n yval=y\n elif isinstance(y,core.frame.DataFrame):\n y=y.values \n else:\n print('******* nrd_fitness.yvalues: unknown data type **********')\n return yval\n\ndef basal(x,y,stim_start):\n start_index=np.fabs(x-stim_start).argmin()\n if start_index==0:\n start_index=1 #use 1st point as basal if stimulation starts at t=0\n yval=yvalues(y)\n wave1y_basal=np.mean(yval[0:start_index])\n return start_index,wave1y_basal\n\ndef peak(x,y,start_index):\n yval=yvalues(y)\n peakpoint=yval[start_index:].argmax()+start_index\n peaktime=x[peakpoint]\n peak=np.mean(yval[peakpoint-1:peakpoint+2]) #3 point average\n return peaktime,peak\n \ndef specie_concentration_fitness(*, voxel=0, species_list, trial=0,start=None,norm='max'):\n def fitness(sim, measurement, full=False):\n logger.debug('sim type {}, exp type {}'.format(type(sim),type(measurement)))\n fitarray=np.zeros((len(species_list),len(sim.output)))\n fit_dict={}\n stim_start=sim.stim_time if start is None else start*ms_to_sec\n for i,species in enumerate(species_list):\n fit_dict[species]={}\n for j,stim_set in enumerate(sim.output):\n if isinstance(measurement,xml.NeurordResult):\n pop1=nrd_output.nrd_output_conc(stim_set,species)\n stim_set.__exit__()\n pop2 = nrd_output.nrd_output_conc(measurement.output[j],species)\n diff = pop2 - pop1\n max_mol=np.mean([np.max(pop1.values),np.max(pop2.values)])\n logger.debug('sim:{} exp:{}'.format(os.path.basename(stim_set.file.filename),os.path.basename(measurement.output[j].file.filename)))\n else: #measurement is experimental data, stored as CSV_conc_set\n if norm=='percent':\n wave1y,wave1x=nrd_output_percent(stim_set,species,stim_start,scale=measurement.data[j].waves[species].scale)\n stim_set.norm=norm\n else:\n pop1=nrd_output.nrd_output_conc(stim_set,species)\n wave1y=pop1.values[:,0]\n wave1x=pop1.index\n stim_set.__exit__()\n pop2 = measurement.data[j].waves[species].wave\n max_mol=np.mean([np.max(wave1y),np.max(pop2.y)])\n # Note: np.interp(x1,x2,y2) returns values for y2 corresponding to x1 timepoints\n #what if x1 is negative? - don't use relative time for data\n pop1y=np.interp(pop2.x,wave1x,wave1y)\n logger.debug('wave1y sim= {}, len= {}, max= {}'.format(measurement.data[j].injection,len(wave1y),os.path.basename(stim_set.file.filename)))\n diff = pop2.y - pop1y\n diffnorm = diff if max_mol==0 else diff/max_mol\n fit_dict[species][stim_set.injection]=float((diffnorm**2).mean()**0.5)\n fitarray[i][j]=float((diffnorm**2).mean()**0.5)\n fitness=np.mean(fitarray)\n #print ('fitarray', fitarray)\n if full:\n return fit_dict\n else:\n return fitness\n return fitness\n\n","sub_path":"ajustador/nrd_fitness.py","file_name":"nrd_fitness.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"552085229","text":"\"\"\"\nThis is a standalone script, to be run on a PC. It receives GPS data\non a localhost port & writes to a replay file.\n\nThe format is pseudo-JSON, as it will be like:\n[\n{\"offset\":1, \"data\":$GPGGA,094013.0,4334.784909,N,11612.766448,W,1 (...) *60},\n{\"offset\":3, \"data\":$GPGGA,094023.0,4334.784913,N,11612.766463,W,1 (...) *61},\n{\"offset\":13, \"data\":$GPGGA,094034.0,4334.784922,N,11612.766471,W, (...) *67},\n\nNotice it starts with a '[', but like won't end with ']' - assuming you\nabort the creation uncleanly. You can manually add one if you wish.\n\n\"offset\" is the number of seconds since the start of the replay save, which\nare used during replay to delay and meter out the sentences in a realistic\nmanner. We'll also need to 'edit' the known sentences to add new TIME and\nDATE values.\n\"\"\"\nimport socket\nimport time\nimport gc\n\nfrom cp_lib.app_base import CradlepointAppBase\nfrom cp_lib.load_gps_config import GpsConfig\nfrom cp_lib.parse_data import clean_string, parse_integer\n\nDEF_BUFFER_SIZE = 1024\nDEF_REPLAY_FILE = 'gps_log.json'\n\n\ndef run_router_app(app_base):\n \"\"\"\n\n :param CradlepointAppBase app_base: prepared resources: logger, cs_client\n :return:\n \"\"\"\n buffer_size = DEF_BUFFER_SIZE\n replay_file_name = DEF_REPLAY_FILE\n\n # use Router API to fetch any configured data\n config = GpsConfig(app_base)\n host_ip, host_port = config.get_client_info()\n del config\n\n section = \"gps\"\n if section in app_base.settings:\n # then load dynamic values\n temp = app_base.settings[section]\n\n # check on our localhost port (not used, but to test)\n if \"host_ip\" in temp:\n # then OVER-RIDE what the router told us\n app_base.logger.warning(\"Settings OVER-RIDE router host_ip\")\n value = clean_string(temp[\"host_ip\"])\n app_base.logger.warning(\"was:{} now:{}\".format(host_ip, value))\n host_ip = value\n\n if \"host_port\" in temp:\n # then OVER-RIDE what the router told us\n app_base.logger.warning(\"Settings OVER-RIDE router host_port\")\n value = parse_integer(temp[\"host_port\"])\n app_base.logger.warning(\"was:{} now:{}\".format(host_port, value))\n host_port = value\n\n if \"buffer_size\" in temp:\n buffer_size = parse_integer(temp[\"buffer_size\"])\n\n if \"replay_file\" in temp:\n replay_file_name = clean_string(temp[\"replay_file\"])\n\n app_base.logger.debug(\"GPS source:({}:{})\".format(host_ip, host_port))\n\n # make sure our log file exists & is empty\n file_han = open(replay_file_name, \"w\")\n file_han.write(\"[\\n\")\n file_han.close()\n\n address = (host_ip, host_port)\n\n while True:\n # define the socket resource, including the type (stream == \"TCP\")\n app_base.logger.info(\"Preparing GPS Listening on {}\".format(address))\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # attempt to actually lock resource, which may fail if unavailable\n # (see BIND ERROR note)\n try:\n sock.bind(address)\n except OSError as msg:\n app_base.logger.error(\"socket.bind() failed - {}\".format(msg))\n\n # technically, Python will close when 'sock' goes out of scope,\n # but be disciplined and close it yourself. Python may warning\n # you of unclosed resource, during runtime.\n try:\n sock.close()\n except OSError:\n pass\n\n # we exit, because if we cannot secure the resource, the errors\n # are likely permanent.\n return -1\n\n # only allow 1 client at a time\n sock.listen(3)\n\n while True:\n # loop forever\n start_time = time.time()\n\n app_base.logger.info(\"Waiting on TCP socket %d\" % host_port)\n client, address = sock.accept()\n app_base.logger.info(\"Accepted connection from {}\".format(address))\n\n # for cellular, ALWAYS enable TCP Keep Alive (see KEEP ALIVE note)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)\n\n # set non-blocking so we can do a manual timeout (use of select()\n # is better ... but that's another sample)\n # client.setblocking(0)\n\n while True:\n app_base.logger.debug(\"Waiting to receive data\")\n data = client.recv(buffer_size)\n # data is type() bytes, to echo we don't need to convert\n # to str to format or return.\n if data:\n # assume we have multiple sentences per segment recv'd\n data = data.decode().split()\n\n print(\"data:{}\".format(data))\n\n file_han = open(replay_file_name, \"a\")\n offset = int(time.time() - start_time)\n\n for line in data:\n result = '{\"offset\":%d, \"data\":\"%s\"},\\n' % (offset,\n line)\n file_han.write(result)\n\n app_base.logger.debug(\"Wrote at offset:{}\".format(offset))\n\n else:\n break\n\n time.sleep(1.0)\n\n app_base.logger.info(\"Client disconnected\")\n client.close()\n\n # since this server is expected to run on a small embedded system,\n # free up memory ASAP (see MEMORY note)\n del client\n gc.collect()\n\n return 0\n\n\nif __name__ == \"__main__\":\n import sys\n from cp_lib.load_settings_ini import copy_config_ini_to_json, \\\n load_sdk_ini_as_dict\n\n copy_config_ini_to_json()\n\n app_path = \"demo/gps_replay\"\n my_app = CradlepointAppBase(app_path)\n # force a heavy reload of INI (app base normally only finds JSON)\n my_app.settings = load_sdk_ini_as_dict(app_path)\n\n _result = run_router_app(my_app)\n my_app.logger.info(\"Exiting, status code is {}\".format(_result))\n sys.exit(_result)\n","sub_path":"demo/gps_replay/save_replay.py","file_name":"save_replay.py","file_ext":"py","file_size_in_byte":6026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"321335805","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom pMuTT import constants as c\nfrom pMuTT.models.empirical.nasa import Nasa\n\n# Gas phase heat capacity data (in J/mol/K) for CH3OH from NIST\n# https://webbook.nist.gov/cgi/cbook.cgi?ID=C67561&Units=SI&Mask=1#Thermo-Gas\nT = np.array([50, 100, 150, 200, 273.15, 298.15, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1750, 2000, 2250, 2500, 2750, 3000])\nCp = np.array([34.00, 36.95, 38.64, 39.71, 42.59, 44.06, 44.17, 51.63, 59.7, 67.19, 73.86, 79.76, 84.95, 89.54, 93.57, 97.12, 100.24, 102.98, 105.4, 110.2, 113.8, 116.5, 118.6, 120, 121])\nCpoR = Cp/c.R('J/mol/K')\n\n#Enthalpy of Formation for CH3OH (in kJ/mol) from NIST\nT_ref = c.T0('K')\nH_ref = -205.\nHoRT_ref = H_ref/c.R('kJ/mol/K')/T_ref\n#Standard molar entropy (in J/mol/K) from Wikipedia, https://en.wikipedia.org/wiki/Methanol_(data_page)\nS_ref = 239.9\nSoR_ref = S_ref/c.R('J/mol/K')\n\n#Units to plot the figure\nCp_units = 'J/mol/K'\nH_units = 'kJ/mol'\nS_units = 'J/mol/K'\nG_units = 'kJ/mol'\n\n#Input the experimental data and fitting to a NASA polynomial\nCH3OH_nasa = Nasa.from_data(name ='CH3OH', T=T, CpoR=CpoR, T_ref=T_ref, HoRT_ref=HoRT_ref, SoR_ref=SoR_ref)\n\n#Compare the Nasa polynomial to the input data\nfig, axes = CH3OH_nasa.plot_empirical(Cp_units=Cp_units, H_units=H_units, S_units=S_units, G_units=G_units)\naxes[0].plot(T, Cp, 'ko')\naxes[1].plot(T_ref, H_ref, 'ko')\naxes[2].plot(T_ref, S_ref, 'ko')\naxes[3].plot(T_ref, H_ref - T_ref * S_ref * c.convert_unit(from_='J', to='kJ'), 'ko')\nplt.show()","sub_path":"examples/Expt_data_to_thermdat/Expt_data_to_thermdat.py","file_name":"Expt_data_to_thermdat.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"170454790","text":"import os\nimport re\nimport sys\nimport json\nimport time\nimport errno\nimport select\nimport signal\nimport socket\nimport logging\nfrom six import reraise\nfrom six.moves import _thread as thread\nfrom six.moves.http_client import OK, TEMPORARY_REDIRECT, SERVICE_UNAVAILABLE\nfrom six.moves.urllib.parse import urlparse\nfrom threading import Thread, RLock\nfrom http_parser.http import HttpParser\n\n\ndef _handle_sigint(signum, frame):\n global _prev_handler, _exc_info\n assert signum == signal.SIGINT\n if _exc_info is not None:\n exc_info = _exc_info\n _exc_info = None\n reraise(*exc_info)\n elif _prev_handler is not None:\n return _prev_handler(signum, frame)\n\n raise KeyboardInterrupt\n\n\n_exc_info = None\n_prev_handler = signal.signal(signal.SIGINT, _handle_sigint)\nLENGTH_PATTERN = re.compile(br'\\d+\\n')\nlogger = logging.getLogger(__name__)\n\n\nclass Connection(object):\n\n def __init__(self, addr, callback):\n host, port = addr.split(':', 2)\n port = int(port)\n self._addr = (host, port)\n self._sock = socket.socket()\n self._sock.setblocking(0)\n try:\n self._sock.connect(self._addr)\n except socket.error as e:\n if e.errno != errno.EAGAIN and e.errno != errno.EINPROGRESS:\n raise\n\n self._parser = HttpParser()\n self._callback = callback\n self._stream_id = None\n self._request = callback.gen_request()\n self._response = b''\n\n @property\n def addr(self):\n return self._addr\n\n @property\n def stream_id(self):\n return self._stream_id\n\n def write(self):\n try:\n sent = self._sock.send(self._request)\n self._request = self._request[sent:]\n return True\n except socket.error as e:\n if e.errno == errno.EAGAIN:\n return True\n\n logger.exception('Failed to send to %s', self._addr)\n return False\n\n def read(self):\n try:\n buf = self._sock.recv(select.PIPE_BUF)\n n_recv = len(buf)\n if n_recv == 0:\n logger.error('Remote %s closed', self.addr)\n return False\n\n n_parsed = self._parser.execute(buf, n_recv)\n if n_parsed != n_recv:\n raise RuntimeError('Failed to parse')\n\n if self._stream_id is None and self._parser.is_headers_complete():\n code = self._parser.get_status_code()\n if code == TEMPORARY_REDIRECT:\n headers = {\n k.upper(): v\n for k, v in list(self._parser.get_headers().items())\n }\n new_master = headers['LOCATION']\n new_master = urlparse(new_master).netloc or new_master\n logger.warning(\n 'Try to redirect to new master: %s', new_master\n )\n self._callback.change_master(new_master)\n return False\n\n elif code == SERVICE_UNAVAILABLE:\n logger.warnig('Master is not available, retry.')\n return False\n\n elif code != OK:\n msg = self._parser.recv_body()\n if not self._parser.is_message_complete():\n msg += ' ...'\n\n raise RuntimeError('Failed with HTTP %s: %s' % (code, msg))\n if not self._parser.is_chunked():\n raise RuntimeError('Response is not chunked')\n\n headers = {\n k.upper(): v\n for k, v in list(self._parser.get_headers().items())\n }\n self._stream_id = headers.get('MESOS-STREAM-ID', '')\n self._callback.stream_id = self._stream_id\n\n if self._parser.is_partial_body():\n self._response += self._parser.recv_body()\n while True:\n m = LENGTH_PATTERN.match(self._response)\n if not m:\n break\n\n captured = m.group(0)\n length = int(captured.strip())\n if len(self._response) < len(captured) + length:\n break\n\n data = self._response[\n len(captured):len(captured) + length]\n self._response = self._response[\n len(captured) + length:]\n try:\n event = json.loads(data.decode('utf-8'))\n except Exception:\n logger.exception('Failed parse json %s', data)\n raise\n\n try:\n self._callback.process_event(event)\n except Exception:\n logger.exception('Failed to process event')\n raise\n\n if self._parser.is_message_complete():\n logger.debug('Event stream ended')\n return False\n\n return True\n except socket.error as e:\n if e.errno == errno.EAGAIN:\n return True\n\n logger.exception('Failed to recv from %s', self._addr)\n return False\n\n def want_write(self):\n return bool(self._request)\n\n def fileno(self):\n return self._sock.fileno()\n\n def close(self):\n self._sock.close()\n self._sock = None\n self._parser = None\n self._request = None\n self._response = None\n self._callback.on_close()\n\n\nclass Process(object):\n\n def __init__(self, master=None):\n self._master = None\n self._started = False\n self._lock = RLock()\n self._wakeup_fds = None\n self._io_thread = None\n self._new_master = master\n self._stream_id = None\n\n @property\n def aborted(self):\n with self._lock:\n return not self._started\n\n @property\n def master(self):\n with self._lock:\n return self._master\n\n @property\n def stream_id(self):\n with self._lock:\n return self._stream_id\n\n @stream_id.setter\n def stream_id(self, _stream_id):\n with self._lock:\n self._stream_id = _stream_id\n\n @property\n def connected(self):\n return self.stream_id is not None\n\n def gen_request(self):\n raise NotImplementedError\n\n def on_event(self, event):\n raise NotImplementedError\n\n def on_close(self):\n raise NotImplementedError\n\n def process_event(self, event):\n if self._started:\n self.on_event(event)\n\n def change_master(self, new_master):\n with self._lock:\n self._new_master = new_master\n\n self._notify()\n\n def _notify(self):\n with self._lock:\n if self._wakeup_fds:\n os.write(self._wakeup_fds[1], b'\\0')\n\n def _shutdown(self):\n pass\n\n def _run(self):\n try:\n with self._lock:\n _wakeup_fd = self._wakeup_fds[0]\n\n conn = None\n self.stream_id = None\n next_connect_deadline = 0\n CONNECT_TIMEOUT = 2\n CONNECT_RETRY_INTERVAL = 2\n while True:\n to_write = set()\n to_read = set([_wakeup_fd])\n with self._lock:\n if not self._started:\n break\n\n if self._new_master != self._master:\n if conn is not None:\n conn.close()\n conn = None\n self.stream_id = None\n next_connect_deadline = (\n time.time() + CONNECT_RETRY_INTERVAL\n )\n\n self._master = self._new_master\n\n if (conn is None and self._master is not None and\n time.time() > next_connect_deadline):\n conn = Connection(self._master, self)\n next_connect_deadline = time.time()\n\n if conn is not None:\n if conn.want_write():\n to_write.add(conn.fileno())\n\n to_read.add(conn.fileno())\n\n now = time.time()\n if next_connect_deadline > now:\n timeout = next_connect_deadline - now\n elif next_connect_deadline + CONNECT_TIMEOUT > now:\n timeout = next_connect_deadline + CONNECT_TIMEOUT - now\n else:\n timeout = None\n\n readable, writeable, _ = select.select(\n to_read, to_write, [], timeout\n )\n\n for fd in writeable:\n assert fd == conn.fileno()\n next_connect_deadline = 0\n if not conn.write():\n conn.close()\n conn = None\n self.stream_id = None\n next_connect_deadline = (\n time.time() + CONNECT_RETRY_INTERVAL\n )\n\n for fd in readable:\n if fd == _wakeup_fd:\n os.read(_wakeup_fd, select.PIPE_BUF)\n elif conn and fd == conn.fileno():\n if not conn.read():\n conn.close()\n conn = None\n self.stream_id = None\n next_connect_deadline = (\n time.time() + CONNECT_RETRY_INTERVAL\n )\n\n if (conn is not None and next_connect_deadline != 0 and\n time.time() > next_connect_deadline + CONNECT_TIMEOUT):\n logger.error('Connect to %s timeout', conn.addr)\n conn.close()\n conn = None\n self.stream_id = None\n next_connect_deadline = (\n time.time() + CONNECT_RETRY_INTERVAL\n )\n\n except Exception:\n logger.exception('Thread abort:')\n with self._lock:\n self._started = False\n\n global _exc_info\n _exc_info = sys.exc_info()\n thread.interrupt_main()\n\n finally:\n self._shutdown()\n\n if conn:\n conn.close()\n conn = None\n\n with self._lock:\n r, w = self._wakeup_fds\n os.close(r)\n os.close(w)\n self._wakeup_fds = None\n\n def start(self):\n with self._lock:\n if self._started:\n logger.warning('Process already started!')\n return\n\n if self._io_thread:\n self.join()\n\n self._wakeup_fds = os.pipe()\n self._started = True\n self._io_thread = Thread(target=self._run, name='Process IO')\n self._io_thread.daemon = True\n self._io_thread.start()\n\n def abort(self):\n self.stop()\n\n def stop(self):\n with self._lock:\n self._started = False\n\n self._notify()\n\n def join(self):\n if self._io_thread:\n self._io_thread.join()\n self._io_thread = None\n\n def run(self):\n self.start()\n self.join()\n","sub_path":"第二次作业/pymesos/pymesos/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":11530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"54710954","text":"import cv2\nimport numpy as np \nimport os \n\nclass Face_Recogination(object):\n\n\tdef __init__(self):\n\t\t# self.mode=mode\n\t\t# self.test_path=test_path\n\n\t\tself.subjects = [\"\", \"Saurav\", \"Gaurav\"]\n\n\t\t# if self.mode == 'test':\n\t\t# \tself.video=cv2.VideoCapture(0)\n\t\t# else:\n\t\t# \tself.test_image=cv2.imread(self.test_path)\n\n\t# def __del__(self):\n\t# \tif self.mode=='test':\n\t# \t\tself.video.release()\n\n\tdef face_detector(self,image):\n\n\t\tface_cascade=cv2.CascadeClassifier('opencv_files\\\\lbpcascade_frontalface.xml')\n\n\t\t# if self.mode == 'test':\n\t\t\t# _,image=self.video.read()\n\t\t# else:\n\t\t# print(image_path)\n\t\t# image=cv2.imread(image_path)\n\t\t\t# cv2.imshow(\"img\",image)\n\t\t\t# cv2.waitKey(0)\n\n\t\timage=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n\t\tfaces=face_cascade.detectMultiScale(image, scaleFactor=1.2, minNeighbors=5)\n\n\t\tif (len(faces)==0):\n\t\t\treturn None,None\n\n\t\t(x,y,w,h)=faces[0]\n\t\t# for (x,y,w,h) in faces:\n\t\t\t# cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)\n\n\t\t# # single image is considerd here \n\t\troi=image[y:y+h,x:x+w]\n\n\t\t# cv2.imshow(\"roi\",roi)\n\t\t# cv2.waitKey(0)\n\t\treturn roi,faces[0]\n\n\n\tdef prep_train_data(self):\n\t\tlabels=[]\n\t\tfaces=[]\n\n\t\tfor label in os.listdir('train_data'):\n\t\t\t# labels.append(label)\n\n\t\t\tfor x in os.listdir(os.path.join('train_data',label)):\n\t\t\t\timage_path=os.path.join('train_data',label,x)\n\t\t\t\t# print(image_path)\n\t\t\t\timg=cv2.imread(image_path)\n\t\t\t\t# cv2.imshow(image)\n\t\t\t\t# cv2.waitKey(0)\n\n\t\t\t\tface,rect=self.face_detector(img)\n\n\t\t\t\tif face is not None:\n\n\t\t\t\t\tif label =='Saurav':\n\t\t\t\t\t\tlabels.append(1)\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tlabels.append(2)\n\t\t\t\t\tfaces.append(face)\n\t\t\t\t\t# labels.append(label)\n\t\t# print(labels)\n\t\treturn faces,labels\n\t\t\t\t\n\n\n\n\n\tdef train(self):\n\t\tfaces,labels=self.prep_train_data()\n\t\t# print(len(faces),len(labels))\n\n\t\t# arr=np.array(labels)\n\t\t# print((arr))\n\n\t\tself.face_recognizer = cv2.face.LBPHFaceRecognizer_create()\n\t\tself.face_recognizer.train(faces, np.array(labels))\n\t\t# self.face_recognizer.train(faces,labels)\n\n\n\tdef predict(self,img):\n\n\t\timg_copy=img.copy()\n\t\t# print(self.test_path)\n\t\tface,rect=self.face_detector(img_copy)\n\n\t\tlabel=self.face_recognizer.predict(face)\n\n\t\t# print(label)\n\t\tlabel_text=self.subjects[label[0]]\n\t\tif label_text ==1:\n\t\t\tlabel_text=\"Saurav\"\n\n\t\t(x,y,w,h)=rect\n\n\t\tcv2.rectangle(img_copy, (x,y), (x+w,y+h), (255,0,0),2)\n\n\t\tcv2.putText(img_copy, label_text, (x,y), cv2.FONT_HERSHEY_PLAIN,2.5,(0,255,0),2)\n\t\t# img_copy = cv2.resize(img_copy, (960, 540)) # Resize image\n\t\t# cv2.imshow(\"img\",img_copy)\n\t\t# cv2.waitKey(0)\n\t\timg_copy = cv2.resize(img_copy, (960, 540))\n\t\tprint(\"prediction complete\")\n\t\treturn img_copy\n\n\n# f=Face_Recogination()\n# f.train()\n\n# img=cv2.imread(\"C:\\\\Users\\\\Saurav Akolia\\\\Documents\\\\GitHub\\\\Face_recognition_PyZMQ\\\\re.jpg\")\n\n# predicted_img=f.predict(img)\n# cv2.imshow(\"predict\",predicted_img)\n# cv2.waitKey(0)","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"430069959","text":"#!/usr/bin/env python\nimport getpass\nimport sys, os, optparse\nimport subprocess\n\nimport re\n\nimport time\nfrom shutil import which\n\nvanilla = \"\"\"Executable = %s\nUniverse = vanilla\ngetenv = true\n%s\noutput = %s\nerror = %s\narguments = \"%s\"\nlog = %s\nnotification = %s\ninitialdir = %s\ntransfer_executable = false\n+Research = True\nrequest_memory = 2*1024\n%s\nQueue\"\"\"\n\n\ndef condor_submit(file):\n \"\"\"\n Submit a config file to condor.\n\n :param file:\n \"\"\"\n p = subprocess.Popen([which('condor_submit'), file])\n p.wait()\n\ndef condor_wait():\n while True:\n p = subprocess.Popen([which('condor_q'), getpass.getuser()], stdout=subprocess.PIPE)\n p.wait()\n try:\n result = p.stdout.read().decode(encoding='utf-8')\n jobs_re = re.search('([0-9]+) jobs;', result)\n num_jobs = int(jobs_re.group(1))\n\n if num_jobs == 0:\n break\n else:\n time.sleep(2)\n except AttributeError:\n time.sleep(2)\n pass\n\ndef condor_wait_notify(body, email, subject=\"Condor Notification\"):\n condor_wait()\n os.system('echo \"{}\" | mail -s \"{}\" {}'.format(body, subject, email))\n\ndef run_cmd(args, prefix, name, email = False, stdin = \"\", cwd = os.getcwd(), env = ''):\n\n # First, make sure the program can be found.\n exe = args[0]\n exe_path = which(exe)\n if not os.path.exists(exe_path):\n print('Error: the command \"%s\" could not be found!' % exe)\n sys.exit(-1)\n if stdin and not os.path.exists(stdin):\n sys.stderr.write('ERROR: The stdin file \"%s\" could not be found' % stdin)\n sys.exit(-127)\n exe = exe_path\n\n if env:\n env = 'environment=\"{}\"'.format(env)\n\n # Create the directory for the prefix, if needed.\n os.makedirs(prefix, exist_ok=True)\n\n # Now, make the commandline back into a string.\n arg_str = ''\n for arg in args[1:]:\n arg_str += '%s ' % arg\n\n fileprefix = os.path.join(prefix, name)\n # Set up the paths we're going to write.\n cmdpath = fileprefix + \".cmd\"\n outpath = fileprefix + \".out\"\n errpath = fileprefix + \".err\"\n logpath = fileprefix + \".log\"\n\n # Now, write the .cmd file to submit to condor.\n cmdfile = open(cmdpath, 'w')\n\n if email:\n notification = 'Complete'\n else:\n notification = 'Never'\n\n if not stdin:\n stdin = '# No stdin given'\n else:\n stdin = 'input = %s' % stdin\n cmdfile.write(vanilla % (exe, stdin, outpath, errpath, arg_str, logpath, notification, cwd, env))\n cmdfile.close()\n\n condor_submit(cmdpath)\n\n\ndef usage():\n return '%prog [OPTIONS] COMMAND'\n\nif __name__ == '__main__':\n\n p = optparse.OptionParser()\n\n p.add_option('--disable-email', dest='email', action='store_false', help=\"Don't send an email at job completion.\", default=True)\n\n\n p.add_option('-i', '--stdin', dest='stdin', help='Supply the following file as stdin')\n\n p.add_option('-p', '--prefix', dest='prefix', default=os.getcwd(), help=\"The directory to store the stderr/stdout files.\")\n p.add_option('-n', '--name', dest='name', default='condor_job')\n p.add_option('-d', '--cwd', dest='cwd', default=os.getcwd())\n (options, args) = p.parse_args(sys.argv)\n\n\n\n if len(args) < 2:\n p.usage = usage()\n p.print_help()\n sys.exit()\n\n run_cmd(args[1:], options.prefix, options.name, options.email, stdin = options.stdin, cwd = options.cwd)\n\n","sub_path":"intent/interfaces/condor.py","file_name":"condor.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"165804077","text":"from xml.etree import ElementTree\nfrom xml.etree.ElementTree import Element, SubElement\n\nfrom .event import Event\nfrom .levelobjecttype import LevelObjectType\n\n\nclass LevelObject:\n\tdef __init__(self, object_type: LevelObjectType, x = 0, y = 0, parameters = None, *, slot = None, sprite_angle = None, events = None,\n\t\t\t\t slotted_objects=None):\n\t\tif parameters is None:\n\t\t\tparameters = dict()\n\t\tif events is None:\n\t\t\tevents = []\n\t\tif slotted_objects is None:\n\t\t\tslotted_objects = []\n\n\t\tself.type = object_type\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.slot = slot\n\t\tself.rotation = sprite_angle\n\t\tself.events = events\n\t\tself.parameters = parameters\n\t\tself.slotted_objects = slotted_objects\n\n\tdef to_xml(self) -> Element:\n\t\txml_object = Element('object')\n\t\txml_object.attrib['type'] = str(int(self.type))\n\t\txml_object.attrib['x'] = str(self.x)\n\t\txml_object.attrib['y'] = str(self.y)\n\t\tif self.slot is not None:\n\t\t\txml_object.attrib['slot'] = str(self.slot)\n\t\tif self.rotation is not None:\n\t\t\txml_object.attrib['sprite_angle'] = str(self.rotation)\n\n\t\tfor event in self.events:\n\t\t\txml_object.append(event.to_xml())\n\n\t\tfor key, value in self.parameters.items():\n\t\t\txml_parameter = SubElement(xml_object, 'param')\n\t\t\txml_parameter.attrib['key'] = key\n\t\t\txml_parameter.attrib['val'] = f'{value:g}'\n\n\t\tfor slotted_object in self.slotted_objects:\n\t\t\txml_slotted_object = slotted_object.to_xml()\n\t\t\txml_slotted_object.tag = 'obj'\n\t\t\txml_object.append(xml_slotted_object)\n\n\t\treturn xml_object\n\n\tdef to_xml_string(self) -> str:\n\t\treturn ElementTree.tostring(self.to_xml(), encoding='utf-8').decode('utf-8')\n\n\t@staticmethod\n\tdef from_xml(xml_object: Element):\n\t\tlevel_object = LevelObject(0)\n\n\t\tfor key, value in xml_object.attrib.items():\n\t\t\tif key == 'type':\n\t\t\t\tlevel_object.type = LevelObjectType(int(value))\n\t\t\telif key == 'x':\n\t\t\t\tlevel_object.x = int(value)\n\t\t\telif key == 'y':\n\t\t\t\tlevel_object.y = int(value)\n\t\t\telif key == 'slot':\n\t\t\t\tlevel_object.slot = int(value)\n\t\t\telif key == 'sprite_angle':\n\t\t\t\tlevel_object.rotation = int(value)\n\n\t\tfor child in xml_object:\n\t\t\tif child.tag == 'event':\n\t\t\t\tlevel_object.events.append(Event.from_xml(child))\n\t\t\telif child.tag == 'param':\n\t\t\t\tlevel_object.parameters[child.attrib['key']] = float(child.attrib['val'])\n\t\t\telif child.tag == 'obj':\n\t\t\t\tlevel_object.slotted_objects.append(LevelObject.from_xml(child))\n\n\t\treturn level_object\n\n\t@staticmethod\n\tdef from_xml_string(xml_string: str):\n\t\treturn LevelObject.from_xml(ElementTree.fromstring(xml_string))\n","sub_path":"iwmlevel/levelobject.py","file_name":"levelobject.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"52432473","text":"from auth import *\nfrom time import sleep\nimport random\nimport arrow\n\n\nclass Fave:\n def __init__(self, ago, hashtags):\n # days to go back\n self.ago = ago\n self.hashtags = hashtags\n\n until = arrow.utcnow()\n until = until.format('YYYY-MM-DD')\n since = arrow.utcnow()\n since = since.replace(days=ago)\n since = since.format('YYYY-MM-DD')\n for tweet in tweepy.Cursor(api.search, q=random.choice(hashtags), since=since,until=until).items(5):\n try:\n # Add \\n escape character to print() to organize tweets\n # Retweet tweets as they are found\n tweet.favorite()\n print('Liked: ' + ' Tweet by: @' + tweet.user.screen_name + '\\n')\n f = open('/code/logs/fave.log', 'w')\n f.write('Liked: ' + ' Tweet by: @' + tweet.user.screen_name + '\\n') # python will convert \\n to os.linesep\n f.close()\n\n sleep(10)\n\n except tweepy.TweepError as e:\n print(e.reason)\n f = open('/code/logs/fave.log', 'w')\n f.write('\\nTweet by: @' + tweet.user.screen_name + ' : ' + e.reason + '\\n') # python will convert \\n to os.linesep\n f.close()\n\n\n except StopIteration:\n break","sub_path":"app/bots/fave.py","file_name":"fave.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"392305652","text":"import optparse\nimport os\nimport signal\nimport subprocess\nimport sys\n\nfrom .env import Env\nfrom .version import __version__\n\n# must have shell = True on Windows\nis_windows = sys.platform == 'win32'\n\nif is_windows:\n params = {'creationflags': subprocess.CREATE_NEW_PROCESS_GROUP}\nelse:\n params = {'preexec_fn': os.setsid}\n\n\nclass Response(Exception):\n def __init__(self, message='', status=0):\n self.message = message\n self.status = status\n\n\nclass Runner(object):\n envdir_usage = \"usage: %prog [--help] [--version] dir child\"\n envshell_usage = \"usage: %prog [--help] [--version] dir\"\n\n def __init__(self):\n self.parser = optparse.OptionParser(version=__version__)\n self.parser.disable_interspersed_args()\n self.parser.prog = 'envdir'\n signal.signal(signal.SIGTERM, self.terminate)\n\n def path(self, path):\n real_path = os.path.realpath(os.path.expanduser(path))\n if not os.path.exists(real_path):\n # use 111 error code to adher to envdir's standard\n raise Response(\"envdir %r does not exist\" % path, 111)\n if not os.path.isdir(real_path):\n # use 111 error code to adher to envdir's standard\n raise Response(\"envdir %r not a directory\" % path, 111)\n return real_path\n\n def open(self, path=None, stacklevel=1):\n if path is None:\n frame = sys._getframe()\n get_parent = lambda frame: frame.f_back\n for _ in range(stacklevel):\n frame = get_parent(frame)\n if frame is not None:\n callerdir = os.path.dirname(frame.f_code.co_filename)\n path = os.path.join(callerdir, 'envdir')\n else:\n # last holdout, assume cwd\n path = 'envdir'\n return Env(self.path(path))\n\n def shell(self, name, *args):\n self.parser.set_usage(self.envshell_usage)\n self.parser.prog = 'envshell'\n options, args = self.parser.parse_args(list(args))\n\n if len(args) == 0:\n raise Response(\"%s\\nError: incorrect number of arguments\" %\n (self.parser.get_usage()), 2)\n\n sys.stdout.write(\"Launching envshell for %s. \"\n \"Type 'exit' or 'Ctrl+D' to return.\\n\" %\n self.path(args[0]))\n sys.stdout.flush()\n self.open(args[0], 2)\n\n shell = os.environ['SHELL']\n\n try:\n subprocess.check_call([shell],\n universal_newlines=True,\n bufsize=0,\n close_fds=not is_windows,\n **params)\n except OSError as err:\n if err.errno == 2:\n raise Response(\"Unable to find shell %s\" % shell, err.errno)\n else:\n raise Response(\"An error occurred: %s\" % err,\n status=err.errno)\n\n raise Response()\n\n def run(self, name, *args):\n self.parser.set_usage(self.envdir_usage)\n self.parser.prog = 'envdir'\n options, args = self.parser.parse_args(list(args))\n\n if len(args) < 2:\n raise Response(\"%s\\nError: incorrect number of arguments\\n\" %\n (self.parser.get_usage()), 2)\n\n self.open(args[0], 2)\n\n # the args to call later\n args = args[1:]\n\n # in case someone passes in -- for any reason to separate the commands\n if args[0] == '--':\n args = args[1:]\n\n try:\n self.process = subprocess.Popen(args,\n universal_newlines=True,\n bufsize=0,\n close_fds=False,\n **params)\n self.process.wait()\n except OSError as err:\n if err.errno == 2:\n raise Response(\"Unable to find command %s\" %\n args[0], err.errno)\n else:\n raise Response(status=err.errno)\n except KeyboardInterrupt:\n self.terminate()\n raise Response(status=self.process.returncode)\n\n def terminate(self, *args, **kwargs):\n # first send mellow signal\n self.quit(signal.SIGTERM)\n if self.process.poll() is None:\n # still running, kill it\n self.quit(signal.SIGKILL)\n\n def quit(self, signal):\n if self.process.poll() is None:\n proc_pgid = os.getpgid(self.process.pid)\n if os.getpgrp() == proc_pgid:\n # Just kill the proc, don't kill ourselves too\n os.kill(self.process.pid, signal)\n else:\n # Kill the whole process group\n os.killpg(proc_pgid, signal)\n","sub_path":"envdir/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":4858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"385941551","text":"from keras.models import load_model\nfrom keras.preprocessing import image\nimport os\nimport numpy as np\n\nmodel = load_model('great_model_ducks')\npath = \"C:\\\\Dev\\\\AI\\\\2U\\\\data\\\\validation\\\\ducks\"\ntotalImagesShown = 500\ncatProb = 0\ndogProb = 0\nduckProb = 0\nfor filename in (os.listdir(path)):\n img = image.load_img(os.path.join(path, filename), target_size=(150,150))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis = 0)\n pred = model.predict(x)\n catProb+=pred[0][0]\n dogProb+=pred[0][1]\n duckProb+=pred[0][2]\n\nprint (\"Cat predictions: \" + str(catProb/totalImagesShown))\nprint (\"Dog predictions: \" + str(dogProb/totalImagesShown))\nprint (\"Duck predictions: \" + str(duckProb/totalImagesShown))","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"360366625","text":"import os\nimport sys\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nif __file__ in [f for f in os.listdir('.') if os.path.isfile(f)]:\n SCRIPT_PATH = os.path.dirname(os.getcwd())\nelse:\n SCRIPT_PATH = os.path.dirname(__file__)\nLOCAL_PATH = os.path.join(SCRIPT_PATH.rsplit('fluxonium-waveguide', 1)[0],\n 'fluxonium-waveguide')\nif LOCAL_PATH not in sys.path:\n sys.path.append(LOCAL_PATH)\n\nfrom local_settings import samples_path\nimport utilities\nfrom plotting import colored_lines\nimport plot_spectrum\nimport plot_anchor_points\n\n\ndef main():\n sample = 'fluxonium022319'\n fitpath = 'Processed Data/Fluxonium Coupled to Harmonic Modes/'\n pltpath = os.path.join(samples_path, sample,\n 'Plots/Fits/Fluxonium Coupled to Harmonic Modes')\n\n filename_in = 'one_mode_6.hdf5'\n \n filename_out = os.path.splitext(filename_in)[0]\n\n filename = os.path.join(samples_path, sample, fitpath, filename_in)\n params = utilities.load_fit(filename)\n utilities.print_params(params)\n\n plot_spectrum.plot_spectrum()\n plot_anchor_points.plot_anchor_points(params['data_set'])\n # plot_anchor_points.plot_anchor_points('data2')\n\n str_freq = ', '.join(['%.3f' % freq for freq in params['frequencies']])\n str_coup = ', '.join(['%.3f|%.3f' % (c, f) for c, f in\n zip(params['n_couplings'], params['phi_couplings'])])\n\n title = ('$E_L/h=$%.3f GHz, $E_C/h=$%.3f GHz, $E_J/h=$%.3f GHz\\n'\n '$f_i\\in${%s} GHz\\n$g_{i,n|\\phi}\\in${%s} GHz' % (params['E_L'],\n params['E_C'], params['E_J'], str_freq, str_coup))\n\n # plt.xlim(-.05, 0.525)\n plot_spectrum.label_axes(title, title_color='w')\n fig_path = os.path.join(pltpath, '%s_spectrum.png' % filename_out)\n plt.savefig(fig_path, dpi=600)\n\n phi_ext = params['phi_ext']\n levels = params['levels']\n weights = params['weights']\n num_tot = params['num_tot']\n\n lines = colored_lines(phi_ext, levels, weights, 0, num_tot)\n for idx in range(params['num_tot']-1):\n plt.gca().add_collection(lines[idx])\n\n # lines = colored_lines(phi_ext, levels, weights, 1, num_tot)\n # for idx in range(params['num_tot']-2):\n # plt.gca().add_collection(lines[idx], '-')\n \n # lines = colored_lines(phi_ext, levels, weights, 0, num_tot, 2)\n # for idx in range(params['num_tot']-1):\n # plt.gca().add_collection(lines[idx])\n\n plot_spectrum.label_axes(title, title_color='k', ylim=[0, 10], xlim=[-0.25, 0.75])\n plt.tight_layout()\n fig_path = os.path.join(pltpath, '%s_spectrum_fit.png' % filename_out)\n plt.savefig(fig_path, dpi=600)\n\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"From Ivan/fluxonium-waveguide/samples/fluxonium022319/plot_spectrum_and_fit_fluxonium_coupled_to_oscillators.py","file_name":"plot_spectrum_and_fit_fluxonium_coupled_to_oscillators.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"578168900","text":"import signal\nimport socket\nimport time\nimport sys\nimport os\n\nfrom periphery import GPIO\n\ntmp = GPIO(7, \"out\")\ntmp = GPIO(8, \"out\")\ntmp = GPIO(73, \"out\")\ntmp = GPIO(138, \"out\")\ntmp.close()\n\ndef reset():\n gpio7 = open('/sys/class/gpio/gpio7/value', 'w');\n gpio73 = open('/sys/class/gpio/gpio73/value', 'w');\n gpio8 = open('/sys/class/gpio/gpio8/value', 'w');\n gpio138 = open('/sys/class/gpio/gpio138/value', 'w');\n return gpio7, gpio73, gpio8, gpio138\n\ns = socket.socket()\ns.connect(('140.112.30.125', 12987))\n\ndef signal_handler(sig, frame):\n gpio7, gpio73, gpio8, gpio138 = reset()\n gpio7.write('0')\n gpio73.write('0')\n gpio8.write('0')\n gpio138.write('0')\n s.close()\n sys.exit(0)\nsignal.signal(signal.SIGINT, signal_handler)\n\nwhile True:\n gpio7, gpio73, gpio8, gpio138 = reset()\n buf = (s.recv(1024)).decode()\n s.send(('ok').encode())\n if buf != 'not defined':\n print(buf)\n if buf == 'move forward':\n gpio7.write('0'); gpio73.write('0'); gpio8.write('1'); gpio138.write('1')\n elif buf == 'move backward':\n gpio7.write('1'); gpio73.write('1'); gpio8.write('0'); gpio138.write('0')\n elif buf == 'turn left':\n gpio7.write('0'); gpio73.write('0'); gpio8.write('1'); gpio138.write('0')\n elif buf == 'turn right':\n gpio7.write('0'); gpio73.write('0'); gpio8.write('0'); gpio138.write('1')\n else:\n gpio7.write('0'); gpio73.write('0'); gpio8.write('0'); gpio138.write('0')","sub_path":"2019_DSP_Final/client_car.py","file_name":"client_car.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"2955416","text":"if __name__ == '__main__':\n import os\n import sys\n sys.path[0] = os.getcwd()\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import KMeans\nimport pandas as pd\n\nfrom src.data.raw_twitter_to_en_text import raw_twitter_to_english_text\nfrom src.util.nlp_concepts import get_concepts_from_kmeans\nfrom src.util.nlp_concepts import print_top_terms\nfrom src.util.nlp_concepts import print_samples_of_text_by_label\n\n\npath_to_raw_data = './data/raw/twitter_stream.txt'\n\n# Create document term tfidf sparse matrix\ntfidf = TfidfVectorizer(ngram_range=(1,2),\n strip_accents='unicode',\n stop_words='english')\nsparse = tfidf.fit_transform(raw_twitter_to_english_text(path_to_raw_data))\nprint(\"Document-Term matrix size:\", sparse.shape)\n\n\n# Choose number of clusters\nnum_clusters = 50\n\n\n# Compute clusters\nkmeans = KMeans(n_clusters=num_clusters)\nkmeans.fit(sparse)\n\n# Measure effectiveness of clusters\nprint(\"Iterations to convergence:\", kmeans.n_iter_)\nif (kmeans.get_params()['max_iter'] <= kmeans.n_iter_):\n print(\"CONVERGENCE WARNING: Iterations maxed out!\")\nprint(\"Inertia:\", kmeans.inertia_)\n\n# Get cluster centers as possible concepts discovered\nconcepts = get_concepts_from_kmeans(tfidf, kmeans)\n\n\n# Choose number of concepts to view\nnum_concepts = 25\n# Choose number of terms to view for each concept\nnum_terms = 12\n# Choose number of tweets to sample from each cluster centered on a concept\nnum_samples = 5\n\n\n# Print top terms of the concepts from the largest clusters\nprint_top_terms(concepts, num_terms, num_concepts)\n\n# Print a sample of tweets from the largest clusters\ndf = pd.DataFrame(raw_twitter_to_english_text(path_to_raw_data), columns=['text'])\ndf['label'] = kmeans.predict(sparse)\nprint_samples_of_text_by_label(df, num_concepts, num_samples)\n","sub_path":"src/exploration/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482280583","text":"from pyspark.sql.types import StringType, IntegerType, FloatType, DoubleType, DateType, TimestampType\nfrom pyspark.sql.types import StructType, StructField\nfrom pyspark.sql.functions import udf\nfrom pyspark.sql import SparkSession\nimport pyspark\nimport pyspark.sql\nimport os, sys, iso8601, datetime\n\n# 시간를 문자열이나 숫자가 아니라 타임스탬프로 전환해야 된다.\ndef convert_hours(hours_minutes):\n hours = hours_minutes[:-2]\n minutes = hours_minutes[-2:]\n \n if hours == '24':\n hours = '23'\n minutes = '59'\n \n time_string = \"{}:{}:00Z\".format(hours, minutes)\n return time_string\n\ndef compose_datetime(iso_date, time_string):\n return \"{} {}\".format(iso_date, time_string)\n\ndef create_iso_string(iso_date, hours_minutes):\n time_string = convert_hours(hours_minutes)\n full_datetime = compose_datetime(iso_date, time_string)\n return full_datetime\n\ndef create_datetime(iso_string):\n return iso8601.parse_date(iso_string)\n\ndef convert_datetime(iso_date, hours_minutes):\n iso_string = create_iso_string(iso_date, hours_minutes)\n dt = create_datetime(iso_string)\n return dt\n\ndef day_of_year(iso_date_string):\n dt = iso8601.parse_date(iso_date_string)\n doy = dt.timetuple().tm_yday\n return doy\n\ndef alter_feature_datetimes(row):\n \n flight_date = iso8601.parse_date(row['FlightDate'])\n scheduled_dep_time = convert_datetime(row['FlightDate'], row['CRSDepTime'])\n scheduled_arr_time = convert_datetime(row['FlightDate'], row['CRSArrTime'])\n \n # 출발,도착 예상시간은 HHMM 이기 때문에 다음날을 표현을 못한다.\n # 그래서 출발 이후 날짜가 변경되었다면 하루(days=1)를 추가해 주는것이다.\n # 야간 운항 처리 \n if scheduled_arr_time < scheduled_dep_time:\n scheduled_arr_time += datetime.timedelta(days=1)\n \n doy = day_of_year(row['FlightDate'])\n \n return {\n 'FlightNum': row['FlightNum'],\n 'FlightDate': flight_date,\n 'DayOfWeek': int(row['DayOfWeek']),\n 'DayOfMonth': int(row['DayOfMonth']),\n 'DayOfYear': doy,\n 'Carrier': row['Carrier'],\n 'Origin': row['Origin'],\n 'Dest': row['Dest'],\n 'Distance': row['Distance'],\n 'DepDelay': row['DepDelay'],\n 'ArrDelay': row['ArrDelay'],\n 'CRSDepTime': scheduled_dep_time,\n 'CRSArrTime': scheduled_arr_time,\n }\n\nproject_home = ''\n\n# 스파크 객체 생성\nconf = pyspark.SparkConf().setAll([('spark.driver.memory', '2g')])\nsc = pyspark.SparkContext(conf=conf)\nspark = pyspark.sql.SparkSession(sc).builder.getOrCreate()\nspark.conf.set(\"spark.sql.files.ignoreCorruptFiles\",\"true\")\n\ndef main():\n #데이터 가져오기\n refined_data = spark.read.parquet(\"{}/data/*\".format(project_home))\n\n # 테이블 등록\n refined_data.registerTempTable(\"Refined_Data\")\n\n # 모델 훈련에 쓰일 데이터 생성\n training_yet_data = spark.sql(\"\"\"\n SELECT\n FlightNum,\n FlightDate,\n DayOfWeek,\n DayofMonth AS DayOfMonth,\n CONCAT(Month, '-', DayofMonth) AS DayOfYear,\n Carrier,\n Origin,\n Dest,\n Distance,\n DepDelay,\n ArrDelay,\n CRSDepTime,\n CRSArrTime\n FROM Refined_Data\n \"\"\")\n \n # alter_feature_datetimes : 날짜 파싱\n training_yet_data=training_yet_data.rdd.map(alter_feature_datetimes).toDF()\n \n # 항공편 번호를 운항 경로로 대체하기\n from pyspark.sql.functions import lit, concat\n\n features_with_route = training_yet_data.withColumn(\n 'Route',\n concat(\n training_yet_data.Origin,\n lit('-'),\n training_yet_data.Dest\n )\n )\n \n #### Bucketizer:목표변수 분류 클래스 나누기 ####\n from pyspark.ml.feature import Bucketizer\n\n splits = [-float(\"inf\"), -15.0, 0, 30.0, float(\"inf\")]\n bucketizer = Bucketizer(\n splits=splits,\n inputCol=\"ArrDelay\", #원시 목표변수\n outputCol=\"ArrDelayBucket\" #클래스 나뉜 목표변수\n )\n\n # Bucketizer 객체 저장\n bucketizer_path = \"{}/models/arrival_bucketizer_2.0.bin\".format(project_home)\n print(bucketizer_path)\n bucketizer.write().overwrite().save(bucketizer_path)\n\n # Bucketizer로 데이터 변환\n ml_bucketized_features = bucketizer.transform(features_with_route)\n \n #### StringIndexer : String 타입의 범주 값을 해당 값의 정수 번호로 변환 ####\n from pyspark.ml.feature import StringIndexer\n\n for column in [\"Carrier\", \"Origin\", \"Dest\", \"Route\"]:\n string_indexer = StringIndexer(\n inputCol=column,\n outputCol=column + \"_index\"\n )\n string_indexer_model = string_indexer.fit(ml_bucketized_features)\n ml_bucketized_features = string_indexer_model.transform(ml_bucketized_features)\n\n ml_bucketized_features = ml_bucketized_features.drop(column)\n\n # StringIndexer 객체 저장\n string_indexer_output_path = \"{}/models/string_indexer_model_{}.bin\".format(\n project_home,\n column\n )\n print(string_indexer_output_path)\n string_indexer_model.write().overwrite().save(string_indexer_output_path)\n \n #### VectorAssembler: 데이터를 벡터화 하기 ####\n from pyspark.ml.feature import VectorAssembler\n\n numeric_columns = [\"DepDelay\", \"Distance\",\n \"DayOfMonth\", \"DayOfWeek\",\n \"DayOfYear\"]\n index_columns = [\"Carrier_index\", \"Origin_index\",\n \"Dest_index\", \"Route_index\"]\n vector_assembler = VectorAssembler(\n inputCols=numeric_columns + index_columns,\n outputCol=\"Features_vec\"\n )\n training_data = vector_assembler.transform(ml_bucketized_features)\n\n # VectorAssembler 객체 저장\n vector_assembler_path = \"{}/models/numeric_vector_assembler.bin\".format(project_home)\n print(vector_assembler_path)\n vector_assembler.write().overwrite().save(vector_assembler_path)\n\n # 필요없는 컬럼 제거\n for column in index_columns:\n training_data = training_data.drop(column)\n \n\n # 모델 : 랜덤포레스트\n from pyspark.ml.classification import RandomForestClassifier\n rfc = RandomForestClassifier(\n featuresCol=\"Features_vec\",\n labelCol=\"ArrDelayBucket\",\n maxBins=4657,\n maxMemoryInMB=1024,\n numTrees = 10,\n maxDepth = 10\n )\n \n # 훈련시작\n model = rfc.fit(training_data)\n\n # 모델 객체 저장\n model_output_path = \"{}/models/spark_random_forest_classifier.flight_delays.5.0.bin\".format(\n project_home\n )\n print(model_output_path)\n model.write().overwrite().save(model_output_path)\n \n \nif __name__ == \"__main__\":\n main()","sub_path":"02_Data_Batch_Processing/02_Model_Training_And_Deployment/model_training.py","file_name":"model_training.py","file_ext":"py","file_size_in_byte":6673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"322140562","text":"import torch\nimport numpy as np\nimport os\nimport glob\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nimport torch.nn as nn\nimport torch.optim as optim\nimport copy\nimport shutil\nimport collections\nimport set_model_ctc\nfrom warpctc_pytorch import CTCLoss\nfrom random import sample\nimport h5py\nimport gc\nfrom ctc_decode import Decoder\n\n\ngpu_dtype = torch.cuda.FloatTensor\n\n\ntrain_dir_base = 'train_ctc'\nval_dir_base = 'cv_ctc'\n\ntrain_files = glob.glob(train_dir_base + '/' + '*.h5')\nval_files = glob.glob(val_dir_base + '/' + '*.h5')\ntrain_num_chunks = len(train_files)\nval_num_chunks = len(val_files)\n\nload_chunks_every = 10 # everytime load this many of .h5 data chunks into memory\n\nlayers = 4 # number of LSTM layers\nhidden_size = 256 # number of cells per direction\nnum_dirs = 2 # number of LSTM directions\n\n\n\nassert num_dirs == 1 or num_dirs == 2, 'num_dirs must be 1 or 2'\n\n\ndef _collate_fn(batch):\n\n def func(p):\n \"\"\"\n p is a tuple, p[0] is the data tensor, p[1] is the target seq label list\n data_tensor: (T, F)\n \"\"\"\n return p[0].size(0)\n\n batch = sorted(batch, reverse = True, key = func)\n longest_sample = batch[0][0]\n feat_size = longest_sample.size(1)\n minibatch_size = len(batch)\n max_seqlength = longest_sample.size(0)\n inputs = torch.zeros(minibatch_size, max_seqlength, feat_size)\n input_sizes = torch.IntTensor(minibatch_size)\n target_sizes = torch.IntTensor(minibatch_size)\n targets = []\n input_sizes_list = []\n for x in range(minibatch_size):\n sample = batch[x]\n tensor = sample[0]\n target = sample[1]\n seq_length = tensor.size(0)\n inputs[x].narrow(0, 0, seq_length).copy_(tensor)\n input_sizes[x] = seq_length\n input_sizes_list.append(seq_length)\n target_sizes[x] = len(target)\n targets.extend(target)\n targets = torch.IntTensor(targets)\n return inputs, targets, input_sizes, input_sizes_list, target_sizes\n\n\n\n\n\ndef get_loader(chunk_list, mode):\n class MyDataset(torch.utils.data.Dataset):\n def __init__(self):\n self.data_files = {}\n i = 0\n for f in chunk_list:\n if mode == 'train': print ('Loading data from %s' %f)\n with h5py.File(f, 'r') as hf:\n for grp in hf:\n self.data_files[i] = (torch.FloatTensor(np.asarray(hf[grp]['data'])), list(map(int, list(np.asarray(hf[grp]['label'])))))\n i += 1\n if mode == 'train': print ('Total %d sequences loaded' %len(self.data_files))\n\n def __getitem__(self, idx):\n return self.data_files[idx]\n\n def __len__(self):\n return len(self.data_files)\n\n dset = MyDataset()\n if mode == 'train':\n loader = DataLoader(dset, batch_size = 4, shuffle = True, collate_fn = _collate_fn, num_workers = 10, pin_memory = False)\n elif mode == 'test':\n loader = DataLoader(dset, batch_size = 4, shuffle = False, collate_fn = _collate_fn, num_workers = 10, pin_memory = False)\n else:\n raise Exception('mode can only be train or test')\n\n return loader\n\n\n\n\n\ndef train_one_epoch(model, loss_fn, optimizer, print_every = 10):\n data_list = sample(train_files, train_num_chunks)\n model.train()\n t = 0\n \n for i in range(0, train_num_chunks, load_chunks_every):\n chunk_list = data_list[i: i + load_chunks_every]\n loader_train = get_loader(chunk_list, 'train')\n for data in loader_train:\n inputs, targets, input_sizes, input_sizes_list, target_sizes = data\n batch_size = inputs.size(0)\n inputs = Variable(inputs, requires_grad=False).type(gpu_dtype)\n target_sizes = Variable(target_sizes, requires_grad=False)\n targets = Variable(targets, requires_grad=False)\n input_sizes = Variable(input_sizes, requires_grad = False)\n \n inputs = nn.utils.rnn.pack_padded_sequence(inputs, input_sizes_list, batch_first=True)\n \n \n out = model(inputs, input_sizes_list)\n \n loss = loss_fn(out, targets, input_sizes, target_sizes) # ctc loss\n loss /= batch_size\n\n if (t + 1) % print_every == 0:\n print('t = %d, loss = %.4f' % (t + 1, loss.data[0]))\n #if (t + 1 ) % 50 == 0: check_accuracy(model)\n optimizer.zero_grad()\n loss.backward()\n\n torch.nn.utils.clip_grad_norm(model.parameters(), 400) # clip gradients\n optimizer.step()\n t += 1\n loader_train.dataset.data_files.clear()\n del loader_train\n gc.collect() \n \n\n\n\n\ndef check_accuracy(model):\n total_num_errs = 0\n total_num_tokens = 0\n decoder = Decoder(space_idx = -1)\n model.eval() # Put the model in test mode (the opposite of model.train(), essentially)\n data_list = val_files\n\n for i in range(0, val_num_chunks, load_chunks_every):\n chunk_list = data_list[i: i + load_chunks_every]\n loader_val = get_loader(chunk_list, 'test')\n for data in loader_val:\n inputs, targets, input_sizes, input_sizes_list, target_sizes = data\n inputs = Variable(inputs, volatile = True, requires_grad=False).type(gpu_dtype)\n inputs = nn.utils.rnn.pack_padded_sequence(inputs, input_sizes_list, batch_first=True)\n probs = model(inputs, input_sizes_list)\n probs = probs.data.cpu()\n total_num_errs += decoder.greedy_decoder(probs, input_sizes_list, targets, target_sizes)\n total_num_tokens += sum(target_sizes)\n loader_val.dataset.data_files.clear()\n del loader_val\n gc.collect()\n acc = 1 - float(total_num_errs) / total_num_tokens\n print('Phone accuracy = %.2f' %(100 * acc ,))\n return 100 * acc\n\n\n\n\ndef adjust_learning_rate(optimizer, decay):\n for param_group in optimizer.param_groups:\n param_group['lr'] *= decay\n\n\n\n\ndef train_epochs(model, loss_fn, init_lr, model_dir):\n if os.path.exists(model_dir):\n shutil.rmtree(model_dir)\n os.makedirs(model_dir)\n\n optimizer = optim.Adam(model.parameters(), lr = init_lr) # setup the optimizer\n\n learning_rate = init_lr\n\n max_iter = 50 # maximum number of epochs\n end_halfing_inc = 0.05 # if cv accuracy increases by less than this threshold, stop training\n start_halfing_inc = 0.25 # if cv accuracy increases by less than this threshold, begin decreasing learning rate\n halfing_factor = 0.1 # new learning rate = current learning rate * halfing_factor\n\n acc_best = -99999\n count = 0 # epoch counter\n best_model_state = None\n best_op_state = None\n half_flag = False\n stop_train = False\n\n while not stop_train:\n if count > max_iter: break\n count += 1\n print (\"Starting epoch\", count)\n\n if half_flag:\n learning_rate *= halfing_factor\n adjust_learning_rate(optimizer, halfing_factor) # decay learning rate\n\n train_one_epoch(model, loss_fn, optimizer) # train one epoch\n acc = check_accuracy(model) # check accuracy\n model_path_accept = model_dir + '/epoch' + str(count) + '_lr' + str(learning_rate) + '_cv' + str(acc) + '.pkl'\n model_path_reject = model_dir + '/epoch' + str(count) + '_lr' + str(learning_rate) + '_cv' + str(acc) + '_rejected.pkl'\n\n if acc > (acc_best + start_halfing_inc): # accept model\n #if half_flag: half_flag = False\n best_model_state = model.state_dict()\n best_op_state = optimizer.state_dict()\n acc_best = acc\n model_path = model_path_accept\n torch.save(model.state_dict(), model_path)\n elif (acc > acc_best) and (not half_flag): # accept model but decay learning rate\n half_flag = True\n best_model_state = model.state_dict()\n best_op_state = optimizer.state_dict()\n acc_best = acc\n model_path = model_path_accept\n torch.save(model.state_dict(), model_path)\n elif (acc <= acc_best) and (not half_flag): # do not accept the model and decay learning rate\n model_path = model_path_reject\n torch.save(model.state_dict(), model_path)\n half_flag = True\n model.load_state_dict(best_model_state) # model back up to the previous best one\n optimizer.load_state_dict(best_op_state) # optimizer back up to the previous best one\n elif half_flag:\n if acc > (acc_best + end_halfing_inc): # still accept model\n best_model_state = model.state_dict()\n best_op_state = optimizer.state_dict()\n acc_best = acc\n model_path = model_path_accept\n torch.save(model.state_dict(), model_path)\n else:\n if acc > acc_best:\n best_model_state = model.state_dict()\n best_op_state = optimizer.state_dict()\n acc_best = acc\n model_path = model_path_accept\n torch.save(model.state_dict(), model_path)\n stop_train = True\n else:\n model_path = model_path_reject\n torch.save(model.state_dict(), model_path)\n model.load_state_dict(best_model_state)\n optimizer.load_state_dict(best_op_state)\n stop_train = True\n \n print (\"End training, best cv accuracy is:\", acc_best)\n best_path = model_dir + '/best_model' + '_cv' + str(acc_best) + '.pkl'\n torch.save(best_model_state, best_path)\n\n\n\n\nif __name__ == '__main__':\n model = set_model_ctc.Layered_RNN(rnn_input_size = 40, nb_layers = layers, rnn_hidden_size = hidden_size, bidirectional = True if num_dirs==2 else False, batch_norm = True, num_classes = 61) #the model will add 1 to the num_classes for the blank label automatically\n model = model.type(gpu_dtype)\n loss_fn = CTCLoss()\n train_epochs(model, loss_fn, 1e-3, 'weights_ctc')\n\n\n\n","sub_path":"train_ctc.py","file_name":"train_ctc.py","file_ext":"py","file_size_in_byte":9993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62161423","text":"import pygame\n\nfrom random import randint\n\n__version__ = \"\" # Esta variable es auto explicatoria, no es algo obligatorio, es solo para que el programa quede mejor\n\npygame.init() # Inicializamos pygame\n\nget_ticks = pygame.time.get_ticks\n\nfuente = pygame.font.SysFont(\"Arial\", 30) # Creamos la fuente para el score\n\nrectangles = [] # Creamos la lista de rectangulos\n\nfps = pygame.time.Clock() # Creamos el el reloj que posteriormente vamos a usar\n\nclass Rectangle(pygame.sprite.Sprite):\n\n\tall_rectangles = pygame.sprite.Group()\n\n\tdef __init__(self):\n\n\t\tpygame.sprite.Sprite.__init__(self)\n\n\t\tself.image = pygame.image.load(\"images/zombie.png\").convert()\n\n\t\tself.rect = self.image.get_rect()\n\n\t\tRectangle.all_rectangles.add(self)\n\n\t\tself.start()\n\t\t\n\t\trectangles.append(self) # Agregamos la instancia de la clase a la lista de rectangulos\n\n\tdef start(self):\n\t\t\n\t\trandom_X = randint(0, 600-75) # random X\n\t\t\n\t\trandom_Y = randint(0, 800-75) # random Y\n\t\t\n\t\tself.rect.top, self.rect.left = random_X, random_Y # Rectangulo.top, Rectangulo.left = X Random, Y Random\n\n\t\tself.check()\n\n\tdef check(self):\n\n\t\tfor rectangle in rectangles:\n\n\t\t\tif self.rect.colliderect(rectangle):\n\n\t\t\t\tself.start()\n\nclass Cursor(): # Esta es la clase que maneja el mouse\n\n\tdef __init__(self):\n\t\n\t\tself.rect = pygame.Rect(0, 0, 1, 1) # Esto genera un rectangulo de 1 pixel de ancho y 1 pixel de alto\n\ncursor = Cursor() # Instanciamos la clase cursor\n\ndef window(caption=\"Window\"): # Esta funcion es la que genera la ventana\n\n\tglobal icon\n\n\tventana = pygame.display.set_mode((800, 600)) # Esto crea una superficie de 800 de alto y 600 de alto\n\n\ticonpath = \"images/icon.png\"\n\n\ticon = pygame.image.load(iconpath).convert()\n\n\tpygame.display.set_icon(icon)\n\t\n\tpygame.display.set_caption(caption) # Esto le pone el titulo a la ventana, si no hay titulo, por defecto el titulo es Window\n\t\t\n\treturn ventana # Esto devuelve la ventana con el titulo\n\ndef generate_rect(number_of_rects=1): # Esta funcion genera 15 rectangulos\n\n\tfor x in range(number_of_rects): # Repite 15 veces\n\n\t\tRectangle() # Instanciamos un rectangulo\n\nscore = 0 # Esta es la variable que contiene el puntaje que se muestra arriba a la izquierda de la ventana\n\nventana = window(\"Rectangle Killer \" + __version__) # Creamos la ventana con la funcion y le mandamos el titulo que es: \"Rectangle Killer\" + \"0.9\"\n\nlooping = True # Corriendo\n\ndead = False\n\nwin = False\n\nlast = get_ticks()\n\nnow = get_ticks()\n\n__delay__ = 300\n\n# ----------------------------- MAINLOOP ----------------------------- #\n\nwhile looping:\n\n\t#BACKGROUND\n\t\n\tventana.fill((255, 255, 255)) # Esto es el fondo\n\t\n\t#BACKGROUND\n\t\n\t#CURSOR\n\t\n\tcursor.rect.left, cursor.rect.top = pygame.mouse.get_pos() # CursorX, CursorY = pygame.mouse.get_pos <--- nos retorna una tupla con la posicion del mouse\n\t\n\t#CURSOR\n\t\n\t#PROCESS\n\n\tif len(rectangles) < 20 and not dead and not win:\n\n\t\tnow = get_ticks()\n\n\t\tif now - last > __delay__:\n\n\t\t\tlast = now\n\n\t\t\tgenerate_rect()\n\n\telse: \n\n\t\tdead = True\n\n\t\tfor rectangle in rectangles:\n\n\t\t\trectangles.remove(rectangle) # Removemos el rectangulo de la lista de rectangulos\n\n\t\t\tRectangle.all_rectangles.remove(rectangle)\n\n\t\t\tdel rectangle # Eliminamos definitivamente el rectangulo\n\n\t\tfuente = pygame.font.SysFont(\"Arial\", 50)\n\n\t\tscore_text = fuente.render(\" The zombies ate your brain\", 0, (255, 0, 0)) # Actualizamos el score\n\n\tif score == 50:\n\n\t\twin = True\n\n\t\tfor rectangle in rectangles:\n\n\t\t\trectangles.remove(rectangle) # Removemos el rectangulo de la lista de rectangulos\n\n\t\t\tRectangle.all_rectangles.remove(rectangle)\n\n\t\t\tdel rectangle # Eliminamos definitivamente el rectangulo\n\n\t\tfuente = pygame.font.SysFont(\"Arial\", 100)\n\n\t\tscore_text = fuente.render(\" You win!\", 0, (0, 255, 0)) # Actualizamos el score\n\n\tfor event in pygame.event.get(): # For evento en la lista de eventos de pygame\n\t\n\t\tif event.type == pygame.QUIT: # Si el evento es cerrar la ventana\n\t\t\n\t\t\tlooping = False # Dejamos de iterar\n\t\t\t\n\t\tif event.type == pygame.MOUSEBUTTONDOWN: # Si el evento es que un boton del mouse se ha presionado\n\n\t\t\tmb1, mb2, mb3 = pygame.mouse.get_pressed()\n\n\t\t\tif mb1 and mb2 or mb3:\n\n\t\t\t\tpass\n\n\t\t\telif mb1:\n\n\t\t\t\tfor rectangle in rectangles: # Por cada rectangulo en la lista de rectangulos\n\n\t\t\t\t\tif cursor.rect.colliderect(rectangle.rect): # Si el rectangulo del cursor esta colisionando con este rectangulo\n\n\t\t\t\t\t\tscore += 1 # Sumamos uno al score\n\t\t\t\t\t\n\t\t\t\t\t\trectangles.remove(rectangle) # Removemos el rectangulo de la lista de rectangulos\n\n\t\t\t\t\t\tRectangle.all_rectangles.remove(rectangle)\n\n\t\t\t\t\t\tdel rectangle # Eliminamos definitivamente el rectangulo\n\t\t\t\n\n\t#PROCESS\n\t\n\t#DRAW \n\n\tRectangle.all_rectangles.draw(ventana)\n\n\t#DRAW\n\n\t#TEXT\n\n\tif not dead and not win:\n\n\t\tscore_text = fuente.render(\"Score: \" + str(score), 0, (randint(0, 255), randint(0, 255), randint(0, 255))) # Actualizamos el score\n\n\tif dead or win:\n\n\t\tventana.blit(score_text, (0, 200)) # Mostramos en pantalla el score\n\n\telse:\n\n\t\tventana.blit(score_text, (0, 0)) # Mostramos en pantalla el score\n\n\t#TEXT\n\t\n\t#WINDOW\n\t\n\tfps.tick(60) # Limitamos a 60 frames por segundo\n\t\n\tpygame.display.flip() # Actualizamos la pantalla\n\t\n\t#WINDOW\n# -------------------------------- END -------------------------------- #\n\npygame.quit() # Salimos de la ventana generada por pygame\n\n\"\"\"\n#########################################################################################################\nTO DO:\n\n- Que se generen mas rectangulos cada cierto tiempo antes de que se terminen los que estan en pantalla √\n\n- Si se llena la pantalla game over √\n\n- Implementar victoria √\n\n- refactoring:\n.constants.py √\n.rectangles.py X\n.game.py X\n.main.py X \n##########################################################################################################\n\"\"\"","sub_path":"workspace/pygamecode/practica/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":5847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"180268535","text":"###!/usr/bin/python3\n \n# import Adafruit IO REST client.\nfrom Adafruit_IO import Client, Feed, RequestError\nfrom Adafruit_IO import MQTTClient\nimport time, serial, sys, board, digitalio\nfrom time import sleep\nindata = []\nupdateStateFlag = False\n\n# Set to your Adafruit IO key.\n# Remember, your key is a secret,\n# so make sure not to publish it when you publish this code!\nADAFRUIT_IO_KEY = 'e2cac4fce1de4ebb802250a704153fa0'\n\n# Set to your Adafruit IO username.\n# (go to https://accounts.adafruit.com to find your username)\nADAFRUIT_IO_USERNAME = 'trongle'\n# Set to the ID of the feed to subscribe to for updates.\nRelay_1 = 'relay1'\nRelay_2 = 'relay2'\nRelay_3 = 'relay3'\nRelay_4 = 'relay4'\nRelay_5 = 'relay5'\nThrehold = 'threhold'\nSettime = 'settime'\n\nprint(\"IoT Farm Project - Graduation Project\")\nprint(\"Adafruit MQTT connected - >>...Start...<< \")\ndef connected(client):\n # Subscribe to changes on a feed named Counter.\n print('Subscribing to Feed {0}'.format(Relay_1))\n client.subscribe(Relay_1)\n\n print('Subscribing to Feed {0}'.format(Relay_2))\n client.subscribe(Relay_2)\n\n print('Subscribing to Feed {0}'.format(Relay_3))\n client.subscribe(Relay_3)\n\n print('Subscribing to Feed {0}'.format(Relay_4))\n client.subscribe(Relay_4)\n\n print('Subscribing to Feed {0}'.format(Relay_5))\n client.subscribe(Relay_5)\n\n print('Subscribing to Feed {0}'.format(Threhold))\n client.subscribe(Threhold)\n\n print('Subscribing to Feed {0}'.format(Settime))\n client.subscribe(Settime)\n\ndef disconnected(client):\n \"\"\"Disconnected function will be called when the client disconnects.\"\"\"\n sys.exit(1)\n\ndef message(client, feed_id, payload):\n \"\"\"Message function will be called when a subscribed feed has a new value.\n The feed_id parameter identifies the feed, and the payload parameter has\n the new value.\n \"\"\"\n print('Feed {0} received new value: {1}'.format(feed_id, payload))\n\n #Threhold detect value\n if(feed_id == 'threhold'):\n print('Temperature Threhold value: ', payload)\n print('Set Temperature threshold to Device\\n')\n ser.write(('threhold'+ payload + '\\r').encode()) \n sleep(1)\n\n if(feed_id == 'settime'):\n print('Timer Threhold value: ', payload)\n print('Set Timer to Device\\n')\n ser.write(('timerSet'+ payload + '\\r').encode()) \n \n #Relay 1\n if(feed_id == 'relay1'):\n if(payload == '1'):\n print('Turn on Relay 1\\n')\n ser.write(('A1\\r').encode())\n sleep(1)\n\n elif(payload == '0'):\n print('Turn off Relay 1\\n')\n ser.write(('A0\\r').encode())\n sleep(1)\n\n #Relay 2\n if(feed_id == 'relay2'):\n if(payload == '1'):\n print('Turn on Relay 2\\n')\n ser.write(('B1\\r').encode())\n sleep(1)\n\n elif(payload == '0'):\n print('Turn off Relay 2\\n')\n ser.write(('B0\\r').encode())\n sleep(1)\n\n #Relay 3\n if(feed_id == 'relay3'):\n if(payload == '1'):\n print('Turn on Relay 3\\n')\n ser.write(('C1\\r').encode())\n sleep(1)\n\n elif(payload == '0'):\n print('Turn off Relay 3\\n')\n ser.write(('C0\\r').encode())\n sleep(1)\n\n #Relay 4\n if(feed_id == 'relay4'):\n if(payload == '1'):\n print('Turn on Relay 4\\n')\n ser.write(('D1\\r').encode())\n sleep(1)\n\n elif(payload == '0'):\n print('Turn off Relay 4\\n')\n ser.write(('D0\\r').encode())\n sleep(1)\n #Relay 5\n if(feed_id == 'relay5'):\n if(payload == '1'):\n print('Turn on Relay 5\\n')\n ser.write(('E1\\r').encode())\n sleep(1)\n\n elif(payload == '0'):\n print('Turn off Relay 5\\n')\n ser.write(('E0\\r').encode())\n sleep(1)\n\n \n \n# Create an MQTT client instance.\nclient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)\naio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)\n\n# Create an MQTT client instance.\nclient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)\n\n##try: # if we have a 'type' feed\nTemperature = aio.feeds('temperature')\nHumidity = aio.feeds('humidity')\nRelay1 = aio.feeds('relay1')\nRelay2 = aio.feeds('relay2')\nRelay3 = aio.feeds('relay3')\nRelay4 = aio.feeds('relay4')\nRelay5 = aio.feeds('relay5')\nthrehold = aio.feeds('threhold')\nsettime = aio.feeds('settime')\nFoodremain = aio.feeds('foodremain')\n##except RequestError: # create a type feed\n## #Sensor Feeds \n## feed = Feed(name=\"temperature\")\n## Temperature = aio.create_feed(feed)\n##\n## feed = Feed(name=\"humidity\")\n## Humidity = aio.create_feed(feed)\n##\n## feed = Feed(name=\"gas\")\n## Gas = aio.create_feed(feed)\n##\n## feed = Feed(name=\"fire\")\n## Fire = aio.create_feed(feed)\n## \n## #Relay Feeds \n## feed = Feed(name=\"relay1\")\n## Relay1 = aio.create_feed(feed)\n##\n## feed = Feed(name=\"relay2\")\n## Relay2 = aio.create_feed(feed)\n##\n## feed = Feed(name=\"relay3\")\n## Relay3 = aio.create_feed(feed)\n##\n## feed = Feed(name=\"relay4\")\n## Relay4 = aio.create_feed(feed)\n\n\nloop_delay = 5 \nser = serial.Serial(\n\tport = '/dev/ttyAMA0',\n\tbaudrate = 115200,\n\tparity = serial.PARITY_NONE,\n\tstopbits = serial.STOPBITS_ONE,\n\tbytesize = serial.EIGHTBITS,\n\ttimeout = 1\n)\n\n\n \n##def findFromStringData(s):\n## for item in indata:\n## if(item.find('temp')) != -1:\n## temp = item[5:]\n## print('Temperature is: ' +temp)\n##\n## if(item.find('humi')) != -1:\n## humid = item[5:]\n## print('Humidity is: ' +humid)\n##\n## if(item.find('gas ')) != -1:\n## gas = item[5:]\n## print('Gas is: ' +gas)\n##\n## if(item.find('fire')) != -1:\n## fire = item[5:]\n## print('Fire is: ' +fire)\n## \ndef relaySwitch():\n #Relay 1\n relay1Data = aio.receive(Relay1.key)\n relay2Data = aio.receive(Relay2.key)\n relay3Data = aio.receive(Relay3.key)\n relay4Data = aio.receive(Relay4.key)\n if int(relay1Data.value) == 1:\n print('received Relay 1 <- ON\\n')\n## string1 = \"Relay 1 On\" + \"\\r\"\n ser.write((\"Relay 1 On\\r\").encode())\n time.sleep(1.5)\n elif int(relay1Data.value) == 0:\n print('received Relay 1 <- OFF\\n')\n## string1 = \"Relay 1 Off\" + \"\\r\"\n ser.write((\"Relay 1 Off\\r\").encode())\n time.sleep(1.5)\n \n #Relay 2\n \n if int(relay2Data.value) == 1:\n print('received Relay 2 <- ON\\n')\n## string2 = \"Relay 2 On\" + \"\\r\"\n ser.write((\"Relay 2 On\\r\").encode())\n time.sleep(1.5)\n elif int(relay2Data.value) == 0:\n print('received Relay 2 <- OFF\\n')\n## string2 = \"Relay 2 Off\" + \"\\r\"\n ser.write((\"Relay 2 Off\\r\").encode())\n time.sleep(1.5)\n \n #Relay 3\n \n if int(relay3Data.value) == 1:\n print('received Relay 3 <- ON\\n')\n## string3 = \"Relay 3 On\" + \"\\r\"\n ser.write((\"Relay 3 On\\r\").encode())\n time.sleep(1.5)\n elif int(relay3Data.value) == 0:\n print('received Relay 3 <- OFF\\n')\n## string3 = \"Relay 3 Off\" + \"\\r\"\n ser.write((\"Relay 3 Off\\r\").encode())\n time.sleep(1.5)\n \n #Relay 4\n \n if int(relay4Data.value) == 1:\n print('received Relay 4 <- ON\\n')\n## string4 = \"Relay 4 On\" + \"\\r\"\n ser.write((\"Relay 4 On\\r\").encode())\n time.sleep(1.5)\n elif int(relay4Data.value) == 0:\n print('received Relay 4 <- OFF\\n')\n## string4 = \"Relay 4 Off\" + \"\\r\"\n ser.write((\"Relay 4 Off\\r\").encode())\n time.sleep(1.5)\nclient.on_connect = connected\nclient.on_disconnect = disconnected\nclient.on_message = message\n\n# Connect to the Adafruit IO server.\nclient.connect()\nclient.loop_background()\n\n\ntry:\n while (True):\n## ser.write(('SS\\r').encode())\n time.sleep(1)\n## time.sleep(0.5)\n## if(updateStateFlag == True):\n## countValue = 6\n## elif(updateStateFlag == False):\n## countValue = 5\n if(ser.in_waiting >0):\n uart = ser.readline()\n data = uart.decode('utf-8')\n data = data.rstrip()\n if data:\n indata.append(data)\n if len(indata) == 5:\n print(indata)\n print('sending data to adafruit io...')\n for item in indata:\n \n if(item.find('temp')) != -1:\n temp = item[5:]\n print('Temperature: ', temp)\n aio.send(Temperature.key, temp)\n \n if(item.find('humi')) != -1:\n humid = item[5:]\n print('humidity: ', humid)\n aio.send(Humidity.key, humid)\n \n## if(item.find('gas ')) != -1:\n## gas = item[5:]\n## print('gas: ', gas)\n## aio.send(Gas.key, gas)\n\n\n if(item.find('food')) != -1:\n foodremain = item[5:]\n print('foodremain: ', foodremain)\n aio.send(Foodremain.key, foodremain)\n \n if(item.find('relay1')) != -1:\n relay1 = item[7:]\n print('Relay 1 update value: ', relay1)\n aio.send(Relay1.key, relay1)\n\n if(item.find('relay2')) != -1:\n relay2 = item[7:]\n print('Relay 2 update value: ', relay2)\n aio.send(Relay2.key, relay2)\n\n if(item.find('relay3')) != -1:\n relay3 = item[7:]\n print('Relay 3 update value: ', relay3)\n aio.send(Relay3.key, relay3)\n\n if(item.find('relay4')) != -1:\n relay4 = item[7:]\n print('Relay 4 update value: ', relay4)\n aio.send(Relay4.key, relay4)\n \n indata = [] \n countValue = False\n time.sleep(4)\n\nexcept KeyboardInterrupt:\n print('DOne')\n\nfinally:\n ser.close()\n\n\n","sub_path":"RASPBERYY_IOT.py","file_name":"RASPBERYY_IOT.py","file_ext":"py","file_size_in_byte":10587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"554596304","text":"\"\"\"py.test configuration file\n\nThis file is required because tests in the Tests folder expect\nthe PDB folder to be relative to the test file.\n\"\"\"\nimport atexit\nimport logging\nimport os\nimport os.path as op\n\nimport pytest\n\nlogger = logging.getLogger(__name__)\n\nCWD = os.getcwd()\nTEST_DIR = op.dirname(op.abspath(__file__))\nif CWD != TEST_DIR:\n os.chdir(TEST_DIR)\n atexit.register(os.chdir, CWD)\n\n\ndef parametrize(arg_string, arg_list):\n \"\"\"\n Args:\n arg_string: Comma-separated string of arguments (e.g. 'pdb_id, pdb_type').\n arg_list: List of arguments or argument dictionaries.\n \"\"\"\n logger.info(\"arg_string: %s\", arg_string)\n logger.info(\"arg_list: %s\", arg_list)\n if \",\" in arg_string:\n keys = arg_string.replace(\" \", \"\").split(\",\")\n args = [tuple(r[k] for k in keys) for r in arg_list]\n else:\n key = arg_string.replace(\" \", \"\")\n if isinstance(arg_list[0], dict) and key in arg_list[0]:\n args = [r[key] for r in arg_list]\n else:\n args = arg_list\n logger.info(\"args: %s\", args)\n return pytest.mark.parametrize(arg_string, args)\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"309309649","text":"from django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns(\n '',\n url(r'^$', 'movies.views.search'),\n url(r'^search/$', 'movies.views.search'),\n\n url(r'^list/(?P[\\w-]+)/$', 'movies.views.list_view'),\n url(r'^people/$', 'movies.views.people'),\n url(r'^friends/$', 'movies.views.friends'),\n url(r'^feed/(?P[\\w-]+)/$', 'movies.views.feed'),\n url(r'^people/(?P[\\w\\d]+)/(?P[\\w-]+)$',\n 'movies.views.list_username'),\n url(r'^recommendation/$', 'movies.views.recommendation'),\n url(r'^preferences/$', TemplateView.as_view(template_name='preferences.html')),\n\n url(r'^remove-record/$', 'movies.views.ajax_remove_record'),\n url(r'^search-movie/$', 'movies.views.ajax_search_movie'),\n url(r'^add-to-list/$', 'movies.views.ajax_add_to_list'),\n url(r'^add-to-list-from-db$', 'movies.views.ajax_add_to_list_from_db'),\n url(r'^save-comment/$', 'movies.views.ajax_save_comment'),\n url(r'^change-rating/$', 'movies.views.ajax_change_rating'),\n url(r'^apply-setting/$', 'movies.views.ajax_apply_settings'),\n # url(r'^download/$', 'movies.views.ajax_download'),\n url(r'^upload-photo-to-wall/$', 'movies.views.ajax_upload_photo_to_wall'),\n url(r'^save-preferences/$', 'movies.views.ajax_save_preferences'),\n\n url(r'^login/$', 'django.contrib.auth.views.login',\n {'template_name': 'login.html'}),\n url(r'^logout/$', 'movies.views.logout_view'),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"movies_project/movies_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"304874907","text":"from Student import Student\r\n\r\n\r\nclass Magistrant(Student):\r\n\r\n def __init__(self, name='Noname', gradeBook='gradeBook', course='course'):\r\n super().__init__(name, gradeBook, course)\r\n self.health = 100\r\n\r\n def get_credit(self):\r\n if self.mind > 0:\r\n self.happiness += 20\r\n self.money += 1000 #стипендия\r\n self.health -= 30\r\n else:\r\n self.health += 30\r\n self.happiness -= 30\r\n print('И так сойдет, все равно не отчислят')\r\n return [self.mind, self.happiness, self.money, self.health]\r\n\r\n def study(self):\r\n self.money -= 100 #(не ходит на работу из-за пар)\r\n self.mind += 40\r\n if self.money <= 0:\r\n print('ПОРА ИДТИ РАБОТАТЬ')\r\n return [self.money, self.mind]\r\n","sub_path":"Magistrant.py","file_name":"Magistrant.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"157056652","text":"__author__ = 'Theodore LaGrow'\n__author__ = 'Jacob Bieker'\n# CIS 410/510\n# Homework #4\n# Daniel Lowd\n# April 2016\n#\n# Language: Python 3.5x\n#\n# Notes from HW4:\n# Worked with Robert Marcy on the implimentation of the alogithm and logic behind __mult__\n#\n# Notes from HW5:\n# (these are the notes)\n#\n# TEMPLATE CODE\nimport sys\nimport tokenize\nimport functools\nfrom collections import Counter\nimport operator\n\n#\n# FACTOR CLASS\n#\n\nclass Factor(dict):\n \"\"\"\n Ranges = cardinality\n vals = phi\n scope =\n \"\"\"\n def __init__(self, scope_, vals_, range_):\n self.scope = scope_\n self.vals = vals_\n self.ranges = range_\n\n def stride(self, l):\n \"\"\" Used to calculate the stride of each variable \"\"\"\n if l not in self.scope:\n return 0\n s = 1\n self.scope.reverse() # Needs to reverse the elements to iterate cleaner\n for i in self.scope:\n if (i == l):\n self.scope.reverse() # Reverse back\n return s\n s *= self.ranges[i]\n\n # print \"stride: \", s # testing\n\n def __mul__(self, other):\n \"\"\" Method to brute force the multiplication \"\"\"\n \"\"\" WARNING: do not try to impliment this function on alarm... \"\"\"\n\n new_scope = []\n for scope in self.scope:\n new_scope.append(scope)\n for scope in other.scope:\n if scope not in self.scope:\n new_scope.append(scope)\n # print \"new_scope\", new_scope\n\n\n new_ranges = {}\n for i in new_scope:\n if (i in self.scope):\n # print \"self.ranges: \", self.ranges # testing\n new_ranges[i] = self.ranges[i]\n elif (i in other.scope):\n new_ranges[i] = other.ranges[i]\n\n\n # print \"new_range: \", new_ranges # testing\n\n\n\n\n x1Ux2_scope = len(new_scope)\n # print \"x1Ux2_scope\", x1Ux2_scope # testing\n\n x1Ux2_cardinality_values = 1\n for key in new_ranges:\n x1Ux2_cardinality_values *= new_ranges[key]\n # print \"x1Ux2_cardinality_values\", x1Ux2_cardinality_values # testing\n\n\n \"\"\" This is the start the implimentation of Alogithm 10.A.1 on pg. 359 \"\"\"\n\n j, k = 0, 0 # Line 1\n assignment = []\n psi_values = []\n\n for l in range(x1Ux2_scope): # Line 2\n assignment.append(0) # Line 3\n\n for i in range(x1Ux2_cardinality_values - 1): # Line 4\n psi_values.append(self.vals[j] * other.vals[k]) # Line 5\n\n for l in new_scope: # Line 6 (modified from the actual algoithem)\n\n assignment[new_scope.index(l)] += 1 # Line 7\n\n if assignment[new_scope.index(l)] == new_ranges[l]: # Line 8\n assignment[new_scope.index(l)] = 0 # Line 9\n\n j = j - (new_ranges[l] - 1) * Factor.stride(self, l) # Line 10\n k = k - (new_ranges[l] - 1) * Factor.stride(other, l) # Line 11\n\n else: # Line 12\n j = j + Factor.stride(self, l) # Line 13\n k = k + Factor.stride(other, l) # Lin3 14\n break # Line 15\n\n\n # print psi_values # testing\n\n psi_values.append(self.vals[j] * other.vals[k])\n new_scope.reverse()\n # END PLACEHOLDER CODE\n return Factor(new_scope, psi_values, new_ranges) # Line 16\n\n def __rmul__(self, other): # never used\n return self * other\n\n def __imul__(self, other): # never used\n return self * other\n\n\ndef sum_out(factor, variable):\n '''\n Choose a random variable from all of the remaining variables that can be summed out\n Collect all the factors that have this random variable and multiply them together\n Sum out the chosen random variable from the resulting factor by summing all the variations of the chosen random\n variable for each combination of other random variables\n Repeat\n :param factor: list of factors that contain the variable with the least values\n :param variable:\n :return:\n '''\n debug = True\n new_vals = [x for x in factor.scope if x != variable]\n if debug: print(\"New Vals: \", new_vals)\n\n new_factor = Factor(new_vals, factor.vals, factor.ranges)\n\n if len(new_vals) > 0:\n val_index = factor.scope.index(variable)\n if debug: print(\"Var Index: \", val_index)\n\n used_val = [False for x in range(len(factor.scope))]\n\n if debug:\n print(\"used var: \", used_val)\n print(\"stride: \", factor.stride(factor.scope[val_index]), \", card: \", factor.vals[val_index])\n\n psi = []\n for i in range(len(new_factor.scope)):\n psi.append(0)\n\n start = 0\n for k in range(len(factor.scope)):\n if used_val[k] == False:\n start = k\n break\n for j in range(factor.ranges[factor.scope[val_index]]):\n if debug:\n print(\"start: \", start, \" stride: \", factor.stride(val_index), \" j: \", j)\n psi[i] += factor.vals[start + factor.stride(val_index) * j]\n used_val[start + factor.stride(val_index) * j] = True\n if debug:\n print(\"psi: \", i, \" \", psi[i])\n\n new_factor.vals = psi[:]\n return new_factor\n\n\n#\n# READ IN MODEL FILE\n#\n\n# Read in all tokens from stdin. Save it to a (global) buf that we use\n# later. (Is there a better way to do this? Almost certainly.)\ncurr_token = 0\ntoken_buf = []\n\n\ndef read_tokens():\n global token_buf\n for line in sys.stdin:\n token_buf.extend(line.strip().split())\n # print \"Num tokens:\",len(token_buf)\n\n\ndef next_token():\n global curr_token\n global token_buf\n curr_token += 1\n return token_buf[curr_token - 1]\n\n\ndef next_int():\n return int(next_token())\n\n\ndef next_float():\n return float(next_token())\n\n\ndef read_model():\n # Read in all tokens and throw away the first (expected to be \"MARKOV\")\n read_tokens()\n s = next_token()\n\n # Get number of vars, followed by their ranges\n num_vars = next_int()\n var_ranges = [next_int() for i in range(num_vars)]\n\n # Get number and scopes of factors\n num_factors = int(next_token())\n factor_scopes = []\n for i in range(num_factors):\n factor_scopes.append([next_int() for i in range(next_int())])\n\n # Read in all factor values\n factor_vals = []\n for i in range(num_factors):\n factor_vals.append([next_float() for i in range(next_int())])\n\n ####################################################################\n # Get variable for the factor scopes\n # This is needed to get the ranges in the correct format\n\n var_dict = dict(zip(range(num_vars), var_ranges))\n factor_ranges = []\n for k in range(num_factors):\n factor_ranges.append({j: var_dict[j] for j in factor_scopes[k]})\n\n ####################################################################\n\n\n # Hella DEBUGing\n # print \"Num vars: \",num_vars\n # print \"Ranges: \",var_ranges\n # print \"var_dict: \", var_dict\n # print \"factor_ranges: \", factor_ranges\n print(\"Scopes: \", factor_scopes)\n # print \"Values: \",factor_vals\n return [Factor(s, v, r) for (s, v, r) in zip(factor_scopes, factor_vals, factor_ranges)]\n\n\n#\n# MAIN PROGRAM\n#\n\ndef main():\n factors = read_model()\n new_factors = []\n # loop through factors, choosing random variable to sum out and sending those factors to sum_out\n total_scope = []\n for factor in factors:\n total_scope.append(factor.scope)\n #print(total_scope)\n\n counted = Counter([item for scope in total_scope for item in scope])\n sorted_x = sorted(counted.items(), key=operator.itemgetter(1))\n print(sorted_x)\n for variable in sorted_x:\n factors_subset = [x for x in factors if variable[0] in x.scope]\n if len(factors_subset) < 2:\n continue\n new_factors = [x for x in factors if x not in factors_subset]\n factored_subset = functools.reduce(Factor.__mul__, factors_subset)\n if len(factored_subset.scope) == 1:\n new_factors.append(Factor([], factored_subset.vals, []))\n elif len(factored_subset.scope) > 1:\n print(factored_subset.scope)\n new_factors.append(sum_out(factored_subset, variable[0]))\n else:\n new_factors.append(factored_subset)\n if len(new_factors) == 1:\n break\n factors = new_factors\n\n # f = functools.reduce(Factor.__mul__, new_factors)\n # Compute Z by brute force... BRUUUUTTTTEEEEEEE\n f = functools.reduce(Factor.__mul__, factors) # Nice function in Python! Whoot whoot!\n #for variable in sorted_x:\n # f = sum_out(f, variable[0])\n z = sum(f.vals)\n print(\"Z = \", z)\n return\n\n\nmain()\n","sub_path":"hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":8802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"79840244","text":"from xorm.columns import Column\nfrom xorm.constraints import *\nfrom xorm.data_type import *\nfrom xorm.log import log\nfrom xorm.model import Model\nfrom xorm.relations import *\nfrom xorm.sql import sql\nfrom xorm.table import Table\n\n\nclass MetaData:\n def __init__(self, db):\n self.db = db\n self.tables = {}\n self.sql = sql[db.db.engine.name]\n self.models = {}\n self.database = self.db.db.engine.url.database\n\n def register(self, model):\n if not issubclass(model, Model):\n raise TypeError\n table_name = model.table_name\n self.models[table_name] = model\n columns = []\n for field_name, field in model.fields.items():\n column = Column(field_name, field)\n columns.append(column)\n Table(table_name, self, *columns)\n log.info('Registered table: {}'.format(table_name))\n\n def sync(self):\n for model_name, model in self.models.items():\n for field_name, field in model.fields.items():\n if isinstance(field, ManyToOne):\n table_name = model_name\n column_name = '{}_id'.format(table_name)\n ref_table_name = field.related_field.table_name\n ref_column_name = '{}_id'.format(ref_table_name)\n table = Table('{}_{}'.format(table_name, field_name),\n self,\n Column(column_name, String()),\n Column(ref_column_name, String())\n )\n table.constraints.append(ForeignKeyConstraint(self.tables[table_name].columns[field_name],\n table.columns[column_name]))\n table.constraints.append(ForeignKeyConstraint(self.tables[ref_table_name].columns['id'],\n table.columns[ref_column_name]))\n table.constraints.append(UniqueConstraint(table.columns[ref_column_name]))\n log.info('Registered ManyToOne Relation: {}'.format('{}_{}'.format(table_name, field_name)))\n elif isinstance(field, OneToOne):\n table_name = model_name\n column_name = '{}_id'.format(table_name)\n ref_table_name = field.related_field.table_name\n ref_column_name = '{}_id'.format(ref_table_name)\n table = Table('{}_{}'.format(table_name, field_name),\n self,\n Column(column_name, String()),\n Column(ref_column_name, String())\n )\n table.constraints.append(ForeignKeyConstraint(self.tables[table_name].columns[field_name],\n table.columns[column_name]))\n table.constraints.append(ForeignKeyConstraint(self.tables[ref_table_name].columns['id'],\n table.columns[ref_column_name]))\n table.constraints.append(UniqueConstraint(table.columns[column_name]))\n table.constraints.append(UniqueConstraint(table.columns[ref_column_name]))\n log.info('Registered OneToOne Relation: {}'.format('{}_{}'.format(table_name, field_name)))\n elif isinstance(field, ManyToMany):\n table_name = model_name\n column_name = '{}_id'.format(table_name)\n ref_table_name = field.related_field.table_name\n ref_column_name = '{}_id'.format(ref_table_name)\n table = Table('{}_{}'.format(table_name, field_name),\n self,\n Column(column_name, String()),\n Column(ref_column_name, String())\n )\n table.constraints.append(ForeignKeyConstraint(self.tables[table_name].columns[field_name],\n table.columns[column_name]))\n table.constraints.append(ForeignKeyConstraint(self.tables[ref_table_name].columns['id'],\n table.columns[ref_column_name]))\n log.info('Registered ManyToMany Relation: {}'.format('{}_{}'.format(table_name, field_name)))\n\n def reflect(self):\n sql = \"select * from information_schema.tables where table_schema = '{}'\"\n sql_format = sql.format(self.database)\n source_tables = self.db.query(sql_format).all()\n\n for source_table in source_tables:\n table = Table(source_table.TABLE_NAME, self)\n\n sql = \"select * from information_schema.columns where table_schema = '{}' AND TABLE_NAME='{}'\"\n sql_format = sql.format(source_table.TABLE_SCHEMA, source_table.TABLE_NAME)\n source_columns = self.db.query(sql_format).all()\n for source_column in source_columns:\n column = Column(source_column.COLUMN_NAME, source_column.COLUMN_TYPE.upper(),\n not_null=(True if source_column.IS_NULLABLE == 'YES' else False),\n default=source_column.COLUMN_DEFAULT)\n column.table = table\n table.columns[column.name] = column\n\n sql = \"\"\"SELECT INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_TYPE, INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME, INFORMATION_SCHEMA.KEY_COLUMN_USAGE.TABLE_NAME AS 'table', INFORMATION_SCHEMA.KEY_COLUMN_USAGE.COLUMN_NAME AS 'column', INFORMATION_SCHEMA.KEY_COLUMN_USAGE.REFERENCED_TABLE_NAME AS 'ref_table' , INFORMATION_SCHEMA.KEY_COLUMN_USAGE.REFERENCED_COLUMN_NAME AS 'ref_column' FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS ON INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_SCHEMA = INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_SCHEMA AND INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME = INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME WHERE INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_SCHEMA = '{schema}' AND INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_SCHEMA = '{schema}'\"\"\"\n sql_format = sql.format(schema=self.database)\n source_constraints = self.db.query(sql_format).all()\n\n for source_constraint in source_constraints:\n if source_constraint.CONSTRAINT_TYPE == 'PRIMARY KEY':\n column_name = source_constraint.column\n table_name = source_constraint.table\n PrimaryKeyConstraint(self.tables[table_name].columns[column_name])\n\n elif source_constraint.CONSTRAINT_TYPE == 'UNIQUE':\n column_name = source_constraint.column\n table_name = source_constraint.table\n UniqueConstraint(self.tables[table_name].columns[column_name])\n\n elif source_constraint.CONSTRAINT_TYPE == 'FOREIGN KEY':\n table_name = source_constraint.table\n column_name = source_constraint.column\n ref_table_name = source_constraint.ref_table\n ref_column_name = source_constraint.ref_column\n ForeignKeyConstraint(self.tables[table_name].columns[column_name],\n self.tables[ref_table_name].columns[ref_column_name])\n","sub_path":"xorm/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":7580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"391939412","text":"__author__ = 'nikhilbv'\n__version__ = '1.0'\n\n\"\"\"\n# Visualize predictions\n# --------------------------------------------------------\n# Copyright (c) 2019 Vidteq India Pvt. Ltd.\n# Licensed under [see LICENSE for details]\n# Written by nikhilbv\n# --------------------------------------------------------\n\"\"\"\n\n\"\"\"\n# Usage\n# --------------------------------------------------------\n# python show_no_of_lanes.py --json_file \n# python show_no_of_lanes.py --json_file pred-7-170919_115403.json\n# --------------------------------------------------------\n\"\"\"\n\nimport argparse\nimport json\nimport os\nimport cv2\n\ndef init_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--json_file', type=str, help='The predicted json 1')\n return parser.parse_args()\n\ndef show_no_of_lanes(json_file):\n with open(json_file, 'r') as file:\n json_lines = file.readlines()\n res_lanes = {'0_lanes':0,'1_lanes':0,'2_lanes':0,'3_lanes':0,'4_lanes':0,'5_lanes':0,'5_lanes':0}\n for line_index,val in enumerate(json_lines):\n #print(line_index)\n json_line = json_lines[line_index]\n sample = json.loads(json_line)\n lanes = sample['lanes']\n res_lane = []\n #print(len(lanes))\n for lane in lanes:\n lane_id_found=False\n for lane_id in lane:\n if lane_id == -2:\n continue\n else:\n lane_id_found=True\n break\n if lane_id_found:\n res_lane.append(lane) \n #print(len(res_lane))\n if len(res_lane) == 0:\n res_lanes['0_lanes']=res_lanes['0_lanes']+1\n elif len(res_lane) == 1:\n res_lanes['1_lanes']=res_lanes['1_lanes']+1\n elif len(res_lane) == 2:\n res_lanes['2_lanes']=res_lanes['2_lanes']+1\n elif len(res_lane) == 3:\n res_lanes['3_lanes']=res_lanes['3_lanes']+1\n elif len(res_lane) == 4:\n res_lanes['4_lanes']=res_lanes['4_lanes']+1\n elif len(res_lane) == 5:\n res_lanes['5_lanes']=res_lanes['5_lanes']+1\n elif len(res_lane) == 6:\n res_lanes['6_lanes']=res_lanes['6_lanes']+1\n print(res_lanes)\n\nif __name__ == '__main__':\n args = init_args()\n show_no_of_lanes(args.json_file)","sub_path":"python/no_of_lanes.py","file_name":"no_of_lanes.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"5834297","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom PIL import Image\r\nfrom PIL import ImageFont\r\nfrom PIL import ImageDraw\r\nimport os\r\nimport logging\r\nimport DEV_Config\r\nimport OLED_Driver\r\nimport time\r\nimport threading\r\nimport RPi.GPIO as GPIO\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\nclass OledManager(object):\r\n def __init__(self, splash_duration=5, splash_images=None):\r\n # type: (int, list) -> object\r\n \"\"\"\r\n OlED display module that allows you to show system information on the screen.\r\n Call Update() with a parameter of type [customtypes].SystemInfo\r\n :param splash_duration: total time to show Splash images at startup\r\n :param splash_images: Image names in a list. Must be mode=gray scale and exactly of size=128x128px\r\n \"\"\"\r\n logger.debug(\"OLEDManager starting...\")\r\n self._data = None\r\n self._activate_screen = False\r\n self.splash_logos = splash_images # MUST BE mode=gray_scale, size=128x1218px\r\n self.splash_duration = splash_duration # seconds\r\n self.font_std = ImageFont.load(OledManager.path_join(\"fonts/courB10.pil\"))\r\n self.font_h1 = ImageFont.load(OledManager.path_join(\"fonts/courB18.pil\"))\r\n self.font_xl = ImageFont.load(OledManager.path_join(\"fonts/courB24.pil\"))\r\n self.img_host = None # pre-rendered images\r\n self.img_network = None\r\n self.img_cpu = None\r\n self.img_disk = None\r\n self._OLED_ScanDir = OLED_Driver.SCAN_DIR_DFT # SCAN_DIR_DFT = D2U_L2R\r\n self.OLED = OLED_Driver.OLED()\r\n self.OLED.OLED_Init(self._OLED_ScanDir)\r\n time.sleep(0.5)\r\n self._display_event = threading.Event()\r\n self._thread = threading.Thread(target=self._internal_thread_loop) # , args=[False])\r\n self._thread.name = \"oled_internal_thread\"\r\n self._thread.do_run = True\r\n self._thread.start()\r\n logger.info(\"OLEDManager init complete\")\r\n\r\n @staticmethod\r\n def script_home_path():\r\n return os.path.dirname(os.path.realpath(__file__))\r\n\r\n @staticmethod\r\n def path_join(filename, basedir=None):\r\n if basedir is None:\r\n basedir = OledManager.script_home_path()\r\n return os.path.join(basedir, filename)\r\n\t\r\n def _internal_thread_loop(self):\r\n logger.debug(\"entering OLED _internal_thread_loop\")\r\n assert threading.current_thread().name == \"oled_internal_thread\"\r\n if len(self.splash_logos) > 0:\r\n self.show_splash()\r\n while self._thread.do_run:\r\n logger.debug(\"loop: self._activate_screen = \" + str(self._activate_screen))\r\n while not self._activate_screen:\r\n logger.debug(\"entering wait()...\")\r\n self.clear_oled()\r\n self._display_event.wait() # sleeps while waiting for event\r\n if not self._thread.do_run:\r\n self.clear_oled()\r\n return\r\n self.show_splash()\r\n logger.debug(\"leaving wait()!!!!\")\r\n self._show_system_info()\r\n\r\n def _internal_thread_stop(self):\r\n if self._thread is not None and self._thread.is_alive():\r\n logger.debug(\"stopping OLED screen background thread...\")\r\n self._activate_screen = True # needed for thread to exit inner WHILE loop\r\n self._thread.do_run = False\r\n self._display_event.set() # wake thread so we can kill it :)\r\n logger.debug(\"waiting for thread.join()\")\r\n self._thread.join()\r\n self._thread = None\r\n else:\r\n logger.debug(\"thread is already dead\")\r\n\r\n def update(self, values):\r\n \"\"\"\r\n Async display of data supplied in [values].\r\n Call off() method to stop.\r\n :param values: [customTypes.py].[SystemInfo]\r\n :return: None\r\n \"\"\"\r\n self._data = values\r\n self._activate_screen = True\r\n self._display_event.set() # Tell internal thread that it should wake up\r\n\r\n def _show_system_info(self):\r\n logger.debug(\"entering Show_system_info()\")\r\n if self._activate_screen and self._data is not None:\r\n self.OLED.OLED_ShowImage(self.get_host_image(), 0, 0)\r\n time.sleep(2.5)\r\n self.OLED.OLED_ShowImage(self.get_network_image(), 0, 0)\r\n time.sleep(2.9)\r\n self.OLED.OLED_ShowImage(self.get_cpu_image(), 0, 0)\r\n time.sleep(2.3)\r\n self.OLED.OLED_ShowImage(self.get_disk_image(), 0, 0)\r\n time.sleep(2.3)\r\n\r\n def show_splash(self, images=None):\r\n \"\"\"\r\n Shows selected images on the screen. Blocking.\r\n This method will lock the screen while it shows the splash images. No other screen updates will be possible.\r\n The image MUST have size exactly equal to 128x128 pixels.\r\n The image MUST have mode GREYSCALE. RGB will cause exceptions\r\n \"\"\"\r\n # acquire screen lock\r\n if images is None:\r\n images = self.splash_logos\r\n duration = self.splash_duration / len(images)\r\n for img in images:\r\n logger.debug(\"SPLASH -> \" + img)\r\n image_plash_logo = Image.open(img)\r\n self.OLED.OLED_ShowImage(image_plash_logo, 0, 0)\r\n time.sleep(duration)\r\n self.clear_oled()\r\n\r\n def get_host_image(self):\r\n if self.img_host is None:\r\n self.img_host = Image.new(\"L\", (128, 128), 0) # blank black image\r\n drawing = ImageDraw.Draw(self.img_host)\r\n drawing.rectangle([(0, 0), (127, 10)], fill=255, outline=255, width=2)\r\n drawing.rectangle([(0, 10), (127, 40)], fill=None, outline=255, width=2)\r\n header_start_pos = (128 - self.font_h1.getsize(self._data.host.hostname)[0]) / 2\r\n drawing.text((header_start_pos, 11), self._data.host.hostname, font=self.font_h1, fill=255)\r\n drawing.rectangle([(0, 28), (127, 40)], fill=255, outline=255, width=2)\r\n drawing.text((10, 50), \"OS:\", font=self.font_std, fill=255)\r\n drawing.text((20, 66), self._data.host.os, font=self.font_std, fill=255)\r\n drawing.text((10, 84), \"UPTIME:\", font=self.font_std, fill=255)\r\n drawing.text((20, 100), self._data.host.up_time, font=self.font_std, fill=255)\r\n drawing = ImageDraw.Draw(self.img_host)\r\n drawing.rectangle([(20, 100), (128, 128)], fill=0, outline=0, width=2)\r\n drawing.text((20, 100), self._data.host.up_time, font=self.font_std, fill=255)\r\n return self.img_host\r\n\r\n def get_network_image(self):\r\n if self.img_network is None:\r\n self.img_network = Image.new(\"L\", (128, 128), 0) # blank black image\r\n drawing = ImageDraw.Draw(self.img_network)\r\n drawing.rectangle([(0, 0), (127, 10)], fill=255, outline=255, width=2)\r\n drawing.rectangle([(0, 10), (127, 40)], fill=None, outline=255, width=2)\r\n header_start_pos = (128 - self.font_h1.getsize(self._data.host.friendly_internet)[0]) / 2\r\n drawing.text((header_start_pos, 11), self._data.host.friendly_internet, font=self.font_h1, fill=255)\r\n drawing.rectangle([(0, 28), (127, 40)], fill=255, outline=255, width=2)\r\n\r\n drawing = ImageDraw.Draw(self.img_network)\r\n drawing.rectangle([(0, 66), (128, 128)], fill=0, outline=0, width=2)\r\n drawing.text((15, 50), \"IP:\", font=self.font_std, fill=255)\r\n drawing.text((5, 66), self._data.host.ip, font=self.font_std, fill=255)\r\n drawing.text((15, 84), \"MAC:\", font=self.font_std, fill=255)\r\n drawing.text((5, 100), self._data.host.mac_address, font=self.font_std, fill=255)\r\n return self.img_network\r\n\r\n def get_cpu_image(self):\r\n if self.img_cpu is None:\r\n self.img_cpu = Image.new(\"L\", (128, 128), 0) # blank black image\r\n icon = Image.open(OledManager.path_join('icons/temp.bmp'), 'r')\r\n icon_h = icon.size[1]\r\n h_offset = 0\r\n if icon_h < 128:\r\n h_offset = (128 - icon_h) / 2\r\n self.img_cpu.paste(icon, (1, h_offset))\r\n \r\n drawing = ImageDraw.Draw(self.img_cpu)\r\n drawing.rectangle([(36, 42), (128, 73)], fill=0, outline=0, width=2)\r\n drawing.rectangle([(42, 92), (128, 128)], fill=0, outline=0, width=2)\r\n drawing.text((36, 42),\r\n self._data.cpu.temp + \" C\", font=self.font_xl, fill=255)\r\n drawing.text((42, 92), \"load = \" + str(self._data.cpu.load) + \"%\", font=self.font_std, fill=255)\r\n return self.img_cpu\r\n\r\n def get_disk_image(self):\r\n if self.img_disk is None:\r\n self.img_disk = Image.new(\"L\", (128, 128), 0) # blank black image\r\n icon = Image.open(OledManager.path_join('icons/sdcard.bmp'), 'r')\r\n icon_h = icon.size[1]\r\n h_offset = 0\r\n if icon_h < 128:\r\n h_offset = (128 - 10 - icon_h) / 2\r\n self.img_disk.paste(icon, (1, h_offset))\r\n\r\n drawing = ImageDraw.Draw(self.img_disk)\r\n drawing.rectangle([(49, 45), (128, 75)], fill=0, outline=0, width=2)\r\n drawing.rectangle([(0, 100), (128, 128)], fill=0, outline=0, width=2)\r\n drawing.text((49, 45), str(self._data.fs.percent) + \"%\", font=self.font_xl, fill=255)\r\n drawing.text((2, 100), self._data.fs.friendly_fs_size(), font=self.font_std, fill=255)\r\n return self.img_disk\r\n\r\n def clear_oled(self):\r\n \"\"\"\r\n Clear screen (black)\r\n :return: None\r\n \"\"\"\r\n self.OLED.OLED_Clear()\r\n return None\r\n\r\n def off(self):\r\n \"\"\"\r\n Pauses screen updates\r\n :return: None\r\n \"\"\"\r\n self._activate_screen = False\r\n self._display_event.clear() # Tell internal thread that it should sleep\r\n logger.debug(\"screen turned off\")\r\n self.clear_oled()\r\n\r\n def close(self):\r\n \"\"\"\r\n Stops the internal thread, This object is no longer useful and should be disposed.\r\n :return:\r\n \"\"\"\r\n self._internal_thread_stop()\r\n logger.debug(\"OLED thread stopped!\")\r\n\r\n def __exit__(self, exc_type, exc_value, traceback):\r\n self._internal_thread_stop()\r\n logger.debug(\"OLED thread stopped!\")\r\n","sub_path":"oledmanager.py","file_name":"oledmanager.py","file_ext":"py","file_size_in_byte":10371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"213156817","text":"import cv2\nimport numpy as np\nfrom kbapi import keyboard_ctl\nimport struct\n\ndef getkeypos():\n endpos = 30\n pos1 = []\n pos2 = []\n pos3 = []\n pos4 = []\n pos5 = []\n\n xpos = endpos\n ypos = 1.9 * 4\n\n leds = [];\n leds.insert(0, 2.4)\n leds.insert(0, 2.4)\n leds.insert(0, 7.2)\n leds.insert(0, 6.9)\n a = ([1.9] * 5)\n leds = a + leds\n\n pos1.append((xpos, ypos))\n\n for a in leds:\n xpos -= a\n pos1.insert(0, (xpos, ypos))\n\n xpos = endpos\n ypos = 1.9 * 3\n\n leds = [];\n leds.insert(0, 3.1)\n a = ([1.9] * 9)\n leds = a + leds\n leds.insert(0, 2.6)\n leds.insert(0, 2.6)\n leds.insert(0, 1.9)\n\n pos2.append((xpos, ypos))\n\n for a in leds:\n xpos -= a\n pos2.append((xpos, ypos))\n\n xpos = endpos\n ypos = 1.9 * 2\n\n leds = [];\n leds.insert(0, 2.6)\n a = ([1.9] * 10)\n leds = a + leds\n leds.insert(0, 3.1)\n leds.insert(0, 3.1)\n\n pos3.append((xpos, ypos))\n\n for a in leds:\n xpos -= a\n pos3.insert(0, (xpos, ypos))\n\n xpos = endpos\n ypos = 1.9 * 1\n\n leds = [];\n leds.insert(0, 2.4)\n a = ([1.9] * 11)\n leds = a + leds\n leds.insert(0, 2.4)\n leds.insert(0, 2.4)\n\n pos4.append((xpos, ypos))\n\n for a in leds:\n xpos -= a\n pos4.append((xpos, ypos))\n\n xpos = endpos\n ypos = 1.9 * 0\n\n leds = [];\n a = ([1.9] * 12)\n leds = a + leds\n leds.insert(0, 2.85)\n leds.insert(0, 2.85)\n\n pos5.append((xpos, ypos))\n\n for a in leds:\n xpos -= a\n pos5.insert(0, (xpos, ypos))\n\n # print(\"keys:\",len(pos),pos)\n #\n # mat=numpy.zeros((400,400,3))\n # for l in pos:\n # mat=cv2.circle(mat,(int(l[0]*10+50),int(l[1]*10+50)),5,(255,255,255))\n # cv2.imshow(\"keys\",mat)\n # cv2.waitKey(0)\n pos = pos1 + pos2 + pos3 + pos4 + pos5\n pos = np.array(pos)\n return pos\n # print(pos)\n\n\nclass keyboard_led:\n def __init__(self, _kb: keyboard_ctl):\n self.keyledpos = getkeypos()\n self.keyledpos[:, 0] -= 0.75\n self.keyledpos[:, 1] += 0.75\n self.keyw = 30;\n self.keyh = 1.9 * 4 + 0.75 * 2\n self.kbaspect = self.keyw / self.keyh\n self.kb = _kb\n self.keymapframe = np.zeros((1, 1, 1))\n\n def gammafunction(self, r, g, b):\n return r,g,b\n return int(255 * pow(r / 255, 1.8)), int(255 * pow(g / 255, 1.8)), int(255 * pow(b / 255, 1.8))\n\n def play_frame_full(self, frame):\n frame = cv2.resize(frame, (128, int(self.keyh / self.keyw * 128)), interpolation=cv2.INTER_NEAREST)\n return self.play_frame(frame)\n\n def play_frame(self, frame):\n xsize = frame.shape[1]\n ysize = frame.shape[0]\n if xsize > 128:\n frame = cv2.resize(frame, (128, int(ysize / xsize * 128)), interpolation=cv2.INTER_NEAREST)\n xsize = frame.shape[1]\n ysize = frame.shape[0]\n aspect = xsize / ysize\n xoffset = yoffset = int(0)\n factor = 1\n if (aspect < self.kbaspect):\n factor = xsize / self.keyw\n kb_vish = factor * self.keyh\n yoffset = int((ysize - kb_vish) / 2)\n else:\n factor = ysize / self.keyh\n kb_visw = factor * self.keyw\n xoffset = int((xsize - kb_visw) / 2)\n if self.keymapframe.shape[0] != ysize and self.keymapframe.shape[1] != xsize:\n\n self.keymapframe = np.zeros((ysize, xsize, 1), dtype='uint8')\n keyid = 1\n for l in self.keyledpos:\n mapx = int(l[0] * factor) + xoffset\n mapy = int(l[1] * factor) + yoffset\n self.keymapframe = cv2.circle(self.keymapframe, (mapx, mapy), int(1 * factor), (keyid), cv2.FILLED)\n keyid += 1\n colordata = bytearray(0)\n keyid = 1\n for l in self.keyledpos:\n # mapx=int(l[0]*factor)+xoffset\n # mapy=int(l[1]*factor)+yoffset\n mapimg = (self.keymapframe == keyid).squeeze()\n colors = frame[mapimg]\n colorb = np.mean(colors[:, 0])\n colorg = np.mean(colors[:, 1])\n colorr = np.mean(colors[:, 2])\n colorr, colorg, colorb = self.gammafunction(colorr, colorg, colorb)\n colordata += struct.pack('BBBB', int(colorb), int(colorg), int(colorr), 0)\n keyid += 1\n self.kb.writedata(0x9000, colordata)\n return colordata\n def switchmode(self,mode:int):\n self.kb.writedata(0x8000, struct.pack('I', mode))\n def getled(self):\n length, data = self.kb.readdata(0x9000, 272)\n return length,data\n def getpreview(self,data,size):\n colors = np.frombuffer(data, dtype='uint8')\n colors = np.reshape(colors, (-1, 4))\n visual = np.zeros((int(size[1]), int(size[0]), 3), dtype='uint8')\n keyid = int(0)\n for l in self.keyledpos:\n posx = l[0] * size[0]/self.keyw\n posy = l[1] * size[1]/self.keyh\n color = (int(colors[keyid][0]), int(colors[keyid][1]), int(colors[keyid][2]))\n # print(color)\n visual = cv2.circle(visual, (int(posx), int(posy)), int(min(size[0]/self.keyw,size[1]/self.keyh)), color, cv2.FILLED)\n keyid += 1\n return visual\n def getpreview_rgb(self,data,size):\n colors = np.frombuffer(data, dtype='uint8')\n colors = np.reshape(colors, (-1, 4))\n visual = np.zeros((int(size[1]), int(size[0]), 3), dtype='uint8')\n keyid = int(0)\n for l in self.keyledpos:\n posx = l[0] * size[0]/self.keyw\n posy = l[1] * size[1]/self.keyh\n color = (int(colors[keyid][2]), int(colors[keyid][1]), int(colors[keyid][0]))\n # print(color)\n visual = cv2.circle(visual, (int(posx), int(posy)), int(min(size[0]/self.keyw,size[1]/self.keyh)), color, cv2.FILLED)\n keyid += 1\n return visual","sub_path":"software/hidtest/kbled.py","file_name":"kbled.py","file_ext":"py","file_size_in_byte":5876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"401828034","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Icate',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('cate_name', models.CharField(verbose_name='项目类别', max_length=30)),\n ('cate_addtime', models.DateTimeField(blank=True, verbose_name='类别添加时间')),\n ('cate_num', models.IntegerField(verbose_name='类别编号', unique=True)),\n ],\n options={\n 'db_table': 'item_cate',\n },\n ),\n migrations.CreateModel(\n name='Item',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('title', models.CharField(verbose_name='项目标题', max_length=30)),\n ('tid', models.CharField(blank=True, verbose_name='项目唯一ID', max_length=64)),\n ('start_time', models.DateTimeField(blank=True, verbose_name='项目开始时间')),\n ('end_time', models.DateTimeField(blank=True, verbose_name='项目结束时间')),\n ('tag', models.CharField(blank=True, verbose_name='标签', max_length=30)),\n ('seenum', models.IntegerField(blank=True, verbose_name='浏览次数')),\n ('disnum', models.IntegerField(blank=True, verbose_name='评论条数')),\n ('jindu', models.FloatField(verbose_name='项目进度(0~1之间)')),\n ('jindu_show', models.TextField(verbose_name='当前进度说明')),\n ('item_show', models.TextField(verbose_name='项目介绍')),\n ('category', models.ForeignKey(related_name='item_cate', to='items.Icate', verbose_name='类别')),\n ],\n options={\n 'db_table': 'item',\n },\n ),\n ]\n","sub_path":"blog/items/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"623352794","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/insights/parsers/tests/test_readlink_openshift_certs.py\n# Compiled at: 2020-03-26 13:06:46\nimport pytest, doctest\nfrom insights.tests import context_wrap\nfrom insights.parsers import readlink_openshift_certs, SkipException\nCLIENT_REAL_FILE_PATH = ('\\n/etc/origin/node/certificates/kubelet-client-2019-10-18-23-17-35.pem\\n').strip()\nSERVER_REAL_FILE_PATH = ('\\n/etc/origin/node/certificates/kubelet-server-2018-10-18-23-29-14.pem\\n').strip()\nBAD_FILE_PATH = ''\n\ndef test_doc_examples():\n env = {'client': readlink_openshift_certs.ReadLinkEKubeletClientCurrent(context_wrap(CLIENT_REAL_FILE_PATH)), \n 'server': readlink_openshift_certs.ReadLinkEKubeletServerCurrent(context_wrap(SERVER_REAL_FILE_PATH))}\n failed, total = doctest.testmod(readlink_openshift_certs, globs=env)\n assert failed == 0\n\n\ndef test_readlink_openshift_certs():\n client = readlink_openshift_certs.ReadLinkEKubeletClientCurrent(context_wrap(CLIENT_REAL_FILE_PATH))\n assert len(client.path) > 0\n assert client.path == CLIENT_REAL_FILE_PATH\n server = readlink_openshift_certs.ReadLinkEKubeletServerCurrent(context_wrap(SERVER_REAL_FILE_PATH))\n assert len(server.path) > 0\n assert server.path == SERVER_REAL_FILE_PATH\n\n\ndef test_fail():\n with pytest.raises(SkipException) as (e):\n readlink_openshift_certs.ReadLinkEKubeletClientCurrent(context_wrap(BAD_FILE_PATH))\n assert 'No Data from command: /usr/bin/readlink -e /etc/origin/node/certificates/kubelet-client-current.pem' in str(e)\n with pytest.raises(SkipException) as (e):\n readlink_openshift_certs.ReadLinkEKubeletServerCurrent(context_wrap(BAD_FILE_PATH))\n assert 'No Data from command: /usr/bin/readlink -e /etc/origin/node/certificates/kubelet-server-current.pem' in str(e)","sub_path":"pycfiles/insights_core-3.0.163-py2.7/test_readlink_openshift_certs.py","file_name":"test_readlink_openshift_certs.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"78309454","text":"#!/usr/bin/python\n\nimport sys\nimport os.path\nimport os\nimport time\nimport traceback\nimport logging\nimport logging.handlers\nimport argparse\nfrom ftplib import FTP\nimport ftplib\nfrom PIL import Image\nimport subprocess\nimport tempfile\nimport shutil\n\nFTPH = None\n\ndef archive_cleanup(archivedir, archivedays):\n\tlogging.info(\"Cleaning from archive {} days {}...\".format(archivedir, archivedays))\n\tday_dirs = sorted(os.listdir(archivedir), reverse = True)\n\tfor day_dir in day_dirs[archivedays:]:\n\t\tlogging.info(\"Removing {}\".format(day_dir))\n\t\tshutil.rmtree(os.path.join(archivedir, day_dir), True)\n\tlogging.info(\"Cleaning of archive done.\")\n\ndef archive_images2(imagedir, archivedir, archivedays):\n\tarchive_cleanup(archivedir, archivedays)\n\tlogging.info(\"Archiving images...\")\n\tfor fname in get_files(imagedir):\n\t\t# split apart the image filename into pieces. The filename from motion\n\t\t# is formatted: 20151117_211520_01\n\t\t# and the target folder structure will be YYYYMMDD/HH/file.jpg\n\t\tif not fname.endswith('jpg') or fname.endswith('_sml.jpg'):\n\t\t\tlogging.debug(\"Skipping archive of file {}, not recognized\".format(fname))\n\t\t\tcontinue\n\n\t\tyyyymmdd = fname.split('_')[0]\n\t\thh = fname.split('_')[1][:2]\n\n\t\ttarget = os.path.join(archivedir, yyyymmdd, hh)\n\t\tlogging.info(\"Archiving {} to {}\".format(fname, target))\n\n\t\tif os.path.isfile(os.path.join(target,fname)):\n\t\t\tlogging.warning(\"File {} already exists in {} during archiving.\".format(fname, target))\n\t\telse:\n\t\t\tif not os.path.isdir(target):\n\t\t\t\tos.makedirs(target)\n\t\t\tshutil.copy(os.path.join(imagedir, fname), target)\n\n\tlogging.info(\"Archiving images done.\")\n\n\ndef archive_timelapse_video(imagedir, archivedir):\n\tlogging.info(\"Archiving timelapse...\")\n\tfor fname in get_files(imagedir, 'AVI'):\n\t\t\n\t\ti = int( time.time() - os.path.getmtime(os.path.join(imagedir, fname)))\n\t\tif (i < 60):\n\t\t\tlogging.debug(\"Skipping archive of file {}, it has recently been modified.\".format(fname))\n\t\t\tcontinue\n\n\t\tyyyymmdd = fname.split('_')[0]\n\t\thh = fname.split('_')[1][:2]\n\n\t\ttarget = os.path.join(archivedir, yyyymmdd, hh)\n\t\tlogging.info(\"Archiving {} to {}\".format(fname, target))\n\n\t\tif os.path.isfile(os.path.join(target,fname)):\n\t\t\tlogging.warning(\"File {} already exists in {} during archiving.\".format(fname, target))\n\t\telse:\n\t\t\tif not os.path.isdir(target):\n\t\t\t\tos.makedirs(target)\n\t\t\tshutil.copy(os.path.join(imagedir, fname), target)\n\t\t# remove avi files during archive. Image files are removed only after FTP upload was success.\n\t\tremove_file(imagedir, fname)\n\n\t\t\n\tlogging.info(\"Archiving timelapse done.\")\n\ndef resize_image(imagedir, imagefname, targetfile):\n\tinfile = os.path.join(imagedir, imagefname)\n\tim = Image.open(infile)\n\tim.thumbnail( (2000,720) )\n\tim.save(targetfile, \"JPEG\", quality = 60)\n\tlogging.info('Resizing {} to {}'.format(infile, targetfile.name))\n\ndef get_files(image_dir, extension = 'JPG'):\n\tfnames = sorted([f for f in os.listdir(image_dir) if f.upper().endswith(extension)])\n\treturn fnames\n\ndef ftp_callback(block):\n\tlogging.debug('Sent block...')\n\ndef get_ftphandle(username, password):\n\tglobal FTPH\n\tif not FTPH:\n\t\tlogging.info('Connecting to FTP server.')\n\t\tFTPH = FTP(timeout=60)\n\t\tFTPH.set_debuglevel(0) # https://docs.python.org/2/library/ftplib.html#ftplib.FTP.set_debuglevel\n\t\tFTPH.connect('ftp.cammy.com',10021)\n\t\tFTPH.login(username, password)\n\treturn FTPH\n\ndef close_ftphandle():\n\tglobal FTPH\n\ttry:\n\t\tif FTPH:\n\t\t\tFTPH.quit()\n\texcept ftplib.all_errors as e:\n\t\tlogging.exception('Exception during closing the FTP handle')\n\tFTPH = None\n\ndef ftp_put(ftph, imagedir, imagefile):\n\tsent = False\n\ttry:\n\t\timagefname = os.path.join(imagedir, imagefile)\n\t\tlogging.info(\"FTP STOR {}\".format(imagefname))\n\t\tresp = ftph.storbinary(\"STOR \" + imagefile, open(imagefname,'rb'), blocksize = 4096, callback = ftp_callback)\n\t\tftph.voidcmd('NOOP')\n\t\tlogging.info(\"FTP STOR response code {}\".format(resp))\n\t\tsent = True\n\texcept ftplib.all_errors as e:\n\t\tlogging.exception('Exception during putting image')\n\texcept Exception as e:\n\t\tlogging.exception('Unexpected exception during putting image')\n\treturn sent\n\ndef remove_file(imagedir, fname):\n\tf = os.path.join(imagedir, fname)\n\tif os.path.isfile(f):\n\t\tlogging.info(\"Removing {}\".format(f))\n\t\tos.remove(f)\n\t\t\ndef get_fileage(imagedir, fname):\n\ttry:\n\t\ti = int( time.time() - os.path.getctime(os.path.join(imagedir,fname)) )\n\texcept Exception as e:\n\t\ti = 0 \n\treturn i\n\ndef ftp_putall(imagedir, username, password, delete, archivedir, archivedays, resize):\n\n\tuploaded = False\n\tup_count = 0\n\twhile True and delete:\n\t\tfnames = get_files(imagedir)\n\t\tlogging.info('^^^ Processing {}, number of images = {}'.format(imagedir, len(fnames)))\n\t\tif len(fnames) == 0:\n\t\t\tbreak\n\n\t\tif archivedir:\n\t\t\tarchive_images2(imagedir, archivedir, archivedays)\n\t\t\tarchive_timelapse_video(imagedir, archivedir)\n\t\t\t\n\t\ti = 0\n\t\tretrycount = 0\n\n\t\tfor i in range(len(fnames)):\n\t\t\tfname = fnames[i]\n\n\t\t\tif fname.endswith('_sml.jpg'):\n\t\t\t\tcontinue\n\n\t\t\tlogging.info(\"Putting image {}, {} of {}\".format(fname, i, len(fnames)))\n\n\t\t\tif get_fileage(imagedir, fname) > (60*30) and delete:\n\t\t\t\tlogging.warning(\"Frame drop! Dropping {}\".format(fname))\n\t\t\t\tremove_file(imagedir, fname)\n\t\t\t\tcontinue\n\n\n\t\t\torig_fname = fname\n\t\t\ttmpfile = tempfile.NamedTemporaryFile()\n\t\t\tif resize:\n\t\t\t\tresize_image(imagedir, fname, tmpfile)\n\t\t\t\tfname = tmpfile.name\n\n\t\t\tuploaded = False\n\t\t\tretrycount = 0\n\t\t\twhile not uploaded and retrycount < 10:\n\t\t\t\tftph = get_ftphandle(username, password)\n\t\t\t\tuploaded = ftp_put(ftph, imagedir, fname)\n\t\t\t\tif not uploaded:\n\t\t\t\t\tlogging.info('Problem during storing {}, retrying'.format(fname))\n\t\t\t\t\tclose_ftphandle()\n\t\t\t\t\tretrycount += 1\n\t\t\t\telse:\n\t\t\t\t\tup_count += 1\n\n\t\t\tif delete:\n\t\t\t\tremove_file(imagedir, orig_fname)\n\t\t\t\n\tclose_ftphandle()\n\tlogging.info('@@@ Finished processing {}. Uploaded {} images.'.format(imagedir, up_count))\n\n\treturn uploaded\t\n\t\n\t\n\ndef main():\n\n\tparser = argparse.ArgumentParser(description='Cammy FTP Uploader.')\n\tparser.add_argument('-u', dest='username', required=True, help='Cammy FTP username')\n\tparser.add_argument('-p', dest='password', required=True, help='Cammy FTP password')\n\tparser.add_argument('--log', help='Log file path', default='cammyput.log')\n\tparser.add_argument('--imagedir', help='Path to images', default='images')\n\tparser.add_argument('--delete', help='Delete images after uploading', action='store_true', default=False)\n\tparser.add_argument('--resize', help='Resize images before sending to cammy', action='store_true', default=False)\n\tparser.add_argument('--archivedir', help='Archive directory', default=None)\n\tparser.add_argument('--archivedays', help='Number of days of history to keep in archive', default=10)\n\tparser.add_argument('--cameras', help='List of camera subdirs, e.g. 01 02 03', nargs='+', required=True)\n\n\targs = parser.parse_args()\n\n\tlogFormatter = logging.Formatter(\"%(asctime)s [%(levelname)-5.5s] %(message)s\")\n\trootLogger = logging.getLogger()\n\tfileHandler = logging.handlers.RotatingFileHandler(args.log, maxBytes=(1048576*5), backupCount=7)\n\tfileHandler.setFormatter(logFormatter)\n\trootLogger.addHandler(fileHandler)\n\n\tconsoleHandler = logging.StreamHandler(sys.stdout)\n\tconsoleHandler.setFormatter(logFormatter)\n\trootLogger.addHandler(consoleHandler)\n\n\trootLogger.setLevel(logging.DEBUG)\n\n\tlogging.info('CammyPut2 started.')\n\n\n\twhile True:\n\t\tfor camera in args.cameras:\n\t\t\tlogging.info('Scanning camera {}...'.format(camera))\n\t\t\tcam_imagedir = os.path.join(args.imagedir, camera)\n\t\t\tcam_archivedir = os.path.join(args.archivedir, camera)\n\n\t\t\tuploaded = ftp_putall(cam_imagedir, args.username, args.password, args.delete, cam_archivedir, \\\n\t\t\t\t\t\targs.archivedays, args.resize)\n\n\t\t\tif uploaded:\n\t\t\t\t# pause for cammy to think theres a new event\n\t\t\t\ttime.sleep(60)\n\n\t\ttime.sleep(1)\n\n\n\n\n\tlogging.info(\"Finished\")\n\n\nif __name__ == '__main__':\n\ttry:\n\t\tmain()\n\texcept KeyboardInterrupt as e:\n\t\ttraceback.print_exc()\n\texcept Exception as e:\n\t\ttraceback.print_exc()\n","sub_path":"cammy_put_d.py","file_name":"cammy_put_d.py","file_ext":"py","file_size_in_byte":7920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"502720999","text":"import pandas as pd\nimport Nutrients.utils as utl\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport seaborn\n\n# %%\nnutrients = utl.load_sql_table('nutrient')\nnutrients['id'] = nutrients['id'].astype('int64')\nquantities = utl.load_sql_table('quantity')\nqty = quantities.pivot_table(index='food_id', columns='nutrient_id', values='value', fill_value=0)\n\nqty_cov = qty.cov(min_periods=50).fillna(0).as_matrix()\ncov_norm = np.log10(1+np.abs(qty_cov)) * np.sign(qty_cov) # normalize for visualization\n# %%\nmatplotlib.rcParams.update({'font.size': 16})\n# fig, ax = plt.subplots(figsize=(12, 8))\n# seaborn.heatmap(np.log10(np.abs(qty_cov+1)) * np.sign(qty_cov), ax=ax)\n# plt.show()\nfig, ax = plt.subplots(figsize=(12, 8))\noffdiag = 1-np.eye(len(cov_norm))\nvar, vbin = np.histogram(np.diag(cov_norm), bins=25)\nwidth = 0.7 * (vbin[1] - vbin[0])\ncenter = (vbin[:-1] + vbin[1:]) / 2\nplt.bar(center, var/sum(var), align='center', width=width, alpha=.5)\ncvar, cvbin = np.histogram(cov_norm[offdiag.astype('bool')], bins=25)\nwidth = 0.7 * (cvbin[1] - cvbin[0])\ncenter = (cvbin[:-1] + cvbin[1:]) / 2\nplt.bar(center, cvar/sum(cvar), align='center', width=width, alpha=.5)\nax.set_yscale('log')\nplt.show()\n\n# %% anecdotes\n\ncov_norm[~offdiag.astype('bool')] = 0\ncovinds = np.argsort(np.ravel(cov_norm))\ncovsubs = [np.unravel_index(idx, cov_norm.shape) for idx in covinds]\ncovsubs = covsubs[::2]\n\nprint('Largest negative covariances:')\nfor subs in covsubs[:5]:\n print(cov_norm[subs], nutrients.iloc[list(subs)]['name'].values)\nprint('Largest positive covariances:')\nfor subs in covsubs[-5:]:\n print(cov_norm[subs], nutrients.iloc[list(subs)]['name'].values)\n","sub_path":"analyze_nutrients/nutrient_features.py","file_name":"nutrient_features.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"418700565","text":"import re\nimport requests\nimport datetime\nfrom urllib.parse import urlencode\nimport psycopg2\nimport pandas as pd\nfrom lovelyrita.config import API_KEY\n\n\nAPI_URL = \"https://maps.googleapis.com/maps/api/geocode/\"\n\n\nclass Geocoder(object):\n def __init__(self, geocodes=None, api_url=API_URL, api_key=API_KEY):\n if geocodes is None:\n geocodes = pd.DataFrame(columns=('lat', 'lng', 'place_id', 'timestamp'))\n geocodes.index.name = 'address'\n self.geocodes = geocodes\n self.api_url = API_URL\n self.api_key = API_KEY\n\n def geocode(self, address):\n \"\"\"\n Pull data from Google Maps API\n\n Parameters\n ----------\n address : str\n \"\"\"\n # check if query has already been run\n try:\n g = self.geocodes.loc[address]\n return g['lat'], g['lng'], g['place_id']\n except KeyError:\n pass\n\n query = {'address': address,\n 'key': self.api_key}\n url = self.api_url + 'json?' + urlencode(query)\n response = requests.get(url)\n if response.status_code == 404:\n raise Exception(\"404 error for {}\".format(url))\n\n content = response.json()\n if content['status'] != 'OK':\n raise Exception(\"Status not OK for {}\".format(url))\n\n place_id = content['results'][0]['place_id']\n lat = content['results'][0]['geometry']['location']['lat']\n lng = content['results'][0]['geometry']['location']['lng']\n timestamp = str(datetime.datetime.now())\n\n new_geocode = pd.Series({'place_id': place_id,\n 'lat': lat, 'lng': lng,\n 'timestamp': timestamp},\n name=address)\n self.geocodes = self.geocodes.append(new_geocode)\n return lat, lng, place_id\n\n @classmethod\n def load(cls, geocode_path):\n return cls(load_geocodes(geocode_path))\n\n def save(self, geocode_path):\n save_geocodes(self.geocodes, geocode_path)\n\n\nclass PostGISGeocoder(object):\n def __init__(self, host='172.17.0.3', database='postgres', user='postgres',\n password='mysecretpassword'):\n \"\"\"A PostGIS geocoder\n \"\"\"\n connection = psycopg2.connect(host=host, database=database,\n user=user, password=password)\n self.connection = connection\n self.cursor = connection.cursor()\n\n def geocode(self, address):\n \"\"\"Get the latitude and longitude of an address\n\n Parameters\n ----------\n address : str\n\n Returns\n -------\n A dictionary containing keys latitude, longitude, street_no, street_name, street_type, and \n rating (a numeric value indicating how uncertain the geocoding is)\n \"\"\"\n patt = \"[\" + re.escape(\"()\\'+\") + \"]\"\n address = re.sub(patt, '', address)\n\n columns = ['rating', 'longitude', 'latitude',\n 'street_no', 'street_name', 'street_type']\n\n query = (\"\"\"SELECT g.rating, ST_X(g.geomout) As lon, ST_Y(g.geomout) As lat, \"\"\"\n \"\"\"(addy).address As stno, (addy).streetname As street, \"\"\"\n \"\"\"(addy).streettypeabbrev As styp, \"\"\"\n \"\"\"(addy).location As city, \"\"\"\n \"\"\"(addy).stateabbrev As st,(addy).zip \"\"\"\n \"\"\"FROM geocode(%s, 1) As g;\"\"\")\n self.cursor.execute(query, (address, ))\n response = self.cursor.fetchone()\n\n if response:\n result = {k: v for k, v in zip(columns, response)}\n else:\n result = [None, ] * len(columns)\n\n return result\n\n\ndef save_addresses(addresses, path):\n with open(path, 'w') as f:\n f.write('\\n'.join(addresses))\n\n\ndef load_addresses(path):\n with open(path, 'r') as f:\n addresses = f.read().split('\\n')\n return addresses\n\n\ndef save_geocodes(geocodes, path):\n geocodes.to_hdf(path, 'geocodes')\n\n\ndef load_geocodes(path):\n return pd.read_hdf(path)\n","sub_path":"lovelyrita/geocode.py","file_name":"geocode.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"586517635","text":"import csv\nimport cv2\nimport numpy as np\nimport sklearn\nimport random \nrandom.seed(10)\nsamples = []\n\ncvs_path = './simulator_data_MORE/driving_log.csv'\n\n\nwith open(cvs_path) as csvfile:\n\treader = csv.reader(csvfile, skipinitialspace=True)\n\tfor line in reader:\n\t\tsamples.append(line)\n\n\nimport matplotlib.pyplot as plt\nsteering_angles = []\n\nfor row in samples:\n\tsteering_angles.append(float(row[3]))\n\n\nsteering_angles = np.array(steering_angles)\n\nnum_bins = 25\navg_samples_per_bin = len(steering_angles)/num_bins\nhists, bins = np.histogram(steering_angles, num_bins)\nwidth = 0.7 * (bins[1] - bins[0])\ncenter = (bins[:-1] + bins[1:]) / 2\nplt.bar(center, hists, align='center', width=width)\nplt.plot((np.min(steering_angles), np.max(steering_angles)), (avg_samples_per_bin, avg_samples_per_bin), 'k--')\nplt.show()\n\nkeep_probabilities = []\ntarget = 0.7*avg_samples_per_bin\nfor i in range(num_bins):\n if hists[i] < target:\n keep_probabilities.append(1.)\n else:\n keep_probabilities.append(1./(hists[i]/target))\nrm_list = []\nfor i in range(len(steering_angles)):\n for j in range(num_bins):\n if steering_angles[i] > bins[j] and steering_angles[i] <= bins[j+1]:\n if np.random.rand() > keep_probabilities[j]:\n rm_list.append(i)\nsamples = np.delete(samples, rm_list, axis=0)\nsteering_angles = np.delete(steering_angles, rm_list)\n\nhists, bins = np.histogram(steering_angles, num_bins)\nplt.bar(center, hists, align='center', width=width)\nplt.plot((np.min(steering_angles), np.max(steering_angles)), (avg_samples_per_bin, avg_samples_per_bin), 'k--')\nplt.show()\n\nfrom sklearn.model_selection import train_test_split\ntrain_samples, validation_samples = train_test_split(samples, test_size = 0.1)\n\ndef generator(samples, batch_size = 128):\n\tnum_samples = len(samples)\n\twhile True:\n\t\tsklearn.utils.shuffle(samples)\n\t\tfor offset in range(0, num_samples, batch_size):\n\t\t\tbatch_samples = samples[offset:offset+batch_size]\n\n\t\t\timgs = []\n\t\t\tmeasurements = []\n\t\t\tfor batch_sample in batch_samples:\n\t\t\t\tfor i in range(3):\n\t\t\t\t\tsource_path = batch_sample[i]\n\t\t\t\t\tfilename = source_path.split('\\\\')[-1]\n\t\t\t\t\tcurrent_path = './simulator_data_MORE/IMG/' + filename\n\t\t\t\t\timage = cv2.imread(current_path)\n\t\t\t\t\tmeasurement = float(batch_sample[3])\n\t\t\t\t\tcorrection = 0.25\n\t\t\t\t\tif i == 0:\n\t\t\t\t\t\tpass\n\t\t\t\t\telif i == 1:\n\t\t\t\t\t\t\tmeasurement += correction\n\t\t\t\t\telse:\n\t\t\t\t\t\t\tmeasurement -= correction\n\t\t\t\t\tif np.random.randint(1) == 0:\n\t\t\t\t\t\timage = np.fliplr(image)\n\t\t\t\t\t\tmeasurement = measurement * -1.0\n\n\t\t\t\t\timgs.append(image)\n\t\t\t\t\tmeasurements.append(measurement)\n\n\n\t\t\tX_train = np.array(imgs)\n\t\t\ty_train = np.array(measurements)\n\t\t\tyield sklearn.utils.shuffle(X_train, y_train)\n\nprint('Total samples: {}.'.format(3*len(samples)))\nprint('Training samples: {}.'.format(3*len(train_samples)))\nprint('Validation samples: {}.'.format(3*len(validation_samples)))\n\ntrain_generator = generator(train_samples)\nvalidation_generator = generator(validation_samples)\n\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Lambda, Dense, Convolution2D, Cropping2D, Dropout\nfrom keras.layers.pooling import MaxPooling2D\nmodel = Sequential()\nmodel.add(Lambda(lambda x: x/127.5 - 1, input_shape = (160,320,3)))\nmodel.add(Cropping2D(cropping=((70,25),(0,0))))\nmodel.add(Convolution2D(24,5,5, subsample=(2,2), activation='relu'))\nmodel.add(Convolution2D(36,5,5, subsample=(2,2), activation='relu'))\nmodel.add(Convolution2D(48,5,5, subsample=(2,2), activation='relu'))\nmodel.add(Convolution2D(64,3,3, activation='relu'))\nmodel.add(Convolution2D(64,3,3, activation='relu'))\nmodel.add(Flatten())\nmodel.add(Dense(100))\nmodel.add(Dense(50))\nmodel.add(Dense(1))\nmodel.compile(loss = 'mse', optimizer = 'adam')\nhistory_object = model.fit_generator(train_generator, samples_per_epoch = \\\n\t3*len(train_samples), validation_data = validation_generator, \\\n\tnb_val_samples=3*len(validation_samples), nb_epoch = 3, verbose=1)\nmodel.save('model.h5')\n\nprint(history_object.history.keys())\nimport matplotlib.pyplot as plt\n\nplt.plot(history_object.history['loss'])\nplt.plot(history_object.history['val_loss'])\nplt.title('Model Mean Squared Error Loss')\nplt.ylabel('Mean Squared Error Loss')\nplt.xlabel('Epoch')\nplt.legend(['Training Set', 'Validation Set'], loc='upper right')\nplt.show()\n\nexit()\n","sub_path":"submission/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"480718630","text":"import sys\nimport glob\nimport os\nfrom fibonacci.fibonacci import fibonacci\nimport math\n\n# First argument = location of the numbers folder\n\ndef main(args=sys.argv[1:]):\n # Load Directory\n # print(\"Loading directoy...\")\n files = glob.glob(args[0] + \"/*.bin\")\n files.sort()\n # print(\"Loaded directory\")\n # Get latest two files\n latest_files = files[len(files)-2:len(files)]\n # Get latest to numbers\n base1 = os.path.basename(latest_files[0])\n base1 = int(os.path.splitext(base1)[0], 16)\n base2 = os.path.basename(latest_files[1])\n base2 = int(os.path.splitext(base2)[0], 16)\n # Initalize F by reading the binary files\n F0 = int.from_bytes(open(latest_files[0], mode='rb').read(), byteorder='big')\n F1 = int.from_bytes(open(latest_files[1], mode='rb').read(), byteorder='big')\n # Compute the next 10 numbers\n F = F0 + (3 * F1)\n # Find out how many bytes will be neccessary\n num_bytes = math.ceil(math.ceil(math.log(F, 2)) / 8) + 1\n # Write number to file\n filename = args[0] + str(hex(base2 + 1))[2:].zfill(50) + \".bin\"\n open(filename, \"wb\").write(F.to_bytes(num_bytes, byteorder='big'))\n print(str(hex(base2 + 1))[2:].zfill(50)) # + \" | \" + str(int(str(hex(base2 + 1))[2:].zfill(50)), 16))\n\n # with open(args[0] + \"/\" + str(i) + \".bin\", \"wb\") as f:\n # s = F[i].to_bytes(1, byteorder='big')\n # print(s)\n # f.write(s)\n # with open(args[0] + \"/\" + str(i) + \".bin\", mode='rb') as f:\n # con = f.read()\n # print(str(int.from_bytes(con, byteorder='big')))\n\nif len(sys.argv) > 2:\n for i in range(1, int(sys.argv[2])):\n main()\n\nmain()","sub_path":"comp.py","file_name":"comp.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"157608898","text":"# 55. Python Convert Octal to Decimal ????\n\noctal = input(\"Enter any number in Binary Format: \")\nif octal != 'x':\n temp = int(octal, 8)\nprint(octal ,\"in decimal =\",(temp))\n\n\n'''\noutput ===\n\nEnter any number in Binary Format: 065\n065 in decimal = 53\n\n# 0 6 5 \n + + == 5*(8**0) + 6 * (8**1) + 0 * (8**2 ) == 53\n 8*2 8**1 8**0\n\n# hexadecimal in multiple backside 16 ** power 2 + last digit ===== to first digit and after add but back right to left value power increased 0,1,2,3,4...??? \n \n'''","sub_path":"python_program/octal_to_decimal.py","file_name":"octal_to_decimal.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"256259654","text":"# class의 역할 : 틀의 역할!\n# => object : 틀을 가지고 만든 실제 대상(객체, 우리가 쓸 수 있는 부품의 형태)\n\nclass Dog:\n\n # 멤버변수\n color = None\n field = ''\n\n # 생성자 함수(객체생성시 자동호출되는 함수, 초기화를 담당)\n def __init__(self,color,field):\n # 생성자에 넣는 가장 많은 초기화처리는 멤버변수값 초기화임.\n self.color = color\n self.field = field\n print('생성자가 호출됨.')\n\n # 오버라이드(재정의)\n # tostring 주소말고 속성값을 보여주도록. return으로 string을 내보냄\n def __str__(self):\n return 'dog의 속성값들 > ' + str(self.color) + ', ' + self.field\n\n # 멤버함수\n def jump(self):\n print('강아지가 점프한다.')\n\n def sleep(self):\n print('강아지가 잔다.')\n\n# 실행할 메인 생성\nif __name__ == '__main__':\n dog1 = Dog('white','진돗개') # 객체생성! 생성자 함수 실행됨. # dog1,dog2는 참조형 변수\n dog2 = Dog('blue','요크셔테리어') # 참조형(주소) = 데이터들이 들어있는 영역에 대한 주소.\n # 객체 생성할 때 dog1에 대한 특성을 저장하기 위해 멤버변수(color, field)가 heap영역에 복사된다.\n print(dog1)\n dog1.jump()\n print(dog2)\n dog2.sleep()\n\n\n","sub_path":"data0506/classmake/animal_module.py","file_name":"animal_module.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"147329267","text":"# -*- coding:utf-8 -*-\nimport os\nfrom configparser import ConfigParser\n\ntry:\n CONFIG_PATH = os.environ.get('PROFITEER_API_CONFIG_PATH')\nexcept Exception:\n raise ValueError\n\n\nconfig = ConfigParser()\nconfig.read(CONFIG_PATH)\n\n# ENV\nENV = config[\"ENV\"]\nCURRENT_ENV = ENV.get(\"CURRENT_ENV\")\n\n\n# gevent 配置\nGEVENT = config[\"GEVENT\"]\nGEVENT_POOL_SIZE = int(GEVENT.get(\"GEVENT_POOL_SIZE\", \"20\"))\n\n\n# PG\nPG = config[\"PG\"]\nPG_POOL_SIZE = int(PG.get(\"PG_POOL_SIZE\", \"20\"))\nPG_MAX_OVER = int(PG.get(\"PG_MAX_OVER\", \"10\"))\nPG_POOL_RECYCLE = int(PG.get(\"PG_POOL_RECYCLE\", \"3600\"))\nPG_POOL_TIMEOUT = int(PG.get(\"PG_POOL_TIMEOUT\", \"500\"))\nPG_URI = PG.get(\"PG_URI\")\n\n\n# MongoDB\nMONGO = config[\"MONGO\"]\nMONGO_POOL_SIZE = MONGO.get(\"MONGO_POOL_SIZE\")\nMONGO_TIMEOUT = MONGO.get(\"MONGO_TIMEOUT\")\nMONGO_CONNECT_TIMEOUT = MONGO.get(\"MONGO_CONNECT_TIMEOUT\")\nMONGO_URI = MONGO.get(\"MONGO_MAIN_URI\")\n\n\n# Redis\nREDIS = config[\"REDIS\"]\nREDIS_POOL_SIZE = REDIS.get(\"REDIS_POOL_SIZE\")\nREDIS_TIMEOUT = REDIS.get(\"REDIS_TIMEOUT\")\nREDIS_CONNECT_TIMEOUT = REDIS.get(\"REDIS_CONNECT_TIMEOUT\")\nREDIS_URI = REDIS.get(\"REDIS_URI\")\n\n\n# user PRC\nRPC = config[\"RPC\"]\nUSER_RPC_SERVERS = RPC.get(\"USER_RPC_SERVERS\").split(',')\n","sub_path":"config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"645996234","text":"#!/usr/bin/env python\n\nfrom os import system,getenv\nfrom sys import argv\nimport argparse\nfrom collections import namedtuple\n\n### SET GLOBAL VARIABLES ###\nbasedir = getenv('SCRAMJETFLAT')+'/' \nparser = argparse.ArgumentParser(description='plot stuff')\nparser.add_argument('--basedir',metavar='basedir',type=str,default=None)\nparser.add_argument('--outdir',metavar='outdir',type=str,default=None)\nargs = parser.parse_args()\n\nylabel = 'Jets'\n\nsname = argv[0]\nif args.basedir:\n basedir = args.basedir\n\nargv=[]\nimport ROOT as root\nroot.gROOT.SetBatch()\nfrom PandaCore.Tools.Misc import *\nimport PandaCore.Tools.Functions\nfrom PandaCore.Drawers.plot_utility import *\nimport PandaCore.Drawers.plot_utility as pu\nimport PandaAnalysis.Tagging.Selection as sel\n\npu.tree_name = 'puppiCA15'\n\n### DEFINE REGIONS ###\n\n### LOAD PLOTTING UTILITY ###\nplot = PlotUtility()\nplot.SetTDRStyle()\nplot.InitLegend()\n#plot.InitLegend(0.7,0.7,0.88,0.9)\nplot.DrawMCErrors(True)\nplot.AddCMSLabel(0.15,0.94,' Simulation')\nplot.cut = 'mSD>110 && mSD<210 && pt<1000'\nplot.SetNormFactor(True)\nplot.AddSqrtSLabel()\nplot.AddPlotLabel(\"110 < m_{SD} < 210 GeV\",.2,.82,False,42,.04)\n\nplot.mc_weight = 'normalizedWeight'\n\n### DEFINE PROCESSES ###\nmatched = Process('Top quark jets',root.kExtra1)\nmatched.additional_cut = 'matched==1 && gensize<1.2'\nmatched.additional_weight = 'ptweight'\n\nqcd = Process('q/g jets',root.kExtra2,1)\n#qcd = Process('q/g jets',root.kExtra2,1)\nqcd.dashed = True\nqcd.additional_weight = 'ptweight_analytic'\nprocesses = [qcd,matched]\n\n### ASSIGN FILES TO PROCESSES ###\nmatched.add_file(basedir+'/ZpTT.root')\nqcd.add_file(basedir+'/QCD.root')\n\nfor p in processes:\n plot.add_process(p)\n\nplot.add_distribution(FDistribution('top_ecfv8_bdt',-1,1,50,'BDT Output','Normalized distribution'))\nplot.add_distribution(FDistribution('tau32SD',0,1,50,'#tau_{32}^{SD}','Normalized distribution'))\n\n\n### DRAW AND CATALOGUE ###\nplot.draw_all(args.outdir)\n","sub_path":"Tagging/plot/plot_scramjet.py","file_name":"plot_scramjet.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"437887802","text":"\"\"\"\nBlade & Soul Character stat.\n\nTo-do:\n\"\"\"\nfrom bs4 import BeautifulSoup\nimport re\nimport requests\n\n\nCOOKIES = {\n# cookies\n}\n\nHEADERS = {\n# headers\n}\n\nRE_STAT = re.compile('
(.*)(.*)
')\n\n\ndef main():\n \"\"\"Main.\"\"\"\n url = 'http://bns.plaync.com/bs/character/profile/Hikai?s=3'\n req = requests.get(url, headers=HEADERS, cookies=COOKIES)\n soup = BeautifulSoup(req.text, \"lxml\")\n stat_name = soup.findAll(\"dt\", {\"class\": \"stat-title\"})\n for stat in stat_name:\n tpl_stat = RE_STAT.findall(str(stat))[0]\n print(\"{}: {}\".format(tpl_stat[0], tpl_stat[1]))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"site/bns_stat.py","file_name":"bns_stat.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"354354560","text":"\nfrom collections import OrderedDict\nimport textwrap\nimport unittest\n\nfrom mock import Mock, ANY\n\nfrom obelus.ami.protocol import (\n BaseAMIProtocol, AMIProtocol, Event, Response, EventList, ActionError)\nfrom obelus.common import Handler\nfrom . import main\n\n\ndef literal_message(text):\n return textwrap.dedent(text.rstrip() + '\\n\\n').encode('utf-8')\n\nEVENT_HANGUP = literal_message(\"\"\"\\\n Event: Hangup\n Privilege: call,all\n Channel: SIP/0004F2060EB4-00000000\n Uniqueid: 1283174108.0\n \"\"\")\n\nCORE_SETTINGS_RESPONSE = literal_message(\"\"\"\\\n Response: Success\n AMIversion: 1.1\n AsteriskVersion: 1.8.13.0~dfsg-1\n \"\"\")\n\nERROR_RESPONSE = literal_message(\"\"\"\\\n Response: Error\n ActionID: 4444\n Message: Invalid/unknown command: xyzzy. (blabla)\n \"\"\")\n\nLOGOFF_RESPONSE = literal_message(\"\"\"\\\n Response: Goodbye\n Message: Thanks for all the fish.\n \"\"\")\n\nCORE_SHOW_VERSION_RESPONSE = literal_message(\"\"\"\\\n Response: Follows\n Privilege: Command\n ActionID: DEF.768\n Asterisk 1.8.13.0~dfsg-1\n --END COMMAND--\n \"\"\")\n\nOTHER_COMMAND_RESPONSE = literal_message(\"\"\"\\\n Response: Follows\n Privilege: Command\n ActionID: 1234\n foo\n bar--END COMMAND--\n \"\"\")\n\nDIALPLAN_START_RESPONSE = literal_message(\"\"\"\\\n Response: Success\n ActionID: 123.567\n EventList: start\n Message: DialPlan list will follow\n \"\"\")\n\nDIALPLAN_RESPONSE_EVENTS = literal_message(\"\"\"\\\n Event: ListDialplan\n ActionID: 123.567\n Context: inbound-call\n Registrar: pbx_config\n\n Event: ListDialplan\n ActionID: 123.567\n Context: default\n IncludeContext: outgoing-call-leg1\n Registrar: pbx_config\n \"\"\")\n\nDIALPLAN_EVENTS_END = literal_message(\"\"\"\\\n Event: ShowDialPlanComplete\n EventList: Complete\n ListItems: 52\n ListExtensions: 19\n ListPriorities: 51\n ListContexts: 19\n ActionID: 123.567\n \"\"\")\n\n\nclass ProtocolTestBase(object):\n\n greeting_line = b\"Asterisk Call Manager/1.4\\r\\n\"\n\n def setUp(self):\n p = self.proto = self.protocol_factory()\n p.greeting_received = Mock()\n\n def ready_proto(self):\n p = self.proto\n p.data_received(self.greeting_line)\n return p\n\n def feed(self, message):\n lines = message.splitlines(True)\n for line in lines:\n self.proto.line_received(line)\n\n def assert_called_once_with_exc(self, callback, exc_class):\n callback.assert_called_once_with(ANY)\n (exc,), _ = callback.call_args\n return exc\n\n\nclass BaseAMIProtocolTest(ProtocolTestBase, unittest.TestCase):\n\n protocol_factory = BaseAMIProtocol\n\n def test_greeting_line(self):\n p = self.proto\n self.assertEqual(p._state, 'init')\n self.assertEqual(p.greeting_received.call_count, 0)\n p.data_received(self.greeting_line)\n p.greeting_received.assert_called_once_with(\n \"Asterisk Call Manager\", \"1.4\")\n self.assertEqual(p._state, 'idle')\n\n def test_event_received(self):\n p = self.ready_proto()\n p.event_received = Mock()\n expected = Event('Hangup', {\n 'Privilege': 'call,all',\n 'Channel': 'SIP/0004F2060EB4-00000000',\n 'Uniqueid': '1283174108.0',\n })\n self.feed(EVENT_HANGUP)\n p.event_received.assert_called_once_with(expected)\n (evt,), _ = p.event_received.call_args\n # Headers are case-insensitive\n self.assertEqual(evt.headers['privilege'], 'call,all')\n self.assertEqual(evt.headers['Privilege'], 'call,all')\n self.assertEqual(p._state, 'idle')\n p.event_received.reset_mock()\n self.feed(EVENT_HANGUP)\n p.event_received.assert_called_once_with(expected)\n self.assertEqual(p._state, 'idle')\n\n def test_response_received(self):\n p = self.ready_proto()\n p.response_received = Mock()\n core_settings = Response('success', {\n 'AMIversion': '1.1',\n 'AsteriskVersion': '1.8.13.0~dfsg-1',\n }, [])\n error = Response('error', {\n 'ActionID': '4444',\n 'Message': 'Invalid/unknown command: xyzzy. (blabla)',\n }, [])\n goodbye = Response('goodbye', {\n 'Message': 'Thanks for all the fish.',\n }, [])\n self.feed(CORE_SETTINGS_RESPONSE)\n p.response_received.assert_called_once_with(core_settings)\n (resp,), _ = p.response_received.call_args\n # Headers are case-insensitive\n self.assertEqual(resp.headers['amiversion'], '1.1')\n self.assertEqual(resp.headers['AmiVersion'], '1.1')\n p.response_received.reset_mock()\n self.feed(ERROR_RESPONSE)\n p.response_received.assert_called_once_with(error)\n p.response_received.reset_mock()\n self.feed(CORE_SETTINGS_RESPONSE)\n p.response_received.assert_called_once_with(core_settings)\n p.response_received.reset_mock()\n self.feed(LOGOFF_RESPONSE)\n p.response_received.assert_called_once_with(goodbye)\n self.assertEqual(p._state, 'idle')\n\n def test_command_response_received(self):\n p = self.ready_proto()\n p.response_received = Mock()\n expected = Response('follows', {\n 'Privilege': 'Command',\n 'ActionID': 'DEF.768',\n }, ['Asterisk 1.8.13.0~dfsg-1'])\n self.feed(CORE_SHOW_VERSION_RESPONSE)\n p.response_received.assert_called_once_with(expected)\n self.assertEqual(p._state, 'idle')\n\n def test_command_response_received_no_eol(self):\n # Sometimes the command payload is concatenated to the\n # '--END COMMAND--' marker without a EOL separator.\n p = self.ready_proto()\n p.response_received = Mock()\n expected = Response('follows', {\n 'Privilege': 'Command',\n 'ActionID': '1234',\n }, ['foo', 'bar'])\n self.feed(OTHER_COMMAND_RESPONSE)\n p.response_received.assert_called_once_with(expected)\n self.assertEqual(p._state, 'idle')\n\n def test_serialize_message(self):\n p = self.ready_proto()\n expected = b\"foo: bar\\r\\n\\r\\n\"\n self.assertEqual(expected, p.serialize_message({'foo': 'bar'}))\n expected = (\n b\"foo: bar\\r\\n\"\n b\"foo: zyxxy\\r\\n\"\n b\"\\r\\n\")\n self.assertEqual(expected,\n p.serialize_message({'foo': ['bar', 'zyxxy']}))\n expected = (\n b\"foo: bar\\r\\n\"\n b\"quux: zyxxy\\r\\n\"\n b\"\\r\\n\")\n headers = OrderedDict([('foo', 'bar'), ('quux', 'zyxxy')])\n self.assertEqual(expected, p.serialize_message(headers))\n\n def test_serialize_message_type_error(self):\n p = self.ready_proto()\n with self.assertRaises(TypeError):\n p.serialize_message({'foo': 1})\n if str is not bytes:\n with self.assertRaises(TypeError):\n p.serialize_message({b'foo': b'bar'})\n\n\nclass AMIProtocolTest(ProtocolTestBase, unittest.TestCase):\n\n protocol_factory = AMIProtocol\n\n def test_event_received(self):\n p = self.ready_proto()\n p.unhandled_event_received = Mock()\n self.feed(EVENT_HANGUP)\n p.unhandled_event_received.assert_called_once_with(\n Event('Hangup', {\n 'Privilege': 'call,all',\n 'Channel': 'SIP/0004F2060EB4-00000000',\n 'Uniqueid': '1283174108.0',\n }))\n\n def test_event_handler(self):\n p = self.ready_proto()\n cb_hangup, cb_foobar = Mock(), Mock()\n p.register_event_handler('Hangup', cb_hangup)\n p.register_event_handler('Foobar', cb_foobar)\n self.feed(EVENT_HANGUP)\n cb_hangup.assert_called_once_with(\n Event('Hangup', {\n 'Privilege': 'call,all',\n 'Channel': 'SIP/0004F2060EB4-00000000',\n 'Uniqueid': '1283174108.0',\n }))\n\n def test_send_action(self):\n p = self.ready_proto()\n p.write = Mock()\n a = p.send_action('Hello', OrderedDict({'foo': 'bar'}))\n self.assertIsInstance(a, Handler)\n p.write.assert_called_once_with(\n b\"foo: bar\\r\\n\"\n b\"Action: Hello\\r\\n\"\n b\"ActionID: 1\\r\\n\"\n b\"\\r\\n\")\n self.assertEqual(a._action_id, '1')\n a = p.send_action('Hi', {'Channel': 'SIP/foo'})\n self.assertIsInstance(a, Handler)\n (data,), _ = p.write.call_args\n lines = data.splitlines()\n self.assertIn(b\"ActionID: 2\", lines)\n self.assertIn(b\"Action: Hi\", lines)\n self.assertIn(b\"Channel: SIP/foo\", lines)\n self.assertEqual(a._action_id, '2')\n self.assertEqual(set(p._actions), {'1', '2'})\n\n def test_send_action_variables(self):\n p = self.ready_proto()\n p.write = Mock()\n a = p.send_action('Hi', OrderedDict(), {})\n (data,), _ = p.write.call_args\n self.assertEqual(data, b\"Action: Hi\\r\\nActionID: 1\\r\\n\\r\\n\")\n a = p.send_action('Hi', {'x': 'y'}, {'foo': '1', 'bar': '2'})\n (data,), _ = p.write.call_args\n lines = data.splitlines(True)\n self.assertEqual(set(lines), {b\"x: y\\r\\n\",\n b\"Variable: foo=1\\r\\n\",\n b\"Variable: bar=2\\r\\n\",\n b\"Action: Hi\\r\\n\",\n b\"ActionID: 2\\r\\n\",\n b\"\\r\\n\"\n })\n\n def test_send_action_override_action_id(self):\n p = self.ready_proto()\n p.write = Mock()\n a = p.send_action('Hi', {'ActionID': 'ABCD'})\n (data,), _ = p.write.call_args\n lines = data.splitlines(True)\n self.assertEqual(set(lines), {b\"Action: Hi\\r\\n\",\n b\"ActionID: ABCD\\r\\n\",\n b\"\\r\\n\"\n })\n self.assertEqual(a._action_id, 'ABCD')\n self.assertEqual(set(p._actions), {'ABCD'})\n\n def test_send_action_response_success(self):\n p = self.ready_proto()\n p.write = Mock()\n a = p.send_action('CoreSettings', {'ActionID': '1234'})\n a.on_result = Mock()\n a.on_exception = Mock()\n resp = literal_message(\"\"\"\\\n Response: Success\n ActionID: 1234\n AsteriskVersion: 1.8.13\n \"\"\")\n p.data_received(resp)\n a.on_result.assert_called_once_with(\n Response('success', {'ActionID': '1234',\n 'AsteriskVersion': '1.8.13'}, []))\n self.assertEqual(a.on_exception.call_count, 0)\n # The handler has been unregistered: no further callbacks\n p.data_received(resp)\n self.assertEqual(a.on_result.call_count, 1)\n self.assertEqual(a.on_exception.call_count, 0)\n\n def test_send_action_response_follows(self):\n p = self.ready_proto()\n p.write = Mock()\n a = p.send_action('Command',\n {'Command': 'core show version',\n 'ActionID': 'DEF.768'})\n a.on_result = Mock()\n a.on_exception = Mock()\n p.data_received(CORE_SHOW_VERSION_RESPONSE)\n a.on_result.assert_called_once_with(\n Response('follows', {'ActionID': 'DEF.768',\n 'Privilege': 'Command'},\n ['Asterisk 1.8.13.0~dfsg-1']))\n self.assertEqual(a.on_exception.call_count, 0)\n\n def test_send_action_response_goodbye(self):\n p = self.ready_proto()\n p.write = Mock()\n a = p.send_action('Logoff',\n {'ActionID': '1234'})\n a.on_result = Mock()\n a.on_exception = Mock()\n resp = literal_message(\"\"\"\\\n Response: Goodbye\n ActionID: 1234\n Message: Thanks for all the fish.\n \"\"\")\n p.data_received(resp)\n a.on_result.assert_called_once_with(\n Response('goodbye', {'ActionID': '1234',\n 'Message': 'Thanks for all the fish.'},\n []))\n self.assertEqual(a.on_exception.call_count, 0)\n\n def test_send_action_response_error(self):\n p = self.ready_proto()\n p.write = Mock()\n a = p.send_action('xyzzy',\n {'ActionID': '4444'})\n a.on_result = Mock()\n a.on_exception = Mock()\n p.data_received(ERROR_RESPONSE)\n self.assertEqual(a.on_result.call_count, 0)\n exc = self.assert_called_once_with_exc(a.on_exception, ActionError)\n self.assertEqual(str(exc), \"Invalid/unknown command: xyzzy. (blabla)\")\n\n def test_send_action_event_list(self):\n p = self.ready_proto()\n p.write = Mock()\n a = p.send_action('ShowDialPlan',\n {'ActionID': '123.567'})\n a.on_result = Mock()\n a.on_exception = Mock()\n p.data_received(DIALPLAN_START_RESPONSE)\n self.assertEqual(a.on_result.call_count, 0)\n self.assertEqual(a.on_exception.call_count, 0)\n p.data_received(DIALPLAN_RESPONSE_EVENTS)\n self.assertEqual(a.on_result.call_count, 0)\n self.assertEqual(a.on_exception.call_count, 0)\n p.data_received(DIALPLAN_EVENTS_END)\n a.on_result.assert_called_once_with(ANY)\n self.assertEqual(a.on_exception.call_count, 0)\n (evlist,), _ = a.on_result.call_args\n self.assertIsInstance(evlist, EventList)\n self.assertEqual(len(evlist.events), 2)\n self.assertEqual(evlist.events[0], Event(\n name='ListDialplan',\n headers={\n 'ActionID': '123.567',\n 'Context': 'inbound-call',\n 'Registrar': 'pbx_config',\n }))\n self.assertEqual(evlist.events[1], Event(\n name='ListDialplan',\n headers={\n 'ActionID': '123.567',\n 'Context': 'default',\n 'IncludeContext': 'outgoing-call-leg1',\n 'Registrar': 'pbx_config',\n }))\n # End headers are merged with start headers\n self.assertEqual(evlist.headers, {\n 'ActionID': '123.567',\n 'EventList': 'Complete',\n 'ListItems': '52',\n 'ListExtensions': '19',\n 'ListPriorities': '51',\n 'ListContexts': '19',\n 'ActionID': '123.567',\n 'Message': 'DialPlan list will follow',\n })\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"obelus/test/test_amiprotocol.py","file_name":"test_amiprotocol.py","file_ext":"py","file_size_in_byte":14564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"288336323","text":"import logging\nfrom json import JSONDecodeError\n\nfrom bunq.sdk import context\n\nlogger = logging.getLogger(__name__)\n\n\nclass Client:\n @classmethod\n def setup_api_context(cls, environment, api_key, description):\n try:\n return context.ApiContext.restore()\n except (FileNotFoundError, JSONDecodeError):\n ctx = context.ApiContext(environment, api_key, description)\n ctx.save()\n\n @classmethod\n def ctx(cls):\n try:\n return context.ApiContext.restore()\n except (FileNotFoundError, JSONDecodeError):\n logger.critical(\n 'ApiContext not yet set. Set it up before using it.')\n","sub_path":"pinsparen/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"61197732","text":"from django.conf.urls import url\r\nfrom .views import (\r\n HomeView,\r\n CreateEmployeeView,\r\n HomeViewStaff,\r\n UpdateEmployeeView,\r\n ListEmployeeView,\r\n DeleteEmployeeView,\r\n EmpJson,\r\n )\r\n\r\nurlpatterns = [\r\n url(r'^$', HomeView.as_view(), name = 'home'),\r\n url(r'^home/$', HomeViewStaff.as_view(), name = 'staffhome'),\r\n url(r'^register/$', CreateEmployeeView.as_view(), name = 'create-employee'),\r\n url(r'^list-employee/$', ListEmployeeView.as_view(), name = 'list-employees'),\r\n url(r'^update-employee/(?P\\d+)/$', UpdateEmployeeView.as_view(), name = 'update-employee'),\r\n url(r'^delete-employee/(?P\\d+)/delete/$', DeleteEmployeeView.as_view(), name = 'remove-employee'),\r\n url(r'^emp-list-json', EmpJson, name= 'emp-list-json'),\r\n]","sub_path":"Django_sample_production_web/apps/profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"418880690","text":"\"\"\"\nAR_XpressoExampleScript\n\nAuthor: Arttu Rautio (aturtur)\nWebsite: http://aturtur.com/\nName-US: AR_XpressoExampleScript\nDescription-US: Creates xpresso setup with couple connected nodes\n> Select object and run the script\nWritten for Maxon Cinema 4D R20.057\n\"\"\"\n# Libraries\nimport c4d\n\n# Functions\ndef main():\n doc = c4d.documents.GetActiveDocument() # Get active document\n selected = doc.GetActiveObject() # Get active object\n\n # Tag setup\n xpressotag = c4d.BaseTag(c4d.Texpresso) # Initialize xpresso tag\n xpressotag.SetName(\"My Xpresso Tag\") # Set xpresso tag name\n selected.InsertTag(xpressotag) # Insert xpresso tag to selected object\n nodemaster = xpressotag.GetNodeMaster() # Get node master\n\n # Node creation\n mathNode = nodemaster.CreateNode(nodemaster.GetRoot(), 400001121, None, x=200, y=100)\n constantNodeA = nodemaster.CreateNode(nodemaster.GetRoot(), 400001120, None, x=100, y=100)\n constantNodeB = nodemaster.CreateNode(nodemaster.GetRoot(), 400001120, None, x=100, y=150)\n resultNode = nodemaster.CreateNode(nodemaster.GetRoot(), 400001118, None, x=350, y=100)\n\n # Node values\n constantNodeA[c4d.GV_CONST_VALUE] = 10\n constantNodeB[c4d.GV_CONST_VALUE] = 5\n mathNode[c4d.GV_MATH_FUNCTION_ID] = 1\n\n # Ports\n constantPortOutA = constantNodeA.GetOutPort(0)\n constantPortOutB = constantNodeB.GetOutPort(0)\n mathPortInA = mathNode.GetInPort(0)\n mathPortInB = mathNode.GetInPort(1)\n mathPortOut = mathNode.GetOutPort(0)\n resultPortIn = resultNode.GetInPort(0)\n\n # Connecting ports\n constantPortOutA.Connect(mathPortInA)\n constantPortOutB.Connect(mathPortInB)\n mathPortOut.Connect(resultPortIn)\n\n # Refresh\n c4d.modules.graphview.RedrawMaster(nodemaster) # Refresh xpresso graph view\n c4d.EventAdd() # Refresh Cinema 4D\n\n# Execute main()\nif __name__=='__main__':\n main()","sub_path":"AR_XpressoExampleScript.py","file_name":"AR_XpressoExampleScript.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"158280047","text":"import os\nimport sys\n\npath = '/home/tugrulv89/shopistproject'\nif path not in sys.path:\n sys.path.insert(0, path)\nos.environ['DJANGO_SETTINGS_MODULE'] = 'shopistproject.settings'\nimport django\n\ndjango.setup()\nfrom django.core.wsgi import get_wsgi_application\n\napplication = get_wsgi_application()\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom Shopist.models import ContentBlog\nimport datetime\n\nsitecontent = []\n\n# atasunoptik mode blog next page 8 gözüküyor.\nfor i in range(1,2):\n i = str(i)\n atasunurl = requests.get(\"http://www.atasunoptik.com.tr/blog/category/moda-ve-trend/page/\" + i + \"/\")\n ataxlm = BeautifulSoup(atasunurl.content, \"lxml\")\n atasuncontent = ataxlm.find_all('div', class_=\"td-module-thumb\")\n for contentata in atasuncontent:\n urlata = contentata.find('a').attrs['href'].replace('//', '')\n ata = requests.get('http://' + urlata)\n atas = BeautifulSoup(ata.content, \"lxml\")\n atasun = atas.find('div', class_=\"td-ss-main-content\")\n sitecontent.append({\n \"title\": atasun.find('h1').get_text(),\n \"image\": \"http://\" + atasun.find('img').get('src').replace('//', ''),\n \"content\": atasun.find('p').get_text(),\n \"site\": \"Atasun\",\n \"slug\": (\"http://\" + urlata).split(\"/\")[-2],\n })\n\n# Pembe Ruj mode blog next page 8 gözüküyor.\nfor pm in range(1,2):\n pm = str(pm)\n atasunurl = requests.get(\"http://pemberuj.net/kategori/moda/page/\" + pm + \"/\")\n ataxlm = BeautifulSoup(atasunurl.content, \"lxml\")\n atacss = ataxlm.find('div', class_=\"td-ss-main-content\")\n atasuncontent = atacss.find_all(\"h3\", class_=\"entry-title\")\n for contentata in atasuncontent:\n urlata = contentata.find('a').attrs['href']\n ata = requests.get(urlata)\n atas = BeautifulSoup(ata.content, \"lxml\")\n atasun = atas.find('div', class_=\"td-ss-main-content\")\n sitecontent.append({\n \"title\": atasun.find('h1', class_=\"entry-title\").get_text(),\n \"image\": atasun.find('img').get('src'),\n \"content\": atasun.find('div', class_=\"td-post-content\").get_text().strip(),\n \"site\": \"Pembe Ruj\",\n \"slug\": urlata.split(\"/\")[-2],\n })\n\nfor pm in range(1,2):\n pm = str(pm)\n atasunurl = requests.get(\"http://blog.sateen.com/page/\" + pm + \"/\")\n ataxlm = BeautifulSoup(atasunurl.content, \"lxml\")\n atacss = ataxlm.find('div', class_=\"content content-home\")\n atasuncontent = atacss.find_all(\"h2\", class_=\"title entry-title\")\n for contentata in atasuncontent:\n urlata = contentata.find('a').attrs['href']\n ata = requests.get(urlata)\n atas = BeautifulSoup(ata.content, \"lxml\")\n atasun = atas.find('div', class_=\"content\")\n sitecontent.append({\n \"title\": atasun.find('h1', class_=\"title entry-title\").get_text(),\n \"image\": atasun.find('img', class_=\"attachment-featured size-featured wp-post-image\").get('src'),\n \"content\": atasun.find('div', class_=\"post-content entry-content single-post-content\").get_text().strip(),\n \"site\": \"saaten\",\n \"slug\": (urlata.split(\"/\")[-2]).split(\".\")[0],\n })\n\n\n\n\n\nfor objectitem in sitecontent:\n cfa = ContentBlog(title=objectitem['title'],\n image=objectitem['image'],\n content=objectitem['content'],\n site=objectitem['site'],\n slug=objectitem['slug'])\n cfa.save()\n\n","sub_path":"bs4cron/blogcontentblade.py","file_name":"blogcontentblade.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"92620674","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nisMinHeap = True # 小顶堆 or 大顶堆\n# 数组实现\nheap = []\n\n# 获取父节点\ndef getFather(iIdx):\n return heap[getFatherIdx(iIdx)]\ndef getFatherIdx(iIdx):\n return (iIdx - 1) / 2\n\n# 获取子节点下标 return [left, right]\ndef getChildrenIdx(iIdx):\n return [iIdx * 2 + 1, iIdx * 2 + 2]\n\n# 入堆(上滤)\ndef pushHeap(iNum):\n heap.append(iNum)\n iIdx = len(heap) - 1\n while True:\n if iIdx == 0:\n break\n iFather = getFather(iIdx)\n bNeedChangePos = iFather > iNum if isMinHeap else iFather < iNum\n if bNeedChangePos:\n # heap[iIdx], heap[getFatherIdx(iIdx)] = iFather, iNum\n heap[iIdx] = iFather\n iIdx = getFatherIdx(iIdx)\n else:\n break\n heap[iIdx] = iNum\n\n# 出堆(下滤)\ndef popHeap():\n if len(heap) <= 1:\n return heap.pop()\n iRes = heap[0]\n iLast = heap.pop()\n\n iSecIdx = 0 # 正在下滤的下标\n while True:\n lChildIdx = getChildrenIdx(iSecIdx)\n\n if lChildIdx[0] >= len(heap):\n break\n iSubChildIdx = lChildIdx[0]\n if lChildIdx[1] < len(heap) and \\\n heap[lChildIdx[1]] < heap[lChildIdx[0]] if isMinHeap else heap[lChildIdx[1]] > heap[lChildIdx[0]]:\n iSubChildIdx = lChildIdx[1]\n if heap[iSubChildIdx] < iLast if isMinHeap else heap[iSubChildIdx] > iLast:\n heap[iSecIdx] = heap[iSubChildIdx]\n iSecIdx = iSubChildIdx\n else:\n break\n heap[iSecIdx] = iLast\n return iRes\n","sub_path":"算法相关/寻路/A星/heap.py","file_name":"heap.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"129894719","text":"# -*- coding: utf-8 -*-\n#\n# Watches for changes in a directory.\n# - Run a program when there is a new XML file.\n# - Publish the changes back.\n#\nimport os\nimport sys\nimport time\nimport glob\nimport uuid\nfrom datetime import datetime\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\nimport pymongo\nfrom pymongo import *\nimport bson\nfrom urllib.parse import urlparse\nimport tinys3\n\nclass Document(object):\n use_dot_notation = True\n use_schemaless = True\n structure = {}\n required_fields = []\n default_values = {}\n\nclass Connect(Document):\n __db = None\n __username = None\n __password = None\n __host = None\n __port = None\n\n def __init__(self):\n self.set_uri()\n\n return None\n\n def set_uri(self):\n uri = urlparse(os.environ.get('MONGO_URL'))\n self.__db = uri.path.split('/')[-1]\n self.__username = uri.username\n self.__password = uri.password\n self.__host = uri.hostname\n self.__port = uri.port\n\n def connection(self):\n # self.set_uri()\n print('---> Connecting to {}:{}'.format(self.__host, self.__port))\n client = MongoClient(self.__host, self.__port)\n try:\n client[self.__db].authenticate(self.__username, self.__password)\n except:\n print('---> Failed authenticating to database')\n\n # Returns the database\n return client[self.__db]\n\nclass Plan(Connect):\n use_dot_notation = True\n use_schemaless = True\n structure = {\n 'workspaceId': u'',\n 'owner': u'',\n 'creator': u'',\n 'createdAt': datetime,\n 'rawData': u'',\n 'imageURL': u''\n }\n required_fields = [\n 'workspaceId',\n 'creator'\n ]\n default_values = {\n 'createdAt': datetime.utcnow()\n }\n\n # required fields:\n # - workspaceId \n # - creator \n def __init__(self, **kwargs):\n super().__init__()\n self.workspaceId = kwargs.get('workspaceId', '0')\n self.creator = kwargs.get('creator', 'No creator')\n self.createdAt = datetime.utcnow()\n\n return None\n\n def upload(self, file_path):\n aws_key = os.environ.get('AWS_KEY')\n aws_secret = os.environ.get('AWS_SECRET')\n s3_endpoint = os.environ.get('AWS_ENDPOINT')\n container_name = os.environ.get('AWS_CONTAINER')\n\n file_name = '{}-p-{}.svg'.format(self.workspaceId, uuid.uuid4())\n upload_path = 'plans/{}'.format(file_name)\n\n print('---> Connecting to the cloud storage at {}'.format(s3_endpoint))\n conn = tinys3.Connection(aws_key, aws_secret, tls=True, endpoint=s3_endpoint)\n\n with open(file_path, 'rb') as file_data:\n conn.upload(upload_path, file_data, container_name)\n\n print('---> Uploading to {}/{}'.format(container_name, upload_path))\n return upload_path\n\n\n\n\n # Write a new plan with data\n def push(self, workspaceId, svgFileURL):\n conn = self.connection()\n\n data = {\n 'workspaceId': self.workspaceId,\n 'creator': self.creator,\n 'createdAt': self.createdAt,\n 'imageURL': svgFileURL,\n # 'rooms': workspace['rooms'],\n # 'relations': workspace['relations']\n }\n return conn.plans.insert(data)\n\n\n\nclass PoolListener(FileSystemEventHandler):\n def __init_(self, src_path):\n super(FileSystemEventHandler, self).__init__(src_path)\n\n def dispatch(self, event):\n if event.event_type == 'created':\n with open(os.path.join('log', 'svg.log'), 'a') as f:\n f.write('{}: New svg file\\n'.format(datetime.utcnow()))\n\n # get the newest file from the plans subdirectories.\n # The format is tmp/plans//*.svg\n newest_file = event.src_path\n\n # Check if it is a .svg file\n _, file_extension = os.path.splitext(newest_file)\n if ((file_extension != '.svg') and (file_extension != '.SVG')):\n return False\n\n # get the workspace direcotry\n workspace_dir = os.path.abspath(os.path.join(newest_file, os.pardir))\n workspace_id = workspace_dir.split('/')[-1]\n # check if the file is under a workspace folder\n if workspace_id == 'plans':\n return False\n\n # Upload the file\n plan = Plan(workspaceId=workspace_id)\n\n # need to change if the file has uploaded\n svg_url = plan.upload(newest_file)\n\n # need to check if the insert was successful\n # https://s3-us-west-1.amazonaws.com/yougenius/plans/Mbxx7vfp3YpWXbuTo-p-3ff0bafc-95d3-43bb-852b-39345a74b60e.svg\n plan.push(workspace_id, 'https://s3-us-west-1.amazonaws.com/yougenius/{}'.format(svg_url))\n\n return True\n\nif __name__ == '__main__':\n print('---> Starting observing {}'.format(datetime.utcnow()))\n path = os.path.abspath(os.path.join('tmp', 'plans'))\n event_handler = PoolListener()\n observer = Observer()\n\n observer.schedule(event_handler, path, recursive=True)\n observer.start()\n\n try:\n while True:\n time.sleep(1)\n except:\n observer.stop()\n observer.join()\n","sub_path":"workers/subscribe_svg.py","file_name":"subscribe_svg.py","file_ext":"py","file_size_in_byte":5202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"80875792","text":"from django import forms \nimport datetime\nclass FieldsForm(forms.Form):\n\n '''\n 1. d = dgs\n 2. t = t10\n 3. conf = confirmed_cases\n 4. rec = recovered_cases\n 5. dth = death\n 6. un = enemployment\n 7. gas = gas_prices\n 8. dies = diesel_prices \n '''\n\n # Row 1\n d1 = forms.CharField(widget=forms.NumberInput(attrs={'id': 'd1_range','class': 'slider-range', 'type':'range', 'value': '2.66', 'step': '.01', 'min': '1.00', 'max': '100.00'}), required=False)\n #d1_ = forms.CharField(widget=forms.TextInput(attrs={'class':'value',}), required=False)\n d1_= forms.CharField(max_length=10, widget= forms.TextInput(attrs={'class':'input-value'}))\n t1 = forms.CharField(widget=forms.NumberInput(attrs={'id': 't1_range','class': 'slider-range', 'type':'range', 'value': '1.7', 'step': '.01', 'min': '1.00', 'max': '100.00'}), required=False)\n t1_= forms.CharField(max_length=10, widget= forms.TextInput(attrs={'class':'input-value'}))\n conf1 = forms.CharField(widget=forms.NumberInput(attrs={'id': 'conf1_range','class': 'slider-range', 'type':'range','value': '1000', 'step': '1', 'min': '1', 'max': '1000000'}), required=False)\n conf1_= forms.CharField(max_length=10, widget= forms.TextInput(attrs={'class':'input-value'}))\n rec1 = forms.CharField(widget=forms.NumberInput(attrs={'id': 'rec1_range','class': 'slider-range', 'type':'range', 'value': '200','step': '1', 'min': '1', 'max': '1000000'}), required=False)\n rec1_= forms.CharField(max_length=10, widget= forms.TextInput(attrs={'class':'input-value'}))\n dth1 = forms.CharField(widget=forms.NumberInput(attrs={'id': 'dth1_range','class': 'slider-range', 'type':'range', 'value': '50','step': '1', 'min': '1', 'max': '1000000'}), required=False)\n dth1_= forms.CharField(max_length=10, widget= forms.TextInput(attrs={'class':'input-value'}))\n un1 = forms.CharField(widget=forms.NumberInput(attrs={'id': 'un1_range','class': 'slider-range', 'type':'range','value': '220100.0', 'step': '.01', 'min': '1', 'max': '1000000.0'}), required=False)\n un1_= forms.CharField(max_length=10, widget= forms.TextInput(attrs={'class':'input-value'}))\n gas1 = forms.CharField(widget=forms.NumberInput(attrs={'id': 'gas1_range','class': 'slider-range', 'type':'range', 'value': '2.329','step': '.001', 'min': '1', 'max': '25.000'}), required=False)\n gas1_= forms.CharField(max_length=10, widget= forms.TextInput(attrs={'class':'input-value'}))\n dies1 = forms.CharField(widget=forms.NumberInput(attrs={'id': 'dies1_range','class': 'slider-range', 'type':'range', 'value': '3.013','step': '.001', 'min': '1', 'max': '25.000'}), required=False)\n dies1_= forms.CharField(max_length=10, widget= forms.TextInput(attrs={'class':'input-value'}))\n file = forms.FileField()\n #d1 = forms.DecimalField(label='d1') \n #t1 = forms.DecimalField(label='t1') \n #conf1 = forms.IntegerField(label='conf1')\n #rec1 = forms.IntegerField(label='rec1') \n #dth1 = forms.IntegerField(label='dth1')\n #un1 = forms.IntegerField(label='un1')\n #gas1 = forms.DecimalField(label='gas1')\n #dies1 = forms.DecimalField(label='dies1')\n #sel1 = forms.BooleanField(label='sel1')\n\n # Row 2\n '''d2 = forms.DecimalField(label='d2') \n t2 = forms.DecimalField(label='t2') \n conf2 = forms.IntegerField(label='conf2')\n rec2 = forms.IntegerField(label='rec2') \n dth2 = forms.IntegerField(label='dth2')\n un2 = forms.IntegerField(label='un2')\n gas2 = forms.DecimalField(label='gas2')\n dies2 = forms.DecimalField(label='dies2')\n sel2 = forms.BooleanField(label='sel2')\n\n # Row 3\n d3 = forms.DecimalField(label='d3') \n t3 = forms.DecimalField(label='t3') \n conf3 = forms.IntegerField(label='conf3')\n rec3 = forms.IntegerField(label='rec3') \n dth3 = forms.IntegerField(label='dth3')\n un3 = forms.IntegerField(label='un3')\n gas3 = forms.DecimalField(label='gas3')\n dies3 = forms.DecimalField(label='dies3')\n sel3 = forms.BooleanField(label='sel3')\n\n # Row 4\n d4 = forms.DecimalField(label='d4') \n t4 = forms.DecimalField(label='t4') \n conf4 = forms.IntegerField(label='conf4')\n rec4 = forms.IntegerField(label='rec4') \n dth4 = forms.IntegerField(label='dth4')\n un4 = forms.IntegerField(label='un4')\n gas4 = forms.DecimalField(label='gas4')\n dies4 = forms.DecimalField(label='dies4')\n sel4 = forms.BooleanField(label='sel4')\n\n # Row 5\n d5 = forms.DecimalField(label='d5') \n t5 = forms.DecimalField(label='t5') \n conf5 = forms.IntegerField(label='conf5')\n rec5 = forms.IntegerField(label='rec5') \n dth5 = forms.IntegerField(label='dth5')\n un5 = forms.IntegerField(label='un5')\n gas5 = forms.DecimalField(label='gas5')\n dies5 = forms.DecimalField(label='dies5')\n sel5 = forms.BooleanField(label='sel5')\n\n # Row 6\n d6 = forms.DecimalField(label='d6') \n t6 = forms.DecimalField(label='t6') \n conf6 = forms.IntegerField(label='conf6')\n rec6 = forms.IntegerField(label='rec6') \n dth6 = forms.IntegerField(label='dth6')\n un6 = forms.IntegerField(label='un6')\n gas6 = forms.DecimalField(label='gas6')\n dies6 = forms.DecimalField(label='dies6')\n sel6 = forms.BooleanField(label='sel6')\n\n #dgs = forms.DecimalField(label='dgs') \n #t10 = forms.DecimalField(label='t10') \n #confirmed_cases = forms.IntegerField(label='confirmed_cases')\n #recovered_cases = forms.IntegerField(label='recovered_cases')\n #deaths = forms.IntegerField(label='deaths')\n #unemployment = forms.IntegerField(label='unemployment')\n #gas_prices = forms.DecimalField(label='gas_prices')\n #diesel_prices = forms.DecimalField(label='diesel_prices')'''\n ","sub_path":"website/c19/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"193119666","text":"from django.test import TestCase\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom .models import Hero\n\n\nclass HeroCRUDTest(TestCase):\n\n def test_django(self):\n print(\"11\")\n self.assertTrue\n\n def test_num_hero(self):\n print(\"10\")\n self.assertEqual(len(Hero.objects.all()), 0)\n\n def test_add_hero(self):\n print(\"9\")\n Hero.objects.create(name='Wolverine', identity='Logan Howlett')\n Hero.objects.create(name='SpiderMan', identity='Peter Parker')\n self.assertEqual(len(Hero.objects.all()), 2)\n\n\n def test_hero_title(self):\n print(\"8\")\n Hero.objects.create(name='Wolverine', identity='Logan Howlett')\n h = Hero.objects.get(pk=1)\n self.assertEqual(h.name, 'Wolverine')\n self.assertEqual(h.identity, 'Logan Howlett')\n\n #Test 7 will fail if run\n def test_hero_edit(self):\n print(\"7\")\n Hero.objects.create(name='Wolverine', identity='Logan Howlett')\n h = Hero.objects.get(pk=1)\n h.name = 'Mark Seaman'\n h.save()\n self.assertEqual(h.name, 'Wolverine')\n self.assertEqual(h.identity, 'Logan Howlett')\n\n def test_hero_edit(self):\n print(\"6\")\n Hero.objects.create(name='Wolverine', identity='Logan Howlett')\n h = Hero.objects.get(pk=1)\n h.delete()\n self.assertEqual(len(Hero.objects.all()), 0)\n\n def test_string_representation(self):\n print(\"5\")\n hero = Hero.objects.create(name='Wolverine', identity='Logan Howlett')\n self.assertEqual(\n str(hero), '1 - Wolverine AKA Logan Howlett')\n \n\n\nclass HeroViewsTest(TestCase):\n\n def test_home(self):\n print(\"4\")\n response = self.client.get('/')\n self.assertEqual(response.status_code, 302)\n\n def test_get_absolute_url(self):\n print(\"3\")\n hero = Hero.objects.create(name='Wolverine', identity='Logan Howlett')\n self.assertEqual(hero.get_absolute_url(), '/hero/1')\n\n #Test 2 will fail if run\n def test_hero_list_view(self):\n print(\"2\")\n response = self.client.get(reverse('hero_list'))\n self.assertEqual(response.status_code, 200)\n\n def test_hero_list_view(self):\n print(\"1\")\n response = self.client.get('/hero/')\n self.assertTemplateUsed(response, 'hero_list.html')\n self.assertTemplateUsed(response, 'hero_theme.html')\n\n","sub_path":"week6/Superhero/hero/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"368988815","text":"#\n# pr9_5_1\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.signal import hilbert\n\nif __name__ == '__main__':\n\tfs = 400 # sample frequency\n\tN = 400 # data length\n\tn = np.arange(0, N)\n\tdt = 1 / fs\n\tt = n * dt # time sequence\n\tA = 0.5 # pluse modulation amplitude\n\t# signal\n\tx = (1 + 0.5 * np.cos(2 * np.pi * 5 * t)) * np.cos(2 * np.pi * 50 * t + A * np.sin(2 * np.pi * 10 * t))\n\tz = hilbert(x)\n\ta = np.abs(z) # envelope\n\tfnor = (np.diff(np.unwrap(np.angle(z)))) / (2 * np.pi) # instantaneous frequency\n\tFNOR = np.zeros(len(z))\n\tFNOR[0] = fnor[0]\n\tFNOR[1:] = fnor\n\t\n\t# figure\n\tplt.figure(1, figsize=(16, 9))\n\tplt.subplot(3, 1, 1)\n\tplt.plot(t, x)\n\tplt.axis([0, max(t), min(x), max(x)])\n\tplt.xlabel('Times [s]')\n\tplt.ylabel('Amplitude')\n\tplt.title('Singal')\n\tplt.subplot(3, 1, 2)\n\tplt.plot(t, a)\n\tplt.axis([0, max(t), 0.4, 1.6])\n\tplt.xlabel('Times [s]')\n\tplt.ylabel('Amplitude')\n\tplt.title('Envelope')\n\tplt.subplot(3, 1, 3)\n\tplt.plot(t, FNOR * fs)\n\tplt.axis([0, max(t), 43, 57])\n\tplt.xlabel('Times [s]')\n\tplt.ylabel('Amplitude')\n\tplt.title('Instantaneous frequency')\n\tplt.savefig('images/Hilbert_Transform', bbox_inches='tight', dpi=600)\n\tplt.show()\n","sub_path":"Chapter9_FormatDetection/pr9_5_1.py","file_name":"pr9_5_1.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"374593700","text":"import sys\nimport argparse\nimport codecs\nimport json\n\ndef attemptIntegerConversion(text):\n\ttry:\n\t\tnumber = int(text)\n\t\treturn number\n\texcept:\n\t\tpass\n\treturn None\n\ndef integerOrNone(text):\n\tif len(text) == 0:\n\t\treturn None\n\telse:\n\t\treturn int(text)\n\ndef file_len(fname):\n\twith open(fname) as f:\n\t\tfor i, l in enumerate(f):\n\t\t\tpass\n\treturn i + 1\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Converts the output of the SentenceSelector to the ST format expected by the annotator and by VERSE')\n\tparser.add_argument('--sentencesFile',type=str,required=True,help='File containing sentences with PMID and entity information')\n\tparser.add_argument('--outDir',type=str,required=True,help='Output directory to save converted files')\n\n\targs = parser.parse_args()\n\n\toutDir = args.outDir\n\tif not outDir.endswith('/'):\n\t\toutDir += '/'\n\n\ttotalLineCount = file_len(args.sentencesFile)\n\tnextPerc = 0.0\n\n\twith codecs.open(args.sentencesFile,'r','utf-8') as inFile:\n\t\tfor sentenceid,line in enumerate(inFile):\n\t\t\tperc = 100.0 * sentenceid / float(totalLineCount)\n\t\t\tif perc > nextPerc:\n\t\t\t\tprint(\"%.1f%%\" % perc)\n\t\t\t\tnextPerc += 1.0\n\n\n\t\t\tsplit = line.rstrip().split('\\t')\n\t\t\tassert len(split) > 4, \"Failed at sentence %d\" % sentenceid\n\t\t\tpmid = split[0]\n\t\t\tpmcid = split[1]\n\t\t\tpubyear = split[2]\n\t\t\ttext = split[3]\n\t\t\t\n\t\t\tbase = \"%s%08d\" % (outDir,sentenceid)\n\t\t\ttxtFilename = base + '.txt'\n\t\t\ta1Filename = base + '.a1'\n\t\t\tjsonFilename = base + '.json'\n\n\t\t\twith codecs.open(txtFilename,'w','utf-8') as txtFile:\n\t\t\t\ttxtFile.write(text)\n\n\t\t\t#print text\n\t\t\t#print split[3:]\n\t\t\tjsonData = {}\n\t\t\tjsonData['pmid'] = integerOrNone(pmid)\n\t\t\tjsonData['pmcid'] = integerOrNone(pmcid)\n\t\t\tjsonData['text'] = text\n\t\t\tjsonData['pubyear'] = pubyear\n\t\t\tjsonData['entities'] = {}\n\t\t\t\n\t\t\twith codecs.open(a1Filename,'w','utf-8') as a1File:\n\t\t\t\tfor entityid,entityData in enumerate(split[4:]):\n\t\t\t\t\tentitytype,entityids,start,end,entitytxt = entityData.split('|')\n\t\t\t\t\tentityidtxt = \"T%d\" % (entityid+1)\n\t\t\t\t\tstart,end = int(start),int(end)\n\t\t\t\t\t#print start,end, text[start:end]\n\t\t\t\t\tassert entitytxt == text[start:end], u\"%s != %s (%s)\" % (entitytxt, text[start:end], base)\n\t\t\t\t\tline = u\"%s\\t%s %d %d\\t%s\\n\" % (entityidtxt,entitytype,start,end,entitytxt)\n\t\t\t\t\ta1File.write(line)\n\n\t\t\t\t\tentityDict = {}\n\t\t\t\t\tentityDict['entitytype'] = entitytype\n\t\t\t\t\tentityDict['entityids'] = entityids\n\t\t\t\t\tentityDict['start'] = start\n\t\t\t\t\tentityDict['end'] = end\n\t\t\t\t\tentityDict['entitytxt'] = entitytxt\n\n\t\t\t\t\tjsonData['entities'][entityidtxt] = entityDict\n\n\n\n\t\t\twith open(jsonFilename,'w') as jsonFile:\n\t\t\t\tjson.dump(jsonData,jsonFile,indent=4)\n\n","sub_path":"parsing/ConvertSentencesToSTFormat.py","file_name":"ConvertSentencesToSTFormat.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172119482","text":"##############################################################################\n#\n# Copyright (c) 2004 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Functional Tests for Onlinehelp\n\n$Id$\n\"\"\"\nimport os\nimport transaction\nimport unittest\n\nfrom zope.site.interfaces import IRootFolder\nfrom zope.app.file import File\nfrom zope.app.testing.functional import BrowserTestCase\nfrom zope.app.onlinehelp.tests.test_onlinehelp import testdir\nfrom zope.app.onlinehelp import globalhelp\nfrom zope.app.onlinehelp.testing import OnlineHelpLayer\n\nclass Test(BrowserTestCase):\n\n def test_contexthelp(self):\n path = os.path.join(testdir(), 'help.txt')\n globalhelp.registerHelpTopic('help', 'Help', '', path, IRootFolder)\n path = os.path.join(testdir(), 'help2.txt')\n globalhelp.registerHelpTopic('help2', 'Help2', '', path, IRootFolder,\n 'contents.html')\n\n transaction.commit()\n\n response = self.publish(\"/+/action.html\", basic='mgr:mgrpw',\n form={'type_name':u'zope.app.content.File',\n 'id':u'file'})\n\n self.assertEqual(response.getStatus(), 302)\n\n response = self.publish('/contents.html', basic='mgr:mgrpw')\n\n self.assertEqual(response.getStatus(), 200)\n body = ' '.join(response.getBody().split())\n self.assert_(body.find(\n \"javascript:popup('contents.html/++help++/@@contexthelp.html\") >= 0)\n\n response = self.publish(\n '/contents.html/++help++/@@contexthelp.html', basic='mgr:mgrpw')\n\n self.assertEqual(response.getStatus(), 200)\n body = ' '.join(response.getBody().split())\n self.assert_(body.find(\"This is another help!\") >= 0)\n\n response = self.publish('/index.html/++help++/@@contexthelp.html',\n basic='mgr:mgrpw')\n\n self.assertEqual(response.getStatus(), 200)\n body = ' '.join(response.getBody().split())\n self.assert_(body.find(\"This is a help!\") >= 0)\n\n response = self.publish('/file/edit.html/++help++/@@contexthelp.html',\n basic='mgr:mgrpw')\n\n self.assertEqual(response.getStatus(), 200)\n body = ' '.join(response.getBody().split())\n self.assert_(body.find(\n \"Welcome to the Zope 3 Online Help System.\") >= 0)\n\n path = '/contents.html/++help++'\n response = self.publish(path, basic='mgr:mgrpw')\n\n self.assertEqual(response.getStatus(), 200)\n body = ' '.join(response.getBody().split())\n self.assert_(body.find(\"Topics\") >= 0)\n\n self.checkForBrokenLinks(body, path, basic='mgr:mgrpw')\n\n\ndef test_suite():\n Test.layer = OnlineHelpLayer\n return unittest.makeSuite(Test)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"zope.app.onlinehelp/branches/3.5/src/zope/app/onlinehelp/browser/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"639400529","text":"import argparse\nimport os\nimport sys\nimport time\nfrom copy import deepcopy\nimport pdb\n\nimport numpy as np\nimport torch\nimport torch.utils.data\n\nfrom utils import audio as audioutils\nfrom utils import datain\nfrom utils import utils\nfrom utils import vocoder\n\n########################################################################################################################\n\n# Arguments\nparser = argparse.ArgumentParser(description='Audio synthesis script')\nparser.add_argument('--seed_input', default=0, type=int, required=False,\n help='(default=%(default)d)')\nparser.add_argument('--seed', default=0, type=int, required=False,\n help='(default=%(default)d)')\nparser.add_argument('--device', default='cuda', type=str, required=False,\n help='(default=%(default)s)')\n# Data\nparser.add_argument('--path_data', default='', type=str, required=False,\n help='(default=%(default)s)')\nparser.add_argument('--trim', default=-1, type=float, required=False,\n help='(default=%(default)f)')\nparser.add_argument('--base_fn_model', default='', type=str, required=True,\n help='(default=%(default)s)')\nparser.add_argument('--path_out', default='../res/', type=str, required=True,\n help='(default=%(default)s)')\nparser.add_argument('--split', default='test', type=str, required=False,\n help='(default=%(default)s)')\nparser.add_argument('--force_source_file', default='', type=str,\n required=False, help='(default=%(default)s)')\nparser.add_argument('--force_source_speaker', default='', type=str,\n required=False, help='(default=%(default)s)')\nparser.add_argument('--force_target_speaker', default='', type=str,\n required=False, help='(default=%(default)s)')\n# Conversion\nparser.add_argument('--fn_list', default='', type=str, required=False,\n help='(default=%(default)s)')\nparser.add_argument('--sbatch', default=256, type=int, required=False,\n help='(default=%(default)d)')\nparser.add_argument('--convert', action='store_true')\nparser.add_argument('--zavg', action='store_true', required=False,\n help='(default=%(default)s)')\nparser.add_argument('--alpha', default=3, type=float, required=False,\n help='(default=%(default)f)')\n# Synthesis\nparser.add_argument('--lchunk', default=-1, type=int, required=False,\n help='(default=%(default)d)')\nparser.add_argument('--stride', default=-1, type=int, required=False,\n help='(default=%(default)d)')\nparser.add_argument('--synth_nonorm', action='store_true')\nparser.add_argument('--maxfiles', default=10000000, type=int, required=False,\n help='(default=%(default)d)')\nparser.add_argument('--sw_path', default='/work/x/blow-mel/res/L128_large_pretrain',\n type=str, required=False, help='(default=%(default)d)')\n\n# Process arguments\nargs = parser.parse_args()\nif args.trim <= 0:\n args.trim = None\nif args.force_source_file == '':\n args.force_source_file = None\nif args.force_source_speaker == '':\n args.force_source_speaker = None\nif args.force_target_speaker == '':\n args.force_target_speaker = None\nif args.fn_list == '':\n args.fn_list = 'list_seed' + str(\n args.seed_input) + '_' + args.split + '.tsv'\n\n# Print arguments\nutils.print_arguments(args)\n\n# Seed\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\nif args.device == 'cuda':\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n torch.cuda.manual_seed(args.seed)\n\n########################################################################################################################\n\n# Load model, pars, & check\n\nprint('Load stuff')\nfrom models import blow\ncheckpoint = torch.load(args.base_fn_model + '.pt')\nmodel2 = blow.Model(**checkpoint)\nmodel2.load_state_dict(checkpoint['model_state_dict'])\n# pars = checkpoint.copy()\n# del pars['model_state_dict']\n# del pars['optimizer_state_dict']\n_, _, model, _ = utils.load_stuff(args.base_fn_model)\npars = checkpoint.copy()\ndel pars['model_state_dict']\ndel pars['optimizer_state_dict']\nclass Namespace:\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\npars = Namespace(**pars)\ntry:\n losses_train, losses_valid, losses_test = np.vstack(\n pars.losses['train']), np.vstack(pars.losses['valid']), \\\n pars.losses['test']\n print('Best losses = ', np.min(losses_train, axis=0),\n np.min(losses_valid, axis=0), losses_test)\nexcept:\n print('[Could not load losses]')\nprint('-' * 100)\nmodel = model.to(args.device)\nutils.print_model_report(model, verbose=1)\nprint('-' * 100)\n\n# Check lchunk & stride\nif args.lchunk <= 0:\n args.lchunk = pars.lchunk\nif args.stride <= 0:\n # args.stride = args.lchunk // 2\n args.stride = args.lchunk\n# if pars.model != 'blow' and not pars.model.startswith('test'):\n# if not args.zavg:\n# print(\n# '[WARNING: You are not using Blow. Are you sure you do not want to use --zavg?]')\n# if args.lchunk != pars.lchunk:\n# args.lchunk = pars.lchunk\n# print(\n# '[WARNING: ' + pars.model + ' model can only operate with same frame size as training. It has been changed, but you may want to change the stride now]')\nif args.stride == args.lchunk:\n print('[Synth with 0% overlap]')\n window = torch.ones(args.lchunk)\nelif args.stride == args.lchunk // 2:\n print('[Synth with 50% overlap]')\n window = torch.hann_window(args.lchunk)\nelif args.stride == args.lchunk // 4 * 3:\n print('[Synth with 25% overlap]')\n window = torch.hann_window(args.lchunk // 2)\n window = torch.cat(\n [window[:len(window) // 2], torch.ones(args.lchunk // 2),\n window[len(window) // 2:]])\nelse:\n print(\n '[WARNING: No specific overlap strategy. Forcing Hann window and normalize]')\n window = torch.hann_window(args.lchunk)\n args.synth_nonorm = False\nwindow = window.view(1, -1)\n\nprint('-' * 100)\n\nif args.path_data == '':\n args.path_data = pars.path_data\n\n########################################################################################################################\n\ndef compute_speaker_averages(speakers, trim=5 * 60):\n print('(' * 100)\n print('[Averages]')\n select_speaker = None\n if args.force_source_speaker is not None and args.force_target_speaker is not None:\n select_speaker = args.force_source_speaker + ',' + args.force_target_speaker\n dataset = datain.DataSet(args.path_data, args.lchunk, args.lchunk,\n sampling_rate=pars.sr, split='train+valid',\n trim=trim,\n select_speaker=select_speaker,\n seed=pars.seed)\n loader = torch.utils.data.DataLoader(dataset, batch_size=args.sbatch,\n shuffle=False, num_workers=0)\n averages = {}\n count = {}\n with torch.no_grad():\n for b, (x, idx) in enumerate(loader):\n x = x.to(args.device)\n s = idx[:, 3].to(args.device)\n z = model.forward(x, s)[0]\n for n in range(len(idx)):\n i, j, last, ispk, ichap = idx[n]\n spk, _ = dataset.filename_split(dataset.filenames[i])\n spk = speakers[spk]\n if spk not in averages:\n averages[spk] = torch.zeros_like(z[n])\n count[spk] = 0\n averages[spk] += z[n]\n count[spk] += 1\n print('\\r---> Speaker(s) average: {:5.1f}%'.format(\n 100 * (b * args.sbatch + x.size(0)) / len(dataset)), end='')\n print()\n for spk in averages.keys():\n averages[spk] = averages[spk] / count[spk]\n print(')' * 100)\n return averages\n\n\n########################################################################################################################\n\n# Data\nprint('Load metadata')\ndataset = datain.DataSet(args.path_data, pars.lchunk, pars.stride,\n sampling_rate=pars.sr, split='train+valid',\n seed=pars.seed, do_audio_load=False)\nspeakers = deepcopy(dataset.speakers)\nlspeakers = list(speakers.keys())\nif args.zavg:\n averages = compute_speaker_averages(speakers)\n\n# Input data\nprint('Load', args.split, 'audio')\ndataset = datain.DataSet(args.path_data, args.lchunk, args.stride,\n sampling_rate=pars.sr, split=args.split,\n trim=args.trim,\n select_speaker=args.force_source_speaker,\n select_file=args.force_source_file,\n seed=pars.seed)\nloader = torch.utils.data.DataLoader(dataset,\n batch_size=1,\n shuffle=False, num_workers=0)\n\n# Get transformation list\nprint('Transformation list')\nnp.random.seed(args.seed)\ntarget_speaker = lspeakers[np.random.randint(len(lspeakers))]\nif args.force_target_speaker is not None: target_speaker = args.force_target_speaker\nfnlist = []\nitrafos = []\nnfiles = 0\nfor x, info in loader:\n isource, itarget = [], []\n for n in range(len(x)):\n\n # Get source and target speakers\n i, j, last, ispk, iut = info[n]\n source_speaker, _ = dataset.filename_split(dataset.filenames[i])\n isource.append(speakers[source_speaker])\n itarget.append(speakers[target_speaker])\n if last == 1 and nfiles < args.maxfiles:\n\n # Get filename\n fn = dataset.filenames[i][:-len(datain.EXTENSION)]\n fnlist.append([fn, source_speaker, target_speaker])\n\n # Restart\n target_speaker = lspeakers[np.random.randint(len(lspeakers))]\n if args.force_target_speaker is not None: target_speaker = args.force_target_speaker\n nfiles += 1\n\n isource, itarget = torch.LongTensor(isource), torch.LongTensor(itarget)\n itrafos.append([isource, itarget])\n if nfiles >= args.maxfiles:\n break\n\n# Write transformation list\nflist = open(os.path.join(args.path_out, args.fn_list), 'w')\nfor fields in fnlist:\n flist.write('\\t'.join(fields) + '\\n')\nflist.close()\n\n########################################################################################################################\n\n# Prepare model\ntry:\n model.precalc_matrices('on')\nexcept:\n pass\nmodel.eval()\nprint('-' * 100)\n\n# Synthesis loop\n# Each loop synthesizes one full audio\nsqueezewave = torch.load(args.sw_path)['model']\nsqueezewave = squeezewave.remove_weightnorm(squeezewave)\nsqueezewave.cuda().eval()\nprint('Synth')\naudio = []\nmels = []\nnfiles = 0\nt_conv = 0\nt_synth = 0\nt_audio = 0\ntry:\n with torch.no_grad():\n for k, (x, info) in enumerate(loader):\n if k >= len(itrafos):\n break\n isource, itarget = itrafos[k]\n\n # Track time\n tstart = time.time()\n\n _, model_fname = os.path.split(args.base_fn_model)\n path_out = os.path.join(args.path_out, 'syn_manual',model_fname)\n os.makedirs(path_out, exist_ok=True)\n synthesized_x = utils.synthesize_one_audio(x, info, itarget,\n filename=fnlist[k][0],\n target_spk=fnlist[k][2],\n blow=model,\n path_out=path_out,\n sw_model=squeezewave,\n print_mel=True,\n convert=args.convert,\n sr=pars.sr,\n normalize=False)\n # normalize=not args.synth_nonorm)\n\n \"\"\"\n # x = utils.get_mel(x)\n # source_mel = x\n # \n # # Convert\n # if args.convert:\n # # Forward & reverse\n # x = x.to(args.device)\n # isource = isource.to(args.device)\n # itarget = itarget.to(args.device)\n # z = model.forward(x, isource)[0]\n # # Apply means?\n # if args.zavg:\n # for n in range(len(x)):\n # z[n] = z[n] + args.alpha * (\n # averages[itarget[n].item()] - averages[\n # isource[n].item()])\n # x = model.reverse(z, itarget)\n # x = x.cpu()\n # \n # # Track time\n # t_conv += time.time() - tstart\n # tstart = time.time()\n # \n # # Vocoder Inference\n # pdb.set_trace()\n # x = vocoder.infer(mel=x,\n # squeezewave_path='/rscratch/x/blow-mel/res/L128_large_pretrain')\n # x = x.cpu()\n\n # Append audio\n # x *= window\n # for n in range(len(x)):\n # audio.append(x[n])\n # mels.append(source_mel[n])\n # i, j, last, ispk, iut = info[n]\n # if last == 1:\n # \n # pdb.set_trace()\n # \n # ## Hacking to print mel_source here\n # fname = fnlist[nfiles][0].split('/')[1] # p285/p285_04452\n # fname = os.path.join(args.path_out,\n # \"{}_mel.pt\".format(fname))\n # torch.save(mels, fname)\n # print(\"Saved mel to {}\".format(fname))\n # ##\n # \n # # Filename\n # fn, source_speaker, target_speaker = fnlist[nfiles]\n # _, fn = os.path.split(fn)\n # if args.convert:\n # fn += '_to_' + target_speaker\n # fn = os.path.join(args.path_out, fn + '.wav')\n # \n # # Synthesize\n # print(str(nfiles + 1) + '/' + str(len(fnlist)) + '\\t' + fn)\n # sys.stdout.flush()\n # audioutils.synthesize(audio, fn, args.stride, sr=pars.sr,\n # normalize=not args.synth_nonorm)\n # \n # # Track time\n # t_audio += ((len(\n # audio) - 1) * args.stride + args.lchunk) / pars.sr\n # \n # # Reset\n # mels = []\n # audio = []\n # nfiles += 1\n # if nfiles >= args.maxfiles:\n # break\n \"\"\"\n\n # Track time\n t_synth += time.time() - tstart\nexcept KeyboardInterrupt:\n print()\n\n########################################################################################################################\n\n# Report times\nprint('-' * 100)\nprint('Time')\nprint('t_synth = {}'.format(t_synth))\n# print(' Conversion:\\t{:6.1f} ms/s'.format(1000 * t_conv / t_audio))\n# print(' Synthesis:\\t{:6.1f} ms/s'.format(1000 * t_synth / t_audio))\n# print(' TOTAL:\\t{:6.1f} ms/s\\t(x{:.1f})'.format(\n# 1000 * (t_conv + t_synth) / t_audio, 1 / ((t_conv + t_synth) / t_audio)))\nprint('-' * 100)\n\n# Done\nif args.convert:\n print('*** Conversions done ***')\nelse:\n print('*** Original audio. No conversions done ***')\n","sub_path":"blow-mel/src/synthesize_seen.py","file_name":"synthesize_seen.py","file_ext":"py","file_size_in_byte":15744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"328741545","text":"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# [START video_detect_faces_gcs]\nfrom google.cloud import videointelligence_v1 as videointelligence\n\n\ndef detect_faces(gcs_uri=\"gs://YOUR_BUCKET_ID/path/to/your/video.mp4\"):\n \"\"\"Detects faces in a video.\"\"\"\n\n client = videointelligence.VideoIntelligenceServiceClient()\n\n # Configure the request\n config = videointelligence.FaceDetectionConfig(\n include_bounding_boxes=True, include_attributes=True\n )\n context = videointelligence.VideoContext(face_detection_config=config)\n\n # Start the asynchronous request\n operation = client.annotate_video(\n request={\n \"features\": [videointelligence.Feature.FACE_DETECTION],\n \"input_uri\": gcs_uri,\n \"video_context\": context,\n }\n )\n\n print(\"\\nProcessing video for face detection annotations.\")\n result = operation.result(timeout=300)\n\n print(\"\\nFinished processing.\\n\")\n\n # Retrieve the first result, because a single video was processed.\n annotation_result = result.annotation_results[0]\n\n for annotation in annotation_result.face_detection_annotations:\n print(\"Face detected:\")\n for track in annotation.tracks:\n print(\n \"Segment: {}s to {}s\".format(\n track.segment.start_time_offset.seconds\n + track.segment.start_time_offset.microseconds / 1e6,\n track.segment.end_time_offset.seconds\n + track.segment.end_time_offset.microseconds / 1e6,\n )\n )\n\n # Each segment includes timestamped faces that include\n # characteristics of the face detected.\n # Grab the first timestamped face\n timestamped_object = track.timestamped_objects[0]\n box = timestamped_object.normalized_bounding_box\n print(\"Bounding box:\")\n print(\"\\tleft : {}\".format(box.left))\n print(\"\\ttop : {}\".format(box.top))\n print(\"\\tright : {}\".format(box.right))\n print(\"\\tbottom: {}\".format(box.bottom))\n\n # Attributes include glasses, headwear, smiling, direction of gaze\n print(\"Attributes:\")\n for attribute in timestamped_object.attributes:\n print(\n \"\\t{}:{} {}\".format(\n attribute.name, attribute.value, attribute.confidence\n )\n )\n\n\n# [END video_detect_faces_gcs]\n","sub_path":"samples/analyze/video_detect_faces_gcs.py","file_name":"video_detect_faces_gcs.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"612078126","text":"import numpy as np\r\nimport cv2\r\nimport argparse\r\n\r\nfrom utils import show, apply_new_background, find_largest_contour\r\n\r\n#defining the argument parser\r\n# parser = argparse.ArgumentParser()\r\n# parser.add_argument('i', '--input', help='path to the input image', required=True)\r\n# parser.add_argument('-n', '--new-background', dest='new_background', action='store_true')\r\n# args = vars(parser.parse_args())\r\n# image = cv2.imread(args['input'])\r\n\r\nimage = cv2.imread('img/photo.jpg')\r\nshow('Input image', image)\r\n# blur the image to smooth out the edges a bit, also reduces a bit of noise\r\nblurred = cv2.GaussianBlur(image, (5, 5), 0)\r\n# convert the image to grayscale\r\ngray = cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY)\r\n# apply thresholding to conver the image to binary format\r\n# after this operation all the pixels below 200 value will be 0...\r\n# and all th pixels above 200 will be 255\r\nret, gray = cv2.threshold(gray, 200, 255, cv2.CHAIN_APPROX_NONE)\r\n# find the largest contour area in the image\r\ncontour = find_largest_contour(gray)\r\nimage_contour = np.copy(image)\r\ncv2.drawContours(image_contour, [contour], 0, (0, 255, 0), 2, cv2.LINE_AA, maxLevel=1)\r\nshow('Contour', image_contour)\r\n\r\n# create a black `mask` the same size as the original grayscale image\r\nmask = np.zeros_like(gray)\r\n# fill the new mask with the shape of the largest contour\r\n# all the pixels inside that area will be white\r\ncv2.fillPoly(mask, [contour], 255)\r\n# create a copy of the current mask\r\nres_mask = np.copy(mask)\r\nres_mask[mask == 0] = cv2.GC_BGD # obvious background pixels\r\nres_mask[mask == 255] = cv2.GC_PR_BGD # probable background pixels\r\nres_mask[mask == 255] = cv2.GC_FGD # obvious foreground pixels\r\n# create a mask for obvious and probable foreground pixels\r\n# all the obvious foreground pixels will be white and...\r\n# ... all the probable foreground pixels will be black\r\nmask2 = np.where((res_mask == cv2.GC_FGD) | (res_mask == cv2.GC_PR_FGD), 255, 0).astype('uint8')\r\n\r\n# create `new_mask3d` from `mask2` but with 3 dimensions instead of 2\r\nnew_mask3d = np.repeat(mask2[:, :, np.newaxis], 3, axis=2)\r\nmask3d = new_mask3d\r\nmask3d[new_mask3d > 0] = 255.0\r\nmask3d[mask3d > 255] = 255.0\r\n# apply Gaussian blurring to smoothen out the edges a bit\r\n# `mask3d` is the final foreground mask (not extracted foreground image)\r\nmask3d = cv2.GaussianBlur(mask3d, (5, 5), 0)\r\nshow('Foreground mask', mask3d)\r\n\r\n# create the foreground image by zeroing out the pixels where `mask2`...\r\n# ... has black pixels\r\nforeground = np.copy(image).astype(float)\r\nforeground[mask2 == 0] = 0\r\nshow('Foreground', foreground.astype(np.uint8))\r\n\r\n# save the images to disk\r\n#save_name = args['input'].split('/')[-1].split('.')[0]\r\nsave_name = \"extImg\"\r\ncv2.imwrite(f\"outputs/{save_name}_foreground.png\", foreground)\r\ncv2.imwrite(f\"outputs/{save_name}_foreground_mask.png\", mask3d)\r\ncv2.imwrite(f\"outputs/{save_name}_contour.png\", image_contour)\r\n\r\n# the `--new-background` flag is `True`, then apply the new background...\r\n# ... to the extracted foreground image\r\napply_new_background(mask3d, foreground, save_name)\r\n# if args['new_background']:\r\n# apply_new_background(mask3d, foreground, save_name)","sub_path":"extracted_foreground.py","file_name":"extracted_foreground.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"609375083","text":"#딕셔너리 형태로 보관된 학생 초기 정보(이름, 학번) 수정하기\r\nstudInfo = {'CHM':0, \"KCM\": 1,\"PCY\" : 2, \"BHR\" :3, \"JHJ\":4}\r\nname = list(studInfo.keys())\r\nidNum =list(studInfo.values())\r\n\r\nfor i in range(len(studInfo)):\r\n print(\"{}학생의 새로운 학번을 입력하시오 : \".format(name[i]), end='')\r\n idNum[i] = int(input())\r\n studInfo[name[i]] = idNum[i]\r\n\r\nprint(studInfo.keys())\r\nprint(studInfo.values())\r\nprint(studInfo.items())\r\n\r\n#학생 확인하기\r\nnameF = input(\"찾고 싶은 학생의 이름을 입력하시오 : \")\r\nif nameF in studInfo:\r\n print(\"{} 학생의 학번은 {} 입니다.\".format(nameF,studInfo.get(nameF)))\r\n","sub_path":"practice1.py","file_name":"practice1.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"363297814","text":"import urllib.parse\nimport urllib.request\n\nclass BotTelegram():\n def __init__(self, token, chatId):\n self._token = token\n self._chatId = chatId\n\n def sendMessage(self, message):\n message = urllib.parse.quote(message)\n responses = list()\n\n for id in self._chatId:\n API = f'https://api.telegram.org/bot{self._token}/sendMessage?chat_id={id}&text={message}'\n \n try:\n urllib.request.urlopen(API)\n responses.append(True)\n print('[telegram] Mensagem enviada com sucesso') # log\n except:\n print('[telegram] Erro ao tentar enviar mensagem') # log\n responses.append(None)\n continue\n\n return responses\n\n def getUpdates(self):\n API = f'https://api.telegram.org/bot{self._token}/getUpdates'\n urllib.request.urlretrieve(urls[i], 'getUpdates.json')\n","sub_path":"core/telegram.py","file_name":"telegram.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"245041002","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\ntry:\n range = xrange\nexcept:\n pass\n\nimport six\nimport tensorflow as tf\n\nfrom rl.utils import summarize_variable\n\n\ndef weight_variable(shape, name=None):\n \"\"\"\n Create weight variable with \"tf.Variable\"\n Args:\n shape (list): shape of weight\n name (str): name of variable\n Returns:\n tf.Variable: weight variable\n Usage:\n >>> weight_variable([100, 100])\n \"\"\"\n return tf.Variable(tf.truncated_normal(shape, stddev=0.1), name=name)\n\n\ndef bias_variable(shape, name=None):\n \"\"\"\n Create bias variable with \"tf.Variable\"\n Args:\n shape (list): shape of bias\n name (str): name of variable\n Returns:\n tf.Variable: bias variable\n Usage:\n >>> bias_variable([100])\n \"\"\"\n return tf.Variable(tf.constant(0.1, shape=shape), name=name)\n\n\ndef multilayer_perceptron(dimensions, alpha=0.2):\n \"\"\"\n Create multilayer perceptron\n Args:\n dimensions (list): dimensions of each layer, including\n input & final layer\n alpha (float): slope of LeakyReLU (default: 1e-3)\n Returns:\n network (tf.Tensor): network operation, output shape is same as last element in dimensions\n input_x (tf.Tensor): input placeholder for network\n variables (dict): a dictionary contains all weight and bias variables\n Usage:\n # Create multilayer perceptron with 2 hidden layers (20, 20)\n >>> network, input_x, variables = multilayer_perceptron([30, 20, 20 , 1])\n >>> print(network)\n Tensor(\"neuron_2:0\", shape=(?, 1), dtype=float32)\n >>> print(input_x)\n Tensor(\"input_x:0\", shape=(?, 30), dtype=float32)\n >>> print(variables)\n {'b_2': , 'b_1': , 'w_1': ,\n 'w_2': , 'b_0': , 'w_0': }\n \"\"\"\n variables = {}\n\n input_x = tf.placeholder(tf.float32, [None, dimensions[0]], name=\"x\")\n\n x = input_x\n for i in range(len(dimensions) - 1):\n w_name = \"w_{}\".format(i)\n b_name = \"b_{}\".format(i)\n y_name = \"y_{}\".format(i)\n act_y_name = \"activate_{}\".format(y_name)\n\n w = weight_variable([dimensions[i], dimensions[i + 1]], name=w_name)\n b = bias_variable([dimensions[i + 1]], name=b_name)\n variables[w_name] = w\n variables[b_name] = b\n summarize_variable(w, w_name)\n summarize_variable(b, b_name)\n\n with tf.name_scope(y_name) as scope:\n y = tf.add(tf.matmul(x, w), b, name=y_name)\n x = tf.nn.leaky_relu(y, alpha, name=act_y_name)\n\n network = x\n\n return network, input_x, variables\n","sub_path":"rl/mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"490914067","text":"from django import forms\nfrom django.core.exceptions import ValidationError\n\n\nclass EvaluationForm(forms.Form):\n nome = forms.CharField(label='Nome', widget=forms.TextInput(\n attrs={'placeholder': 'Nome', 'class': 'form-control'}))\n morada = forms.CharField(label='Email', widget=forms.TextInput(\n attrs={'placeholder': 'Email', 'class': 'form-control'}))\n nif = forms.CharField(label='NIF', widget=forms.TextInput(\n attrs={'placeholder': 'Número de identificação fiscal', 'class': 'form-control'}))\n cartao_cidadao = forms.CharField(label='CC', widget=forms.TextInput(\n attrs={'placeholder': 'Cartão do Cidadão', 'class': 'form-control'}))\n email = forms.EmailField(label='Email', widget=forms.TextInput(\n attrs={'placeholder': 'Email', 'class': 'form-control'}))\n date_nasc = forms.DateField(label='Data de Nascimento',\n widget=forms.DateInput(\n attrs={'placeholder': 'dd/mm/yyyy', 'class': 'form-control date', ' data-provide': 'datepicker',\n 'data-date-format': 'dd/mm/yyyy'}))\n phone = forms.CharField(label='Telefone', required=False, widget=forms.TextInput(\n attrs={'placeholder': 'Contato', 'class': 'form-control'}))\n phone1 = forms.CharField(label='Telefone 2', required=False, widget=forms.TextInput(\n attrs={'placeholder': 'Contato urgente', 'class': 'form-control'}))\n tipo_mensalidade = forms.CharField(label='Mensalidade', required=False, widget=forms.TextInput(\n attrs={'placeholder': 'Tipo mensalidade', 'class': 'form-control'}))\n date1 = forms.DateField(label='Data inicio',\n widget=forms.DateInput(\n attrs={'placeholder': 'dd/mm/yyyy', 'class': 'form-control date', ' data-provide': 'datepicker',\n 'data-date-format': 'dd/mm/yyyy'}))\n\n message = forms.CharField(label='Mensagem', widget=forms.Textarea(\n attrs={'placeholder': 'Mensagem', 'class': 'form-control', 'rows': '5'}))\n\n def clean_name(self):\n name = self.cleaned_data['name']\n words = [w.capitalize() for w in name.split()]\n return ' '.join(words)\n\n def clean(self):\n self.cleaned_data = super().clean()\n if not self.cleaned_data.get('email') and not self.cleaned_data.get('phone'):\n raise ValidationError('Informe seu e-mail ou telefone.')\n\n return self.cleaned_data","sub_path":"kettclub/reviewsphysicals/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"289574614","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import *\n\ndata_path = \"hdfs://10.1.4.11:9000/user/hduser/\"\n\nspark = SparkSession.builder \\\n .master(\"local[*]\") \\\n .appName(\"ConvertParquet\") \\\n .getOrCreate()\n\nschema_batch_task = StructType([\\\n StructField(\"task_name\", StringType(), True),\\\n StructField(\"instance_num\", LongType(), True),\\\n StructField(\"job_name\", StringType(), True), \\\n StructField(\"task_type\", StringType(), True), \\\n StructField(\"status\", StringType(), True), \\\n StructField(\"start_time\", LongType(), True),\\\n StructField(\"end_time\", LongType(), True),\\\n StructField(\"plan_cpu\", DoubleType(), True), \\\n StructField(\"plan_mem\", DoubleType(), True)])\n\ndf_batch_task = spark \\\n .read \\\n .csv(data_path + \"batch_task.csv\", schema=schema_batch_task, header=False) \\\n\nprint(\"batch_task:\")\ndf_batch_task.show()\n\n# Save as parquet file\ndf_batch_task \\\n .write \\\n .parquet(data_path + \"batch_task_parquet\")\n","sub_path":"src/convert-parquet/batch_task.py","file_name":"batch_task.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"504879950","text":"from tkinter import *\nt = Tk()\nt.geometry('600x800')\nt.title('Человек')\nc = Canvas(t,height=600, width=380)\ncaptrurebtn=Button(text=\"CAPTURE\")\nanimatebtn=Button(text=\"ANIMATE\")\nclass Person():\n def __init__(self):\n self.y1 = 0\n self.y2 = 50\n self.y1 = 0\n self.x2 = 0\n self.length = 50\n self.leftarm1deg = 0\n self.rightarm1deg = 0\n self.leftarm2deg = 0\n self.rightarm2deg = 0\n self.leftleg1deg = 0\n self.rightleg1deg = 0\n self.leftleg2deg = 0\n self.rightleg2deg = 0\n self.create()\n self.move()\n def create(self):\n canvas.create_oval(0,0,0,0)\n body=canvas.create_line(0,0,0,0)\n leftarm1=canvas.create_line(0,0,0,0)\n leftarm2=canvas.create_line(0,0,0,0)\n rightarm1=canvas.create_line(0,0,0,0)\n rightarm2=canvas.create_line(0,0,0,0)\n leftleg1=canvas.create_line(0,0,0,0)\n leftleg2canvas.create_line(0,0,0,0)\n rightleg1=canvas.create_line(0,0,0,0)\n rightleg2=canvas.create_line(0,0,0,0)\n def headmoving(self):\n c.coords(head,x1,y2,x1,y2)\n def bodymoving(self):\n c.coords(body,x1,y1,x2,y2)\n def x_coordinate(start_X,length,angle):\n return start_X + length * math.cos((angle-90)*math.pi / 180)\n def y_coordinate(start_Y,length,angle):\n return start_Y + length * math.sin((angle-90)*math.pi / 180)\n\n def draw_left_lokot(self):\n anglefunc = sclua.get()\n self.x_left_lokot = x_coordinate(self.x1,self.length, self.anglefunc)\n self.y_left_lokot = y_coordinate(self.y1,self.length, self.anglefunc)\n c.coords(self.leftarm1,self.x1, self.y1, self.x_left_lokot,self.y_left_lokot)\f\n def left_arm(self):\n self.leftarmx1 = self.x_left_lokot\n self.leftarmy1 = self.y_left_lokot\n anglefunc = sclda.get()\n self.leftarmx2 = x_coordinate(self.leftarmx1,25,self.anglefunc)\n self.leftarmy2 = y_coordinate(self.leftarmx1,25,self.anglefunc)\n c.coords(leftarm2,leftarmx1,leftarmy1,leftarmx2,leftarmy2)\n\n def draw_right_lokot(self):\n anglefunc = scrua.get()\n self.x_right_lokot = x_coordinate(self.x1,self.length, self.anglefunc)\n self.y_right_lokot = y_coordinate(self.y1,self.length, self.anglefunc)\n c.coords(self.rightarm1,self.x1, self.y1, self.x_right_lokot,self.y_right_lokot)\f\n def right_arm(self):\n self.rightarmx1 = self.x_right_lokot\n self.rightarmy1 = self.y_right_lokot\n anglefunc = scrda.get()\n self.rightarmx2 = x_coordinate(self.rightarmx1,25,self.anglefunc)\n self.rightarmy2 = y_coordinate(self.rightarmx1,25,self.anglefunc)\n c.coords(rightarm2,rightarmx1,rightarmy1,rightarmx2,rightarmy2)\n\n def draw_left_bedro(self):\n anglefunc = sclul.get()\n self.x_left_bedro = x_coordinate(self.x2,self.length, self.anglefunc)\n self.y_left_bedro = y_coordinate(self.y2,self.length, self.anglefunc)\n c.coords(self.leftleg1,self.x2, self.y2, self.x_left_bedro,self.y_left_bedro)\f\n def left_leg(self):\n anglefunc = scldl.get()\n self.leftlegx1 = self.x_left_bedro\n self.leftlegy1 = self.y_left_bedro\n self.leftlegx2 = x_coordinate(self.leftlegx1,25,self.anglefunc)\n self.leftlegy2 = y_coordinate(self.leftlrgx1,25,self.anglefunc)\n c.coords(leftleg2,leftlegx1,leftlegy1,leftlegx2,leftlegy2)\n\n def draw_left_bedro(self):\n anglefunc = sclul.get()\n self.x_left_bedro = x_coordinate(self.x2,self.length, self.anglefunc)\n self.y_left_bedro = y_coordinate(self.y2,self.length, self.anglefunc)\n c.coords(self.leftleg1,self.x2, self.y2, self.x_left_bedro,self.y_left_bedro)\f\n def left_leg(self):\n anglefunc = scldl.get()\n self.leftlegx1 = self.x_left_bedro\n self.leftlegy1 = self.y_left_bedro\n self.leftlegx2 = x_coordinate(self.leftlegx1,25,self.anglefunc)\n self.leftlegy2 = y_coordinate(self.leftlegx1,25,self.anglefunc)\n c.coords(leftleg2,leftlegx1,leftlegy1,leftlegx2,leftlegy2)\n\n def draw_right_bedro(self):\n anglefunc = scrul.get()\n self.x_right_bedro = x_coordinate(self.x2,self.length, self.anglefunc)\n self.y_right_bedro = y_coordinate(self.y2,self.length, self.anglefunc)\n c.coords(self.rightleg1,self.x2, self.y2, self.x_right_bedro,self.y_right_bedro)\f\n def right_leg(self):\n anglefunc = scrdl.get()\n self.rightlegx1 = self.x_right_bedro\n self.rightlegy1 = self.y_right_bedro\n self.rightlegx2 = x_coordinate(self.rightlegx1,25,self.anglefunc)\n self.rightlegy2 = y_coordinate(self.rightlegx1,25,self.anglefunc)\n c.coords(rightleg2,rightlegx1,rightlegy1,rightlegx2,rightlegy2)\n\n def move():\n self.draw_left_lokot()\n self.left_arm()\n self.draw_right_lokot()\n self.right_arm()\n self.draw_left_bedro()\n self.left_leg()\n self.draw_right_bedro()\n self.right_leg()\n\nif 1==1:\n sclul = Scale(t,orient=HORIZONTAL,length=200,from_=-100, to=100, tickinterval=20,resolution=5,label=\"Left Up Leg\")\n scldl = Scale(t,orient=HORIZONTAL,length=200,from_=-100, to=100, tickinterval=20,resolution=5,label=\"Left Down Leg\")\n scrul = Scale(t,orient=HORIZONTAL,length=200,from_=-100, to=100, tickinterval=20,resolution=5,label=\"Right Up Leg\")\n scrdl = Scale(t,orient=HORIZONTAL,length=200,from_=-100, to=100, tickinterval=20,resolution=5,label=\"Right Down Leg\")\n sclua = Scale(t,orient=HORIZONTAL,length=200,from_=-100, to=100, tickinterval=20,resolution=5,label=\"Left Up Arm\")\n sclda = Scale(t,orient=HORIZONTAL,length=200,from_=-100, to=100, tickinterval=20,resolution=5,label=\"Left Down Arm\")\n scrua = Scale(t,orient=HORIZONTAL,length=200,from_=-100, to=100, tickinterval=20,resolution=5,label=\"Right Up Arm\")\n scrda = Scale(t,orient=HORIZONTAL,length=200,from_=-100, to=100, tickinterval=20,resolution=5,label=\"Right Down Arm\")\n scpx = Scale(t,orient=HORIZONTAL,length=200,from_=-100, to=100, tickinterval=20,resolution=5,label=\"Position X\")\n scpy = Scale(t,orient=VERTICAL,length=200,from_=-100, to=100, tickinterval=20,resolution=5,label=\"Position Y\")\n c.grid(row=0,column=0,columnspan=1, rowspan=10,pady=0.1)\n captrurebtn.grid(row=0,column=3,rowspan=1,columnspan=4,pady=0.1)\n animatebtn.grid(row=1,column=3,rowspan=1,columnspan=4,pady=0.1) \n sclul.grid(row=2,column=3,rowspan=1,columnspan=4,pady=0.1)\n scldl.grid(row=3,column=3,rowspan=1,columnspan=4,pady=0.1)\n scrul.grid(row=4,column=3,rowspan=1,columnspan=4,pady=0.1)\n scrdl.grid(row=5,column=3,rowspan=1,columnspan=4,pady=0.1)\n sclua.grid(row=6,column=3,rowspan=1,columnspan=4,pady=0.1)\n scrua.grid(row=7,column=3,rowspan=1,columnspan=4,pady=0.1)\n scrda.grid(row=8,column=3,rowspan=1,columnspan=4,pady=0.1)\n scpx.grid(row=9,column=3,rowspan=1,columnspan=4,pady=0.1)\n scpy.grid(row=10,column=3,rowspan=1,columnspan=4,pady=0.1)\nt.mainloop()","sub_path":"People/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"69351519","text":"'''\n\nCIB Hall\n\nPart of a series of external utils that creates kernels for Limber integrals. This one is for CIB.\n\n Implementation of the single-spectra-energy-distribution (SSED) model of the from Hall et. al. 2010 (arxiv:0912.4315)\n\n\nYou want to return a spline function W(l,chi,z) with l multipole chi comiving distance z redsfhit which is what is needed for limber.\n\nEVERYTHING IS IN h UNITS\n\n\n\n'''\n\nimport numpy as np\nimport scipy\n# import util\n# constants\nh = 6.626068e-34 # J.s planck constant\nc = 299792458. # m/s speed of light\nk = 1.3806504e-23 # m^2 kg s^{-2} K^{-1} boltzmann constant\ntcmb = 2.7255 # K cmb temperature (Fixsen et. al. 2009)\n\nalpha_mid_ir = -2.\nnu_mid_ir = 4954611330474.7109\n\n\ndef planck(nu, T):\n \"\"\" returns the planck blackbody function (in W sr^{-1} Hz^{-1})\n at frequency \\nu (in Hz) for a blackbody with temperature T (in K). \"\"\"\n return 2 * h * nu**3 / c**2 / (np.exp(h * nu / k / T) - 1.)\n\n\ndef ssed_graybody(nu, Td=34., beta=2):\n return nu**(beta) * planck(nu, Td)\n\n\ndef ssed(nu, Td=34., beta=2., alpha_mid_ir=alpha_mid_ir, nu_mid_ir=nu_mid_ir):\n \"\"\" Calculation of the SSED f_{\\nu} defined between pages 4 and 5 of Hall et. al. \"\"\"\n if np.isscalar(nu):\n if nu > nu_mid_ir:\n return (ssed_graybody(nu_mid_ir, Td, beta) / (nu_mid_ir)**\n (alpha_mid_ir) * nu**(alpha_mid_ir))\n else:\n return ssed_graybody(nu, Td, beta)\n else:\n ret = ssed_graybody(nu, Td, beta)\n ret[np.where(nu > nu_mid_ir)] = (\n ssed_graybody(nu_mid_ir, Td, beta) / (nu_mid_ir)**\n (alpha_mid_ir) * nu**(alpha_mid_ir))[np.where(nu > nu_mid_ir)]\n return ret\n\n\ndef jbar(nu,\n z,\n x,\n zc=2.,\n sigmaz=2.,\n norm=7.5374829969423142e-15,\n ssed_kwargs={}):\n \"\"\" Eq. 10 of Hall et. al. nu in Hz, returns in Jansky. \"\"\"\n # a * \\chi^2 * exp( - (z-zc)/2/\\sigma_z^2) f_{nu (1+z)}\n return 1. / (1. + z) * x**2 * np.exp(-(z - zc)**2 / (\n 2. * sigmaz**2)) * ssed(nu * (1 + z), **ssed_kwargs) * norm\n\n\nclass ssed_kern():\n def __init__(self,\n h0,\n zdist,\n chispline,\n hspline,\n nu,\n b=1.0,\n jbar_kwargs={},\n ssed_kwargs={}):\n '''\n\n Ref: Hall et. al. Eq. 5. Cl = int dz 1/H(z)/chi(z)^2 (ab j(\\nu, z))^2 P_lin(l/chi,z)\n return 1./(1.+z) * self.b * jbar(self.nu, z, x, ssed_kwargs=self.ssed_kwargs, **self.jbar_kwargs) with h0 correction to have right h dimensions\n '''\n\n wb = np.zeros(np.size(zdist))\n zmax = zdist[0]\n zmin = zdist[np.size(zdist) - 1]\n self.zmin = zmin\n self.zmax = zmax\n self.nu = nu\n self.b = b\n self.h0 = h0\n self.jbar_kwargs = jbar_kwargs\n self.ssed_kwargs = ssed_kwargs\n self.chispline = chispline\n self.hspline = hspline\n\n # for i, z in enumerate(zdist - 0.001):\n # wb[i] = 1. / (1. + z) * self.b * jbar(self.nu, z, chispline(z),\n # ssed_kwargs=self.ssed_kwargs, **self.jbar_kwargs) / h0 ** 3\n # self.w = wb\n # self.w_interp = scipy.interpolate.interp1d(zdist, wb)\n\n def w_lxz(self, l, x, z):\n return 1. / (1. + z) * self.b / self.hspline(z) * jbar(\n self.nu,\n z,\n self.chispline(z),\n ssed_kwargs=self.ssed_kwargs,\n **self.jbar_kwargs) / self.h0**3\n\n # Ref: Hall et. al. Eq. 5. Cl = int dz 1/H(z)/chi(z)^2 (ab j(\\nu, z))^2 P_lin(l/chi,z)\n # return 1./(1.+z) * self.b * jbar(self.nu, z, x,\n # ssed_kwargs=self.ssed_kwargs, **self.jbar_kwargs)\n","sub_path":"Code/hall_CIB_kernel.py","file_name":"hall_CIB_kernel.py","file_ext":"py","file_size_in_byte":3732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"328947367","text":"from flask import Flask, request, session, redirect, render_template\nimport os\nfrom random import randint\nfrom datetime import datetime\n\napp = Flask(__name__)\napp.secret_key = os.urandom(24) \n\n@app.route('/')\ndef return_index():\n if \"gold\" not in session:\n session[\"gold\"] = 0\n\n if \"activities\" not in session:\n session[\"activities\"] = []\n\n colors = []\n activities = []\n for activity in session[\"activities\"]:\n activities.insert(0, activity)\n if \"Earned\" in activity:\n colors.insert(0, \"earned\")\n else:\n colors.insert(0, \"lost\")\n\n return render_template(\"index.html\", gold=session[\"gold\"], activities=activities, colors=colors) \n\n@app.route('/process-money', methods=[\"POST\"])\ndef process_money():\n if request.form[\"building\"] == \"farm\":\n earned = randint(10,20)\n session[\"gold\"] += earned\n session[\"activities\"].append(\"Earned \" + str(earned) + \" golds from the \" + request.form['building'] + \" (\" + datetime.now().strftime(\"%c\") + \")\")\n elif request.form[\"building\"] == \"cave\":\n earned = randint(5,10)\n session[\"gold\"] += earned\n session[\"activities\"].append(\"Earned \" + str(earned) + \" golds from the \" + request.form['building'] + \" (\" + datetime.now().strftime(\"%c\") + \")\")\n elif request.form[\"building\"] == \"house\":\n earned = randint(2,5)\n session[\"gold\"] += earned\n session[\"activities\"].append(\"Earned \" + str(earned) + \" golds from the \" + request.form['building'] + \" (\" + datetime.now().strftime(\"%c\") + \")\")\n elif request.form[\"building\"] == \"casino\":\n earned = randint(-50,50)\n session[\"gold\"] += earned\n if earned >= 0:\n session[\"activities\"].append(\"Earned \" + str(earned) + \" golds from the \" + request.form['building'] + \" (\" + datetime.now().strftime(\"%c\") + \")\")\n else: \n session[\"activities\"].append(\"Entered the casino and lost \" + str(earned) + \"...Ouch...\" + \" (\" + datetime.now().strftime(\"%c\") + \")\")\n \n return redirect('/')\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"02-flask/02-flask/09-ninja_gold/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"365102450","text":"#Huffman decoding for the encoded scring based on the given codes\r\nsimp = []\r\nss=[]\r\nres=[]\r\ndef decode(codes, encoded):\r\n test = \"\"\r\n for j in codes:\r\n simp.append(j.split(\"\\t\"))\r\n for i in range(len(simp)):\r\n for j in range(len(simp[i])):\r\n ss.append(simp[i][j])\r\n #print(ss)\r\n comp=\"\"\r\n for i in range(len(encoded)):\r\n test = test +encoded[i]\r\n if test in ss:\r\n comp = comp + ss[ss.index(test)-1]\r\n test = \"\"\r\n #res.append(comp.split(\"\\n\"))\r\n return comp\r\n\r\nif __name__ == '__main__':\r\n codes_count = int(raw_input().strip())\r\n codes=[] \r\n for _ in range(codes_count):\r\n codes_item = raw_input()\r\n codes.append(codes_item)\r\n encoded = raw_input()\r\n ress = decode(codes,encoded)\r\n res = ress.split(\"\\\\n\")\r\n for i in res:\r\n print(i)\r\n \r\n \r\n","sub_path":"Python Codes/Huffman_Decoding.py","file_name":"Huffman_Decoding.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"225462207","text":"import paho.mqtt.client as mqtt\nimport json\nimport sys\nimport time\n\nstart = time.time()\nMQTT_SERVER = sys.argv[1] #ip address of raspberry pi. needed for MQTT broker\nMQTT_PATH = \"Humidity\"\n\n#the following code runs upon connecting\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected. Result code: \" + str(rc))\n client.subscribe(MQTT_PATH)\n\n#the on_message function runs once a message is received from the broker\ndef on_message(client, userdata, msg):\n received_json = json.loads(msg.payload) #convert the string to json object\n if \"Done\" in received_json:\n client.loop_stop()\n client.disconnect()\n end = time.time()\n timer = end-start\n print(\"Humidity subscriber closing. Runtime: \" + str(timer))\n with open(\"macResults.txt\", \"a\") as myfile:\n myfile.write(\"Humidity subscriber runtime = \" + str(timer) + \"\\n\")\n else:\n pi_file = open(\"DataModelPi.json\", \"r\") #open the file in read-only mode\n pi_model = json.load(pi_file) #convert file object to json object\n pi_file.close()\n if pi_model[\"pi\"][\"sensors\"][\"humidity\"][\"value\"] != received_json[\"Humidity\"]:\n pi_file = open(\"DataModelPi.json\", \"w\") # open the file in write mode\n pi_model[\"pi\"][\"sensors\"][\"humidity\"][\"value\"] = received_json[\"Humidity\"] #change data model\n json.dump(pi_model, pi_file, indent=2) #overwrite previous data model\n pi_file.close()\n\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.connect(MQTT_SERVER, 1883, 60) #ip, port and...\nclient.loop_forever() #continue waiting for messages","sub_path":"humidityMicroserviceSubscriber.py","file_name":"humidityMicroserviceSubscriber.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"489607876","text":"from django.shortcuts import render, get_object_or_404\nfrom django.views import generic\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse, reverse_lazy\nfrom django.views.generic.edit import UpdateView, DeletionMixin, CreateView\nfrom django.views.generic.edit import FormView\n\nfrom django.conf import settings\n\nfrom questions.models import Category, Question\nfrom questions.forms import SubmitQuestionForm, CategoryFormSet\n\nimport datetime\n\nclass QuestionDetailView(generic.DetailView):\n model = Question\n\n# Peer access to update a question.\n# Reference: https://stackoverflow.com/questions/51772361/\n# how-to-include-delete-function-in-updateview-instead-a-deleteview\nclass QuestionEditView(DeletionMixin, UpdateView):\n model = Question\n fields = ['category', 'reply', 'status']\n template_name = 'questions/edit_question.html'\n success_url = reverse_lazy('peaccess')\n\n def post(self, request, *args, **kwargs):\n \"\"\" Handling update and delete quests in the form differently. \"\"\"\n # When updating, manually update the quesiton object.\n if 'update_question' in self.request.POST:\n # Get the reference to the form and the question being edited.\n form = self.get_form()\n question = self.get_object()\n\n if form.is_valid():\n # Udpate the question with form data.\n question.reply = form.cleaned_data['reply']\n question.status = form.cleaned_data['status']\n # Clean the many-to-many field of category.\n question.category.clear()\n # Iterate through all the categories and add each one.\n for category in form.cleaned_data['category']:\n question.category.add(category)\n question.save()\n\n return HttpResponseRedirect(reverse('submit-success'))\n\n else: # if 'delete_question' in self.request.POST, use deletionmixin.\n return self.delete(request, *args, **kwargs)\n\n\nclass CategoryListAddView(FormView):\n \"\"\" Display formset of categories for editing existed categories and adding\n new ones.\"\"\"\n\n form_class = CategoryFormSet\n success_url = reverse_lazy('peaccess')\n template_name = 'questions/view_add_category.html'\n\n def form_valid(self, form):\n \"\"\" Save all the new names as new categories in the database. \"\"\"\n form.save()\n\n # Return to success_url\n return HttpResponseRedirect(self.get_success_url())\n\ndef submit_question(request):\n # If this is a POST request then process form data\n if request.method == 'POST':\n # Grab the question from the request\n form = SubmitQuestionForm(request.POST)\n\n # Check if the question is actually valid\n if form.is_valid():\n # If it is, then create a new PrivateQuestion data\n new_question = Question(\n subject = form.cleaned_data['subject'],\n content = form.cleaned_data['content'],\n post_date = datetime.date.today())\n\n # If op choses to give us his email, record it\n if form.data['email']:\n new_question.op_email = form.cleaned_data['email']\n\n # Query the new question to the database\n new_question.save()\n\n return HttpResponseRedirect(reverse('submit-success'))\n\n # If this is a GET request then give out the new form\n else:\n form = SubmitQuestionForm()\n\n context = {'form': form, }\n\n return render(request, 'questions/submit_question.html', context)\n\ndef submit_question_success(request):\n # Render the success page.\n return render(request, 'questions/submit_question_success.html')\n\n\n\"\"\"Testing using rest and ajax to dynamically filter.\"\"\"\n\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\nfrom rest_framework.generics import ListAPIView\nfrom .serializers import QuestionSerializers\nfrom .models import Question, Category\nfrom .pagination import StandardResultsSetPagination\n\n\"\"\" Views that everyone can access. \"\"\"\n\ndef getCategories(request):\n # Return all the categories.\n if request.method == 'GET' and request.is_ajax():\n # Get all the question objects.\n category_objs = Category.objects.all()\n # List the name out to be a string array.\n category_names = []\n for cat in category_objs:\n category_names.append(cat.id)\n\n data = {\n 'categories': category_names,\n }\n return JsonResponse(data, status=200)\n\n\ndef public_question_list(request):\n return render(request, 'questions/public_question.html')\n\nclass PublicQuestionList(ListAPIView):\n serializer_class = QuestionSerializers\n pagination_class = StandardResultsSetPagination\n\n def get_queryset(self):\n\n # For filtering by which time frame the qusetoin is posted in.\n DAY = 'Past Day'\n WEEK = 'Pask Week'\n MONTH = 'Past Month'\n YEAR = 'Past Year'\n DAYS_A_WEEK = 7\n DAYS_A_MONTH = 30\n DAYS_A_YEAR = 365\n\n POST_DATE_CHOICES = {\n DAY: 1,\n WEEK: DAYS_A_WEEK,\n MONTH: DAYS_A_MONTH,\n YEAR: DAYS_A_YEAR,\n }\n\n # Query based on filters applied.\n query_list = Question.objects.filter(status__iexact='p')\n category = self.request.query_params.get('categories', None)\n post_date = self.request.query_params.get('post_in', None)\n sort_by = self.request.query_params.get('sort_by', None)\n\n # If category filters applied:\n if category:\n # Get all the questions whose category matches at least one of the\n # applied categories.\n query_list = query_list.filter(category__id=category).distinct()\n\n # If post_date filter applied:\n if post_date:\n query_list = query_list.filter(\n post_date__gt=datetime.datetime.today() -\n datetime.timedelta(days=(POST_DATE_CHOICES.get(\n post_date, DAYS_A_YEAR)))\n )\n\n # After query, if sort_by filter applied:\n if sort_by:\n if sort_by == 'Oldest First':\n # Order by date, ascending as dates get newer/bigger.\n query_list = query_list.order_by('post_date')\n else:\n query_list = query_list.order_by('-post_date')\n\n return query_list\n\n\"\"\" Views that need authorization to access \"\"\"\n\ndef all_question_list(request):\n return render(request, 'questions/peaccess_questions.html')\n\nclass AllQuestionList(ListAPIView):\n serializer_class = QuestionSerializers\n pagination_class = StandardResultsSetPagination\n\n def get_queryset(self):\n\n # For filtering by which time frame the qusetoin is posted in.\n DAY = 'Past Day'\n WEEK = 'Pask Week'\n MONTH = 'Past Month'\n YEAR = 'Past Year'\n DAYS_A_WEEK = 7\n DAYS_A_MONTH = 30\n DAYS_A_YEAR = 365\n\n POST_DATE_CHOICES = {\n DAY: 1,\n WEEK: DAYS_A_WEEK,\n MONTH: DAYS_A_MONTH,\n YEAR: DAYS_A_YEAR,\n }\n\n # Query based on filters applied.\n query_list = Question.objects.all()\n category = self.request.query_params.get('categories', None)\n post_date = self.request.query_params.get('post_in', None)\n status = self.request.query_params.get('status', None)\n sort_by = self.request.query_params.get('sort_by', None)\n\n # If category filters applied:\n if category:\n # Get all the questions whose category matches at least one of the\n # applied categories.\n query_list = query_list.filter(category__id=category).distinct()\n\n # If post_date filter applied:\n if post_date:\n query_list = query_list.filter(\n post_date__gt=datetime.datetime.today() -\n datetime.timedelta(days=(POST_DATE_CHOICES.get(\n post_date, DAYS_A_YEAR)))\n )\n\n # If status filter applied:\n if status:\n query_list = query_list.filter(status__iexact=status)\n\n # After query, if sort_by filter applied:\n if sort_by:\n if sort_by == 'Oldest First':\n # Order by date, ascending as dates get newer/bigger.\n query_list = query_list.order_by('post_date')\n else:\n query_list = query_list.order_by('-post_date')\n\n return query_list\n","sub_path":"questions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"237117463","text":"#!/usr/bin/env python\n\nimport re\n\nwith open('products_out.csv', 'r') as f:\n\tmy_output = f.read().strip().split('\\n')\nwith open('product_mapping.csv', 'r') as f:\n\ttheir_output = f.read().split()\n\ncanon = {}\npatt = re.compile('\\\"?([a-z0-9]+)\\\"?,\\\"([a-z0-9:/.]+)\\\"')\nfor i in their_output[1:]:\n\tmatch = patt.findall(i)[0] # Remove the list \"outer shell\" to leave just a tuple \n\tcanon[match[0]] = match[1]\n\ncluster = {}\nmatched = {}\na_unmatched = {}\ng_unmatched = {}\nduplicates = 0\ntp = 0\nfp = 0\nfn = 0\ncluster_id_patt = re.compile('([\\d]+),(amazon|google)')\namaz_patt = re.compile('amazon,([a-z0-9]+)')\ngoog_patt = re.compile('google,([a-z0-9:/.]+)')\nfor i in my_output[1:]: # first element is the keys\n\tcluster_id = cluster_id_patt.findall(i)[0] # Remove the list \"outer shell\" to leave just a tuple \n\tcid = cluster_id[0]\n\tname = cluster_id[1]\n\tamaz = amaz_patt.findall(i)\n\tgoog = goog_patt.findall(i)\n\tcomp = amaz if len(amaz) > 0 else goog\n\tcomp = comp[0]\n\t\n\tif cluster.has_key(cid):\n\t\tif cluster[cid][0] == name:\n\t\t\tduplicates += 1 # duplicate from same source (i.e., there were 2 amazon or 2 google products present\n\t\telse:\n\t\t\tif name == 'amazon': # we know anything past the first clause isn't a duplicate\n\t\t\t\tmatched[comp] = cluster[cid][1]\n\t\t\telse:\n\t\t\t\tmatched[cluster[cid][1]] = comp\n\t\t\tdel cluster[cid] # remove any matched cluster_ids from the cluster dict\n\telse:\n\t\tcluster[cid] = (name, comp)\n# number of total entries = 3626, number of amazon = 1234, number of google = 2392\nfor i in cluster.values():\n\tif i[0] == 'amazon':\n\t\ta_unmatched[i[1]] = 0 # arbitrary value to take adv of hash table lookup\n\telse:\n\t\tg_unmatched[i[1]] = 0 # \"\t\t\t\t\t\t\"\n# find true and false positives\nfor k,v in matched.items():\n\tif canon.has_key(k) and canon[k] == v:\n\t\ttp += 1\n\telse:\n\t\tfp += 1\n# find false negatives and values that aren't in the canonical\nfor k in a_unmatched.keys():\n\tif canon.has_key(k):\n\t\tfn += 1\n\t\tif g_unmatched.has_key(canon[k]):\n\t\t\tdel g_unmatched[canon[k]]\n\t'''else:\n\t\tprint(\"{} isn't in canonical\".format(k))'''\nfor k in g_unmatched.keys():\n\tif k in canon.values():\n\t\tfn += 1\n\t'''else:\n\t\tprint(\"{} isn't in canonical\".format(k))'''\nprint('Duplicates: {}'.format(duplicates))\nprint('Precision: {}'.format(float(tp) / (tp + fp)))\nprint('Recall: {}'.format(float(tp) / (tp + fn)))\n","sub_path":"lab5/part1/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"490908527","text":"import re\nfrom typing import List, Union, Any\nfrom telegram import Update\nfrom .trigger_result import TriggerResult\nfrom ..dict_enum import DictEnum\nfrom .basic_triggers import BaseTrigger\n\n\nclass _RegExpTrigger(BaseTrigger):\n \"\"\"\n Regular-expression-based trigger. This is used to trigger a rule when an incoming message\n matches the given pattern.\n \"\"\"\n\n def __init__(self, pattern: str):\n \"\"\"\n Constructs the trigger.\n\n :param pattern: The pattern to test the message's match with\n \"\"\"\n super().__init__()\n self.pattern = pattern\n\n def check_trigger(self, update: Update) -> TriggerResult:\n if update.message.text is not None:\n text = update.message.text.replace('\\n', ' ')\n match = re.match(self.pattern, text)\n if match is not None:\n return TriggerResult(should_respond=True,\n response_payload={'match': match.groups()})\n\n return TriggerResult(should_respond=False)\n\n\nclass _HasSubstringTrigger(_RegExpTrigger):\n \"\"\"\n Substring trigger. This is used to trigger a rule when a certain substring (or one of a list\n of substrings) exists in an incoming message.\n \"\"\"\n\n def __init__(self, substring: Union[str, List[str]], exact: bool = False):\n \"\"\"\n Constructs the trigger.\n\n :param substring: The substring/s to search in the message\n :param exact: Whether the exact substring should appear (as a whole word) in the message\n \"\"\"\n if isinstance(substring, str):\n regexp_for_substring = substring\n elif isinstance(substring, list):\n if self.__are_all_elements_strings(substring):\n regexp_for_substring = '|'.join(substring)\n else:\n raise TypeError('Parameter \\'substring\\' should be either a string or a list of '\n 'strings, but a list containing non-strings was given.')\n else:\n raise TypeError(f'Parameter \\'substring\\' should be either a string or a list of '\n f'strings, but {type(substring)} was given')\n\n prefix = '(?:.* )?' if exact else '.*'\n postfix = '(?: .*)?' if exact else '.*'\n super().__init__(f'^{prefix}({regexp_for_substring}){postfix}$')\n\n @staticmethod\n def __are_all_elements_strings(list_to_check: List[Any]):\n \"\"\"\n Checks whether all elements in a list are strings or not.\n :param list_to_check: The list to check the elements in\n :return: `True` if all elements are strings, `False` otherwise\n \"\"\"\n return all(map(lambda element: isinstance(element, str), list_to_check))\n\n\nclass _HasExactWordTrigger(_HasSubstringTrigger):\n \"\"\"\n Word trigger - the same as substring trigger, but for exact words search. This is used to\n trigger a rule when a certain word (or one of a list of words) exists in an incoming message.\n \"\"\"\n\n def __init__(self, word: Union[str, List[str]]):\n \"\"\"\n Constructs the trigger.\n\n :param word: The word/s to search in the message\n \"\"\"\n try:\n super().__init__(word, exact=True)\n except TypeError:\n raise TypeError( # pylint: disable=raise-missing-from\n f'Parameter \\'word\\' should be either a string or a list of strings'\n f' ({type(word)} given)'\n )\n\n\nclass TextTriggers(DictEnum):\n \"\"\"Text-based triggers.\"\"\"\n\n has_substring = _HasSubstringTrigger\n \"\"\"A substring trigger. See more in :class:`_HasSubstringTrigger`.\"\"\"\n\n has_exact_word = _HasExactWordTrigger\n \"\"\"A word trigger. See more in :class:`_HasExactWordTrigger`.\"\"\"\n\n regexp = _RegExpTrigger\n \"\"\"A regexp-based trigger. See more in :class:`_RegExpTrigger`.\"\"\"\n","sub_path":"gramhopper/triggers/text_triggers.py","file_name":"text_triggers.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"291160611","text":"\"\"\"\nGovJobs spider created on the top of ATSSpider\n\nscrapy crawl govjobs -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://www.governmentjobs.com/careers/denver/\"\n\nSample URL:\n https://www.governmentjobs.com/careers/denver/\n\"\"\"\n\nfrom re import compile\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\nfrom urllib import urlencode\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, Replace\n\n\nclass GovJobs(ATSSpider):\n\n name = 'govjobs'\n REF_REGEX = compile(r'jobs\\/([^\\/]*)')\n ZIPCODE = compile(r'(\\d{5})\\s*,')\n headers = {\n 'Accept': '*/*',\n 'X-Requested-With': 'XMLHttpRequest',\n }\n params = {\n 'agency': 'denver',\n 'isDescendingSort': 'false',\n 'sort': 'PositionTitle'\n }\n\n def parse(self, response):\n yield Request(\n callback=self.parse_jobs_list,\n headers=self.headers,\n url=urljoin(response.url, '/careers/home/index?%s' % urlencode(self.params))\n )\n\n def parse_jobs_list(self, response):\n sel = Selector(response)\n # set expected job count\n if not self.expected_job_count_set:\n expected_count = sel.xpath(\n '//span/h1/span[@id=\"job-postings-number\"]/text()'\n ).extract()\n if expected_count:\n self.expected_job_count = expected_count\n for li in sel.xpath(\n '//ul[contains(@class, \"search-results-listing-container\")]/li[@class=\"list-item\"]'\n ):\n href = li.xpath('./h2/a[@class=\"item-details-link\"]/@href').extract()\n if href:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'title': li.xpath(\n './h2/a[@class=\"item-details-link\"]/text()'\n ).extract(),\n 'jobcategory': li.xpath(\n './ul/li[@class=\"categories-list\"]/text()'\n ).extract(),\n },\n url=urljoin(response.url, href[0])\n )\n\n next_page = sel.xpath(\n '//ul[@class=\"pagination\"]/li[@class=\"active\"]/following-sibling::li[1]/a/text()'\n ).extract()\n if next_page:\n self.params.update({'page': str(next_page[0])})\n yield Request(\n callback=self.parse_jobs_list,\n headers=self.headers,\n url=urljoin(response.url, '/careers/home/index?%s' % urlencode(self.params))\n )\n\n def parse_job(self, response):\n \"\"\"\n Extract all required information.\n \"\"\"\n sel = Selector(response)\n loader = BrightcorpItemLoader(selector=sel)\n loader.add_xpath(\n 'title',\n '//div/h2[@class=\"entity-title\"]/text()'\n )\n if not loader.get_output_value('title'):\n loader.add_value(\n 'title', response.meta.get('title')\n )\n raw_loc = sel.xpath(\n '//div/h4[contains(text(), \"Location\")]/following-sibling::p[1]/text()'\n ).extract()\n loader.add_value(\n 'location', raw_loc, Replace(self.ZIPCODE)\n )\n loader.add_value(\n 'zip_code', raw_loc, re=self.ZIPCODE\n )\n loader.add_value(\n 'referencenumber',\n response.url,\n Prefix('%s-' % self.name),\n re=self.REF_REGEX\n )\n loader.add_value('url', response.url)\n loader.add_xpath(\n 'description',\n '//div/div[@id=\"details-info\"]'\n )\n loader.add_xpath(\n 'company',\n '//div[contains(@class, \"agency-name\")]/dl/dd/text()'\n )\n loader.add_xpath(\n 'jobtype',\n '//div/h4[contains(text(), \"Job Type\")]/following-sibling::p[1]/text()'\n )\n loader.add_xpath(\n 'baseSalary',\n '//div/h4[contains(text(), \"Salary\")]/following-sibling::p[1]/text()'\n )\n loader.add_value(\n 'jobcategory',\n response.meta.get('jobcategory'),\n Replace('Category: ')\n )\n loader.add_value('apply_url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/govjobs.py","file_name":"govjobs.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"394300351","text":"from importlib import import_module\n\nimport pytest\n\nfrom demo import get_product_from_openfoodfacts\n\nclass MyMonkeyPatch:\n \"\"\"Monkey patches a callable.\"\"\"\n\n def __init__(self):\n \"\"\"Initializes the instance.\"\"\"\n self._callable = None\n self._module = None\n self._original_callable = None\n\n def setattr(self, import_string, mock):\n \"\"\"Monkey patches a given callable by a mock.\"\"\"\n mod, self._callable = import_string.rsplit(\".\", maxsplit=1)\n self._module = import_module(mod)\n self._original = getattr(self._module, self._callable)\n setattr(self._module, self._callable, mock) \n\n def reset(self):\n \"\"\"Reverses the monkey patching, reassigning back the original callable to its identifier.\"\"\"\n setattr(self._module, self._callable, self._original)\n\n\n@pytest.fixture\ndef mymonkeypatch():\n \"\"\"Reproduces naively the behaviour of the monkypatch fixture from pytest.\"\"\"\n mk = MyMonkeyPatch()\n\n yield mk\n\n mk.reset()\n\n\ndef test_get_product_from_openfoodfacts_returns_list_with_produit1(mymonkeypatch):\n class MockGet:\n\n def __init__(self, url, params):\n self.status_code = 200\n\n def json(self):\n return {\n \"products\": [\n {\"product_name\": \"Produit 1\"},\n {\"product_name\": \"Produit 2\"},\n {\"product_name\": \"Produit 3\"},\n ]\n }\n\n mymonkeypatch.setattr('requests.get', MockGet)\n result = get_product_from_openfoodfacts(\"pizza\")\n assert len(result) == 3\n assert result[0][\"product_name\"] == \"Produit 1\"","sub_path":"tests/test_demo.py","file_name":"test_demo.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"621892290","text":"import bs4 as bs\nimport urllib.request\n\ndef roubaInfo(siteToRobe):#passar url como parametro\n sauce = urllib.request.urlopen(siteToRobe,).read()\n soup = bs.BeautifulSoup(sauce,'lxml')\n mainInfo = soup.find('div', class_='texto-livro')\n\n if soup.find('h1', class_='archive_title'):\n print('Title: -- ' + soup.find('h1', class_='archive_title').text)\n title = soup.find('h1', class_='archive_title').text\n else:\n title = \"\"\n\n #print('IMG: -- ' + soup.find('div', class_='coverbook').find('img').get('src'))\n if soup.find('div', class_='coverbook').find('img'):\n img = soup.find('div', class_='coverbook').find('img').get('src')\n else:\n img = \"\"\n\n #print('Sinopse: -- ' + mainInfo.find('p',class_='lead').text)\n if mainInfo.find('p',class_='lead'):\n sinopse = mainInfo.find('p',class_='lead').text\n else:\n sinopse = ''\n\n #print('Autor: -- ' + mainInfo.find_all('a')[0].text)\n if mainInfo.find_all('a')[0]:\n autor = mainInfo.find_all('a')[0].text\n else:\n autor = \"\"\n\n #print('Genero: -- ' + mainInfo.find_all('a')[1].text)\n if len(mainInfo.find_all('a')) > 1:\n genero = mainInfo.find_all('a')[1].text\n else:\n genero = \"\"\n\n odInfo = []\n for a in mainInfo.find_all('div')[-1]:\n #print(a.string)\n odInfo.append(a.string)\n\n #print([title,img,sinopse,autor,genero,odInfo[3],odInfo[4],odInfo[5],odInfo[6]])\n print(\"=======================================================\")\n print(\"Page Complete\")\n print(\"=======================================================\")\n\n return [siteToRobe,title,img,sinopse,autor,odInfo[3],odInfo[4],odInfo[5],odInfo[6]]\n\n# print( roubaInfo(siteToRobe) )\n","sub_path":"RobeScript.py","file_name":"RobeScript.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583264406","text":"from simulation.Core import SimulationEnvironment\n\nimport csv\nimport os\n\nfrom collections import defaultdict\n\n\ndef mk_result_dir(filename: str, offset: int = 0):\n try:\n path = os.path.join(\"results\", \"%s_%s\" % (filename, str(offset)))\n os.mkdir(path)\n return offset\n except FileExistsError:\n return mk_result_dir(filename, offset + 1)\n\n\ndef write_to_csv(result: dict, filename: str, offset: int):\n print(\"Writing to CSV\")\n for dict_format, frame_list in result.items():\n path = os.path.join(\"results\", \"%s_%s\" % (filename, str(offset)), \"%s.csv\" % dict_format)\n with open(path, \"a\", encoding=\"utf-8\") as file:\n writer = csv.DictWriter(file, fieldnames=frame_list[0].keys(), delimiter=\",\", lineterminator=\"\\n\")\n if os.stat(path).st_size == 0:\n writer.writeheader()\n for frame_dict in frame_list:\n writer.writerow(frame_dict)\n print(\"Done\")\n\n\ndef simulate_multiple(sim_generator, count: int, runtime: int, filename: str = None, offset: int = None):\n result = defaultdict(list)\n for i in range(0, count):\n sim_env: SimulationEnvironment = sim_generator.__next__()\n sim_env.run(runtime)\n sim_result: dict = sim_env.get_data()\n print(\"Simulation %d/%d done\" % (i + 1, count))\n for dict_format, frame_list in sim_result.items():\n result[dict_format] += frame_list\n if filename is not None:\n if offset is None:\n try:\n os.mkdir(\"results\")\n except FileExistsError:\n pass\n offset = mk_result_dir(filename)\n write_to_csv(result, filename, offset)\n return result\n\n\ndef simulate_multiple_multiple(sim_generator_list: list, count: int, runtime: int, filename: str = None):\n try:\n os.mkdir(\"results\")\n except FileExistsError:\n pass\n offset = mk_result_dir(filename)\n i = 1\n for sim_generator in sim_generator_list:\n simulate_multiple(sim_generator, count, runtime, filename, offset)\n print(\"Simulation %d done\" % i)\n i += 1\n","sub_path":"simulation/Wrapper.py","file_name":"Wrapper.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"414228273","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nDEPRECATED!!!\n\nParser for a disjunctions of constraint systems\n(each element in a new line)\nStructure TASKLIST: TASK \"/\" TASKLIST | \"\"\nStructure TASK: DIS \"|\" DIS\nStructure DIS: SYSTEM \"#\" SYSTEM\nStructure SYSTEM: CON SYSTEM | \"\"\nStructure CON: NUMLIST TYPE NUM\nStructure NUMLIST: NUM NUMLIST | \"\"\nStructure TYPE: \"<=\" | \"<\"\nStructure NUM: float | int\n\"\"\"\nfrom typing import List, Union, Optional\n\nfrom z3 import BoolRef\n\nfrom interpolant.interpolant_calculator_disjunctions import calculate_interpolant_with_dis_obj\nfrom task_parser.constrains import Disjunction\nfrom task_parser.parser import Task, parse_line\nfrom ..constrains import ConstraintSystem\n\n\n@DeprecationWarning\nclass TaskDisjunction(Task):\n \"\"\"\n Interpolant calculation task for disjunctions of constraint systems\n \"\"\"\n\n def calculate_interpolant(self) \\\n -> Union[BoolRef, List[List[BoolRef]]]:\n return calculate_interpolant_with_dis_obj(\n self.get_a(), self.get_b()\n )\n\n def to_csisat_format(self) -> str:\n return f\"{self.a_matrix.to_csisat_format()} ; {self.b_matrix.to_csisat_format()};\"\n\n def __init__(self):\n self.a_matrix: Optional[Disjunction] = None\n self.b_matrix: Optional[Disjunction] = None\n\n def set_a(self, disjunction: Disjunction) -> None:\n \"\"\"\n Sets matrix a\n\n :param disjunction:\n :return:\n \"\"\"\n self.a_matrix = disjunction\n\n def set_b(self, disjunction: Disjunction) -> None:\n \"\"\"\n Sets matrix b\n\n :param disjunction:\n :return:\n \"\"\"\n self.b_matrix = disjunction\n\n def get_a(self) -> Disjunction:\n \"\"\"\n Returns matrix a\n\n :return:\n \"\"\"\n return self.a_matrix\n\n def get_b(self) -> Disjunction:\n \"\"\"\n Returns matrix b\n\n :return:\n \"\"\"\n return self.b_matrix\n\n\n@DeprecationWarning\ndef parse(file_path: str) -> List[TaskDisjunction]:\n \"\"\"\n Task task_parser for disjunction of conjunction of constraint systems\n\n :param file_path: Data set\n :return: List of calculation tasks\n \"\"\"\n tasks: List[TaskDisjunction] = []\n task: TaskDisjunction = TaskDisjunction()\n disjunction: Disjunction = Disjunction()\n system: ConstraintSystem = ConstraintSystem()\n with open(file_path) as file:\n for line in file.readlines():\n if line.startswith(\"/\"): # close task and open new one\n disjunction.append(system)\n system = ConstraintSystem()\n task.set_b(disjunction)\n disjunction = Disjunction()\n tasks.append(task)\n task = TaskDisjunction()\n elif line.startswith(\"|\"): # close disjunction and open new one\n disjunction.append(system)\n system = ConstraintSystem()\n task.set_a(disjunction)\n disjunction = Disjunction()\n elif line.startswith(\"#\"): # close conjunction and open new one\n disjunction.append(system)\n system = ConstraintSystem()\n else:\n parse_line(line, system)\n return tasks\n","sub_path":"InterGen/task_parser/disjunction_parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"311724809","text":"import unittest\nfrom app import app\nimport json\nimport copy\nimport datetime\n\nclass TestCrud(unittest.TestCase):\n def setUp(self):\n self.client = app.test_client()\n\n def check_app_json_and_status_code(self, response, expected_code):\n self.assertEqual('application/json', response.headers['Content-Type'])\n self.assertEqual(response.status_code, expected_code)\n\n def test_get_users_order_by_followers(self):\n response = self.client.get(\"/user?order=followers\")\n self.check_app_json_and_status_code(response, 200)\n data = json.loads(response.data.decode())\n self.assertEqual(len(data['users'][0][\"followers\"]), 4)\n\n def test_get_users_empty_response(self):\n # emoty response if receives different filter\n response = self.client.get(\"/user?unknow=followers\")\n # 422 for Unprocessable Entity (unknow arg)\n self.check_app_json_and_status_code(response, 422)\n\n def test_get_total_posts_by_given_hour(self):\n #\"E MMM d y hh:mm:ss \"\n # from 01 jul 2016 20:00 to 21:00:00\n response = self.client.get(\"/post?from=1467414000&to=1467417600\")\n data = json.loads(response.data.decode())\n expected_n_of_users = 1\n self.assertEqual(len(data['users']), expected_n_of_users)\n\n def test_get_posts_empty_response(self):\n # emoty response if receives different filter\n response = self.client.get(\"/post?unknow=filter\")\n # 501 for not implemented\n self.check_app_json_and_status_code(response, 501)\n\n response2 = self.client.get(\"/post\")\n # 422 for Unprocessable Entity (unknow arg)\n self.check_app_json_and_status_code(response2, 422)\n\n def test_get_total_post_by_language_and_tag(self):\n response = self.client.get(\"/post?lang=en\")\n data = json.loads(response.data.decode())\n expected_n_of_users = 5\n self.assertEqual(len(data['users']), expected_n_of_users)\n\n response = self.client.get(\"/post?lang=en&tag=devops\")\n data = json.loads(response.data.decode())\n expected_n_of_users = 2\n self.assertEqual(len(data['users']), expected_n_of_users)\n\n def tearDown(self):\n pass\n","sub_path":"apps/twitter_api/tests/test_crud.py","file_name":"test_crud.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"371569015","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 15 11:29:41 2020\n\n@author: cynicos\n\"\"\"\n\n\nimport random\nM=int(input(\"შეიყვანეთ M: \"))\nN=int(input(\"შეიყვანეთ N: \"))\n\nMatrix = [[0 for x in range(M)] for y in range(N)] \n\nfor i in range(len(Matrix)) : \n for j in range(len(Matrix[i])) : \n if(i==0):\n Matrix[i][j]=random.randrange(1, 10)\n else:\n Matrix[i][j]=Matrix[i-1][j]*2\n print(Matrix[i][j], end=\" \") \n print() ","sub_path":"MLmidterm/davaleba_3.py","file_name":"davaleba_3.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"413278291","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# System\nimport os\nimport sys\nimport time\nfrom datetime import datetime\nimport multiprocessing\nfrom joblib import Parallel, delayed\nfrom tqdm import tqdm\n\n# Data Processing\nimport pandas as pd\n\n# Linear Algebra\nimport numpy as np\n\n# Data Visualization\nimport seaborn as sns\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom matplotlib import pyplot as plt\nfrom matplotlib import style\nfrom pandas.plotting import scatter_matrix\nfrom mpl_toolkits.mplot3d import Axes3D\n\n # Scaling and Sampling\nimport imblearn\nfrom imblearn.under_sampling import RandomUnderSampler, TomekLinks\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn import preprocessing\nfrom matplotlib.ticker import PercentFormatter\n\n# Clustering Algorithms\nfrom tslearn.clustering import KShape\nfrom sklearn.cluster import KMeans\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.svm import OneClassSVM\n\n#Outlier Detection\nfrom minisom import MiniSom\n\n# File management and databases\nimport csv\n#import teradatasql\nfrom zipfile import ZipFile\nfrom urllib.request import urlopen\n\nimport warnings\nwarnings.simplefilter(action=\"ignore\", category=UserWarning)\nwarnings.simplefilter(action=\"ignore\", category=FutureWarning)\n\nprint(\"Packages Imported\")\n\n\n# In[6]:\n\n\n# hourly data per cell with downtime less than 5 minutes in an hour\nseca_hh = pd.DataFrame()\n\ntry:\n seca_hh = seca_hh.append(pd.read_csv(\"/vha/home/61072380/seca_hh_norm.csv\"))\n \n cols = ['starttime', 'yyyy', 'mm', 'dd', 'hh', 'weekday', 'cellname', 'rrc_connreq_att', 'dl_mac_mb',\n 'thrp_bits_ul', 'traffic_user_avg', 'traffic_user_max', 'hho_interenb_interfr_att',\n 'ra_ta_ue_index3', 'traffic_activeuser_dl_qci_1', 'traffic_activeuser_dl_qci_8',\n 'traffic_activeuser_dl_qci_9', 'traffic_activeuser_dl_avg', 'prb_dl_uti', 'observed', 'season',\n 'trend', 'remainder', 'remainder_l1', 'remainder_l2', 'anomaly', 'recomposed_l1', 'recomposed_l2']\n \n seca_hh = seca_hh[cols]\nexcept:\n print(\"file not found\")\n\n\n# In[71]:\n\n\nseca_hh_anomolies = pd.DataFrame()\n\ntry:\n seca_hh_anomolies = seca_hh_anomolies.append(pd.read_csv(\"/vha/home/61072380/seca_hh_anomolies.csv\"))\nexcept:\n print(\"file not found\")\n\n\n# In[83]:\n\n\nanomolies = list(set(seca_hh_anomolies['cellname']))\nlen(anomolies)\n\n\n# In[9]:\n\n\nseca_hh.describe()\n\n\n# In[10]:\n\n\ncells = list(set(seca_hh['cellname']))\nstarttimes = list(set(seca_hh['starttime']))\nlen(cells)\n\n\n# In[11]:\n\n\nmissing = pd.DataFrame(seca_hh['cellname'].value_counts())len(starttimes)\ncells_duplicated = list(duplicates[duplicates['cellname']==True].index)\nfull_cells = list(set(full_cells)-set(cells_duplicated))\nlen(full_cells)\n\n\n# In[12]:\n\n\nlen(cells_missing)\n\n\n# In[13]:\n\n\nlen(cells_duplicated)\n\n\n# In[14]:\n\n\nnum_cores = multiprocessing.cpu_count()\n\n\n# In[105]:\n\n\nseca_hh['users'] = seca_hh['traffic_user_avg']\nseca_hh_anom = seca_hh[seca_hh['cellname'].isin(anomolies)]\nseca_hh_norm = seca_hh[seca_hh['cellname'].isin(list(set(full_cells)-set(anomolies)))]\n\na_idxs = seca_hh_anom[seca_hh_anom['anomaly']==\"Yes\"].index\nn_idxs = seca_hh_norm[seca_hh_norm['observed']==-1].index\n\nseca_hh_anom['users'].loc[a_idxs] = seca_hh_anom['trend'].loc[a_idxs].copy()\nseca_hh_norm['users'].loc[n_idxs] = seca_hh_norm['trend'].loc[n_idxs].copy()\n\nseca_hh_fin = pd.concat([seca_hh_anom, seca_hh_norm], ignore_index=True)\n\ndf = pd.concat([pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['users'].median()),\n pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['users'].max()),\n pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['users'].min()),\n pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['users'].mean()),\n pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['users'].std()),\n pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['users'].quantile(0.9)),\n pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['traffic_user_avg'].median()),\n pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['traffic_user_avg'].max()),\n pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['traffic_user_avg'].min()),\n pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['traffic_user_avg'].mean()),\n pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['traffic_user_avg'].std()),\n pd.DataFrame(seca_hh_fin.groupby(seca_hh_fin.starttime)['traffic_user_avg'].quantile(0.9))],\n axis=1)\n\ndf.columns = [\"users Median\", \"users Max\", \"users Min\", \"users Mean\", \"users Standard Deviation\", \"users 90th Perc\",\n \"traffic_user_avg Median\", \"traffic_user_avg Max\", \"traffic_user_avg Min\", \"traffic_user_avg Mean\", \"traffic_user_avg Standard Deviation\", \"traffic_user_avg 90th Perc\"]\ndf\n\n\n# In[106]:\n\n\nindex = pd.date_range(starttimes[0], periods=336, freq=\"h\", name=\"date\")\nwide_df = pd.DataFrame(np.array(df[['users Median', 'traffic_user_avg Median']]), index,\n ['users Median', 'traffic_user_avg Median'])\n\nplt.figure(figsize=(16, 6))\nax = sns.lineplot(data=wide_df, dashes=False)\n\n\n# # Address missing values\n\n# In[ ]:\n\n\ndef fillinblank(x, y, c, d):\n\n return {'starttime': d,\n 'yyyy': x.strftime(\"%Y\"),\n 'mm': x.strftime(\"%m\"),\n 'dd': x.strftime(\"%d\"),\n 'hh': x.strftime(\"%H\"),\n 'weekday': x.strftime(\"%w\"),\n 'cellname': c,\n 'rrc_connreq_att': y[y['hh']==int(x.strftime(\"%H\"))]['rrc_connreq_att'].median(),\n 'dl_mac_mb': y[y['hh']==int(x.strftime(\"%H\"))]['dl_mac_mb'].median(),\n 'thrp_bits_ul': y[y['hh']==int(x.strftime(\"%H\"))]['thrp_bits_ul'].median(),\n 'traffic_user_avg': y[y['hh']==int(x.strftime(\"%H\"))]['traffic_user_avg'].median(),\n 'traffic_user_max': y[y['hh']==int(x.strftime(\"%H\"))]['traffic_user_max'].median(),\n 'hho_interenb_interfr_att': y[y['hh']==int(x.strftime(\"%H\"))]['hho_interenb_interfr_att'].median(),\n 'ra_ta_ue_index3': y[y['hh']==int(x.strftime(\"%H\"))]['ra_ta_ue_index3'].median(),\n 'traffic_activeuser_dl_qci_1': y[y['hh']==int(x.strftime(\"%H\"))]['traffic_activeuser_dl_qci_1'].median(),\n 'traffic_activeuser_dl_qci_8': y[y['hh']==int(x.strftime(\"%H\"))]['traffic_activeuser_dl_qci_8'].median(),\n 'traffic_activeuser_dl_qci_9': y[y['hh']==int(x.strftime(\"%H\"))]['traffic_activeuser_dl_qci_9'].median(),\n 'traffic_activeuser_dl_avg': y[y['hh']==int(x.strftime(\"%H\"))]['traffic_activeuser_dl_avg'].median(),\n 'prb_dl_uti': y[y['hh']==int(x.strftime(\"%H\"))]['prb_dl_uti'].median()\n }\n\n\n# In[ ]:\n\n\ndef missing(c, y, d):\n\n dates = list(set(d)-set(y['starttime']))\n df = pd.DataFrame()\n \n for date in dates:\n x = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')\n df = df.append(fillinblank(x, y, c, date), ignore_index=True)\n \n return df\n\n\n# In[ ]:\n\n\nif __name__ == \"__main__\":\n filled = Parallel(n_jobs=num_cores)(delayed(missing)(cell, seca_hh[seca_hh['cellname']==cell], starttimes)\n for cell in tqdm(cells_missing))\n\n seca_hh = seca_hh.append(filled, ignore_index=True)\n\n\n# # Scale all cells individually\n\n# In[107]:\n\n\ndef scale(df, d):\n values = np.array(df.users).reshape(-1, 1)\n \n if len(values)==len(d):\n return StandardScaler().fit_transform(values)\n \nprint(\"scale() ready.\")\n\n\n# In[108]:\n\n\ntimestr = time.strftime(\"%Y%m%d_%H%M%S\")\nusers = np.array([])\n\n\n# In[109]:\n\n\nif __name__ == \"__main__\":\n scaled = Parallel(n_jobs=num_cores)(delayed(scale)(seca_hh[seca_hh['cellname']==cell],\n starttimes) for cell in tqdm(full_cells[0:1000]))\n users = np.append(users, scaled)\n\n#np.savetxt(\"/vha/home/61072380/seca_scaled_\"+timestr+\".csv\", users, delimiter=\",\")\n\n\n# In[110]:\n\n\ncluster_numbers = list(np.arange(2, 34, 2))\n\n\n# In[111]:\n\n\ndata = np.reshape(np.nan_to_num(users), (-1, len(starttimes), 1))\n\nseed = 0\nnp.random.seed(seed)\nsz = data.shape[1]\n\noutput = pd.DataFrame()\noutput['cellname'] = full_cells[0:1000]\n\nfor cluster_number in cluster_numbers:\n print(cluster_number)\n ks = KShape(n_clusters=cluster_number, verbose=True, random_state=seed)\n y_pred = ks.fit_predict(data)\n output[cluster_number] = y_pred\n\n\n# In[ ]:\n\n\ntry:\n output = pd.read_csv(\"/vha/home/61072380/seca_hh_clusters_20190930_200800.csv\")\n output = output.drop(output.columns[0], axis=1)\nexcept:\n print(\"No scaled data\")\n\ncluster_counts = pd.DataFrame()\ncluster_counts['index'] = cluster_numbers\ncluster_counts = cluster_counts.set_index('index', drop=True)\ncluster_medians = pd.DataFrame()\n\nfor cluster_number in cluster_numbers:\n counts = pd.DataFrame(output[str(cluster_number)].value_counts())\n cluster_counts = pd.concat([cluster_counts, counts], axis=1)\n \n try:\n cluster_medians = pd.read_csv(\"/vha/home/61072380/seca_hh_medians_20190930_200800.csv\")\n cluster_medians = cluster_medians.drop(cluster_medians.columns[0], axis=1)\n except:\n for y in range(0, cluster_number):\n cluster_medians[str(cluster_number)+\"_\"+str(y)] = ks.cluster_centers_[y].ravel()\n\ncluster_counts = cluster_counts.drop(32)\ncluster_counts\n\n\n# In[ ]:\n\n\noutput.head()\n\n\n# In[ ]:\n\n\n#cluster_medians.to_csv(\"/vha/home/61072380/seca_hh_medians_\"+timestr+\".csv\")\nstarttimes.sort()\ncluster_medians['starttime'] = starttimes\ncluster_medians.to_csv(\"/vha/home/61072380/seca_hh_medians_20190930_200800.csv\")\ncluster_medians\n\n\n# In[ ]:\n\n\nstarttimes.sort()\ncols = [col for col in cluster_medians.columns if '32_13' in col]\ncols = ['32_20', '32_22', '32_28', '32_29']\ncols = ['32_14', '32_12', '32_18']\nindex = pd.date_range(starttimes[0], periods=336, freq=\"h\", name=\"date\")\nwide_df = pd.DataFrame(np.array(cluster_medians[cols]), index, cols)\n\nplt.figure(figsize=(16, 6))\nax = sns.lineplot(data=wide_df, dashes=False)\n\n\n# In[ ]:\n\n\nscatter_df = pd.concat([pd.DataFrame(cluster_medians.median()),\n pd.DataFrame(cluster_medians.max()),\n pd.DataFrame(cluster_medians.min()),\n pd.DataFrame(cluster_medians.mean()),\n pd.DataFrame(cluster_medians.std()),\n pd.DataFrame(cluster_medians.quantile(0.9))],\n axis=1)\nscatter_df = scatter_df.reset_index()\nscatter_df.columns = [\"Cluster\", \"Median\", \"Max\", \"Min\", \"Mean\", \"Standard Deviation\", \"90th Perc\"]\nscatter_df\n\n\n# In[ ]:\n\n\noutput.to_csv(\"/vha/home/61072380/seca_hh_clusters_\"+timestr+\".csv\")\n\n\n# In[114]:\n\n\nn=32\n\nplt.figure(figsize=(16, n*4))\nfor yi in range(n):\n plt.subplot(n, 2, 1 + yi)\n for xx in data[y_pred == yi]:\n plt.plot(xx.ravel(), \"k-\", alpha=.2)\n plt.plot(ks.cluster_centers_[yi].ravel(), \"r-\")\n plt.xlim(0, sz)\n plt.ylim(-5, 5)\n plt.title(\"Users Cluster %d\" % (yi))\n\nplt.tight_layout()\nplt.show()\n\n\n# In[ ]:\n\n\nclusters = [\"0\", \"3\", \"4\", \"5\", \"6\", \"7\", \"15\", \"24\", \"27\", \"30\", \"31\"]\nanomaly_cells = list(set(seca_hh[seca_hh['cellname'].isin(list(output[output['32'].isin(clusters)]['cellname']))]['cellname']))\n\n\n# In[ ]:\n\n\npd.DataFrame(anomaly_cells).to_csv(\"/vha/home/61072380/seca_hh_anomaly_cells.csv\")\n\n\n# In[ ]:\n\n\nclusters = [\"X32_0\", \"X32_3\", \"X32_4\", \"X32_5\", \"X32_6\", \"X32_7\", \"X32_15\", \"X3_24\", \"X32_27\", \"X32_30\", \"X32_31\"]\n#to_drop = []\n\nfor cluster in clusters:\n tmp = anomalized[anomalized['cluster']==cluster]\n anomalies = list(tmp[tmp['anomaly']==\"Yes\"]['starttime'])\n anomaly_cells = list(set(seca_hh[seca_hh['cellname'].isin(list(output[output['32']==int(cluster.split(\"_\")[1])]['cellname']))]['cellname']))\n \n todo = len(anomalies)*len(anomaly_cells)\n count = 1\n \n for anomaly in anomalies:\n for anomaly_cell in anomaly_cells:\n to_drop.append(seca_hh.loc[(seca_hh['cellname']==anomaly_cell) &\n (seca_hh['starttime']==anomaly)].index[0])\n print(cluster, count, round(100*count/todo, 3))\n count+=1\n \n pd.DataFrame(to_drop).to_csv(\"/vha/home/61072380/seca_hh_todrop.csv\")\n\n\n# In[ ]:\n\n\ntry:\n to_drop = pd.read_csv(\"/vha/home/61072380/seca_hh_todrop.csv\")\n to_drop = to_drop.drop(to_drop.columns[0], axis=1)\nexcept:\n print(\"Nothing to drop\")\n \nseca_hh_norm = seca_hh.drop(list(to_drop['0']))\nseca_hh_norm = seca_hh_norm[seca_hh_norm['cellname'].isin(list(output[output['32']!=1]['cellname']))]\nseca_hh_norm\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"seca_v2.py","file_name":"seca_v2.py","file_ext":"py","file_size_in_byte":13089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"398157841","text":"# This could is created produce the following\n# 1. Total number of votes cast\n# 2. A complete list of candidates who received votes\n# 3. Total number of votes each candidate received\n# 4. Percentage of votes each candidate won\n# 5. The winner of the election based on popular vote\n# The below comments relate to the 1 - 5 products that are produced.\n\n#Open the data file.\n# Add our dependencies.\nimport csv\nimport os\n\n#Assign a variable to load a file for a path.\nfile_to_load = os.path.join(\"Resources\", \"election_results.csv\")\n\n#Assign a variable to save the file to a path.\nfile_to_save = os.path.join(\"analysis\", \"election_analysis.txt\")\n\n#1. The total number of votes cast\n#1. Initialize a total vote counter.\ntotal_votes = 0\n\n#2. A complete list of all the candidates.\ncandidate_options = []\n\n#3. Create a dictonary to hold the candidate options and thier count of votes.\ncandidate_votes = {}\n\n#4. Determine winning candidate along with winning count and percentage\n#4. initiate variables for winning candidate, winning count and winning percentage\nwinning_candidate = \"\"\nwinning_count = 0\nwinning_percentage = 0\n\n#Open the election results and read the file\nwith open(file_to_load) as election_data:\n file_reader = csv.reader(election_data)\n\n #Print each row in the CSV file.\n headers = next(file_reader)\n \n #Print each row inthe CSV file.\n for row in file_reader:\n #1. Add to the total vote count.\n total_votes += 1\n \n #2, Print the candidate name from each row\n candidate_name = row[2]\n\n #2. If the candidate does not match any existing candidate.\n if candidate_name not in candidate_options:\n #2. Add it to the list of candidates\n candidate_options.append(candidate_name)\n\n #3. Begin tacking the candidate's vote count.\n candidate_votes[candidate_name] = 0\n\n #3. Add a vote to the candidate's count.\n candidate_votes[candidate_name] += 1\n\n#ASave the results to our text file.\nwith open(file_to_save, \"w\") as txt_file:\n #Print the final vote count to the terminal.\n election_results = (\n f\"\\nElection Results\\n\"\n f\"-------------------------\\n\"\n f\"Total Votes: {total_votes:,}\\n\"\n f\"-------------------------\\n\")\n print(election_results, end=\"\")\n # Save the final vote count to the text file.\n txt_file.write(election_results)\n\n #4. Determine the percentage of votes for each candidate by looping through\n #4. Iterate through the candidate list.\n for candidate_name in candidate_votes:\n #4. Retrieve vote count of candidate.\n votes = candidate_votes[candidate_name]\n \n #4. Calcualte the percentage of votes.\n vote_percentage = float(votes) / float(total_votes) * 100\n \n #4. Print the candidaate name and percentage of votes.\n # print(f\"{candidate_name}: received {vote_percentage:.1f}% of the vote\")\n\n #5. Determine winning vote count and candidate\n #5. Determine if the votes are greater that the winning count.\n if (votes > winning_count) and (vote_percentage > winning_percentage):\n #5 if ture then set winning_count = votes and wining_percent = vote_percentage.\n winning_count = votes\n winning_percentage = vote_percentage\n winning_candidate = candidate_name\n\n # Print each candidate, their voter count, and the percentage to the terminal.\n candidate_results = (f\" {candidate_name}: {vote_percentage:.1f}% ({votes:,})\\n\")\n print(candidate_results)\n # Save the candidate results to our text file.\n txt_file.write(candidate_results)\n \n \n winning_candidate_summary = (\n f\"-------------------------\\n\"\n f\"Winner: {winning_candidate}\\n\"\n f\"Winning Vote Count: {winning_count:,}\\n\"\n f\"Winning Percentage: {winning_percentage:.1f}%\\n\"\n f\"-------------------------\\n\")\n #5. Print(winning_candidate_summary)\n print(winning_candidate_summary)\n \n #5. Save the winning candidate's name to the text file.\n txt_file.write(winning_candidate_summary)","sub_path":"PyPoll.py","file_name":"PyPoll.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"324939199","text":"#__author: xlu.com\n#date : 2018/8/8\n\nfrom bs4 import BeautifulSoup\n# import html5lib\nimport requests\n\ndef get_CountentByUrl(url):\n res = requests.get(url)\n html = res.content.decode('gbk')\n bss = BeautifulSoup(html,features=\"lxml\")\n # list_a = bss.find_all('a',attrs={'href':True})\n list_a = bss.find('div',class_='bd3r').find_all('div',class_='co_area2')\n ret_list = []\n for item in list_a:\n for con in item.find_all('tr'):\n # it = con.get_text('|',strip=True)//获取标签内的所有字符串 以|隔开\n it = [];\n for string in con.stripped_strings:\n it.append(string)\n ret_list.append(it)\n print(it)\n print(ret_list)\nif __name__ == '__main__':\n get_CountentByUrl('http://www.dytt8.net/')\n","sub_path":"pc/2/bs4_1.py","file_name":"bs4_1.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"32752133","text":"# coding: utf-8\n\n\"\"\"\n Cloudera Manager API\n\n

Cloudera Manager API v33

Introduced in Cloudera Manager 6.3.0

Cloudera Product Documentation

\n\n OpenAPI spec version: 6.3.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nfrom pprint import pformat\nfrom six import iteritems\nimport re\n\n\nclass ApiHdfsSnapshot(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'path': 'str',\n 'snapshot_name': 'str',\n 'snapshot_path': 'str',\n 'creation_time': 'str'\n }\n\n attribute_map = {\n 'path': 'path',\n 'snapshot_name': 'snapshotName',\n 'snapshot_path': 'snapshotPath',\n 'creation_time': 'creationTime'\n }\n\n def __init__(self, path=None, snapshot_name=None, snapshot_path=None, creation_time=None):\n \"\"\"\n ApiHdfsSnapshot - a model defined in Swagger\n \"\"\"\n\n self._path = None\n self._snapshot_name = None\n self._snapshot_path = None\n self._creation_time = None\n\n if path is not None:\n self.path = path\n if snapshot_name is not None:\n self.snapshot_name = snapshot_name\n if snapshot_path is not None:\n self.snapshot_path = snapshot_path\n if creation_time is not None:\n self.creation_time = creation_time\n\n @property\n def path(self):\n \"\"\"\n Gets the path of this ApiHdfsSnapshot.\n Snapshotted path.\n\n :return: The path of this ApiHdfsSnapshot.\n :rtype: str\n \"\"\"\n return self._path\n\n @path.setter\n def path(self, path):\n \"\"\"\n Sets the path of this ApiHdfsSnapshot.\n Snapshotted path.\n\n :param path: The path of this ApiHdfsSnapshot.\n :type: str\n \"\"\"\n\n self._path = path\n\n @property\n def snapshot_name(self):\n \"\"\"\n Gets the snapshot_name of this ApiHdfsSnapshot.\n Snapshot name.\n\n :return: The snapshot_name of this ApiHdfsSnapshot.\n :rtype: str\n \"\"\"\n return self._snapshot_name\n\n @snapshot_name.setter\n def snapshot_name(self, snapshot_name):\n \"\"\"\n Sets the snapshot_name of this ApiHdfsSnapshot.\n Snapshot name.\n\n :param snapshot_name: The snapshot_name of this ApiHdfsSnapshot.\n :type: str\n \"\"\"\n\n self._snapshot_name = snapshot_name\n\n @property\n def snapshot_path(self):\n \"\"\"\n Gets the snapshot_path of this ApiHdfsSnapshot.\n Read-only. Fully qualified path for the snapshot version of \\\"path\\\".

For example, if a snapshot \\\"s1\\\" is present at \\\"/a/.snapshot/s1, then the snapshot path corresponding to \\\"s1\\\" for path \\\"/a/b\\\" will be \\\"/a/.snapshot/s1/b\\\".\n\n :return: The snapshot_path of this ApiHdfsSnapshot.\n :rtype: str\n \"\"\"\n return self._snapshot_path\n\n @snapshot_path.setter\n def snapshot_path(self, snapshot_path):\n \"\"\"\n Sets the snapshot_path of this ApiHdfsSnapshot.\n Read-only. Fully qualified path for the snapshot version of \\\"path\\\".

For example, if a snapshot \\\"s1\\\" is present at \\\"/a/.snapshot/s1, then the snapshot path corresponding to \\\"s1\\\" for path \\\"/a/b\\\" will be \\\"/a/.snapshot/s1/b\\\".\n\n :param snapshot_path: The snapshot_path of this ApiHdfsSnapshot.\n :type: str\n \"\"\"\n\n self._snapshot_path = snapshot_path\n\n @property\n def creation_time(self):\n \"\"\"\n Gets the creation_time of this ApiHdfsSnapshot.\n Snapshot creation time.\n\n :return: The creation_time of this ApiHdfsSnapshot.\n :rtype: str\n \"\"\"\n return self._creation_time\n\n @creation_time.setter\n def creation_time(self, creation_time):\n \"\"\"\n Sets the creation_time of this ApiHdfsSnapshot.\n Snapshot creation time.\n\n :param creation_time: The creation_time of this ApiHdfsSnapshot.\n :type: str\n \"\"\"\n\n self._creation_time = creation_time\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n if not isinstance(other, ApiHdfsSnapshot):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n","sub_path":"venv/lib/python3.7/site-packages/cm_client/models/api_hdfs_snapshot.py","file_name":"api_hdfs_snapshot.py","file_ext":"py","file_size_in_byte":5898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"541298423","text":"#authors: Ryan Carey and Ryan Hough using open source computer vision, stackexchange, docs and APIs\nimport numpy as np\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom pathlib import Path\nimport cv2\nfrom datetime import datetime, timedelta\nimport platform\nimport os\nimport sys\nimport csv\nimport time\nimport glob\nfrom matplotlib import pyplot as graphme\nimport base64\nimport copyreg\n\ndef comparewithsaved(suspecturl, suspectarray):\n\tsuspectkeypoints, suspectdescriptors = detectfeatures(suspectarray)\n\tfor filename in glob.glob(os.path.join(numpyproperpath, '*.npz')): #traverse the savedarrays folder and load all the numpy arrays\n\t\ttrustednumpy = np.load(filename) #load references to the data in filename into variables\n\t\ttrustedimage = trustednumpy['trustedimage']\n\t\ttrustedkeypoints = trustednumpy['keypoints']\n\t\ttrusteddescriptors = trustednumpy['descriptors']\n\t\tmatchedDescriptors = brute.match(suspectdescriptors, trusteddescriptors)\n\t\tmatchedDescriptors = sorted(matchedDescriptors, key = lambda x:x.distance) #sort by minimum distance\n\t\tcumdist = 0\n\t\ttrustedurl = os.path.basename(filename)\n\t\ttrustedurl = trustedurl[:-4]\n\t\ttrustedurl = trustedurl.encode('UTF-8')\n\t\ttrustedurl = base64.urlsafe_b64decode(trustedurl)\n\t\ttrustedurl = trustedurl.decode('UTF-8')\n\t\tfor match in matchedDescriptors[:10]:\n\t\t\tcumdist += match.distance\n\t\tif (cumdist < 100 and cumdist != 0): #check validity of the match\n\t\t\tresponse = 'This url is likely a fishing site. It has features in common with ' + trustedurl\n\t\t\tmatchdisplay = cv2.drawMatches(suspectarray, suspectkeypoints, trustedimage, trustedkeypoints, matchedDescriptors[:10], None, flags=2)\n\t\t\tgraphme.title('Visual representation of the matched features')\n\t\t\tgraphme.imshow(matchdisplay,None,None,'equal'),graphme.show()\n\t\t\treturn response\n\t\telif (cumdist == 0 and trustedurl == suspecturl):\n\t\t\tresponse = 'This url is a legitimate site we have saved information for.'\n\t\t\tmatchdisplay = cv2.drawMatches(suspectarray, suspectkeypoints, trustedimage, trustedkeypoints, matchedDescriptors[:10], None, flags=2)\n\t\t\tgraphme.title('Visual representation of the matched features')\n\t\t\tgraphme.imshow(matchdisplay,None,None,'equal'),graphme.show()\n\t\t\treturn response\n\t\telif cumdist > 100:\n\t\t\tresponse = 'This url is not similar to any of our saved sites, and is not in the phishing csv.'\n\t\ttrustednumpy.close()\n\treturn response\n\ndef buildstoredimageswithfeatures():\n\twith open(os.path.join(currpath, 'top500.csv'), 'r') as trusted: #open and read urls from the trusted top500 sites.\n\t\treadtrusted = csv.reader(trusted)\n\t\trfields = readtrusted.__next__()\n\t\ttrustedurlField = rfields.index('URL')\n\t\tfor row in readtrusted:\n\t\t\ttrustedurl = row[trustedurlField]\n\t\t\ttrustedurl = prependurl(trustedurl)\n\t\t\tgetpagescreenshot(trustedurl, 'trustedurl.png')\n\t\t\twhile not os.path.isfile('trustedurl.png'):\n\t\t\t\ttime.sleep(1)\n\t\t\ttrustedimage = cv2.imread('trustedurl.png', cv2.IMREAD_GRAYSCALE)\n\t\t\ttrustedimage = resizer(trustedimage) #now it's been resized\n\t\t\tkeypoints, descriptors = detectfeatures(trustedimage)\n\t\t\ttrustedurl = trustedurl.encode('UTF-8')\n\t\t\ttrustedurlstorage = base64.urlsafe_b64encode(trustedurl) #change trustedurl into a form that can be used as a filename while keeping the url intact for decoding later\n\t\t\ttrustedurlstorage = trustedurlstorage.decode('UTF-8')#decode trustedurl so we don't get a type error related to the bytes type\n\t\t\tcopyreg.pickle(cv2.KeyPoint().__class__, _pickle_keypoints)\n\t\t\tnp.savez(os.path.join(numpypath, trustedurlstorage), trustedimage=trustedimage, keypoints=keypoints, descriptors=descriptors)\n\t\t\tif os.path.isfile('trustedurl.png'):\n\t\t\t\tos.remove('trustedurl.png')\n\t\t\t\n\tinput('finally done...\\n')\n\ndef _pickle_keypoints(point):#workaround to allow saving keypoints which normally throw an error when trying to write them to a .npz\n return cv2.KeyPoint, (*point.pt, point.size, point.angle,\n point.response, point.octave, point.class_id)\ndef prependurl(url):\n\turl = 'http://'+url\n\treturn url\n\ndef resizer(nump):\n\tscale_percent = 50 #see above in buildstoredimageswithfeatures\n\twidth = int(nump.shape[1] * scale_percent / 100)\n\theight = int(nump.shape[0] * scale_percent / 100)\n\tdim = (width, height)\n\tnump = cv2.resize(nump, dim, interpolation = cv2.INTER_AREA) #resized\n\treturn nump\n\ndef detectfeatures(nump):\n\tkeyp, desc = orb.detectAndCompute(nump,None)\n\treturn keyp, desc\n\ndef getpagescreenshot(url, imagename):\n\tdriver.get(url) #go to the given url\n\tdriver.save_screenshot(imagename)\n\t\ndef phishingcsv():\n\tif os.path.isfile('verified_online.csv'):\n\t\tif datetime.fromtimestamp(os.path.getmtime(\"verified_online.csv\")) < one_hour_ago:\n\t\t\tos.remove('verified_online.csv')\n\t\t\tdriver.get('http://data.phishtank.com/data/6b865298ce2d0dd22ca4be46fd06c61314cca790d8d4de36ff0a7a4a6ebbf9f6/online-valid.csv')\n\telse:\n\t\tdriver.get('http://data.phishtank.com/data/6b865298ce2d0dd22ca4be46fd06c61314cca790d8d4de36ff0a7a4a6ebbf9f6/online-valid.csv')\n\twhile not os.path.isfile('verified_online.csv'):\n\t\ttime.sleep(1)\n\telse:\n\t\twith open(os.path.join(currpath, 'verified_online.csv'), 'r') as knownphishes:\n\t\t\treadphishes = csv.reader(knownphishes)\n\t\t\tpfields = readphishes.__next__()\n\t\t\turlField = pfields.index('url')\n\t\t\tfor row in readphishes:\n\t\t\t\tif prependurl(row[urlField]) == suspecturl:\n\t\t\t\t\tinput('This is a fishing site according to the database.Type enter to exit.')\n\t\t\t\t\texit()\n\norb = cv2.ORB_create()\nbrute = cv2.BFMatcher_create(cv2.NORM_HAMMING, crossCheck=True)\ncurrpath = os.path.abspath(os.path.curdir)\nnumpypath = os.path.abspath(os.path.join(currpath, 'savedarrays'))\nnumpyproperpath = Path(numpypath)\nprecompute = input('Would you like to go through the top sites and rebuild the comparison data for them? Type y for yes. All other answers mean no: ')\n\noptions = webdriver.ChromeOptions()\noptions.add_argument('--ignore-certificate-errors')\noptions.add_argument(\"--test-type\")\ndownloadpref = {\"download.default_directory\": currpath,\n \"directory_upgrade\": True,\n\t\t\t \"download.prompt_for_download\": False,\n \"safebrowsing.enabled\": False }\noptions.add_experimental_option(\"prefs\", downloadpref)\ndriver = webdriver.Chrome(executable_path=ChromeDriverManager().install(), options=options)\n\n\nif (precompute == 'y') or (precompute == 'Y'):\n\tbuildstoredimageswithfeatures()\nsuspecturl = input('Enter or copy/paste a URL: ')\none_hour_ago = datetime.now() - timedelta(hours=1)\nif not suspecturl[0:4] == 'http':\n\tsuspecturl = prependurl(suspecturl)\ntry:\n\tgetpagescreenshot(suspecturl, 'suspecturl.png')\nexcept:\n\tsuspecturl = input('Try a different url, that one did not work: ')\nphishingcsv()\n\nsuspectimage = cv2.imread('suspecturl.png', cv2.IMREAD_GRAYSCALE)\nsuspectimage = resizer(suspectimage) #resized\n\nprint(comparewithsaved(suspecturl, suspectimage))\ndriver.close()","sub_path":"SRA211/phishingorb/phishingorb.py","file_name":"phishingorb.py","file_ext":"py","file_size_in_byte":6851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"567155473","text":"\nimport unittest\n\nfrom requests.exceptions import HTTPError\n\nfrom drone.users import Drone\n\n\nclass TestUsers(unittest.TestCase):\n def setUp(self):\n self.users = Drone.Users()\n\n def test_all(self):\n with self.assertRaises(HTTPError) as err:\n self.users.all()\n self.assertEqual(err.response.status_code, 403)\n\n def test_info(self):\n with self.assertRaises(HTTPError) as err:\n self.users.info(user='tinvaan')\n self.assertEqual(err.response.status_code, 403)\n\n def test_delete(self):\n with self.assertRaises(HTTPError) as err:\n self.users.delete('tinvaan')\n self.assertEqual(err.response.status_code, 403)\n\n def test_create(self):\n with self.assertRaises(HTTPError) as err:\n user = {\n \"login\": \"octocat\",\n \"email\": \"octocat@github.com\",\n \"avatar_url\": \"http://www.gravatar.com/avatar/7194e8d48fa1d2b689f99443b767316c\",\n \"active\": True\n }\n self.users.create(**user)\n self.assertEqual(err.response.status_code, 403)\n \n def test_update(self):\n with self.assertRaises(HTTPError) as err:\n user = {\n \"login\": \"foobar\",\n \"email\": \"foobar@github.com\",\n \"avatar_url\": \"http://www.gravatar.com/avatar/7194e8d48fa1d2b689f99443b767316c\",\n \"active\": False\n }\n self.users.update('tinvaan', **user)\n self.assertEqual(err.response.status_code, 403)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_users.py","file_name":"test_users.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"327625215","text":"from django.shortcuts import render, get_object_or_404, redirect\n\nfrom .forms import PaymentInfoForm\nfrom .decorators import make_order\n\nfrom account.models import Account, PaymentInfo\n\n\n@make_order\ndef checkout_page(request):\n \"\"\"\n Handles GET requests to the order page.\n If user has at least one element in their cart, return info about that item\n If user has no items in their cart, redirect to the products page.\n \"\"\"\n try:\n account = get_object_or_404(Account, user=request.user)\n\n except TypeError:\n device = request.COOKIES['device']\n account, created = Account.objects.get_or_create(device=device)\n\n if hasattr(account, 'paymentinfo'):\n info = PaymentInfo.objects.filter(account=account)[0]\n initial_info_obj = {\n 'name': info.name_of_cardholder,\n 'street_name': info.street_name,\n 'house_number': info.house_number,\n 'city': info.city,\n 'postal_code': info.postal_code,\n 'name_of_cardholder': info.name_of_cardholder,\n 'card_number': info.card_number,\n 'expiration_year': info.expiration_date.year,\n 'expiration_month': info.expiration_date.month,\n 'cvc': info.cvc\n }\n payment_form = PaymentInfoForm(initial=initial_info_obj)\n else:\n payment_form = PaymentInfoForm()\n\n cart = account.cart\n cart_items = cart.cartitem_set.all()\n\n # If cart is empty, redirect\n if len(cart_items) == 0:\n return redirect('products', 'cereal')\n\n cart_info = {'count': 0, 'price': 0}\n for item in cart_items:\n cart_info['count'] += 1 * item.quantity\n cart_info['price'] += item.product.price * item.quantity\n\n context = {'form': payment_form, 'cart_info': cart_info}\n return render(request, 'order/order.html', context)\n","sub_path":"order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608746637","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport os\n\n\nclass FioDocument:\n def __init__(self):\n self.prefix = {'io': 0.0, 'bw': 0.0, 'iops': 0.0, 'runt': 0.0}\n self.clat = {'min': 0.0, 'max': 0.0, 'avg': 0.0, 'stdev': 0.0}\n self.clat_percentiles = {1.00: 0, 5.00: 0, 10.00: 0, 20.00: 0, 30.00: 0, 40.00: 0, 50.00: 0, 60.00: 0, 70.00: 0,\n 80.00: 0, 90.00: 0, 95.00: 0, 99.00: 0, 99.50: 0, 99.90: 0, 99.95: 0, 99.99: 0}\n self.bw = {'min': 0.0, 'max': 0.0, 'per': 0.0, 'avg': 0.0, 'stdev': 0.0};\n self.all_jobs = {'io': 0.0, 'aggrb': 0.0, 'minb': 0.0, 'maxb': 0.0, 'mint': 0.0, 'maxt': 0.0}\n\n def getattribute(self, item):\n return self.__getattribute__(item)\n\n def init_data(self):\n self.__init__()\n\n def print_all_kv(self):\n print(\"prefix\")\n print(self.prefix)\n print(\"clat\")\n print(self.clat)\n print(\"clat_percentiles\")\n print(self.clat_percentiles)\n print(\"bw\")\n print(self.bw)\n print(\"all_jobs\")\n print(self.all_jobs)\n\n\nclass FioRWDocument:\n def __init__(self, fio_read_document, fio_write_document):\n self.fio_read_document = fio_read_document\n self.fio_write_document = fio_write_document\n\n def __init__(self):\n self.test_parameter = {'direct': 0, 'iodepth': 0, 'rw': 'readwrite', 'ioengine': 'psync', 'bs': 0, 'size': 0,\n 'numjobs': 0, 'runtime': 0, 'name': ''}\n self.fio_read_document = None\n self.fio_write_document = None\n self.lat_usec = {2: 0.0, 4: 0.0, 10: 0.0, 20: 0.0, 50: 0.0, 100: 0.0, 250: 0.0, 500: 0.0, 750: 0.0, 1000: 0.0}\n self.lat_msec = {2: 0.0, 4: 0.0, 10: 0.0, 20: 0.0, 50: 0.0, 100: 0.0, 250: 0.0, 500: 0.0, 750: 0.0, 1000: 0.0,\n 2000: 0.0,\n 2001: 0.0}\n self.cpu = {'usr': 0.0, 'sys': 0.0, 'ctx': 0.0, 'majf': 0.0, 'minf': 0.0}\n self.io_depths = {1: 0.0, 2: 0.0, 4: 0.0, 8: 0.0, 16: 0.0, 32: 0.0, 64: 0.0, 65: 0.0}\n self.submit = {0: 0.0, 2: 0.0, 4: 0.0, 8: 0.0, 16: 0.0, 32: 0.0, 64: 0.0, 65: 0.0}\n self.complete = {0: 0.0, 2: 0.0, 4: 0.0, 8: 0.0, 16: 0.0, 32: 0.0, 64: 0.0, 65: 0.0}\n self.issued = {'total': 0, 'short': 0, 'drop': 0}\n self.latency = {'target': 0, 'window': 0, 'percentile': 0, 'depth': 0}\n\n def getattribute(self, item):\n return self.__getattribute__(item)\n\n def init_data(self): # 不销毁对象 只清除数据 和__init__()函数不能混为一谈\n # self.test_parameter = {'direct': 0, 'iodepth': 0, 'rw': 'readwrite', 'ioengine': 'psync', 'bs': 0, 'size': 0,\n # 'numjobs': 0, 'runtime': 0, 'name': ''}\n # 不能清理 这里的值一个fio文件才输出一个 后面很多操作要根据这里的参数进行例如读写方式,一旦清理,后面会失去操作依据\n self.fio_read_document = None\n self.fio_write_document = None\n self.lat_usec = {2: 0.0, 4: 0.0, 10: 0.0, 20: 0.0, 50: 0.0, 100: 0.0, 250: 0.0, 500: 0.0, 750: 0.0, 1000: 0.0}\n self.lat_msec = {2: 0.0, 4: 0.0, 10: 0.0, 20: 0.0, 50: 0.0, 100: 0.0, 250: 0.0, 500: 0.0, 750: 0.0, 1000: 0.0,\n 2000: 0.0,\n 2001: 0.0}\n self.cpu = {'usr': 0.0, 'sys': 0.0, 'ctx': 0.0, 'majf': 0.0, 'minf': 0.0}\n self.io_depths = {1: 0.0, 2: 0.0, 4: 0.0, 8: 0.0, 16: 0.0, 32: 0.0, 64: 0.0, 65: 0.0}\n self.submit = {0: 0.0, 2: 0.0, 4: 0.0, 8: 0.0, 16: 0.0, 32: 0.0, 64: 0.0, 65: 0.0}\n self.complete = {0: 0.0, 2: 0.0, 4: 0.0, 8: 0.0, 16: 0.0, 32: 0.0, 64: 0.0, 65: 0.0}\n self.issued = {'total': 0, 'short': 0, 'drop': 0}\n self.latency = {'target': 0, 'window': 0, 'percentile': 0, 'depth': 0}\n\n def print_all_kv(self):\n print(\"test_parameter\")\n print(self.test_parameter)\n print(\"lat_usec\")\n print(self.lat_usec)\n print(\"lat_msec\")\n print(self.lat_msec)\n print(\"cpu\")\n print(self.cpu)\n print(\"io_depths\")\n print(self.io_depths)\n print(\"submit\")\n print(self.submit)\n print(\"complete\")\n print(self.complete)\n print(\"issued\")\n print(self.issued)\n print(\"latency\")\n print(self.latency)\n","sub_path":"batch/LuspinfAnalysis/fio_document.py","file_name":"fio_document.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"398905415","text":"import numpy as np\r\nimport argparse\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser(description='Screening by trained LBS')\r\n parser.add_argument('--data', type=str, metavar='D', help='data to be screened (required)')\r\n parser.add_argument('--model', type=str, default='lbsmodel', metavar='M', help='filename of the LBS model trained, default is lbsmodel.npz (optional)')\r\n parser.add_argument('--result', type=str, default='ScreenResult', metavar='R', help='filename to keep the result of screening, default is ScreenResult.txt (optional)')\r\n args = parser.parse_args()\r\n if args.result[-4:]!='.txt':\r\n args.result=args.result+'.txt'\r\n if args.model[-4:]!='.npz':\r\n args.model=args.model+'.npz'\r\n model=np.load(args.model)\r\n subset=model['subset']\r\n #print(subset)\r\n center=model['center']\r\n radius=model['radius']\r\n Xtest=np.loadtxt(args.test,delimiter=',',dtype=np.float32)\r\n Xtest=Xtest[:,subset]\r\n if Xtest.ndim>1:\r\n t=np.sum((Xtest-center)**2,axis=1)\r\n else:\r\n t=(Xtest-center)**2\r\n ind=np.where(t<=radius)[0]\r\n print(ind)\r\n with open(args.result,'w+') as f:\r\n for item in ind:\r\n f.write(\"%d, \" % item)\r\n\r\nif __name__=='__main__':\r\n main()\r\n","sub_path":"Machine Learning Data/DML Prediction script (Python).py","file_name":"DML Prediction script (Python).py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"328737893","text":"\"\"\"\nGiven a Binary Search Tree and a target number, \nreturn true if there exist two elements in the BST such that their sum is equal to the given target.\n\n# Solved on 09/10/2019 by William\"\"\"\n\n# BFS\n\nfrom collections import deque\n\ndef findTarget(root, k):\n queue = deque()\n queue.append(root)\n nums = []\n\n while queue:\n Queue = queue.popleft()\n\n if k - Queue.val in nums:\n return True \n nums.append(Queue.val)\n\n if Queue.left:\n queue.append(Queue.left)\n if Queue.right:\n queue.append(Queue.right)\n \n return False","sub_path":"LeetCode/0653.py","file_name":"0653.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"414667206","text":"import os, sys\nimport numpy as np\nfrom easydict import EasyDict as edict\nimport tensorflow as tf\n\n# module\nfrom Utils import _variable_on_cpu, _variable_with_weight_decay\nfrom NN_base.nn_skeleton import Autoencoder\nfrom NN_base.convLSTM import ConvLSTMCell, ConvGRUCell\n\n\nclass VGG16_NAIVE_FS_MR_SegNet(Autoencoder):\n def __init__(self, mc):\n Autoencoder.__init__(self, mc)\n\n # Setup downsample params\n self.down_ksize = 2\n self.down_stride = 2\n \n # ConvLSTM parameters setup\n self.lstm_cell = ConvLSTMCell(512, \\\n k_size=3, \\\n batch_size=self.batch_size, \\\n height=12, \\\n width=15, \\\n initializer=self.conv_init())\n self.state = None\n\n \n def build(self):\n for step in xrange(self.seq_len):\n # reuse flag for network\n lstm_reuse = True if step > 0 else None\n\n # Approx-Encoder\n encoder_out = self._approx_encoder(self.images_node[:, step, ...], \\\n step, lstm_reuse)\n\n # ConvLSTM\n with tf.variable_scope('convLSTM', reuse=lstm_reuse) as scope:\n if step == 0:\n self.state = self.lstm_cell.zero_state(self.batch_size)\n conv_lstm_out, self.state = self.lstm_cell(encoder_out, self.state)\n\n # Decoder\n conv_decode1_1 = self._decoder(conv_lstm_out, reuse=lstm_reuse)\n\n # Classification\n with tf.variable_scope('conv_classifier', reuse=lstm_reuse) as scope:\n logits = self._conv_layer(conv_decode1_1,\n [1, 1, 64, self.n_classes],\n init=self._msra_initializer(1, 64),\n act=False,\n wd=0.0005,\n batch_norm=False,\n name=scope.name)\n\n # Total loss\n self.total_loss += self._loss(logits, self.labels[:, step, ...])\n \n # Logits seq\n self.logits.append(logits)\n\n # Transpose from TNHWC to NTHWC\n self.logits = tf.stack(self.logits)\n self.logits = tf.transpose(self.logits, perm=[1, 0, 2, 3, 4])\n\n\n def _approx_encoder(self, inputT, step, reuse):\n # Preprocess images\n with tf.variable_scope('preprocess', reuse=reuse) as scope:\n # Take HR images first step, \n # and MR images ever since\n if step == 0:\n images = inputT\n else:\n images = self._max_pool(inputT, self.down_ksize, \\\n self.down_stride, name='mr_images')\n\n norm1 = tf.nn.lrn(images, depth_radius=5, bias=1.0, \\\n alpha=0.0001, beta=0.75, name='norm1')\n\n # Encoder\n pool5, _ = self._encoder(norm1, reuse=reuse)\n\n # Upsample MR feature maps if needed\n cond_up_reuse = True if step > 1 else False\n with tf.variable_scope('cond_up', reuse=cond_up_reuse) as scope:\n if step == 0:\n encoder_out = pool5\n else:\n encoder_out = self._deconv_layer(pool5, [2, 2, 512, 512], \\\n [self.batch_size, 12, 15, 512], 2, \\\n \"encoder_up\")\n \n return encoder_out\n\n\n def _encoder(self, inputT, reuse):\n with tf.variable_scope('encoder', reuse=reuse) as scope:\n conv1_1 = self._conv_layer(inputT, [3, 3, 3, 64], name=\"conv1_1\")\n conv1_2 = self._conv_layer(conv1_1, [3, 3, 64, 64], name=\"conv1_2\")\n pool1, pool1_indices = self._max_pool_arg(conv1_2, 2, 2, name='pool1') \n\n conv2_1 = self._conv_layer(pool1, [3, 3, 64, 128], name=\"conv2_1\")\n conv2_2 = self._conv_layer(conv2_1, [3, 3, 128, 128], name=\"conv2_2\")\n pool2, pool2_indices = self._max_pool_arg(conv2_2, 2, 2, name='pool2') \n\n conv3_1 = self._conv_layer(pool2, [3, 3, 128, 256], name=\"conv3_1\")\n conv3_2 = self._conv_layer(conv3_1, [3, 3, 256, 256], name=\"conv3_2\")\n conv3_3 = self._conv_layer(conv3_2, [3, 3, 256, 256], name=\"conv3_3\")\n pool3, pool3_indices = self._max_pool_arg(conv3_3, 2, 2, name='pool3') \n\n conv4_1 = self._conv_layer(pool3, [3, 3, 256, 512], name=\"conv4_1\")\n conv4_2 = self._conv_layer(conv4_1, [3, 3, 512, 512], name=\"conv4_2\")\n conv4_3 = self._conv_layer(conv4_2, [3, 3, 512, 512], name=\"conv4_3\")\n pool4, pool4_indices = self._max_pool_arg(conv4_3, 2, 2, name='pool4') \n\n conv5_1 = self._conv_layer(pool4, [3, 3, 512, 512], name=\"conv5_1\")\n conv5_2 = self._conv_layer(conv5_1, [3, 3, 512, 512], name=\"conv5_2\")\n conv5_3 = self._conv_layer(conv5_2, [3, 3, 512, 512], name=\"conv5_3\")\n pool5, pool5_indices = self._max_pool_arg(conv5_3, 2, 2, name='pool5') \n\n return pool5, pool5_indices\n\n\n def _decoder(self, inputT, reuse):\n with tf.variable_scope('decoder', reuse=reuse) as scope:\n up5 = self._deconv_layer(inputT, [2, 2, 512, 512], [self.batch_size, 23, 30, 512], 2, \"up5\")\n conv_decode5_3 = self._conv_layer(up5, [3, 3, 512, 512], act=False, name=\"conv_decode5_3\")\n conv_decode5_2 = self._conv_layer(conv_decode5_3, [3, 3, 512, 512], act=False, name=\"conv_decode5_2\")\n conv_decode5_1 = self._conv_layer(conv_decode5_2, [3, 3, 512, 512], act=False, name=\"conv_decode5_1\")\n\n up4 = self._deconv_layer(conv_decode5_1, [2, 2, 512, 512], [self.batch_size, 45, 60, 512], 2, \"up4\")\n conv_decode4_3 = self._conv_layer(up4, [3, 3, 512, 512], act=False, name=\"conv_decode4_3\")\n conv_decode4_2 = self._conv_layer(conv_decode4_3, [3, 3, 512, 512], act=False, name=\"conv_decode4_2\")\n conv_decode4_1 = self._conv_layer(conv_decode4_2, [3, 3, 512, 256], act=False, name=\"conv_decode4_1\")\n\n up3 = self._deconv_layer(conv_decode4_1, [2, 2, 256, 256], [self.batch_size, 90, 120, 256], 2, \"up3\")\n conv_decode3_3 = self._conv_layer(up3, [3, 3, 256, 256], act=False, name=\"conv_decode3_3\")\n conv_decode3_2 = self._conv_layer(conv_decode3_3, [3, 3, 256, 256], act=False, name=\"conv_decode3_2\")\n conv_decode3_1 = self._conv_layer(conv_decode3_2, [3, 3, 256, 128], act=False, name=\"conv_decode3_1\")\n\n up2 = self._deconv_layer(conv_decode3_1, [2, 2, 128, 128], [self.batch_size, 180, 240, 128], 2, \"up2\")\n conv_decode2_2 = self._conv_layer(up2, [3, 3, 128, 128], act=False, name=\"conv_decode2_2\")\n conv_decode2_1 = self._conv_layer(conv_decode2_2, [3, 3, 128, 64], act=False, name=\"conv_decode2_1\")\n\n up1 = self._deconv_layer(conv_decode2_1, [2, 2, 64, 64], [self.batch_size, 360, 480, 64], 2, \"up1\")\n conv_decode1_2 = self._conv_layer(up1, [3, 3, 64, 64], act=False, name=\"conv_decode1_2\")\n conv_decode1_1 = self._conv_layer(conv_decode1_2, [3, 3, 64, 64], act=False, name=\"conv_decode1_1\")\n\n return conv_decode1_1\n","sub_path":"Nets/vgg16_naive_fs_mr_segnet.py","file_name":"vgg16_naive_fs_mr_segnet.py","file_ext":"py","file_size_in_byte":6707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"246856039","text":"from ftw.builder import Builder\nfrom ftw.builder import create\nfrom ooxml_docprops import read_properties\nfrom opengever.dossier.docprops import DocPropertyWriter\nfrom opengever.dossier.docprops import TemporaryDocFile\nfrom opengever.journal.handlers import DOC_PROPERTIES_UPDATED\nfrom opengever.journal.tests.utils import get_journal_entry\nfrom opengever.journal.tests.utils import get_journal_length\nfrom opengever.testing import FunctionalTestCase\nfrom plone.app.testing import TEST_USER_ID\n\n\nclass TestDocPropertyWriter(FunctionalTestCase):\n\n expected_user_properties = {\n 'User.ID': TEST_USER_ID,\n 'User.FullName': 'Peter',\n }\n expected_dossier_properties = {\n 'Dossier.ReferenceNumber': 'Client1 / 1',\n 'Dossier.Title': 'My dossier',\n }\n expected_document_properties = {\n 'Document.ReferenceNumber': 'Client1 / 1 / 1',\n 'Document.SequenceNumber': '1',\n }\n\n def setUp(self):\n super(TestDocPropertyWriter, self).setUp()\n self.grant('Manager')\n self.setup_fullname(fullname='Peter')\n self.set_docproperty_export_enabled(True)\n\n self.dossier = create(Builder('dossier').titled(u'My dossier'))\n self.document = create(\n Builder('document')\n .within(self.dossier)\n .titled(\"Document with props\")\n .with_asset_file('with_gever_properties.docx'))\n\n @property\n def writer(self):\n return DocPropertyWriter(self.document)\n\n def tearDown(self):\n self.set_docproperty_export_enabled(False)\n super(TestDocPropertyWriter, self).tearDown()\n\n def test_with_file(self):\n self.assertTrue(self.writer.has_file())\n self.document.file = None\n self.assertFalse(self.writer.has_file())\n\n def test_is_export_enabled(self):\n self.assertTrue(self.writer.is_export_enabled())\n self.set_docproperty_export_enabled(False)\n self.assertFalse(self.writer.is_export_enabled())\n\n def test_is_supported_file(self):\n self.assertTrue(self.writer.is_supported_file())\n self.document.file.contentType = 'text/foo'\n self.assertFalse(self.writer.is_supported_file())\n\n def test_existing_doc_properties_are_updated(self):\n expected_doc_properties = [\n ('User.ID', TEST_USER_ID,),\n ('User.FullName', 'Peter',),\n ('Dossier.ReferenceNumber', 'Client1 / 1'),\n ('Dossier.Title', 'My dossier'),\n ('Document.ReferenceNumber', 'Client1 / 1 / 1'),\n ('Document.SequenceNumber', '1'),\n ]\n\n self.writer.update_doc_properties(only_existing=True)\n with TemporaryDocFile(self.document.file) as tmpfile:\n properties = read_properties(tmpfile.path)\n self.assertItemsEqual(expected_doc_properties, properties)\n\n def test_files_with_custom_properties_are_not_updated(self):\n document = create(\n Builder('document')\n .within(self.dossier)\n .titled(\"Document with custom props\")\n .with_asset_file('with_custom_properties.docx'))\n\n expected_doc_properties = [('Test', 'Peter',)]\n\n writer = DocPropertyWriter(document)\n writer.update_doc_properties(only_existing=True)\n with TemporaryDocFile(document.file) as tmpfile:\n properties = read_properties(tmpfile.path)\n self.assertItemsEqual(expected_doc_properties, properties)\n\n self.assertEqual(1, get_journal_length(document))\n entry = get_journal_entry(document)\n self.assertNotEqual(entry['action']['type'], DOC_PROPERTIES_UPDATED)\n\n def test_properties_can_be_added_to_file_without_properties(self):\n document = create(\n Builder('document')\n .within(self.dossier)\n .titled(\"Document without props\")\n .with_asset_file('without_custom_properties.docx'))\n\n expected_doc_properties = [\n ('User.ID', TEST_USER_ID,),\n ('User.FullName', 'Peter',),\n ('Dossier.ReferenceNumber', 'Client1 / 1'),\n ('Dossier.Title', 'My dossier'),\n ('Document.ReferenceNumber', 'Client1 / 1 / 2'),\n ('Document.SequenceNumber', '2'),\n ]\n\n writer = DocPropertyWriter(document)\n writer.update_doc_properties(only_existing=False)\n with TemporaryDocFile(document.file) as tmpfile:\n properties = read_properties(tmpfile.path)\n self.assertItemsEqual(expected_doc_properties, properties)\n","sub_path":"opengever/dossier/tests/test_docprops.py","file_name":"test_docprops.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"434860458","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport yfinance as yf\n\n\ndef TSMStrategy(returns, period=1, shorts=False):\n \"\"\"returns_: Pandas series\"\"\"\n if shorts:\n position = returns.rolling(period).mean().map(lambda x: -1 if x <= 0 else 1)\n else:\n position = returns.rolling(period).mean().map(lambda x: 0 if x <= 0 else 1)\n\n performance = position.shift(1) * returns\n return performance\n\n\nticker = \"GME\"\nyfObj = yf.Ticker(ticker)\ndata = yfObj.history(start='2010-01-01', end='2020-12-31')\nreturns = np.log(data['Close'] / data['Close'].shift(1)).dropna()\nperf = TSMStrategy(returns)\nyears = (perf.index.max() - perf.index.min()).days / 365\nperf_cum = np.exp(perf.cumsum())\ntot = perf_cum[-1] - 1\nann = perf_cum[-1] ** (1 / years) - 1\nvol = perf.std() * np.sqrt(252)\n# vol2 = perf.dropna().std() * np.sqrt(252)\ntot2 = np.sum(perf) # perf.cumsum()[-1]\nrfr = 0.02\nsharpe = (ann - rfr) / vol\n\nprint(f\"1-day TSM strategy yield:\" +\n f\"\\n\\ttotal returns {tot * 100:.2f}%\" +\n f\"\\n\\tannual returns {ann * 100:.2f}% \" +\n f\"\\n\\tSharpe Ratio {sharpe:.2f} \")\n\nperf_buy_hold_cum = np.exp(returns.cumsum())\ntot_buy_hold = perf_buy_hold_cum[-1] - 1\nann_buy_hold = perf_buy_hold_cum[-1] ** (1 / years) - 1\nvol_buy_hold = returns.std() * np.sqrt(252)\nsharpe_buy_hold = (ann_buy_hold - rfr) / vol_buy_hold\nprint(f\"1-day buy hold strategy yield:\" +\n f\"\\n\\ttotal returns buy hold {tot_buy_hold * 100:.2f}%\" +\n f\"\\n\\tannual returns buy hold {ann_buy_hold * 100:.2f}% \" +\n f\"\\n\\tSharpe Ratio buy hold {sharpe_buy_hold:.2f} \")\n\nperiods = [1, 3, 5, 15, 30, 90]\nfig = plt.figure(figsize=(12, 6)) # plt.figure(가로, 세로)\ngs = fig.add_gridspec(4, 4)\nax0 = fig.add_subplot(gs[:2, :4])\nax1 = fig.add_subplot(gs[2:, :2])\nax2 = fig.add_subplot(gs[2:, 2:])\nax0.plot((np.exp(returns.cumsum()) - 1) * 100, label=ticker, linestyle='-')\nperf_dict = dict()\nperf_dict['tot_ret'] = {'buy_and_hold': np.exp(returns.sum()) - 1}\nperf_dict['ann_ret'] = {'buy_and_hold': ann_buy_hold}\nperf_dict['sharpe'] = {'buy_and_hold': sharpe_buy_hold}\n\nfor p in periods:\n log_perf = TSMStrategy(returns, period=p, shorts=False)\n perf = np.exp(log_perf.cumsum())\n perf_dict['tot_ret'][p] = perf[-1] - 1\n ann = perf[-1] ** (1 / years) - 1\n perf_dict['ann_ret'][p] = ann\n vol = log_perf.std() * np.sqrt(252)\n perf_dict['sharpe'][p] = (ann - rfr) / vol\n ax0.plot((perf - 1) * 100, label=f\"{p}-day mv strategy\")\n\nax0.set_ylabel('Returns(%)')\nax0.set_xlabel('Date')\nax0.set_title('Cumulative returns')\nax0.grid()\nax0.legend()\n\n_ = [ax1.bar(i, v * 100) for i, v in enumerate(perf_dict['ann_ret'].values())]\nax1.set_xticks([i for i, k in enumerate(perf_dict['ann_ret'].values())])\nax1.set_xticklabels([f\"{k}-days MA\" if type(k) is int else ticker for k in perf_dict['ann_ret'].keys()], rotation=45)\nax1.set_xlabel('Strategy')\nax1.set_ylabel('Return(%)')\nax1.set_title('Annualized returns')\n# ax1.legend()\nax1.grid()\n\n_ = [ax2.bar(i, v) for i, v in enumerate(perf_dict['sharpe'].values())]\nax2.set_xticks([i for i, v in enumerate(perf_dict['sharpe'].values())])\nax2.set_xticklabels([f\"{lb}-day MV\" if type(lb) is int else ticker for i, lb in enumerate(perf_dict['sharpe'].keys())],\n rotation=45)\nax2.set_xlabel('Strategy')\nax2.set_ylabel('Returns')\nax2.set_title('Sharpe ratio')\n# ax2.legend()\nax2.grid()\n\nplt.tight_layout()\nplt.show()\n\n# test_returns = pd.Series(np.array([1, 2, 3, 4]))\n# rolling_mean = test_returns.rolling(3).mean()\n# print(rolling_mean)\n\n# aa=data['Close'].fshift(1)\n# test_data = data[:5]\n# test_data2 = data['Close'][:5]\n# test_data2.shift(1)\n# rolling_mean = test_data.rolling(3).mean()\n#\n# sample = lambda x: 0 if x < 0 else 1\n# a = sample('a')\n# print(test_data)\n# position = test_data.rolling(3).mean()\n# position = test_data.rolling(3).mean().map(lambda x: 0 if x <= 0 else 1)\n# print(position)\n#\n# perf = TSMStrategy(test_data, 3)\n# print(perf)\n#\n# # test_rtn=np.log(test_data['Close'])\n# print(test_data['Close'].shift(1))\n# test_returns = np.log(test_data['Close'] / test_data['Close'].shift(1)).dropna()\n# test_data['Close'].shift(1)\n# print(test_returns)\n# # perf = TSMStrategy(test_data, period=3)\n# # print(perf)\n# print(data)\n# print(data['Clse'].head())\n# print(data['Close'].shift(1))\n# print(data['Close'])\n# data['Close'].shift(1)\n# returns = np.log(data['Close'] / data['Close'].shift(1)).dropna()\n# print(f\"returns -> {returns}\")\n# returns = pd.Series(np.array([-1, 2, 3, 4]))\n# perf = TSMStrategy(returns)\n# print(perf)\n# print(f\"perf -> {perf}\")\n\n# x = np.array([-1, 2, 1])\n# df = pd.Series(x)\n# print(df)\n# print(df.shift(1))\n# print(df.shift(1).dropna())\n# print(f\"TSMStrategy(df)\\n{TSMStrategy(df)}\")\n\n# ticker = 'AAPL'\n# msft = yf.Ticker('MSFT')\n# start = '2000-06-02'\n# end = '2016-04-26'\n#\n# AdjClose = yf.download(ticker, start=start, end=end)['Adj Close']\n\n# data = yf.download(\"GME\", start='2020-01-01', end='2020-12-31')\n\n#\n# yfObj = yf.Ticker(ticker)\n# data = yfObj.history(start='2021-01-01', end='2020-12-31')\n\n# print(data)\n# print(data)\n\n# xx = np.array([0.2, -0.4, 0.5])\n# ps = pd.Series(xx)\n# # print(ps)\n# perf = TSMStrategy(ps)\n# print(perf)\n","sub_path":"How To Build Your First Momentum Trading Strategy in Python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439066014","text":"import cv2\r\nimport numpy as np\r\n\r\ndef main():\r\n image = cv2.imread(\"attackoftitans.jpg\")\r\n print(image.shape)\r\n mask = np.zeros(image.shape[:2],np.uint8)\r\n \"\"\"\r\n image ' nin boyutunu içeren bir zeros yani 0 matrix i oluşturduk\r\n image.shape[:2]=resmin boyutu, yüksekliği ve genişliği\r\n \"\"\"\r\n\r\n bglModel = np.zeros((1,65),dtype = np.float64)#BackGroundModel\r\n fglModel = np.zeros((1,65),dtype = np.float64)#FrontGroundModel\r\n\r\n rect = (100,0,700,600)#(x,y,weight(genişlik),height(yükseklik))\r\n\r\n cv2.grabCut(image,mask,rect,bglModel,fglModel,5,cv2.GC_INIT_WITH_RECT)\r\n\r\n mask2 = np.where((mask == 0) | (mask == 2),0,1).astype(np.uint8)\r\n \"\"\"\r\n (0-2) ArkaPlan -> Siyah\r\n (1-3) ÖnPlan -> Beyaz\r\n \"\"\"\r\n\r\n image = image*mask2[:,:,np.newaxis]\r\n\r\n cv2.imshow(\"Image\",image)\r\n\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"ArkaplanFiltreleme.py","file_name":"ArkaplanFiltreleme.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62736407","text":"from uuid import uuid4\nimport datetime\nimport random\nimport string\nfrom picklefield.fields import PickledObjectField\n\nfrom django.db import models\nfrom django.conf import settings\nfrom django.utils import timezone\n\nfrom .signals import (\n payment_process, payment_success, payment_fail, payment_reversed)\n\n\ntry:\n User = settings.AUTH_USER_MODEL\nexcept (ImportError, AttributeError):\n from django.contrib.auth import get_user_model\n User = get_user_model()\n\n\ndef get_uid():\n return ''.join([random.choice(list(string.digits)) for x in range(10)])\n\n\nclass Payment(models.Model):\n class STATUS:\n PROCESSED = 'processed'\n SUCCESS = 'success'\n FAIL = 'fail'\n REVERSED = 'reversed'\n\n CHOICES = (\n (PROCESSED, 'Новый'),\n (SUCCESS, 'Оплачен'),\n (FAIL, 'Отменён'),\n (REVERSED, 'Возвращён'),\n )\n\n class TRTYPE:\n AUTHORIZATION = 0\n RETAIL_FINANCIAL = 1\n SALES_COMPLETION = 21\n REVERSAL = 24\n\n CHOICES = (\n (AUTHORIZATION, 'Authorization'),\n (RETAIL_FINANCIAL, 'Retail Financial'),\n (SALES_COMPLETION, 'Sales Completion'),\n (REVERSAL, 'Reversal'),\n )\n\n class ACTION:\n SUCCESS = 0\n DUPLICATE = 1\n DECLINED = 2\n FAULT = 3\n INFORMATION = 4\n\n CHOICES = (\n (SUCCESS, 'Transaction successfully completed'),\n (DUPLICATE, 'Duplicate transaction detected'),\n (DECLINED, 'Transaction declined'),\n (FAULT, 'Transaction processing fault'),\n (INFORMATION, 'Information message')\n )\n\n user = models.ForeignKey(User, blank=True, null=True,\n related_name='pcb_user',\n verbose_name='Пользователь')\n status = models.CharField('Статус', max_length=16,\n choices=STATUS.CHOICES,\n default=STATUS.PROCESSED)\n order = models.CharField('Номер заказа',\n unique=True, max_length=20,\n default=get_uid)\n amount = models.DecimalField('Сумма',\n max_digits=12, decimal_places=2)\n currency = models.CharField('Валюта',\n max_length=3,\n default=settings.PCB_PAYMENT_CURRENCY)\n description = models.CharField('Назначение платежа',\n max_length=50, null=True)\n terminal = models.CharField('Номер терминала',\n max_length=8,\n default=settings.PCB_PAYMENT_TERMINAL)\n merchant = models.CharField('Номер продавца',\n max_length=15,\n default=settings.PCB_PAYMENT_MERCHANT)\n created = models.DateTimeField('Время создания')\n modified = models.DateTimeField('Время модификации',\n auto_now=True, blank=True, null=True)\n success_url = models.URLField('URL успешной оплаты',\n default=settings.PAYMENT_SUCCESS_URL)\n fail_url = models.URLField('URL неуспешной оплаты',\n default=settings.PAYMENT_FAIL_URL)\n extra_data = PickledObjectField(null=True)\n fail_comment = models.CharField('Причина неудачи',\n max_length=255,\n null=True)\n\n def save(self, *args, **kwargs):\n if not self.id:\n self.created = timezone.now()\n super(Payment, self).save(*args, **kwargs)\n\n @property\n def is_payed(self):\n return getattr(self, 'status', '') == self.STATUS.SUCCESS\n\n def send_signals(self):\n status = self.status\n if status == self.STATUS.PROCESSED:\n payment_process.send(sender=self)\n if status == self.STATUS.SUCCESS:\n payment_success.send(sender=self)\n if status == self.STATUS.FAIL:\n payment_fail.send(sender=self)\n if status == self.STATUS.REVERSED:\n payment_reversed.send(sender=self)\n\n class Meta:\n ordering = ('created',)\n verbose_name = 'Платеж'\n verbose_name_plural = 'Платежи'\n","sub_path":"apps/pcb_payment/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"224879066","text":"def convert_to_mandarin(us_num):\n '''\n us_num, a string representing a US number 0 to 99\n returns the string mandarin representation of us_num\n '''\n # FILL IN YOUR CODE HERE\n trans = {'0':'ling', '1':'yi', '2':'er', '3':'san', '4': 'si',\n '5':'wu', '6':'liu', '7':'qi', '8':'ba', '9':'jiu', '10': 'shi'}\n\n sue = []\n result = []\n us_num2 = int(us_num)\n\n if us_num2 != 0:\n while us_num2 > 0:\n temp = us_num2 % 10\n if temp == 0:\n if us_num2 // 10 != 0 and us_num2 > 20:\n sue.append(10)\n us_num2 = us_num2 //10\n elif us_num2 < 20:\n sue.append(10)\n us_num2 = us_num2 - 10\n else:\n sue.append(0)\n\n else:\n sue.append(temp)\n\n us_num2 = us_num2 - temp\n else:\n sue.append(0)\n\n sue.reverse()\n sol = ''\n for i in sue:\n if str(i) in trans.keys():\n result += trans[str(i)] + ' '\n\n for i in range(len(result)-1):\n sol += result[i]\n\n return sol\n\n\nprint(convert_to_mandarin('33'))\n\n","sub_path":"Final_exams/convToMandarin.py","file_name":"convToMandarin.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"119917416","text":"\nfrom rit_lib import *\n\nclass Pet(struct):\n _slots = ((str,'name'),(int,'age'),(str,'species'))\n\n def birthday(self):\n self.age += 1\n print(\"Happy Birthday,\", self.name,\"!\")\n\n\ndef createPet(name, spec):\n return Pet(name,0,spec)\n\np = createPet(\"Chip\",\"dog\")\nprint(p)\np.birthday()\nprint(p)\n\nprint(p.name)","sub_path":"Computer Science 1/Miscellaneous/problem5.py","file_name":"problem5.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"378186116","text":"'''\nProblem 206\n\nFind the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0,\nwhere each “_” is a single digit.\n'''\n\nimport time\n\nimport math\n\ndef concealed_square():\n\tlower_bound = math.floor(1020304050607080900 ** 0.5)\n\tupper_bound = math.ceil(1929394959697989900 ** 0.5)\n\n\tcandidate = lower_bound - lower_bound % 100\n\twhile candidate <= upper_bound:\n\t\tfor addend in [30, 40]:\n\t\t\tcandidate += addend\n\t\t\tsquare = str(candidate ** 2)\n\t\t\tfound = True\n\t\t\tfor i in range(10):\n\t\t\t\tif int(square[2*i]) != (i + 1) % 10:\n\t\t\t\t\tfound = False\n\t\t\t\t\tbreak\n\t\t\tif found:\n\t\t\t\treturn candidate\n\t\tcandidate += 30\n\nif __name__ == '__main__':\n\n\tstart = time.time()\n\tprint(concealed_square())\n\tend = time.time()\n\n\tprint(\"Execution time: %fs\" %(end - start))\n","sub_path":"solutions/concealed_square.py","file_name":"concealed_square.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"274533642","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name=\"index\"),\n url(r'^login$', views.login_handler, name=\"login\"),\n url(r'^register$', views.register_handler, name=\"register\"),\n url(r'^logout$', views.logout, name=\"logout\"),\n\n url(r'^activation-needed$', views.email_validation_wait, name=\"activation-needed\"),\n url(r'^activate/(?P[0-9A-Za-z_\\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate_email, name=\"activate-email\"),\n\n url(r'^finish-setup$', views.finish_user_setup, name=\"finish-setup\")\n]\n","sub_path":"session/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"238442199","text":"from django import forms\nfrom aspc.coursesearch.models import (Department, Course, Meeting,\n RequirementArea, CAMPUSES, CAMPUSES_FULL_NAMES, CAMPUSES_LOOKUP)\nfrom django.db.models import Count, F\n\nimport re\nfrom itertools import groupby\nfrom django.forms.widgets import Widget, Select\nfrom django.forms.models import ModelChoiceIterator\nfrom django.utils.safestring import mark_safe\n\ndef requirement_area_label(campus_value):\n return CAMPUSES_FULL_NAMES[campus_value]\n\nclass GroupedModelChoiceField(forms.ModelChoiceField):\n def __init__(self, group_by_field, group_label=None, *args, **kwargs):\n \"\"\"\n group_by_field is the name of a field on the model\n group_label is a function to return a label for each choice group\n \"\"\"\n super(GroupedModelChoiceField, self).__init__(*args, **kwargs)\n self.group_by_field = group_by_field\n if group_label is None:\n self.group_label = lambda group: group\n else:\n self.group_label = group_label\n \n def _get_choices(self):\n \"\"\"\n Exactly as per ModelChoiceField except returns new iterator class\n \"\"\"\n if hasattr(self, '_choices'):\n return self._choices\n return GroupedModelChoiceIterator(self)\n choices = property(_get_choices, forms.ModelChoiceField._set_choices)\n \n def label_from_instance(self, obj):\n campus_code = CAMPUSES[obj.campus - 1][1]\n reqarea_name = re.sub(campus_code + r'\\s+?', '', obj.name)\n return reqarea_name\n\nclass GroupedModelChoiceIterator(ModelChoiceIterator):\n def __iter__(self):\n if self.field.empty_label is not None:\n yield (u\"\", self.field.empty_label)\n if self.field.cache_choices:\n if self.field.choice_cache is None:\n self.field.choice_cache = [\n (self.field.group_label(group), [self.choice(ch) for ch in choices])\n for group,choices in groupby(self.queryset.all(),\n key=lambda row: getattr(row, self.field.group_by_field))\n ]\n for choice in self.field.choice_cache:\n yield choice\n else:\n for group, choices in groupby(self.queryset.all(),\n key=lambda row: getattr(row, self.field.group_by_field)):\n yield (self.field.group_label(group), [self.choice(ch) for ch in choices])\n\nclass DeptModelChoice(forms.ModelChoiceField):\n def label_from_instance(self, obj):\n return \"%s - %s\" % (obj.code, obj.name)\n\nTIME_INPUT_FORMATS = [\n '%H:%M:%S',\n '%H:%M',\n '%I:%M%p',\n '%I:%M %p',\n]\n\nPOSSIBLE_CREDIT = (('A', 'any'), ('F', 'full'), ('P', 'partial'), (0.0, '0.0'), (0.25, '0.25'), (0.5, '0.5'), (1.0, '1.0'), (1.5, '1.5'), (2.0, '2.0'), (3.0, '3.0'), (4.0, '4.0'), (6.0, '6.0'))\n\nkeyword_regex = re.compile(r'(\\w+)')\n\nclass SearchForm(forms.Form):\n department = DeptModelChoice(queryset=Department.objects.annotate(\n num_courses=Count('course_set')).\\\n filter(num_courses__gt=0).distinct().order_by('code'),\n required=False, empty_label=\"(any)\"\n )\n requirement_area = GroupedModelChoiceField(\n 'campus',\n group_label=requirement_area_label,\n queryset=RequirementArea.objects.annotate(num_courses=Count('course_set')).\\\n filter(num_courses__gt=0).distinct().order_by('code'),\n required=False, empty_label=\"(no particular)\"\n )\n only_at_least = forms.ChoiceField(choices=(('A', 'at least'), ('O', 'only'),))\n m = forms.BooleanField(required=False)\n t = forms.BooleanField(required=False)\n w = forms.BooleanField(required=False)\n r = forms.BooleanField(required=False)\n f = forms.BooleanField(required=False)\n \n instructor = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'size':'40'}))\n spots_left = forms.BooleanField(required=False, initial=True)\n course_number_min = forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'4'}))\n course_number_max = forms.IntegerField(required=False, widget=forms.TextInput(attrs={'size':'4'}))\n credit = forms.ChoiceField(choices=POSSIBLE_CREDIT)\n \n start_range = forms.TimeField(required=False, input_formats=TIME_INPUT_FORMATS, widget=forms.TextInput(attrs={'size':'10'})) #widget=SelectTimeWidget(twelve_hr=True, use_seconds=False))\n end_range = forms.TimeField(required=False, input_formats=TIME_INPUT_FORMATS, widget=forms.TextInput(attrs={'size':'10'})) #widget=SelectTimeWidget(twelve_hr=True, use_seconds=False))\n \n c_cgu = forms.BooleanField(required=False)\n c_cm = forms.BooleanField(required=False)\n c_ks = forms.BooleanField(required=False)\n c_hm = forms.BooleanField(required=False)\n c_po = forms.BooleanField(required=False)\n c_pz = forms.BooleanField(required=False)\n c_sc = forms.BooleanField(required=False)\n \n keywords = forms.CharField(max_length=100, required=False)\n \n def clean(self):\n cleaned_data = self.cleaned_data\n if self._errors:\n return cleaned_data # user has to fix field errors first\n if not any(map(cleaned_data.get, ('m', 't', 'w', 'r', 'f', 'instructor',\n 'start_range', 'end_range', 'c_cgu', 'c_cm', 'c_ks', 'c_hm', 'c_po', 'c_pz', 'c_sc',\n 'department', 'requirement_area', 'keywords'))):\n raise forms.ValidationError(\"You must specify at least one constraint.\")\n return cleaned_data\n \n def build_queryset(self):\n qs = Course.objects.all()\n if self.cleaned_data.get('department'):\n qs = qs.filter(departments=self.cleaned_data['department'])\n \n if self.cleaned_data.get('requirement_area'):\n qs = qs.filter(requirement_areas=self.cleaned_data['requirement_area'])\n \n if self.cleaned_data.get('only_at_least') == 'O':\n \n m = Meeting.objects.filter(monday=True)\n if self.cleaned_data.get('m', False):\n qs = qs.filter(meeting__in=m)\n else:\n qs = qs.exclude(meeting__in=m)\n \n t = Meeting.objects.filter(tuesday=True)\n if self.cleaned_data.get('t', False):\n qs = qs.filter(meeting__in=t)\n else:\n qs = qs.exclude(meeting__in=t)\n \n \n w = Meeting.objects.filter(wednesday=True)\n if self.cleaned_data.get('w', False):\n qs = qs.filter(meeting__in=w)\n else:\n qs = qs.exclude(meeting__in=w)\n \n r = Meeting.objects.filter(thursday=True)\n if self.cleaned_data.get('r', False):\n qs = qs.filter(meeting__in=r)\n else:\n qs = qs.exclude(meeting__in=r)\n \n f = Meeting.objects.filter(friday=True)\n if self.cleaned_data.get('f', False):\n qs = qs.filter(meeting__in=f)\n else:\n qs = qs.exclude(meeting__in=f)\n \n if self.cleaned_data.get('start_range'):\n qs = qs.filter(meeting__in=Meeting.objects.filter(begin__gte=self.cleaned_data['start_range']))\n if self.cleaned_data.get('end_range'):\n qs = qs.filter(meeting__in=Meeting.objects.filter(end__lte=self.cleaned_data['end_range']))\n \n elif self.cleaned_data.get('only_at_least') == 'A':\n if self.cleaned_data.get('m') == True: qs = qs.filter(meeting__monday=self.cleaned_data['m'])\n if self.cleaned_data.get('t') == True: qs = qs.filter(meeting__tuesday=self.cleaned_data['t'])\n if self.cleaned_data.get('w') == True: qs = qs.filter(meeting__wednesday=self.cleaned_data['w'])\n if self.cleaned_data.get('r') == True: qs = qs.filter(meeting__thursday=self.cleaned_data['r'])\n if self.cleaned_data.get('f') == True: qs = qs.filter(meeting__friday=self.cleaned_data['f'])\n if self.cleaned_data.get('start_range'):\n qs = qs.filter(meeting__begin__gte=self.cleaned_data['start_range'])\n if self.cleaned_data.get('end_range'):\n qs = qs.filter(meeting__end__lte=self.cleaned_data['end_range'])\n \n \n campus_ids = []\n if self.cleaned_data.get('c_cgu'): campus_ids.append(CAMPUSES_LOOKUP['CGU'])\n if self.cleaned_data.get('c_cm'): campus_ids.append(CAMPUSES_LOOKUP['CMC'])\n if self.cleaned_data.get('c_ks'): campus_ids.append(CAMPUSES_LOOKUP['KS'])\n if self.cleaned_data.get('c_hm'): campus_ids.append(CAMPUSES_LOOKUP['HM'])\n if self.cleaned_data.get('c_po'): campus_ids.append(CAMPUSES_LOOKUP['PO'])\n if self.cleaned_data.get('c_pz'): campus_ids.append(CAMPUSES_LOOKUP['PZ'])\n if self.cleaned_data.get('c_sc'): campus_ids.append(CAMPUSES_LOOKUP['SC'])\n \n if campus_ids:\n qs = qs.filter(meeting__campus__in=campus_ids)\n \n if self.cleaned_data.get('course_number_min'):\n qs = qs.filter(number__gte=self.cleaned_data.get('course_number_min'))\n \n if self.cleaned_data.get('course_number_max'):\n qs = qs.filter(number__lte=self.cleaned_data.get('course_number_max'))\n \n \n if self.cleaned_data.get('instructor'):\n qs = qs.filter(instructor__icontains=self.cleaned_data['instructor'])\n if self.cleaned_data.get('credit'):\n if self.cleaned_data['credit'] == 'A':\n pass\n elif self.cleaned_data['credit'] == 'F':\n qs = qs.filter(credit__gte=1.0)\n elif self.cleaned_data['credit'] == 'P':\n qs = qs.filter(credit__lt=1.0, credit__gt=0.0)\n else:\n qs = qs.filter(credit=self.cleaned_data['credit'])\n \n if self.cleaned_data.get('spots_left'):\n qs = qs.exclude(spots=F('filled'))\n \n if self.cleaned_data.get('keywords'):\n keywords = [a.lower() for a in keyword_regex.findall(self.cleaned_data['keywords'])]\n qs_descfilter = qs\n qs_namefilter = qs\n for kw in keywords:\n qs_descfilter = qs_descfilter.filter(description__icontains=kw)\n qs_namefilter = qs_namefilter.filter(name__icontains=kw)\n qs = (qs_descfilter or qs_namefilter)\n qs = qs.distinct()\n \n qs = qs.distinct().order_by('code')\n return qs\n\nclass ScheduleForm(forms.Form):\n key = forms.CharField(max_length=100)\n\nclass ICalExportForm(forms.Form):\n start = forms.DateField(label=\"First day of classes\")\n end = forms.DateField(label=\"Last day of classes\")\n\n def clean_end(self):\n if not (self.cleaned_data.get('start') and self.cleaned_data.get('end')):\n raise forms.ValidationError(\"You must specify both start and end dates\")\n start, end = self.cleaned_data['start'], self.cleaned_data['end']\n if end > start:\n return end\n else:\n raise forms.ValidationError(\"The last day of the semester \"\n \"must be after the first day of classes.\")\n","sub_path":"aspc/coursesearch/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":11186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"500627670","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 18 16:52:43 2018\r\n\r\n@author: rm_an\r\n\"\"\"\r\nfrom Graph import *\r\nclass dfsGraph(Graph):\r\n \r\n def __init__(self):\r\n super().__init__()\r\n self.time = 0\r\n \r\n def dfs(self):\r\n for ver in self:\r\n ver.setColor('white')\r\n ver.setPred(None)\r\n self.time = 0\r\n \r\n for ver in self:\r\n if ver.getColor() == 'white':\r\n self.dfsVisit(ver)\r\n \r\n def dfsOofFinish(self, sortedKeys):\r\n for ver in self:\r\n ver.setColor('white')\r\n ver.setPred(None)\r\n self.time = 0\r\n \r\n sortedVer = [self.getVertex(key) for key in sortedKeys]\r\n \r\n for ver in sortedVer:\r\n if ver.getColor() == 'white':\r\n self.dfsVisit(ver)\r\n return sortedKeys\r\n \r\n \r\n def dfsVisit(self, ver):\r\n self.time += 1\r\n ver.setDiscovery(self.time)\r\n ver.setColor('gray')\r\n for nbr in ver.getConnections():\r\n if nbr.getColor() == 'white':\r\n nbr.setPred(ver)\r\n self.dfsVisit(nbr)\r\n ver.setColor('black')\r\n self.time += 1\r\n ver.setFinish(self.time)\r\n \r\n def orderOfFinish(self):\r\n sortedKeys = []\r\n for ver in self:\r\n sortedKeys.append((ver.getFinish(),ver.getId()))\r\n sortedKeys.sort(key=lambda x: x[0], reverse=True)\r\n return [key[1] for key in sortedKeys]\r\n \r\n def printPaths(self, sortedkeys):\r\n sortedkeys.reverse()\r\n sortedVer=[self.getVertex(key) for key in sortedkeys]\r\n \r\n for ver in sortedVer:\r\n if ver.getColor() == 'black':\r\n print (self.getPath(ver))\r\n \r\n def getPath(self, ver):\r\n path = []\r\n currentVer= ver\r\n currentVer.setColor('white')\r\n path.append(currentVer.getId())\r\n while currentVer.getPred():\r\n path.append(currentVer.getPred().getId())\r\n currentVer = currentVer.getPred()\r\n currentVer.setColor('white')\r\n for otherVer in self:\r\n if otherVer.getColor() == 'black' and otherVer.getPred():\r\n if otherVer.getPred().getId() in path:\r\n path.append(otherVer.getId())\r\n otherVer.setColor('white')\r\n return path\r\n \r\n def transpose(self):\r\n Gtranspose = dfsGraph()\r\n for ver in self.getVertices():\r\n nbrs = list(self.getVertex(ver).getConnections())\r\n for nbr in nbrs:\r\n Gtranspose.addEdge(nbr.getId(), ver)\r\n return Gtranspose\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n ","sub_path":"DepthFirstSearch.py","file_name":"DepthFirstSearch.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"278611259","text":"# coding=utf-8\nfrom selenium import webdriver\nimport unittest\nimport time\n\nclass MyTest(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Chrome()\n self.driver.maximize_window()\n self.driver.implicitly_wait(10)\n self.base_url = \"http://www.youdao.com \"\n\n def test_youdao(self):\n driver=self.driver\n driver.get(self.base_url+'/')\n driver.find_element_by_xpath(\"//input[@id='translateContent']\").clear()\n driver.find_element_by_id(\"translateContent\").send_keys(\"webdriver\")\n driver.find_element_by_name(\"q\").click()\n time.sleep(2)\n title=driver.title\n self.assertEqual(title,u'有道首页')\n\n def tearDown(self):\n # self.driver.quit()\n self.driver.close()\nif __name__==\"__main__\":\n unittest.main()","sub_path":"testyoudao.py","file_name":"testyoudao.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"610552145","text":"from util.eval.bleu import *\nfrom util.eval.cider import *\nfrom util.eval.cosine import *\nfrom util.eval.rouge import *\nfrom util.metrics.dist import csim_np\nfrom loaders.dictionary import id2sent, reorder_sents\n\n\ndef get_reward(pred_sents=None, targ_sents=None, method=None,\n pred_inds=None, targ_inds=None, embs=None,\n lengths=None, model=None, n = 2, alpha = 0.5,\n bsize=256, dist='cosine', mean=True):\n\n \"\"\"don't confuse model methods with decoder, they are just evaluators\"\"\"\n if method == 'cosine' or method == 'cos':\n return torch_cos_sim(pred_sents, targ_sents, embs)\n elif method == 'bleu':\n return convert2bleu(pred_sents, targ_sents, lengths)\n elif method == 'wmd':\n return sum([model.wmd(p_sent, t_sent) for (p_sent, t_sent) in zip(pred_sents, targ_sents)])/len(pred_sents)\n elif method in ['infersent', 'uniskip', 'biskip', 'bert', 'elmo',\n 'gpt', 'gpt2', 'transformer', 'transformerxl'] and model is not None:\n\n # try:\n # except:\n # print(targ_sents)\n # ValueError(\"This batch caused problems CUDA error: unspecified launch failure\")\n\n if method == 'infersent':\n pred_embs = model.encode(pred_sents, bsize)\n targ_embs = model.encode(targ_sents, bsize)\n elif method == 'uniskip' or method == 'biskip':\n pred_embs = model(pred_inds)\n targ_embs = model(targ_inds)\n\n if type(pred_embs) == torch.Tensor:\n pred_embs = F.normalize(pred_embs, p=2, dim=1)\n targ_embs = F.normalize(targ_embs, p=2, dim=1)\n if dist == 'cosine':\n sim = F.cosine_similarity(pred_embs, targ_embs)\n elif dist == 'euclidean':\n y_norm = torch.norm(pred_embs - targ_embs, 2, dim=1)\n sim = 1/(1+y_norm)\n elif dist == 'manhattan':\n y_norm = torch.norm(pred_embs - targ_embs, 1, dim=1)\n sim = 1/(1+y_norm)\n return sim.mean() if mean else sim\n\n elif type(pred_embs) == np.ndarray:\n sim = csim_np(pred_embs, targ_embs)\n if mean: sim = np.mean(sim)\n print(sim)\n print()\n return sim\n elif method == 'meta':\n model()\n elif method == 'rouge':\n return rouge_n(targ_sents, pred_sents, n, alpha)\n elif method == 'cider':\n return get_cider(pred_sents ,targ_sents, lengths)\n elif method == 'meteor':\n pass\n\n\ndef get_task_score(words, labels, args, pre_emb=None, vocab=None, sent_mod=None):\n\n if args.critic_reward == 'rouge':\n policy_values = rouge_l(words, labels)\n\n elif args.critic_reward == 'bleu':\n words_c, labels_c = words.cpu().numpy(), labels.cpu().numpy()\n policy_values = get_bleu(words_c, labels_c, seq_len=4, bleu_len=2)\n policy_values = torch.Tensor([policy_values]).cuda()\n\n elif args.critic_reward == 'cider':\n policy_values = get_reward()\n\n elif args.critic_reward == 'wmd':\n if type(words) == torch.Tensor:\n words = words.cpu().numpy()\n if type(labels) == torch.Tensor:\n labels = labels.cpu().numpy()\n pred_sents = reorder_sents([id2sent(vocab, words[:, i]) for i in range(words.shape[1])])\n targ_sents = reorder_sents([id2sent(vocab, labels[:, i]) for i in range(labels.shape[1])])\n # print(targ_sents)\n policy_values = torch.from_numpy(np.asarray([1 - pre_emb.wmdistance(pred_sent, targ_sent) for\n (pred_sent, targ_sent) in\n zip(pred_sents, targ_sents)])).cuda()\n # print(policy_values)\n # print(\"policy values shape {}\".format(policy_values.size()))\n elif args.critic_reward == 'cosine' or args.critic_reward == 'cos':\n policy_values = torch_cos_sim(words, labels, vocab.id2vec, mean=False)\n elif args.critic_reward in ['infersent', 'bert', 'elmo', 'gpt', 'gpt2', 'transformer', 'transformerxl']:\n pred_sents = reorder_sents([id2sent(vocab, words[:, i]) for i in range(words.shape[1])])\n targ_sents = reorder_sents([id2sent(vocab, labels[:, i]) for i in range(labels.shape[1])])\n policy_values = get_reward(pred_sents, targ_sents, method=args.critic_reward, model=sent_mod,\n bsize=args.batch_size, dist=args.reward_dist, mean=False)\n policy_values = np.asarray(policy_values, dtype=np.float32)\n\n elif args.critic_reward in ['uniskip', 'biskip']:\n policy_values = get_reward(pred_inds=words, targ_inds=labels, method=args.critic_reward, model=sent_mod,\n bsize=args.batch_size, dist=args.reward_dist, mean=False)\n else:\n policy_values = rouge_l(words, labels)\n return policy_values\n\n\nif __name__ == \"__main__\":\n words = torch.randint(1, 5, (80, 24)).type(torch.LongTensor)\n labels = torch.randint(1, 5, (80, 24)).type(torch.LongTensor)\n\n print(rouge_l(words, labels))","sub_path":"util/eval/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"472498485","text":"# coding=utf-8\nimport functools\nimport numba\nimport numpy as np\nfrom scipy import fftpack as fft\n\n\ndef PoissonLongitudinalSolver(rho, k, NG, epsilon_0=1, neutralize=True):\n \"\"\"solves the Poisson equation spectrally, via FFT\n\n the Poisson equation can be written either as\n (in position space)\n $$\\nabla \\cdot E = \\rho/\\epsilon_0$$\n $$\\nabla^2 V = -\\rho/\\epsilon_0$$\n\n Assuming that all functions in fourier space can be represented as\n $$\\exp{i(kx - \\omega t)}$$\n It is easy to see that upon Fourier transformation $\\nabla \\to ik$, so\n\n (in fourier space)\n $$E = \\rho /(ik \\epsilon_0)$$\n $$V = \\rho / (-k^2 \\epsilon_0)$$\n\n Calculate that, fourier transform back to position space\n and both the field and potential pop out easily\n\n The conceptually problematic part is getting the $k$ wave vector right\n # DOCUMENTATION: finish this description\n \"\"\"\n\n rho_F = fft.fft(rho) # OPTIMIZE check if it's possible to use rfft here\n if neutralize:\n rho_F[0] = 0\n field_F = rho_F / (1j * k * epsilon_0)\n # potential_F = field_F / (-1j * k * epsilon_0)\n field = fft.ifft(field_F).real\n return field\n\n\n@numba.njit()\ndef BunemanTransversalSolver(electric_field, magnetic_field, current_yz, dt, c, epsilon_0):\n # dt = dx/c\n Fplus = 0.5 * (electric_field[:, 0] + c * magnetic_field[:, 1])\n Fminus = 0.5 * (electric_field[:, 0] - c * magnetic_field[:, 1])\n Gplus = 0.5 * (electric_field[:, 1] + c * magnetic_field[:, 0])\n Gminus = 0.5 * (electric_field[:, 1] - c * magnetic_field[:, 0])\n\n Fplus[1:] = Fplus[:-1] - 0.5 * dt * (current_yz[2:-1, 0]) / epsilon_0\n Fminus[:-1] = Fminus[1:] - 0.5 * dt * (current_yz[1:-2, 0]) / epsilon_0\n Gplus[1:] = Gplus[:-1] - 0.5 * dt * (current_yz[2:-1, 1]) / epsilon_0\n Gminus[:-1] = Gminus[1:] - 0.5 * dt * (current_yz[1:-2, 1]) / epsilon_0\n\n new_electric_field = np.zeros_like(electric_field)\n new_magnetic_field = np.zeros_like(magnetic_field)\n\n new_electric_field[:, 0] = Fplus + Fminus\n new_electric_field[:, 1] = Gplus + Gminus\n new_magnetic_field[:, 0] = (Gplus - Gminus) / c\n new_magnetic_field[:, 1] = (Fplus - Fminus) / c\n\n return new_electric_field, new_magnetic_field\n\n@numba.njit()\ndef BunemanLongitudinalSolver(electric_field, current_x, dt, epsilon_0):\n return electric_field - dt / epsilon_0 * current_x[:-1]\n\nclass Solver:\n def __init__(self, solve_algorithm, initialiation_algorithm):\n self.solve = solve_algorithm\n self.init_solver = initialiation_algorithm\n\n\ndef solve_fourier(grid, neutralize = False):\n grid.electric_field[1:-1, 0] = PoissonLongitudinalSolver(\n grid.charge_density[:-1], grid.k, grid.NG, epsilon_0=grid.epsilon_0, neutralize=neutralize\n )\n\n grid.electric_field[:, 1:], grid.magnetic_field[:, 1:] = BunemanTransversalSolver(grid.electric_field[:, 1:],\n grid.magnetic_field[:, 1:],\n grid.current_density_yz, grid.dt,\n grid.c, grid.epsilon_0)\n return None\n\n\nsolve_fourier_neutral = functools.partial(solve_fourier, neutralize=True)\n\n\ndef solve_buneman(grid):\n grid.electric_field[:, 0] = BunemanLongitudinalSolver(grid.electric_field[:, 0],\n grid.current_density_x,\n grid.dt,\n grid.epsilon_0,\n )\n grid.electric_field[:, 1:], grid.magnetic_field[:, 1:] = BunemanTransversalSolver(grid.electric_field[:, 1:],\n grid.magnetic_field[:, 1:],\n grid.current_density_yz, grid.dt,\n grid.c, grid.epsilon_0)\n return None\n\n\nFourierSolver = Solver(solve_fourier_neutral, solve_fourier_neutral)\nBunemanSolver = Solver(solve_buneman, solve_fourier)\n\n","sub_path":"pythonpic/algorithms/FieldSolver.py","file_name":"FieldSolver.py","file_ext":"py","file_size_in_byte":4299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"180372112","text":"from django.http import JsonResponse\nfrom django.views.generic import View\nfrom django.views.generic.detail import SingleObjectMixin\nfrom django.views.generic.edit import FormMixin\n\nfrom .forms import AttachmentForm\n\n\nclass FileUploadView(FormMixin, SingleObjectMixin, View):\n form_class = AttachmentForm\n\n def post(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n\n files = []\n\n if form.is_valid():\n for file in request.FILES.getlist('files'):\n attachment = self.get_object()\n\n attachment.file = file\n attachment.name = file.name\n attachment.save(**kwargs)\n\n files.append({\n \"pk\": attachment.pk,\n \"name\": file.name,\n \"size\": file.size,\n \"url\": attachment.file.url\n })\n\n data = {\"files\": files}\n\n return JsonResponse(data)\n else:\n return JsonResponse({\n 'status': 'false',\n 'message': 'Bad Request'\n }, status=400)\n","sub_path":"django_summernote_ajax/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"177898460","text":"import requests\nimport time\nimport telegram\nimport os\nimport logging\nfrom dotenv import load_dotenv\n\n\ndef request_devman_api(bot, logger, devman_token, telegram_id, server_max_timeout):\n url = 'https://dvmn.org/api/long_polling/'\n headers = {\n 'Authorization': 'Token ' + devman_token,\n }\n params = {}\n while True:\n try:\n response = requests.get(url, headers=headers, params=params, timeout=server_max_timeout)\n response.raise_for_status()\n json_data = response.json()\n if json_data['status'] == 'found':\n attempts = json_data['new_attempts']\n for attempt in attempts:\n if attempt['is_negative']:\n bot.send_message(chat_id=telegram_id,\n text=f\"У вас проверили работу {attempt['lesson_title']} \\n\"\n f\"https://dvmn.org{attempt['lesson_url']}\\n\"\n f\"В работе нашлись ошибки\")\n else:\n bot.send_message(chat_id=telegram_id,\n text=f\"У вас проверили работу {attempt['lesson_title']} \\n\"\n f\"https://dvmn.org{attempt['lesson_url']}\\n\"\n f\"В работе нет ошибок\")\n params = {\n 'timestamp': json_data['last_attempt_timestamp']\n }\n else:\n params = {\n 'timestamp': json_data['timestamp_to_request']\n }\n except requests.exceptions.ReadTimeout as err:\n logger.critical(err, exc_info=True)\n except requests.exceptions.ConnectionError as err:\n logger.error(err, exc_info=True)\n time.sleep(1)\n except ConnectionResetError as err:\n logger.error(err, exc_info=True)\n time.sleep(1)\n except requests.exceptions.HTTPError as err:\n logger.error(err, exc_info=True)\n time.sleep(360)\n\n\ndef main():\n load_dotenv()\n devman_token = os.environ['DEVMAN_TOKEN']\n telegram_token = os.environ['TELEGRAM_TOKEN']\n telegram_id = int(os.environ['TELEGRAM_ID'])\n server_max_timeout = int(os.environ['SERVER_MAX_TIMEOUT'])\n bot = telegram.Bot(token=telegram_token)\n\n class MyLogsHandler(logging.Handler):\n\n def emit(self, record):\n log_entry = self.format(record)\n bot.send_message(chat_id=telegram_id, text=log_entry)\n\n logger = logging.getLogger(\"MyLogsHandler\")\n logger.setLevel(logging.ERROR)\n logger.addHandler(MyLogsHandler())\n logger.info(\"Бот запущен!\")\n request_devman_api(bot, logger, devman_token, telegram_id, server_max_timeout)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"516713438","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 3 00:47:47 2021\n\n@author: danyuribe\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys, os\n\nFILE_NAMES = []\nTITLE = \"H_FMR Summary Before and After Anneal\"\nXLABEL = \"f (GHZ)\"\nYLABEL = \"$H_{FMR} (Oe)$\"\n\ndef DataFinder(path, extension):\n extensions = [\".dat\", \".txt\", \".csv\"]\n \n if not extension in extensions:\n print(\"Cannot reada data from this file type.\\n\")\n else:\n for root, dirs, files in os.walk(path):\n for filename in files:\n filename = str(filename)\n if filename.endswith(extension):\n if \"HFMR\" in filename:\n FILE_NAMES.append(filename)\n\ndef main():\n path = os.path.abspath(__file__)\n dir_path = os.path.dirname(path)\n \n DataFinder(dir_path, \".dat\")\n \n fill_value = 0\n conv= {i: lambda s: float(s.strip() or fill_value) for i in range(3)}\n \n for file in FILE_NAMES:\n \n x, y, error = np.genfromtxt(file, dtype=\"f8\", converters=conv, skip_header=1, unpack=True)\n #plt.error(x, y, error, fmt='o', ecolor='lightgray', elinewidth=3, capsize=0)\n m, b = np.polyfit(x, y, 1)\n \n file_label = (\"Before: \" + \"{:.2f}\".format(m) + \"x + \" + \"{:.2f}\".format(b)) if (\"Before\" in file) else (\"After: \" + \"{:.2}\".format(m) + \"x + \" + \"{:.2}\".format(b)) \n file_color =\"b\" if (\"Before\" in file) else \"orange\"\n \n plt.plot(x,y,'o',color=file_color, label=file_label)\n plt.plot(x, m*x + b, file_color)\n \n plt.title(TITLE)\n plt.xlabel(XLABEL)\n plt.ylabel(YLABEL)\n plt.legend()\n plt.show()\n \nif __name__ == \"__main__\":\n main()","sub_path":"HFMR_SumPlot.py","file_name":"HFMR_SumPlot.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"100612101","text":"import pytest\nfrom owslib.wmts import WebMapTileService\nfrom owslib.util import ServiceException\nfrom urllib import request\nfrom lxml import etree\n\ndef get_xsd(name):\n # since this function is only being called by getcapabilities set to wmts/1.0.0\n # the exception schema is available from http://schemas.opengis.net/ows/1.1.0/\n xsd_f = request.urlopen(\"http://schemas.opengis.net/wmts/1.0/\" + name)\n schema_doc = etree.parse(xsd_f)\n return etree.XMLSchema(schema_doc)\n\n\ndef check_wmts_error(url, expected_error_message=None, expected_status_code=400):\n try:\n resp = request.urlopen(url, timeout=10)\n\n # Should not get here\n assert False\n except Exception as e:\n # Validate status code\n assert e.getcode() == expected_status_code\n\n resp_content = e.fp.read()\n assert expected_error_message in str(resp_content)\n resp_xml = etree.XML(resp_content)\n assert resp_xml is not None\n\n\ndef test_no_request(ows_server):\n # Make empty request to server:\n check_wmts_error(ows_server.url + \"/wmts\", \"No operation specified\", 400)\n\n\ndef test_invalid_operation(ows_server):\n # Make invalid operation request to server:\n check_wmts_error(ows_server.url + \"/wmts?request=NoSuchOperation\", \"Unrecognised operation: NOSUCHOPERATION\", 400)\n\n\ndef test_getcap_badsvc(ows_server):\n # Make bad service request to server:\n check_wmts_error(ows_server.url + \"/wmts?request=GetCapabilities&service=NotWMTS\", \"Invalid service\", 400)\n\n\n@pytest.mark.xfail(reason=\"OWS Getcaps don't pass XSD\")\ndef test_wmts_getcap(ows_server):\n resp = request.urlopen(ows_server.url + \"/wmts?request=GetCapabilities&service=WMTS&version=1.0.0\", timeout=10)\n\n # Confirm success\n assert resp.code == 200\n\n # Validate XML Schema\n resp_xml = etree.parse(resp.fp)\n gc_xds = get_xsd(\"wmtsGetCapabilities_response.xsd\")\n assert gc_xds.validate(resp_xml)\n\n\ndef test_wmts_getcap_section(ows_server):\n section_options = ['all', 'serviceidentification', 'serviceprovider', 'operationsmetadata', 'contents', 'themes']\n for section in section_options:\n resp = request.urlopen(ows_server.url + \"/wmts?request=GetCapabilities&service=WMTS&version=1.0.0§ion={}\".format(\n section\n ), timeout=10)\n\n # Confirm success\n assert resp.code == 200\n\n\ndef test_wmts_server(ows_server):\n # Use owslib to confirm that we have a somewhat compliant WCS service\n wmts = WebMapTileService(url=ows_server.url+\"/wmts\")\n\n assert wmts.identification.type == \"OGC WMTS\"\n assert wmts.identification.version == \"1.0.0\"\n\n # Ensure that we have at least some layers available\n contents = list(wmts.contents)\n assert contents\n\n\ndef test_wmts_gettile(ows_server):\n wmts = WebMapTileService(url=ows_server.url+\"/wmts\")\n\n contents = list(wmts.contents)\n test_layer_name = contents[0]\n\n tile = wmts.gettile(\n layer=test_layer_name,\n tilematrixset='WholeWorld_WebMercator',\n tilematrix='0',\n row=0, column=0,\n format=\"image/png\"\n )\n\n assert tile\n assert tile.info()['Content-Type'] == 'image/png'\n\ndef test_wmts_gettile_wkss(ows_server):\n wmts = WebMapTileService(url=ows_server.url+\"/wmts\")\n\n contents = list(wmts.contents)\n test_layer_name = contents[0]\n\n tile = wmts.gettile(\n layer=test_layer_name,\n tilematrixset=\"urn:ogc:def:wkss:OGC:1.0:GoogleMapsCompatible\",\n tilematrix='0',\n row=0, column=0,\n format=\"image/png\"\n )\n\n assert tile\n assert tile.info()['Content-Type'] == 'image/png'\n\ndef test_wmts_gettile_exception(ows_server):\n wmts = WebMapTileService(url=ows_server.url+\"/wmts\")\n\n contents = list(wmts.contents)\n test_layer_name = contents[0]\n try:\n # supplying an unsupported tilematrixset\n wmts.gettile(\n layer=test_layer_name,\n tilematrixset='WholeWorld_WebMercatorxxx',\n tilematrix='0',\n row=0, column=0,\n format=\"image/png\"\n )\n except ServiceException as e:\n assert 'Invalid Tile Matrix Set:' in str(e)\n else:\n assert False","sub_path":"integration_tests/test_wmts_server.py","file_name":"test_wmts_server.py","file_ext":"py","file_size_in_byte":4160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"218904019","text":"import json\nimport logging\nimport os\nimport sys\nfrom collections import OrderedDict\n\nfrom tqdm.autonotebook import tqdm\n\nLOG_MSG = \"LOG\"\nTQDM_MSG = \"TQDM\"\n\n\nclass TqdmHandler(logging.StreamHandler):\n \"\"\"\n Handler that synchronizes the log output with the\n :class:`~tqdm.tqdm` progress bar.\n \"\"\"\n def emit(self, record):\n try:\n msg = self.format(record)\n self.flush()\n tqdm.write(msg, file=sys.stderr)\n except (KeyboardInterrupt, SystemExit) as e:\n raise e\n except Exception:\n self.handleError(record)\n\n\nclass MCMCLoggingHandler(logging.Handler):\n \"\"\"\n Main logging handler used by :class:`~pyro.infer.mcmc`,\n to handle both progress bar updates and regular `logging`\n messages.\n\n :param log_handler: default log handler for logging\n output.\n :param progress_bar: If provided, diagnostic information\n is updated using the bar.\n \"\"\"\n def __init__(self, log_handler, progress_bar=None):\n logging.Handler.__init__(self)\n self.log_handler = log_handler\n self.progress_bar = progress_bar\n\n def emit(self, record):\n try:\n if self.progress_bar and record.msg_type == TQDM_MSG:\n diagnostics = json.loads(record.getMessage(),\n object_pairs_hook=OrderedDict)\n self.progress_bar.set_postfix(diagnostics)\n self.progress_bar.update()\n else:\n self.log_handler.handle(record)\n except (KeyboardInterrupt, SystemExit) as e:\n raise e\n except Exception:\n self.handleError(record)\n\n\nclass MetadataFilter(logging.Filter):\n \"\"\"\n Adds auxiliary information to log records, like `chain_id` and\n `msg_type`.\n \"\"\"\n def __init__(self, chain_id):\n self.chain_id = chain_id\n super(MetadataFilter, self).__init__()\n\n def filter(self, record):\n record.chain_id = self.chain_id\n if not getattr(record, \"msg_type\", None):\n record.msg_type = LOG_MSG\n return True\n\n\ndef initialize_progbar(warmup_steps, num_samples, min_width=100, max_width=120, pos=None):\n \"\"\"\n Initialize progress bar using :class:`~tqdm.tqdm`.\n\n :param int warmup_steps: Number of warmup steps.\n :param int num_samples: Number of MCMC samples.\n :param int min_width: Minimum column width of the bar.\n :param int max_width: Maximum column width of the bar.\n :param int pos: Position of the bar (e.g. in the case of\n multiple parallel samplers).\n \"\"\"\n description = \"Warmup\" if pos is None else \"Warmup [{}]\".format(pos)\n total_steps = warmup_steps + num_samples\n # Disable progress bar in \"CI\"\n # (see https://github.com/travis-ci/travis-ci/issues/1337).\n disable = \"CI\" in os.environ\n progress_bar = tqdm(total=total_steps, desc=description,\n position=pos, file=sys.stderr, disable=disable)\n\n if getattr(progress_bar, \"ncols\", None) is not None:\n progress_bar.ncols = min(min_width, progress_bar.ncols)\n progress_bar.ncols = max(max_width, progress_bar.ncols)\n return progress_bar\n\n\ndef initialize_logger(logger, chain_id, progress_bar=None):\n \"\"\"\n Initialize logger for the :class:`pyro.infer.mcmc` module.\n\n :param logger: logger instance.\n :param int chain_id: `id` of the sampler, in case of\n multiple samplers.\n :param progress_bar: a :class:`tqdm.tqdm` instance.\n \"\"\"\n # Reset handler with new `progress_bar`.\n logger.handlers = []\n logger.propagate = False\n handler = TqdmHandler()\n logging_handler = MCMCLoggingHandler(handler, progress_bar)\n logging_handler.addFilter(MetadataFilter(chain_id))\n logger.addHandler(logging_handler)\n return logger\n","sub_path":"pyro/infer/mcmc/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"58247323","text":"import unittest\nimport numpy as np\nfrom smt.applications.mixed_integer import (\n MixedIntegerContext,\n FLOAT,\n ENUM,\n INT,\n check_xspec_consistency,\n)\nfrom smt.problems import Sphere\nfrom smt.sampling_methods import LHS\nfrom smt.surrogate_models import KRG\n\n\nclass TestMixedInteger(unittest.TestCase):\n def test_check_xspec_consistency(self):\n xtypes = [FLOAT, (ENUM, 3), INT]\n xlimits = [[-10, 10], [\"blue\", \"red\", \"green\"]] # Bad dimension\n with self.assertRaises(ValueError):\n check_xspec_consistency(xtypes, xlimits)\n\n xtypes = [FLOAT, (ENUM, 3), INT]\n xlimits = [[-10, 10], [\"blue\", \"red\"], [-10, 10]] # Bad enum\n with self.assertRaises(ValueError):\n check_xspec_consistency(xtypes, xlimits)\n\n def test_krg_mixed_5D(self):\n xtypes = [FLOAT, (ENUM, 3), INT]\n xlimits = [[-10, 10], [\"blue\", \"red\", \"green\"], [-10, 10]]\n mixint = MixedIntegerContext(xtypes, xlimits)\n\n sm = mixint.build_surrogate(KRG(print_prediction=False))\n sampling = mixint.build_sampling_method(LHS, criterion=\"m\")\n\n fun = Sphere(ndim=5)\n xt = sampling(20)\n yt = fun(xt)\n sm.set_training_values(xt, yt)\n sm.train()\n\n x_out = mixint.fold_with_enum_indexes(xt)\n eq_check = True\n for i in range(x_out.shape[0]):\n if abs(float(x_out[i, :][2]) - int(float(x_out[i, :][2]))) > 10e-8:\n eq_check = False\n if not (x_out[i, :][1] == 0 or x_out[i, :][1] == 1 or x_out[i, :][1] == 2):\n eq_check = False\n self.assertTrue(eq_check)\n\n def test_mixed_integer_lhs(self):\n import numpy as np\n from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import\n import matplotlib.pyplot as plt\n\n from smt.sampling_methods import LHS\n from smt.applications.mixed_integer import (\n FLOAT,\n INT,\n ENUM,\n MixedIntegerSamplingMethod,\n )\n\n xtypes = [(ENUM, 2), FLOAT]\n xlimits = [[\"blue\", \"red\"], [0.0, 4.0]]\n sampling = MixedIntegerSamplingMethod(xtypes, xlimits, LHS, criterion=\"ese\")\n\n num = 40\n x = sampling(num)\n\n print(x.shape)\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection=\"3d\")\n ax.scatter(x[:, 0], x[:, 1], x[:, 2], \"o\")\n ax.set_xlabel(\"x0 blue (1) or not (0)\")\n ax.set_ylabel(\"x1 red (1) or not (0)\")\n ax.set_zlabel(\"x2 float\")\n plt.show()\n\n def test_mixed_integer_qp(self):\n import numpy as np\n import matplotlib.pyplot as plt\n\n from smt.surrogate_models import QP\n from smt.applications.mixed_integer import MixedIntegerSurrogate, INT\n\n xt = np.array([0.0, 1.0, 2.0, 3.0, 4.0])\n yt = np.array([0.0, 1.0, 1.5, 0.5, 1.0])\n\n # xtypes = [FLOAT, INT, (ENUM, 3), (ENUM, 2)]\n # FLOAT means x1 continuous\n # INT means x2 integer\n # (ENUM, 3) means x3, x4 & x5 are 3 levels of the same categorical variable\n # (ENUM, 2) means x6 & x7 are 2 levels of the same categorical variable\n\n sm = MixedIntegerSurrogate(xtypes=[INT], xlimits=[[0, 4]], surrogate=QP())\n sm.set_training_values(xt, yt)\n sm.train()\n\n num = 100\n x = np.linspace(0.0, 4.0, num)\n y = sm.predict_values(x)\n\n plt.plot(xt, yt, \"o\")\n plt.plot(x, y)\n plt.xlabel(\"x\")\n plt.ylabel(\"y\")\n plt.legend([\"Training data\", \"Prediction\"])\n plt.show()\n","sub_path":"smt/applications/tests/test_mixed_integer.py","file_name":"test_mixed_integer.py","file_ext":"py","file_size_in_byte":3549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"375337966","text":"#!/usr/bin/env python\n# demodata.py\n\nfrom urlparse import urljoin\n\nimport SOAPpy\n\nfrom config.properties import get_properties\nfrom config.models import MCProperty\nfrom users.models import User\nfrom groups.models import Group, Practice, Practiceccrevent, Groupadmin, \\\n delete_group\n\nfrom utils import sql_execute, default_context\n\nfrom django.db import transaction\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\n\n\n#\t First name\tLast name Email\n#\t ----------\t--------- -----\n#\t\tCurrent CCR\n#\t\tReason\n#\t\t[CCR List]\nPATIENTS = [('Jane', 'Hernandez', 'jhernandez@medcommons.net',\n\t\t\"3ea6d35fa4c9d81352b0b3266562e58b878aa6e1\",\n\t\t'3D Imaging Consult', []),\n\n\t ('Jim', 'Jones', 'jjones@medcommons.net', None, '', []),\n\n\t ('Jane', 'Bewell', 'jbewell@medcommons.net',\n\t\t\"83244f558bbd74021fe9b13da9cad52840fc3ace\",\n\t\t'Update for Diabetes Checkup',\n\t\t[\"f198a83583d6a6428e74acd34592efaff7c59abd\"]),\n\n\t ('Stella', 'Paterson', 'spaterson@medcommons.net',\n\t\t\"d5af8707f5ab103a6f31c3a48e44f9dc89c5bb26\",\n\t\t'For the patient', []),\n]\n\nACCOUNT_RLS_SQL = \"\"\"\nINSERT INTO account_rls (ar_accid, ar_rls_url)\nVALUES (%s, %s)\n\"\"\"\n\nDOCUMENT_TYPE_SQL = \"\"\"\nINSERT INTO document_type (dt_id, dt_account_id, dt_type, dt_tracking_number,\n\t\t\t dt_privacy_level, dt_guid, dt_create_date_time,\n\t\t\t dt_comment)\nVALUES (NULL, %s, 'CURRENTCCR', '', 'Private', %s, CURRENT_TIMESTAMP,\n\t'Demo Current CCR')\n\"\"\"\n\t\t\nCCRLOG_SQL = \"\"\"\nINSERT INTO ccrlog (id, accid, idp, guid, status, date, src, dest,\n\t\t subject, einfo, tracking, merge_status)\nVALUES (NULL, %s, 'idp', %s, 'Complete', {ts '2005-11-01 18:24:18.000'},\n\t'UNKNOWN', '', %s, NULL, %s, NULL)\n\"\"\"\n\nTODIR_SQL = \"\"\"\nINSERT INTO todir (groupid, xid, alias, contactlist, sharedgroup,\n\t\t pinstate, accid)\nVALUES (%s, '', %s, %s, 0, 0, %s)\n\"\"\"\n\nURL = 'http://mcid.internal:1080/mcid'\nNS = 'http://www.medcommons.net/locals'\n\nmcid_generator = SOAPpy.SOAPProxy('http://mcid.internal:1080/mcid',\n\t\t\t\t namespace = NS)\n\ntn_generator = SOAPpy.SOAPProxy('http://mcid.internal:1080/tracking_number',\n\t\t\t\tnamespace = NS)\n\ndef index_req(request):\n\tproperties = get_properties()\n\n\tcontext = default_context(request)\n\n\tif 'DemoDoctor' in properties:\n\t\tpatients = []\n\t\tfor first_name, last_name, email, ccr, reason, ccrs in PATIENTS:\n\t\t\tpatients += User.objects.filter(first_name = first_name,\n\t\t\t\t\t\t\tlast_name = last_name,\n\t\t\t\t\t\t\temail = email)\n\n\t\tcontext['mcid'] = properties['DemoDoctor']\n\t\tcontext['doctor'] = User.objects.get(mcid = context['mcid'])\n\t\tcontext['patients'] = patients\n\n\treturn render_to_response('demos/index.html', context)\n\ndef create_req(request):\n\tif 'create' in request.POST:\n\t\tproperties = get_properties()\n\t\tif 'Site' in properties:\n\t\t\turl_root = properties['Site']\n\t\telse:\n\t\t\turl_root = request.META['SERVER_NAME']\n\n\t\tcreate_data(url_root)\n\n\treturn HttpResponseRedirect('.')\n\ndef delete_req(request):\n\tif 'delete' in request.POST:\n\t\tdelete_data()\n\n\treturn HttpResponseRedirect('.')\n\ndef create_data(url_root):\n\tgateway = urljoin(url_root, 'router/')\n\n\ttransaction.enter_transaction_management()\n\n\tdoctor = User()\n\tdoctor.mcid = mcid_generator.next_mcid()\n\tdoctor.first_name = 'Demo'\n\tdoctor.last_name = 'Doctor'\n\tdoctor.email = 'demodoctor@medcommons.net'\n\tdoctor.updatetime = 0\n\tdoctor.ccrlogupdatetime = 0\n\tdoctor.save()\n\n\tphysician = User()\n\tphysician.mcid = mcid_generator.next_mcid()\n\tphysician.first_name = 'Demo'\n\tphysician.last_name = 'Physician'\n\tphysician.email = 'demophysician@medcommons.net'\n\tphysician.updatetime = 0\n\tphysician.ccrlogupdatetime = 0\n\tphysician.save()\n\n\tg, p = create_group('Demo Group Worklist',\n\t\t\t 'group-demodoctor@medcommons.net', url_root,\n\t\t\t doctor.mcid)\n\n\tadd_to_group(g, physician.mcid)\n\n\tpatients = []\n\tfor first_name, last_name, email, currentccr, reason, ccrs in PATIENTS:\n\t\tuser = User()\n\t\tuser.first_name = first_name\n\t\tuser.last_name = last_name\n\t\tuser.email = email\n\t\tuser.mcid = mcid_generator.next_mcid()\n\t\tuser.acctype = 'USER'\n\t\tuser.rolehack = 'ccrlhm'\n\t\tuser.updatetime = 0\n\t\tuser.ccrlogupdatetime = 0\n\t\tuser.save()\n\n\t\tpatients.append(user)\n\n\t\t# Set worklist\n\t\tsql_execute(ACCOUNT_RLS_SQL, user.mcid, p.practiceRlsUrl)\n\n\t\tif not currentccr:\n\t\t\tcontinue\n\n\t\tsql_execute(DOCUMENT_TYPE_SQL, user.mcid, currentccr)\n\n\t\tev = Practiceccrevent()\n\t\tev.practiceid = p\n\t\tev.PatientGivenName = user.first_name\n\t\tev.PatientFamilyName = user.last_name\n\t\tev.PatientIdentifier = user.mcid\n\t\tev.PatientIdentifierSource = 'Patient Medcommons ID'\n\t\tev.Guid = currentccr\n\t\tev.Purpose = reason\n\t\tev.SenderProviderId = 'idp'\n\t\tev.ReceiverProviderId = 'idp'\n\t\tev.DOB = '16 Jan 1968 05:00:00 GMT'\n\t\tev.CXPServerURL = ''\n\t\tev.CXPServerVendor = 'Medcommons'\n\t\tev.ViewerURL = urljoin(gateway, 'access?g=%s' % currentccr)\n\t\tev.Comment = '\\n 3D Imaging Consult\\n '\n\t\tev.CreationDateTime = 1162365858\n\t\tev.ConfirmationCode = tn_generator.next_tracking_number()\n\t\tev.RegistrySecret = ''\n\t\tev.PatientSex = 'Female'\n\t\tev.PatientAge = ''\n\t\tev.Status = 'New'\n\t\tev.ViewStatus = 'Visible'\n\t\tev.save()\n\n\t\tsql_execute(CCRLOG_SQL, user.mcid, currentccr, 'CCR',\n\t\t\t ev.ConfirmationCode)\n\n\t\tfor ccr in ccrs:\n\t\t\tsql_execute(CCRLOG_SQL, user.mcid, ccr, 'CCR',\n\t\t\t\t tn_generator.next_tracking_number())\n\n\tsql_execute(TODIR_SQL, g.groupinstanceid, doctor.email,\n\t\t doctor.email, doctor.mcid)\n\n\tsql_execute(TODIR_SQL, g.groupinstanceid, physician.email,\n\t\t physician.email, physician.mcid)\n\n\tdemoCCR = 'fdfbbb9cf53f8577b420ed72567cd2104589fb0d'\n\n\tsql_execute(CCRLOG_SQL, doctor.mcid, demoCCR, 'DICOM Import',\n\t\t tn_generator.next_tracking_number())\n\n\tsql_execute(CCRLOG_SQL, patients[0].mcid, demoCCR, 'DICOM Import',\n\t\t tn_generator.next_tracking_number())\n\n\tsql_execute(CCRLOG_SQL, patients[0].mcid, PATIENTS[0][3],\n\t\t 'DICOM Import',\n\t\t tn_generator.next_tracking_number())\n\n\n\t# Secondary group\n\tif 0:\n\t\tg2, p2 = create_group('Healthy Doctors',\n\t\t\t\t 'group2-demodoctor@medcommons.net',\n\t\t\t\t url_root, doctor.mcid)\n\n\tp = MCProperty()\n\tp.property = 'acDemoDoctor'\n\tp.value = doctor.mcid\n\tp.save()\n\n\ttransaction.leave_transaction_management()\n\ndef delete_data():\n\tproperties = get_properties()\n\n\tdelete_user(properties['DemoDoctor'])\n\n\tfor first_name, last_name, email, ccr, reason, ccrs in PATIENTS:\n\t\tusers = User.objects.filter(first_name = first_name,\n\t\t\t\t\t last_name = last_name,\n\t\t\t\t\t email = email)\n\n\t\tfor user in users:\n\t\t\tdelete_user(user.mcid)\n\n\tsql_execute(\"DELETE FROM mcproperties WHERE property='acDemoDoctor'\")\n\ndef delete_user(mcid):\n\tfor ga in Groupadmin.objects.filter(adminaccid = mcid):\n\t\tg = Group.objects.get(groupinstanceid = ga.groupinstanceid)\n\n\t\tdelete_group(g)\n\t\tga.delete()\n\n\tsql_execute(\"DELETE FROM ccrlog WHERE accid = %s\", mcid)\n\tsql_execute(\"DELETE FROM todir WHERE accid = %s\", mcid)\n\tsql_execute(\"DELETE FROM groupmembers WHERE memberaccid = %s\", mcid)\n\tsql_execute(\"DELETE FROM document_type WHERE dt_account_id = %s\", mcid)\n\tsql_execute(\"DELETE FROM users WHERE mcid = %s\", mcid)\n\ndef create_group(name, email, url_root, owner):\n\t\"\"\"\n\t_name_\t\tName of group\n\t_email_\t\tEmail address for group (?)\n\t_url_root_\tacSite\n\t_owner_\t\tMCID of user/doctor that controls this group\n\t\"\"\"\n\tu = User()\n\tu.mcid = mcid_generator.next_mcid()\n\tu.email = email\n\tu.set_password(str(u.mcid))\n\tu.first_name = name\n\tu.last_name = 'Group'\n\tu.rolehack = 'rls'\n\tu.acctype = 'GROUP'\n\tu.updatetime = 0\n\tu.ccrlogupdatetime = 0\n\tu.save()\n\n\tg = Group()\n\tg.grouptypeid = 0\n\tg.name = name\n\tg.accid_id = u.mcid\n\tg.save()\n\t\n\tp = Practice()\n\tp.providergroupid = g\n\tp.practicename = name\n\tp.accid_id = u.mcid\n\tp.save()\n\n\tp.practiceRlsUrl = urljoin(url_root,\n\t\t\t\t 'acct/ws/R.php?pid=%d' % p.practiceid)\n\tp.save()\n\n\tg.parentid = p.practiceid\n\tg.save()\n\n\tga = Groupadmin()\n\tga.groupinstanceid = g.groupinstanceid\n\tga.adminaccid = owner\n\tga.save()\n\n\tadd_to_group(g, owner)\n\n\treturn g, p\n\ndef add_to_group(g, mcid):\n\tsql_execute(\"\"\"INSERT INTO groupmembers (groupinstanceid, memberaccid)\n\t\t\tVALUES (%s, %s)\"\"\", g.groupinstanceid, mcid)\n\n#\n# $rightsResult = file_get_contents($GLOBALS['Commons_Url'].\"/demodata.php\");\n# if($rightsResult==false) {\n# err(\"Unable to grant rights for $janesEmail to access current ccr $demoCcrGuid\");\n# }\n#\n# $gwResetURL = gpath('Default_Repository').\"/ResetDemoData.action\";\n# $gwResult = file_get_contents($gwResetURL);\n# if($gwResult==false) {\n# err(\"Unable to reset demo data on gateawy using \".$gwResetURL);\n# }\n","sub_path":"console/demos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"97602071","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2015, Universal Resource Trading Limited and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe, os, shutil #, nltk \nfrom frappe.model.document import Document\nfrom datetime import date, timedelta\n\nimport xml.etree.cElementTree as ET\nimport requests\n#import mechanize\n\nIS_TESTING = False\nNO_IMAGES = True\n\n\n#Save to public directory so one can download\ngarage_xml_path = '/home/frappe/frappe-bench/sites/site1.local/public/files/xml/'\nif(IS_TESTING): garage_xml_path = '/home/frappe/frappe-bench/sites/erpnext.vm/public/files/xml/'\n\n\nsite_files_path= '/home/frappe/frappe-bench/sites/site1.local/public/files/'\nif(IS_TESTING): site_files_path= '/home/frappe/frappe-bench/sites/erpnext.vm/public/files/'\n\n\nimages_url = 'http://www.universalresourcetrading.com'\n\n\n\n@frappe.whitelist()\ndef run_cron_create_xml(garagesale_export_date):\n \n #added to apps/frappe/frappe/hooks.py: @TODO CRON DOES NOT WORK\n frappe.msgprint(\"Exporting all listings created on/after: \" + garagesale_export_date)\n \n if garagesale_export_date ==\"\": \n today = date.today()\n export_date = today.isoformat()\n else:\n export_date = garagesale_export_date\n \n export_to_garage_sale_xml(export_date)\n \n \n return\n\n\n\n\ndef export_to_garage_sale_xml(creation_date):\n post_code = \"NP4 0HZ\"\n design = \"Pro: Classic\"\n layout = \"thumb gallery\"\n decline = 0.9\n accept = 0.1\n duration = 1000 # GTC = 1000\n handling_time = 1\n\n \n root = ET.Element(\"items\")\n\n records = get_item_records_by_creation(creation_date)\n\n for r in records:\n if r.brand: title = r.brand + \" \"\n else: title = \"\"\n title += r.item_name\n item_code = r.name\n category = lookup_category(r.item_group)\n \n price = r.price\n quantity = r.actual_qty\n \n #image = r.image\n ws_image = r.website_image\n ss_images_list = get_slideshow_records(r.slideshow)\n \n \n pounds, ounces = kg_to_imperial(r.net_weight)\n \n body = \"
\"\n body += \"The price includes VAT and we can provide VAT invoices.\"\n body += \"

\"\n if r.function_grade == \"0\": body += \"Free 45-day return policy if you are unhappy with your purchase for any reason.\"\n if r.function_grade == \"1\" or r.function_grade == \"2\": body += \"Product Guarantee: We guarantee this product will work properly or your money back with our free 45-day return policy.\"\n if r.function_grade == \"3\": body += \"Product Guarantee: Whilst we haven't tested every function of this item, we guarantee it will work properly or your money back with our free 45-day return policy.\"\n if r.function_grade == \"4\": body += \"Product Guarantee: Whilst we haven't tested this item, we guarantee it will work properly or your money back with our free 45-day return policy.\"\n if r.function_grade == \"5\": body += \"Product Guarantee: This item is sold as spares/repairs only. It may require servicing or repair. However, we still offer our free 45-day return policy if you are unhappy with your purchase for any reason.\"\n body += \"

\"\n \n body += r.description\n \n body += \"

Accessories / Extras

NOTE: No cables, remotes, accessories, power supplies, consumables or any other item is included unless shown in the item photo or is in the item description

\"\n\n if r.accessories_extras or r.power_cable_included or r.power_supply_included or r.remote_control_included or r.case_included:\n #s = \"

Also included in the sale:

\"\n if r.power_cable_included: body += \"
  • Power cable
  • \"\n if r.power_supply_included: body += \"
  • Power supply/transformer
  • \"\n if r.remote_control_included: body += \"
  • Remote Control
  • \"\n if r.case_included: body += \"
  • Case
  • \"\n if r.accessories_extras: body += \"
  • \" + r.accessories_extras + \"
  • \"\n\n body += \"

    Grade

    The item has been graded as shown in bold below:

    \"\n body += grade(r.condition, r.function_grade)\n if r.grade_details: body += \"

    The item has \" + first_lower(r.grade_details)\n \n if r.tech_details: body += \"

    Specifications

    \" + r.tech_details\n body += \"sku: \" + r.item_code\n body += \"]]\"\n \n \n #if r.warranty: body += \"XX day warranty on this item\"\n \n \n if(not price):\n price = 0.0 \n #TODO Probably better writing this to a LOG file and not exporting it?\n \n #quantity = 1\n if(not quantity):\n quantity = 1\n # or break ?? \n \n doc = ET.SubElement(root, \"item\")\n\n ET.SubElement(doc, \"bestOffer\").text = \"true\"\n #ET.SubElement(doc, \"bestOfferAutoAcceptPrice\").text = str(price - (price * accept))\n #ET.SubElement(doc, \"bestOfferAutoDeclinePrice\").text = str(price - (price * decline)) \n ET.SubElement(doc, \"buyItNowPrice\").text = str(price)\n ET.SubElement(doc, \"category\").text = category \n #ET.SubElement(doc, \"category2\").text =\n ET.SubElement(doc, \"condition\").text = lookup_condition(r.condition, r.function_grade)\n ET.SubElement(doc, \"conditionDescription\").text = r.grade_details\n ET.SubElement(doc, \"convertDescriptionToHTML\").text = \"true\"\n ET.SubElement(doc, \"convertMarkdownToHTML\").text = \"true\"\n ET.SubElement(doc, \"description\").text = body\n ET.SubElement(doc, \"design\").text = design\n #dom_ship = ET.SubElement(doc, \"domesticShippingService\").text =\n #dom_ship.set(\"serviceAdditionalFee\", \"0\")\n #dom_ship.set(\"serviceFee\", \"0\")\n ET.SubElement(doc, \"duration\").text = str(duration)\n ET.SubElement(doc, \"handlingTime\").text = str(handling_time) \n\n\n #for ssi in ss_images_list:\n #if exists(images_url + ssi.image):\n #if ssi.image: \n #if URL_IMAGES: \n #ET.SubElement(doc, \"imageURL\").text = images_url + ssi.image\n \n #else:\n # throw('Problem with image' + ssi.image)\n\n # IF there is no slideshow then try the ws_image\n #if(!ssi):\n # if (r.website_image != 'NULL'):\n # ET.SubElement(doc, \"imageURL\").text = images_url + ws_image\n \n #int_ship = ET.SubElement(doc, \"internationalShippingService\").text = \"\"\n #int_ship.set(\"serviceAdditionalFee\", \"0\")\n #int_ship.set(\"serviceFee\",\"0\") \n\n ET.SubElement(doc, \"layout\").text = layout\n #ET.SubElement(doc, \"lotSize\").text = \"1\"\n if r.height: ET.SubElement(doc, \"packageDepth\").text = str(r.height)\n if r.length: ET.SubElement(doc, \"packageLength\").text = str(r.length)\n ET.SubElement(doc, \"packageOunces\").text = str(ounces)\n ET.SubElement(doc, \"packagePounds\").text = str(pounds)\n if r.width: ET.SubElement(doc, \"packageWidth\").text = str(r.width)\n #ET.SubElement(doc, \"paymentInstructions\").text = \"\"\n ET.SubElement(doc, \"privateAuction\").text = \"false\"\n ET.SubElement(doc, \"quantity\").text = str(quantity)\n #ET.SubElement(doc, \"reservePrice\").text = \"\"\n #ET.SubElement(doc, \"siteName\").text = \"\"\n ET.SubElement(doc, \"SKU\").text = item_code\n #ET.SubElement(doc, \"startingBid\").text = \"\"\n #ET.SubElement(doc, ****storCaterogry).text = \"\"\n #ET.SubElement(doc, \"subTitle\").text = sub_title\n ET.SubElement(doc, \"title\").text = title\n #ET.SubElement(doc, \"variation\").text = \"\"\n ET.SubElement(doc, \"zipCode\").text = post_code\n \n \n tree = ET.ElementTree(root)\n today = date.today()\n tree.write(garage_xml_path + creation_date + \"_garageimportfile.xml\")\n\n \n\n return\n\n\ndef grade(cond, func):\n\n\n c0 = \"\"\n f0 = \"Not Applicable\"\n c1 = 'New. Boxed in original packaging.'\n f1 = 'Tested. Working. Reconditioned.'\n c2 = 'New or as new. Not in original packaging.'\n f2 = 'Tested. Working.'\n c3 = 'Minor cosmetic damage. Otherwise excellent condition.'\n f3 = 'Powers up but not tested further.'\n c4 = 'Good condition. Some signs of use. Possible limited damage e.g. dents or scratches'\n f4 = 'Untested'\n c5 = 'Heavy use. Scratches, often heavy, or blemishes.'\n f5 = 'Not working - for spares or repair'\n\n grade = ''\n\n if cond and func:\n grade += ''\n \n grade += ''\n\n\n grade += ''\n grade += ''\n if cond == '0': grade += '' %(c0) \n else: grade += ''\n if func == '0': grade += '' %f0 \n else: grade += ''\n\n grade += ''\n\n\n grade += ''\n grade += ''\n if cond == '1': grade += '' %(c1) \n else: grade += '' %c1\n if func == '1': grade += '' %f1 \n else: grade += '' %f1\n\n grade += ''\n\n grade += ''\n grade += ''\n if cond == '2': grade += '' %c2 \n else: grade += '' %c2\n if func == '2': grade += '' %f2 \n else: grade += '' %f2\n grade += ''\n\n grade += ''\n grade += ''\n if cond == '3': grade += '' %c3 \n else: grade += '' %c3\n if func == '3': grade += '' %f3 \n else: grade += '' %f3\n grade += ''\n\n grade += ''\n grade += ''\n if cond == '4': grade += '' %c4 \n else: grade += '' %c4\n if func == '4': grade += '' %f4 \n else: grade += '' %f4\n grade += ''\n\n grade += ''\n grade += ''\n if cond == '5': grade += '' %c5 \n else: grade += '' %c5\n if func == '5': grade += '' %f5 \n else: grade += '' %f5\n grade += ''\n\n grade += '
    GradeConditionFunction
    %s %s' + f0 + '
    1 %s %s%s%s
    2%s%s%s%s
    3%s%s%s%s
    4%s%s%s%s
    5%s%s%s%s
    '\n\n return grade\n\n\ndef lookup_condition(con_db, func_db):\n # options: New, New other, Manufacturer refurbished, Seller refurbished, Used, For parts or not working\n \n condition = \"Used\"\n\n if con_db == \"1\":\n condition = \"New\"\n if con_db == \"2\":\n condition = \"New\"\n if con_db == \"3\":\n condition = \"Used\"\n if con_db == \"4\":\n condition = \"Used\"\n if con_db == \"5\":\n condition = \"Used\"\n \n if func_db == \"5\":\n condition = \"For parts or not working\"\n\n return condition\n\n\ndef lookup_category(cat_db):\n \n val = 0\n\n if cat_db:\n val = frappe.get_value(\"Item Group\", str(cat_db), \"ebay_category_code\")\n\n\n return val\n\n\n\ndef rid_html(txt):\n\n return txt\n \n \n \n\ndef get_item_records_by_item(item_code):\n \n entries = frappe.db.sql(\"\"\"select\n\n where it.name = '\"\"\" + item_code + \"\"\"'\n \"\"\" , as_dict=1)\n\n \n return entries\n\n \ndef get_item_records_by_creation(creation_date):\n \n entries = frappe.db.sql(\"\"\"select\n it.item_code, it.name, it.item_name, it.item_group\n , it.brand, it.description, it.tech_details\n , it.image, it.website_image, it.slideshow\n , it.accessories_extras, it.power_cable_included, it.power_supply_included, it.remote_control_included, it.case_included\n , it.condition, it.function_grade, it.grade_details\n , it.warranty_period\n , it.net_weight, it.length, it.width, it.height\n , bin.actual_qty\n , it.standard_rate as price\n \n from `tabItem` it\n \n left join `tabBin` bin\n on bin.item_code = it.name\n \n left join `tabItem Price` ip\n on ip.item_code = it.name\n \n where it.creation >= '\"\"\" + creation_date + \"\"\"'\n \"\"\" , as_dict=1)\n \n\n return entries\n\n\n\n\n\n\ndef get_slideshow_records(parent):\n \n records = []\n if (parent!= None):\n records = frappe.db.sql(\"\"\"select\n wsi.image \n from `tabWebsite Slideshow Item` wsi\n \n where wsi.parent = '\"\"\" + parent + \"\"\"'\n \"\"\" , as_dict=1)\n \n \n return records\n\n\n'''UTILITIES'''\n \ndef kg_to_imperial(kg):\n \n ounces = kg * 35.27396195\n pounds = kg * 2.2046226218\n ounces = ounces - (pounds * 12.0)\n \n return pounds, ounces\n\n\ndef first_lower(s):\n if not s:\n return \"\"\n return s[0].lower() + s[1:]\n\n\ndef exists(path):\n r = requests.head(path)\n return r.status_code == requests.codes.ok\n\n\ndef list_directories(path):\n \n # requires import os\n \n directories = filter(os.path.isdir, os.listdir(path))\n \n return directories\n\n\ndef list_files(path):\n # returns a list of names (with extension, without full path) of all files \n # in folder path\n \n \n # requires import os\n \n files = []\n for name in os.listdir(path):\n if os.path.isfile(os.path.join(path, name)):\n files.append(name)\n return files\n\n\ndef scp_files(local_files):\n # THIS IS OF NO USE AS FILES ARE NOT LOCAL !!?? Unless scp using static ip address?\n # requires import scp\n \n\n \n remote_file = local_files\n \n client = scp.Client(host=host, user=user, password=password)\n\n # and then\n client.transfer(local_path + local_file, remote_path + remote_file)\n \n return\n\n\n \n\n#
    \"Created
    \n","sub_path":"erpnext_ebay/garage_sale.py","file_name":"garage_sale.py","file_ext":"py","file_size_in_byte":14594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"152855563","text":"#!/usr/bin/env python\n\nimport logging\nimport datetime\nfrom pymongo import MongoClient\nfrom w1thermsensor import W1ThermSensor\n\n\n# Logging config\nlogging.basicConfig(filename=\"/var/log/smartgreen/sensor_temperature.log\",\n level=logging.DEBUG,\n format=\"%(asctime)s %(message)s\")\n# logging.info(\"====================\")\n\n\n# DB\nclientMongo = MongoClient('localhost:27017')\ndb = clientMongo.SmartGreen\ncollection = db.coleta03\n\n# Temperature Sensor\nsensor = W1ThermSensor()\ntemp_celsius = sensor.get_temperature()\n\n\n# Save data\nlogging.info(temp_celsius)\ncollection.insert({\n \"type\": \"sensor\",\n \"sensor\": \"temperature\",\n \"when\": datetime.datetime.utcnow(),\n \"temperature\": temp_celsius,\n \"channel\": 0,\n \"published\": False\n})\n","sub_path":"python/sensor_temperature.py","file_name":"sensor_temperature.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"125909946","text":"from gpu_task_scheduler.gpu_task import GPUTask\nfrom pacgan.bricks import PacGAN\nfrom pacgan.distributions import circle_gaussian_mixture\nfrom pacgan.streams import create_packing_gaussian_mixture_data_streams\nfrom pacgan.extensions import ModelLogger, GraphLogger, MetricLogger\n\nfrom ali.algorithms import ali_algorithm\nfrom ali.utils import as_array\n\nimport numpy, os, random, fuel, blocks\nfrom theano import tensor, function\nfrom blocks.algorithms import Adam\nfrom blocks.bricks import MLP, Rectifier, Identity, LinearMaxout, Linear\nfrom blocks.bricks.bn import BatchNormalization\nfrom blocks.bricks.sequences import Sequence\nfrom blocks.extensions import FinishAfter, Timing, Printing, ProgressBar\nfrom blocks.extensions.monitoring import DataStreamMonitoring\nfrom blocks.extensions.saveload import Checkpoint\nfrom blocks.graph import ComputationGraph, apply_dropout\nfrom blocks.graph.bn import (batch_normalization, get_batch_normalization_updates)\nfrom blocks.filter import VariableFilter\nfrom blocks.initialization import IsotropicGaussian, Constant\nfrom blocks.model import Model\nfrom blocks.main_loop import MainLoop\nfrom blocks.roles import INPUT\nfrom blocks.select import Selector\n\n\nclass PacGANTask(GPUTask):\n def required_env(self):\n ans = {}\n if self._config[\"blocks_random\"]:\n seed = random.randint(1, 100000)\n blocksrc_path = os.path.join(self._work_dir, \".blocksrc\")\n f = open(blocksrc_path, \"w\")\n f.write(\"default_seed: {}\\n\".format(seed))\n f.close()\n blocks.config.config.default_seed = seed\n ans = {\"BLOCKS_CONFIG\": blocksrc_path}\n return ans\n \n def create_model_brick(self):\n decoder = MLP(\n dims=[self._config[\"num_zdim\"], self._config[\"gen_hidden_size\"], self._config[\"gen_hidden_size\"], self._config[\"gen_hidden_size\"], self._config[\"gen_hidden_size\"], self._config[\"num_xdim\"]],\n activations=[Sequence([BatchNormalization(self._config[\"gen_hidden_size\"]).apply,\n self._config[\"gen_activation\"]().apply],\n name='decoder_h1'),\n Sequence([BatchNormalization(self._config[\"gen_hidden_size\"]).apply,\n self._config[\"gen_activation\"]().apply],\n name='decoder_h2'),\n Sequence([BatchNormalization(self._config[\"gen_hidden_size\"]).apply,\n self._config[\"gen_activation\"]().apply],\n name='decoder_h3'),\n Sequence([BatchNormalization(self._config[\"gen_hidden_size\"]).apply,\n self._config[\"gen_activation\"]().apply],\n name='decoder_h4'),\n Identity(name='decoder_out')],\n use_bias=False,\n name='decoder')\n\n discriminator = Sequence(\n application_methods=[\n LinearMaxout(\n input_dim=self._config[\"num_xdim\"] * self._config[\"num_packing\"],\n output_dim=self._config[\"disc_hidden_size\"],\n num_pieces=self._config[\"disc_maxout_pieces\"],\n weights_init=IsotropicGaussian(self._config[\"weights_init_std\"]),\n biases_init=self._config[\"biases_init\"],\n name='discriminator_h1').apply,\n LinearMaxout(\n input_dim=self._config[\"disc_hidden_size\"],\n output_dim=self._config[\"disc_hidden_size\"],\n num_pieces=self._config[\"disc_maxout_pieces\"],\n weights_init=IsotropicGaussian(self._config[\"weights_init_std\"]),\n biases_init=self._config[\"biases_init\"],\n name='discriminator_h2').apply,\n LinearMaxout(\n input_dim=self._config[\"disc_hidden_size\"],\n output_dim=self._config[\"disc_hidden_size\"],\n num_pieces=self._config[\"disc_maxout_pieces\"],\n weights_init=IsotropicGaussian(self._config[\"weights_init_std\"]),\n biases_init=self._config[\"biases_init\"],\n name='discriminator_h3').apply,\n Linear(\n input_dim=self._config[\"disc_hidden_size\"],\n output_dim=1,\n weights_init=IsotropicGaussian(self._config[\"weights_init_std\"]),\n biases_init=self._config[\"biases_init\"],\n name='discriminator_out').apply],\n name='discriminator')\n\n gan = PacGAN(decoder=decoder, discriminator=discriminator, weights_init=IsotropicGaussian(self._config[\"weights_init_std\"]), biases_init=self._config[\"biases_init\"], name='gan')\n gan.push_allocation_config()\n decoder.linear_transformations[-1].use_bias = True\n gan.initialize()\n \n print(\"Number of parameters in discriminator: {}\".format(numpy.sum([numpy.prod(v.shape.eval()) for v in Selector(gan.discriminator).get_parameters().values()])))\n print(\"Number of parameters in decoder: {}\".format(numpy.sum([numpy.prod(v.shape.eval()) for v in Selector(gan.decoder).get_parameters().values()])))\n \n return gan\n \n def create_models(self):\n gan = self.create_model_brick()\n x = tensor.matrix('features')\n zs = []\n for i in range(self._config[\"num_packing\"]):\n z = circle_gaussian_mixture(num_modes=self._config[\"num_zmode\"], num_samples=x.shape[0], dimension=self._config[\"num_zdim\"], r=self._config[\"z_mode_r\"], std=self._config[\"z_mode_std\"])\n zs.append(z)\n\n def _create_model(with_dropout):\n cg = ComputationGraph(gan.compute_losses(x, zs))\n if with_dropout:\n inputs = VariableFilter(\n bricks=gan.discriminator.children[1:],\n roles=[INPUT])(cg.variables)\n cg = apply_dropout(cg, inputs, 0.5)\n inputs = VariableFilter(\n bricks=[gan.discriminator],\n roles=[INPUT])(cg.variables)\n cg = apply_dropout(cg, inputs, 0.2)\n return Model(cg.outputs)\n\n model = _create_model(with_dropout=False)\n with batch_normalization(gan):\n bn_model = _create_model(with_dropout=False)\n\n pop_updates = list(set(get_batch_normalization_updates(bn_model, allow_duplicates=True)))\n \n # merge same variables\n names = []\n counts = []\n pop_update_merges = []\n pop_update_merges_finals = []\n for pop_update in pop_updates:\n b = False\n for i in range(len(names)):\n if (pop_update[0].auto_name == names[i]):\n counts[i] += 1\n pop_update_merges[i][1] += pop_update[1]\n b = True\n break\n if not b:\n names.append(pop_update[0].auto_name)\n counts.append(1)\n pop_update_merges.append([pop_update[0], pop_update[1]])\n for i in range(len(pop_update_merges)):\n pop_update_merges_finals.append((pop_update_merges[i][0], pop_update_merges[i][1] / counts[i]))\n \n bn_updates = [(p, m * 0.05 + p * 0.95) for p, m in pop_update_merges_finals]\n\n return model, bn_model, bn_updates\n \n def create_main_loop(self):\n model, bn_model, bn_updates = self.create_models()\n gan, = bn_model.top_bricks\n discriminator_loss, generator_loss = bn_model.outputs\n step_rule = Adam(learning_rate=self._config[\"learning_rate\"], beta1=self._config[\"beta1\"])\n algorithm = ali_algorithm(discriminator_loss, gan.discriminator_parameters, step_rule, generator_loss, gan.generator_parameters, step_rule)\n algorithm.add_updates(bn_updates)\n streams = create_packing_gaussian_mixture_data_streams(\n num_packings=self._config[\"num_packing\"], \n batch_size=self._config[\"batch_size\"], \n monitoring_batch_size=self._config[\"monitoring_batch_size\"], \n means=self._config[\"x_mode_means\"], \n variances=self._config[\"x_mode_variances\"], \n priors=self._config[\"x_mode_priors\"],\n num_examples=self._config[\"num_sample\"])\n main_loop_stream, train_monitor_stream, valid_monitor_stream = streams\n bn_monitored_variables = (\n [v for v in bn_model.auxiliary_variables if 'norm' not in v.name] +\n bn_model.outputs)\n monitored_variables = (\n [v for v in model.auxiliary_variables if 'norm' not in v.name] +\n model.outputs)\n extensions = [\n Timing(),\n FinishAfter(after_n_epochs=self._config[\"num_epoch\"]),\n DataStreamMonitoring(\n bn_monitored_variables, train_monitor_stream, prefix=\"train\",\n updates=bn_updates),\n DataStreamMonitoring(\n monitored_variables, valid_monitor_stream, prefix=\"valid\"),\n Checkpoint(os.path.join(self._work_dir, self._config[\"main_loop_file\"]), after_epoch=True, after_training=True, use_cpickle=True),\n ProgressBar(),\n Printing(),\n ]\n if self._config[\"log_models\"]:\n extensions.append(ModelLogger(folder=self._work_dir, after_epoch=True))\n if self._config[\"log_figures\"]:\n extensions.append(GraphLogger(num_modes=self._config[\"num_zmode\"], num_samples=self._config[\"num_log_figure_sample\"], dimension=self._config[\"num_zdim\"], r=self._config[\"z_mode_r\"], std=self._config[\"z_mode_std\"], folder=self._work_dir, after_epoch=True, after_training=True))\n if self._config[\"log_metrics\"]:\n extensions.append(MetricLogger(means=self._config[\"x_mode_means\"], variances=self._config[\"x_mode_variances\"], folder=self._work_dir, after_epoch=True))\n main_loop = MainLoop(model=bn_model, data_stream=main_loop_stream, algorithm=algorithm, extensions=extensions)\n return main_loop\n \n def main(self):\n if self._config[\"fuel_random\"]:\n seed = random.randint(1, 100000)\n fuelrc_path = os.path.join(self._work_dir, \".fuelrc\")\n f = open(fuelrc_path, \"w\")\n f.write(\"default_seed: {}\\n\".format(seed))\n f.close()\n fuel.config.default_seed = seed\n\n main_loop = self.create_main_loop()\n main_loop.run()","sub_path":"synthetic_data_experiments/2DGrid_GAN&PacGAN/pacgan_task.py","file_name":"pacgan_task.py","file_ext":"py","file_size_in_byte":10576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"572477985","text":"'''\r\nfrom flask import Flask\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef index(): \r\n return \"Hello World\"\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n'''\r\n\r\nimport numpy as np\r\nfrom flask import Flask, request, jsonify, render_template\r\nimport pickle\r\nfrom xgboost import XGBClassifier\r\nimport sklearn\r\n#print(xgboost.__version__)\r\n#print(xgboost.__version__)\r\n\r\napp = Flask(__name__)\r\nmodel = pickle.load(open('model.pkl', 'rb'))\r\n#model1 = pickle.load(open('model1.pkl','rb'))\r\n#model2 = pickle.load(open('model2.pkl','rb'))\r\n#model3 = pickle.load(open('model3.pkl','rb'))\r\ntest_data = pickle.load(open('X_test.pkl','rb'))\r\n\r\n@app.route('/')\r\ndef home():\r\n return render_template('index.html')\r\n\r\n@app.route('/predict',methods=['POST'])\r\ndef predict():\r\n '''\r\n For rendering results on HTML GUI\r\n '''\r\n int_features = [float(x) for x in request.form.values()]\r\n final_features = np.array(int_features)\r\n final_features = final_features.reshape(1, -1)\r\n\r\n prediction = model.predict(final_features)\r\n #prediction1 = model1.predict(final_features)\r\n #prediction2 = model2.predict(final_features)\r\n #prediction3 = model3.predict(final_features)\r\n #pred_list = [int(prediction), int(prediction1), int(prediction2), int(prediction3)]\r\n output = round(prediction[0], 2)\r\n #zero = pred_list.count(0)\r\n #one = pred_list.count(1)\r\n output_value = \"\" \r\n #if zero > one:\r\n # output_value = \"0 : No chance for sepsis\"\r\n #elif one > zero:\r\n # output_value = \"1 : The patient is affected with sepsis\"\r\n #elif one == zero:\r\n # output_value = \" There is a possiblity of sepsis\"\r\n #print(pred_list)\r\n return render_template('index.html', prediction_text='Predicted value : {}'.format(output))\r\n\r\n@app.route('/testcasepredict',methods=['POST'])\r\ndef testcasepredict():\r\n int_features = [int(x) for x in request.form.values()][0]\r\n print(int_features)\r\n \r\n \r\n \r\n single_pred = (model.predict(np.array(test_data[int_features]).reshape(1,-1)))\r\n single_pred_proba = (model.predict_proba(np.array(test_data[int_features]).reshape(1,-1)))\r\n print(single_pred)\r\n print(single_pred_proba)\r\n single_pred_proba = single_pred_proba[0]\r\n ans = \"\"\r\n if int(single_pred[0]) == 0:\r\n ans = \"0 : No chance for sepsis\"\r\n else:\r\n ans = \"1 : There is a chance for sepsis\"\r\n \r\n return render_template('index.html', prediction_testcase='Predicted value : {}'.format(ans), proba_0 = single_pred_proba[0], proba_1 = single_pred_proba[-1])\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":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"637171151","text":"\"\"\"Pronunciation dictionaries for use in alignment and transcription\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport math\nimport os\nimport re\nimport subprocess\nimport sys\nfrom collections import Counter, defaultdict\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Collection,\n Dict,\n List,\n NamedTuple,\n Optional,\n Set,\n Tuple,\n Union,\n)\n\nimport yaml\n\nfrom .config.base_config import (\n DEFAULT_CLITIC_MARKERS,\n DEFAULT_COMPOUND_MARKERS,\n DEFAULT_DIGRAPHS,\n DEFAULT_PUNCTUATION,\n DEFAULT_STRIP_DIACRITICS,\n)\nfrom .exceptions import DictionaryError, DictionaryFileError, DictionaryPathError\nfrom .utils import get_available_dictionaries, get_dictionary_path, thirdparty_binary\n\nif TYPE_CHECKING:\n IpaType = Optional[List[str]]\n PunctuationType = Optional[str]\n from logging import Logger\n\n from .corpus.classes import Speaker\n\nDictionaryEntryType = List[Dict[str, Union[Tuple[str], float, None, int]]]\nReversedMappingType = Dict[int, str]\nWordsType = Dict[str, DictionaryEntryType]\nMappingType = Dict[str, int]\nMultiSpeakerMappingType = Dict[str, str]\n\n__all__ = [\n \"compile_graphemes\",\n \"sanitize\",\n \"check_format\",\n \"check_bracketed\",\n \"parse_ipa\",\n \"DictionaryData\",\n \"Dictionary\",\n \"MultispeakerDictionary\",\n]\n\n\ndef compile_graphemes(graphemes: Set[str]) -> re.Pattern:\n \"\"\"\n Compiles the list of graphemes into a regular expression pattern.\n\n Parameters\n ----------\n graphemes: Set[str]\n Set of characters to treat as orthographic text\n\n Returns\n -------\n re.Pattern\n Compiled pattern that matches all graphemes\n \"\"\"\n base = r\"^\\W*([{}]+)\\W*\"\n string = re.escape(\"\".join(graphemes))\n try:\n return re.compile(base.format(string))\n except Exception:\n print(graphemes)\n raise\n\n\ndef check_bracketed(word: str, brackets: Optional[List[Tuple[str, str]]] = None) -> bool:\n \"\"\"\n Checks whether a given string is surrounded by brackets.\n\n Parameters\n ----------\n word : str\n Text to check for final brackets\n brackets: List[Tuple[str, str]]], optional\n Brackets to check, defaults to [('[', ']'), ('{', '}'), ('<', '>'), ('(', ')')]\n\n Returns\n -------\n bool\n True if the word is fully bracketed, false otherwise\n \"\"\"\n if brackets is None:\n brackets = [(\"[\", \"]\"), (\"{\", \"}\"), (\"<\", \">\"), (\"(\", \")\")]\n for b in brackets:\n if word.startswith(b[0]) and word.endswith(b[-1]):\n return True\n return False\n\n\ndef sanitize(\n item: str, punctuation: Optional[str] = None, clitic_markers: Optional[str] = None\n) -> str:\n \"\"\"\n Sanitize an item according to punctuation and clitic markers\n\n Parameters\n ----------\n item: str\n Word to sanitize\n punctuation: str\n Characters to treat as punctuation\n clitic_markers: str\n Characters to treat as clitic markers, will be collapsed to the first marker\n\n Returns\n -------\n str\n Sanitized form\n \"\"\"\n if punctuation is None:\n punctuation = DEFAULT_PUNCTUATION\n if clitic_markers is None:\n clitic_markers = DEFAULT_CLITIC_MARKERS\n for c in clitic_markers:\n item = item.replace(c, clitic_markers[0])\n if not item:\n return item\n if check_bracketed(item):\n return item\n sanitized = re.sub(rf\"^[{punctuation}]+\", \"\", item)\n sanitized = re.sub(rf\"[{punctuation}]+$\", \"\", sanitized)\n\n return sanitized\n\n\ndef check_format(path: str) -> Tuple[bool, bool]:\n \"\"\"\n Check the pronunciation dictionary format\n\n Parameters\n ----------\n path: str\n Path of pronunciation dictionary\n\n Returns\n -------\n bool\n Flag for whether the dictionary has pronunciation probabilities\n bool\n Flag for whether the dictionary includes silence probabilities\n \"\"\"\n count = 0\n pronunciation_probabilities = True\n silence_probabilities = True\n with open(path, \"r\", encoding=\"utf8\") as f:\n for line in f:\n line = line.strip()\n if not line:\n continue\n line = line.split()\n _ = line.pop(0) # word\n next_item = line.pop(0)\n if pronunciation_probabilities:\n try:\n prob = float(next_item)\n if prob > 1 or prob < 0:\n raise ValueError\n except ValueError:\n pronunciation_probabilities = False\n try:\n next_item = line.pop(0)\n except IndexError:\n silence_probabilities = False\n if silence_probabilities:\n try:\n prob = float(next_item)\n if prob > 1 or prob < 0:\n raise ValueError\n except ValueError:\n silence_probabilities = False\n count += 1\n if count > 10:\n break\n return pronunciation_probabilities, silence_probabilities\n\n\ndef parse_ipa(\n transcription: List[str], strip_diacritics: IpaType = None, digraphs: IpaType = None\n) -> Tuple[str, ...]:\n \"\"\"\n Parse a transcription in a multilingual IPA format (strips out diacritics and splits digraphs).\n\n Parameters\n ----------\n transcription: List[str]\n Transcription to parse\n strip_diacritics: List[str]\n List of diacritics to remove from characters in the transcription\n digraphs: List[str]\n List of digraphs to split up into separate characters\n\n Returns\n -------\n Tuple[str, ...]\n Parsed transcription\n \"\"\"\n if strip_diacritics is None:\n strip_diacritics = DEFAULT_STRIP_DIACRITICS\n if digraphs is None:\n digraphs = DEFAULT_DIGRAPHS\n new_transcription = []\n for t in transcription:\n new_t = t\n for d in strip_diacritics:\n new_t = new_t.replace(d, \"\")\n if \"g\" in new_t:\n new_t = new_t.replace(\"g\", \"ɡ\")\n\n found = False\n for digraph in digraphs:\n if re.match(r\"^{}$\".format(digraph), new_t):\n found = True\n if found:\n new_transcription.extend(new_t)\n continue\n new_transcription.append(new_t)\n return tuple(new_transcription)\n\n\nclass DictionaryData(NamedTuple):\n \"\"\"\n Information required for parsing Kaldi-internal ids to text\n \"\"\"\n\n silences: Set[str]\n multilingual_ipa: bool\n words_mapping: MappingType\n reversed_words_mapping: ReversedMappingType\n reversed_phone_mapping: ReversedMappingType\n punctuation: PunctuationType\n clitic_set: Set[str]\n clitic_markers: PunctuationType\n compound_markers: PunctuationType\n strip_diacritics: IpaType\n oov_int: int\n oov_code: str\n words: WordsType\n\n\nclass Dictionary:\n \"\"\"\n Class containing information about a pronunciation dictionary\n\n Parameters\n ----------\n input_path : str\n Path to an input pronunciation dictionary\n output_directory : str\n Path to a directory to store files for Kaldi\n oov_code : str, optional\n What to label words not in the dictionary, defaults to ``''``\n position_dependent_phones : bool, optional\n Specifies whether phones should be represented as dependent on their\n position in the word (beginning, middle or end), defaults to True\n num_sil_states : int, optional\n Number of states to use for silence phones, defaults to 5\n num_nonsil_states : int, optional\n Number of states to use for non-silence phones, defaults to 3\n shared_silence_phones : bool, optional\n Specify whether to share states across all silence phones, defaults\n to True\n sil_prob : float, optional\n Probability of optional silences following words, defaults to 0.5\n word_set : Collection[str], optional\n Word set to limit output files\n debug: bool, optional\n Flag for whether to perform debug steps and prevent intermediate cleanup\n logger: :class:`~logging.Logger`, optional\n Logger to output information to\n punctuation: str, optional\n Punctuation to use when parsing text\n clitic_markers: str, optional\n Clitic markers to use when parsing text\n compound_markers: str, optional\n Compound markers to use when parsing text\n multilingual_ipa: bool, optional\n Flag for multilingual IPA mode, defaults to False\n strip_diacritics: List[str], optional\n Diacritics to strip in multilingual IPA mode\n digraphs: List[str], optional\n Digraphs to split up in multilingual IPA mode\n \"\"\"\n\n topo_template = \" {cur_state} {cur_state} {cur_state} 0.75 {next_state} 0.25 \"\n topo_sil_template = \" {cur_state} {cur_state} {transitions} \"\n topo_transition_template = \" {} {}\"\n positions: List[str] = [\"_B\", \"_E\", \"_I\", \"_S\"]\n has_multiple = False\n\n def __init__(\n self,\n input_path: str,\n output_directory: str,\n oov_code: str = \"\",\n position_dependent_phones: bool = True,\n num_sil_states: int = 5,\n num_nonsil_states: int = 3,\n shared_silence_phones: bool = True,\n sil_prob: float = 0.5,\n word_set: Optional[Collection[str]] = None,\n debug: bool = False,\n logger: Optional[logging.Logger] = None,\n punctuation: PunctuationType = None,\n clitic_markers: PunctuationType = None,\n compound_markers: PunctuationType = None,\n multilingual_ipa: bool = False,\n strip_diacritics: IpaType = None,\n digraphs: IpaType = None,\n ):\n self.multilingual_ipa = multilingual_ipa\n self.strip_diacritics = DEFAULT_STRIP_DIACRITICS\n self.digraphs = DEFAULT_DIGRAPHS\n if strip_diacritics is not None:\n self.strip_diacritics = strip_diacritics\n if digraphs is not None:\n self.digraphs = digraphs\n self.punctuation = DEFAULT_PUNCTUATION\n self.clitic_markers = DEFAULT_CLITIC_MARKERS\n self.compound_markers = DEFAULT_COMPOUND_MARKERS\n if punctuation is not None:\n self.punctuation = punctuation\n if clitic_markers is not None:\n self.clitic_markers = clitic_markers\n if compound_markers is not None:\n self.compound_markers = compound_markers\n\n if not os.path.exists(input_path):\n raise (DictionaryPathError(input_path))\n if not os.path.isfile(input_path):\n raise (DictionaryFileError(input_path))\n self.input_path = input_path\n self.name = os.path.splitext(os.path.basename(input_path))[0]\n self.debug = debug\n self.output_directory = os.path.join(output_directory, self.name)\n os.makedirs(self.output_directory, exist_ok=True)\n self.log_file = os.path.join(self.output_directory, f\"{self.name}.log\")\n if logger is None:\n self.logger = logging.getLogger(\"dictionary_setup\")\n self.logger.setLevel(logging.INFO)\n handler = logging.FileHandler(self.log_file, \"w\", \"utf-8\")\n handler.setFormatter = logging.Formatter(\"%(name)s %(message)s\")\n self.logger.addHandler(handler)\n self.individual_logger = True\n else:\n self.logger = logger\n self.individual_logger = False\n self.num_sil_states = num_sil_states\n self.num_nonsil_states = num_nonsil_states\n self.shared_silence_phones = shared_silence_phones\n self.sil_prob = sil_prob\n self.oov_code = oov_code\n self.sil_code = \"!sil\"\n self.oovs_found = Counter()\n self.position_dependent_phones = position_dependent_phones\n\n self.words = {}\n self.nonsil_phones: Set[str] = set()\n self.sil_phones = {\"sp\", \"spn\", \"sil\"}\n self.optional_silence = \"sp\"\n self.nonoptional_silence = \"sil\"\n self.graphemes = set()\n self.max_disambiguation_symbol = 0\n self.disambiguation_symbols = set()\n self.all_words = defaultdict(list)\n self.clitic_set = set()\n self.specials_set = {self.oov_code, self.sil_code, \"\", \"\", \"\"}\n self.words[self.sil_code] = [{\"pronunciation\": (\"sp\",), \"probability\": 1}]\n self.words[self.oov_code] = [{\"pronunciation\": (\"spn\",), \"probability\": 1}]\n self.pronunciation_probabilities, self.silence_probabilities = check_format(input_path)\n progress = f'Parsing dictionary \"{self.name}\"'\n if self.pronunciation_probabilities:\n progress += \" with pronunciation probabilities\"\n else:\n progress += \" without pronunciation probabilities\"\n if self.silence_probabilities:\n progress += \" with silence probabilities\"\n else:\n progress += \" without silence probabilities\"\n self.logger.info(progress)\n with open(input_path, \"r\", encoding=\"utf8\") as inf:\n for i, line in enumerate(inf):\n line = line.strip()\n if not line:\n continue\n line = line.split()\n word = sanitize(line.pop(0).lower(), self.punctuation, self.clitic_markers)\n if not line:\n raise DictionaryError(\n f\"Line {i} of {input_path} does not have a pronunciation.\"\n )\n if word in [\"!sil\", oov_code]:\n continue\n self.graphemes.update(word)\n prob = None\n if self.pronunciation_probabilities:\n prob = float(line.pop(0))\n if prob > 1 or prob < 0:\n raise ValueError\n if self.silence_probabilities:\n right_sil_prob = float(line.pop(0))\n left_sil_prob = float(line.pop(0))\n left_nonsil_prob = float(line.pop(0))\n else:\n right_sil_prob = None\n left_sil_prob = None\n left_nonsil_prob = None\n if self.multilingual_ipa:\n pron = parse_ipa(line, self.strip_diacritics, self.digraphs)\n else:\n pron = tuple(line)\n pronunciation = {\n \"pronunciation\": pron,\n \"probability\": prob,\n \"disambiguation\": None,\n \"right_sil_prob\": right_sil_prob,\n \"left_sil_prob\": left_sil_prob,\n \"left_nonsil_prob\": left_nonsil_prob,\n }\n if self.multilingual_ipa:\n pronunciation[\"original_pronunciation\"] = tuple(line)\n if not any(x in self.sil_phones for x in pron):\n self.nonsil_phones.update(pron)\n if word in self.words and pron in {x[\"pronunciation\"] for x in self.words[word]}:\n continue\n if word not in self.words:\n self.words[word] = []\n self.words[word].append(pronunciation)\n # test whether a word is a clitic\n is_clitic = False\n for cm in self.clitic_markers:\n if word.startswith(cm) or word.endswith(cm):\n is_clitic = True\n if is_clitic:\n self.clitic_set.add(word)\n if word_set is not None:\n word_set = {y for x in word_set for y in self._lookup(x)}\n word_set.add(\"!sil\")\n word_set.add(self.oov_code)\n self.word_set = word_set\n if self.word_set is not None:\n self.word_set = self.word_set | self.clitic_set\n if not self.graphemes:\n raise DictionaryFileError(f\"No words were found in the dictionary path {input_path}\")\n self.word_pattern = compile_graphemes(self.graphemes)\n self.log_info()\n self.phone_mapping = {}\n self.words_mapping = {}\n\n def __hash__(self) -> Any:\n \"\"\"Return the hash of a given dictionary\"\"\"\n return hash(self.input_path)\n\n @property\n def output_paths(self) -> Dict[str, str]:\n \"\"\"\n Mapping of output directory for this dictionary\n \"\"\"\n return {self.name: self.output_directory}\n\n @property\n def silences(self) -> Set[str]:\n \"\"\"\n Set of symbols that correspond to silence\n \"\"\"\n return {self.optional_silence, self.nonoptional_silence}\n\n def get_dictionary(self, speaker: Union[Speaker, str]) -> Dictionary:\n \"\"\"\n Wrapper function to return this dictionary for any arbitrary speaker\n\n Parameters\n ----------\n speaker: Union[Speaker, str]\n Speaker to look up dictionary for\n\n Returns\n -------\n Dictionary\n This dictionary\n \"\"\"\n return self\n\n def data(self, word_set: Optional[Collection[str]] = None) -> DictionaryData:\n \"\"\"\n Generates a dictionary data for use in parsing utilities\n\n Parameters\n ----------\n word_set: Collection[str], optional\n Word set to limit data to\n\n Returns\n -------\n DictionaryData\n Data necessary for parsing text\n \"\"\"\n\n def word_check(word):\n \"\"\"Check whether a word should be included in the output\"\"\"\n if word in word_set:\n return True\n if word in self.clitic_set:\n return True\n if word in self.specials_set:\n return True\n return False\n\n if word_set:\n words_mapping = {k: v for k, v in self.words_mapping.items() if word_check(k)}\n reversed_word_mapping = {\n k: v for k, v in self.reversed_word_mapping.items() if word_check(v)\n }\n words = {k: v for k, v in self.words.items() if word_check(k)}\n else:\n words_mapping = self.words_mapping\n reversed_word_mapping = self.reversed_word_mapping\n words = self.words\n return DictionaryData(\n self.silences,\n self.multilingual_ipa,\n words_mapping,\n reversed_word_mapping,\n self.reversed_phone_mapping,\n self.punctuation,\n self.clitic_set,\n self.clitic_markers,\n self.compound_markers,\n self.strip_diacritics,\n self.oov_int,\n self.oov_code,\n words,\n )\n\n def cleanup_logger(self) -> None:\n \"\"\"\n Clean up and detach logger from handles\n \"\"\"\n if not self.individual_logger:\n return\n handlers = self.logger.handlers[:]\n for handler in handlers:\n handler.close()\n self.logger.removeHandler(handler)\n\n def log_info(self) -> None:\n \"\"\"\n Dump debugging information to the logger\n \"\"\"\n self.logger.debug(f'\"{self.name}\" DICTIONARY INFORMATION')\n if self.pronunciation_probabilities:\n self.logger.debug(\"Has pronunciation probabilities\")\n else:\n self.logger.debug(\"Has NO pronunciation probabilities\")\n if self.silence_probabilities:\n self.logger.debug(\"Has silence probabilities\")\n else:\n self.logger.debug(\"Has NO silence probabilities\")\n\n self.logger.debug(f\"Grapheme set: {', '.join(sorted(self.graphemes))}\")\n self.logger.debug(f\"Phone set: {', '.join(sorted(self.nonsil_phones))}\")\n self.logger.debug(f\"Punctuation: {self.punctuation}\")\n self.logger.debug(f\"Clitic markers: {self.clitic_markers}\")\n self.logger.debug(f\"Clitic set: {', '.join(sorted(self.clitic_set))}\")\n if self.multilingual_ipa:\n self.logger.debug(f\"Strip diacritics: {', '.join(sorted(self.strip_diacritics))}\")\n self.logger.debug(f\"Digraphs: {', '.join(sorted(self.digraphs))}\")\n\n def set_word_set(self, word_set: List[str]) -> None:\n \"\"\"\n Limit output to a subset of overall words\n\n Parameters\n ----------\n word_set: List[str]\n Word set to limit generated files to\n \"\"\"\n word_set = {y for x in word_set for y in self._lookup(x)}\n word_set.add(self.sil_code)\n word_set.add(self.oov_code)\n self.word_set = word_set | self.clitic_set\n self.generate_mappings()\n\n @property\n def actual_words(self) -> Dict[str, DictionaryEntryType]:\n \"\"\"\n Mapping of words to integer IDs without Kaldi-internal words\n \"\"\"\n return {\n k: v\n for k, v in self.words.items()\n if k not in [self.sil_code, self.oov_code, \"\"] and len(v)\n }\n\n def split_clitics(self, item: str) -> List[str]:\n \"\"\"\n Split a word into subwords based on clitic and compound markers\n\n Parameters\n ----------\n item: str\n Word to split up\n\n Returns\n -------\n List[str]\n List of subwords\n \"\"\"\n if item in self.words:\n return [item]\n if any(x in item for x in self.compound_markers):\n s = re.split(rf\"[{self.compound_markers}]\", item)\n if any(x in item for x in self.clitic_markers):\n new_s = []\n for seg in s:\n if any(x in seg for x in self.clitic_markers):\n new_s.extend(self.split_clitics(seg))\n else:\n new_s.append(seg)\n s = new_s\n return s\n if any(\n x in item and not item.endswith(x) and not item.startswith(x)\n for x in self.clitic_markers\n ):\n initial, final = re.split(rf\"[{self.clitic_markers}]\", item, maxsplit=1)\n if any(x in final for x in self.clitic_markers):\n final = self.split_clitics(final)\n else:\n final = [final]\n for clitic in self.clitic_markers:\n if initial + clitic in self.clitic_set:\n return [initial + clitic] + final\n elif clitic + final[0] in self.clitic_set:\n final[0] = clitic + final[0]\n return [initial] + final\n return [item]\n\n def __len__(self) -> int:\n \"\"\"Return the number of pronunciations across all words\"\"\"\n return sum(len(x) for x in self.words.values())\n\n def exclude_for_alignment(self, word: str) -> bool:\n \"\"\"\n Check for whether to exclude a word from alignment lexicons (if there is a word set in the dictionary,\n checks whether the given string is in the word set)\n\n Parameters\n ----------\n word: str\n Word to check\n\n Returns\n -------\n bool\n True if there is no word set on the dictionary, or if the word is in the given word set\n \"\"\"\n if self.word_set is None:\n return False\n if word not in self.word_set and word not in self.clitic_set:\n return True\n return False\n\n def generate_mappings(self) -> None:\n \"\"\"\n Generate phone and word mappings from text to integer IDs\n \"\"\"\n if self.phone_mapping:\n return\n self.phone_mapping = {}\n i = 0\n self.phone_mapping[\"\"] = i\n if self.position_dependent_phones:\n for p in self.positional_sil_phones:\n i += 1\n self.phone_mapping[p] = i\n for p in self.positional_nonsil_phones:\n i += 1\n self.phone_mapping[p] = i\n else:\n for p in sorted(self.sil_phones):\n i += 1\n self.phone_mapping[p] = i\n for p in sorted(self.nonsil_phones):\n i += 1\n self.phone_mapping[p] = i\n\n self.words_mapping = {}\n i = 0\n self.words_mapping[\"\"] = i\n for w in sorted(self.words.keys()):\n if self.exclude_for_alignment(w):\n continue\n i += 1\n self.words_mapping[w] = i\n\n self.words_mapping[\"#0\"] = i + 1\n self.words_mapping[\"\"] = i + 2\n self.words_mapping[\"\"] = i + 3\n self.oovs_found = Counter()\n self.add_disambiguation()\n\n def add_disambiguation(self) -> None:\n \"\"\"\n Calculate disambiguation symbols for each pronunciation\n \"\"\"\n subsequences = set()\n pronunciation_counts = defaultdict(int)\n\n for w, prons in self.words.items():\n if self.exclude_for_alignment(w):\n continue\n for p in prons:\n pronunciation_counts[p[\"pronunciation\"]] += 1\n pron = p[\"pronunciation\"][:-1]\n while pron:\n subsequences.add(tuple(p))\n pron = pron[:-1]\n last_used = defaultdict(int)\n for w, prons in sorted(self.words.items()):\n if self.exclude_for_alignment(w):\n continue\n for p in prons:\n if (\n pronunciation_counts[p[\"pronunciation\"]] == 1\n and not p[\"pronunciation\"] in subsequences\n ):\n disambig = None\n else:\n pron = p[\"pronunciation\"]\n last_used[pron] += 1\n disambig = last_used[pron]\n p[\"disambiguation\"] = disambig\n if last_used:\n self.max_disambiguation_symbol = max(last_used.values())\n else:\n self.max_disambiguation_symbol = 0\n self.disambiguation_symbols = set()\n i = max(self.phone_mapping.values())\n for x in range(self.max_disambiguation_symbol + 2):\n p = f\"#{x}\"\n self.disambiguation_symbols.add(p)\n i += 1\n self.phone_mapping[p] = i\n\n def create_utterance_fst(self, text: List[str], frequent_words: List[Tuple[str, int]]) -> str:\n \"\"\"\n Create an FST for an utterance with frequent words as a unigram language model\n\n Parameters\n ----------\n text: List[str]\n Text of the utterance\n frequent_words: List[Tuple[str, int]]\n Frequent words to incorporate into the FST\n Returns\n -------\n str\n FST created from the utterance text and frequent words\n \"\"\"\n num_words = len(text)\n word_probs = Counter(text)\n word_probs = {k: v / num_words for k, v in word_probs.items()}\n word_probs.update(frequent_words)\n fst_text = \"\"\n for k, v in word_probs.items():\n cost = -1 * math.log(v)\n w = self.to_int(k)[0]\n fst_text += f\"0 0 {w} {w} {cost}\\n\"\n fst_text += f\"0 {-1 * math.log(1 / num_words)}\\n\"\n return fst_text\n\n def to_int(self, item: str) -> List[int]:\n \"\"\"\n Convert a given word into integer IDs\n\n Parameters\n ----------\n item: str\n Word to look up\n\n Returns\n -------\n List[int]\n List of integer IDs corresponding to each subword\n \"\"\"\n if item == \"\":\n return []\n sanitized = self._lookup(item)\n text_int = []\n for item in sanitized:\n if not item:\n continue\n if item not in self.words_mapping:\n self.oovs_found.update([item])\n text_int.append(self.oov_int)\n else:\n text_int.append(self.words_mapping[item])\n return text_int\n\n def save_oovs_found(self, directory: str) -> None:\n \"\"\"\n Save all out of vocabulary items to a file in the specified directory\n\n Parameters\n ----------\n directory : str\n Path to directory to save ``oovs_found.txt``\n \"\"\"\n with open(os.path.join(directory, \"oovs_found.txt\"), \"w\", encoding=\"utf8\") as f, open(\n os.path.join(directory, \"oov_counts.txt\"), \"w\", encoding=\"utf8\"\n ) as cf:\n for oov in sorted(self.oovs_found.keys(), key=lambda x: (-self.oovs_found[x], x)):\n f.write(oov + \"\\n\")\n cf.write(f\"{oov}\\t{self.oovs_found[oov]}\\n\")\n\n def _lookup(self, item: str) -> List[str]:\n \"\"\"\n Look up a word and return the list of sub words if necessary taking into account clitic and compound markers\n\n Parameters\n ----------\n item: str\n Word to look up\n\n Returns\n -------\n List[str]\n List of subwords that are in the dictionary\n \"\"\"\n if item in self.words:\n return [item]\n sanitized = sanitize(item, self.punctuation, self.clitic_markers)\n if sanitized in self.words:\n return [sanitized]\n split = self.split_clitics(sanitized)\n oov_count = sum(1 for x in split if x not in self.words)\n if oov_count < len(\n split\n ): # Only returned split item if it gains us any transcribed speech\n return split\n return [sanitized]\n\n def check_word(self, item: str) -> bool:\n \"\"\"\n Check whether a word is in the dictionary, takes into account sanitization and\n clitic and compound markers\n\n Parameters\n ----------\n item: str\n Word to check\n\n Returns\n -------\n bool\n True if the look up would not result in an OOV item\n \"\"\"\n if item == \"\":\n return False\n if item in self.words:\n return True\n sanitized = sanitize(item, self.punctuation, self.clitic_markers)\n if sanitized in self.words:\n return True\n\n sanitized = self.split_clitics(sanitized)\n if all(s in self.words for s in sanitized):\n return True\n return False\n\n @property\n def reversed_word_mapping(self) -> ReversedMappingType:\n \"\"\"\n A mapping of integer ids to words\n \"\"\"\n mapping = {}\n for k, v in self.words_mapping.items():\n mapping[v] = k\n return mapping\n\n @property\n def reversed_phone_mapping(self) -> ReversedMappingType:\n \"\"\"\n A mapping of integer ids to phones\n \"\"\"\n mapping = {}\n for k, v in self.phone_mapping.items():\n mapping[v] = k\n return mapping\n\n @property\n def oov_int(self) -> int:\n \"\"\"\n The integer id for out of vocabulary items\n \"\"\"\n return self.words_mapping[self.oov_code]\n\n @property\n def positional_sil_phones(self) -> List[str]:\n \"\"\"\n List of silence phones with positions\n \"\"\"\n sil_phones = []\n for p in sorted(self.sil_phones):\n sil_phones.append(p)\n for pos in self.positions:\n sil_phones.append(p + pos)\n return sil_phones\n\n @property\n def positional_nonsil_phones(self) -> List[str]:\n \"\"\"\n List of non-silence phones with positions\n \"\"\"\n nonsil_phones = []\n for p in sorted(self.nonsil_phones):\n for pos in self.positions:\n nonsil_phones.append(p + pos)\n return nonsil_phones\n\n @property\n def optional_silence_csl(self) -> str:\n \"\"\"\n Phone id of the optional silence phone\n \"\"\"\n return str(self.phone_mapping[self.optional_silence])\n\n @property\n def silence_csl(self) -> str:\n \"\"\"\n A colon-separated list (as a string) of silence phone ids\n \"\"\"\n if self.position_dependent_phones:\n return \":\".join(map(str, (self.phone_mapping[x] for x in self.positional_sil_phones)))\n else:\n return \":\".join(map(str, (self.phone_mapping[x] for x in self.sil_phones)))\n\n @property\n def phones_dir(self) -> str:\n \"\"\"\n Directory to store information Kaldi needs about phones\n \"\"\"\n return os.path.join(self.output_directory, \"phones\")\n\n @property\n def phones(self) -> set:\n \"\"\"\n The set of all phones (silence and non-silence)\n \"\"\"\n return self.sil_phones | self.nonsil_phones\n\n @property\n def words_symbol_path(self) -> str:\n \"\"\"\n Path of word to int mapping file for the dictionary\n \"\"\"\n return os.path.join(self.output_directory, \"words.txt\")\n\n @property\n def disambig_path(self) -> str:\n \"\"\"\n Path of disambiguated lexicon fst (L.fst)\n \"\"\"\n return os.path.join(self.output_directory, \"L_disambig.fst\")\n\n def write(self, write_disambiguation: Optional[bool] = False) -> None:\n \"\"\"\n Write the files necessary for Kaldi\n\n Parameters\n ----------\n write_disambiguation: bool, optional\n Flag for including disambiguation information\n \"\"\"\n self.logger.info(\"Creating dictionary information...\")\n os.makedirs(self.phones_dir, exist_ok=True)\n self.generate_mappings()\n self._write_graphemes()\n self._write_phone_map_file()\n self._write_phone_sets()\n self._write_phone_symbol_table()\n self._write_disambig()\n self._write_topo()\n self._write_word_boundaries()\n self._write_extra_questions()\n self._write_word_file()\n self._write_align_lexicon()\n self._write_fst_text(write_disambiguation=write_disambiguation)\n self._write_fst_binary(write_disambiguation=write_disambiguation)\n self.cleanup()\n\n def cleanup(self) -> None:\n \"\"\"\n Clean up temporary files in the output directory\n \"\"\"\n if not self.debug:\n if os.path.exists(os.path.join(self.output_directory, \"temp.fst\")):\n os.remove(os.path.join(self.output_directory, \"temp.fst\"))\n if os.path.exists(os.path.join(self.output_directory, \"lexicon.text.fst\")):\n os.remove(os.path.join(self.output_directory, \"lexicon.text.fst\"))\n\n def _write_graphemes(self) -> None:\n \"\"\"\n Write graphemes to temporary directory\n \"\"\"\n outfile = os.path.join(self.output_directory, \"graphemes.txt\")\n if os.path.exists(outfile):\n return\n with open(outfile, \"w\", encoding=\"utf8\") as f:\n for char in sorted(self.graphemes):\n f.write(char + \"\\n\")\n\n def export_lexicon(\n self,\n path: str,\n write_disambiguation: Optional[bool] = False,\n probability: Optional[bool] = False,\n ) -> None:\n \"\"\"\n Export pronunciation dictionary to a text file\n\n Parameters\n ----------\n path: str\n Path to save dictionary\n write_disambiguation: bool, optional\n Flag for whether to include disambiguation information\n probability: bool, optional\n Flag for whether to include probabilities\n \"\"\"\n with open(path, \"w\", encoding=\"utf8\") as f:\n for w in sorted(self.words.keys()):\n for p in sorted(\n self.words[w],\n key=lambda x: (x[\"pronunciation\"], x[\"probability\"], x[\"disambiguation\"]),\n ):\n phones = \" \".join(p[\"pronunciation\"])\n if write_disambiguation and p[\"disambiguation\"] is not None:\n phones += f\" #{p['disambiguation']}\"\n if probability:\n f.write(f\"{w}\\t{p['probability']}\\t{phones}\\n\")\n else:\n f.write(f\"{w}\\t{phones}\\n\")\n\n def _write_phone_map_file(self) -> None:\n \"\"\"\n Write the phone map to the temporary directory\n \"\"\"\n outfile = os.path.join(self.output_directory, \"phone_map.txt\")\n if os.path.exists(outfile):\n return\n with open(outfile, \"w\", encoding=\"utf8\") as f:\n for sp in self.sil_phones:\n if self.position_dependent_phones:\n new_phones = [sp + x for x in [\"\", \"\"] + self.positions]\n else:\n new_phones = [sp]\n f.write(\" \".join(new_phones) + \"\\n\")\n for nsp in self.nonsil_phones:\n if self.position_dependent_phones:\n new_phones = [nsp + x for x in [\"\"] + self.positions]\n else:\n new_phones = [nsp]\n f.write(\" \".join(new_phones) + \"\\n\")\n\n def _write_phone_symbol_table(self) -> None:\n \"\"\"\n Write the phone mapping to the temporary directory\n \"\"\"\n outfile = os.path.join(self.output_directory, \"phones.txt\")\n if os.path.exists(outfile):\n return\n with open(outfile, \"w\", encoding=\"utf8\") as f:\n for p, i in sorted(self.phone_mapping.items(), key=lambda x: x[1]):\n f.write(f\"{p} {i}\\n\")\n\n def _write_word_boundaries(self) -> None:\n \"\"\"\n Write the word boundaries file to the temporary directory\n \"\"\"\n boundary_path = os.path.join(self.output_directory, \"phones\", \"word_boundary.txt\")\n boundary_int_path = os.path.join(self.output_directory, \"phones\", \"word_boundary.int\")\n if os.path.exists(boundary_path) and os.path.exists(boundary_int_path):\n return\n with open(boundary_path, \"w\", encoding=\"utf8\") as f, open(\n boundary_int_path, \"w\", encoding=\"utf8\"\n ) as intf:\n if self.position_dependent_phones:\n for p in sorted(self.phone_mapping.keys(), key=lambda x: self.phone_mapping[x]):\n if p == \"\" or p.startswith(\"#\"):\n continue\n cat = \"nonword\"\n if p.endswith(\"_B\"):\n cat = \"begin\"\n elif p.endswith(\"_S\"):\n cat = \"singleton\"\n elif p.endswith(\"_I\"):\n cat = \"internal\"\n elif p.endswith(\"_E\"):\n cat = \"end\"\n f.write(\" \".join([p, cat]) + \"\\n\")\n intf.write(\" \".join([str(self.phone_mapping[p]), cat]) + \"\\n\")\n\n def _write_word_file(self) -> None:\n \"\"\"\n Write the word mapping to the temporary directory\n \"\"\"\n words_path = os.path.join(self.output_directory, \"words.txt\")\n if os.path.exists(words_path):\n return\n if sys.platform == \"win32\":\n newline = \"\"\n else:\n newline = None\n with open(words_path, \"w\", encoding=\"utf8\", newline=newline) as f:\n for w, i in sorted(self.words_mapping.items(), key=lambda x: x[1]):\n f.write(f\"{w} {i}\\n\")\n\n def _write_align_lexicon(self) -> None:\n \"\"\"\n Write the alignment lexicon text file to the temporary directory\n \"\"\"\n path = os.path.join(self.phones_dir, \"align_lexicon.int\")\n if os.path.exists(path):\n return\n\n with open(path, \"w\", encoding=\"utf8\") as f:\n for w, i in self.words_mapping.items():\n if self.exclude_for_alignment(w):\n continue\n if w not in self.words: # special characters\n continue\n for pron in sorted(\n self.words[w],\n key=lambda x: (x[\"pronunciation\"], x[\"probability\"], x[\"disambiguation\"]),\n ):\n\n phones = list(pron[\"pronunciation\"])\n if self.position_dependent_phones:\n if len(phones) == 1:\n phones[0] += \"_S\"\n else:\n for j in range(len(phones)):\n if j == 0:\n phones[j] += \"_B\"\n elif j == len(phones) - 1:\n phones[j] += \"_E\"\n else:\n phones[j] += \"_I\"\n p = \" \".join(str(self.phone_mapping[x]) for x in phones)\n f.write(f\"{i} {i} {p}\\n\".format(i=i, p=p))\n\n def _write_topo(self) -> None:\n \"\"\"\n Write the topo file to the temporary directory\n \"\"\"\n filepath = os.path.join(self.output_directory, \"topo\")\n if os.path.exists(filepath):\n return\n sil_transp = 1 / (self.num_sil_states - 1)\n initial_transition = [\n self.topo_transition_template.format(x, sil_transp)\n for x in range(self.num_sil_states - 1)\n ]\n middle_transition = [\n self.topo_transition_template.format(x, sil_transp)\n for x in range(1, self.num_sil_states)\n ]\n final_transition = [\n self.topo_transition_template.format(self.num_sil_states - 1, 0.75),\n self.topo_transition_template.format(self.num_sil_states, 0.25),\n ]\n with open(filepath, \"w\") as f:\n f.write(\"\\n\")\n f.write(\"\\n\")\n f.write(\"\\n\")\n if self.position_dependent_phones:\n phones = self.positional_nonsil_phones\n else:\n phones = sorted(self.nonsil_phones)\n f.write(f\"{' '.join(str(self.phone_mapping[x]) for x in phones)}\\n\")\n f.write(\"\\n\")\n states = [\n self.topo_template.format(cur_state=x, next_state=x + 1)\n for x in range(self.num_nonsil_states)\n ]\n f.write(\"\\n\".join(states))\n f.write(f\"\\n {self.num_nonsil_states} \\n\")\n f.write(\"\\n\")\n\n f.write(\"\\n\")\n f.write(\"\\n\")\n if self.position_dependent_phones:\n phones = self.positional_sil_phones\n else:\n phones = self.sil_phones\n f.write(f\"{' '.join(str(self.phone_mapping[x]) for x in phones)}\\n\")\n f.write(\"\\n\")\n states = []\n for i in range(self.num_sil_states):\n if i == 0:\n transition = \" \".join(initial_transition)\n elif i == self.num_sil_states - 1:\n transition = \" \".join(final_transition)\n else:\n transition = \" \".join(middle_transition)\n states.append(self.topo_sil_template.format(cur_state=i, transitions=transition))\n f.write(\"\\n\".join(states))\n f.write(f\"\\n {self.num_sil_states} \\n\")\n f.write(\"\\n\")\n f.write(\"\\n\")\n\n def _write_phone_sets(self) -> None:\n \"\"\"\n Write phone symbol sets to the temporary directory\n \"\"\"\n sharesplit = [\"shared\", \"split\"]\n if not self.shared_silence_phones:\n sil_sharesplit = [\"not-shared\", \"not-split\"]\n else:\n sil_sharesplit = sharesplit\n\n sets_file = os.path.join(self.output_directory, \"phones\", \"sets.txt\")\n roots_file = os.path.join(self.output_directory, \"phones\", \"roots.txt\")\n\n sets_int_file = os.path.join(self.output_directory, \"phones\", \"sets.int\")\n roots_int_file = os.path.join(self.output_directory, \"phones\", \"roots.int\")\n if (\n os.path.exists(sets_file)\n and os.path.exists(roots_file)\n and os.path.exists(sets_int_file)\n and os.path.exists(roots_int_file)\n ):\n return\n\n with open(sets_file, \"w\", encoding=\"utf8\") as setf, open(\n roots_file, \"w\", encoding=\"utf8\"\n ) as rootf, open(sets_int_file, \"w\", encoding=\"utf8\") as setintf, open(\n roots_int_file, \"w\", encoding=\"utf8\"\n ) as rootintf:\n\n # process silence phones\n for i, sp in enumerate(self.sil_phones):\n if self.position_dependent_phones:\n mapped = [sp + x for x in [\"\"] + self.positions]\n else:\n mapped = [sp]\n setf.write(\" \".join(mapped) + \"\\n\")\n setintf.write(\" \".join(map(str, (self.phone_mapping[x] for x in mapped))) + \"\\n\")\n if i == 0:\n line = sil_sharesplit + mapped\n lineint = sil_sharesplit + [self.phone_mapping[x] for x in mapped]\n else:\n line = sharesplit + mapped\n lineint = sharesplit + [self.phone_mapping[x] for x in mapped]\n rootf.write(\" \".join(line) + \"\\n\")\n rootintf.write(\" \".join(map(str, lineint)) + \"\\n\")\n\n # process nonsilence phones\n for nsp in sorted(self.nonsil_phones):\n if self.position_dependent_phones:\n mapped = [nsp + x for x in self.positions]\n else:\n mapped = [nsp]\n setf.write(\" \".join(mapped) + \"\\n\")\n setintf.write(\" \".join(map(str, (self.phone_mapping[x] for x in mapped))) + \"\\n\")\n line = sharesplit + mapped\n lineint = sharesplit + [self.phone_mapping[x] for x in mapped]\n rootf.write(\" \".join(line) + \"\\n\")\n rootintf.write(\" \".join(map(str, lineint)) + \"\\n\")\n\n def _write_extra_questions(self) -> None:\n \"\"\"\n Write extra questions symbols to the temporary directory\n \"\"\"\n phone_extra = os.path.join(self.phones_dir, \"extra_questions.txt\")\n phone_extra_int = os.path.join(self.phones_dir, \"extra_questions.int\")\n if os.path.exists(phone_extra) and os.path.exists(phone_extra_int):\n return\n with open(phone_extra, \"w\", encoding=\"utf8\") as outf, open(\n phone_extra_int, \"w\", encoding=\"utf8\"\n ) as intf:\n if self.position_dependent_phones:\n sils = sorted(self.positional_sil_phones)\n else:\n sils = sorted(self.sil_phones)\n outf.write(\" \".join(sils) + \"\\n\")\n intf.write(\" \".join(map(str, (self.phone_mapping[x] for x in sils))) + \"\\n\")\n\n if self.position_dependent_phones:\n nonsils = sorted(self.positional_nonsil_phones)\n else:\n nonsils = sorted(self.nonsil_phones)\n outf.write(\" \".join(nonsils) + \"\\n\")\n intf.write(\" \".join(map(str, (self.phone_mapping[x] for x in nonsils))) + \"\\n\")\n if self.position_dependent_phones:\n for p in self.positions:\n line = [x + p for x in sorted(self.nonsil_phones)]\n outf.write(\" \".join(line) + \"\\n\")\n intf.write(\" \".join(map(str, (self.phone_mapping[x] for x in line))) + \"\\n\")\n for p in [\"\"] + self.positions:\n line = [x + p for x in sorted(self.sil_phones)]\n outf.write(\" \".join(line) + \"\\n\")\n intf.write(\" \".join(map(str, (self.phone_mapping[x] for x in line))) + \"\\n\")\n\n def _write_disambig(self) -> None:\n \"\"\"\n Write disambiguation symbols to the temporary directory\n \"\"\"\n disambig = os.path.join(self.phones_dir, \"disambiguation_symbols.txt\")\n disambig_int = os.path.join(self.phones_dir, \"disambiguation_symbols.int\")\n if os.path.exists(disambig) and os.path.exists(disambig_int):\n return\n with open(disambig, \"w\", encoding=\"utf8\") as outf, open(\n disambig_int, \"w\", encoding=\"utf8\"\n ) as intf:\n for d in sorted(self.disambiguation_symbols, key=lambda x: self.phone_mapping[x]):\n outf.write(f\"{d}\\n\")\n intf.write(f\"{self.phone_mapping[d]}\\n\")\n\n def _write_fst_binary(self, write_disambiguation: Optional[bool] = False) -> None:\n \"\"\"\n Write the binary fst file to the temporary directory\n\n Parameters\n ----------\n write_disambiguation: bool, optional\n Flag for including disambiguation symbols\n \"\"\"\n if write_disambiguation:\n lexicon_fst_path = os.path.join(self.output_directory, \"lexicon_disambig.text.fst\")\n output_fst = os.path.join(self.output_directory, \"L_disambig.fst\")\n else:\n lexicon_fst_path = os.path.join(self.output_directory, \"lexicon.text.fst\")\n output_fst = os.path.join(self.output_directory, \"L.fst\")\n if os.path.exists(output_fst):\n return\n\n phones_file_path = os.path.join(self.output_directory, \"phones.txt\")\n words_file_path = os.path.join(self.output_directory, \"words.txt\")\n\n log_path = os.path.join(self.output_directory, \"fst.log\")\n temp_fst_path = os.path.join(self.output_directory, \"temp.fst\")\n with open(log_path, \"w\") as log_file:\n compile_proc = subprocess.Popen(\n [\n thirdparty_binary(\"fstcompile\"),\n f\"--isymbols={phones_file_path}\",\n f\"--osymbols={words_file_path}\",\n \"--keep_isymbols=false\",\n \"--keep_osymbols=false\",\n lexicon_fst_path,\n temp_fst_path,\n ],\n stderr=log_file,\n )\n compile_proc.communicate()\n if write_disambiguation:\n temp2_fst_path = os.path.join(self.output_directory, \"temp2.fst\")\n phone_disambig_path = os.path.join(self.output_directory, \"phone_disambig.txt\")\n word_disambig_path = os.path.join(self.output_directory, \"word_disambig.txt\")\n with open(phone_disambig_path, \"w\") as f:\n f.write(str(self.phone_mapping[\"#0\"]))\n with open(word_disambig_path, \"w\") as f:\n f.write(str(self.words_mapping[\"#0\"]))\n selfloop_proc = subprocess.Popen(\n [\n thirdparty_binary(\"fstaddselfloops\"),\n phone_disambig_path,\n word_disambig_path,\n temp_fst_path,\n temp2_fst_path,\n ],\n stderr=log_file,\n )\n selfloop_proc.communicate()\n arc_sort_proc = subprocess.Popen(\n [\n thirdparty_binary(\"fstarcsort\"),\n \"--sort_type=olabel\",\n temp2_fst_path,\n output_fst,\n ],\n stderr=log_file,\n )\n else:\n arc_sort_proc = subprocess.Popen(\n [\n thirdparty_binary(\"fstarcsort\"),\n \"--sort_type=olabel\",\n temp_fst_path,\n output_fst,\n ],\n stderr=log_file,\n )\n arc_sort_proc.communicate()\n\n def _write_fst_text(self, write_disambiguation: Optional[bool] = False) -> None:\n \"\"\"\n Write the text fst file to the temporary directory\n\n Parameters\n ----------\n write_disambiguation: bool, optional\n Flag for including disambiguation symbols\n \"\"\"\n if write_disambiguation:\n lexicon_fst_path = os.path.join(self.output_directory, \"lexicon_disambig.text.fst\")\n sildisambig = f\"#{self.max_disambiguation_symbol + 1}\"\n else:\n lexicon_fst_path = os.path.join(self.output_directory, \"lexicon.text.fst\")\n if os.path.exists(lexicon_fst_path):\n return\n if self.sil_prob != 0:\n silphone = self.optional_silence\n nonoptsil = self.nonoptional_silence\n\n silcost = -1 * math.log(self.sil_prob)\n nosilcost = -1 * math.log(1.0 - self.sil_prob)\n startstate = 0\n loopstate = 1\n silstate = 2\n else:\n loopstate = 0\n nextstate = 1\n\n with open(lexicon_fst_path, \"w\", encoding=\"utf8\") as outf:\n if self.sil_prob != 0:\n outf.write(\n \"\\t\".join(map(str, [startstate, loopstate, \"\", \"\", nosilcost]))\n + \"\\n\"\n ) # no silence\n\n outf.write(\n \"\\t\".join(map(str, [startstate, loopstate, nonoptsil, \"\", silcost]))\n + \"\\n\"\n ) # silence\n outf.write(\n \"\\t\".join(map(str, [silstate, loopstate, silphone, \"\"])) + \"\\n\"\n ) # no cost\n nextstate = 3\n if write_disambiguation:\n disambigstate = 3\n nextstate = 4\n outf.write(\n \"\\t\".join(\n map(str, [startstate, disambigstate, silphone, \"\", silcost])\n )\n + \"\\n\"\n ) # silence.\n outf.write(\n \"\\t\".join(map(str, [silstate, disambigstate, silphone, \"\", silcost]))\n + \"\\n\"\n ) # no cost.\n outf.write(\n \"\\t\".join(map(str, [disambigstate, loopstate, sildisambig, \"\"]))\n + \"\\n\"\n ) # silence disambiguation symbol.\n\n for w in sorted(self.words.keys()):\n if self.exclude_for_alignment(w):\n continue\n for pron in sorted(\n self.words[w],\n key=lambda x: (x[\"pronunciation\"], x[\"probability\"], x[\"disambiguation\"]),\n ):\n phones = list(pron[\"pronunciation\"])\n prob = pron[\"probability\"]\n disambig_symbol = pron[\"disambiguation\"]\n if self.position_dependent_phones:\n if len(phones) == 1:\n phones[0] += \"_S\"\n else:\n for i in range(len(phones)):\n if i == 0:\n phones[i] += \"_B\"\n elif i == len(phones) - 1:\n phones[i] += \"_E\"\n else:\n phones[i] += \"_I\"\n if not self.pronunciation_probabilities:\n pron_cost = 0\n else:\n if prob is None:\n prob = 1.0\n elif not prob:\n prob = 0.001 # Dithering to ensure low probability entries\n pron_cost = -1 * math.log(prob)\n\n pron_cost_string = \"\"\n if pron_cost != 0:\n pron_cost_string = f\"\\t{pron_cost}\"\n\n s = loopstate\n word_or_eps = w\n local_nosilcost = nosilcost + pron_cost\n local_silcost = silcost + pron_cost\n while len(phones) > 0:\n p = phones.pop(0)\n if len(phones) > 0 or (\n write_disambiguation and disambig_symbol is not None\n ):\n ns = nextstate\n nextstate += 1\n outf.write(\n \"\\t\".join(map(str, [s, ns, p, word_or_eps]))\n + pron_cost_string\n + \"\\n\"\n )\n word_or_eps = \"\"\n pron_cost_string = \"\"\n s = ns\n elif self.sil_prob == 0:\n ns = loopstate\n outf.write(\n \"\\t\".join(map(str, [s, ns, p, word_or_eps]))\n + pron_cost_string\n + \"\\n\"\n )\n word_or_eps = \"\"\n pron_cost_string = \"\"\n s = ns\n else:\n outf.write(\n \"\\t\".join(\n map(str, [s, loopstate, p, word_or_eps, local_nosilcost])\n )\n + \"\\n\"\n )\n outf.write(\n \"\\t\".join(map(str, [s, silstate, p, word_or_eps, local_silcost]))\n + \"\\n\"\n )\n if write_disambiguation and disambig_symbol is not None:\n outf.write(\n \"\\t\".join(\n map(\n str,\n [\n s,\n loopstate,\n f\"#{disambig_symbol}\",\n word_or_eps,\n local_nosilcost,\n ],\n )\n )\n + \"\\n\"\n )\n outf.write(\n \"\\t\".join(\n map(\n str,\n [\n s,\n silstate,\n f\"#{disambig_symbol}\",\n word_or_eps,\n local_silcost,\n ],\n )\n )\n + \"\\n\"\n )\n\n outf.write(f\"{loopstate}\\t0\\n\")\n\n\nclass MultispeakerDictionary(Dictionary):\n \"\"\"\n Class containing information about a pronunciation dictionary with different dictionaries per speaker\n\n Parameters\n ----------\n input_path : str\n Path to an input pronunciation dictionary\n output_directory : str\n Path to a directory to store files for Kaldi\n oov_code : str, optional\n What to label words not in the dictionary, defaults to ``''``\n position_dependent_phones : bool, optional\n Specifies whether phones should be represented as dependent on their\n position in the word (beginning, middle or end), defaults to True\n num_sil_states : int, optional\n Number of states to use for silence phones, defaults to 5\n num_nonsil_states : int, optional\n Number of states to use for non-silence phones, defaults to 3\n shared_silence_phones : bool, optional\n Specify whether to share states across all silence phones, defaults\n to True\n sil_prob : float, optional\n Probability of optional silences following words, defaults to 0.5\n word_set : Collection[str], optional\n Word set to limit output files\n debug: bool, optional\n Flag for whether to perform debug steps and prevent intermediate cleanup\n logger: :class:`~logging.Logger`, optional\n Logger to output information to\n punctuation: str, optional\n Punctuation to use when parsing text\n clitic_markers: str, optional\n Clitic markers to use when parsing text\n compound_markers: str, optional\n Compound markers to use when parsing text\n multilingual_ipa: bool, optional\n Flag for multilingual IPA mode, defaults to False\n strip_diacritics: List[str], optional\n Diacritics to strip in multilingual IPA mode\n digraphs: List[str], optional\n Digraphs to split up in multilingual IPA mode\n \"\"\"\n\n has_multiple = True\n\n def __init__(\n self,\n input_path: str,\n output_directory: str,\n oov_code: Optional[str] = \"\",\n position_dependent_phones: Optional[bool] = True,\n num_sil_states: Optional[int] = 5,\n num_nonsil_states: Optional[int] = 3,\n shared_silence_phones: Optional[bool] = True,\n sil_prob: Optional[float] = 0.5,\n word_set: Optional[List[str]] = None,\n debug: Optional[bool] = False,\n logger: Optional[Logger] = None,\n punctuation: PunctuationType = None,\n clitic_markers: PunctuationType = None,\n compound_markers: PunctuationType = None,\n multilingual_ipa: Optional[bool] = False,\n strip_diacritics: IpaType = None,\n digraphs: IpaType = None,\n ):\n self.multilingual_ipa = multilingual_ipa\n self.strip_diacritics = DEFAULT_STRIP_DIACRITICS\n self.digraphs = DEFAULT_DIGRAPHS\n if strip_diacritics is not None:\n self.strip_diacritics = strip_diacritics\n if digraphs is not None:\n self.digraphs = digraphs\n self.punctuation = DEFAULT_PUNCTUATION\n self.clitic_markers = DEFAULT_CLITIC_MARKERS\n self.compound_markers = DEFAULT_COMPOUND_MARKERS\n if punctuation is not None:\n self.punctuation = punctuation\n if clitic_markers is not None:\n self.clitic_markers = clitic_markers\n if compound_markers is not None:\n self.compound_markers = compound_markers\n self.input_path = input_path\n self.debug = debug\n self.output_directory = os.path.join(output_directory, \"dictionary\")\n os.makedirs(self.output_directory, exist_ok=True)\n self.log_file = os.path.join(self.output_directory, \"dictionary.log\")\n if logger is None:\n self.logger = logging.getLogger(\"dictionary_setup\")\n self.logger.setLevel(logging.INFO)\n handler = logging.FileHandler(self.log_file, \"w\", \"utf-8\")\n handler.setFormatter = logging.Formatter(\"%(name)s %(message)s\")\n self.logger.addHandler(handler)\n else:\n self.logger = logger\n self.num_sil_states = num_sil_states\n self.num_nonsil_states = num_nonsil_states\n self.shared_silence_phones = shared_silence_phones\n self.sil_prob = sil_prob\n self.oov_code = oov_code\n self.sil_code = \"!sil\"\n self.oovs_found = Counter()\n self.position_dependent_phones = position_dependent_phones\n self.max_disambiguation_symbol = 0\n self.disambiguation_symbols = set()\n self.optional_silence = \"sp\"\n self.nonoptional_silence = \"sil\"\n\n if word_set is not None:\n word_set = {sanitize(x, self.punctuation, self.clitic_markers) for x in word_set}\n word_set.add(\"!sil\")\n word_set.add(self.oov_code)\n self.word_set = word_set\n\n if not os.path.exists(input_path):\n raise (DictionaryPathError(input_path))\n if not os.path.isfile(input_path):\n raise (DictionaryFileError(input_path))\n\n self.speaker_mapping = {}\n self.dictionary_mapping = {}\n self.logger.info(\"Parsing multispeaker dictionary file\")\n available_langs = get_available_dictionaries()\n with open(input_path, \"r\", encoding=\"utf8\") as f:\n data = yaml.safe_load(f)\n for speaker, path in data.items():\n if path in available_langs:\n path = get_dictionary_path(path)\n dictionary_name = os.path.splitext(os.path.basename(path))[0]\n self.speaker_mapping[speaker] = dictionary_name\n if dictionary_name not in self.dictionary_mapping:\n self.dictionary_mapping[dictionary_name] = Dictionary(\n path,\n output_directory,\n oov_code=self.oov_code,\n position_dependent_phones=self.position_dependent_phones,\n word_set=self.word_set,\n num_sil_states=self.num_sil_states,\n num_nonsil_states=self.num_nonsil_states,\n shared_silence_phones=self.shared_silence_phones,\n sil_prob=self.sil_prob,\n debug=self.debug,\n logger=self.logger,\n punctuation=self.punctuation,\n clitic_markers=self.clitic_markers,\n compound_markers=self.compound_markers,\n multilingual_ipa=self.multilingual_ipa,\n strip_diacritics=self.strip_diacritics,\n digraphs=self.digraphs,\n )\n\n self.nonsil_phones = set()\n self.sil_phones = {\"sp\", \"spn\", \"sil\"}\n self.words = set()\n self.clitic_set = set()\n for d in self.dictionary_mapping.values():\n self.nonsil_phones.update(d.nonsil_phones)\n self.sil_phones.update(d.sil_phones)\n self.words.update(d.words)\n self.clitic_set.update(d.clitic_set)\n self.words_mapping = {}\n self.phone_mapping = {}\n\n @property\n def silences(self) -> set:\n \"\"\"\n Set of silence phones\n \"\"\"\n return {self.optional_silence, self.nonoptional_silence}\n\n def get_dictionary_name(self, speaker: Union[str, Speaker]) -> str:\n \"\"\"\n Get the dictionary name for a given speaker\n\n Parameters\n ----------\n speaker: Union[Speaker, str]\n Speaker to look up\n\n Returns\n -------\n str\n Dictionary name for the speaker\n \"\"\"\n if not isinstance(speaker, str):\n speaker = speaker.name\n if speaker not in self.speaker_mapping:\n return self.speaker_mapping[\"default\"]\n return self.speaker_mapping[speaker]\n\n def get_dictionary(self, speaker: Union[Speaker, str]) -> Dictionary:\n \"\"\"\n Get a dictionary for a given speaker\n\n Parameters\n ----------\n speaker: Union[Speaker, str]\n Speaker to look up\n\n Returns\n -------\n Dictionary\n Dictionary for the speaker\n \"\"\"\n return self.dictionary_mapping[self.get_dictionary_name(speaker)]\n\n def generate_mappings(self) -> None:\n \"\"\"\n Generate phone and word mappings from text to integer IDs\n \"\"\"\n self.phone_mapping = {}\n i = 0\n self.phone_mapping[\"\"] = i\n if self.position_dependent_phones:\n for p in self.positional_sil_phones:\n i += 1\n self.phone_mapping[p] = i\n for p in self.positional_nonsil_phones:\n i += 1\n self.phone_mapping[p] = i\n else:\n for p in sorted(self.sil_phones):\n i += 1\n self.phone_mapping[p] = i\n for p in sorted(self.nonsil_phones):\n i += 1\n self.phone_mapping[p] = i\n\n self.words_mapping = {}\n i = 0\n self.words_mapping[\"\"] = i\n for w in sorted(self.words):\n if self.exclude_for_alignment(w):\n continue\n i += 1\n self.words_mapping[w] = i\n\n self.words_mapping[\"#0\"] = i + 1\n self.words_mapping[\"\"] = i + 2\n self.words_mapping[\"\"] = i + 3\n self.words.update([\"\", \"#0\", \"\", \"\"])\n self.oovs_found = Counter()\n self.max_disambiguation_symbol = 0\n for d in self.dictionary_mapping.values():\n d.generate_mappings()\n if d.max_disambiguation_symbol > self.max_disambiguation_symbol:\n self.max_disambiguation_symbol = d.max_disambiguation_symbol\n i = max(self.phone_mapping.values())\n self.disambiguation_symbols = set()\n for x in range(self.max_disambiguation_symbol + 2):\n p = f\"#{x}\"\n self.disambiguation_symbols.add(p)\n i += 1\n self.phone_mapping[p] = i\n\n def write(self, write_disambiguation: Optional[bool] = False) -> None:\n \"\"\"\n Write all child dictionaries to the temporary directory\n\n Parameters\n ----------\n write_disambiguation: bool, optional\n Flag to use disambiguation symbols in the output\n \"\"\"\n os.makedirs(self.phones_dir, exist_ok=True)\n self.generate_mappings()\n for d in self.dictionary_mapping.values():\n d.phone_mapping = self.phone_mapping\n d.write(write_disambiguation)\n\n @property\n def output_paths(self) -> Dict[str, str]:\n \"\"\"\n Mapping of output directory for child dictionaries\n \"\"\"\n return {d.name: d.output_directory for d in self.dictionary_mapping.values()}\n\n\nif TYPE_CHECKING:\n DictionaryType = Union[MultispeakerDictionary, Dictionary]\n","sub_path":"montreal_forced_aligner/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":69407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"214069808","text":"from __future__ import division\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import axes_grid1 # For colorbars\n\nfrom scipy.ndimage import grey_dilation\n\nfrom skimage import img_as_float\nfrom skimage import color\nfrom skimage import exposure\nfrom skimage.util.dtype import dtype_limits\n\nfrom matplotlib.colors import NoNorm, BoundaryNorm, ListedColormap\nfrom matplotlib import cm\nfrom matplotlib.cm import ScalarMappable, get_cmap\n\n\n__all__ = ['imshow_all', 'imshow_with_histogram', 'mean_filter_demo',\n 'mean_filter_interactive_demo', 'plot_cdf', 'plot_histogram', 'colorbars','add_colorbar','match_axes_height', 'scatter_matrix',\n 'discrete_cmap', \n 'discrete_colorbar', 'show_segmentation', 'show_features']\n\n\n# Gray-scale images should actually be gray!\nplt.rcParams['image.cmap'] = 'gray'\n\n\n#--------------------------------------------------------------------------\n# Custom `imshow` functions\n#--------------------------------------------------------------------------\n\ndef imshow_rgb_shifted(rgb_image, shift=100, ax=None):\n \"\"\"Plot each RGB layer with an x, y shift.\"\"\"\n if ax is None:\n ax = plt.gca()\n\n height, width, n_channels = rgb_image.shape\n x = y = 0\n for i_channel, channel in enumerate(iter_channels(rgb_image)):\n image = np.zeros((height, width, n_channels), dtype=channel.dtype)\n\n image[:, :, i_channel] = channel\n ax.imshow(image, extent=[x, x+width, y, y+height], alpha=0.7)\n x += shift\n y += shift\n # `imshow` fits the extents of the last image shown, so we need to rescale.\n ax.autoscale()\n ax.set_axis_off()\n\n\ndef imshow_all(*images, **kwargs):\n \"\"\" Plot a series of images side-by-side.\n\n Convert all images to float so that images have a common intensity range.\n\n Parameters\n ----------\n limits : str\n Control the intensity limits. By default, 'image' is used set the\n min/max intensities to the min/max of all images. Setting `limits` to\n 'dtype' can also be used if you want to preserve the image exposure.\n titles : list of str\n Titles for subplots. If the length of titles is less than the number\n of images, empty strings are appended.\n kwargs : dict\n Additional keyword-arguments passed to `imshow`.\n \"\"\"\n images = [img_as_float(img) for img in images]\n\n titles = kwargs.pop('titles', [])\n if len(titles) != len(images):\n titles = list(titles) + [''] * (len(images) - len(titles))\n\n limits = kwargs.pop('limits', 'image')\n if limits == 'image':\n kwargs.setdefault('vmin', min(img.min() for img in images))\n kwargs.setdefault('vmax', max(img.max() for img in images))\n elif limits == 'dtype':\n vmin, vmax = dtype_limits(images[0])\n kwargs.setdefault('vmin', vmin)\n kwargs.setdefault('vmax', vmax)\n\n nrows, ncols = kwargs.get('shape', (1, len(images)))\n\n size = nrows * kwargs.pop('size', 5)\n width = size * len(images)\n if nrows > 1:\n width /= nrows * 1.33\n fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(width, size))\n for ax, img, label in zip(axes.ravel(), images, titles):\n ax.imshow(img, **kwargs)\n ax.set_title(label)\n\n\ndef imshow_with_histogram(image, xlim=None, **kwargs):\n \"\"\" Plot an image side-by-side with its histogram.\n\n - Plot the image next to the histogram\n - Plot each RGB channel separately (if input is color)\n - Automatically flatten channels\n - Select reasonable bins based on the image's dtype\n\n See `plot_histogram` for information on how the histogram is plotted.\n \"\"\"\n width, height = plt.rcParams['figure.figsize']\n fig, (ax_image, ax_hist) = plt.subplots(ncols=2, figsize=(2*width, height))\n\n kwargs.setdefault('cmap', plt.cm.gray)\n ax_image.imshow(image, **kwargs)\n plot_histogram(image, ax=ax_hist, xlim=xlim)\n\n # pretty it up\n ax_image.set_axis_off()\n match_axes_height(ax_image, ax_hist)\n return ax_image, ax_hist\n\n\n#--------------------------------------------------------------------------\n# Helper functions\n#--------------------------------------------------------------------------\n\ndef add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs):\n \"\"\"Add a vertical color bar to an image plot.\n \n See https://stackoverflow.com/a/33505522\"\"\"\n divider = axes_grid1.make_axes_locatable(im.axes)\n width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect)\n pad = axes_grid1.axes_size.Fraction(pad_fraction, width)\n current_ax = plt.gca()\n cax = divider.append_axes(\"right\", size=width, pad=pad)\n plt.sca(current_ax)\n return im.axes.figure.colorbar(im, cax=cax, **kwargs)\n\ndef colorbars(axes=None, fig=None, return_handles=False, \n aspect=20, pad_fraction=0.5, **kwargs):\n # Add colorbars to all axes that contain an image\n # axes: Axes object or list of Axes\n # fig: if axes is None, figure from which to extract axes\n # Returns a list of Colorbar objects\n if (axes==None):\n if (fig==None):\n fig = plt.gcf()\n axes=fig.axes\n if (type(axes) is list):\n cbars=[]\n for ax in plt.gcf().axes:\n cbars.extend(colorbars(ax, return_handles=True))\n else:\n imgs=axes.images\n if (len(imgs)>0):\n #return [plt.colorbar(imgs[0],ax=axes)] # Use first image from the axes\n cbars=[add_colorbar(imgs[0],aspect=aspect, pad_fraction=pad_fraction, **kwargs)]\n else:\n cbars=[]\n if return_handles: \n return cbars\n else: \n return\n\ndef match_axes_height(ax_src, ax_dst):\n \"\"\" Match the axes height of two axes objects.\n\n The height of `ax_dst` is synced to that of `ax_src`.\n \"\"\"\n # HACK: plot geometry isn't set until the plot is drawn\n plt.draw()\n dst = ax_dst.get_position()\n src = ax_src.get_position()\n ax_dst.set_position([dst.xmin, src.ymin, dst.width, src.height])\n\n\ndef plot_cdf(image, ax=None, xlim=None):\n img_cdf, bins = exposure.cumulative_distribution(image)\n ax.plot(bins, img_cdf, 'r')\n ax.set_ylabel(\"Fraction of pixels below intensity\")\n if (xlim is None):\n if (image.dtype=='uint8'):\n ax.set_xlim(0,255)\n else:\n ax.set_xlim(xlim[0],xlim[1])\n\n\ndef plot_histogram(image, ax=None, xlim=None, **kwargs):\n \"\"\" Plot the histogram of an image (gray-scale or RGB) on `ax`.\n\n Calculate histogram using `skimage.exposure.histogram` and plot as filled\n line. If an image has a 3rd dimension, assume it's RGB and plot each\n channel separately.\n \"\"\"\n ax = ax if ax is not None else plt.gca()\n \n\n if image.ndim == 2:\n _plot_histogram(ax, image, color='black', **kwargs)\n elif image.ndim == 3:\n # `channel` is the red, green, or blue channel of the image.\n for channel, channel_color in zip(iter_channels(image), 'rgb'):\n _plot_histogram(ax, channel, color=channel_color, **kwargs)\n\n if (xlim is None):\n if (image.dtype=='uint8'):\n ax.set_xlim(0,255)\n else:\n ax.set_xlim(xlim[0],xlim[1])\n\n\ndef _plot_histogram(ax, image, alpha=0.3, **kwargs):\n # Use skimage's histogram function which has nice defaults for\n # integer and float images.\n hist, bin_centers = exposure.histogram(image)\n ax.fill_between(bin_centers, hist, alpha=alpha, **kwargs)\n ax.set_xlabel('intensity')\n ax.set_ylabel('# pixels')\n\n\ndef iter_channels(color_image):\n \"\"\"Yield color channels of an image.\"\"\"\n # Roll array-axis so that we iterate over the color channels of an image.\n for channel in np.rollaxis(color_image, -1):\n yield channel\n\n\n#--------------------------------------------------------------------------\n# Convolution Demo\n#--------------------------------------------------------------------------\n\ndef mean_filter_demo(image, vmax=1):\n mean_factor = 1.0 / 9.0 # This assumes a 3x3 kernel.\n iter_kernel_and_subimage = iter_kernel(image)\n\n image_cache = []\n\n def mean_filter_step(i_step):\n while i_step >= len(image_cache):\n filtered = image if i_step == 0 else image_cache[-1][1]\n filtered = filtered.copy()\n\n (i, j), mask, subimage = iter_kernel_and_subimage.next()\n filter_overlay = color.label2rgb(mask, image, bg_label=0,\n colors=('yellow', 'red'))\n filtered[i, j] = np.sum(mean_factor * subimage)\n image_cache.append((filter_overlay, filtered))\n\n imshow_all(*image_cache[i_step], vmax=vmax)\n plt.show()\n return mean_filter_step\n\n\ndef mean_filter_interactive_demo(image):\n from IPython.html import widgets\n mean_filter_step = mean_filter_demo(image)\n step_slider = widgets.IntSliderWidget(min=0, max=image.size-1, value=0)\n widgets.interact(mean_filter_step, i_step=step_slider)\n\n\ndef iter_kernel(image, size=1):\n \"\"\" Yield position, kernel mask, and image for each pixel in the image.\n\n The kernel mask has a 2 at the center pixel and 1 around it. The actual\n width of the kernel is 2*size + 1.\n \"\"\"\n width = 2*size + 1\n for (i, j), pixel in iter_pixels(image):\n mask = np.zeros(image.shape, dtype='int16')\n mask[i, j] = 1\n mask = grey_dilation(mask, size=width)\n mask[i, j] = 2\n subimage = image[bounded_slice((i, j), image.shape[:2], size=size)]\n yield (i, j), mask, subimage\n\n\ndef iter_pixels(image):\n \"\"\" Yield pixel position (row, column) and pixel intensity. \"\"\"\n height, width = image.shape[:2]\n for i in range(height):\n for j in range(width):\n yield (i, j), image[i, j]\n\n\ndef bounded_slice(center, xy_max, size=1, i_min=0):\n slices = []\n for i, i_max in zip(center, xy_max):\n slices.append(slice(max(i - size, i_min), min(i + size + 1, i_max)))\n return slices\n \n#-------------------------------------------------------------------------\n# Classification demo\n#-------------------------------------------------------------------------\n\nfrom matplotlib.colors import Normalize, colorConverter\n\ndef discrete_cmap(N=8, colors=None, cmap='viridis', norm=None, \n use_bounds=False, zero=None):\n if (colors is None):\n if (norm is None):\n if (use_bounds):\n norm=Normalize(vmin=0, vmax=N-1)\n else:\n norm=Normalize(vmin=-0.5, vmax=N-0.5)\n sm=cm.ScalarMappable(cmap=cmap,norm=norm)\n cols=sm.to_rgba(range(N))[:,:3]\n else:\n cols=colors\n N=len(colors) # Number of rows\n \n if (zero is not None):\n zcol=colorConverter.to_rgb(zero)\n cols=np.insert(cols,0,zcol, axis=0)\n return ListedColormap(cols)\n\ndef discrete_colorbar(colors, labels=None, ax=None, cax=None):\n \"\"\"\n Add a discrete colorbar with custom colors to current axes.\n \n Parameters:\n \n colors: list of RGB tuple\n \n labels: list of tick labels\n assume ticks are at range(len(labels))\n \"\"\"\n N=len(colors)\n vmin=0; vmax=N-1;\n norm = BoundaryNorm(np.arange(-0.5+vmin,vmax+1.5,1), N)\n s=ScalarMappable(norm=norm, cmap=ListedColormap(colors))\n s.set_array(range(N))\n cb=plt.colorbar(mappable=s, ticks=range(vmin,vmax+1), ax=ax, cax=cax)\n cb.set_norm(norm)\n plt.clim(-0.5+vmin, vmax + 0.5)\n cbticks = plt.getp(cb.ax.axes, 'yticklines')\n plt.setp(cbticks, visible=False)\n if (labels is not None):\n cb.set_ticklabels(labels)\n return cb\n \ndef scatter_matrix(data, c=None, labels=None, title=None, cmap='viridis', norm=None,\n figsize=(6,4), show_colorbar=False, class_labels=None):\n '''\n Equivalent of pandas.scatter_matrix or seaborne.pairplot\n '''\n from matplotlib import cm\n nb_features = data.shape[1]\n if (labels is None):\n labels=['Feature {}'.format(i) for i in range(nb_features)]\n if (len(labels)!=nb_features):\n raise ValueError('labels of length {} should have same size as data rows {}'.format(len(labels),nb_features))\n if (data.shape[0]0 and j=4 and last!=None:\n winner = last\n else:\n streak = 1\n last = j\n return winner\n\n\n def check_diag_down(self):\n streak = 0\n last = None\n winner = None\n for i in range(0,len(self.board)-4):\n for j in range(0, len(self.board[i]) -4):\n for k in range(4):\n streak = 0\n last = None\n if self.board[i+k][j+k] == last:\n streak+=1\n if streak >=4 and last!=None:\n return last\n else:\n streak = 1\n last = self.board[i+k][j+k]\n return winner\n\n def check_diag_up(self):\n streak = 0\n last = None\n winner = None\n for i in range(0,len(self.board)-4):\n for j in range(len(self.board[i])-1, 3, -1):\n streak = 0\n last = None\n for k in range(4):\n if self.board[i+k][j-k] == last:\n streak+=1\n if streak >=4 and last!=None:\n return last\n else:\n streak = 1\n last = self.board[i+k][j-k]\n return winner\n\n\n def checkall(self):\n winner = self.check_vertical()\n if winner != None:\n return winner\n winner = self.check_horizontal()\n if winner != None:\n return winner\n winner = self.check_diag_down()\n if winner != None:\n return winner\n winner = self.check_diag_up()\n if winner != None:\n return winner\n return None\n\n\n def addp1(self, x):\n self.board[x][self.tops[x]] = 1\n self.tops[x]+=1\n\n\n def addp2(self,x):\n self.board[x][self.tops[x]] = 2\n self.tops[x] +=1\n","sub_path":"c4.py","file_name":"c4.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"148435087","text":"from ChestClinic import *\nfrom Fire import *\n\n\ndef calculate_KLdistance_from_a_network(type_of_network, file_path, n_occorrences):\n network = type_of_network(file_path)\n network.build_graph()\n network.graph_build_occorrences()\n network.graph_count_occorrences(n_occorrences)\n network.graph_build_probabilities()\n network.build_real_distribution()\n return network.calculate_Kullback_Leibler_distance()\n\n\ndef test_FireNetwork_changing_n_occorences():\n n_occorences = 100\n result = []\n occ = []\n\n while n_occorences <= 1000000:\n result.append(calculate_KLdistance_from_a_network(Fire, \"fire.dat\", n_occorences))\n occ.append(n_occorences)\n n_occorences *= 10\n print(\"I risultati dell'apprendimento della FireNetwork valutati mediante la divergenza di Kullback-Leibler sono:\")\n for i in range(len(result)):\n print('L\\'apprendimento con un dataset di dimensione {} ha una divergenza pari a {}'.format(occ[i],\n \"{0:.5f}\".format(\n result[i])))\n\n\ndef test_ChestClinicNetwork_changing_n_occorences():\n n_occorences = 100\n result = []\n occ = []\n\n while n_occorences <= 1000000:\n result.append(calculate_KLdistance_from_a_network(ChestClinic, \"chestclinic.dat\", n_occorences))\n occ.append(n_occorences)\n n_occorences *= 10\n print(\n \"I risultati dell'apprendimento della ChestClinicNetwork valutati mediante la divergenza di Kullback-Leibler sono:\")\n for i in range(len(result)):\n print('L\\'apprendimento con un dataset di dimensione {} ha una divergenza pari a {}'.format(occ[i],\n \"{0:.5f}\".format(\n result[i])))\n\n\ntest_FireNetwork_changing_n_occorences()\ntest_ChestClinicNetwork_changing_n_occorences()\n","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"53700587","text":"from django.urls import path\nfrom userlogin import views\n\n\nurlpatterns = [\n path('register/',views.Register, name='Register'),\n path('login/',views.Login, name='login'),\n path('home/',views.Home, name='home'),\n path('base/',views.base, name='base'),\n]","sub_path":"userlogin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"459210970","text":"def to_rna(nutides):\n '''Takes a DNA strand and converts it to its complement RNA strand\n\n keyword arguments:\n nutides -- the DNA nucleotide to be transcribed\n\n returns string\n\n '''\n rna = {'C': 'G', 'G': 'C', 'A': 'T', 'U': 'A'}\n transcribed = [] \n \n for x in nutides: \n [transcribed.append(k) for k, v in rna.items() if x == v]\n\n return ''.join(transcribed)\n","sub_path":"python/rna-transcription/dna.py","file_name":"dna.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"631960459","text":"import pandas as pd\nimport numpy as np\nimport collections\nfrom matplotlib import pyplot as plt\nfrom matplotlib import colors\nimport matplotlib.cm as cmx\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pandas as pd\n\ndef Trans(cam_coords):\n return np.matrix([[1, 0, 0, -cam_coords[0]],\n [0, 1, 0, -cam_coords[1]],\n [0, 0, 1, -cam_coords[2]],\n [0, 0, 0, 1]])\n\ndef R_yaw_trans(yaw):\n return np.matrix([[np.cos(yaw), -np.sin(yaw), 0, 0],\n [np.sin(yaw), np.cos(yaw), 0, 0],\n [ 0, 0, 1, 0]])\n\ndef R_pitch_trans(pitch):\n return np.matrix([[1, 0, 0],\n [0, np.cos(pitch), np.sin(pitch)],\n [0, -np.sin(pitch), np.cos(pitch)]])\n\ndef R_roll_trans(roll):\n return np.matrix([[np.cos(roll), 0, -np.sin(roll)],\n [0, 1, 0],\n [np.sin(roll), 0, np.cos(roll)]])\n\ndef R_axis_trans():\n return np.matrix([[1, 0, 0],\n [0, 0,-1],\n [0, 1, 0]])\n\ndef rotate(pose, X_world):\n #camera coords [easting, northing, elevation, yaw, pitch ,roll]\n easting = pose[0]\n northing = pose[1]\n elevation = pose[2]\n cam_coords = np.array([easting, northing, elevation])\n\n #camera angle\n yaw = pose[3] # radians\n pitch = pose[4] # radians\n roll = pose[5] # radians\n\n\n T = Trans(cam_coords)\n R_yaw = R_yaw_trans(yaw)\n R_pitch = R_pitch_trans(pitch)\n R_roll = R_roll_trans(roll)\n R_axis = R_axis_trans()\n C = R_axis.dot(R_roll).dot(R_pitch).dot(R_yaw).dot(T)\n x = []\n y = []\n z = []\n I = []\n\n for index, coord in X_world.iterrows():\n np_coord = np.array(coord)\n np_coord = np.append(coord, 1)\n xyz_coords = C.dot(np_coord).T\n x.append(xyz_coords.item(0))\n y.append(xyz_coords.item(1))\n z.append(xyz_coords.item(2))\n\n return x, y, z\n\n #############################################################################\n ############################## MAIN ###############################\n #############################################################################\n","sub_path":"project1/rotation.py","file_name":"rotation.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"218977883","text":"# グレースケール化\nimport cv2\nimport numpy as np\n\nimg = cv2.imread(\"source/imori.jpg\")\n\nb = img[:, :, 0]\ng = img[:, :, 1] \nr = img[:, :, 2]\n\ngray = np.array(0.2126*r + 0.7152*g + 0.0722*b, dtype='uint8')\n\ncv2.imwrite(\"answer/answer_Q2.jpg\", gray)\n","sub_path":"Q1-10/Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"3794495","text":"# Put your name and student ID here before submitting!\n# Otto Mättas (6324363)\n\nimport game as g\nfrom random_agent import RandomAgent\n\nimport random\nimport copy\nimport time\nimport numpy as np\n\nclass BanditAgent():\n def __init__(self, timelimit, id):\n self.timelimit = timelimit\n self.id = id\n\n def make_move(self, g):\n start = time.perf_counter()\n number_of_possible_moves = len(g.board.free_positions())\n \n # Create arrays for evaluating the position\n position_win_probability = np.zeros(number_of_possible_moves)\n position_score = np.zeros(number_of_possible_moves)\n position_counter = np.zeros(number_of_possible_moves)\n\n # Check for free positions\n free_positions = g.board.free_positions()\n #print(\"Free positions:\\n\", free_positions)\n\n # run until time is up\n while time.perf_counter() - start < self.timelimit / 1000:\n\n #################\n # Start rollout #\n #################\n\n # Copy the board for simulation\n b = copy.deepcopy(g.board)\n #print(\"Deepcopy:\\n\", b)\n\n # Set epsilon\n epsilon = (time.perf_counter() - start) / (self.timelimit / 1000)\n #print(\"Epsilon is: \",epsilon)\n \n # Select a greedy move\n if random.random() > epsilon:\n # Find the index of highest probability\n index = np.argmax(position_win_probability)\n #print('Returned index of highest probability :', highest_probability_index)\n \n # Select the move\n selected_move = free_positions[index]\n #print(\"Selected greedy move:\", selected_move)\n\n # Select a random move\n else:\n # Create an index for the move\n index = random.randrange(0, len(free_positions))\n\n # Select a random move\n selected_move = free_positions[index]\n #print(\"Selected random move:\", selected_move)\n\n # Take the move on the copied board\n b.place(selected_move, self.id)\n\n # Set parameters for simulation\n simulation_players = [RandomAgent(2), RandomAgent(1)]\n simulation_game = g.from_board(b, g.objectives, simulation_players, g.print_board)\n\n # Check if there is already a winner\n if simulation_game.victory(selected_move, self.id) == False:\n # Simulate and determine the winner\n winner = simulation_game.play()\n #print(\"Simulation END:\\n\", b, \"\\nWinner is: \", winner)\n else:\n winner = self\n \n # Give values to states\n # winner==True\n if winner:\n # if player 1 , value 1\n if winner.id == 1:\n position_score[index] += 1\n #print(\"position_score after win\", position_score[index])\n\n # if player 2, value -1\n else:\n position_score[index] -= 1\n #print(\"position_score after loss\", position_score[index])\n\n # winner==False\n else:\n # if draw, value 0\n position_score[index] += 0\n #print(\"position_score after draw\", position_score[index])\n\n # Count the times a position is visited\n position_counter[index] += 1\n #print(\"position_counter is\", position_counter[index])\n\n # Calculate average position value\n position_win_probability[index] = position_score[index] / position_counter[index]\n #print(\"Average value is\", position_win_probability[index])\n\n # Find the highest probability index\n highest_probability_index = np.argmax(position_win_probability)\n #print('Returned tuple of highest probabilities :', highest_probability)\n \n # Select the move\n selected_move = free_positions[highest_probability_index]\n #print(\"Selected greedy move:\", selected_move) \n \n # return the best move you've found here\n return selected_move\n\n def __str__(self):\n return f'Player {self.id} (BanditAgent)'\n","sub_path":"3_nn-agent-1/bandit_agent.py","file_name":"bandit_agent.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"460247729","text":"from classytags.arguments import Argument\nfrom classytags.core import Options\nfrom classytags.helpers import AsTag\nfrom cms.utils.plugins import get_plugins\nfrom cms.utils.urlutils import admin_reverse\nfrom django import template\n\nfrom djangocms_blog.models import PostContent\n\nregister = template.Library()\n\n\n@register.simple_tag(name=\"media_plugins\", takes_context=True)\ndef media_plugins(context, post_content):\n \"\"\"\n Extract :py:class:`djangocms_blog.media.base.MediaAttachmentPluginMixin`\n plugins from the ``media`` placeholder of the provided post.\n\n They can be rendered with ``render_plugin`` templatetag:\n\n .. code-block: python\n\n {% media_plugins post as media_plugins %}\n {% for plugin in media_plugins %}{% render_plugin plugin %}{% endfor %}\n\n :param context: template context\n :type context: dict\n :param post: post instance\n :type post: :py:class:`djangocms_blog.models.Post`\n :return: list of :py:class:`djangocms_blog.media.base.MediaAttachmentPluginMixin` plugins\n :rtype: List[djangocms_blog.media.base.MediaAttachmentPluginMixin]\n \"\"\"\n if post_content and post_content.media and post_content.media.get_plugins().exists():\n return get_plugins(context[\"request\"], post_content.media, None)\n return []\n\n\n@register.simple_tag(name=\"media_images\", takes_context=True)\ndef media_images(context, post_content, main=True):\n \"\"\"\n Extract images of the given size from all the\n :py:class:`djangocms_blog.media.base.MediaAttachmentPluginMixin`\n plugins in the ``media`` placeholder of the provided post.\n\n Support ``djangocms-video`` ``poster`` field in case the plugin\n does not implement ``MediaAttachmentPluginMixin`` API.\n\n Usage:\n\n .. code-block: python\n\n {% media_images post False as thumbs %}\n {% for thumb in thumbs %}{% endfor %}\n\n .. code-block: python\n\n {% media_images post as main_images %}\n {% for image in main_images %}{% endfor %}\n\n :param context: template context\n :type context: dict\n :param post: post instance\n :type post: :py:class:`djangocms_blog.models.Post`\n :param main: retrieve main image or thumbnail\n :type main: bool\n :return: list of images urls\n :rtype: list\n \"\"\"\n plugins = media_plugins(context, post_content)\n if main:\n image_method = \"get_main_image\"\n else:\n image_method = \"get_thumb_image\"\n images = []\n for plugin in plugins:\n try:\n images.append(getattr(plugin, image_method)())\n except Exception:\n try:\n image = plugin.poster\n if image:\n images.append(image.url)\n except AttributeError:\n pass\n return images\n\n\nclass GetAbsoluteUrl(AsTag):\n \"\"\"Classy tag that returns the url for editing PageContent in the admin.\"\"\"\n name = \"absolute_url\"\n post_content_type = None\n\n options = Options(\n Argument('post_content'),\n Argument(\"language\", required=False, default=None),\n 'as',\n Argument('varname', required=False, resolve=False)\n )\n\n def get_value(self, context, post_content, language):\n if not post_content:\n return \"\"\n\n toolbar = getattr(context[\"request\"], \"toolbar\", None)\n if toolbar:\n if toolbar.edit_mode_active:\n return self.endpoint_url(\"cms_placeholder_render_object_edit\", post_content)\n if toolbar.preview_mode_active:\n return self.endpoint_url(\"cms_placeholder_render_object_preview\", post_content)\n return post_content.get_absolute_url(language)\n\n @staticmethod\n def endpoint_url(admin, obj):\n if GetAbsoluteUrl.post_content_type is None:\n # Use class as cache\n from django.contrib.contenttypes.models import ContentType\n\n GetAbsoluteUrl.post_content_type = ContentType.objects.get_for_model(PostContent).pk\n return admin_reverse(admin, args=[GetAbsoluteUrl.post_content_type, obj.pk])\n\n\nregister.tag(GetAbsoluteUrl.name, GetAbsoluteUrl)\n","sub_path":"djangocms_blog/templatetags/djangocms_blog.py","file_name":"djangocms_blog.py","file_ext":"py","file_size_in_byte":4127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"595652236","text":"from django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\n# from z_mine.request.routers import router\nfrom request.viewsFolder import invoice_views\napp_name = 'invoice'\nurlpatterns = [\n path('form', invoice_views.form, name='pro_form'),\n path('index', invoice_views.invoice_index, name='invoice_index'),\n path('find', invoice_views.invoice_find, name='invoice_find'),\n path('/', include([\n path('', invoice_views.invoice_details, name='invoice_details'),\n path('delete', invoice_views.invoice_delete, name='invoice_delete'),\n path('edit', invoice_views.invoice_edit, name='invoice_edit'),\n ])),\n ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL,\n document_root=settings.STATIC_ROOT)\n","sub_path":"app/request/urls/invoice_url.py","file_name":"invoice_url.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"364422706","text":"import sys\nimport glob\nimport datetime\nfrom pymongo import MongoClient\nimport json\n\n\ndef f0010main(json_folder,mongo_database , mongo_collection, mongo_host, mongo_port):\n client = MongoClient(mongo_host, int(mongo_port))\n db = client[mongo_database]\n\n path = '{}/*.json'.format(json_folder)\n i=0\n start = datetime.datetime.now()\n for fname in glob.glob(path):\n i=i+1\n print(\"{}: {}\".format(i, fname))\n with open(fname) as f:\n data = json.load(f)\n db[mongo_collection].insert_one(data)\n end = datetime.datetime.now()\n print('{} files are imported into {}.{}'.format(i, mongo_database, mongo_collection))\n print('Completed in {}'.format(end - start))\n print('Done!')\n\nif __name__ == \"__main__\":\n print(\"Arg1 (JSON Folder): {}\".format(sys.argv[1]))\n print(\"Arg2 (MongoDB Database): {}\".format(sys.argv[2]))\n print(\"Arg3 (MongoDB Collection): {}\".format(sys.argv[3]))\n print(\"Arg4 (MongoDB Host): {}\".format(sys.argv[4]))\n print(\"Arg5 (MongoDB Port): {}\".format(sys.argv[5]))\n sys.exit(f0010main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]))\n\n","sub_path":"f0010/f0010main.py","file_name":"f0010main.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"190636201","text":"\nfrom numpy import *\n\n\ndef mult(matriz1,matriz2):\n if matriz1.shape[1] != matriz2.shape[0]:\n return (\"Dimensiones incorrectas\")\n else:\n nmatriz = zeros((matriz1.shape[0],matriz2.shape[1]))\n for i in range(matriz1.shape[0]):\n for j in range(matriz2.shape[1]):\n for k in range(matriz2.shape[0]):\n nmatriz[i][j]+= matriz1[i][k]*matriz2[k][j]\n return nmatriz\n\t\t\ndef transp(matriz):\n\ttmatriz=zeros((matriz.shape[1],matriz.shape[0]))\n\tfor i in range(matriz.shape[0]):\n\t\tfor j in range(matriz.shape[1]):\n\t\t\ttmatriz[j][i] = matriz[i][j]\n\treturn tmatriz\n","sub_path":"probando.py","file_name":"probando.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62590449","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\n\n#### MY PKGS\n\nfrom nameticker import getTickerName\n\n####\n\nfrom GoogleNews import GoogleNews\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport nltk\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nimport requests\nimport numpy as np\nimport multiprocessing\nimport time\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\nimport os\nimport json\n\n\n\nclass NewsSentiment(object):\n \n def __init__(self, word, days, synonyms=None):\n self.agent = {\"User-Agent\":'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/83.0.4103.61 Chrome/83.0.4103.61 Safari/537.36'}\n if synonyms != None:\n self.synonyms = synonyms.split(',')\n else:\n self.synonyms = [self.getNameFromTicker(word)]\n self.word = word\n self.start, self.end = self.dayMinusDays(days)\n\n\n def getNameFromTicker(self,ticker):\n dic = {}\n with open('./ticker-dict.json','r') as JSON:\n dic = json.load(JSON)\n \n if ticker.upper() not in dic.keys():\n getTickerName([ticker.upper()])\n with open('./ticker-dict.json','r') as JSON:\n dic = json.load(JSON)\n return dic[ticker.upper()]\n else:\n return dic[ticker.upper()]\n \n \n def getHtml(self, url, body):\n page = requests.get(url, headers=self.agent)\n if page.text != None:\n body += [page.text]\n else:\n body += ['']\n \n \n def genAllText(self, body, allWords):\n allText = []\n for bod in body:\n soup = BeautifulSoup(bod)\n paragraphs = soup.findAll('p')\n tmpText = ''\n for txt in paragraphs:\n for syn in allWords:\n if syn.lower() in str(txt).lower():\n tmpText += txt.getText()\n tmpText = tmpText.replace('\\n',' ')\n allText += [tmpText]\n return allText\n\n \n def genBody(self, links):\n manager = multiprocessing.Manager()\n body = manager.list()\n for url in links:\n print(url)\n p = multiprocessing.Process(target=self.getHtml, args=(url, body,))\n p.start()\n p.join(4)\n if p.is_alive():\n print(\"timed out...\")\n p.terminate()\n p.join()\n body += ['']\n else:\n print('Requests success!')\n return body\n\n \n ################### NOT IN USE ######################\n def genBodyHeadless(self, links):\n chrome_options = Options()\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument(\"window-size=1920,1080\")\n driver = webdriver.Chrome(ChromeDriverManager().install(),options=chrome_options)\n HTMLs = []\n for url in links:\n driver.get(url)\n HTMLs += [str(driver.page_source.encode(\"utf-8\"))]\n driver.quit()\n return HTMLs\n #####################################################\n \n \n def measureSentiment(self, allText):\n sia = SentimentIntensityAnalyzer()\n pos = 0\n neg = 0\n neu = 0\n com = 0\n count = 0\n print(f'Groups: {len(allText)}')\n for group in allText:\n count += 1\n sentiment = sia.polarity_scores(group)\n pos += sentiment['pos']\n neg += sentiment['neg']\n neu += sentiment['neu']\n com += sentiment['compound']\n print(f'done-{count}')\n return pos,neg,neu,com,count\n\n \n def avSentiment(self, pos, neg, neu, com, count):\n return pos/count, neg/count, neu/count, com/count\n \n \n def dayMinusDays(self, days):\n timestamp = time.time()\n dateBefore = datetime.datetime.fromtimestamp(timestamp-(days*24*60*60))\n dateNow = datetime.datetime.fromtimestamp(timestamp)\n b = str(dateBefore).split(' ')[0].replace('-','/')\n before = b[5:7]+'/'+b[8:10]+'/'+b[0:4]\n n = str(dateNow).split(' ')[0].replace('-','/')\n now = n[5:7]+'/'+n[8:10]+'/'+n[0:4]\n print(f'Start: {before}')\n print(f'End: {now}')\n return before,now\n \n \n def genCalList(self, start, end):\n MONTHS = [31,28,31,30,31,30,31,31,30,31,30,31]\n start_d = int(start[3:5])\n start_m = int(start[0:2])\n end_d = int(end[3:5])\n end_m = int(end[0:2])\n year = int(end[6:])\n month_dif = end_m - start_m\n day_dif = end_d - start_d\n calList = []\n \n if month_dif == 0:\n for d in range(start_d,end_d+1):\n date = str(year)+'/'+self.formatDay(start_m)+'/'+self.formatDay(d)\n calList += [date]\n return calList\n\n for m in range(month_dif+1):\n if m == 0:\n for d in range(start_d, MONTHS[start_m-1]+1):\n date = self.formatDay(start_m)+'/'+self.formatDay(d)+'/'+str(year)\n calList += [date]\n elif m == month_dif:\n for d in range(1,end_d+1):\n date = self.formatDay(end_m)+'/'+self.formatDay(d)+'/'+str(year)\n calList += [date]\n else:\n for d in range(1,MONTHS[start_m+m-1]+1):\n date = self.formatDay(start_m+m)+'/'+self.formatDay(d)+'/'+str(year)\n calList += [date] \n return calList\n \n \n def formatDay(self, day):\n if int(day) < 10:\n return f'0{day}'\n return str(day)\n \n \n def extrapolate(self, array):\n indices = [i for i, x in enumerate(array) if x == 0]\n av = sum(array)/(len(array)-len(indices))\n for ind in indices:\n array[ind] = av\n return array\n \n \n def getSentimentFromJson(self, jsonPath):\n with open(jsonPath, 'r') as JSON:\n data = json.load(JSON)\n dates = [i for i in data.keys()]\n calList = self.genCalList(dates[0],dates[-1])\n pos,neg,neu,com = [],[],[],[]\n samples = 0\n missing = 0\n for date in calList:\n try:\n pos += [data[date]['pos']]\n neg += [data[date]['neg']]\n neu += [data[date]['neu']]\n com += [data[date]['com']]\n samples += data[date]['sample size']\n except:\n pos += [0.0]\n neg += [0.0]\n neu += [0.0]\n com += [0.0]\n missing += 1\n print(f'Missing: {missing}')\n print(f'Total: {len(calList)}\\n')\n return pos,neg,neu,com,samples\n \n \n def genTrend(self, days, data, path):\n x = [i for i in range(len(data[-days:]))]\n y = [i for i in self.extrapolate(data[-days:])]\n z = np.polyfit(x, y, 1)\n p = np.poly1d(z)\n ext = f\"trend-{days}.npy\"\n with open(path+ext,'wb') as f:\n np.save(f, np.array(p(x)))\n \n \n def getComData(self):\n path = f'./news/data/{self.word}/'\n pos,neg,neu,com,samples = self.getSentimentFromJson(path+f'{self.word}.json')\n com = self.extrapolate(com)\n return com\n \n \n def trend(self):\n path = f'./news/data/{self.word}/'\n pos,neg,neu,com,samples = self.getSentimentFromJson(path+f'{self.word}.json')\n days = [180,90,30,10,3]\n comL = self.extrapolate(com)\n for day in days:\n if len(comL) >= day:\n self.genTrend(day,comL,path)\n print(f'{day} success!')\n else:\n print(f'{day} not enough data...')\n \n \n def getSlope(self,data):\n first = data[0]\n last = data[-1]\n slope = (last-first)/len(data)\n return slope\n \n \n def slope(self):\n self.trend()\n formatted = {}\n days = [3,10,30,90,180]\n for day in days:\n path = f'./news/data/{self.word}/trend-{day}.npy'\n data = np.load(path)\n slope = self.getSlope(data)\n formatted[str(day)] = slope\n with open(f'./news/data/{self.word}/slopes.json','w') as JSON:\n json.dump(formatted,JSON)\n \n \n def run(self):\n googlenews = GoogleNews()\n calList = self.genCalList(self.start,self.end)\n posL,negL,neuL,comL = [],[],[],[]\n\n pageCount = 10\n ALL_RESULT = {}\n t = time.time()\n\n for date in calList:\n print(f'\\n\\n{date}')\n PREV_RES = []\n RESULT = {}\n continu = True\n\n for page in range(1,pageCount+1):\n t1 = time.time()\n googlenews = GoogleNews(start=date, end=date, lang='en')\n googlenews.search(self.word)\n googlenews.getpage(page)\n results = googlenews.result()\n googlenews.clear()\n \n if results == []:\n continu = False\n break\n\n results = [dict(t) for t in {tuple(d.items()) for d in results}]\n results = [i for i in results if i not in PREV_RES]\n if len(results) < 1:\n break\n\n for res in results:\n RESULT[res['title']] = res['link']\n \n PREV_RES = results\n print(f\"Page: {page}. Name: {self.word}. t={round(time.time()-t1,2)}s\")\n\n if not os.path.exists(f'./news/data/{self.word}'):\n os.mkdir(f'./news/data/{self.word}')\n\n old_data = {}\n if os.path.isfile(f'./news/data/{self.word}/{self.word}.json'):\n with open(f'./news/data/{self.word}/{self.word}.json','r') as JSON:\n old_data = json.load(JSON)\n JSON.close()\n\n if continu == False:\n print('No results.')\n with open(f'./news/data/{self.word}/{self.word}.json','w') as JSON:\n old_data[date] = {}\n json.dump(old_data,JSON)\n JSON.close()\n continue\n\n titles = [i for i in RESULT.keys()]\n links = [i for i in RESULT.values()]\n body = self.genBody(links)\n allWords = [self.word] + self.synonyms\n\n print('\\nFetching

    text...')\n oldText = self.genAllText(body,allWords)\n allText = [i for i in oldText if i != '']\n print(f\"Texts aquired of total: {(len(allText)/len(oldText))*100}%\")\n\n if allText == []:\n with open(f'./news/data/{self.word}/{self.word}.json','w') as JSON:\n old_data[date] = {}\n json.dump(old_data,JSON)\n JSON.close()\n continue\n\n print('Sentiment analysis...')\n pos,neg,neu,com,count = self.measureSentiment(allText)\n pos_,neg_,neu_,com_ = self.avSentiment(pos,neg,neu,com,count)\n\n posL += [pos_]\n negL += [neg_]\n neuL += [neu_]\n comL += [com_]\n\n formatted = {'synonyms':self.synonyms,'pos':pos_,'neg':neg_,'neu':neu_,'com':com_,'raw text':allText,'sample size':len(RESULT),'page count':pageCount}\n old_data[date] = formatted\n with open(f'./news/data/{self.word}/{self.word}.json','w') as JSON:\n json.dump(old_data,JSON)\n JSON.close()\n\n print(time.time()-t)\n\n\n\n#word = 'gt gold corp'\n#days = 15\n#n = NewsSentiment(word,days,synonyms='gt gold')\n\n#n.run()\n\n\n\n\n\n\n","sub_path":"Momentum/newssentiment.py","file_name":"newssentiment.py","file_ext":"py","file_size_in_byte":11894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"81589123","text":"# -*- coding: utf-8 -*-\n\n# не забывай делать комиты и выполнять TODO\n\n#TODO не работает выход на крестик\n\nimport pygame\nimport random\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0)\nBLUE = (50,80,200)\n\nrandom_counter = 0\npuli = []\npuli_vers = []\ngo_to = 'r'\ngo_to_vers = 'r'\ncheat_flag = False\n\nlife = 100\nlife_vers = 100\ngame_over = False\n\nshot_flag = False\nshot_vers_flag = False\npygame.init()\n\ndef draw_random(x,y):\n x = random.randint(0,1000)\n y = random.randint(0,600)\n pygame.draw.rect(screen, RED,(x,y,5,5), 0)\n\ndef draw_tank(x, y,color):\n global screen\n pygame.draw.rect(screen, color, (x+10,y+10,20,20), 0)\n #TODO нарисуй нормальный танк вроде такого\n # *\n # ***\n # ***\n # * *\n # например как несколько квадратов\n \ndef draw_bullets(arr, color):\n #TODO сделай пули посередине квадрата\n global screen\n for p in arr:\n x = p[0]\n y = p[1]\n pygame.draw.rect(screen, color, [10+x,10+y,5,5], 0)\n\nsize = [1000, 600]\nscreen = pygame.display.set_mode(size)\n\npygame.display.set_caption(\"Tanks 5.2\")\n# Loop until the user clicks the close button.\ndone = False\n# Used to manage how fast the screen updates\nclock = pygame.time.Clock()\n# Hide the mouse cursor\npygame.mouse.set_visible(0)\nshot_speed = 8\nshot_speed_vers = 8\nx_speed = 0\ny_speed = 0\n\nx_coord_vers = 10\ny_coord_vers = 10\n \nx_speed_vers = 0\ny_speed_vers = 0\n\nx_coord = 100\ny_coord = 100\n# -------- Main Program Loop -----------\nwhile not done:\n # --- Event Processing\n for event in pygame.event.get():\n if game_over == True:\n done = True\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RCTRL:\n shot_speed += 1\n if event.key == pygame.K_LCTRL:\n shot_speed -= 1\n if event.key == pygame.K_LEFT:\n x_speed = -3\n y_speed = 0\n go_to = 'l'\n elif event.key == pygame.K_RIGHT:\n x_speed = 3\n y_speed = 0\n go_to = 'r'\n elif event.key == pygame.K_UP:\n y_speed = -3\n x_speed = 0\n go_to = 'u'\n elif event.key == pygame.K_DOWN:\n y_speed = 3\n x_speed = 0\n go_to = 'd'\n elif event.key == pygame.K_SPACE:\n shot_vers_flag = True\n \n elif event.key == pygame.K_w:\n y_speed_vers -= 3\n x_speed_vers = 0\n go_to_vers = 'u'\n elif event.key == pygame.K_a:\n y_speed_vers = 0\n x_speed_vers -= 3\n go_to_vers = 'l'\n elif event.key == pygame.K_s:\n y_speed_vers += 3\n x_speed_vers = 0 \n go_to_vers = 'd'\n elif event.key == pygame.K_d:\n y_speed_vers = 0\n x_speed_vers += 3 \n go_to_vers = 'r'\n elif event.key == pygame.K_RSHIFT:\n shot_flag = True\n \n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT:\n x_speed = 0\n elif event.key == pygame.K_RIGHT:\n x_speed = 0\n elif event.key == pygame.K_UP:\n y_speed = 0\n elif event.key == pygame.K_DOWN:\n y_speed = 0\n\n elif event.key == pygame.K_w:\n y_speed_vers = 0\n elif event.key == pygame.K_a:\n x_speed_vers = 0\n elif event.key == pygame.K_s:\n y_speed_vers = 0\n elif event.key == pygame.K_d:\n x_speed_vers = 0 \n \n # --- Game Logic\n x_coord = x_coord + x_speed\n y_coord = y_coord + y_speed\n \n x_coord_vers += x_speed_vers \n y_coord_vers += y_speed_vers\n \n if shot_flag:\n if go_to == 'l':\n puli.append([x_coord, y_coord, 'l'])\n elif go_to == 'r':\n puli.append([x_coord, y_coord, 'r'])\n elif go_to == 'u':\n puli.append([x_coord, y_coord, 'u'])\n elif go_to == 'd':\n puli.append([x_coord, y_coord, 'd'])\n shot_flag = False\n if shot_vers_flag:\n if go_to_vers == 'l':\n puli_vers.append([x_coord_vers, y_coord_vers, 'l'])\n elif go_to_vers == 'r':\n puli_vers.append([x_coord_vers, y_coord_vers, 'r'])\n elif go_to_vers == 'u':\n puli_vers.append([x_coord_vers, y_coord_vers, 'u'])\n elif go_to_vers == 'd':\n puli_vers.append([x_coord_vers, y_coord_vers, 'd'])\n shot_vers_flag = False\n\n for p in puli:\n if p[2] == 'r':\n p[0] += shot_speed\n elif p[2] == 'l':\n p[0] -= shot_speed\n elif p[2] == 'u':\n p[1] -= shot_speed\n elif p[2] == 'd':\n p[1] += shot_speed\n if ((0 > p[0] or p[0] > size[0]) or (0 > p[1] or p[1] > size[1])):\n puli.remove(p)\n \n elif (x_coord_vers < p[0]+5 and p[0]+5 < x_coord_vers + 20) and (y_coord_vers < p[1]+5 and p[1]+5 < y_coord_vers + 20):\n puli.remove(p)\n life_vers -= 10\n \n for p in puli_vers:\n if p[2] == 'r':\n p[0] += shot_speed_vers\n elif p[2] == 'l':\n p[0] -= shot_speed_vers\n elif p[2] == 'u':\n p[1] -= shot_speed_vers\n elif p[2] == 'd':\n p[1] += shot_speed_vers\n if (0 > p[0] or p[0] > size[0] and 0 > p[1] or p[1] > size[1]):\n puli_vers.remove(p)\n elif (x_coord < p[0]+5 and p[0]+5 < x_coord + 20) and (y_coord < p[1]+5 and p[1]+5 < y_coord + 20):\n puli_vers.remove(p)\n life -= 10\n\n # --- Drawing Code\n screen.fill(BLACK)\n\n font = pygame.font.Font(None, 25)\n\n#TODO сделай текст life посередине\n\n text = font.render(str(life),True,WHITE)\n text_vers = font.render(str(life_vers),True,WHITE)\n\n screen.blit(text, [x_coord+6,y_coord-7])\n screen.blit(text_vers, [x_coord_vers+6,y_coord_vers-7])\n\n if life == 0:\n font = pygame.font.Font(None, 200)\n text_win = font.render(\"BLUE WINS\", True, GREEN)\n text_size = font.size(\"BLUE WINS\")\n # обрати внимание как текст делается посередине\n # сделай то же самое в других местах\n screen.blit(text_win, [(size[0]-text_size[0])/2,(size[1]-text_size[1])/2])\n game_over = True\n\n elif life_vers == 0:\n font = pygame.font.Font(None, 200)\n text_win = font.render(\"RED WINS\",True,GREEN)\n text_size = font.size(\"RED WINS\")\n screen.blit(text_win, [(size[0]-text_size[0])/2,(size[1]-text_size[1])/2])\n game_over = True\n\n else: \n draw_bullets(puli, RED)\n draw_bullets(puli_vers, BLUE)\n draw_tank(x_coord, y_coord, RED)\n draw_tank(x_coord_vers, y_coord_vers, BLUE)\n if random_counter == 0:\n draw_random(x_coord,y_coord)\n random_counter += 1\n pygame.display.flip()\n \n clock.tick(60)\npygame.quit()\n","sub_path":"Tanks/tanks.py","file_name":"tanks.py","file_ext":"py","file_size_in_byte":7359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"207507553","text":"################################################################\n# Write a python program that will read your JavaScript syntax program\n# as input into your program\n# Determine the number of lines in the JavaScript program \n# and display it to the user\n# Determine how many “else” statements are in the JavaScript program\n# How many characters(total) are in the JavaScript Program?\n#################################################################\n\nwith open(\"basic.js\", \"r\") as f:\n #get number of lines in file\n numlines = -1\n numelse = 0\n numchar = 0\n currline = \"a\"\n while len(currline) > 0:\n currline = f.readline()\n numchar+= len(currline)\n if 'else' in currline:\n numelse+=1\n numlines+=1\nprint(\"numlines in file is: \", numlines)\nprint(\"number of else in file: \", numelse)\nprint(\"number of chars in file: \", numchar)\n\n# Write a python program that will:\n# read all the files and their sizes from a directory\n# print a nice little report that tells us the number of files and the total size of the directory\n\nfrom pathlib import Path\n\np = Path('.')\ntotalsize = 0\ntotalfiles = 0\nfor currFile in p.iterdir():\n totalfiles+=1\n totalsize += currFile.stat().st_size\n\nprint(\"In the Current Directory\\n\")\nprint(\" Total number of files: \", totalfiles)\nprint(\" Total size of files: \", totalsize, \"bytes\")\n\n# use a dictionary (don’t use“if” statements) to total “res_cnt” by\n# CLASS\n# SECTOR\n# count the number of lines\n# print a nice little report at the end\n# write the report to a file called report.txt.\n\nwith open(\"Census_By_Community_2018.csv\", \"r\") as f:\n #get number of lines in file\n numlines = 1\n numchar = 0\n maxlen = 0\n #ignore first line of file, has data column names\n currline = f.readline()\n \n classes = {}\n sectors = {}\n #read first data line\n currline = f.readline()\n \n\n while len(currline) > 0:\n \n splitline = currline.split(\",\")\n a1 = splitline[0]\n b4 = splitline[4]\n c9 = int(splitline[9])\n\n d = classes.get(a1, 0)\n newclassrescount = d+c9\n classes[currclass] = newclassrescount\n\n e = sectors.get(b4, 0)\n f = e+c9\n sectors[b4] = f\n maxlen = max(maxlen, len(a1), len(b4))\n numlines+=1\n\n currline = f.readline()\n\nwith open(\"report.txt\", \"w+\") as f:\n nextline = f'Class{\" \" * (maxlen - 3)}Residents'\n print(nextline)\n f.write(nextline+'\\n')\n nextline = f'{\"-\" * (maxlen+11)} '\n print(nextline)\n f.write(nextline+'\\n')\n for key in classes:\n nextline = f'{key}{\" \" * (maxlen-len(key)+1)}{format(classes[key],\" 10,\")}'\n print(nextline)\n f.write(nextline+'\\n')\n\n nextline = f'\\nSector{\" \" * (maxlen - 4)}Residents'\n print(nextline)\n f.write(nextline+'\\n')\n nextline = f'{\"-\" * (maxlen+11)} '\n print(nextline)\n f.write(nextline+'\\n')\n\n for key in sectors:\n \n nextline = f'{key}{\" \" * (maxlen-len(key)+1)}{format(sectors[key],\" 10,\")}'\n print(nextline)\n f.write(nextline+'\\n')\n\n\n nextline = f'Number of lines in file is: {numlines}'\n print(nextline)\n f.write(nextline+'\\n')\n","sub_path":"python/Comp220/filestats.py","file_name":"filestats.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608581329","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n#\n# pyre-strict\nfrom typing import Dict, List, Optional, Sequence, Set, Tuple, Union\n\nimport libcst\nfrom libcst.codemod._context import CodemodContext\nfrom libcst.codemod._visitor import ContextAwareVisitor\n\n\nclass GatherImportsVisitor(ContextAwareVisitor):\n def __init__(self, context: CodemodContext) -> None:\n super().__init__(context)\n # Track the available imports in this transform\n self.module_imports: Set[str] = set()\n self.object_mapping: Dict[str, Set[str]] = {}\n # Track the aliased imports in this transform\n self.module_aliases: Dict[str, str] = {}\n self.alias_mapping: Dict[str, List[Tuple[str, str]]] = {}\n # Track all of the imports found in this transform\n self.all_imports: List[Union[libcst.Import, libcst.ImportFrom]] = []\n\n def _get_string_name(self, node: Optional[libcst.CSTNode]) -> str:\n if node is None:\n return \"\"\n elif isinstance(node, libcst.Name):\n return node.value\n elif isinstance(node, libcst.Attribute):\n return self._get_string_name(node.value) + \".\" + node.attr.value\n else:\n raise Exception(f\"Invalid node type {type(node)}!\")\n\n def visit_Import(self, node: libcst.Import) -> None:\n # Track this import statement for later analysis.\n self.all_imports.append(node)\n\n for name in node.names:\n asname = name.asname\n if asname is not None:\n # Track this as an aliased module\n self.module_aliases[\n self._get_string_name(name.name)\n ] = libcst.ensure_type(asname.name, libcst.Name).value\n else:\n # Get the module we're importing as a string.\n self.module_imports.add(self._get_string_name(name.name))\n\n def visit_ImportFrom(self, node: libcst.ImportFrom) -> None:\n # Track this import statement for later analysis.\n self.all_imports.append(node)\n\n if len(node.relative) > 0 or node.module is None:\n # Don't support relative-only imports at the moment.\n return\n\n # Get the module we're importing as a string.\n module = self._get_string_name(node.module)\n nodenames = node.names\n if isinstance(nodenames, libcst.ImportStar):\n # We cover everything, no need to bother tracking other things\n self.object_mapping[module] = set(\"*\")\n return\n elif isinstance(nodenames, Sequence):\n # Get the list of imports we're aliasing in this import\n new_aliases = [\n # pyre-ignore We check ia.asname below, this is safe\n (self._get_string_name(ia.name), ia.asname.name.value)\n for ia in nodenames\n if ia.asname is not None\n ]\n if new_aliases:\n if module not in self.alias_mapping:\n self.alias_mapping[module] = []\n self.alias_mapping[module].extend(new_aliases)\n\n # Get the list of imports we're importing in this import\n new_objects = {\n self._get_string_name(ia.name) for ia in nodenames if ia.asname is None\n }\n if new_objects:\n if module not in self.object_mapping:\n self.object_mapping[module] = set()\n\n # Make sure that we don't add to a '*' module\n if \"*\" in self.object_mapping[module]:\n self.object_mapping[module] = set(\"*\")\n return\n\n self.object_mapping[module].update(new_objects)\n","sub_path":"libcst/codemod/visitors/_gather_imports.py","file_name":"_gather_imports.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"212872730","text":"class Solution:\n LETTERS = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\n def letterCombinations(self, digits):\n if not digits:\n return []\n ans, level, s = [], 0, ''\n self.findCombinations(level, ans, digits, s)\n return ans\n \n def findCombinations(self, level, ans, digits, s):\n if level == len(digits):\n ans.append(s)\n return\n for l in self.LETTERS[digits[level]]:\n self.findCombinations(level+1, ans, digits, s+l)\n","sub_path":"Week_03/letters-combination-17.py","file_name":"letters-combination-17.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"315077998","text":"import math\r\ndef dac(A, target):\r\n l = 0\r\n h = len(A)-1\r\n while l<=h:\r\n mid = round((h+l)/2)\r\n if A[mid] == target:\r\n return mid\r\n elif A[mid] < target:\r\n l = mid + 1\r\n else:\r\n h = mid - 1\r\n return \"not found\"\r\n \r\nA = [1,4]\r\ntarget = 0\r\nprint(dac(A, target))\r\n","sub_path":"divide_and_conquer.py","file_name":"divide_and_conquer.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"27733307","text":"import komand\nfrom .schema import RelatedInput, RelatedOutput\n# Custom imports below\nfrom komand.exceptions import PluginException\n\n\nclass Related(komand.Action):\n def __init__(self):\n super(self.__class__, self).__init__(\n name='related',\n description='Returns a list of domain names that have been frequently seen',\n input=RelatedInput(),\n output=RelatedOutput())\n\n def run(self, params={}):\n domain = params.get('domain')\n try:\n related = self.connection.investigate.related(domain)\n except Exception as e:\n raise PluginException(preset=PluginException.Preset.UNKNOWN)\n founded = related.get('found')\n if founded:\n return {\"related\": related.get('tb1')}\n\n self.logger.info(\"No results found\")\n return {\"related\": []}\n\n def test(self):\n return {\"related\": []}\n","sub_path":"cisco_umbrella_investigate/komand_cisco_umbrella_investigate/actions/related/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"533655700","text":"import json\nimport random\nimport re\nimport tempfile\nimport uuid\nfrom pathlib import Path\nfrom zipfile import ZIP_DEFLATED, ZipFile, ZipInfo\nimport itertools\n\n\nclass UnsupportedFileTypeException(Exception):\n pass\n\n\nclass DatabricksConvert:\n def __init__(self, input_path, output_path, output_type):\n self.input_path = Path(input_path)\n self.output_path = Path(output_path)\n self.temp_path = Path(tempfile.mkdtemp())\n self.output_type = output_type\n\n def convert(self):\n \"\"\"\n Converts source files/directories into databricks dbc archive\n \"\"\"\n if self.input_path.is_file():\n self._convert_file(\n self.input_path, self.temp_path.joinpath(self.input_path.name)\n )\n else:\n self._convert_directory(self.input_path, self.temp_path)\n\n if self.output_type == \"dbc\":\n self._create_zip(\n self.temp_path,\n self.output_path.joinpath(self.input_path.with_suffix(\".dbc\").name),\n )\n\n def _convert_directory(self, input_path, output_path):\n \"\"\"\n Recursively converts files into databricks json preserving folder structure.\n \"\"\"\n for input_file in input_path.glob(\"**/*.*\"):\n if input_file.is_dir() or input_file.parent.stem.startswith(\".\"):\n continue\n output_file = self.temp_path.joinpath(\n input_file.relative_to(input_path.parent)\n )\n output_file.parent.mkdir(parents=True, exist_ok=True)\n self._convert_file(input_file, output_file)\n\n def _import_file(self, input_file):\n content = input_file.read_text()\n if input_file.suffix in (\".scala\", \".py\"):\n commands = re.split(\n r\"[#\\/\\s]+COMMAND -+\",\n content.replace(\"# MAGIC \", \"\").replace(\n \"# Databricks notebook source\", \"\"\n ),\n )\n language = \"python\" if input_file.suffix == \".py\" else \"scala\"\n elif input_file.suffix == \".ipynb\":\n content = json.loads(content)\n commands = [\"\".join(x[\"source\"]) for x in content[\"cells\"]]\n language = content[\"metadata\"][\"language_info\"][\"name\"]\n else:\n raise UnsupportedFileTypeException()\n\n return commands, language\n\n def _convert_file(self, input_file, output_file):\n \"\"\"\n Converts source file into databricks json\n \"\"\"\n try:\n _commands, language = self._import_file(input_file)\n except UnsupportedFileTypeException:\n return\n except KeyError:\n return\n\n n = random.randrange(100000000000000, 999999999999999)\n commands = [\n {\n \"version\": \"CommandV1\",\n \"origId\": n + i,\n \"guid\": str(uuid.uuid4()),\n \"subtype\": \"command\",\n \"commandType\": \"auto\",\n \"position\": float(i + 1),\n \"command\": x.strip(),\n \"commandVersion\": 1,\n \"state\": \"finished\",\n \"results\": {\n \"type\": \"html\",\n \"data\": '

    ',\n \"arguments\": {},\n \"addedWidgets\": {},\n \"removedWidgets\": [],\n \"datasetInfos\": [],\n },\n \"errorSummary\": None,\n \"error\": None,\n \"workflows\": [],\n \"startTime\": 0,\n \"submitTime\": 0,\n \"finishTime\": 0,\n \"collapsed\": False,\n \"bindings\": {},\n \"inputWidgets\": {},\n \"displayType\": \"table\",\n \"width\": \"auto\",\n \"height\": \"auto\",\n \"xColumns\": None,\n \"yColumns\": None,\n \"pivotColumns\": None,\n \"pivotAggregation\": None,\n \"useConsistentColors\": False,\n \"customPlotOptions\": {},\n \"commentThread\": [],\n \"commentsVisible\": False,\n \"parentHierarchy\": [],\n \"diffInserts\": [],\n \"diffDeletes\": [],\n \"globalVars\": {},\n \"latestUser\": \"\",\n \"latestUserId\": None,\n \"commandTitle\": \"\",\n \"showCommandTitle\": False,\n \"hideCommandCode\": False,\n \"hideCommandResult\": False,\n \"isLockedInExamMode\": False,\n \"iPythonMetadata\": None,\n \"streamStates\": {},\n \"datasetPreviewNameToCmdIdMap\": {},\n \"nuid\": str(uuid.uuid4()),\n }\n for i, x in enumerate(_commands)\n ]\n\n notebook = {\n \"version\": \"NotebookV1\",\n \"name\": output_file.stem,\n \"language\": language,\n \"commands\": commands,\n \"guid\": str(uuid.uuid4()),\n \"origId\": n,\n }\n\n output_file.with_suffix(f\".{language}\").write_text(\n json.dumps(notebook, indent=4)\n )\n\n def _create_zip(self, input_path, output_file):\n \"\"\"\n Zips file to create the .dbc archive\n \"\"\"\n\n def _get_directories(p):\n p = p.parent\n while p != input_path:\n yield p.relative_to(input_path)\n p = p.parent\n\n directories = list(\n set(\n itertools.chain(\n *[_get_directories(x) for x in input_path.glob(\"**/*.*\")]\n )\n )\n )\n output_file.parent.mkdir(parents=True, exist_ok=True)\n with ZipFile(output_file, \"w\", compression=ZIP_DEFLATED) as zipf:\n\n for directory in directories:\n zi = ZipInfo(str(directory) + \"/\")\n # zi.external_attr = 0x10\n zi.compress_type = ZIP_DEFLATED\n zipf.writestr(zi, \"\")\n\n for path in input_path.glob(\"**/*.*\"):\n base_path = path.relative_to(input_path)\n zi = ZipInfo(str(base_path))\n zi.compress_type = ZIP_DEFLATED\n zi.flag_bits = None\n # zi.external_attr = 0x20\n zipf.writestr(zi, path.read_text())\n","sub_path":"databricks_convert/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":6352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"440541874","text":"# 1. Дан список строк my_list. Создать новый список в который поместить\n# элементы из my_list по следующему правилу:\n# Если строка стоит на нечетном месте в my_list, то ее заменить на\n# перевернутую строку. \"qwe\" на \"ewq\".\n# Если на четном - оставить без изменения.\n# Задание сделать с использованием enumerate и��и range.\n\n\n\nmy_list = [\"один\", \"два\", \"три\", \"четыре\", \"пять\", \"шесть\"]\nnew_list = []\n\nfor string in range(len(my_list)):\n if not string % 2:\n new_list.append(my_list[string][::-1])\n else:\n new_list.append(my_list[string])\nprint(new_list)\n\n\n\n\n# 2. Дан список строк my_list. Создать новый список в который поместить\n# элементы из my_list у которых первый символ - буква \"a\".\n\n\n\nmy_list = [\"aerty\", \"dfgh\", \"dfghj\", \"awert\", \"aert\"]\nnew_list = []\n\nfor element in my_list:\n if element[0] == \"a\":\n new_list.append(element)\nprint(new_list)\n\n\n\n# 3. Дан список строк my_list. Создать новый список в который поместить\n# элементы из my_list в которых есть символ - буква \"a\" на любом месте.\n\n\n\nmy_list = [\"aerty\", \"dfagh\", \"dfghj\", \"wert\", \"erta\"]\nnew_list = []\n\nfor element in my_list:\n if \"a\" in element:\n new_list.append(element)\nprint(new_list)\n\n\n\n# 4. Дан список my_list в котором могут быть как строки (type str) так и целые числа (type int).\n# Например [1, 2, 3, \"11\", \"22\", 33]\n# Создать новый список в который поместить только строки из my_list.\n\n\n\nmy_list = [1, 2, 3, \"11\", \"22\", 33, \"juhi\"]\nnew_list = []\n\nfor element in my_list:\n if type(element) is str:\n new_list.append(element)\nprint(new_list)\n\n\n\n# 5. Дана строка my_str. Создать список в который поместить те символы из my_str,\n# которые встречаются в строке ТОЛЬКО ОДИН раз.\n\n\n\nmy_str = \"qweewewqeqwwewerwqqqq\"\n\nfor symbol in my_str:\n count_symbol = my_str.count(symbol)\n if count_symbol == 1:\n print(symbol)\n\n\n# 6. Даны две строки. Создать список в который поместить те символы,\n# которые есть в обеих строках хотя бы раз.\n\n\n\nmy_str_1 = \"qweewewqeqwwewerwqqqq\"\nmy_str_2 = \"qweefkllkewjblvjqwwfjnvlewqq\"\n\nmy_set_1 = set(my_str_1)\nmy_set_2 = set(my_str_2)\n\nintersection_of_sets = list(my_set_1.intersection(my_set_2))\nprint(intersection_of_sets)\n\n\n\n# 7. Даны две строки. Создать список в который поместить те символы, которые есть в обеих строках,\n# но в каждой ТОЛЬКО ПО ОДНОМУ разу.\n\n\n\nmy_str_1 = \"zqweewewq8eqwweywerwqqqq\"\nmy_str_2 = \"qzweefkllkewjbly8vjqwwfjnvlewqq\"\nmy_list = []\n\nmy_set_1 = set(my_str_1)\nmy_set_2 = set(my_str_2)\n\nintersection_of_sets = list(my_set_1.intersection(my_set_2))\n\nfor element in intersection_of_sets:\n if my_str_1.count(element) == 1 and my_str_2.count(element) == 1:\n my_list.append(element)\nprint(my_list)\n\n\n\n# 8. Описать с помощью словаря следующую структуру для конкретного человека (можно придумать):\n# Фамилия\n# Имя\n# Возраст\n# Проживание\n# Страна\n# Город\n# Улица\n# Работа\n# Наличие\n# Должность\n\n\n\nperson = {\"Person\": {\"Фамилия\": \"Bakanova\",\n \"Имя\": \"Valeriia\",\n \"Возраст\": 31},\n \"Проживание\": {\"Страна\": \"Ukraine\",\n \"Город\": \"Dnipro\",\n \"Улица\": \"Artekivska\"},\n \"Работа\": {\"Наличие\": \"+\",\n \"Должность\": \"Manual QA\"}}\n\n\n\n# 9. Описать с помощью словаря следующую структуру (рецепт ненастоящего торта,\n# придумать и указать граммы для продуктов):\n# Составляющие\n# Коржи\n# Мука\n# Молоко\n# Масло\n# Яйцо\n# Крем\n# Сахар\n# Масло\n# Ваниль\n# Сметана\n# Глазурь\n# Какао\n# Сахар\n# Масло\n\n\n\ncake = {\"Составляющие\": {\"Коржи\": {\"Мука\": 1000,\n \"Молоко\": 500,\n \"Масло\": 200,\n \"Яйцо\": 150},\n \"Крем\": {\"Сахар\": 250,\n \"Масло\": 400,\n \"Ваниль\": 7,\n \"Сметана\": 500},\n \"Глазурь\": {\"Какао\": 40,\n \"Сахар\": 60,\n \"Масло\": 50}}}\n","sub_path":"HW6/hw_6.py","file_name":"hw_6.py","file_ext":"py","file_size_in_byte":5414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172756880","text":"# -*- coding: utf-8 -*-\n#\n# ServiceReference to PiconName - Converter\n#\n# Coded by dre (c) 2014 - 2016\n# Support: www.dreambox-tools.info\n# E-Mail: dre@dreambox-tools.info\n#\n# This plugin is open source but it is NOT free software.\n#\n# This plugin may only be distributed to and executed on hardware which\n# is licensed by Dream Property GmbH.\n# In other words:\n# It's NOT allowed to distribute any parts of this plugin or its source code in ANY way\n# to hardware which is NOT licensed by Dream Property GmbH.\n# It's NOT allowed to execute this plugin and its source code or even parts of it in ANY way\n# on hardware which is NOT licensed by Dream Property GmbH.\n#\n# If you want to use or modify the code or parts of it,\n# you have to keep MY license and inform me about the modifications by mail.\n#\n\nfrom Components.Converter.Converter import Converter\nfrom Components.Element import cached\nfrom enigma import eServiceCenter, eServiceReference, iPlayableServicePtr, iServiceInformation\n\nclass RefToPiconName(Converter, object):\n\tREFERENCE = 0\n\tNAME = 1\n\t\n\tdef __init__(self, type):\n\t\tif type == \"Name\":\n\t\t\tself.type = self.NAME\n\t\telse:\n\t\t\tself.type = self.REFERENCE\n\t\t\t\t\n\t\tConverter.__init__(self, type)\n\n\t@cached\n\tdef getText(self):\n\t\tref = self.source.service\n\t\t\n\t\tif ref is not None:\n\t\t\tif not isinstance(ref, iPlayableServicePtr):\n\t\t\t\t#bouquet or marker\n\t\t\t\tif ref.flags & (eServiceReference.isDirectory|eServiceReference.isMarker):\n\t\t\t\t\tinfo = eServiceCenter.getInstance().info(ref)\n\t\t\t\t\tif info:\n\t\t\t\t\t\treturn info.getName(ref).replace(\" \",\"_\")\n\t\t\t\t#alternatives\n\t\t\t\telif ref.flags & (eServiceReference.isGroup):\n\t\t\t\t\tif self.type == self.NAME:\n\t\t\t\t\t\treturn eServiceCenter.getInstance().list(ref).getContent(\"N\")[0].replace(\" \",\"_\")\t\t\t\t\n\t\t\t\t\treturn eServiceCenter.getInstance().list(ref).getContent(\"S\")[0]\n\t\t\t\t#channel\n\t\t\t\tif self.type == self.NAME:\n\t\t\t\t\tinfo = eServiceCenter.getInstance().info(ref)\n\t\t\t\t\tif info:\n\t\t\t\t\t\treturn info.getName(ref).replace(\" \", \"_\")\t\t\t\t\n\t\t\t\treturn ref.toString()\n\t\t\telse:\n\t\t\t\tinfo = ref and ref.info()\n\t\t\t\tservice = None\n\t\t\t\n\t\t\t\tif info:\n\t\t\t\t\tsRef = service and info.getInfoString(service, iServiceInformation.sServiceRef) or info.getInfoString(iServiceInformation.sServiceref)\n\t\t\t\t\tif sRef is None or sRef is \"\" or self.type == self.NAME:\n\t\t\t\t\t\treturn info.getName().replace(\" \",\"_\")\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sRef\n\t\treturn \"\"\n\t\t\n\ttext = property(getText)\n","sub_path":"reftopiconname/src/RefToPiconName.py","file_name":"RefToPiconName.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"190106847","text":"import sys\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport requests\r\n\r\ndef soup(url):\r\n res = requests.get(url)\r\n soup = BeautifulSoup(res.text,'html.parser')\r\n\r\n return soup\r\n\r\n#各カテゴリのURL\r\ntopics = ['domestic','world','business','entertainment','sports','it','science','local']\r\nbase_url = 'https://news.yahoo.co.jp/topics/'\r\n\r\nlink_jump_dec = {}\r\n#1ページ目から\r\n\r\nfor topic in topics:\r\n page=1\r\n link_jump_list=[]\r\n\r\n while 1:\r\n #1つのカテゴリ\r\n url = base_url + topic +'?page={}'.format(page)\r\n\r\n #続きを読むを押したあとのリンク\r\n\r\n if(soup(url).find('div',id = 'errorContents') == None):\r\n # 各記事のURLを取得し、そこからさらに続きを読むのリンクを取得してリストに追加\r\n for link in soup(url).find_all('a', class_='newsFeed_item_link'):\r\n soup_jump = soup(link.get('href'))\r\n link_jump = soup_jump.find('p', class_='sc-kaCJFH jSvclU')\r\n link_jump_list.append(link_jump.find('a').get('href'))\r\n else:\r\n print('ページが見つかりません')\r\n break\r\n print(page)\r\n time.sleep(1)\r\n page = page+1\r\n\r\n print(topic)\r\n #print(link_jump_list)\r\n link_jump_dec[topic] = link_jump_list\r\n\r\n#print(link_jump_dec)\r\n\r\n\r\nd = {'\\u3000': None, '\\n': None, ' ': None}\r\ntbl = str.maketrans(d)\r\ncontents = []\r\n\r\n#辞書のキーからトピック、リンクからタイトル・URL・記事を取得\r\nfor topic in topics:\r\n print('start')\r\n for url in link_jump_dec[topic]:\r\n\r\n soup_article = soup(url)\r\n\r\n title_tag = soup_article.find('h1',class_='sc-gVLVqr kEhnvA')\r\n if(title_tag == None):\r\n print('タイトルがありません')\r\n\r\n else:\r\n title = title_tag.text.translate(tbl)\r\n article = soup_article.find('p', class_='sc-kxynE cNCqYV yjSlinkDirectlink').text.translate(tbl)\r\n\r\n content = {'トピック': topic,\r\n 'タイトル': title,\r\n 'URL': url,\r\n '記事': article}\r\n contents.append(content)\r\n time.sleep(1)\r\n\r\nprint(contents)\r\n\r\n\r\n# 変数contentsを使って、データフレームを作成する\r\ndf = pd.DataFrame(contents)\r\ndf.to_csv('yahoo_info2021327.csv', index=None, encoding='utf-8-sig')\r\nprint(pd.read_csv('yahoo_info2021318.csv'))\r\n\r\n\r\n\"\"\"title = soup_article.find('h1',class_='sc-gVLVqr kEhnvA').text\r\n #print(title)\r\n #sys.exit()\r\n article = soup_article.find('p',class_='sc-kxynE cNCqYV yjSlinkDirectlink').text\r\n content = {'トピック':topic,\r\n 'タイトル':title,\r\n 'URL':url,\r\n '記事':article}\r\n contents.append(content)\r\n print(contents)\"\"\"\r\n\r\n\"\"\"if soup_article.original_encoding == 'windows-1252':\r\n print('error')\r\n else:\"\"\"","sub_path":"project_re.py","file_name":"project_re.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"385125613","text":"from setuptools import setup\n\n__VERSION__ = '0.1.5'\n\nsetup(\n name='json_resource_http',\n version=__VERSION__,\n packages=['json_resource_http'],\n long_description=open('./README.rst').read(),\n author='Ernst Odolphi',\n author_email='ernst.odolphi@gmail.com',\n install_requires=['json_resource', 'requests'],\n tests_require=['mock', 'nose'],\n test_suite='nose.collector'\n)\n","sub_path":"pypi_install_script/json_resource_http-0.1.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"95727630","text":"import random\n\naluno = \"Bruno\" # aluno = input(\"Nome do aluno: \")\nmatricula = 123456789 # matricula = input(\"Matricla do aluno: \")\nnumeronotas = 3 # numeronotas = int(input(\"Número de notas: \"))\n\ncontador = 0\nnota = 0\nnotatotal = 0\n\nwhile contador < numeronotas:\n #nota = float(input(\"Nota %dª: \" % (contador+1)))\n nota = random.randint(-12, 10)\n print(nota)\n while (nota < 0 or nota > 10):\n nota = int(input(\"\\n%dª nota está inválida, digite-a novamente: \" % (contador+1)))\n notatotal = notatotal + nota\n contador += 1\n\nprint(\"Media do aluno: %.2f\" % (notatotal/numeronotas))","sub_path":"estruturas repeticao/codigos/q1.1.py","file_name":"q1.1.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"152145010","text":"from django.urls import include, path\nfrom rest_framework.authtoken.views import obtain_auth_token\nfrom rest_framework import routers\nfrom . import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r'avaliacoes', views.AvaliacaoViewSet)\nrouter.register(r'pacientes', views.PacienteViewSet)\nrouter.register(r'core-sets', views.CoreSetViewSet)\nrouter.register(r'fontes-informacao', views.FonteInformacaoViewSet)\n\nurlpatterns = [\n path('', include(router.urls)),\n path('avaliar/', views.criar_avaliacao),\n path('usuario/', views.usuario),\n path('atualizar-usuario/', views.atualizar_usuario),\n path('novo-usuario/', views.novo_usuario),\n path('api-token-auth/', obtain_auth_token, name='api_token_auth'),\n]","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"604028902","text":"from datetime import datetime, time\nfrom typing import Callable, List, Optional\n\nimport pytest\nfrom dagster.check import CheckError\nfrom dagster.core.definitions.partition import (\n DynamicPartitionParams,\n Partition,\n ScheduleType,\n StaticPartitionParams,\n TimeBasedPartitionParams,\n)\nfrom dagster.utils.partitions import DEFAULT_HOURLY_FORMAT_WITH_TIMEZONE\n\n\n@pytest.mark.parametrize(\n argnames=[\"partitions\"],\n argvalues=[([Partition(\"a_partition\")],), ([Partition(x) for x in range(10)],)],\n)\ndef test_static_partition_params(partitions: List[Partition]):\n partition_params = StaticPartitionParams(partitions)\n\n assert partition_params.get_partitions(current_time=None) == partitions\n\n\n@pytest.mark.parametrize(\n argnames=[\"schedule_type\", \"start\", \"execution_day\", \"end\", \"error_message_regex\"],\n ids=[\n \"start should be before end\",\n \"hourly partitions, execution day should not be provided\",\n \"daily partitions, execution day should not be provided\",\n \"weekly partitions, execution day should be between 0 and 6\",\n \"monthly partitions, execution day should be between 1 and 31\",\n ],\n argvalues=[\n (\n ScheduleType.DAILY,\n datetime(year=2021, month=1, day=3),\n None,\n datetime(year=2021, month=1, day=1),\n r\"Selected date range start .* is after date range end\",\n ),\n (\n ScheduleType.HOURLY,\n datetime(year=2021, month=1, day=1),\n 1,\n datetime(year=2021, month=1, day=3),\n \"Execution day should not be provided\",\n ),\n (\n ScheduleType.DAILY,\n datetime(year=2021, month=1, day=1),\n 1,\n datetime(year=2021, month=1, day=3),\n \"Execution day should not be provided\",\n ),\n (\n ScheduleType.WEEKLY,\n datetime(year=2021, month=1, day=1),\n 7,\n datetime(year=2021, month=2, day=1),\n \"Execution day .* must be between 0 and 6\",\n ),\n (\n ScheduleType.MONTHLY,\n datetime(year=2021, month=1, day=1),\n 0,\n datetime(year=2021, month=2, day=1),\n \"Execution day .* must be between 1 and 31\",\n ),\n ],\n)\ndef test_time_based_partition_params_invariants(\n schedule_type: ScheduleType,\n start: datetime,\n execution_day: Optional[int],\n end: Optional[datetime],\n error_message_regex: str,\n):\n with pytest.raises(CheckError, match=error_message_regex):\n TimeBasedPartitionParams(\n schedule_type=schedule_type,\n start=start,\n execution_day=execution_day,\n execution_time=None,\n end=end,\n fmt=None,\n inclusive=None,\n timezone=None,\n offset=None,\n )\n\n\n@pytest.mark.parametrize(\n argnames=[\n \"schedule_type\",\n \"start\",\n \"execution_day\",\n \"execution_time\",\n \"end\",\n \"fmt\",\n \"inclusive\",\n \"timezone\",\n \"offset\",\n \"expected_partitions\",\n ],\n ids=[\n \"daily partitions, not inclusive\",\n \"daily partitions, inclusive\",\n \"daily partitions, different start/end year\",\n \"daily partitions, leap year\",\n \"daily partitions, not leap year\",\n \"monthly partitions\",\n \"monthly partitions, different start/end year\",\n \"monthly partitions, start/end not at least a month apart\",\n \"weekly partitions\",\n \"hourly partitions, Spring DST\",\n \"hourly partitions, Spring DST with timezone\",\n \"hourly partitions, Fall DST\",\n \"hourly partitions, Fall DST with timezone\",\n ],\n argvalues=[\n (\n ScheduleType.DAILY,\n datetime(year=2020, month=1, day=1),\n None,\n None,\n datetime(year=2020, month=1, day=6),\n None,\n False,\n None,\n None,\n [\"2020-01-01\", \"2020-01-02\", \"2020-01-03\", \"2020-01-04\", \"2020-01-05\"],\n ),\n (\n ScheduleType.DAILY,\n datetime(year=2020, month=1, day=1),\n None,\n None,\n datetime(year=2020, month=1, day=6, hour=1),\n None,\n True,\n None,\n None,\n [\"2020-01-01\", \"2020-01-02\", \"2020-01-03\", \"2020-01-04\", \"2020-01-05\", \"2020-01-06\"],\n ),\n (\n ScheduleType.DAILY,\n datetime(year=2020, month=12, day=29),\n None,\n None,\n datetime(year=2021, month=1, day=3),\n None,\n None,\n None,\n None,\n [\"2020-12-29\", \"2020-12-30\", \"2020-12-31\", \"2021-01-01\", \"2021-01-02\"],\n ),\n (\n ScheduleType.DAILY,\n datetime(year=2020, month=2, day=28),\n None,\n None,\n datetime(year=2020, month=3, day=3),\n None,\n None,\n None,\n None,\n [\"2020-02-28\", \"2020-02-29\", \"2020-03-01\", \"2020-03-02\"],\n ),\n (\n ScheduleType.DAILY,\n datetime(year=2019, month=2, day=28),\n None,\n None,\n datetime(year=2019, month=3, day=3),\n None,\n None,\n None,\n None,\n [\"2019-02-28\", \"2019-03-01\", \"2019-03-02\"],\n ),\n (\n ScheduleType.MONTHLY,\n datetime(year=2020, month=1, day=1),\n None,\n None,\n datetime(year=2020, month=3, day=6),\n None,\n None,\n None,\n None,\n [\"2020-01-01\", \"2020-02-01\"],\n ),\n (\n ScheduleType.MONTHLY,\n datetime(year=2020, month=12, day=1),\n None,\n None,\n datetime(year=2021, month=2, day=6),\n None,\n None,\n None,\n None,\n [\"2020-12-01\", \"2021-01-01\"],\n ),\n (\n ScheduleType.MONTHLY,\n datetime(year=2020, month=2, day=12),\n None,\n None,\n datetime(year=2020, month=3, day=11),\n None,\n None,\n None,\n None,\n [],\n ),\n (\n ScheduleType.WEEKLY,\n datetime(year=2020, month=1, day=1),\n None,\n None,\n datetime(year=2020, month=1, day=27),\n None,\n None,\n None,\n None,\n [\"2020-01-01\", \"2020-01-08\", \"2020-01-15\"],\n ),\n (\n ScheduleType.HOURLY,\n datetime(year=2019, month=3, day=10, hour=1),\n None,\n None,\n datetime(year=2019, month=3, day=10, hour=4),\n DEFAULT_HOURLY_FORMAT_WITH_TIMEZONE,\n True,\n \"UTC\",\n None,\n [\n \"2019-03-10-01:00+0000\",\n \"2019-03-10-02:00+0000\",\n \"2019-03-10-03:00+0000\",\n \"2019-03-10-04:00+0000\",\n ],\n ),\n (\n ScheduleType.HOURLY,\n datetime(year=2019, month=3, day=10, hour=1),\n None,\n None,\n datetime(year=2019, month=3, day=10, hour=4),\n DEFAULT_HOURLY_FORMAT_WITH_TIMEZONE,\n True,\n \"US/Central\",\n None,\n [\"2019-03-10-01:00-0600\", \"2019-03-10-03:00-0500\", \"2019-03-10-04:00-0500\"],\n ),\n (\n ScheduleType.HOURLY,\n datetime(year=2019, month=11, day=3, hour=0),\n None,\n None,\n datetime(year=2019, month=11, day=3, hour=3),\n DEFAULT_HOURLY_FORMAT_WITH_TIMEZONE,\n True,\n \"UTC\",\n None,\n [\n \"2019-11-03-00:00+0000\",\n \"2019-11-03-01:00+0000\",\n \"2019-11-03-02:00+0000\",\n \"2019-11-03-03:00+0000\",\n ],\n ),\n (\n ScheduleType.HOURLY,\n datetime(year=2019, month=11, day=3, hour=0),\n None,\n None,\n datetime(year=2019, month=11, day=3, hour=3),\n DEFAULT_HOURLY_FORMAT_WITH_TIMEZONE,\n True,\n \"US/Central\",\n None,\n [\n \"2019-11-03-00:00-0500\",\n \"2019-11-03-01:00-0500\",\n \"2019-11-03-01:00-0600\",\n \"2019-11-03-02:00-0600\",\n \"2019-11-03-03:00-0600\",\n ],\n ),\n ],\n)\ndef test_time_based_partition_params(\n schedule_type: ScheduleType,\n start: datetime,\n execution_day: Optional[int],\n execution_time: Optional[time],\n end: Optional[datetime],\n fmt: Optional[str],\n inclusive: Optional[bool],\n timezone: Optional[str],\n offset: Optional[int],\n expected_partitions: List[str],\n):\n partition_params = TimeBasedPartitionParams(\n schedule_type=schedule_type,\n start=start,\n execution_day=execution_day,\n execution_time=execution_time,\n end=end,\n fmt=fmt,\n inclusive=inclusive,\n timezone=timezone,\n offset=offset,\n )\n\n generated_partitions = partition_params.get_partitions(current_time=None)\n\n assert all(\n isinstance(generated_partition, Partition) for generated_partition in generated_partitions\n )\n assert len(generated_partitions) == len(expected_partitions)\n assert all(\n generated_partition.name == expected_partition_name\n for generated_partition, expected_partition_name in zip(\n generated_partitions, expected_partitions\n )\n )\n\n\n@pytest.mark.parametrize(\n argnames=[\"partition_fn\"],\n argvalues=[\n (lambda _current_time: [Partition(\"a_partition\")],),\n (lambda _current_time: [Partition(x) for x in range(10)],),\n ],\n)\ndef test_dynamic_partitions(partition_fn: Callable[[Optional[datetime]], List[Partition]]):\n partition_params = DynamicPartitionParams(partition_fn)\n\n assert partition_params.get_partitions(current_time=None) == partition_fn(None)\n","sub_path":"python_modules/dagster/dagster_tests/core_tests/partition_tests/test_partition.py","file_name":"test_partition.py","file_ext":"py","file_size_in_byte":10208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583618173","text":"# Copyright (c) Jeremías Casteglione \n# See LICENSE file.\n\nfrom os import getenv\nfrom io import StringIO\n\nfrom _sadm import log, cfg\nfrom _sadm.web import tpl\nfrom _sadm.web.app import wapp, view\n\n@wapp.route('/')\n@view('index.html')\n@tpl.data('home')\ndef index():\n\tlog.debug(\"index\")\n\tconfig = cfg.new()\n\treturn {\n\t\t'cfgfile': config.filename(),\n\t\t'cfg': _getCfg(config),\n\t\t'user': getenv('USER', 'nouser?'),\n\t}\n\ndef _getCfg(config):\n\tbuf = StringIO()\n\tconfig.reload()\n\tconfig.write(buf)\n\tbuf.seek(0, 0)\n\treturn buf.read()\n","sub_path":"_sadm/web/view/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"472479898","text":"import graphene\nfrom graphene import ObjectType\nfrom rethinkdb import RethinkDB\nfrom rx import Observable\nfrom enum import Enum\n\nfrom connman import ReDBConnection\n\n\nclass Change(graphene.Enum):\n Initial = 'initial'\n Add = 'add'\n Remove = 'remove'\n Change = 'change'\n\n\ndef str_to_changetype(s: str) -> Change:\n if s == 'initial':\n return Change.Initial\n elif s == 'add':\n return Change.Add\n elif s == 'remove':\n return Change.Remove\n elif s == 'change':\n return Change.Change\n else:\n raise ValueError(f\"No such ChangeType: {s}\")\n\ndef MakeSubscriptionWithChangeType(_class : type) -> type:\n return type(f'{_class.__name__}sSubscription',\n (ObjectType, ),\n {\n 'change_type': graphene.Field(Change, required=True, description=\"Change type\"),\n 'value': graphene.Field(_class, required=True)\n })\n\ndef MakeSubscription(_class : type) -> type:\n '''\n Creates a subscription type for resolve_item_by_pkey\n This is suitable when one wants to subscribe to changes for one particular item\n :param _class:\n :return:\n '''\n #return type(f'{_class.__name__}Subscription',\n # (ObjectType, ),\n # {\n # _class.__name__: graphene.Field(_class)\n # })\n return _class\n\n\ndef resolve_item_by_key(item_class: type, db, table_name : str, key_name: str='uuid'):\n \"\"\"\n Returns an asynchronous function that resolves every change in RethinkDB table with item with said primary key\n If item is deleted or does not exist, returns null in place of an item\n :param item_class: A GraphQL object type that has the same shape as a table\n :param table: a RethinkDB table to retrieve updates from\n :return: function that returns Observable. Works with asyncio\n \"\"\"\n def resolve_item(root, info, **args) -> Observable:\n '''\n Create a field with MakeSubscription(type)\n :param root:\n :param info:\n :param args:\n :return:\n '''\n async def iterable_to_item():\n async with ReDBConnection().get_async_connection() as conn:\n key = args.get(key_name, None)\n if not key:\n yield None\n return\n table = db.table(table_name)\n changes = await table.get_all(key) \\\n .pluck(*item_class._meta.fields)\\\n .changes(include_types=True, include_initial=True).run(conn)\n while True:\n change = await changes.next()\n if not change:\n break\n if change['type'] == 'remove' or change['new_val'] is None:\n yield None\n continue\n else:\n value = change['new_val']\n\n yield item_class(**value)\n\n return Observable.from_future(iterable_to_item())\n return resolve_item\n\n\ndef resolve_all_items_changes(item_class: type, db, table_name : str):\n \"\"\"\n Returns an asynchronous function that resolves every change in RethinkDB table\n\n :param item_class: GraphQL object type that has same shape as a table\n :param table: RethinkDB table\n :return:\n \"\"\"\n def resolve_items(root, info) -> Observable:\n '''\n Returns subscription updates with the following shape:\n {\n changeType: one of Initial, Add, Mod, Remove\n value: of type item_class\n }\n Create a field with MakeSubscriptionWithChangeType(type)\n :param info:\n :return:\n '''\n async def iterable_to_items():\n async with ReDBConnection().get_async_connection() as conn:\n table = db.table(table_name)\n changes = await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=True).run(conn)\n while True:\n change = await changes.next()\n if not change:\n break\n if change['type'] == 'remove':\n value = change['old_val']\n else:\n value = change['new_val']\n\n value = item_class(**value)\n yield MakeSubscriptionWithChangeType(item_class)(change_type=str_to_changetype(change['type']),\n value=value)\n\n return Observable.from_future(iterable_to_items())\n return resolve_items\n","sub_path":"handlers/graphql/resolvers/subscription_utils.py","file_name":"subscription_utils.py","file_ext":"py","file_size_in_byte":4686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"161449527","text":"import pandas as pd\n\ndf1 = pd.read_csv('automl3_result.csv')\n\ndf1 = df1.loc[:, ['Id', 'predicted_SalePrice']]\n\ndf1 = df1.rename(columns={'predicted_SalePrice': 'SalePrice'})\n\ndf2 = pd.read_csv('forest_result.csv')\n\ndf_new = df1.append(df2, ignore_index=True).drop_duplicates(subset=\"Id\")\n\ndf_new.to_csv('automl4_result.csv', index=False)","sub_path":"automl_combine.py","file_name":"automl_combine.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"521024331","text":"# coding: utf-8\n\n\"\"\"\n Alfresco Content Services REST API\n\n **Core API** Provides access to the core features of Alfresco Content Services. # noqa: E501\n\n The version of the OpenAPI document: 1\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom openapi_client.configuration import Configuration\n\n\nclass ActionDefinition(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'id': 'str',\n 'name': 'str',\n 'title': 'str',\n 'description': 'str',\n 'applicable_types': 'list[str]',\n 'track_status': 'bool',\n 'parameter_definitions': 'list[ActionParameterDefinition]'\n }\n\n attribute_map = {\n 'id': 'id',\n 'name': 'name',\n 'title': 'title',\n 'description': 'description',\n 'applicable_types': 'applicableTypes',\n 'track_status': 'trackStatus',\n 'parameter_definitions': 'parameterDefinitions'\n }\n\n def __init__(self, id=None, name=None, title=None, description=None, applicable_types=None, track_status=None, parameter_definitions=None, local_vars_configuration=None): # noqa: E501\n \"\"\"ActionDefinition - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._id = None\n self._name = None\n self._title = None\n self._description = None\n self._applicable_types = None\n self._track_status = None\n self._parameter_definitions = None\n self.discriminator = None\n\n self.id = id\n if name is not None:\n self.name = name\n if title is not None:\n self.title = title\n if description is not None:\n self.description = description\n self.applicable_types = applicable_types\n self.track_status = track_status\n if parameter_definitions is not None:\n self.parameter_definitions = parameter_definitions\n\n @property\n def id(self):\n \"\"\"Gets the id of this ActionDefinition. # noqa: E501\n\n Identifier of the action definition — used for example when executing an action # noqa: E501\n\n :return: The id of this ActionDefinition. # noqa: E501\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"Sets the id of this ActionDefinition.\n\n Identifier of the action definition — used for example when executing an action # noqa: E501\n\n :param id: The id of this ActionDefinition. # noqa: E501\n :type: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and id is None: # noqa: E501\n raise ValueError(\"Invalid value for `id`, must not be `None`\") # noqa: E501\n\n self._id = id\n\n @property\n def name(self):\n \"\"\"Gets the name of this ActionDefinition. # noqa: E501\n\n name of the action definition, e.g. \\\"move\\\" # noqa: E501\n\n :return: The name of this ActionDefinition. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this ActionDefinition.\n\n name of the action definition, e.g. \\\"move\\\" # noqa: E501\n\n :param name: The name of this ActionDefinition. # noqa: E501\n :type: str\n \"\"\"\n\n self._name = name\n\n @property\n def title(self):\n \"\"\"Gets the title of this ActionDefinition. # noqa: E501\n\n title of the action definition, e.g. \\\"Move\\\" # noqa: E501\n\n :return: The title of this ActionDefinition. # noqa: E501\n :rtype: str\n \"\"\"\n return self._title\n\n @title.setter\n def title(self, title):\n \"\"\"Sets the title of this ActionDefinition.\n\n title of the action definition, e.g. \\\"Move\\\" # noqa: E501\n\n :param title: The title of this ActionDefinition. # noqa: E501\n :type: str\n \"\"\"\n\n self._title = title\n\n @property\n def description(self):\n \"\"\"Gets the description of this ActionDefinition. # noqa: E501\n\n describes the action definition, e.g. \\\"This will move the matched item to another space.\\\" # noqa: E501\n\n :return: The description of this ActionDefinition. # noqa: E501\n :rtype: str\n \"\"\"\n return self._description\n\n @description.setter\n def description(self, description):\n \"\"\"Sets the description of this ActionDefinition.\n\n describes the action definition, e.g. \\\"This will move the matched item to another space.\\\" # noqa: E501\n\n :param description: The description of this ActionDefinition. # noqa: E501\n :type: str\n \"\"\"\n\n self._description = description\n\n @property\n def applicable_types(self):\n \"\"\"Gets the applicable_types of this ActionDefinition. # noqa: E501\n\n QNames of the types this action applies to # noqa: E501\n\n :return: The applicable_types of this ActionDefinition. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._applicable_types\n\n @applicable_types.setter\n def applicable_types(self, applicable_types):\n \"\"\"Sets the applicable_types of this ActionDefinition.\n\n QNames of the types this action applies to # noqa: E501\n\n :param applicable_types: The applicable_types of this ActionDefinition. # noqa: E501\n :type: list[str]\n \"\"\"\n if self.local_vars_configuration.client_side_validation and applicable_types is None: # noqa: E501\n raise ValueError(\"Invalid value for `applicable_types`, must not be `None`\") # noqa: E501\n\n self._applicable_types = applicable_types\n\n @property\n def track_status(self):\n \"\"\"Gets the track_status of this ActionDefinition. # noqa: E501\n\n whether the basic action definition supports action tracking or not # noqa: E501\n\n :return: The track_status of this ActionDefinition. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._track_status\n\n @track_status.setter\n def track_status(self, track_status):\n \"\"\"Sets the track_status of this ActionDefinition.\n\n whether the basic action definition supports action tracking or not # noqa: E501\n\n :param track_status: The track_status of this ActionDefinition. # noqa: E501\n :type: bool\n \"\"\"\n if self.local_vars_configuration.client_side_validation and track_status is None: # noqa: E501\n raise ValueError(\"Invalid value for `track_status`, must not be `None`\") # noqa: E501\n\n self._track_status = track_status\n\n @property\n def parameter_definitions(self):\n \"\"\"Gets the parameter_definitions of this ActionDefinition. # noqa: E501\n\n\n :return: The parameter_definitions of this ActionDefinition. # noqa: E501\n :rtype: list[ActionParameterDefinition]\n \"\"\"\n return self._parameter_definitions\n\n @parameter_definitions.setter\n def parameter_definitions(self, parameter_definitions):\n \"\"\"Sets the parameter_definitions of this ActionDefinition.\n\n\n :param parameter_definitions: The parameter_definitions of this ActionDefinition. # noqa: E501\n :type: list[ActionParameterDefinition]\n \"\"\"\n\n self._parameter_definitions = parameter_definitions\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ActionDefinition):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, ActionDefinition):\n return True\n\n return self.to_dict() != other.to_dict()\n","sub_path":"openapi_client/models/action_definition.py","file_name":"action_definition.py","file_ext":"py","file_size_in_byte":9301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"364702983","text":"# File: TestLinkedList.py\n\n# Description: Linked List assignment\n\n# Student Name: Hussain Bharmal\n\n# Student UT EID: hab889\n\n# Partner Name: N/A\n\n# Partner UT EID: N/A\n\n# Course Name: CS 313E\n\n# Unique Number: 51340\n\n# Date Created: 03/29/2018\n\n# Date Last Modified: 03/29/2018\n\nclass Link (object):\n\tdef __init__(self, item, next = None):\n\t\tself.item = item\n\t\tself.next = next\n\t\n\tdef __str__(self):\n\t return str(self.item)\n\nclass LinkedList (object):\n\n\t# constructor \n\tdef __init__(self):\n\t\tself.first = None\n\n\t# get number of links \n\tdef get_num_links (self):\n\t\tcount = 0\n\t\tcurrent = self.first\n\t\twhile (current.next != None):\n\t\t\tcount += 1\n\t\t\tcurrent = current.next\n\t\treturn count\n\t\n\t# add an item at the beginning of the list\n\tdef insert_first (self, item): \n\t\tnewFirst = Link(item)\n\t\tnewFirst.next = self.first\n\t\tself.first = newFirst\n\n\t# add an item at the end of a list\n\tdef insert_last (self, item): \n\t\tnewLast = Link(item)\n\t\tcurrent = self.first\n\t\tif (current == None):\n\t\t self.first = newLast\n\t\t return\n\t\twhile (current.next != None):\n\t\t\tcurrent = current.next\n\t\tcurrent.next = newLast\n\n\t# add an item in an ordered list in ascending order\n\tdef insert_in_order (self, item): \n\t\tif (self.first == None):\n\t\t\tself.insert_first(item)\n\t\t\treturn\n\t\telif (item < self.first.item):\n\t\t\tself.insert_first(item)\n\t\t\treturn\n\t\telse:\n\t\t\tnewLink = Link(item)\n\t\t\tcurrent = self.first\n\t\t\tprevious = self.first\n\t\t\twhile (item > current.item):\n\t\t\t\tif (current.next == None):\n\t\t\t\t\tself.insert_last(item)\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\tprevious = current \n\t\t\t\t\tcurrent = current.next\n\t\t\tprevious.next = newLink\n\t\t\tnewLink.next = current\n\n\t# search in an unordered list, return None if not found\n\tdef find_unordered (self, item): \n\t\tcurrent = self.first\n\t\tif (current == None):\n\t\t\treturn None\n\t\twhile (current != None):\n\t\t\tif (current.item == item):\n\t\t\t\treturn current\n\t\t\telse:\n\t\t\t\tcurrent = current.next\n\t\treturn None\n\n\t# Search in an ordered list, return None if not found\n\tdef find_ordered (self, item): \n\t\tcurrent = self.first\n\t\tif (current == None):\n\t\t\treturn None\n\t\twhile (current.next != None):\n\t\t\tif (current.item == item):\n\t\t\t\treturn current\n\t\t\telif (item < current.item):\n\t\t\t\treturn None\n\t\t\telse:\n\t\t\t\tcurrent = current.next\n\t\treturn None\n\n\n\t# Delete and return Link from an unordered list or None if not found\n\tdef delete_link (self, item):\n\t\tcurrent = self.first\n\t\tprevious = self.first\n\t\tif (current == None):\n\t\t\treturn None\n\t\twhile (current.next != None):\n\t\t\tif (current.item == item):\n\t\t\t\tif (current == self.first):\n\t\t\t\t\tself.first = self.first.next\n\t\t\t\telse:\n\t\t\t\t\tprevious.next = current.next\n\t\t\t\treturn current\n\t\t\telse:\n\t\t\t\tprevious = current\n\t\t\t\tcurrent = current.next\n\t\treturn None\n\n\t# String representation of data 10 items to a line, 2 spaces between data\n\tdef __str__ (self):\n\t\ttext = \"\"\n\t\tcurrent = self.first\n\t\titer = 1\n\t\tif (self.is_empty()):\n\t\t\treturn \"LinkedList is Empty\"\n\t\twhile (current.next != None):\n\t\t\tif (iter % 10 == 0):\n\t\t\t\ttext += \"\\n\"\n\t\t\t\ttext += str(current.item) + \" \"\n\t\t\telse:\n\t\t\t\ttext += str(current.item) + \" \"\n\t\t\titer += 1\n\t\t\tcurrent = current.next\n\t\treturn text\n\n\t# Copy the contents of a list and return new list\n\tdef copy_list (self):\n\t\tclone = LinkedList()\n\t\tcurrent = self.first\n\t\twhile (current != None):\n\t\t\tclone.insert_last(current.item)\n\t\t\tcurrent = current.next\n\t\treturn clone\n\n\t# Reverse the contents of a list and return new list\n\tdef reverse_list (self): \n\t\tclone = LinkedList()\n\t\tcurrent = self.first\n\t\twhile (current != None):\n\t\t\tclone.insert_first(current.item)\n\t\t\tcurrent = current.next\n\t\treturn clone\n\n\t# Sort the contents of a list in ascending order and return new list\n\tdef sort_list (self): \n\t\tsorted_list = LinkedList()\n\t\tcurrent = self.first\n\t\tif (self.is_empty()):\n\t\t\treturn sorted_list\n\t\twhile (current != None):\n\t\t\tsorted_list.insert_in_order(current.item)\n\t\t\tcurrent = current.next\n\t\treturn sorted_list\n\n\t# Return True if a list is sorted in ascending order or False otherwise\n\tdef is_sorted (self):\n\t\tcurrent = self.first\n\t\tif (self.is_empty() or self.get_num_links() == 1):\n\t\t\treturn True\n\t\twhile (current != None):\n\t\t\tif (current.item > current.next.item):\n\t\t\t\treturn False\n\t\t\tcurrent = current.next\n\t\treturn True\n\n\t# Return True if a list is empty or False otherwise\n\tdef is_empty (self): \n\t\treturn (self.first == None)\n\n\t# Merge two sorted lists and return new list in ascending order\n\tdef merge_list (self, other):\n\t\tnew_list = LinkedList()\n\t\tcurrent = self.first\n\t\twhile current.next != None:\n\t\t\tnew_list.insert_in_order(current.item)\n\t\t\tcurrent = current.next\n\t\tcurrent = other.first\n\t\twhile current.next != None:\n\t\t\tnew_list.insert_in_order(current.item)\n\t\t\tcurrent = current.next\n\t\treturn new_list\n\n\t# Test if two lists are equal, item by item and return True\n\tdef is_equal (self, other):\n\t\tif (self.get_num_links() != other.get_num_links()):\n\t\t\treturn False\n\t\tif (self.is_empty() and other.is_empty()):\n\t\t\treturn True\n\t\tcurrent_1 = self.first\n\t\tcurrent_2 = other.first\n\t\twhile (current_1.next != None):\n\t\t\tif (current_1.item != current_2.item):\n\t\t\t\treturn False\n\t\t\tcurrent_1 = current_1.next\n\t\t\tcurrent_2 = current_2.next\n\t\treturn True\n\n\t# Return a new list, keeping only the first occurence of an element\n\t# and removing all duplicates. Do not change the order of the elements.\n\tdef remove_duplicates (self):\n\t\tnew_list = self.copy_list()\n\t\tprevious = new_list.first\n\t\tcurrent = new_list.first\n\t\telements = []\n\t\twhile (current.next != None):\n\t\t\tif (current.item in elements):\n\t\t\t\tprevious.next = current.next\n\t\t\telse:\n\t\t\t\telements.append(current.item)\n\t\t\t\tprevious = current\n\t\t\tcurrent = current.next\n\t\treturn new_list\n\ndef main():\n\ttest_case = [1, 2, 5, 9, 4, 8, 7]\n\t\n\t# Test methods insert_first() and __str__() by adding more than 10 items to a list and printing it.\n\tprint(\"Testing methods insert_first() & __str__().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_first(test_case[i])\n\tprint(test_list)\n\tdel test_list\n\tprint()\n\n\t# Test method insert_last()\n\tprint(\"Testing method insert_last().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_last(test_case[i])\n\tprint(test_list)\n\tdel test_list\n\tprint()\n\n\t# Test method insert_in_order()\n\tprint(\"Testing method insert_in_order().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_in_order(test_case[i])\n\tprint(test_list)\n\tdel test_list\n\tprint()\n\n\t# Test method get_num_links()\n\tprint(\"Testing method get_num_links().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_first(test_case[i])\n\tprint(\"List: %s\" %(test_list))\n\tprint(\"Result: %s\" %(test_list.get_num_links()))\n\tdel test_list\n\tprint()\n\n\t# Test method find_unordered() \n\t# Consider two cases - item is there, item is not there \n\tprint(\"Testing method find_unordered().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_first(test_case[i])\n\tprint(\"Find 9: %s\" %(test_list.find_unordered(9)))\n\tprint(\"Find 3: %s\" %(test_list.find_unordered(3)))\n\tdel test_list\n\tprint()\n\n\t# Test method find_ordered() \n\t# Consider two cases - item is there, item is not there\n\tprint(\"Testing method find_ordered().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_in_order(test_case[i])\n\tprint(\"Find 9: %s\" %(test_list.find_ordered(9)))\n\tprint(\"Find 3: %s\" %(test_list.find_ordered(3)))\n\tdel test_list\n\tprint()\n\n\t# Test method delete_link()\n\t# Consider two cases - item is there, item is not there \n\tprint(\"Testing method delete().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_first(test_case[i])\n\tprint(\"Delete 9: %s\" %(test_list.delete_link(9)))\n\tprint(\"Delete 3: %s\" %(test_list.delete_link(3)))\n\tdel test_list\n\tprint()\n\n\t# Test method copy_list()\n\tprint(\"Testing method copy_list().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_last(test_case[i])\n\ttest_list_copy = test_list.copy_list()\n\tprint(\"Initial List: %s\" %(test_list))\n\tprint(\"Copy List: %s\" %(test_list_copy))\n\tdel test_list\n\tprint()\n\n\t# Test method reverse_list()\n\tprint(\"Testing method reverse_list().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_last(test_case[i])\n\ttest_list_reverse = test_list.reverse_list()\n\tprint(\"Initial List: %s\" %(test_list))\n\tprint(\"Reverse List: %s\" %(test_list_reverse))\n\tdel test_list\n\tprint()\n\n\t# Test method sort_list()\n\tprint(\"Testing method sort_list().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_last(test_case[i])\n\ttest_list_sorted = test_list.sort_list()\n\tprint(\"Initial List: %s\" %(test_list))\n\tprint(\"Sorted List: %s\" %(test_list_sorted))\n\tdel test_list\n\tprint()\n\n\t# Test method is_sorted()\n\t# Consider two cases - list is sorted, list is not sorted\n\tprint(\"Testing method is_sorted().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_last(test_case[i])\n\ttest_list_sorted = test_list.sort_list()\n\tprint(\"Initial List: %s\" %(test_list))\n\tprint(\"Sorted List: %s\" %(test_list_sorted))\n\tdel test_list\n\tprint()\n\n\t# Test method is_empty()\n\tprint(\"Testing method is_empty().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_last(test_case[i])\n\tprint(\"Current List: %s\" %(test_list))\n\tprint(\"Result: %s\" %(test_list.is_empty()))\n\tdel test_list\n\tprint()\n\n\t# Test method merge_list()\n\tprint(\"Testing method merge_list().\")\n\ttest_list = LinkedList()\n\ttest_list_2 = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_last(test_case[i])\n\t\ttest_list_2.insert_first(test_case[i])\n\tmerged_list = test_list.merge_list(test_list_2)\n\tprint(\"Initial List: %s\" %(test_list))\n\tprint(\"Merged List: %s\" %(merged_list))\n\tdel test_list, test_list_2\n\tprint()\n\n\t# Test method is_equal()\n\t# Consider two cases - lists are equal, lists are not equal\n\tprint(\"Testing method is_equal().\")\n\ttest_list = LinkedList()\n\ttest_list_2 = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_in_order(test_case[i])\n\t\ttest_list_2.insert_first(test_case[i])\n\tprint(\"List 1: %s\" %(test_list))\n\tprint(\"List 2: %s\" %(test_list_2))\n\tprint(\"Result: %s\" %(test_list.is_equal(test_list_2)))\n\ttest_list_3 = test_list_2.sort_list()\n\tprint(\"List 1: %s\" %(test_list))\n\tprint(\"List 2: %s\" %(test_list_3))\n\tprint(\"Result: %s\" %(test_list.is_equal(test_list_3))) \n\tdel test_list, test_list_2, test_list_3\n\tprint()\n\n\t# Test remove_duplicates()\n\tprint(\"Testing method remove_duplicates().\")\n\ttest_list = LinkedList()\n\tfor i in range (len(test_case)):\n\t\ttest_list.insert_in_order(test_case[i])\n\ttest_list.insert_in_order(4)\n\ttest_list.insert_in_order(8)\n\tremoved = test_list.remove_duplicates()\n\tprint(\"List with duplicates: %s\" %(test_list))\n\tprint(\"List without duplicates: %s\" %(removed))\n\tdel test_list, removed\n\tprint()\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"TestLinkedLists.py","file_name":"TestLinkedLists.py","file_ext":"py","file_size_in_byte":10807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"612548055","text":"# -*- coding: utf-8 -*-\nimport Tkinter as tk\nfrom Tkinter import *\nfrom select_queries import SelectQueries\nfrom select_features import SelectFeatures\nfrom select_test_data import SelectTestData\n\nclass StdoutRedirector(object):\n def __init__(self, text_ctrl):\n self.output = text_ctrl\n\n def write(self, string):\n self.output.config(state=\"normal\")\n self.output.insert(\"insert\", string)\n self.output.config(state=\"disabled\")\n\n\nclass IORedirector(object):\n def __init__(self, text_area):\n self.text_area = text_area\n\n\nclass TwitterAnalysisApp(Tk):\n def __init__(self, *args, **kwargs):\n Tk.__init__(self, *args, **kwargs)\n\n container = tk.Frame(self)\n container.grid(sticky=tk.N + tk.S + tk.E + tk.W)\n # container.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=tk.YES)\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n\n self.data_storage = {'queries': []}\n self.frames = {}\n for F in (SelectQueries,SelectFeatures,SelectTestData):\n page_name = F.title_frame\n frame = F(container, self)\n self.frames[page_name] = frame\n frame.grid(row=0, column=0, sticky=tk.N + tk.S + tk.E + tk.W)\n self.show_frame(\"Select Test Data\")\n\n\n def show_frame(self, page_name):\n # frame = self.frames[page_name]\n # frame.tkraise()\n # frame.winfo_toplevel().geometry(\"\")\n for frame in self.frames.values():\n frame.grid_remove()\n frame = self.frames[page_name]\n frame.grid()\n frame.winfo_toplevel().geometry(\"\")\n\n\napp = TwitterAnalysisApp()\napp.wm_title(u'WoS Data Analyser © Copyright Mladen Dinev')\n# app.geometry(\"450x150\")\nmenubar = Menu(app)\nfile = Menu(menubar, tearoff=0)\nfile.add_command(label=\"Quit\", command=lambda: app.quit())\nmenubar.add_cascade(label=\"File\", menu=file)\n\naboutMenu = Menu(app, tearoff=0)\naboutMenu.add_command(label=\"About\", command='')\nmenubar.add_cascade(label=\"Help\", menu=aboutMenu)\napp.config(menu=menubar)\napp.mainloop()\n","sub_path":"src/GUI/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"72266414","text":"import discord\nfrom discord.ext import commands\nfrom osuapi import OsuApi, AHConnector\nimport osuapi.enums\nimport utils.errors\n\nclass Osu:\n def __init__(self, bot):\n self.bot = bot\n if bot.config['osu']:\n self.api = OsuApi(bot.config['osu'], connector=AHConnector())\n else:\n self.api = None\n\n @classmethod\n def osu_mode_converter(self, mode=None):\n if mode is 0 or 'standard' or 'osu!standard' or 'osu!' or None:\n return osuapi.enums.OsuMode.osu\n elif mode is 1 or 'ctb' or 'catchthebeat' or 'osu!catch' or 'catch':\n return osuapi.enums.OsuMode.catch\n elif mode is 2 or 'taiko' or 'osu!taiko':\n return osuapi.enums.OsuMode.taiko\n elif mode is 3 or 'mania' or 'osu!mania':\n return osuapi.enums.OsuMode.mania\n else:\n return 'Unknown'\n\n\n @commands.group()\n async def osu(self, ctx):\n \"\"\"Commands for osu!\"\"\"\n if ctx.invoked_subcommand is None:\n help_em = discord.Embed(title='Commands for osu!', colour=0x690E8)\n help_em.add_field(name='user', value='Gets info on osu! players. `^osu user *user*`')\n await ctx.send(embed=help_em)\n\n @osu.command()\n async def user(self, ctx, u: str, mode=None):\n \"\"\"Returns information on a osu! player.\n If the player name you are searching has spaces, use quotation marks.\n e.g. ^osu user \"player name with spaces\"\n Special thanks to khazhyk for the library this command uses.\n\n By default this command defaults to osu!standard.\n All modes are supported.\n To use osu!standard, leave mode blank, or use 'standard', 'osu!standard', 'osu!' or 0.\n To use osu!catch, use 'catch', 'osu!catch', or 1.\n To use osu!taiko, use 'taiko', 'osu!taiko', or 2.\n To use osu!mania, use 'mania', 'osu!mania', or 3.\n Any other modes will return 'Unknown' error. (Service error)\n \"\"\"\n if self.api:\n mode = self.osu_mode_converter(mode=mode)\n if mode == 'Unknown':\n raise utils.errors.ServiceError('Unknown mode')\n user = await self.api.get_user(u, mode=mode)\n try:\n user = user[0]\n except IndexError:\n return await ctx.send('User does not exist, maybe try one that does')\n else:\n raise utils.errors.ServiceError('osu! api key not configured')\n osu_embed = discord.Embed(title=f'osu! stats', colour=0x690E8)\n osu_embed.set_author(name=f'{u} ({user.country})',icon_url=f'https://osu.ppy.sh/images/flags/{user.country}.png')\n osu_embed.set_image(url=f'https://a.ppy.sh/{user.user_id}')\n osu_embed.add_field(name='User ID', value=user.user_id)\n osu_embed.add_field(name='Hits (300 score)', value=user.count300)\n osu_embed.add_field(name='Hits (100 score)', value=user.count100)\n osu_embed.add_field(name='Hits (50 score)', value=user.count50)\n osu_embed.add_field(name='Play count', value=user.playcount)\n osu_embed.add_field(name='Ranked score', value=user.ranked_score)\n osu_embed.add_field(name='Total score', value=user.total_score)\n osu_embed.add_field(name='Global rank', value=f'#{user.pp_rank}')\n osu_embed.add_field(name='Country rank', value=f'#{user.pp_country_rank}')\n osu_embed.add_field(name='Level', value=user.level)\n osu_embed.add_field(name='Total PP', value=user.pp_raw)\n osu_embed.add_field(name='Accuracy', value=f'{user.accuracy:.1f}%')\n osu_embed.add_field(name='Total SS plays', value=user.count_rank_ss)\n osu_embed.add_field(name='Total S plays', value=user.count_rank_s)\n osu_embed.add_field(name='Total A plays', value=user.count_rank_a)\n await ctx.send(embed=osu_embed)\n\ndef setup(bot):\n bot.add_cog(Osu(bot))\n","sub_path":"cogs/osu.py","file_name":"osu.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"116768041","text":"from django.db import models\nfrom issuer.models import Issuer\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\n\nclass Identifier(models.Model):\n \"\"\"Model for various identifiers.\"\"\"\n\n def __str__(self):\n \"\"\"Return a human readable representation of each record.\"\"\"\n return 'Identifiers for {}'.format(\n self.issuer.legal_name)\n\n issuer = models.OneToOneField(\n Issuer,\n on_delete=models.PROTECT,\n )\n\n lei = models.CharField(\n max_length=20,\n null=True,\n blank=True,\n )\n\n corporate_registration_id = models.CharField(\n max_length=100,\n null=True,\n blank=True,\n )\n\n\n@receiver(post_save, sender=Issuer)\ndef issuer_setup_identifier(sender, instance, created, **kwargs):\n \"\"\"Makes sure there is an instance whenever someone\n saves the corporate model.\"\"\"\n\n p, _ = Identifier.objects.get_or_create(issuer=instance,\n lei=instance.lei)\n","sub_path":"ncr_website/issuer/models/identifier.py","file_name":"identifier.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"201997944","text":"from PyQt5 import QtGui, QtWidgets, QtCore\nimport numpy as np\nimport sys\nimport math\nfrom gui import Ui_PlotForm\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pyqtgraph as pg\n\nclass ApplicationWindow(QtWidgets.QMainWindow):\n \n def __init__(self):\n super(ApplicationWindow, self).__init__()\n self.ui = Ui_PlotForm()\n self.ui.setupUi(self)\n self.time = np.arange(0,1,0.001) #in sec but step in 1 msec\n self.vector= np.matrix ([0,0,1]) #da range sabt\n\n pixelIntensity = 255 #depend on pixel choosen\n\n self.T1 = self.createT1(pixelIntensity)\n self.T2 = self.createT2(pixelIntensity)\n self.PD = self.createPD(pixelIntensity)\n \n\n self.ui.rotationAngle.textChanged.connect(self.plot) #any change in lineEdit text\n \n self.ui.te.textChanged.connect(self.plot) #any change in lineEdit text\n self.ui.tr.textChanged.connect(self.plot) #any change in lineEdit text\n \n self.ui.Plot.clicked.connect(self.plot)\n \n def plot(self):\n self.ui.decayMx.clear()\n self.ui.decayMy.clear()\n self.ui.recoveryMz.clear()\n \n self.DecayMx = self.ui.decayMx\n self.DecayMy = self.ui.decayMy\n self.RecoveryMz = self.ui.recoveryMz\n\n\n self.theta = ((float) (self.ui.rotationAngle.text())) #5ly balk not global \n self.Tr = ((float) (self.ui.tr.text()))\n self.Te = ((float) (self.ui.te.text()))\n \n\n speed =1 \n\n self.Mx = []\n self.My = []\n self.Mz =[]\n \n self.vector = self.rotationAroundYaxisMatrix(self.theta,self.vector)\n\n for i in range(len(self.time)):\n self.vector = self.rotationAroundZaxisMatrixXY(self.Tr,speed,self.vector,self.time[i])\n self.vector = self.recoveryDecayEquation(self.T1,self.T2,self.PD, self.vector,self.time[i])\n \n self.Mx = np.append(self.Mx,self.vector.item(0))\n self.My = np.append(self.My,self.vector.item(1))\n self.Mz = np.append(self.Mz,self.vector.item(2))\n \n \n\n self.DecayMx.plot(self.time,np.ravel(self.Mx))\n self.DecayMy.plot(self.time,np.ravel(self.My))\n self.RecoveryMz.plot(self.time,np.ravel(self.Mz))\n\n self.RecoveryMz.addLine(x=self.Tr)\n self.RecoveryMz.addLine(x=self.Te)\n self.DecayMx.addLine(x=self.Tr)\n self.DecayMx.addLine(x=self.Te)\n\n \n def createPD(self,intensity):\n return (1/255)*intensity \n \n def createT1 (self,intensity):\n return ((6*intensity)+500)/1000\n\n def createT2(self,intensity):\n return ((2*intensity)+20)/1000\n def returnIntensity(self,Pd): # proton intensity vales from 0 till 1 \n return 255*Pd\n \n\n \n def mappingT1 (self,T1): #T1 in msec assumption\n return (T1-500)/6\n\n def mappingT2 (self,T2): #T1 in msec assumption\n return (T2-20)/2\n\n def rotationAroundYaxisMatrix(self,theta,vector):\n vector = vector.transpose()\n theta = (math.pi / 180) * theta\n R = np.matrix ([[np.cos(theta), 0, np.sin(theta)], [0, 1, 0], [-np.sin(theta), 0, np.cos(theta)]] )\n R = np.dot(R, vector)\n R = R.transpose()\n return np.matrix(R)\n\n\n def rotationAroundZaxisMatrixXY(self,TR,speed,vector,time): #time = self.time\n vector = vector.transpose()\n theta = speed * (time/ TR)\n theta = (math.pi / 180) * theta\n XY = np.matrix([[np.cos(theta),-np.sin(theta),0], [np.sin(theta), np.cos(theta),0],[0, 0, 1]])\n XY = np.dot(XY,vector)\n XY = XY.transpose()\n return np.matrix(XY) \n\n\n def recoveryDecayEquation(self,T1,T2,PD,vector,time):\n vector = vector.transpose()\n Decay =np.matrix([[np.exp(-time/T2),0,0],[0,np.exp(-time/T2),0],[0,0,np.exp(-time/T1)]])\n Decay = np.dot(Decay,vector)\n \n Rec= np.dot(np.matrix([[0,0,(1-(np.exp(-time/T1)))]]),PD)\n Rec = Rec.transpose()\n Decay = np.matrix(Decay)\n Rec = np.matrix(Rec) \n \n RD = Decay + Rec\n RD = RD.transpose()\n return RD\n\n\n\n\n\napp = QtWidgets.QApplication(sys.argv)\napplication = ApplicationWindow()\napplication.show()\napp.exec_()\n\n\n","sub_path":"Trajectory.py","file_name":"Trajectory.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"399504060","text":"import requests\nimport unittest\nimport time\nimport common.HTMLTestRunnerNew as HT\n#设置装这些用例的容器\nsuite=unittest.TestSuite()\n#发现这些用例的工具\nload=unittest.defaultTestLoader\n#load发现用例\ntestcases=load.discover('test_cases',pattern='test*.py',top_level_dir=None)\n#发现的用例放在容器中\nsuite.addTests(testcases)\n#设置测试报告的文档名字——固定的名字reporter+当前系统时间+.html\n#currenttime=time.strftime(\"%Y-%m-%d %H-%M-%S\")\nfilename=r'report/reporter.html'\n#生成测试报告\nwith open(filename,'wb+') as fp:\n runner=HT.HTMLTestRunner(stream=fp,\n title='学生管理系统接口测试报告',\n description='测试',\n tester=\"张三\")\n runner.run(suite)","sub_path":"run_test.py","file_name":"run_test.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"152060394","text":"#2014 Dec 8 -- Makes entropy contour plot in Rp-Mp space\n\nimport mesa as ms\nimport pylab as plt\nimport math\nimport numpy as np\nimport glob\nfrom scipy.interpolate import griddata\nimport os\n\nMJup_to_Msol = 1.898e27/1.9891e30\nRJup_to_Rsol = 69911./6.955e5\nRJup_to_cm = 7.1492e9 #from Paxton+ (2013)\n\nage = []\ncenter_entropy = []\nradius = []\nmass = []\n\n#dirs = glob.glob('models/Mpinit*')[::-1]\ndirs = glob.glob('models/Mpinit*MJup_qs5/')[::-1]\n#'''\nfor current_dir in dirs:\n# os.system('rm '+current_dir+'/LOGS1/history.datasa')\n a1 = ms.history_data(sldir=current_dir+'/LOGS1/', slname='history.data')\n temp_entropy = a1.get('center_entropy')\n\n# for cur_file in files:\n# a1 = ms.history_data(sldir=current_dir, slname='binary_history.data')\n temp_age = a1.get('star_age')\n temp_radius = a1.get('radius_cm')/RJup_to_cm\n temp_mass = a1.get('star_mass')/MJup_to_Msol\n\n if((len(temp_radius) == len(temp_entropy)) and \\\n (temp_mass.all() > 0.)):\n age.extend(temp_age)\n center_entropy.extend(temp_entropy)\n radius.extend(temp_radius)\n mass.extend(temp_mass)\n\nwith file('Rp_vs_Mp_constS.bin', 'wb') as f:\n np.save(f, age)\n np.save(f, center_entropy)\n np.save(f, radius)\n np.save(f, mass)\n#'''\n\nwith file('Rp_vs_Mp_constS.bin', 'rb') as f:\n age = np.load(f)\n center_entropy = np.load(f)\n radius = np.load(f)\n mass = np.load(f)\n\n#convert to Jupiter masses\n#x = [mass[i]/MJup_to_Msol for i in range(len(mass))]\n#y = [radius[i]/RJup_to_Rsol for i in range(len(radius))]\nx = mass\ny = radius\n#z = center_entropy\nz = age/1e9\nnpts = 100\ndel_x = (max(x) - min(x))/(npts - 1.)\nxi = np.linspace(min(x), max(x) + del_x, npts)\ndel_y = (max(y) - min(y))/(npts - 1.)\nyi = np.linspace(min(y), max(y) + del_y, npts)\n# grid the data.\nzi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear')\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n#CS = plt.contour(xi,yi,zi,range(7,12),linewidths=3)\nCS = plt.contour(xi,yi,zi,[0.01, 0.1, 1],linewidths=3)\nplt.clabel(CS, inline=1, fontsize=18, cmap=plt.cm.jet, fmt='%i')\nax.set_xscale('log')\nplt.xlim(0.1, 11)\nplt.ylim(0.8, 2.5)\n\nplt.xlabel(\"$M_\\mathrm{p}\\ (M_\\mathrm{Jup})$\")\nplt.ylabel(\"$R_\\mathrm{p}\\ (R_\\mathrm{Jup})$\")\n\n#CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet)\n#plt.colorbar() # draw colorbar\n# plot data points.\n#plt.scatter(x,y,marker='o',c='b',s=5)\n#plt.title('griddata test (%d points)' % npts)\nplt.text(2, 2.3, '$R_\\mathrm{p, init} = 3\\ R_\\mathrm{Jup}$', fontsize=24)\nplt.show()\n#plt.savefig('/Users/bjackson/research/superpig/RLO/Rp_vs_Mp_constS_no-core.png', bbox_inches='tight')\n","sub_path":"make_planets_initial-RLO_variable-core/Rp_vs_Mp_constS.py","file_name":"Rp_vs_Mp_constS.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"377479645","text":"def binarySearch(alist,item):\n first = 0\n last = len(alist) - 1\n found = False\n\n while first <= last and not found:\n midpoint = (first + last)//2\n if alist[midpoint] == item:\n found = True\n else:\n if item < alist[midpoint]:\n last = midpoint - 1\n else:\n first = midpoint + 1\n return found\ntestlist = [1,2,3,4,5,6,7,8,9,10]\nprint(binarySearch(testlist,3))\nprint(len(testlist))\n\n'''\n\nfirst = 0\nlast = 10-1 = 9\n\n\n----------------\nmidpoint = 4\nalist[4] = 5 > 3\nlast = 3\nfirst = 0\n----------------\nmidpoint = 1\nalist[1] = 2 < 3\nfirst = 2\nlast = 3\n----------------\nmidpoint = 2\nalist[2] = 3 == 3\n\n'''\n\n#递归二分查找 O(logN)\ndef dgbinarySearch(alist,item):\n if len(alist) == 0:\n return False\n else:\n midpoint = len(alist)//2\n if alist[midpoint] == item:\n return True\n else:\n if item < alist[midpoint]:\n return binarySearch(alist[:midpoint],item)\n else:\n return binarySearch(alist[midpoint+1:],item)\n","sub_path":"python_data_structure/二分查找.py","file_name":"二分查找.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"118890173","text":"# 1 将给定字符串的PHP替换为Python\n# best_language = \"PHP is the best programming language in the world! \"\n\nbest_language = \"PHP is the best programming language in the world! \"\nprint(best_language.replace(\"PHP\", \"Python\"))\n\n# 2 编写代码,提示用户输入1-7七个数字,分别代表周一到周日,打印输出“今天是周几”\n\ncus_input = input(\"请输入1-7数字:\")\nprint(\"今天是周{}\".format(cus_input))\n\n# 3 给定一个字符串: Python is the BEST programming Language!\n# 编写一个正则表达式用来判断该字符串是否全部为小写。\nimport re\nstr1 = 'Python is the BEST programming Language!'\npattern = re.search('^[a-z]+$', str1)\nif pattern:\n print('全为小写')\nelse:\n print(\"不全是小写!\")\n\n# 4 读取一个字符串,要求使用正则表达式来读取其中的电话号码,电话号码的格式假定为:\n# (xxx) xxx-xxxx或xxx-xxx-xxxx。\n\n\ndef find(a):\n phone = re.findall(r\"(\\d{3})\\-(\\d{3})\\-(\\d{4})|\\((\\d{3})\\)\\s(\\d{3})\\-(\\d{4})\", a)\n print(\"phone: \", phone)\n\n\nstr2 = input(\"请输入一个含有电话号码的字符串:\")\nfind(str2)\n\n# 5 利用正则表达式从下列不同的字符串中获取指定格式的日期。日期的格式为yyyy-mm-dd。\n# '今天是2022/9/24', '今天是2017/09/25', '今天是2012-07-25', '今天是2020年04月25'\n\n\ndef find2(b):\n date = re.findall(r\"(\\d{4}-\\d{1,2}-\\d{1,2})\", b)\n print(\"date: \", date)\n\n\nstr3 = \"今天是2022/9/24', '今天是2017/09/25', '今天是2012-07-25', '今天是2020年04月25\"\nfind2(str3)\n","sub_path":"homework6/Group13/hw6_1720405.py","file_name":"hw6_1720405.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"508345555","text":"##############################################################################\n#\n# Copyright (c) 2004, 2005 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"\nUse 'structured monkey patching' to enable zope.app.container event sending for\nZope 2 objects.\n\n$Id: eventconfigure.py 61205 2005-11-02 15:18:34Z efge $\n\"\"\"\n\nfrom Products.Five.event import doMonkies\nfrom OFS.subscribers import deprecatedManageAddDeleteClasses\n\ndef setDeprecatedManageAddDelete(class_):\n \"\"\"Instances of the class will still see their old methods called.\"\"\"\n deprecatedManageAddDeleteClasses.append(class_)\n\ndef cleanUp():\n deprecatedManageAddDeleteClasses[:] = []\n\ndef containerEvents(_context):\n _context.action(\n discriminator=None,\n callable=doMonkies,\n args=(),\n )\n\ndef deprecatedManageAddDelete(_context, class_):\n _context.action(\n discriminator=('five:deprecatedManageAddDelete', class_),\n callable=setDeprecatedManageAddDelete,\n args=(class_,),\n )\n\nfrom zope.testing.cleanup import addCleanUp\naddCleanUp(cleanUp)\ndel addCleanUp\n","sub_path":"Five/eventconfigure.py","file_name":"eventconfigure.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"33121064","text":"import requests\nfrom video import Video\nfrom customer import Customer\nfrom rental import Rental\n#URL = \"http://127.0.0.1:5000\"\nBACKUP_URL = \"https://retro-video-store-api.herokuapp.com\"\n\n\ndef print_brand():\n print()\n print(\"✨ ⏩ ⭐️ 🔥 🎞️ 🤠 📼 RETRO VIDEO STORE 📼 ⏩ 🔥 🤠 ⭐️ 🎞️ ✨\")\n print()\n print( \".................... 💗 Be Kind. 💗 ........................\")\n print(\" ..................🥺 Please Rewind. 🥺 ................... \")\n\ndef menu_options():\n options = {\n \"1\": \"Add 1 Video to our Extensive Collection \", \n \"2\": \"Update 1 Video's Information\",\n \"3\": \"Delete a Video\", \n \"4\": \"View all Video Info\", \n \"5\": \"Info on 1 Video\", \n \"6\": \"New Customer Sign Up\",\n \"7\": \"Update a Customer's Information\",\n \"8\": \"Delete 1 Customer \",\n \"9\": \"View Info on 1 Customer\",\n \"10\": \"View all Customers\",\n \"11\" : \"Check in 1 Video\",\n \"12\": \"Check out 1 Video Return\",\n \"13\" : \"List all Options\",\n \"14\": \"Q U I T\"\n }\n for one_option in options:\n print(f\"Option #{one_option}. {options[one_option]} \\n\")\n \n return options\ndef make_choice(options, video, customer, rental):\n valid_choices = options.keys()\n choice = None\n\n while choice not in valid_choices:\n print_brand()\n print()\n print(\"Please reference the list above for all the options you have \\n\")\n choice = input(\"What do you want to do?! Select a valid option: \")\n # check to make sure choice is a valid input by checking isnumeirc \n\n if choice in ['2','3'] and video.selected_video == None:\n print(\"You must select a video before updating it, deleting it\")\n print(\"Please select a Video!\")\n # select info on one video\n choice = \"5\"\n \n if choice in [\"7\", \"8\"] and customer.selected_customer == None:\n print(\"You must select a customer before updating it, deleting it\")\n print(\"Please select a Customer!\")\n choice = \"9\"\n \n return choice \n\ndef main(play=True):\n # initialize video_store\n video = Video(url = BACKUP_URL)\n customer = Customer(url= BACKUP_URL)\n rental = Rental(url=BACKUP_URL)\n print_brand()\n print()\n options = menu_options()\n\n while play == True:\n # get input and validate \n choice = make_choice(options, video, customer, rental)\n video.print_selected()\n customer.print_selected()\n\n # \"1\": \"Add 1 Video to our Extensive Collection \" \n if choice == '1':\n print(\"Let's get started on adding a new video to our growing collection !\\n \")\n title=input(\"What is the title of the video? \\n\").title()\n release_date =input(\"When was the video realeased? \\n\")\n total_inventory =input(\"How many video copies do we own? \\n\")\n response = video.create_video(title=title, release_date =release_date, total_inventory=total_inventory)\n print()\n print(\"New Video Added to the Collection:\", title.title())\n #print(\"New Video:\", response[\"title\"]) # I need to return the name of the video here \n ## \"2\": \"Update 1 Video's Information\" \n elif choice == '2':\n print(f\"Let's update the video: {video.selected_video}\")\n title=input(\"What is the new title of your video?\\n\")\n release_date=input(\"What is the new release date of your video? YYYY-MM-DD\\n\")\n total_inventory = int(input(\"What is the total inventory?\\n\"))\n response = video.edit_video(title=title, release_date=release_date, total_inventory=total_inventory)\n print()\n print(\"Updated Video:\", response)\n ## \"3\": \"Delete a Video\" \n elif choice == '3':\n video.delete_video()\n print()\n print(\"Video has been deleted.\")\n print()\n print(video.list_videos())\n ## \"4\": \"View all Video Info\" \n elif choice == '4':\n for video in video.list_videos():\n print(video)\n ## \"5\": \"Info on 1 Video\" \n elif choice == '5':\n select_by = input(\"Would you like to select by? Enter title or id: \\n \")\n if select_by==\"title\":\n title = input(\"Which video title would you like to select? \\n\")\n video.get_video(title=title)\n elif select_by==\"id\":\n id = input(\"Which video id would you like to select? \\n\")\n if id.isnumeric():\n id = int(id)\n video.get_video(id=id)\n else:\n print(\"Could not locate. Please enter a valid id or title we have in our collection.\")\n \n if video.selected_video:\n print()\n print(\"Selected Video: \", video.selected_video)\n # \"6\": \"New Customer Sign Up\" \n elif choice == '6':\n print(\"Let's get started on adding a new customer!\\n \")\n name=input(\"What is the name of the customer? \\n\").title()\n postal_code =input(\"What's the customer's postal code? \\n\")\n phone =input(\"What is the customer's phone number? \\n\")\n response = customer.create_new_customer(name=name, postal_code =postal_code, phone=phone)\n print()\n print(\"New Customer added to the Retro Video Store:\", name.title())\n ## \"7\": \"Update a Customer's Information\" \n elif choice == '7':\n print(f\"Let's update the customer's information: {customer.selected_customer}\")\n name=input(\"What updates do you want to make to the customer's name?\\n\")\n postal_code=input(\"What updates do you want to make to the customer's postal code?\\n\")\n phone = input(\"What updates do you want to make to the customer's phone?\\n\")\n response = customer.update_customer(name=name, postal_code=postal_code, phone=phone)\n print()\n print(\"Updated Customer:\", response)\n ## \"8\": \"Delete 1 Customer \" \n elif choice == '8':\n customer.delete_customer()\n print()\n print(\"The Customer has been deleted.\")\n print()\n print(customer.list_customers())\n ## \"9\": \"View Info on 1 Customer\" \n elif choice == '9':\n select_by = input(\"Would you like to select by? Enter name or id: \\n \")\n if select_by==\"name\":\n name = input(\"Which customer name would you like to locate? \\n\")\n customer.get_customer(name=name)\n elif select_by==\"id\":\n id = input(\"Which customer id would you like to locate? \\n\")\n if id.isnumeric():\n id = int(id)\n customer.get_customer(id=id)\n else:\n print(\"Could not locate. Please enter a valid customer id or name\")\n \n if customer.selected_customer:\n print()\n print(\"Selected Customer: \", customer.selected_customer)\n ## \"10\": \"View all Customers\" \n elif choice == '10':\n for customer in customer.list_customers():\n print(customer)\n # \"11\" : \"Check in 1 Video\" \n elif choice == '11':\n print(\"Let's get started with the check-in process!\\n \")\n video_id = input(\"What is the video id: \")\n if video_id.isnumeric():\n video_id = int(video_id)\n video.selected_video = video.get_video(id=video_id)\n print(video.selected_video) \n customer_id = input(\"What is the customer's id checking ing the video: \")\n if customer_id.isnumeric():\n customer_id = int(customer_id)\n customer.selected_customer = customer.get_customer(id=customer_id)\n print(customer.selected_customer)\n \n checked_in_rental = rental.check_in(customer_id, video_id)\n print(checked_in_rental)\n print(\" Success ! The video was checked in!\")\n\n ## \"12\": \"Check out 1 Video Return\" \n elif choice == '12':\n print(\"Let's get started with the check-out process!\\n \")\n video_id = input(\"What is the video id: \")\n if video_id.isnumeric():\n video_id = int(video_id)\n video.selected_video = video.get_video(id=video_id)\n print(video.selected_video)\n\n customer_id = input(\"What is the customer's id: \")\n if customer_id.isnumeric():\n customer_id = int(customer_id)\n customer.selected_customer = customer.get_customer(id=customer_id)\n print(customer.selected_customer)\n \n checked_out_rental = rental.check_out(customer_id, video_id)\n print(\"Success! The video was checked out!\")\n print(checked_out_rental)\n print() \n ## \"13\" : \"List all Options\"\n elif choice=='13':\n menu_options()\n # \"14\": \"Q U I T\"\n elif choice=='14':\n play=False\n print(\"\\n 💸 💰 Thank you for logging off for the day! 💰 💸 \\n 💆🏽‍♀️ 🍓 have a good rest of your day! 🍧 💅🏾\")\n \n \n\n\nmain()\n\n# you can just call main function to set up the cli, the only on she called \n# this tells the interpreter to run first in order for cli to show up bc you have other function involved \n# common pattern \n# you can remove this line and just call main \n# python interprets from the top down\n#if __name__ == \"__main__\":\n# main()\n\n# think of the logic on how to quit a program, i want to include it after each response, \n# on each line \n#select_by = input(\"First, How would you like to start the video look up process? Locating the title or id?: \\n \")\n# if select_by == \"title\":\n# title = input(\"Which video title would you like to select? \\n\")\n# video.get_video(title=title)\n# elif select_by ==\"id\":\n# if id.isnumeric():\n# id = int(id)\n# video.get_video(id=id)\n# else:\n# print(\"Could not locate. Please enter a valid video id or name\")\n# # now that I got the video I need to ask the user for the customer's id and add it to their rentals \n# print(\"That's a great movie!\")\n# select_by_customer = input(\"Who is the customer you would you like to rent this out to? Enter id or name: \\n \")\n# if select_by_customer == \"name\":\n# name = input(\"Which customer name would you like to locate? \\n\")\n# customer.get_customer(name=name)\n# elif select_by ==\"id\":\n# id = input(\"Which customer id would you like to locate? \\n\")\n# if id.isnumeric():\n# id = int(id)\n# customer.get_customer(id=id)\n# else:\n# print(\"Could not locate. Please enter a valid video id or name\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"510219088","text":"import numpy as np\nimport tensorflow as tf\nfrom sklearn.metrics import precision_recall_curve, roc_curve\nfrom sklearn.metrics import average_precision_score, auc\nfrom load_data import load_data\nfrom model import build_model,compileModel,build_model_CNN\nfrom scipy import interpolate\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('-gene', dest='gene', default=None, type=str, help='select the gene')\n parser.add_argument('-condition', dest='condition', default=None, type=str, help='select full or exon')\n parser.add_argument('-length', dest='length', default=None, type=str,\n help='specify the two ends sequence length 125/250/500/1000')\n parser.add_argument('-mode', default=None, type=str, help='select your framework, CNN or CNN+RNN')\n args = parser.parse_args()\n\n ## assign the input value to variables\n gene = args.gene\n condition = args.condition\n length = args.length\n mode = args.mode\n\n data_path = '/home/yuxuan/dp/longer_seq_data/{}_{}_{}.csv'.format(gene, condition, length)\n\n _, x_test, _, y_test, _, _ = load_data(data_path)\n\n if mode =='CNN+RNN':\n model = build_model(x_test)\n checkpoint_path = '/home/yuxuan/dp/model/{}_{}_{}_CRNNmodel_test.h5'.format(gene, condition, length)\n else:\n model =build_model_CNN(x_test)\n checkpoint_path = '/home/yuxuan/dp/model/{}_{}_{}_best_model.h5'.format(gene, condition, length)\n print(checkpoint_path)\n\n model.load_weights(checkpoint_path)\n y_score = model.predict(x_test)\n precision, recall, _ = precision_recall_curve(y_true=y_test, probas_pred=y_score)\n average_precision = average_precision_score(y_true=y_test, y_score=y_score)\n\n## ROC curve\n fpr, tpr, _ = roc_curve(y_true=y_test, y_score=y_score)\n roc_auc = auc(fpr, tpr)\n\nif __name__ == '__main__':\n main()","sub_path":"plot_curves.py","file_name":"plot_curves.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"379777700","text":"class node:\n def __init__(self,data=None):\n self.data = data\n self.next = None\n\nclass LinkedList:\n def __init__(self,data):\n self.head = node()\n\n def append(self,data):\n new_node = node(data)\n cur = self.head\n while cur.next!= None:\n cur =cur.next\n cur.next = new_node\n def printList(self):\n temp = self.head\n while (temp):\n print(temp.data, \"-> \", end=\"\")\n temp = temp.next\n print()\n\n\ndef addTwoNumbers(l1,l2):\n\n cur1 = l1\n cur2 = l2\n list1 = []\n list2 = []\n \n while cur1:\n list1.append(cur1.data)\n cur1 = cur1.next\n\n while cur2:\n list2.append(cur2.data)\n cur2 = cur2.next\n \n \n list11 = [str(i) for i in list1]\n list22 = [str(i) for i in list2]\n \n num1 = int(\"\".join(list11))\n num2 = int(\"\".join(list22))\n ans = str(num1 + num2)\n \n node = ListNode(ans[0])\n counter = node\n \n for i in range(1, len(ans)):\n new = ListNode(ans[i])\n counter.next = new\n counter = counter.next\n \n return node\n\nl1 = LinkedList()\nl2 = LinkedList()\n\nl1.append(5)\nl1.append(6)\nl1.append(3)\nl2.append(8)\nl2.append(4)\nl2.append(2)\n\naddTwoNumbers(l1,l2).printList()\n\n\n\n \n# class ListNode:\n# def __init__(self,x):\n# self.val = x\n# self.next = None\n# class Solution:\n# def addSum(self,l1):\n\n# prev = None\n# cur = self.head\n \n# while cur:\n# next = cur.next\n# cur.next = prev\n# prev = cur\n# cur = next\n# self.head = prev \n# return cur\n\n\n","sub_path":"week-4/Python/Adedapo-Adetayo.py","file_name":"Adedapo-Adetayo.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"222874425","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nimport json\nfrom django.db.models import Max\n\nfrom discounts.models import Period, Agreement\n\ndef index(request):\n \"\"\"\n main page. Render only link to admin page\n \"\"\"\n return HttpResponse(\"Please, visit Admin Page.\")\n\ndef calendar(request):\n \"\"\"\n View for api. Gets the GET request like /agreements/calendar?country=1,2,7&negotitator=4,8&company=1,2\n Respond with json like \n {\n 2014: [0, 0, 0, 0, 0, 0, 0, 0, 12, 1, 0, 5],\n 2015: [1, 0, 0, 4, 0, 0, 0, 1, 7, 10, 0, 4]\n }\n \"\"\"\n # Parse GET parameters to dictionary of lists of ints\n dict_params = {}\n for param in ('country', 'negotiator', 'company'):\n if request.GET.get(param) is not None:\n dict_params[param] = map(lambda n: int(n), request.GET[param].split(','))\n # Get all agreements with additional field which include date of max period in agreement\n agreements = Agreement.objects.annotate(max_period_end=Max('periods__end_date'))\n # Get agreements, filtered by country\n if dict_params.get('country') is not None:\n agreements = agreements.filter(company__country__id__in=dict_params['country'])\n # Get agreements, filtered by country and negotiator\n if dict_params.get('negotiator') is not None:\n agreements = agreements.filter(negotiator__id__in=dict_params['negotiator'])\n # Get agreements, filtered by country, negotiator and company\n if dict_params.get('company') is not None:\n agreements = agreements.filter(company__id__in=dict_params['company'])\n\n # scan all filtered agreements and group periods by month and year\n result = {}\n for agreement in agreements:\n year = agreement.max_period_end.year\n if result.get(year) is None:\n result[year] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n result[year][agreement.max_period_end.month - 1] += 1\n \n return HttpResponse(json.dumps(result), content_type='application/json')","sub_path":"discounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"641440507","text":"import json\nfrom .SdsStreamIndex import SdsStreamIndex\nfrom .SdsStreamPropertyOverride import SdsStreamPropertyOverride\n\n\nclass SdsStream(object):\n \"\"\"Sds stream definition\"\"\"\n\n def __init__(self, id=None, name=None, description=None, typeId=None,\n propertyOverrides=None, indexes=None, interpolationMode=None,\n extrapolationMode=None):\n \"\"\"\n\n :param id: required\n :param name: not required\n :param description: not required\n :param typeId: required\n :param propertyOverrides: array of SdsStreamPropertyOverride\n not required\n :param indexes: array of SdsStreamIndex not required\n :param interpolationMode: SdsInterpolationMode default is null\n not required\n :param extrapolationMode: SdsExtrapolationMode default is null\n not required\n \"\"\"\n self.Id = id\n self.Name = name\n self.Description = description\n self.TypeId = typeId\n self.PropertyOverrides = propertyOverrides\n self.Indexes = indexes\n self.InterpolationMode = interpolationMode\n self.ExtrapolationMode = extrapolationMode\n\n @property\n def Id(self):\n \"\"\"\n required\n :return:\n \"\"\"\n return self.__id\n\n @Id.setter\n def Id(self, id):\n \"\"\"\"\n required\n :param id:\n :return:\n \"\"\"\n self.__id = id\n\n @property\n def Name(self):\n \"\"\"\n not required\n :return:\n \"\"\"\n return self.__name\n\n @Name.setter\n def Name(self, name):\n \"\"\"\n not required\n :param name:\n :return:\n \"\"\"\n self.__name = name\n\n @property\n def Description(self):\n \"\"\"\n not required\n :return:\n \"\"\"\n return self.__description\n\n @Description.setter\n def Description(self, description):\n \"\"\"\n not required\n :param description:\n :return:\n \"\"\"\n self.__description = description\n\n @property\n def TypeId(self):\n \"\"\"\n required\n :return:\n \"\"\"\n return self.__typeId\n\n @TypeId.setter\n def TypeId(self, typeId):\n \"\"\"\n required\n :param typeId:\n :return:\n \"\"\"\n self.__typeId = typeId\n\n @property\n def PropertyOverrides(self):\n \"\"\"\n array of SdsStreamPropertyOverride not required\n :return:\n \"\"\"\n return self.__propertyOverrides\n\n @PropertyOverrides.setter\n def PropertyOverrides(self, propertyOverrides):\n \"\"\"\n array of SdsStreamPropertyOverride not required\n :param propertyOverrides:\n :return:\n \"\"\"\n self.__propertyOverrides = propertyOverrides\n\n @property\n def Indexes(self):\n \"\"\"\n array of SdsStreamIndex not required\n :return:\n \"\"\"\n return self.__indexes\n\n @Indexes.setter\n def Indexes(self, indexes):\n \"\"\"\n array of SdsStreamIndex not required\n :param indexes:\n :return:\n \"\"\"\n self.__indexes = indexes\n\n @property\n def InterpolationMode(self):\n \"\"\"\n SdsInterpolationMode default is null not required\n :return:\n \"\"\"\n return self.__interpolationMode\n\n @InterpolationMode.setter\n def InterpolationMode(self, interpolationMode):\n \"\"\"\n SdsInterpolationMode default is null not required\n :param interpolationMode:\n :return:\n \"\"\"\n self.__interpolationMode = interpolationMode\n\n @property\n def ExtrapolationMode(self):\n \"\"\"\n SdsExtrapolationMode default is null not required\n :return:\n \"\"\"\n return self.__extrapolationMode\n\n @ExtrapolationMode.setter\n def ExtrapolationMode(self, extrapolationMode):\n \"\"\"\n SdsExtrapolationMode default is null not required\n :param extrapolationMode:\n :return:\n \"\"\"\n self.__extrapolationMode = extrapolationMode\n\n def toJson(self):\n return json.dumps(self.toDictionary())\n\n def toDictionary(self):\n # required properties\n dictionary = {'Id': self.Id, 'TypeId': self.TypeId}\n\n # optional properties\n if hasattr(self, 'Name'):\n dictionary['Name'] = self.Name\n\n if hasattr(self, 'Description'):\n dictionary['Description'] = self.Description\n\n if hasattr(self, 'InterpolationMode'):\n dictionary['InterpolationMode'] = self.InterpolationMode\n\n if hasattr(self, 'ExtrapolationMode'):\n dictionary['ExtrapolationMode'] = self.ExtrapolationMode\n\n if hasattr(self, 'PropertyOverrides'):\n if self.PropertyOverrides is not None:\n dictionary['PropertyOverrides'] = []\n for value in self.PropertyOverrides:\n dictionary['PropertyOverrides'].append(\n value.toDictionary())\n\n if hasattr(self, 'Indexes'):\n if self.Indexes is not None:\n dictionary['Indexes'] = []\n for value in self.Indexes:\n dictionary['Indexes'].append(value.toDictionary())\n\n return dictionary\n\n @staticmethod\n def fromJson(jsonObj):\n return SdsStream.fromDictionary(jsonObj)\n\n @staticmethod\n def fromDictionary(content):\n stream = SdsStream()\n\n if not content:\n return stream\n\n if 'Id' in content:\n stream.Id = content['Id']\n\n if 'Name' in content:\n stream.Name = content['Name']\n\n if 'Description' in content:\n stream.Description = content['Description']\n\n if 'InterpolationMode' in content:\n stream.InterpolationMode = content['InterpolationMode']\n\n if 'ExtrapolationMode' in content:\n stream.ExtrapolationMode = content['ExtrapolationMode']\n\n if 'TypeId' in content:\n stream.TypeId = content['TypeId']\n\n if 'PropertyOverrides' in content:\n propertyOverrides = content['PropertyOverrides']\n if propertyOverrides is not None and len(propertyOverrides) > 0:\n stream.PropertyOverrides = []\n for value in propertyOverrides:\n stream.PropertyOverrides.append(\n SdsStreamPropertyOverride.fromDictionary(value))\n\n if 'Indexes' in content:\n indexes = content['Indexes']\n if indexes is not None and len(indexes) > 0:\n stream.Indexes = []\n for value in indexes:\n stream.Indexes.append(SdsStreamIndex.fromDictionary(value))\n\n return stream\n","sub_path":"library_samples/Python/ocs_sample_library_preview/SDS/SdsStream.py","file_name":"SdsStream.py","file_ext":"py","file_size_in_byte":6825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"39607598","text":"from dagster.cli.load_handle import _cli_load_invariant, handle_for_pipeline_cli_args\nfrom dagster.core.definitions.container import get_active_repository_data_from_image\nfrom dagster.core.snap import PipelineSnapshot\nfrom dagster.seven import is_module_available\n\n\ndef get_pipeline_snapshot_from_cli_args(cli_args):\n _cli_load_invariant(cli_args.get('pipeline_name') is not None)\n\n if cli_args.get('image'):\n _cli_load_invariant(\n is_module_available('docker'),\n msg='--image is not supported without dagster[docker] or the Python package docker installed.',\n )\n active_repo_data = get_active_repository_data_from_image(cli_args.get('image'))\n return active_repo_data.get_pipeline_snapshot(cli_args.get('pipeline_name')[0])\n else:\n pipeline_definition = handle_for_pipeline_cli_args(cli_args).build_pipeline_definition()\n return PipelineSnapshot.from_pipeline_def(pipeline_definition)\n","sub_path":"python_modules/dagster/dagster/cli/load_snapshot.py","file_name":"load_snapshot.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62159573","text":"import sys\n\n# Always import and patch import hooks before loading anything else\nfrom .internal.import_hooks import patch as patch_import_hooks\n\npatch_import_hooks() # noqa: E402\n\nfrom .monkey import patch, patch_all # noqa: E402\nfrom .pin import Pin # noqa: E402\nfrom .span import Span # noqa: E402\nfrom .tracer import Tracer # noqa: E402\nfrom .settings import config # noqa: E402\nfrom .utils.deprecation import deprecated # noqa: E402\n\n\n__version__ = \"0.2.1\"\n\n\n# a global tracer instance with integration settings\ntracer = Tracer()\n\n__all__ = [\n \"patch\",\n \"patch_all\",\n \"Pin\",\n \"Span\",\n \"tracer\",\n \"Tracer\",\n \"config\",\n]\n\n\n_ORIGINAL_EXCEPTHOOK = sys.excepthook\n\n\ndef _excepthook(tp, value, traceback):\n tracer.global_excepthook(tp, value, traceback)\n if _ORIGINAL_EXCEPTHOOK:\n return _ORIGINAL_EXCEPTHOOK(tp, value, traceback)\n\n\n@deprecated(\"This method will be removed altogether\", \"1.0.0\")\ndef install_excepthook():\n \"\"\"Install a hook that intercepts unhandled exception and send metrics about them.\"\"\"\n global _ORIGINAL_EXCEPTHOOK\n _ORIGINAL_EXCEPTHOOK = sys.excepthook\n sys.excepthook = _excepthook\n\n\n@deprecated(\"This method will be removed altogether\", \"1.0.0\")\ndef uninstall_excepthook():\n \"\"\"Uninstall the global tracer except hook.\"\"\"\n sys.excepthook = _ORIGINAL_EXCEPTHOOK\n","sub_path":"ddtrace/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"20392390","text":"from django.http import HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom app.models import MainShow, MainWheel, MainNav, MainMustBuy, MainShop, Goods, FoodType, CartModel\nfrom django.core.urlresolvers import reverse\n\ndef home(request):\n if request.method == 'GET':\n mainShow = MainShow.objects.all()\n banner = MainWheel.objects.all()\n nav = MainNav.objects.all()\n mustBuy = MainMustBuy.objects.all()\n shops = MainShop.objects.all()\n return render(request, 'home/home.html',{'mainshow': mainShow,'banner':banner,'nav':nav,'mustBuy':mustBuy,\n 'shop1':shops[0],\n 'shop2':shops[1:3],\n 'shop3':shops[3:7],\n 'shop4':shops[7:11:]})\ndef mine(request):\n if request.method == 'GET':\n return render(request, 'mine/mine.html')\ndef market(request):\n if request.method == 'GET':\n return HttpResponseRedirect(reverse('app:marketparams', kwargs={\n 'typeid':104749,\n 'cid':0,\n 'sid':0\n\n }))\ndef marketparams(request,typeid,cid,sid):\n foodtype = FoodType.objects.all()\n\n a = FoodType.objects.filter(typeid =typeid).first().childtypenames\n if cid == '0':\n goods = Goods.objects.filter(categoryid=typeid)\n else:\n goods = Goods.objects.filter(categoryid=typeid,\n childcid=cid)\n if sid == '0':\n pass\n elif sid == '1':\n goods = goods.order_by('productnum')\n elif sid == '2':\n goods = goods.order_by('-price')\n elif sid == '3':\n goods = goods.order_by('price')\n child = [i.split(':') for i in a.split('#')]\n user = request.user\n if user.id:\n try:\n cart_goods = CartModel.objects.filter(user=user)\n except CartModel.DoesNotExist:\n cart_goods = []\n else:\n cart_goods = []\n goods_ids = []\n if len(cart_goods) > 0:\n for cart_good in cart_goods:\n goods_ids.append(cart_good.goods.id)\n data={\n 'foodtype':foodtype,\n 'goods':goods,\n 'child':child,\n 'cid':cid,\n 'typeid':typeid,\n 'goods_ids' : goods_ids,\n 'cart_goods' : cart_goods\n }\n return render(request,'market/market.html',data)\ndef add_goods(request):\n\n if request.method == 'POST':\n\n data = {}\n data['code'] = 1001\n\n user = request.user\n if user and user.id:\n goods_id = request.POST.get('goods_id')\n # 获取购物车信息\n user_carts = CartModel.objects.filter(user=user, goods_id=goods_id).first()\n # 如果用户选了商品\n if user_carts:\n user_carts.c_num += 1\n user_carts.save()\n data['c_num'] = user_carts.c_num\n else:\n # 如果用户没选商品,就创建\n CartModel.objects.create(user=user,\n goods_id=goods_id,\n c_num=1)\n data['c_num'] = 1\n data['code'] = 200\n data['msg'] = '成功'\n return JsonResponse(data)\n return JsonResponse(data)\ndef sub_goods(request):\n\n if request.method == 'POST':\n data = {\n 'code':'200',\n 'msg': '请求成功'\n }\n user = request.user\n goods_id = request.POST.get('goods_id')\n\n if user and user.id:\n # 查看当前商品是否已经在购物中\n user_carts = CartModel.objects.filter(user=user,\n goods_id=goods_id).first()\n # 如果存在,则减一\n if user_carts:\n # 如果商品的数量为1,则删除\n if user_carts.c_num == 1:\n user_carts.delete()\n data['c_num'] = 0\n else:\n # 如果商品数量不为一,则减一\n user_carts.c_num -= 1\n user_carts.save()\n data['c_num'] = user_carts.c_num\n return JsonResponse(data)\ndef cart(request):\n\n if request.method == 'GET':\n data = {}\n user = request.user\n cart_goods = CartModel.objects.filter(user=user)\n data['cart_goods'] = cart_goods\n data['cart_sum'] = get_cart_sum(user)\n return render(request, 'cart/cart.html', data)\n\n\ndef get_cart_sum(user):\n cart_goods = CartModel.objects.filter(user=user)\n cart_sum = 0\n for cart_good in cart_goods:\n cart_sum += cart_good.goods.price * cart_good.c_num\n return cart_sum","sub_path":"axf02/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"226666048","text":"import gc\n\nimport mitmproxy.test.tutils\nfrom mitmproxy.tools import console\nfrom mitmproxy import proxy\nfrom mitmproxy.tools.console import common\n\nfrom .. import tutils, mastertest\n\n\nclass TestConsoleState:\n\n def test_flow(self):\n \"\"\"\n normal flow:\n\n connect -> request -> response\n \"\"\"\n c = console.master.ConsoleState()\n f = self._add_request(c)\n assert f in c.flows\n assert c.get_focus() == (f, 0)\n\n def test_focus(self):\n \"\"\"\n normal flow:\n\n connect -> request -> response\n \"\"\"\n c = console.master.ConsoleState()\n f = self._add_request(c)\n\n assert c.get_focus() == (f, 0)\n assert c.get_from_pos(0) == (f, 0)\n assert c.get_from_pos(1) == (None, None)\n assert c.get_next(0) == (None, None)\n\n f2 = self._add_request(c)\n assert c.get_focus() == (f, 0)\n assert c.get_next(0) == (f2, 1)\n assert c.get_prev(1) == (f, 0)\n assert c.get_next(1) == (None, None)\n\n c.set_focus(0)\n assert c.get_focus() == (f, 0)\n c.set_focus(-1)\n assert c.get_focus() == (f, 0)\n c.set_focus(2)\n assert c.get_focus() == (f2, 1)\n\n c.delete_flow(f2)\n assert c.get_focus() == (f, 0)\n c.delete_flow(f)\n assert c.get_focus() == (None, None)\n\n def _add_request(self, state):\n f = tutils.tflow()\n return state.add_flow(f)\n\n def _add_response(self, state):\n f = self._add_request(state)\n f.response = mitmproxy.test.tutils.tresp()\n state.update_flow(f)\n\n def test_add_response(self):\n c = console.master.ConsoleState()\n f = self._add_request(c)\n f.response = mitmproxy.test.tutils.tresp()\n c.focus = None\n c.update_flow(f)\n\n def test_focus_view(self):\n c = console.master.ConsoleState()\n self._add_request(c)\n self._add_response(c)\n self._add_request(c)\n self._add_response(c)\n self._add_request(c)\n self._add_response(c)\n assert not c.set_view_filter(\"~s\")\n assert len(c.view) == 3\n assert c.focus == 0\n\n def test_settings(self):\n c = console.master.ConsoleState()\n f = self._add_request(c)\n c.add_flow_setting(f, \"foo\", \"bar\")\n assert c.get_flow_setting(f, \"foo\") == \"bar\"\n assert c.get_flow_setting(f, \"oink\") is None\n assert c.get_flow_setting(f, \"oink\", \"foo\") == \"foo\"\n assert len(c.flowsettings) == 1\n c.delete_flow(f)\n del f\n gc.collect()\n assert len(c.flowsettings) == 0\n\n\ndef test_format_keyvals():\n assert common.format_keyvals(\n [\n (\"aa\", \"bb\"),\n None,\n (\"cc\", \"dd\"),\n (None, \"dd\"),\n (None, \"dd\"),\n ]\n )\n\n\ndef test_options():\n assert console.master.Options(replay_kill_extra=True)\n\n\nclass TestMaster(mastertest.MasterTest):\n def mkmaster(self, **options):\n if \"verbosity\" not in options:\n options[\"verbosity\"] = 0\n o = console.master.Options(**options)\n return console.master.ConsoleMaster(o, proxy.DummyServer())\n\n def test_basic(self):\n m = self.mkmaster()\n for i in (1, 2, 3):\n self.dummy_cycle(m, 1, b\"\")\n assert len(m.state.flows) == i\n\n def test_intercept(self):\n \"\"\"regression test for https://github.com/mitmproxy/mitmproxy/issues/1605\"\"\"\n m = self.mkmaster(intercept=\"~b bar\")\n f = tutils.tflow(req=mitmproxy.test.tutils.treq(content=b\"foo\"))\n m.request(f)\n assert not m.state.flows[0].intercepted\n f = tutils.tflow(req=mitmproxy.test.tutils.treq(content=b\"bar\"))\n m.request(f)\n assert m.state.flows[1].intercepted\n f = tutils.tflow(resp=mitmproxy.test.tutils.tresp(content=b\"bar\"))\n m.request(f)\n assert m.state.flows[2].intercepted\n","sub_path":"mitmproxy/test/mitmproxy/console/test_master.py","file_name":"test_master.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"213749458","text":"#!/usr/bin/env python3\n\nfrom pyrsistent import thaw\nimport esp_ast as ast\n\"\"\"\nclass StackFrame:\n\tdef __init__(self, fn, vars):\n\t\tself.fn = fn\n\t\tself.vars = vars\n\t\n\tdef __str__(self):\n\t\treturn \"StackFrame\" + str(self.vars)\n\t__repr__ = __str__\n\nSIMPLE_OPS = {\n\t\"+\": lambda x, y: x + y,\n\t\"-\": lambda x, y: x - y,\n\t\"*\": lambda x, y: x * y,\n\t\"/\": lambda x, y: x / y,\n\t\"%\": lambda x, y: x % y,\n\t\"**\": lambda x, y: x ** y,\n\t\"//\": lambda x, y: x // y,\n\t\"%%\": None,\n\t\"..\": lambda x, y: range(x, y),\n\t\"...\": None,\n\t\n\t\"!\": lambda x, y: not y,\n\t\"~\": lambda x, y: ~y,\n\t\"&\": lambda x, y: x & y,\n\t\"|\": lambda x, y: x | y,\n\t\"^\": lambda x, y: x ^ y,\n\t\n\t\"!!\": lambda x, y: bool(y),\n\t\"~~\": None,\n\t\"||\": lambda x, y: x or y,\n\t\"&&\": lambda x, y: x and y,\n\t\"^^\": None,\n\t\n\t\"==\": lambda x, y: x == y,\n\t\"!=\": lambda x, y: x != y,\n\t\"===\": lambda x, y: x is y,\n\t\"!==\": lambda x, y: x is not y,\n\t\"<\": lambda x, y: x < y,\n\t\"<=\": lambda x, y: x <= y,\n\t\">\": lambda x, y: x > y,\n\t\">=\": lambda x, y: x >= y,\n\t\"<>\": lambda x, y: (x <= y) - (x >= y),\n\t\"<<\": lambda x, y: x << y,\n\t\"<<<\": None,\n\t\">>\": lambda x, y: x >> y,\n\t\">>>\": None\n}\n\nclass EspBaseException(BaseException): pass\n\nclass Signal(EspBaseException): pass\nclass BreakSignal(Signal): pass\nclass ContinueSignal(Signal): pass\n\nclass ReturnSignal(Signal):\n\tdef __init__(self, value):\n\t\tself.value = value\n\nclass EspException(EspBaseException): pass\n\nclass SemanticError(EspException):\n\tdef __init__(self, origin, msg):\n\t\tif origin:\n\t\t\tp, l, c = origin.pos, origin.line, origin.col\n\t\t\tmsg += f\" ({l}|{c}:{p})\\n\"\n\t\t\tmsg += origin.src.split('\\n')[l - 1].replace('\\t', ' ')\n\t\t\tmsg += f\"\\n{'-'*c}^\"\n\t\t\n\t\tsuper().__init__(msg)\n\t\tself.origin = origin\n\nclass EspRefError(EspException):\n\tdef __init__(self, ref):\n\t\tsuper().__init__(f\"No such variable {ref!r}\")\n\nruntime_global = {\n\t\"iter\": iter,\n\t\"next\": next,\n\t\"print\": lambda *x: print(*x, end='') or EspNone,\n\t\"pyimport\": __import__,\n\t\"none\": EspNone,\n\t\"true\": True,\n\t\"false\": False,\n\t\"nan\": float('nan'),\n\t\"inf\": float('inf'),\n\t\"char\": chr\n}\n\nclass LValue:\n\tdef __init__(self, obj, index):\n\t\tself.obj = obj\n\t\tself.index = index\n\t\t\n\t\tassert(type(index) == list)\n\t\n\tdef get(self):\n\t\ttry:\n\t\t\treturn self.obj[self.index[0]]\n\t\texcept (AttributeError, KeyError, TypeError) as e:\n\t\t\tpass\n\t\t\n\t\tif type(self.obj) == EspList:\n\t\t\tprint(self.obj[self.index[0]])\n\t\t#print(\"getattr\", type(self.obj), self.obj, self.index)\n\t\treturn getattr(self.obj, self.index[0])\n\t\n\tdef set(self, value):\n\t\ttry:\n\t\t\tself.obj[self.index[0]] = value\n\t\t\treturn value\n\t\texcept (AttributeError, KeyError, TypeError) as e:\n\t\t\tpass\n\t\t\n\t\tsetattr(self.obj, self.index[0], value)\n\t\treturn value\n\"\"\"\n\ndef brinc(block, by=1):\n\t'''\n\tIncrement the labels of branch instructions. This is necessary when\n\tthe compiler inserts blocks which aren't visible to the user code\n\t'''\n\tfor b in block:\n\t\tif b[0] in {'break', 'loop'}:\n\t\t\tyield [b[0], b[1] + by]\n\t\telse:\n\t\t\tyield b\n\ndef mkblock(th, el):\n\tth, el = list(th), list(el)\n\t\n\tyield from [\n\t\t['block', len(th)], *th, ['else', len(el)], *el\n\t]\n\ndef mkif(cond, th, el):\n\tcond, th, el = list(cond), list(th), list(el)\n\t\n\tyield from [\n\t\t*cond, ['if', len(th)], *th, ['else', len(el)], *el, ['end']\n\t]\n\nclass Lower1(ast.Visitor):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\t\n\t\tself.blocks = 0\n\t\tself.targets = []\n\t\n\tdef visit_subex(self, expr, inc=0):\n\t\t'''Visit a subexpression contained by one or more shadow blocks'''\n\t\tself.targets.append(self.blocks + inc)\n\t\tyield from self.visit(expr)\n\t\tself.targets.pop()\n\t\n\tdef visit(self, x):\n\t\traise NotImplemented(f\"esp_lower1({type(x)})\")\n\t\n\tdef visit(self, x: None):\n\t\tyield from []\n\t\n\tdef visit(self, x: ast.Prog):\n\t\tfor statement in x.elems:\n\t\t\tyield from self.visit(statement)\n\t\n\tdef visit(self, x: ast.Block):\n\t\tyield from self.mkblock(x.elems)\n\t\n\tdef visit(self, x: ast.If):\n\t\tcond = list(self.visit(x.cond))\n\t\t\n\t\tth = list(self.visit(x.th))\n\t\tel = list(self.visit(x.el))\n\t\tyield from mkif(cond, th, el)\n\t\n\tdef visit(self, x: ast.Loop):\n\t\t# (loop always cond body then else)\n\t\t\n\t\tyield from mkblock([\n\t\t\t*self.visit_subex(x.always),\n\t\t\t*mkif(self.visit_subex(self.cond), [\n\t\t\t# then\n\t\t\t\t*self.brinc(self.visit(x.body)), ['break', 1]\n\t\t\t],\n\t\t\t# else\n\t\t\t\tself.brinc(self.visit(x.th))\n\t\t\t)\n\t\t], self.visit(x.el))\n\t\n\tdef visit(self, x: ast.Op):\n\t\top = x.op\n\t\tif op == \"after\":\n\t\t\tyield from self.visit(x[0])\n\t\t\tyield from self.visit(x[1])\n\t\t\tyield [\"pop\"]\n\t\telif op == \"format\":\n\t\t\tyield self.visit(x[0])\n\t\t\tfor part in x[1:]:\n\t\t\t\tyield self.visit(part)\n\t\t\t\tyield [\"add\"]\n\t\telif op == \"break\":\n\t\t\tpass\n\t\telse:\n\t\t\tyield from self.visit(x[0])\n\t\t\tyield from self.visit(x[1])\n\t\t\tyield [op]\n\ndef eval(x):\n\tprint(\"ast\", ast)\n\t#return EvalVisitor().visit(x)\n\n'''\nwhile(cond()) {\n\tif(test()) {\n\t\tbreak 0;\n\t}\n}\nloop {\n\tif(cond()) {\n\t\tbreak 1\n\t}\n}\n\nloop {\n\talways\n} while(cond) {\n\tbody\n} then {\n\tth\n} else {\n\tel\n}\n\nblock\n\talways\n\tcond\n\tif\n\t\tbody\n\telse\n\t\tth\n\tend\nelse\n\tel\nend\n\nfor(;;) {\n\talways\n\tif(cond) {\n\t\tbody\n\t}\n\telse {\n\t\tth\n\t\tgoto finish\n\t}\n}\nel\nfinish\n'''","sub_path":"old/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"5626268","text":"from .models import ReadStats\nfrom ..authentication.models import User\nfrom rest_framework.permissions import IsAuthenticated, IsAdminUser\nfrom rest_framework.views import APIView\nfrom .serializers import (UserStatsSerializer,\n ArticleStatsSerializer,\n AdminStatsSerializer)\nfrom rest_framework.response import (Response)\nfrom rest_framework import status\nfrom ..articles.models import Articles\nfrom django.db.models import Sum\n# Create your views here.\n\n\nclass UserStatsView(APIView):\n \"\"\"\n A user should be view his/her own read stats\n \"\"\"\n lookup_field = 'username'\n permission_classes = (IsAuthenticated,)\n serializer_class = UserStatsSerializer\n\n def get(self, request, *args, **kwargs):\n # Save read status\n\n stats = ReadStats.objects.filter(user=request.user)\n\n if stats:\n serializer = UserStatsSerializer(stats, many=True)\n return Response(\n {\n \"total_reads\": len(stats),\n \"stats\": serializer.data\n },\n status=status.HTTP_200_OK\n )\n else:\n return Response(\n {\n \"status\": 404,\n \"error\": \"No stats available\"\n }, status=status.HTTP_404_NOT_FOUND\n )\n\n\nclass ArticStatsView(APIView):\n \"\"\"\n A user should be view his/her own read stats\n \"\"\"\n lookup_field = 'slug'\n permission_classes = (IsAuthenticated,)\n serializer_class = ArticleStatsSerializer\n\n def get(self, request, slug, *args, **kwargs):\n\n try:\n\n article = Articles.objects.get(slug=slug)\n\n if article.author == request.user:\n\n stats = ReadStats.objects.filter(article=article)\n\n if stats:\n serializer = ArticleStatsSerializer(stats, many=True)\n return Response(\n {\n \"total_views\":\n stats.aggregate(Sum('views'))['views__sum'],\n \"stats\": serializer.data\n },\n status=status.HTTP_200_OK\n )\n else:\n return Response(\n {\n \"status\": 404,\n \"error\":\n \"{} does not have any stats\".format(article.title)\n }, status=status.HTTP_404_NOT_FOUND\n )\n\n else:\n return Response(\n {\n \"status\": 403,\n \"error\": \"Not allowed\"\n }, status=status.HTTP_403_FORBIDDEN\n )\n\n except Articles.DoesNotExist:\n return Response(\n {\n \"status\": 404,\n \"error\": \"Article not found\"\n }, status=status.HTTP_404_NOT_FOUND\n )\n\n\nclass AdminStatsView(APIView):\n \"\"\"\n A user should be view his/her own read stats\n \"\"\"\n permission_classes = (IsAdminUser,)\n serializer_class = AdminStatsSerializer\n\n def get_queryset(self):\n queryset = ReadStats.objects.all()\n username = self.request.query_params.get('username', None)\n article = self.request.query_params.get('article', None)\n ascendingviews = self.request.query_params.get('asc_views', None)\n descendingviews = self.request.query_params.get('desc_views', None)\n\n # search\n if username is not None:\n queryset = queryset.filter(user__username__icontains=username)\n if article is not None:\n queryset = queryset.filter(article__title__icontains=article)\n # ascending&descending\n if ascendingviews is not None:\n queryset = queryset.order_by('views')\n else:\n if descendingviews is not None:\n queryset = queryset.order_by('-views')\n\n return queryset\n\n def get(self, request, *args, **kwargs):\n\n stats = self.get_queryset()\n\n if stats:\n serializer = AdminStatsSerializer(stats, many=True)\n return Response(\n {\n \"stats\": serializer.data\n },\n status=status.HTTP_200_OK\n )\n else:\n return Response(\n {\n \"status\": 404,\n \"error\": \"No stats available\"\n }, status=status.HTTP_404_NOT_FOUND\n )\n","sub_path":"authors/apps/readstats/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"247459775","text":"import csv\nimport json\n\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.tokenize import word_tokenize\n\nfrom util import archive_name_path, archive_data_path, parse_queries\n\n\"\"\"\nPerforms the preprocessing of the raw query data and the table data by using the nltk library. \nMoreover, after the data is cleaned up the files are saved as text files \n\"\"\"\n\nporter_stemmer = PorterStemmer()\nstop_words = set(stopwords.words('english'))\n\n\ndef clean_up(sentence):\n sentence = sentence.lower()\n sentence = word_tokenize(sentence)\n sentence = [w for w in sentence if not w in stop_words]\n sentence = [w for w in sentence if w.isalpha()]\n stem_sentence = []\n for word in sentence:\n stem_sentence.append(porter_stemmer.stem(word))\n return \" \".join(stem_sentence)\n\n\ndef create_index(query):\n with open(archive_name_path, 'r') as file:\n table_names = file.readlines()\n\n iter_tables = iter(table_names)\n next(iter_tables)\n queries = [int(x.strip().split(\",\")[0]) - 1 for x in iter_tables]\n iter_tables = iter(table_names)\n next(iter_tables)\n table_names = [x.strip().split(\",\")[2] for x in iter_tables]\n table_location = [i.split(\"-\")[1:3] for i in table_names]\n not_found = []\n filewriter = open(\"semantic_data/index_body/\" + str(query) + \".txt\", \"a+\")\n for table_query, location in zip(queries, table_location):\n if table_query != query:\n continue\n table_stem = \"table-\" + location[0] + \"-\"\n with open(archive_data_path + \"re_tables-\" + location[0] + \".json\") as f:\n data = json.load(f)\n table_id = table_stem + location[1]\n if table_id in data:\n data = data[table_id]\n data_pt = data[\"pgTitle\"]\n data_ct = \" \".join(data[\"title\"])\n data_b = \" \".join([\" \".join(i) for i in data[\"data\"]])\n data_sect = data[\"secondTitle\"]\n data_cap = data[\"caption\"]\n query_line = \"%s %s %s %s %s\" % (str(data_b), str(data_pt), str(data_ct), str(data_sect), str(data_cap))\n cleaned_query_line = clean_up(query_line)\n query_line = \"%s %s\" % (str(table_id),\n str(cleaned_query_line))\n filewriter.write(query_line + \"\\n\")\n else:\n not_found.append(table_id)\n filewriter.close()\n\n\ndef create_query():\n with open(\"queries.csv\", newline=\"\") as file:\n reader = csv.reader(file)\n iter_reader = iter(reader)\n next(iter_reader)\n filewriter = open(\"semantic_data/cleaned_queries.txt\", \"+a\")\n for line in iter_reader:\n cleaned_line = clean_up(line[1])\n filewriter.write(line[0] + \",\" + cleaned_line + \"\\n\")\n filewriter.close()\n\n\nif __name__ == \"__main__\":\n # create_query() # use when you want to create queries\n queries = parse_queries() # use when you want to create the tables\n for query in queries:\n create_index(query[0])\n","sub_path":"semantic_index_creation.py","file_name":"semantic_index_creation.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"64201573","text":"# -*- coding: utf-8 -*-\n# © 2018 AITIC\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nfrom odoo import models, api, fields, _\nfrom odoo.exceptions import UserError\nimport datetime\nfrom . import number_to_letter\nfrom odoo.addons import decimal_precision as dp\n\nclass AccountPaymentGroup(models.Model):\n _inherit = \"account.payment.group\"\n\n amount_withholding = fields.Float(string='Withhol. Base.')\n amount_total_payable = fields.Float(string='Total', readonly=True, store=True,\n compute='_compute_amount_total_payable')\n\n withholding_base_amount = fields.Float(string='Withholding Amount', readonly=True, store=True,\n compute='_compute_withholding_base_amount', digits=dp.get_precision('Account'))\n withholding_id = fields.Many2one('account.withholding', string='Retencion', domain=[('type_aliquot', '=', 'earnings')])\n\n total_amount_cancel = fields.Float(string='Total amount canceled')\n is_canceled = fields.Boolean(\"Canceled\", compute='_compute_is_canceled')\n withholding_certificate = fields.Char(string=\"No.Withholding Certificate\", default=\"Draft Certificate\")\n exempt_withholding = fields.Boolean(string=\"Without withholding\", default=False)\n withholding_tax_base = fields.Float(string='Withholding tax base', store=True,\n compute='_compute_withholding_tax_base',\n inverse='_set_withholding_tax_base',\n digits=dp.get_precision('Account'))\n edit_withholding = fields.Boolean(string=\"Edit withholding tax base\", default=False)\n withholding_tax_base_real = fields.Float(string='Withholding tax base',\n digits=dp.get_precision('Account'))\n group_invoice_ids = fields.One2many('account.payment.group.invoice', 'group_id', string='Invoice')\n\n def _convert_payment(self, currency, from_amount, to_currency, company, date, divide=False):\n return currency._convert(from_amount, to_currency, company, date)\n\n def calculate_base_amount_withholding(self):\n base_amount_withholding = self.amount_payable\n to_pay_move_line_ids = self.to_pay_move_line_ids[0] if self.to_pay_move_line_ids else self.env['account.move.line']\n amount_count = self.amount_payable + (self.to_pay_move_line_ids[0].balance if self.to_pay_move_line_ids else 0.0)\n i = 1\n while amount_count > 0.0 and len(self.to_pay_move_line_ids) > i:\n to_pay_move_line_ids += self.to_pay_move_line_ids[i]\n amount_count += self.to_pay_move_line_ids[i].balance\n i += 1\n no_withholding_amount_iibb = 0.0\n for invoice in self.to_pay_move_line_ids.mapped('invoice_id'):\n if invoice.currency_id != self.currency_id:\n no_withholding_amount_iibb += invoice.currency_id._convert(invoice.no_withholding_amount_iibb,\n self.currency_id, self.env.user.company_id,\n invoice.date or fields.Date.today())\n else:\n no_withholding_amount_iibb += invoice.no_withholding_amount_iibb\n\n residual = 0.0\n for invoice in self.to_pay_move_line_ids.mapped('invoice_id'):\n if invoice.currency_id != self.currency_id:\n residual += invoice.currency_id._convert(invoice.residual,\n self.currency_id, self.env.user.company_id,\n invoice.date or fields.Date.today())\n else:\n residual += invoice.residual\n\n self._update_group_invoice_ids()\n\n if self.selected_debt < residual:\n subtract = (residual - self.selected_debt)\n #no_withholding_amount_iibb -= subtract\n residual -= subtract\n\n payment_withholding_amount_iibb = sum((group.withholding_tax_base_real -\n sum(x.withholding_tax_real for x in group.group_invoice_ids))\n for group in\n self.to_pay_move_line_ids.mapped('payment_id.payment_group_id'))\n\n if payment_withholding_amount_iibb > 0:\n no_withholding_amount_iibb -= payment_withholding_amount_iibb\n\n if self.invoice_group_ids:\n for inv in self.invoice_group_ids:\n if inv.invoice_id.no_withholding_amount_iibb > inv.advance_amount:\n no_withholding_amount_iibb -= (inv.invoice_id.no_withholding_amount_iibb - inv.advance_amount)\n\n if self.amount_payable >= residual and residual > 0:\n base_amount_withholding = no_withholding_amount_iibb + (self.amount_payable - residual)\n # elif self.amount_payable >= no_withholding_amount_iibb:\n # base_amount_withholding = no_withholding_amount_iibb\n else: #if self.amount_payable < no_withholding_amount_iibb\n base_amount_w = 0\n amount = self.amount_payable + sum(x.amount_residual for x in self.to_pay_move_line_ids.filtered(lambda x: x.payment_id))\n for invoice in self.to_pay_move_line_ids.sorted(key=lambda p: (p.date, p.id)).mapped('invoice_id'):\n if invoice.residual <= amount:\n amount -= invoice.residual\n base_amount_w += invoice.no_withholding_amount_iibb\n else:\n if invoice.no_withholding_amount_iibb > amount:\n base_amount_w += amount\n else:\n base_amount_w += invoice.no_withholding_amount_iibb\n\n base_amount_w -= payment_withholding_amount_iibb\n base_amount_withholding = base_amount_w\n\n return base_amount_withholding\n\n @api.one\n @api.depends('amount_payable', 'to_pay_move_line_ids', 'edit_withholding')\n def _compute_withholding_tax_base(self):\n base_amount_withholding = self.calculate_base_amount_withholding()\n amount_withholding = 0.0\n if not self._context.get('no_update_withholding', False) and not self.is_canceled:\n amount_withholding = base_amount_withholding if self.to_pay_move_line_ids.mapped('invoice_id') and base_amount_withholding <= self.amount_payable else self.amount_payable\n elif self._context.get('no_update_withholding', False) or self.is_canceled:\n amount_withholding = self.withholding_tax_base_real\n\n self.withholding_tax_base = amount_withholding if amount_withholding >= 0.0 else 0.0\n\n @api.one\n def _set_withholding_tax_base(self):\n #if self.withholding_tax_base > self.amount_payable:\n #raise UserError(_('The withholding tax base can not be greater than the amount to be paid.'))\n return True\n\n @api.one\n @api.depends('payment_ids')\n def _compute_is_canceled(self):\n withholdings = self.env['account.withholding'].search([('payment_id', 'in', self.mapped('payment_ids').ids),\n ('state', '=', 'declared')])\n if withholdings:\n self.is_canceled = True\n else:\n self.is_canceled = False\n\n\n def _update_group_invoice_ids(self):\n if self.state == 'draft':\n self.group_invoice_ids = self.env['account.payment.group.invoice']\n for invoice in self.to_pay_move_line_ids.mapped('invoice_id'):\n self.group_invoice_ids += self.env['account.payment.group.invoice'].new({\n 'invoice_id': invoice.id,\n 'withholding_tax_base': invoice.no_withholding_amount_iibb,\n })\n\n # def _get_is_canceled(self):\n # payment_withholding = self.mapped('payment_ids').filtered(lambda x:x.is_withholding)\n # if self.is_canceled or payment_withholding:\n # return True\n # else:\n # return False\n\n @api.multi\n @api.depends('to_pay_move_line_ids.amount_residual', 'date', 'amount_payable', 'exempt_withholding', 'withholding_tax_base')\n def _compute_withholding_base_amount(self):\n for rec in self:\n if not rec.exempt_withholding:\n if not self._context.get('no_update_withholding') and not rec.is_canceled:\n rec.withholding_base_amount = rec._do_compute_withholding_amount()\n else:\n rec.withholding_base_amount = rec._get_amount_earnings_w_pay()\n\n @api.model\n def _get_default_start_date(self):\n date = fields.Date.from_string(self.date)\n start = datetime.date(date.year, date.month, 1)\n return start\n\n\n def _get_previous_amount_withholding(self, is_regimen=False):\n # payments = self.env['account.payment.group'].search([('partner_type', '=', 'supplier'),\n # ('partner_id', '=', self.partner_id.id),\n # ('date', '<=', self.date),\n # ('date', '>=', self._get_default_start_date()),\n # ('state', 'in', ['posted', 'reconciled'])])\n # pay_amount = sum(pay.amount_withholding for pay in payments)\n # withholding_base_amount = sum(pay._get_amount_earnings_w_pay() for pay in payments)\n domain = [('partner_id', '=', self.partner_id.id), ('date', '<=', self.date),\n ('date', '>=', self._get_default_start_date()), ('type_aliquot', '=', 'earnings')]\n if is_regimen:\n domain.append(('regimen_retencion_id', '=', self.partner_id.regimen_retencion_id.id))\n withholdings = self.env['account.withholding'].search(domain)\n pay_amount = sum(wi.withholding_tax_base_real for wi in withholdings)\n withholding_base_amount = sum(wi.withholding_amount for wi in withholdings)\n domain.append(('active', '=', False))\n withholdings_not_active = self.env['account.withholding'].search(domain)\n pay_amount += sum(wi.withholding_tax_base_real for wi in withholdings_not_active)\n withholding_base_amount += sum(wi.withholding_amount for wi in withholdings_not_active)\n return pay_amount, withholding_base_amount\n\n def _do_compute_withholding_amount(self):\n diff = 0.0\n if self.env.user.company_id.calculate_wh and self.partner_type == 'supplier'\\\n and self.partner_id and self.date and self.amount_payable > 0:\n regimen = self.partner_id.regimen_retencion_id\n if regimen and not self.partner_id.get_exempt_earnings(self.date) and self.withholding_tax_base > 0.0:\n is_regimen = self.env.user.company_id.regime_wh\n pay_amount, withholding_base_amount = self._get_previous_amount_withholding(is_regimen)\n #pay_amount += self.calculate_base_amount_withholding()\n pay_amount += self.withholding_tax_base\n\n monto_deducible = self.partner_id.inscripto and regimen.montos_no_sujeto or 0.0\n if monto_deducible > 0.0 and pay_amount > monto_deducible:\n diff = pay_amount - monto_deducible\n percent = self.partner_id.inscripto and regimen.por_ins or regimen.por_no_ins\n s_escala = self.partner_id.inscripto and regimen.segun_escala_ins or regimen.segun_escala_nins\n if not s_escala:\n diff = diff * (percent / 100)\n else:\n scala = self.env['afip.gain.withholding'].search([('amount_from', '<=', diff),\n ('amount_to', '>=', diff)])\n if not scala:\n diff = 0\n else:\n diff = diff - scala[0].excess_amount\n if diff < 0:\n diff = 0\n else:\n diff = diff * (scala[0].rate / 100)\n diff += scala[0].amount\n diff -= withholding_base_amount\n return diff if diff > 0.0 else 0.0\n\n def _get_amount_earnings_w_pay(self):\n self.ensure_one()\n return sum(pay.amount for pay in self.mapped('payment_ids').filtered(lambda x:x.is_withholding and\n x.type_aliquot == 'earnings'))\n\n @api.multi\n @api.onchange('to_pay_move_line_ids.amount_residual', 'amount_payable', 'withholding_tax_base')\n def _onchange_amount_withholding(self):\n for rec in self:\n rec.amount_withholding = 0.0\n if rec.partner_type == \"supplier\":\n if not self._context.get('no_update_withholding'):\n #rec.amount_withholding = rec.calculate_base_amount_withholding()\n rec.amount_withholding = rec.withholding_tax_base\n else:\n # rec.amount_withholding = self._context.get('amount_withholding')\n rec.amount_withholding = rec._get_amount_w_pay()\n\n @api.multi\n @api.onchange('to_pay_move_line_ids', 'amount_payable', 'state', 'withholding_base_amount')\n def _onchange_to_pay_amount(self):\n super(AccountPaymentGroup, self)._onchange_to_pay_amount()\n for rec in self:\n if not rec.is_canceled:\n rec.to_pay_amount -= rec.withholding_base_amount\n\n @api.multi\n @api.depends('amount_payable')\n def _compute_payable_wtax(self):\n super(AccountPaymentGroup, self)._compute_payable_wtax()\n for rec in self:\n rec.amount_payable_wtax += rec.withholding_base_amount\n\n @api.multi\n @api.depends('amount_payable', 'unreconciled_amount', 'partner_id', 'withholding_base_amount')\n def _compute_to_pay_amount(self):\n super(AccountPaymentGroup, self)._compute_to_pay_amount()\n for rec in self:\n if not rec.is_canceled:\n rec.to_pay_amount -= rec.withholding_base_amount\n\n @api.multi\n @api.depends('payments_amount', 'withholding_base_amount', 'state')\n def _compute_amount_total_payable(self):\n for rec in self:\n if rec.state == \"draft\" and not rec.is_canceled:\n rec.amount_total_payable = rec.payments_amount + rec.withholding_base_amount\n else:\n rec.amount_total_payable = rec.payments_amount\n\n def create_withholding_payments(self):\n if self.withholding_base_amount > 0.0 and not self.mapped('payment_ids').filtered(lambda x: x.is_withholding and x.type_aliquot == 'earnings'):\n journal_id = self.company_id.supplier_wh_journal_id\n if not journal_id:\n raise UserError(_('You must comfigurate in the company the withholding journal.'))\n payment_method_id = self.env.ref('account.account_payment_method_manual_out', False)\n currency = self.currency_id\n withholding_base_amount = self.withholding_base_amount\n currency_journal = journal_id.currency_id or journal_id.company_id.currency_id\n if currency_journal and currency_journal != currency:\n # withholding_base_amount = currency._convert(self.withholding_base_amount, currency_journal,\n # self.env.user.company_id,\n # self.date or fields.Date.today())\n withholding_base_amount = self._convert_payment(currency, self.withholding_base_amount, currency_journal,\n self.env.user.company_id, self.date or fields.Date.today())\n\n currency = currency_journal\n vals = {\n 'journal_id': journal_id.id,\n 'payment_method_id': payment_method_id.id,\n 'payment_date': self.date,\n 'payment_type': 'outbound',\n 'currency_id': currency.id,\n 'communication': _(\"Withholding Earnings\"),\n 'partner_id': self.partner_id.id,\n 'partner_type': self.partner_type,\n 'payment_group_company_id': self.company_id.id,\n # 'payment_group': True,\n 'amount': withholding_base_amount,\n 'amount_aliquot_in_words': number_to_letter.to_word_no_decimal(withholding_base_amount),\n 'name': '',\n 'is_withholding': True,\n 'type_aliquot': 'earnings',\n 'state': 'draft'}\n\n self.payment_ids += self.env['account.payment'].create(vals)\n\n def _get_amount_w_pay(self):\n self.ensure_one()\n return sum(pay.amount for pay in self.mapped('payment_ids').filtered(lambda x:x.is_withholding and\n x.type_aliquot == 'earnings'))\n\n def _get_is_aliquot(self):\n return False\n\n def generate_withholding_payments(self):\n for rec in self:\n if rec.partner_type == \"supplier\":\n if not rec.is_canceled:\n rec.create_withholding_payments()\n is_certificate = rec._get_is_aliquot()\n if is_certificate:\n rec.withholding_certificate = self.env['ir.sequence'].next_by_code('withholding.certificate')\n else:\n amount_total = 0.0\n for pay in rec.payment_ids:\n if pay.currency_id != rec.currency_id:\n # amount_total += pay.currency_id._convert(pay.amount, rec.currency_id, rec.env.user.company_id,\n # rec.date or fields.Date.today())\n amount_total += pay._convert_payment(pay.currency_id, pay.amount,\n rec.currency_id, rec.env.user.company_id,\n rec.date or fields.Date.today())\n # amount_total = sum(pay.amount for pay in rec.payment_ids)\n if amount_total > rec.total_amount_cancel:\n raise UserError(_('The amount to be paid must not be greater than the amount initially paid.'))\n\n rec.withholding_tax_base_real = rec.withholding_tax_base\n ctx = dict(self._context)\n ctx.update({'no_update_withholding': True,\n 'amount_withholding': self.amount_withholding,\n 'withholding_base_amount': self.withholding_base_amount})\n res = super(AccountPaymentGroup, self.with_context(ctx)).generate_withholding_payments()\n return res\n\n def create_withholding(self):\n res = super(AccountPaymentGroup, self).create_withholding()\n for rec in self:\n # rec.is_canceled = False\n rec.to_pay_move_line_ids.mapped('payment_id.payment_group_id').update_payment_down()\n rec._post_update_group_invoice_ids()\n\n if rec.withholding_base_amount > 0.0 and rec.company_id.calculate_wh:\n payment = rec.mapped('payment_ids').filtered(lambda x: x.is_withholding and\n x.type_aliquot == 'earnings')\n if payment:\n if not rec.withholding_id:\n sequence = rec.env['ir.sequence'].with_context(ir_sequence_date=payment.payment_date).next_by_code(\n 'account.withholding')\n withholding = rec.env['account.withholding'].create({'name': sequence,\n 'withholding_amount': payment.amount,\n 'date': rec.date,\n 'partner_id': rec.partner_id.id,\n 'regimen_retencion_id': rec.partner_id.regimen_retencion_id.id,\n 'invoice_ids': [(4, invoice.id, None) for\n invoice in rec.invoice_ids],\n 'reference': rec.name,\n 'payment_id': payment[0].id,\n 'state': 'done',\n 'withholding_tax_base_real': rec.withholding_tax_base_real,\n 'type_aliquot': 'earnings'})\n rec.withholding_id = withholding.id\n elif payment and rec.withholding_id:\n rec.withholding_id.write({\n 'withholding_amount': payment.amount,\n 'date': rec.date,\n 'partner_id': rec.partner_id.id,\n # 'regimen_retencion_id': rec.partner_id.regimen_retencion_id.id,\n 'invoice_ids': [(5, 0, 0)] + [(4, invoice.id, None) for invoice in rec.invoice_ids],\n 'reference': rec.name,\n 'payment_id': payment[0].id,\n 'state': 'done' if rec.withholding_id.state != 'declared' else 'declared',\n 'withholding_tax_base_real': rec.withholding_tax_base_real,\n })\n elif rec.env.user.company_id.calculate_wh and rec.partner_type == 'supplier' and rec.amount_payable > 0:\n regimen = rec.partner_id.regimen_retencion_id\n if regimen and not rec.partner_id.get_exempt_earnings(rec.date) and rec.withholding_tax_base > 0.0:\n withholding = rec.env['account.withholding'].create({'name': 'Withholding 0.0',\n 'withholding_amount': rec.withholding_base_amount,\n 'date': rec.date,\n 'partner_id': rec.partner_id.id,\n 'regimen_retencion_id': rec.partner_id.regimen_retencion_id.id,\n 'invoice_ids': [(4, invoice.id, None) for\n invoice in rec.invoice_ids],\n 'reference': rec.name,\n 'payment_id': rec.mapped('payment_ids')[0].id,\n 'state': 'done',\n 'withholding_tax_base_real': rec.withholding_tax_base_real,\n 'type_aliquot': 'earnings',\n 'active': False})\n return res\n\n def _post_update_group_invoice_ids(self):\n withholding_tax_real_total = self.withholding_tax_base_real\n for line in self.with_context({'payment_group_id': self.id,\n 'matched_lines': True}).matched_move_line_ids.filtered(lambda x:\n x.invoice_id).sorted(key=lambda i: i.amount_residual_currency, reverse=True):\n group_invoice = self.group_invoice_ids.filtered(lambda x: x.invoice_id == line.invoice_id)\n if group_invoice and withholding_tax_real_total > 0.0:\n if withholding_tax_real_total > group_invoice[0].withholding_tax_base:\n withholding_tax_real = group_invoice[0].withholding_tax_base\n else:\n withholding_tax_real = withholding_tax_real_total\n withholding_tax_real_total -= withholding_tax_real\n group_invoice[0].write({\n 'withholding_tax_real': withholding_tax_real\n })\n\n def update_payment_down(self):\n for rec in self:\n withholding_tax_real_total = rec.withholding_tax_base_real - sum(x.withholding_tax_real for x in rec.group_invoice_ids)\n for move in rec.matched_move_line_ids.with_context(payment_group_id=rec.id).sorted(key=lambda p: (p.date, p.id)):\n if move.invoice_id and not rec.group_invoice_ids.filtered(lambda x: x.invoice_id == move.invoice_id):\n if withholding_tax_real_total > 0:\n withholding_tax_real = withholding_tax_real_total if withholding_tax_real_total < move.invoice_id.no_withholding_amount_iibb else move.invoice_id.no_withholding_amount_iibb\n self.env['account.payment.group.invoice'].create({\n 'invoice_id': move.invoice_id.id,\n 'group_id': rec.id,\n 'withholding_tax_base': move.invoice_id.no_withholding_amount_iibb,\n 'withholding_tax_real': withholding_tax_real,\n })\n withholding_tax_real_total -= withholding_tax_real\n\n\n def _create_group_invoice_ids(self, invoice):\n withholding_tax_real_total = self.withholding_tax_base_real\n withholding_tax_real_sum = sum(x.withholding_tax_real for x in self.group_invoice_ids)\n withholding_tax_real = withholding_tax_real_total - withholding_tax_real_sum\n if withholding_tax_real > invoice.no_withholding_amount_iibb:\n withholding_tax_real = invoice.no_withholding_amount_iibb\n self.env['account.payment.group.invoice'].create({\n 'invoice_id': invoice.id,\n 'group_id': self.id,\n 'withholding_tax_base': invoice.no_withholding_amount_iibb,\n 'withholding_tax_real': withholding_tax_real,\n })\n\n @api.multi\n def cancel(self):\n for rec in self:\n rec.write({\n # 'is_canceled': True,\n 'total_amount_cancel': rec.amount_payable\n })\n\n rec._compute_to_pay_amount()\n\n super(AccountPaymentGroup, rec.with_context({'no_update_withholding': True,\n 'amount_withholding': rec.amount_withholding,\n 'withholding_tax_base': rec.withholding_tax_base,\n })).cancel()\n rec.payment_ids.write({'move_name': False})\n if rec.withholding_id and rec.withholding_id.state == 'done':\n rec.withholding_id.action_annulled()\n withholding_ids = self.env['account.withholding'].search([('active', '=', False)]).filtered(lambda x: x.payment_group_id == rec)\n if withholding_ids:\n withholding_ids.unlink()\n return True\n\n @api.multi\n def write(self, vals):\n for rec in self:\n if not 'state' in vals:\n vals['state'] = self.state\n return super(AccountPaymentGroup, self).write(vals)\n\n @api.multi\n def unlink(self):\n for rec in self:\n if rec.withholding_id and rec.withholding_id.state == 'declared':\n raise UserError(_(\n \"You cannot delete a payment with declared withholdings.\"))\n elif rec.withholding_id:\n rec.withholding_id.unlink()\n return super(AccountPaymentGroup, self).unlink()\n\n @api.one\n def get_withholding_receipt(self):\n if self.payment_ids.filtered(lambda x: x.customers_withholding):\n return True\n else:\n return False\n return super(AccountPaymentGroup, self).unlink()\n\n @api.model\n def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None):\n value = False\n if self._name == 'account.payment.group':\n a = []\n value = False\n for do in domain:\n if do[0] == 'payment_ids':\n value = do[2]\n domain.remove(do)\n records = self.search(domain or [], offset=offset, limit=limit, order=order)\n if value:\n if self._context.get('journal_search', False):\n payms = self.env['account.payment'].search([('journal_id', 'ilike', value)])\n records = records.mapped('payment_ids').filtered(lambda x: x in payms).mapped('payment_group_id')\n else:\n if records[0].partner_type == 'customer':\n payms = self.env['account.payment'].search([('withholding_receipt', 'ilike', value)])\n records = records.mapped('payment_ids').filtered(lambda x: x in payms).mapped('payment_group_id')\n else:\n withholding = self.env['account.withholding'].search([('name', 'ilike', value)])\n records = records.filtered(lambda x: x.withholding_id in withholding)\n\n if not records:\n return []\n\n if fields and fields == ['id']:\n return [{'id': record.id} for record in records]\n\n # TODO: Move this to read() directly?\n if 'active_test' in self._context:\n context = dict(self._context)\n del context['active_test']\n records = records.with_context(context)\n\n result = records.read(fields)\n if len(result) <= 1:\n return result\n\n index = {vals['id']: vals for vals in result}\n return [index[record.id] for record in records if record.id in index]\n\nclass AccountPaymentGroupInvoice(models.Model):\n _name = \"account.payment.group.invoice\"\n\n invoice_id = fields.Many2one('account.invoice', string='Invoice')\n withholding_tax_base = fields.Float(string='withholding tax base',\n digits=dp.get_precision('Account'), default=0.0)\n withholding_tax_real = fields.Float(string='withholding tax base',\n digits=dp.get_precision('Account'), default=0.0)\n group_id = fields.Many2one('account.payment.group', string='Group', ondelete='cascade')\n\n\n","sub_path":"l10n_ar_account_group_withholding/models/account_payment_group.py","file_name":"account_payment_group.py","file_ext":"py","file_size_in_byte":31297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"17941045","text":"from collections import Counter\n\ndef main():\n n = int(input())\n a = list(map(int,input().split()))\n q = int(input())\n c = Counter(a)\n allsum = 0\n for k,v in c.items():\n allsum += k*v\n ans = []\n for i in range(q):\n bi,ci = list(map(int,input().split()))\n allsum += ci*c[bi] - bi*c[bi]\n c[ci] = c[ci] + c[bi]\n c[bi] = 0\n ans.append(allsum)\n for i in ans:\n print(i) \nmain()","sub_path":"Python_codes/p02630/s816203710.py","file_name":"s816203710.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"515927388","text":"import click\nimport time\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom tcfcli.cmds.native.common.invoke_context import InvokeContext\nfrom tcfcli.cmds.local.common.options import invoke_common_options\nfrom tcfcli.common.user_exceptions import InvalidEnvParameters\nfrom tcfcli.common.scf_client.scf_log_client import ScfLogClient\n\nTM_FORMAT = '%Y-%m-%d %H:%M:%S'\n@click.command()\n@click.option('-n', '--name', help=\"Function name\")\n@click.option('-ns', '--namespace', default=\"default\", help=\"Namespace name\")\n@click.option('--region', default=None, help=\"The region of the service (e.g. ap-guangzhou)\")\n@click.option('-c', '--count', type=int,\n help=\"The count of logs,the maximum value is 10000 and the minimum value is 1\")\n@click.option('-s', '--start-time', type=str, default=None, help=\"Fetch logs starting at this time, conflict with --tail\")\n@click.option('-e', '--end-time', type=str, default=None, help=\"Fetch logs up to this time, conflict with --tail\")\n@click.option('-d', '--duration', type=int, default=None, help=\"The duration between starttime and current time(unit:second)\")\n@click.option('-f', '--failed', is_flag=True, default=False, help=\"Fetch the failed log\")\n@click.option('-t', '--tail', is_flag=True ,default=False, help=\"Tail the log output\")\ndef logs(name, namespace, region, count, start_time, end_time, duration, failed, tail):\n \"\"\"\n \\b\n Fetch logs of scf from service.\n Common usage:\n \\b\n Fetch logs using the function's name\n \\b\n $ scf logs -n(--name) function\n \\b\n Specify a namespace, the default value is 'default'\n \\b\n $ scf logs -n function -ns(--namespace) nodefault\n \\b\n Specific time range using the -s (--starttime) and -e (--endtime) options\n \\b\n $ scf logs -n function -s xxxx-xx-xx 00:00:00 -e xxxx-xx-xx 00:00:10\n \\b\n Specify a duration between starttime and current time(unit:second)\n \\b\n $ scf logs -n function -d(--duration) 10\n \\b\n Fetch logs that was exceptional \n \\b\n $ scf logs -n function -f(--failed)\n \\b\n Specify region of service\n \\b\n $ scf logs -n function --region ap-guangzhou\n \"\"\"\n if name is None:\n raise InvalidEnvParameters(\"Function name is unspecified\")\n\n if duration and (start_time or end_time):\n raise InvalidEnvParameters(\"Duration is conflict with (start_time, end_time)\")\n\n if tail:\n start = datetime.now()\n end = start + timedelta(days=1)\n if count:\n end = start\n start = end - timedelta(days=1)\n else: \n start, end = _align_time(start_time, end_time, duration)\n client = ScfLogClient(name, namespace, region, failed)\n if tail and count:\n client.fetch_log_tail_c(start.strftime(TM_FORMAT), \n end.strftime(TM_FORMAT), count, tail)\n return\n if not count:\n count = 10000 #cloudapi limit\n client.fetch_log(start.strftime(TM_FORMAT), end.strftime(TM_FORMAT), count, tail)\n\n\n\n\ndef _align_time(_start, _end, _offset):\n start = end = None\n if _start:\n start = datetime.strptime(_start, TM_FORMAT)\n\n if _end:\n end = datetime.strptime(_end, TM_FORMAT)\n \n \n if _offset:\n end = datetime.now()\n start = end - timedelta(seconds=_offset)\n elif start and end:\n pass\n elif (not start) and (not end):\n end = datetime.now()\n start = end - timedelta(seconds=60) \n elif not start:\n raise InvalidEnvParameters(\"start-time name is unspecified\")\n else:\n raise InvalidEnvParameters(\"end-time name is unspecified\")\n\n if start >= end:\n raise InvalidEnvParameters(\"endtime must be greater than starttime\")\n return start, end\n","sub_path":"tcfcli/cmds/logs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"89648615","text":"def Tensor(a,b):\r\n for i in range(len(a)):\r\n for j in range(len(a[0])):\r\n m=[]\r\n for x in range(len(b)):\r\n for y in range(len(b[0])):\r\n m.append(multiplicacion(a[i][j],b[x][y]))\r\n a[i][j]=c\r\n return a\r\ndef multmatrices(m1,m2):\r\n if len(m1[0])==len(m2):\r\n mat=[[(0,0)]*len(m2[0]) for i in range(len(m1))]\r\n for i in range(len(m1)):\r\n for j in range(len(m2[0])):\r\n for z in range(len(m2)):\r\n p=multiplicacion(m1[i][z],m2[z][j])\r\n m=mat[i][j]\r\n mat[i][j] = (p[0]+m[0],p[1]+m[1])\r\n \r\n for i in mat:\r\n print(i)\r\n else:\r\n print(\"No se puede realizar la multiplicacion entre matrices ya que no cumplen con la condicion de que las columnas de m1 sean iguales a las filas de m2\")\r\ndef multiplicacion(m1,m2):\r\n rta=[]\r\n rta.append(m1[0]*m2[0]-m1[1]*m2[1])\r\n rta.append(m1[0]*m2[1]+m1[1]*m2[0])\r\n if rta[1]>=0:\r\n return (rta[0]),(rta[1])\r\n else:\r\n return (rta[0]),(rta[1])\r\ndef mult_vector_matriz(v,b):\r\n filas=len(b)\r\n columnas=len(v[0])\r\n if filas==columnas:\r\n filas=len(v)\r\n columnas=len(b[0])\r\n matriz=[[[0,0] for j in range(columnas)] for i in range(filas)]\r\n for i in range(filas):\r\n for j in range(columnas):\r\n for k in range(0,len(b)):\r\n m=multiplicacion(v[i][k],b[k][j])\r\n n=matriz[i][j]\r\n matriz[i][j]=(m[0]+n[0],m[1]+n[1])\r\n return matriz\r\n else:\r\n return False\r\ndef matriztras(matriz):\r\n filas=len(matriz)\r\n columnas=len(matriz[0])\r\n return [[matriz[j][i] for j in range(filas)]for i in range(columnas)]\r\ndef grafo(m,v,cantidad):\r\n n=m\r\n while cantidad != 0:\r\n f=mult_vector_matriz(n,m)\r\n n=f\r\n cantidad-=1\r\n v=matriztras(v)\r\n x=mult_vector_matriz(n,v)\r\n return x\r\n\r\n\r\ndef balas(m,v,cantidad):\r\n n=m\r\n while cantidad != 0:\r\n f=mult_vector_matriz(n,m)\r\n n=f\r\n cantidad-=1\r\n v=matriztras(v)\r\n o=mult_vector_matriz(n,v)\r\n return o\r\n\r\n\r\n\r\ndef doble(m): \r\n f=mult_vector_matriz(m,m)\r\n matriz=[[0 for j in range(8)] for i in range(8)]\r\n for i in range(len(f)):\r\n for j in range(len(f[0])):\r\n matriz[i][j]=(f[i][j][0]**2+f[i][j][1]**2)**0.5\r\n return matriz\r\n \r\n","sub_path":"SegundoTercio.py","file_name":"SegundoTercio.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"426896332","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch.optim as optim\nfrom utils.utils import progress_bar\n\ndef train(network, trainloader, device, optimizer, criterion, epoch):\n print('\\nEpoch: %d' % epoch)\n network.train()\n train_loss = 0\n correct = 0\n total = 0\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n inputs, targets = inputs.to(device), targets.to(device)\n optimizer.zero_grad()\n outputs = network(inputs)\n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n progress_bar(batch_idx, len(trainloader), 'Train >> Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\n \n '''print('Train:: Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))'''\n \ndef test(network, testloader, device, criterion, epoch):\n network.eval()\n test_loss = 0\n correct = 0\n total = 0\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(testloader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = network(inputs)\n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n progress_bar(batch_idx, len(testloader), 'Test >> Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n \n '''print('Test:: Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))'''\n \ndef testWithAccPlt(network, testloader, device, criterion, valaccuracies, vallosses, epoch):\n network.eval()\n test_loss = 0\n correct = 0\n total = 0\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(testloader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = network(inputs)\n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n accuracy = 100.*correct/total\n\n progress_bar(batch_idx, len(testloader), 'Test >> Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), accuracy, correct, total))\n \n # scheduler.step(effective_loss)\n \n valaccuracies.append(accuracy)\n test_loss /= len(testloader.dataset)\n vallosses.append(test_loss)\n print(test_loss)\n return test_loss\n \ndef trainWithAccPlt(network, trainloader, device, optimizer, criterion, trainaccuracies, trainlosses, epoch):\n print('\\nEpoch: %d' % epoch)\n network.train()\n train_loss = 0\n correct = 0\n total = 0\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n inputs, targets = inputs.to(device), targets.to(device)\n optimizer.zero_grad()\n outputs = network(inputs)\n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n accuracy = 100.*correct/total\n \n progress_bar(batch_idx, len(trainloader), 'Train >> Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (train_loss/(batch_idx+1), accuracy, correct, total))\n \n '''print('Train:: Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))'''\n \n trainaccuracies.append(accuracy)\n train_loss /= len(trainloader.dataset)\n trainlosses.append(train_loss)\n\ndef plotmetrics(target,trainaccuracies, testaccuracies, trainlosses, testlosses, savefilename):\n \n \n fig, axs = plt.subplots(1, 2, figsize=(15,10))\n \n # Plot Accuracy\n axs[0].plot(trainaccuracies, label='Train Accuracy')\n axs[0].plot(testaccuracies, label='Test Accuracy')\n axs[0].set_title(\"Accuracy\")\n axs[0].legend(loc=\"upper left\")\n \n # Plot loss\n axs[1].plot(trainlosses, label='Train Loss')\n axs[1].plot(testlosses, label='Test Loss')\n axs[1].set_title(\"Loss\")\n axs[1].legend(loc=\"upper left\")\n \n plt.show()\n fig.savefig(\"{}.png\".format(savefilename))\n \n print('Max. Train Accuracy outoff {}-epochs is : {} at {}-Epoach'.format(len(trainaccuracies),max(trainaccuracies),trainaccuracies.index(max(trainaccuracies))+1))\n print('Max. Test Accuracy outoff {}-epochs is : {} at {}-Epoach'.format(len(testaccuracies),max(testaccuracies),testaccuracies.index(max(testaccuracies))+1))\n \n print(\"\\n\\nMin. Train Loss outoff {}-epochs is : {:.6f} at {}-Epoach\".format(len(trainlosses),min(trainlosses),trainlosses.index(min(trainlosses))+1))\n print(\"Min. Test Loss outoff {}-epochs is : {:.6f} at {}-Epoach\".format(len(testlosses),min(testlosses),testlosses.index(min(testlosses))+1))\n \n \n for i,v in enumerate(trainaccuracies):\n if v>float(target):\n print(\"\\n\\nTarget-{}% achieved at {}th epoach,Train accuracy is : {}\".format(float(target),i+1,v))\n break\n \n for i,v in enumerate(testaccuracies):\n if v>float(target):\n print(\"Target-{}% achieved at {}th epoach,Test accuracy is : {}\".format(float(target),i+1,v))\n break","sub_path":"S15/lib/trainTestMethods.py","file_name":"trainTestMethods.py","file_ext":"py","file_size_in_byte":5860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"406136367","text":"import sys\nimport importlib\nfrom types import SimpleNamespace\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom scipy.special import softmax\nfrom joblib import Parallel, delayed\nimport seaborn as sns\n\nsys.path.append(\"../src\")\nsys.path.append(\"../configs\")\n\nsys.argv = ['--config', 'config1']\n\nfrom models import *\nfrom loss import *\nfrom train import *\nfrom data import *\nimport numpy as np\n\ndef gpu_unravel(batch):\n input_dict, target_dict = batch\n input_dict = {k: input_dict[k].cuda() for k in input_dict}\n target_dict = {k: target_dict[k].cuda() for k in target_dict}\n return input_dict, target_dict\n\ndef get_embeddings(dl, model):\n with torch.no_grad():\n embeddings = np.zeros((len(dl.dataset) , 512))\n total = len(dl)\n target_list = [] #Added!!!\n for idx, batch in tqdm(enumerate(dl), total=len(dl)):\n input_dict, target_dict = dict_unravel(batch)\n\n outs = model.forward(input_dict, get_embeddings=True)[\"embeddings\"]\n\n target_list.append(target_dict['target']) #Added!!!\n embeddings[idx*batch_size:idx*batch_size+outs.size(0),:] = outs.detach().cpu().numpy()\n\n return embeddings, target_list #Changed!!!\n\nif __name__ == '__main__':\n\n dict_unravel = gpu_unravel\n\n name = \"config1\"\n # pretrained_weights = \"../models/config1_ckpt_10.pth\"\n pretrained_weights = \"../models/config1/config1_ckpt_10.pth\"\n\n csv = \"train\"\n\n #このtrainはGLRv2のfull trainだと思う。\n # train = pd.read_csv(f\"../embeddings/{csv}.csv\")\n train = pd.read_csv(f\"../../input/GLDv2/{csv}.csv\")\n\n # train[\"img_folder\"] = \"/ssd/kaggle-landmark/input/train/\"\n train[\"img_folder\"] = \"../../input/GLDv2/train/\"\n # train[\"img_folder\"] = \"/home/ubuntu/kaggle/input/GLDv2/train/\"\n# train[\"target\"] = 0\n train=train.rename(columns={'landmark_id': 'target'})\n\n train=train[['id','img_folder','target']]\n \n train=train[:5120]\n print(\"train[:2]\")\n\n aug = A.Compose([\n A.SmallestMaxSize(512),\n A.CenterCrop(always_apply=False, p=1.0, height=512, width=512),\n ],\n p=1.0\n )\n\n\n val_ds = GLRDataset(train, normalization=args.normalization, aug=aug)\n\n batch_size = 512\n print(f'batch_size {batch_size}')\n #batch_size = 8\n nw=24\n print(f'num_workers {nw}')\n val_dl = DataLoader(dataset=val_ds,\n batch_size=batch_size,\n sampler=SequentialSampler(val_ds), collate_fn=collate_fn, num_workers=nw, pin_memory=True)\n\n print(\"load model\")\n model = Net(args,pretrained=False)\n model.eval()\n model.cuda()\n model.load_state_dict(torch.load(pretrained_weights))\n model = nn.DataParallel(model)\n for i in tqdm(range(1000)):\n pass\n print(\"get embeddings\")\n #landmark_id to calss_idは不要か。\n embeddings, target_list = get_embeddings(val_dl, model) #Changed!!\n #print(f\"shape of embeddings:{embeddings.shape}\")\n print(\"saving the embeddings\")\n np.save(f\"../embeddings/{name}_{csv}_embeddings_TEST\", embeddings)\n print(\"saving is done\")\n \n #Added!!!!\n import pickle\n print(\"saving the target_lists\")\n with open(f\"../embeddings/{name}_{csv}_target_list_TEST.pkl\", 'wb') as f:\n pickle.dump(target_list, f)\n print(\"saving is done\")\n","sub_path":"notebooks/get_embeddings.py","file_name":"get_embeddings.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"377065100","text":"import os\nimport unittest\nimport sqlite3\nimport pisces\n\nclass DataBaseTests(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.db_extension = \"data/pisces_test.db\"\n\t\tself.db_path = os.path.join(pisces.app.root_path, self.db_extension)\n\n\tdef test_initDatabase(self):\n\t\tpisces.initDatabase(self.db_path)\n\t\tconn = sqlite3.connect(self.db_path)\n\t\tcursor = conn.cursor()\n\n\t\tuser_results = cursor.execute(\"SELECT * FROM users\")\n\t\tfish_results = cursor.execute(\"SELECT * FROM fish\")\n\n\t\tself.assertEqual(user_results.fetchone(), None)\n\t\tself.assertEqual(fish_results.fetchone(), None)\n\t\t\n\t\tconn.close()\t\n\n\tdef tearDown(self):\n\t\tpass\n\ndef main():\n\tunittest.main()\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"website/pisces_test.py","file_name":"pisces_test.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"497727257","text":"#!/usr/bin/env python\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport argparse\nimport builtins\nimport os\nimport shutil\nimport copy\n\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nimport torch.optim\n\nimport torchvision.models as models\nfrom data.dataset import load_train, load_val\nfrom research_tools.store import ExperimentLogWriter\nimport utils\n\nparser = argparse.ArgumentParser(description='PyTorch ImageNet Training', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('--dataset', choices=['imagenet', 'tiny-imagenet'], default='tiny-imagenet',\n help='Which dataset to evaluate on.')\nparser.add_argument('-a', '--arch', metavar='ARCH', default='resnet50')\nparser.add_argument('-j', '--workers', default=32, type=int, metavar='N',\n help='number of data loading workers (default: 32)')\nparser.add_argument('--epochs', default=100, type=int, metavar='N',\n help='number of total epochs to run')\nparser.add_argument('--start_epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('-b', '--batch_size', default=256, type=int,\n metavar='N',\n help='mini-batch size (default: 256), this is the total '\n 'batch size of all GPUs on the current node when '\n 'using Data Parallel or Distributed Data Parallel')\nparser.add_argument('--lr', '--learning-rate', default=30., type=float,\n metavar='LR', help='initial learning rate', dest='lr')\nparser.add_argument('--schedule', default=[60, 80], nargs='*', type=int,\n help='learning rate schedule (when to drop lr by a ratio)')\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum')\nparser.add_argument('--wd', '--weight_decay', default=0., type=float,\n metavar='W', help='weight decay (default: 0.)',\n dest='weight_decay')\nparser.add_argument('-p', '--print_freq', default=10, type=int,\n metavar='N', help='print frequency (default: 10)')\nparser.add_argument('--eval_first', action='store_true',\n help='If this is true, we eval -1.pth.')\n\nparser.add_argument('--num_per_class', type=int, default=int(1e10),\n help='Number of images per class for getting a subset of Imagenet')\nparser.add_argument('--data_aug', type=str, help='Choice of augmentation to use for training linear classifier.')\nparser.add_argument('--checkpoint_every', type=int, default=5, help='How often to evaluate linear classification (every how many epochs).')\nparser.add_argument('--specific_ckpts', nargs='*', help='filenames of specific checkpoints to evaluate')\n\nbest_acc1 = 0\n\ndef load_model(state_dict):\n for key in list(state_dict.keys()):\n if key.startswith('online_encoder.net'):\n state_dict[key[len('online_encoder.net.'):]] = state_dict[key]\n del state_dict[key]\n model = models.resnet50(num_classes=200)\n model.load_state_dict(state_dict, strict=True)\n return model\n\ndef main():\n args = parser.parse_args()\n logger = ExperimentLogWriter('/tiger/u/kshen6/byol-pytorch', None)\n for fname in sorted(os.listdir('.')):\n if fname not in args.specific_ckpts: continue\n eval_ckpt(fname, args, logger)\n\ndef eval_ckpt(fname, args, logger):\n model = load_model(torch.load(fname)).cuda()\n dict_id = fname.split('.')[0]\n logger.create_data_dict(\n ['epoch', 'train_acc', 'val_acc','train_loss', 'val_loss', 'train5', 'val5'],\n dict_id=dict_id)\n\n # freeze all layers but the last fc\n for name, param in model.named_parameters():\n if name not in ['fc.weight', 'fc.bias']:\n param.requires_grad = False\n # init the fc layer\n model.fc.weight.data.normal_(mean=0.0, std=0.01)\n model.fc.bias.data.zero_()\n\n # define loss function (criterion) and optimizer\n criterion = nn.CrossEntropyLoss().cuda()\n\n # optimize only the linear classifier\n parameters = list(filter(lambda p: p.requires_grad, model.parameters()))\n assert len(parameters) == 2 # fc.weight, fc.bias\n optimizer = torch.optim.SGD(parameters, args.lr,\n momentum=args.momentum,\n weight_decay=args.weight_decay)\n\n cudnn.benchmark = True\n\n # Data loading code\n train_sampler, train_loader = load_train(args.dataset, args.num_per_class, False,\n args.batch_size, args.workers, data_aug=args.data_aug)\n val_loader = load_val(args.dataset, args.batch_size, args.workers)\n\n best_acc1 = 0\n\n for epoch in range(args.start_epoch, args.epochs):\n adjust_learning_rate(optimizer, epoch, args)\n\n # train for one epoch\n top1, top5, losses = train(train_loader, model, criterion, optimizer, epoch, args)\n\n # always test after 1 epoch of linear evaluation\n if epoch == 0 or (epoch + 1) % args.checkpoint_every == 0:\n # evaluate on validation set\n acc1, acc5, val_losses = validate(val_loader, model, criterion, args)\n\n # remember best acc@1 and save checkpoint\n is_best = acc1 > best_acc1\n best_acc1 = max(acc1, best_acc1)\n\n logger.update_data_dict(\n {\n 'epoch' : epoch + 1,\n 'train_acc' : top1, \n 'val_acc' : acc1,\n 'train_loss' : losses,\n 'val_loss' : val_losses,\n 'train5' : top5,\n 'val5' : acc5\n }, dict_id=dict_id)\n logger.save_data_dict(dict_id=dict_id)\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': model.state_dict(),\n 'best_acc1': best_acc1,\n 'optimizer' : optimizer.state_dict(),\n }, filename='linevalckpt-' + dict_id + '.tar')\n\ndef train(train_loader, model, criterion, optimizer, epoch, args):\n losses = utils.AverageMeter('Loss', ':.4e')\n top1 = utils.AverageMeter('Acc@1', ':6.2f')\n top5 = utils.AverageMeter('Acc@5', ':6.2f')\n progress = utils.ProgressMeter(\n len(train_loader),\n [losses, top1, top5],\n prefix=\"Epoch: [{}]\".format(epoch))\n\n \"\"\"\n Switch to eval mode:\n Under the protocol of linear classification on frozen features/models,\n it is not legitimate to change any part of the pre-trained model.\n BatchNorm in train mode may revise running mean/std (even if it receives\n no gradient), which are part of the model parameters too.\n \"\"\"\n model.eval()\n\n for i, (images, target) in enumerate(train_loader):\n images = images.cuda(non_blocking=True)\n target = target.cuda(non_blocking=True)\n\n # compute output\n output = model(images)\n loss = criterion(output, target)\n\n # measure accuracy and record loss\n acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))\n losses.update(loss.item(), images.size(0))\n top1.update(acc1[0], images.size(0))\n top5.update(acc5[0], images.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i + 1) % args.print_freq == 0:\n progress.display(i)\n\n return top1.avg, top5.avg, losses.avg\n\ndef validate(val_loader, model, criterion, args):\n losses = utils.AverageMeter('Loss', ':.4e')\n top1 = utils.AverageMeter('Acc@1', ':6.2f')\n top5 = utils.AverageMeter('Acc@5', ':6.2f')\n progress = utils.ProgressMeter(\n len(val_loader),\n [losses, top1, top5],\n prefix='Test: ')\n\n # switch to evaluate mode\n model.eval()\n\n with torch.no_grad():\n for i, (images, target) in enumerate(val_loader):\n images = images.cuda(non_blocking=True)\n target = target.cuda(non_blocking=True)\n\n # compute output\n output = model(images)\n loss = criterion(output, target)\n\n # measure accuracy and record loss\n acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))\n losses.update(loss.item(), images.size(0))\n top1.update(acc1[0], images.size(0))\n top5.update(acc5[0], images.size(0))\n\n if i % args.print_freq == 0:\n progress.display(i)\n\n # TODO: this should also be done with the ProgressMeter\n # is the above todo done??\n print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'\n .format(top1=top1, top5=top5))\n\n return top1.avg, top5.avg, losses.avg\n\ndef save_checkpoint(state, filename):\n torch.save(state, filename)\n\ndef adjust_learning_rate(optimizer, epoch, args):\n \"\"\"Decay the learning rate based on schedule\"\"\"\n lr = args.lr\n for milestone in args.schedule:\n lr *= 0.1 if epoch >= milestone else 1.\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\nif __name__ == '__main__':\n main()\n","sub_path":"lineval.py","file_name":"lineval.py","file_ext":"py","file_size_in_byte":9178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466328213","text":"from app.libraries.raspi_capture.gpio import GPIOHandler\nfrom picamera import PiCamera\nfrom picamera.array import PiRGBArray\nimport time\nimport os\n\n\nclass CaptCamera:\n\n def __init__(self, gpio_list):\n self.gpio_handler = GPIOHandler(gpio_list)\n self.camera = PiCamera()\n self.raw_capture = PiRGBArray(self.camera)\n\n def capture_to_array(self, warmup=1):\n self.gpio_handler.setON()\n self.camera.start_preview()\n time.sleep(warmup)\n self.camera.capture(self.raw_capture)\n self.camera.stop_preview()\n image = self.raw_capture.array\n\n self.gpio_handler.setOFF()\n time.sleep(warmup / 2)\n return image\n\n def capture_to_file(self, file, warmup=1):\n self.gpio_handler.setON()\n self.camera.start_preview()\n time.sleep(warmup)\n self.camera.capture(file)\n self.camera.stop_preview()\n self.gpio_handler.setOFF()\n time.sleep(warmup / 2)\n return None\n","sub_path":"capture.py","file_name":"capture.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"167092748","text":"#!/usr/bin/env python\n\nimport rospy\nget = rospy.get_param\n\n\n# import services defined in quad_control\n# Four SERVICES ARE BEING USED: SaveData, ServiceTrajectoryDesired, Mocap_Id, StartSim\n# SaveData is for saving data in txt file\n# TrajDes is for selecting trajectory\n# Mocap_Id for body detection from QUALISYS\n# StartSim stop simulator\nfrom quad_control.srv import LandmarksTrade\nfrom std_srvs.srv import Empty\nfrom quad_control.msg import camera_pose\n\n# to work with directories relative to ROS packages\nfrom rospkg import RosPack\n\nimport utilities.coverage_giorgio as cov\n\nimport numpy\n\n# For reading landmarks\nimport json\n\n\nclass TradeNode():\n\n\tdef __init__(self):\n\n\t\tself.frequency = 1e1\n\n\t\trospy.init_node('trade_node', anonymous=True)\n\n\t\tself.D_OPT = get(\"/D_OPT\",3.)\n\t\tself.name_agents = get(\"/name_agents\", '').rsplit(' ')\n\t\tself.n_ag = len(self.name_agents)\n\n\t\tself.trade_matrix = numpy.zeros([self.n_ag, self.n_ag])\n\n\t\tself.cams = {}\n\t\tself.lmks = {}\n\n\t\tself.index_agents = {}\n\t\ti = 0\n\t\tfor ns in self.name_agents:\n\t\t\tself.cams[ns] = cov.Camera()\n\t\t\tself.lmks[ns] = cov.Landmark_list([])\n\t\t\tself.index_agents[ns] = i\n\t\t\ti += 1\n\t\t\trospy.Subscriber(\"/\" + ns + \"/camera_pose\", camera_pose, lambda data,ns = ns: self.camera_pose_callback(data,ns))\n\n\t\trospy.Service('trade_request', LandmarksTrade, self.trade_request_handle)\n\n\t\t\t\n\n\n\tdef camera_pose_callback(self,data,ns):\n\t\tself.cams[ns].new_pose(data)\n\n\tdef trade_request_handle(self,data):\n\t\tns = data.name_agent\n\t\tself.lmks[ns] = cov.Landmark_list([])\n\t\tself.lmks[ns].from_lists(q = data.q, u = data.u)\n\t\tself.trade_matrix[self.index_agents[ns],self.index_agents[ns]] = 1\n\t\treturn {}\n \n\n\tdef run(self):\n\t\trate = rospy.Rate(self.frequency)\n\n\t\twhile not rospy.is_shutdown():\n\t\t\tfor ns in self.name_agents:\n\t\t\t\tag = self.index_agents[ns]\n\t\t\t\tif self.trade_matrix[ag,ag]:\n\t\t\t\t\tif all(self.trade_matrix[ag]):\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tpartner = ag\n\t\t\t\t\twhile (self.trade_matrix[ag,partner]):\n\t\t\t\t\t\tpartner += 1\n\t\t\t\t\t\tif partner >= self.n_ag:\n\t\t\t\t\t\t\tpartner = 0\n\t\t\t\t\tns_partner = 'to_change'\n\t\t\t\t\tfor ns_i in self.name_agents:\n\t\t\t\t\t\tif self.index_agents[ns_i] == partner:\n\t\t\t\t\t\t\tns_partner = ns_i\n\t\t\t\t\tif not(self.trade_matrix[partner,partner]):\n\t\t\t\t\t\tself.trade_matrix[ag,partner] = 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tresult,Q_ag,Q_partner = cov.trade_function(self.cams[ns],self.lmks[ns],self.cams[ns_partner],self.lmks[ns_partner],self.D_OPT)\n\t\t\t\t\t\tif result:\n\t\t\t\t\t\t\trospy.logerr(\"Succesful trade between %s and %s\" %(ns,ns_partner))\n\t\t\t\t\t\t\tself.trade_matrix[ag] = numpy.zeros(self.n_ag)\n\t\t\t\t\t\t\tself.trade_matrix[partner] = numpy.zeros(self.n_ag)\n\t\t\t\t\t\t\tq_ag, u_ag = Q_ag.to_lists()\n\t\t\t\t\t\t\tq_partner, u_partner = Q_partner.to_lists()\n\t\t\t\t\t\t\tservice_name = \"/\"+ ns+'/change_landmarks'\n\t\t\t\t\t\t\trospy.wait_for_service(service_name,2.0)\n\t\t\t\t\t\t\tchange_lmks_srv = rospy.ServiceProxy(service_name, LandmarksTrade,2.0)\n\t\t\t\t\t\t\tchange_lmks_srv(q = q_ag, u = u_ag, name_agent = ns)\n\t\t\t\t\t\t\tservice_name = \"/\"+ ns_partner + '/change_landmarks'\n\t\t\t\t\t\t\trospy.wait_for_service(service_name,2.0)\n\t\t\t\t\t\t\tchange_lmks_srv = rospy.ServiceProxy(service_name, LandmarksTrade,2.0)\n\t\t\t\t\t\t\tchange_lmks_srv(q = q_partner, u = u_partner, name_agent = ns_partner)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.trade_matrix[ag,partner] = 1\n\t\t\t\t\t\t\tself.trade_matrix[partner,ag] = 1\n\n\t\t\tif (self.trade_matrix.all().all()):\n\t\t\t\trospy.logerr('Trade completed!')\n\t\t\trate.sleep()\n\n\n\nif (get(\"/trade_allowed\",False)):\n\tATradeNode = TradeNode()\n\ttry:\n\t\tATradeNode.run()\n\texcept rospy.ROSInterruptException:\n\t\tpass","sub_path":"quad_control/scripts/trade_node.py","file_name":"trade_node.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"8113313","text":"# coding: utf-8\n\n\"\"\"\n Payment Gateway API Specification.\n\n The documentation here is designed to provide all of the technical guidance required to consume and integrate with our APIs for payment processing. To learn more about our APIs please visit https://docs.firstdata.com/org/gateway. # noqa: E501\n\n The version of the OpenAPI document: 21.5.0.20211029.001\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass DecryptedGooglePay(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'account_number': 'str',\n 'expiration': 'str',\n 'cardholder_name': 'str',\n 'brand': 'str',\n 'cryptogram': 'str',\n 'eci_indicator': 'str',\n 'stored_credentials': 'StoredCredential'\n }\n\n attribute_map = {\n 'account_number': 'accountNumber',\n 'expiration': 'expiration',\n 'cardholder_name': 'cardholderName',\n 'brand': 'brand',\n 'cryptogram': 'cryptogram',\n 'eci_indicator': 'eciIndicator',\n 'stored_credentials': 'storedCredentials'\n }\n\n def __init__(self, account_number=None, expiration=None, cardholder_name=None, brand=None, cryptogram=None, eci_indicator=None, stored_credentials=None): # noqa: E501\n \"\"\"DecryptedGooglePay - a model defined in OpenAPI\"\"\" # noqa: E501\n\n self._account_number = None\n self._expiration = None\n self._cardholder_name = None\n self._brand = None\n self._cryptogram = None\n self._eci_indicator = None\n self._stored_credentials = None\n self.discriminator = None\n\n self.account_number = account_number\n self.expiration = expiration\n if cardholder_name is not None:\n self.cardholder_name = cardholder_name\n if brand is not None:\n self.brand = brand\n if cryptogram is not None:\n self.cryptogram = cryptogram\n if eci_indicator is not None:\n self.eci_indicator = eci_indicator\n if stored_credentials is not None:\n self.stored_credentials = stored_credentials\n\n @property\n def account_number(self):\n \"\"\"Gets the account_number of this DecryptedGooglePay. # noqa: E501\n\n Payment card number. # noqa: E501\n\n :return: The account_number of this DecryptedGooglePay. # noqa: E501\n :rtype: str\n \"\"\"\n return self._account_number\n\n @account_number.setter\n def account_number(self, account_number):\n \"\"\"Sets the account_number of this DecryptedGooglePay.\n\n Payment card number. # noqa: E501\n\n :param account_number: The account_number of this DecryptedGooglePay. # noqa: E501\n :type: str\n \"\"\"\n if account_number is None:\n raise ValueError(\"Invalid value for `account_number`, must not be `None`\") # noqa: E501\n if account_number is not None and not re.search(r'[0-9]{13,19}', account_number): # noqa: E501\n raise ValueError(r\"Invalid value for `account_number`, must be a follow pattern or equal to `/[0-9]{13,19}/`\") # noqa: E501\n\n self._account_number = account_number\n\n @property\n def expiration(self):\n \"\"\"Gets the expiration of this DecryptedGooglePay. # noqa: E501\n\n Card expiration date in MMYYYY format. # noqa: E501\n\n :return: The expiration of this DecryptedGooglePay. # noqa: E501\n :rtype: str\n \"\"\"\n return self._expiration\n\n @expiration.setter\n def expiration(self, expiration):\n \"\"\"Sets the expiration of this DecryptedGooglePay.\n\n Card expiration date in MMYYYY format. # noqa: E501\n\n :param expiration: The expiration of this DecryptedGooglePay. # noqa: E501\n :type: str\n \"\"\"\n if expiration is None:\n raise ValueError(\"Invalid value for `expiration`, must not be `None`\") # noqa: E501\n if expiration is not None and not re.search(r'[0-9]{6}', expiration): # noqa: E501\n raise ValueError(r\"Invalid value for `expiration`, must be a follow pattern or equal to `/[0-9]{6}/`\") # noqa: E501\n\n self._expiration = expiration\n\n @property\n def cardholder_name(self):\n \"\"\"Gets the cardholder_name of this DecryptedGooglePay. # noqa: E501\n\n Name of the cardholder. # noqa: E501\n\n :return: The cardholder_name of this DecryptedGooglePay. # noqa: E501\n :rtype: str\n \"\"\"\n return self._cardholder_name\n\n @cardholder_name.setter\n def cardholder_name(self, cardholder_name):\n \"\"\"Sets the cardholder_name of this DecryptedGooglePay.\n\n Name of the cardholder. # noqa: E501\n\n :param cardholder_name: The cardholder_name of this DecryptedGooglePay. # noqa: E501\n :type: str\n \"\"\"\n if cardholder_name is not None and len(cardholder_name) > 96:\n raise ValueError(\"Invalid value for `cardholder_name`, length must be less than or equal to `96`\") # noqa: E501\n if cardholder_name is not None and not re.search(r'^(?!\\s*$).+', cardholder_name): # noqa: E501\n raise ValueError(r\"Invalid value for `cardholder_name`, must be a follow pattern or equal to `/^(?!\\s*$).+/`\") # noqa: E501\n\n self._cardholder_name = cardholder_name\n\n @property\n def brand(self):\n \"\"\"Gets the brand of this DecryptedGooglePay. # noqa: E501\n\n Card brand. # noqa: E501\n\n :return: The brand of this DecryptedGooglePay. # noqa: E501\n :rtype: str\n \"\"\"\n return self._brand\n\n @brand.setter\n def brand(self, brand):\n \"\"\"Sets the brand of this DecryptedGooglePay.\n\n Card brand. # noqa: E501\n\n :param brand: The brand of this DecryptedGooglePay. # noqa: E501\n :type: str\n \"\"\"\n if brand is not None and not re.search(r'^(?!\\s*$).+', brand): # noqa: E501\n raise ValueError(r\"Invalid value for `brand`, must be a follow pattern or equal to `/^(?!\\s*$).+/`\") # noqa: E501\n\n self._brand = brand\n\n @property\n def cryptogram(self):\n \"\"\"Gets the cryptogram of this DecryptedGooglePay. # noqa: E501\n\n The wallet cryptogram from the decrypted data. # noqa: E501\n\n :return: The cryptogram of this DecryptedGooglePay. # noqa: E501\n :rtype: str\n \"\"\"\n return self._cryptogram\n\n @cryptogram.setter\n def cryptogram(self, cryptogram):\n \"\"\"Sets the cryptogram of this DecryptedGooglePay.\n\n The wallet cryptogram from the decrypted data. # noqa: E501\n\n :param cryptogram: The cryptogram of this DecryptedGooglePay. # noqa: E501\n :type: str\n \"\"\"\n if cryptogram is not None and not re.search(r'^(?!\\s*$).+', cryptogram): # noqa: E501\n raise ValueError(r\"Invalid value for `cryptogram`, must be a follow pattern or equal to `/^(?!\\s*$).+/`\") # noqa: E501\n\n self._cryptogram = cryptogram\n\n @property\n def eci_indicator(self):\n \"\"\"Gets the eci_indicator of this DecryptedGooglePay. # noqa: E501\n\n The ECI indicator from the decrypted data. # noqa: E501\n\n :return: The eci_indicator of this DecryptedGooglePay. # noqa: E501\n :rtype: str\n \"\"\"\n return self._eci_indicator\n\n @eci_indicator.setter\n def eci_indicator(self, eci_indicator):\n \"\"\"Sets the eci_indicator of this DecryptedGooglePay.\n\n The ECI indicator from the decrypted data. # noqa: E501\n\n :param eci_indicator: The eci_indicator of this DecryptedGooglePay. # noqa: E501\n :type: str\n \"\"\"\n if eci_indicator is not None and not re.search(r'[0-9]{2}', eci_indicator): # noqa: E501\n raise ValueError(r\"Invalid value for `eci_indicator`, must be a follow pattern or equal to `/[0-9]{2}/`\") # noqa: E501\n\n self._eci_indicator = eci_indicator\n\n @property\n def stored_credentials(self):\n \"\"\"Gets the stored_credentials of this DecryptedGooglePay. # noqa: E501\n\n\n :return: The stored_credentials of this DecryptedGooglePay. # noqa: E501\n :rtype: StoredCredential\n \"\"\"\n return self._stored_credentials\n\n @stored_credentials.setter\n def stored_credentials(self, stored_credentials):\n \"\"\"Sets the stored_credentials of this DecryptedGooglePay.\n\n\n :param stored_credentials: The stored_credentials of this DecryptedGooglePay. # noqa: E501\n :type: StoredCredential\n \"\"\"\n\n self._stored_credentials = stored_credentials\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, DecryptedGooglePay):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"openapi_client/models/decrypted_google_pay.py","file_name":"decrypted_google_pay.py","file_ext":"py","file_size_in_byte":10285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"290518979","text":"# -*- coding: utf-8 -*-\r\n'''\r\n設計変数: 任意\r\n目的関数: 1次元配列\r\n解集団形状: 1次元配列, 2重配列(島モデル)\r\n\r\n各個体にランク(自然数), 混雑度(実数)が割り当てられる\r\n集団評価値(参考): ハイパーボリューム\r\n\r\n解集団 =~ [個体]\r\n\r\n選択\r\n[個体] => [個体]\r\n\r\n個体が生成されるのは次の3通りのいずれか\r\n初期化: [] => 個体\r\n交叉: [個体] => 個体 / [個体] => [個体]\r\n突然変異: 個体 => 個体\r\n'''\r\n\r\nimport argparse\r\nimport os\r\nimport pickle\r\nimport random\r\nimport shutil\r\nfrom itertools import islice\r\nfrom operator import attrgetter, itemgetter\r\n\r\nimport numpy as np\r\n\r\nfrom ..base import Individual\r\nfrom ..base import Population\r\nfrom ..base.population import Normalization\r\nfrom ..base import NondominatedSortIterator\r\nfrom ..base import CrowdingDistanceCalculator\r\n# from ..operations import SelectionIterator\r\n# from ..operations import MatingIterator\r\nfrom .iterators import SelectionIterator\r\nfrom .iterators import MatingIterator\r\n\r\n# デフォルト用\r\nfrom ..operations import UniformInitializer\r\nfrom ..operations import RandomSelection\r\nfrom ..operations import RouletteSelection\r\nfrom ..operations import TournamentSelection\r\nfrom ..operations import TournamentSelectionStrict\r\nfrom ..operations import TournamentSelectionDCD\r\nfrom ..operations import BlendCrossover\r\nfrom ..operations import SimulatedBinaryCrossover\r\nfrom ..operations import PolynomialMutation\r\n\r\n# default_selection = TournamentSelection(ksize=2)s\r\ndefault_selection = TournamentSelectionStrict(ksize=2)\r\n# default_selection = TournamentSelectionDCD()\r\n# default_crossover = BlendCrossover(alpha=0.5)\r\ndefault_crossover = SimulatedBinaryCrossover(rate=0.9, eta=20)\r\ndefault_mutation = PolynomialMutation(rate=0.05, eta=20)\r\n\r\n\r\n################################################################################\r\n# スカラー化関数\r\n################################################################################\r\n\r\ndef scalar_weighted_sum(indiv, weight, ref_point):\r\n return -np.sum(weight * np.abs(indiv.wvalue - ref_point))\r\n\r\ndef scalar_chebyshev(indiv, weight, ref_point):\r\n return -np.max(weight * np.abs(indiv.wvalue - ref_point))\r\n\r\ndef scalar_boundaryintersection(indiv, weight, ref_point):\r\n ''' norm(weight) == 1\r\n '''\r\n nweight = weight / np.linalg.norm(weight)\r\n\r\n bi_theta = 5.0\r\n d1 = np.abs(np.dot((indiv.wvalue - ref_point), nweight))\r\n d2 = np.linalg.norm(indiv.wvalue - (ref_point - d1 * nweight))\r\n return -(d1 + bi_theta * d2)\r\n\r\n\r\n################################################################################\r\n\r\nclass MOEAD(object):\r\n ''' MOEADモデル(2D)\r\n '''\r\n name = 'MOEA/D'\r\n\r\n def __init__(self, popsize=None, problem=None, pool=None, ksize=3,\r\n scalar=scalar_chebyshev,\r\n selection=default_selection,\r\n crossover=default_crossover,\r\n mutation=default_mutation,\r\n normalization=False,\r\n n_obj=2):\r\n self.popsize = popsize\r\n self.ksize = ksize\r\n self.problem = problem\r\n\r\n self.nobj = int(n_obj)\r\n print(\"set nobj = \",self.nobj)\r\n self.scalar = scalar\r\n self.normalization = normalization\r\n\r\n self.n_parents = 2 # 1回の交叉の親個体の数\r\n self.n_cycle = 2 # 選択候補をリセットする周期(n_parentsの倍数にすること)\r\n self.alternation = 'new' # 世代交代方法\r\n\r\n self.select_it = SelectionIterator(selection=selection, pool=pool)\r\n self.mate_it = MatingIterator(crossover=crossover,\r\n mutation=mutation,\r\n pool=pool)\r\n self.sort_it = NondominatedSortIterator\r\n self.share_fn = CrowdingDistanceCalculator(key=attrgetter('data')) # Fitness -> Individual\r\n\r\n if not self.popsize:\r\n self.init_weight()\r\n # else:\r\n # self.ref_point = np.full(self.nobj, 'inf', dtype=np.float64)\r\n\r\n def __call__(self, population):\r\n if not self.popsize:\r\n self.popsize = len(population)\r\n self.init_weight()\r\n population.sort(key=attrgetter('data'))\r\n\r\n if self.normalization:\r\n try:\r\n population = self.normalizing(population)\r\n except:\r\n print(\"Normalizing init...\")\r\n self.normalizing = Normalization(population)\r\n population = self.normalizing(population)\r\n\r\n next_population = self.advance(population)\r\n for fit in next_population:\r\n fit_value = self.scalar(fit.data, self.weight, self.ref_point)\r\n fit.set_fitness((fit_value, ),1)\r\n\r\n return self.alternate(population, next_population)\r\n\r\n def init_weight(self, popsize=None, ksize=None):\r\n ''' 重みベクトルと近傍テーブルの初期化\r\n '''\r\n if popsize:\r\n self.popsize = popsize\r\n if ksize:\r\n self.ksize = ksize\r\n if not self.popsize or not self.ksize:\r\n return\r\n\r\n self.weight = self.weight_generator(nobj=self.nobj, divisions=self.popsize)\r\n self.popsize = self.weight.shape[0]\r\n print(\"popsize = \", len(self.weight))\r\n # self.weight = np.array([[i+1, self.popsize-i]\r\n # for i in range(self.popsize)])\r\n\r\n def get_neighbor(index):\r\n imin = min(max(index-(self.ksize-1)//2, 0),\r\n self.popsize-self.ksize)\r\n return list(range(imin, imin+self.ksize))\r\n\r\n def get_neighbor2(index):\r\n norms = np.zeros((self.weight.shape[0], self.weight.shape[1]+2))\r\n self.neighbers = np.zeros((self.weight.shape[0], self.ksize))\r\n w1 = self.weight[index]\r\n\r\n for i, w2 in enumerate(self.weight):\r\n norms[i,0] = np.linalg.norm(w1 - w2)\r\n norms[i,1] = i\r\n norms[i,2:] = w2\r\n \r\n norms_sort = norms[norms[:,0].argsort(),:] #normの大きさでnormsをソート\r\n # print(norms)\r\n neighber_index = np.zeros((self.ksize), dtype=\"int\")\r\n for i in range(self.ksize):\r\n neighber_index[i] = norms_sort[i,1]\r\n \r\n # print(neighber_index)\r\n return neighber_index\r\n\r\n\r\n self.table = np.array([get_neighbor2(i) for i in range(self.popsize)])\r\n # print(self.table) #for debug\r\n # print(self.weight) #for debug\r\n self.ref_point = np.full(self.nobj, 'inf', dtype=np.float64)\r\n\r\n def update_reference(self, indiv):\r\n try:\r\n self.ref_point = np.min([self.ref_point, np.array(indiv.wvalue)],axis=0)\r\n # print(\"update ref point = \", self.ref_point)\r\n except:\r\n print(self.ref_point.dtype)\r\n print(self.ref_point)\r\n print(np.array(indiv.wvalue).dtype)\r\n print(np.array(indiv.wvalue))\r\n print([self.ref_point, np.array(indiv.wvalue)])\r\n raise\r\n\r\n def init_population(self, creator, popsize=None, popdata=None):\r\n ''' 初期集団生成\r\n '''\r\n if popsize:\r\n self.popsize = popsize\r\n self.init_weight()\r\n\r\n if not popdata:\r\n population = Population(capacity=self.popsize, origin=self)\r\n else:\r\n population = Population(capacity=self.popsize, data=popdata)\r\n\r\n i = 0\r\n while not population.filled():\r\n i+=1\r\n print(f\"indiv{i:>3d}\", end=\"\\r\")\r\n indiv = creator()\r\n fitness = indiv.evaluate(self.problem)\r\n population.append(fitness)\r\n\r\n if self.normalization:\r\n self.normalizing = Normalization(population)\r\n population = self.normalizing(population)\r\n\r\n # self.calc_fitness(population)\r\n # self.weight = np.array([[i ,w] for i,w in zip(range(self.popsize), population[0].data.wvalue)])\r\n # self.weight = np.array([population[i].data.wvalue for i in (range(self.popsize))])\r\n\r\n self.ref_point = np.min([fit.data.wvalue for fit in population], axis=0)\r\n # print(self.normalizing.max_obj_val)\r\n print(\"ref point \",self.ref_point)\r\n return population\r\n\r\n def advance(self, population):\r\n ''' 選択→交叉→突然変異→評価→適応度計算→世代交代\r\n '''\r\n next_population = Population(capacity=self.popsize, origin=self)\r\n # select_it = self.select_it(self.population, reset_cycle=self.n_cycle)\r\n # select_it = iter(select_it) # Fixed\r\n\r\n for i in range(self.popsize):\r\n print(f\"indiv{i:>3d}\", end=\"\\r\")\r\n child_fit = self.get_offspring(i, population, self.table[i],\r\n self.weight[i])\r\n next_population.append(child_fit)\r\n\r\n return next_population\r\n\r\n def alternate(self, population, next_population):\r\n return next_population\r\n\r\n def get_offspring(self, index, population, table, weight):\r\n ''' 各個体の集団内における適応度を計算する\r\n 1. スカラー化関数\r\n 交叉,突然変異を行い最良個体を1つ返す\r\n * 2018.11.21 新しい解が古い解より良い場合に置き換える処理に変更\r\n '''\r\n \r\n subpopulation = [population[i] for i in table]\r\n\r\n for i, fit in enumerate(subpopulation):\r\n fit_value = self.scalar(fit.data, weight, self.ref_point)\r\n fit.set_fitness((fit_value,), 1)\r\n\r\n select_it = self.select_it(subpopulation, reset_cycle=self.n_cycle)\r\n paretns = list(islice(select_it, self.n_parents))\r\n\r\n # offspring = []\r\n\r\n child = random.choice(list(self.mate_it(paretns)))\r\n # for child in self.mate_it(paretns):\r\n child_fit = child.evaluate(self.problem)\r\n \r\n if self.normalization:\r\n child_fit = self.normalizing.normalize_fit(child_fit) #normalize\r\n \r\n self.update_reference(child)\r\n fit_value = self.scalar(child_fit.data, weight, self.ref_point)\r\n child_fit.set_fitness((fit_value,), 1)\r\n # offspring.append(child_fit)\r\n\r\n if self.alternation == 'new':\r\n return max(population[index], child_fit)\r\n elif self.alternation == 'all':\r\n return max(*subpopulation, child_fit)\r\n else:\r\n print('Unexpected alternation type:', self.alternation)\r\n raise Exception('UnexpectedAlternation')\r\n\r\n def calc_rank(self, population, n=None):\r\n ''' 各個体の集団内におけるランクを計算して設定する\r\n 外部から呼ぶ\r\n '''\r\n for i, front in enumerate(self.sort_it(population)):\r\n rank = i + 1\r\n for fit in front:\r\n fit.rank = rank\r\n return population\r\n\r\n ################################################################################\r\n # weight vector \r\n ################################################################################\r\n def weight_generator(self, nobj=None, divisions=None, coeff=1):\r\n '''\r\n 任意の次元を持つ重みベクトルを作成\r\n '''\r\n import copy\r\n\r\n if not nobj:\r\n nobj = self.nobj\r\n if not divisions:\r\n divisions = self.popsize\r\n if coeff:\r\n divisions = divisions*coeff\r\n \r\n # if nobj == 2:\r\n # weights = [[1,0],[0,1]]\r\n # weights.extend([(i/(divisions-1.0), 1.0-i/(divisions-1.0)) \r\n # for i in range(1, divisions-1)])\r\n # else:\r\n weights = []\r\n # ele_candidate = np.array(list(range(popsize+1)))/popsize\r\n\r\n def weight_recursive(weights, weight, left, total, idx=0):\r\n\r\n if idx == nobj-1:\r\n weight[idx] = float(left)/float(total)\r\n weights.append(copy.copy(weight))\r\n # return weights\r\n else:\r\n for i in range(left+1):\r\n weight[idx] = float(i)/float(total)\r\n weight_recursive(weights, weight, left-i, total, idx+1)\r\n\r\n weight_recursive(weights, [0.0]*nobj, divisions, divisions)\r\n\r\n weights = np.array(weights)\r\n # np.savetxt(\"temp.txt\", weights, fmt='%.2f', delimiter='\\t')\r\n return weights\r\n \r\n\r\n################################################################################\r\n\r\ndef __test__():\r\n pass\r\n\r\n\r\ndef get_args():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--test', '-t', action='store_true',\r\n help='Run as test mode')\r\n args = parser.parse_args()\r\n return args\r\n\r\n\r\ndef main():\r\n args = get_args()\r\n\r\n if args.test:\r\n __test__()\r\n return\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"eclib/optimizers/moead.py","file_name":"moead.py","file_ext":"py","file_size_in_byte":13059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"263944069","text":"from guillotina.annotations import AnnotationData\nfrom guillotina.content import create_content_in_container\nfrom guillotina.fields.annotation import BucketDictValue\nfrom guillotina.interfaces import IAnnotations\nfrom guillotina.tests.utils import login\nfrom guillotina.transactions import transaction\nfrom guillotina.utils import get_database\n\nimport os\nimport pytest\n\n\npytest.mark.skipif(os.environ.get(\"DATABASE\") == \"cockroachdb\", reason=\"Flaky cockroachdb test\")\n\n\nasync def test_create_annotation(db, guillotina_main):\n db = await get_database(\"db\")\n login()\n\n async with transaction(db=db):\n container = await create_content_in_container(db, \"Container\", \"container\", title=\"Container\")\n ob = await create_content_in_container(container, \"Item\", \"foobar\")\n\n annotations = IAnnotations(ob)\n data = AnnotationData()\n data[\"foo\"] = \"bar\"\n await annotations.async_set(\"foobar\", data)\n\n async with transaction(db=db):\n container = await db.async_get(\"container\")\n ob = await container.async_get(\"foobar\")\n annotations = IAnnotations(ob)\n assert \"foobar\" in (await annotations.async_keys())\n await annotations.async_del(\"foobar\")\n\n async with transaction(db=db):\n container = await db.async_get(\"container\")\n ob = await container.async_get(\"foobar\")\n annotations = IAnnotations(ob)\n assert \"foobar\" not in (await annotations.async_keys())\n await container.async_del(\"foobar\")\n await db.async_del(\"container\")\n\n\nasync def test_bucket_dict_value(db, guillotina_main):\n db = await get_database(\"db\")\n login()\n bucket = BucketDictValue(bucket_len=10)\n\n async with transaction(db=db):\n container = await create_content_in_container(db, \"Container\", \"container\", title=\"Container\")\n ob = await create_content_in_container(container, \"Item\", \"foobar\")\n for index in range(50):\n await bucket.assign(ob, str(index), index)\n\n assert len(bucket) == 50\n assert await bucket.get(ob, \"1\") == 1\n\n async with transaction(db=db):\n container = await db.async_get(\"container\")\n ob = await container.async_get(\"foobar\")\n await bucket.clear(ob)\n assert len(bucket) == 0\n assert await bucket.get(ob, \"1\") is None\n\n async with transaction(db=db):\n container = await db.async_get(\"container\")\n ob = await container.async_get(\"foobar\")\n for index in range(50, 100):\n await bucket.assign(ob, str(index), index)\n\n assert len(bucket) == 50\n assert await bucket.get(ob, \"50\") == 50\n","sub_path":"guillotina/tests/test_annotations.py","file_name":"test_annotations.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"300148351","text":"def int_lst_input():\n return [int(val) for val in input().split(' ')]\n\ndef int_input():\n return int(input())\n\ndef print_lst(lst):\n print(' '.join([str(val) for val in lst]))\n\ndef solve():\n t = int_input()\n\n for i in range(t):\n k = int_input()\n s = list(input())\n\n a = 0\n\n while True:\n local_a = 0\n for j in range(1, len(s)):\n if s[j-1] == 'A' and s[j] == 'P':\n local_a += 1\n s[j] = 'a'\n\n if local_a == 0:\n break\n\n a += 1\n for j in range(len(s)):\n if s[j] == 'a':\n s[j] = 'A'\n\n print(a)\n\n\nif __name__ == '__main__':\n solve()\n","sub_path":"1287A_angry_students.py","file_name":"1287A_angry_students.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"135651063","text":"\nimport requests\nimport json\nfrom pybuses import PyBuses, MongoDB, Stop, StopGetter, StopGetterUnavailable, StopNotExist\n\ndb = MongoDB(host=\"192.168.0.99\", db_name=\"vigobus\", stops_collection_name=\"stops\")\n\n# # GETTERS CON API VITRASA\n\nAPI_URL = \"192.168.0.99:55022\"\n# API_URL = \"localhost:5000\"\n\n\ndef getter_vitrasa(stopid) -> Stop:\n r = requests.get(f\"http://{API_URL}/stop/{stopid}\").text\n j = json.loads(r)\n if j[\"error\"]:\n raise StopGetterUnavailable()\n if not j[\"exists\"]:\n raise StopNotExist()\n return Stop(stopid=stopid, name=j[\"name\"], lat=j[\"lat\"], lon=j[\"lon\"])\n\n\ngetter_vitrasa: StopGetter = getter_vitrasa\n# getter_vitrasa.online = True # no hace falta declararlo aquí, se declara al llamar a add_stop_getter\n# aunque se podría probar para cuando se pruebe a pasar getter en constructor\n\n# # TESTS\n\n\ndef test_find_all_stops_threaded():\n pybuses.find_all_stops(start=1, end=1000, threads=10)\n\n\ndef test_find_all_stops_nonthreaded():\n pybuses.find_all_stops(start=5800, end=5810, threads=0)\n\n\nif __name__ == \"__main__\":\n pybuses = PyBuses()\n pybuses.add_stop_getter(getter_vitrasa, online=True)\n pybuses.add_stop_getter(db.find_stop)\n pybuses.add_stop_setter(db.save_stop)\n # pybuses.add_stop_deleter(db.delete_stop)\n\n test_find_all_stops_threaded()\n # test_find_all_stops_nonthreaded()\n","sub_path":"misctests.py","file_name":"misctests.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"298428735","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom requests import session\nimport requests\nimport os\nimport json\nfrom bs4 import BeautifulSoup\nfrom time import time, gmtime, strftime\nimport json\nimport time\n\ndata_file = open(os.path.expanduser(\"~\") + '/credentials.json')\ncredential_data = json.load(data_file)\n\npayload = {\n 'scriptData': 'KGRwMAou',\n 'script': '/status/portal.py/displayStatus',\n 'password': credential_data['rz'][0]['password'],\n 'optData': 'KGRwMAou',\n 'ndsname': credential_data['rz'][0]['nds'],\n 'language': 'Deutsch',\n 'action': 'Anmelden'\n}\n\noutfile = open(os.path.expanduser(\"~\") + '/log-traffic.csv', 'a')\n\nwhile True:\n try:\n r = requests.post(\n 'https://www-wohnheim.uni-regensburg.de/utils/login.py/checkAuthentication', data=payload)\n\n soup = BeautifulSoup(r.text)\n\n title = soup.findAll('title')[0].get_text()\n\n login_page = title.find('Login') > 0\n\n if(login_page):\n print('login failed')\n print('change password?')\n break\n\n rzdatatable = soup.find(\"table\", {\"id\": \"rzdatatable\"})\n\n data = rzdatatable.findAll('tr')[1]\n\n wohnheim = data.findAll('td')[0].get_text()\n zimmer = data.findAll('td')[1].get_text()\n status = data.findAll('td')[2].span.get_text()\n empfangen = data.findAll('td')[3].get_text()\n gesendet = data.findAll('td')[4].get_text()\n summe = data.findAll('td')[5].get_text()\n limit = data.findAll('td')[6].get_text()\n\n # print(wohnheim + \"(\" + zimmer + \"), status: \" + status)\n # print(\"Volumen: \" + str(summe) + \"mb von \" + str(limit) + \"mb (\" + str(round(100*float(summe)/float(limit),2)) + \"%), davon \" + gesendet + \"mb gesendet und \" + empfangen + \"mb empfangen.\")\n\n time_info = strftime(\"%Y-%m-%d;%H:%M:%S\", gmtime())\n line = time_info + \";\" + str(summe) + \";\"\n\n outfile.write(line + \"\\n\")\n print(line)\n time.sleep(300)\n except requests.ConnectionError:\n print('No Connection')\n break\noutfile.close()\n","sub_path":"python/volume_rz.py","file_name":"volume_rz.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"422820490","text":"version = 'r561'\npi = 3.14159265358979323846264338327950288419716939937510\neu = 2.71828182845904523536028747135266249775724709369995\n# p means precision\n\n\ndef mconst(n):\n # Get the value of a constant\n if n == 'c':\n # Speed of light in vacuum, in m s\n r = 299792458\n elif n == 'atm':\n # Atmosphere in Pa\n r = 101325\n elif n == 'e':\n # Euler's number\n r = 2.71828182845904523536028747135266249775724709369995\n elif n == 'pi':\n # Pi\n r = 3.14159265358979323846264338327950288419716939937510\n elif n == 'mp':\n # Mass of Proton in kg\n r = 1.67262189821 * 10 ** -27\n elif n == 'me':\n # Mass of Electron in kg\n r = 9.1093835611 * 10 ** -31\n elif n == 'mn':\n # Mass of Neutron in kg\n r = 1.67492747121 * 10 ** -27\n elif n == 'mu':\n # Atomic Mass Constant in kg\n r = 1.66053904020 * 10 ** -27\n elif n == 'μ0':\n # Magnetic Constant / Vacuum Permeability in H m\n r = 4 * 3.14159265358979323846264338327950288419716939937510 * 10 ** -7\n elif n == 'ε0':\n # Electric Constant / Vacuum Permittivity in F m\n r = 1 / ((4 * 3.14159265358979323846264338327950288419716939937510 * 10 ** -7) * 299792458 ** 2)\n elif n == 'gn':\n # Acceleration due to Gravity in m s^(-2)\n r = 9.80665\n elif n == 'G':\n # Newtonian Constant of Gravitation / Gravitational Constant in m^(3) kg^(-1) s^(-2)\n r = 6.6740831 * 10 ** -11\n elif n == 'h':\n # Planck Constant in J s\n r = 6.62607004081 * 10 ** -34\n elif n == 'h-':\n # Reduced Planck Constant / Dirac Constant in J s\n r = (6.62607004081 * 10 ** -34) / (2 * 3.14159265358979323846264338327950288419716939937510)\n elif n == 'Z0':\n # Characteristic Impedance of Vacuum / Impedance of free space\n r = (4 * 3.14159265358979323846264338327950288419716939937510 * 10 ** -7) * 299792458\n else:\n r = ''\n return r\n\n\ndef mabs(n):\n # absolute value of n\n if n < 0:\n return n * -1\n else:\n return n\n\n\ndef magm(a, b):\n # arithmetic-geometric mean of a and b\n while a - b:\n b = sqrt(a * b)\n a = (1 / 2) * (a + b ** 2 / a)\n return a\n\n\ndef mari(x, y):\n # armstrong number within an interval\n c = []\n for d in range(x, y + 1):\n e = len(str(d))\n f = 0\n g = d\n while g > 0:\n h = g % 10\n f += h ** e\n g //= 10\n if d == f:\n c.append(d)\n return c\n\n\ndef marm(n):\n # test if n is an armstrong number\n a = 0\n b = n\n while b > 0:\n d = b % 10\n a += d ** 3\n b //= 10\n if n == a:\n return True\n else:\n return False\n\n\ndef mexp(n):\n # euler number to the power n\n return eu ** n\n\n\ndef mfac(n):\n # factorial of n\n if n < 1:\n return 1\n else:\n return n * mfac(n - 1)\n\n\ndef mfat(n):\n # find all factors of n\n return [i for i in range(1, n + 1) if n % i == 0]\n\n\ndef mfib(n):\n # fibonacci sequence of n th term\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return mfib(n-1) + mfib(n-2)\n\n\ndef mfii(n):\n # fibonacci sequence up to n term\n b = []\n c = 0\n d = 0\n f = 1\n if n <= 0:\n return None\n elif n == 1:\n return 1\n else:\n while c < n:\n b.append(d)\n g = d + f\n d = f\n f = g\n c += 1\n return b\n\n\ndef mhcf(x, y):\n # highest common factor between x and y\n r = 0\n if x > y:\n n = y\n else:\n n = x\n for i in range(1, int(n + 1)):\n if (x % i == 0) and (y % i == 0):\n r = i\n return r\n\n\ndef mlcm(a, b):\n # least common multiple between x and y\n if a > b:\n c = a\n else:\n c = b\n while True:\n if (c % a == 0) and (c % b == 0):\n d = c\n break\n c += 1\n return d\n\n\ndef mlogc(n, b=10, p=10):\n #common log n in base 10 with precision p\n r = 0\n i = 1\n j = 0\n while j <= p:\n while n >= b:\n n = n / b\n r = r + i\n n = n ** b\n i = i / b\n j = j + 1\n return r\n\n\ndef mlog(n, b=10, p=10):\n # log n in base b with precision p\n return float((\"{0:.\" + str(p) + \"f}\").format(mlogc(n) / mlogc(b)))\n\n\ndef mmaa(a, b):\n # matrix addition\n return [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]\n\n\ndef mmam(a, b):\n # matrix multiplication\n return [[sum(c * d for c, d in zip(a_row, b_col)) for b_col in zip(*b)] for a_row in a]\n\n\ndef mmat(a):\n # matrix transposition\n return [[a[j][i] for j in range(len(a))] for i in range(len(a[0]))]\n\n\ndef mncr(n, r):\n # nCr combination\n return mfac(n) / (mfac(r) * mfac(n - r))\n\n\ndef mnpr(n, r):\n # nPr permutation\n return mfac(n) / mfac(n - r)\n\n\ndef mpri(a, b):\n # get all prime number within an interval\n c = []\n for i in range(a, b + 1):\n # prime numbers are greater than 1\n if i > 1:\n for j in range(2, i):\n if (i % j) == 0:\n break\n else:\n c.append(i)\n return c\n\n\ndef mprm(n):\n # test if n a prime number\n if n > 1:\n for i in range(2, n):\n if (n % i) == 0:\n return False\n else:\n return True\n\n\ndef mque(a, b, c):\n # quadratic equation with no complex number support\n d = (b ** 2) - (4 * a * c)\n e = (-b - sqrt(d)) / (2 * a)\n f = (-b + sqrt(d)) / (2 * a)\n return [e, f]\n\n\ndef msum(n):\n # sum of natural number up to n th term\n return n * (n + 1) / 2\n\n\ndef sqrt(n, p=20):\n # square root of number n\n r = n / 2\n for i in range(p):\n r = (n / r + r) / 2\n return r\n\n\n# trigonometry\ndef msin(n, p=20):\n # sine of an acute angle\n n = mabs(n) / 180 * pi\n r = n - n ** 3 / mfac(3)\n for i in range(int(p)):\n if i > 4:\n if i % 2 == 1:\n if i % 4 == 1:\n r = r + n ** i / mfac(i)\n elif i % 4 == 3:\n r = r - n ** i / mfac(i)\n return r\n\n\ndef mcos(n, p=20):\n # cosine of an acute angle\n n = mabs(n) / 180 * pi\n r = 1 - n ** 2 / mfac(2)\n for i in range(int(p)):\n if i > 3:\n if i % 2 == 0:\n if i % 4 == 0:\n r = r + n ** i / mfac(i)\n elif i % 4 == 2:\n r = r - n ** i / mfac(i)\n return r\n\n\ndef mtan(n, p=20):\n # tangent of an acute angle\n return msin(n, p) / mcos(n, p)\n\n\ndef msina(n, p=20):\n # arcsine of an acute angle\n return 0\n\n\ndef msec(n, p=20):\n # secant of an acute angle\n return 1 / mcos(n, p)\n\n\ndef mcsc(n, p=20):\n # cosecant of an acute angle\n return 1 / msin(n, p)\n\n\ndef mcot(n, p=20):\n # cotangent of an acute angle\n return 1 / mtan(n, p)\n\n\ndef msin2(n, p=20):\n # sine squared of an acute angle\n return msin(n, p) ** 2\n\n\ndef mcos2(n, p=20):\n # cosine squared of an acute angle\n return mcos(n, p) ** 2\n\n\ndef mtan2(n, p=20):\n # tangent squared of an acute angle\n return mtan(n, p) ** 2\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"31041799","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy # imported SQLAlchemy for data storage and retrival\n\napp = Flask(__name__)\n# Initializing Database String\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://testdb:123@localhost/testdb'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\n# db contains flask object\ndb = SQLAlchemy(app)\n\n\n# created Books Model to fetch Book related data\nclass Books(db.Model):\n # __tablename__ = 'books'\n id = db.Column(db.String(100), primary_key=True)\n name = db.Column(db.String(100))\n\n # Constructor of Books Model\n def __init__(self, id, name) -> object:\n self.id = id\n self.name = name\n\n\n# created Authors Model to fetch Author related data\nclass Authors(db.Model):\n # __tablename__ = 'author';\n id = db.Column(db.String, primary_key=True)\n name = db.Column(db.String(100))\n oid = db.Column(db.String)\n\n # Constructor of Author Model\n def __init__(self, id, name, oid):\n self.id = id\n self.name = name\n self.oid = oid\n\n\nif __name__ == '__main__':\n app.run();\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"66129124","text":"# -*- coding:utf-8 -*-\nfrom os import path, makedirs\nfrom logging import getLogger\nimport time\nfrom Queue import Empty, Full\nimport multiprocessing\nimport os\nimport uuid\nimport signal\n\nfrom migrate_tool.filter import Filter\n\n\nlogger = getLogger(__name__)\nfail_logger = getLogger('migrate_tool.fail_file')\npool_stop = False\nrestore_process_finish = False\n\n\ndef handler_user1(sig, frame):\n logger.info(\"got signal: %d, means restore process is finish\", sig)\n global restore_process_finish\n restore_process_finish = True\n\n\ndef handler_stop(sig, frame):\n logger.info(\"got signal: %d, means need stop\", sig)\n global pool_stop\n pool_stop = True\n\n\ndef work_thread(share_queue, lock, work_dir, output_service, input_service):\n logger.info(\"multiprocessing pool worker me: %d, is starting\", os.getpid())\n # _filter = Filter(work_dir)\n\n # todo, signal\n signal.signal(signal.SIGUSR1, handler_user1)\n\n # signal.signal(signal.SIGINT, handler_stop)\n # signal.signal(signal.SIGTERM, handler_stop)\n # signal.signal(signal.SIGHUP, handler_stop)\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n signal.signal(signal.SIGTERM, signal.SIG_DFL)\n signal.signal(signal.SIGHUP, signal.SIG_DFL)\n\n while True:\n global pool_stop\n if pool_stop:\n logger.info(\"pool_stop is true, work process: %d, will exit\", os.getpid())\n break\n\n # check restore process is finish or not\n global restore_process_finish\n if restore_process_finish and share_queue.empty():\n logger.info(\"restore process is finish, and share task queue is empty, pool worker me: %d will exit\",\n os.getpid())\n break\n\n try:\n logger.info(\"get one task from running task queue begin\")\n task = share_queue.get_nowait()\n except Empty:\n logger.info(\"task queue is empty, will sleep 3 seconds\")\n time.sleep(3)\n continue\n\n logger.info(\"finally get one task from running task queue done, task: %s\", task.key)\n\n task_path = task.key\n if task_path.startswith('/'):\n task_path = task_path[1:]\n if isinstance(task_path, str):\n task_path = task_path.decode('utf-8')\n\n localpath = unicode(path.join(work_dir, uuid.uuid4().hex))\n try:\n try:\n os.makedirs(path.dirname(localpath))\n except OSError as e:\n # directory is exists\n logger.warn(\"local path: %s, exists, possible work dir ! warn: %s\", localpath, str(e))\n\n # step 1, check exists\n try:\n ret = input_service.exists(task)\n if ret:\n logger.info(\"finally check task: %s, exists, skip it\", task_path.encode('utf-8'))\n # with lock:\n # _filter.add(task_path)\n continue\n else:\n logger.info(\"finally check task: %s, not exists, will download it to local path: %s\",\n task_path.encode('utf-8'), localpath)\n except Exception as e:\n # todo, override ?\n logger.exception(\"finally check task: %s, exists failed, error: %s\", task_path.encode('utf-8'), str(e))\n\n # step 2, download file\n try:\n output_service.download(task, localpath)\n except Exception as e:\n logger.exception(\"finally download task: %s, to local path: %s, failed, error: %s\",\n task_path.encode('utf-8'), localpath, str(e))\n fail_logger.error(task_path)\n # with lock:\n # fail += 1\n continue\n logger.info(\"finally download task: %s, success, size: %d, to local path: %s\", task.key, task.size,\n localpath)\n\n # step 3, upload file\n try:\n input_service.upload(task, localpath)\n except Exception as e:\n logger.exception(\"finally upload task: %s, from local path: %s, failed, error: %s\",\n task_path.encode('utf-8'), localpath, str(e))\n # with lock:\n # fail += 1\n fail_logger.error(task_path)\n continue\n logger.info(\"finally upload task: %s, success, size: %d, from local path: %s\", task.key, task.size,\n localpath)\n\n # step 4, remove tmp file\n try:\n if isinstance(localpath, unicode):\n localpath = localpath.encode('utf-8')\n os.remove(localpath)\n try:\n os.removedirs(path.dirname(localpath))\n except OSError:\n pass\n except Exception as e:\n logger.exception(\"finally remove task tmp file: %s, failed, size: %d, local path: %s, error: %s\",\n task.key, task.size, localpath, str(e))\n continue\n logger.info(\"finally remove task tmp file: %s, success, size: %d, local path: %s\", task.key, task.size,\n localpath)\n # todo, check task etag between source and destination\n # if isinstance(task_path, unicode):\n # logger.info(\"inc succ with {}\".format(task_path.encode('utf-8')))\n # else:\n # logger.info(\"inc succ with {}\".format(task_path.encode('utf-8')))\n\n # with lock:\n # add task to filter\n # succ += 1\n # _filter.add(task_path)\n except Exception as e:\n logger.exception(\"try except for deleting file, error: %s\", str(e))\n finally:\n if isinstance(localpath, unicode):\n localpath = localpath.encode('utf-8')\n try:\n os.remove(localpath)\n os.removedirs(path.dirname(localpath))\n except OSError:\n pass\n pass\n logger.info(\"multiprocessing pool worker: %d, will exit\", os.getpid())\n pass\n\n\n","sub_path":"migrate_tool/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":6167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"274383182","text":"import sys\nimport pandas as pd\nfrom trees.node import Node\t\t\t# Node class for each node of the tree\nfrom f_growtree import grow_tree\t# the ID3 algorithm, more or less\n\n'''\nmain(): completes parts a, b, and c of the assignment;\n\tthe program takes two arguments: the training and\n\ttest datasets\n\targuments must either:\n\t\t1) be file names within the same directory\n\t\tas id3_zhiyue_wang.py, or\n\t\t2) be full directory paths\n'''\ndef main(argv):\n\tif len(argv) is not 2:\n\t\tprint(\"Please enter two file names\")\n\t\tsys.exit()\n\ttrain_file = argv[0]\n\ttest_file = argv[1]\n\ttry:\n\t\ttrain = pd.read_table(train_file)\n\t\ttest = pd.read_table(test_file)\n\texcept:\n\t\tprint(\"Not valid file names or files aren't in the current directory or not '.dat' files\")\n\t\tsys.exit()\n\t\n\ttree = grow_tree(train)\n\ttree.print_tree()\n\taccuracy = tree.classify(train)\n\tprint(\"\\n\")\n\tprint(\"Accuracy on training set (\" + str(len(train)) + \n\t\t\" instances): \" + str(round(accuracy * 100, 1)) + \"%\")\n\taccuracy = tree.classify(test)\n\tprint(\"\\n\")\n\tprint(\"Accuracy on test set (\" + str(len(test)) + \n\t\" instances): \" + str(round(accuracy * 100, 1)) + \"%\")\n\t\t\n\nif __name__ == \"__main__\":\n\tmain(sys.argv[1:])\n","sub_path":"id3.py","file_name":"id3.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"220618075","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nfrom collections import defaultdict\n\n\nclass Solution:\n def isSymmetric(self, root: TreeNode) -> bool:\n res = defaultdict(list)\n\n def dfs(root, level):\n if not root:\n return\n res[level].append(root.val if root else None)\n dfs(root.left, level + 1)\n dfs(root.right, level + 1)\n\n dfs(root, 0)\n for k, v in res.items():\n if v != v[::-1]:\n return False\n return True\n\n\nif __name__ == '__main__':\n sn = Solution()\n root = [1, 2, 2, 3, 4, 4, 3]\n from gen_tree import generate_tree\n\n print(sn.isSymmetric(generate_tree(root)))\n","sub_path":"字节/101.py","file_name":"101.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"213629631","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .models import Notification\nfrom django.contrib.auth.decorators import login_required\n\nfrom restaurant.models import User\nfrom .forms import AcceptanceForm, PaymentForm, ReplyForm\n\n@login_required\ndef notifications(request):\n return render(request, 'notifications/base.html')\n\ndef show_app(request, notification_id):\n context = {\n 'notification': Notification.objects.get(id=notification_id),\n }\n return render(request, 'notifications/app_notifications.html', context)\n\n\ndef show_gen(request, notification_id):\n notification = Notification.objects.get(id=notification_id)\n context = {\n 'notification': Notification.objects.get(id=notification_id),\n 'form': ReplyForm()\n }\n if request.method == 'POST':\n form = ReplyForm(request.POST)\n if form.is_valid():\n a = User.objects.get(username=notification.curr_user)\n b = a.notification_set.create(title=notification.title, message=form.cleaned_data['reply'],curr_user=notification.dest_user,type=\"General\")\n return redirect('/notifications')\n\n return render(request, 'notifications/gen_notifications.html', context)\n\n\ndef show_ord(request, notification_id):\n notification = Notification.objects.get(id=notification_id)\n user = User.objects.get(username=request.user.username)\n\n context = {\n 'notification': Notification.objects.get(id=notification_id),\n 'user': user,\n 'form': AcceptanceForm()\n }\n if request.method == 'POST':\n form = AcceptanceForm(request.POST)\n if form.is_valid():\n if form.cleaned_data['choice'] == 'A':\n a = User.objects.get(username=notification.curr_user)\n b = a.notification_set.create(title=\"Order Recieved\", message=\"Your Order has been received successfully.!!..Proceed Further With Payment.!!..Thanks!\",\n curr_user=notification.dest_user,type=\"Order\")\n elif form.cleaned_data['choice'] == 'R':\n a = User.objects.get(username=notification.curr_user)\n b = a.notification_set.create(title=\"Order Cancelled\", message=\"Sorry!!..Your Order has been cancelled because of unavailability of item.!!..Money Paid will be refunded.!!\",\n curr_user=notification.dest_user,type=\"Order\")\n return redirect('/notifications')\n\n return render(request, 'notifications/ord_notifications.html', context)\n\n\ndef show_pay(request, notification_id):\n notification = Notification.objects.get(id=notification_id)\n user = User.objects.get(username=request.user.username)\n\n context = {\n 'notification': Notification.objects.get(id=notification_id),\n 'user': user,\n 'form': PaymentForm()\n }\n if request.method == 'POST':\n form = PaymentForm(request.POST)\n if form.is_valid():\n if form.cleaned_data['choice'] == 'A':\n a = User.objects.get(username=notification.curr_user)\n b = a.notification_set.create(title=\"Payment Done\", message=\"Your Payment has been received successfully.!!..Thanks.!!..Enjoy Food.!!\",\n curr_user=notification.dest_user,type=\"Payment\")\n elif form.cleaned_data['choice'] == 'R':\n a = User.objects.get(username=notification.curr_user)\n b = a.notification_set.create(title=\"Payment Not Recieved\", message=\"Sorry.!!..Your Payment was not received.!!..Please Check Once.!!\",\n curr_user=notification.dest_user,type=\"Payment\")\n return redirect('/notifications')\n\n return render(request, 'notifications/pay_notifications.html', context)\n\n\ndef delete_notification(request, notification_id):\n n = Notification.objects.get(id=notification_id)\n n.viewed = True\n n.save()\n return redirect('/notifications')\n\n\ndef give_g(request,usrname):\n a = User.objects.get(username=usrname)\n b = a.notification_set.create(title=request.POST['title'], message=request.POST['message'], curr_user=request.user.username,type=\"General\")\n b.save()\n return redirect('/notifications')\n\ndef give_o(request,usrname):\n a = User.objects.get(username=usrname)\n b = a.notification_set.create(order=request.POST['order'], message=request.POST['message'], curr_user=request.user.username,type=\"Order\")\n b.save()\n return redirect('/notifications')\n\ndef give_p(request,usrname):\n a = User.objects.get(username=usrname)\n b = a.notification_set.create(title=request.POST['title'], message=request.POST['message'], curr_user=request.user.username,type=\"Payment\")\n b.save()\n return redirect('/notifications')\n\n\ndef give_g_notification(request,usrname):\n context = {\n 'users' : User.objects.all()\n }\n return render(request, 'notifications/give_gen.html', context)\n\n\ndef give_o_notification(request,usrname):\n context = {\n 'users' : User.objects.all()\n }\n return render(request, 'notifications/give_order.html', context)\n\ndef give_p_notification(request,usrname):\n context = {\n 'users' : User.objects.all()\n }\n return render(request, 'notifications/give_payment.html', context)\n\n\n@login_required\ndef loggedin_a(request):\n context = {\n 'full_name': request.user.username,\n 'notifications': Notification.objects.filter(dest_user=request.user, viewed=False, type=\"App\"),\n }\n return render(request, 'notifications/view_app.html', context)\n\n@login_required\ndef loggedin_g(request):\n context = {\n 'full_name': request.user.username,\n 'notifications': Notification.objects.filter(dest_user=request.user, viewed=False, type=\"General\"),\n }\n return render(request, 'notifications/view_general.html', context)\n\n@login_required\ndef loggedin_o(request):\n context = {\n 'full_name': request.user.username,\n 'notifications': Notification.objects.filter(dest_user=request.user, viewed=False, type=\"Order\"),\n }\n return render(request, 'notifications/view_order.html', context)\n\n@login_required\ndef loggedin_p(request):\n context = {\n 'full_name': request.user.username,\n 'notifications': Notification.objects.filter(dest_user=request.user, viewed=False, type=\"Payment\"),\n }\n return render(request, 'notifications/view_pay.html', context)\n","sub_path":"notifications/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62898372","text":"# encoding: utf-8\nimport time\nimport os\nimport numpy as np\nimport multiprocessing as mp\nimport threading\nimport math\nimport config\nimport torch\nimport torch.nn as nn\nfrom skimage import io, img_as_ubyte\nfrom urllib import parse, request\nimport cv2\nfrom concurrent.futures import ProcessPoolExecutor, as_completed # 线程池\nfrom app_logging import logger\nfrom core.ocr_detection import ocr_cv\nfrom core.ocr_files_class import file_class, img_class_sencod\nfrom core.ocr_recognization import eng_recog\nfrom core.ocr_recognization.ocr_bbox_content import extract_sentence\nfrom core.ocr_recognization import crnn, alphabets\nfrom core.ocr_detection import ocr_rotation\nfrom . import rotation_content_judg\nimport asyncio\nimport logging\nfrom socket import error as SocketError\nimport errno\n__all__ = ('image_deal',)\n\n# crnn_model_path = './models/crnn_Rec_done_99.pth'\n# alphabet = alphabets.alphabet\n# nclass = len(alphabet) + 1\n# # crnn network\n# model = crnn.CRNN(32, 1, nclass, 256)\n# if torch.cuda.is_available() and config.IS_USE_CUDA:\n# model = model.cuda()\n# # 导入已经训练好的crnn模型\n# # # GPU\n# model.load_state_dict(torch.load(crnn_model_path))\n# if torch.cuda.device_count() > 1:\n# model = nn.DataParallel(model)\n# # # CPU\n# else:\n# model.load_state_dict(torch.load(crnn_model_path, map_location='cpu'))\n# logger.info('CRNN model loaded.')\n#global set_method\n#set_method=True\nif not (torch.cuda.is_available() and config.IS_USE_CUDA):\n crnn_model_path = './models/crnn_Rec_done_99.pth'\n alphabet = alphabets.alphabet\n nclass = len(alphabet) + 1\n # crnn network\n model = crnn.CRNN(32, 1, nclass, 256)\n model.load_state_dict(torch.load(crnn_model_path, map_location='cpu'))\n logger.info('CRNN model loaded.')\nelse:\n logger.info('will CRNN model loaded with gpu.')\n\ndef load_model_with_cuda():\n crnn_model_path = './models/crnn_Rec_done_99.pth'\n alphabet = alphabets.alphabet\n nclass = len(alphabet) + 1\n # crnn network\n model = crnn.CRNN(32, 1, nclass, 256)\n #if torch.cuda.is_available() and config.IS_USE_CUDA:\n model = model.cuda()\n # 导入已经训练好的crnn模型\n # # GPU\n model.load_state_dict(torch.load(crnn_model_path))\n if torch.cuda.device_count() > 1:\n model = nn.DataParallel(model)\n return model\n\n\ndef image_deal(self):\n start_time = time.time()\n # 区域检测\n detection(self)\n logger.info('[ticket:%s] detection_list_len: %d' % (self.ticket, len(self.detection_list)))\n # 区域文字识别\n result_e, result_c = recognization(self)\n cost_time = time.time() - start_time\n # with open('./data/merge_content_test/result_e.txt', 'r', encoding='utf8') as f:\n # result_e = eval(f.read())\n # with open('./data/merge_content_test/result_c.txt', 'r', encoding='utf8') as f:\n # result_c = eval(f.read())\n # 将识别的内容按照pdf页码的顺序进行重排,从旋转90和270中的内容中选一个\n result_e = result_rearrange(result_e)\n result_c = result_rearrange(result_c)\n logger.info('[ticket:%s] detection and recognization finished. image number:%s, time cost:%ss' % (self.ticket, self.slice_num, round(cost_time, 3)))\n return result_e, result_c\n\n\n# 图片文��区域检测\ndef detection(self):\n start_time = time.time()\n if self.data_dir:\n save_dir = self.data_dir + '/detect_image'\n # if os.path.exists(save_dir):\n # shutil.rmtree(save_dir)\n # if os.path.exists(self.data_dir):\n # os.mkdir(save_dir)\n if not os.path.exists(save_dir) and os.path.exists(self.data_dir):\n os.mkdir(save_dir)\n else:\n save_dir = ''\n # 以url集合的方式处理图片\n if self.img_data_dir:\n logger.info('[ticket:%s] detection start. by url...' % (self.ticket))\n for i in self.img_data_dir:\n img_url = i.get('path', '')\n suffix = img_url.split('.')[-1]\n if suffix not in ['jpg', 'png', 'jpeg']:\n continue\n # 读取图片\n try:\n # start_time = time.time()\n # logger.info('[ticket:%s] %s read image start.' % (self.ticket, img_url))\n image_path = parse.quote(img_url, encoding='utf8').replace('%3A', ':')\n resp = request.urlopen(image_path)\n img = np.asarray(bytearray(resp.read()), dtype=\"uint8\")\n img = cv2.imdecode(img, cv2.IMREAD_COLOR)\n # logger.info('[ticket:%s] %s read image end.time cost:%ss' % (self.ticket, image_path, round(time.time() - start_time, 3)))\n except Exception as e:\n logger.warning('[ticket:%s] %s error' % (self.ticket, image_path))\n logger.warning(e)\n # 判断图片是否需要旋转\n if not ocr_rotation.detect_rotation(img, 127):\n logger.info('[ticket:%s] %s 旋转图片.' % (self.ticket, img_url))\n # 旋转90度,并进行文本检测\n img_90 = np.rot90(img)\n detection_image(self, img_90, save_dir, i=i, rotation_angle=90)\n # 旋转270度,并进行文本检测\n img_270 = np.rot90(img, 3)\n detection_image(self, img_270, save_dir, i=i, rotation_angle=270)\n detection_image(self, img, save_dir, i=i, rotation_angle=0)\n else:\n # 图片文本检测和表格检测\n detection_image(self, img, save_dir, i=i, rotation_angle=0)\n # 处理本地图片\n elif not self.ocr_data_files and os.path.exists(r'%s/' % self.data_dir):\n # we store unzipped images in company_name's temporary directory\n logger.info('[ticket:%s] detection start. by local path. data_dir:%s' % (self.ticket, self.data_dir))\n for file in sorted(os.listdir(r'%s/' % self.data_dir), key=lambda x: x):\n if os.path.isdir((r'%s/' % self.data_dir) + file):\n for im in sorted(os.listdir((r'%s/' % self.data_dir) + file), key=lambda x: x):\n suffix = im.split('.')[-1]\n if suffix not in ['jpg', 'png', 'jpeg']:\n continue\n # 读图片\n image_path = r'%s/%s/%s' % (self.data_dir, file, im)\n img = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), -1)\n # 判断图片是否需要旋转\n if not ocr_rotation.detect_rotation(img, 127):\n logger.info('[ticket:%s] %s 旋转图片.' % (self.ticket, image_path))\n # 旋转90度,并进行文本检测\n img_90 = np.rot90(img)\n detection_image(self, img_90, save_dir, rotation_angle=90, file=file, type='path')\n # 旋转270度,并进行文本检测\n img_270 = np.rot90(img, 3)\n detection_image(self, img_270, save_dir, rotation_angle=270, file=file, type='path')\n detection_image(self, img, save_dir, rotation_angle=0, file=file, type='path')\n else:\n # 图片文本检测和表格检测\n detection_image(self, img, save_dir, rotation_angle=0, file=file, type='path')\n\n logger.info('[ticket:%s] detection finished. time cost:%ss' % (self.ticket, round(time.time() - start_time, 3)))\n\n\ndef sub_loop(each_params_list,model):\n # print('each_num_list',each_num_list)\n log = logging.getLogger('run_subloop')\n log.info('go sub_loop')\n\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n tasks = []\n for param_e in each_params_list:\n if bool(model):\n param_e['model']=model\n tasks.append(recog_box2word(param_e))\n\n # tasks_e = [recog_box2word(param_e) for param_e in each_params_list]\n # tasks_c = [recog_box2word(**param_c) for param_c in each_params_list_c]\n\n # tasks.extend(tasks_e)\n # tasks.extend(tasks_c)\n ##最后结果返回的是二维列表,里面每个小列表都是一个进程对应的一组任务,每组任务的顺序是按照task提交顺序返回的\n ##该组任务,必须完成之后才能继续做下面的,且该组任务只能有一个进程控制\n ##返回结果好像是按照调用的顺序的\n results = loop.run_until_complete(asyncio.gather(*tasks))\n return results\n\nasync def run(executor, params_list=None):\n\n if torch.cuda.is_available() and config.IS_USE_CUDA:\n s_t=time.time()\n model = load_model_with_cuda()\n print('model load time',time.time()-s_t)\n else:\n model=None\n log = logging.getLogger('run_blocking_tasks')\n log.info('starting')\n log.info('creating executor tasks')\n loop = asyncio.get_event_loop()\n # url = 'http://127.0.0.1:5000'\n # urls = [url for _ in range(100)]\n # print('excutor',executor)\n results = await loop.run_in_executor(executor, sub_loop, params_list,model)\n\n # await asyncio.get_event_loop().run_in_executor(executor, sub_loop,urls)\n # results = [t.result() for t in completed]\n # log.info('results: {!r}'.format(results))\n # print('gogo')\n return results\n\n\ndef chunks(list_num, size):\n n = math.ceil(len(list_num) / size)\n\n for i in range(0, len(list_num), n):\n yield list_num[i:i + n]\n# 区域文字识别,分别使用tesseract和“中文识别模型”\ndef recognization(self):\n # max_workers = (os.cpu_count() - 2) if os.cpu_count() < config.THREADS_NUMBER else config.THREADS_NUMBER\n max_workers = (os.cpu_count() ) if os.cpu_count() < config.THREADS_NUMBER else config.THREADS_NUMBER\n\n logger.info('[ticket:%s] recognization start. max_workers:%s' % (self.ticket, max_workers))\n start_time = time.time()\n result_e = {}\n result_c = {}\n # lock = threading.Lock()\n # 多线程\n if self.parallel == 1:\n # 构建线程池, 线程池默认线程是cpu核数*5, (os.cpu_count() or 1)*5\n if torch.cuda.is_available() and config.IS_USE_CUDA :#and set_method:\n #mp.set_start_method('spawn')\n try:\n mp.set_start_method('spawn')\n #set_method=False\n except RuntimeError:\n pass\n with ProcessPoolExecutor(max_workers=max_workers) as recog_executor:\n new_loop = asyncio.new_event_loop()\n asyncio.set_event_loop(new_loop)\n event_loop = asyncio.get_event_loop()\n try:\n\n ss = time.time()\n # all_task_e = []\n # all_task_c = []\n all_task_params_e = []\n all_task_params_c = []\n all_task_params_groups=[]\n\n\n\n\n ##获取中文和英文模型所需参数的列表\n for i in range(len(self.detection_list)):\n d = self.detection_list[i]\n img_name = d['img_name']\n use_model = [i[1] for i in self.rd.chi_tra if img_name == i[0]]\n use_model = use_model[0] if use_model else ''\n # 创建英文任务参数列表\n if use_model in ('', 'english'):\n\n param_e = {'self': self, 'd': d, 'i': i, 'type': 'english', 'use_model': use_model}\n # english = recog_executor.submit(recog_box2word, (param_e))\n all_task_params_e.append(param_e)\n # 创建中文任务参数列表\n if use_model in ('', 'chinese', 'chi_tra', 'chi_sim'):\n param_c = {'self': self, 'd': d, 'i': i, 'type': 'chinese', 'use_model': use_model}\n # chinese = recog_executor.submit(recog_box2word, (param_c))\n all_task_params_c.append(param_c)\n\n ##要将任务分组,让每个进程得到几乎均等的任务,并行的进行计算;此处将参数列表进行分组\n # url = 'http://127.0.0.1:5000'\n # all_urls = [url for _ in range(100)]\n ##要加判断两个模型参数都存在的时候才能调用\n\n len_e=len(all_task_params_e)\n len_c=len(all_task_params_c)\n if len_e>0:\n all_task_params_groups.extend(chunks(all_task_params_e,recog_executor._max_workers))\n if len_c>0:\n all_task_params_groups.extend(chunks(all_task_params_c,recog_executor._max_workers))\n\n #if torch.cuda.is_available() and config.IS_USE_CUDA:\n # if len_e>0:\n # all_task_params_groups.extend(chunks(all_task_params_e,recog_executor._max_workers))\n # if len_c>0:\n # all_task_params_groups.extend(chunks(all_task_params_c,recog_executor._max_workers))\n #else:\n # if len_e > 0:\n # all_task_params_groups.extend(chunks(all_task_params_e, len_e/recog_executor._max_workers))\n # if len_c > 0:\n # all_task_params_groups.extend(chunks(all_task_params_c, len_c/recog_executor._max_workers))\n\n tasks = [run(recog_executor, chunked) for chunked in\n all_task_params_groups]\n\n\n\n res = event_loop.run_until_complete(asyncio.gather(*tasks))\n #��二维列表变成一维列表\n res=sum(res,[])\n\n logger.info('{} workers cost time final {} s'.format(recog_executor._max_workers, time.time() - ss))\n #print('{} workers cost time final'.format(recog_executor._max_workers), time.time() - ss)\n # print\n\n # 获取英文任务的执行结果\n for index_e,e in enumerate(res[0:len_e]):\n result_e[str(index_e)] = e\n\n # 获取中文任务的执行结果\n for index_c,c in enumerate(res[len_e:]):\n result_c[str(index_c)] = c\n except Exception as e:\n logger.info('exception err',e,e.errno)\n if e.errno != errno.ECONNRESET:\n raise\n pass\n finally:\n event_loop.close()\n\n\n # 单线程\n else:\n for i in range(len(self.detection_list)):\n d = self.detection_list[i]\n img_name = d['img_name']\n use_model = [i[1] for i in self.rd.chi_tra if img_name == i[0]]\n use_model = use_model[0] if use_model else ''\n # 英文模型识别\n if use_model in ('', 'english'):\n param_e = {'self': self, 'd': d, 'i': i, 'type': 'english', 'use_model': use_model}\n try:\n data_e = recog_box2word(param_e)\n if data_e:\n result_e[str(i)] = data_e\n except Exception as e:\n logger.info('[ticket:%s] ocr_read_image. %s ' % (self.ticket, e))\n # 中文模型识别\n if use_model in ('', 'chinese', 'chi_tra', 'chi_sim'):\n param_c = {'self': self, 'd': d, 'i': i, 'type': 'chinese', 'use_model': use_model}\n try:\n data_c = recog_box2word(param_c)\n if data_c:\n result_c[str(i)] = data_c\n except Exception as e:\n logger.info('[ticket:%s] ocr_read_image. %s ' % (self.ticket, e))\n if img_class_sencod(self):\n result_class_sencod(self, result_e)\n result_class_sencod(self, result_c)\n if self.data_dir and os.path.exists(self.data_dir):\n logger.info('[ticket:%s] 写文件recoged_result.txt' % (self.ticket))\n write_content = {'result_e': result_e, 'result_c': result_c}\n with open('%s/recoged_result.txt' % self.data_dir, 'w', encoding='utf8') as f:\n f.write(str(write_content) + '\\n')\n logger.info('[ticket:%s] recognization finished. time cost:%ss' % (self.ticket, round(time.time() - start_time, 3)))\n return result_e, result_c\n\n\ndef result_class_sencod(self, result):\n for i, r in result.items():\n img_url = r['img_url']\n img_name = r['img_name']\n img_name_1 = self.img_url_class[img_url]\n if img_name != img_name_1:\n r['img_name'] = img_name_1\n # result[str(i)]['img_name'] = img_name_1\n # return result\n\n\nasync def recog_box2word(param):\n # model=load_model_with_cuda()\n #global model\n if not (torch.cuda.is_available() and config.IS_USE_CUDA):\n global model\n model = model\n else:\n model = param['model']\n self = param['self']\n d = param['d']\n type = param['type']\n use_model = param['use_model']\n if use_model:\n type = use_model\n img_name = d['img_name']\n # lock = param['lock']\n logger.info('[ticket:%s] %s %s %s model start.' % (self.ticket, d['img_name'], d['img_url'], type))\n start_time = time.time()\n img_gray = d['img_gray']\n detectied_region = d['detectied_region']\n table_bbox = d['table_bbox']\n point_sets = d['point_sets']\n tmp = {}\n # lock.acquire() # 获取锁\n recoged_result = eng_recog.box2word(img_gray, detectied_region, model, type, img_name)\n recoged_result = y_axis_deviation_deal(recoged_result)\n # lock.release() # 释放锁\n tmp['img_url'] = d['img_url']\n tmp['rotation_angle'] = d['rotation_angle']\n\n # 文件分类, 只有“其他文件”和“打包文件”入口的文件才需要进行分类,\n # 且当“合同”、“发票”,“箱单”,“运单”,“申报要素”,“入库单”等入口有对应文件时,\n # 舍弃掉“其他文件”和“打包文件”入口对应的文件\n if img_name in ('other_files', 'package_upload'):\n # class_time = time.time()\n # lock.acquire()\n img_name_new = file_class(recoged_result, self.rd, self.img_url_class, d['img_url'], img_name)\n logger.info('[ticket:%s] 文件分类.origin:%s,new:%s' % (self.ticket, img_name, img_name_new))\n # lock.release()\n if img_name_new not in ('other_files', 'package_upload') and img_name_new in self.source_list:\n tmp = {}\n elif not recoged_result: # recoged_result的内容为空\n tmp = {}\n else:\n tmp['img_name'] = img_name_new\n # result[str(i)] = tmp\n else:\n tmp['img_name'] = d['img_name']\n if recoged_result:\n recoged_result = extract_sentence(table_bbox, recoged_result, d['img_gray'], tmp['img_name'])\n tmp['recoged_result'] = recoged_result\n tmp['id'] = d.get('id', '')\n tmp['page'] = d.get('page', '')\n tmp['table_bbox'] = table_bbox\n tmp['point_sets'] = point_sets\n logger.info('[ticket:%s] %s %s %s model end.time cost:%ss' % (self.ticket, img_name, d['img_url'], type, round(time.time() - start_time, 3)))\n return tmp if tmp else None\n\n\n# y轴偏差处理, y相差2-3个距离时,进行统一\ndef y_axis_deviation_deal(DL):\n DL_sorted = sorted(DL, key=lambda x: x[2])\n DL_mask = [0 for _ in range(len(DL_sorted))]\n for i in range(len(DL_sorted)):\n DL_i = DL_sorted[i]\n for j in range(i + 1, len(DL_sorted)):\n DL_j = DL_sorted[j]\n if DL_j[2] - DL_j[2] > 30:\n break\n elif DL_mask[j] == 1:\n continue\n elif 0 < abs(DL_i[2] - DL_j[2]) < 10:\n y_offset = DL_j[2] - DL_i[2]\n DL_sorted[j][2] -= y_offset\n DL_mask[j] == 1\n return DL_sorted\n\n\ndef result_rearrange(result):\n try:\n pdf_id_dict = {}\n for i, r in result.items():\n img_url = r['img_url']\n pdf_id = r.get('id', 'pdf_id_default')\n page = r.get('page', 0)\n if str(page).strip() == '':\n page = 0\n if pdf_id in pdf_id_dict:\n if img_url in pdf_id_dict[pdf_id]:\n pdf_id_dict[pdf_id][img_url]['index_list'].append(i)\n\n else:\n pdf_id_dict[pdf_id][img_url] = {'index_list': [i], \"page\": page}\n else:\n pdf_id_dict[pdf_id] = {img_url: {\"index_list\": [i], \"page\": page}}\n\n result_new = {}\n for pdf_id, values in pdf_id_dict.items():\n # 将识别的内容按照pdf页码的顺序进行重排\n for im_url, v in sorted(values.items(), key=lambda x: int(x[1]['page'])):\n index_list = v['index_list']\n # 从旋转90和270,0中的内容中选一个\n if len(index_list) == 3:\n index_0 = [i for i in index_list\n if result[str(i)].get('rotation_angle', None) == 0][0]\n index_90 = [i for i in index_list\n if result[str(i)].get('rotation_angle', None) == 90][0]\n index_270 = [i for i in index_list\n if result[str(i)].get('rotation_angle', None) == 270][0]\n _, rotation_angle = \\\n rotation_content_judg.content_judgment_three(result[str(index_0)]['recoged_result'],\n result[str(index_90)]['recoged_result'],\n result[str(index_270)]['recoged_result'])\n if rotation_angle == 0:\n index = index_0\n elif rotation_angle == 90:\n index = index_90\n else:\n index = index_270\n else:\n index = index_list[0]\n result_new[str(index)] = result[str(index)]\n return result_new\n except Exception as e:\n logger.info(e)\n return result\n\n\ndef detection_image(self, img, save_dir, rotation_angle, i=None, file=None, type='url'):\n if type == 'url':\n source = i.get('type', '')\n img_url = i.get('path', '')\n img_time = time.time()\n logger.info('[ticket:%s] %s %s detection start.' % (self.ticket, source, img_url))\n detectied_region, img_gray, table_bbox, point_sets = ocr_cv.detect_word(img, img_url, 'url', self.ticket, companyName=self.companyName, source=source, data_dir=save_dir)\n logger.info('[ticket:%s] %s %s detection end. time cost:%ss' % (self.ticket, source, img_url, round(time.time() - img_time, 3)))\n tmp = {}\n tmp['rotation_angle'] = rotation_angle\n tmp['detectied_region'] = detectied_region\n tmp['img_gray'] = img_gray\n tmp['img_name'] = source\n tmp['img_url'] = img_url\n tmp['id'] = i.get('id', '')\n tmp['page'] = i.get('page', '')\n tmp['table_bbox'] = table_bbox\n tmp['point_sets'] = point_sets\n self.detection_list.append(tmp)\n else:\n img_path = r'%s/%s/%s' % (self.data_dir, file, img)\n tmp_img_path = '%s/%s' % (file, img)\n detectied_region, img_gray, table_bbox, point_sets = ocr_cv.detect_word(img, img_path, data_dir=save_dir)\n tmp = {}\n tmp['rotation_angle'] = rotation_angle\n tmp['detectied_region'] = detectied_region\n tmp['img_gray'] = img_gray\n tmp['img_name'] = file\n tmp['img_url'] = ''\n tmp['id'] = ''\n tmp['page'] = ''\n tmp['table_bbox'] = table_bbox\n tmp['point_sets'] = point_sets\n self.detection_list.append(tmp)\n\n","sub_path":"coroutine_process/multi_process_coroutine/ocr_read_image.py","file_name":"ocr_read_image.py","file_ext":"py","file_size_in_byte":23370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"300064719","text":"#!python3\n\n\"\"\"\nCreate a variable that contains an empy list.\nAsk a user to enter 5 words. Add the words into the list.\nPrint the list\ninputs:\nstring \nstring\nstring\nstring\nstring\n\noutputs:\nstring\n\nexample:\nEnter a word: apple\nEnter a word: worm\nEnter a word: dollar\nEnter a word: shingle\nEnter a word: virus\n\n['apple', 'worm', 'dollar', 'shingle', 'virus']\n\"\"\"\none=input(\"First word \").strip()\ntwo=input(\"second word \").strip()\nthree=input(\"third word \").strip()\nfour=input(\"Fourth word \").strip()\nfive=input(\"Fifth word \").strip()\nx=[]\nx.append(one)\nx.append(two)\nx.append(three)\nx.append(four)\nx.append(five)\nprint(x)\n","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"558878550","text":"import os\nimport webapp2\nimport json\nimport cloudstorage\nfrom google.appengine.api import app_identity\n\nimport constants\nfrom entities import Pin\n\nclass CreateJsonHandler(webapp2.RequestHandler):\n def get(self):\n bucket_name = os.environ.get('BUCKET_NAME',\n app_identity.get_default_gcs_bucket_name())\n filename = '/' + bucket_name + '/' + constants.PIN_JSON_FILENAME\n\n pins_array = []\n for pin in Pin.query(Pin.is_activated == True).fetch():\n pin_dict = {}\n pin_dict[\"id\"] = pin.key.id()\n pin_dict[\"icon\"] = pin.pin_icon\n pin_dict[\"lat\"] = pin.point.lat\n pin_dict[\"lng\"] = pin.point.lon\n pins_array.append(pin_dict)\n\n with cloudstorage.open(filename, 'w', content_type='text/json') as cloudstorage_file:\n cloudstorage_file.write(json.dumps(pins_array))\n self.response.set_status(200)\n\napp = webapp2.WSGIApplication([\n ('/admin/create_pins_json', CreateJsonHandler),\n], debug=True)\n","sub_path":"admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"506157304","text":"import sys\nimport os\nimport unittest\nimport shutil\nfrom io import StringIO\nsys.path.append(\".\")\nimport annogesiclib.blast_class as blast_class\n\nclass Mock_func(object):\n\n def mock_read_file(self, blast_file):\n repeats = {'RNA_test1': ['hit_1|strain_b|dnaA', 'hit_2|strain_c|dnaa']}\n return Example().read_out, repeats\n\n\nclass TestBlastClass(unittest.TestCase):\n\n def setUp(self):\n self.example = Example()\n self.test_folder = \"test_folder\"\n if (not os.path.exists(self.test_folder)):\n os.mkdir(self.test_folder)\n self.blast_file = os.path.join(self.test_folder, \"test.csv\")\n with open(self.blast_file, \"w\") as rh:\n rh.write(self.example.blast)\n\n def tearDown(self):\n if os.path.exists(self.test_folder):\n shutil.rmtree(self.test_folder)\n\n def test_read_file(self):\n datas, repeats = blast_class.read_file(self.blast_file)\n for index in range(0, 3):\n self.assertDictEqual(datas[index], self.example.read_out[index])\n self.assertDictEqual(repeats, {'RNA_test1': ['hit_1|strain_b|dnaA', 'hit_2|strain_c|dnaa']})\n\n def test_blast_class(self):\n blast_class.read_file = Mock_func().mock_read_file\n lines = []\n out_file = os.path.join(self.test_folder, \"test.out\")\n blast_class.blast_class(self.blast_file, out_file)\n with open(out_file) as fh:\n for line in fh:\n line = line.strip()\n lines.append(line)\n self.assertEqual(set(lines), set(self.example.blast_table.split(\"\\n\")))\n\nclass Example(object):\n blast = \"\"\"aaa\tRNA_test1\t+\t100\t200\thit_1|strain_b|dnaA\t0.0005\naaa\tRNA_test1\t+\t100\t200\thit_2|strain_c|dnaa\t0.0007\naaa\tRNA_test2\t-\t400\t450\thit_3|strain_b|dnaC\t0.000002\"\"\"\n read_out = [{'ID': 'hit_1', 'srna_name': 'dnaA', 'blast_strain': 'strain_b', 'strain': 'aaa', 'start': '100', 'name': 'RNA_test1', 'strand': '+', 'end': '200', 'e': '0.0005'},\n {'ID': 'hit_2', 'srna_name': 'dnaa', 'blast_strain': 'strain_c', 'strain': 'aaa', 'start': '100', 'name': 'RNA_test1', 'strand': '+', 'end': '200', 'e': '0.0007'},\n {'ID': 'hit_3', 'srna_name': 'dnaC', 'blast_strain': 'strain_b', 'strain': 'aaa', 'start': '400', 'name': 'RNA_test2', 'strand': '-', 'end': '450', 'e': '0.000002'}]\n\n blast_table = \"\"\"All strain:\nsRNA_name\tamount\ndnaA\t2\ndnaC\t1\n\nrepeat counting:\nRNA_test1:hit_1|strain_b|dnaA;hit_2|strain_c|dnaa\"\"\"\n\nif __name__ == \"__main__\":\n unittest.main()\n\n","sub_path":"tests/test_blast_class.py","file_name":"test_blast_class.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"625133329","text":"class Dicionario:\n def __init__(self, string):\n self.key = []\n self.values = []\n string = string.split()\n for palavra in string:\n valor = self.get(palavra)\n if valor == None:\n self.put(palavra, 1)\n else:\n self.put(palavra, valor + 1)\n\n def __str__(self):\n s = \"\"\n for i in range(len(self.values)):\n s += \"%s %d\\n\"%(self.key[i],self.values[i])\n return s\n\n def indice(self, chave):\n for i in range(len(self.key)):\n if self.key[i] == chave:\n return i\n return None\n\n def get(self,chave):\n index = self.indice(chave)\n if index != None:\n return self.values[index]\n return None\n\n def put(self, chave, valor):\n index = self.indice(chave)\n if index != None:\n self.values[index] = valor\n else:\n self.key.append(chave)\n self.values.append(valor)\n\ndef main():\n lst_pal = 'Ola Chen Ola Chen Marcos Tudo Bom Bom Bom BOM '\n dicio = Dicionario(lst_pal)\n print(dicio)\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Dicionario/dicionario.py","file_name":"dicionario.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"474709488","text":"import time\nimport numpy as np\nimport scipy\nfrom utils import combine, NOISE_FILENAME, FORCEVECTOR_FILENAME\nfrom scipy.spatial.transform import Rotation as R\nimport matplotlib.pyplot as plt\n\n\n\nclass ServoControl:\n def __init__(self, robot):\n self.frequency = 1/500\n\n self.threshold = 70\n self.contactMean = 3 * 2 #Newton\n self.contactSTD = 1\n\n self.robot = robot\n\n def convertForceInBase2TCP(self,ftInBase):\n tcpPose = self.robot.getActualTCPPose()\n rot = R.from_rotvec(tcpPose[3:6])\n rMatrix = scipy.linalg.inv(rot.as_matrix())\n return rMatrix @ ftInBase[0:3]\n \n def saveForceVector(self, vector, pose):\n with open(FORCEVECTOR_FILENAME, 'w+') as file:\n string = \"\"\n for value in pose:\n string += str(value) + \" \"\n for value in vector:\n string += str(value) + \" \"\n string = string[0:-1]\n file.write(string)\n\n def loadNoiseValues(self):\n with open(NOISE_FILENAME, 'r') as file:\n values = file.readline().split(\" \")\n #noiseMean = float(values[0])\n noiseSTD = float(values[1])\n #acceleration = [float(acc) for acc in values[2:-1]]\n self.contactSTD = noiseSTD\n \n\n def run(self, positionalTrajectory, velocity = 0.5, acceleration = 0.5, lookAheadTime = 0.1, gain = 600, runCusum = True, nrOfPointsToBacktrack = 400):\n self.loadNoiseValues()\n \n pose = positionalTrajectory[0]\n self.robot.moveL(pose)\n\n backtrackedTraj = []\n magnitudeList = []\n ftsInTCP = []\n tcpPoss = []\n cusumValues = [0]\n\n self.robot.zeroFtSensor()\n resetTime = time.time()\n for i, point in enumerate(positionalTrajectory):\n startTime = time.time()\n\n self.robot.servoL(point, velocity, acceleration, self.frequency/2, lookAheadTime, gain)\n\n\n if runCusum:\n ftInTCP = self.convertForceInBase2TCP(self.robot.getActualTCPForce())\n ftsInTCP.append(ftInTCP)\n\n tcpPoss.append(self.robot.getActualTCPPose()[0:3])\n\n magnitudeList.append(np.linalg.norm(ftInTCP))\n\n mean = np.asarray(magnitudeList).mean()\n sk = ((magnitudeList[-1] - mean)**2-(magnitudeList[-1] - self.contactMean)**2)/(2*self.contactSTD**2)\n cusumValues.append(np.maximum(0, cusumValues[-1] + sk))\n\n if cusumValues[-1] > self.threshold:\n if i > nrOfPointsToBacktrack:\n backtrackedTraj = positionalTrajectory[i-nrOfPointsToBacktrack:i]\n else:\n backtrackedTraj = positionalTrajectory[0:i]\n break\n \n \n if time.time() - resetTime > 0.1:\n self.robot.zeroFtSensor()\n resetTime = time.time()\n \n \n diff = time.time() - startTime\n if(diff < self.frequency):\n time.sleep(self.frequency - diff)\n \n self.robot.servoStop()\n if cusumValues[-1] > self.threshold:\n print(\"Contact!\")\n self.saveForceVector(ftInTCP, self.robot.getActualTCPPose())\n #self.plotRun(magnitudeList, cusumValues[1:], np.asarray(ftsInTCP).T, np.asarray(tcpPoss).T)\n elif runCusum:\n print(\"No contact!\")\n time.sleep(0.01)\n return backtrackedTraj\n \n def plotRun(self,ftMagnitude, cusumValues, ftsInTCP, tcpPoss):\n xAxis = range(0,len(ftMagnitude))\n\n plot1 = plt.figure(1)\n axes = plt.gca()\n plt.plot(xAxis,ftMagnitude, color='r', label=\"Force magnitude [N]\")\n plt.plot(xAxis, cusumValues, color='black', label=\"CUSUM Values\")\n plt.xlabel(\"# Measurement\")\n axes.set_ylim([-1,8])\n plt.legend()\n\n fig1, axs = plt.subplots(3, 2, sharex=True)\n\n axs[0,0].plot(xAxis, ftsInTCP[0,:], color='orange', label=\"Force\")\n axs[0,0].set_xlabel(\"# Measurement\")\n axs[0,0].title.set_text(\"x-axis\")\n axs[0,0].set_ylabel(\"F [N]\")\n\n axs[1,0].plot(xAxis, ftsInTCP[1,:], color='orange', label=\"Force\")\n axs[1,0].set_xlabel(\"# Measurement\")\n axs[1,0].title.set_text(\"y-axis\")\n axs[1,0].set_ylabel(\"F [N]\")\n\n axs[2,0].plot(xAxis, ftsInTCP[2,:], color='orange', label=\"Force\")\n axs[2,0].set_xlabel(\"# Measurement\")\n axs[2,0].title.set_text(\"z-axis\")\n axs[2,0].set_ylabel(\"F [N]\")\n axs[2,0].legend()\n\n axs[0,1].plot(xAxis, tcpPoss[0,:], color='black', label=\"TCP Position\")\n axs[0,1].set_xlabel(\"# Measurement\")\n axs[0,1].set_ylabel(\"x-coordinate\")\n axs[0,1].title.set_text(\"x-axis\")\n\n axs[1,1].plot(xAxis, tcpPoss[1,:], color='black', label=\"TCP Position\")\n axs[1,1].set_xlabel(\"# Measurement\")\n axs[1,1].set_ylabel(\"y-coordinate\")\n axs[1,1].title.set_text(\"y-axis\")\n\n axs[2,1].plot(xAxis, tcpPoss[2,:], color='black', label=\"TCP Position\")\n axs[2,1].set_xlabel(\"# Measurement\")\n axs[2,1].set_ylabel(\"z-coordinate\")\n axs[2,1].title.set_text(\"z-axis\")\n axs[2,1].legend()\n\n\n plt.show()\n\n def getForceVector(self):\n with open(FORCEVECTOR_FILENAME, 'r') as file:\n vector = file.readline().split(\" \")\n vector = [float(i) for i in vector]\n return vector\n\n def generatePointsToVisit(self, vector, nrOfPoints = 3, size = 0.1):\n nVector = vector[6:9]\n point = vector[0:3]\n Q = scipy.linalg.null_space(np.asmatrix(nVector))\n randomPoints = np.random.rand(2,nrOfPoints) - 0.5\n offsetPointsInVectorDirection = (np.asarray(nVector).reshape(3,1)/np.linalg.norm(nVector))*0.05\n points = np.asarray(point).reshape((3,1)) + np.matmul(Q,randomPoints*size) - offsetPointsInVectorDirection\n return points\n \n def addPointsTogether(self, p1, p2):\n for p in p2.T:\n p1.append(p)\n return p1\n\n\n def recursiveSearch(self, startPoint, contactPoints, forceVectors, allPoints, depth, nrOfPointsToBacktrack = 2000):\n forceVector = self.getForceVector()\n forceVectors.append(forceVector)\n\n if depth >= 2:\n return contactPoints, forceVectors, allPoints\n\n points = self.generatePointsToVisit(forceVector)\n allPoints = self.addPointsTogether(allPoints, points)\n\n for point in points.T:\n traj = np.linspace(startPoint, point, nrOfPointsToBacktrack)\n traj = combine(traj)\n backtrackedTrajectory = self.run(traj)\n if backtrackedTrajectory:\n contactPoints.append(backtrackedTrajectory[-1][0:3])\n self.recursiveSearch(startPoint, contactPoints, forceVectors, allPoints, depth+1)\n time.sleep(0.05)\n return contactPoints, forceVectors, allPoints\n\n\n def searchForObstacle(self, backtrackedTraj, nrOfPointsToBacktrack_ = 400):\n print(\"Searching for obstacle!\")\n backtrackedTraj = list(reversed(backtrackedTraj))\n nrOfPointsToBacktrack = nrOfPointsToBacktrack_\n self.run(backtrackedTraj, runCusum=False, nrOfPointsToBacktrack=nrOfPointsToBacktrack)\n time.sleep(0.3)\n contactPoints, forceVectors, allPoints = self.recursiveSearch(backtrackedTraj[-1][0:3], [backtrackedTraj[0][0:3]], [self.getForceVector()], [],0)\n contactPoints = np.asmatrix(contactPoints)\n forceVectors = np.asmatrix(forceVectors)\n allPoints = np.asmatrix(allPoints)\n return contactPoints.T, forceVectors.T, allPoints.T\n \n","sub_path":"UR5/ServoControl.py","file_name":"ServoControl.py","file_ext":"py","file_size_in_byte":7707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"556016882","text":"#encoding: UTF-8\n\n# Autor:Rodrigo Rivera Salinas, A01375000\n# Descripcion: calcular el porcentaje de hombres y mujeres que estan en una clase\n\n# A partir de aquí escribe tu programa\n\nh=int(input(\"dar cantidad de hombres\"))\nm=int(input(\"dar cantidad de mujeres\"))\ntotal=h+m\n\nhombres=(h*100)/total\nmujeres=(m*100)/total\n\nprint(\"el porcentaje de hombres es: \",hombres, \"%\")\nprint(\"el porcentaje de mujeres es: \",mujeres, \"%\")\n\n","sub_path":"porcentajes.py","file_name":"porcentajes.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"248151946","text":"import time\r\nclass Test:\r\n def __init__(self):\r\n print(\"object Initalization\")\r\n def __del__(self):\r\n print(\"fulfilling last wish and performing cleanup activity\")\r\nt1=Test()\r\nt1=None\r\ntime.sleep(10)\r\nprint(\"End of application\")\r\n","sub_path":"14_gc_7.py","file_name":"14_gc_7.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"349573946","text":"from sklearn.metrics import jaccard_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn.linear_model import RidgeClassifierCV\nimport numpy as np\n\n\ndef _ridgeclassifiercv(*, train, test, x_predict=None, metrics, alphas=(0.1, 1.0, 10.0), fit_intercept=True, normalize=False,\n scoring=None, cv=None, class_weight=None, store_cv_values=False):\n \"\"\"For for info visit : \n https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeClassifierCV.html#sklearn.linear_model.RidgeClassifierCV\n \"\"\"\n\n model = RidgeClassifierCV(alphas=alphas, fit_intercept=fit_intercept, normalize=normalize, scoring=scoring, cv=cv,\n class_weight=class_weight, store_cv_values=store_cv_values)\n model.fit(train[0], train[1])\n model_name = 'RidgeClassifierCV'\n y_hat = model.predict(test[0])\n\n if metrics == 'f1_score':\n accuracy = f1_score(test[1], y_hat)\n if metrics == 'jaccard_score':\n accuracy = jaccard_score(test[1], y_hat)\n if metrics == 'accuracy_score':\n accuracy = accuracy_score(test[1], y_hat)\n\n if x_predict is None:\n return (model_name, accuracy, None)\n\n y_predict = model.predict(x_predict)\n return (model_name, accuracy, y_predict)","sub_path":"datascientist/model/classification/skl/linear_model/ridgeclassifiercv.py","file_name":"ridgeclassifiercv.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306026976","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 16 12:55:54 2017\n\n@author: Thomas\n\"\"\"\n\n\nimport socket\nfrom sys import exit\n\nfrom time import sleep\n#import os\n#from numpy import around\nfrom serial import Serial, SerialException\n\n\n'''Socketserver zur GUI wird erstellt und wartet auf ankommende Verbindungen'''\n\nip = '127.0.0.1'\ntry:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n s.bind((ip, 60110)) \n s.listen(40)\nexcept OSError:\n print('Already running, terminating')\n exit()\n\nsteve_msg = ''\n\ncom_ports = ['COM2','COM3','COM4','COM5','COM6']\n\n\n''' Initialisierung'''\n''' Festlegen welche Ports genutzt werden sollen. '''\n\narduino = True\nstev = False\n\ncon_ard_enable = False\n\n#\n#operating_system = os.name\n#\n#if os.name == 'nt': laptop == True\n#if os.name == '': raspberry == True\n\n'''AKtivieren der gewählten Ports'''\n\nif stev:\n steve = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n steve.bind(('localhost', 60120))\n steve.listen(5) \n \nprint('----- Welcome to the Raspberry Distributor -----')\nprint()\nprint('Chosen Settings')\nprint('Connect to Arduino:\\t', arduino)\nprint('Connect to Steve:\\t', stev)\nprint()\nprint('Trying to activate all possible Connections:')\n\nif arduino:\n com_ports_red = com_ports[:-1]\n for i, val in enumerate(com_ports_red):\n if not con_ard_enable:\n try:\n 'Serial-Objekt instanziieren'\n device = Serial()\n 'Port festlegen'\n device.port = com_ports[i]\n 'Baudrate festlegen'\n device.baudrate = 115200\n 'Timeout festlegen'\n device.timeout = 1\n \n device.open()\n \n con_ard_enable = True\n print('Connected to Arduino by', com_ports[i],'.')\n except SerialException:\n print('Connection to Arduino by ',com_ports[i],' not possible, trying ',com_ports[i+1],'.')\n \n if not con_ard_enable:\n try:\n i=i+1 \n 'Serial-Objekt instanziieren'\n device = Serial()\n 'Port festlegen'\n device.port = com_ports[i]\n 'Baudrate festlegen'\n device.baudrate = 115200\n 'Timeout festlegen'\n device.timeout = 1\n \n device.open()\n con_ard_enable = True\n print('Connected to Arduino by ', com_ports[i],'.')\n \n except SerialException:\n print('Connection to Arduino by ', com_ports[i],' not possible, trying ttyACM0.')\n \n if not con_ard_enable:\n try:\n 'Serial-Objekt instanziieren'\n device = Serial()\n 'Port festlegen'\n device.port = '/dev/ttyACM0'\n 'Baudrate festlegen'\n device.baudrate = 115200\n 'Timeout festlegen'\n device.timeout = 1\n \n device.open()\n con_ard_enable = True\n print('Connected to Arduino by ttyACM0')\n \n except SerialException:\n print('Connection to Arduino by ttyAMC0 not possible, conntact Support.')\n\n\nprint() \nprint('--- Server Running ---')\nprint()\n\n''' Main '''\n\n#v_time = around(time.clock(), 5)\n#a_time = around(time.clock(), 5)\n\n\n''' Verbindung zu Steve herstellen '''\nif stev:\n steve_com, steve_addr = steve.accept()\n print('Connection to Steve established')\n\n\nwhile True:\n \n try: \n \n while True:\n \n ''' Verbindungen von der GUI akzeptieren '''\n komm, addr = s.accept()\n print('Connection to GUI established')\n \n while True:\n '''Empfangen der Daten von der GUI'''\n data = komm.recv(56)\n \n if not data: \n komm.close()\n break\n \n# a_time = around(time.clock(), 5)\n# print(a_time - v_time , ' ' , data)#\n# v_time = around(a_time - v_time, 5)\n \n nachricht = data.decode('ascii')\n \n \n print('Nachricht: ', nachricht)\n# print(nachricht)\n \n '''Durchrouten an Steve'''\n '''Nachricht wird für Steve codiert'''\n if stev:\n steve_msg_p = nachricht.split(' ')\n for i in range (1,11):\n steve_msg += steve_msg_p[i]\n \n steve_msg += '00' \n steve_com.send(steve_msg.encode('ascii'))\n print('Steve: \\t', steve_msg)\n steve_msg = ''\n \n '''Nachricht wird über den Laptopport geroutet'''\n if arduino:\n \n wiederversuch = True \n while wiederversuch:\n try:\n device.write(nachricht.encode('ascii'))\n print('Laptop: \\t', nachricht)\n # print(nachricht[0])\n # print(nachricht[1])\n # print(nachricht[2])\n '''Wenn die GUI Anfrage mit 30 beginnt, Antwort vom\n Arduino abwarten und an die GUI leiten'''\n if nachricht[0] == '1':\n sleep(2)\n if nachricht[0] == '3' and nachricht [1] == '0':\n # print('warte auf Antwort')\n sleep(1/200) \n antwort_raw = device.readline()\n # antwort = antwort_raw.decode()\n antwort = str(antwort_raw[:-2].decode())\n antwort += ' '\n antwort = '{0:{1}<26}'.format(antwort, '0')\n \n # antwort += ' '\n # for i in range(len(antwort), 29):\n # antwort += '0'\n # antwort.ljust(100, '0')\n print('Antwort: \\t', antwort)\n \n# device.flushInput()\n \n komm.send(antwort.encode('ascii'))\n if nachricht[0] == '5':\n# if arduino == False:\n# antwort = '000'\n# komm.send(antwort.encode('ascii'))\n# print(antwort)\n# else:\n print('warte auf Antwort')\n sleep(1/50) \n antwort_raw = device.readline()\n # antwort = antwort_raw.decode()\n antwort = str(antwort_raw[:-2].decode())\n# antwort = '110'\n antwort += ' '\n antwort = '{0:{1}<26}'.format(antwort, '0')\n \n # antwort += ' '\n # for i in range(len(antwort), 29):\n # antwort += '0'\n # antwort.ljust(100, '0')\n print('Antwort: \\t', antwort)\n \n# device.flushInput()\n \n komm.send(antwort.encode('ascii'))\n wiederversuch = False\n except:\n wiederversuch = True\n print('Falsche Antwort')\n# device.flushInput()\n\n if not arduino:\n if nachricht[0] == '5':\n antwort = '000 '\n antwort = '{0:{1}<26}'.format(antwort, '0')\n \n print('Antwort: \\t', antwort)\n\n \n komm.send(antwort.encode('ascii'))\n \n \n# '''Nachricht über den Raspberry Port routen''' \n# if raspberry:\n# device.write(nachricht.encode('ascii'))\n# print('Laptop: \\t', nachricht)\n## print(nachricht[0])\n## print(nachricht[1])\n## print(nachricht[2])\n# if nachricht[0] == '3' and nachricht [1] == '0':\n## print('warte auf Antwort')\n# antwort_raw = device.readline()\n## antwort = antwort_raw.decode()\n# antwort = str(antwort_raw[:-2].decode())\n# antwort += ' '\n# antwort = '{0:{1}<26}'.format(antwort, '0')\n# \n## antwort += ' '\n## for i in range(len(antwort), 29):\n## antwort += '0'\n## antwort.ljust(100, '0')\n# print('Antwort: \\t', antwort)\n# \n# komm.send(antwort.encode('ascii'))\n print()\n \n '''Fehler abgreifen und Steve zurücksetzen, es wird davon \n ausgegangen, dass die GUI neu gestartet wurde. '''\n except ConnectionAbortedError:\n print('Connection aborted.')\n if stev: \n steve_msg = '09090.000018090.000000090.000009090.000009090.000000' \n steve_com.send(steve_msg.encode('ascii'))\n print('Steve wurde resettet')\n steve_msg = ''\n except ConnectionResetError:\n print('Connection to GUI lost')\n if stev: \n steve_msg = '09090.000018090.000000090.000009090.000009090.000000' \n steve_com.send(steve_msg.encode('ascii'))\n print('Steve wurde resettet')\n steve_msg = ''\n\nprint('---Server shutdown---')","sub_path":"RoboterSteuerung/Robotersteuerung_Dennis/Arduino_Schnittstelle/Arduino_schnittstelle.py","file_name":"Arduino_schnittstelle.py","file_ext":"py","file_size_in_byte":10501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"420289742","text":"import sys\r\nimport tweepy\r\nfrom mysettings import *\r\n\r\nif sys.version_info[0] == 2:\r\n\tfrom io import open\r\n\r\ndef main():\r\n\tif len(sys.argv) > 1:\r\n\t\tinput_file_name = sys.argv[1]\r\n\telse:\r\n\t\tinput_file_name = follow_input_file\r\n\twith open(input_file_name) as f:\r\n\t\tauth = tweepy.OAuthHandler(api_key, api_secret)\r\n\t\tauth.set_access_token(access_token, access_token_secret)\r\n\t\tapi = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\r\n\t\tfor user in f:\r\n\t\t\tuser = user.strip()\r\n\t\t\ttry:\r\n\t\t\t\tres = api.create_friendship(screen_name=user)\r\n\t\t\t\tprint('Followed %s' % res.screen_name)\r\n\t\t\texcept tweepy.error.TweepError as e:\r\n\t\t\t\tprint('Error following %s: %s' % (user, e))\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n","sub_path":"Twitter_CSV/follow_file_2.py","file_name":"follow_file_2.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"370930692","text":"from knock20 import getUKtext\nimport re\n\n\nsection_re = re.compile('(?P
    =+)(?P[^=]+)=+')\nfor line in getUKtext().split('\\n'):\n match = section_re.match(line)\n if match is not None:\n name = match.group('name')\n level = len(match.group('section'))\n print('level: {}, name: \"{}\"'.format(level, name))\n","sub_path":"ryosuke/chapter03/knock23.py","file_name":"knock23.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"49136982","text":"from django.db import models\nfrom django.utils.timezone import now\n\n# Create your models here.\n\n\nclass PUser(models.Model):\n\n id = models.AutoField(primary_key=True)\n name = models.CharField(max_length=100)\n email = models.EmailField(max_length=100)\n email_verified_at = models.CharField(max_length=100)\n password = models.CharField(max_length=100)\n created_at = models.DateTimeField(default=now)\n updated_at = models.DateTimeField(default=now)\n\n def __str__(self):\n return self.name\n\n class Meta:\n db_table = \"users\"\n\n\nclass Product(models.Model):\n\n Product_id = models.AutoField(primary_key=True)\n added_by = models.ForeignKey(PUser, on_delete=models.CASCADE)\n qty_in_stock = models.IntegerField()\n product_name = models.CharField(max_length=100)\n product_image = models.CharField(max_length=100)\n created_at = models.DateTimeField(default=now)\n updated_at = models.DateTimeField(default=now)\n\n def __str__(self):\n return self.product_name\n\n class Meta:\n db_table = \"products\"\n\n\nclass Location(models.Model):\n\n location_id = models.AutoField(primary_key=True)\n product_id = models.ForeignKey(\n Product, on_delete=models.CASCADE, related_name='location', null=True, blank=True)\n locate = models.CharField(max_length=200, null=True, blank=True)\n created_at = models.DateTimeField(default=now)\n updated_at = models.DateTimeField(default=now)\n\n def __str__(self):\n return self.locate\n\n class Meta:\n db_table = \"location\"\n\n\nclass ProductMovements(models.Model):\n\n id = models.AutoField(primary_key=True)\n product_id = models.ForeignKey(\n Product, on_delete=models.CASCADE, related_name='movelocation', null=True, blank=True)\n from_location = models.CharField(max_length=100, null=True, blank=True)\n to_location = models.CharField(max_length=100, null=True, blank=True)\n qty_to_be_moved = models.IntegerField(null=True, blank=True)\n\n status = models.IntegerField(null=True, blank=True)\n created_at = models.DateTimeField(default=now)\n updated_at = models.DateTimeField(default=now)\n\n class Meta:\n db_table = \"product_movements\"\n","sub_path":"productManager/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"393132672","text":"#!/usr/bin/env python3\n\n\nimport argparse\n\n\nfrom crfunctions import btcprice\nfrom crfunctions import ltcprice\nfrom crfunctions import ethprice\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--btc', dest='btcprice', help='Displays the current price of Bitcoin.',default=False,\n action='store_true')\nparser.add_argument('--ltc', dest='ltcprice', help='Displays the current price of Litecoin.', default=False,\n action='store_true')\nparser.add_argument('--eth', dest='ethprice', help='Displays the current price of Ethereum.', default=False,\n action='store_true')\nargs = parser.parse_args()\n\nif args.btcprice:\n btcprice()\nelif args.ltcprice:\n ltcprice()\nelif args.ethprice:\n ethprice()\n","sub_path":"cryptorip/cryptorip.py","file_name":"cryptorip.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"388923106","text":"import inspect\nimport os\nimport sys\nimport importlib\nimport re\nimport logging\nimport asyncio\nimport aiohttp\nimport aioredis\nfrom configmaster import YAMLConfigFile\nfrom configmaster.ConfigFile import ConfigFile\n\nfrom . import registry\n\ntry:\n from os import scandir\nexcept ImportError:\n from scandir import scandir\n\nfrom configmaster.ConfigKey import ConfigKey\n\nlogger = logging.getLogger(\"Strouline::Bot\")\n\ncsrf_pat = re.compile(r'\"csrf_token\":\"(.*?)\"')\n\n\nclass DontLoadMe(Exception): pass\n\n\ndef get_caller():\n return inspect.stack()[2][3]\n\n\nclass Bot(object):\n instance = None\n\n def __init__(self, cfg: ConfigKey):\n \"\"\"\n Create a new Strouline bot.\n \"\"\"\n self.config = cfg\n\n self._plugin_config_obj = YAMLConfigFile.YAMLConfigFile(\"plugins.yml\")\n assert isinstance(self._plugin_config_obj, ConfigFile)\n populated = self._plugin_config_obj.initial_populate({\"enabled\": {}})\n if populated:\n self._plugin_config_obj.dump()\n self._plugin_config_obj.reload()\n\n self._plugin_config = self._plugin_config_obj.config\n\n self.token = \"\"\n self.uid = 0\n\n self.http_session = aiohttp.ClientSession()\n self.http_session._connector._verify_ssl = self.config.TLS_UNVERIFY_SURREAL\n self._loop = asyncio.get_event_loop()\n\n self.close_coros = []\n\n self.log_general = logging.getLogger(\"Strouline::Bot\")\n self.log_http = logging.getLogger(\"Strouline::Bot::HTTP\")\n\n self._loop.run_until_complete(self.login())\n\n self.redis_conn = self._loop.run_until_complete(aioredis.create_redis((self.config.redis.host,\n self.config.redis.port)))\n\n def __del__(self):\n self.http_session.close()\n # Prevent spammery on close\n self._loop.set_exception_handler(lambda *args, **kwargs: None)\n\n def add_plugin(self, plugin: str):\n if plugin in self._plugin_config[\"enabled\"]:\n pass\n else:\n self._plugin_config[\"enabled\"][plugin] = True\n\n def allow_plugin(self, plugin: str):\n if plugin not in self._plugin_config[\"enabled\"]:\n return True\n else:\n return self._plugin_config[\"enabled\"][plugin]\n\n def post_handler(self, name):\n \"\"\"\n Decorator for a Post handler\n \"\"\"\n\n def real_dec(func):\n registry.post_rules[name] = func\n return func\n\n return real_dec\n\n def topic_handler(self, name):\n \"\"\"\n Decorator for a Topic handler\n \"\"\"\n\n def real_dec(func):\n registry.topic_rules[name] = func\n return func\n\n return real_dec\n\n def mention_handler(self, name):\n \"\"\"\n Registry for a Mention handler\n \"\"\"\n\n def real_dec(func):\n registry.mention_rules[name] = func\n return func\n\n return real_dec\n\n def no_handler(self, name):\n \"\"\"\n Define a coro that runs, but has no specific handler.\n \"\"\"\n\n def real_dec(func):\n self.create_task(func())\n return func\n\n return real_dec\n\n @asyncio.coroutine\n def post(self, url, *args, **kwargs):\n \"\"\"Post a new message\"\"\"\n self.log_http.debug(\"POST: {}\".format(self.config.nodebb.serv + url))\n req = yield from self.http_session.post(self.config.nodebb.serv + url, *args, **kwargs)\n self.log_http.debug(\"{} {}\".format(req.status, req.reason))\n return req\n\n @asyncio.coroutine\n def put(self, url, *args, **kwargs):\n \"\"\"Post a new message\"\"\"\n req = yield from self.http_session.put(self.config.nodebb.serv + url, *args, **kwargs)\n return req\n\n @asyncio.coroutine\n def delete(self, url, *args, **kwargs):\n \"\"\"Post a new message\"\"\"\n self.log_http.debug(\"DELETE: {}\".format(self.config.nodebb.serv + url))\n req = yield from self.http_session.delete(self.config.nodebb.serv + url, *args, **kwargs)\n self.log_http.debug(\"{} {}\".format(req.status, req.reason))\n return req\n\n @asyncio.coroutine\n def get(self, url, *args, **kwargs):\n \"\"\"Post a new message\"\"\"\n self.log_http.debug(\"GET: {} ({})\".format(self.config.nodebb.serv + url, get_caller()))\n req = yield from self.http_session.get(self.config.nodebb.serv + url, *args, **kwargs)\n self.log_http.debug(\"{} {}\".format(req.status, req.reason))\n return req\n\n @asyncio.coroutine\n def get_api(self, url, *args, uid=None, **kwargs):\n params = kwargs.pop(\"params\", {})\n params.update({\"_uid\": uid or self.uid})\n kwargs[\"params\"] = params\n self.log_http.debug(\"Token: {} / UID: {}\".format(self.token, uid or self.uid))\n return (yield from self.get(\"/api/v1/\" + url, *args, **kwargs))\n\n @asyncio.coroutine\n def get_json(self, url, *args, uid=None, **kwargs) -> dict:\n req = yield from self.get_api(url, *args, uid=uid, **kwargs)\n js = yield from req.json()\n yield from req.release()\n return js\n\n @asyncio.coroutine\n def post_api(self, url, *args, uid=None, **kwargs):\n data = kwargs.pop(\"data\", {})\n data.update({\"_uid\": uid or self.uid})\n kwargs[\"data\"] = data\n self.log_http.debug(\"Token: {} / UID: {}\".format(self.token, uid or self.uid))\n return (yield from self.post(\"/api/v1/\" + url, *args, **kwargs))\n\n @asyncio.coroutine\n def put_api(self, url, *args, uid=None, **kwargs):\n params = kwargs.pop(\"params\", {})\n params.update({\"_uid\": uid or self.uid})\n kwargs[\"params\"] = params\n self.log_http.debug(\"Token: {} / UID: {}\".format(self.token, uid or self.uid))\n return (yield from self.put(\"/api/v1/\" + url, *args, **kwargs))\n\n @asyncio.coroutine\n def delete_api(self, url, *args, uid=None, **kwargs):\n params = kwargs.pop(\"params\", {})\n params.update({\"_uid\": uid or self.uid})\n kwargs[\"params\"] = params\n self.log_http.debug(\"Token: {} / UID: {}\".format(self.token, uid or self.uid))\n return (yield from self.delete(\"/api/v1/\" + url, *args, **kwargs))\n\n def on_close(self, func):\n # Add event to run on close.\n self.close_coros.append(func)\n\n @asyncio.coroutine\n def login(self):\n logger = logging.getLogger(\"Strouline::Login\")\n logger.info(\"Logging into bot account {}\".format(self.config.nodebb.user))\n while True:\n # Get the login page to find the CSRF token.\n login_page = yield from self.get(\"/login\")\n text = (yield from login_page.text())\n # Regex extract it\n try:\n csrf = csrf_pat.findall(text)[0]\n except IndexError:\n pass\n else:\n break\n csrf = csrf.split(',')[0]\n logger.info(\"Got CSRF: {}\".format(csrf))\n res = yield from self.post(\"/login\", data={\"username\": self.config.nodebb.user,\n \"password\": self.config.nodebb.passwd,\n \"remember\": \"on\", \"returnTo\": self.config.nodebb.serv},\n headers={\"x-csrf-token\": csrf})\n yield from res.release()\n if res.status != 200:\n logger.critical(\"Failed to log in to NodeBB. Check your username/password.\")\n logger.critical(\"Status code was {}.\".format(res.status))\n sys.exit(2)\n else:\n logger.info(\"Session cookie set: {}\".format(res.headers[\"SET-COOKIE\"]))\n logger.info(\"Getting our UID...\")\n user_page = yield from self.get(\"/api/user/{}\".format(self.config.nodebb.user))\n user_data = yield from user_page.json()\n yield from user_page.release()\n\n self.uid = int(user_data[\"uid\"])\n logger.info(\"Got UID: {}\".format(self.uid))\n\n logger.info(\"Verifying Write API works...\")\n\n self.token = self.config.nodebb.token\n # Update default ClientSession tokens.\n self.http_session._default_headers[\"Authorization\"] = \"Bearer {}\".format(self.token)\n logger.info(\"Token: {}\".format(self.token))\n logger.info(\"Fetching Strouline user tokens...\")\n tokens = yield from self.get_api(\"/users/{}/tokens\".format(self.uid))\n yield from tokens.release()\n if tokens.status == 200:\n logger.info(\"Strouline logged in correctly.\")\n else:\n logger.critical(\"Strouline failed to log in. Check your API token.\")\n sys.exit(2)\n\n def _on_shutdown(self):\n self._plugin_config_obj.dump()\n\n def run(self):\n from . import tasks\n logger.info(\"Bot entering main loop.\")\n self.create_task(tasks.fetch_new_posts(self))\n logger.info(\"Upon startup, {} tasks pending.\"\n .format(len(asyncio.Task.all_tasks(self._loop))))\n try:\n self._loop.run_forever()\n except (KeyboardInterrupt, EOFError):\n # for coro in self.close_coros:\n # yield from coro()\n logger.info(\"Strouline shutting down.\")\n self._on_shutdown()\n self._loop.stop()\n self._loop.close()\n\n def load_plugins(self):\n \"\"\"\n Load plugins from the cwd/plugins\n \"\"\"\n if not os.path.exists(os.path.join(os.getcwd(), \"plugins\")):\n logger.error(\"No plugin directory.\")\n return\n # Else\n sys.path.insert(0, os.path.join(os.getcwd(), \"plugins\"))\n for fn in scandir(os.path.join(os.getcwd(), \"plugins\")):\n if fn.name == \"__pycache__\":\n continue\n if not fn.name.endswith(\".py\"):\n continue\n logger.info(\"Loading plugin {}\".format(fn))\n try:\n i = importlib.import_module(fn.name.split('.')[0])\n except DontLoadMe:\n logger.info(\"Not loading plugin: {}\".format(fn))\n\n def create_task(self, coro):\n self._loop.create_task(coro)\n","sub_path":"strouline/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":10116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"235016585","text":"# ===============================================================================\n# Copyright 2021 Intel Corporation\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 sklearn.svm import SVR as sklearn_SVR\nfrom sklearn.utils.validation import _deprecate_positional_args\n\nfrom daal4py.sklearn._utils import sklearn_check_version\nfrom onedal.svm import SVR as onedal_SVR\n\nfrom .._device_offload import dispatch, wrap_output_data\nfrom ._common import BaseSVR\n\n\nclass SVR(sklearn_SVR, BaseSVR):\n __doc__ = sklearn_SVR.__doc__\n\n if sklearn_check_version(\"1.2\"):\n _parameter_constraints: dict = {**sklearn_SVR._parameter_constraints}\n\n @_deprecate_positional_args\n def __init__(\n self,\n *,\n kernel=\"rbf\",\n degree=3,\n gamma=\"scale\",\n coef0=0.0,\n tol=1e-3,\n C=1.0,\n epsilon=0.1,\n shrinking=True,\n cache_size=200,\n verbose=False,\n max_iter=-1,\n ):\n super().__init__(\n kernel=kernel,\n degree=degree,\n gamma=gamma,\n coef0=coef0,\n tol=tol,\n C=C,\n epsilon=epsilon,\n shrinking=shrinking,\n cache_size=cache_size,\n verbose=verbose,\n max_iter=max_iter,\n )\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"\n Fit the SVM model according to the given training data.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features) \\\n or (n_samples, n_samples)\n Training vectors, where `n_samples` is the number of samples\n and `n_features` is the number of features.\n For kernel=\"precomputed\", the expected shape of X is\n (n_samples, n_samples).\n\n y : array-like of shape (n_samples,)\n Target values (class labels in classification, real numbers in\n regression).\n\n sample_weight : array-like of shape (n_samples,), default=None\n Per-sample weights. Rescale C per sample. Higher weights\n force the classifier to put more emphasis on these points.\n\n Returns\n -------\n self : object\n Fitted estimator.\n\n Notes\n -----\n If X and y are not C-ordered and contiguous arrays of np.float64 and\n X is not a scipy.sparse.csr_matrix, X and/or y may be copied.\n\n If X is a dense array, then the other methods will not support sparse\n matrices as input.\n \"\"\"\n if sklearn_check_version(\"1.2\"):\n self._validate_params()\n if sklearn_check_version(\"1.0\"):\n self._check_feature_names(X, reset=True)\n dispatch(\n self,\n \"fit\",\n {\n \"onedal\": self.__class__._onedal_fit,\n \"sklearn\": sklearn_SVR.fit,\n },\n X,\n y,\n sample_weight,\n )\n\n return self\n\n @wrap_output_data\n def predict(self, X):\n \"\"\"\n Perform regression on samples in X.\n\n For an one-class model, +1 (inlier) or -1 (outlier) is returned.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n For kernel=\"precomputed\", the expected shape of X is\n (n_samples_test, n_samples_train).\n\n Returns\n -------\n y_pred : ndarray of shape (n_samples,)\n The predicted values.\n \"\"\"\n if sklearn_check_version(\"1.0\"):\n self._check_feature_names(X, reset=False)\n return dispatch(\n self,\n \"predict\",\n {\n \"onedal\": self.__class__._onedal_predict,\n \"sklearn\": sklearn_SVR.predict,\n },\n X,\n )\n\n def _onedal_fit(self, X, y, sample_weight=None, queue=None):\n onedal_params = {\n \"C\": self.C,\n \"epsilon\": self.epsilon,\n \"kernel\": self.kernel,\n \"degree\": self.degree,\n \"gamma\": self.gamma,\n \"coef0\": self.coef0,\n \"tol\": self.tol,\n \"shrinking\": self.shrinking,\n \"cache_size\": self.cache_size,\n \"max_iter\": self.max_iter,\n }\n\n self._onedal_estimator = onedal_SVR(**onedal_params)\n self._onedal_estimator.fit(X, y, sample_weight, queue=queue)\n self._save_attributes()\n\n def _onedal_predict(self, X, queue=None):\n return self._onedal_estimator.predict(X, queue=queue)\n","sub_path":"sklearnex/svm/svr.py","file_name":"svr.py","file_ext":"py","file_size_in_byte":5130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"238095302","text":"# A program to find the simple interest given principal amount, rate of interest and time.\r\ndef simple_interest(principal, rate, time):\r\n print(f\"The principal amount is {principal}\")\r\n print(f\"The rate of interest is {rate}\")\r\n print(f\"The time range is {time} years.\")\r\n si = (principal * rate * time) / 100\r\n print(f\"The Simple Interest is {si}\")\r\n return si\r\n\r\n\r\np = float(input(\"Enter the principal amount: \"))\r\nr = float(input(\"Enter the rate of interest: \"))\r\nt = float(input(\"Enter the time range: \"))\r\nsimple_interest(p, r, t)\r\n","sub_path":"simple_interest.py","file_name":"simple_interest.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"375198853","text":"from eLink.FileManager import FileManager\r\nfrom eLink.elinkScriptUtils import *\r\nfrom apscheduler.schedulers import background\r\nfrom eLink.PowerMeter import *\r\nimport random\r\nfrom datetime import datetime\r\nimport os\r\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\r\n\r\ntry:\r\n import asyncio\r\nexcept ImportError:\r\n import trollius as asyncio\r\n\r\ndefault_elinkvkm = \"10.42.0.101\"\r\nnew_ramdom = random.choice(list(VncMode))\r\naction = \"None\"\r\n\r\ntestScheduler = AsyncIOScheduler()\r\npowermeter = PowerMeterController(name=\"test Power\", port=\"COM13\")\r\n\r\ntestScheduler.start()\r\ncount = 0\r\n\r\n\r\ndef getPowerMeterChannel():\r\n powermeter.sendGetDataChannel(InaChannel.INA1_ID, action)\r\n powermeter.sendGetDataChannel(InaChannel.INA2_ID, action)\r\n\r\n\r\ndef remove_and_upload_file(elinkObj):\r\n filemnger = FileManager(elinkObj)\r\n entry = filemnger.find_entry(\"opencv_world341.dll\")\r\n powermeter.getPowerInfo(vnc_switch_mode.__name__, Action.FILE_TRANSFER, ActionState.ACTION_START)\r\n if entry:\r\n entry.show()\r\n filemnger.remove_file(entry)\r\n filemnger.upload_file(\"E:\\project\\elink-tutorial\\opencv_world341.dll\",\r\n \"/A:\")\r\n entry = filemnger.find_entry(\"opencv_world341.dll\")\r\n if entry:\r\n entry.show()\r\n else:\r\n filemnger.upload_file(\"E:\\project\\elink-tutorial\\opencv_world341.dll\",\r\n \"/A:\")\r\n entry = filemnger.find_entry(\"opencv_world341.dll\")\r\n if entry:\r\n entry.show()\r\n\r\n\r\nasync def vnc_switch_mode():\r\n global count\r\n global new_ramdom\r\n global action\r\n print(\"Test {}\".format(count))\r\n print(\"Enable power\")\r\n\r\n powermeter.sendSetSwChannel(InaChannel.INA1_ID, 0x01)\r\n powermeter.sendSetSwChannel(InaChannel.INA2_ID, 0x01)\r\n\r\n powermeter.getPowerInfo(vnc_switch_mode.__name__, Action.POWER_ON, ActionState.ACTION_START, testcount=count)\r\n\r\n WaitForELinkKVMReady(default_elinkvkm)\r\n elinkObj = elink.newConnection(default_elinkvkm)\r\n sleep(1)\r\n powermeter.getPowerInfo(vnc_switch_mode.__name__, Action.FILE_TRANSFER, ActionState.ACTION_FINISH, testcount=count)\r\n print(\"current mode {}\".format(new_ramdom))\r\n if new_ramdom != VncMode.VNC_MODE_RGB:\r\n ramdom_mode = random.choice(list(VncMode))\r\n while new_ramdom == ramdom_mode:\r\n ramdom_mode = random.choice(list(VncMode))\r\n else:\r\n ramdom_mode = VncMode.VNC_MODE_RGB\r\n elinkObj.setVncMode(ramdom_mode)\r\n powermeter.getPowerInfo(vnc_switch_mode.__name__, Action.SWITCH_MODE_VNC, ActionState.ACTION_START,\r\n detail=\"{}\".format(ramdom_mode), testcount=count)\r\n new_ramdom = ramdom_mode\r\n sleep(5)\r\n elinkObj.close()\r\n sleep(1)\r\n powermeter.getPowerInfo(vnc_switch_mode.__name__, Action.SWITCH_MODE_VNC, ActionState.ACTION_FINISH,\r\n detail=\"{}\".format(ramdom_mode), testcount=count)\r\n powermeter.sendSetSwChannel(InaChannel.INA1_ID, 0x00)\r\n powermeter.sendSetSwChannel(InaChannel.INA2_ID, 0x00)\r\n powermeter.getPowerInfo(vnc_switch_mode.__name__, Action.POWER_OFF, ActionState.ACTION_FINISH, testcount=count)\r\n count += 1\r\n if count >= 20000:\r\n testScheduler.shutdown()\r\n # exit\r\n\r\n\r\nif __name__ == '__main__':\r\n testScheduler.add_job(vnc_switch_mode, 'interval', seconds=6, id=\"test\")\r\n # testScheduler.add_job(getPowerMeterChannel, 'interval', seconds=0.3, max_instances=3)\r\n try:\r\n asyncio.get_event_loop().run_forever()\r\n except (KeyboardInterrupt, SystemExit):\r\n pass\r\n","sub_path":"test/test_switch_vnc_mode.py","file_name":"test_switch_vnc_mode.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"369695524","text":"import os\nimport tempfile\nimport dill\n\nfrom flask import Flask, request, render_template\nfrom werkzeug import secure_filename\n\nimport skimage, skimage.io\nimport numpy as np\n\napp = Flask(__name__)\n\nh_models = dill.load(open('models/h_models.pkl'))\nsv_models = dill.load(open('models/sv_models.pkl'))\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n@app.route(\"/cover\", methods = ['GET', 'POST'])\ndef cover():\n bins = np.arange(9) * (1./8)\n file = request.files['cover']\n if file:\n filename = secure_filename(file.filename)\n rgb = skimage.io.imread(file.stream)\n hsv = skimage.color.convert_colorspace(rgb,'RGB','HSV')\n _,s_mean,v_mean = hsv.mean((0,1))\n _,s_std,v_std = hsv.std((0,1)) \n hues,_ = np.histogram(hsv[:,:,0],bins=bins,density=True)\n # return str(hues)\n predictions = [(sv_models[k].predict_proba([[s_mean,s_std,v_mean,v_std]])[0][1], k) for k in h_models]\n predictions = reversed([(g,p) for p,g in sorted(predictions)][-5:])\n return render_template('results.html', predictions=predictions)\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port, debug=True)","sub_path":"flask/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"442781094","text":"import cv2\n\n\nclass BinaryBlobDetector():\n def __init__(self, maximum_center_offset=31):\n self.params = cv2.SimpleBlobDetector_Params()\n self.params.filterByColor = False\n self.params.filterByArea = False\n self.params.filterByCircularity = False\n self.params.filterByConvexity = False\n self.params.filterByInertia = False\n self.params.minArea = 0\n self.params.maxArea = float('inf')\n self.params.minCircularity = 0\n self.params.maxCircularity = 1\n self.params.minConvexity = 0\n self.params.maxConvexity = 1\n self.params.minInertiaRatio = 0\n self.params.maxInertiaRatio = 1\n # https://stackoverflow.com/questions/59217213/opencv-blob-detector-has-offset-on-found-position\n self.params.minThreshold = 128\n self.params.maxThreshold = 129\n self.params.thresholdStep = 1\n self.params.minRepeatability = 1\n self.maximum_center_offset = maximum_center_offset\n\n self.blob_detector = cv2.SimpleBlobDetector_create(self.params)\n\n def DetectBlobs(self, binary_img):\n keypoints = self.blob_detector.detect(\n 255 - binary_img) # cv2.SimpleBlobDetector expects black blobs on a white background\n\n annotated_img = cv2.cvtColor(binary_img, cv2.COLOR_GRAY2BGR)\n img_shape_HW = binary_img.shape\n\n seedPoint_boundingBox_list = []\n runningNdx = 0\n for kp in keypoints:\n center = (int(round(kp.pt[0])), int(round(kp.pt[1])) )\n fill_color = ((runningNdx * 17) % 256, (runningNdx * 43) % 256, (runningNdx * 57) % 256)\n if fill_color[0] == 0 and fill_color[1] == 0 and fill_color[2] == 0:\n fill_color = (128, 128, 128)\n closest_white_point = self.ClosestWhitePoint(binary_img, center)\n if closest_white_point is not None:\n retval, _, _, bounding_box = cv2.floodFill(annotated_img, mask=None, seedPoint=closest_white_point,\n newVal=fill_color)\n cv2.circle(annotated_img, closest_white_point, 5, (fill_color[0] / 2, fill_color[1] / 2, fill_color[2] / 2),\n thickness=-1)\n runningNdx += 1\n if bounding_box[2] < img_shape_HW[1] or bounding_box[3] < img_shape_HW[0]:\n seedPoint_boundingBox_list.append( (closest_white_point, bounding_box) )\n seedPoint_boundingBox_list = self.RemoveDuplicates(seedPoint_boundingBox_list, annotated_img)\n return seedPoint_boundingBox_list, annotated_img\n\n def ClosestWhitePoint(self, binary_img, point):\n if binary_img[point[1], point[0]] == 255:\n return point\n img_shape_HW = binary_img.shape\n closest_point = None\n for neighborhood_size in range(3, 2 * self.maximum_center_offset + 1, 2):\n neighborhood = [point[0] - neighborhood_size // 2, point[1] - neighborhood_size // 2,\n neighborhood_size, neighborhood_size]\n neighborhood[0] = max(neighborhood[0], 0)\n neighborhood[1] = max(neighborhood[1], 0)\n neighborhood[2] = min(neighborhood_size, img_shape_HW[1] - neighborhood[0])\n neighborhood[3] = min(neighborhood_size, img_shape_HW[0] - neighborhood[1])\n neighborhood_img = binary_img[neighborhood[1]: neighborhood[1] + neighborhood[3],\n neighborhood[0]: neighborhood[0] + neighborhood[2]]\n number_of_nonzero_pixels = cv2.countNonZero(neighborhood_img)\n if number_of_nonzero_pixels > 0:\n for y in range(neighborhood_img.shape[0]):\n for x in range(neighborhood_img.shape[1]):\n if neighborhood_img[y, x] == 255:\n closest_point = (neighborhood[0] + x, neighborhood[1] + y)\n break\n return closest_point\n\n def RemoveDuplicates(self, seedPoint_boundingBox_list, annotated_img):\n cleaned_seedPoint_boundingBox_list = []\n for candidate_seedPoint_boundingBox in seedPoint_boundingBox_list:\n candidate_boundingBox_is_already_present = False\n for already_counted_pair in cleaned_seedPoint_boundingBox_list:\n if already_counted_pair[1] == candidate_seedPoint_boundingBox[1]: # The bounding boxes coincide\n candidate_boundingBox_is_already_present = True\n cv2.circle(annotated_img, candidate_seedPoint_boundingBox[0], 9,\n (0, 0, 255),\n thickness=1)\n break\n if not candidate_boundingBox_is_already_present:\n cleaned_seedPoint_boundingBox_list.append(candidate_seedPoint_boundingBox)\n return cleaned_seedPoint_boundingBox_list","sub_path":"utilities/blob_analysis.py","file_name":"blob_analysis.py","file_ext":"py","file_size_in_byte":4867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"67355116","text":"# ProximitySearch.py\n# THIS CODE WILL DO FUZZY SEARCH FOR SEARCH TERM INSIDE A DATABASE. THE PRECENDENCE OF SEARCH STARTS WITH THE # NARROWEST FILTER WHICH SLOWLY WIDENES UP. THE IDEA IS TO GET TO PERFECT MATCHES BEFORE NEAR MATCHES. EACH # FILTER HAS ITS OWN THRESHOLD CUTOFF.\n\n#IMPORT THE PACKAGES NEEDED\nimport pandas as pd\nfrom fuzzywuzzy import fuzz\nfrom fuzzywuzzy import process\nimport csv\nimport os\n\n\n#DEFINE AND CONFIGURE\nFULL_MATCHING_THRESHOLD = 80\nPARTIAL_MATCHING_THRESHOLD = 100\nSORT_MATCHING_THRESHOLD = 100\nTOKEN_MATCHING_THRESHOLD = 100\nMAX_MATCHES=1\n\n#READ THE CURRENT DATABASE\ncompanies_db = \"C:/Accounts1.csv\"\npwd = os.getcwd()\nos.chdir(os.path.dirname(companies_db))\ncurrent_db_dataframe = pd.read_csv(os.path.basename(companies_db),skiprows=1,index_col=False, names=['Account Name'])\nos.chdir(pwd)\n\ndef find_matches(matchThis):\n rows = current_db_dataframe['Account Name'].values.tolist();\n rows.remove(matchThis)\n matches= process.extractBests(matchThis,rows,scorer=fuzz.ratio,score_cutoff=FULL_MATCHING_THRESHOLD,limit=MAX_MATCHES)\n if len(matches)==0:\n matches= process.extractBests(matchThis,rows,scorer=fuzz.partial_ratio,score_cutoff=PARTIAL_MATCHING_THRESHOLD,limit=MAX_MATCHES);\n if len(matches)==0:\n matches= process.extractBests(matchThis,rows,scorer=fuzz.token_set_ratio,score_cutoff=TOKEN_MATCHING_THRESHOLD,limit=MAX_MATCHES);\n if len(matches)==0:\n matches= process.extractBests(matchThis,rows,scorer=fuzz.token_sort_ratio,score_cutoff=SORT_MATCHING_THRESHOLD,limit=MAX_MATCHES);\n \n return matches[0][0] if len(matches)>0 else None\n\n\nfn_find_matches = lambda x: find_matches(x)\ncurrent_db_dataframe['Duplicate']=current_db_dataframe.applymap(fn_find_matches)\n\ncurrent_db_dataframe.to_csv(\"results.csv\")","sub_path":"dedupe.py","file_name":"dedupe.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"542846130","text":"def bubbleSort(lst):\n n = len(lst)-1\n for i in range(0, n):\n for j in range(n, i, -1):\n if lst[j]max:\n max=a\n maxindex=index\n a = int(input())\n index+=1\nprint(maxindex)","sub_path":"Simple Examples/The index of the maximum of a sequence.py","file_name":"The index of the maximum of a sequence.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"10375383","text":"\nmat = [[1,3,5,8],[4,2,1,7],[4,3,2,3]] # maze\nrow = len(mat)\ncol = len(mat[0])\n\ndp_mat = [-1]*row\nfor i in range(0,row):\n dp_mat[i] = [0]*col\n\n\ndef framer():\n dp_mat[0][0] = mat[0][0]\n for i in range(1, row):\n dp_mat[i][0] = mat[i][0] + dp_mat[i-1][0]\n for i in range(1,col):\n dp_mat[0][i] = mat[0][i] + dp_mat[0][i-1]\n\n\ndef filldp():\n for i in range(1,row):\n for j in range(1,col):\n dp_mat[i][j] = mat[i][j] + min(dp_mat[i-1][j], dp_mat[i][j-1])\n\ndef pathfinder():\n current = [row-1,col-1]\n path = [(current[0], current[1])]\n\n while current != [0,0]:\n if dp_mat[current[0]-1][current[1]] < dp_mat[current[0]][current[1]-1]:\n current[0] -= 1\n else:\n current[1] -= 1\n path.append((current[0], current[1]))\n\n return list(reversed(path))\n\nframer()\nfilldp()\nprint(\"least cost : \", dp_mat[row-1][col-1])\nprint(\"least cost path co-ordinates: \", pathfinder())\n\n'''\ninput :\n3\n\n\n'''\n","sub_path":"least cost path problem.py","file_name":"least cost path problem.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"131447677","text":"#########################################################################\n# File Name: vector.py\n# Author: Jun M\n# mail: warrior97@gmail.com\n# Created Time: Mon 23 Nov 20:52:11 2015\n#########################################################################\n#!/usr/bin/env python\n\n\"\"\"\nImplementation of vectors\n\"\"\"\nimport sys\nimport math\n\nclass Vector(object):\n def __init__(self, args):\n \"\"\" Create a vector with a real number list, example: v = Vector([0.1,2,3]) \"\"\"\n if len(args) == 0:\n self.value = [0.0,0]\n else:\n self.value = args\n\n def add_element(self, element, index = -1):\n \"\"\"add a real/int number to the end of the vector\"\"\"\n if isinstance(element, int) or isinstance(element, float):\n if index == -1:\n self.value.append(element)\n elif len(self.value) >= index:\n self.value.insert(index, element)\n else:\n raise ValueError(\"Out of Index Error\")\n else:\n raise ValueError(\"float or int values needed for vectors\")\n\n def remove_element(self, index):\n \"\"\"remove a element from the vector\"\"\"\n if len(self.value) > index:\n del self.value[index]\n else:\n raise ValueError(\"Out of Index Error\")\n\n\n def add_vec(self, vec):\n \"\"\"add one vector with the current one and return the sum vector.\n If the two vectors have different sizes, raise an ValueError\n exception.\n \"\"\"\n if len(self.value) != len(vec.value):\n raise ValueError(\"the two vectors are not equal in length\")\n else:\n return Vector([x+y for x,y in zip(self.value, vec.value)])\n\n def multiple_num(self, number):\n self.value = [number * x for x in self.value]\n\n def dot_product(self, vec):\n \"\"\"return the dot product of the current vector with another one.\n If the two vectors have different sizes, raise an ValueError\n exception.\n \"\"\"\n if len(self.value) != len(vec.value):\n raise ValueError(\"the two vectors are not equal in length\")\n else:\n return sum([x*y for x,y in zip(self.value, vec.value)])\n\n def set_element(self, element, index):\n \"\"\"\n Set the value of an element at self.value[index]\n \"\"\"\n if isinstance(element, int) or isinstance(element, float):\n if len(self.value) > index:\n self.value[index] = element\n else:\n raise ValueError(\"Out of Index Error\")\n else:\n raise ValueError(\"float or int values needed for vectors\")\n\n def set_vector(self, veclst):\n \"\"\"set the vector of the instance\"\"\"\n self.value = veclst\n\n\ndef main():\n \"\"\"Main entry point for the script.\"\"\"\n pass\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"Python/PythonLearning/pylearn/utils/vector.py","file_name":"vector.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"170954534","text":"import Classes.Query as Query\n\n\nclass QueryRetrievalModel:\n indexReader = []\n\n def __init__(self, ixReader):\n self.indexReader = ixReader\n\n # self.allword = self.indexReader.sumcount() # get the REF\n self.allword = 1864857\n self.result = []\n\n return\n\n # query: The query to be searched for.\n # topN: The maximum number of returned documents.\n # The returned results (retrieved documents) should be ranked by the score (from the most relevant to the least).\n # You will find our IndexingLucene.Myindexreader provides method: docLength().\n # Returned documents should be a list of Document.\n def retrieveQuery(self, query, topN):\n self.probtablesmoo = {}\n postcontainer = {}\n table = {} # the table of each doc and q freq\n container = {}\n newpostlist = []\n postlistlen = {}\n que = query\n que = que.split()\n self.probtable = {}\n result = []\n probabily = {}\n # allword=self.indexReader.sumcount()\n\n for q in que:\n container[q] = {}\n if self.indexReader.DocFreq(q) != 0:\n # print(self.indexReader.DocFreq(q))\n container[q]['total_count'] = self.indexReader.CollectionFreq(q) # total count of this word\n postlist = self.indexReader.getPostingList(q)\n postcontainer[q] = postlist\n container[q]['docfreq'] = self.indexReader.DocFreq(q)\n else:\n container[q]['total_count'] = 1\n postcontainer[q] = {}\n container[q]['docfreq'] = {}\n\n for q in postcontainer:\n for lis in postcontainer[q]:\n newpostlist.append(lis)\n\n newpostlist = list(set(newpostlist))\n\n for doc in newpostlist:\n postlistlen[doc] = self.indexReader.getDocLength(doc) # store the length of each doc\n # print(postlistlen)\n\n for doc in newpostlist:\n table[doc] = {}\n for q in container:\n table[doc][q] = postcontainer[q].get(doc, 0)\n # table[doc][lenght] = self.indexReader.\n\n # smooth table\n # table is like the matrix in exam\n for doc in table:\n self.probtable[doc] = {}\n lendoc = postlistlen[doc]\n for q in table[doc]:\n countword = table[doc].get(q)\n totalkeyword = container[q]['total_count']\n self.probtable[doc][q] = self.smooth(lendoc, countword, totalkeyword)\n self.probtablesmoo = self.probtable\n\n for doc in self.probtable:\n prob = 1.0\n for q in self.probtable[doc]:\n prob *= self.probtable[doc].get(q)\n probabily[doc] = prob\n\n newprob = sorted(probabily.items(), key=lambda d: d[1], reverse=True) # sort the rank list\n\n results = newprob[:topN]\n for r in results:\n resultq = Query.Query()\n docNo = self.indexReader.getDocNo(r[0])\n resultq.setDocNo(docNo)\n resultq.setScore(r[1])\n\n result.append(resultq)\n\n return result\n\n # smooth method\n def smooth(self, lendoc, countword, totalkeyword):\n miu = 500\n newprob = (countword + miu * (totalkeyword / self.allword)) / (lendoc + miu)\n return newprob\n\n def smoothprob(self):\n #print(self.probtablesmoo.keys())\n return self.probtablesmoo","sub_path":"IR_finalproject/PseudoRFSearch/QueryRetrievalModel.py","file_name":"QueryRetrievalModel.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"354441911","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2020-2021 TU Wien.\n#\n# Invenio-Keycloak is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Pre-defined defaults and helpers for Invenio-Keycloak configuration.\"\"\"\n\n\nclass KeycloakSettingsHelper:\n \"\"\"Helper for creating REMOTE_APP configuration dictionaries for Keycloak.\n\n This class can be used to easily create a base configuration with sensible\n defaults for a default-ish Keycloak setup.\n It requires knowledge about the base URL of the Keycloak instance and the\n realm on which the Invenio client application is configured.\n Because the default endpoint URLs follow a simple schema, this information\n can be used to create a simple base configuration.\n\n The methods ``remote_app()`` and ``remote_rest_app()`` create and return\n a dictionary in the form expected by Invenio-OAuthClient.\n The latter can be used for providing SSO capabilities to SPAs communicating\n with Invenio via the REST API.\n\n Further, the helper provides some properties for commonly used default\n endpoint URLs.\n \"\"\"\n\n def __init__(self, base_url, realm):\n \"\"\"The constructor takes two arguments.\n\n :param base_url: The base URL on which Keycloak is running\n (e.g. \"http://localhost:8080\")\n :param realm: Realm in which the invenio client application is defined\n \"\"\"\n self.base_url = base_url\n self.realm = realm\n self._access_token_url = self.make_url(\"token\")\n self._authorize_url = self.make_url(\"auth\")\n self._user_info_url = self.make_url(\"userinfo\")\n self._realm_url = self.make_realm_url()\n\n @property\n def access_token_url(self):\n \"\"\"URL for the access token endpoint.\"\"\"\n return self._access_token_url\n\n @property\n def authorize_url(self):\n \"\"\"URL for the authorization endpoint.\"\"\"\n return self._authorize_url\n\n @property\n def user_info_url(self):\n \"\"\"URL for the user info endpoint.\"\"\"\n return self._user_info_url\n\n @property\n def realm_url(self):\n \"\"\"URL for the realm's endpoint.\"\"\"\n return self._realm_url\n\n def make_realm_url(self):\n \"\"\"Create a URL pointing towards the Keycloak realm.\"\"\"\n base_url = self.base_url.rstrip(\"/\")\n return \"{}/auth/realms/{}\".format(base_url, self.realm)\n\n def make_url(self, endpoint):\n \"\"\"Create an endpoint URL following the default Keycloak URL schema.\n\n :param endpoint: The endpoint to use (e.g. \"auth\", \"token\", ...)\n \"\"\"\n return \"{}/protocol/openid-connect/{}\" \\\n .format(self.make_realm_url(), endpoint)\n\n def remote_app(self):\n \"\"\"Create a KEYCLOAK_REMOTE_APP using the given base URL and realm.\"\"\"\n return dict(\n title=\"Keycloak\",\n description=\"Your local keycloak installation\",\n icon=\"\",\n\n authorized_handler=\"invenio_oauthclient.handlers\"\n \":authorized_signup_handler\",\n disconnect_handler=\"invenio_oauthclient.contrib.keycloak.handlers\"\n \":disconnect_handler\",\n signup_handler=dict(\n info=\"invenio_oauthclient.contrib.keycloak.handlers\"\n \":info_handler\",\n setup=\"invenio_oauthclient.contrib.keycloak.handlers\"\n \":setup_handler\",\n view=\"invenio_oauthclient.handlers:signup_handler\"\n ),\n\n params=dict(\n base_url=self.base_url,\n\n request_token_params={\"scope\": \"openid\"},\n request_token_url=None,\n\n access_token_url=self.access_token_url,\n access_token_method=\"POST\",\n\n authorize_url=self.authorize_url,\n app_key=\"KEYCLOAK_APP_CREDENTIALS\",\n )\n )\n\n def remote_rest_app(self):\n \"\"\"Crete a KEYCLOAK_REMOTE_REST_APP using the given configuration.\"\"\"\n return self.remote_app().update(dict(\n authorized_handler=\"invenio_oauthclient.handlers.rest\"\n \":authorized_signup_handler\",\n disconnect_handler=\"invenio_oauthclient.contrib.keycloak.handlers\"\n \":disconnect_rest_handler\",\n signup_handler=dict(\n info=\"invenio_oauthclient.contrib.keycloak.handlers\"\n \":info_handler\",\n setup=\"invenio_oauthclient.contrib.keycloak.handlers\"\n \":setup_handler\",\n view=\"invenio_oauthclient.handlers.rest:signup_handler\"\n ),\n\n response_handler=(\n \"invenio_oauthclient.handlers.rest\"\n \":default_remote_response_handler\"\n ),\n\n authorized_redirect_url=\"/\",\n disconnect_redirect_url=\"/\",\n signup_redirect_url=\"/\",\n error_redirect_url=\"/\"\n ))\n\n\nhelper = KeycloakSettingsHelper(\"https://locahost:8080\", \"invenio\")\nOAUTHCLIENT_KEYCLOAK_REALM_URL = helper.realm_url\nOAUTHCLIENT_KEYCLOAK_USER_INFO_URL = helper.user_info_url\nOAUTHCLIENT_KEYCLOAK_REMOTE_APP = helper.remote_app()\nOAUTHCLIENT_KEYCLOAK_REMOTE_REST_APP = helper.remote_rest_app()\nOAUTHCLIENT_KEYCLOAK_VERIFY_AUD = True\nOAUTHCLIENT_KEYCLOAK_VERIFY_EXP = True\nOAUTHCLIENT_KEYCLOAK_AUD = \"invenio\"\n","sub_path":"invenio_oauthclient/contrib/keycloak/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"581854439","text":"num = {'One': 'Один', 'Two': 'Два', 'Three': 'Три', 'Four': 'Четыре'}\nnew_file = []\nwith open(\"task_4_text.txt\") as f_obj:\n content = f_obj.read()\n print(f'Изначальное содержимое: \\n{content}')\n f_obj.seek(0)\n for i in f_obj:\n i = i.split(' ', 1)\n new_file.append(num[i[0]] + ' ' + i[1])\n print(f'Содержимое для нового файла: {new_file} успешно записано в файл task_4_text_new.txt')\n\nwith open('task_4_text_new.txt', 'w') as f_obj_2:\n f_obj_2.writelines(new_file)\n","sub_path":"homework_5/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"244957463","text":"from flask import Flask, render_template, request, redirect,url_for\nimport userdb\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_world():\n return redirect(url_for('index'))\n\n@app.route('/index')\ndef index():\n task_list = userdb.task_list()\n maxlength = 0\n for task in task_list:\n if not task['todo']:\n print(\"Empty object\")\n if len(task['todo']) > maxlength:\n maxlength = len(task['todo'])\n if maxlength > 0:\n maxlength += 20\n return render_template(\"index.html\", task_list=task_list, row_length=maxlength)\n\n\n@app.route('/insert_page', methods=['POST'])\ndef insert_page():\n new_task = request.form['task']\n if request.form['urgent'] == \"true\":\n urgent = True\n else:\n urgent = False\n userdb.insert_task(new_task, urgent)\n return redirect(url_for('index'))\n\n\n@app.route('/delete_page/')\ndef delete_page(id_task):\n userdb.delete_task(id_task)\n return redirect(url_for('index'))\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"640597693","text":"import pathlib\nimport re\n\nimport setuptools\n\n\nPROJECT_ROOT = pathlib.Path(__file__).parent\n\nwith open(PROJECT_ROOT / \"requirements.in\") as f:\n INSTALL_REQUIRES = f.read().splitlines()\n\nwith open(PROJECT_ROOT / \"dev-requirements.in\") as f:\n DEV_INSTALL_REQUIRES = f.read().splitlines()\n\nsetuptools.setup(\n name=\"mario\",\n version=\"0.0.122\",\n description=\"Shell pipes for Python.\",\n long_description=open(PROJECT_ROOT / \"README.rst\").read(),\n long_description_content_type=\"text/x-rst\",\n author=\"mario contributors\",\n author_email=\"mario@example.com\",\n packages=setuptools.find_packages(\"src\"),\n package_dir={\"\": \"src\"},\n url=\"https://github.com/python-mario/mario\",\n include_package_data=True,\n zip_safe=False,\n classifiers=[\n # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"Operating System :: Unix\",\n \"Operating System :: POSIX\",\n \"Operating System :: Microsoft :: Windows\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Programming Language :: Python :: Implementation :: PyPy\",\n \"Topic :: Utilities\",\n ],\n keywords=[\n # eg: 'keyword1', 'keyword2', 'keyword3',\n ],\n python_requires=\">=3.7\",\n install_requires=INSTALL_REQUIRES,\n entry_points={\n \"console_scripts\": [\"mario = mario.cli:cli\"],\n \"mario_plugins\": [\"basic = mario.plugins\"],\n },\n extras_require={\"dev\": DEV_INSTALL_REQUIRES},\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"244248944","text":"import cv2\nimport numpy as np\nfrom PIL import Image\nimport pytesseract\nimport os\nimport cv2\nimport scipy.misc as misc\nimport matplotlib.pyplot as plt\nimport time\nfrom skimage import io, filters\nfrom numpy import linalg as LA\n\nfrom imutils import perspective\nfrom imutils import contours\nimport imutils\nimport argparse\n\nfrom fuzzywuzzy import fuzz\nimport difflib\nfrom nltk.util import ngrams\nfrom nltk.corpus import udhr\nfrom skimage.data import page\nfrom skimage.filters import (threshold_sauvola)\n\ndef four_point_transform(image, pts):\n\trect = order_points_old(pts)\n\t(tl, tr, br, bl) = rect\n\n\twidthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))\n\twidthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))\n\tmaxWidth = max(int(widthA), int(widthB))\n\n\theightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))\n\theightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))\n\tmaxHeight = max(int(heightA), int(heightB))\n\n\n\tdst = np.array([\n\t\t[0, 0],\n\t\t[maxWidth - 1, 0],\n\t\t[maxWidth - 1, maxHeight - 1],\n\t\t[0, maxHeight - 1]], dtype = \"float32\")\n\n\t# compute the perspective transform matrix and then apply it\n\tM = cv2.getPerspectiveTransform(rect, dst)\n\twarped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))\n\n\t# return the warped image\n\treturn warped\n\ndef order_points_old(pts):\n # initialize a list of coordinates that will be ordered\n # such that the first entry in the list is the top-left,\n # the second entry is the top-right, the third is the\n # bottom-right, and the fourth is the bottom-left\n rect = np.zeros((4, 2), dtype=\"float32\")\n\n # the top-left point will have the smallest sum, whereas\n # the bottom-right point will have the largest sum\n s = pts.sum(axis=1)\n rect[0] = pts[np.argmin(s)]\n rect[2] = pts[np.argmax(s)]\n\n # now, compute the difference between the points, the\n # top-right point will have the smallest difference,\n # whereas the bottom-left will have the largest difference\n diff = np.diff(pts, axis=1)\n rect[1] = pts[np.argmin(diff)]\n rect[3] = pts[np.argmax(diff)]\n\n # return the ordered coordinates\n return rect\n\ncap = cv2.VideoCapture(0)\nwhile(1):\n ret, frame = cap.read()\n \n cv2.imshow(\"image\",frame)\n if not ret:\n break\n k = cv2.waitKey(1)\n if k%256 == 27:\n # ESC pressed\n print(\"Escape hit, closing...\")\n break\n elif k%256 == 32:\n cv2.imwrite(\"image27.png\",frame)\n cv2.imshow(\"image\",frame)\n #frame=cv2.imread(name)\n #frame = cv2.resize(frame,(400,600))\n cv2.imwrite(\"resized.png\",frame)\n img=Image.open(\"resized.png\")\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n # fluroscent pink\n '''\n lower_bound = np.array([151,100,100]) \n upper_bound = np.array([171,255,255])'''\n # fluroscent yellow\n lower_bound = np.array([20,100,100]) \n upper_bound = np.array([40,255,255])\n mask = cv2.inRange(hsv, lower_bound, upper_bound)\n res = cv2.bitwise_and(frame,frame, mask= mask)\n median = cv2.medianBlur(res,15)\n cv2.imwrite(\"median.png\",median)\n grayscaled = cv2.cvtColor(median,cv2.COLOR_BGR2GRAY)\n ret,thresh = cv2.threshold(grayscaled,10,255,cv2.THRESH_BINARY)\n edged = cv2.Canny(thresh, 30, 150)\n #cv2.imwrite('mask.png',mask)\n (_, cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\n frame_copy=frame\n cv2.drawContours(frame_copy, cnts[0], -1, (0,255,0), 3)\n cv2.imshow(\"input\",frame_copy)\n BlackPixelMatrix=cnts[0]\n '''minCol=cnts[0][0][0][0]\n maxCol=cnts[0][0][0][0]\n minRow=cnts[0][0][0][1]\n maxRow=cnts[0][0][0][1]\n\n for j in range(0,len(cnts[0])):\n if(minCol>(cnts[0][j][0][0])):\n minCol=cnts[0][j][0][0]\n if(maxCol<(cnts[0][j][0][0])):\n maxCol=cnts[0][j][0][0]\n if(minRow>(cnts[0][j][0][1])):\n minRow=cnts[0][j][0][1]\n if(maxRow<(cnts[0][j][0][1])):\n maxRow=cnts[0][j][0][1]\n \n #print(\"minCol : {} ,maxCol : {} , minRow : {} , maxRow : {} \".format(minCol,maxCol,minRow,maxRow))\n mask1=Image.open(\"resized.png\")\n newmask=mask1.crop((minCol-20,minRow-20,maxCol+20,maxRow+20))\n newmask=newmask.convert(\"RGB\")\n newmask.save(\"masked.png\")\n mask2=cv2.imread(\"masked.png\")\n newmask=mask2\n col,row,_=newmask.shape\n print(newmask.shape)\n print(\"col : {} ,row : {} \" .format(col,row))\n for rw in range(0,row-1):\n for c in range(0,col-1):\n b=newmask[c][rw][0]\n g=newmask[c][rw][1]\n r=newmask[c][rw][2]\n if(b<12):\n if(g<150):\n if(r<125):\n #print(\"pixel value : {} {} {}\" .format(b,g,r))\n newmask[c][rw]=[0,0,0]\n else:\n newmask[c][rw]=[255,255,255]\n else:\n newmask[c][rw]=[255,255,255]\n else:\n newmask[c][rw]=[255,255,255]\n\n cv2.imshow(\"changed image\",newmask)\n white_bgd_img=newmask\n\n \n BlackPixelMatrix=[]\n #trial_image=cv2.imread(\"trial_image.png\")\n #(row,col,_)=trial_image.shape\n (row,col,_)=white_bgd_img.shape\n for x in range (0,row-1):\n for z in range(0,col-1):\n if (np.all((white_bgd_img[x,z]==[0,0,0]))):\n BlackPixelMatrix.append([x,z])'''\n\n BlackPixelMatrix=np.array(BlackPixelMatrix)\n x=[]\n y=[]\n for h in range (len(BlackPixelMatrix)-1):\n x.append(BlackPixelMatrix[h][0][0])\n y.append(BlackPixelMatrix[h][0][1])\n x = x - np.mean(x)\n y = y - np.mean(y)\n coords = np.vstack([x, y])\n cov = np.cov(coords)\n evals, evecs = np.linalg.eig(cov)\n sort_indices = np.argsort(evals)[::-1]\n evec1, evec2 = evecs[:, sort_indices]\n x_v1, y_v1 = evec1 # Eigenvector with largest eigenvalue\n x_v2, y_v2 = evec2\n theta = np.rad2deg((np.arctan((y_v1)/(x_v1))))\n theta2 = np.rad2deg((np.arctan((y_v2)/(x_v2))))\n print(\"theta : {} , {}\" .format(theta,theta2))\n RotateImg1 = img.rotate((0-theta))\n RotateImg1.save(\"RotatedImage\"+\".jpg\")\n rotated=cv2.imread(\"RotatedImage.jpg\")\n cv2.imshow(\"Rotated Image\",rotated)\n hsv = cv2.cvtColor(rotated, cv2.COLOR_BGR2HSV)\n mask = cv2.inRange(hsv, lower_bound, upper_bound)\n res = cv2.bitwise_and(rotated,rotated, mask= mask)\n median3 = cv2.medianBlur(res,15)\n grayscaled = cv2.cvtColor(median3,cv2.COLOR_BGR2GRAY)\n ret,thresh = cv2.threshold(grayscaled,10,255,cv2.THRESH_BINARY)\n edged = cv2.Canny(thresh, 30, 150)\n (_, cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\n frame_copy=frame\n cv2.drawContours(frame_copy, cnts[0], -1, (0,255,0), 3)\n cv2.imshow(\"input\",frame_copy)\n BlackPixelMatrix2=cnts[0]\n BlackPixelMatrix2=np.array(BlackPixelMatrix2)\n x2=[]\n y2=[]\n for h in range (len(BlackPixelMatrix2)-1):\n x2.append(BlackPixelMatrix2[h][0][0])\n y2.append(BlackPixelMatrix2[h][0][1])\n x2 = x2 - np.mean(x)\n y2 = y2 - np.mean(y)\n coords2 = np.vstack([x2, y2])\n cov2 = np.cov(coords2)\n evals2, evecs2 = np.linalg.eig(cov2)\n sort_indices2 = np.argsort(evals2)[::-1]\n evec1_2, evec2_2 = evecs2[:, sort_indices2]\n x_v1, y_v1 = evec1_2 # Eigenvector with largest eigenvalue\n x_v2, y_v2 = evec2_2\n theta_2 = np.rad2deg((np.arctan((y_v1)/(x_v1))))\n theta2_2 = np.rad2deg((np.arctan((y_v2)/(x_v2))))\n print(\"theta2 : {} , {}\" .format(theta_2,theta2_2))\n if(abs(theta_2)>5):\n RotateImg2 = img.rotate((0-theta2))\n RotateImg2.save(\"RotatedImage\"+\".jpg\")\n rotated=cv2.imread(\"RotatedImage.jpg\")\n cv2.imshow(\"Rotated Image2\",rotated)\n \n ###########TILT################\n frame=rotated\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-n\", \"--new\", type=int, default=-1,\n help=\"whether or not the new order points should should be used\")\n args = vars(ap.parse_args())\n hsv = cv2.cvtColor(rotated, cv2.COLOR_BGR2HSV)\n mask = cv2.inRange(hsv, lower_bound, upper_bound)\n res = cv2.bitwise_and(rotated,rotated, mask= mask)\n median3 = cv2.medianBlur(res,15)\n grayscaled = cv2.cvtColor(median3,cv2.COLOR_BGR2GRAY)\n ret,thresh = cv2.threshold(grayscaled,10,255,cv2.THRESH_BINARY)\n edged = cv2.Canny(thresh, 30, 150)\n edged_cp=edged\n # find contours in the edge map\n (_,cnts,_) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n #cnts = cnts[0] if imutils.is_cv2() else cnts[1]\n #print(cnts)\n cv2.imshow(\"cnt1\",edged_cp)\n '''newCnts=cnts\n cnt_len_list=[]\n max_len_index=0 \n if(len(newCnts)>2):\n for h in range(0,(len(newCnts)-2)):\n \n if((len(newCnts[max_len_index]))<(len(newCnts[h+1]))):\n max_len_index=h+1;\n \n else:\n if(len(newCnts)==2):\n if(len(newCnts[0]) \"ProjectBuildRequests\":\n build_requests = ProjectBuildRequests()\n library_projects = projects.library_projects\n build_requests.extend(\n [\n ProjectBuildRequest(project=project)\n for project in library_projects\n if project.needs_build\n ]\n )\n return build_requests\n\n @staticmethod\n def standard_projects(projects: Projects) -> \"ProjectBuildRequests\":\n build_requests = ProjectBuildRequests()\n build_requests.extend(\n [\n ProjectBuildRequest(project=project)\n for project in projects.standard_projects\n if project.needs_build\n ]\n )\n return build_requests\n\n @property\n def success(self) -> bool:\n return len(self) == 0 or all([request.run_successful for request in self])\n\n @property\n def failed(self) -> \"ProjectBuildRequests\":\n return ProjectBuildRequests(\n [request for request in self if request.run_successful is False]\n )\n\n\nclass BuildExecutor:\n def execute_builds(\n self, project_build_requests: ProjectBuildRequests\n ) -> ProjectBuildRequests:\n for project_build_request in project_build_requests:\n self.run_build(project_build_request)\n if project_build_request.project.project_type == ProjectType.Library:\n InstallerManager().copy_installer_to_shared_folder(\n project_build_request\n )\n return project_build_requests\n\n def run_build(self, project_build_request: ProjectBuildRequest):\n write_to_console(\n f\"{project_build_request.project.name} Building\", color=\"blue\", bold=True\n )\n if not project_build_request.project.needs_build:\n project_build_request.build_status = BuildRequestStatus.NotNeeded\n write_to_console(\"Build not needed\")\n return\n\n InstallerManager().copy_installers_to_project(project_build_request.project)\n result = subprocess.run(\n [\"./build.sh\"], cwd=project_build_request.project.project_path\n )\n project_build_request.build_status = BuildRequestStatus.Complete\n project_build_request.run_successful = result.returncode == 0\n\n\nclass InstallerManager:\n def __init__(self):\n self._s3_bucket = None\n\n def copy_installer_to_shared_folder(\n self, project_build_request: ProjectBuildRequest\n ):\n configuration = ConfigurationManager.get()\n dist_folder = f\"{project_build_request.project.project_path}/{configuration.project_distributable_folder}\"\n for installer in Path(dist_folder).iterdir():\n if configuration.installer_location_type == InstallerLocationType.folder:\n shutil.copy(str(installer), configuration.installer_folder)\n if configuration.installer_location_type == InstallerLocationType.s3:\n self._get_s3_bucket(configuration).upload_file(\n str(installer), installer.name\n )\n\n def _get_s3_bucket(self, configuration: Configuration):\n if not self._s3_bucket:\n self._s3_bucket = boto3.client(\"s3\").Bucket(\n configuration.installer_s3_bucket\n )\n return self._s3_bucket\n\n def copy_installers_to_project(self, project: Project):\n configuration = ConfigurationManager.get()\n project_installer_folder = os.path.join(\n project.project_path, configuration.installer_folder\n )\n if configuration.installer_location_type == InstallerLocationType.folder:\n shutil.copytree(configuration.installer_folder, project_installer_folder)\n if configuration.installer_location_type == InstallerLocationType.s3:\n bucket = self._get_s3_bucket(configuration)\n for file in bucket.objects:\n bucket.download_file(\n file.key, os.path.join(project_installer_folder, file.key)\n )\n","sub_path":"monorepo_builder/build_executor.py","file_name":"build_executor.py","file_ext":"py","file_size_in_byte":4985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"17713973","text":"import io\nimport xlsxwriter\n\n\ndef WriteToExcel(pricing_data, product=None):\n output = io.BytesIO()\n workbook = xlsxwriter.Workbook(output)\n\n # Here we will adding the code to add data\n worksheet_s = workbook.add_worksheet(\"Pricing Summary\")\n\n # excel styles\n title = workbook.add_format({\n 'bold': True,\n 'font_size': 14,\n 'align': 'center',\n 'valign': 'vcenter'\n })\n header = workbook.add_format({\n 'bg_color': '#F7F7F7',\n 'color': 'black',\n 'align': 'center',\n 'valign': 'top',\n 'border': 1\n })\n\n workbook.close()\n xlsx_data = output.getvalue()\n # xlsx_data contains the Excel file\n return xlsx_data","sub_path":"upload/excel_utils.py","file_name":"excel_utils.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"252756254","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\n# Licensed under the Open Software License (\"OSL\") v. 3.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.opensource.org/licenses/osl-3.0.php\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 re\n\nfrom pmock import *;\n\nfrom pyccuracy.drivers.core.selenium_driver import SeleniumDriver\nfrom pyccuracy.drivers import DriverError\nfrom pyccuracy.common import Context, Settings\nfrom utils import assert_raises\n\ndef test_can_create_selenium_browser_driver():\n context = Context(Settings())\n driver = SeleniumDriver(context)\n\n assert driver is not None\n\ndef test_selenium_driver_keeps_context():\n context = Context(Settings())\n driver = SeleniumDriver(context)\n\n assert driver.context == context\n\ndef test_selenium_driver_overrides_start_test_properly():\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(once()).start()\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n\n driver.start_test(\"http://localhost\")\n selenium_mock.verify()\n\ndef test_selenium_driver_overrides_start_test_properly_when_extra_args_specified():\n context = Context(Settings())\n context.settings.extra_args = {\n \"selenium.server\":\"localhost\",\n \"selenium.port\":4444\n }\n selenium_mock = Mock()\n selenium_mock.expects(once()).start()\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n\n driver.start_test(\"http://localhost\")\n selenium_mock.verify()\n\ndef test_selenium_driver_raises_on_start_test_when_selenium_cant_start():\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(once()).start().will(raise_exception(DriverError(\"invalid usage\")))\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n\n assert_raises(DriverError, driver.start_test, url=\"http://localhost\", exc_pattern=re.compile(r\"Error when starting selenium. Is it running ?\"))\n selenium_mock.verify()\n\ndef test_selenium_driver_calls_proper_selenese_on_stop_test():\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(once()).stop()\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n\n driver.stop_test()\n selenium_mock.verify()\n\ndef test_selenium_driver_overrides_page_open_properly():\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(once()).open(eq(\"http://localhost\"))\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n\n driver.page_open(\"http://localhost\")\n selenium_mock.verify()\n\ndef test_selenium_resolve_element_key_returns_element_key_for_null_context():\n driver = SeleniumDriver(None)\n assert driver.resolve_element_key(None, \"button\", \"SomethingElse\") == \"SomethingElse\"\n\ndef test_selenium_resolve_element_key_uses_SeleniumElementSelector_for_non_null_contexts():\n context = Context(Settings())\n driver = SeleniumDriver(context)\n key = driver.resolve_element_key(context, \"Button\", \"SomethingElse\")\n expected = \"//*[(@name='SomethingElse' or @id='SomethingElse')]\"\n assert key == expected, \"Expected %s, Actual: %s\" % (expected, key)\n\ndef test_selenium_driver_calls_proper_selenese_on_wait_for_page():\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(once()).wait_for_page_to_load(eq(10000))\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n\n driver.wait_for_page()\n selenium_mock.verify()\n\ndef test_selenium_driver_calls_proper_selenese_on_click_element():\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(once()).click(eq(\"some\"))\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n\n driver.click_element(\"some\")\n selenium_mock.verify()\n\ndef test_selenium_driver_calls_proper_selenese_on_get_title():\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(once()).get_title().will(return_value(\"Some title\"))\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n\n title = driver.get_title()\n assert title == \"Some title\"\n selenium_mock.verify()\n \ndef test_selenium_driver_calls_get_eval():\n javascript = \"some javascript\"\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(once()).get_eval(eq(javascript)).will(return_value(\"ok\"))\n \n driver = SeleniumDriver(context, selenium=selenium_mock)\n \n assert driver.exec_js(javascript) == \"ok\"\n\ndef test_selenium_driver_calls_type_keys():\n input_selector = \"//some_xpath\"\n text = \"text to type\"\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(once()).type_keys(eq(input_selector), eq(text))\n \n driver = SeleniumDriver(context, selenium=selenium_mock)\n driver.type_keys(input_selector, text)\n selenium_mock.verify()\n\ndef test_wait_for_presence():\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(once()).is_element_present(eq('some element')).will(return_value(True))\n selenium_mock.expects(once()).is_visible(eq('some element')).will(return_value(True))\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n driver.wait_for_element_present(\"some element\", 1)\n selenium_mock.verify()\n\ndef test_wait_for_presence_works_even_when_is_visible_raises():\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(at_least_once()).is_element_present(eq('some element')).will(return_value(True))\n selenium_mock.expects(once()).is_visible(eq('some element')).will(raise_exception(Exception(\"ERROR: Element some element not found\"))).id(\"is_visible #1\")\n selenium_mock.expects(once()).is_visible(eq('some element')).will(return_value(True)).after(\"is_visible #1\")\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n driver.wait_for_element_present(\"some element\", 1)\n selenium_mock.verify()\n\ndef test_wait_for_disappear():\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(once()).is_element_present(eq('some element')).will(return_value(True))\n selenium_mock.expects(once()).is_visible(eq('some element')).will(return_value(False))\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n driver.wait_for_element_to_disappear(\"some element\", 1)\n selenium_mock.verify()\n\ndef test_wait_for_disappear_works_even_when_is_visible_raises():\n context = Context(Settings())\n selenium_mock = Mock()\n selenium_mock.expects(at_least_once()).is_element_present(eq('some element')).will(return_value(True))\n selenium_mock.expects(once()).is_visible(eq('some element')).will(raise_exception(Exception(\"ERROR: Element some element not found\")))\n\n driver = SeleniumDriver(context, selenium=selenium_mock)\n driver.wait_for_element_to_disappear(\"some element\", 1)\n selenium_mock.verify()\n\n","sub_path":"tests/unit/test_selenium_browser_driver.py","file_name":"test_selenium_browser_driver.py","file_ext":"py","file_size_in_byte":7299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"13369687","text":"import copy\n\nimport numpy as np\n\nfrom .simple_arithmetic_crossover import simple_arithmetic_crossover\nfrom .single_arithmetic_crossover import single_arithmetic_crossover\nfrom .whole_arithmetic_crossover import whole_arithmetic_crossover\n\n\ndef crossover(pool, crossover_probability, crosspoint, crossover_method, alpha):\n new_pool = []\n\n # each crossover generates 2 offspring\n num_children = len(pool) // 2\n\n for _ in range(num_children):\n parent1 = np.random.choice(pool)\n parent2 = np.random.choice(pool)\n child1 = copy.deepcopy(parent1)\n child2 = copy.deepcopy(parent2)\n\n num_cells_non_fixed = len(parent1.get_cells(\"non_fixed\"))\n if crossover_method == \"simple_arithmetic\":\n for i in range(crosspoint + 1, num_cells_non_fixed):\n simple_arithmetic_crossover(child1.get_cells(\"non_fixed\")[i],\n child2.get_cells(\"non_fixed\")[i],\n alpha)\n\n elif crossover_method == \"single_arithmetic\":\n single_arithmetic_crossover(child1, child2, alpha)\n\n elif crossover_method == \"whole_arithmetic\":\n for i in range(num_cells_non_fixed):\n whole_arithmetic_crossover(child1.get_cells(\"non_fixed\")[i],\n child2.get_cells(\"non_fixed\")[i],\n alpha)\n\n new_pool.append(child1)\n new_pool.append(child2)\n\n return new_pool\n","sub_path":"files/crossover/crossover.py","file_name":"crossover.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"272278727","text":"# -*- codeing = utf-8 -*-\n# @Time : 2021/3/23 14:50\n# @Author : 水印红枫\n# @Software: PyCharm\n\nfrom bs4 import BeautifulSoup # 网页解析获取数据\nimport re # 正则表达式,进行文字匹配\nimport urllib.request, urllib.error, urllib.parse # 指定url获取网络数据\nimport xlwt # 进行excel操作\nimport sqlite3 # 进行数据库操作\nimport json\nimport time\n# findImgSrc = re.compile(r' threshold\n\n\ndef test_rnn():\n \n ds = DataSet(features.mfcc_spec, data_path='data/', shuffle=True, balance=True, categorical=True)\n \n r = RNN1()\n\n epochs_count = 1\n\n history, net, clf = train(ds.X_train, ds.y_train, ds.X_test, ds.y_test, r, epochs=epochs_count)\n\n plot_training(history, net, epochs_count)\n\n if predict(ds.X_test, ds.y_test, net):\n ds_sub = DataSet(full=True)\n submission(net, None, ds_sub, network=True, trained=True)\n\n\ndef test_vgg16():\n \n ds = DataSet(data_path='data/', shuffle=True, balance=True, categorical=True, padd=True, combine=3)\n \n r = VGG16_net()\n\n epochs_count = 10\n\n history, net, clf = train(ds.X_train, ds.y_train, ds.X_test, ds.y_test, r, epochs=epochs_count)\n\n #plot_training(history, net, epochs_count)\n\n if predict(ds.X_test, ds.y_test, net):\n full_ds = DataSet(data_path='data/', padd=True, combine=3)\n\n #submission(net, None, full_ds, network=True, trained=True)\n submmiss_clf(net, clf, full_ds)\n\nif __name__ == '__main__':\n\n test_vgg16()\n #test_rnn()\n","sub_path":"test_network.py","file_name":"test_network.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"576650242","text":"import tensorflow as tf\nimport keras.backend as K\nimport numpy as np\nimport odl.contrib.tensorflow\n\n\nclass ANETT:\n\n def __init__(self, encoder, decoder, operator, batch_size=8, size=512, sess=None, weights=None, loss='gauss'):\n if sess is None:\n self._sess = K.get_session()\n else:\n self._sess = sess\n\n # Operators\n self._encoder = encoder\n self._decoder = decoder\n # Could be made better with K.int_shape\n self._input_shape = [tuple([batch_size] + [int(z) for z in s.shape[1:]]) for s in self._decoder.inputs]\n\n self._shape = operator.range.shape\n self._operator = odl.contrib.tensorflow.as_tensorflow_layer(operator)\n self._size = size\n\n # Primal variable\n self._x = tf.placeholder(tf.float32, shape=(batch_size, self._size, self._size, 1))\n self._x_var = tf.Variable(self._x)\n self._x_predicted = self._decoder(self._encoder(self._x))\n\n self._enc_x = self._encoder(self._x_var)\n self._x_decoded = self._decoder(self._enc_x)\n\n # Splitting variable\n self._xi = self._encoder(self._x)\n self._xi_var = [tf.Variable(x, dtype=tf.float32) for x in self._xi]\n\n # Dual variable\n self._dual = [tf.placeholder(tf.float32, shape=s) for s in self._input_shape]\n self._dual_var = [tf.Variable(x, dtype=tf.float32) for x in self._dual]\n\n # Parametes for minimization\n self._alpha = tf.placeholder(tf.float32)\n self._beta = tf.placeholder(tf.float32)\n self._rho = tf.placeholder(tf.float32)\n self._q = tf.placeholder(tf.float32)\n self._lr = tf.placeholder(tf.float32, name='learning_rate')\n self._data = tf.placeholder(tf.float32, (batch_size, ) + operator.range.shape + (1,))\n self._mom = tf.placeholder(tf.float32)\n self._weights = self._constant_weights() if weights is None else self._decaying_weights()\n\n # Loss terms for minimization in x direction\n self._regrec = self._regularizer_reconstructable() # Reconstruction regularizer\n self._reglq = self._regularizer_lq() # Lq regularizer\n self._datafit = self._data_discrepancy(loss=loss) # Data fit error\n self._auglag = self._augmented_lagrangian() # Augmented Lagrangian\n\n self._loss_x = self._datafit + self._rho*self._auglag + self._alpha*self._beta*self._regrec\n self._loss_total = self._datafit + self._alpha*self._reglq + self._alpha*self._beta*self._regrec\n\n # Optimizer for minimization in x\n self._optimizer = tf.train.GradientDescentOptimizer(learning_rate=self._lr)\n self._minimize = self._optimizer.minimize(self._loss_x, var_list=[self._x_var])\n\n # Shrinkage operator for minimization in xi\n\n self._update_xi_variable = self._xi_update()\n self._constraint_error = self._list_norm(self._list_subtract(self._enc_x, self._xi_var))\n\n # Dual ascent update\n self._update_dual_variable = self._dual_update()\n\n # Optimizer with momentum for minimization in x\n self._optimizer_momentum = tf.train.MomentumOptimizer(learning_rate=self._lr,\n momentum=self._mom,\n use_nesterov=True)\n self._minimize_momentum = self._optimizer_momentum.minimize(self._loss_x, var_list=[self._x_var])\n\n # Variable initializer for all variables!\n self._var_init = tf.variables_initializer([self._x_var] + self._xi_var + self._dual_var +\n self._optimizer_momentum.variables())\n print(\"ANETT initialization successful!\", flush=True)\n pass\n\n def _xi_update(self):\n if isinstance(self._enc_x, list):\n ret = [z.assign(self._shrinkage(e + u, (self._alpha/self._rho)*w)) for e, z, u, w in\n zip(self._enc_x, self._xi_var, self._dual_var, self._weights)]\n else:\n ret = self._xi_var[0].assign(self._shrinkage(self._enc_x + self._dual_var[0], (self._alpha/self._rho)*self._weights[0]))\n return ret\n\n def _dual_update(self):\n if isinstance(self._enc_x, list):\n ret = [u.assign(u+e-xi) for u, e, xi in zip(self._dual_var, self._enc_x, self._xi_var)]\n else:\n ret = self._dual_var[0].assign(self._dual_var[0] + self._enc_x - self._xi_var[0])\n return ret\n\n def _variable_initialization(self, x0):\n fd = {self._x: x0}\n xi_inp = self._sess.run(self._xi, feed_dict=fd)\n\n if isinstance(xi_inp, list):\n for i in range(len(xi_inp)):\n fd[self._xi[i].name] = xi_inp[i] # initialize xi[i] as E(x)[i]\n fd[self._dual[i].name] = np.zeros(self._input_shape[i]) # initialize u[i] as zero\n else:\n fd[self._xi[0].name] = xi_inp\n fd[self._dual[0].name] = np.zeros(self._input_shape[0])\n\n self._sess.run(self._var_init, feed_dict=fd)\n del xi_inp\n del fd\n pass\n\n def _update_x_variable(self, feed_dict, niter=100, tol=10**(-5)):\n err = [self._sess.run(self._loss_x, feed_dict=feed_dict)]\n # Improv has to be remade to avoid weird stuff happening because of batches\n for i in range(niter):\n self._sess.run(self._minimize_momentum, feed_dict=feed_dict) # make gradient step with momentum\n err.append(self._sess.run(self._loss_x, feed_dict=feed_dict))\n pass\n\n def reconstruct(self, x0, data, niter=10, lr=10**(-3), alpha=10**(-3), beta=10**(-3), rho=10**(-3),\n niterx=100, mom=0.8, tol=10**(-3)):\n self._variable_initialization(x0=x0)\n fd = {self._data: data[..., None],\n self._alpha: alpha,\n self._beta: beta,\n self._rho: rho,\n self._lr: 0,\n self._mom: mom}\n err = [self._sess.run(self._loss_total, feed_dict=fd)]\n\n for it in range(niter):\n fd[self._lr] = lr(it) if callable(lr) else lr\n\n self._update_x_variable(feed_dict=fd, niter=niterx, tol=tol) # Step 1: argmin_x\n self._sess.run(self._update_xi_variable, feed_dict=fd) # Step 2: argmin_xi\n self._sess.run(self._update_dual_variable, feed_dict=fd) # Step 3: Dual ascent\n\n err.append(self._sess.run(self._loss_total, feed_dict=fd)) # Calculate loss after iteration\n\n xout = self._sess.run(self._x_var, feed_dict=fd)\n xdec = self._sess.run(self._x_decoded)\n return xout, xdec, err\n\n def _regularizer_lq(self, q=1):\n return K.sum([tf.norm(self._enc_x[i], ord=q)**q for i in range(len(self._enc_x))])\n\n def _regularizer_reconstructable(self, p=2):\n return (1./p) * self._norm(self._x_var - self._x_decoded, p=p)\n\n def add_regularizer(self, reg):\n self._loss_x += reg(self._x_var)\n self._loss_total += reg(self._x_var)\n print(\"Added addiotional regularizer!\", flush=True)\n pass\n\n def _data_discrepancy(self, p=2, loss='gauss', mu=0.02, photons=1e4):\n if loss == 'gauss':\n ret = (1./p)*self._norm(self._operator(self._x_var) - self._data, p=p)\n elif loss == 'poisson':\n k_value = (tf.exp(-mu*self._data)*photons - 1)\n lambda_x = tf.exp(-mu*self._operator(self._x_var))*photons\n pois = lambda_x - k_value*tf.log(lambda_x)\n ret = tf.reduce_sum(pois)\n elif loss == 'poisson_approx':\n k_value = (tf.exp(-mu * self._data) * photons - 1)\n lambda_x = tf.exp(-mu * self._operator(self._x_var)) * photons\n ret = tf.log(lambda_x) + (1./lambda_x)*tf.squared_difference(lambda_x, k_value)\n ret = 0.5*tf.reduce_sum(ret)\n elif loss == 'poisson_l2':\n k_value = (tf.exp(-mu * self._data) * photons - 1)\n lambda_x = tf.exp(-mu * self._operator(self._x_var)) * photons\n ret = tf.squared_difference(lambda_x, k_value)/lambda_x\n ret = 0.5*tf.reduce_sum(ret)\n elif loss == 'kl':\n k_value = (tf.exp(-mu * self._data) * photons - 1)\n lambda_x = tf.exp(-mu * self._operator(self._x_var)) * photons\n\n ret = tf.reduce_sum(lambda_x*tf.log(lambda_x/k_value) - lambda_x)\n elif loss == 'mixture':\n # Poisson\n k_value = (tf.exp(-mu * self._data) * photons - 1)\n lambda_x = tf.exp(-mu * self._operator(self._x_var)) * photons\n ret = tf.squared_difference(lambda_x, k_value) / lambda_x\n ret = 0.5 * tf.reduce_sum(ret)\n\n # l2\n ret += (1. / p) * self._norm(self._operator(self._x_var) - self._data, p=p)\n\n else:\n ret = tf.zeros(1)\n print(\"WARNING: No data-discrepancy chosen!\", flush=True)\n return ret\n\n def _augmented_lagrangian(self):\n v = self._list_subtract(self._xi_var, self._dual_var)\n ret = self._list_norm(self._list_subtract(self._enc_x, v))\n return 0.5*ret\n\n def _decaying_weights(self):\n w = []\n for s in self._decoder.inputs:\n t = s.shape[1:]\n scale = 2 ** (1 + np.log2(s.shape[1].value) - np.log2(self._size))\n w.append(np.ones([1, ] + [z.value for z in t]) * scale)\n return w\n\n def _constant_weights(self):\n return [np.ones([1, ] + [z.value for z in s.shape[1:]]) for s in self._decoder.inputs]\n\n @staticmethod\n def _shrinkage(xi, gamma):\n return tf.maximum(tf.abs(xi) - gamma, 0) * tf.sign(xi)\n\n @staticmethod\n def _norm(x, p=2):\n \"\"\"\n Implementation of p-norm to the power of p. This is used in optimization since tf.norm is numerically\n instable for x = 0.\n \"\"\"\n return K.sum(K.pow(K.abs(x), p))\n\n @staticmethod\n def _list_subtract(a, b):\n if isinstance(a, list):\n ret = [i - j for i, j in zip(a, b)]\n else:\n ret = a - b\n return ret\n\n def _list_norm(self, a, p=2):\n if isinstance(a, list):\n ret = K.sum([self._norm(i, p=p) for i in a])\n else:\n ret = self._norm(a, p=p)\n return ret\n\n def predict(self, x):\n fd = {self._x: np.asarray(x)[..., None]}\n pred = self._sess.run(self._x_predicted, feed_dict=fd)\n return pred\n","sub_path":"imports/anett_admm_batch.py","file_name":"anett_admm_batch.py","file_ext":"py","file_size_in_byte":10354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"405266743","text":"from django.db import models\nfrom Usuarios_k.models import *\nfrom django.core.exceptions import ValidationError\n\n# Create your models here.\nclass Sigue(models.Model):\n \n usuario_tutor = models.ForeignKey(User, on_delete=models.CASCADE, related_name=\"user_tutor\") \n usuario_alumno = models.ForeignKey(to=User,on_delete=models.CASCADE, related_name='%(class)s_requests_created') \n fecha_hora=models.DateTimeField('Registro de hora',auto_now_add=True)\n\ndef __str__(self):\n return str(self.usuario_tutor)\n\ndef save(self, *args, **kwargs):\n # Revisar campos duplicados\n try:\n sigue = Sigue.objects.get(usuario_alumno=self.usuario_alumno, usuario_tutor=self.usuario_tutor)\n raise NotImplementedError('Registros duplicados', code='invalid')\n except self.DoesNotExist:\n super().save(*args, **kwargs)\n\n # Campos duplicados inversos\n try:\n sigue_new = Sigue.objects.get(usuario_tutor=self.usuario_alumno, usuario_alumno=self.usuario_tutor)\n raise NotImplementedError('Registros duplicados', code='invalid')\n except self.DoesNotExist:\n super().save(*args, **kwargs)\n \n","sub_path":"knowtured/Sigue_k/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"113465062","text":"# -*- coding:utf-8 -*-\n__author__ = 'Tnew'\n\nfrom appium.webdriver.common.mobileby import MobileBy\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\n\n\"\"\"\nadb shell\ndumpsys window|grep mCurrent 得到activity\n\ncom.tencent.wework/com.tencent.wework.launch.WwMainActivity\n\nchromedriver可以有三种方式放置\n1 放在appium默认路径下面,对应版本就行'D:/Study/Automation_Tester_Guide/Lesson6_appium/Appium-windows-1.19.1/resources/app/node_modules/appium/node_modules/appium-chromedriver/chromedriver/win'\n2 设置 \"ChromedriverExecutable\":\"D:/Study/Automation_Tester_Guide/Lesson6_appium/chromedriver\"\n3 可以用mapping.json的方式匹配,新建json,对应版本号映射匹配,然后在caps里面设置\n \"chromedriverExecutableDir\":\"D:/Study/Automation_Tester_Guide/Lesson6_appium/chromedriver\"\n \"chromedriverChromeMappingFile\": mapping.json的对应绝对路径\n\"\"\"\nfrom appium import webdriver\n\n\nclass TestDW:\n def setup(self):\n desire_caps = {\n \"platformName\":'android',\n \"deviceName\":'192.168.216.101:5555',\n \"appPackage\":'com.xueqiu.android',\n \"appActivity\":'com.xueqiu.android.common.MainActivity',\n \"noReset\":'true',\n \"ChromedriverExecutable\":\"D:/Study/Automation_Tester_Guide/Lesson6_appium/chromedriver\"\n }\n # desire_caps['dontStopAppOnReset'] = 'true'\n # desire_caps['skipDeviceInitialization'] = 'true'\n # desire_caps['unicodeKeyBoard']='true'\n # desire_caps['resetKeyBoard'] = 'true'\n self.driver = webdriver.Remote(\"http://127.0.0.1:4723/wd/hub\", desire_caps)\n self.driver.implicitly_wait(5)\n # desire_caps['ChromedriverExecutable']='D:/Study/Automation_Tester_Guide/Lesson6_appium/Appium-windows-1.19.1/resources/app/node_modules/appium/node_modules/appium-chromedriver/chromedriver/win'\n\n def teardown(self):\n self.driver.quit()\n\n def test_xueqiu(self):\n \"\"\"\n 打开雪球\n 点击交易\n 点击A股开户\n 输入手机和验证码\n 点击立即开户\n\n :return:\n \"\"\"\n print(self.driver.contexts)\n #点击交易\n self.driver.find_element(MobileBy.XPATH,\"//*[@text='交易']\").click()\n print(self.driver.contexts)\n #切换上下文\n self.driver.switch_to.context(self.driver.contexts[-1])\n print(self.driver.window_handles)\n #点击A股开户\n a_locator = (MobileBy.XPATH,\"//*[@id='app']/div/div/div/ul/li[1]/div[2]/h1\")\n WebDriverWait(self.driver,20).until(expected_conditions.element_to_be_clickable(a_locator))\n self.driver.find_element(*a_locator).click()\n\n print(self.driver.window_handles)\n self.driver.switch_to.window(self.driver.window_handles[-1])\n #输入用户名\n user_locator = (MobileBy.XPATH,\"//*[@id='phone-number']\")\n WebDriverWait(self.driver,10).until(expected_conditions.element_to_be_clickable(user_locator))\n self.driver.find_element(*user_locator).send_keys(\"13918342345\")\n #输入密码\n self.driver.find_element(MobileBy.ID,\"code\").send_keys(\"152452\")\n self.driver.find_element(MobileBy.XPATH,'/html/body/div/div/div[2]/div/div[2]/h1').click()\n\n\n","sub_path":"pratice_lesson6_appium/test_webview_xueqiu.py","file_name":"test_webview_xueqiu.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"247531222","text":"from skimage.feature import match_template\nfrom skimage.filters import threshold_otsu\nfrom skimage.io import imread\nimport os.path\n\n# characters that should be clearly examined using template matching\nconfusing_chars = {'2', 'Z', 'B', '8', 'D', '0', '5', 'S', 'Q', 'R', '7'}\n\n# a dictionary that keeps track of characters that are similar to the\n# confusing characters\nsimilar_characters = {\n '2':['Z'], 'Z':['2', '7'], '8':['B'], 'B':['8', 'R'], '5':['S'], 'S':['5'],\n '0':['D', 'Q'], 'D':['0', 'Q'], 'Q':['D', '0'], '7':['Z']\n}\n\ndef template_match(predicted_label, image_data, training_dir):\n \"\"\"\n applies the concept of template matching to determine the\n character among the similar ones that have the highest match and\n returns the label\n\n Parameters:\n ------------\n predicted_label: str; the character that was predicted by the machine\n learning model\n image_data: 2D numpy array image of the character that was predicted\n training_dir: the directory for the images that will be used in matching\n\n Returns:\n ---------\n The label with the highest match value\n \"\"\"\n image_data = image_data.reshape(20, 20)\n prediction_fraction = fraction_match(predicted_label, training_dir,\n image_data)\n highest_fraction = prediction_fraction\n highest_fraction_label = predicted_label\n similar_labels_list = similar_characters[predicted_label]\n\n for each_similar_label in similar_labels_list:\n match_value = fraction_match(each_similar_label, training_dir,\n image_data)\n if match_value > highest_fraction:\n highest_fraction = match_value\n highest_fraction_label = each_similar_label\n\n return highest_fraction_label\n\n\ndef fraction_match(label, training_dir, image_data):\n fraction = 0\n for i in range(10):\n image_dir = os.path.join(training_dir, label, label+'_'+str(i)+'.jpg')\n image_sample = imread(image_dir, as_grey=True)\n image_sample = image_sample < threshold_otsu(image_sample)\n match_fraction = match_template(image_data, image_sample)\n\n fraction += (match_fraction[0, 0] / 10)\n return fraction","sub_path":"Models/License-Plate-Recognition-Nigerian-vehicles-master/License-Plate-Recognition-Nigerian-vehicles-master/ml_code/templatematching.py","file_name":"templatematching.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"530612676","text":"from django.core.management.base import BaseCommand\nfrom api.models import Wine\nimport csv\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n with open('_winemag.csv') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n rowPoints = int(row['points'])\n if not row['price']: row['price'] = 999\n rowPrice = float(row['price'])\n p = Wine(name=row['title'], description=row['description'], price=rowPrice, points=rowPoints, ratio=rowPoints/rowPrice)\n p.save()\n","sub_path":"app/api/management/commands/before.py","file_name":"before.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"217677367","text":"from django.db.models import Sum\nfrom django.http import HttpResponse\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.exceptions import PermissionDenied, ValidationError\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom products.models import Product\nfrom stocks.filters import StockInFilter, StockOutFilter, StockCardFilter\nfrom stocks.models import StockCard, StockIn, ItemIn, StockOut, ItemOut\nfrom stocks.permissions import IsAccessDeleteStockIn\nfrom stocks.serializers import StockCardSerializer, StockInSerializer, ItemInSerializer, StockOutSerializer, \\\n ItemOutSerializer\nfrom utils.pdf import TOPDF, TOCSV\n\n\nclass StockCardViewSet(viewsets.ModelViewSet):\n serializer_class = StockCardSerializer\n permission_classes = [\n IsAuthenticated,\n ]\n queryset = StockCard.objects.all()\n\n search_fields = [\n 'numcode',\n 'product__name',\n ]\n\n filterset_class = StockCardFilter\n\n message = 'Not implemented for this action!'\n\n def create(self, request, *args, **kwargs):\n raise PermissionDenied(self.message)\n\n def update(self, request, *args, **kwargs):\n raise PermissionDenied(self.message)\n\n def partial_update(self, request, *args, **kwargs):\n raise PermissionDenied(self.message)\n\n def destroy(self, request, *args, **kwargs):\n raise PermissionDenied(self.message)\n\n @action(methods=['POST', 'GET'], detail=False)\n def export_csv(self, request, pk=None):\n response = HttpResponse(content_type='application/csv')\n response['Content-Disposition'] = 'attachment; filename=somefilename.csv'\n queryset = self.filter_queryset(self.get_queryset().filter(is_init=False))\n queryset = queryset.values(\n 'product__name',\n 'product__numcode',\n 'date',\n ).annotate(\n Sum('init_balance'),\n Sum('total_in'),\n Sum('total_out'),\n Sum('end_balance')\n ).order_by('-date')\n\n temp = []\n header = [\n 'Nomer Produk',\n 'Nama Produk',\n 'Tanggal',\n 'Saldo Awal',\n 'Stok Masuk',\n 'Stok Keluar',\n 'Stok Akhir'\n ]\n for obj in queryset:\n temp.append([\n obj.get('product__numcode'),\n obj.get('product__name'),\n obj.get('date'),\n obj.get('init_balance__sum'),\n obj.get('total_in__sum'),\n obj.get('total_out__sum'),\n obj.get('end_balance__sum'),\n ])\n\n csv = TOCSV(header, temp, response)\n return csv.build()\n\n @action(methods=['POST', 'GET'], detail=False)\n def export_pdf(self, request, pk=None):\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'\n queryset = self.filter_queryset(self.get_queryset().filter(is_init=False))\n products = queryset.values(\n 'product',\n ).annotate(\n Sum('total_in'),\n Sum('total_out'),\n Sum('end_balance')\n )\n\n pdf = TOPDF(response, 'Laporan Kartu Stok Barang', None)\n pdf.set_table_detail([\n pdf.set_subject('Laporan Kartu Stok'),\n pdf.set_periode(request),\n pdf.set_user(request),\n pdf.set_date_created()\n ])\n pdf.set_page_break()\n\n temp = []\n number = 1\n header = [\n '#',\n 'Tanggal',\n 'Saldo Awal',\n 'Stok Masuk',\n 'Stok Keluar',\n 'Stok Akhir'\n ]\n for obj in products:\n product = Product.objects.get(pk=obj.get('product'))\n stock_cards = queryset.filter(product=product)\n pdf.set_table_detail([\n pdf.set_other('Kode Produk', product.numcode),\n pdf.set_other('Nama Produk', product.name),\n pdf.set_other('Total Masuk', obj.get('total_in__sum')),\n pdf.set_other('Total Keluar', obj.get('total_out__sum')),\n pdf.set_other('Total Saat Ini', product.stock),\n ])\n pdf.set_break()\n for sc in stock_cards:\n temp.append([\n number,\n sc.date,\n sc.init_balance,\n sc.total_in,\n sc.total_out,\n sc.end_balance\n ])\n number += 1\n pdf.set_table(header, temp, 'LEFT', None)\n temp = []\n number = 1\n pdf.set_page_break()\n\n return pdf.build()\n\n\nclass StockInViewSet(viewsets.ModelViewSet):\n serializer_class = StockInSerializer\n permission_classes = (\n IsAuthenticated,\n IsAccessDeleteStockIn,\n )\n queryset = StockIn.objects.all().order_by('-created')\n\n search_fields = [\n 'numcode',\n 'supplier__name',\n 'user__username',\n 'user__email',\n ]\n\n filterset_class = StockInFilter\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n @action(methods=['POST'], detail=True)\n def calculate(self, request, pk=None):\n stock_in = self.get_object()\n if not stock_in.supplier:\n raise ValidationError({'detail': f'Supplier is not added'})\n\n item_ins = ItemIn.objects.filter(stockin=stock_in, is_init=False)\n stock_cards = []\n if item_ins.exists():\n for item_in in item_ins:\n if item_in.quantity < 1:\n raise ValidationError({'detail': f'Item {item_in.product.name} may not be zero.'})\n\n stock_cards.append(StockCard(\n numcode=stock_in.numcode,\n date=stock_in.date,\n product=item_in.product,\n init_balance=item_in.product.stock,\n total_in=item_in.quantity,\n end_balance=item_in.product.stock + item_in.quantity,\n is_init=False\n ))\n product = item_in.product\n product.stock = product.stock + item_in.quantity\n product.save()\n\n stock_in.is_calculate = True\n stock_in.save()\n StockCard.objects.bulk_create(stock_cards)\n\n else:\n raise ValidationError({'detail': 'Item cannot be empty.'})\n return Response(self.serializer_class(stock_in).data)\n\n @action(methods=['POST', 'GET'], detail=False)\n def export_csv(self, request, pk=None):\n response = HttpResponse(content_type='application/csv')\n response['Content-Disposition'] = 'attachment; filename=somefilename.csv'\n queryset = self.filter_queryset(self.get_queryset().filter(is_calculate=True, is_init=False))\n\n queryset = queryset.prefetch_related('stockinitemin').values(\n 'numcode',\n 'supplier',\n 'supplier__name',\n 'supplier__numcode',\n 'supplier__phone',\n 'stockinitemin__product__numcode',\n 'stockinitemin__product__name',\n 'date',\n ).annotate(Sum('stockinitemin__quantity'))\n data = []\n header = [\n 'Kode Stok',\n 'Tanggal',\n 'Kode Supplier',\n 'Nama Supplier',\n 'Kontak Supplier',\n 'Kode Produk',\n 'Produk',\n 'Stok Masuk',\n ]\n\n for obj in queryset:\n data.append([\n obj.get('numcode'),\n obj.get('date'),\n obj.get('supplier__numcode'),\n obj.get('supplier__name'),\n obj.get('supplier__phone'),\n obj.get('stockinitemin__product__numcode'),\n obj.get('stockinitemin__product__name'),\n obj.get('stockinitemin__quantity__sum'),\n ])\n\n csv = TOCSV(header, data, response)\n return csv.build()\n\n @action(methods=['POST', 'GET'], detail=False)\n def export_pdf(self, request, pk=None):\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'\n queryset = self.filter_queryset(self.get_queryset().filter(is_calculate=True, is_init=False))\n queryset = queryset.prefetch_related('stockinitemin')\n\n pdf = TOPDF(response, 'Laporan Barang Masuk', None)\n for obj in queryset:\n temp_detail = []\n temp_detail += [\n pdf.set_subject(f'Laporan Stok Masuk {obj.numcode}'),\n pdf.set_periode(request),\n pdf.set_user(request),\n pdf.set_date_created(),\n ]\n\n temp = []\n header = [\n 'Nomer Produk',\n 'Nama Produk',\n 'Stok Masuk'\n ]\n items = obj.stockinitemin.values(\n 'product__numcode',\n 'product__name',\n ).annotate(Sum('quantity'))\n total = obj.stockinitemin.aggregate(Sum('quantity'))\n\n for item in items:\n temp.append([\n item.get('product__numcode'),\n item.get('product__name'),\n item.get('quantity__sum'),\n ])\n\n temp_detail += [\n pdf.set_other('Nomer Stok Masuk', obj.numcode),\n pdf.set_other('Tanggal', obj.date),\n pdf.set_other('Nomer Supplier', obj.supplier.numcode),\n pdf.set_other('Supplier', obj.supplier.name),\n pdf.set_other('Kontak Supplier', obj.supplier.phone),\n pdf.set_other('Total Stok Masuk', total.get('quantity__sum')),\n ]\n pdf.set_table_detail(temp_detail)\n pdf.set_break(0.2, 0.2)\n\n pdf.set_table(header, temp, 'LEFT', None)\n pdf.set_page_break()\n return pdf.build()\n\n @action(methods=['GET'], detail=True)\n def print_pdf(self, request, pk=None):\n obj = self.get_object()\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'\n\n pdf = TOPDF(response, 'Laporan Barang Masuk', None)\n temp_detail = []\n temp_detail += [\n pdf.set_subject(f'Laporan Stok Masuk {obj.numcode}'),\n pdf.set_periode(request),\n pdf.set_user(request),\n pdf.set_date_created(),\n ]\n\n temp = []\n header = [\n 'Nomer Produk',\n 'Nama Produk',\n 'Stok Masuk'\n ]\n items = obj.stockinitemin.values(\n 'product__numcode',\n 'product__name',\n ).annotate(Sum('quantity'))\n total = obj.stockinitemin.aggregate(Sum('quantity'))\n\n for item in items:\n temp.append([\n item.get('product__numcode'),\n item.get('product__name'),\n item.get('quantity__sum'),\n ])\n\n temp_detail += [\n pdf.set_other('Nomer Stok Masuk', obj.numcode),\n pdf.set_other('Tanggal', obj.date),\n pdf.set_other('Nomer Supplier', obj.supplier.numcode),\n pdf.set_other('Supplier', obj.supplier.name),\n pdf.set_other('Kontak Supplier', obj.supplier.phone),\n pdf.set_other('Total Stok Masuk', total.get('quantity__sum')),\n ]\n pdf.set_table_detail(temp_detail)\n pdf.set_break(0.2, 0.2)\n\n pdf.set_table(header, temp, 'LEFT', None)\n pdf.set_page_break()\n return pdf.build()\n\n\nclass ItemInViewSet(viewsets.ModelViewSet):\n serializer_class = ItemInSerializer\n permission_classes = (\n IsAuthenticated,\n )\n queryset = ItemIn.objects.all()\n\n search_fields = [\n 'stockin__numcode',\n 'product__name',\n ]\n\n filterset_fields = [\n 'stockin',\n 'product',\n 'is_init',\n ]\n\n\nclass StockOutViewSet(viewsets.ModelViewSet):\n serializer_class = StockOutSerializer\n queryset = StockOut.objects.all().order_by('-created')\n\n search_fields = [\n 'numcode',\n 'customer__name',\n 'user__username',\n 'user__email',\n ]\n\n filterset_class = StockOutFilter\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n @action(methods=['POST'], detail=True)\n def calculate(self, request, pk=None):\n stock_out = self.get_object()\n\n if not stock_out.customer:\n raise ValidationError({'detail': f'Customer is not added'})\n\n item_outs = ItemOut.objects.filter(stockout=stock_out, is_init=False)\n stock_cards = []\n if item_outs.exists():\n for item_out in item_outs:\n if not item_out.product:\n raise ValidationError({'detail': f'one item does not have a product.'})\n\n if item_out.product.stock - item_out.quantity < 0:\n raise ValidationError({'detail': f'product stock does not meet.'})\n\n if item_out.quantity < 1:\n raise ValidationError({'detail': f'Item {item_out.product.name} may not be zero.'})\n\n # Stock Cards\n stock_cards.append(StockCard(\n numcode=stock_out.numcode,\n date=stock_out.date,\n product=item_out.product,\n init_balance=item_out.product.stock,\n total_out=item_out.quantity,\n end_balance=item_out.product.stock - item_out.quantity,\n is_init=False\n ))\n\n product = item_out.product\n product.stock = product.stock - item_out.quantity\n product.save()\n\n stock_out.is_calculate = True\n stock_out.save()\n StockCard.objects.bulk_create(stock_cards)\n else:\n raise ValidationError({'detail': 'Item cannot be empty.'})\n\n return Response(self.serializer_class(stock_out).data)\n\n @action(methods=['POST', 'GET'], detail=False)\n def export_csv(self, request, pk=None):\n response = HttpResponse(content_type='application/csv')\n response['Content-Disposition'] = 'attachment; filename=somefilename.csv'\n queryset = self.filter_queryset(self.get_queryset().filter(is_calculate=True, is_init=False))\n\n queryset = queryset.prefetch_related('stockoutitemout').values(\n 'numcode',\n 'customer',\n 'customer__name',\n 'customer__numcode',\n 'customer__phone',\n 'stockoutitemout__product__numcode',\n 'stockoutitemout__product__name',\n 'date',\n ).annotate(Sum('stockoutitemout__quantity'))\n data = []\n header = [\n 'Kode Stok',\n 'Tanggal',\n 'Kode Pelanggan',\n 'Nama Pelanggan',\n 'Kontak Pelanggan',\n 'Kode Produk',\n 'Produk',\n 'Stok Keluar',\n ]\n\n for obj in queryset:\n data.append([\n obj.get('numcode'),\n obj.get('date'),\n obj.get('customer__numcode'),\n obj.get('customer__name'),\n obj.get('customer__phone'),\n obj.get('stockoutitemout__product__numcode'),\n obj.get('stockoutitemout__product__name'),\n obj.get('stockoutitemout__quantity__sum'),\n ])\n\n csv = TOCSV(header, data, response)\n return csv.build()\n\n @action(methods=['POST', 'GET'], detail=False)\n def export_pdf(self, request, pk=None):\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'\n queryset = self.filter_queryset(self.get_queryset().filter(is_calculate=True, is_init=False))\n queryset = queryset.prefetch_related('stockoutitemout')\n\n pdf = TOPDF(response, 'Laporan Barang Keluar', None)\n for obj in queryset:\n temp_detail = []\n temp_detail += [\n pdf.set_subject(f'Laporan Stok Keluar {obj.numcode}'),\n pdf.set_periode(request),\n pdf.set_user(request),\n pdf.set_date_created(),\n ]\n\n temp = []\n header = [\n 'Nomer Produk',\n 'Nama Produk',\n 'Stok Keluar'\n ]\n items = obj.stockoutitemout.values(\n 'product__numcode',\n 'product__name',\n ).annotate(Sum('quantity'))\n total = obj.stockoutitemout.aggregate(Sum('quantity'))\n\n for item in items:\n temp.append([\n item.get('product__numcode'),\n item.get('product__name'),\n item.get('quantity__sum'),\n ])\n\n temp_detail += [\n pdf.set_other('Nomer Stok Keluar', obj.numcode),\n pdf.set_other('Tanggal', obj.date),\n pdf.set_other('Nomer Pelanggan', obj.customer.numcode),\n pdf.set_other('Pelanggan', obj.customer.name),\n pdf.set_other('Kontak Supplier', obj.customer.phone),\n pdf.set_other('Total Stok Keluar', total.get('quantity__sum')),\n ]\n pdf.set_table_detail(temp_detail)\n pdf.set_break(0.2, 0.2)\n\n pdf.set_table(header, temp, 'LEFT', None)\n pdf.set_page_break()\n return pdf.build()\n\n @action(methods=['GET'], detail=True)\n def print_pdf(self, request, pk=None):\n obj = self.get_object()\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'\n\n pdf = TOPDF(response, 'Laporan Barang Keluar', None)\n temp_detail = []\n temp_detail += [\n pdf.set_subject(f'Laporan Stok Keluar {obj.numcode}'),\n pdf.set_periode(request),\n pdf.set_user(request),\n pdf.set_date_created(),\n ]\n\n temp = []\n header = [\n 'Nomer Produk',\n 'Nama Produk',\n 'Stok Masuk'\n ]\n items = obj.stockoutitemout.values(\n 'product__numcode',\n 'product__name',\n ).annotate(Sum('quantity'))\n total = obj.stockoutitemout.aggregate(Sum('quantity'))\n\n for item in items:\n temp.append([\n item.get('product__numcode'),\n item.get('product__name'),\n item.get('quantity__sum'),\n ])\n\n temp_detail += [\n pdf.set_other('Nomer Stok Keluar', obj.numcode),\n pdf.set_other('Tanggal', obj.date),\n pdf.set_other('Nomer Pelanggan', obj.customer.numcode),\n pdf.set_other('Pelanggan', obj.customer.name),\n pdf.set_other('Kontak Pelanggan', obj.customer.phone),\n pdf.set_other('Total Stok Keluar', total.get('quantity__sum')),\n ]\n pdf.set_table_detail(temp_detail)\n pdf.set_break(0.2, 0.2)\n\n pdf.set_table(header, temp, 'LEFT', None)\n pdf.set_page_break()\n return pdf.build()\n\n\nclass ItemOutViewSet(viewsets.ModelViewSet):\n serializer_class = ItemOutSerializer\n permission_classes = (\n IsAuthenticated,\n )\n queryset = ItemOut.objects.all()\n\n search_fields = [\n 'stockout__numcode',\n 'product__name',\n ]\n\n filterset_fields = [\n 'stockout',\n 'product',\n 'is_init',\n ]\n","sub_path":"stocks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"624994328","text":"import webapp2\n\nmonths = [\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\"]\nmonths_abbv = dict((m[:3].lower(), m) for m in months)\n\ndef valid_year(year):\n\tif year and year.isdigit():\n\t\tyear = int(year)\n\t\tif year > 1900 and year <= 2020:\n\t\t\treturn year\n\ndef valid_month(month):\n\t\tif month:\n\t\t\tshort_month = month[:3].lower()\n\t\t\treturn months_abbv.get(short_month)\n\ndef valid_day(day):\n\tif day and day.isdigit():\n\t\tday = int(day)\n\t\tif day > 0 and day <= 31:\n\t\t\treturn day\n\n# def escape_html(s):\n# \tfor (i, o) in ((\"&\", \"&\"),\n# \t\t\t\t\t(\">\", \">\"),\n# \t\t\t\t\t(\"<\", \"<\"),\n# \t\t\t\t\t('\"', \""\")):\n# \t\ts = s.replace(i, o);\n# \treturn s\n\nimport cgi\ndef escape_html(s):\n\treturn cgi.escape(s, quote=True)\n\nform=\"\"\"\n
    \n\tWhat is your birthday?\n\t
    \n\t\n\t\n\t\n\t
    %(error)s
    \n\t
    \n\t
    \n\t\n
    \n\"\"\"\n\nclass MainPage(webapp2.RequestHandler):\n\tdef write_form(self, error=\"\", month=\"\", day=\"\", year=\"\"):\n\t\tself.response.out.write(form % {\"error\": error,\n\t\t\t\t\t\t\t\t\t\t\"month\": escape_html(month),\n\t\t\t\t\t\t\t\t\t\t\"day\": escape_html(day),\n\t\t\t\t\t\t\t\t\t\t\"year\": escape_html(year)} )\n\n\tdef get(self):\n\t\tself.write_form()\n\n\tdef post(self):\n\t\tuser_month = self.request.get(\"month\")\n\t\tuser_day = self.request.get(\"day\")\n\t\tuser_year = self.request.get(\"year\")\n\n\t\tmonth = valid_month(user_month)\n\t\tday = valid_day(user_day)\n\t\tyear = valid_year(user_year)\n\n\t\tif not (month and day and year):\n\t\t\tself.write_form(\"That was not a valid date.\", user_month, user_day, user_year)\n\t\telse:\n\t\t\tself.redirect(\"/thanks\")\n\nclass ThanksHandler(webapp2.RequestHandler):\n\tdef get(self):\n\t\tself.response.out.write(\"Thanks! Totally valid!\")\n\napp = webapp2.WSGIApplication([('/', MainPage),\n\t\t\t\t\t\t\t\t('/thanks', ThanksHandler)],\n\t\t\t\t\t\t\t\tdebug=True)","sub_path":"helloworld/helloworld.py","file_name":"helloworld.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"167346461","text":"#-*-coding: utf-8-*-\n\nimport requests\nimport json\n\nclass Weixin(object):\n def __init__ (self, corpid = None, corpsecret = None):\n self.corpid = corpid\n self.corpsecret = corpsecret\n self.access_token = ''\n # 获取ACCESS_TOKEN\n def getToken (self):\n if (self.corpid and self.corpsecret):\n # 拼接请求地址\n requrl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + self.corpid +'&corpsecret=' + self.corpsecret\n # 存储接收到的数据\n res = requests.get(requrl).json()\n if (res['errcode'] == 0):\n self.access_token = res['access_token']\n # print(res)\n return res['errcode'], res['access_token']\n # 发送消息\n def sendMessage (self, option = None):\n # 拼接请求地址\n requrl = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.access_token\n # print(option)\n # print(self.access_token)\n res = requests.post(requrl, data = json.dumps(option)).json()\n return res\n # 获得JS-SDK使用权限签名\n def getJsApiTicket (self):\n # 拼接请求地址\n requrl = 'https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=' + self.access_token\n # print(option)\n res = requests.get(requrl).json()\n return res","sub_path":"weixin.py","file_name":"weixin.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"178660062","text":"'''\n\n풀이\n\n최단거리를 활용한 시뮬레이션\n\n1.손님찾기\n택시의 현재위치 남은 손님의 위치자표를 토대로 가장 택시와 가까운 손님을 고른다.\n- bfs를 통해 최단거리에 위치한 모든 손님리스트를 구한다.\n- 손님리스트를 행 오름차순, 열 오름차순으로 정렬 후 0번째 인덱스의 손님을 고른다.\n\n2.이동 가능 여부 체크\n손님위치과 택시 dfs 계산 + 손님위치와 목적지 dfs 계산한게 현재 연료 [이하]면 드라이브 가능\n이동이 가능하다면\n- 택시 현재 위치를 손님 도착위치로 바꿔줌\n- 손님을 후보에서 제거\n- 연료 갱신\n이동이 불가능 하다면\n- -1 리턴하고 종료\n\n3.남은 손님 리스트가 없을때까지 진행하고 연료 리턴\n\n'''\nfrom collections import deque\nimport sys\ninput = sys.stdin.readline\n\nN,M,gas = map(int,input().split())\nmat = [list(map(int,input().split())) for i in range(N)]\nstart = list(map(int,input().split()))\nguests = [list(map(int,input().split())) for i in range(M)]\nderive_cnt = 0\n\nguests_start,guests_end = [],[]\ndx,dy = [0,0,1,-1],[-1,1,0,0]\n\nfor i,geust in enumerate(guests):\n guests_start.append([geust[0]-1,geust[1]-1])\n guests_end.append([geust[2]-1,geust[3]-1])\n\n mat[geust[0]-1][geust[1]-1] = (i+1)*(-1) # 손님 위치와 인덱스 표시\n\ndef is_in_mat(x,y):\n if x<0 or x==N or y<0 or y==N:\n return False\n return True\n\ndef find_candi(cx,cy):\n\n visited = [[0 for i in range(N)] for j in range(N)]\n q = deque([[cx,cy]])\n ch = False\n candi_li = []\n\n #자기위치라면\n if mat[cx][cy] < 0:\n return [[cx,cy,mat[cx][cy]]]\n\n while q:\n # print(\"q : \",q)\n q_size = len(q)\n\n if ch:\n return candi_li\n\n for _ in range(q_size):\n tx,ty = q.popleft()\n\n for i in range(4):\n nx,ny = dx[i]+tx,dy[i]+ty\n\n if is_in_mat(nx,ny) and not visited[nx][ny] and mat[nx][ny] != 1:\n\n if mat[nx][ny] < 0:\n ch=True\n candi_li.append([nx,ny,mat[nx][ny]])\n visited[nx][ny] = 1\n q.append([nx,ny])\n\n # print(\"candi_li : \",candi_li)\n return candi_li\n\ndef find_guest(t):\n cx,cy = t[0],t[1]\n\n gs = find_candi(cx,cy)\n\n\n if not gs:\n return False\n elif len(gs) == 1:\n return gs[0]\n else:\n gs.sort()\n return gs[0]\n\ndef dist(sx,sy,ex,ey):\n\n visited = [[0 for i in range(N)] for j in range(N)]\n visited[sx][sy] = 1\n q = deque([[sx,sy]])\n d = 0\n ch=True\n\n while q:\n q_size = len(q)\n for _ in range(q_size):\n tx,ty = q.popleft()\n\n if tx == ex and ty == ey:\n # print(\"거리 : \",d)\n return d\n\n for i in range(4):\n \n nx,ny = dx[i]+tx,dy[i]+ty\n\n if is_in_mat(nx,ny) and not visited[nx][ny] and mat[nx][ny] != 1:\n visited[nx][ny] = 1\n q.append([nx,ny])\n d+=1\n\n if ch:#경로가 없는 경우\n return \"NOWAY\"\n return d\n\n\n\n\ndef drive(tx,ty,gx,gy,gi):\n global gas\n #도착을 못한다면 false\n tx_to_gs = dist(tx,ty,gx,gy)\n # print(\"tx_to_gs : \",tx_to_gs)\n # print(\"시작,끝 : \",gx,gy,guests_end[gi][0],guests_end[gi][1])\n gs_to_dest = dist(gx,gy,guests_end[gi][0],guests_end[gi][1])\n # print(\"gs_to_dest : \",gs_to_dest)\n\n if tx_to_gs == \"NOWAY\" or gs_to_dest == \"NOWAY\":\n return False\n\n if gas >= tx_to_gs+gs_to_dest:\n gas = gas-tx_to_gs+gs_to_dest\n return True\n else:\n return False\n\ncul_taxi = [start[0]-1,start[1]-1]\n\nwhile True:\n g = find_guest(cul_taxi)\n \n # for i in mat:\n # print(i)\n # print()\n\n # print(\"g : \",g)\n # print(\"gas : \",gas)\n\n if not g:\n if derive_cnt < M:\n print(-1)\n else:\n print(gas)\n break\n\n gx,gy,gi = g[0],g[1],(g[2]+1)*(-1)\n\n if not drive(cul_taxi[0],cul_taxi[1],gx,gy,gi):\n print(-1)\n break\n else:\n mat[gx][gy] = 0\n cul_taxi[0] = guests_end[gi][0]\n cul_taxi[1] = guests_end[gi][1]\n \n derive_cnt+=1\n \n ","sub_path":"백준/Python/카테고리/8회차/19238(스타트 택시).py","file_name":"19238(스타트 택시).py","file_ext":"py","file_size_in_byte":4260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"237821215","text":"import bpy, math\n\n#from . import cache\nfrom .. utility import *\n\ndef init(self, prev_container):\n\n #store_existing(prev_container)\n\n #set_settings()\n\n configure_world()\n\n configure_lights()\n\n configure_meshes(self)\n\ndef configure_world():\n pass\n\ndef configure_lights():\n pass\n\ndef configure_meshes(self):\n\n # for obj in bpy.data.objects:\n # if obj.type == \"MESH\":\n # if obj.TLM_ObjectProperties.tlm_mesh_lightmap_use:\n # cache.backup_material_restore(obj)\n\n # for obj in bpy.data.objects:\n # if obj.type == \"MESH\":\n # if obj.TLM_ObjectProperties.tlm_mesh_lightmap_use:\n # cache.backup_material_rename(obj)\n\n for mat in bpy.data.materials:\n if mat.users < 1:\n bpy.data.materials.remove(mat)\n\n for mat in bpy.data.materials:\n if mat.name.startswith(\".\"):\n if \"_Original\" in mat.name:\n bpy.data.materials.remove(mat)\n\n for image in bpy.data.images:\n if image.name.endswith(\"_baked\"):\n bpy.data.images.remove(image, do_unlink=True)\n\n iterNum = 0\n currentIterNum = 0\n\n scene = bpy.context.scene\n\n for obj in bpy.data.objects:\n if obj.type == \"MESH\":\n if obj.TLM_ObjectProperties.tlm_mesh_lightmap_use:\n obj.hide_select = False #Remember to toggle this back\n\n currentIterNum = currentIterNum + 1\n\n obj.octane.baking_group_id = currentIterNum\n\n for slot in obj.material_slots:\n if \".\" + slot.name + '_Original' in bpy.data.materials:\n if bpy.context.scene.TLM_SceneProperties.tlm_verbose:\n print(\"The material: \" + slot.name + \" shifted to \" + \".\" + slot.name + '_Original')\n slot.material = bpy.data.materials[\".\" + slot.name + '_Original']\n\ndef set_settings():\n\n scene = bpy.context.scene\n cycles = scene.cycles\n scene.render.engine = \"CYCLES\"\n sceneProperties = scene.TLM_SceneProperties\n engineProperties = scene.TLM_EngineProperties\n cycles.device = scene.TLM_EngineProperties.tlm_mode\n\n if cycles.device == \"GPU\":\n scene.render.tile_x = 256\n scene.render.tile_y = 256\n else:\n scene.render.tile_x = 32\n scene.render.tile_y = 32\n \n if engineProperties.tlm_quality == \"0\":\n cycles.samples = 32\n cycles.max_bounces = 1\n cycles.diffuse_bounces = 1\n cycles.glossy_bounces = 1\n cycles.transparent_max_bounces = 1\n cycles.transmission_bounces = 1\n cycles.volume_bounces = 1\n cycles.caustics_reflective = False\n cycles.caustics_refractive = False\n elif engineProperties.tlm_quality == \"1\":\n cycles.samples = 64\n cycles.max_bounces = 2\n cycles.diffuse_bounces = 2\n cycles.glossy_bounces = 2\n cycles.transparent_max_bounces = 2\n cycles.transmission_bounces = 2\n cycles.volume_bounces = 2\n cycles.caustics_reflective = False\n cycles.caustics_refractive = False\n elif engineProperties.tlm_quality == \"2\":\n cycles.samples = 512\n cycles.max_bounces = 2\n cycles.diffuse_bounces = 2\n cycles.glossy_bounces = 2\n cycles.transparent_max_bounces = 2\n cycles.transmission_bounces = 2\n cycles.volume_bounces = 2\n cycles.caustics_reflective = False\n cycles.caustics_refractive = False\n elif engineProperties.tlm_quality == \"3\":\n cycles.samples = 1024\n cycles.max_bounces = 256\n cycles.diffuse_bounces = 256\n cycles.glossy_bounces = 256\n cycles.transparent_max_bounces = 256\n cycles.transmission_bounces = 256\n cycles.volume_bounces = 256\n cycles.caustics_reflective = False\n cycles.caustics_refractive = False\n elif engineProperties.tlm_quality == \"4\":\n cycles.samples = 2048\n cycles.max_bounces = 512\n cycles.diffuse_bounces = 512\n cycles.glossy_bounces = 512\n cycles.transparent_max_bounces = 512\n cycles.transmission_bounces = 512\n cycles.volume_bounces = 512\n cycles.caustics_reflective = True\n cycles.caustics_refractive = True\n else: #Custom\n pass\n\ndef store_existing(prev_container):\n\n scene = bpy.context.scene\n cycles = scene.cycles\n\n selected = []\n\n for obj in bpy.data.objects:\n if obj.select_get():\n selected.append(obj.name)\n\n prev_container[\"settings\"] = [\n cycles.samples,\n cycles.max_bounces,\n cycles.diffuse_bounces,\n cycles.glossy_bounces,\n cycles.transparent_max_bounces,\n cycles.transmission_bounces,\n cycles.volume_bounces,\n cycles.caustics_reflective,\n cycles.caustics_refractive,\n cycles.device,\n scene.render.engine,\n bpy.context.view_layer.objects.active,\n selected,\n [scene.render.resolution_x, scene.render.resolution_y]\n ]","sub_path":"addon/utility/octane/configure.py","file_name":"configure.py","file_ext":"py","file_size_in_byte":5007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"194867996","text":"import json\r\nimport psycopg2\r\n\r\ndef cleanStr4SQL(s):\r\n return s.replace(\"'\",\"`\").replace(\"\\n\",\" \")\r\n\r\ndef int2BoolStr (value):\r\n if value == 0:\r\n return 'False'\r\n else:\r\n return 'True'\r\n\r\ndef insert2BusinessTable():\r\n #reading the JSON file\r\n with open('./yelp_business.JSON','r') as f: #TODO: update path for the input file\r\n outfile = open('./yelp_business.SQL', 'w') #uncomment this line if you are writing the INSERT statements to an output file.\r\n line = f.readline()\r\n count_line = 0\r\n\r\n #connect to yelpdb database on postgres server using psycopg2\r\n #TODO: update the database name, username, and password\r\n try:\r\n conn = psycopg2.connect(\"dbname='milestone2' user='postgres' host='localhost' password='teamsk'\")\r\n except:\r\n print('Unable to connect to the database!')\r\n cur = conn.cursor()\r\n\r\n while line:\r\n data = json.loads(line)\r\n # Generate the INSERT statement for the cussent business\r\n # TODO: The below INSERT statement is based on a simple (and incomplete) businesstable schema. Update the statement based on lsyour own table schema and\r\n # include values for all businessTable attributes\r\n sql_str = \"INSERT INTO Business (Business_id, Name, State,City,Address,Zipcode,Stars,Is_open,Latitude,Longitude,Review_count,Review_ratings,Num_checkins) \" \\\r\n \"VALUES ('\" + cleanStr4SQL(data['business_id']) + \"','\" + cleanStr4SQL(data[\"name\"]) + \"','\" + cleanStr4SQL(data[\"state\"]) + \"','\" + \\\r\n cleanStr4SQL(data[\"city\"]) + \"','\" + cleanStr4SQL(data[\"address\"]) + \"','\" + cleanStr4SQL(data[\"postal_code\"]) + \"',\" + str(data[\"stars\"]) + \",\" + \\\r\n str(data[\"is_open\"]) + \",\" + str(data[\"latitude\"]) + \",\" + str(data[\"longitude\"]) + \",\" + str(data[\"review_count\"]) + \",0.0,0\" +\");\"\r\n\r\n try:\r\n cur.execute(sql_str)\r\n except:\r\n #print(\"Insert to businessTABLE failed!\"+ \" \" + data['business_id'] + \" \" + data['name'] +\" \"+ data['state'] + \" \" + data['city'] +\" \")\r\n print(\"Insert to businessTABLE failed! \\n\"+sql_str)\r\n conn.commit()\r\n # optionally you might write the INSERT statement to a file.\r\n outfile.write(sql_str)\r\n\r\n line = f.readline()\r\n count_line +=1\r\n\r\n cur.close()\r\n conn.close()\r\n\r\n print(count_line)\r\n outfile.close() #uncomment this line if you are writing the INSERT statements to an output file.\r\n f.close()\r\n\r\ndef insert2Categories():\r\n #reading the JSON file\r\n with open('./yelp_business.JSON','r') as f: #TODO: update path for the input file\r\n outfile = open('./yelp_categories.SQL', 'w') #uncomment this line if you are writing the INSERT statements to an output file.\r\n line = f.readline()\r\n count_line = 0\r\n\r\n #connect to yelpdb database on postgres server using psycopg2\r\n #TODO: update the database name, username, and password\r\n try:\r\n conn = psycopg2.connect(\"dbname='milestone2' user='postgres' host='localhost' password='teamsk'\")\r\n except:\r\n print('Unable to connect to the database!')\r\n cur = conn.cursor()\r\n\r\n while line:\r\n data = json.loads(line)\r\n for category in data['categories']:\r\n sql_str= \"INSERT INTO Categories (Business_id,Categories_name) \"\\\r\n \"VALUES ('\"+data['business_id']+\"','\"+cleanStr4SQL(category)+\"');\"\r\n #print(sql_str)\r\n #return\r\n try:\r\n cur.execute(sql_str)\r\n except:\r\n #print(\"Insert to businessTABLE failed!\"+ \" \" + data['business_id'] + \" \" + data['name'] +\" \"+ data['state'] + \" \" + data['city'] +\" \")\r\n print(\"Insert to CategoriesTable failed! \\n\"+sql_str)\r\n conn.commit()\r\n # optionally you might write the INSERT statement to a file.\r\n outfile.write(sql_str)\r\n count_line +=1\r\n line = f.readline()\r\n \r\n\r\n cur.close()\r\n conn.close()\r\n\r\n print(count_line)\r\n outfile.close() #uncomment this line if you are writing the INSERT statements to an output file.\r\n f.close()\r\n\r\ndef insert2Checkin():\r\n\r\n\r\n morning=[5,6,7,8,9,10]\r\n afternoon=[11,12,13,14,15,16]\r\n evening=[17,18,19,20,21,22]\r\n night=[23,0,1,2,3,4]\r\n count =0\r\n\r\n #reading the JSON file\r\n with open('./yelp_checkin.JSON','r') as f: #TODO: update path for the input file\r\n outfile = open('./yelp_checkin.SQL', 'w') #uncomment this line if you are writing the INSERT statements to an output file.\r\n line = f.readline()\r\n count_line = 0\r\n\r\n #connect to yelpdb database on postgres server using psycopg2\r\n #TODO: update the database name, username, and password\r\n try:\r\n conn = psycopg2.connect(\"dbname='milestone2' user='postgres' host='localhost' password='teamsk'\")\r\n except:\r\n print('Unable to connect to the database!')\r\n cur = conn.cursor()\r\n\r\n while line:\r\n data = json.loads(line)\r\n\r\n for i,j in data.items(): \r\n \r\n if(type(j) is dict):\r\n for x,y in j.items(): # x = dayname y = checkins with time \r\n checkin_filter = { 'morning' :0, 'afternoon':0, 'evening':0, 'night':0}\r\n for s,h in y.items():\r\n \r\n timeVar=s.split(\":\")\r\n #print(timeVar[0],h)\r\n \r\n if int(timeVar[0]) in morning:\r\n checkin_filter[\"morning\"]+=int(h)\r\n if int(timeVar[0]) in afternoon:\r\n checkin_filter[\"afternoon\"]+=int(h)\r\n if int(timeVar[0]) in evening:\r\n checkin_filter[\"evening\"]+=int(h)\r\n if int(timeVar[0]) in night:\r\n checkin_filter[\"night\"]+=int(h)\r\n #print(data['business_id'],\" \", x ,\" \",checkin_filter)\r\n for i,j in checkin_filter.items():\r\n #print(data['business_id'],\" \", x ,\" \",i,j)\r\n sql_str = \"INSERT INTO Checkin (Business_id, Checkin_day, Checkin_time,Checkin_count) \" \\\r\n \"VALUES ('\" + cleanStr4SQL(data['business_id']) + \"','\" + x+\"','\"+ i+\"','\"+str(j)+\"');\"\r\n try:\r\n cur.execute(sql_str)\r\n except:\r\n print(\"Insert to Checkin failed! \\n\"+sql_str)\r\n conn.commit()\r\n outfile.write(sql_str)\r\n count_line +=1\r\n # print(\"\\n\")\r\n #print(data['business_id'],x,checkin_filter)\r\n \r\n\r\n line = f.readline()\r\n cur.close()\r\n conn.close()\r\n\r\n print(count_line)\r\n outfile.close() #uncomment this line if you are writing the INSERT statements to an output file.\r\n f.close()\r\n\r\ndef insert2Hours():\r\n #reading the JSON file\r\n with open('./yelp_business.JSON','r') as f: #TODO: update path for the input file\r\n outfile = open('./yelp_hours.SQL', 'w') #uncomment this line if you are writing the INSERT statements to an output file.\r\n line = f.readline()\r\n count_line = 0\r\n\r\n #connect to yelpdb database on postgres server using psycopg2\r\n #TODO: update the database name, username, and password\r\n try:\r\n conn = psycopg2.connect(\"dbname='milestone2' user='postgres' host='localhost' password='teamsk'\")\r\n except:\r\n print('Unable to connect to the database!')\r\n cur = conn.cursor()\r\n\r\n while line:\r\n data = json.loads(line)\r\n if data['hours']!={}:\r\n for x,y in data['hours'].items():\r\n tem=(y.split(\"-\"))\r\n #print(data['business_id'],x,tem[0],tem[1])\r\n sql_str = \"INSERT INTO Hours (Business_id, Hours_day,Hours_open,Hours_close) \" \\\r\n \"VALUES ('\" + cleanStr4SQL(data['business_id']) + \"','\" + x+\"','\"+ tem[0]+\"','\"+tem[1]+\"');\"\r\n try:\r\n cur.execute(sql_str)\r\n except:\r\n print(\"Insert to businessTABLE failed! \\n\"+sql_str)\r\n conn.commit()\r\n # optionally you might write the INSERT statement to a file.\r\n count_line +=1\r\n outfile.write(sql_str)\r\n line = f.readline()\r\n cur.close()\r\n conn.close()\r\n print(count_line)\r\n outfile.close() #uncomment this line if you are writing the INSERT statements to an output file.\r\n f.close()\r\n\r\n\r\ndef insert2FriendsWith():\r\n #reading the JSON file\r\n with open('./yelp_user.JSON','r') as f: #TODO: update path for the input file\r\n outfile = open('./yelp_friendswith.SQL', 'w') #uncomment this line if you are writing the INSERT statements to an output file.\r\n line = f.readline()\r\n count_line = 0\r\n\r\n #connect to yelpdb database on postgres server using psycopg2\r\n #TODO: update the database name, username, and password\r\n try:\r\n conn = psycopg2.connect(\"dbname='milestone2' user='postgres' host='localhost' password='teamsk'\")\r\n except:\r\n print('Unable to connect to the database!')\r\n cur = conn.cursor()\r\n\r\n while line:\r\n data = json.loads(line)\r\n for i in data['friends']:\r\n #print(data['user_id'],\" \",i)\r\n sql_str = \"INSERT INTO Friends_with (user_id, Friends_id) \" \\\r\n \"VALUES ('\" + cleanStr4SQL(data['user_id']) + \"','\" + i+\"');\"\r\n try:\r\n cur.execute(sql_str)\r\n except:\r\n print(\"Insert to Friends_with failed! \\n\"+sql_str)\r\n conn.commit()\r\n # optionally you might write the INSERT statement to a file.\r\n count_line +=1\r\n outfile.write(sql_str)\r\n line = f.readline()\r\n cur.close()\r\n conn.close()\r\n print(count_line)\r\n outfile.close() #uncomment this line if you are writing the INSERT statements to an output file.\r\n f.close()\r\n\r\n\r\n\r\ndef insert2UsersTable():\r\n with open('./yelp_user.JSON','r') as f:\r\n outfile = open('./yelp_user.SQL', 'w')\r\n line = f.readline()\r\n count_line = 0\r\n try:\r\n conn = psycopg2.connect(\"dbname='milestone2' user='postgres' host='localhost' password='teamsk'\")\r\n except:\r\n print('Unable to connect to the database!')\r\n cur = conn.cursor()\r\n\r\n while line:\r\n data = json.loads(line)\r\n sql_str = \"INSERT INTO Users (User_id, Average_stars, Fans, Name, Cool,Funny,Useful,Review_count,Yelping_since, User_latitude, User_longitude) \" \\\r\n \"VALUES ('\" + cleanStr4SQL(data['user_id']) + \"',\" + str(data[\"average_stars\"]) + \",\" + str(data[\"fans\"]) + \",'\" + \\\r\n cleanStr4SQL(data[\"name\"]) + \"',\" + str(data[\"cool\"]) + \",\" + str(data[\"funny\"]) + \",\" + str(data[\"useful\"]) + \",\" + \\\r\n str(data[\"review_count\"]) + \",'\" + str(data[\"yelping_since\"]) + \"',0.0,0.0\" +\");\"\r\n try:\r\n cur.execute(sql_str)\r\n except:\r\n print(\"Insert to usersTable failed! \\n\"+sql_str)\r\n conn.commit()\r\n outfile.write(sql_str)\r\n line = f.readline()\r\n count_line +=1\r\n cur.close()\r\n conn.close()\r\n print(count_line)\r\n f.close()\r\n\r\n\r\ndef insert2ReviewTable():\r\n with open('./yelp_review.JSON','r') as f:\r\n outfile = open('./yelp_review.SQL', 'w')\r\n line = f.readline()\r\n count_line = 0\r\n try:\r\n conn = psycopg2.connect(\"dbname='milestone2' user='postgres' host='localhost' password='teamsk'\")\r\n except:\r\n print('Unable to connect to the database!')\r\n cur = conn.cursor()\r\n while line:\r\n data = json.loads(line)\r\n sql_str = \"INSERT INTO Review (Review_id, Text, Review_date, Review_stars,Funny,Cool,useful,Business_id,User_id) \" \\\r\n \"VALUES ('\" + cleanStr4SQL(data['review_id']) + \"','\" + cleanStr4SQL(data[\"text\"]) + \"','\" + str(data[\"date\"]) + \"',\" + \\\r\n str(data[\"stars\"]) + \",\" + str(data[\"funny\"]) + \",\" + str(data[\"cool\"]) + \",\" + str(data[\"useful\"]) + \",'\" + \\\r\n cleanStr4SQL(data[\"business_id\"]) +\"','\"+cleanStr4SQL(data[\"user_id\"])+\"');\"\r\n try:\r\n cur.execute(sql_str)\r\n except:\r\n print(\"Insert to ReviewTable failed! \\n\"+sql_str)\r\n conn.commit()\r\n outfile.write(sql_str)\r\n line = f.readline()\r\n count_line +=1\r\n cur.close()\r\n conn.close()\r\n print(count_line)\r\n f.close()\r\n\r\n\r\n\r\n\r\n\"\"\"\r\ninsert2BusinessTable()\r\ninsert2Categories()\r\ninsert2Checkin()\r\ninsert2Hours()\r\ninsert2UsersTable()\r\ninsert2FriendsWith()\r\ninsert2ReviewTable()\r\n\"\"\"\r\ninsert2ReviewTable()","sub_path":"Milestone2/TeamSK_milestone2/parseAndInsert_Sample.py","file_name":"parseAndInsert_Sample.py","file_ext":"py","file_size_in_byte":13612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"523613554","text":"\"\"\" Print report to the screen. \"\"\"\nfrom drupdates.constructors.reports import Report\n\nclass Druptest(Report):\n \"\"\" Print plugin to screen. \"\"\"\n\n def send_message(self, report_text):\n \"\"\" Print the report to the screen, or stdout.\"\"\"\n report_text = \"Drupdtest {0}\".format(report_text)\n print(report_text)\n","sub_path":"drupdates/tests/unit/classes/Stdout/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"6791714","text":"\nfrom django.db import models\nfrom django.db.migrations.operations import AlterField\n\nfrom sortedm2m.fields import SORT_VALUE_FIELD_NAME\n\nclass AlterSortedManyToManyField(AlterField):\n def database_forwards(self, app_label, schema_editor, from_state, to_state):\n super(AlterSortedManyToManyField, self).database_forwards(app_label, schema_editor, from_state, to_state)\n\n to = to_state.render().get_model(app_label, self.model_name)\n tf = to._meta.get_field_by_name(self.name)[0]\n m2m_model = tf.rel.through\n\n if hasattr(m2m_model._meta, 'db_table'):\n if hasattr(m2m_model, '_sort_field_name'):\n schema_editor.add_field(m2m_model, self.make_sort_by_field(m2m_model))\n\n def database_backwards(self, app_label, schema_editor, from_state, to_state):\n super(AlterSortedManyToManyField, self).database_backwards(app_label, schema_editor, from_state, to_state)\n\n f = from_state.render().get_model(app_label, self.model_name)\n ff = f._meta.get_field_by_name(self.name)[0]\n m2m_model = ff.rel.through\n\n if hasattr(m2m_model._meta, 'db_table'):\n if hasattr(m2m_model, '_sort_field_name'):\n schema_editor.remove_field(m2m_model, m2m_model._meta.get_field_by_name(SORT_VALUE_FIELD_NAME)[0])\n\n def make_sort_by_field(self, model):\n return models.IntegerField(name=SORT_VALUE_FIELD_NAME)\n","sub_path":"sortedm2m/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"17752379","text":"from src.src.controllers.service_controllers.SoundcloudController import SoundcloudController\nfrom src.src.controllers.service_controllers.SpotifyController import SpotifyController\nfrom src.src.models.Entity.Entity import Entity\n\nfrom src.src.controllers.service_controllers.TwitterController import TwitterController\n\n\ndef load_soundcloud():\n entities = Entity.get_all_entities()\n for entity in entities:\n SoundcloudController.get_entity_profile_info(entity=entity)\n print(\"soundcloud\")\n\n\ndef load_spotify():\n entities = Entity.get_all_entities()\n for entity in entities:\n SpotifyController.get_entity_profile_info(entity=entity)\n print(\"spotify\")\n\n\ndef load_twitter():\n entities = Entity.get_all_entities()\n for entity in entities:\n TwitterController.get_entity_profile_info(entity=entity)\n print(\"twitter\")","sub_path":"src/src/loaders/global_loader.py","file_name":"global_loader.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"448975903","text":"import nltk\r\nfrom nltk.corpus import brown\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport numpy as np\r\n\r\n# a function that will draw a 3D plot with axes for:\r\n# Word length (in characters)\r\n# Word frequency\r\n# Word ambiguity\r\ndef Plot3DCorrelation(tagWords):\r\n word_length = []\r\n word_frequency = []\r\n word_ambiguity = []\r\n \r\n words_by_freq = nltk.FreqDist([w for (w,t) in tagWords])\r\n difCouples = nltk.FreqDist(tagWords).keys()\r\n word_by_ambiguity = nltk.FreqDist([w for (w,t) in difCouples])\r\n for w in words_by_freq.keys():\r\n word_frequency.append(words_by_freq[w])\r\n word_length.append(len(w)) \r\n word_ambiguity.append(word_by_ambiguity[w]) \r\n\r\n fig = plt.figure()\r\n ax = fig.gca(projection='3d')\r\n ax.set_title('Correlation between word size or frequency and ambiguity level')\r\n ax.set_xlabel('Word frequency')\r\n ax.set_ylabel('Word ambiguity')\r\n ax.set_zlabel('Word length')\r\n ax.scatter( word_frequency , word_ambiguity ,word_length, c='b')\r\n \r\n plt.show()\r\n \r\ndef main():\r\n tagWords = brown.tagged_words(categories='news')\r\n Plot3DCorrelation(tagWords)\r\n \r\nif __name__ == '__main__':\r\n main() ","sub_path":"NLP1/q1_3.py","file_name":"q1_3.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"394201475","text":"import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom pprint import pprint\n\nscope = [\"https://spreadsheets.google.com/feeds\",'https://www.googleapis.com/auth/spreadsheets',\"https://www.googleapis.com/auth/drive.file\",\"https://www.googleapis.com/auth/drive\"]\n\ncreds = ServiceAccountCredentials.from_json_keyfile_name(\"creds.json\",scope)\n\nclient = gspread.authorize(creds)\n\nsheet = client.open(\"database\").sheet1\n\ndata=sheet.get_all_records()\n\ncolumn = sheet.col_values(3)\nrow = sheet.row_values(3)\ncell = sheet.cell(1,2).value\n\n\n#insertRow = [\"hello\", 5, \"red\", \"blue\"]\n#sheet.add_rows(insertRow, 4) # Insert the list as a row at index 4\n\n#sheet.update_cell(2,2, \"CHANGED\") # Update one cell\n\npprint(row)\n\n# /* sheetsID 1uqCwaVqo4EV3DC4Ue8bpi4BdwVLwzTG1w_xq6YTyxEU\n# api key=AIzaSyDoQGn2-znSaFRPN9Ks_ZUWyXL4NxMKIEY */","sub_path":"Raspberry/Main/grace/old/sheets.py","file_name":"sheets.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"255351175","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nimport os\n\nfrom setuptools import setup, find_packages\n\n#version\nhere = os.path.dirname(os.path.abspath(__file__))\nversion = next((line.split(\"=\")[1].strip().replace(\"\\\"\", \"\") for line in open(os.path.join(here,\"pytimetrack\",\"__init__.py\")) if line.startswith(\"__version__ = \")),\"0.0.0\")\nprint(version)\n\ntry:\n with open(\"README.rst\") as f:\n readme = f.read()\nexcept IOError:\n readme = \"\"\n\ndef _requires_from_file(filename):\n return open(filename).read().splitlines()\n\nsetup(\n name = \"pytimetrack\",\n version = version,\n author = \"Yusaku Takano\",\n author_email= \"takano-yuusaku@ed.tmu.ac.jp\",\n license = \"MIT License\",\n description = \"Track Classification\",\n long_description=readme,\n packages=find_packages(),\n url=\"https://github.com/ty-edelweiss/pycurvature\",\n install_requires=_requires_from_file(\"requirements.txt\"),\n classifiers = [\n \"Programming Language :: Python :: 3.6\",\n \"License :: OSI Approved :: MIT License\"\n ],\n)\n","sub_path":"pypi_install_script/pytimetrack-0.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"63259008","text":"from string import ascii_lowercase\r\n\r\ns = input()\r\nt = input()\r\n\r\nd_s2t = dict()\r\nd_t2s = dict()\r\n\r\nflg = True\r\nfor ss, tt in zip(s, t):\r\n if d_s2t.get(ss) is None:\r\n d_s2t[ss] = tt\r\n else:\r\n if not d_s2t[ss] == tt:\r\n flg = False\r\n break\r\n\r\n if d_t2s.get(tt) is None:\r\n d_t2s[tt] = ss\r\n else:\r\n if not d_t2s[tt] == ss:\r\n flg = False\r\n break\r\n\r\nif flg:\r\n if len(set(d_s2t.keys())) != len(set(d_s2t.values())):\r\n flg = False\r\n if len(set(d_t2s.keys())) != len(set(d_t2s.values())):\r\n flg = False\r\n\r\nprint('Yes' if flg else 'No')","sub_path":"Source Codes/AtCoder/abc110/C/4937630.py","file_name":"4937630.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"646833740","text":"# (Hint: You might try importing a data structure you built during the week)\n\nimport time\n\nfrom binary_search_tree import BSTNode\n\nstart_time = time.time()\n\nf = open('names_1.txt', 'r')\nnames_1 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nf = open('names_2.txt', 'r')\nnames_2 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nduplicates = [] # Return the list of duplicates in this data structure\n\n# grab the first name to start tree\nbst = BSTNode(names_1[0])\n\n# insert the rest from first file into the tree\nfor name in names_1[1:]:\n bst.insert(name)\n\nfor name in names_2:\n if bst.contains(name):\n duplicates.append(name)\n\n\nend_time = time.time()\nprint(\n f\"{len(duplicates)} duplicates:\\n\\n{', '.join(duplicates)}\\n\\n\")\nprint(f\"runtime: {end_time - start_time} seconds*******Logarithmic Time******\")\n\n\n# ---------- Stretch Goal -----------\n# Python has built-in tools that allow for a very efficient approach to this problem\n# What's the best time you can accomplish? There are no restrictions on techniques or data\n# structures, but you may not import any additional libraries that you did not write yourself.\n\nstretch_duplicates = []\nstart_time = time.time()\ncache = {}\nfor name in names_1:\n if name not in cache:\n cache[name] = name\n\nfor name in names_2:\n if name in cache:\n stretch_duplicates.append(name)\n\nend_time = time.time()\nprint(\n f\"\\n\\n{len(stretch_duplicates)} duplicates:\\n\\n{', '.join(stretch_duplicates)}\\n\\n\")\nprint(f\"runtime: {end_time - start_time} ***********STRETCH is FASTER**********\")","sub_path":"names/names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"65503955","text":"import time\nimport threading\n\n_lock = threading.Lock()\n\n\nclass MyThread(threading.Thread):\n def __init__(self, thread_id, thread_name, exec_count, time_interval, whether_lock):\n threading.Thread.__init__(self)\n self.thread_id = thread_id # 自定义线程ID\n self.thread_name = thread_name # 自定义线程名字\n self.exec_count = exec_count # 线程执行次数\n self.time_interval = time_interval # 线程执行前后的间隔\n self.whether_lock = whether_lock # 是否加锁\n\n def run(self) -> None:\n print('# %s start...' % self.thread_name)\n if self.whether_lock:\n _lock.acquire()\n be_called(self.thread_name, self.time_interval, self.exec_count)\n _lock.release()\n else:\n be_called(self.thread_name, self.time_interval, self.exec_count)\n print('# %s end...' % self.thread_name)\n\n\ndef be_called(thread_name, time_interval, count):\n while count:\n time.sleep(time_interval)\n print('%s: %s' % (thread_name, time.ctime(time.time())))\n count -= 1\n\n\nif __name__ == '__main__':\n thread_list = []\n thread1 = MyThread(thread_id=1, thread_name='thread1', exec_count=3, time_interval=1, whether_lock=True)\n thread2 = MyThread(thread_id=2, thread_name='thread2', exec_count=3, time_interval=2, whether_lock=True)\n\n thread1.start()\n thread2.start()\n\n thread_list.append(thread1)\n thread_list.append(thread2)\n\n for thread in thread_list:\n thread.join()\n\n print('主线程退出!')\n","sub_path":"Async/Thread/sync_thread.py","file_name":"sync_thread.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"116184668","text":"# -*- encoding: utf-8 -*-\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 unittest\n\nfrom tuskar.templates import heat\nfrom tuskar.templates import namespace as ns_utils\nfrom tuskar.templates import plan\n\n\nclass DeploymentPlanTests(unittest.TestCase):\n\n def test_empty(self):\n # Test\n p = plan.DeploymentPlan(description='test-desc')\n str(p) # should not error\n\n # Verify\n self.assertTrue(isinstance(p.master_template, heat.Template))\n self.assertTrue(isinstance(p.environment, heat.Environment))\n self.assertEqual('test-desc', p.master_template.description)\n\n def test_existing_pieces(self):\n # Test\n t = heat.Template()\n e = heat.Environment()\n p = plan.DeploymentPlan(master_template=t, environment=e)\n\n # Verify\n self.assertTrue(p.master_template is t)\n self.assertTrue(p.environment is e)\n\n def test_add_template(self):\n # Test\n p = plan.DeploymentPlan()\n t = self._generate_template()\n p.add_template('ns1', t, 'template-1.yaml')\n\n # Verify Master Template Parameters\n self.assertEqual(2, len(p.master_template.parameters))\n for original, added in zip(t.parameters, p.master_template.parameters):\n self.assertTrue(added is not original)\n\n expected_name = ns_utils.apply_template_namespace('ns1',\n original.name)\n self.assertEqual(added.name, expected_name)\n self.assertEqual(added.param_type, original.param_type)\n\n # Verify Resource\n self.assertEqual(1, len(p.master_template.resources))\n added = p.master_template.resources[0]\n\n expected_id = plan._generate_resource_id('ns1')\n self.assertEqual(added.resource_id, expected_id)\n expected_type = ns_utils.apply_resource_alias_namespace('ns1')\n self.assertEqual(added.resource_type, expected_type)\n\n for param, prop in zip(t.parameters, added.properties):\n v = ns_utils.apply_template_namespace('ns1', param.name)\n expected_value = {'get_param': [v]}\n self.assertEqual(prop.value, expected_value)\n\n # Verify Environment Parameters\n self.assertEqual(2, len(p.environment.parameters))\n for env_param, template_param in zip(p.environment.parameters,\n t.parameters):\n expected_name =\\\n ns_utils.apply_template_namespace('ns1', template_param.name)\n self.assertEqual(env_param.name, expected_name)\n self.assertEqual(env_param.value, '')\n\n # Verify Resource Registry Entry\n self.assertEqual(1, len(p.environment.registry_entries))\n added = p.environment.registry_entries[0]\n expected_alias = ns_utils.apply_resource_alias_namespace('ns1')\n self.assertEqual(added.alias, expected_alias)\n self.assertEqual(added.filename, 'template-1.yaml')\n\n def test_remove_template(self):\n # Setup & Sanity Check\n p = plan.DeploymentPlan()\n t = self._generate_template()\n p.add_template('ns1', t, 'template-1.yaml')\n p.add_template('ns2', t, 'template-2.yaml')\n\n self.assertEqual(4, len(p.master_template.parameters))\n self.assertEqual(4, len(p.master_template.outputs))\n self.assertEqual(2, len(p.master_template.resources))\n\n self.assertEqual(4, len(p.environment.parameters))\n self.assertEqual(2, len(p.environment.registry_entries))\n\n # Test\n p.remove_template('ns1')\n\n # Verify\n self.assertEqual(2, len(p.master_template.parameters))\n self.assertEqual(2, len(p.master_template.outputs))\n self.assertEqual(1, len(p.master_template.resources))\n\n self.assertEqual(2, len(p.environment.parameters))\n self.assertEqual(1, len(p.environment.registry_entries))\n\n def test_set_value(self):\n # Setup\n p = plan.DeploymentPlan()\n set_me = heat.EnvironmentParameter('p1', 'v1')\n p.environment.add_parameter(set_me)\n\n # Test\n p.set_value('p1', 'v2')\n\n # Verify\n self.assertEqual(p.environment.find_parameter_by_name('p1').value,\n 'v2')\n\n def test_set_value_missing_parameter(self):\n # Setup\n p = plan.DeploymentPlan()\n\n # Test\n self.assertRaises(ValueError, p.set_value, 'missing', 'irrelevant')\n\n def _generate_template(self):\n t = heat.Template()\n\n t.add_parameter(heat.Parameter('param-1', 'type-1'))\n t.add_parameter(heat.Parameter('param-2', 'type-2'))\n\n t.add_output(heat.Output('out-1', 'value-1'))\n t.add_output(heat.Output('out-2', 'value-2'))\n\n return t\n","sub_path":"tuskar/tests/templates/test_plan.py","file_name":"test_plan.py","file_ext":"py","file_size_in_byte":5283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"589143856","text":"# coding: utf-8\n\"\"\" 「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ. \"\"\"\n\ndef main():\n \"\"\"\n zipで複数のシーケンスオブジェクトを同時にループ回せる.\n sep.join(seq)はsepを区切り文字としてseqを連結しひとつの文字列にする.\n リスト内包表記したものを空文字でjoinしている.\n \"\"\"\n string = \"\".join(i+j for i, j in zip(\"パトカー\", \"タクシー\"))\n print(string)\n\nif __name__ == '__main__':\n main()\n","sub_path":"chapter1/knock02.py","file_name":"knock02.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"113880253","text":"incomingAJAXData = [\n\t{ \"name\": 'Mario', \"lastName\": 'Montes' },\n\t{ \"name\": 'Joe', \"lastName\": 'Biden' },\n\t{ \"name\": 'Bill', \"lastName\": 'Clon' },\n\t{ \"name\": 'Hilary', \"lastName\": 'Mccafee' },\n\t{ \"name\": 'Bobby', \"lastName\": 'Mc birth' }\n]\n\n#Your code go here:\ndef my_var(x):\n\tnewArr=x[\"name\"]+' '+x[\"lastName\"]\n\treturn newArr\ntransformedData = list(map(my_var, incomingAJAXData))\nprint(transformedData)","sub_path":"exercises/12.6-Transformers/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"89471682","text":"from rdkit import Chem\nfrom rdkit.Chem import MolStandardize\nfrom tqdm import tqdm\nfrom classes import Tokenizer\n\n\nclass Preprocess:\n\n def __init__(self):\n self.nrm = MolStandardize.normalize.Normalizer()\n self.lfc = MolStandardize.fragment.LargestFragmentChooser()\n self.uc = MolStandardize.charge.Uncharger()\n\n def clean(self, smi):\n mol = Chem.MolFromSmiles(smi)\n if mol:\n mol = self.nrm.normalize(mol)\n mol = self.lfc.choose(mol)\n mol = self.uc.uncharge(mol)\n return Chem.MolToSmiles(mol, isomericSmiles=False, canonical=True)\n else:\n return None\n\n\nif __name__ == \"__main__\":\n\n with open('data/canonical_smiles.smi', 'r') as file:\n smiles = [line.rstrip() for line in file]\n\n print(\"Initial number of sequences %i\" % len(smiles))\n p = Preprocess()\n t = Tokenizer()\n\n # Normalization, uncharging, removing chirality and light fragments\n nn_smi = [p.clean(smile) for smile in tqdm(smiles)]\n unn_smi = list(set([smile for smile in nn_smi if smile]))\n\n # Limit sequence length 34-128\n cl_smi = []\n for smile in unn_smi:\n if 34 <= len(t.tokenize(smile)) <= 128:\n cl_smi.append(smile)\n\n print(\"Number of sequences after cleaning %i\" % len(cl_smi))\n\n with open('data/cleaned_smiles.smi', 'w') as file:\n for line in cl_smi:\n file.write(line + '\\n')\n\n\n\n\n","sub_path":"cleanup_smiles.py","file_name":"cleanup_smiles.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"175847750","text":"#!/usr/bin/env python\nimport rospy\nfrom geometry_msgs.msg import PoseStamped\nfrom std_msgs.msg import Header\nfrom trajectory_msgs.msg import MultiDOFJointTrajectory\nfrom threading import Thread\nfrom math import atan2\nfrom tf.transformations import quaternion_from_euler\nfrom numpy.linalg import norm\n\n\n\nclass OffboardPosctl():\n def __init__(self):\n self.local_pos = PoseStamped()\n self.local_pos_sub = rospy.Subscriber('mavros/local_position/pose', PoseStamped, self.local_pos_callback)\n self.trajectory = MultiDOFJointTrajectory()\n self.trajectory_sub = rospy.Subscriber('waypoints', MultiDOFJointTrajectory, self.trajectory_callback)\n self.curr_goal = PoseStamped()\n self.curr_goal_pub = rospy.Publisher('mavros/setpoint_position/local', PoseStamped, queue_size=1)\n self.sub_topics_ready = {\n key: False\n for key in [\n 'local_pos', 'trajectory'\n ]\n }\n self.curr_goal_thread = Thread(target=self.mainLoop, args=())\n self.curr_goal_thread.daemon = True\n self.curr_goal_thread.start()\n \n def local_pos_callback(self, data):\n self.local_pos = data\n if not self.sub_topics_ready['local_pos']:\n self.sub_topics_ready['local_pos'] = True\n\n def trajectory_callback(self, data):\n self.trajectory = data\n if not self.sub_topics_ready['trajectory']:\n self.sub_topics_ready['trajectory'] = True\n self.curr_goal.pose.position.x = self.trajectory.points[1].transforms[0].translation.x\n self.curr_goal.pose.position.y = self.trajectory.points[1].transforms[0].translation.y\n self.curr_goal.pose.position.z = self.trajectory.points[1].transforms[0].translation.z\n print(\"got trajectory bitches\")\n\n def mainLoop(self):\n YAW_THRESH = .5\n rate = rospy.Rate(10)\n self.curr_goal.header = Header()\n self.curr_goal.header.frame_id = \"base_link\"\n while not rospy.is_shutdown():\n if self.sub_topics_ready['trajectory'] and self.sub_topics_ready['local_pos']:\n self.curr_goal.header.stamp = rospy.Time.now()\n diffs = [self.curr_goal.pose.position.x - self.local_pos.pose.position.x, self.curr_goal.pose.position.y - self.local_pos.pose.position.y]\n if norm(diffs) > YAW_THRESH:\n yaw = atan2(diffs[1], diffs[0])\n q = quaternion_from_euler(0, 0, yaw)\n self.curr_goal.pose.orientation.x = q[0]\n self.curr_goal.pose.orientation.y = q[1]\n self.curr_goal.pose.orientation.z = q[2]\n self.curr_goal.pose.orientation.w = q[3]\n self.curr_goal_pub.publish(self.curr_goal)\n try:\n rate.sleep()\n except rospy.ROSInterruptException:\n pass\n \nif __name__ == '__main__':\n rospy.init_node('test_node', anonymous=True)\n print(\"starting bitches\")\n posctl = OffboardPosctl();\n\n rospy.spin();\n","sub_path":"trajectory_gen/scripts/breadcrumb.py","file_name":"breadcrumb.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"505413451","text":"\"\"\"\nApple Push Notification Service\nDocumentation is available on the iOS Developer Library:\nhttps://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/...\nApplePushService.html\n\"\"\"\n\nimport json\nimport ssl\nimport struct\nfrom binascii import unhexlify\nfrom socket import socket\nfrom django.core.exceptions import ImproperlyConfigured\nfrom . import NotificationError\nfrom .settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS\nfrom datetime import datetime\n\n\nclass APNSError(NotificationError):\n\tpass\n\n\nclass APNSDataOverflow(APNSError):\n\tpass\n\nAPNS_MAX_NOTIFICATION_SIZE = 256\nAPNS_SOCKET = 0\nAPNS_FEEDBACK_SOCKET = 1\n\n\ndef _apns_create_socket(socket_type):\n\tsock = socket()\n\tcertfile = SETTINGS.get(\"APNS_CERTIFICATE\")\n\tif not certfile:\n\t\traise ImproperlyConfigured(\n\t\t\t'You need to set PUSH_NOTIFICATIONS_SETTINGS[\"APNS_CERTIFICATE\"] to send messages through APNS.'\n\t\t)\n\n\ttry:\n\t\tf = open(certfile, \"r\")\n\t\tf.read()\n\t\tf.close()\n\texcept Exception as e:\n\t\traise ImproperlyConfigured(\"The APNS certificate file at %r is not readable: %s\" % (certfile, e))\n\n\tsock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv3, certfile=certfile)\n\tif socket_type is APNS_SOCKET:\n\t\tsock.connect((SETTINGS[\"APNS_HOST\"], SETTINGS[\"APNS_PORT\"]))\n\telse:\n\t\tsock.connect((SETTINGS[\"APNS_FEEDBACK_HOST\"], SETTINGS[\"APNS_FEEDBACK_PORT\"]))\n\n\treturn sock\n\n\ndef _apns_pack_message(token, data):\n\tfmt = \"!cH32sH%ds\" % (len(data))\n\treturn struct.pack(fmt, b\"\\0\", 32, unhexlify(token), len(data), data)\n\n\ndef _apns_unpack_feedback(data):\n\tfmt = '!lh32s'\n\ttimestamp, _, token = struct.unpack(fmt, data)\n\treturn timestamp, token\n\n\ndef _apns_send(token, alert, badge=0, sound=\"chime\", content_available=False, action_loc_key=None, loc_key=None,\n\t\t\t\tloc_args=None, extra=None, socket=None):\n\tdata = {}\n\n\tif action_loc_key or loc_key or loc_args:\n\t\talert = {\"body\": alert}\n\t\tif action_loc_key:\n\t\t\talert[\"action-loc-key\"] = action_loc_key\n\t\tif loc_key:\n\t\t\talert[\"loc-key\"] = loc_key\n\t\tif loc_args:\n\t\t\talert[\"loc-args\"] = loc_args\n\n\tdata[\"alert\"] = alert\n\n\tif badge:\n\t\tdata[\"badge\"] = badge\n\n\tif sound:\n\t\tdata[\"sound\"] = sound\n\n\tif content_available:\n\t\tdata[\"content-available\"] = 1\n\n\tif extra:\n\t\tdata.update(extra)\n\n\t# convert to json, avoiding unnecessary whitespace with separators\n\tdata = json.dumps({\"aps\": data}, separators=(\",\", \":\"))\n\n\tif len(data) > APNS_MAX_NOTIFICATION_SIZE:\n\t\traise APNSDataOverflow(\"Notification body cannot exceed %i bytes\" % (APNS_MAX_NOTIFICATION_SIZE))\n\n\tdata = _apns_pack_message(token, data)\n\n\tif socket:\n\t\tsocket.write(data)\n\telse:\n\t\tsocket = _apns_create_socket(APNS_SOCKET)\n\t\tsocket.write(data)\n\t\tsocket.close()\n\n\ndef apns_send_message(registration_id, data, **kwargs):\n\t\"\"\"\n\tSends an APNS notification to a single registration_id.\n\tThis will send the notification as form data.\n\tIf sending multiple notifications, it is more efficient to use\n\tapns_send_bulk_message()\n\tNote that \\a data should always be a string.\n\t\"\"\"\n\n\treturn _apns_send(registration_id, data, **kwargs)\n\n\ndef apns_send_bulk_message(registration_ids, data, **kwargs):\n\t\"\"\"\n\tSends an APNS notification to one or more registration_ids.\n\tThe registration_ids argument needs to be a list.\n\t\"\"\"\n\tsocket = _apns_create_socket(APNS_SOCKET)\n\tfor registration_id in registration_ids:\n\t\t_apns_send(registration_id, data, socket=socket, **kwargs)\n\n\tsocket.close()\n\n\ndef apns_get_feedback():\n\tsocket = _apns_create_socket(APNS_FEEDBACK_SOCKET)\n\tdevices = []\n\twhile True:\n\t\tdata = socket.recv(38)\n\t\tif len(data) is 0:\n\t\t\tbreak\n\t\ttimestamp, token = _apns_unpack_feedback(data)\n\t\tdevices.append({\n\t\t\t'timestamp': datetime.utcfromtimestamp(timestamp),\n\t\t\t'token': token\n\t\t})\n\tsocket.close()\n\treturn devices\n","sub_path":"push_notifications/apns.py","file_name":"apns.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"361919045","text":"#!/usr/bin/env python3\n\n# pip3 install python-varname\nfrom varname import varname\nimport copy\n \nBOND_NONE = -2\nBOND_PLUS = -1 \n\nSTATE_UNSET = 'state_unset'\n\n# using BNGL naming for classes, samne as here: https://www.dropbox.com/s/rm0535pgom2zr6i/Sekar-RuleBasedPrimer-2012.pdf?dl=0\n#\n# also, this is just an example, there might be some things not completely thought through \n# regarding states and bonds, e.g. which are unset, which are don't care \n# \n\nclass ComponentType:\n def __init__(self, states=[], name=''):\n \n # name and allowed_states serve for component template\n if name: \n self.name = name\n else:\n self.name = varname() # store the name of the created object variable (maintained with shallow copy)\n \n # states are converted to string\n self.allowed_states = [] \n for s in states:\n self.allowed_states.append(str(s))\n\n # called when the object is called as a function\n # creates an instance from a previously created template \n def __call__(self, state=STATE_UNSET, bond=BOND_NONE):\n return ComponentInstance(self, state, bond)\n\n # prints out the declaration of the component in BNGL (template information)\n def __str__(self):\n res = self.name\n \n for s in self.allowed_states:\n res += '~' + s \n\n return res\n\n\nclass ComponentInstance:\n def __init__(self, component_type: ComponentType, state:str=STATE_UNSET, bond:int=BOND_NONE):\n self.component_type = component_type\n self.bond = bond\n self.state = STATE_UNSET\n \n state = str(state)\n # set component state\n if state != STATE_UNSET:\n if state not in self.component_type.allowed_states:\n msg = 'ComponentType ' + self.component_type.name + ': state ' + state + ' is not in allowed states ' + str(self.allowed_states) + '.'\n raise ValueError(msg)\n else:\n self.state = state\n\n \n def __str__(self):\n res = self.component_type.name\n \n if self.state != STATE_UNSET:\n res += '~' + self.state \n\n if self.bond != BOND_NONE:\n if self.bond == BOND_PLUS:\n res += '!+'\n else:\n res += '!' + str(self.bond)\n \n return res \n \nclass MoleculeType:\n def __init__(self, diff_const, name = '', components=[]):\n # name, diff_const, and all_components serve for component template\n if name: \n self.name = name\n else:\n self.name = varname() # store the name of the created object variable (maintained with shallow copy)\n self.diff_const = diff_const\n \n self.components = []\n for ct in components:\n if type(ct) != ComponentType:\n raise ValueError('Only objects of ComponentType can be passed as MoleculeType components.') \n self.components.append(ct) \n self.all_components = components\n \n\n def __call__(self, *args):\n return MoleculeInstance(self, *args)\n \n \n # prints out the declaration of the component in BNGL (template information) \n def __str__(self):\n res = self.name + '('\n \n num_components = len(self.all_components)\n for i in range(num_components):\n res += str(self.all_components[i])\n if i != num_components-1:\n res += ',' \n \n res += ')'\n return res \n \n \nclass MoleculeInstance:\n def __init__(self, molecule_type: MoleculeType, *args):\n self.molecule_type = molecule_type\n \n self.components = []\n for ci in args:\n if type(ci) != ComponentInstance:\n raise ValueError('Only objects of ComponentInstance can be passed as MoleculeInstance components.') \n self.components.append(ci)\n\n # prints out speicifc instance information \n def __str__(self):\n res = self.molecule_type.name + '('\n \n num_components = len(self.components)\n for i in range(num_components):\n res += str(self.components[i])\n if i != num_components-1:\n res += ',' \n \n res += ')'\n return res \n \n \n# used in reactions as reactants and products as a matching pattern \nclass ComplexInstance:\n def __init__(self, *args):\n self.molecule_types = []\n \n for v in args:\n if type(v) != MoleculeInstance:\n raise ValueError('Only objects of MoleculeInstance can be passed as Complex constructor arguments.') \n self.molecule_types.append(v)\n \n \n def __str__(self): \n res = ''\n \n num_molecule_types = len(self.molecule_types)\n for i in range(num_molecule_types):\n res += str(self.molecule_types[i])\n if i != num_molecule_types-1:\n res += '.' \n return res\n \n \nclass RxnRule:\n def __init__(self, name, fwd_rate, rev_rate, reactants, products):\n self.name = name\n self.fwd_rate = fwd_rate\n self.rev_rate = rev_rate \n # TODO: check types of passed objects\n self.reactants = reactants\n self.products = products\n \n def __str__(self): \n res = \"\"\n res += \"name: \" + self.name + \"\\n\"\n res += \"fwd_rate: \" + str(self.fwd_rate) + \"\\n\"\n res += \"rev_rate: \" + str(self.rev_rate) + \"\\n\" \n res += \"reactants:\\n\"\n for r in self.reactants:\n res += \" \" + str(r) + \"\\n\"\n res += \"products:\\n\"\n for p in self.products:\n res += \" \" + str(p) + \"\\n\"\n \n return res\n \n# ------------------------- definition of molecule types and reactions --------------\n \n# ------------------------- CaM -------------- \n\nC = ComponentType( \n states = [0,1,2]\n)\n\nprint(\"ComponentType declaration:\")\nprint(C) \nprint(\"\")\n\nN = ComponentType(\n states = [0,1,2]\n)\nng = ComponentType()\ncamkii = ComponentType()\n\n\n\nY286 = ComponentType(\n states = ['0','P']\n)\n\n\nCaM = MoleculeType(\n diff_const =10.0,\n components = [C, N]\n)\n\n# ------------------------- CaMKII --------------\n\n\n\nd = ComponentType() # no states \nl = ComponentType()\nr = ComponentType()\nY286 = ComponentType(\n states = ['0','P']\n)\nS306 = ComponentType(\n states = ['0','P']\n)\ncam = ComponentType()\n\n\nCaMKII = MoleculeType(\n diff_const =10.0,\n components = [d, r, l, Y286, S306] \n)\n \nprint(\"Molecule type declaration:\")\nprint(CaM)\nprint(\"\")\n \nprint(\"Molecule type declaration:\")\nprint(CaMKII)\nprint(\"\")\n\nmol_type_inst = CaMKII( d(), r(), l(), Y286(0), S306(0), cam() )\n\nprint(\"Molecule type instance:\")\nprint(mol_type_inst)\nprint(\"\")\n\n# this is already an instance of a complex\n# serves as a pattern when used in a reaction\ncplx = ComplexInstance( \n # Y286('0') means Y286~0\n CaMKII( d(), r(), l(bond=1), Y286(0), S306(0), cam() ),\n CaMKII( d(), r(bond=1), l(), Y286(0), S306(0), cam() )\n)\n\nprint(\"Complex instance:\")\nprint(cplx)\nprint(\"\")\n\n\nV = 0.125*1e-15 # um^3 -> liters\nNA = 6.022e23/1e6\nk_onCaMKII = 50/(NA*V) #1/uM 1/s \nk_offCaMKII = 60 #1/s \n \n# CaMKII(l,r,Y286~0,cam!+) + CaMKII(l,r,cam!+) <-> CaMKII(l!1,r,Y286~0,cam!+).CaMKII(l,r!1,cam!+) k_onCaMKII, k_offCaMKII \nrxn = RxnRule(\n name = \"sixth rxn\",\n fwd_rate = k_onCaMKII,\n rev_rate = k_offCaMKII, # I found more often 'reverse reaction' to be used than 'backward reaction', but please comment on this if bkwd_rate makes more sense\n # note: components are in different order than in molecule type definition, this is apparently allowed\n \n # component patter is used with the meaning that when no state is specified, any state is fine\n reactants=[\n ComplexInstance( \n CaMKII( l(), r(), Y286('0'), cam(bond=BOND_PLUS) ) \n ),\n ComplexInstance( \n CaMKII( l(), r(), cam(bond=BOND_PLUS) ) \n )\n ], \n products=[\n ComplexInstance( \n CaMKII( l(bond=1), r(), Y286('0'), cam(bond=BOND_PLUS) ),\n CaMKII( l(), r(bond=1), cam(bond=BOND_PLUS) )\n )\n ]\n)\n\n\nprint(\"Reaction rule:\")\nprint(rxn)\nprint(\"\")\n\n\n","sub_path":"api_prototype_2020/bng_species_and_rxns/bngl_proposal_functor.py","file_name":"bngl_proposal_functor.py","file_ext":"py","file_size_in_byte":8394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"629445239","text":"\r\nfrom __future__ import print_function\r\nimport argparse\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nfrom torchvision import datasets, transforms\r\nfrom torch.optim.lr_scheduler import StepLR\r\nimport matplotlib.pyplot as plt\r\n\r\nrunning_loss_list= []\r\nepochs_list = []\r\naccuracy_list = []\r\n\r\nclass Net(nn.Module):\r\n def __init__(self):\r\n super(Net, self).__init__()\r\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\r\n self.conv2 = nn.Conv2d(32, 64, 3, 1)\r\n self.fc1 = nn.Linear(9216, 128)\r\n self.fc2 = nn.Linear(128, 10)\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n x = F.relu(x)\r\n x = self.conv2(x)\r\n x = F.relu(x)\r\n x = F.max_pool2d(x, 2)\r\n x = torch.flatten(x, 1)\r\n x = self.fc1(x)\r\n x = F.relu(x)\r\n x = self.fc2(x)\r\n output = F.log_softmax(x, dim=1)\r\n return output\r\n\r\n\r\nclass Net2(nn.Module):\r\n def __init__(self):\r\n super(Net2, self).__init__()\r\n self.conv1 = nn.Conv2d(1, 16, 3, 1)\r\n self.conv2 = nn.Conv2d(16, 32, 3, 1)\r\n self.conv3 = nn.Conv2d(32, 64, 3, 1)\r\n self.conv4 = nn.Conv2d(64, 128, 3, 1)\r\n self.fc1 = nn.Linear(2048, 128)\r\n self.fc2 = nn.Linear(128, 10)\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n x = F.relu(x)\r\n x = self.conv2(x)\r\n x = F.relu(x)\r\n x = F.max_pool2d(x, 2)\r\n x = self.conv3(x)\r\n x = F.relu(x)\r\n x = self.conv4(x)\r\n x = F.relu(x)\r\n x = F.max_pool2d(x, 2)\r\n x = torch.flatten(x, 1)\r\n x = self.fc1(x)\r\n x = F.relu(x)\r\n x = self.fc2(x)\r\n output = F.log_softmax(x, dim=1)\r\n return output\r\nclass BasicBlock(nn.Module):\r\n\tdef __init__(self, channel_num):\r\n\t\tsuper(BasicBlock, self).__init__()\r\n\t\tself.conv_block1 = nn.Sequential(\r\n\t\t\tnn.Conv2d(channel_num, channel_num, 3, padding=1),\r\n\t\t\tnn.BatchNorm2d(channel_num),\r\n\t\t\tnn.ReLU(),\r\n\t\t) \r\n\t\tself.conv_block2 = nn.Sequential(\r\n\t\t\tnn.Conv2d(channel_num , channel_num, 3, padding=1),\r\n\t\t\tnn.BatchNorm2d(channel_num),\r\n\t\t)\r\n\t\tself.relu = nn.ReLU()\r\n\t\r\n\tdef forward(self, x):\r\n\t\tresidual = x\r\n\t\tx = self.conv_block1(x)\r\n\t\tx = self.conv_block2(x)\r\n\t\tx = x + residual\r\n\t\tout = self.relu(x)\r\n\t\treturn out\r\n \r\nclass Net3(nn.Module):\r\n def __init__(self):\r\n channel_num = 32\r\n super(Net3, self).__init__()\r\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\r\n self.fc1 = nn.Linear(5408, 128)\r\n self.fc2 = nn.Linear(128, 10)\r\n self.basic_blocks = nn.ModuleList([BasicBlock(channel_num) for i in range(2)])\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n x = F.relu(x)\r\n for i, _ in enumerate(self.basic_blocks):\r\n x = self.basic_blocks[i](x)\r\n \r\n x = F.max_pool2d(x, 2)\r\n x = torch.flatten(x, 1)\r\n x = self.fc1(x)\r\n x = F.relu(x)\r\n x = self.fc2(x)\r\n output = F.log_softmax(x, dim=1)\r\n return output\r\n \r\ndef train(args, model, device, train_loader, optimizer, epoch):\r\n model.train()\r\n for batch_idx, (data, target) in enumerate(train_loader):\r\n data, target = data.to(device), target.to(device)\r\n optimizer.zero_grad()\r\n output = model(data)\r\n loss = F.nll_loss(output, target)\r\n loss.backward()\r\n optimizer.step()\r\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {}'.format(\r\n epoch, batch_idx * len(data), len(train_loader.dataset),\r\n 100. * batch_idx / len(train_loader), loss.item()))\r\n epochs_list.append(epoch)\r\n running_loss_list.append(loss.item())\r\n \r\n\r\n\r\ndef test(model, device, test_loader):\r\n model.eval()\r\n test_loss = 0\r\n correct = 0\r\n with torch.no_grad():\r\n for data, target in test_loader:\r\n data, target = data.to(device), target.to(device)\r\n output = model(data)\r\n test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\r\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\r\n correct += pred.eq(target.view_as(pred)).sum().item()\r\n\r\n test_loss /= len(test_loader.dataset)\r\n\r\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\r\n test_loss, correct, len(test_loader.dataset),\r\n 100. * correct / len(test_loader.dataset)))\r\n accuracy_list.append(correct/len(test_loader.dataset))\r\n\r\n\r\ndef main():\r\n # Training settings\r\n parser = argparse.ArgumentParser(description='PyTorch MNIST Example')\r\n parser.add_argument('--batch-size', type=int, default=64, metavar='N',\r\n help='input batch size for training (default: 64)')\r\n parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\r\n help='input batch size for testing (default: 1000)')\r\n parser.add_argument('--epochs', type=int, default=30, metavar='N',\r\n help='number of epochs to train (default: 30)')\r\n parser.add_argument('--lr', type=float, default=1.0, metavar='LR',\r\n help='learning rate (default: 1.0)')\r\n parser.add_argument('--gamma', type=float, default=0.7, metavar='M',\r\n help='Learning rate step gamma (default: 0.7)')\r\n parser.add_argument('--no-cuda', action='store_true', default=False,\r\n help='disables CUDA training')\r\n parser.add_argument('--dry-run', action='store_true', default=False,\r\n help='quickly check a single pass')\r\n parser.add_argument('--seed', type=int, default=1, metavar='S',\r\n help='random seed (default: 1)')\r\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\r\n help='how many batches to wait before logging training status')\r\n parser.add_argument('--save-model', action='store_true', default=False,\r\n help='For Saving the current Model')\r\n parser.add_argument('--model', type = int)\r\n args = parser.parse_args()\r\n use_cuda = not args.no_cuda and torch.cuda.is_available()\r\n\r\n torch.manual_seed(args.seed)\r\n\r\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\r\n\r\n train_kwargs = {'batch_size': args.batch_size}\r\n test_kwargs = {'batch_size': args.test_batch_size}\r\n if use_cuda:\r\n cuda_kwargs = {'num_workers': 1,\r\n 'pin_memory': True,\r\n 'shuffle': True}\r\n train_kwargs.update(cuda_kwargs)\r\n test_kwargs.update(cuda_kwargs)\r\n\r\n transform=transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.1307,), (0.3081,))\r\n ])\r\n dataset1 = datasets.MNIST('./data', train=True, download=True,\r\n transform=transform)\r\n dataset2 = datasets.MNIST('./data', train=False,\r\n transform=transform)\r\n train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)\r\n test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)\r\n #val = input(\"Enter model # (1, 2, 3): \")\r\n model = Net().to(device)\r\n if args.model == 1:\r\n model = Net().to(device)\r\n elif args.model == 2:\r\n model = Net2().to(device)\r\n elif args.model == 3:\r\n model = Net3().to(device)\r\n else:\r\n exit()\r\n\r\n \r\n optimizer = optim.Adadelta(model.parameters(), lr=args.lr)\r\n\r\n scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)\r\n for epoch in range(1, args.epochs + 1):\r\n train(args, model, device, train_loader, optimizer, epoch)\r\n test(model, device, test_loader)\r\n scheduler.step()\r\n plt.plot(epochs_list, running_loss_list)\r\n plt.xlabel('Epoch')\r\n plt.ylabel('Training Loss')\r\n plt.title('Epoch vs Training Loss')\r\n plt.show()\r\n\r\n plt.plot(epochs_list, accuracy_list)\r\n plt.xlabel('Epoch')\r\n plt.ylabel('Test Accuracy')\r\n plt.title('Epoch vs Test Accuracy')\r\n plt.show()\r\n\r\n\r\n if args.model == 1:\r\n torch.save(model.state_dict(), \"model1.pt\")\r\n elif args.model == 2:\r\n torch.save(model.state_dict(), \"model2.pt\")\r\n elif args.model == 3:\r\n torch.save(model.state_dict(), \"model3.pt\")\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","sub_path":"hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":8342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"499922910","text":"import subprocess\nimport sys\nimport re\nimport os.path\nimport xml.etree.ElementTree as etree\nimport argparse\nimport urllib.request\n\nimport pdb\nclass DependencyStore:\n \"\"\"Encapsulates a list of dependencies\"\"\"\n\n _cache = {}\n\n class Dependency:\n def __init__(self, name):\n self._name = name\n self.resolve()\n\n def __str__(self):\n return self._resolved_name\n\n def resolve(self):\n if not subprocess.call(\n ['rospack','find',self._name], stdout = subprocess.DEVNULL, \n stderr = subprocess.DEVNULL):\n self._resolved_name = self._name\n return\n\n with subprocess.Popen(\n ['rosdep', 'resolve', self._name], stdout = subprocess.PIPE, \n stderr = subprocess.DEVNULL, universal_newlines=True\n ) as rosdep_stream:\n rosdep_result = rosdep_stream.stdout.readlines()\n if len(rosdep_result) == 2:\n self._resolved_name = rosdep_result[1]\n else:\n print(\n\"\"\"The dependency {name} could not be found by either both rospack or rosdep.\nMaybe you forgot to source the appropriate setup.bash, or there is no rosdep\nbinding for {name} for this OS?\"\"\".format(self._name))\n exit(1)\n\n def get_dependency(name):\n if name not in DependencyStore._cache:\n DependencyStore._cache[name] = DependencyStore.Dependency(name) \n return DependencyStore._cache[name]\n\n def __init__(self, buildtool_depends, build_depends, run_depends):\n self._build = {p:DependencyStore.get_dependency(p) for p in build_depends + buildtool_depends}\n self._run = {p:DependencyStore.get_dependency(p) for p in run_depends}\n\n def __str__(self):\n return \"Build: {b}\\nRun: {r}\".format(b = self._build.__str__(), \n r = self._run.__str__())\n \n def build_packages(self):\n return self._build.values()\n\n def run_packages(self):\n return self._run.values()\n\n\ndef extract_all_text(element):\n \"Extracts the text from a node, stripping any tags and removing excess whitespace\"\n mod_lst = []\n for text in element.itertext():\n if type(text) == list:\n text = \"\".join(text)\n mod_lst.append(text)\n return re.sub('\\s+', ' ', \"\".join(mod_lst).strip())\n\nclass RPMSpec:\n def factory(packagePath, wsPath, override, distro):\n tree = etree.parse(packagePath+\"/package.xml\")\n root = tree.getroot()\n name = root.find('name').text\n version = root.find('version').text\n url = root.find('url').text\n\n if override.description != None:\n description = override.description\n else:\n description = extract_all_text(root.find('description'))\n description = description[0].upper() + description[1:]\n \n if override.summary != None:\n summary = override.summary\n else:\n summary = description.split(\".\", 1)[0]\n \n license = root.find('license').text\n with subprocess.Popen(\n ['wstool', 'info', '-t', wsPath, '--only', 'cur_uri,version', name], \n stdout = subprocess.PIPE, universal_newlines = True\n ) as wstool:\n str_out = re.sub('\\n', '', wstool.stdout.readline())\n if \"ros-gbp\" in str_out:\n source = re.sub('\\.git,', '/archive/', str_out) + '.tar.gz'\n print(\"ros-gbp package detected. URL: \" + source)\n else:\n source = re.sub(',.*', '', str_out)\n\n elementText = lambda e: e.text\n\n dependencies = DependencyStore(\n list(map(elementText, root.findall('buildtool_depend'))),\n list(map(elementText, root.findall('build_depend'))),\n list(map(elementText, root.findall('run_depend')))\n )\n\n has_python = os.path.isfile(packagePath + \"/setup.py\")\n\n if root.find(\"export\") == None:\n is_metapackage = False\n else:\n is_metapackage = root.find(\"export\").find(\"metapackage\") != None\n\n return RPMSpec(name, version, source, url, description, summary, \n license, dependencies, has_python, is_metapackage, distro)\n\n def __init__(self, name, version, source, url, description, summary, license, \n dependencies, has_python, is_metapackage, distro):\n self.name = name\n self.version = version\n self.source = source\n self.url = url\n self.description = description\n self.summary = summary\n self.license = license\n self.dependencies = dependencies\n self.has_python = has_python\n self.is_metapackage = is_metapackage\n self.distro = distro\n\n def generate_service(self, stream):\n download_files_srv = \"\"\" \"\"\"\n tar_scm_srv = \"\"\" \n {source}\n {version}\n master\n git \n \n\"\"\".format(source = self.source, version = self.version)\n\n stream.write(\"\"\"\n{srv}\n\n\"\"\".format(srv = (download_files_srv if \"ros-gbp\" in self.source else tar_scm_srv)))\n\n def render(self, stream):\n header_template = \"\"\"%define __pkgconfig_path {{\"\"}}\n\nName: {pkg_name}\nVersion: {version}\nRelease: 0\nLicense: {license}\nSummary: {summary}\nUrl: {url}\nGroup: Productivity/Scientific/Other\nSource0: {source}\nSource1: {pkg_name}-rpmlintrc\n\nBuildRequires: python-devel\nBuildRequires: gcc-c++\nBuildRequires: python-rosmanifestparser\n\"\"\"\n\n # correction for tar_scm\n if re.search(\"(\\.git)$\", self.source):\n src = self.name + '-' + self.version + '.tar'\n else:\n src = self.source\n\n stream.write(header_template.format(pkg_name = self.name, \n version = self.version, license = self.license, summary = self.summary, \n url = self.url, source = src))\n\n for build_dependency in sorted(map(str, self.dependencies.build_packages())):\n stream.write(\"BuildRequires: {0}\\n\".format(build_dependency))\n for run_dependency in sorted(map(str, self.dependencies.run_packages())):\n stream.write(\"Requires: {0}\\n\".format(run_dependency))\n stream.write(\"\\n%description\\n{0}\\n\".format(self.description))\n\n body = \"\"\"\n%define install_dir {install_space}\n%define catkin_make %{{install_dir}}/bin/catkin_make\n\n%prep\n%setup -q -c -n workspace\nmv * {name}\nmkdir src\nmv {name} src\n\n%build\nsource %{{install_dir}}/setup.bash\nDESTDIR=%{{?buildroot}} %{{catkin_make}} -DCMAKE_INSTALL_PREFIX=%{{install_dir}} -DSETUPTOOLS_DEB_LAYOUT=\"OFF\"\n\n%install\nsource %{{install_dir}}/setup.bash\nDESTDIR=%{{?buildroot}} %{{catkin_make}} install -DCMAKE_INSTALL_PREFIX=%{{install_dir}}\nif [ -f %{{buildroot}}/opt/ros/hydro/.catkin ];\nthen\n rm %{{?buildroot}}%{{install_dir}}/.catkin \\\n %{{?buildroot}}%{{install_dir}}/.rosinstall \\\n %{{?buildroot}}%{{install_dir}}/env.sh \\\n %{{?buildroot}}%{{install_dir}}/_setup_util.py \\\n %{{?buildroot}}%{{install_dir}}/setup*\nfi\n{pkgconfig}\nrosmanifestparser {name} build/install_manifest.txt %{{?buildroot}} {has_python}\n\n%files -f ros_install_manifest\n%defattr(-,root,root)\n\n%changelog\n\"\"\"\n pkg_config_cmds = \"\"\"mkdir -p %{{?buildroot}}%{{install_dir}}/share/pkgconfig\nmv %{{?buildroot}}%{{install_dir}}/lib/pkgconfig/{name}.pc %{{?buildroot}}%{{install_dir}}/share/pkgconfig/\nrmdir %{{?buildroot}}%{{install_dir}}/lib/pkgconfig\n\"\"\".format(name=self.name)\n\n stream.write(body.format(\n pkgconfig = pkg_config_cmds if not self.is_metapackage else '',\n name = self.name, has_python = self.has_python, \n install_space = \"/opt/ros/\" + self.distro))\n\nclass PackageOverride:\n \"\"\"Allows overriding summary and description, and allows ignoring a package\"\"\"\n def __init__(self, summary = None, description = None, ignore = False):\n self.summary = summary\n self.description = description\n self.ignore = ignore\n\ndef generate_override(element):\n summary = element.find('summary')\n if summary != None:\n summary = extract_all_text(summary)\n description = element.find('description')\n if description != None:\n description = extract_all_text(description)\n ignore = (element.find('ignore') != None)\n return PackageOverride(summary, description, ignore)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description = \"Generate RPM spec files from ROS packages\")\n parser.add_argument('workspace', type = str,\n help = 'path to the root of the workspace')\n parser.add_argument('destination', type = str,\n help = 'path to the spec root')\n parser.add_argument('--packages', type = str, dest = 'packages', nargs = '+',\n help = 'process only the specifed packages')\n parser.add_argument('--skip', type = str, dest = 'skipped', nargs = '+',\n help = 'skip the specified packages')\n parser.add_argument('--local', dest = 'remote', action = 'store_false',\n help = 'don\\'t upload results to server')\n parser.add_argument('--remote', dest = 'remote', action = 'store_true',\n help = 'upload results to server; set by default')\n parser.add_argument('--resume-at', type = str, dest = 'pack_resume', nargs = '?',\n help = 'if the script failed previously, resume at the specified package')\n parser.add_argument('--distro', type = str, dest = 'distro', nargs = '?',\n help = 'the ROS distribution to install (default is hydro)')\n parser.set_defaults(remote = True, distro = 'hydro', skipped = [])\n args = parser.parse_args()\n\n workspace_config = etree.parse(args.workspace + '/.ros2spec.xml').getroot()\n overrides = dict()\n for package in workspace_config:\n overrides[package.attrib['name']] = generate_override(package)\n\n srcdir = args.workspace + '/src/'\n if args.packages == None:\n packages = [name for name in os.listdir(srcdir) if os.path.isdir(srcdir + name)]\n else:\n packages = args.packages\n\n print(\"Listing packages on server ...\")\n with subprocess.Popen(\n [\"osc\", \"list\", args.destination.split('/')[-1]], \n stdout = subprocess.PIPE, universal_newlines = True) as server_results:\n remote_packages = [line.replace('\\n', '') for line in server_results.stdout]\n skip = args.pack_resume != None\n\n for package in packages:\n if skip and (package != args.pack_resume):\n continue\n else:\n skip = False\n\n if package in args.skipped:\n continue\n\n try:\n override = overrides[package]\n except KeyError:\n override = PackageOverride()\n if override.ignore:\n continue\n spec = RPMSpec.factory(srcdir + '/' + package, srcdir, override, args.distro)\n target_dir = args.destination + '/' + package\n os.chdir(args.destination)\n if package not in remote_packages:\n print(\"Package \" + package + \" was not found on server.\")\n if (os.path.exists(target_dir)):\n print(\"\"\"The package was not found on the server, but the directory was found locally.\nPlease resolve this manually before continuing.\"\"\")\n exit(1)\n print(\"Creating package \" + package + \" ...\")\n subprocess.call(['osc', 'mkpac', target_dir])\n os.chdir(target_dir)\n else:\n if not os.path.exists(target_dir):\n print(\"Checking out package ...\")\n subprocess.call(['osc', 'co', package])\n os.chdir(target_dir)\n else:\n os.chdir(target_dir)\n print(\"Updating existing package ...\")\n subprocess.call(['osc', 'up'])\n\n print('Generating files in ' + target_dir + ' ...')\n with open(target_dir + '/_service', mode = \"w\") as srv_file:\n spec.generate_service(srv_file)\n with open(target_dir + '/' + spec.name + \".spec\", mode = \"w\") as rpmSpec:\n spec.render(rpmSpec)\n with open(target_dir + '/' + spec.name + \"-rpmlintrc\", mode = \"w\") as lintFile:\n lintFile.write(\"\"\"setBadness('devel-file-in-non-devel-package', 0)\nsetBadness('shlib-policy-name-error', 0)\"\"\")\n\n subprocess.check_call(['osc', 'addremove'])\n with subprocess.Popen([\"osc\", \"st\"], stdout = subprocess.PIPE) as status:\n if status == '':\n print(\"No changes to commit.\")\n continue\n if (args.remote):\n print(\"Performing check-in...\")\n subprocess.check_call(['osc', 'ci', '-m', '\"ros2spec automated check-in\"'])\n \n","sub_path":"ros2spec.py","file_name":"ros2spec.py","file_ext":"py","file_size_in_byte":12102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"208102917","text":"import numpy as np\nfrom numpy import zeros, hstack, size, diag\nfrom numpy.random import rand, randn\nfrom numpy.random import multivariate_normal as gaussian\nfrom scipy.integrate import odeint\n\nimport util\n\ndef rollout(start, policy, H, plant, cost, return_cost=False):\n\t\"\"\"\n\tGenerate a state trajectory using an ODE solver.\n\n\tInput arguments:\n\tstart\t\tinitial states\t(nX,)\n\tpolicy\t\tpolicy structure\n\t.fcn\t\tpolicy function (use random actions if empty)\n\t.p\t\tparameters\n\t.max_u\t\tcontrol input saturation values\t(nU,)\n\tH\t\trollout horizon in steps\n\tplant\t\tdynamical system structure\n\t.poli\t\tindices for states passed to policy\n\t.dyno\t\tindices for states passed to cost\n\t.odei\t\tindices for states passed to the ode solver\n\t.angi\t\tindices of angles in states\n\tcost\t\tcost structure\n\n\tReturn:\n\tx\t\tmatrix of observed states\t(H, nX + nU)\n\ty\t\tmatrix of observed successor states\t(H, nX)\n\tL\t\tcost incurred at each time step\t(H,)\n\t\"\"\"\n\todei = plant['odei']\n\tpoli = plant['poli']\n\tdyno = plant['dyno']\n\tangi = plant['angi']\n\n\tnX = len(odei)\n\tnU = len(policy['max_u'])\n\tnA = len(angi)\n\n\t# initializations\n\tstate = start\n\tx = zeros((H + 1, nX + 2*nA))\n\tx[0, odei] = gaussian(start, plant['noise'])\n\t\n\tu = zeros((H, nU))\n\ty = zeros((H, nX))\n\tL = zeros(H)\n\tlatent = zeros((H + 1, size(state) + nU))\n\n\tfor i in range(H):\n\t\ts = x[i, dyno]\n\t\ta, _, _ = util.trig(s, diag(zeros(size(s))), angi)\n\t\ts = hstack((s, a))\n\t\tx[i, -2*nA:] = s[-2*nA:]\n\n\t\tf = policy.get('fcn')\n\t\tif f is None:\t# perform random actions\n\t\t\tu[i, :] = policy['max_u']*(2*rand(nU) - 1)\n\t\telse:\t# or apply policy\n\t\t\tu[i, :] = f(policy, s[poli], zeros(len(poli)))\n\t\tlatent[i, :] = hstack((state, u[i, :]))\n\t\t\n\t\t# solve dynamics\n\t\tdynamics = plant['dynamics']\n\t\tdt = plant['dt']\n\t\tnext = odeint(dynamics, state[odei], [0, dt], args=(u[i, :],))\n\t\tstate = next[-1, :]\n\t\tx[i + 1, odei] = gaussian(state[odei], plant['noise'])\n\n\t\tif return_cost:\n\t\t\tL[i] = cost['fcn'](cost, state[dyno], zeros(len(dyno)))\n\t\t\n\ty = x[1:H + 1, 0:nX]\n\tx = hstack((x[0:H, :], u[0:H, :]))\n\tlatent[H, 0:nX] = state\n\n\tif return_cost: return x, y, L, latent\n\treturn x, y, latent\n","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"605431502","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 31 17:08:52 2019\r\n\r\n@author: Administrator\r\n\"\"\"\r\n\r\n\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\n# 不同的vgg结构,这样写可以有效节约代码空间。\r\n\r\nclass VGG(nn.Module):\r\n#nn.Module是一个特殊的nn模块,加载nn.Module,这是为了继承父类\r\n def __init__(self, vgg_name):\r\n super(VGG, self).__init__()\r\n #super 加载父类中的__init__()函数\r\n cfg = {'VGG11': [64, 'M', 128, 'M', 256,'M', 512, 'M', 512,'M'],\r\n 'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\r\n 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],\r\n 'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],\r\n }\r\n self.features = self._make_layers(cfg[vgg_name])\r\n self.fc1=nn.Linear(512*9*9,150)\r\n self.fc2=nn.Linear(150,2)\r\n #该网络输入为Cifar10数据集,因此输出为(512,1,1)\r\n\r\n def forward(self, x):\r\n out = self.features(x)\r\n out = out.view(out.size(0),-1)\r\n #这一步将out拉成out.size(0)的一维向量\r\n out = self.fc1(out)\r\n out = nn.ReLU(inplace=True)(out)\r\n out = F.dropout(out)\r\n out = self.fc2(out)\r\n \r\n return out\r\n\r\n def _make_layers(self, cfg):\r\n layers = []\r\n in_channels = 3\r\n for x in cfg:\r\n if x == 'M':\r\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\r\n else:\r\n layers += [nn.Conv2d(in_channels, x, kernel_size=3, \r\n padding=1,bias=False),\r\n nn.BatchNorm2d(x),\r\n nn.ReLU(inplace=True)]\r\n in_channels = x\r\n return nn.Sequential(*layers)\r\n \r\n \r\ndef t():\r\n net = VGG('VGG11')\r\n x = torch.randn(5,3,300,300)\r\n y = net(x)\r\n print(y.shape)\r\nif __name__ == \"__main__\":\r\n t()\r\n ","sub_path":"project2/stage2/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"182444860","text":"import os\nimport json\nimport time\nimport datetime\nimport sys\n\nimport database\nfrom exception import CustomizeException\nfrom file_util import read_file, write_json, read_json\n\ndb = database.connectdb()\n\ndef output_download_timeas_str(m_dict):\n for entry in m_dict:\n path = entry['url']\n tmp = path.split('/')\n line = '/home/fdse/data/prior_repository/' + tmp[-2] + '/' + tmp[-1]\n if not os.path.exists(line):\n print('err')\n break\n # print(line)\n sh = 'stat ' + line\n ff = os.popen(sh)\n result = ff.read()\n data = result.split('\\n')\n date = ''\n for line in data:\n if line.startswith('Change: '):\n date = line.strip('\\n')[8:]\n break\n m_time = date.split('.')[0]\n # print(m_time)\n entry['download_time'] = m_time\n\n\ndef output_repo_time_as_str(m_dict):\n for entry in m_dict:\n path = entry['url']\n tmp = path.split('/')\n line = '/home/fdse/data/prior_repository/' + tmp[-2] + '/' + tmp[-1]\n if not os.path.exists(line):\n print('err')\n break\n # print(line)\n sh = 'git --git-dir=' + line + '/.git log -n 1 --date=iso'\n ff = os.popen(sh)\n result = ff.read()\n data = result.split('\\n')\n date = ''\n for line in data:\n if line.startswith('Date'):\n date = line.strip('\\n')\n break\n m_time = date.split('te:')[1][0:-6]\n entry['head_commit_time'] = m_time.strip(' ')\n\n\n# def threshold_time(weekNum):\n# delta_one_year = (datetime.datetime.now()+datetime.timedelta(weeks=weekNum)).strftime(\"%Y-%m-%d %H:%M:%S\")\n# now = time.time()\n# thtime = time.strptime(delta_one_year,'%Y-%m-%d %H:%M:%S')\n# thstamp = int(time.mktime(thtime))\n# return thstamp\n\ndef input_repo_time_compare(num):\n with open('E:/data/projs.8.11.time.json', 'r') as f:\n content = f.read()\n m_dict = json.loads(content)\n cnt = 0\n print(len(m_dict))\n for entry in m_dict:\n download_time = entry['download_time']\n head_commit_time = entry['head_commit_time']\n download_time2 = time.strptime(download_time, '%Y-%m-%d %H:%M:%S')\n head_commit_time2 = time.strptime(head_commit_time, '%Y-%m-%d %H:%M:%S')\n download_time3 = int(time.mktime(download_time2))\n head_commit_time3 = int(time.mktime(head_commit_time2))\n\n if download_time3 - head_commit_time3 > time_interval(num):\n # print(threshold_time(time, 52))\n cnt += 1\n\n print(cnt)\n\n\ndef time_interval(days):\n prev_time = time.strptime(\"2018-07-20 02:44:16\", '%Y-%m-%d %H:%M:%S')\n curr_time = time.strptime(\"2018-07-21 02:44:16\", '%Y-%m-%d %H:%M:%S')\n prev_time_num = int(time.mktime(prev_time))\n curr_time_num = int(time.mktime(curr_time))\n one_day = curr_time_num - prev_time_num\n return one_day * days\n\n\ndef get_maven_proj_update_within_three_months(num):\n proj_array = []\n id_array = []\n with open('E:/data/projs.8.11.time.json', 'r') as f:\n content = f.read()\n m_dict = json.loads(content)\n print(len(m_dict))\n cnt = 0\n print(len(m_dict))\n final_result = {}\n for entry in m_dict:\n download_time = entry['download_time']\n head_commit_time = entry['head_commit_time']\n download_time2 = time.strptime(download_time, '%Y-%m-%d %H:%M:%S')\n head_commit_time2 = time.strptime(head_commit_time, '%Y-%m-%d %H:%M:%S')\n download_time3 = int(time.mktime(download_time2))\n head_commit_time3 = int(time.mktime(head_commit_time2))\n\n # if download_time3 - head_commit_time3 > time_interval(90) and download_time3 - head_commit_time3 <= time_interval(120):\n if download_time3 - head_commit_time3 <= time_interval(num):\n type_ = entry[\"proj-type\"]\n # if type_ == \"proj-type: maven\":\n # if type_ == \"proj-type: maven-gradle\":\n # if type_ == \"proj-type: maven-gradle\":\n url = entry[\"url\"]\n sql = \"SELECT * FROM project WHERE url = '\" + url + \"'\"\n query_result = database.querydb(db, sql)\n if len(query_result) > 0:\n id = query_result[0][0]\n id_array.append(id)\n # url = url.replace(\"https://github.com/\", \"\").replace(\"/\", \"__fdse__\")\n # name = url\n # if os.path.exists(\"D:/gradle_maven200_500/\" + url):\n # url = \"D:/gradle_maven200_500/\" + url\n # elif os.path.exists(\"D:/gradle_maven500/\" + url):\n # url = \"D:/gradle_maven500/\" + url\n # elif os.path.exists(\"C:/gradle200_500/\" + url):\n # url = \"C:/gradle200_500/\" + url\n # elif os.path.exists(\"C:/gradle500/\" + url):\n # url = \"C:/gradle500/\" + url\n # elif os.path.exists(\"E:/maven200_500/\" + url):\n # url = \"E:/maven200_500/\" + url\n # elif os.path.exists(\"E:/maven500/\" + url):\n # url = \"E:/maven500/\" + url\n # else:\n # raise CustomizeException(\"Not in local:\" + url)\n # obj = {}\n # obj[\"id\"] = id\n # obj[\"name\"] = name\n # obj[\"local_addr\"] = url\n # proj_array.append(obj)\n #\n # final_result[str(query_result[0][0])] = url\n # with open(\"four_months.txt\", \"a\") as f:\n # f.write(str(query_result[0][0]) + \"\\n\")\n # f.write(query_result[0][1] + \"\\n\")\n # f.close()\n else:\n raise CustomizeException(\"Not in db:\" + url)\n cnt += 1\n print(id_array)\n # print(proj_array)\n # print(len(proj_array))\n # write_json(\"three_month.txt\", proj_array)\n # write_json(\"four_month.txt\", final_result)\n\n # return gradle_array\n\n\ndef get_update_proj_in_three_months():\n lines = read_file(\"three_months.txt\")\n proj_ids = []\n proj_id = -1\n proj_path = None\n for line in lines:\n if not line.startswith(\"https\"):\n proj_id = line\n if proj_id not in proj_ids:\n proj_ids.append(proj_id)\n\n print(len(proj_ids))\n\n update_path = \"E:/data/proj_update_lib\"\n files = os.listdir(update_path)\n for file_name in files:\n id = file_name.replace(\".txt\",\"\")\n if id in proj_ids:\n print(id)\n # os.remove(os.path.join(update_path,file_name))\n\n# arg = sys.argv[1]\n# input_repo_time_compare(int(arg))\n\n# def a1():\n# with open('projs.json' ,'r') as f:\n# content = f.read()\n# m_dict = json.loads(content)\n# output_repo_time_as_str(m_dict)\n# output_download_timeas_str(m_dict)\n# with open('projs2.json','w') as f:\n# json.dump(m_dict,f)\n# a1()\n\n# input_repo_time_compare(52)\n# input_repo_time_compare(90)\n\n# get_maven_proj_update_within_three_months(90)\n# get_update_proj_in_three_months()\n# data = read_json(\"four_month.txt\")\n# for key in data.keys():\n# data[key] = data[key].replace(\"gradle_maven200_500/\", \"\").replace(\"gradle_maven500/\", \"\").replace(\"gradle200_500/\", \"\").replace(\"gradle500/\", \"\").replace(\"maven200_500/\", \"\").replace(\"maven500/\", \"\")\n# print(len(data))\n# write_json(\"four_month.txt\", data)","sub_path":"Crawler/check_time.py","file_name":"check_time.py","file_ext":"py","file_size_in_byte":7408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"339771737","text":"from . import balance\nfrom security.validate import validate_api_key\n\nfrom models import PurchaseHistory\n\nfrom flask import Response, request\n\nfrom app import db\n\nimport json\n\n@balance.route('/purchase/add', methods=['POST'])\n@validate_api_key\ndef add_purchase():\n json_data = request.get_json()\n\n purchase = PurchaseHistory(json_data['note'], json_data['owner'], json_data['buyer'], json_data['price'])\n\n db.session.add(purchase)\n db.session.commit()\n\n return Response(status=200)\n\n@balance.route('/purchase/get', methods=['GET'])\n@validate_api_key\ndef get_purhcase():\n purchases = db.session.query(PurchaseHistory).filter(PurchaseHistory.owner == request.headers['owner']).all()\n\n purchase_list = []\n\n for purchase in purchases:\n purchase_data = {\n\n 'note': purchase.note,\n 'owner': purchase.owner,\n 'buyer': purchase.buyer,\n 'price': purchase.price,\n 'date': str(purchase.date)\n\n }\n\n purchase_list.append(purchase_data)\n\n return Response(status=200, response=json.dumps(purchase_list))\n","sub_path":"balance/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"620513730","text":"import pytube\nfrom flask import Flask, request, render_template\n\napp = Flask(__name__)\n\n@app.route('/',methods = ['GET','POST'])\ndef getWordAndURL():\n if request.method == 'POST':\n word = request.form.get('word')\n url = request.form.get('utube') # include mp4 videos and implement with speech to text api\n\n yt = pytube.YouTube(url)\n subt = yt.captions.get_by_language_code(\"en\") #add more caption languages\n sub = subt.generate_srt_captions().lower()\n subtitles = sub.split('\\n')\n for x in range(len(subtitles)):\n subtitles[x] = subtitles[x].split(\" \")\n time_stamps = []\n for x in range(len(subtitles)): # finding word\n for j in range(len(subtitles[x])):\n if subtitles[x][j] == word:\n time_stamps.append(subtitles[x - 1][0][:-4])\n if not time_stamps:\n return render_template('controlf.html', name = 'Sorry! We could not find your word. :(', back = True)\n else:\n links = []\n timestamps = list(dict.fromkeys(time_stamps))\n for time in timestamps:\n split_time = time.split(':')\n second = int(split_time[0])*3600 + int(split_time[1])*60 + int(split_time[2])\n link_timestamps = url + \"&t=\" + str(second) + \"s\"\n links.append(link_timestamps)\n return render_template('controlf.html', name = 'Here are your time stamps:', links_timestamps = zip(links,timestamps), back = True)\n else:\n return render_template('controlf.html',form = True)\n\nif __name__ == \"__main__\":\n app.run(port=5000, debug=True) ","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"273614752","text":"from Products.Five.browser import BrowserView\n\nimport json\nfrom plone import api\n\n\nclass GraphLayout(BrowserView):\n \"\"\"Class to handle the Workflow Manager graph layouts.\n\n propSheet:\n the property sheet containing all of the layouts\n\n layout:\n the actual value of the individual property on the propSheet\n representing the layout of the graph\n \"\"\"\n\n def __init__(self, context, request, workflow=None):\n self.context = context\n self.request = request\n\n self.REGISTRY_KEY = \"plone.app.workflowmanager.layouts\"\n\n if workflow is None:\n self.workflow = self.request.form['workflow'] or None\n else:\n self.workflow = workflow\n self.layout = {}\n layouts = self.getLayouts()\n\n if layouts is None:\n layouts = {}\n\n if self.workflow not in layouts:\n layouts[unicode(self.workflow)] = u'{}'\n else:\n self.layout = json.loads(layouts[self.workflow])\n\n def __call__(self):\n self.layout = json.loads(self.request.form['layout'])\n self.saveLayout()\n\n def getLayouts(self):\n return api.portal.get_registry_record(self.REGISTRY_KEY)\n\n def saveLayout(self):\n layouts = self.getLayouts() or {}\n layouts[unicode(self.workflow)] = unicode(json.dumps(self.layout))\n api.portal.set_registry_record(self.REGISTRY_KEY, layouts)\n\n def getLayout(self):\n if(self.workflow == ''):\n return False\n\n return json.dumps(self.layout)\n","sub_path":"src/plone/app/workflowmanager/browser/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"204321702","text":"# -*- coding: UTF-8 -*-\nimport tensorflow as tf\nimport random\nimport numpy as np\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\n\nclass CNN_test1(object):\n # def inference(self,images):\n # with tf.variable_scope(\"conv_1\") as scope:\n #\n # w=tf.get_variable(\"w\",[5,5,1,32],initializer=tf.truncated_normal_initializer(stddev=0.1))\n # b=tf.get_variable(\"b\",[32],initializer=tf.truncated_normal_initializer(stddev=0.1))\n # out=tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(images,w,strides=[1,1,1,1],padding=\"SAME\"),b))\n # out=tf.nn.max_pool(out,ksize=[1,2,2,1],strides=[1,2,2,1],padding=\"SAME\")\n #\n #\n # with tf.variable_scope(\"conv_2\") as scope:\n # w=tf.get_variable(\"w\",[5,5,32,64],initializer=tf.truncated_normal_initializer(stddev=0.1))\n # b=tf.get_variable(\"b\",[64],initializer=tf.truncated_normal_initializer(stddev=0.1))\n # out=tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(out,w,strides=[1,1,1,1],padding=\"SAME\"),b))\n # out=tf.nn.max_pool(out,ksize=[1,2,2,1],strides=[1,2,2,1],padding=\"SAME\")\n # print(w)\n #\n # with tf.variable_scope(\"full_1\") as scope:\n # out=tf.reshape(out,[-1,7*7*64])\n # w=tf.get_variable(\"w\",[7*7*64,1024],initializer=tf.truncated_normal_initializer(stddev=0.1))\n # b=tf.get_variable(\"b\",[1024],initializer=tf.truncated_normal_initializer(stddev=0.1))\n # out=tf.add(tf.matmul(out,w),b,name=\"out\")\n #\n #\n # with tf.variable_scope(\"full_2\") as scope:\n # w=tf.get_variable(\"w\",[1024,10],initializer=tf.truncated_normal_initializer(stddev=0.1))\n # b=tf.get_variable(\"b\",[10],initializer=tf.truncated_normal_initializer(stddev=0.1))\n # logits=tf.matmul(out,w)+b\n # return logits\n\n def inference(self,images):\n\n with tf.name_scope(\"conv_1\") as scope:\n output = tf.contrib.layers.conv2d(\n images,\n 32,\n 5,\n padding='SAME',\n weights_initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32),\n biases_initializer=tf.zeros_initializer(dtype=tf.float32),\n activation_fn=tf.nn.relu,\n scope=scope+\"1\"\n )\n output=tf.contrib.layers.max_pool2d(\n output,\n 2,\n stride=2,\n padding='SAME',\n scope=scope+\"2\"\n )\n with tf.name_scope(\"conv_2\") as scope:\n output = tf.contrib.layers.conv2d(\n output,\n 64,\n 5,\n padding='SAME',\n weights_initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32),\n biases_initializer=tf.zeros_initializer(dtype=tf.float32),\n activation_fn=tf.nn.relu,\n scope=scope+\"3\"\n )\n output = tf.contrib.layers.max_pool2d(\n output,\n 2,\n stride=2,\n padding='SAME',\n scope=scope+\"4\"\n )\n\n with tf.name_scope(\"fully_connect\") as scope:\n shape=output.get_shape()\n output=tf.reshape(output,[-1,shape[1].value*shape[2].value*shape[3].value])\n output=tf.contrib.layers.fully_connected(\n output,\n 1024,\n activation_fn=None,\n weights_initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32),\n biases_initializer=tf.zeros_initializer(dtype=tf.float32),\n scope=\"ful_1\"\n )\n print(output.name)\n output = tf.contrib.layers.fully_connected(\n output,\n 10,\n activation_fn=None,\n weights_initializer=tf.truncated_normal_initializer(stddev=0.1, dtype=tf.float32),\n biases_initializer=tf.zeros_initializer(dtype=tf.float32),\n scope=\"ful_2\"\n )\n print(output.name)\n #全连接层用RELU函数就是完蛋的 这代码和上面的代码是等价的\n return output\n\n def loss(self,logits,labels):\n print(labels)\n print(logits)\n cross_entropy=tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=labels)\n return tf.reduce_mean(cross_entropy)\n\n def accuracy(self,logits,labels):\n #acc=tf.nn.in_top_k(logits,labels,1)\n #return tf.reduce_mean(tf.cast(acc,tf.float32))\n return tf.reduce_mean(tf.cast(tf.equal(tf.argmax(logits,1),tf.argmax(labels,1)),tf.float32))\n\n\n def input(self):\n X = tf.placeholder(tf.float32, [None, 28, 28, 1], name=\"X\")\n Y = tf.placeholder(tf.int32, [None, 10],name=\"Y\")\n return X,Y\n\n\ndef main(unused_argv):\n # images=np.random.randint(0,256,[100,28,28,1])\n # #print(images)\n # labels = np.random.randint(0, 2, [100])\n #print(labels.shape)\n\n model=CNN_test1()\n X,Y=model.input()\n # X = tf.placeholder(tf.float32, [None, 28, 28, 1],name=\"X\")\n # Y = tf.placeholder(tf.int32, [None,10])\n\n output=model.inference(X)\n _loss=model.loss(output,Y)\n _acc=model.accuracy(output,Y)\n optimizer=tf.train.AdamOptimizer(learning_rate=0.001).minimize(_loss)\n saver=tf.train.Saver(max_to_keep=3)\n #step=tf.Variable(0,tf.int16)\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n #saver.restore(sess,\"./model_output/model.ckpt-0\")\n #saver.restore(sess, tf.train.latest_checkpoint('./model_output'))\n for step in range(10000):\n batch_xs, batch_ys = mnist.train.next_batch(100)\n batch_xs=batch_xs.reshape([-1,28,28,1])\n _,los,acc=sess.run([optimizer,_loss,_acc],feed_dict={X:batch_xs,Y:batch_ys})\n #_, los, acc = sess.run([optimizer, _loss, _acc], feed_dict={X: images, Y: labels})\n if step%20==0:\n saver.save(sess,\"./model_output/model.ckpt\",global_step=step)\n print(\"step: %d losses: %.3f accuracy:%.3f\" % (step,los,acc))\n\n #应该是这个网络不行导致的原因、 主要问题是训练误差太大的原因 这肯定是偏差过大的问题 所以我及时果断的调整了参数 结果非常的理想!\n #图像是随机生成的都能拟合 真是厉害!\nif __name__ == '__main__':\n tf.app.run()\n\n\n","sub_path":"tensorflow/model_test/architect_cnn.py","file_name":"architect_cnn.py","file_ext":"py","file_size_in_byte":6560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"469717722","text":"from django.core.management.base import BaseCommand, CommandError\n\nfrom gallery.models import Picture, ExifTag, Event, EventRegex\n\nclass Command(BaseCommand):\n help = 'Removes all items from the database'\n \n def add_arguments(self, parser):\n parser.add_argument('-y', action='store_true', default=False)\n \n def handle(self, *args, **options):\n if options['y'] or input('Really delete all items? [y/n] ').lower() == 'y':\n for tag in ExifTag.objects.all():\n \ttag.delete()\n for pic in Picture.objects.all():\n pic.delete()\n for event in Event.objects.all():\n event.delete()\n for regex in EventRegex.objects.all():\n regex.delete()\n","sub_path":"gallery/management/commands/cleardb.py","file_name":"cleardb.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"105894918","text":"# Tencent is pleased to support the open source community by making TNN available.\n#\n# Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.\n#\n# Licensed under the BSD 3-Clause License (the \"License\"); you may not use this file except\n# in compliance with the License. You may obtain a copy of the License at\n#\n# https://opensource.org/licenses/BSD-3-Clause\n#\n# Unless required by applicable law or agreed to in writing, software distributed\n# under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations under the License.\n\nimport src.c2oObject as Node\nimport numpy as np\nfrom typing import *\nfrom onnx import TensorProto\nimport copy\n\n\ndef need_add_reshape(input_shape: List[List]) -> bool:\n return len(input_shape[0]) != len(input_shape[1])\n\n\ndef get_param_shape(input_shape: List[List]) -> List:\n input = input_shape[0]\n scale = copy.deepcopy(input_shape[1])\n if len(input) > len(scale):\n for i in range(len(input) - len(scale)):\n scale.append(1)\n return scale\n\ndef broadcast_scale(input_shape: List[List]) -> List[List]:\n input = input_shape[0]\n scale = input_shape[1]\n if len(input) > len(scale):\n for i in range(len(input) - len(scale)):\n scale.append(1)\n broadcast_shape = [input, scale]\n elif len(input) < len(scale):\n print(\"the scale should be less than input\")\n exit(-1)\n else:\n broadcast_shape = [input, scale]\n return broadcast_shape\n\n\ndef get_mul_output_shape(input_shape: List[List]) -> List[List]:\n output_shape = input_shape[0]\n return [output_shape]\n\n\ndef create_mul_node(layer, node_name, input_name, output_name, input_shape):\n\n output_shape = get_mul_output_shape(input_shape)\n\n node = Node.c2oNode(layer, node_name, 'Mul', input_name, output_name, input_shape, output_shape)\n\n return node\n","sub_path":"tools/caffe2onnx/src/OPs/Mul.py","file_name":"Mul.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"122776900","text":"# c06ex16.py\n# face drawing program\n\n\nfrom graphics import *\n\ndef drawFace(center, size, window):\n eyeSize = 0.15 * size\n eyeOff = size / 3.0\n mouthSize = 0.8 * size\n mouthOff = size / 2.0\n head = Circle(center, size)\n head.setFill(\"yellow\")\n head.draw(window)\n leftEye = Circle(center, eyeSize)\n leftEye.move(-eyeOff, -eyeOff)\n rightEye = Circle(center, eyeSize)\n rightEye.move(eyeOff, -eyeOff)\n leftEye.draw(window)\n rightEye.draw(window)\n p1 = center.clone()\n p1.move(-mouthSize/2, mouthOff)\n p2 = center.clone()\n p2.move(mouthSize/2, mouthOff)\n mouth = Line(p1,p2)\n mouth.draw(window)\n\ndef interactiveFace(w):\n center = w.getMouse()\n edge = w.getMouse()\n radius = distance(center, edge)\n drawFace(center, radius, w)\n\ndef distance(p1, p2):\n dx = p2.getX() - p1.getX()\n dy = p2.getY() - p1.getY()\n return (dx*dx + dy*dy)**.5\n\ndef createPicWin(picFile):\n img = Image(Point(0,0),picFile)\n width = img.getWidth()\n height = img.getHeight()\n win = GraphWin(picFile, width, height)\n img.move(width//2, height//2)\n img.draw(win)\n return win\n \ndef main():\n print(\"Photo Anonymizer: Draw faces over pictures.\")\n picFile = input(\"Enter name of file containing GIF image: \")\n win = createPicWin(picFile)\n numFaces = int(input(\"How many faces to draw? \"))\n for i in range(numFaces):\n print(\"Click center and edge of a face.\")\n interactiveFace(win)\n print(\"Click again to quit.\")\n win.getMouse()\n win.close()\n \nmain()\n","sub_path":"code/chapter06/c06ex16.py","file_name":"c06ex16.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"424084443","text":"from django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom comidas_rapidas.apps.home.forms import *\nfrom comidas_rapidas.apps.home.models import producto,bebida,marca,combo,ingredientes\nfrom comidas_rapidas.apps.home.forms import add_product_form, add_bebida_form, add_marca_form, add_combo_form, add_ingredientes_form\nfrom django.http import HttpResponseRedirect\nfrom comidas_rapidas.apps.home.forms import login_form\nfrom django.contrib.auth import login, logout, authenticate\nfrom django.core.paginator import Paginator, EmptyPage, InvalidPage \nfrom django.contrib.auth.models import User\n\n\n\ndef index_view (request) :\n\treturn render_to_response('home/index.html', context_instance = RequestContext(request))\n\n\n\ndef single_product_view(request, id_prod):\n\tprod = producto.objects.get(id=id_prod)\n\tctx = {'producto':prod}\n\treturn render_to_response('home/single_producto.html',ctx,context_instance= RequestContext(request))\n\ndef single_combos_view(request, id_prod):\n\tprod = combo.objects.get(id=id_prod)\n\tctx = {'combo':prod}\n\treturn render_to_response('home/single_combos.html',ctx,context_instance= RequestContext(request))\n\ndef single_marca_view(request, id_prod):\n\tprod = marca.objects.get(id=id_prod)\n\tctx = {'marca':prod}\n\treturn render_to_response('home/single_marca.html',ctx,context_instance= RequestContext(request))\n\ndef single_bebidas_view(request, id_prod):\n\tprod = bebida.objects.get(id=id_prod)\n\tctx = {'bebida':prod}\n\treturn render_to_response('home/single_bebidas.html',ctx,context_instance= RequestContext(request))\n\ndef single_ingredientes_view(request, id_prod):\n\tprod = ingredientes.objects.get(id=id_prod)\n\tctx = {'ingredientes':prod}\n\treturn render_to_response('home/single_ingredientes.html',ctx,context_instance= RequestContext(request))\n\n\ndef productos_view(request, pagina):\n\tlista_prod = producto.objects.filter()\n\tpaginator = Paginator(lista_prod,3)\n\ttry:\n\t\tpage = int(pagina)\n\texcept:\n\t\tpage = 1\n\ttry:\n\t\tproductos = paginator.page(page)\n\texcept (EmptyPage,InvalidPage):\n\t\tproductos = paginator.page(paginator.num_pages)\n\n\tctx ={ 'productos':productos}\n\treturn render_to_response ('home/productos.html', ctx, context_instance = RequestContext(request))\n\n\ndef combos_view(request, pagina):\n\tlista_prod = combo.objects.filter()\n\tpaginator = Paginator(lista_prod,3)\n\ttry:\n\t\tpage = int(pagina)\n\texcept:\n\t\tpage = 1\n\ttry:\n\t\tcombos = paginator.page(page)\n\texcept (EmptyPage,InvalidPage):\n\t\tcombos = paginator.page(paginator.num_pages)\n\n\tctx ={ 'combos':combos }\n\treturn render_to_response ('home/combos.html', ctx, context_instance = RequestContext(request))\n\ndef bebidas_view(request, pagina):\n\tlista_prod = bebida.objects.filter()\n\tpaginator = Paginator(lista_prod,3)\n\ttry:\n\t\tpage = int(pagina)\n\texcept:\n\t\tpage = 1\n\ttry:\n\t\tbebidas = paginator.page(page)\n\texcept (EmptyPage,InvalidPage):\n\t\tbebidas = paginator.page(paginator.num_pages)\n\n\tctx ={ 'bebidas':bebidas}\n\treturn render_to_response ('home/bebidas.html', ctx, context_instance = RequestContext(request))\n\n\ndef login_view(request):\n\tmensaje = \"\"\n\tif request.user.is_authenticated():\n\t\treturn HttpResponseRedirect('/')\n\telse:\n\t\tif request.method == \"POST\":\n\t\t\tformulario = login_form(request.POST)\n\t\t\tif formulario.is_valid():\n\t\t\t\tusu = formulario.cleaned_data['usuario']\n\t\t\t\tpas = formulario.cleaned_data['clave']\n\t\t\t\tusuario = authenticate(username = usu, password = pas)\n\t\t\t\tif usuario is not None and usuario.is_active:\n\t\t\t\t\tlogin(request, usuario)\n\t\t\t\t\treturn HttpResponseRedirect('/')\n\t\t\t\telse:\n\t\t\t\t\tmensaje = \"usuario y/o clave incorrecta\"\n\t\tformulario = login_form()\n\t\tctx = {'form':formulario, 'mensaje':mensaje}\n\t\treturn render_to_response('home/login.html',ctx,context_instance = RequestContext(request))\n\ndef logout_view(request):\n\tlogout(request)\n\treturn HttpResponseRedirect('/')\n\n\ndef register_view(request):\n\tform = registerform()\n\tif request.method == \"POST\":\n\t\tform = registerform(request.POST)\n\t\tif form.is_valid():\n\t\t\tusuario = form.cleaned_data['username']\n\t\t\temail = form.cleaned_data['email']\n\t\t\tpassword_one = form.cleaned_data['password_one']\n\t\t\tpassword_two = form.cleaned_data['password_two']\n\t\t\tu = User.objects.create_user(username=usuario,email=email,password=password_one)\n\t\t\tu.save()\n\t\t\treturn render_to_response('home/thanks_register.html', context_instance=RequestContext(request))\n\t\telse:\n\t\t\tctx = {'form':form}\n\t\t\treturn render_to_response('home/register.html',ctx, context_instance=RequestContext(request))\n\tctx = {'form':form}\n\treturn render_to_response('home/register.html',ctx,context_instance=RequestContext(request))\n\n\n","sub_path":"comidas_rapidas/apps/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"485174112","text":"import os\nfrom setuptools import find_packages, setup\n\nreadme_file = os.path.join(os.path.dirname(__file__), 'README.md')\n\nwith open(readme_file) as readme:\n README = f\"{readme.read()}\"\nREADME = README.replace(README.split('# Install')[0], '')\n\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\n\n\nsetup(\n name=\"django-tokko-auth\",\n version=\"0.0.3\",\n packages=find_packages(),\n include_package_data=True,\n license=\"BSD License\",\n description=\"Tokko Auth2 flavor.\",\n long_description=README,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/TokkoLabs/authorization.git\",\n author=\"Jose Salgado\",\n author_email=\"jsalgado@navent.com\",\n install_requires=[\n \"kafka-python\",\n \"json-rpc\",\n \"arrow\",\n \"python-jose\",\n \"requests\",\n \"crypto\",\n \"pycryptodome\",\n \"psycopg2\"\n ],\n classifiers=[\n \"Environment :: Web Environment\",\n \"Framework :: Django\",\n \"Framework :: Django :: 3.0\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.8\",\n \"Topic :: Internet :: WWW/HTTP\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n ],\n)\n","sub_path":"pypi_install_script/django-tokko-auth-0.0.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"94563237","text":"# KERAS -----------------------------------------------------------\n'''\nTutorial https://elitedatascience.com/keras-tutorial-deep-learning-in-python\nDocumentation: https://keras.io/\n\nData type: int to float32\n For all weights and neuron activations, if you are using a \n method based on backpropagation for training updates, \n then you need a data type that approximates real numbers, \n so that you can apply fractional updates based on differentiation. \n Best weight values are often going to be fractional, non-whole \n numbers. Non-linearities such as sigmoid are also going to \n output floats. So after the input layer you have matrices of \n float values anyway. There is not much speed advantage \n multiplying integer matrix with float one (possibly even \n slightly slower, depending on type casting mechanism). \n So the input may as well be float.\n https://datascience.stackexchange.com/questions/13636/\n neural-network-data-type-conversion-float-from-int\n'''\n\n# IMPORT PYTHON MODULES -------------------------------------------\nimport numpy as np\nnp.random.seed(123)\n\n# Import Feed Forward CNN\nfrom keras.models import Sequential\n\n# Import Core Layer Types (core because they are used in almost every NN)\nfrom keras.layers import Dense, Dropout, Activation, Flatten\n\n# Import Keras CNN Layers \nfrom keras.layers import Convolution2D, MaxPooling2D\n\n# Import Utilities\nfrom keras.utils import np_utils\n\n# Import Matplotlib\nfrom matplotlib import pyplot as plt\n\n# Import Opencv\nimport cv2\n\n# LOAD DATASET -----------------------------------------------------\n\n# MNIST dataset\n'https://en.wikipedia.org/wiki/MNIST_database'\nfrom keras.datasets import mnist\n\n# Load Train / Test SPlit\n'Why tuples?'\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\n# Print Shape (60,000 samples, 28x28 pixel images)\n'''\nprint('Training set shape => {}'.format(X_train.shape))\n'''\n\n# Show Image\n'''\ncv2.imshow('Training Example', X_train[0])\ncv2.waitKey(0)\n'''\n\n\n# PREPROCESS DATA --------------------------------------------------\n'''\nDocs: When using Theano backend, you must explicitly declare a dimension for the depth\n of the input image. Full color with all 3 RGB channels will have depth of 3. \n The data from MNIST will have depth of 1. \n\nnp.reshape (array to reshape, newshape?, depth, row, col)\n'''\n\n# Reshape Training Data\nX_train = X_train.reshape(X_train.shape[0], 1, 28, 28)\nX_test = X_test.reshape(X_test.shape[0], 1, 28, 28)\n'X_train.shape = (60000, 1, 28, 28)'\n\n# Convert to Float32i (notice that the current data type is numpy.unit8')\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\n\n# Normalize Data (Point?)\nX_train /= 255\nX_test /= 255\n\n# Convert 1-dimensional class arrays to 10-dimensional class matrices\n'Is this because the Softmax will return a 10x1 matrices?'\nY_train = np_utils.to_categorical(y_train, 10)\nY_test = np_utils.to_categorical(y_test, 10)\n\n\n# DECLARE MODEL ARCHITECTURE ----------------------------------------\n\n# Define Model\n'''\ncore.layers https://keras.io/layers/core/\nnum.convs https://keras.io/layers/convolutional/\ninput_shape should be the shape of one input. In this case its 1,28,28\n32 Refers to the number of convolutions\n3,3 Number of rows and cols of the kernel used for the convolution\n So we are going from a 28x28 to 3x3 matrix?\n\n'''\nmodel = Sequential()\nmodel.add(Convolution2D(32, 3, 3, activation='relu', input_shape=(1,28,28)))\n\n\n# Add More Layers\nmodel.add(Convolution2D(32, 3, 3, activation='relu')) # why do we add another convolution of 32?\nmodel.add(MaxPooling2D(pool_size=(2,2))) # so we are going to get a 2x2 matrix?\nmodel.add(Dropout(0,25)) # When we add layers, are they sequential?\n\n\n# Add Fully Connected Layer\n'''Questions:\n 1.) Why do we add a larger layer at the end?\n 2.) Why do we add an activation function at a hidden layer (assuming this is hidden)?\n'''\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation='softmax'))\n\n\n# Step 8: Compile Model\nmodel.compile(loss='categorical_crossentropy', \n optimizer='adam', \n metrics=['accuracy'])\n\n# Step 9: Fit model on training data\nmodel.fit(X_train, Y_train, \n batch_size=32, nb_epoch=10, verbose=1)\n\n\n# Step 10: Evaluate model on test data\nscore = model.evaluate(X_test, Y_test, verbose=0)\n\nprint(score)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tutorials/sequential/tutorial1.py","file_name":"tutorial1.py","file_ext":"py","file_size_in_byte":4760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"317857027","text":"########\n# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# * See the License for the specific language governing permissions and\n# * limitations under the License.\n\n# Built-in Imports\nimport requests\nimport json\nimport constants\nimport sys\nimport os\nimport auth\nimport utils\nfrom cloudify.exceptions import NonRecoverableError\nfrom cloudify import ctx\nfrom cloudify.decorators import operation\n\n\n@operation\ndef creation_validation(**_):\n for property_key in constants.DISK_REQUIRED_PROPERTIES:\n utils.validate_node_properties(property_key, ctx.node.properties)\n\n\n@operation\ndef create_disk(**_):\n\n curr_disk_key = \"{0}{1}{2}\".format(constants.DATA_DISK_KEY, ctx.node.id, ctx.instance.id)\n if curr_disk_key in ctx.instance.runtime_properties:\n ctx.logger.info(\"Using disk {0}\".format(ctx.instance.runtime_properties[curr_disk_key]))\n return\n\n utils.set_runtime_properties_from_file()\n current_disk_name = constants.DATA_DISK_PREFIX+utils.random_suffix_generator()\n ctx.instance.runtime_properties[curr_disk_key] = current_disk_name\n ctx.logger.info(\"create_disk: {0} is {1}\".format(curr_disk_key, current_disk_name))\n ctx.instance.runtime_properties[constants.DATA_DISK_SIZE_KEY] = ctx.node.properties[constants.DATA_DISK_SIZE_KEY]\n ctx.instance.runtime_properties[constants.DATA_DISK_LUN_KEY] = ctx.node.properties[constants.DATA_DISK_LUN_KEY]\n ctx.logger.info(\"create_disk: {0} is {1}\".format(current_disk_name,\n ctx.instance.runtime_properties[constants.DATA_DISK_SIZE_KEY]))\n\n\n@operation\ndef delete_disk(**_):\n utils.clear_runtime_properties()\n\n\n@operation\ndef set_storageaccount_details(azure_config, **kwargs):\n utils.write_target_runtime_properties_to_file([constants.RESOURCE_GROUP_KEY, constants.STORAGE_ACCOUNT_KEY]+constants.REQUIRED_CONFIG_DATA)\n\n\n","sub_path":"azurecloudify/datadisk.py","file_name":"datadisk.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"158556802","text":"# vim: set fileencoding=utf-8 :\n# Written by Behdad Esfahbod, 2007,2009\n# Not copyrighted, in public domain.\n\n# A theme file should define two functions:\n#\n# - prepare_page(renderer): should draw any background and return a tuple of\n# x,y,w,h that is the area to use for slide canvas.\n# \n# - draw_bubble(renderer, x, y, w, h, data=None): should setup canvas for the\n# slide to run. Can draw a speaking-bubble for example. x,y,w,h is the\n# actual extents that the slide will consume. Data will be the user-data\n# dictionary from the slide.\n#\n# Renderer is an object similar to a cairo.Context and pangocairo.CairoContext\n# but has its own methods too. The more useful of them here are put_text and\n# put_image. See their pydocs.\n\nimport cairo\n\nside_margin = .08\ntop_margin = .02\nbottom_margin = .14\npadding = .005\nbubble_rad = .25\n\ndef bubble (cr, x0, y0, x, y, w, h):\n\n\tr = min (w, h) * (bubble_rad / (1 - 2./8*bubble_rad))\n\n\tp = r / 7.\n\tx, y, w, h, r = x - p, y - p, w + 2*p, h + 2*p, r + p\n\n\tx1, y1, x2, y2 = x, y, x + w, y + h\n\n\tcr.move_to (x1+r, y1)\n\tcr.line_to (x2-r, y1)\n\tcr.curve_to (x2, y1, x2, y1, x2, y1+r)\n\tcr.line_to (x2, y2-r)\n\tcr.curve_to (x2, y2, x2, y2, x2-r, y2)\n\tcr.line_to (x1+r, y2)\n\tcr.curve_to (x1, y2, x1, y2, x1, y2-r)\n\tcr.line_to (x1, y1+r)\n\tcr.curve_to (x1, y1, x1, y1, x1+r, y1)\n\tcr.close_path ()\n\n\txc, yc = .5 * (x1 + x2), .5 * (y1 + y2)\n\tcr.move_to (xc+r, yc)\n\tcr.curve_to (xc+r, y0, .5 * (xc+r+x0), (yc+y0*2)/3, x0, y0)\n\tcr.curve_to (.5 * (xc-r+x0), (yc+y0*2)/3, xc-r, y0, xc-r, yc)\n\n\ndef prepare_page (renderer):\n\tcr = renderer.cr\n\twidth = renderer.width\n\theight = renderer.height\n\t\n\ts = side_margin * width\n\tl = top_margin * height\n\tf = bottom_margin * height\n\tp = padding * min (width, height)\n\tp2 = 2 * p\n\n\tcr.set_source_rgb (128/255., 255/255., 148/255.)\n\tcr.paint ()\n\n\tcr.move_to (.5 * width, height-p2)\n\tcr.set_source_rgba (0,.2,0)\n\trenderer.put_text (\"July 5th, 2009\", height=(f-p2)*.5, valign=-1)\n\n\tcr.move_to (width-p, height-p)\n\trenderer.put_image (\"grancanariadesktopsummit.png\", height = f-p2, valign=-1, halign=-1)\n\n\t# Cartoon icons for speakers\n\tcr.move_to (p, height-p)\n\trenderer.put_image (\"behdad.svg\", width = s-p2, valign=-1, halign=+1)\n\n\t# Compute rectangle available for slide content\n\tw = width - s - s - p * 2\n\tx = s + p\n\th = height - l - f - p * 2\n\ty = l + p\n\n\t# Adjust for bubble padding. the 8 comes from bezier calculations\n\td = min (w, h) * bubble_rad / 8.\n\tx, y, w, h = x + d, y + d, w - d*2, h - d*2\n\n\treturn x, y, w, h\n\ndef draw_bubble (renderer, x, y, w, h, data=None):\n\t# Fancy speech bubble!\n\tcr = renderer.cr\n\twidth = renderer.width\n\theight = renderer.height\n\t\n\ts = side_margin * width\n\tp = padding * min (width, height)\n\n\tcr.save()\n\tx, y = cr.user_to_device (x, y)\n\tw, h = cr.user_to_device_distance (w, h)\n\tcr.identity_matrix ()\n\n\twho = data.get ('who', None)\n\tif not who:\n\t\txc, yc = x + w*.5, y + h*.5\n\telif who < 0:\n\t\txc, yc = s * .9, height - .7 * s\n\telse:\n\t\txc, yc = width - s * .9, height - .7 * s\n\n\tbubble (cr, xc, yc, x, y, w, h)\n\tcr.rectangle (width, 0, -width, height)\n\tcr.clip ()\n\n\ta = .5\n\n\tbubble (cr, xc, yc, x, y, w, h)\n\tcr.set_source_rgb (64/255.*a, 128/255.*a, 64/255.*a)\n\tcr.set_line_width (p)\n\tcr.set_miter_limit (20)\n\tcr.stroke_preserve ()\n\n\tcr.restore ()\n\n\tcr.clip ()\n\tcr.set_source_rgba (.92, .98, 1, 1)\n\tcr.paint ()\n\n\tcr.set_source_rgb (96/255.*a, 128/255.*a, 96/255.*a)\n","sub_path":"stateoftext/stateoftext_theme.py","file_name":"stateoftext_theme.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"91520537","text":"import torch\nimport torch.nn as nn\nfrom torch3d.nn import SetAbstraction, FeaturePropagation\n\n\nclass PointNetSSG(nn.Module):\n def __init__(self, in_channels, num_classes, dropout=0.5):\n super(PointNetSSG, self).__init__()\n self.sa1 = SetAbstraction(in_channels, [32, 32, 64], 1024, 32, 0.1, bias=False)\n self.sa2 = SetAbstraction(64 + 3, [64, 64, 128], 256, 32, 0.2, bias=False)\n self.sa3 = SetAbstraction(128 + 3, [128, 128, 256], 64, 32, 0.4, bias=False)\n self.sa4 = SetAbstraction(256 + 3, [256, 256, 512], 16, 32, 0.8, bias=False)\n self.fp1 = FeaturePropagation(512 + 256, [256, 256], 3, bias=False)\n self.fp2 = FeaturePropagation(256 + 128, [256, 256], 3, bias=False)\n self.fp3 = FeaturePropagation(256 + 64, [256, 128], 3, bias=False)\n self.fp4 = FeaturePropagation(128, [128, 128], 3, bias=False)\n self.mlp = nn.Sequential(\n nn.Conv1d(128, 128, 1, bias=False),\n nn.BatchNorm1d(128),\n nn.ReLU(True),\n nn.Dropout(dropout),\n nn.Conv1d(128, 128, 1, bias=False),\n nn.BatchNorm1d(128),\n nn.ReLU(True),\n nn.Dropout(dropout),\n )\n self.fc = nn.Conv1d(128, num_classes, 1)\n\n def forward(self, x):\n p = x[:, :3]\n x1 = self.sa1(x)\n x2 = self.sa2(x1)\n x3 = self.sa3(x2)\n x4 = self.sa4(x3)\n x3 = self.fp1(x4, x3)\n x2 = self.fp2(x3, x2)\n x1 = self.fp3(x2, x1)\n x = self.fp4(x1, p)\n x = x[:, 3:]\n x = self.mlp(x)\n x = self.fc(x)\n return x\n","sub_path":"torch3d/models/segmentation/pointnet2.py","file_name":"pointnet2.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"647121953","text":"# There are comments with the names of\n# the required functions to build.\n# Please paste your solution underneath\n# the appropriate comment.\n\n# factorial\ndef factorial(n):\n if n < 0:\n raise ValueError\n elif n < 2:\n return 1\n else:\n return n * factorial(n-1)\n\n\n# reverse\n\ndef reverse(text):\n if len(text)==1 or len(text)== 0:\n return text \n else:\n return text[-1] + reverse(text[:-1])\n\n# bunny\ndef bunny(count):\n if count == 0:\n return 0\n return 2 + bunny(count - 1)\n\n\n\n# is_nested_parens\ndef is_nested_parens(parens):\n left_parenthesis = []\n right_parenthesis = []\n for char in parens:\n if char == \"(\":\n left_parenthesis.append(char)\n elif char == \")\":\n right_parenthesis.append(char)\n if len(left_parenthesis) == len(right_parenthesis):\n return True\n return False\n\n\n","sub_path":"part-1.py","file_name":"part-1.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"83440920","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function\n\nimport multiprocessing\nimport pickle\nimport json\nfrom collections import Counter\n\nimport numpy as np\n\nfrom mar import MAR\nfrom demos import cmd\n\n\ndef run_target_1():\n try:\n with open('./params.json') as json_file:\n params = json.load(json_file)\n except:\n raise Exception('wrong params file path')\n\n arglist = []\n for filename in params['dataset_files']:\n for fea in params['features']:\n for trec in params['trecs']:\n for i in range(30):\n arglist.append((str(fea), i, str(filename), trec))\n\n pool = multiprocessing.Pool()\n pool.map(error_hpcc_feature_ds_wrapper, arglist)\n pool.close()\n\n\ndef run_missing_target_1():\n try:\n with open('./params.json') as json_file:\n params = json.load(json_file)\n except:\n raise Exception('wrong params file path')\n\n arglist = []\n for ds in params['dataset_files']:\n ds = str(ds).replace('.csv', '')\n\n with open(\"../memory/rerun_params_{}.pickle\".format(ds), \"r\") as handle:\n rerun = pickle.load(handle)\n # print(rerun)\n\n for execution in rerun:\n arglist.append((execution['fea'], int(execution['seed']), execution['filename'],\n float(execution['trec'])))\n\n pool = multiprocessing.Pool()\n pool.map(error_hpcc_feature_ds_wrapper, arglist)\n pool.close()\n\n\ndef error_hpcc_feature_ds_wrapper(args):\n error_hpcc_feature_ds(*args)\n\n\ndef error_hpcc_feature_ds(fea, seed=1, filename='drupal_combine.csv', trec=0.95):\n np.random.seed(int(seed))\n\n strec = '@' + str(int(trec * 100))\n round_id = \"hpcc_{}_{}_{}_{}\".format(filename.split(\".\")[0], fea, strec, seed)\n\n if fea == 'combine':\n read = Combine(filename=filename, trec=trec, seed=seed, round_id=round_id)\n elif fea == 'text':\n read = Text(filename=filename, trec=trec, seed=seed, round_id=round_id)\n elif fea == 'crash':\n read = CRASH(filename=filename, trec=trec, seed=seed, round_id=round_id)\n elif fea == 'random':\n read = Rand(filename=filename, trec=trec, seed=seed, round_id=round_id)\n else:\n raise Exception('wrong feature provided')\n\n execution_results = {'loops': read.record, 'stats': read.results}\n read.results[\"reached\"] = True\n\n target = int((read.results[\"truepos\"] + read.results[\"unknownyes\"]) * trec)\n vul_found = read.results[\"truepos\"]\n\n if vul_found < target:\n read.results[\"reached\"] = False\n\n with open(\"../dump/features_\" + round_id + \".pickle\", \"w\") as handle:\n pickle.dump(execution_results, handle)\n\n\ndef Combine(filename='vuls_data_new.csv', trec=0.95, seed=0, round_id='@unknow'):\n thres = 0\n starting = 1\n np.random.seed(seed)\n\n read = MAR()\n read.step = 10\n read.roundname = round_id\n read.correction = 'no'\n read.crash = 'append'\n read = read.create(filename, 'all')\n\n read.interval = 100000\n\n num2 = read.get_allpos()\n target = int(num2 * trec)\n\n read.enable_est = False\n\n while True:\n pos, neg, total = read.get_numbers()\n # print(pos, pos+neg)\n\n if pos + neg >= total:\n break\n\n if pos < starting or pos + neg < thres:\n for id in read.BM25_get():\n read.code_error(id, error='none')\n else:\n a, b, c, d = read.train(weighting=True, pne=True)\n\n if pos >= target:\n break\n\n if pos < 10:\n for id in a:\n read.code_error(id, error='none')\n else:\n for id in c:\n read.code_error(id, error='none')\n read.results = analyze(read)\n print(read.roundname, read.results['unique'] / len(read.body[\"code\"]))\n return read\n\n\ndef Text(filename='vuls_data_new.csv', seed=0, trec=0.95, round_id='@unknow'):\n thres = 0\n starting = 1\n np.random.seed(seed)\n read = MAR()\n read.roundname = round_id\n read.correction = 'no'\n read = read.create(filename, 'all')\n read.interval = 100000\n\n num2 = read.get_allpos()\n target = int(num2 * trec)\n\n read.enable_est = False\n read.step = 10\n\n while True:\n pos, neg, total = read.get_numbers()\n\n if pos + neg >= total:\n break\n\n if pos < starting or pos + neg < thres:\n for id in read.random():\n read.code_error(id, error='none')\n else:\n a, b, c, d = read.train(weighting=True, pne=True)\n\n if pos >= target:\n break\n\n if pos < 10:\n for id in a:\n read.code_error(id, error='none')\n else:\n for id in c:\n read.code_error(id, error='none')\n\n read.results = analyze(read)\n print(read.roundname, read.results['unique'] / len(read.body[\"code\"]))\n return read\n\n\ndef Rand(filename='vuls_data_new.csv', seed=0, trec=0.95, round_id='@unknow'):\n np.random.seed(seed)\n\n read = MAR()\n read = read.create(filename, 'all')\n read.interval = 100000\n read.step = 10\n read.roundname = round_id\n read.enable_est = False\n\n num2 = read.get_allpos()\n target = int(num2 * trec)\n\n while True:\n pos, neg, total = read.get_numbers()\n # try:\n # print(\"%d, %d, %d\" %(pos,pos+neg, read.est_num))\n # except:\n # print(\"%d, %d\" %(pos,pos+neg))\n\n if pos + neg >= total or pos >= target:\n break\n\n for id in read.random():\n read.code_error(id, error='none')\n\n read.results = analyze(read)\n print(read.roundname, read.results['unique'] / len(read.body[\"code\"]))\n return read\n\n\ndef CRASH(filename='vuls_data_new.csv', trec=0.95, seed=0, round_id='@unknow'):\n starting = 1\n np.random.seed(seed)\n\n read = MAR()\n read = read.create(filename, 'all')\n thres = Counter(read.body.crashes > 0)[True]\n read.interval = 100000\n read.roundname = round_id\n\n num2 = read.get_allpos()\n target = int(num2 * trec)\n\n read.enable_est = False\n read.step = 10\n\n while True:\n pos, neg, total = read.get_numbers()\n # print(\"%d, %d\" %(pos,pos+neg))\n\n if pos + neg >= total:\n break\n\n # todo: confirm condition\n if (pos < starting or pos + neg < thres) and pos < target:\n for id in read.BM25_get():\n read.code_error(id, error='none')\n else:\n break\n # if pos >= target:\n # break\n\n read.results = analyze(read)\n print(read.roundname, read.results['unique'] / len(read.body[\"code\"]))\n\n # todo: understand why\n result = {'est': read.record_est, 'pos': read.record}\n\n return read\n\n\ndef analyze(read):\n unknown = np.where(np.array(read.body['code']) == \"undetermined\")[0]\n pos = np.where(np.array(read.body['code']) == \"yes\")[0]\n neg = np.where(np.array(read.body['code']) == \"no\")[0]\n yes = np.where(np.array(read.body['label']) == \"yes\")[0]\n no = np.where(np.array(read.body['label']) == \"no\")[0]\n falsepos = len(set(pos) & set(no))\n truepos = len(set(pos) & set(yes))\n falseneg = len(set(neg) & set(yes))\n unknownyes = len(set(unknown) & set(yes))\n unique = len(read.body['code']) - len(unknown)\n count = sum(read.body['count'])\n correction = read.correction\n return {\"falsepos\": falsepos, \"truepos\": truepos, \"falseneg\": falseneg, \"unknownyes\": unknownyes, \"unique\": unique,\n \"count\": count, \"correction\": correction, \"files\": len(read.body['code'])}\n\n\nif __name__ == \"__main__\":\n eval(cmd())","sub_path":"src/new_runner.py","file_name":"new_runner.py","file_ext":"py","file_size_in_byte":7673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"41092295","text":"'''Test wolff.reinitializers.peng_reinitialization'''\n\nimport unittest\nimport numpy as np\nimport numpy.testing as npt\nfrom wolff.grid import Grid\nfrom wolff.adjoint.yang_adjoint_solver import YangAdjointSolver\n\n\nclass TestYangAdjointSolver(unittest.TestCase):\n '''Test wolff.solver'''\n\n def test_default_simulation_time(self):\n '''Has default simulation time'''\n s = YangAdjointSolver()\n self.assertEqual(s.simulation_time, 0.0)\n\n def test_set_simulation_time(self):\n '''Can set solver simulation time'''\n s = YangAdjointSolver()\n s.simulation_time = 10.0\n self.assertAlmostEqual(s.simulation_time, 10.0)\n\n def test_cannot_set_negative_time(self):\n '''Cannot set a negative simulation time'''\n def instantiate():\n s = YangAdjointSolver()\n s.simulation_time = -1.0\n self.assertRaises(ValueError, instantiate)\n\n def test_default_grids_true(self):\n '''Has default grids_true'''\n s = YangAdjointSolver()\n self.assertEqual(s.grids_true, [])\n\n def test_set_grids_true(self):\n '''Can set solver grids_true'''\n s = YangAdjointSolver()\n\n grids = []\n\n grid = Grid()\n grid.data = np.zeros((3, 3, 3))\n grid.data[1, 1, 1] = 0.5\n\n grids.append(grid)\n\n s.grids_true = grids\n\n npt.assert_array_almost_equal(s.grids_true[0].data, grid.data)\n\n def test_default_grids_predicted(self):\n '''Has default grids_true'''\n s = YangAdjointSolver()\n self.assertEqual(s.grids_predicted, [])\n\n def test_set_grids_predicted(self):\n '''Can set solver grids_predicted'''\n s = YangAdjointSolver()\n\n grids = []\n\n grid = Grid()\n grid.data = np.zeros((3, 3, 3))\n grid.data[1, 1, 1] = 0.5\n\n grids.append(grid)\n\n s.grids_predicted = grids\n\n npt.assert_array_almost_equal(s.grids_predicted[0].data, grid.data)\n\n def test_default_F(self):\n '''Has default F'''\n s = YangAdjointSolver()\n self.assertEqual(s.F, None)\n\n def test_set_F(self):\n '''Can set solver F'''\n s = YangAdjointSolver()\n\n grids = []\n\n grid = Grid()\n grid.data = np.zeros((3, 3, 3))\n grid.data[1, 1, 1] = 0.5\n\n grids.append(grid)\n\n s.F = grids\n\n npt.assert_array_almost_equal(s.F[0].data, grid.data)\n\n def test_default_dt(self):\n '''Has default dt'''\n s = YangAdjointSolver()\n self.assertEqual(s.dt, np.inf)\n\n def test_set_dt(self):\n '''Can set solver dt'''\n s = YangAdjointSolver()\n s.dt = 0.5\n self.assertEqual(s.dt, 0.5)\n\n def test_cannot_set_negative_dt(self):\n '''Can set solver dt'''\n def instantiate():\n s = YangAdjointSolver()\n s.dt = -0.5\n self.assertRaises(ValueError, instantiate)\n\n def test_cannot_set_grid_as_non_grid_objects(self):\n '''Cannot set grid as non-Grid object'''\n def instantiate():\n s = YangAdjointSolver()\n s.grid = object()\n self.assertRaises(TypeError, instantiate)\n\n def test_cannot_add_non_sink_objects(self):\n '''Cannot add a non-sink object'''\n def instantiate():\n s = YangAdjointSolver()\n s.add_sink(object())\n self.assertRaises(TypeError, instantiate)\n\n def test_halt_on_max_iterations(self):\n '''Halts at max iterations'''\n\n grid_adjoint = Grid()\n grid_adjoint.spacing = np.array([1.0, 1.0, 1.0])\n grid_adjoint.origin = np.array([0.0, 0.0, 0.0])\n grid_adjoint.data = np.zeros([3, 3, 3])\n\n grid_true = Grid()\n grid_true.spacing = np.array([1.0, 1.0, 1.0])\n grid_true.origin = np.array([0.0, 0.0, 0.0])\n grid_true.data = np.zeros([3, 3, 3])\n grid_true.data[1, 1, 1] = 1.0\n\n grid_predicted = Grid()\n grid_predicted.spacing = np.array([1.0, 1.0, 1.0])\n grid_predicted.origin = np.array([0.0, 0.0, 0.0])\n grid_predicted.data = np.zeros([3, 3, 3])\n grid_predicted.data[1, 1, 1] = 0.5\n\n grids_true = []\n grids_true.append(grid_true)\n\n grids_predicted = []\n grids_predicted.append(grid_true)\n\n F_initial = grid_adjoint.Copy()\n F_initial.data = np.ones_like(grid_adjoint.data)\n\n F = []\n F.append(F_initial)\n\n s = YangAdjointSolver()\n s.grid = grid_adjoint\n s.grids_true = grids_true\n s.grids_predicted = grids_predicted\n s.F = F\n s.dt = 0.5\n s.simulation_time = 1.0\n\n s.simulate()\n\n self.assertTrue(s.elapsed_time, 0)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/adjoint/test_yang_adjoint_solver.py","file_name":"test_yang_adjoint_solver.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"23473003","text":"from flask import Flask, request\n\nimport urllib\n\nimport json\n\nfrom flask_ngrok import run_with_ngrok\n\n\nurl = \"https://api.covid19india.org/v4/data.json\"\n\n\nresponse = urllib.request.urlopen(url)\n\n\n\n\ndata = json.loads(response.read())\n\n\n\n# data['GJ']['districts']['Surat']\n\n\n\ndef covid_parameters(state, city):\n temp = data[state]['districts'][city]\n \n try:\n active = temp['total']['confirmed'] - temp['total']['recovered']\n population = temp['meta']['population']\n daily_cases = temp['delta']['confirmed']\n daily_recovered = temp['delta']['recovered']\n active_ratio = (active/population)*100\n daily_cases_ratio = ((daily_cases - daily_recovered)/population)*1000\n except:\n active = 0\n population = 0\n daily_cases = 0\n daily_recovered = 0\n active_ratio = 0\n daily_cases_ratio = 0\n \n results = {\n 'active' : active,\n 'population' : population,\n 'daily_cases' : daily_cases,\n 'daily_recovered' : daily_recovered,\n 'active_ratio' : active_ratio,\n 'daily_cases_ratio' : daily_cases_ratio,\n }\n \n return results\n\n\n\n\n\ndef safety_score(results):\n active_score = 0\n if (results['active_ratio'] < 0.25):\n active_score = results['active_ratio']*20\n elif (results['active_ratio'] < 0.5):\n active_score = 5\n elif (results['active_ratio'] < 1):\n active_score = 10\n elif (results['active_ratio'] < 2):\n active_score = 50\n elif (results['active_ratio'] < 4):\n active_score = 80\n else:\n active_score = 100\n daily_score = 0\n if (results['daily_cases_ratio'] < 0.25):\n daily_score = results['daily_cases_ratio']*20\n elif (results['daily_cases_ratio'] < 0.5):\n daily_score = 5\n elif (results['daily_cases_ratio'] < 1):\n daily_score = 10\n elif (results['daily_cases_ratio'] < 2):\n daily_score = 50\n elif (results['daily_cases_ratio'] < 4):\n daily_score = 80\n else:\n daily_score = 100\n \n return 100 - (active_score + daily_score)/2\n\n\n# safety_score(covid_parameters('GJ', 'Ahmedabad'))\n\n\n\n\napp = Flask(__name__)\nrun_with_ngrok(app)\n\n\n\n\n@app.route('/city-safety')\ndef safety():\n try:\n state = request.args.get('state')\n city = request.args.get('city')\n \n if state != None and city != None:\n return str(safety_score(covid_parameters(state, city)))\n else:\n return \"Send proper argumnets\"\n except:\n return \"Send proper argumnets\"\n\n\n\nif __name__ == '__main__':\n app.run()\n\n\n\n\n\n\n\n","sub_path":"Flask/covid-api.py","file_name":"covid-api.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"609059145","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nScript Header\n\n$Id: US24765\n\nCopyright (c) 2016-2017 Cisco Systems, Inc.\n\nName:\n cmCC24765_3pcc_BS_IOT_Interop_177_PHONESCAParkedCall\n\nPurpose:\n This test case verifies the DUT’s interoperability with BroadWorks for\n handling notification of a call parked on a shared line\n\nAuthor:\n Purushotham S (pshivara@cisco.com)\n\nReferences:\n BW-SIPPhone-InteropTestPlan-R21.0\n\nDescription:\n PHONE – SCA: Parked Call.\n\nTest bed requirement:\n 1: 3 3pcc phones\n 2: 2 phones should register successfully with private line\n 3: Another 1 Phone should register successfully with shared line.\n\nTest Steps:\n 1. BroadWorks User A dials BroadWorks User B.\n 2. Both BroadWorks User A and User B are alerted.\n 3. BroadWorks User B answers the call\n 4. BroadWorks User A dials a second call to Call Park feature code *68 to\n park the call\n 5. BroadWorks User A supplies the DUT’s extension to park the call against\n 6. BroadWorks User A is now held\n 7. BroadWorks User B hangs up\n\nVerify:\n 1. Two-way voice path is established BroadWorks User A and User B.\n 2. Verify the SIP signaling to and from the DUT.\n − BroadWorks sends a SCA NOTIFY with call-info event and containing an\n x broadworks-callpark-info+xml body with parked element identifying\n the parked user.\n − DUT responds with a 200 OK.\n\nKnown Bugs:\n\n\"\"\"\n\nimport tng\nimport logging\nfrom tng_sl.device.endpoint.synergylite.synergylite_3pcc_extended \\\n import wait_for_ccapi_call_states\nfrom tng_sl.contrib.mpp.phone_line_reg_helper import PhoneLineRegHelper\nfrom tng_sl.contrib.mpp.phone_line_reg_helper import PhoneConfigHelper\nfrom tng_sl.contrib.mpp.tshark_helper import TsharkHelper\nfrom tng_sl.contrib.mpp.broadsoft_login_helper import BroadsoftLoginHelper\nfrom tng_sl.contrib.setup_helper import SetupHelpersTestCase\n\nlog = logging.getLogger('PHONESCAParkedCall')\n\n\nclass PHONESCAParkedCall(SetupHelpersTestCase, tng.api.TestCase):\n helpers = (\n PhoneConfigHelper, BroadsoftLoginHelper, PhoneLineRegHelper,\n TsharkHelper)\n helper_num_devices = 3\n\n def setUp(self):\n log.info(\"Start of setUp\")\n self.serverproxy = self.toolkit.get_test_env_info(\n section='bsoft', parameter_name=\"as_ip_addr\")\n\n self.shared_userID = '{}{}'.format(self.user_id1, 'a')\n self.devices = (self.oPhone1, self.oPhone2, self.oPhone3)\n self.device_type = 'Cisco-Hybrid{}'.format(\n self.oPhone1.get_web_status('Product_Name')[2:])\n\n # Configure Shared line on Phone1\n self.shared_name = self.bsoft_web.configure_shared_line(\n shared_number=self.shared_userID,\n device_type=self.device_type, user_phone_num=self.user_id1)\n\n # Delete configured Shared line\n self.addCleanup(\n self.bsoft_web.delete_shared_line, user_phone_num=self.user_id1,\n shared_name=self.shared_name)\n\n # Configure Multiple Call Arrangement on Phone1\n self.bsoft_web.configure_multiple_call_arrangement(\n account_type='group admin', user_phone_num=self.user_id1)\n\n # Configure call park notification on Phone1\n self.bsoft_web.enable_disable_call_park_notification(\n account_type='group admin', user_phone_num=self.user_id1)\n\n # Disable call park notification\n self.addCleanup(\n self.bsoft_web.enable_disable_call_park_notification,\n account_type='group admin', user_phone_num=self.user_id1)\n log.info(\"End of setUp\")\n\n def test_PHONE_SCA_Parked_Call(self):\n log.info(\"Start of test_PHONE_SCA_Parked_Call\")\n\n self.oPhone1.log.info(\n \"Setting Share Ext=Shared, Shared call appearance=Yes and\"\n \" Call Park Monitor Enable=Yes\")\n self.oPhone1.ui.set_web_parameter_by_resync(\n Share_Call_Appearance_1=['Share_Call_Appearance_1_', 'shared'],\n Share_Ext_1=['Share_Ext_1_', 'Yes'],\n Call_Park_Monitor_Enable_1_=['Call_Park_Monitor_Enable_1_', 'Yes'])\n\n apperance1, share_ext1, monitor_enable1 = self.oPhone1.get_web_config(\n 'Share_Call_Appearance_1_', 'Share_Ext_1_',\n 'Call_Park_Monitor_Enable_1_')\n self.assertEqual(\n apperance1, \"shared\",\n \"Shared call appearance is not set on Phone1\")\n self.assertEqual(\n share_ext1, \"Yes\", \"Share Ext is not set on Phone1\")\n self.assertEqual(\n monitor_enable1, 'Yes', \"Call park monitor is not set on Phone1\")\n self.oPhone1.log.info(\n \"Share Ext=Shared, Shared call appearance=Yes and \"\n \"Call Park Monitor Enable=Yes are set\")\n\n log.info('Start tshark on linux')\n dut1_ip = self.oPhone1.ip\n filter_cmd = 'port sip and host {}'.format(dut1_ip)\n capture_file = self.tshark.tshark_start(filter_cmd)\n\n log.info(\"Phone2 dials Phone3 number: {}\".format(self.user_id3))\n self.oPhone2.ccapi.dial('null', self.user_id3, '', 1, 0, 1)\n # check phone2 ringout and phone3 ringing status, phone1 idle status\n wait_for_ccapi_call_states(\n self.devices, (\"IDLE\", \"PROCEEDING\", \"RINGING\"), timeout=30)\n\n log.info(\"Phone3 answers the call\")\n self.oPhone3.ccapi.accept(\"0000\")\n # check phones 2 & 3 are in connected and Phone1 in idle status\n wait_for_ccapi_call_states(\n self.devices, (\"IDLE\", \"CONNECTED\", \"CONNECTED\"), timeout=30)\n\n user_id1_hash = \"{}#\".format(self.user_id1)\n log.info(\"Phone2 initiates call park by dialing *68\")\n self.oPhone2.ccapi.dial('null', '*68', '', 1, 0, 1)\n # check phone2 is in Hold\n wait_for_ccapi_call_states(\n self.devices, (\"IDLE\", \"HOLD\", \"CONNECTED\"), timeout=30)\n\n log.info(\"Phone2 gives phone1 (DUT) extension to park the call\")\n for digit in list(user_id1_hash):\n self.oPhone2.ccapi.sendDialDigit('0001', digit)\n wait_for_ccapi_call_states(\n self.devices, (\"IDLE\", \"IDLE\", \"CONNECTED\"), timeout=30)\n\n log.info(\"Disconnect the call from Phone1 (DUT)\")\n self.oPhone3.ccapi.hangUp('0000')\n # check phone1, phone2 and phone3 status are in idle status\n wait_for_ccapi_call_states(\n self.devices, (\"IDLE\", \"IDLE\", \"IDLE\"), timeout=30)\n\n log.info('Stop tshark on linux')\n self.tshark.tshark_stop()\n\n # analyse tshark capture\n log.info(\"Get CSeq and Call-ID of NOTIFY from DUT\")\n notify_dut1_cseq, notify_dut1_call_id = (\n self.tshark.tshark_get_string_cseq_call_id(\n capture_file, self.serverproxy, dut1_ip,\n search_string='x-broadworks-callpark-info+xml',\n method='Request: NOTIFY', header='Content-Type'))\n\n log.info(\n \"Check BroadWorks sends a SCA NOTIFY with call-info event and \"\n \"containing an x broadworks-callpark-info+xml body with parked \"\n \"element identifying the parked user\")\n for message_type in 'parked', 'identity display':\n self.tshark.tshark_check_string_in_message(\n capture_file, 'Request: NOTIFY', message_type,\n self.serverproxy, dut1_ip, cseq=notify_dut1_cseq,\n call_id=notify_dut1_call_id)\n log.info(\n \"BroadWorks sends a SCA NOTIFY with call-info event and containing\"\n \" an x broadworks-callpark-info+xml body with parked element \"\n \"identifying the parked user\")\n\n log.info(\"Check DUT responds with a 200 OK\")\n self.tshark.tshark_check_string_in_message(\n capture_file, '200 OK', '200 OK', dut1_ip, self.serverproxy,\n cseq=notify_dut1_cseq, call_id=notify_dut1_call_id,\n header='Status-Line')\n log.info(\"DUT responds with a 200 OK\")\n\n log.info(\"==Verification success!==\")\n log.info(\"End of test_PHONE_SCA_Parked_Call\")\n\n\n# this is called by 'tng run'\ndef main():\n tng.api.runner()\n\nif __name__ == '__main__':\n tng.run(main)\n","sub_path":"common/IOT/Broadsoft_Interop/section_8/cc_shared/cmCC24765_3pcc_BS_IOT_Interop_177_PHONESCAParkedCall.py","file_name":"cmCC24765_3pcc_BS_IOT_Interop_177_PHONESCAParkedCall.py","file_ext":"py","file_size_in_byte":8102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"207448865","text":"import numpy as np\nimport random\nimport multiprocessing\n\nG = 1.0\nsF=4.0\n\ndef parallelOptimization_K(K):\n stepFactor=sF\n n = 500\n print(K)\n eta = stepFactor * np.log(n*K) / (n*K)\n e3 = 0;\n for rep in range(reps):\n e3 += randomReshuffleNonLipHess(eta, n, K)\n\n eps3_i = 1.0*e3/reps\n epsr1_i = 1.0/K**2\n epsr2_i = 1.0*(np.log(K*n)**2)/K**2\n return [eps3_i, epsr1_i, epsr2_i]\n\ndef randomReshuffleNonLipHess(eta, n, K):\n x=0\n for i in range(1, K+1):\n r = np.random.permutation(np.concatenate((-np.ones(np.int(n/2)), np.ones(np.int(n/2)))))\n for j in range(0, n):\n if (x>0):\n x = (1 - eta*4.0)*x - eta*r[j]\n else:\n x = (1 - eta)*x - eta*r[j]\n return x**2\n\n\nreps = 1000\nK_beg=30\nK_end=200\nx_list=[]\nl1=[];l2=[];l3=[]\npool = multiprocessing.Pool(16)\nK_range = range(K_beg,K_end)\nresults = pool.map(parallelOptimization_K, K_range)\n\nf = open('plotdata/experiment_K_parallel_'+str(sF), 'w') # Replace with desired output file name\nf.write(\",\".join([str(K) for K in K_range]) + \"\\n\" + \"\\n\".join([\",\".join([str(r) for r in res]) for res in results]))\n","sub_path":"LowerBound_K.py","file_name":"LowerBound_K.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"490058454","text":"import abc\nimport fnmatch\nfrom typing import Tuple\n\nimport attr\nimport six\nfrom sqlalchemy import MetaData\nfrom sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.sql.ddl import CreateSchema\nfrom sqlalchemy.sql.schema import Table\n\nfrom pytest_mock_resources import compat\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass AbstractAction(object):\n @abc.abstractmethod\n def run(self, engine_manager):\n \"\"\"Run an action on a database via the passed-in engine_manager instance.\"\"\"\n\n\nclass Rows(AbstractAction):\n def __init__(self, *rows):\n self.rows = rows\n\n def run(self, engine_manager):\n rows = self._get_stateless_rows(self.rows)\n\n metadatas = self._get_metadatas(rows)\n\n for metadata in metadatas:\n engine_manager.create_ddl(metadata)\n\n self._create_rows(engine_manager.engine, rows)\n\n @staticmethod\n def _get_stateless_rows(rows):\n \"\"\"Create rows that aren't associated with any other SQLAlchemy session.\"\"\"\n stateless_rows = []\n for row in rows:\n row_args = row.__dict__\n row_args.pop(\"_sa_instance_state\", None)\n\n stateless_row = type(row)(**row_args)\n\n stateless_rows.append(stateless_row)\n return stateless_rows\n\n @staticmethod\n def _get_metadatas(rows):\n return {row.metadata for row in rows}\n\n @staticmethod\n def _create_rows(engine, rows):\n Session = sessionmaker(bind=engine)\n session = Session()\n\n session.add_all(rows)\n\n session.commit()\n session.close()\n\n\nclass Statements(AbstractAction):\n def __init__(self, *statements):\n self.statements = statements\n\n def run(self, engine_manager):\n for statement in self.statements:\n engine_manager.engine.execute(statement)\n\n\n@attr.s\nclass EngineManager(object):\n engine = attr.ib()\n ordered_actions = attr.ib(default=attr.Factory(tuple))\n tables: Tuple = attr.ib(default=None, converter=attr.converters.optional(tuple))\n session = attr.ib(default=False)\n default_schema = attr.ib(default=None)\n\n _ddl_created = False\n\n def _run_actions(self):\n BaseType = type(declarative_base())\n\n for action in self.ordered_actions:\n if isinstance(action, MetaData):\n self.create_ddl(action)\n elif isinstance(action, BaseType):\n self.create_ddl(action.metadata)\n elif isinstance(action, AbstractAction):\n action.run(self)\n elif callable(action):\n self._execute_function(action)\n else:\n raise ValueError(\n \"create_fixture function takes in sqlalchemy.MetaData or actions as inputs only.\"\n )\n\n def _create_schemas(self, metadata):\n if self._ddl_created:\n return\n\n all_schemas = {table.schema for table in metadata.tables.values() if table.schema}\n\n for schema in all_schemas:\n if self.default_schema == schema:\n continue\n\n statement = CreateSchema(schema, quote=True)\n self.engine.execute(statement)\n\n def _create_tables(self, metadata):\n if not self.tables:\n metadata.create_all(self.engine)\n return\n\n table_objects = {\n table_object\n for table in self.tables\n for table_object in identify_matching_tables(metadata, table)\n }\n\n metadata.create_all(self.engine, tables=list(table_objects))\n\n def _execute_function(self, fn):\n Session = sessionmaker(bind=self.engine)\n session = Session()\n\n fn(session)\n\n session.commit()\n session.close()\n\n def create_ddl(self, metadata):\n self._create_schemas(metadata)\n self._create_tables(metadata)\n self._ddl_created = True\n\n def manage(self, session=None):\n try:\n self._run_actions()\n\n if session:\n if isinstance(session, sessionmaker):\n session_factory = session\n else:\n session_factory = sessionmaker(bind=self.engine)\n\n Session = scoped_session(session_factory)\n session = Session(bind=self.engine)\n yield session\n session.close()\n else:\n yield self.engine\n finally:\n self.engine.dispose()\n\n def manage_sync(self, session=None):\n try:\n self._run_actions()\n\n if session:\n if isinstance(session, sessionmaker):\n session_factory = session\n else:\n session_factory = sessionmaker(bind=self.engine)\n\n Session = scoped_session(session_factory)\n session = Session(bind=self.engine)\n yield session\n session.close()\n else:\n yield self.engine\n finally:\n self.engine.dispose()\n\n async def manage_async(self, session=None):\n try:\n self._run_actions()\n\n async_engine = self._get_async_engine()\n\n if session:\n if isinstance(session, sessionmaker):\n session_factory = session\n else:\n session_factory = sessionmaker(\n async_engine,\n expire_on_commit=False,\n class_=compat.sqlalchemy.asyncio.AsyncSession,\n )\n async with session_factory() as session:\n yield session\n else:\n yield async_engine\n finally:\n self.engine.dispose()\n\n def _get_async_engine(self, isolation_level=None):\n url = compat.sqlalchemy.URL(\n drivername=\"postgresql+asyncpg\",\n username=self.engine.pmr_credentials.username,\n password=self.engine.pmr_credentials.password,\n host=self.engine.pmr_credentials.host,\n port=self.engine.pmr_credentials.port,\n database=self.engine.pmr_credentials.database,\n query=dict(ssl=\"disable\"),\n )\n options = {}\n if isolation_level:\n options[\"isolation_level\"] = isolation_level\n return compat.sqlalchemy.asyncio.create_async_engine(url, **options)\n\n\ndef identify_matching_tables(metadata, table_specifier):\n if isinstance(table_specifier, DeclarativeMeta):\n return [table_specifier.__table__]\n\n if isinstance(table_specifier, Table):\n return [table_specifier]\n\n tables = [\n table\n for table_name, table in metadata.tables.items()\n if fnmatch.fnmatch(table_name, table_specifier)\n ]\n\n if tables:\n return tables\n\n table_names = \", \".join(sorted(metadata.tables.keys()))\n raise ValueError(\n 'Could not identify any tables matching \"{}\" from: {}'.format(table_specifier, table_names)\n )\n","sub_path":"src/pytest_mock_resources/fixture/database/relational/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":7066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"83748968","text":"\ninFile = open(\"day23.in\", \"r\").read().strip()\n\ncups = [int(x) for x in inFile]\n\nminVal = sorted(cups)[0]\nmaxVal = sorted(cups)[-1]\n\ncurrentCup = 0\ncount = 0\nfor i in range(100):\n\tcount += 1\n\tcurLabel = cups[currentCup]\n\n\tif currentCup < len(cups) - 4:\n\t\toutCups = cups[currentCup + 1: currentCup + 4]\n\t\tcups = cups[:currentCup + 1] + cups[4 - (len(cups) - currentCup):]\n\telse:\n\t\toutCups = cups[currentCup + 1:] + cups[:4 - (len(cups) - currentCup)]\n\t\tcups = cups[4 - (len(cups) - currentCup):currentCup + 1]\n\n\tdestination = cups[min(currentCup, len(cups) - 1)] - 1\n\n\twhile destination in outCups or destination < minVal:\n\t\tdestination -= 1\n\t\tif destination < minVal:\n\t\t\tdestination = maxVal\n\n\tdestPos = cups.index(destination)\n\n\tcups = cups[:destPos + 1] + outCups + cups[destPos + 1:]\n\n\tcurrentCup = cups.index(curLabel)\n\n\tcurrentCup += 1\n\tcurrentCup = currentCup % len(cups)\n\nwhile cups.index(1) != 0:\n\tcups.append(cups.pop(0))\n\ncups.pop(0)\n\nprint(''.join(str(x) for x in cups))\n","sub_path":"2020/day23-1.py","file_name":"day23-1.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"532995323","text":"\n\n\n# Az A,B,C háromszögben keressük a P pontot\n# Megrajzoljuk az AB, AC, AP egyeneseket, ha AP meredeksége a kettő meredekség között van, akkor benne van abban a siknegyedben\n# Megrajzoljuk az BA, BC, BP egyeneseket, Ba AP meredeksége a kettő meredekség között van, akkor benne van abban a siknegyedben\n\nax=0\nay=0\n\nbx=5\nby=0\n\ncx=2.6\ncy=5\n\npx=2\npy=1.8\n\nmAB=(by-ay)/(bx-ax)\nmAP=(py-ay)/(px-ax)\nmAC=(cy-ay)/(cx-ax)\n\nmBA=(ay-by)/(ax-bx)\nmBP=(py-by)/(px-bx)\nmBC=(cy-by)/(cx-bx)\n\nprint(\"A: {},{}\".format(ax,ay))\nprint(\"B: {},{}\".format(bx,by))\nprint(\"C: {},{}\".format(cx,cy))\nprint(\"P: {},{}\".format(px,py))\n\nAPok = (mAB <= mAP <= mAC) or (mAC <= mAP <= mAB)\nBPok = (mBA <= mBP <= mBC) or (mBC <= mBP <= mBA)\n\nprint(\"mAB:{} mAP:{} mAC:{} between:{}\".format(mAB,mAP,mAC,APok))\nprint(\"mBA:{} mBP:{} mBC:{} between:{}\".format(mBA,mBP,mBC,BPok))\n\n","sub_path":"tsp_Sierpinsky/tsp_point_in_triangle.py","file_name":"tsp_point_in_triangle.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"113746773","text":"'''\r\nAWP | Astrodynamics with Python by Alfonso Gonzalez\r\nhttps://github.com/alfonsogonzalez/AWP\r\nhttps://www.youtube.com/c/AlfonsoGonzalezSpaceEngineering\r\n\r\nSpacecraft Class Unit Tests\r\n'''\r\n\r\n# 3rd party libraries\r\nimport pytest\r\nimport numpy as np\r\n\r\n# AWP library\r\nfrom Spacecraft import Spacecraft as SC\r\nimport planetary_data as pd\r\n\r\n# Treat all warnings as errors\r\npytestmark = pytest.mark.filterwarnings( 'error' )\r\n\r\ndef test_Spacecraft_basic_propagation( plot = False ):\r\n\tsc = SC( {\r\n\t\t'coes' : [ pd.earth[ 'radius' ] + 1000.0, 0.0, 0.0, 0.0, 0.0, 0.0 ],\r\n\t\t'tspan': '1',\r\n\t\t'dt' : 100.0,\r\n\t\t'rtol' : 1e-8\r\n\t\t} )\r\n\tassert sc.cb == pd.earth\r\n\r\n\t'''\r\n\tSince inclination is 0, all z-axis components of Spacecraft\r\n\tposition and velocity should be 0\r\n\t'''\r\n\tassert np.all( sc.states[ :, 2 ] == 0.0 )\r\n\tassert np.all( sc.states[ :, 5 ] == 0.0 )\r\n\r\n\t'''\r\n\tSince there are no orbital perturbations, all COEs except\r\n\ttrue anomaly should\tbe close to constant\r\n\t(not exactly constant due to numerical error).\r\n\tHowever, since this is a circular orbit, periapsis is loosely\r\n\tdefined, causing errors in true anomaly (not exactly linear),\r\n\targument of periapsis (bounces back and forth between\r\n\t0 and 359.9 degrees), eccentricity (random noise), and\r\n\tsemi-major axis (drift / random noise)\r\n\t'''\r\n\tsc.calc_coes()\r\n\tassert sc.coes_calculated\r\n\tassert pytest.approx(\r\n\t\tsc.coes[ :, 0 ],\r\n\t\tabs = 1e-3 ) == pd.earth[ 'radius' ] + 1000.0 # sma\r\n\tassert pytest.approx( sc.coes[ :, 1 ], abs = 1e-6 ) == 0.0 # ecc\r\n\tassert np.all( sc.coes[ :, 2 ] == 0.0 ) # inc\r\n\tassert np.all( sc.coes[ :, 5 ] == 0.0 ) # raan\r\n\r\n\tsc.calc_apoapses_periapses()\r\n\tapse_diffs = sc.apoapses - sc.periapses\r\n\tassert pytest.approx( apse_diffs, abs = 1e-3 ) == 0.0\r\n\r\n\tif plot:\r\n\t\tsc.plot_coes()\r\n\r\nif __name__ == '__main__':\r\n\ttest_Spacecraft_basic_propagation()\r\n","sub_path":"src/python_tools/unit_tests/test_Spacecraft.py","file_name":"test_Spacecraft.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"276741989","text":"# ununsed imports here, to bring them into scope for other files\nimport sys\nimport sqlite3\nimport warnings\n\nfrom itertools import chain\nfrom pathlib import Path\nfrom urllib.parse import unquote\nfrom datetime import datetime, timezone\nfrom typing import List, Iterator, Optional, NamedTuple, Dict, Union, Tuple, Sequence\nfrom dataclasses import dataclass\n\n\nfrom ..log import logger\nfrom ..model import Visit, Metadata\nfrom ..common import PathIsh, PathIshOrConn, func_if_some, expand_path\nfrom ..sqlite import execute_query\n\n\n@dataclass\nclass Schema:\n cols: List[str]\n where: str\n order_by: Optional[str] = None\n\n @property\n def query(self) -> str:\n qr = f\"SELECT {', '.join(self.cols)} {self.where}\"\n if self.order_by is not None:\n qr += f\" ORDER BY {self.order_by}\"\n return qr\n\n\nDetector = str\nPaths = Sequence[Path]\n\n\n@dataclass\nclass Browser:\n schema: Schema # used to create the query to extract visit from database\n detector: Detector # semi-unique name of table, or a query to run on database to detect this type\n has_save: bool = True # if this browser works with the save command\n has_form_history_save: bool = False # if this can backup form history\n\n @classmethod\n def detect(cls, path: PathIshOrConn) -> bool:\n \"\"\"\n Run the detector against the given path/connection to detect if the current Browser matches the schema\n \"\"\"\n # if the user provided something that had spaces - is a query\n if \" \" in cls.detector.strip():\n detector_query = cls.detector\n else:\n detector_query = f\"SELECT * FROM {cls.detector}\"\n logger.debug(f\"{cls.__name__}: Running detector query '{detector_query}'\")\n try:\n list(execute_query(path, detector_query))\n return True\n except sqlite3.OperationalError as sql_err:\n logger.debug(str(sql_err))\n return False\n\n @classmethod\n def extract_visits(cls, path: PathIshOrConn) -> Iterator[Visit]:\n \"\"\"\n Given a path or a sqlite3 connection, extract visits\n \"\"\"\n raise NotImplementedError\n\n @classmethod\n def data_directory(cls) -> Path:\n warnings.warn(\n \"'data_directory' method is deprecated. Please switch to 'data_directories'\"\n )\n dirs = cls.data_directories()\n assert len(dirs) > 0\n if len(dirs) > 1:\n logger.warn(\n \"got multiple alternaitves for data directory, picking the first\"\n )\n return dirs[0]\n\n @classmethod\n def data_directories(cls) -> Paths:\n \"\"\"\n The local data directories for this browser\n \"\"\"\n raise NotImplementedError\n\n @classmethod\n def locate_database(cls, profile: str) -> Path:\n \"\"\"\n Locate this database on the users' computer so it can be backed up\n \"\"\"\n raise NotImplementedError\n\n @classmethod\n def locate_form_history(cls, profile: str) -> Path:\n \"\"\"\n Locate the Form History (e.g. Usernames/Form fields) database so it can be backed up\n \"\"\"\n raise NotImplementedError\n\n\ndef from_datetime_microseconds(ts: int) -> datetime:\n return datetime.fromtimestamp(ts / 1_000_000, tz=timezone.utc)\n\n\nerrmsg = \"\"\"Expected to match a single database, but found:\n{}\n\nYou can use the --profile argument to select one of the profiles/match a particular file\"\"\"\n\n\ndef handle_glob(bases: Sequence[Path], stem: str, recursive: bool = False) -> Path:\n dbs: List[Path]\n method = Path.rglob if recursive else Path.glob\n dbs = list(chain(*[method(base, stem) for base in bases]))\n recur_desc = \"recursive\" if recursive else \"non recursive\"\n logger.debug(f\"Glob {bases} with {stem} ({recur_desc}) matched {dbs}\")\n if len(dbs) > 1:\n human_readable_db_paths: str = \"\\n\".join([str(db) for db in dbs])\n raise RuntimeError(errmsg.format(human_readable_db_paths))\n elif len(dbs) == 1:\n # found the match!\n return dbs[0]\n else:\n # if we werent trying to search recursively, try a recursive search as a fallback\n if not recursive:\n return handle_glob(bases, stem, recursive=True)\n else:\n raise RuntimeError(f\"Could not find database, using '{bases}' and '{stem}'\")\n\n\nPathMapEntry = Union[PathIsh, Sequence[PathIsh]]\n\n\ndef handle_path(\n pathmap: Dict[str, PathMapEntry],\n browser_name: str,\n *,\n key: Optional[str] = None,\n default_behaviour: str = \"linux\",\n) -> Paths:\n \"\"\"\n Handles the repetitive task of having to resolve/expand a path\n which describes the location of the data directory on each\n opreating system\n \"\"\"\n loc: Sequence[PathIsh]\n # if the user didn't provide a key, assume this is a 'sys.platform' map - using\n # darwin/linux to specify the location\n if key is None:\n key = sys.platform\n # use the key provided, or the first item (dicts after python3.7 are ordered)\n # in the pathmap if that doesnt exist\n maybeloc: Optional[PathMapEntry] = pathmap.get(key)\n if maybeloc is None:\n warnings.warn(\n f\"\"\"Not sure where {browser_name} history is installed on {sys.platform}\nDefaulting to {default_behaviour} behaviour...\n\nIf you're using a browser/platform this currently doesn't support, please make an issue\nat https://github.com/seanbreckenridge/browserexport/issues/new with information.\nIn the meantime, you can point this directly at a history database using the --path flag\"\"\"\n )\n maybeloc = pathmap[list(pathmap.keys())[0]]\n assert maybeloc is not None # convince mypy\n if isinstance(maybeloc, (Path, str)):\n loc = [maybeloc]\n else:\n loc = maybeloc\n return tuple(expand_path(p) for p in loc)\n\n\ndef test_handle_path() -> None:\n import pytest\n import sys\n\n oldplatform = sys.platform\n\n sys.platform = \"linux\"\n\n from .firefox import Firefox\n\n expected_linux = (\n Path(\"~/.mozilla/firefox/\").expanduser().absolute(),\n Path(\"~/.var/app/org.mozilla.firefox/.mozilla/firefox/\")\n .expanduser()\n .absolute(),\n Path(\"~/snap/firefox/common/.mozilla/firefox/\").expanduser().absolute(),\n )\n\n assert Firefox.data_directories() == expected_linux\n\n sys.platform = \"darwin\"\n assert Firefox.data_directories() == (\n Path(\"~/Library/Application Support/Firefox/Profiles/\").expanduser().absolute(),\n )\n\n sys.platform = \"something else\"\n # should default to linux\n with pytest.warns(UserWarning, match=r\"history is installed\"):\n assert Firefox.data_directories() == expected_linux\n\n sys.platform = oldplatform\n","sub_path":"browserexport/browsers/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":6679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"179942433","text":"# coding:utf-8\nimport networkx\n\ndef search_rec(graph,node_from,node_to):\n dict_costs=networkx.get_edge_attributes(graph,\"weight\")\n MAX_COST=float(\"Infinity\")\n min_cost=MAX_COST\n list_node_min=[]\n for node_start in graph.predecessors(node_to):\n cost=int(dict_costs[(node_start,node_to)])\n if cost<=min_cost:\n if cost\"+skill_to)\n path_skill=search_rec(graph,skill_from,skill_to)[0]\n if len(path_skill)==0:\n print(\"習得不可\")\n else:\n print(path_skill)\n return path_skill\n","sub_path":"src/lib/optgraph.py","file_name":"optgraph.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"123648487","text":"from craton.tests.functional import DeviceTestBase\n\n\nclass APIV1NetworkDeviceTest(DeviceTestBase):\n\n resource = 'network-devices'\n\n def test_create_with_parent_id(self):\n parent = self.create_network_device(\n name='test1',\n cloud=self.cloud,\n region=self.region,\n device_type='switch',\n ip_address='192.168.1.1',\n )\n child = self.create_network_device(\n name='test2',\n cloud=self.cloud,\n region=self.region,\n device_type='switch',\n ip_address='192.168.1.2',\n parent_id=parent['id'],\n )\n self.assertEqual(parent['id'], child['parent_id'])\n\n def test_update_with_parent_id(self):\n parent = self.create_network_device(\n name='test1',\n cloud=self.cloud,\n region=self.region,\n device_type='switch',\n ip_address='192.168.1.1',\n )\n\n child = self.create_network_device(\n name='test2',\n cloud=self.cloud,\n region=self.region,\n device_type='switch',\n ip_address='192.168.1.2',\n )\n self.assertIsNone(child['parent_id'])\n\n url = '{}/v1/network-devices/{}'.format(self.url, child['id'])\n child_update_resp = self.put(\n url, data={'parent_id': parent['id']}\n )\n self.assertEqual(200, child_update_resp.status_code)\n child_update = child_update_resp.json()\n self.assertEqual(parent['id'], child_update['parent_id'])\n\n def test_update_with_parent_id_equal_id_fails(self):\n network_device = self.create_network_device(\n name='test1',\n cloud=self.cloud,\n region=self.region,\n device_type='switch',\n ip_address='192.168.1.1',\n )\n\n url = '{}/v1/network-devices/{}'.format(self.url, network_device['id'])\n network_device_update_resp = self.put(\n url, data={'parent_id': network_device['id']}\n )\n self.assertEqual(400, network_device_update_resp.status_code)\n\n def test_update_with_parent_id_equal_descendant_id_fails(self):\n parent = self.create_network_device(\n name='test1',\n cloud=self.cloud,\n region=self.region,\n device_type='switch',\n ip_address='192.168.1.1',\n )\n self.assertIsNone(parent['parent_id'])\n\n child = self.create_network_device(\n name='test2',\n cloud=self.cloud,\n region=self.region,\n device_type='switch',\n ip_address='192.168.1.2',\n parent_id=parent['id'],\n )\n self.assertEqual(parent['id'], child['parent_id'])\n\n grandchild = self.create_network_device(\n name='test3',\n cloud=self.cloud,\n region=self.region,\n device_type='switch',\n ip_address='192.168.1.3',\n parent_id=child['id'],\n )\n self.assertEqual(child['id'], grandchild['parent_id'])\n\n url = '{}/v1/network-devices/{}'.format(self.url, parent['id'])\n parent_update_resp = self.put(\n url, data={'parent_id': grandchild['id']}\n )\n self.assertEqual(400, parent_update_resp.status_code)\n","sub_path":"craton/tests/functional/test_network_device_calls.py","file_name":"test_network_device_calls.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"173023816","text":"# *********************************************************************************************************************\n# PURPOSE: Uses multiprocessing to make concurrent WMS requests in separate processes for load testing a WMS service.\n# Supports the use of WMS as a tile map service (such as GeoWebCache services)\n#\n# USAGE: Edit the parameters before main() to set:\n# 1. The proxy server (if required)\n# 2. The number of requests and concurrent processes to run\n# 3. The WMS service parameters\n# 4. The min/max map width and bounding box(es). These limit the randomised map extents to the area(s) of interest\n#\n# TO DO:\n# 1. Add support for WMTS services\n# 2. Improve logging to record request failures (failures currently printed to screen only)\n#\n# NOTE: The log file will only be output after all test cases have been run, this is to avoid writing to a shared\n# log file from multiple processes (possible in Python, but complicated...)\n#\n# LICENSE: Creative Commons Attribution 4.0 (CC BY 4.0)\n# *********************************************************************************************************************\n\nimport csv\nimport datetime\nimport math\nimport multiprocessing\nimport os\nimport random\nimport ssl\nimport time\nimport traceback\nimport urllib.request\n\n# WMS or WFS?\nrequest_type = \"WFS\"\n\n# # Set proxy for web requests (if required)\n# proxy = urllib.request.ProxyHandler({'http': ''})\n# opener = urllib.request.build_opener(proxy)\n# urllib.request.install_opener(opener)\n\n# Total number of requests\nrequests = 1000\n\n# Number of concurrent processes to run\nprocesses = 20\n\n# Max pause between requests (in whole milliseconds)\nmax_pause = 500\n\n# WMS Map tiles? (i.e. 256 x 256 pixel images in a Google/Bing Maps grid?)\nmap_tiles = True\n\n# Min/max zoom levels (only required if map_tiles = True)\nmin_tile_level = 11\nmax_tile_level = 16\n\n# Map width limits in wms_srid units - allows random zoom scales to be tested\n# (required if map_tiles = False or request_type = \"WFS\")\nmin_map_width = 3000.0\nmax_map_width = 30000.0\n\n# Map image width and height in pixels (required if map_tiles = False or request_type = \"WFS\")\nmap_image_width = 1024\nmap_image_height = 768\n\n# AWS Lambda WFS parameters\nbase_url = \"https://859uppjni0.execute-api.ap-southeast-2.amazonaws.com/dev\"\n# base_url = \"http://127.0.0.1:5000\"\n\n# Dictionary of max and min coordinates in web mercator (metres). Used to randomly set map extents\nmax_bounding_boxes = {1: [16796997.0, -4020748.0, 16835959.0, -3995282.0], # Sydney\n 2: [16124628.0, -4559667.0, 16163590.0, -4534318.0], # Melbourne\n 3: [17021863.0, -3192356.0, 17048580.0, -3174789.0], # Brisbane\n 4: [15417749.0, -4162522.0, 15447805.0, -4143515.0], # Adelaide\n 5: [12884117.0, -3773816.0, 12921966.0, -3748880.0], # Perth\n 6: [16391795.0, -5296763.0, 16410719.0, -5284614.0], # Hobart\n 7: [16587717.0, -4225203.0, 16609981.0, -4187007.0]} # Canberra\n\ntable_name = \"vw_locality_bdys_display_full_res_display\"\n\n\ndef main():\n\n # get list of map request urls\n request_list = create_requests(table_name)\n\n # Create pool of processes to get map images/tiles\n pool = multiprocessing.Pool(processes)\n\n start_time = datetime.datetime.now()\n print(\"\\nStart {1} Stress Test : {0}\\n\".format(start_time, request_type))\n\n # Fire off requests\n results = pool.imap_unordered(get_url, request_list)\n results_list = list(results)\n\n pool.close()\n pool.join()\n\n elapsed_time = datetime.datetime.now() - start_time\n\n # Finish by logging parameters used and the results\n log_results(results_list, elapsed_time)\n\n\ndef create_requests(table_name):\n request_list = list()\n\n # get list of random map extents\n bounds_list = create_random_bounds_list()\n\n for bounds in bounds_list:\n # get random zoom level\n zoom_level = str(random.randint(min_tile_level, max_tile_level))\n\n # add zoom level\n bounds.append(zoom_level)\n # add table name\n bounds.append(table_name)\n\n # Construct URL\n bounds_str = \"/\".join(bounds)\n\n url = \"/\".join([base_url, bounds_str]) + \"/\"\n # print(url)\n\n request_list.append(url)\n\n return request_list\n\n\ndef create_random_bounds_list():\n # Set default map tile set parameters\n if map_tiles and request_type == \"WMS\":\n global map_image_width\n global map_image_height\n map_image_width = 256\n map_image_height = 256\n map_ratio = 1.0\n else:\n map_ratio = float(map_image_height) / float(map_image_width)\n\n # Count of bounding boxes to map within\n max_bounding_box_count = len(max_bounding_boxes)\n\n bounds_list = list()\n\n # Set random map extents and fire off WMS requests in separate processes\n for i in range(0, requests):\n # Get random max/min bounding box\n max_bbox_num = random.randint(1, max_bounding_box_count)\n max_bbox = max_bounding_boxes.get(max_bbox_num)\n\n # Get random map width and height in wms_srid units\n if map_tiles and request_type == \"WMS\":\n tile_level = random.randint(min_tile_level, max_tile_level)\n map_width = 256.0 * tile_pixel_sizes[tile_level]\n map_height = map_width\n else:\n map_width = random.uniform(float(min_map_width), float(max_map_width))\n map_height = map_width * map_ratio\n\n # Calculate random bottom/left map coordinates\n left = random.uniform(float(max_bbox[0]), float(max_bbox[2]) - map_width)\n bottom = random.uniform(float(max_bbox[1]), float(max_bbox[3]) - map_height)\n\n # Adjust bottom/left map coordinates to the Google/Bing Maps tile grid if creating map tiles\n if map_tiles and request_type == \"WMS\":\n left = math.floor(left / map_width) * map_width\n bottom = math.floor(bottom / map_height) * map_height\n\n # Get top/right map coordinates\n right = left + map_width\n top = bottom + map_height\n\n # convert to lat/long if WFS\n if request_type == \"WFS\":\n bottom, left = web_mercator_to_wgs84(bottom, left)\n top, right = web_mercator_to_wgs84(top, right)\n\n bounds_list.append([str(left), str(bottom), str(right), str(top)])\n\n return bounds_list\n\n\n# Gets a map image and returns the time taken (seconds), image size (bytes) and the URL for logging\ndef get_url(url):\n\n context = ssl._create_unverified_context()\n\n # wait for a random time to simulate real-world use\n random_pause = float(random.randint(0, max_pause)) / 1000.0\n time.sleep(random_pause) # in seconds\n\n file_size = 0\n start_time = datetime.datetime.now()\n\n try:\n # Request map image and get its size as evidence of success or failure for logging\n request = urllib.request.Request(url)\n result = urllib.request.urlopen(request, context=context).read()\n file_size = len(result)\n # flag an error in the 'valid' response\n if \"epic fail\" in str(result).lower():\n file_size = -99999\n except urllib.request.URLError:\n # Print failures to screen (these aren't logged)\n print(''.join([\"MAP REQUEST FAILED : \", url, '\\n', traceback.format_exc()]))\n\n elapsed_time = datetime.datetime.now() - start_time\n elapsed_seconds = float(elapsed_time.microseconds) / 1000000.0\n\n return [elapsed_seconds, file_size, url]\n\n\n# Default Google/Bing map tile scales per level (metres per pixel)\ntile_pixel_sizes = [156543.033906250000000000,\n 78271.516953125000000000,\n 39135.758476562500000000,\n 19567.879238281200000000,\n 9783.939619140620000000,\n 4891.969809570310000000,\n 2445.984904785160000000,\n 1222.992452392580000000,\n 611.496226196289000000,\n 305.748113098145000000,\n 152.874056549072000000,\n 76.437028274536100000,\n 38.218514137268100000,\n 19.109257068634000000,\n 9.554628534317020000,\n 4.777314267158510000,\n 2.388657133579250000,\n 1.194328566789630000,\n 0.597164283394814000,\n 0.298582141697407000,\n 0.149291070848703000,\n 0.074645535424351700,\n 0.037322767712175800,\n 0.018661383856087900,\n 0.009330691928043960,\n 0.004665345964021980,\n 0.002332672982010990,\n 0.001166336491005500,\n 0.000583168245502748,\n 0.000291584122751374,\n 0.000145792061375687]\n\n\ndef web_mercator_to_wgs84(mercator_y, mercator_x):\n\n if abs(mercator_x) < 180 and abs(mercator_y) < 90:\n return\n if abs(mercator_x) > 20037508.3427892 or abs(mercator_y) > 20037508.3427892:\n return\n\n x = mercator_x\n y = mercator_y\n num3 = x / 6378137.0\n num4 = num3 * 57.295779513082323\n num5 = math.floor((num4 + 180.0) / 360.0)\n num6 = num4 - (num5 * 360.0)\n num7 = 1.5707963267948966 - (2.0 * math.atan(math.exp((-1.0 * y) / 6378137.0)))\n longitude = num6\n latitude = num7 * 57.295779513082323\n\n return [latitude, longitude]\n\n\ndef log_results(results_list, elapsed_time):\n log_entries = list()\n\n # Title, parameters used and results summary\n log_entries.append([\"{0} Stress Test Results\".format(request_type,)])\n log_entries.append([])\n # log_entries.append([\"Elapsed time\", \"'\" + str(elapsed_time)]) # not a relevant measure as processes pause randomly\n # log_entries.append([])\n log_entries.append([\"Concurrent processes\", str(processes)])\n if request_type == \"WMS\":\n log_entries.append([\"Map image size\", str(map_image_width) + \" x \" + str(map_image_height), \"pixels\"])\n log_entries.append([])\n log_entries.append([\"Max random delay (ms)\", max_pause])\n log_entries.append([])\n log_entries.append([\"Requests\", requests])\n log_entries.append([])\n\n success_count = 0\n fail_count = 0\n bad_count = 0\n total_seconds = 0.0\n total_size = 0.0\n max_seconds = 0.0\n max_size = 0.0\n\n # Calculate some stats\n for item in results_list:\n seconds = item[0]\n file_size = item[1]\n\n if file_size > 0:\n success_count += 1\n total_seconds += seconds\n total_size += file_size\n\n if seconds > max_seconds:\n max_seconds = seconds\n\n if file_size > max_size:\n max_size = file_size\n\n elif file_size == 0:\n fail_count += 1\n else:\n bad_count += 1\n\n if success_count > 0:\n avg_seconds = total_seconds / float(success_count)\n avg_size = (float(total_size) / float(success_count)) / 1024.0\n else:\n avg_seconds = 0\n avg_size = 0\n\n log_entries.append([\"Successful requests\", success_count])\n log_entries.append([\"Average time\", avg_seconds, \"seconds\"])\n log_entries.append([\"Average size\", avg_size, \"Kb\"])\n log_entries.append([\"Maximum time\", max_seconds, \"seconds\"])\n log_entries.append([\"Maximum size\", max_size / 1024.0, \"Kb\"])\n log_entries.append([\"Request/response failures\", fail_count])\n log_entries.append([\"Invalid responses\", bad_count])\n log_entries.append([])\n log_entries.append([\"Time_seconds\", \"Image_bytes\", \"URL\"])\n\n # Output results to log file\n log_file = open(time_stamped_file_name(os.path.abspath(__file__).replace(\".py\", \"\")) + \".csv\", 'w')\n log_writer = csv.writer(log_file, delimiter=',', quoting=csv.QUOTE_MINIMAL)\n log_writer.writerows(log_entries)\n log_writer.writerows(results_list)\n log_file.close()\n\n print(\"Finished:\")\n print(\"\\t- elapsed time : {}\".format(elapsed_time))\n print(\"\\t- success : {}\".format(success_count))\n print(\"\\t- avg response time : {}\".format(avg_seconds))\n print(\"\\t- avg size : {}\".format(avg_size))\n print(\"\\t- max response time : {}\".format(max_seconds))\n print(\"\\t- max size : {}\".format(max_size / 1024.0))\n print(\"\\t- failures:\")\n print(\"\\t\\t- request/response failures : {}\".format(fail_count))\n print(\"\\t\\t- invalid response : {}\".format(bad_count))\n\n\n# Adds a time stamp to a file name\ndef time_stamped_file_name(file_name, fmt='{file_name}_%Y_%m_%d_%H_%M_%S'):\n return datetime.datetime.now().strftime(fmt).format(file_name=file_name)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/display_boundaries/sample_map_server/aws-lambda-test-harness.py","file_name":"aws-lambda-test-harness.py","file_ext":"py","file_size_in_byte":12726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"137970628","text":"\"\"\"\nA happy string is a string that:\n\nconsists only of letters of the set ['a', 'b', 'c'].\ns[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).\nFor example, strings \"abc\", \"ac\", \"b\" and \"abcbabcbcb\" are all happy strings and strings \"aa\", \"baa\" and \"ababbc\" are not happy strings.\n\nGiven two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.\n\nReturn the kth string of this list or return an empty string if there are less than k happy strings of length n.\n\nExample 1:\n Input: n = 1, k = 3\n Output: \"c\"\n Explanation: The list [\"a\", \"b\", \"c\"] contains all happy strings of length 1. The third string is \"c\".\n\nExample 2:\n Input: n = 1, k = 4\n Output: \"\"\n Explanation: There are only 3 happy strings of length 1.\n\nExample 3:\n Input: n = 3, k = 9\n Output: \"cab\"\n Explanation: There are 12 different happy string of length 3 [\"aba\", \"abc\", \"aca\", \"acb\", \"bab\", \"bac\", \"bca\", \"bcb\", \"cab\", \"cac\", \"cba\", \"cbc\"]. You will find the 9th string = \"cab\"\n\nExample 4:\n Input: n = 2, k = 7\n Output: \"\"\n\nExample 5:\n Input: n = 10, k = 100\n Output: \"abacbabacb\"\n\nConstraints:\n 1 <= n <= 10\n 1 <= k <= 100\n\"\"\"\n\ndef getHappyString(n, k):\n strings = [\"a\", \"b\", \"c\"]\n while n > 1:\n newStrings = []\n for string in strings:\n if string[-1] == \"a\":\n newStrings.append(string + \"b\")\n newStrings.append(string + \"c\")\n elif string[-1] == \"b\":\n newStrings.append(string + \"a\")\n newStrings.append(string + \"c\")\n else:\n newStrings.append(string + \"a\")\n newStrings.append(string + \"b\")\n strings = newStrings\n n -= 1\n if k <= len(strings):\n return strings[k-1]\n else:\n return \"\"\n\nn1 = 1\nk1 = 3\n\nn2 = 1\nk2 = 4\n\nn3 = 3\nk3 = 9\n\nn4 = 2\nk4 = 7\n\nn5 = 10\nk5 = 100\n\nprint(getHappyString(n5, k5))\n","sub_path":"LeetCode-Python/The k-th Lexicographical String of All Happy Strings of Length n.py","file_name":"The k-th Lexicographical String of All Happy Strings of Length n.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"319660106","text":"import os\nimport pickle\nimport numpy as np\nimport pandas as pd\n\nfrom pyspark.sql import SparkSession\n\nspark = SparkSession\\\n\t\t.builder\\\n .appName(\"Distance Calculation\")\\\n .getOrCreate()\n\nsc = spark.sparkContext\n\ndata_dir = '/home/rz729/bigdata/data'\n\nwith (open(os.path.join(data_dir, 'center', 'centers30.pkl'), \"rb\")) as openfile:\n centersDF = pickle.load(openfile)\n\nwith (open(os.path.join(data_dir, 'average', 'average.pkl'), \"rb\")) as openfile:\n averagesDF = pickle.load(openfile)\n\ncenters = centersDF.values.tolist()\naverages = spark.createDataFrame(averagesDF).rdd\n\ndef distancebwavg_center(average):\n\tdistance_list = []\n\tfor center in centers:\n\t\tdistance_list.append(np.linalg.norm(np.array(average)-np.array(center)))\n\treturn distance_list\n\ndistance = averages\\\n\t\t\t .map(lambda _: ((_[0], _[1], _[2]),np.array(_[3:]).astype(float)))\\\n\t\t\t .mapValues(lambda v : distancebwavg_center(v))\\\n\t\t\t .collect()\n\npd.DataFrame(distance).to_pickle(os.path.join(data_dir, 'distance', 'distance.pkl'))\n","sub_path":"src/preprocess/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"428437097","text":"import datetime\n\nimport dateutil.parser\n\nfrom automaton import Automaton, Braindead, logger\nfrom market import Market\nfrom positionmanager import PositionManager\n\n\nclass Braindead2(Automaton):\n\n def __init__(self, pos: PositionManager, market: Market):\n super().__init__(pos, market)\n self.name = 'Braindead2'\n self.cash = 100000\n self.trailing = 0\n self.stop = 0\n self.trailingp = 0.05\n self.last_seen = datetime.datetime.min\n self.prev_macd = 0\n self.macd = 0\n self.last_avg_price=None\n self.pos_price=None\n\n def serialize(self):\n s = super().serialize()\n s['name'] = self.name\n s['config'] = {\n 'trailing': self.trailing,\n 'stop': self.stop,\n 'last_seen': self.last_seen,\n 'cash': self.cash,\n 'macd': self.macd,\n 'prev_macd': self.prev_macd,\n 'last_avg_price': self.last_avg_price,\n 'pos_price': self.pos_price\n }\n return s\n\n @staticmethod\n def from_dict(d: dict, market: Market):\n pos = PositionManager.from_dict(d, market)\n b = Braindead(pos, market)\n b.name = d['name']\n b.trailing = d['config']['trailing']\n b.stop = d['config']['stop']\n b.last_seen = dateutil.parser.parse(d['config']['last_seen'])\n b.cash = d['config']['cash']\n b.macd = d['config']['macd']\n b.prev_macd = d['config']['prev_macd']\n b.last_avg_price = d['config']['last_avg_price']\n b.pos_price = d['config']['pos_price']\n #b.log(\"Resumed Braindead instance\", loglevel=1)\n return b\n\n def status(self):\n if self.pos.position == 0:\n return 'I am flat. Current MACD is {:.0f}, previous MACD is {:.0f}, waiting for current MACD to change sign'.format(self.macd, self.prev_macd)\n else:\n return 'I am {}.\\nMy position is {:.2f}, my position price is {:.0f}.\\nStop conditions: {:.0f} {} {:.0f} and {:.0f} {} {:.0f}'.format(\n 'long' if self.pos.position > 0 else 'short',\n self.pos.position,\n self.pos_price,\n self.prev_macd, '>' if self.pos.position > 0 else '<',\n self.macd,\n self.last_avg_price if self.last_avg_price is not None else 0,\n '<' if self.pos.position > 0 else '>',\n self.stop)\n\n\n def think(self, cur_time):\n logger.debug('Entering Braindead.think() method')\n logger.debug('Status before the loop: {}'.format(self.status()))\n\n macd = self.market.get_MACD(from_date=cur_time - datetime.timedelta(days=120), to_date=cur_time)\n\n if macd.iloc[-2]['MACDdiff'] is None or macd.iloc[-1]['MACDdiff'] is None:\n # case where we're too early in the backtesting, just skip to next round\n return\n\n self.macd = macd.iloc[-1]['MACDdiff']\n self.prev_macd = macd.iloc[-2]['MACDdiff']\n\n if self.pos.position == 0:\n\n if self.prev_macd < 0 <= self.macd:\n # go long\n self.pos_price = self.market.get_latestprice(cur_time)\n ex = self.pos.newtrade(quantity=round(self.cash / self.pos_price, 3), way='Buy', timestamp=cur_time)\n self.pos_price = ex['price']\n self.trailing = self.pos_price * self.trailingp\n self.stop = self.pos_price - self.trailing\n self.cash = 0\n self.last_seen = macd.iloc[-1].name\n self.log('Go long now !! Im buying at {:.0f}.'.format(self.pos_price), loglevel=0)\n self.log(self.status())\n\n elif self.prev_macd > 0 >= self.macd:\n # go short\n self.pos_price = self.market.get_latestprice(cur_time)\n ex = self.pos.newtrade(quantity=round(self.cash / self.pos_price, 3), way='Sell', timestamp=cur_time)\n self.pos_price = ex['price']\n self.trailing = self.pos_price * self.trailingp\n self.stop = self.pos_price + self.trailing\n self.cash *= 2\n self.last_seen = macd.iloc[-1].name\n self.log('Go short now !! Im selling at {:.0f}.'.format(self.pos_price), loglevel=0)\n self.log(self.status())\n else:\n #self.last_avg_price = self.market.get_wavgprice(to_date=cur_time)\n\n self.last_avg_price = self.market.get_OHLC(\n summarize_by='5M',\n from_date=cur_time - datetime.timedelta(minutes=15),\n to_date=cur_time).iloc[-1]['Wavg_price']\n\n if self.last_avg_price is None:\n logger.warning('no execs in the last 5 minutes to {}, skipping'.format(cur_time))\n return\n\n if self.pos.position > 0 and (self.last_avg_price < self.stop and self.prev_macd > self.macd):\n # stop reached, selling\n p = abs(self.pos.position)\n ex = self.pos.newtrade(quantity=p, way='Sell', timestamp=cur_time)\n self.cash += p * ex['price']\n self.log('Sell the position now !! Im selling at {:.0f}'.format(ex['price']))\n self.log(self.status())\n elif self.pos.position < 0 and (self.last_avg_price > self.stop and self.prev_macd < self.macd):\n # stop reached, buying back\n p = abs(self.pos.position)\n ex = self.pos.newtrade(quantity=p, way='Buy', timestamp=cur_time)\n self.cash -= p * ex['price']\n self.log('Buy back the position now !! Im buying at {:.0f}'.format(ex['price']))\n self.log(self.status())\n\n if self.pos.position > 0:\n self.stop = max(self.stop, self.last_avg_price - self.trailing)\n elif self.pos.position < 0:\n self.stop = min(self.stop, self.last_avg_price + self.trailing)\n\n logger.debug('Status after the loop: {}'.format(self.status()))","sub_path":"braindead2.py","file_name":"braindead2.py","file_ext":"py","file_size_in_byte":6063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306504","text":"import shapely\nimport matplotlib.pyplot as plt\nfrom shapely.geometry.point import Point\nfrom shapely.geometry import box\nimport random\nimport math\n\n\nplt.figure()\nx = []\ny = []\nd = input(\"Point Number: \")\nd = int(d)\nfor i in range(0,d):\n\tx.append(random.uniform(1,1000));\n\ty.append(random.uniform(1,1000));\n\tplt.plot(x[i],y[i],marker ='o')\n\no = input(\"Box Number1: \")\no = int(o)\np = input(\"Box Number2: \")\np = int(p)\nmax=0\nmaxbox=box(0,0,1,1);\nfor m in range(0,1):\n\ta=(o)\n\tb=(o)\n\tw=(p)\n\th=(p)\n\tf=box(a,b,a+w,b+h)\n\t\nx,y=f.exterior.coords.xy;\nplt.plot(x,y)\nplt.show()","sub_path":"p42.py","file_name":"p42.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"604659858","text":"import pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nimport tensorflow as tf\nimport os, time, sys, sklearn\nfrom sklearn.externals import joblib\nfrom rnn_functions import *\n\n\nos.environ[\"TF_MIN_GPU_MULTIPROCESSOR_COUNT\"] = \"4\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = tf.Session(config=config)\n\nSKIPROWS = np.arange(1,300000,1)\nSKIPROWS = None\nNROWS = 300000\n\n#Load\ndf = pd.read_csv(\"./DATA/x_82_ETF_FOREX_5MIN_RETONLY.csv\", header=0, skiprows = SKIPROWS, nrows = NROWS)\n# df = pd.read_csv(\"./DATA/x_82_ETF_FOREX_5MIN_RETONLY.csv\")\ndf[\"Date\"] = pd.to_datetime(df[\"Date\"])\ndf = df.set_index(\"Date\")\nprint(\"Load: Done!\")\n\n#Import scaler\nrun_dir = \"RUNS/EURUSD-60-2-2-10-0.3-0.0002-256-200-1538974780\"\nrun_dir = \"RUNS/EURUSD-60-5-2-5-0.3-0.0002-256-200-1538993858\"\nrun_dir = \"RUNS/USDCHF-60-5-2-5-0.3-0.0002-256-200-1538996078\"\n\nscaler = joblib.load(f'{run_dir}/rnn_scaler.pkl')\nx_columns = joblib.load(f'{run_dir}/x_columns.pkl')\nPARAMS_INFO = joblib.load(f'{run_dir}/PARAMS_INFO.pkl')\nprint(\"Import Scaler: Done!\")\n\ndf[x_columns] = scaler.transform(df[x_columns].values)\ntdf = df[x_columns]\nSEQ_LEN = PARAMS_INFO[\"SEQ_LEN\"]\n\nsequential_data = []\nprev_days = deque(maxlen = SEQ_LEN)\n\nsequential_list_dict = []\nfor i, j in zip(tdf.values, tdf.index):\n prev_days.append(i)\n if len(prev_days) == SEQ_LEN:\n sequential_list_dict.append(dict(t = j, x = np.array(prev_days)))\n\nprint(\"Transform: Done!\")\n\n\nmodel_input = \"./tohost_model/RNN_Final-031-0.525.model\"\nmodel_input = \"./tohost_model/RNN_Final-071-0.6957-0.5541.model\"\nmodel_input = \"./tohost_model/RNN_Final-086-0.6787-0.5830.model\"\n\n\nrnn_model = tf.keras.models.load_model(filepath = model_input, custom_objects=None, compile=False)\n\nprint(\"Model Loaded!\")\n\n\nx_list_3d = []\nt_list = []\n\nfor seq_dict in sequential_list_dict:\n t = seq_dict[\"t\"]\n x = seq_dict[\"x\"]\n t_list.append(t)\n x_list_3d.append(x)\n\nx_list_3d = np.array(x_list_3d)\n\nprint(\"Dimension: \", x_list_3d.shape)\n\n\ny = rnn_model.predict(np.array(x_list_3d))\n\nprint(\"Predict: Done!\")\npred_df = pd.DataFrame(dict(Date = t_list, signal_raw = y.reshape((-1))))\nprint(pred_df.head(5))\nprint(pred_df.tail(5))\n\ninstrument_name = PARAMS_INFO[\"TARGET_TO_PREDICT\"]\npred_df.to_csv(\"rnn_signal_{}.csv\".format(instrument_name), index = False)\nprint(\"Export: Done!\")\n","sub_path":"export_signal.py","file_name":"export_signal.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"117726462","text":"# 카펫\n\ndef solution(brown, red):\n answer = []\n area = brown + red\n\n for width in range(3, area):\n height = int(area / width)\n\n if area % width == 0:\n if height > width:\n continue\n elif (width - 2) * (height - 2) == red:\n answer.append(width)\n answer.append(height)\n break\n\n return answer\n","sub_path":"study-1/brute-force/LeeYuRi/Solution04.py","file_name":"Solution04.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"222541539","text":"from database import engine, Predictions as sql_Predictions\nfrom sqlalchemy.orm import sessionmaker\nimport requests\nimport random\nfrom time import sleep\nimport csv\nfrom models import Stop, Prediction\nfrom ast import literal_eval\nfrom time import sleep\n# from redis import Redis\n# from rq import Queue\nfrom submit_prediction_data import process_prediction\nimport logging\nimport random\nimport json\nfrom datetime import datetime\n\n# from huey import RedisHuey\n# huey = RedisHuey('predictor', host='redis')\n\nclass Predictor:\n def __init__(self):\n self.token_list = [\n '9A9392AEE88125369B928F281DBD341B',\n '59D69D98A213F47907DCC4666C429F97',\n '4D8D94A3FF690D5DF8A99632D14DF06C',\n '1E2B2B65A3BB9B09E6581DB918E59552',\n '7C8EB1A0359B4FCB17645149332000EA',\n 'E73043FEBE5FE52ECE7E35E4AD29C1F0',\n 'C1C124A2128F34A92DE7BA44E1723ADC',\n '1FBF820DDA7B36BC245B4662C8652142',\n '6EDE923273A789628CC571F8381228C1',\n 'FEA38127BA898B57C50E44BA8CC4ED5B',\n 'BB23E1BB9E6A1FFA9FC90DBF1667CA0E',\n 'CEF6C4904CAB78D632C2ED96AD835A4D',\n '846CEAE09EF0ED844DA114929C3B06F0',\n 'DECCCBDEAABEC6E7F5462628664D43BC',\n 'A11EB2F3B50E1BAC9781B64E3AB703DF',\n '234E960C8F3367C64DF67A8CCB3538A7',\n '337EAEE9402F615021C2F41CE6808EA1',\n 'FD87E46473298FCB4245BA8F0A1D5136',\n '4F15092F9CB725502FB1506DD630B805',\n '0031A200345291CBACC08DDAEC4D6A00'\n\n ]\n self.stop_index = 0\n self.token_index = 0\n self.api_rate = 100\n self.url = \"https://api.actransit.org/transit/stops/{}/predictions/?token=\" + self.token_list[self.token_index]\n\n\n # @huey.task()\n def process_prediction(self, prediction_data):\n\n session = Session()\n\n predictions = []\n if prediction_data == None:\n pass\n else:\n if type(prediction_data == list):\n try:\n for prediction in prediction_data:\n # # print(\"type of prediction list...\", type(prediction))\n predictions.append(Prediction(prediction))\n except:\n pass\n\n \n\n for prediction in predictions:\n predicted_departure_dt = datetime.strptime(prediction.predicted_departure, \"%Y-%m-%dT%H:%M:%S\")\n prediction_datetime_dt = datetime.strptime(prediction.prediction_datetime, \"%Y-%m-%dT%H:%M:%S\")\n delta = predicted_departure_dt - prediction_datetime_dt\n if (delta.seconds > 600):\n # logging.warning(\"=====BAD TIMING DATA=====\")\n continue\n\n\n\n\n \n # logging.warning(\"===Made it to has predictions====\")\n # logging.warning(\"===I has this many predictions====\")\n # logging.warning(len(predictions))\n sql_predictions = []\n\n\n for prediction in predictions:\n sql_predictions.append(\n sql_Predictions(\n stop_id=prediction.stop_id,\n trip_id=prediction.trip_id,\n vehicle_id=prediction.vehicle_id,\n route_name=prediction.route_name,\n predicted_delay=prediction.predicted_delay,\n predicted_departure=prediction.predicted_departure,\n prediction_datetime=prediction.prediction_datetime\n\n )\n )\n \n session.add_all(sql_predictions)\n session.commit()\n \n def get_prediction_data(self, stop_id):\n r = requests.get(self.url.format(stop_id))\n prediction_list = []\n predictions = r.content\n\n\n if r.status_code == '404' or r.content == b'':\n return None\n else:\n\n predictions = predictions.decode(\"utf-8\")\n predictions = json.loads(predictions)\n for prediction in predictions:\n if type(prediction) != dict:\n continue\n else:\n logging.warning(\"===PREDICTION AS LIST====\")\n for prediction in predictions:\n logging.warning(prediction)\n prediction_list.append(list(prediction.values()))\n\n return prediction_list\n\n\n\n def read_stops_from_csv(self):\n stops = []\n stops_file = open(\"stops.csv\", \"r\")\n stops_table = csv.reader(stops_file, delimiter=',')\n for stops_row in stops_table:\n stop = Stop(stops_row)\n if '72' not in stop.route.split(\" \"):\n continue\n stops.append(stop)\n return stops \n\n def cycle_token_and_stop_index(self):\n token = None\n if (self.stop_index % 250 == 0):\n if self.token_index > 19:\n self.token_index = 0\n\n token = self.token_list[self.token_index]\n self.token_index += 1\n \n if (self.stop_index == 5291):\n self.stop_index = 0\n\n return token\n\n\nif __name__ == '__main__':\n\n \n\n\n logging.warning(\"sleeeeping\")\n sleep(1)\n predictor = Predictor()\n prediction_data = []\n Session = sessionmaker()\n Session.configure(bind=engine)\n\n\n while (True):\n try:\n # logging.warning(\"Made it to try block of loops WUMPPPPX\")\n predictions = []\n\n stops = predictor.read_stops_from_csv()\n\n\n\n stop_list = stops\n stop = random.choice(stop_list)\n\n \n # prediction_data = predictor.get_prediction_data(stop_id=stop.stop_id)\n prediction_data.extend(predictor.get_prediction_data(stop_id=stop.stop_id))\n print(\"pred count is..... \", len(prediction_data))\n\n if len(prediction_data) > 25:\n print(\"processing predictions\")\n predictor.process_prediction(prediction_data[:100])\n prediction_data = []\n\n\n predictor.stop_index += 1\n \n token = predictor.cycle_token_and_stop_index()\n \n except Exception as e:\n # sleep(.1)\n logging.warning(\"I threw an exception in the loop!\")\n logging.warning(str(e))\n\n","sub_path":"compose/predictions/store_predictions.py","file_name":"store_predictions.py","file_ext":"py","file_size_in_byte":6190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"274450536","text":"import aerosandbox as asb\nimport aerosandbox.numpy as np\nimport pytest\nfrom scipy import integrate\n\nu_e_0 = 8\nv_e_0 = 0\nw_e_0 = -6\nspeed_0 = (u_e_0 ** 2 + w_e_0 ** 2) ** 0.5\ngamma_0 = np.arctan2(-w_e_0, u_e_0)\ntrack_0 = 0\n\ntime = np.linspace(0, 2 * np.pi, 501)\n\n\ndef get_trajectory(\n parameterization: type = asb.DynamicsPointMass3DCartesian,\n plot=False\n):\n if parameterization is asb.DynamicsPointMass3DCartesian:\n dyn = parameterization(\n mass_props=asb.MassProperties(mass=1),\n x_e=0,\n y_e=0,\n z_e=0,\n u_e=u_e_0,\n v_e=v_e_0,\n w_e=w_e_0,\n )\n elif parameterization is asb.DynamicsPointMass3DSpeedGammaTrack:\n dyn = parameterization(\n mass_props=asb.MassProperties(mass=1),\n x_e=0,\n y_e=0,\n z_e=0,\n speed=speed_0,\n gamma=gamma_0,\n track=track_0,\n )\n else:\n raise ValueError(\"Bad value of `parameterization`!\")\n\n def derivatives(t, y):\n this_dyn = dyn.get_new_instance_with_state(y)\n this_dyn.add_force(\n Fy=8,\n axes=\"wind\"\n )\n\n return this_dyn.unpack_state(this_dyn.state_derivatives())\n\n res = integrate.solve_ivp(\n fun=derivatives,\n t_span=(time[0], time[-1]),\n t_eval=time,\n y0=dyn.unpack_state(),\n method=\"LSODA\",\n rtol=1e-9,\n atol=1e-9,\n )\n\n dyn = dyn.get_new_instance_with_state(res.y)\n\n if plot:\n import matplotlib.pyplot as plt;\n import aerosandbox.tools.pretty_plots as p\n\n fig, ax = plt.subplots()\n p.plot_color_by_value(dyn.x_e, dyn.altitude, c=dyn.speed, colorbar=True)\n # p.equal()\n p.show_plot(\"Trajectory\", \"$x_e$\", \"$z_e$\")\n\n return dyn\n\n\ndef test_final_position_Cartesian():\n dyn = get_trajectory(\n parameterization=asb.DynamicsPointMass3DCartesian,\n )\n assert dyn[-1].x_e == pytest.approx(0, abs=1e-6)\n assert dyn[-1].y_e == pytest.approx(0, abs=1e-6)\n assert dyn[-1].z_e == pytest.approx(2 * np.pi * -6, abs=1e-6)\n assert dyn[-1].u_e == pytest.approx(8, abs=1e-6)\n assert dyn[-1].v_e == pytest.approx(0, abs=1e-6)\n assert dyn[-1].w_e == pytest.approx(-6, abs=1e-6)\n\n\ndef test_final_position_SpeedGammaTrack():\n dyn = get_trajectory(\n parameterization=asb.DynamicsPointMass3DSpeedGammaTrack,\n )\n assert dyn[-1].x_e == pytest.approx(0, abs=1e-6)\n assert dyn[-1].y_e == pytest.approx(0, abs=1e-6)\n assert dyn[-1].z_e == pytest.approx(2 * np.pi * -6, abs=1e-6)\n assert dyn[-1].u_e == pytest.approx(8, abs=1e-6)\n assert dyn[-1].v_e == pytest.approx(0, abs=1e-6)\n assert dyn[-1].w_e == pytest.approx(-6, abs=1e-6)\n\n\ndef test_cross_compare():\n dyn1 = get_trajectory(\n parameterization=asb.DynamicsPointMass3DCartesian,\n )\n dyn2 = get_trajectory(\n parameterization=asb.DynamicsPointMass3DSpeedGammaTrack,\n )\n assert dyn1[-1].x_e == pytest.approx(dyn2[-1].x_e, abs=1e-6, rel=1e-6)\n assert dyn1[-1].y_e == pytest.approx(dyn2[-1].y_e, abs=1e-6, rel=1e-6)\n assert dyn1[-1].z_e == pytest.approx(dyn2[-1].z_e, abs=1e-6, rel=1e-6)\n assert dyn1[-1].u_e == pytest.approx(dyn2[-1].u_e, abs=1e-6, rel=1e-6)\n assert dyn1[-1].v_e == pytest.approx(dyn2[-1].v_e, abs=1e-6, rel=1e-6)\n assert dyn1[-1].w_e == pytest.approx(dyn2[-1].w_e, abs=1e-6, rel=1e-6)\n\n\nif __name__ == '__main__':\n # pytest.main()\n dyn1 = get_trajectory(\n asb.DynamicsPointMass3DCartesian,\n plot=True\n )\n dyn2 = get_trajectory(\n asb.DynamicsPointMass3DSpeedGammaTrack,\n plot=True\n )\n","sub_path":"aerosandbox/dynamics/point_mass/point_3D/test/test_helix_3D.py","file_name":"test_helix_3D.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"41452450","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport argparse\nimport numpy as np\nfrom multiprocessing import Pool\nfrom pic import path, profile, file, omake\n\n## CUI\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n## path\n#path.DATA_PATH = '../data/'\n#path.PLOT_PATH = './'\n#profile.reload()\n\nPROC = 1\n\nORIGIN = 'lower'\nINTERPOLATION = 'spline36'\nC_MAX = 0.01\nC_MIN = -C_MAX\nC_MAP = omake.generate_cmap(['blue', '#222222', 'red'])\n#cm = plt.cm.seismic\n\nx = range(0, profile.LX, 1)\ny = range(0, profile.LY, 1)\n\nX, Y = np.meshgrid(x, y)\nlevels = np.linspace(0.1, 1.5, 100)\n\ndef parse():\n parser = argparse.ArgumentParser(\n description='fieldデータから2dのカラーコンタをつくるやーつ'\n )\n # 必須\n parser.add_argument('-s', '--species', type=str, required=True)\n parser.add_argument('-t', '--times', type=int, required=True)\n \n # 任意\n parser.add_argument('-cmax', type=int)\n parser.add_argument('-cmin', type=int)\n parser.add_argument('--version', action='version', version='%(prog)s 2.0')\n \n return parser.parse_args()\n \ndef load(prefix, ts, pid):\n for n in range(profile.SIZE):\n #print(file.input([prefix, ts, n]))\n d = np.loadtxt(file.input([prefix, ts, n]), delimiter=\"\\t\")\n if (d.size > 0):\n d = d.reshape(d.size//7, 7)\n\n if (d == pid).any():\n pid_ = np.where(d == pid)\n d[pid_[0], 1] = d[pid_[0], 1] - 2.0 + n * profile.LZ0\n return np.c_[d[pid_[0], 1:4][0]]\n\ndef save(file_path, fig):\n fig.savefig(file_path, bbox_inches='tight', transparent=True)\n\n\ndef plot(ts):\n global m1, m2, p1, p2, n1\n\n fig = plt.figure()\n\n ax1 = fig.add_subplot(121)\n ax2 = fig.add_subplot(122)\n\n p1 = np.hstack((p1, load(species, ts, 110051503)))\n p2 = np.hstack((p2, load(species, ts, 77255503)))\n m1 = np.hstack((m1, load(species, ts, 108405403)))\n m2 = np.hstack((m2, load(species, ts, 70137108)))\n n1 = np.hstack((n1, load(species, ts, 50848704)))\n\n #if (p1.shape[1] > times):\n # p1 = np.delete(p1, 0, 1)\n # p2 = np.delete(p2, 0, 1)\n # m1 = np.delete(m1, 0, 1)\n # m2 = np.delete(m2, 0, 1)\n # n1 = np.delete(n1, 0, 1)\n\n w = 200\n\n imin = profile.LX/2-w\n imax = profile.LX/2+w\n jmin = profile.LY/2-w\n jmax = profile.LY/2+w\n\n a = 0.2\n\n aplot\n\n ax1.plot(p1[2], p1[0], \".\", label='P1', color='red', alpha=1.00)\n ax1.plot(m1[2], m1[0], \".\", label='M1', color='blue', alpha=1.00)\n\n #ax.plot(X, Y, k + .1*d[k, :, :], zdir='z', levels=k + .1*levels, alpha=.2)\n ax.plot(p1[2], p1[1], p1[0], label='P1', color='red', alpha=1.00)\n ax.plot(p2[2], p2[1], p2[0], label='P2', color='red', alpha=1.00)\n ax.plot(m1[2], m1[1], m1[0], label='M1', color='blue', alpha=1.00)\n ax.plot(m2[2], m2[1], m2[0], label='M2', color='blue', alpha=1.00)\n ax.plot(n1[2], n1[1], n1[0], label='N1', color='green', alpha=1.00)\n\n cset = ax.plot(p1[2], p1[1], 0, zdir='z', color='red', alpha=a)\n cset = ax.plot(p2[2], p2[1], 0, zdir='z', color='red', alpha=a)\n cset = ax.plot(m1[2], m1[1], 0, zdir='z', color='blue', alpha=a)\n cset = ax.plot(m2[2], m2[1], 0, zdir='z', color='blue', alpha=a)\n cset = ax.plot(n1[2], n1[1], 0, zdir='z', color='green', alpha=a)\n \n cset = ax.plot(p1[1], p1[0], imin, zdir='x', color='red', alpha=a)\n cset = ax.plot(p2[1], p2[0], imin, zdir='x', color='red', alpha=a)\n cset = ax.plot(m1[1], m1[0], imin, zdir='x', color='blue', alpha=a)\n cset = ax.plot(m2[1], m2[0], imin, zdir='x', color='blue', alpha=a)\n cset = ax.plot(n1[1], n1[0], imin, zdir='x', color='green', alpha=a)\n\n cset = ax.plot(p1[2], p1[0], jmax, zdir='y', color='red', alpha=a)\n cset = ax.plot(p2[2], p2[0], jmax, zdir='y', color='red', alpha=a)\n cset = ax.plot(m1[2], m1[0], jmax, zdir='y', color='blue', alpha=a)\n cset = ax.plot(m2[2], m2[0], jmax, zdir='y', color='blue', alpha=a)\n cset = ax.plot(n1[2], n1[0], jmax, zdir='y', color='green', alpha=a)\n\n ax.legend()\n\n ax.set_xlim3d(imin, imax)\n ax.set_ylim3d(jmin, jmax)\n ax.set_zlim3d(0, profile.LZ0*profile.SIZE)\n\n\n save(file.output([species, ts]), fig)\n plt.clf()\n \ndef main():\n global species, times, m1, m2, p1, p2, n1\n args = parse()\n species = args.species\n times = args.times\n\n p1 = load(species, 0, 110051503)\n p2 = load(species, 0, 77255503)\n m1 = load(species, 0, 108405403)\n m2 = load(species, 0, 70137108)\n n1 = load(species, 0, 50848704)\n\n\n\n \n \n for ts in range(0, profile.TIMESTEP_MAX+1, 1):\n print(ts)\n plot(ts)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"particle_velo.py","file_name":"particle_velo.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"406028132","text":"from PythonClientAPI.game.PointUtils import *\nfrom PythonClientAPI.game.Entities import FriendlyUnit, EnemyUnit, Tile\nfrom PythonClientAPI.game.Enums import Team\nfrom PythonClientAPI.game.World import World\nfrom PythonClientAPI.game.TileUtils import TileUtils\n\nimport math\nfrom random import randint\nNORTH_WEST = 0\nSOUTH_WEST = 1\nSOUTH_EAST = 2\nNORTH_EAST = 3\n\n\nclass PlayerAI:\n\n def __init__(self):\n ''' Initialize! '''\n self.turn_count = 0 # game turn count\n self.target = None # target to send unit to!\n self.outbound = True # is the unit leaving, or returning?\n self.targetQueue = []\n self.recalibrating_making_squares = False\n self.attacking = None\n\n\n def do_move(self, world, friendly_unit, enemy_units):\n '''\n This method is called every turn by the game engine.\n Make sure you call friendly_unit.move(target) somewhere here!\n\n Below, you'll find a very rudimentary strategy to get you started.\n Feel free to use, or delete any part of the provided code - Good luck!\n\n :param world: world object (more information on the documentation)\n - world: contains information about the game map.\n - world.path: contains various pathfinding helper methods.\n - world.util: contains various tile-finding helper methods.\n - world.fill: contains various flood-filling helper methods.\n\n :param friendly_unit: FriendlyUnit object\n :param enemy_units: list of EnemyUnit objects\n '''\n self.turn_count += 1\n if friendly_unit.status == 'DISABLED':\n print(\"Turn {0}: Disabled - skipping move.\".format(str(self.turn_count)))\n self.target = None\n self.outbound = True\n return\n\n if self.target is None and self.outbound: # Making squares for the first time\n self.target = self.start_making_squares(friendly_unit, world)\n elif self.attacking is not None:\n if friendly_unit.position in self.attacking.body: # We've killed them, I think\n self.attacking = None\n self.target = self.start_making_squares(friendly_unit, world)\n else:\n self.target = world.util.get_closest_enemy_body_from(friendly_unit.position, None).position\n elif self.target is not None and self.outbound: # We're going to the target to capture squares or kill someone\n if friendly_unit.position == self.target: #\n if self.targetQueue:\n self.target = self.targetQueue.pop(0)\n elif self.recalibrating_making_squares:\n self.target = self.start_making_squares(friendly_unit, world)\n self.recalibrating_making_squares = False\n else:\n self.outbound = False\n self.target = world.util.get_closest_friendly_territory_from(friendly_unit.position, friendly_unit.snake).position\n elif self.target is not None and not self.outbound: # Going back to home territory\n if friendly_unit.position == self.target: # Found home territory, going back to capture territory mode (outbound = True)\n enemy_to_attack = should_attack(friendly_unit.position, world)\n if enemy_to_attack is not None:\n self.attacking = world.get_unit_by_team(enemy_to_attack.body)\n self.target = world.util.get_closest_enemy_body_from(friendly_unit.position, None).position\n else:\n target_corners = world.util.get_friendly_territory_corners()\n target_corner = self.get_best_corner(target_corners, world, enemy_units)\n self.target = target_corner\n self.recalibrating_making_squares = True\n self.outbound = True\n next_move = world.path.get_shortest_path(friendly_unit.position, self.target, friendly_unit.body)[0]\n friendly_unit.move(next_move)\n\n\n print(\"Turn {0}: currently at {1}, making {2} move to {3}.\".format(\n str(self.turn_count),\n str(friendly_unit.position),\n 'outbound' if self.outbound else 'inbound',\n str(self.target)\n ))\n\n def get_best_corner(self, corners, world, enemy_units):\n min_distance = float(\"inf\")\n best_corner = None\n\n capturable_territory = set([])\n capturable_territory.update(world.get_neutral_points())\n for enemy_unit in enemy_units:\n capturable_territory.update(enemy_unit.territory)\n\n for corner in corners:\n distanceFromCorner = 0\n for capturable_point in capturable_territory:\n distanceFromCorner += world.path.get_taxi_cab_distance(corner.position, capturable_point)\n if distanceFromCorner < min_distance:\n min_distance = distanceFromCorner\n best_corner = corner\n\n return best_corner.position\n\n\n\n def start_making_squares(self, friendly_unit, world):\n \"\"\"\n :param friendly_unit: Our snake\n :param world\n :return: First coordinate of the square we're making\n \"\"\"\n starting_point = friendly_unit.position\n our_territory = friendly_unit.territory\n width = world.get_width()\n height = world.get_height()\n\n best_direction = self.get_best_quadrant(starting_point, our_territory, width, height)\n # TODO: FIND AN OPTIMAL LENGTH\n targets = make_square(starting_point, 5, best_direction)\n self.targetQueue.extend(targets)\n\n return self.targetQueue.pop(0)\n\n def get_best_quadrant(self, startingPoint, our_captured_territory, width, length):\n areas = [startingPoint[0] * startingPoint[1], startingPoint[0] * (length - startingPoint[1]), (length - startingPoint[1]) * (width - startingPoint[0]), (width - startingPoint[0]) * startingPoint[1]]\n for coord in our_captured_territory:\n if coord[0] > startingPoint[0]:\n if coord[1] > startingPoint[1]:\n areas[1] -= 1 # SWArea\n else:\n areas[0] -= 1 # NWArea\n else:\n if coord[1] > startingPoint[1]:\n areas[2] -= 1 # SEArea\n else:\n areas[3] -= 1 # NEArea\n #return areas.index(max(areas))\n\n # Need to find closest capturable territory in a quadrant\n\n\n return randint(0, len(areas) - 1)\n\n\ndef make_square(startingPoint, length, best_direction):\n # LEft and right edges\n x = startingPoint[0]\n y = startingPoint[1]\n #if x - length >= 0:\n if best_direction == NORTH_EAST or best_direction == SOUTH_EAST:\n rightSide = x + length\n firstVertex = (rightSide, y)\n else:\n leftSide = x - length\n firstVertex = (leftSide, y)\n\n\n # north and south edges\n if best_direction == NORTH_EAST or best_direction == NORTH_WEST:\n northSide = y - length\n secondVertex = (firstVertex[0], northSide)\n else:\n southSide = y + length\n secondVertex = (firstVertex[0], southSide)\n\n thirdVertex = (startingPoint[0], secondVertex[1])\n\n return [firstVertex, secondVertex, thirdVertex]\n\n\ndef should_attack(curr_position, world):\n closest_enemy_body_tile = world.util.get_closest_enemy_body_from(curr_position, None)\n if closest_enemy_body_tile is None: # Not sure why this happens\n return None\n enemy_owner = world.get_unit_by_team(closest_enemy_body_tile.body)\n if world.path.get_taxi_cab_distance(curr_position, closest_enemy_body_tile.position) < \\\n world.path.get_taxi_cab_distance(enemy_owner.position, world.util.get_closest_territory_by_team(\n enemy_owner.position, closest_enemy_body_tile.body, None).position):\n return closest_enemy_body_tile\n else: # SHouldn't attack otherwise\n return None\n\n\n","sub_path":"Bots/yeye/PlayerAI.py","file_name":"PlayerAI.py","file_ext":"py","file_size_in_byte":7992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"503712577","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport pickle\nimport os.path\n\nword_definitions_dict = {}\nword_synonyms_dict = {}\n\nurl = \"https://he.wiktionary.org/wiki/%D7%9E%D7%99%D7%95%D7%97%D7%93:%D7%9B%D7%9C_%D7%94%D7%93%D7%A4%D7%99%D7%9D?from\" \\\n \"=%D7%AA%D7%A4%D7%A1%D7%AA+%D7%9E%D7%A8%D7%95%D7%91%D7%94+%D7%9C%D7%90+%D7%AA%D7%A4%D7%A1%D7%AA&to=&namespace=0 \"\n\n\ndef get_definitions(word, divider):\n \"\"\"\n\n :param word:\n :param divider:\n :return:\n \"\"\"\n definitions_ol = divider.find_next('ol')\n if definitions_ol is not None:\n definitions = []\n for li in definitions_ol.find_all(\"li\"):\n dls = definitions_ol.find_all('dl')\n for dl in dls:\n dl.decompose()\n definition = str(li.get_text())\n if definition:\n definitions.append(definition.replace('\\n', ''))\n word_definitions_dict[word] = definitions\n\n\ndef get_synonyms(word, divider):\n \"\"\"\n\n :param word:\n :param divider:\n :return:\n \"\"\"\n synonyms = divider.find(id='מילים_נרדפות')\n if synonyms is None:\n return\n\n synonyms_ul = synonyms.find_next('ul')\n if synonyms_ul is None:\n return\n\n synonyms = []\n for li in synonyms_ul.find_all('li'):\n synonym = str(li.get_text())\n if synonym:\n synonyms.append(synonym.replace('\\n', ''))\n\n word_synonyms_dict[word] = synonyms\n\n\ndef scrape(origin_url, path_to_definitions, path_to_synonyms):\n \"\"\"\n\n :param origin_url:\n :param path_to_definitions:\n :param path_to_synonyms:\n :return:\n \"\"\"\n while True:\n origin_html = urlopen(origin_url)\n origin_soup = BeautifulSoup(origin_html, 'html.parser')\n words_links = origin_soup.find(\"div\", class_=\"mw-allpages-body\")\n\n for link in words_links.find_all('a'):\n word = str(link.get_text())\n if '\"' in word:\n continue\n word_url = \"https://he.wiktionary.org\" + link.get(\"href\")\n word_html = urlopen(word_url)\n word_soup = BeautifulSoup(word_html, 'html.parser')\n divider = word_soup.find(\"div\", class_=\"mw-parser-output\")\n if len(word) <= 10:\n get_definitions(word, divider)\n get_synonyms(word, divider)\n\n page_links = origin_soup.find(\"div\", class_=\"mw-allpages-nav\")\n nav_links = page_links.find_all('a')\n if len(nav_links) == 2:\n origin_url = \"https://he.wiktionary.org\" + nav_links[1].get('href')\n else:\n break\n\n with open(path_to_definitions, 'wb') as word_definitions_file, \\\n open(path_to_synonyms, \"wb\") as word_synonyms_file:\n pickle.dump(word_definitions_dict, word_definitions_file)\n pickle.dump(word_synonyms_dict, word_synonyms_file)\n\n\ndef main():\n scrape(url, os.path.expanduser('~/PycharmProjects/crossword/word_definitions.p'),\n os.path.expanduser('~/PycharmProjects/crossword/word_synonyms.p'))\n\n\nmain()\n","sub_path":"wiktionary_scraping.py","file_name":"wiktionary_scraping.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"50807160","text":"#!/usr/bin/env python3\n\nfrom __future__ import print_function\nimport sys\nimport os\nimport io\nimport hashlib\nimport base64\nimport time\nimport math\nimport random\nfrom datetime import datetime, timedelta\nimport contextlib\nimport argparse\nimport asyncio\nfrom textwrap import dedent\n\nimport boto3\nimport botocore\n\n\nclass Specs(dict):\n \"\"\"Default ec2 instance specs\"\"\"\n def __init__(self):\n super(Specs, self).__init__()\n self['ami'] = 'ami-0d987ffbb488908b0'\n self['instance_types'] = {\n 't3a.small': {'max_price': '0.008', 'cores': 1},\n }\n self['hours'] = 16\n self['keypair'] = 'claudiok'\n self['region'] = 'us-east-2'\n self['public_zones'] = {\n 'us-east-2a': 'subnet-0b284de90164ece23',\n 'us-east-2b': 'subnet-07e62479ad8964a27',\n 'us-east-2c': 'subnet-01b1763702ded170c',\n }\n self['private_zones'] = {\n 'us-east-2a': 'subnet-0c5b40d944c5db6d0',\n 'us-east-2b': 'subnet-02ffde5210f3ddf53',\n 'us-east-2c': 'subnet-0fa2166b9bf3b0011',\n }\n self['security_group'] = 'sg-1affe374' # make sure the VPC this is running in has an Endpoint to S3\n self['fleet_role'] = 'arn:aws:iam::085443031105:role/aws-service-role/spotfleet.amazonaws.com/AWSServiceRoleForEC2SpotFleet'\n\n\ndef format_user_data(text):\n text = dedent(text)\n if sys.version_info[0] < 3:\n return base64.b64encode(text)\n else:\n return base64.b64encode(text.encode('utf-8')).decode('utf-8')\n\n\nclass Instance:\n \"\"\"Wrapper for ec2 instance\"\"\"\n def __init__(self, ec2, user_data, spec, public=False, spot=True, termination_not_an_error=False, name='server'):\n self.ec2 = ec2\n self.user_data = user_data\n self.spec = spec\n self.public = public\n self.name = name\n self.spot = spot\n self.termination_not_an_error = termination_not_an_error\n\n self.request_id = None\n self.instance_id = None\n self.zone = None\n self.dnsname = None\n self.ipv6_address = None\n self.ipv4_address = None\n\n async def __aenter__(self):\n \"\"\"\n Create and wait to come up.\n \"\"\"\n if self.public:\n zones = self.spec['public_zones']\n else:\n zones = self.spec['private_zones']\n self.zone = random.choice(list(zones.keys()))\n\n if self.spot:\n ret = self.ec2.request_spot_instances(\n DryRun=False,\n SpotPrice=self.spec['price'],\n InstanceCount=1,\n Type='one-time',\n InstanceInterruptionBehavior='terminate',\n BlockDurationMinutes=int(math.ceil(self.spec['hours'])*60),\n LaunchSpecification={\n 'ImageId': self.spec['ami'],\n 'KeyName': self.spec['keypair'],\n 'Placement': {\n 'AvailabilityZone': self.zone\n },\n 'NetworkInterfaces': [\n {\n 'AssociatePublicIpAddress': self.public, # for ipv4\n 'DeleteOnTermination': True,\n 'DeviceIndex': 0,\n 'Groups': [self.spec['security_group']],\n 'Ipv6AddressCount': 1,\n 'SubnetId': zones[self.zone],\n }\n ],\n 'UserData': format_user_data(self.user_data),\n 'InstanceType': self.spec['instance_type'],\n }\n )\n self.request_id = ret['SpotInstanceRequests'][0]['SpotInstanceRequestId']\n try:\n self.instance_id = ret['SpotInstanceRequests'][0]['InstanceId']\n except Exception:\n self.instance_id = None\n else:\n ret = self.ec2.run_instances(\n DryRun=False,\n InstanceInitiatedShutdownBehavior='terminate',\n InstanceType=self.spec['instance_type'],\n UserData=dedent(self.user_data),\n KeyName=self.spec['keypair'],\n Placement = {\n 'AvailabilityZone': self.zone\n },\n NetworkInterfaces = [{\n 'AssociatePublicIpAddress': self.public, # for ipv4\n 'DeleteOnTermination': True,\n 'DeviceIndex': 0,\n 'Groups': [self.spec['security_group']],\n 'Ipv6AddressCount': 1,\n 'SubnetId': zones[self.zone],\n }],\n TagSpecifications = [{\n 'ResourceType': 'instance',\n 'Tags' : [{\n 'Key': 'Name',\n 'Value': self.name\n }]\n }],\n ImageId=self.spec['ami'],\n MinCount=1,\n MaxCount=1)\n self.instance_id = ret['Instances'][0]['InstanceId']\n if not self.instance_id: raise Exception(\"Instance could not be created\")\n self.request_id = None\n \n await asyncio.sleep(1)\n\n try:\n if self.spot:\n while not self.instance_id:\n print(self.name, 'waiting for spot instance creation')\n ret = self.ec2.describe_spot_instance_requests(\n SpotInstanceRequestIds=[self.request_id],\n )\n try:\n self.instance_id = ret['SpotInstanceRequests'][0]['InstanceId']\n except Exception:\n self.instance_id = None\n if not self.instance_id:\n if 'Status' in ret['SpotInstanceRequests'][0] and 'Message' in ret['SpotInstanceRequests'][0]['Status']:\n print(self.name, ' ', ret['SpotInstanceRequests'][0]['Status']['Message'])\n await asyncio.sleep(10)\n\n # set the instance name\n self.ec2.create_tags(\n DryRun=False,\n Resources=[self.instance_id],\n Tags=[{\n 'Key': 'Name',\n 'Value': self.name\n }]\n )\n\n while True:\n print(self.name, 'waiting for server startup')\n ret = self.ec2.describe_instances(\n InstanceIds=[self.instance_id],\n )\n state = ret['Reservations'][0]['Instances'][0]['State']['Name']\n if state == 'pending':\n await asyncio.sleep(10)\n continue\n if state != 'running':\n raise Exception(\"State after `pending` is unexpected (expected `running`): {}\".format(state))\n # we are done!\n break\n\n while not self.ipv6_address:\n print(self.name, 'waiting for server startup')\n ret = self.ec2.describe_instances(\n InstanceIds=[self.instance_id],\n )\n try:\n self.dnsname = ret['Reservations'][0]['Instances'][0]['PublicDnsName']\n self.ipv4_address = ret['Reservations'][0]['Instances'][0]['PrivateIpAddress']\n for interface in ret['Reservations'][0]['Instances'][0]['NetworkInterfaces']:\n self.ipv6_address = interface['Ipv6Addresses'][0]['Ipv6Address']\n if self.ipv6_address:\n break\n except Exception:\n self.dnsname = None\n self.ipv6_address = None\n self.ipv4_address = None\n if not self.ipv6_address:\n await asyncio.sleep(5)\n \n except (KeyboardInterrupt,Exception):\n if self.request_id:\n self.ec2.cancel_spot_instance_requests(\n SpotInstanceRequestIds=[self.request_id],\n )\n if self.instance_id:\n self.ec2.terminate_instances(\n InstanceIds=[self.instance_id],\n )\n raise\n\n print(self.name, 'started', self.dnsname, self.ipv6_address, self.ipv4_address)\n\n async def monitor(self, timeout=10000000000000000, frequency_seconds=60):\n \"\"\"Monitor instance and die after `timeout` seconds.\"\"\"\n end_time = time.time()+timeout\n while self.instance_id and time.time() < end_time:\n ret = self.ec2.describe_instances(\n InstanceIds=[self.instance_id],\n )\n state = ret['Reservations'][0]['Instances'][0]['State']['Name']\n try:\n assert state == 'running'\n except Exception:\n print(self.name, 'instance seems to be not running. (state={}) about to quit monitor()'.format(state))\n self.instance_id = None\n else:\n await asyncio.sleep(frequency_seconds)\n \n if self.termination_not_an_error:\n print(self.name, 'instance terminated')\n else:\n raise Exception(f'{self.name} instance terminated unexpectedly')\n\n async def __aexit__(self, exc_type, exc, tb):\n print(self.name, 'instance termination requested')\n if self.request_id:\n print(self.name, 'canceling spot instance request')\n self.ec2.cancel_spot_instance_requests(\n SpotInstanceRequestIds=[self.request_id],\n )\n print(self.name, 'spot instance request canceled')\n if self.instance_id:\n print(self.name, 'terminating instance')\n self.ec2.terminate_instances(\n InstanceIds=[self.instance_id],\n )\n print(self.name, 'instance terminated')\n \n\nclass SpotFleet:\n \"\"\"Wrapper for ec2 spot fleet\"\"\"\n def __init__(self, ec2, user_data, spec, num=1, name='fleet'):\n self.ec2 = ec2\n self.user_data = user_data\n self.spec = spec\n self.num = num\n self.name = name\n\n self.fleet_id = None\n\n async def __aenter__(self):\n \"\"\"\n Create and wait to come up.\n \"\"\"\n user_data_b64 = format_user_data(self.user_data)\n\n date_from = datetime.utcnow()\n date_to = date_from + timedelta(hours=self.spec['hours'])\n\n launch_specs = []\n for inst in self.spec['instance_types']:\n for zone in self.spec['private_zones']:\n launch_specs.append({\n 'ImageId': self.spec['ami'],\n 'KeyName': self.spec['keypair'],\n 'Placement': {\n 'AvailabilityZone': zone\n },\n 'NetworkInterfaces': [\n {\n 'AssociatePublicIpAddress': False,\n 'DeleteOnTermination': True,\n 'DeviceIndex': 0,\n 'Groups': [self.spec['security_group']],\n 'Ipv6AddressCount': 1,\n 'SubnetId': self.spec['private_zones'][zone],\n }\n ],\n 'UserData': user_data_b64,\n 'InstanceType': inst,\n 'SpotPrice': self.spec['instance_types'][inst]['max_price'],\n 'WeightedCapacity': self.spec['instance_types'][inst]['cores'],\n 'TagSpecifications': [\n {\n 'ResourceType': 'instance',\n 'Tags' : [{\n 'Key': 'Name',\n 'Value': self.name\n }]\n }\n ],\n })\n\n request = self.ec2.request_spot_fleet(\n SpotFleetRequestConfig={\n 'TargetCapacity': self.num,\n 'ValidFrom': date_from.strftime('%Y-%m-%dT%H:%M:%SZ'),\n 'ValidUntil': date_to.strftime('%Y-%m-%dT%H:%M:%SZ'),\n 'TerminateInstancesWithExpiration': True,\n 'IamFleetRole': self.spec['fleet_role'],\n 'LaunchSpecifications': launch_specs,\n 'Type': 'maintain',\n 'AllocationStrategy': 'lowestPrice',\n # 'InstancePoolsToUseCount': len(launch_specs)\n }\n )\n self.fleet_id = request['SpotFleetRequestId']\n print('fleet success:', self.fleet_id)\n\n \n async def monitor(self, timeout=10000000000000000):\n \"\"\"Monitor instance and die after `timeout` seconds.\"\"\"\n end_time = time.time()+timeout\n while self.instance_id and time.time() < end_time:\n ret = self.ec2.describe_instances(\n InstanceIds=[self.instance_id],\n )\n try:\n assert ret['Reservations'][0]['Instances'][0]['State']['Name'] == 'running'\n except Exception:\n self.instance_id = None\n else:\n await asyncio.sleep(60)\n raise Exception('fleet terminated')\n\n async def __aexit__(self, exc_type, exc, tb):\n if self.fleet_id:\n print('terminating spot fleet')\n self.ec2.cancel_spot_fleet_requests(\n SpotFleetRequestIds=[self.fleet_id],\n TerminateInstances=True,\n )\n print('fleet terminated')\n\n\nclass TempS3File:\n \"\"\"Upload a file for temporary use to an S3 bucket\"\"\"\n def __init__(self, s3, bucket, data=None, filename=None, url_expiration_sec=3600):\n self.s3 = s3\n self.bucket = bucket\n self.data = data\n self.filename = filename\n self.object_name = None\n self.uuid = None\n self.url_expiration_sec = url_expiration_sec\n self.obj_url = None\n\n async def __aenter__(self):\n \"\"\"\n Upload to s3 bucket\n \"\"\"\n \n if self.data is None and self.filename is not None:\n print('reading input data from {}'.format(self.filename))\n with open(self.filename, 'rb') as f:\n self.data = f.read()\n \n # create a temporary object name\n uuid = hashlib.sha256(self.data).hexdigest()\n object_name = uuid + '.dat'\n print('will upload data as {} to bucket {}'.format(object_name, self.bucket))\n \n fo = io.BytesIO(self.data)\n try:\n response = self.s3.upload_fileobj(fo, self.bucket, object_name)\n except ClientError as e:\n print('upload failed.')\n del fo\n self.data = None\n raise\n\n self.object_name = object_name\n self.uuid = uuid\n \n print('upload success. creating pre-signed URL..')\n \n response = self.s3.generate_presigned_url(\n ClientMethod='get_object',\n Params={'Bucket': self.bucket,\n 'Key': self.object_name},\n ExpiresIn=self.url_expiration_sec)\n\n assert response is not None\n \n self.obj_url = response\n\n print('success.')\n \n\n async def __aexit__(self, exc_type, exc, tb):\n if self.object_name:\n print('deleting s3 object')\n self.s3.delete_object(\n Bucket=self.bucket,\n Key=self.object_name\n )\n print('s3 object deleted')\n\ndef create_presigned_put_url(s3, bucket, key, timeout_hours=24):\n return s3.generate_presigned_url(\n 'put_object', \n Params={'Bucket':bucket,'Key':key}, \n ExpiresIn=3600*timeout_hours, \n HttpMethod='PUT'\n )\n\n\nasync def main():\n parser = argparse.ArgumentParser(description='launch ec2 pool')\n parser.add_argument('-f', '--in-file', help=\"input .i3 data in JSON format\",\n type=str, default=None)\n parser.add_argument('-n','--num', default=1, type=int,\n help='number of servers in the worker pool')\n parser.add_argument('--collector-num', default=2, type=int,\n help='number of servers in the collector pool')\n parser.add_argument('-b','--bucket', default='icecube-skymap-staging',\n type=str, help='S3 bucket name for temporary file upload')\n parser.add_argument('-o','--outbucket', default='icecube-skymap-output',\n type=str, help='S3 bucket name for final output')\n parser.add_argument('-i','--nside', default=1, type=int,\n help='Healpix nside (number of pixels is 12*nside^2)')\n parser.add_argument('-p','--pulsar', default=\"pulsar+ssl://pulsar.api.icecube.aq:6651\",\n type=str, help='Pulsar server URL')\n parser.add_argument('-t','--token', default=None,\n type=str, help='Pulsar authentication token')\n args = vars(parser.parse_args())\n\n if args['token'] is None:\n parser.error('You need to specify a pulsar authentication token --token=')\n \n session = boto3.session.Session()\n\n spec = Specs()\n s3 = session.client(\n service_name='s3',\n region_name=spec['region'],\n config=botocore.client.Config(signature_version='s3v4')\n )\n ec2 = session.client(\n service_name='ec2',\n region_name=spec['region']\n )\n\n\n producer_spec = spec.copy()\n producer_spec['instance_type'] = 't2.small'\n producer_spec['price'] = '0.02'\n producer_spec['hours'] = 1\n producer_user_data = \"\"\"\\\n #!/bin/bash\n\n docker run --rm icecube/skymap_scanner:latest producer '{event_url}' --broker {queue_url} --auth-token {queue_token} --nside {nside} -n event_{uuid}\n shutdown -hP now\n \"\"\"\n \n collector_spec = spec.copy()\n collector_spec['instance_type'] = 'r5.large'\n collector_spec['instance_types'] = {\n 'r5.xlarge': {'max_price': '0.1', 'cores': 1},\n 'r5a.xlarge': {'max_price': '0.1', 'cores': 1},\n 'r5n.xlarge': {'max_price': '0.1', 'cores': 1},\n 'r4.xlarge': {'max_price': '0.1', 'cores': 1},\n }\n\n collector_user_data = \"\"\"\\\n #!/bin/bash\n\n docker run --rm icecube/skymap_scanner:latest collector --broker {queue_url} --auth-token {queue_token}\n shutdown -hP now\n \"\"\"\n \n worker_spec = spec.copy()\n worker_spec['instance_type'] = 't3a.small'\n worker_spec['instance_types'] = {\n 'c5.4xlarge': {'max_price': '0.012', 'cores': 16},\n 'c5d.4xlarge': {'max_price': '0.012', 'cores': 16},\n 'c5n.4xlarge': {'max_price': '0.012', 'cores': 16},\n 'c5.9xlarge': {'max_price': '0.012', 'cores': 36},\n 'c5d.9xlarge': {'max_price': '0.012', 'cores': 36},\n 'c5n.9xlarge': {'max_price': '0.012', 'cores': 36},\n 'c5d.12xlarge': {'max_price': '0.012', 'cores': 48},\n 'c5.18xlarge': {'max_price': '0.012', 'cores': 72},\n 'c5d.18xlarge': {'max_price': '0.012', 'cores': 72},\n 'c5n.18xlarge': {'max_price': '0.012', 'cores': 72},\n 'm5.4xlarge': {'max_price': '0.012', 'cores': 16},\n 'm5a.4xlarge': {'max_price': '0.012', 'cores': 16},\n 'm5n.4xlarge': {'max_price': '0.012', 'cores': 16},\n 'r5.4xlarge': {'max_price': '0.012', 'cores': 16},\n 'r5a.4xlarge': {'max_price': '0.012', 'cores': 16},\n 'r5n.4xlarge': {'max_price': '0.012', 'cores': 16},\n }\n worker_user_data = \"\"\"\\\n #!/bin/bash\n \n cat >/root/supervisord.conf < 0:\n print('-- bringing up Fleet (collector)')\n collector = SpotFleet(\n ec2,\n collector_user_data.format(\n queue_url=args['pulsar'],\n queue_token=args['token'],\n ),\n collector_spec,\n num=args['collector_num'],\n name='collector-fleet'\n )\n to_await.append(stack.enter_async_context(collector))\n\n if args['in_file'] is not None:\n print('-- bringing up Instance (saver)')\n saver = Instance(\n ec2,\n saver_user_data.format(\n queue_url=args['pulsar'],\n queue_token=args['token'],\n nside=args['nside'],\n uuid=event_id,\n out_url=presigned_output_url\n ),\n saver_spec,\n spot=False, # could be long-running, do not use a spot instance\n # termination_not_an_error=True, # not an error if this terminates, in fact - we are done when this terminates\n name='saver-' + event_id\n )\n to_await.append(stack.enter_async_context(saver))\n print('-- adding monitoring to futures (saver)')\n futures.append(saver.monitor())\n\n\n if args['num'] > 0:\n print('-- bringing up Fleet (worker)')\n fleet = SpotFleet(\n ec2,\n worker_user_data.format(\n queue_url=args['pulsar'],\n queue_token=args['token'],\n ),\n worker_spec, \n num=args['num'],\n name='worker-fleet'\n )\n to_await.append(stack.enter_async_context(fleet))\n \n print('-- awaiting startup')\n await asyncio.wait(to_await, return_when=asyncio.FIRST_EXCEPTION)\n print('-- startup completed')\n \n if args['in_file'] is None:\n print('-- waiting for spot fleet expiration')\n await asyncio.sleep( worker_spec['hours']*3600 )\n print('-- spot fleet expired')\n \n if len(futures) > 0:\n print('-- awaiting all monitoring futures')\n await asyncio.wait(futures, return_when=asyncio.FIRST_EXCEPTION)\n print('-- done')\n \n print('-- exit')\n\n\nif __name__ == '__main__':\n try:\n asyncio.run(main())\n except KeyboardInterrupt:\n pass\n","sub_path":"aws_ec2/submit_scan_to_ec2.py","file_name":"submit_scan_to_ec2.py","file_ext":"py","file_size_in_byte":25295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"478509078","text":"# qna/views.py\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Question, Answer\nfrom .forms import AnswerForm\nfrom exqna.forms import ExtraAnswerForm\nfrom django.utils import timezone\nfrom exqna.models import ExtraQuestion, ExtraAnswer\nfrom django.contrib.auth.decorators import login_required\nfrom qna.utils import get_today_id\nimport datetime\nfrom django.contrib import messages\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\n\n\n@login_required\ndef question(request):\n today_id = get_today_id()\n #우리가 윤년을 기본으로 하고 윤년이 아닌 년은 2월 29일 질문을 배제시키는 구조이기 때문에 이렇게 했다\n #today_id 기반이라 새벽 4시에 같이 바뀜\n\n question = Question.objects.get(id=today_id)\n # 그날에 맞는 질문을 골라 온다.\n already_answer = Answer.objects.filter(question=question, user=request.user, created_at__year=timezone.now().year) # 오늘 이미 답변했으면 넘어가기\n\n if already_answer:\n return redirect('exqna:exquestion')\n\n if request.method == 'POST':\n form = AnswerForm(request.POST, request.FILES)\n if form.is_valid():\n answer = form.save(commit=False)\n answer.user = request.user\n answer.question = question\n answer = form.save()\n return redirect('exqna:exquestion')\n else:\n form = AnswerForm()\n\n\n # if 'check' in form.is_public:\n # checked = 'asdnjkgsd'\n return render(request, 'qna/question.html', {\n 'form': form,\n 'question': question,\n })\n\n\n\n\n@login_required\ndef main(request):\n today_id = get_today_id()\n question = Question.objects.get(id=today_id) #오늘의 질문 불러오기\n qs = Answer.objects.filter(question=question, user=request.user) #오늘의 질문에 대해 했던 답 싹 다 불러오기\n exquestion = ExtraQuestion.objects.filter(is_new=True).first() #오늘의 추가질문 불러오기(없을 수도 있음)\n if not exquestion:\n return render(request, 'qna/main.html', {\n 'question':question,\n 'answer_list':qs,\n })\n has_extraAnswer = ExtraAnswer.objects.filter(question=exquestion, user=request.user).first()\n if has_extraAnswer: #이미 대답했을 경우 추가질문의 대답도 보여주기\n return render(request, 'qna/main.html', {\n 'question':question,\n 'answer_list':qs,\n 'exquestion':exquestion,\n 'ex_answer':has_extraAnswer,\n })\n else: #추가질문 대답안했을 경우 폼 만들어주기\n if request.method =='POST':\n form = ExtraAnswerForm(request.POST, request.FILES)\n if form.is_valid():\n extra_answer = form.save(commit=False)\n extra_answer.user = request.user\n extra_answer.question = exquestion\n extra_answer.save()\n return redirect('qna:main')\n else:\n form = AnswerForm()\n return render(request, 'qna/main.html', {\n 'question':question,\n 'answer_list':qs,\n 'exquestion':exquestion,\n 'form':form,\n })\n\n#제목으로 검색\n@login_required\ndef question_search(request):\n\n if request.GET.get('search_keyword'): #이거 search 에서 search_keyword로 바꿈/ day검색과의 차별성을 위해\n today_id = get_today_id()\n search_keyword = request.GET.get('search_keyword')\n search_ques1 = Question.objects.exclude(answer=None) #답 안한 것들 제거\n search_ques1 = search_ques1.filter(question__icontains=search_keyword, answer__user=request.user) #질문에 search 들어있는 것만 선택\n search_ques2 = ExtraAnswer.objects.filter(question__title__icontains=search_keyword,user=request.user) #추가질문 답한 것에 대해서도 질문에 search들어있는 것 선택\n\n for i in range(1, 11): # 앞으로의 열흘 동안의 질문은 검색되지 않도록 하기\n exclude_id = (today_id + i) % 366 # 366을 넘는 경우에 대해서 나머지로 처리\n if not id: # today_id+1이 0일 경우 366으로 바꿔줘야 함\n exclude_id = 366\n\n exclude_question = Question.objects.get(id=exclude_id)\n search_ques1 = search_ques1.exclude(question=exclude_question)\n search_ques1 = search_ques1.distinct()\n\n page = request.GET.get('page', 1)\n paginator1 = Paginator(search_ques1, 12)\n paginator2 = Paginator(search_ques2, 12)\n\n if search_ques1.count()==0 and search_ques2.count()==0 :\n messages.info(request, '검색결과가 없습니다')\n return redirect('qna:question_search')\n\n # 페이징\n try:\n searched_keyword1 = paginator1.page(page)\n searched_keyword2 = paginator2.page(page)\n\n except PageNotAnInteger:\n searched_keyword1 = paginator1.page(1)\n searched_keyword2 = paginator2.page(1)\n except EmptyPage:\n searched_keyword1 = paginator1.page(paginator1.num_pages)\n searched_keyword2 = paginator2.page(paginator2.num_pages)\n\n random_list = [1, 2, 3]\n\n # 중복 제거\n return render(request, 'qna/question_search.html', {\n 'search_keyword': search_keyword,\n # 'search_ques1': search_ques1,\n # 'search_ques2': search_ques2,\n 'search_ques1' : searched_keyword1,\n 'search_ques2' : searched_keyword2,\n 'random_list': random_list,\n\n })\n else:\n return render(request, 'qna/question_search.html')\n\n#날짜로 검색\n@login_required\ndef question_search_day(request):\n if request.GET.get('search_day'):\n today_id = get_today_id()\n search_day=request.GET.get('search_day')\n #search_day는 'July 26' 구조로 들어옴\n daylist = search_day.split(' ')\n\n def month_string_to_number(string):\n m = {\n 'jan': 1,\n 'feb': 2,\n 'mar': 3,\n 'apr': 4,\n 'may': 5,\n 'jun': 6,\n 'jul': 7,\n 'aug': 8,\n 'sep': 9,\n 'oct': 10,\n 'nov': 11,\n 'dec': 12\n }\n s = string.strip()[:3].lower()\n\n try:\n out = m[s]\n return out\n except:\n raise ValueError('Not a month')\n\n num=month_string_to_number(daylist[0])\n num=str(num)\n\n if daylist[1] < '10':\n daylist[1] = daylist[1][1]\n\n search_day_ques1=Question.objects.filter(month=num, day=daylist[1], answer__user=request.user)\n\n search_day_ques2=ExtraAnswer.objects.filter(created_at__month=num,created_at__day=daylist[1],user=request.user)\n\n for i in range(1, 11): # 앞으로의 열흘 동안의 질문은 검색되지 않도록 하기\n exclude_id = (today_id + i) % 366 # 366을 넘는 경우에 대해서 나머지로 처리\n if not id: # today_id+1이 0일 경우 366으로 바꿔줘야 함\n exclude_id = 366\n\n exclude_question = Question.objects.get(id=exclude_id)\n search_day_ques1 = search_day_ques1.exclude(question=exclude_question)\n search_day_ques1 = search_day_ques1.distinct()\n\n if search_day_ques1.count()==0 and search_day_ques2.count()==0 :\n messages.info(request, '검색결과가 없습니다')\n return redirect('qna:question_search_day')\n\n random_list = [1, 2, 3]\n\n page = request.GET.get('page', 1)\n paginator1 = Paginator(search_day_ques1, 12)\n paginator2 = Paginator(search_day_ques2, 12)\n\n # 페이징\n try:\n searched_day1 = paginator1.page(page)\n searched_day2 = paginator2.page(page)\n\n except PageNotAnInteger:\n searched_day1 = paginator1.page(1)\n searched_day2 = paginator2.page(1)\n except EmptyPage:\n searched_day1 = paginator1.page(paginator1.num_pages)\n searched_day2 = paginator2.page(paginator2.num_pages)\n\n\n # 중복 제거\n return render(request, 'qna/question_search_day.html', {\n 'search_day': search_day,\n # 'search_ques1': search_day_ques1,\n # 'search_ques2':search_day_ques2,\n 'search_ques1': searched_day1,\n 'search_ques2': searched_day2,\n 'random_list': random_list,\n })\n\n else:\n return render(request, 'qna/question_search_day.html')\n\n#내용으로 검색\n@login_required\ndef question_search_content(request):\n if request.GET.get('search_content'):\n today_id = get_today_id()\n search_content=request.GET.get('search_content')\n\n search_content_ques1=Question.objects.filter(answer__content__icontains=search_content ,answer__user=request.user)\n\n search_content_ques2=ExtraAnswer.objects.filter(content__icontains=search_content ,user=request.user)\n\n for i in range(1, 11): # 앞으로의 열흘 동안의 질문은 검색되지 않도록 하기\n exclude_id = (today_id + i) % 366 # 366을 넘는 경우에 대해서 나머지로 처리\n if not id: # today_id+1이 0일 경우 366으로 바꿔줘야 함\n exclude_id = 366\n\n exclude_question = Question.objects.get(id=exclude_id)\n search_content_ques1 = search_content_ques1.exclude(question=exclude_question)\n search_content_ques1 = search_content_ques1.distinct()\n\n if search_content_ques1.count()==0 and search_content_ques2.count()==0 :\n messages.info(request, '검색결과가 없습니다')\n return redirect('qna:question_search_content')\n\n random_list = [1, 2, 3]\n\n page = request.GET.get('page', 1)\n paginator1 = Paginator(search_content_ques1, 12)\n paginator2 = Paginator(search_content_ques2, 12)\n\n # 페이징\n try:\n searched_content1 = paginator1.page(page)\n searched_content2 = paginator2.page(page)\n\n except PageNotAnInteger:\n searched_content1 = paginator1.page(1)\n searched_content2 = paginator2.page(1)\n except EmptyPage:\n searched_content1 = paginator1.page(paginator1.num_pages)\n searched_content2 = paginator2.page(paginator2.num_pages)\n\n return render(request, 'qna/question_search_content.html',{\n 'search_content':search_content,\n # 'search_ques1':search_content_ques1,\n # 'search_ques2':search_content_ques2,\n 'searched_ques1':searched_content1,\n 'searched_ques2':searched_content2,\n 'random_list': random_list,\n })\n else:\n return render(request, 'qna/question_search_content.html')\n\n\n\n@login_required\ndef question_detail(request, question_id):\n answer_set = Answer.objects.filter(question__id=question_id, user=request.user)\n\n return render(request, 'qna/question_detail.html', {\n 'answer_set': answer_set,\n })\n\n\n@login_required\ndef question_edit(request, answer_id):\n today_id = get_today_id()\n question = Question.objects.get(id=today_id) #오늘의 질문 불러오기\n answer = get_object_or_404(Answer, id=answer_id)\n\n if answer.user_id != request.user.id:\n return redirect('qna:main')\n # url로 남의 답변에 접근 방지\n if answer.created_at + datetime.timedelta(hours=1) < timezone.now():\n messages.info(request, '수정 가능 시간이 지났습니다.')\n # 1시간 지났을 경우 수정 불가\n\n return redirect('qna:main')\n\n if request.method == 'POST':\n form = AnswerForm(request.POST, request.FILES, instance=answer)\n if form.is_valid():\n new_answer = form.save(commit=False)\n new_answer.user = request.user\n new_answer.question = question\n new_answer.save()\n return redirect('qna:main')\n else:\n form = AnswerForm(instance=answer)\n\n return render(request, 'qna/question.html', {\n 'form':form,\n 'question' : question,\n })\n\n\n@login_required\ndef other_people(request):\n today_id = get_today_id()\n question = Question.objects.get(id=today_id) #오늘의 질문 불러오기\n answer_set = Answer.objects.filter(question=question, is_public=True) #공유한다고 한 것만 불러오기\n other_answer_set = answer_set.exclude(user=request.user) #자기 답은 제외\n return render(request, 'qna/other_people.html', {\n 'question':question,\n 'answer_set':other_answer_set,\n })\n\n@login_required\ndef other_people(request):\n today_id = get_today_id()\n question = Question.objects.get(id=today_id) #오늘의 질문 불러오기\n\n answer_set = Answer.objects.filter(question=question, is_public=True) #공유한다고 한 것만 불러오기\n other_answer_set = answer_set.exclude(user=request.user)#자기 답은 제외\n\n page = request.GET.get('page', 1)\n paginator = Paginator(other_answer_set, 12)\n\n try:\n other_answer = paginator.page(page)\n except PageNotAnInteger:\n other_answer = paginator.page(1)\n except EmptyPage:\n other_answer = paginator.page(paginator.num_pages)\n\n\n return render(request, 'qna/other_people.html', {\n 'question':question,\n 'answer_set':other_answer_set,\n 'other_answer': other_answer\n })\n","sub_path":"qna/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"8111827","text":"\"\"\"Binary sensor platform for irrigation_unlimited.\"\"\"\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers import entity_platform\nimport homeassistant.util.dt as dt\nfrom datetime import datetime, timedelta\nfrom homeassistant.const import MAJOR_VERSION, MINOR_VERSION\n\nif MAJOR_VERSION >= 2021 and MINOR_VERSION >= 6:\n from homeassistant.components.recorder import history\nelse:\n from homeassistant.components import history\n\nimport json\n\nfrom homeassistant.const import (\n STATE_ON,\n)\n\nfrom .entity import IUEntity\nfrom .service import register_platform_services\nfrom .const import (\n ATTR_ENABLED,\n ATTR_STATUS,\n ATTR_INDEX,\n DOMAIN,\n COORDINATOR,\n ICON_CONTROLLER_OFF,\n ICON_CONTROLLER_ON,\n ICON_CONTROLLER_PAUSED,\n ICON_OFF,\n ICON_ON,\n ICON_DISABLED,\n ICON_BLOCKED,\n CONF_SCHEDULES,\n CONF_ZONES,\n CONF_ZONE_ID,\n)\n\nRES_MANUAL = \"Manual\"\nRES_NOT_RUNNING = \"not running\"\nRES_NONE = \"none\"\nRES_CONTROLLER = \"Controller\"\nRES_ZONE = \"Zone\"\nRES_MASTER = \"Master\"\n\nATTR_CURRENT_SCHEDULE = \"current_schedule\"\nATTR_CURRENT_NAME = \"current_name\"\nATTR_CURRENT_ADJUSTMENT = \"current_adjustment\"\nATTR_CURRENT_START = \"current_start\"\nATTR_CURRENT_DURATION = \"current_duration\"\nATTR_TIME_REMAINING = \"time_remaining\"\nATTR_PERCENT_COMPLETE = \"percent_complete\"\nATTR_ZONE_COUNT = \"zone_count\"\nATTR_CURRENT_ZONE = \"current_zone\"\nATTR_TOTAL_TODAY = \"today_total\"\n\n\nasync def async_setup_platform(hass, config, async_add_entities, discovery_info=None):\n \"\"\"Setup binary_sensor platform.\"\"\"\n\n coordinator = hass.data[DOMAIN][COORDINATOR]\n entities = []\n for controller in coordinator._controllers:\n entities.append(IUMasterEntity(coordinator, controller, None))\n for zone in controller.zones:\n entities.append(IUZoneEntity(coordinator, controller, zone))\n async_add_entities(entities)\n\n platform = entity_platform.current_platform.get()\n register_platform_services(platform)\n\n return\n\n\ndef on_duration(\n hass: HomeAssistant, start: datetime, end: datetime, entity_id: str\n) -> timedelta:\n \"\"\"Return the total on time between start and end\"\"\"\n history_list = history.state_changes_during_period(hass, start, end, entity_id)\n\n elapsed = timedelta()\n current_state: str = None\n current_time: datetime = None\n\n if len(history_list) > 0:\n if entity_id in history_list:\n for item in history_list.get(entity_id):\n\n # Initialise on first pass\n if current_state is None:\n current_state = item.state\n current_time = item.last_changed\n continue\n\n if current_state == STATE_ON and item.state != STATE_ON:\n elapsed += item.last_changed - current_time\n\n current_state = item.state\n current_time = item.last_changed\n\n if current_state == STATE_ON:\n elapsed += end - current_time\n\n return timedelta(seconds=round(elapsed.total_seconds()))\n\n\ndef midnight(utc: datetime) -> datetime:\n \"\"\"Accept a UTC time and return midnight for that day\"\"\"\n return dt.as_utc(\n dt.as_local(utc).replace(hour=0, minute=0, second=0, microsecond=0)\n )\n\n\ndef today_on_duration(hass: HomeAssistant, entity_id: str) -> timedelta:\n end = dt.utcnow()\n start = midnight(end)\n return on_duration(hass, start, end, entity_id)\n\n\nclass IUMasterEntity(IUEntity):\n \"\"\"irrigation_unlimited controller binary_sensor class.\"\"\"\n\n @property\n def unique_id(self):\n \"\"\"Return a unique ID.\"\"\"\n return f\"c{self._controller.index + 1}_m\"\n\n @property\n def name(self):\n \"\"\"Return the friendly name of the binary_sensor.\"\"\"\n return self._controller.name\n\n @property\n def is_on(self):\n \"\"\"Return true if the binary_sensor is on.\"\"\"\n return self._controller.is_on\n\n @property\n def should_poll(self):\n \"\"\"Indicate that we nee to poll data\"\"\"\n return False\n\n @property\n def icon(self):\n \"\"\"Return the icon to use in the frontend.\"\"\"\n if self._controller.enabled:\n if self._controller.is_on:\n return ICON_CONTROLLER_ON\n else:\n if self._controller.is_paused:\n return ICON_CONTROLLER_PAUSED\n else:\n return ICON_CONTROLLER_OFF\n else:\n return ICON_DISABLED\n\n @property\n def device_state_attributes(self):\n \"\"\"Return the state attributes of the device.\"\"\"\n attr = {}\n attr[ATTR_INDEX] = self._controller.index\n attr[ATTR_ENABLED] = self._controller.enabled\n attr[ATTR_STATUS] = self._controller.status\n attr[ATTR_ZONE_COUNT] = len(self._controller._zones)\n attr[CONF_ZONES] = \"\"\n current = self._controller.runs.current_run\n if current is not None:\n attr[ATTR_CURRENT_ZONE] = current.zone.index + 1\n attr[ATTR_CURRENT_NAME] = current.zone.name\n attr[ATTR_CURRENT_START] = dt.as_local(current.start_time)\n attr[ATTR_CURRENT_DURATION] = str(current.duration)\n attr[ATTR_TIME_REMAINING] = str(current.time_remaining)\n attr[ATTR_PERCENT_COMPLETE] = current.percent_complete\n else:\n attr[\"current_schedule\"] = \"deprecated (use current_zone)\"\n attr[ATTR_CURRENT_ZONE] = RES_NOT_RUNNING\n attr[ATTR_PERCENT_COMPLETE] = 0\n\n next = self._controller.runs.next_run\n if next is not None:\n attr[\"next_zone\"] = next.zone.index + 1\n attr[\"next_name\"] = next.zone.name\n attr[\"next_start\"] = dt.as_local(next.start_time)\n attr[\"next_duration\"] = str(next.duration)\n else:\n attr[\"next_schedule\"] = RES_NONE\n return attr\n\n\nclass IUZoneEntity(IUEntity):\n \"\"\"irrigation_unlimited zone binary_sensor class.\"\"\"\n\n @property\n def unique_id(self):\n \"\"\"Return a unique ID.\"\"\"\n return f\"c{self._controller.index + 1}_z{self._zone.index + 1}\"\n\n @property\n def name(self):\n \"\"\"Return the friendly name of the binary_sensor.\"\"\"\n return self._zone.name\n\n @property\n def is_on(self):\n \"\"\"Return true if the binary_sensor is on.\"\"\"\n return self._zone.is_on\n\n @property\n def should_poll(self):\n \"\"\"Indicate that we nee to poll data\"\"\"\n return False\n\n @property\n def icon(self):\n \"\"\"Return the icon to use in the frontend.\"\"\"\n if self._controller.enabled:\n if self._zone.enabled:\n if self._zone.is_on:\n return ICON_ON\n else:\n return ICON_OFF\n else:\n return ICON_DISABLED\n else:\n return ICON_BLOCKED\n\n @property\n def device_state_attributes(self):\n \"\"\"Return the state attributes of the device.\"\"\"\n attr = {}\n attr[CONF_ZONE_ID] = self._zone.zone_id\n attr[ATTR_INDEX] = self._zone.index\n attr[ATTR_ENABLED] = self._zone.enabled\n attr[ATTR_STATUS] = self._zone.status\n attr[\"schedule_count\"] = len(self._zone.schedules)\n attr[CONF_SCHEDULES] = \"\"\n attr[\"adjustment\"] = str(self._zone.adjustment)\n current = self._zone.runs.current_run\n if current is not None:\n if current.schedule is not None:\n attr[ATTR_CURRENT_SCHEDULE] = current.schedule.index + 1\n attr[ATTR_CURRENT_NAME] = current.schedule.name\n if current.is_sequence and current.sequence.adjustment.has_adjustment:\n attr[ATTR_CURRENT_ADJUSTMENT] = str(current.sequence.adjustment)\n else:\n attr[ATTR_CURRENT_ADJUSTMENT] = str(self._zone.adjustment)\n else:\n attr[ATTR_CURRENT_SCHEDULE] = RES_MANUAL\n attr[ATTR_CURRENT_NAME] = RES_MANUAL\n attr[ATTR_CURRENT_ADJUSTMENT] = \"None\"\n attr[ATTR_CURRENT_START] = dt.as_local(current.start_time)\n attr[ATTR_CURRENT_DURATION] = str(current.duration)\n attr[ATTR_TIME_REMAINING] = str(current.time_remaining)\n attr[ATTR_PERCENT_COMPLETE] = current.percent_complete\n else:\n attr[ATTR_CURRENT_SCHEDULE] = RES_NOT_RUNNING\n attr[ATTR_PERCENT_COMPLETE] = 0\n\n next = self._zone.runs.next_run\n if next is not None:\n if next.schedule is not None:\n attr[\"next_schedule\"] = next.schedule.index + 1\n attr[\"next_name\"] = next.schedule.name\n else:\n attr[\"next_schedule\"] = RES_MANUAL\n attr[\"next_name\"] = RES_MANUAL\n attr[\"next_start\"] = dt.as_local(next.start_time)\n attr[\"next_duration\"] = str(next.duration)\n if next.is_sequence and next.sequence.adjustment.has_adjustment:\n attr[\"next_adjustment\"] = str(next.sequence.adjustment)\n else:\n attr[\"next_adjustment\"] = str(self._zone.adjustment)\n else:\n attr[\"next_schedule\"] = RES_NONE\n attr[ATTR_TOTAL_TODAY] = round(\n today_on_duration(self.hass, self.entity_id).total_seconds() / 60, 1\n )\n if self._zone.show_config:\n attr[\"configuration\"] = json.dumps(self._zone.as_dict(), default=str)\n if self._zone.show_timeline:\n attr[\"timeline\"] = json.dumps(self._zone.runs.as_list(), default=str)\n return attr\n","sub_path":"custom_components/irrigation_unlimited/binary_sensor.py","file_name":"binary_sensor.py","file_ext":"py","file_size_in_byte":9560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"242408965","text":"from . import cst as cst_\nfrom . import errors\nfrom mtots import util\nfrom mtots.util import dataclasses\nfrom mtots.util.dataclasses import dataclass\nfrom mtots.void import typing\nfrom mtots.void.parser import base\nfrom mtots.void.util.multimethods import multimethod\nimport contextlib\n\n\nclass Scope:\n def __init__(self, parent):\n self.parent = parent\n self.table = {}\n if parent is None:\n self.stack = []\n self.root = self\n else:\n self.stack = parent.stack\n self.root = parent.root\n\n def _parent_get(self, key):\n return self.parent[key]\n\n def __getitem__(self, key):\n if key in self.table:\n return self.table[key]\n elif self.parent is None:\n raise errors.KeyError(self.stack, f'{repr(key)} not defined')\n return self._parent_get(key)\n\n def __setitem__(self, key, value):\n if key in self.table:\n with self.push_mark(self.table[key].mark):\n raise errors.KeyError(\n self.stack, f'{repr(key)} already defined')\n self.table[key] = value\n\n def __contains__(self, key):\n return key in self.table or key in self.parent\n\n def __iter__(self):\n yield from self.table\n\n for key in self.parent:\n if key not in self.table:\n yield key\n\n def error(self, message):\n return errors.TypeError(self.stack, message)\n\n @contextlib.contextmanager\n def push_mark(self, *marks):\n self.stack.extend(marks)\n try:\n yield\n finally:\n for _ in marks:\n self.stack.pop()\n\n\nclass LambdaScope(Scope):\n \"\"\"Mostly like Scope, but local variables from parents must\n be explicitly captured.\n Further, capture variables must not be mutable.\n \"\"\"\n def _parent_get(self, key):\n node = self.parent[key]\n if isinstance(node, BaseLocalVariableDeclaration):\n if node.mutable:\n with self.push_mark(node.mark):\n raise self.error(\n f'Mutable local variable {repr(key)} cannot '\n f'be captured from lambda (capture variables '\n f'must be final)')\n capture = CaptureVariable(\n declaration=node,\n type=node.type,\n name=node.name,\n )\n self.table[key] = capture\n return capture\n else:\n return node\n\n\nclass TopMacroScope(Scope):\n \"\"\"Convert non-macro outer scope value for usage with macros\n \"\"\"\n def _parent_get(self, key):\n node = self.parent[key]\n if isinstance(node, Metadata):\n return node.value\n else:\n raise self.error(\n f'Non-metadata in macros not yet supported ({node})')\n\n\nclass InnerMacroScope(Scope):\n pass\n\n\nclass Type:\n def usable_as(self, other_type):\n return self is other_type\n\n def is_object_type(self):\n return False\n\n def is_primitive_type(self):\n return isinstance(self, PrimitiveType)\n\n def is_function_type(self):\n return isinstance(self, FunctionType)\n\n\n@typing.enforce\n@dataclass(frozen=True)\nclass PrimitiveType(Type):\n name: str\n\n def __str__(self):\n return f'(primitive-type {self.name})'\n\n\nVOID = PrimitiveType('void')\nBOOL = PrimitiveType('bool')\nINT = PrimitiveType('int')\nDOUBLE = PrimitiveType('double')\nSTRING = PrimitiveType('string')\n\n\n@typing.enforce\n@dataclass(frozen=True)\nclass FunctionType(Type):\n return_type: Type\n parameter_types: typing.Tuple[Type, ...]\n\n\n@typing.enforce\n@util.dataclass(frozen=True)\nclass PrimitiveOperator:\n name: str\n method_name: str\n types: typing.Tuple[PrimitiveType, ...]\n return_type: Type\n\n_PRIMITIVE_OPERATORS = tuple(\n PrimitiveOperator(name, method_name, tuple(types), return_type)\n for name, method_name, types, return_type in [\n ('int==int', '__eq__', [INT, INT], BOOL),\n ('double==int', '__eq__', [DOUBLE, INT], BOOL),\n ('int==double', '__eq__', [INT, DOUBLE], BOOL),\n ('double==double', '__eq__', [DOUBLE, DOUBLE], BOOL),\n\n ('int**int', '__pow__', [INT, INT], INT),\n ('double**int', '__pow__', [DOUBLE, INT], DOUBLE),\n ('int**double', '__pow__', [INT, DOUBLE], DOUBLE),\n ('double**double', '__pow__', [DOUBLE, DOUBLE], DOUBLE),\n\n ('int\", moment_of_inertia_of_angular_pipe)\n TOP.geometry(\"400x400\")\n TOP.configure(background=\"#307678\")\n TOP.title(\"Moment Calculator\")\n TOP.resizable(width=False, height=False)\n LABLE = Label(TOP, bg=\"#307678\", text=\"Welcome to Moment Calculator\", font=(\"Helvetica\", 15, \"bold\"), pady=10)\n LABLE.place(x=55, y=0)\n LABLE1 = Label(TOP, bg=\"#cef0f1\", text=\"Enter radius_1:\", bd=6,\n font=(\"Helvetica\", 10, \"bold\"), pady=5)\n LABLE1.place(x=55, y=60)\n ENTRY1 = Entry(TOP, bd=8, width=6, font=\"Roboto 11\")\n ENTRY1.place(x=240, y=60)\n LABLE2 = Label(TOP, bg=\"#cef0f1\", text=\"Enter radius_2:\", bd=6,\n font=(\"Helvetica\", 10, \"bold\"), pady=5)\n LABLE2.place(x=55, y=121)\n ENTRY2 = Entry(TOP, bd=8, width=6, font=\"Roboto 11\")\n ENTRY2.place(x=240, y=121)\n LABLE3 = Label(TOP, bg=\"#cef0f1\", text=\"Enter mass:\", bd=6,\n font=(\"Helvetica\", 10, \"bold\"), pady=5)\n LABLE3.place(x=55, y=171)\n ENTRY3 = Entry(TOP, bd=8, width=6, font=\"Roboto 11\")\n ENTRY3.place(x=240, y=171)\n BUTTON = Button(bg=\"#2187e7\", bd=12, text=\"Moment\", padx=33, pady=15, command=moment_of_inertia_of_angular_pipe,\n font=(\"Helvetica\", 20, \"bold\"))\n BUTTON.grid(row=3, column=0, sticky=W)\n BUTTON.place(x=115, y=250)\n TOP.mainloop()","sub_path":"Moment calculator.py","file_name":"Moment calculator.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"622363838","text":"from django.conf.urls import patterns\nfrom views import *\n\nurlpatterns = patterns(\n '',\n (r'signups/$', signups),\n (r'schools/$', schools),\n (r'majors/$', majors),\n (r'numrides/$', numrides),\n (r'emails/$', emails),\n (r'current_emails/$', current_emails),\n (r'duration/$', duration),\n (r'gender/$', gender),\n (r'housing/$', housing),\n (r'paid/$', paid),\n (r'year/$', year),\n (r'payment/$', payment),\n (r'waived/$', waived),\n (r'checkouts/$', checkouts),\n (r'dump/$', dump),\n)\n","sub_path":"penncycle/stats/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"630746679","text":"from WMCore.Configuration import Configuration\n\nconfig = Configuration()\n\nconfig.section_('General')\nconfig.General.requestName = 'PASingleMuon_PARun2016B_PromptReco_v1_ZMMfilter_FOREST'\nconfig.General.transferLogs = False\n\nconfig.section_('JobType')\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.psetName = 'runForestAOD_pPb_DATA_80X_ZMMfilter.py'\n# forest_CMSSW_8_0_22\n# https://github.com/CmsHI/cmssw/commit/8e55358ae9a5842cb986078b5db42fac7e5b95ad\n# runForestAOD_pPb_DATA_80X.py commit + Zmm filter\n# https://github.com/CmsHI/cmssw/commit/5f80b18a63a6006b1e2d2773baa213c88705a5d0\n\nconfig.section_('Data')\nconfig.Data.inputDataset = '/PASingleMuon/PARun2016B-PromptReco-v1/AOD'\nconfig.Data.inputDBS = 'global'\n# related : https://hypernews.cern.ch/HyperNews/CMS/get/hi-general/3581.html\n# /afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions16/13TeV/HI/Cert_285090-285383_HI5TeV_PromptReco_Collisions16_JSON_noL1T_MuonPhys.txt\nconfig.Data.lumiMask = 'Cert_285090-285383_HI5TeV_PromptReco_Collisions16_JSON_noL1T_MuonPhys.txt'\n#config.Data.runRange = '263233-263284'\nconfig.Data.splitting = 'FileBased'\nconfig.Data.unitsPerJob = 10\nconfig.Data.totalUnits = -1\nconfig.Data.publication = False\nconfig.Data.outputDatasetTag = 'PARun2016B_PromptReco_v1_ZMMfilter_FOREST'\nconfig.Data.outLFNDirBase = '/store/user/katatar/'\n\n# https://github.com/richard-cms/production/commits/2016-03-17-reRECO-foresting/crabConfig.py\nconfig.section_('Site')\nconfig.Site.storageSite = \"T2_US_MIT\"\n#config.Site.whitelist = [\"T2_US_MIT\", \"T2_US_Vanderbilt\"]\n","sub_path":"data/HIRun2016PA/PASingleMuon_PARun2016B_PromptReco_v1_ZMMfilter/crabConfig_FOREST.py","file_name":"crabConfig_FOREST.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"623536012","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2021/7/1 16:56\n# @Author : Leanper\n# @File : 创建读取excel.py\n# @Software: PyCharm\n# @Desc:\n\n\nimport openpyxl\n\n\nfile_1 = openpyxl.load_workbook('studyexcel.xlsx')\nfile_1.create_sheet('表单三')\nsheet2 = file_1.get_sheet_by_name('表单2')\nprint(sheet2)\n\nfile_1.close()\n\n","sub_path":"python/study/文件处理/excel/创建读取excel.py","file_name":"创建读取excel.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134727668","text":"'''\nCreated on Jul 19, 2012\n\n@author: zouf\n'''\n#from photos.models import BusinessPhoto\nfrom api.authenticate import get_default_user\nfrom api.models import Business, BusinessRating, BusinessTopic, BusinessType, \\\n BusinessCache, Type, BusinessTopicRating, UserTopic, UserCache, Topic\nfrom api.photos import get_photo_id, get_photo_url_medium, get_photo_url_large\nfrom api.ratings import getBusinessRatings, getBusAverageRating\nfrom decimal import getcontext, Decimal\nfrom django.contrib.auth.models import User\nfrom django.db.models.aggregates import Avg\nfrom recommendation.recengine import get_best_current_recommendation, \\\n get_recommendation_by_topic, get_node_average, get_main_node_average, get_average_simple\nimport api.json_serializer as topic_type_serializer\nimport json\nimport logging\nimport operator\nimport time\n\n#TODO put this in a constants file\nNUM_STARRED_RESULTS = 3\nlogger = logging.getLogger(__name__)\n\n \n\n\ndef test_serializer():\n b = Business.objects.filter(state='NJ')\n filtered =b.select_related('metadata').prefetch_related('businesstopic', 'businesstype','businesstopic__bustopicrating','businesstopic__topic', 'businesstopic__topic__children')\n newlist = []\n for i in range(0,filtered.count()):\n f = filtered[i]\n newlist.append(f)\n\n t = Topic.objects.get(descr='Main')\n res = get_average_simple(b,user) #get_main_node_average(newlist[0],t.id,get_default_user())\n\ndef get_bus_data_ios(business_list, user,detail=False):\n data = dict()\n data['businesses'] = []\n filtered = business_list.select_related('metadata').prefetch_related('businesstopic', 'businesstype','businesstopic__bustopicrating','businesstopic__topic', 'businesstopic__topic__children')\n newlist = []\n for i in range(0,filtered.count()):\n newlist.append(filtered[i])\n\n for b in newlist:\n logger.debug('BUSINESS IS ' + str(b) + ' + ID IS ' + str(b.id))\n d = get_single_bus_data_ios(b, user,detail=detail)\n data['businesses'].append(d)\n \n newlist = sorted(data['businesses'],key=lambda bus: bus['ratingRecommendation'],reverse=True)\n \n i = 0\n for e in newlist:\n if i < NUM_STARRED_RESULTS:\n e['starred'] =True\n i += 1\n data['businesses'] = newlist\n data['userPreferences'] = topic_type_serializer.get_usertopic_data(user)\n return data\n\n\ndef get_all_nearby(mylat,mylng,distance=1):\n\n current_pg_point = \"point '({:.5f}, {:.5f})'\".format(mylng, mylat)\n buses_query = \" \".join([\"SELECT *\",\n \"FROM (SELECT id, (point(lon, lat) <@> {}) AS dist FROM ratings_business) AS dists\",\n \"WHERE dist <= {:4f} ORDER BY dist ASC;\"]).format(current_pg_point, distance)\n buses = Business.objects.raw(buses_query)\n return buses\n\n\n#isSideBar is true if we're using small images\ndef get_single_bus_data_ios(b, user,detail):\n \n d = dict()\n try:\n cache= b.businesscache.cachedata\n d = json.loads(cache)\n logger.debug('cached ' + str(b.name))\n\n except Exception as e:\n logger.debug('exception ' + str(e))\n #now we just grab the related data\n bustypes = b.businesstype.all()\n #bustopics = b.businesstopic.all()\n \n d['businessID'] = b.id\n d['businessName'] = b.name\n \n d['latitude'] = b.lat\n d['longitude'] = b.lon\n \n d['businessCity'] = b.city\n d['businessState'] = b.state\n d['streetAddr'] = b.address\n d['zipcode'] = b.zipcode\n d['businessPhone'] = b.phone\n \n if b.metadata:\n d['businessHours'] = b.metadata.hours #TODO Set hours\n d['averagePrice'] = b.metadata.average_price #TODO Set hours\n d['servesAlcohol'] = b.metadata.serves #TODO Set hours\n d['hasWiFi'] = b.metadata.wifi #TODO Set hours\n d['businessURL'] = b.url #TODO Set URL\n \n d['photo'] = get_photo_id(b)\n \n #d['ratingOverAllUsers'] = getBusAverageRating(b)\n d['types'] = topic_type_serializer.get_bustypes_data(bustypes,user)\n \n d['health_info'] = topic_type_serializer.get_health_info(b.metadata)\n \n d['photoMedURL'] = get_photo_url_medium(b)\n # \n d['photoLargeURL'] = get_photo_url_large(b)\n \n BusinessCache.objects.create(cachedata=json.dumps(d),business=b)\n \n\n #does caching internally \n d['ratingRecommendation'] = \"%.2f\" % get_recommendation_by_topic(b, user) \n if detail: \n try:\n #try to get a cached version!\n cache = UserCache.objects.get(user=user,business=b)\n cachedata = json.loads(cache.cachedata)\n d['categories'] = cachedata['categories'] \n logger.debug('Used cached user data')\n except:\n u = User.objects.filter(id=user.id).prefetch_related('usertopic_set__topic').select_related()[0]\n cachedata = {} \n d['categories'] = topic_type_serializer.get_bustopics_data(b.businesstopic.all(),u,detail=True)\n cachedata['categories'] = d['categories']\n UserCache.objects.create(cachedata=json.dumps(cachedata),user=user,business=b)\n\n # if the business has this attribute et (from some other calculation) then use it\n if hasattr(b, 'distance'):\n d['distanceFromCurrentUser'] = \"%.2f\" % b.distance.mi\n else:\n #calculate it\n dist = b.get_distance(user)\n if dist is not None:\n d['distanceFromCurrentUser'] = \"%.2f\" % dist.miles\n else:\n d['distanceFromCurrentUser'] = str(-1)\n return d\n","sub_path":"api/business_serializer.py","file_name":"business_serializer.py","file_ext":"py","file_size_in_byte":5652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"584048571","text":"import os.path\nfrom argparse import ArgumentParser\n\nfrom tensorflow.python.keras.models import load_model\nfrom tqdm import tqdm\n\nfrom baseline_model.data_helpers import *\nfrom baseline_model.tokenizer import Tokenizer\n\n\ndef parse_args():\n parser = ArgumentParser()\n parser.add_argument(\"input_path\", help=\"The path of the input file\")\n parser.add_argument(\"output_path\", help=\"The path of the output file\")\n parser.add_argument(\"resources_path\", help=\"The path of the resources needed to load your model\")\n\n return parser.parse_args()\n\n\ndef predict(input_path, output_path, resources_path):\n \"\"\"\n This is the skeleton of the prediction function.\n The predict function will build your model, load the weights from the checkpoint and write a new file (output_path)\n with your predictions in the BIES format.\n \n The resources folder should contain everything you need to make the predictions. It is the \"resources\" folder in your submission.\n \n N.B. DO NOT HARD CODE PATHS IN HERE. Use resource_path instead, otherwise we will not be able to run the code.\n\n :param input_path: the path of the input file to predict.\n :param output_path: the path of the output file (where you save your predictions)\n :param resources_path: the path of the resources folder containing your model and stuff you might need.\n :return: None\n \"\"\"\n\n # load tokenizer\n tokenizer_path = os.path.join(resources_path, 'dict.pic')\n tokenizer = Tokenizer(verbose=True)\n tokenizer.load(tokenizer_path)\n\n # load model\n model_path = os.path.join(resources_path, 'model.h5')\n model = load_model(model_path)\n # model.summary()\n\n # load test sentences\n tst_snts = read_sentences([input_path])\n x_uni_tst, x_bi_tst = process_sentences(tst_snts, tokenizer)\n\n # predict\n predictions = []\n batch_size = 32\n steps = int(len(x_uni_tst) / batch_size)\n for uni_b, bi_b in tqdm(test_data_generator([x_uni_tst, x_bi_tst], batch_size),\n desc='Predict Loop', total=steps):\n p = model.predict([uni_b, bi_b])\n # get label for each character\n p = np.argmax(p, axis=2)\n\n predictions.extend(p.tolist())\n\n # remove padding\n predictions = remove_padding(predictions, tst_snts)\n # convert to list of strings\n predictions = [''.join(map(str, p)) for p in predictions]\n # convert to BIES format\n predictions = [p.replace('1', 'B').replace('2', 'I').\n replace('3', 'E').replace('4', 'S').replace('0', 'S')\n for p in predictions]\n # write predictions to output file\n with open(output_path, 'w') as f:\n f.writelines('\\n'.join(predictions))\n\n\ndef remove_padding(predictions, sentences):\n _p = []\n for p, s in zip(predictions, sentences):\n _p.append(p[:len(s)])\n\n return _p\n\n\nif __name__ == '__main__':\n args = parse_args()\n predict(args.input_path, args.output_path, args.resources_path)\n","sub_path":"baseline_model/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"288555226","text":"import os\nimport re\n\nfile_path = os.path.join(\"Resources\", \"paragraph_1.txt\")\nwith open (file_path, \"r\") as myfile:\n paragraph=myfile.read()\n\n #first, lets repalce new line to form one paragraph\n paragraph = paragraph.replace('\\n', \" \")\n\n #now, create a list of words\n word = paragraph.split(\" \") \n word_count = len(word)\n ltr_count = 0\n\n #the, count letters by looping over all words to skip white spaces\n for x in range(len(word)):\n ltr_count += len(word[x])\n\n #finally use regular expression to split paragraph by finding . or ? or !\n sentence = re.split(\"(?<=[.!?]) +\", str(paragraph))\n sentence_count = len(sentence)\n avg_sent_lth = round(word_count/sentence_count,1)\n avg_ltr_cnt = round(ltr_count/word_count,1)\noutput = []\noutput.append(\"Paragraph Analysis\")\noutput.append(\"-----------------\")\noutput.append(f'Approximate Word Count: {word_count}')\noutput.append(f'Approximate Sentence Count: {sentence_count}')\noutput.append(f'Average Letter Count: {avg_ltr_cnt}')\noutput.append(f'Average Sentence Length: {avg_sent_lth}')\noutput = '\\n'.join(output)\nprint(output)\nwith open('Output/PyParagraph_output.txt', 'w') as txtfile:\n txtfile.write(str(output))\n \n","sub_path":"PyParagraph.py","file_name":"PyParagraph.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"39435524","text":"import graphics as gr\nimport random\n\nw = 800\nh = 600\n\n\ndef cloud(w1, h1, r):\n circle1 = gr.Circle(gr.Point(w1, h1), r)\n circle2 = gr.Circle(gr.Point(w1 + r, h1), r)\n circle3 = gr.Circle(gr.Point(w1 + 3 * r / 2, h1 + r / 2), r)\n circle4 = gr.Circle(gr.Point(w1 + r / 2, h1 + r / 2), r)\n circle5 = gr.Circle(gr.Point(w1 - r / 2, h1 + r / 2), r)\n circle1.setFill('white')\n circle2.setFill('white')\n circle3.setFill('white')\n circle4.setFill('white')\n circle5.setFill('white')\n circle1.draw(window)\n circle2.draw(window)\n circle3.draw(window)\n circle4.draw(window)\n circle5.draw(window)\n\n\ndef wheel(cx, cy, r1, r2):\n circle1 = gr.Circle(gr.Point(cx, cy), r2)\n circle1.setFill('black')\n circle2 = gr.Circle(gr.Point(cx, cy), r1)\n circle2.setFill('gray')\n circle1.draw(window)\n circle2.draw(window)\n\n\n\nwindow = gr.GraphWin(\"Jenkslex and Ganzz project\", w, h)\n\nsky = gr.Rectangle(gr.Point(0, 0), gr.Point(w, h/2))\nsky.setFill('blue')\n\nground = gr.Rectangle(gr.Point(0, h/2), gr.Point(w, h))\nground.setFill('green')\n\nsky.draw(window)\nground.draw(window)\n\nsun = gr.Circle(gr.Point(700, 50), 40)\nsun.setFill('yellow')\nsun.draw(window)\n\ncloudx1 = 100\ncloudy1 = 20\ncloud_distance = 30\nn = 8\n\nfor i in range(1, n):\n cloud(cloudx1 * i, cloudy1 + random.randint(1, 600) / 100 * cloud_distance, 20)\n\ncorp = gr.Polygon(gr.Point(290, 490), gr.Point(290, 405), gr.Point(340, 405), gr.Point(350, 445), gr.Point(405, 445), gr.Point(405, 490), gr.Point(300, 490))\ncorp.setFill('red')\ncorp.draw(window)\n\nwind = gr.Polygon(gr.Point(295, 445), gr.Point(295, 410), gr.Point(335, 410), gr.Point(343.75, 445), gr.Point(295, 445))\nwind.setFill('green')\nwind.draw(window)\n\nline1 = gr.Line(gr.Point(295, 445), gr.Point(295, 490))\nline1.setFill('black')\nline1.draw(window)\n\nline2 = gr.Line(gr.Point(343.75, 445), gr.Point(343.75, 490))\nline2.setFill('black')\nline2.draw(window)\n\nhandle = gr.Rectangle(gr.Point(330, 450), gr.Point(340, 453))\nhandle.setFill('black')\nhandle.draw(window)\n\nwheel(300, 485, 20, 30)\nwheel(400, 500, 10, 15)\n\ntree = gr.Rectangle(gr.Point(700, 250), gr.Point(720, 450))\ntree.setFill('brown')\ntree.draw(window)\n\nleaflayer1 = gr.Polygon(gr.Point(650, 400), gr.Point(710, 320), gr.Point(770, 400))\nleaflayer1.setFill('darkgreen')\nleaflayer1.draw(window)\n\nleaflayer2 = gr.Polygon(gr.Point(670, 350), gr.Point(710, 270), gr.Point(750, 350))\nleaflayer2.setFill('darkgreen')\nleaflayer2.draw(window)\n\nleaflayer3 = gr.Polygon(gr.Point(675, 320), gr.Point(710, 220), gr.Point(745, 320))\nleaflayer3.setFill('darkgreen')\nleaflayer3.draw(window)\n\nhouse = gr.Rectangle(gr.Point(20, 250), gr.Point(120, 350))\nhouse.setFill('gray')\nhouse.draw(window)\n\nroof = gr.Polygon(gr.Point(20, 250), gr.Point(70, 200), gr.Point(120, 250))\nroof.setFill('brown')\nroof.draw(window)\n\nwind1 = gr.Rectangle(gr.Point(50, 280), gr.Point(90, 320))\nwind1.setFill('yellow')\nwind1.draw(window)\n\nwline1 = gr.Line(gr.Point(70, 280), gr.Point(70, 320))\nwline1.setWidth(3)\nwline1.draw(window)\n\nwline2 = gr.Line(gr.Point(50, 300), gr.Point(90, 300))\nwline2.setWidth(3)\nwline2.draw(window)\n\nwindow.getMouse()\n\nwindow.close()","sub_path":"lab3/task 1.py","file_name":"task 1.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"575347512","text":"\"\"\"\nTic-Tac-Toe game!\n\nThe board will look like this:\n\n 0 1 2\n0| | | |\n -------\n1| | | |\n -------\n2| | | |\n\nPlayers make their selection by entering a row (1 - 3) and column (A - C).\n\"\"\"\nimport string\n\n\ndef get_players():\n\tprint()\n\tprint(\"*************************\")\n\tprint(\"*WELCOME TO TIC-TAC-TOE!*\")\n\tprint(\"*************************\")\n\tprint()\n\n\tprint()\n\n\tplayer_1 = input(\"Enter Player 1 name: \")\n\n\tplayer_2 = input(\"Enter Player 2 name: \")\n\n\tplayers = (player_1, player_2)\n\t\n\treturn players\n\n\n\ndef draw_board(board):\n\t\"\"\"\n\tDraw the tictactoe board using values in 'board'\n\t\"\"\"\n\tprint()\n\t\n\tprint(\" 0 1 2\")\n\n\tfor row in range(0,3):\n\t\tprint(str(row) + \"|\",end=\"\")\n\n\t\tfor col in range(0,3):\n\t\t\tif col == 2:\n\t\t\t\tprint(board[row][col] + \"|\")\n\n\t\t\telse:\n\t\t\t\tprint(board[row][col] + \"|\",end=\"\")\n\n\t\tprint(\" -------\")\n\n\ndef player_turn(players, turn):\n\tselection = input(\"{}'s turn. Enter row(0-2) and col(0-2): \".\\\n\tformat(players[turn]))\n\n\tif turn == 0:\n\t\tvalue = \"X\"\n\n\telse:\n\t\tvalue = \"O\"\n\n\trow = int(selection[0])\n\n\tcol = int(selection[1])\n\n\treturn row, col, value\n\n\t\ndef update_board(board, row, col, value):\n\t\"\"\"\n\tSet the value of a square in the tic-tac-toe board\n\t\"\"\"\n\n\t# if there's already a value in the selected square:\n\tif board[row][col] != ' ':\n\t\tprint(\"Invalid selection, please try again.\")\n\n\telse:\n\t\tboard[row][col] = value\n\n\treturn board\n\ndef check_board(board):\n\t\"\"\"\n\tCheck for three in a row or full board\n\t\"\"\"\n\t\n\t# if non blank three in a row \n\tif (board[0][0] == board[0][1] == board[0][2] and board[0][0] != \" \") \\\n\tor (board[1][0] == board[1][1] == board[1][2] and board[1][0] != \" \") \\\n\tor (board[2][0] == board[2][1] == board[2][2] and board[2][0] != \" \") \\\n\tor (board[0][0] == board[1][1] == board[2][2] and board[0][0] != \" \") \\\n\tor (board[0][2] == board[1][1] == board[1][0] and board[0][2] != \" \") \\\n\tor (board[0][0] == board[1][0] == board[2][0] and board[0][0] != \" \") \\\n\tor (board[0][1] == board[1][1] == board[2][1] and board[0][1] != \" \") \\\n\tor (board[0][2] == board[1][2] == board[2][2] and board[0][2] != \" \"):\n\t\treturn \"win\"\n\n\n\t# if board has one or more blank squares\n\tfor row in range(0,len(board)):\n\t\tfor col in range(0,len(board[row])):\n\t\t\tif board[row][col] == \" \":\n\t\t\t\treturn \"cont\"\n\n\t# if no blank and no win\n\treturn \"tie\"\n\nwhile True:\n\n\tboard = [[\" \",\" \",\" \"],\n\t [\" \",\" \",\" \"],\n\t [\" \",\" \",\" \"]]\n\n\tplayers = get_players()\n\n\tdraw_board(board)\n\n\tturn = 0\n\n\twhile check_board(board) == \"cont\":\n\n\t\tcurr_turn = turn\n\n\t\tselection = player_turn(players, turn)\n\n\t\trow = selection[0]\n\n\t\tcol = selection[1]\n\n\t\tvalue = selection[2]\n\n\t\tboard = update_board(board, row, col, value)\n\n\t\tdraw_board(board)\n\n\t\tif turn == 0:\n\t\t\tturn = 1\n\n\t\telse:\n\t\t\tturn = 0\n\n\tprint()\n\n\tprint(\"* * * G A M E O V E R ! * * *\")\n\n\tif check_board(board) == \"win\":\n\t\tprint(\"*** {} WINS! ****\".format(players[curr_turn]))\n\n\telse:\n\t\tprint(\"It's a tie!\")\n\n\t\tprint()\n\n\tresponse = input(\"Play again? (Y/N): \")\n\n\tif response.upper() != \"Y\":\n\t\tprint(\"Goodbye!\")\n\n\t\tbreak\n\n\n","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"383704452","text":"\r\n# Implement int sqrt(int x).\r\n\r\n# Compute and return the square root of x, where x is guaranteed to be a non-negative integer.\r\n\r\n# Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.\r\n\r\n# 之保留整数部分,而不是近似到最近的整数\r\n\r\nclass Solution(object):\r\n def mySqrt(self, x):\r\n \"\"\"\r\n :type x: int\r\n :rtype: int\r\n \"\"\"\r\n if x < 2: # 0, 1\r\n return x\r\n \r\n left, right = 1, x // 2 + 1\r\n while left < right:\r\n mid = (left + right) // 2\r\n if mid < x // mid:\r\n left = mid + 1\r\n else:\r\n right = mid\r\n return left if left * left <= x else left - 1\r\n\r\nclass Solution(object):\r\n def mySqrt(self, x):\r\n \"\"\"\r\n :type x: int\r\n :rtype: int\r\n \"\"\"\r\n if x < 2:\r\n return x\r\n \r\n left, right = 1, x // 2 + 1\r\n while left <= right:\r\n mid = (right + left) // 2\r\n if mid > x // mid: # since mid*mid>x, so mid definitely is not the ans,\r\n right = mid - 1 # so move right to mid-1\r\n else: # mid*mid<=x, try mid+1\r\n left = mid + 1\r\n return left - 1\r\n\r\n#class Solution:\r\n# def mySqrt(self, x):\r\n# \"\"\"\r\n# :type x: int\r\n# :rtype: int\r\n# \"\"\"\r\n# if x==0:\r\n# return x\r\n# \r\n# left, right = 1, x // 2 + 1\r\n# while left <= right: # or use while True:\r\n# mid = (right + left) // 2\r\n# if mid > x // mid: # since mid*mid>x, so mid definitely is not the ans,\r\n# right = mid - 1 # so move right to mid-1\r\n# else: \r\n# if x // (mid+1) < (mid+1): # mid*mid<=x<(mid+1)*(mid+1)\r\n# return mid\r\n# left = mid + 1 # mid*mid1e-6:\r\n# result=(result+x/result)/2.0\r\n# return int(result)\r\n \r\n#class Solution(object):\r\n# def mySqrt(self, x):\r\n# \"\"\"\r\n# :type x: int\r\n# :rtype: int\r\n# \"\"\"\r\n# if x<2:\r\n# return x\r\n# start,end=1,x//2+1\r\n# while start+10:\r\n# res |= mask # try every bit from the most significant to least significant.\r\n# if x//res < res: # curr res is too large, so use xor cancel this bit\r\n# res ^= mask\r\n# mask >>=1 # move one bit to left\r\n# return res\r\n \r\n \r\nif __name__ == \"__main__\":\r\n print(Solution().mySqrt(0))\r\n print(Solution().mySqrt(4))\r\n print(Solution().mySqrt(8))\r\n print(Solution().mySqrt(4187))\r\n print(Solution().mySqrt(2147395599))\r\n","sub_path":"69. Sqrt(x).py","file_name":"69. Sqrt(x).py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"323927300","text":"# -*- coding: utf-8 -*-\n\n\nclass AssociativeArray:\n def __init__(self, sz, stp):\n self.size = sz\n self.step = stp\n self.slots = [None] * self.size\n self.values = [None] * self.size\n\n def _hash_fun(self, key):\n res = 0\n for i in key:\n res += ord(i)\n return res % self.size\n\n def put(self, key, value):\n hash_key = self.find(key)\n if self.slots[hash_key] is None:\n self.slots[hash_key] = key\n self.values[hash_key] = value\n\n def is_key(self, key):\n hash_key = self.find(key)\n if hash_key is not None:\n if self.slots[hash_key] == key:\n return True\n return False\n\n def get(self, key):\n hash_key = self.find(key)\n if hash_key is not None:\n return self.values[hash_key]\n return None\n\n def _seek_slot(self, key):\n hash_key = self._hash_fun(key)\n limit = self.step * (self.size // self.step)\n while self.slots[hash_key] is not None and limit > 0:\n if self.slots[hash_key] is key:\n return hash_key\n hash_key = (hash_key + self.step) % self.size\n limit -= 1\n if limit == 0:\n return None\n return hash_key\n\n def find(self, key):\n return self._seek_slot(key)\n\n\ndef test_hash_func():\n hs = AssociativeArray(17, 3)\n print()\n assert hs._hash_fun('1') == 15\n\n\ndef test_put():\n hs = AssociativeArray(17, 3)\n\n hs.put('12', 1)\n hs.put('21', 2)\n\n hs_test_slots = [None] * 17\n hs_test_values = [None] * 17\n hs_test_slots[14] = '12'\n hs_test_values[14] = 1\n hs_test_slots[0] = '21'\n hs_test_values[0] = 2\n assert hs.size == len(hs_test_slots) == len(hs_test_values)\n\n for i, i_v, t_i, t_i_v in zip(hs.slots, hs.values, hs_test_slots, hs_test_values):\n assert i == t_i\n assert i_v == t_i_v\n\n\ndef test_is_key():\n hs = AssociativeArray(17, 3)\n\n hs.put('12', 1)\n hs.put('21', 2)\n\n assert hs.is_key('12')\n assert hs.is_key('21')\n assert not hs.is_key('1')\n\n\ndef test_get():\n hs = AssociativeArray(17, 3)\n\n hs.put('12', 1)\n hs.put('21', 2)\n\n assert hs.get('12') == 1\n assert hs.get('21') == 2\n assert hs.get('1') is None\n\n\ndef test_seek():\n hs = AssociativeArray(17, 3)\n\n hs.put('12', 1)\n hs.put('21', 2)\n\n assert hs._seek_slot('12') == 14\n assert hs._seek_slot('21') == 0\n\n\nif __name__ == '__main__':\n test_hash_func()\n test_put()\n test_seek()\n test_is_key()\n test_get()\n","sub_path":"associative_array.py","file_name":"associative_array.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"94953462","text":"import sqlite3\n\nfrom aiohttp.web import Application\nfrom aiohttp.web import post\nfrom telegram.ext import Dispatcher\n\nfrom db.utils import check_db\nfrom .handlers import WebHookHandler\n\n\nasync def init_db(app):\n db = sqlite3.connect(app['db_name'], check_same_thread=False)\n db.row_factory = sqlite3.Row\n check_db(db)\n app['dispatcher'].bot.db = db\n\n\nasync def close_dispatcher(app):\n app['dispatcher'].bot.db.close()\n app['dispatcher'].stop()\n\n\nasync def make_app(dispatcher: Dispatcher) -> Application:\n handler = WebHookHandler(dispatcher)\n\n app = Application(logger=dispatcher.bot.logger)\n app.add_routes([\n post('/', handler.handle_payload),\n ])\n\n app['db_name'] = 'database.db'\n app['dispatcher'] = dispatcher\n\n app.on_startup.append(init_db)\n app.on_cleanup.append(close_dispatcher)\n\n return app\n","sub_path":"web/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"215086706","text":"# workarounds\n\nHACK_need_init = [ 'bNES', 'gambatte', 'SNES9x' ]\nHACK_need_audio_sample_batch = [ 'FCEUmm', 'gambatte', 'Genesis Plus GX', 'SNES9x', 'VBA Next' ]\nHACK_need_audio_sample = [ 'bNES', 'bSNES', 'Meteor GBA' ]\n\n\n# constants\n\nDEVICE_MASK = 0xff\n\nDEVICE_NONE = 0\nDEVICE_JOYPAD = 1\nDEVICE_MOUSE = 2\nDEVICE_KEYBOARD = 3\nDEVICE_LIGHTGUN = 4\nDEVICE_ANALOG = 5\n\nDEVICE_JOYPAD_MULTITAP = ((1 << 8) | DEVICE_JOYPAD)\nDEVICE_LIGHTGUN_SUPER_SCOPE = ((1 << 8) | DEVICE_LIGHTGUN)\nDEVICE_LIGHTGUN_JUSTIFIER = ((2 << 8) | DEVICE_LIGHTGUN)\nDEVICE_LIGHTGUN_JUSTIFIERS = ((3 << 8) | DEVICE_LIGHTGUN)\n\nDEVICE_ID_JOYPAD_B = 0\nDEVICE_ID_JOYPAD_Y = 1\nDEVICE_ID_JOYPAD_SELECT = 2\nDEVICE_ID_JOYPAD_START = 3\nDEVICE_ID_JOYPAD_UP = 4\nDEVICE_ID_JOYPAD_DOWN = 5\nDEVICE_ID_JOYPAD_LEFT = 6\nDEVICE_ID_JOYPAD_RIGHT = 7\nDEVICE_ID_JOYPAD_A = 8\nDEVICE_ID_JOYPAD_X = 9\nDEVICE_ID_JOYPAD_L = 10\nDEVICE_ID_JOYPAD_R = 11\nDEVICE_ID_JOYPAD_L2 = 12\nDEVICE_ID_JOYPAD_R2 = 13\nDEVICE_ID_JOYPAD_L3 = 14\nDEVICE_ID_JOYPAD_R3 = 15\n\n\nDEVICE_INDEX_ANALOG_LEFT = 0\nDEVICE_INDEX_ANALOG_RIGHT = 1\nDEVICE_ID_ANALOG_X = 0\nDEVICE_ID_ANALOG_Y = 1\n\nDEVICE_ID_MOUSE_X = 0\nDEVICE_ID_MOUSE_Y = 1\nDEVICE_ID_MOUSE_LEFT = 2\nDEVICE_ID_MOUSE_RIGHT = 3\n\nDEVICE_ID_LIGHTGUN_X = 0\nDEVICE_ID_LIGHTGUN_Y = 1\nDEVICE_ID_LIGHTGUN_TRIGGER = 2\nDEVICE_ID_LIGHTGUN_CURSOR = 3\nDEVICE_ID_LIGHTGUN_TURBO = 4\nDEVICE_ID_LIGHTGUN_PAUSE = 5\nDEVICE_ID_LIGHTGUN_START = 6\n\nREGION_NTSC = 0\nREGION_PAL = 1\n\nMEMORY_MASK = 0xff\nMEMORY_SAVE_RAM = 0\nMEMORY_RTC = 1\nMEMORY_SYSTEM_RAM = 2\nMEMORY_WRAM = 2 # backwards compat\nMEMORY_VIDEO_RAM = 3\n\nMEMORY_SNES_BSX_RAM = ((1 << 8) | MEMORY_SAVE_RAM)\nMEMORY_SNES_BSX_PRAM = ((2 << 8) | MEMORY_SAVE_RAM)\nMEMORY_SNES_SUFAMI_TURBO_A_RAM = ((3 << 8) | MEMORY_SAVE_RAM)\nMEMORY_SNES_SUFAMI_TURBO_B_RAM = ((4 << 8) | MEMORY_SAVE_RAM)\nMEMORY_SNES_GAME_BOY_RAM = ((5 << 8) | MEMORY_SAVE_RAM)\nMEMORY_SNES_GAME_BOY_RTC = ((6 << 8) | MEMORY_RTC)\n\nGAME_TYPE_BSX = 0x101\nGAME_TYPE_BSX_SLOTTED = 0x102\nGAME_TYPE_SUFAMI_TURBO = 0x103\nGAME_TYPE_SUPER_GAME_BOY = 0x104\n\nENVIRONMENT_SET_ROTATION = 1\nENVIRONMENT_GET_OVERSCAN = 2\nENVIRONMENT_GET_CAN_DUPE = 3\nENVIRONMENT_GET_VARIABLE = 4\nENVIRONMENT_SET_VARIABLES = 5\nENVIRONMENT_SET_MESSAGE = 6\nENVIRONMENT_SHUTDOWN = 7\nENVIRONMENT_SET_PERFORMANCE_LEVEL = 8\nENVIRONMENT_GET_SYSTEM_DIRECTORY = 9\nENVIRONMENT_SET_PIXEL_FORMAT = 10\n\nPIXEL_FORMAT_0RGB1555 = 0\nPIXEL_FORMAT_XRGB8888 = 1\n\n# backwards compat:\nPORT_1 = 0\nPORT_2 = 1\n\n","sub_path":"cy_retro/retro_globals.py","file_name":"retro_globals.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"364157844","text":"class Solution:\n def maxProfit(self, prices):\n if not prices or len(prices) == 1:\n return 0\n minprice = prices[0]\n maxprofit = prices[1] - prices[0]\n for currentprice in prices[1:]:\n if currentprice < minprice:\n minprice = currentprice\n elif currentprice - minprice > maxprofit:\n maxprofit = currentprice - minprice\n if maxprofit < 0:\n return 0\n else:\n return maxprofit\n","sub_path":"BestTimetoBuyandSellStock/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"431960593","text":"import torch\nimport torch.nn as nn\nfrom ..function import qsigned, qunsigned\nfrom ..function.extra import SEConv2d, Adder2d, adder2d_function\nfrom .foldmodule import _FoldModule\nfrom .utils import isShiftAdder\n\n\nclass SA2dBNReLU(_FoldModule):\n def __init__(self, shiftadder, bn, relu):\n super().__init__()\n if isShiftAdder(shiftadder) and isinstance(\n bn, nn.BatchNorm2d) and (isinstance(relu, nn.ReLU)\n or isinstance(relu, nn.ReLU6)):\n self.shift = shiftadder[0]\n self.adder = shiftadder[1]\n self.bn = bn\n self.relu = nn.ReLU() if isinstance(relu, nn.ReLU) else nn.ReLU6()\n self.bn_weight(bn)\n self.adder_weight(shiftadder[1])\n self.acti_bit_width = relu.acti_bit_width\n self.acti_log2_t = relu.acti_log2_t\n self.bn_freezing = False\n self.quant = False\n\n def adder_weight(self, adder):\n self.adder_weight_bit_width = adder.weight_bit_width\n self.adder_weight_log2_t = adder.weight.abs().max().detach().data.log2(\n )\n\n def bn_weight(self, bn):\n bn_var = bn.running_var.detach().clone().data.reshape(-1, 1, 1, 1)\n bn_mean = bn.running_mean.detach().clone().data.reshape(-1, 1, 1, 1)\n bn_weight = bn.weight.detach().clone().data.reshape(-1, 1, 1, 1)\n bn_bias = bn.bias.detach().clone().data.reshape(-1, 1, 1, 1)\n bn_weight = bn_weight / (bn_var + bn.eps).sqrt()\n bn_bias = bn_weight * (-bn_mean) / (bn_var + bn.eps).sqrt() + bn_bias\n self.bn_weight_bit_width = bn.weight_bit_width\n self.bn_weight_log2_t = torch.nn.Parameter(\n bn_weight.abs().max().detach().data.log2())\n self.bn_bias_bit_width = bn.bias_bit_width\n self.bn_bias_log2_t = torch.nn.Parameter(\n bn_bias.abs().max().detach().data.log2())\n\n def bn_freeze(self, mode=True):\n self.bn_freezing = mode\n\n def quantilize(self):\n self.quant = True\n self.bn_weight_log2_t.requires_grad = True\n self.adder_weight_log2_t.requires_grad = True\n self.bn_bias_log2_t.requires_grad = True\n self.acti_log2_t.requires_grad = True\n\n def floatilize(self):\n self.quant = False\n self.bn_weight_log2_t.requires_grad = False\n self.adder_weight_log2_t.requires_grad = False\n self.bn_bias_log2_t.requires_grad = False\n self.acti_log2_t.requires_grad = False\n\n def forward(self, input):\n if self.bn_freezing:\n bn_var = self.bn.running_var.detach().clone().data.reshape(\n -1, 1, 1, 1)\n bn_mean = self.bn.running_mean.detach().clone().data.reshape(\n -1, 1, 1, 1)\n bn_weight = self.bn.weight.detach().clone().data.reshape(\n -1, 1, 1, 1)\n bn_bias = self.bn.bias.detach().clone().data.reshape(-1, 1, 1, 1)\n else:\n bn_var = self.bn.running_var.reshape(-1, 1, 1, 1)\n bn_mean = self.bn.running_mean.reshape(-1, 1, 1, 1)\n bn_weight = self.bn.weight.reshape(-1, 1, 1, 1)\n bn_bias = self.bn.bias.reshape(-1, 1, 1, 1)\n bn_weight = bn_weight / (bn_var + self.bn.eps).sqrt()\n bn_bias = bn_weight * (-bn_mean) / (bn_var +\n self.bn.eps).sqrt() + bn_bias\n if self.quant and self.bn_freezing:\n adder_weight = qsigned(self.adder.weight, self.adder_weight_log2_t,\n self.adder_weight_bit_width)\n bn_weight = qsigned(bn_weight, self.bn_weight_log2_t,\n self.bn_weight_bit_width)\n bn_bias = qsigned(bn_bias, self.bn_bias_log2_t,\n self.bn_bias_bit_width)\n inter = self.shift(input)\n inter = adder2d_function(inter,\n adder_weight,\n stride=self.adder.stride,\n padding=self.adder.padding)\n inter = bn_weight * inter + bn_bias\n elif self.quant and self.bn_freezing == False:\n adder_weight = qsigned(self.adder.weight, self.adder_weight_log2_t,\n self.adder_weight_bit_width)\n inter = self.shift(input)\n inter = adder2d_function(inter,\n adder_weight,\n stride=self.adder.stride,\n padding=self.adder.padding)\n inter = self.bn(inter)\n else:\n inter = self.shift(input)\n inter = adder2d_function(inter, self.adder.weight,\n self.adder.stride, self.adder.padding)\n inter = self.bn(inter)\n\n inter = self.relu(inter)\n\n if self.quant:\n inter = qunsigned(inter, self.acti_log2_t, self.acti_bit_width)\n return inter\n","sub_path":"tqt/fold/sabnact.py","file_name":"sabnact.py","file_ext":"py","file_size_in_byte":4969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"579896668","text":"#!/usr/bin/env python3\n\n\"\"\"\nimport re\n\nregex = re.compile(\"[\\.\\- ]+\")\ninfilename = \"pdbtm_alpha_nr.fasta\"\noutfilename = \"pdbtm_alpha_nr_nospace.fasta\"\nwith open(infilename, 'r') as in_handle, open(outfilename, 'w') as out_handle:\n for l in in_handle:\n print(l)\n # l = l.strip()\n #out_handle.write(regex.sub(\"\", l))\n\n\"\"\"\n\nfrom Bio import SeqIO\n\nw_handle = open(\"pdbtm_alpha_redundant_nospace_nonewline.fasta\", 'w')\n\nwith open(\"pdbtm_alpha_redundant.seq\", 'rU') as r_handle:\n for record in SeqIO.parse(r_handle, \"fasta\"):\n seq = str(record.seq)\n w_handle.write('>'+record.id+\"\\n\"+seq+\"\\n\")\n\nw_handle.close()","sub_path":"fasta_trim.py","file_name":"fasta_trim.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"422690339","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport binascii, logging, os, sys\nfrom rest_framework.authtoken.models import Token\nfrom django.contrib.auth.models import User\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.core.exceptions import ObjectDoesNotExist, ValidationError\n\nlogger = logging.getLogger('project_logging')\n\nclass Command(BaseCommand):\n help = \"\"\"Set specific token for user.\n\n If user does not exist, creates user.first.\n \"\"\"\n\n def add_arguments(self, parser):\n parser.add_argument('username')\n parser.add_argument('token')\n \n\n def handle(self, *args, **options):\n try:\n u = User.objects.get(username=options['username'])\n\n except ObjectDoesNotExist:\n u = User()\n u.username = options['username']\n u.set_password(options['token'])\n u.full_clean()\n u.save()\n\n try:\n if not hasattr(u, 'auth_token'):\n logger.info('Create token here')\n t = Token(user=u, key=options['token'])\n t.full_clean()\n t.save()\n \n t = u.auth_token\n logger.info('Prev token: {}, {}'.format(u.username, t.key))\n \n t.delete()\n t = Token(user=u, key=options['token'])\n t.full_clean()\n t.save()\n logger.info('New token: {}, {}'.format(u.username, t.key))\n\n except ValidationError as e:\n sys.stderr.write('{}\\n'.format(e.messages))\n\n# vim: ai et ts=4 sw=4 sts=4 ru nu\n","sub_path":"chap04_restapi/restapi_project/aws_bucket_app/management/commands/set_client_token.py","file_name":"set_client_token.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"489652332","text":"import bs4\nimport requests\nfrom bs4 import BeautifulSoup as soup\nfrom urllib.request import urlopen as uReq\n\nfor i in range(1,5): #page loop starts at 1 and ends with 5\n my_url='https://www.aljco.com/index.php/manufacturer.html?limit=30&p={}'.format(i)\n ## opening up connection and grabbing the page\n uClient= uReq(my_url)\n page_html = uClient.read()\n uClient.close()\n ##hrml parsing\n page_soup = soup(page_html,'html.parser')\n ## find.All(what we want to find,the object or name of the tag, and name of the thing\n containers = page_soup.findAll('div',{'class':'grid_wrap'})\n\n filename = 'aljco_scrape.csv'\n f = open(filename,'a')\n headers = 'Brand, Price, Status\\n'\n f.write(headers)\n\n for container in containers:\n brand_container = container.findAll('h2',{'class':'product-name'})\n brand = brand_container[0].text.strip()\n\n price_container = container.findAll('span',{'class':'price'})\n price = price_container[0].text.strip()\n\n status_container = container.findAll('div',{'class':'desc_grid'})\n status = status_container[0].text\n\n print ('brand: ' + brand)\n print ('price:' + price)\n print ('status: ' + status)\n\n f.write(brand +',' + price+',' + status + '\\n')\n f.close()\n","sub_path":"Website Scrape to CSV.py","file_name":"Website Scrape to CSV.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"429109117","text":"import os.path\n\nfrom thryft.generator.document import Document\nfrom thryft.generators.ts._ts_named_construct import _TsNamedConstruct\nfrom yutil import indent\n\n\nclass TsDocument(Document, _TsNamedConstruct):\n def __init__(self, **kwds):\n Document.__init__(self, **kwds)\n self.__ts_path = None\n\n def _save_to_dir(self, out_dir_path):\n assert out_dir_path == self._parent_generator().ts_out_dir_path\n return self._save_to_file(self.ts_path())\n\n def _save_to_file(self, out_file_path):\n assert out_file_path == self.ts_path(), \"%s vs. %s\" % (out_file_path, self.ts_path())\n return self._save_to_file_helper(self.ts_repr(), out_file_path)\n\n def ts_path(self):\n if self.__ts_path is None:\n self.__ts_path = \\\n os.path.join(\n self._parent_generator().ts_out_dir_path,\n self.namespace_by_scope(('ts', '*')).name.replace('.', os.path.sep),\n self.name + '.ts'\n )\n return self.__ts_path\n\n def _ts_references_definition(self, **kwds):\n references = []\n for definition in self.definitions:\n references.extend(definition.ts_references_definition(**kwds))\n return references\n\n def ts_repr(self):\n definitions = \\\n \"\\n\\n\".join(definition.ts_repr()\n for definition in self.definitions)\n if len(definitions) == 0:\n return ''\n\n sections = []\n\n references = \"\\n\".join(sorted(list(set(self.ts_references_definition(self.ts_path())))))\n if len(references) > 0:\n sections.append(references)\n\n try:\n module_qname = self.namespace_by_scope(('ts', '*')).name\n definitions = indent(' ' * 4, definitions)\n definitions = \"\"\"\\\nmodule %(module_qname)s {\n%(definitions)s\n}\"\"\" % locals()\n except KeyError:\n definitions = definitions\n sections.append(definitions)\n return \"\\n\".join(sections) + \"\\n\"\n","sub_path":"compiler/src/thryft/generators/ts/ts_document.py","file_name":"ts_document.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"194046287","text":"\"\"\"Test querying with properties.\"\"\"\nfrom reasoner_transpiler.cypher import get_query\nfrom .fixtures import fixture_database\n\n\ndef test_numeric(database):\n \"\"\"Test querying with numeric property.\"\"\"\n qgraph = {\n \"nodes\": {\n \"n0\": {\n \"categories\": \"biolink:Gene\",\n \"length\": 277,\n },\n },\n \"edges\": {},\n }\n output = database.run(get_query(qgraph))\n for record in output:\n assert len(record[\"results\"]) == 1\n results = sorted(\n record[\"knowledge_graph\"][\"nodes\"].values(),\n key=lambda node: node[\"name\"],\n )\n expected_nodes = [\n \"CASP3\",\n ]\n for ind, result in enumerate(results):\n assert result[\"name\"] == expected_nodes[ind]\n\n\ndef test_string(database):\n \"\"\"Test querying with string property.\"\"\"\n qgraph = {\n \"nodes\": {\n \"n0\": {\n \"categories\": \"biolink:Gene\",\n \"chromosome\": \"17\",\n },\n },\n \"edges\": {},\n }\n output = database.run(get_query(qgraph))\n for record in output:\n assert len(record[\"results\"]) == 1\n results = sorted(\n record[\"knowledge_graph\"][\"nodes\"].values(),\n key=lambda node: node[\"name\"],\n )\n expected_nodes = [\n \"BRCA1\",\n ]\n for ind, result in enumerate(results):\n assert result[\"name\"] == expected_nodes[ind]\n\n\ndef test_bool(database):\n \"\"\"Test querying with boolean property.\"\"\"\n qgraph = {\n \"nodes\": {\n \"n0\": {\n \"categories\": \"biolink:ChemicalSubstance\",\n },\n \"n1\": {\n \"categories\": \"biolink:Disease\",\n },\n },\n \"edges\": {\n \"e01\": {\n \"subject\": \"n0\",\n \"object\": \"n1\",\n \"predicates\": \"biolink:treats\",\n \"fda_approved\": True,\n },\n },\n }\n output = database.run(get_query(qgraph))\n for record in output:\n assert len(record[\"results\"]) == 1\n results = sorted(\n record[\"knowledge_graph\"][\"nodes\"].values(),\n key=lambda node: node[\"name\"],\n )\n expected_nodes = [\n \"metformin\", \"type 2 diabetes mellitus\",\n ]\n for ind, result in enumerate(results):\n assert result[\"name\"] == expected_nodes[ind]\n\n\ndef test_publications(database):\n \"\"\"Test publications.\"\"\"\n qgraph = {\n \"nodes\": {\n \"n0\": {\n \"ids\": \"NCBIGene:836\",\n },\n \"n1\": {\n \"ids\": \"NCBIGene:841\",\n },\n },\n \"edges\": {\n \"e01\": {\n \"subject\": \"n0\",\n \"object\": \"n1\",\n },\n },\n }\n cypher = get_query(qgraph)\n output = list(database.run(cypher))[0]\n edges = output[\"knowledge_graph\"][\"edges\"]\n assert len(edges) == 1\n attributes = list(edges.values())[0][\"attributes\"]\n assert len(attributes) == 1\n assert attributes[0] == {\n \"original_attribute_name\": \"publications\",\n \"attribute_type_id\": \"EDAM:data_0971\",\n \"value\": [\"xxx\"],\n }\n\n\ndef test_constraints(database):\n \"\"\"Test querying with 'constraints' property.\"\"\"\n qgraph = {\n \"nodes\": {\n \"n0\": {\n \"categories\": \"biolink:Gene\",\n \"constraints\": [],\n },\n \"n1\": {\n \"constraints\": [],\n },\n },\n \"edges\": {\n \"e01\": {\n \"subject\": \"n0\",\n \"object\": \"n1\",\n \"attribute_constraints\": [],\n },\n },\n }\n output = list(database.run(get_query(qgraph)))[0]\n assert len(output[\"results\"]) == 10\n","sub_path":"tests/test_props.py","file_name":"test_props.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"332339498","text":"from collections import OrderedDict\nimport re\n\nclass feature2id_class():\n\n def __init__(self, feature_statistics, threshold):\n self.statistics = feature_statistics # statistics class, for each feature gives empirical counts\n self.threshold = threshold # feature count threshold - empirical count must be higher than this\n\n self.n_total_features = 0 # Total number of features accumulated\n\n self.n_tag_pairs = 0\n self.n_tag_pairs_p = 0\n self.n_tag_pairs_n = 0\n self.n_suffix_tags = 0\n self.n_prefix_tags = 0\n self.n_trigram_tags = 0\n self.n_bigram_tags = 0\n self.n_unigram_tags = 0\n self.n_capitalized_tags = 0\n self.n_Allcapitalized_tags = 0\n self.n_contain_capital_tags = 0\n self.n_hyphen_tags = 0\n self.n_apos_tags = 0\n self.n_dot_tags = 0\n self.n_contains_number_tags = 0\n\n # Init all features dictionaries\n self.words_tags_dict = OrderedDict()\n self.pwords_tags_dict = OrderedDict()\n self.nwords_tags_dict = OrderedDict()\n self.ppwords_tags_dict = OrderedDict()\n self.nnwords_tags_dict = OrderedDict()\n self.words_suffix_tags_dict = OrderedDict()\n self.words_prefix_tags_dict = OrderedDict()\n self.trigram_tags_dict = OrderedDict()\n self.bigram_tags_dict = OrderedDict()\n self.unigram_tags_dict = OrderedDict()\n self.capitalized_tags_dict = OrderedDict()\n self.contain_capital_tags_dict = OrderedDict()\n self.Allcapitalized_tags_dict = OrderedDict()\n\n self.hyphen_tags_dict = OrderedDict()\n self.dot_tags_dict = OrderedDict()\n self.apos_tags_dict = OrderedDict()\n\n self.contain_number_tags_dict = OrderedDict()\n\n def get_word_tag_pairs(self, file_path):\n \"\"\"\n Extract out of text all word/tag pairs\n :param file_path: full path of the file to read\n return all word/tag pairs with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n splited_words = re.split(' |\\n', line)\n del splited_words[-1]\n splited_words.insert(0, \"*_*\")\n splited_words.append(\"*_*\")\n\n for word_idx in range(1, len(splited_words)-1):\n\n pword, _ = splited_words[word_idx - 1].split('_')\n cur_word, cur_tag = splited_words[word_idx].split('_')\n nword, _ = splited_words[word_idx + 1].split('_')\n\n if ((cur_word, cur_tag) not in self.words_tags_dict) \\\n and (self.statistics.words_tags_count_dict[(cur_word, cur_tag)] >= self.threshold):\n self.words_tags_dict[(cur_word, cur_tag)] = self.n_total_features\n self.n_total_features += 1\n self.n_tag_pairs += 1\n\n if ((pword, cur_tag) not in self.pwords_tags_dict) \\\n and (self.statistics.pwords_tags_count_dict[(pword, cur_tag)] >= self.threshold):\n self.pwords_tags_dict[(pword, cur_tag)] = self.n_total_features\n self.n_total_features += 1\n self.n_tag_pairs += 1\n\n if ((nword, cur_tag) not in self.nwords_tags_dict) \\\n and (self.statistics.nwords_tags_count_dict[(nword, cur_tag)] >= self.threshold):\n self.nwords_tags_dict[(nword, cur_tag)] = self.n_total_features\n self.n_total_features += 1\n self.n_tag_pairs += 1\n\n def get_pre_suf_tag_pairs(self, file_path, pre_suf_flag):\n \"\"\"\n Extract out of text all pre-suf/tag pairs\n :param file_path: full path of the file to read\n :param pre_suf_flag: flag to choose between suffix (True) and prefix (False)\n return all word/tag pairs with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n split_words = re.split(' |\\n', line)\n del split_words[-1]\n for word_idx in range(len(split_words)):\n cur_word, cur_tag = split_words[word_idx].split('_')\n cur_part = \"\"\n cur_word_len = len(cur_word)\n pre_suf_slice_size = min(cur_word_len, 4)\n if pre_suf_flag:\n cur_part = cur_word[-pre_suf_slice_size:]\n else:\n cur_part = cur_word[:pre_suf_slice_size]\n for i in reversed(range(1,pre_suf_slice_size+1)):\n if pre_suf_flag:\n if (cur_part[-i:], cur_tag) not in self.words_suffix_tags_dict \\\n and (self.statistics.words_suffix_tags_count_dict[(cur_part[-i:], cur_tag)] >= self.threshold):\n self.words_suffix_tags_dict[(cur_part[-i:], cur_tag)] = self.n_total_features\n self.n_total_features += 1\n self.n_suffix_tags += 1\n else:\n if (cur_part[:i], cur_tag) not in self.words_prefix_tags_dict \\\n and (self.statistics.words_prefix_tags_count_dict[\n (cur_part[:i], cur_tag)] >= self.threshold):\n self.words_prefix_tags_dict[(cur_part[:i], cur_tag)] = self.n_total_features\n self.n_total_features += 1\n self.n_prefix_tags += 1\n\n def get_trigram_tags(self, file_path):\n \"\"\"\n Extract out of text all trigram counts\n We padded with one '*' at the beginning and end of sentence\n This is because the information captured by \"* * tag\" is also captured by the bigram\n :param file_path: full path of the file to read\n return all trigram counts with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n splited_words = re.split(' |\\n', line)\n del splited_words[-1]\n splited_words.insert(0, \"*_*\") # add '*' at the beginning\n splited_words.insert(0, \"*_*\") # add '*' at the beginning\n for word_idx in range(len(splited_words) - 2):\n _, prev_prev_tag = splited_words[word_idx].split('_')\n _, prev_tag = splited_words[word_idx + 1].split('_')\n _, cur_tag = splited_words[word_idx + 2].split('_')\n curr_key = (prev_prev_tag, prev_tag, cur_tag)\n if curr_key not in self.trigram_tags_dict \\\n and (self.statistics.trigram_tags_count_dict[curr_key] >= self.threshold):\n self.trigram_tags_dict[curr_key] = self.n_total_features\n self.n_total_features += 1\n self.n_trigram_tags += 1\n\n def get_bigram_tags(self, file_path):\n \"\"\"\n Extract out of text all bigram counts\n We padded with one '*' at the beginning and end of sentence\n :param file_path: full path of the file to read\n return all trigram counts with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n splited_words = re.split(' |\\n', line)\n del splited_words[-1]\n splited_words.insert(0, \"*_*\") # add '*' at the beginning\n for word_idx in range(len(splited_words) - 1):\n _, prev_tag = splited_words[word_idx].split('_')\n _, cur_tag = splited_words[word_idx + 1].split('_')\n curr_key = (prev_tag, cur_tag)\n if curr_key not in self.bigram_tags_dict \\\n and (self.statistics.bigram_tags_count_dict[curr_key] >= self.threshold):\n self.bigram_tags_dict[curr_key] = self.n_total_features\n self.n_total_features += 1\n self.n_bigram_tags += 1\n\n def get_unigram_tags(self, file_path):\n \"\"\"\n Extract out of text all uniram counts\n :param file_path: full path of the file to read\n return all trigram counts with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n splited_words = re.split(' |\\n', line)\n del splited_words[-1]\n for word_idx in range(len(splited_words)):\n _, cur_tag = splited_words[word_idx].split('_')\n curr_key = cur_tag\n if curr_key not in self.unigram_tags_dict \\\n and (self.statistics.unigram_tags_count_dict[curr_key] >= self.threshold):\n self.unigram_tags_dict[curr_key] = self.n_total_features\n self.n_total_features += 1\n self.n_unigram_tags += 1\n\n def get_capitalized_tags(self, file_path):\n \"\"\"\n Extract out of text all the counts for capitalized tags\n :param file_path: full path of the file to read\n return all capitalized tags counts with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n splited_words = re.split(' |\\n', line)\n del splited_words[-1]\n for word_idx in range(len(splited_words)):\n cur_word, cur_tag = splited_words[word_idx].split('_')\n flag = True\n for ch in cur_word:\n if 'A' > ch or 'Z' < ch:\n flag = False\n if 'A' <= cur_word[0] <= 'Z' and not flag:\n curr_key = cur_tag\n if curr_key not in self.capitalized_tags_dict \\\n and (self.statistics.capitalized_tags_count_dict[curr_key] >= self.threshold):\n self.capitalized_tags_dict[curr_key] = self.n_total_features\n self.n_total_features += 1\n self.n_capitalized_tags += 1\n\n def get_Allcapitalized_tags(self, file_path):\n \"\"\"\n Extract out of text all the counts for capitalized tags\n :param file_path: full path of the file to read\n return all capitalized tags counts with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n splited_words = re.split(' |\\n', line)\n del splited_words[-1]\n for word_idx in range(len(splited_words)):\n cur_word, cur_tag = splited_words[word_idx].split('_')\n flag = True\n for ch in cur_word:\n if 'A' > ch or 'Z' < ch:\n flag = False\n if flag:\n curr_key = cur_tag\n if curr_key not in self.Allcapitalized_tags_dict \\\n and (self.statistics.Allcapitalized_tags_count_dict[curr_key] >= self.threshold):\n self.Allcapitalized_tags_dict[curr_key] = self.n_total_features\n self.n_total_features += 1\n self.n_Allcapitalized_tags += 1\n\n def get_contain_capital_tags(self, file_path):\n \"\"\"\n Extract out of text all the counts for capitalized tags\n :param file_path: full path of the file to read\n return all capitalized tags counts with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n splited_words = re.split(' |\\n', line)\n del splited_words[-1]\n for word_idx in range(len(splited_words)):\n cur_word, cur_tag = splited_words[word_idx].split('_')\n flag_all = True\n for ch in cur_word:\n if 'A' > ch or 'Z' < ch:\n flag_all = False\n\n flag_first = 'A' <= cur_word[0] <= 'Z'\n\n flag_contain = False\n for ch in cur_word:\n if 'A' <= ch <= 'Z':\n flag_contain = True\n\n if not flag_first and not flag_all and flag_contain:\n curr_key = cur_tag\n if curr_key not in self.contain_capital_tags_dict \\\n and (self.statistics.contain_capital_tags_count_dict[curr_key] >= self.threshold):\n self.contain_capital_tags_dict[curr_key] = self.n_total_features\n self.n_total_features += 1\n self.n_contain_capital_tags += 1\n\n def get_hyphen_tags(self, file_path):\n \"\"\"\n Extract out of text all the counts for capitalized tags\n :param file_path: full path of the file to read\n return all capitalized tags counts with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n splited_words = re.split(' |\\n', line)\n del splited_words[-1]\n for word_idx in range(len(splited_words)):\n cur_word, cur_tag = splited_words[word_idx].split('_')\n if '.' in cur_word:\n curr_key = cur_tag\n if curr_key not in self.dot_tags_dict \\\n and (self.statistics.dot_tags_count_dict[curr_key] >= self.threshold):\n self.dot_tags_dict[curr_key] = self.n_total_features\n self.n_total_features += 1\n self.n_dot_tags += 1\n if '\\'' in cur_word:\n curr_key = cur_tag\n if curr_key not in self.apos_tags_dict \\\n and (self.statistics.apos_tags_count_dict[curr_key] >= self.threshold):\n self.apos_tags_dict[curr_key] = self.n_total_features\n self.n_total_features += 1\n self.n_apos_tags += 1\n if '-' in cur_word:\n curr_key = cur_tag\n if curr_key not in self.hyphen_tags_dict \\\n and (self.statistics.hyphen_tags_count_dict[curr_key] >= self.threshold):\n self.hyphen_tags_dict[curr_key] = self.n_total_features\n self.n_total_features += 1\n self.n_hyphen_tags += 1\n\n def get_contains_number_tags(self, file_path):\n \"\"\"\n Extract out of text all the counts for capitalized tags\n :param file_path: full path of the file to read\n return all capitalized tags counts with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n splited_words = re.split(' |\\n', line)\n del splited_words[-1]\n for word_idx in range(len(splited_words)):\n cur_word, cur_tag = splited_words[word_idx].split('_')\n flag = False\n for ch in cur_word:\n if '0' <= ch <= '9':\n flag = True\n if flag:\n curr_key = cur_tag\n if curr_key not in self.contain_number_tags_dict \\\n and (self.statistics.contain_number_tags_count_dict[curr_key] >= self.threshold):\n self.contain_number_tags_dict[curr_key] = self.n_total_features\n self.n_total_features += 1\n self.n_contains_number_tags += 1\n\n\n def get_nnword_tag_pairs(self, file_path):\n \"\"\"\n Extract out of text all word/tag pairs\n :param file_path: full path of the file to read\n return all word/tag pairs with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n splited_words = re.split(' |\\n', line)\n del splited_words[-1]\n splited_words.append(\"*_*\")\n splited_words.append(\"*_*\")\n for word_idx in range(len(splited_words)-2):\n\n _, cur_tag = splited_words[word_idx].split('_')\n nnword, _ = splited_words[word_idx + 2].split('_')\n if ((nnword, cur_tag) not in self.nnwords_tags_dict) \\\n and (self.statistics.nnwords_tags_count_dict[(nnword, cur_tag)] >= self.threshold):\n self.nnwords_tags_dict[(nnword, cur_tag)] = self.n_total_features\n self.n_total_features += 1\n self.n_tag_pairs += 1\n def get_ppword_tag_pairs(self, file_path):\n \"\"\"\n Extract out of text all word/tag pairs\n :param file_path: full path of the file to read\n return all word/tag pairs with index of appearance\n \"\"\"\n with open(file_path) as f:\n for line in f:\n splited_words = re.split(' |\\n', line)\n del splited_words[-1]\n splited_words.insert(0, \"*_*\") # add '*' at the beginning\n splited_words.insert(0, \"*_*\") # add '*' at the beginning\n for word_idx in range(2,len(splited_words)):\n\n _, cur_tag = splited_words[word_idx].split('_')\n ppword, _ = splited_words[word_idx - 2].split('_')\n if ((ppword, cur_tag) not in self.ppwords_tags_dict) \\\n and (self.statistics.ppwords_tags_count_dict[(ppword, cur_tag)] >= self.threshold):\n self.ppwords_tags_dict[(ppword, cur_tag)] = self.n_total_features\n self.n_total_features += 1\n self.n_tag_pairs += 1\n\n def get_all_ids(self, file_path):\n self.get_word_tag_pairs(file_path)\n self.get_pre_suf_tag_pairs(file_path, True)\n self.get_pre_suf_tag_pairs(file_path, False)\n self.get_capitalized_tags(file_path)\n self.get_trigram_tags(file_path)\n self.get_trigram_tags(file_path)\n self.get_bigram_tags(file_path)\n self.get_unigram_tags(file_path)\n self.get_Allcapitalized_tags(file_path)\n self.get_hyphen_tags(file_path)\n self.get_contains_number_tags(file_path)\n self.get_nnword_tag_pairs(file_path)\n self.get_ppword_tag_pairs(file_path)\n self.get_contain_capital_tags(file_path)","sub_path":"Wet1/Code Directory/Code/feature2id_class.py","file_name":"feature2id_class.py","file_ext":"py","file_size_in_byte":19050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"200077597","text":"\ndef isPerm(num):\n if num==int(str(num)[::-1]):\n return True\n return False\n\nout=1; \nfor i in range(100,1000):\n for j in range(i,1000):\n num=i*j;\n if isPerm(num):\n if out'\n\n\tdef initialize(self):\n\t\t\"\"\"\n\t\tInitializes component\n\t\t\"\"\"\n\t\tNnrecognizerConsumer.LOGGER.info('Initializing component')\n\t\ttry:\n\t\t\tmodel_path = NnrecognizerConsumer.get_path(self.parameters['model'])\n\t\t\tself.model = load_model(model_path)\n\t\t\tNnrecognizerConsumer.LOGGER.info('Loaded network model')\n\t\texcept Exception as e:\n\t\t\tNnrecognizerConsumer.LOGGER.error('Cannot load model: ' + str(e))\n\n\t\tself.initialized = True\n\n\tdef run(self, context: ConsumerContext):\n\t\tif not self.initialized:\n\t\t\tself.initialize()\n\n\t\t# the data is expected to be the detected face\n\t\tface = context.data\n\t\tcontext.alert = True\n\n\t\tif face is not None:\n\t\t\tNnrecognizerConsumer.LOGGER.info('Running face recognition...')\n\t\t\tif self.recognize(face):\n\t\t\t\tcontext.alert = False\n\t\t\t\tcontext.alert_data = 'Positive recognition'\n\t\t\t\tNnrecognizerConsumer.LOGGER.info(context.alert_data)\n\t\t\telse:\n\t\t\t\tcontext.alert_data = NnrecognizerConsumer.img_to_str(face)\n\t\t\t\tNnrecognizerConsumer.LOGGER.info('Negative recognition')\n\t\telse:\n\t\t\tNnrecognizerConsumer.LOGGER.warning('Face was not provided (is None)')\n\t\t\tcontext.alert_data = 'No face provided'\n\n\t\treturn context\n\n\tdef recognize(self, face: np.ndarray):\n\t\t\"\"\"\n\t\tRuns the face through the neural network\n\t\t:param face: detected face\n\t\t:return:\n\t\t\"\"\"\n\t\t# Resize\n\t\tface = cv2.resize(face, (self.size, self.size))\n\n\t\t# Normalize image\n\t\tface = np.asarray([face]).reshape(-1, self.size, self.size, 1).astype('float32') / 255\n\n\t\t# Run it through the network\n\t\tprediction = self.model.predict(face)\n\t\tprediction = np.argmax(np.round(prediction), axis=1)\n\t\tif prediction[0] == 1:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n","sub_path":"src/raspberry_sec/module/nnrecognizer/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"414317262","text":"import unittest\n\nimport numpy as np\nimport math\n\nimport storyboard.planner\nimport testdata.bench_gen\n\n\ndef main():\n print(\"Generating Data\")\n df = testdata.bench_gen.gen_data(\n 2_000_000,\n [(2,0), (10, 1), (10, 1), (10, 1)],\n f_skew=1.2,\n f_card=100_000_000\n )\n wp = storyboard.planner.WorkloadProperties(\n pred_weights=[.3, .3, .3],\n max_time_segments=1,\n )\n fp = storyboard.planner.FreqProcessor(\n total_size=2000,\n workload_prop=wp,\n )\n print(\"Creating Storyboard\")\n groups = fp.create_storyboard(\n df_input=df,\n dim_col_names=[\"d0\", \"d1\", \"d2\"],\n val_col_name=\"f\"\n )\n print(groups)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"python/gen_storyboard.py","file_name":"gen_storyboard.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"82856930","text":"from tkinter import *\nimport tkinter as tk\nimport requests\nimport tkinter.messagebox\nimport os\n\n\n#设置窗口居中\ndef window_info():\n ws = window.winfo_screenwidth()\n hs = window.winfo_screenheight()\n x = (ws / 2) - 200\n y = (hs / 2) - 200\n return x,y\n \n#设置登陆窗口属性\nwindow = tk.Tk()\nwindow.title('湖南涉外经济学院')\na,b=window_info()\nwindow.geometry(\"450x300+%d+%d\"%(a,b))\n\n#登陆界面的信息\ntk.Label(window,text=\"校园网登录系统\",font=(\"宋体\",32)).place(x=80,y=50)\ntk.Label(window,text=\"账号:\").place(x=127,y=140)\ntk.Label(window,text=\"密码:\").place(x=127,y=180)\n#显示输入框\nvar_usr_name = tk.StringVar()\n#显示默认账号\nvar_usr_name.set('174030138')\nentry_usr_name=tk.Entry(window,textvariable=var_usr_name)\nentry_usr_name.place(x=178,y=140)\nvar_usr_pwd = tk.StringVar()\n#设置输入密码后显示*号\nvar_usr_pwd.set('191039')\nentry_usr_pwd = tk.Entry(window,textvariable=var_usr_pwd,show='*')\nentry_usr_pwd.place(x=178,y=180)\n\ndef usr_login():\n #获取输入的账号密码\n usr_name = var_usr_name.get()\n usr_pwd = var_usr_pwd.get()\n url='http://172.16.18.6/a70.htm'\n \n cookies = {\n '__guid': '149234166.3958882504061907500.1568543011125.1177',\n 'monitor_count': '99',\n }\n \n headers = {\n 'Origin': 'http://172.16.18.6',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Cache-Control': 'max-age=0',\n 'Referer': 'http://172.16.18.6/a70.htm',\n 'Connection': 'keep-alive',\n }\n \n data = {\n 'DDDDD': usr_name,\n 'upass': usr_pwd,\n 'R1': '0',\n 'R2': '',\n 'R3': '0',\n 'R6': '1',\n 'para': '00',\n '0MKKey': '123456',\n 'buttonClicked': '',\n 'redirect_url': '',\n 'err_flag': '',\n 'username': '',\n 'password': '',\n 'user': '',\n 'cmd': '',\n 'Login': '',\n 'v6ip': ''\n }\n \n response = requests.post(url, headers=headers, cookies=cookies, data=data)\n exit_code = os.system('ping 58.20.127.201 -n 1')\n if exit_code ==0:\n tkinter.messagebox.showinfo(\"登录结果\",\"你已成功登录!\")\n \ndef logout():\n cookie = {\n '__guid': '149234166.3958882504061907500.1568543011125.1177',\n 'monitor_count': '172',\n }\n \n header = {\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Referer': 'http://172.16.18.6/',\n 'Connection': 'keep-alive',\n }\n \n response_Logout = requests.get('http://172.16.18.6/F.htm', headers=header, cookies=cookie)\n exit_code = os.system('ping 58.20.127.201 -n 1')\n if exit_code:\n tkinter.messagebox.showinfo(\"注销结果\",\"你已成功注销!\")\n\n\ndef ex():\n window.quit()\n exit()\n\nexit_code = os.system('ping 58.20.127.201 -n 1')\n\nif exit_code == 0:\n tkinter.messagebox.showinfo(\"登录结果\",\"你已成功登录!\")\nbtn_login = tk.Button(window,text=\"关闭\",command=ex,width=8,height=2)\nbtn_login.place(x=100,y=230)\nbtn_login = tk.Button(window,text=\"登录\",command=usr_login,width=8,height=2)\nbtn_login.place(x=190,y=230)\nbtn_login = tk.Button(window,text=\"注销\",command=logout,width=8,height=2)\nbtn_login.place(x=280,y=230)\n\nwindow.mainloop()","sub_path":"src/Login/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"401428974","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport telebot\nimport threading\nimport main\nimport os\n\nimport traceback\ntypes = telebot.types\nbot = telebot.TeleBot(os.environ['FALAFEL_BOT_TOKEN'])\nadmin_mode = False\n\n\n# Переопределение метода отправки сообщения (защита от ошибок)\ndef send_message(chat_id, message, reply_markup=None, parse_mode='markdown', to_admin=False):\n try:\n return bot.send_message(chat_id, message, reply_markup=reply_markup, parse_mode=parse_mode)\n except Exception:\n main.send_error(str(traceback.format_exc()))\n\n\ndef edit_message(chat_id, message_id, message_text, reply_markup=None, parse_mode='markdown'):\n try:\n return bot.edit_message_text(chat_id=chat_id, message_id=message_id,\n text=message_text, reply_markup=reply_markup, parse_mode=parse_mode)\n except Exception as e:\n main.send_error(str(traceback.format_exc()))\n return False\n\n\ndef edit_image_message(chat_id, message_id, message_text, reply_markup=None, parse_mode='markdown'):\n return bot.edit_message_caption(chat_id=chat_id, message_id=message_id,\n caption=message_text, reply_markup=reply_markup)\n\n\ndef delete_message(chat_id=None, message_id=None, call=None):\n try:\n if call is not None:\n return bot.delete_message(call.message.chat.id, call.message.message_id)\n return bot.delete_message(chat_id, message_id)\n except telebot.apihelper.ApiException:\n pass\n\n\ndef answer_callback_query(call, text, alert=True):\n try:\n bot.answer_callback_query(call.id, text=text, show_alert=alert)\n except Exception as e:\n main.send_error(str(traceback.format_exc()))\n","sub_path":"bot_methods.py","file_name":"bot_methods.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"45991074","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom sklearn.model_selection import KFold\r\nfrom scipy.optimize import curve_fit\r\nimport copy\r\n\r\n# PyDREAM imports\r\nfrom pydream.core import run_dream\r\nfrom pysb.integrate import Solver\r\nfrom pydream.parameters import SampledParam\r\nfrom scipy.stats import norm, uniform\r\nimport os\r\nfrom datetime import datetime\r\nimport inspect\r\nfrom pydream.convergence import Gelman_Rubin\r\n\r\n\r\n# Import data set and split into predictor variables (receptors, JAKs, SOCS, etc.) and response variables (STATs)\r\nIFNg_dose = 100 # pM\r\nImmGen_df = pd.read_excel('MasterTable_ImmGen_pSTAT.xlsx', sheet_name='G-CSF', axis=1)\r\nImmGen_df['pSTAT1norm'] = ImmGen_df['pSTAT1']/ImmGen_df['STAT1']\r\nImmGen_df['pSTAT3norm'] = ImmGen_df['pSTAT3']/ImmGen_df['STAT3']\r\n\r\n#create df of results and features from full dataframe\r\nresponse_variable_names = ['pSTAT1', 'pSTAT3']\r\nresponse_variables = ImmGen_df[response_variable_names]\r\n\r\npredictor_variable_names = [c for c in ImmGen_df.columns.values if c not in response_variable_names + ['Cell_type']]\r\npredictor_variables = ImmGen_df[predictor_variable_names]\r\n\r\n# Compute pairwise correlations between all variables\r\ndef pairwise_correlation():\r\n f = plt.figure(figsize=(19, 15))\r\n df = ImmGen_df[response_variable_names + predictor_variable_names]\r\n plt.matshow(df.corr(), fignum=f.number)\r\n plt.xticks(range(df.shape[1]), df.columns, fontsize=14, rotation=45)\r\n plt.yticks(range(df.shape[1]), df.columns, fontsize=14)\r\n cb = plt.colorbar()\r\n cb.ax.tick_params(labelsize=14)\r\n plt.title('Correlation Matrix', fontsize=16);\r\n plt.tight_layout()\r\n plt.show()\r\n\r\ndef SOCS_histograms():\r\n labels = ['SOCS1', 'SOCS2', 'SOCS3', 'SOCS4', 'SOCS5', 'SOCS6', 'SOCS7', 'PIAS1', 'PIAS2', 'PIAS3', 'PIAS4', 'CIS', 'SHP1', 'SHP2']\r\n colours = sns.color_palette(n_colors=len(labels))\r\n # Plot each individually\r\n fig, axes = plt.subplots(nrows=int(np.ceil(len(labels)/3.)), ncols=3)\r\n for lidx, l in enumerate(labels):\r\n sns.distplot(ImmGen_df[l], color=colours[lidx], label=l, ax=axes[int(lidx/3)][lidx%3], axlabel=l)\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n # Plot on same axis\r\n for lidx, l in enumerate(['SOCS1', 'SOCS2', 'SOCS3', 'PIAS1', 'SHP1']):\r\n sns.distplot(ImmGen_df[l], color=colours[lidx], label=l)\r\n ax = plt.gca()\r\n fig = plt.gcf()\r\n ax.set_xlim(left=30, right=5000)\r\n ax.set_xscale('log')\r\n ax.set_xlabel('Gene Expression (# transcripts)')\r\n ax.set_ylabel('Frequency')\r\n fig.legend()\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\n\r\n# Create the receptor models\r\n#global variables applicable to all receptors\r\nNA = 6.022E23\r\ncell_density = 1E6 # cells per mL\r\nvolEC = 1E-3/cell_density # L\r\nrad_cell = 5E-6 # m\r\npi = np.pi\r\nvolPM = 4*pi*rad_cell**2 # m**2\r\nvolCP = (4/3)*pi*rad_cell**3 # m**3\r\n\r\nclass Cytokine_Receptor:\r\n \"\"\"Cytokine_Receptor class\r\n This class allows the user to quickly create copies of the same equilibrium\r\n receptor model which have different parameters, and then use this model to\r\n make predictions and fit data.\r\nAttributes:\r\n STAT_names (list): each element is a string identifying the name of an equilibrium_model_output from activating this receptor\r\n parameters (dict): each entry is a dict with key from self.STAT_names, and entry is another dict which has\r\n for keys the names (str) and values (float or int) for the equilibrium model of that\r\n corresponding STAT response; parameters should be given in units of molecules where\r\n possible, not molarity.\r\n keys: R_total, Delta, Jak1, Jak2, STAT_total, K_ligand, K_Jak1, K_Jak2, K_R1R2, K_STAT, K_rc\r\n cytokine_name (str): the name of the cytokine which binds specifically to this receptor\r\nMethods:\r\n def equilibrium_model_output():\r\n :param cytokine_dose: (float) the stimulation of cytokine in pM\r\n :return STAT_response: (dict) the predicted pSTAT response for each key, STAT, in self.STAT_names\r\n def equilibrium_model_for_SOCS_competing_with_STAT():\r\n :param cytokine_dose: (float) the stimulation of cytokine in pM\r\n :return STAT_response: (dict) the predicted pSTAT response for each key, STAT, in self.STAT_names\r\n\"\"\"\r\n def __init__(self, STAT_names, parameters, cytokine_name):\r\n self.STAT_names = STAT_names\r\n self.parameters = parameters\r\n self.cytokine_name = cytokine_name\r\n if not all(elem in self.STAT_names for elem in self.parameters.keys()):\r\n print(\"Not all parameters were defined for all STAT outputs\")\r\n raise KeyError\r\n\r\n def equilibrium_model_output(self, cytokine_dose):\r\n dose = cytokine_dose*1E-12*NA*volEC\r\n STAT_response = {}\r\n for STAT in self.STAT_names:\r\n cytokine_R = self.parameters[STAT]['K_R1R2']/2 * \\\r\n (1 + self.parameters[STAT]['R_total']/self.parameters[STAT]['K_R1R2'] -\\\r\n np.sqrt(1 + (2*self.parameters[STAT]['R_total']*self.parameters[STAT]['K_R1R2']\\\r\n + self.parameters[STAT]['Delta']**2)/self.parameters[STAT]['K_R1R2']**2))\r\n Rstar = cytokine_R*self.parameters[STAT]['Jak1']*self.parameters[STAT]['K_Jak1']*self.parameters[STAT]['Jak2']*\\\r\n self.parameters[STAT]['K_Jak2']/(1+self.parameters[STAT]['K_ligand']/dose)\r\n response = self.parameters[STAT]['STAT_total']/(1+self.parameters[STAT]['K_STAT']*volPM/Rstar)\r\n STAT_response[STAT] = response\r\n return STAT_response\r\n\r\n def equilibrium_model_for_SOCS_competing_with_STAT(self, cytokine_dose, SOCS_name):\r\n dose = cytokine_dose*1E-12*NA*volEC\r\n STAT_response = {}\r\n for STAT in self.STAT_names:\r\n cytokine_R = self.parameters[STAT]['K_R1R2']/2 * \\\r\n (1 + self.parameters[STAT]['R_total']/self.parameters[STAT]['K_R1R2'] -\\\r\n np.sqrt(1 + (2*self.parameters[STAT]['R_total']*self.parameters[STAT]['K_R1R2']\\\r\n + self.parameters[STAT]['Delta']**2)/self.parameters[STAT]['K_R1R2']**2))\r\n PR1active = self.parameters[STAT]['Jak1']*self.parameters[STAT]['K_Jak1'] / (1 + self.parameters[STAT]['Jak1']*self.parameters[STAT]['K_Jak1'])\r\n PR2active = self.parameters[STAT]['Jak2']*self.parameters[STAT]['K_Jak2'] / (1 + self.parameters[STAT]['Jak2']*self.parameters[STAT]['K_Jak2'])\r\n Rstar = cytokine_R*PR1active*PR2active/(1+self.parameters[STAT]['K_ligand']/dose)\r\n print(Rstar)\r\n exit()\r\n response = self.parameters[STAT]['STAT_total']/(1+self.parameters[STAT]['K_STAT']*(1+self.parameters[STAT][SOCS_name]/self.parameters[STAT]['K_SOCS'])*volPM/Rstar)\r\n STAT_response[STAT] = response\r\n return STAT_response\r\n\r\n def equilibrium_model_with_SOCS_ec50(self, SOCS_name):\r\n ec50_dict = {}\r\n for STAT in self.STAT_names:\r\n term1 = self.parameters[STAT]['Jak1'] * self.parameters[STAT]['K_Jak1'] * self.parameters[STAT]['Jak2'] * self.parameters[STAT]['K_Jak2']\r\n term2 = self.parameters[STAT]['K_R1R2'] + self.parameters[STAT]['R_total'] - self.parameters[STAT]['K_R1R2'] * np.sqrt((self.parameters[STAT]['K_R1R2']**2 + 2*self.parameters[STAT]['K_R1R2']*self.parameters[STAT]['R_total']+self.parameters[STAT]['Delta']**2)/self.parameters[STAT]['K_R1R2']**2)\r\n term3 = (1+self.parameters[STAT]['K_Jak1']*self.parameters[STAT]['Jak1']) * (1+self.parameters[STAT]['K_Jak2']*self.parameters[STAT]['Jak2'])\r\n term4 = self.parameters[STAT]['K_STAT']*(self.parameters[STAT]['K_STAT'] + self.parameters[STAT][SOCS_name])\r\n numerator = 2*volPM*self.parameters[STAT]['K_ligand']*term3*term4\r\n denominator = 2*volPM*term3*term4 + self.parameters[STAT]['K_SOCS']*term1*term2\r\n ec50 = numerator/denominator\r\n ec50_dict[STAT] = ec50/(NA*volEC) # (M)\r\n return ec50_dict\r\n\r\n def equilibrium_model_with_SOCS_pSTATmax(self, SOCS_name):\r\n pSTAT_max_dict = {}\r\n for STAT in self.STAT_names:\r\n term1 = self.parameters[STAT]['Jak1'] * self.parameters[STAT]['K_Jak1'] * self.parameters[STAT]['Jak2'] * self.parameters[STAT]['K_Jak2']\r\n term2 = self.parameters[STAT]['K_R1R2'] + self.parameters[STAT]['R_total'] - self.parameters[STAT]['K_R1R2'] * np.sqrt((self.parameters[STAT]['K_R1R2']**2 + 2*self.parameters[STAT]['K_R1R2']*self.parameters[STAT]['R_total']+self.parameters[STAT]['Delta']**2)/self.parameters[STAT]['K_R1R2']**2)\r\n numerator = self.parameters[STAT]['K_SOCS']*self.parameters[STAT]['STAT_total']*term1*term2\r\n term3 = (1+self.parameters[STAT]['K_Jak1']*self.parameters[STAT]['Jak1']) * (1+self.parameters[STAT]['K_Jak2']*self.parameters[STAT]['Jak2'])\r\n denominator = 2*volPM*term3*self.parameters[STAT]['K_STAT']*(self.parameters[STAT]['K_SOCS']+self.parameters[STAT][SOCS_name]) + self.parameters[STAT]['K_SOCS']*term1*term2\r\n pSTAT_max_dict[STAT] = numerator/denominator\r\n return pSTAT_max_dict\r\n\r\n\r\ndefault_SOCS_name = 'SOCS2'\r\nIFNg_parameters = {'pSTAT1': {'R_total': 2000, # infer from Immgen\r\n 'Delta': 0, # infer from Immgen\r\n 'Jak1': 1000, # infer from Immgen\r\n 'Jak2': 1000, # infer from Immgen\r\n 'STAT_total': 2000, # infer from Immgen\r\n default_SOCS_name: 200, # infer from Immgen\r\n 'USP18': 0, # infer from Immgen\r\n 'K_ligand': NA*volEC/(4*pi*0.5E10), # from literature\r\n 'K_Jak1': 1E6/(NA*volCP), # fit for each receptor\r\n 'K_Jak2': 1E6/(NA*volCP), # fit for each receptor\r\n 'K_R1R2': 4*pi*0.5E-12/volPM, # from literature\r\n 'K_STAT': 1000/volPM, # fit for each receptor/STAT pair\r\n 'K_SOCS': 1000, # fit for each receptor\r\n 'K_USP18': 150}, # fit for each receptor\r\n\r\n 'pSTAT3': {'R_total': 2000,\r\n 'Delta': 0,\r\n 'Jak1': 1000,\r\n 'Jak2': 1000,\r\n 'STAT_total': 2000,\r\n default_SOCS_name: 200,\r\n 'USP18': 0,\r\n 'K_ligand': NA*volEC/(4*pi*0.5E10),\r\n 'K_Jak1': 1E6/(NA*volCP),\r\n 'K_Jak2': 1E6/(NA*volCP),\r\n 'K_R1R2': 4*pi*0.5E-12/volPM,\r\n 'K_STAT': 1000/volPM,\r\n 'K_SOCS': 1000,\r\n 'K_USP18': 150}\r\n }\r\n\r\n\r\ndef plot_dose_response(IFNg_parameters, SOCS_name, model=1):\r\n IFNg_receptor = Cytokine_Receptor(['pSTAT1', 'pSTAT3'], IFNg_parameters, 'IFNgamma')\r\n if model==1:\r\n pSTAT1_dose_response = [IFNg_receptor.equilibrium_model_output(d, SOCS_name)['pSTAT1'] for d in np.logspace(-2, 3)]\r\n elif model==2:\r\n pSTAT1_dose_response = [IFNg_receptor.equilibrium_model_for_SOCS_competing_with_STAT(d, SOCS_name)['pSTAT1'] for d in np.logspace(-2, 3)]\r\n plt.figure()\r\n ax = plt.gca()\r\n ax.set_xscale('log')\r\n plt.xlabel(r'IFN$\\gamma$ (pM)')\r\n plt.ylabel('pSTAT1 (# molec.)')\r\n plt.plot(np.logspace(-2, 3), pSTAT1_dose_response)\r\n plt.show()\r\n\r\n\r\ndef infer_protein(dataset, cell_type, protein_names):\r\n \"\"\"\r\n Assumes that the steady-state protein level is simply one-to-one with the transcript level measured.\r\n :param dataset: pandas dataframe with ImmGen transcript levels for the cell_type of interest\r\n :param cell_type: row label to select from dataset\r\n :param protein_names: column names to extract transcript values from dataset\r\n :return: proteins (dict): keys are protein_names and values are the numbers of the proteins to use in\r\n Cytokine_Receptor.parameters\r\n \"\"\"\r\n if 'allSOCS' in protein_names:\r\n all_SOCS_names = ['SOCS1', 'SOCS2', 'SOCS3', 'SOCS4', 'SOCS5', 'SOCS6', 'SOCS7', 'CIS', 'SHP1', 'SHP2', 'PIAS1', 'PIAS2', 'PIAS3', 'PIAS4']\r\n SOCS_transcripts = np.sum(dataset.loc[dataset['Cell_type'] == cell_type][all_SOCS_names].values.flatten())\r\n transcripts = dataset.loc[dataset['Cell_type'] == cell_type][[p for p in protein_names if p!='allSOCS']].values.flatten()\r\n d = dict(zip([p for p in protein_names if p!='allSOCS'], transcripts))\r\n d['allSOCS'] = SOCS_transcripts\r\n return d\r\n else:\r\n transcripts = dataset.loc[dataset['Cell_type'] == cell_type][protein_names].values.flatten()\r\n #mean_transcripts = dataset.mean()[protein_names].values\r\n #proteins = [mean_transcripts[i] * 2**(np.log10(transcripts[i]/mean_transcripts[i])) for i in range(len(protein_names))]\r\n return dict(zip(protein_names, transcripts))\r\n\r\n\r\ndef equilibrium_pSTAT1_and_pSTAT3(dose, K_Jak1=1E6 / (NA * volCP), K_Jak2=1E6 / (NA * volCP),\r\n K_STAT_STAT1=1000/volPM, K_STAT_STAT3=1000/volPM, K_USP18=150):\r\n cell_types = ImmGen_df['Cell_type'].values\r\n\r\n # Set input parameters for model\r\n default_parameters = IFNg_parameters.copy()\r\n # receptor parameters\r\n default_parameters['pSTAT1']['K_Jak1'] = K_Jak1\r\n default_parameters['pSTAT3']['K_Jak1'] = K_Jak1\r\n default_parameters['pSTAT1']['K_Jak2'] = K_Jak2\r\n default_parameters['pSTAT3']['K_Jak2'] = K_Jak2\r\n default_parameters['pSTAT1']['K_USP18'] = K_USP18\r\n default_parameters['pSTAT3']['K_USP18'] = K_USP18\r\n\r\n # receptor:STAT parameters\r\n default_parameters['pSTAT1']['K_STAT'] = K_STAT_STAT1\r\n default_parameters['pSTAT3']['K_STAT'] = K_STAT_STAT3\r\n\r\n response = {'Cell_type': [], 'pSTAT1': [], 'pSTAT3': []}\r\n for c in cell_types:\r\n IFNg_ImmGen_parameters = infer_protein(ImmGen_df, c, ['IFNGR1', 'IFNGR2', 'JAK1', 'JAK2', 'STAT1', 'STAT3'])\r\n for S in ['pSTAT1', 'pSTAT3']:\r\n default_parameters[S]['R_total'] = IFNg_ImmGen_parameters['CSF3r']/(1+IFNg_ImmGen_parameters['USP18']/default_parameters[S]['K_USP18'])\r\n default_parameters[S]['Delta'] = 0\r\n default_parameters[S]['Jak1'] = IFNg_ImmGen_parameters['JAK1']\r\n default_parameters[S]['Jak2'] = IFNg_ImmGen_parameters['JAK2']\r\n default_parameters[S]['STAT_total'] = IFNg_ImmGen_parameters[S[1:]]\r\n # Make predictions\r\n IFNg_receptor = Cytokine_Receptor(['pSTAT1', 'pSTAT3'], IFNg_parameters, 'GCSF')\r\n q = IFNg_receptor.equilibrium_model_output(dose)\r\n response['Cell_type'].append(c)\r\n response['pSTAT1'].append(q['pSTAT1'])\r\n response['pSTAT3'].append(q['pSTAT3'])\r\n return pd.DataFrame.from_dict(response)\r\n\r\n\r\ndef SOCS_competes_STAT_pSTAT1_and_pSTAT3(dose, SOCS_name, K_Jak1=1E6 / (NA * volCP), K_Jak2=1E6 / (NA * volCP),\r\n K_STAT_STAT1=1000/volPM, K_STAT_STAT3=1000/volPM, K_SOCS=1000, K_USP18=150, df=ImmGen_df):\r\n cell_types = df['Cell_type'].values\r\n\r\n # Set input parameters for model\r\n default_parameters = copy.deepcopy(IFNg_parameters)\r\n # receptor parameters\r\n default_parameters['pSTAT1']['K_Jak1'] = K_Jak1\r\n default_parameters['pSTAT3']['K_Jak1'] = K_Jak1\r\n default_parameters['pSTAT1']['K_Jak2'] = K_Jak2\r\n default_parameters['pSTAT3']['K_Jak2'] = K_Jak2\r\n default_parameters['pSTAT1']['K_SOCS'] = K_SOCS\r\n default_parameters['pSTAT3']['K_SOCS'] = K_SOCS\r\n default_parameters['pSTAT1']['K_USP18'] = K_USP18\r\n default_parameters['pSTAT3']['K_USP18'] = K_USP18\r\n\r\n # receptor:STAT parameters\r\n default_parameters['pSTAT1']['K_STAT'] = K_STAT_STAT1\r\n default_parameters['pSTAT3']['K_STAT'] = K_STAT_STAT3\r\n\r\n response = {'Cell_type': [], 'pSTAT1': [], 'pSTAT3': []}\r\n for c in cell_types:\r\n IFNg_ImmGen_parameters = infer_protein(df, c, ['CSF3r', 'JAK1', 'JAK2', 'STAT1', 'STAT3', SOCS_name, 'USP18'])\r\n for S in ['pSTAT1', 'pSTAT3']:\r\n default_parameters[S]['R_total'] = IFNg_ImmGen_parameters['CSF3r']/(1+IFNg_ImmGen_parameters['USP18']/default_parameters[S]['K_USP18'])\r\n default_parameters[S]['Delta'] = 0\r\n default_parameters[S]['Jak1'] = IFNg_ImmGen_parameters['JAK1']\r\n default_parameters[S]['Jak2'] = IFNg_ImmGen_parameters['JAK2']\r\n default_parameters[S]['STAT_total'] = IFNg_ImmGen_parameters[S[1:]]\r\n default_parameters[S][SOCS_name] = IFNg_ImmGen_parameters[SOCS_name]\r\n # Make predictions\r\n IFNg_receptor = Cytokine_Receptor(['pSTAT1', 'pSTAT3'], default_parameters, 'IFNgamma')\r\n q = IFNg_receptor.equilibrium_model_for_SOCS_competing_with_STAT(dose, SOCS_name)\r\n response['Cell_type'].append(c)\r\n response['pSTAT1'].append(q['pSTAT1'])\r\n response['pSTAT3'].append(q['pSTAT3'])\r\n return pd.DataFrame.from_dict(response)\r\n\r\n\r\ndef equilibrium_model(dose, p1, p2, p3, p4, scale_factor):\r\n y_pred = equilibrium_pSTAT1_and_pSTAT3(dose, K_Jak1=p1, K_Jak2=p2, K_STAT_STAT1=p3, K_STAT_STAT3=p4)[['pSTAT1', 'pSTAT3']]\r\n return np.divide(y_pred.values.flatten(), scale_factor)\r\n\r\n\r\ndef fit_IFNg_equilibrium():\r\n default_parameters = [1E7 / (NA * volCP), 1E7 / (NA * volCP), 10000 / volPM, 10000 / volPM, 70]\r\n\r\n y_true = ImmGen_df[['pSTAT1', 'pSTAT3']].values.flatten()\r\n pfit, pcov = curve_fit(equilibrium_model, IFNg_dose, y_true, p0=default_parameters,\r\n bounds=(np.multiply(default_parameters, 0.1), np.multiply(default_parameters, 10)))\r\n return pfit, pcov\r\n\r\n\r\ndef make_SOCS_competes_STAT_model(SOCS_name, df=ImmGen_df):\r\n def SOCS_model(dose, p1, p2, p3, p4, p5, scale_factor, p6):\r\n y_pred = SOCS_competes_STAT_pSTAT1_and_pSTAT3(dose, SOCS_name, K_Jak1=p1, K_Jak2=p2, K_STAT_STAT1=p3,\r\n K_STAT_STAT3=p4, K_SOCS=p5, K_USP18=p6, df=df)[['pSTAT1', 'pSTAT3']]\r\n return np.divide(y_pred.values.flatten(), scale_factor)\r\n return SOCS_model\r\n\r\n\r\ndef fit_IFNg_with_SOCS_competes_STAT(SOCS_name, df=ImmGen_df):\r\n if SOCS_name=='allSOCS':\r\n default_parameters = [1E7 / (NA * volCP), 1E8 / (NA * volCP), 1000 / volPM, 1000 / volPM, 1.6e-02, 1]\r\n else:\r\n min_response_row = df.loc[df[response_variable_names[0]].idxmin()]\r\n min_response_SOCS_expression = infer_protein(df, min_response_row.loc['Cell_type'], [SOCS_name])[SOCS_name]\r\n #\r\n # [4.64594123e-02, 6.72673774e+00, 9.50605181e+00, 2.92182513e+00, 2.08449593e-01, 1.63205262e+02]\r\n # K_Jak1, K_Jak2, K_STAT_STAT1, K_STAT_STAT3, K_SOCS, scale_factor\r\n default_parameters = [1E7 / (NA * volCP), 1E8 / (NA * volCP), 1000 / volPM, 1000 / volPM, 0.0006*min_response_SOCS_expression, 1]\r\n y_true = df[['pSTAT1', 'pSTAT3']].values.flatten()\r\n pfit, pcov = curve_fit(make_SOCS_competes_STAT_model(SOCS_name, df), IFNg_dose, y_true, p0=default_parameters,\r\n bounds=(np.multiply(default_parameters, 0.1), np.multiply(default_parameters, 10)))\r\n return pfit, pcov\r\n\r\n\r\ndef k_fold_cross_validate_SOCS_competes_STAT(k=10, df=ImmGen_df, neg_feedback_name='SOCS2'):\r\n \"\"\"\r\n Validate the estimated R^2 value for the SOCS model fit using k-fold cross validation\r\n :param k: (int) number of folds to split data into\r\n :param df: (DataFrame) combined predictor and response variables\r\n :return r2, r2_variance: (floats) the estimated R^2 value and variance in the estimate\r\n \"\"\"\r\n kf = KFold(n_splits=k, shuffle=True, random_state=1)\r\n r2_samples = []\r\n for result in kf.split(df):\r\n # Split data\r\n train = df.iloc[result[0]]\r\n test = df.iloc[result[1]]\r\n\r\n # Fit\r\n pfit, pcov = fit_IFNg_with_SOCS_competes_STAT(neg_feedback_name, df=train)\r\n\r\n # Predict\r\n SOCS_model = make_SOCS_competes_STAT_model(neg_feedback_name, df=test)\r\n fit_pred = np.reshape(SOCS_model(IFNg_dose, *pfit), (test.shape[0], len(response_variable_names)))\r\n\r\n # Compute R**2 value\r\n residuals = np.subtract(np.log(fit_pred), np.log(test[['pSTAT1', 'pSTAT3']].values))\r\n ss_res = np.sum(residuals**2)\r\n ss_tot = np.sum((np.log(test[['pSTAT1', 'pSTAT3']].values)-np.log(np.mean(test[['pSTAT1', 'pSTAT3']].values)))**2)\r\n r_squared = 1 - (ss_res / ss_tot)\r\n r2_samples.append(r_squared)\r\n\r\n return np.mean(r2_samples), np.var(r2_samples)\r\n\r\n\r\ndef fit_without_SOCS(df=ImmGen_df):\r\n pfit, pcov = fit_IFNg_equilibrium()\r\n print(pfit)\r\n\r\n # Predict\r\n fit_pred = np.reshape(equilibrium_model(IFNg_dose, *pfit), (15, len(response_variable_names)))\r\n fit_pred_labelled = [[df['Cell_type'].values[i], fit_pred[i][0], fit_pred[i][1]] for i in range(df.shape[0])]\r\n\r\n # Compute R**2 value\r\n residuals = np.subtract(np.log(fit_pred), np.log(df[['pSTAT1', 'pSTAT3']].values))\r\n ss_res = np.sum(residuals ** 2)\r\n ss_tot = np.sum((np.log(df[['pSTAT1', 'pSTAT3']].values) - np.log(np.mean(df[['pSTAT1', 'pSTAT3']].values))) ** 2)\r\n r_squared = 1 - (ss_res / ss_tot)\r\n print(\"r-squared value (log scale): \", r_squared)\r\n\r\n # Plot\r\n fit_prediction = pd.DataFrame.from_records(fit_pred_labelled, columns=['Cell_type', 'pSTAT1', 'pSTAT3'])\r\n fit_prediction.insert(0, 'Class', ['Model' for _ in range(df.shape[0])])\r\n measured_response = df[['Cell_type', 'pSTAT1', 'pSTAT3']]\r\n measured_response.insert(0, 'Class', ['CyTOF' for _ in range(df.shape[0])])\r\n\r\n df = pd.concat([fit_prediction, measured_response])\r\n\r\n fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12.8, 5))\r\n subplot_titles = ['pSTAT1', 'pSTAT3']\r\n sns.barplot(x=\"Cell_type\", y=\"pSTAT1\", data=df, hue='Class', ax=ax[0])\r\n sns.barplot(x=\"Cell_type\", y=\"pSTAT3\", data=df, hue='Class', ax=ax[1])\r\n for i in [0, 1]:\r\n ax[i].set_xticklabels(ax[i].get_xticklabels(), rotation=90)\r\n ax[i].set_title(subplot_titles[i])\r\n\r\n plt.suptitle(r\"$R^{2}$ (log scale) = \" + \"{:.2f}\".format(r_squared))\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef fit_with_SOCS_competes_STAT(df=ImmGen_df, k_fold=1, neg_feedback_name='SOCS2'):\r\n pfit, pcov = fit_IFNg_with_SOCS_competes_STAT(neg_feedback_name, df)\r\n print(pfit)\r\n\r\n # Predict\r\n SOCS_model = make_SOCS_competes_STAT_model(neg_feedback_name)\r\n fit_pred = np.reshape(SOCS_model(IFNg_dose, *pfit), (df.shape[0], len(response_variable_names)))\r\n fit_pred_labelled = [[df['Cell_type'].values[i], fit_pred[i][0], fit_pred[i][1]] for i in range(df.shape[0])]\r\n\r\n # Compute R**2 value\r\n if k_fold==1:\r\n residuals = np.subtract(np.log(fit_pred), np.log(df[['pSTAT1', 'pSTAT3']].values))\r\n ss_res = np.sum(residuals ** 2)\r\n ss_tot = np.sum((np.log(df[['pSTAT1', 'pSTAT3']].values) - np.log(np.mean(df[['pSTAT1', 'pSTAT3']].values))) ** 2)\r\n r_squared = 1 - (ss_res / ss_tot)\r\n print(\"r-squared value (log scale): \", r_squared)\r\n else:\r\n r_squared, r2_var = k_fold_cross_validate_SOCS_competes_STAT(k=k_fold)\r\n print(\"k-fold cross validation of R2 value (in log scale) is estimated to be {:.2f} +/- {:.2f}\".format(r_squared, np.sqrt(r2_var)))\r\n\r\n # Plot\r\n fit_prediction = pd.DataFrame.from_records(fit_pred_labelled, columns=['Cell_type', 'pSTAT1', 'pSTAT3'])\r\n fit_prediction.insert(0, 'Class', ['Model' for _ in range(df.shape[0])])\r\n measured_response = df[['Cell_type', 'pSTAT1', 'pSTAT3']]\r\n measured_response.insert(0, 'Class', ['CyTOF' for _ in range(df.shape[0])])\r\n\r\n df = pd.concat([fit_prediction, measured_response])\r\n\r\n fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12.8, 5))\r\n subplot_titles = ['pSTAT1', 'pSTAT3']\r\n sns.barplot(x=\"Cell_type\", y=\"pSTAT1\", data=df, hue='Class', ax=ax[0])\r\n sns.barplot(x=\"Cell_type\", y=\"pSTAT3\", data=df, hue='Class', ax=ax[1])\r\n for i in [0,1]:\r\n ax[i].set_xticklabels(ax[i].get_xticklabels(), rotation=90)\r\n ax[i].set_title(subplot_titles[i])\r\n\r\n if k_fold==1:\r\n plt.suptitle(r\"$R^{2}$ (log scale) = \"+ \"{:.2f}\".format(r_squared))\r\n else:\r\n plt.suptitle(r\"$R^{2}$ (log scale) = \" + \"{:.2f}\".format(r_squared) + \" ({}-fold cross-validation)\".format(k_fold))\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef compare_model_errors(df=ImmGen_df, neg_feedback_name='SOCS2'):\r\n # ------------\r\n # With SOCS\r\n # ------------\r\n pfit, pcov = fit_IFNg_with_SOCS_competes_STAT(neg_feedback_name, df)\r\n\r\n # Predict\r\n SOCS_model = make_SOCS_competes_STAT_model(neg_feedback_name)\r\n SOCS_fit_pred = np.reshape(SOCS_model(IFNg_dose, *pfit), (df.shape[0], len(response_variable_names)))\r\n\r\n # Residual\r\n SOCS_residuals = np.divide(np.subtract(SOCS_fit_pred, df[['pSTAT1', 'pSTAT3']].values), df[['pSTAT1', 'pSTAT3']].values)\r\n #SOCS_res_pred_labelled = [[df['Cell_type'].values[i], SOCS_residuals[i][0], SOCS_residuals[i][1]] for i in range(df.shape[0])]\r\n\r\n # ------------\r\n # Without SOCS\r\n # ------------\r\n pfit, pcov = fit_IFNg_equilibrium()\r\n\r\n # Predict\r\n fit_pred = np.reshape(equilibrium_model(IFNg_dose, *pfit), (df.shape[0], len(response_variable_names)))\r\n\r\n # Residual\r\n residuals = np.divide(np.subtract(fit_pred, df[['pSTAT1', 'pSTAT3']].values), df[['pSTAT1', 'pSTAT3']].values)\r\n #res_pred_labelled = [[df['Cell_type'].values[i], residuals[i][0], residuals[i][1]] for i in range(df.shape[0])]\r\n\r\n # ------------\r\n # Plot\r\n # ------------\r\n fig, ax = plt.subplots(nrows=1, ncols=2)\r\n for i in [0, 1]:\r\n ax[i].set_title('pSTAT{}'.format(i*2 + 1))\r\n ax[i].set_xscale('log')\r\n ax[i].set_yscale('log')\r\n ax[i].set_xlabel('% error in no-SOCS model')\r\n ax[i].set_ylabel('% error in SOCS model')\r\n ax[i].scatter(np.abs(residuals[:, i]), np.abs(SOCS_residuals[:, i]))\r\n ax[i].plot(np.logspace(np.log10(min(np.abs(residuals[:, i]))), np.log10(max(np.abs(residuals[:, i])))),\r\n np.logspace(np.log10(min(np.abs(residuals[:, i]))), np.log10(max(np.abs(residuals[:, i])))), 'k--')\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef fit_with_DREAM(sim_name, parameter_dict, likelihood):\r\n original_params = [parameter_dict[k] for k in parameter_dict.keys()]\r\n\r\n priors_list = []\r\n for p in original_params:\r\n priors_list.append(SampledParam(norm, loc=np.log(p), scale=1.0))\r\n # Set simulation parameters\r\n niterations = 10000\r\n converged = False\r\n total_iterations = niterations\r\n nchains = 5\r\n\r\n # Make save directory\r\n today = datetime.now()\r\n save_dir = \"PyDREAM_\" + today.strftime('%d-%m-%Y') + \"_\" + str(niterations)\r\n os.makedirs(os.path.join(os.getcwd(), save_dir), exist_ok=True)\r\n\r\n # Run DREAM sampling. Documentation of DREAM options is in Dream.py.\r\n sampled_params, log_ps = run_dream(priors_list, likelihood, start=np.log(original_params),\r\n niterations=niterations, nchains=nchains, multitry=False,\r\n gamma_levels=4, adapt_gamma=True, history_thin=1, model_name=sim_name,\r\n verbose=True)\r\n\r\n # Save sampling output (sampled parameter values and their corresponding logps).\r\n for chain in range(len(sampled_params)):\r\n np.save(os.path.join(save_dir, sim_name + str(chain) + '_' + str(total_iterations)), sampled_params[chain])\r\n np.save(os.path.join(save_dir, sim_name + str(chain) + '_' + str(total_iterations)), log_ps[chain])\r\n\r\n # Check convergence and continue sampling if not converged\r\n\r\n GR = Gelman_Rubin(sampled_params)\r\n print('At iteration: ', total_iterations, ' GR = ', GR)\r\n np.savetxt(os.path.join(save_dir, sim_name + str(total_iterations) + '.txt'), GR)\r\n\r\n old_samples = sampled_params\r\n if np.any(GR > 1.2):\r\n starts = [sampled_params[chain][-1, :] for chain in range(nchains)]\r\n while not converged:\r\n total_iterations += niterations\r\n\r\n sampled_params, log_ps = run_dream(priors_list, likelihood, start=starts, niterations=niterations,\r\n nchains=nchains, multitry=False, gamma_levels=4, adapt_gamma=True,\r\n history_thin=1, model_name=sim_name, verbose=True, restart=True)\r\n\r\n for chain in range(len(sampled_params)):\r\n np.save(os.path.join(save_dir, sim_name + '_' + str(chain) + '_' + str(total_iterations)),\r\n sampled_params[chain])\r\n np.save(os.path.join(save_dir, sim_name + '_' + str(chain) + '_' + str(total_iterations)),\r\n log_ps[chain])\r\n\r\n old_samples = [np.concatenate((old_samples[chain], sampled_params[chain])) for chain in range(nchains)]\r\n GR = Gelman_Rubin(old_samples)\r\n print('At iteration: ', total_iterations, ' GR = ', GR)\r\n np.savetxt(os.path.join(save_dir, sim_name + '_' + str(total_iterations) + '.txt'), GR)\r\n\r\n if np.all(GR < 1.2):\r\n converged = True\r\n try:\r\n # Plot output\r\n total_iterations = len(old_samples[0])\r\n burnin = int(total_iterations / 2)\r\n samples = np.concatenate(list((old_samples[i][burnin:, :] for i in range(len(old_samples)))))\r\n np.save(os.path.join(save_dir, sim_name+'_samples'), samples)\r\n ndims = len(old_samples[0][0])\r\n colors = sns.color_palette(n_colors=ndims)\r\n for dim in range(ndims):\r\n fig = plt.figure()\r\n sns.distplot(samples[:, dim], color=colors[dim])\r\n fig.savefig(os.path.join(save_dir, sim_name + '_dimension_' + str(dim) + '_' + list(parameter_dict.keys())[dim]+ '.pdf'))\r\n\r\n # Convert to dataframe\r\n df = pd.DataFrame(samples, columns=parameter_dict.keys())\r\n g = sns.pairplot(df)\r\n for i, j in zip(*np.triu_indices_from(g.axes, 1)):\r\n g.axes[i,j].set_visible(False)\r\n g.savefig(os.path.join(save_dir, 'corner_plot.pdf'))\r\n\r\n # Basic statistics\r\n mean_parameters = np.mean(samples, axis=0)\r\n median_parameters = np.median(samples, axis=0)\r\n np.save(os.path.join(save_dir, 'mean_parameters'), mean_parameters)\r\n np.save(os.path.join(save_dir, 'median_parameters'), median_parameters)\r\n df.describe().to_csv(os.path.join(save_dir, 'descriptive_statistics.csv'))\r\n\r\n except ImportError:\r\n pass\r\n return 0\r\n\r\n\r\ndef fit_IFNg_SOCS_competes_STAT_with_DREAM(SOCS_name, df=ImmGen_df):\r\n def __likelihood__(parameters, df=ImmGen_df):\r\n import numpy as np\r\n from scipy.stats import norm\r\n\r\n def __infer_protein__(dataset, cell_type, protein_names):\r\n if 'allSOCS' in protein_names:\r\n all_SOCS_names = ['SOCS1', 'SOCS2', 'SOCS3', 'SOCS4', 'SOCS5', 'SOCS6', 'SOCS7', 'CIS', 'SHP1', 'SHP2',\r\n 'PIAS1', 'PIAS2', 'PIAS3', 'PIAS4']\r\n SOCS_transcripts = np.sum(\r\n dataset.loc[dataset['Cell_type'] == cell_type][all_SOCS_names].values.flatten())\r\n transcripts = dataset.loc[dataset['Cell_type'] == cell_type][\r\n [p for p in protein_names if p != 'allSOCS']].values.flatten()\r\n d = dict(zip([p for p in protein_names if p != 'allSOCS'], transcripts))\r\n d['allSOCS'] = SOCS_transcripts\r\n return d\r\n else:\r\n transcripts = dataset.loc[dataset['Cell_type'] == cell_type][protein_names].values.flatten()\r\n # mean_transcripts = dataset.mean()[protein_names].values\r\n # proteins = [mean_transcripts[i] * 2**(np.log10(transcripts[i]/mean_transcripts[i])) for i in range(len(protein_names))]\r\n return dict(zip(protein_names, transcripts))\r\n\r\n parameters = np.exp(parameters) # parameters are passed in log form\r\n\r\n # Create the receptor models\r\n # global variables applicable to all receptors\r\n NA = 6.022E23\r\n cell_density = 1E6 # cells per mL\r\n volEC = 1E-3 / cell_density # L\r\n rad_cell = 5E-6 # m\r\n pi = np.pi\r\n volPM = 4 * pi * rad_cell ** 2 # m**2\r\n volCP = (4 / 3) * pi * rad_cell ** 3 # m**3\r\n\r\n cell_types = ['Granulocytes', 'Ly6Chi_Mo', 'Ly6Clo_Mo', 'preB_FrC', 'preB_FrD', 'MPP34F', 'ST34F', 'CMP', 'GMP',\r\n 'MEP', 'CDP', 'MDP', 'LT-HSC', 'ST-HSC', 'Mac_BM']\r\n base_parameters = {'pSTAT1': {'R_total': 2000, # infer from Immgen\r\n 'Delta': 0, # infer from Immgen\r\n 'CSF3r': 2000, # infer from Immgen\r\n 'Jak1': 1000, # infer from Immgen\r\n 'Jak2': 1000, # infer from Immgen\r\n 'STAT_total': 2000, # infer from Immgen\r\n SOCS_name: 200, # infer from Immgen\r\n 'USP18': 0, # infer from ImmGen\r\n 'K_ligand': NA*volEC/(4*pi*0.5E10), # from literature\r\n 'K_Jak1': 1E6/(NA*volCP), # fit for each receptor\r\n 'K_Jak2': 1E6/(NA*volCP), # fit for each receptor\r\n 'K_R1R2': 4*pi*0.5E-12/volPM, # from literature\r\n 'K_STAT': 1000/volPM, # fit for each receptor/STAT pair\r\n 'K_SOCS': 1000, # fit for each receptor\r\n 'K_USP18': 150}, # fit for each receptor\r\n\r\n 'pSTAT3': {'R_total': 2000,\r\n 'Delta': 0,\r\n 'CSF3r': 2000,\r\n 'Jak1': 1000,\r\n 'Jak2': 1000,\r\n 'STAT_total': 2000,\r\n SOCS_name: 200,\r\n 'USP18': 0,\r\n 'K_ligand': NA*volEC/(4*pi*0.5E10),\r\n 'K_Jak1': 1E6/(NA*volCP),\r\n 'K_Jak2': 1E6/(NA*volCP),\r\n 'K_R1R2': 4*pi*0.5E-12/volPM,\r\n 'K_STAT': 1000/volPM,\r\n 'K_SOCS': 1000,\r\n 'K_USP18': 150}\r\n }\r\n output_names = ['pSTAT1', 'pSTAT3']\r\n protein_names = ['CSF3r', 'JAK1', 'JAK2', 'STAT1', 'STAT3', SOCS_name, 'USP18']\r\n dose = 100 * 1E-12 * NA * volEC\r\n for STAT in output_names:\r\n base_parameters[STAT]['K_Jak1'] = parameters[0]\r\n base_parameters[STAT]['K_Jak2'] = parameters[1]\r\n base_parameters[STAT]['K_SOCS'] = parameters[4]\r\n base_parameters[STAT]['K_USP18'] = parameters[6]\r\n\r\n # receptor:STAT parameters\r\n base_parameters['pSTAT1']['K_STAT'] = parameters[2]\r\n base_parameters['pSTAT3']['K_STAT'] = parameters[3]\r\n\r\n fit_pred = []\r\n for c in cell_types:\r\n #transcripts = df.loc[df['Cell_type'] == c][protein_names].values.flatten()\r\n #mean_transcripts = df.mean()[protein_names].values\r\n #proteins = [mean_transcripts[i] * 2**(np.log10(transcripts[i]/mean_transcripts[i])) for i in range(len(protein_names))]\r\n\r\n #df.loc[df['Cell_type'] == c][protein_names].values.flatten()\r\n IFNg_ImmGen_parameters = __infer_protein__(df, c, protein_names)\r\n\r\n STAT_response = []\r\n for S in output_names:\r\n base_parameters[S]['R_total'] = IFNg_ImmGen_parameters['CSF3r']/(1+IFNg_ImmGen_parameters['USP18']/base_parameters[S]['K_USP18'])\r\n base_parameters[S]['Delta'] = 0\r\n base_parameters[S]['Jak1'] = IFNg_ImmGen_parameters['JAK1']\r\n base_parameters[S]['Jak2'] = IFNg_ImmGen_parameters['JAK2']\r\n base_parameters[S]['STAT_total'] = IFNg_ImmGen_parameters[S[1:]] # remove leading 'p' from 'pSTAT1' or 'pSTAT3'\r\n base_parameters[S][SOCS_name] = IFNg_ImmGen_parameters[SOCS_name]\r\n\r\n cytokine_R = base_parameters[S]['K_R1R2'] / 2 * \\\r\n (1 + base_parameters[S]['R_total'] / base_parameters[S]['K_R1R2'] - \\\r\n np.sqrt(1 + (2 * base_parameters[S]['R_total'] * base_parameters[S]['K_R1R2'] \\\r\n + base_parameters[S]['Delta'] ** 2) / base_parameters[S]['K_R1R2'] ** 2))\r\n PR1active = base_parameters[S]['Jak1'] * base_parameters[S]['K_Jak1'] / (1 + base_parameters[S]['Jak1'] * base_parameters[S]['K_Jak1'])\r\n PR2active = base_parameters[S]['Jak2'] * base_parameters[S]['K_Jak2'] / (1 + base_parameters[S]['Jak2'] * base_parameters[S]['K_Jak2'])\r\n Rstar = cytokine_R * PR1active * PR2active / (1 + base_parameters[S]['K_ligand'] / dose)\r\n response = base_parameters[S]['STAT_total'] / (1 + base_parameters[S]['K_STAT'] * (\r\n 1 + base_parameters[S][SOCS_name] / base_parameters[S]['K_SOCS']) * volPM / Rstar)\r\n response = response / parameters[5]\r\n STAT_response.append(response)\r\n fit_pred.append(STAT_response)\r\n\r\n # sse\r\n # GCSF at 100 pM\r\n data = [[14.6, 37.26],\r\n [2.43, 16.9],\r\n [1.42, 5.54],\r\n [0.18, 0.32],\r\n [0.64, 0.41],\r\n [2.32, 51.8],\r\n [0.18, 34.2],\r\n [2.49, 18.53],\r\n [1.74, 22.65],\r\n [1.05, 10.8],\r\n [1.09, 3.14],\r\n [1.51, 27.3],\r\n [1.99, 11.68],\r\n [1.09, 29.66],\r\n [4.9, 7.4]]\r\n\r\n like_ctot = norm(loc=np.log10(data), scale=np.ones(np.shape(data)))\r\n logp_ctotal = np.sum(like_ctot.logpdf(np.log10(fit_pred)))\r\n\r\n # If model simulation failed due to integrator errors, return a log probability of -inf.\r\n if np.isnan(logp_ctotal):\r\n logp_ctotal = -np.inf\r\n return logp_ctotal\r\n\r\n\r\n #min_response_row = df.loc[df[response_variable_names[0]].idxmin()]\r\n #min_response_SOCS_expression = infer_protein(df, min_response_row.loc['Cell_type'], [SOCS_name])[SOCS_name]\r\n # old: [1E7 / (NA * volCP), 1E6 / (NA * volCP), 900 / volPM, 1000 / volPM, min_response_SOCS_expression, 1]\r\n # K_Jak1, K_Jak2, K_STAT_STAT1, K_STAT_STAT3, K_SOCS, scale_factor\r\n prior = [3.17147014e-03, 3.17147014e+00, 3.18309889e+11, 1.00760330e+12, 1.67829414e-02, 1e-01, 150]\r\n prior = dict(zip(['K_Jak1', 'K_Jak2', 'K_STAT_STAT1', 'K_STAT_STAT3', 'K_SOCS', 'scale_factor', 'K_USP18'], prior))\r\n\r\n fit_with_DREAM(SOCS_name, prior, __likelihood__)\r\n\r\n\r\ndef sample_DREAM_IFNg_SOCS_competes_STAT(samples_filename, neg_feedback_name, df=ImmGen_df, step_size=500, find_map=True):\r\n samples = np.load(samples_filename)\r\n # Convert back to true value rather than log value\r\n converted_samples = np.exp(samples)\r\n\r\n # Predict\r\n SOCS_model = make_SOCS_competes_STAT_model(neg_feedback_name)\r\n fit_pred = []\r\n sample_count = 0\r\n for p in range(0, len(converted_samples), step_size):\r\n sample_count += 1\r\n pred = np.reshape(SOCS_model(IFNg_dose, *converted_samples[p]), (15, len(response_variable_names)))\r\n pred_labelled = [['Model', df['Cell_type'].values[i], pred[i][0], pred[i][1]] for i in range(df.shape[0])]\r\n fit_pred += pred_labelled\r\n print(\"{} samples used\".format(sample_count))\r\n\r\n fit_prediction = pd.DataFrame.from_records(fit_pred, columns=['Class', 'Cell_type', 'pSTAT1', 'pSTAT3'])\r\n\r\n cell_type_pred = fit_prediction.drop('Class', axis=1).groupby('Cell_type')\r\n\r\n # Compute posterior predictive p-value\r\n # First compute the posterior of the test statistic. Use the residual from the log[median prediction].\r\n # The motivation for this is that for log-normal distributed predictions, the median is the point\r\n # for which there is a 50 % chance of a given posterior prediction being greater.\r\n # i.e. E[log[median prediction] - log[data]] = 0 when median prediction = data\r\n log_median_pred = np.log(cell_type_pred.median().values)\r\n test_statistic_distribution = []\r\n total_res_samples = 0\r\n for p in range(0, len(converted_samples), step_size):\r\n total_res_samples += 1\r\n log_pred = np.log(np.reshape(SOCS_model(IFNg_dose, *converted_samples[p]), (15, len(response_variable_names))))\r\n residual = np.sum(np.subtract(log_median_pred, log_pred))\r\n test_statistic_distribution.append(residual)\r\n # Compute what fraction of predictions have a residual greater than the median with the observed data\r\n data_residual = np.sum(np.subtract(log_median_pred, np.log(df[['pSTAT1', 'pSTAT3']].values)))\r\n r_count = 0\r\n for r in test_statistic_distribution:\r\n if r > data_residual:\r\n r_count += 1\r\n ppp_value = r_count/total_res_samples\r\n\r\n # Plot\r\n fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12.8, 5))\r\n #ax[0].set_yscale('log')\r\n #ax[1].set_yscale('log')\r\n subplot_titles = ['pSTAT1', 'pSTAT3']\r\n measured_response = df[['Cell_type', 'pSTAT1', 'pSTAT3']]\r\n measured_response.insert(0, 'Class', ['CyTOF' for _ in range(df.shape[0])])\r\n\r\n plot_df = pd.concat([fit_prediction, measured_response])\r\n\r\n sns.catplot(x=\"Cell_type\", y=\"pSTAT1\", data=plot_df[plot_df['Class']=='Model'], hue='Class', ax=ax[0], kind=\"bar\")\r\n sns.catplot(x=\"Cell_type\", y=\"pSTAT3\", data=plot_df[plot_df['Class']=='Model'], hue='Class', ax=ax[1], kind=\"bar\")\r\n\r\n sns.catplot(x=\"Cell_type\", y=\"pSTAT1\", data=plot_df[plot_df['Class'] == 'CyTOF'], hue='Class', ax=ax[0],\r\n kind=\"strip\", size=8, palette=sns.color_palette(\"hls\", 16))\r\n sns.catplot(x=\"Cell_type\", y=\"pSTAT3\", data=plot_df[plot_df['Class']=='CyTOF'], hue='Class', ax=ax[1],\r\n kind=\"strip\", size=8, palette=sns.color_palette(\"hls\", 16))\r\n for i in [0, 1]:\r\n ax[i].set_xticklabels(ax[i].get_xticklabels(), rotation=90)\r\n ax[i].set_title(subplot_titles[i])\r\n fig.suptitle(\"Posterior p-value = {:.2f}\\n (p close to 0.5 is good)\".format(ppp_value), fontsize=12)\r\n #plt.tight_layout()\r\n plt.show()\r\n\r\n # Find best single estimator\r\n if find_map:\r\n best_parameter = []\r\n best_residual = 1E16\r\n data = np.log(df[['pSTAT1', 'pSTAT3']].values.clip(min=1E-6)) # necessary because there are a few negative meas.\r\n for p in range(0, len(converted_samples), 1):\r\n log_pred = np.log(np.reshape(SOCS_model(IFNg_dose, *converted_samples[p]), (15, len(response_variable_names))))\r\n square_residual = np.sum(np.square(np.subtract(log_pred, data)))\r\n if square_residual < best_residual:\r\n best_parameter = converted_samples[p]\r\n best_residual = square_residual\r\n print(best_parameter)\r\n print(best_residual)\r\n\r\n\r\ndef compare_model_to_ImmGen(pset, SOCS_name='SOCS2'):\r\n # Predict\r\n SOCS_model = make_SOCS_competes_STAT_model(SOCS_name)\r\n fit_pred = np.reshape(SOCS_model(IFNg_dose, *pset), (ImmGen_df.shape[0], len(response_variable_names)))\r\n fit_pred_labelled = [[ImmGen_df['Cell_type'].values[i], fit_pred[i][0], fit_pred[i][1]] for i in\r\n range(ImmGen_df.shape[0])]\r\n\r\n # R-squared\r\n residuals = np.subtract(np.log(fit_pred), np.log(ImmGen_df[['pSTAT1', 'pSTAT3']].values.clip(min=1E-6)))\r\n ss_res = np.sum(np.square(residuals))\r\n ss_tot = np.sum(np.square((np.log(ImmGen_df[['pSTAT1', 'pSTAT3']].values.clip(min=1E-6)) - np.log(np.mean(ImmGen_df[['pSTAT1', 'pSTAT3']].values.clip(min=1E-6))))))\r\n r_squared = 1 - (ss_res / ss_tot)\r\n\r\n # non-log R-squared\r\n residuals = np.subtract(fit_pred, ImmGen_df[['pSTAT1', 'pSTAT3']].values.clip(min=1E-6))\r\n ss_res = np.sum(np.square(residuals))\r\n ss_tot = np.sum(np.square((ImmGen_df[['pSTAT1', 'pSTAT3']].values.clip(min=1E-6) - np.mean(ImmGen_df[['pSTAT1', 'pSTAT3']].values.clip(min=1E-6)))))\r\n print(\"r-squared (linear) = \", 1 - (ss_res / ss_tot))\r\n\r\n # Plot\r\n fit_prediction = pd.DataFrame.from_records(fit_pred_labelled, columns=['Cell_type', 'pSTAT1', 'pSTAT3'])\r\n fit_prediction.insert(0, 'Class', ['Model' for _ in range(ImmGen_df.shape[0])])\r\n measured_response = ImmGen_df[['Cell_type', 'pSTAT1', 'pSTAT3']]\r\n measured_response.insert(0, 'Class', ['CyTOF' for _ in range(ImmGen_df.shape[0])])\r\n\r\n df = pd.concat([fit_prediction, measured_response])\r\n\r\n fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12.8, 5))\r\n fig.suptitle('R-squared (log scale) = {:.2f}'.format(r_squared))\r\n subplot_titles = ['pSTAT1', 'pSTAT3']\r\n sns.barplot(x=\"Cell_type\", y=\"pSTAT1\", data=df, hue='Class', ax=ax[0])\r\n sns.barplot(x=\"Cell_type\", y=\"pSTAT3\", data=df, hue='Class', ax=ax[1])\r\n for i in [0, 1]:\r\n ax[i].set_xticklabels(ax[i].get_xticklabels(), rotation=90)\r\n ax[i].set_title(subplot_titles[i])\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n # Measured vs Predicted\r\n fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12.8, 5))\r\n fig.suptitle('R-squared (log scale) = {:.2f}'.format(r_squared))\r\n subplot_titles = ['pSTAT1', 'pSTAT3']\r\n ax[0].scatter(measured_response.pSTAT1.values, fit_prediction.pSTAT1.values)\r\n ax[0].plot([0, 20], [0, 20], 'k--')\r\n ax[1].scatter(measured_response.pSTAT3.values, fit_prediction.pSTAT3.values)\r\n ax[1].plot([0, 40], [0, 40], 'k--')\r\n for i in [0, 1]:\r\n ax[i].set_title(subplot_titles[i])\r\n ax[i].set_xlabel('Measured')\r\n ax[i].set_ylabel('Predicted')\r\n plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n # Check variance in predictors\r\n #df = ImmGen_df[response_variable_names + predictor_variable_names]\r\n #print(pd.Series(np.diag(df.cov().values), index=df.columns))\r\n\r\n #pairwise_correlation()\r\n #SOCS_histograms()\r\n\r\n #fit_without_SOCS()\r\n #fit_with_SOCS_competes_STAT(neg_feedback_name='allSOCS')\r\n\r\n #compare_model_errors()\r\n\r\n #print(ec50_for_all_cell_types('SOCS2'))\r\n #make_ec50_predictions_plot()\r\n\r\n #fit_IFNg_SOCS_competes_STAT_with_DREAM('SOCS7')\r\n\r\n save_dir = \"PyDREAM_04-12-2019_10000_GCSF\"\r\n sim_name = \"SOCS7\"\r\n #sample_DREAM_IFNg_SOCS_competes_STAT(os.path.join(save_dir, sim_name+'_samples' + '.npy'), sim_name, step_size=250, find_map=True)\r\n\r\n ## ['K_Jak1', 'K_Jak2', 'K_STAT_STAT1', 'K_STAT_STAT3', 'K_SOCS', 'scale_factor', 'K_USP18']\r\n #min_response_row = ImmGen_df.loc[ImmGen_df[response_variable_names[0]].idxmin()]\r\n #min_response_SOCS_expression = infer_protein(ImmGen_df, min_response_row.loc['Cell_type'], [sim_name])[sim_name]\r\n # [1E7 / (NA * volCP), 1E6 / (NA * volCP), 900 / volPM, 1000 / volPM, 0.006*min_response_SOCS_expression, 0.5]\r\n #p_prior = [3.171470138e-02, 3.17147013799e-03, 2.864788975654e+12, 3.183098861837e+12, 5.77815e-01, 5e-01]\r\n p_best = [3.17147014e-03, 3.17147014e+00, 3.18309889e+11, 1.00760330e+12, 1.67829414e-02, 1e-01]\r\n\r\n # SOCSS2\r\n p_best_by_MCMC = [9.19293300e+02, 3.33434463e+01, 2.20985969e+04, 2.71081941e+02, 4.54009422e-01, 4.88918115e+01, 1.49339725e-03]\r\n\r\n # SOCS7\r\n #p_best_by_MCMC = [98.96069551, 850.44550422, 97.8516537, 448.41519007, 52.27743194, 437.50172928, 353.38670015]\r\n compare_model_to_ImmGen(p_best_by_MCMC, SOCS_name='SOCS2')\r\n\r\n","sub_path":"ifnscripts/NIH/equilibrium_GCSF.py","file_name":"equilibrium_GCSF.py","file_ext":"py","file_size_in_byte":48322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"219674583","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/chris/GitHub/MetaWards/build/lib.macosx-10.9-x86_64-3.7/metawards/_variableset.py\n# Compiled at: 2020-04-17 13:53:44\n# Size of source mod 2**32: 21907 bytes\nfrom typing import List as _List\nfrom typing import Dict as _Dict\n__all__ = [\n 'VariableSets', 'VariableSet']\n\nclass VariableSet:\n __doc__ = 'This class holds a single set of adjustable variables that\\n are used to adjust the variables as part of a model run\\n\\n Examples\\n --------\\n >>> v = VariableSet()\\n >>> v[\"beta[1]\"] = 0.95\\n >>> v[\"beta[2]\"] = 0.9\\n >>> print(v.fingerprint())\\n (beta[1]=0.95, beta[2]=0.9)[repeat 1]\\n >>> params = Parameters()\\n >>> params.set_disease(\"ncov\")\\n >>> v.adjust(params)\\n >>> print(params.disease_params.beta[1],\\n >>> params.disease_params.beta[2])\\n 0.95 0.9\\n '\n\n def __init__(self, variables: _Dict[(str, float)]=None, repeat_index: int=1, names: _List[str]=None, values: _List[float]=None):\n \"\"\"Construct a new VariableSet from the passed adjusted variable\n values.\n\n Parameters\n ----------\n names: List[str]\n The list of the names of the variables to adjust\n values: List[float]\n The values of the variables to adjust (same order as names)\n variables: Dict[str, float]\n names and values of variables to adjust passed as a dictionary\n repeat_index: int\n the index used to distinguish different repeats of the same\n VariableSet from one another\n\n Examples\n --------\n >>> v = VariableSet()\n >>> v[\"beta[1]\"] = 0.95\n >>> v[\"beta[2]\"] = 0.9\n >>> print(v.fingerprint())\n (beta[1]=0.95, beta[2]=0.9)[repeat 1]\n \"\"\"\n self._names = None\n self._vals = None\n self._varnames = None\n self._varidxs = None\n self._idx = None\n if variables is not None:\n for name, value in variables.items():\n self._add(name, value)\n\n if values is not None:\n if names is None:\n names = [\n 'beta[2]', 'beta[3]', 'progress[1]',\n 'progress[2]', 'progress[3]']\n if len(names) != len(values):\n raise IndexError(f\"The number of variable values '{values}' must equal the number of variable names '{names}'\")\n for name, value in zip(names, values):\n self._add(name, value)\n\n self._idx = repeat_index\n\n def __str__(self):\n \"\"\"Return a printable representation of the variables to\n be adjusted\n \"\"\"\n s = []\n if self._vals is not None:\n if len(self._vals) > 0:\n for key, value in zip(self._names, self._vals):\n s.append(f\"{key}={value}\")\n\n if len(s) == 0:\n return f\"(NO_CHANGE)[repeat {self._idx}]\"\n return f\"({', '.join(s)})[repeat {self._idx}]\"\n\n def __repr__(self):\n return str(self)\n\n def __eq__(self, other):\n if isinstance(other, dict):\n other = VariableSet(variables=other)\n if self._idx != other._idx:\n return False\n if len(self) != len(other):\n return False\n if self._vals is None:\n return\n for i in range(0, len(self._vals)):\n if self._vals[i] != other._vals[i]:\n return False\n if self._varnames[i] != other._varnames[i]:\n return False\n if self._varidxs[i] != other._varidxs[i]:\n return False\n if self._names[i] != other._names[i]:\n return False\n\n return True\n\n def __len__(self):\n if self._vals is None:\n return 0\n return len(self._vals)\n\n def __getitem__(self, key):\n if self._vals is None:\n raise KeyError(f\"No adjustable parameter {key} in an empty set\")\n for i, name in enumerate(self._names):\n if key == name:\n return self._vals[i]\n\n raise KeyError(f\"No adjustable parameter {key}. Available parameters are '{self._names}'\")\n\n def __setitem__(self, key, value):\n if self._names is None:\n self._names = []\n for i, name in enumerate(self._names):\n if key == name:\n self._vals[i] = value\n return\n\n self._add(key, value)\n\n def _add(self, name, value):\n \"\"\"Internal function to add a new variable called 'name' to\n be varied - it will be set equal to 'value'\n \"\"\"\n import re\n if self._vals is None:\n self._names = []\n self._vals = []\n self._varnames = []\n self._varidxs = []\n else:\n name = name.strip()\n m = re.search('(\\\\w+)\\\\[(\\\\d+)\\\\]', name)\n if m:\n self._varnames.append(m.group(1))\n self._varidxs.append(int(m.group(2)))\n self._names.append(name)\n self._vals.append(float(value))\n else:\n self._varnames.append(name)\n self._varidxs.append(None)\n self._names.append(name)\n self._vals.append(float(value))\n\n def variable_names(self):\n \"\"\"Return the names of the variables that will be adjusted\n by this VariableSet\n\n Returns\n -------\n names: List[str]\n The list of names of variables to be adjusted\n \"\"\"\n if self._vals is None or len(self._vals) == 0:\n return\n from copy import deepcopy\n return deepcopy(self._names)\n\n def variable_values(self):\n \"\"\"Return the values that the variables will be adjusted to.\n Note that 'None' means that the variable won't be adjusted\n from its default (original) value\n\n Returns\n -------\n values: List[float]\n The list of values for variables to be adjusted to\n \"\"\"\n if self._vals is None or len(self._vals) == 0:\n return\n from copy import deepcopy\n return deepcopy(self._vals)\n\n def variables(self):\n \"\"\"Return the variables (name and values) to be adjusted\n\n Returns\n -------\n variables: Dict[str, float]\n The dictionary mapping the names of the variables that\n with be adjusted to their desired values\n \"\"\"\n v = {}\n for name, value in zip(self._names, self._vals):\n v[name] = value\n\n return v\n\n def repeat_index(self):\n \"\"\"Return the repeat index of this set. The repeat index is the\n ID of this set if the VariableSet is repeated. The index should\n range from 1 to nrepeats\n\n Returns\n -------\n index: int\n The repeat index of this set\n \"\"\"\n return self._idx\n\n def make_compatible_with(self, other):\n \"\"\"Return a copy of this VariableSet which has been made\n compatible with 'other'. This means that it will change\n the same variables as 'other', e.g. by adding 'None'\n changes for missing variables. This will raise an error\n if it is not possible to make this set compatible\n\n Parameters\n ----------\n other: VariableSet\n The passed VariableSet for which this should be made compatible\n\n Returns\n -------\n result: VariableSet\n A copy of this VariableSet which is now compatible with 'other'\n\n Example\n -------\n >>> v1 = VariableSet()\n >>> v1[\"beta1\"] = 0.9\n >>> v1[\"beta2\"] = 0.8\n\n >>> v2 = VariableSet()\n >>> v2[\"beta1\"] = 0.6\n >>> v2 = v2.make_compatible_with(v1)\n >>> print(v2)\n (beta1=0.6, beta2=0.8)[repeat 1]\n \"\"\"\n from copy import deepcopy\n if self._names is None:\n v = deepcopy(other)\n v._idx = self._idx\n return v\n if other._names is None:\n raise ValueError(f\"VariableSet {self} is not compatible with VariableSet {other}\")\n nmatch = 0\n for name in self._names:\n if name not in other._names:\n raise ValueError(f\"VariableSet {self} is not compatible with VariableSet {other}\")\n nmatch += 1\n\n if len(other._names) == nmatch:\n return deepcopy(self)\n v = deepcopy(self)\n for name in other._names:\n if name not in self._names:\n v[name] = other[name]\n\n return v\n\n @staticmethod\n def extract_values(fingerprint: str):\n \"\"\"Return the original values from the passed fingerprint\n or filename. This assumes that the fingerprint\n was created using the 'fingerprint' function, namely\n that any integers are actually 0.INTEGER\n\n Parameters\n ----------\n fingerprint: str\n The fingerprint (or filename) to decode\n\n Returns\n -------\n (values, repeat): (List[float], int)\n The list of values of the variables and the repeat\n index. The repeat index is None if it wasn't included\n in the fingerprint\n \"\"\"\n from pathlib import Path\n fingerprint = Path(Path(fingerprint).name)\n for suffix in fingerprint.suffixes:\n fingerprint = str(fingerprint).replace(suffix, '')\n\n parts = fingerprint.split('-')\n if len(parts) > 1:\n repeat_index = int(parts[(-1)])\n fingerprint = '-'.join(parts[0:-1])\n else:\n repeat_index = None\n values = []\n for part in fingerprint.split('_'):\n try:\n if part.startswith('~'):\n scl = -1.0\n part = part[1:]\n else:\n scl = 1.0\n if part.find('.') != -1:\n value = float(part)\n else:\n part = f\"0.{part}\"\n value = float(part)\n values.append(value)\n except Exception:\n pass\n\n return (values, repeat_index)\n\n def fingerprint(self, include_index: bool=False):\n \"\"\"Return a fingerprint for this VariableSet. This can be\n used to quickly identify and distinguish the values of\n the variables in this set from the values in other\n VariableSets which have the same adjustable variables,\n but different parameters\n\n Parameters\n ----------\n include_index: bool\n Whether or not to include the repeat_index in the fingerprint\n\n Returns\n -------\n fingerprint: str\n The fingerprint for this VariableSet\n \"\"\"\n if self._vals is None or len(self._vals) == 0:\n f = 'NO_CHANGE'\n else:\n f = None\n for val in self._vals:\n v = str(val)\n if v.startswith('-'):\n v = v[1:]\n if v.startswith('0'):\n v = v[1:]\n if v.startswith('.'):\n v = v[1:]\n if val < 0:\n v = '~' + v\n if f is None:\n f = v\n else:\n f += '_' + v\n\n if include_index:\n return '%s-%03d' % (f, self._idx)\n return f\n\n def adjust(self, params):\n \"\"\"Use the variables in this set to adjust the passed parameters.\n Note that this directly modifies 'params'\n\n Parameters\n ----------\n params: Parameters\n The parameters whose variables will be adjusted\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> v = VariableSet()\n >>> v[\"beta[1]\"] = 0.95\n >>> v[\"beta[2]\"] = 0.9\n >>> print(v.fingerprint())\n (beta[1]=0.95, beta[2]=0.9)[repeat 1]\n >>> params = Parameters()\n >>> params.set_disease(\"ncov\")\n >>> v.adjust(params)\n >>> print(params.disease_params.beta[1],\n >>> params.disease_params.beta[2])\n 0.95 0.9\n \"\"\"\n if self._vals is None or len(self._vals) == 0:\n return\n try:\n for varname, varidx, value in zip(self._varnames, self._varidxs, self._vals):\n if value is not None:\n if varname == 'beta':\n params.disease_params.beta[varidx] = value\n elif varname == 'progress':\n params.disease_params.progress[varidx] = value\n elif varname == 'too_ill_to_move':\n params.disease_params.too_ill_to_move[varidx] = value\n elif varname == 'contrib_foi':\n params.disease_params.contrib_foi[varidx] = value\n else:\n raise KeyError(f\"Cannot set unrecognised parameter {varname} to {value}\")\n\n except Exception as e:\n try:\n raise ValueError(f\"Unable to set parameters from {self}. Error equals {e.__class__}: {e}\")\n finally:\n e = None\n del e\n\n\nclass VariableSets:\n __doc__ = 'This class holds the collection of all VariableSet objects\\n that contain the set of adjustable variables that are used\\n to control a single run of the model\\n\\n Examples\\n --------\\n >>> v = VariableSets()\\n >>> v.append({\"beta[2]\": 0.95, \"beta[3]\": 0.9})\\n >>> v.append({\"beta[1]\": 0.86, \"beta[2]\": 0.89})\\n >>> print(v)\\n {(beta[2]=0.95, beta[3]=0.9)[repeat 1], (beta[1]=0.86,\\n beta[2]=0.89)[repeat 1]}\\n >>> v = v.repeat(2)\\n >>> print(v)\\n {(beta[2]=0.95, beta[3]=0.9)[repeat 1], (beta[1]=0.86,\\n beta[2]=0.89)[repeat 1], (beta[2]=0.95, beta[3]=0.9)[repeat 2],\\n (beta[1]=0.86, beta[2]=0.89)[repeat 2]}\\n '\n\n def __init__(self):\n \"\"\"Initialise an empty VariableSets object\n\n Parameters\n ----------\n None\n\n Returns\n -------\n None\n \"\"\"\n self._vars = []\n\n def __str__(self):\n s = []\n for v in self._vars:\n s.append(str(v))\n\n if len(s) == 1:\n return s[0]\n if len(s) > 0:\n return '{' + ', '.join(s) + '}'\n return 'VariableSets:empty'\n\n def __repr__(self):\n return str(self)\n\n def __eq__(self, other):\n if isinstance(other, dict):\n v = VariableSet(variables=other)\n other = VariableSets()\n other.append(v)\n if len(self._vars) != len(other._vars):\n return False\n for v0, v1 in zip(self._vars, other._vars):\n if v0 != v1:\n return False\n\n return True\n\n def __len__(self):\n if self._vars is None:\n return 0\n return len(self._vars)\n\n def __getitem__(self, i: int):\n \"\"\"Return the VariableSet at the specified index\"\"\"\n if self._vars is None:\n raise IndexError('Cannot index an empty VariableSets object')\n else:\n return self._vars[i]\n\n def append(self, variables: VariableSet):\n \"\"\"Append the passed set of variables to the set that will\n be used to run a model. If there are any existing\n VariableSet objects in this list, then the new VariableSet\n must adjust the same variables\n\n Parameters\n ----------\n variables: VariableSet\n The VariableSet to append to this list. If you pass a\n dict of {str: float} values, then this will automatically\n be converted into a VariableSet. Note that all VariableSet\n objects in a VariableSets must adjust the same variables\n\n Returns\n -------\n None\n \"\"\"\n if isinstance(variables, dict):\n variables = VariableSet(variables=variables)\n if self._vars is None:\n self._vars = []\n if len(self._vars) > 0:\n variables = variables.make_compatible_with(self._vars[0])\n self._vars.append(variables)\n\n def repeat(self, nrepeats: int):\n \"\"\"Return a copy of this VariableSet in which all of the\n unique VaribleSet objects have been repeated 'nrepeats'\n times\n\n Parameters\n ----------\n nrepeats: int\n The number of repeats of the VariableSet objects to\n perform\n\n Returns\n -------\n repeats: VariableSets\n A new VariableSets object containing 'nrepeats' copies\n of the VariableSet objects from this set\n \"\"\"\n if nrepeats <= 1:\n return self\n from copy import deepcopy\n repeats = VariableSets()\n for i in range(1, nrepeats + 1):\n for v in self._vars:\n v2 = deepcopy(v)\n v2._idx = i\n repeats.append(v2)\n\n return repeats\n\n @staticmethod\n def read(filename: str, line_numbers: _List[int]=None):\n \"\"\"Read and return collection of VariableSet objects from the\n specified line number(s) of the specified file\n\n Parameters\n ----------\n filename: str\n The name of the file from which to read the VariableSets\n line_numbers: List[int]\n The line numbers from the file to read. This is 0-indexed,\n meaning that the first line is line 0. If this is None,\n then all lines are read and used\n\n Returns\n -------\n variables: VariableSets\n The collection of VariableSet objects that have been read,\n in the order they were read from the file\n \"\"\"\n if not isinstance(line_numbers, list):\n if line_numbers is not None:\n line_numbers = [\n line_numbers]\n variables = VariableSets()\n i = -1\n with open(filename, 'r') as (FILE):\n line = FILE.readline()\n first_line = None\n separator = ','\n titles = [\n 'beta[2]', 'beta[3]', 'progress[1]',\n 'progress[2]', 'progress[3]']\n while line:\n i += 1\n line = line.strip()\n if first_line is None:\n if len(line) > 0:\n if line.find(',') != -1:\n separator = ','\n else:\n separator = None\n first_line = line\n words = line.split(separator)\n try:\n float(words[0])\n is_title_line = False\n except Exception:\n is_title_line = True\n\n if is_title_line:\n titles = words\n line = FILE.readline()\n continue\n if line_numbers is None or i in line_numbers:\n words = line.split(separator)\n if len(words) != len(titles):\n raise ValueError(f\"Corrupted input file. Expecting {len(titles)} values. Received {line}\")\n vals = []\n try:\n for word in words:\n vals.append(float(word))\n\n except Exception:\n raise ValueError(f\"Corrupted input file. Expected {len(titles)} numbers. Received {line}\")\n\n variables.append(VariableSet(names=titles, values=vals))\n if line_numbers is not None:\n if len(variables) == len(line_numbers):\n return variables\n line = FILE.readline()\n\n if line_numbers is None:\n return variables\n raise ValueError(f\"Cannot read parameters from line {line_numbers} as the number of lines in the file is {i + 1}\")","sub_path":"pycfiles/metawards-0.7.1-cp37-cp37m-macosx_10_9_x86_64/_variableset.cpython-37.py","file_name":"_variableset.cpython-37.py","file_ext":"py","file_size_in_byte":20676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466511691","text":"# Jack C. Cook\n# Sunday, January 31, 2021\n\n\"\"\"\nBlackbody Radiation:\nThis file will include all functions associated with black body radiation\n\"\"\"\n\nfrom math import pi, exp\nfrom scipy.integrate import quad\nimport numpy as np\nnp.warnings.filterwarnings('ignore')\nfrom scipy.interpolate import interp1d\nfrom itertools import count\nfrom itertools import takewhile\nfrom scipy.integrate import cumtrapz\n\n\ndef Eblambda(lmbda: float, T: float, n: float = 1):\n \"\"\"\n The relatiion for the spectral blackbody emissive power Eb,lambda was developed by Max Planck in\n 1901. This formulation is also referred to as Planck's law.\n\n Equation 12-4 on page 720.\n\n E_{b\\lambda}(\\lambda,T) = \\dfrac{C_1}{\\lambda^5[exp(C_2/\\lambda T)-1]}\\;\\;\\;(W/m^2\\cdot\\mu m)\n\n :param T: the temperature of the surface (K)\n :param lmbda: the wavelength of the radiation emitted (micrometers)\n :param n: refractive index, assumed to be 1 (air)\n :return: the spectral black body emissive power at some temperature and wavelength (W/m^2/micrometer)\n \"\"\"\n # Constants\n # c_0: the speed of light in a vacuum\n c_0: float = 2.9979 * 10**8 # (m/s)\n # k: Boltzmann's constant\n k: float = 1.38065 * 10**(-23) # (J/K)\n # h: Planck's constant\n h: float = 6.626 * 10**(-34)\n\n # Convert micrometers to meters, for every one million micrometers there is one meter\n mm_to_m: float = 10 ** 6\n lmbda /= mm_to_m\n\n # Compute additional constants\n C_1: float = 2 * pi * h * c_0**2\n C_2: float = h * c_0 / k\n\n numerator: float = C_1\n\n # Theres some floating point issues with this function at some values\n denominator: float = lmbda**5 / n**2 * (np.exp(C_2/(n * lmbda * T))-1)\n\n return numerator / denominator / mm_to_m\n\n\ndef Eb(T: float):\n \"\"\"\n Equation 12-6 on page 722.\n\n The total black body emissive power integrated over the whole range\n :param T: the temperature of the surface (K)\n :return: the total black body emissive power (W/m^2)\n \"\"\"\n y, erf = quad(Eblambda, 0, np.inf, args=(T,))\n return y, erf\n\n\ndef Eb_vectorized(T: np.ndarray):\n \"\"\"\n The Eb(T) function specifically takes in one temperature float value.\n To make use of the function by passing a numpy array, the function must be vectorized.\n\n\n Parameters\n ----------\n T: np.ndarray\n A numpy matrix of size (m, n)\n\n Returns\n -------\n The black body emissive power matrix that is the same size as the input T matrix\n \"\"\"\n\n def call_Eb(Temp):\n y, erf = Eb(Temp)\n return y\n\n _Eb = np.vectorize(call_Eb)\n return _Eb(T)\n\n\ndef Eb_0_lambda(lmbda: float, T: float):\n \"\"\"\n Integrate over some wavelength band.\n\n Equation 12-7\n\n :param lmbda: the wavelength of the radiation emitted (micrometers)\n :param T: the temperature of the surface (K)\n :return: the black body emissive power over some band (W/m^2)\n \"\"\"\n return quad(Eblambda, 0, lmbda, args=(T,))\n\n\ndef f_lambda(lmbda: float, T: float):\n \"\"\"\n The fraction of radiation emitted from a blackbody at temperature T\n in the wavelength band from lambda = 0 to lambda.\n\n Equation 12-8 on page 724\n\n :param lmbda: the wavelength of the radiation emitted (micrometers)\n :param T: the temperature of the surface (K)\n :return: The blackbody radiation function\n \"\"\"\n y_num, _ = Eb_0_lambda(lmbda, T)\n y_den, _ = Eb(T)\n\n return y_num / y_den\n\n\ndef effective_spectral(lmbda_1: float, lmbda_2: float, T: float, f: interp1d, step: float=.01):\n \"\"\"\n Find the effective or average\n Parameters\n ----------\n lmbda_1: float\n The $\\lambda_1$ in micrometers\n lmbda_2: float\n The $\\lambda_2$ in micrometers\n T: float\n Temperature of the surface of the blackbody\n f: interp1d\n A 1d scipy interpolation of the $\\alpha$, $\\rho$, $\\tau$\n\n Returns\n -------\n The effective or average spectral hemispherical __\n \"\"\"\n def any_range(start, stop, step):\n start = type(start + step)(start)\n return takewhile(lambda n: n < stop, count(start, step))\n\n y_den, _ = Eb(T)\n # lambda_1 may need to be 0.1\n wavelengths: list = list(any_range(lmbda_1, lmbda_2, step))\n eff_Eblambdas: list = []\n Eblambdas: list = []\n for _, lmbda in enumerate(wavelengths):\n Eblmda = Eblambda(lmbda, T)\n eff_Eblambdas.append(Eblmda * f(lmbda))\n Eblambdas.append(Eblmda)\n\n # integrate over y(x) using the composite trapezoidal rule\n y = cumtrapz(eff_Eblambdas, wavelengths)\n y_num = y.tolist()[-1] # take the last value as the total integral\n\n eff = y_num / y_den\n\n return eff, wavelengths, eff_Eblambdas, Eblambdas\n","sub_path":"RadiationHeatTransfer/blackbody.py","file_name":"blackbody.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"521040543","text":"\"\"\"\nGiven an array of integers nums and an integer target, return indices\nof the two numbers such that they add up to target.\n\nYou may assume that each input would have exactly one solution, and you\nmay not use the same element twice.\n\nYou can return the answer in any order.\n\nEx1:\nInput: nums = [2, 7, 11, 15], target = 9\nOutput: [0, 1]\nOutput: Because nums[0] + nums[1] == 9, we return [0, 1].\n\nEx2:\nInput: nums = [3, 2, 4], target = 6\nOutput: [1, 2]\n\nEx3:\nInput: nums = [3, 3], target = 6\nOutput: [0, 1]\n\nStrategy\nThink it is best to precache each number and its location in the first pass.\nThen with the second pass, we immediately know if there is a complement\nfor each target-digit.\n\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n\n number_location = {}\n for i, n in enumerate(nums):\n what_we_want = target - n\n if what_we_want in number_location:\n return [number_location[what_we_want], i]\n number_location[n] = i\n return []\n\n\ndef test_twosum():\n s = Solution()\n assert s.twoSum([2, 7, 11, 15], 9) == [0, 1]\n assert s.twoSum([3, 2, 4], 6) == [1, 2]\n assert s.twoSum([3, 3], 6) == [0, 1]\n\ntest_twosum()\n","sub_path":"leetcode/001_two_sum/two_sum.py","file_name":"two_sum.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"292901296","text":"#CSCI 1133 Homework 3\n#Sid Lin\n#Problem 3A\ndef invert(lst):\n new_list = [] #first list\n sorted = [] #final list\n length = len(lst)\n for i in range(length):\n if (type(lst[i]) == int):\n new_list.append(lst[i]) #creates a new list with ints\n\n #this is the selection sort algorithm we did in lab\n for j in range(len(new_list)):\n max = new_list[j]\n for k in range(j + 1, len(new_list)):\n\n if(new_list[k]>max):\n max = new_list[k]\n index = new_list.index(max)\n temp = new_list[j]\n new_list[j] = max\n new_list[index] = temp\n\n sorted.append(new_list[j])\n\n return sorted\n\ndef main():\n print(\"Welcome to the list reverser.\")\n testls = [1,2, \"three\", 4, 5, 8, 9, 1111, [6, 7, 8]]\n final = invert(testls)\n print(final)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Eleven Thirty Three/hw3/linx1052_3A.py","file_name":"linx1052_3A.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"391028624","text":"from flask import Flask, jsonify, render_template, url_for, request, redirect, json\nfrom flask_sqlalchemy import SQLAlchemy, functools\nfrom flask_cors import CORS, cross_origin\nfrom datetime import datetime, timedelta\n\nimport pymysql, os, math, requests, uuid\n\nimport cherrypy\nfrom cherrypy import log\n\nimport logging\nfrom logging.handlers import *\nimport logging.config\n\n# Directory imports\nfrom routes import app, logger\n\n\nif __name__ == '__main__':\n\tLOG_CONF = {\n\t\t'version': 1,\n\t\t'formatters': {\n\t\t\t'void': {\n\t\t\t\t'format': ''\n\t\t\t},\n\t\t\t'standard': {\n\t\t\t\t'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'\n\t\t\t},\n\t\t},\n\t\t'handlers': {\n\t\t\t'default': {\n\t\t\t\t'level':'INFO',\n\t\t\t\t'class':'logging.StreamHandler',\n\t\t\t\t'formatter': 'standard',\n\t\t\t\t'stream': 'ext://sys.stdout'\n\t\t\t},\n\t\t\t'cherrypy_console': {\n\t\t\t\t'level':'INFO',\n\t\t\t\t'class':'logging.StreamHandler',\n\t\t\t\t'formatter': 'void',\n\t\t\t\t'stream': 'ext://sys.stdout'\n\t\t\t},\n\t\t\t'cherrypy_access': {\n\t\t\t\t'level':'INFO',\n\t\t\t\t'class': 'logging.handlers.RotatingFileHandler',\n\t\t\t\t'formatter': 'void',\n\t\t\t\t'filename': 'app.log',\n\t\t\t\t'maxBytes': 10485760,\n\t\t\t\t'backupCount': 20,\n\t\t\t\t'encoding': 'utf8'\n\t\t\t},\n\t\t\t'cherrypy_error': {\n\t\t\t\t'level':'INFO',\n\t\t\t\t'class': 'logging.handlers.RotatingFileHandler',\n\t\t\t\t'formatter': 'void',\n\t\t\t\t'filename': 'app.log',\n\t\t\t\t'maxBytes': 10485760,\n\t\t\t\t'backupCount': 20,\n\t\t\t\t'encoding': 'utf8'\n\t\t\t},\n\t\t},\n\t\t'loggers': {\n\t\t\t'': {\n\t\t\t\t'handlers': ['default'],\n\t\t\t\t'level': 'INFO'\n\t\t\t},\n\t\t\t'db': {\n\t\t\t\t'handlers': ['default'],\n\t\t\t\t'level': 'INFO' ,\n\t\t\t\t'propagate': False\n\t\t\t},\n\t\t\t'cherrypy.access': {\n\t\t\t\t'handlers': ['cherrypy_access'],\n\t\t\t\t'level': 'INFO',\n\t\t\t\t'propagate': False\n\t\t\t},\n\t\t\t'cherrypy.error': {\n\t\t\t\t'handlers': ['cherrypy_console', 'cherrypy_error'],\n\t\t\t\t'level': 'INFO',\n\t\t\t\t'propagate': False\n\t\t\t},\n\t\t}\n}\n\t# app_logged = TransLogger(app)\n\t# Mount the application\n\tcherrypy.tree.graft(app, \"/\")\n\tcherrypy.config.update({\n\t\t'global' : {\n\t\t\t'engine.autoreload.on' : True,\n\t\t\t'log.screen': True\n\t\t},\n\t\t'log.screen': True,\n\t\t'log.error_file': \"app.log\"\n\t})\n\t# Unsubscribe the default server\n\tcherrypy.server.unsubscribe()\n\n\t# Instantiate a new server object\n\tserver = cherrypy._cpserver.Server()\n\n\t# Configure the server object\n\tserver.socket_host = \"0.0.0.0\"\n\tserver.socket_port = 5000\n\tserver.thread_pool = 30\n\tserver.log = True\n\tserver.screen = True\n\n\t# For SSL Support\n\t# server.ssl_module = 'pyopenssl'\n\t# server.ssl_certificate = 'ssl/certificate.crt'\n\t# server.ssl_private_key = 'ssl/private.key'\n\t# server.ssl_certificate_chain = 'ssl/bundle.crt'\n\n\t# Subscribe this server\n\tserver.subscribe()\n\n\t# Start the server engine (Option 1 *and* 2)\n\tlogging.config.dictConfig(LOG_CONF)\n\tcherrypy.engine.start()\n\tcherrypy.engine.block()\n","sub_path":"flaskcli/base_templates/default/app/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"412450975","text":"n = int(input())\ninp = []\nfor i in range(n):\n inp.append(int(input()))\ninp.sort()\n\ndef smart(n , inp):\n minm = []\n for j in range(n):\n if minm == None:\n minm = inp[j]*(n-j)\n else:\n minm.append(inp[j]*(n-j))\n \n return max(minm)\nprint(smart(n, inp))","sub_path":"smartphone.py","file_name":"smartphone.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"110238610","text":"import sqlite3\nimport pandas as pd\n\nconn = sqlite3.connect('buddymove_holidayiq.sqlite3')\ncurs = conn.cursor()\nreview = pd.read_csv('buddymove_holidayiq.csv')\nreview.to_sql('review', con=conn, if_exists = 'replace')\n\n\ndef execute_query(cursor, query):\n cursor.execute(query)\n result = cursor.fetchall()\n print(result)\n\n\nROW_COUNT= \"\"\" \nSELECT COUNT(*) FROM review;\n\"\"\"\n\n\nprint('Row Count:')\nexecute_query(curs, ROW_COUNT)\n\n\nUSER_COUNT = \"\"\"\nSELECT COUNT(*)\nFROM review\nWHERE Nature >= 100\nAND Shopping >= 100;\n\"\"\"\n\n\nprint('Users who love nature and shopping count:')\nexecute_query(curs, USER_COUNT)","sub_path":"module1-introduction-to-sql/buddymove_holidayiq.py","file_name":"buddymove_holidayiq.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"622376842","text":"import tensorflow as tf\nimport logging\nimport sys\n\nimport Seq2Seq as s2s\n\n\ndef main():\n print(\"STARTED \\n\")\n\n if len(sys.argv) > 1:\n mode = sys.argv[1]\n else:\n raise ValueError(\"Main mode option not provided\")\n\n tf.logging._logger.setLevel(logging.INFO)\n if mode.upper() == \"TRAINING\":\n #FOR TRAINING\n print(\"Training Started\")\n s2s.train_seq2seq('Data/final_question_file', 'Data/final_answer_file', 'Data/vocab_map', 'model/seq2seq')\n elif mode.upper() == \"INFERENCE\":\n if len(sys.argv) > 2:\n pass\n else:\n sys.argv.append(\"COMMAND\")\n #FOR PREDICTION --- 'file'/'command'\n infer_mode = sys.argv[2]\n if infer_mode.upper() == \"FILE\":\n print(\"Entered Inference File Mode\")\n s2s.predict_seq2seq('Data/prediction_input','Data/vocab_map', 'model/seq2seq', 'FILE')\n elif infer_mode.upper() == \"COMMAND\":\n print(\"Entered Inference Command Mode\")\n command_line_input = input(\"Question: \")\n ans = s2s.predict_seq2seq('Data/prediction_input','Data/vocab_map', 'model/seq2seq', 'COMMAND', None,\n command_line_input)\n print(\"\\nQuestion: \", command_line_input)\n print(\"\\nAnswer: \", ans.replace('',''))\n else:\n raise ValueError(\"Correct Inference mode (FILE/COMMAND) was not supplied\")\n elif mode.upper() == 'TESTING':\n s2s.predict_seq2seq('Data/testing_input_file', 'Data/vocab_map', 'model/seq2seq', 'TESTING',\n 'Data/testing_ref_file')\n else:\n raise ValueError(\"Correct Main mode (Training/Inference) was not supplied\")\n\n print(\"\\nFINISHED \\n\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"280057773","text":"from io import StringIO\nfrom unittest import main, TestCase\n# pega a função e encapsula num contexto, pra \"mentir\" como ela funciona\nfrom unittest.mock import patch\n\ndef stdout(string):\n return(string)\n\nclass Test_stdout(TestCase):\n def test_stdout(self):\n resultado_esperado = \"Rapidinha de Python\"\n\n # coloque no arquivo de saida sys o resultado esperado de algum teste fake\n with patch('sys.stdout', new=StringIO()) as fake_out:\n stdout(resultado_esperado)\n self.assertEqual(fake_out.getvalue(), resultado_esperado)\n\nif __name__ == '__main__':\n main()","sub_path":"LIVES-EDUARD0-MEIRELES/RAPIDINHAS-PYTHONICAS/compreensaoStdout.py","file_name":"compreensaoStdout.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"227985929","text":"from heapq import *\n\n\ndef maximize_capital(capitals, profits, number_of_projects, initial_capital):\n min_heap = []\n max_heap = []\n\n for i in range(len(capitals)):\n heappush(min_heap, (capitals[i], i))\n\n available_capital = initial_capital\n for _ in range(number_of_projects):\n while min_heap and min_heap[0][0] <= available_capital:\n capital, idx = heappop(min_heap)\n heappush(max_heap, -profits[idx])\n\n available_capital += -(max_heap.pop())\n return available_capital\n\n","sub_path":"revise-daily/june_2021/educative/7_maximize_capital.py","file_name":"7_maximize_capital.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"226851001","text":"from argparse import ArgumentParser\nfrom .version import VERSION\n\n\nsnippet_name_parser = ArgumentParser(add_help=False)\nsnippet_name_parser.add_argument('snippet_name', action='store', help='Snippet name')\n\nsnippet_content_parser = ArgumentParser(add_help=False)\nsnippet_content_parser.add_argument('snippet_content', action='store', help='Snippet content')\n\nbase_parser = ArgumentParser(prog='pysnip', description='Save and Retreive command line snippets.')\nsp = base_parser.add_subparsers()\nsave_subparser = sp.add_parser('save', help='Save snippet', parents=[snippet_name_parser, snippet_content_parser])\nsave_subparser.set_defaults(command='save')\n\nget_subparser = sp.add_parser('get', help='Get snippet with key', parents=[snippet_name_parser])\nget_subparser.set_defaults(command='get')\n\ndel_subparser = sp.add_parser('del', help='Delete snippet with key', parents=[snippet_name_parser])\ndel_subparser.set_defaults(command='del')\n\nlist_subparser = sp.add_parser('list', help='List all snippets')\nlist_subparser.set_defaults(command='list')\n\nfind_subparser = sp.add_parser('find', help='Find snippet', parents=[snippet_name_parser])\nfind_subparser.set_defaults(command='find')\n\n\nargs = base_parser.parse_args()\n__all__ = ['args']\n__version__ = VERSION","sub_path":"pysnip/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"422454140","text":"# -*- coding: utf-8 -*-\n\"\"\"Implementation of a SignatureClassifier\n\nUtilises the signature method of feature extraction.\nThis method was built according to the best practices\nand methodologies described in the paper:\n \"A Generalised Signature Method for Time Series\"\n [arxiv](https://arxiv.org/pdf/2006.00873.pdf).\n\"\"\"\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.pipeline import Pipeline\n\nfrom sktime.classification.base import BaseClassifier\nfrom sktime.transformations.panel.signature_based._checks import (\n _handle_sktime_signatures,\n)\nfrom sktime.transformations.panel.signature_based._signature_method import (\n SignatureTransformer,\n)\nfrom sktime.utils._maint import deprecated\n\n\nclass SignatureClassifier(BaseClassifier):\n \"\"\"Classification module using signature-based features.\n\n DEPRECATED. Please use `SignatureClassifier` from\n `sktime.classification.feature_based` instead.\n\n This simply initialises the SignatureTransformer class which builds\n the feature extraction pipeline, then creates a new pipeline by\n appending a classifier after the feature extraction step.\n\n The default parameters are set to best practice parameters found in\n \"A Generalised Signature Method for Multivariate TimeSeries\"\n [https://arxiv.org/pdf/2006.00873.pdf]\n\n Note that the final classifier used on the UEA datasets involved tuning\n the hyper-parameters:\n - `depth` over [1, 2, 3, 4, 5, 6]\n - `window_depth` over [2, 3, 4]\n - RandomForestClassifier hyper-parameters.\n as these were found to be the most dataset dependent hyper-parameters.\n\n Thus, we recommend always tuning *at least* these parameters to any given\n dataset.\n\n Parameters\n ----------\n classifier: sklearn estimator, This should be any sklearn-type\n estimator. Defaults to RandomForestClassifier.\n augmentation_list: list of tuple of strings, List of augmentations to be\n applied before the signature transform is applied.\n window_name: str, The name of the window transform to apply.\n window_depth: int, The depth of the dyadic window. (Active only if\n `window_name == 'dyadic']`.\n window_length: int, The length of the sliding/expanding window. (Active\n only if `window_name in ['sliding, 'expanding'].\n window_step: int, The step of the sliding/expanding window. (Active\n only if `window_name in ['sliding, 'expanding'].\n rescaling: str, The method of signature rescaling.\n sig_tfm: str, String to specify the type of signature transform. One of:\n ['signature', 'logsignature']).\n depth: int, Signature truncation depth.\n random_state: int, Random state initialisation.\n\n Attributes\n ----------------\n signature_method: sklearn.Pipeline, An sklearn pipeline that performs the\n signature feature extraction step.\n pipeline: sklearn.Pipeline, The classifier appended to the\n `signature_method` pipeline to make a classification pipeline.\n \"\"\"\n\n @deprecated(\n \"Please use `SignatureClassifier` from `sktime.classification.feature_based` instead.\" # noqa: E501\n )\n def __init__(\n self,\n classifier=None,\n augmentation_list=(\"basepoint\", \"addtime\"),\n window_name=\"dyadic\",\n window_depth=3,\n window_length=None,\n window_step=None,\n rescaling=None,\n sig_tfm=\"signature\",\n depth=4,\n random_state=None,\n ):\n super(SignatureClassifier, self).__init__()\n self.classifier = classifier\n self.augmentation_list = augmentation_list\n self.window_name = window_name\n self.window_depth = window_depth\n self.window_length = window_length\n self.window_step = window_step\n self.rescaling = rescaling\n self.sig_tfm = sig_tfm\n self.depth = depth\n self.random_state = random_state\n np.random.seed(random_state)\n\n self.signature_method = SignatureTransformer(\n augmentation_list,\n window_name,\n window_depth,\n window_length,\n window_step,\n rescaling,\n sig_tfm,\n depth,\n ).signature_method\n\n def _setup_classification_pipeline(self):\n \"\"\"Setup the full signature method pipeline.\"\"\"\n # Use rf if no classifier is set\n if self.classifier is None:\n classifier = RandomForestClassifier(random_state=self.random_state)\n else:\n classifier = self.classifier\n\n # Main classification pipeline\n self.pipeline = Pipeline(\n [(\"signature_method\", self.signature_method), (\"classifier\", classifier)]\n )\n\n # Handle the sktime fit checks and convert to a tensor\n @_handle_sktime_signatures(check_fitted=False)\n def fit(self, data, labels):\n # Join the classifier onto the signature method pipeline\n self._setup_classification_pipeline()\n\n # Fit the pre-initialised classification pipeline\n self.pipeline.fit(data, labels)\n self._is_fitted = True\n return self\n\n # Handle the sktime predict checks and convert to tensor format\n @_handle_sktime_signatures(check_fitted=True, force_numpy=True)\n def predict(self, data):\n return self.pipeline.predict(data)\n\n # Handle the sktime predict checks and convert to tensor format\n @_handle_sktime_signatures(check_fitted=True, force_numpy=True)\n def predict_proba(self, data):\n return self.pipeline.predict_proba(data)\n","sub_path":"sktime/classification/signature_based/_signature_classifier.py","file_name":"_signature_classifier.py","file_ext":"py","file_size_in_byte":5561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"78041511","text":"from argparse import ArgumentParser\nimport configparser\nimport os.path\n\nimport internals.config as CONFIG\nfrom server.servercontroller import ServerDatabase\nfrom server.server import Server\nfrom server.ui.launcher import start_server_gui\n\n\ndef argparse_config(default_host, default_port):\n parser = ArgumentParser(description='Run the chat server.')\n parser.add_argument('-p',\n help=f'server port, defaults to {default_port}',\n default=default_port,\n type=int)\n parser.add_argument('-a',\n help='server address, listens all interfaces by default',\n default=default_host)\n parser.add_argument('--console',\n help='run in a console mode (without GUI)',\n action='store_true')\n\n user_arguments = vars(parser.parse_args())\n return user_arguments['a'], user_arguments['p'], user_arguments['console']\n\n\ndef setup_config():\n file_config = configparser.ConfigParser()\n dir_path = os.path.dirname(os.path.realpath(__file__))\n file_config.read(f\"{dir_path}/{CONFIG.SERVER_CONFIG_FILENAME}\")\n\n default_port = file_config['SETTINGS']['default_port']\n default_host = file_config['SETTINGS']['default_host']\n\n host, port, is_console_mode = argparse_config(default_host, default_port)\n\n return {\n 'host': host,\n 'port': port,\n 'db_path': file_config['SETTINGS']['database_path'],\n 'db_filename': file_config['SETTINGS']['database_file'],\n 'file_config': file_config,\n 'is_console_mode': is_console_mode\n }\n\n\ndef run_console_server(server_thread):\n while True:\n command = input('Enter exit to stop the server')\n if command == 'exit':\n server_thread.is_running = False\n server_thread.join()\n break\n\n\ndef run_gui_server(server_thread, db, file_config):\n # GUI start\n start_server_gui(server_thread, db, file_config)\n\n # Finishing thread after GUI app exits\n server_thread.is_running = False\n\n\ndef main():\n config = setup_config()\n\n # Setup data storage\n db_path = os.path.join(config['db_path'], config['db_filename'])\n server_db = ServerDatabase(db_path)\n\n # Spinning up the chat server\n chat_server_thread = Server(\n host=config['host'],\n port=config['port'],\n db=server_db\n )\n\n # To run in a background\n chat_server_thread.daemon = True\n chat_server_thread.start()\n\n if config['is_console_mode']:\n run_console_server(chat_server_thread)\n else:\n run_gui_server(chat_server_thread, server_db, config['file_config'])\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"361174900","text":"# -*- coding: utf-8 -*-\nimport logging\nimport mock\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.test import TestCase\n\nfrom billing_proxy.worker import cache_manager\n\nLOG = logging.getLogger(__name__)\n\n\nclass CacheTestCase(TestCase):\n \"\"\"Test case base class for cache test\"\"\"\n\n def setUp(self):\n super(CacheTestCase, self).setUp()\n cache_manager.CACHE_KEY_CONTRACT = \"FAKE_CONTRACTS\"\n\n def test_get_all_contracts(self):\n self.test_contracts = {\n \"datacenterCode\": settings.DATACENTER_CODE,\n \"contracts\": [\n {\n \"account\": \"testuser1\",\n \"contractId\": \"baa164553cdc43d196141f70fd878ec4\",\n \"contractCode\": \"BJ001-009\",\n \"isDisplayPrice\": False,\n \"contractType\": \"2\",\n \"contractDetail\": []\n },\n {\n \"account\": \"testuser1\",\n \"contractId\": \"baa164553cdc55555666666\",\n \"contractCode\": \"BJ001-011\",\n \"isDisplayPrice\": True,\n \"contractType\": \"2\",\n \"contractDetail\": []\n },\n {\n \"account\": \"testuser2\",\n \"contractId\": \"baa164553cdc5555566fff\",\n \"contractCode\": \"BJ001-012\",\n \"isDisplayPrice\": True,\n \"contractType\": \"2\",\n \"contractDetail\": []\n }\n ]\n }\n cache.set(cache_manager.CACHE_KEY_CONTRACT, None)\n self.get_contract_func = mock.Mock(return_value=self.test_contracts)\n\n cache_manager.get_contracts_decorator(self.get_contract_func)(None,\n None)\n expected_contract = {\n \"testuser1\": [\n {\n 'account': 'testuser1',\n 'contractCode': 'BJ001-009',\n 'contractDetail': [\n\n ],\n 'contractId':\n 'baa164553cdc43d196141f70fd878ec4',\n 'contractType': '2',\n 'isDisplayPrice': False,\n 'BJ001-009': [\n\n ]\n },\n {\n 'account': 'testuser1',\n 'contractCode': 'BJ001-011',\n 'contractDetail': [\n\n ],\n 'contractId':\n 'baa164553cdc55555666666',\n 'contractType': '2',\n 'isDisplayPrice': True,\n 'BJ001-011': [\n\n ]\n },\n ],\n \"testuser2\": [\n {\n 'account': 'testuser2',\n 'contractCode': 'BJ001-012',\n 'contractDetail': [\n\n ],\n 'contractId':\n 'baa164553cdc5555566fff',\n 'contractType': '2',\n 'isDisplayPrice': True,\n 'BJ001-012': [\n\n ]\n }\n ]\n }\n self.assertIsNotNone(cache.get(cache_manager.CACHE_KEY_CONTRACT))\n contracts = cache.get(cache_manager.CACHE_KEY_CONTRACT)\n LOG.info(\"contracts: {0}\".format(contracts))\n self.assertIn(\"contracts\", contracts)\n self.assertIn(\"index\", contracts)\n self.assertIn(\"datacenterCode\", contracts)\n self.assertEqual(contracts[\"contracts\"], expected_contract)\n\n def tearDown(self):\n cache.set(cache_manager.CACHE_KEY_CONTRACT, None)\n super(CacheTestCase, self).tearDown()\n","sub_path":"billing_proxy/tests/units/test_update_cache.py","file_name":"test_update_cache.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"255980570","text":"from openerp import models, fields, api, _\nfrom openerp.exceptions import except_orm, Warning, RedirectWarning\nfrom openerp.tools import float_compare\nimport openerp.addons.decimal_precision as dp\nfrom openerp.modules import get_module_resource\nimport math\nfrom math import modf\nimport base64\nfrom tempfile import TemporaryFile\nimport csv\n\nimport time\nfrom datetime import datetime\n\n\n\nclass GetPartnerCsv(models.TransientModel):\n _name = \"get.partner.csv\"\n _description = \"Partner Uploads\"\n\n name = fields.Char('Upload File Template')\n template_file = fields.Binary('Partners', readonly=True, help=\"Set this CSV file as the template file\")\n data = fields.Binary(sring='CSV File')\n partner_ids = fields.One2many('get.partner.details','partner_id', string='Partners')\n valid = fields.Boolean('Valid', default=False)\n# is_customer = fields.Boolean(string='Customer', help=\"Partner\", default=True)\n# is_supplier = fields.Boolean(string='Supplier', help=\"Supplier\")\n invalid = fields.Text(\"Invalid Items\", readonly=True) \n\n def default_get(self, cr, uid, fields, context=None):\n data = super(GetPartnerCsv, self).default_get(cr, uid, fields, context=context)\n plugin_file = open(get_module_resource('dmpi_base','data_import/csv', 'partner_upload_template.csv'),'rb')\n data['template_file'] = base64.encodestring(plugin_file.read())\n return data\n\n\n\n def _validate_line(self, l):\n res = {}\n\n valid = \"\"\n error = 0\n\n if not self.env['res.partner.channel'].search([('code','=',l['channel'])], limit=1).id > 0:\n #Display error but allow updating\n #error = error+1\n valid = \"%s %s \" %(valid,\"Invalid Channel\")\n\n if not self.env['res.users'].search([('ref','=',l['salesman'])], limit=1).id > 0:\n error = error+1\n valid = \"%s %s \" %(valid,\"Invalid Salesman\")\n\n if error > 0:\n res['is_valid'] = False\n res['valid'] = valid\n else:\n res['is_valid'] = True\n if valid:\n res['valid'] = \"Valid: WARNING %s\" % valid\n else:\n res['valid'] = \"Valid\"\n return res\n\n\n @api.multi\n def onchange_data(self, data):\n res={}\n vals={}\n\n error = 0\n lines = []\n\n if data:\n fileobj = TemporaryFile('w+') #Temporary File\n fileobj.write(base64.decodestring(data)) \n #Check for consistency in the uploaded file\n fileobj.seek(0)\n\n reader = csv.DictReader(fileobj)\n\n for row in reader:\n if all (key in row for key in (\"name\",\"ref\",\"channel\",\n \"salesman\",\"street\",\"street2\",\"vat\",\"phone\")):\n \n vals['name'] = row['name'] \n vals['ref'] = row['ref']\n vals['channel'] = row['channel']\n vals['salesman'] = row['salesman']\n vals['street'] = row['street']\n vals['street2'] = row['street2']\n vals['vat'] = row['vat']\n vals['phone'] = row['phone']\n\n v = self._validate_line(vals)\n vals['is_valid'] = v['is_valid']\n vals['valid'] = v['valid']\n if not v['is_valid']:\n error += 1\n\n lines.append(vals.copy())\n #print lines\n\n else:\n raise except_orm(_('ERROR'), _('Please make sure that the format of the CSV is correct'))\n \n fileobj.close()\n\n\n res['partner_ids'] = lines\n if error > 0:\n res['invalid'] = '%s Errors Encountered during loading please see lines below:' % error\n res['valid'] = False\n \n if error == 0:\n res['valid'] = True\n \n \n return {'value': res}\n\n\n\n\n @api.multi\n def view_created_partners(self,partner_ids):\n \"\"\" open a view on one of the given Sales orders \"\"\"\n return {\n 'domain': str([('id', 'in', partner_ids)]),\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'res_model': 'res.partner',\n 'view_id': False,\n 'type': 'ir.actions.act_window',\n 'name' : _('Partners'),\n 'res_id': partner_ids\n }\n\n\n @api.multi\n def upload_data(self):\n partner_ids = []\n\n for rec in self:\n for l in rec.partner_ids: #Line Items\n\n p = {\n 'name' : l.name,\n 'ref' : l.ref,\n 'channel_id' : self.env['res.partner.channel'].search([('code','=',l.channel)], limit=1).id or False,\n 'user_id' : self.env['res.users'].search([('ref','=',l.salesman)], limit=1).id or False,\n 'street' : l.street,\n 'street2' : l.street2,\n 'vat' : l.vat,\n 'phone' : l.phone,\n 'customer' : True,\n }\n\n\n partner = self.env['res.partner'].create(p)\n partner_ids.append(partner.id) \n\n if partner_ids:\n return self.view_created_partners(partner_ids)\n\nclass GetPartnerDetails(models.TransientModel):\n _name = \"get.partner.details\"\n\n partner_id = fields.Many2one('get.partner.csv','Partner')\n name = fields.Char('Name')\n ref = fields.Char('Reference')\n channel = fields.Char('Channel')\n salesman = fields.Char('Salesman')\n street = fields.Char('Street')\n street2 = fields.Char('Street2')\n vat = fields.Char('TIN')\n phone = fields.Char('Phone')\n is_valid = fields.Boolean('is valid')\n valid = fields.Char('Valid') ","sub_path":"dmpi_base/data_import/partner.py","file_name":"partner.py","file_ext":"py","file_size_in_byte":5826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"353435745","text":"# Time: O(m * n)\n# Space: O(n)\n\n# 712\n# Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.\n#\n# Example 1:\n# Input: s1 = \"sea\", s2 = \"eat\"\n# Output: 231\n# Explanation: Deleting \"s\" from \"sea\" adds the ASCII value of \"s\" (115) to the sum.\n# Deleting \"t\" from \"eat\" adds 116 to the sum.\n# At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.\n#\n# Example 2:\n# Input: s1 = \"delete\", s2 = \"leet\"\n# Output: 403\n# Explanation: Deleting \"dee\" from \"delete\" to turn the string into \"let\",\n# adds 100[d]+101[e]+101[e] to the sum. Deleting \"e\" from \"leet\" adds 101[e] to the sum.\n# At the end, both strings are equal to \"let\", and the answer is 100+101+101+101 = 403.\n# If instead we turned both strings into \"lee\" or \"eet\", we would get answers of 433 or 417, which are higher.\n#\n# Note:\n# - 0 < s1.length, s2.length <= 1000.\n# - All elements of each string will have an ASCII value in [97, 122].\n\n# DP with rolling window\nclass Solution(object):\n\n def minimumDeleteSum(self, s1: str, s2: str) -> int: # USE THIS: ming's soluion, min delete equivalent to max keep\n s1, s2 = list(map(ord, s1)), list(map(ord, s2))\n sum1, sum2 = sum(s1), sum(s2)\n if sum1 == 0:\n return sum2\n elif sum2 == 0:\n return sum1\n\n dp = [0] * len(s2)\n for m in s1:\n ndp = [max(dp[0], m * (m == s2[0]))]\n for j in range(1, len(s2)):\n if m == s2[j]:\n ndp.append(dp[j - 1] + m)\n else:\n ndp.append(max(ndp[-1], dp[j]))\n dp = ndp\n return sum1 + sum2 - 2 * dp[-1]\n\n def minimumDeleteSum_bookshadow(self, s1, s2): # also good, not do complimentary\n a1, a2 = map(ord, s1), map(ord, s2)\n l1, l2 = len(s1), len(s2)\n dp = [0]\n for x in range(l1):\n dp.append(dp[-1] + a1[x])\n for x in range(1, l2 + 1):\n ndp = [dp[0] + a2[x - 1]]\n for y in range(1, l1 + 1):\n if a2[x - 1] == a1[y - 1]: ndp.append(dp[y - 1])\n else: ndp.append(min(dp[y] + a2[x - 1], ndp[y - 1] + a1[y - 1]))\n dp = ndp\n return dp[-1]\n\n\n def minimumDeleteSum_kamyu(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: int\n \"\"\"\n dp = [[0] * (len(s2)+1) for _ in xrange(2)]\n for j in xrange(len(s2)):\n dp[0][j+1] = dp[0][j] + ord(s2[j])\n\n for i in xrange(len(s1)):\n dp[(i+1)%2][0] = dp[i%2][0] + ord(s1[i])\n for j in xrange(len(s2)):\n if s1[i] == s2[j]:\n dp[(i+1)%2][j+1] = dp[i%2][j]\n else:\n dp[(i+1)%2][j+1] = min(dp[i%2][j+1] + ord(s1[i]), \\\n dp[(i+1)%2][j] + ord(s2[j]))\n\n return dp[len(s1)%2][-1]\n\n\n# Time: O(m * n)\n# Space: O(m * n)\nclass Solution2(object):\n def minimumDeleteSum(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: int\n \"\"\"\n dp = [[0] * (len(s2)+1) for _ in xrange(len(s1)+1)]\n for i in xrange(len(s1)):\n dp[i+1][0] = dp[i][0] + ord(s1[i])\n for j in xrange(len(s2)):\n dp[0][j+1] = dp[0][j] + ord(s2[j])\n\n for i in xrange(len(s1)):\n for j in xrange(len(s2)):\n if s1[i] == s2[j]:\n dp[i+1][j+1] = dp[i][j]\n else:\n dp[i+1][j+1] = min(dp[i][j+1] + ord(s1[i]), \\\n dp[i+1][j] + ord(s2[j]))\n\n return dp[-1][-1]\n\nprint(Solution().minimumDeleteSum(\"sea\", \"eat\")) # 231\nprint(Solution().minimumDeleteSum(\"delete\", \"leet\")) # 403\n","sub_path":"Python/minimum-ascii-delete-sum-for-two-strings.py","file_name":"minimum-ascii-delete-sum-for-two-strings.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"539964267","text":"from flask import Flask, render_template, request\nfrom pymongo import MongoClient\nimport pymongo\nimport pandas as pd\n\nclass Artist_searcher:\n def __init__(self):\n self.query = None\n self.select_type = None\n\n def set_info(self, query=None, select_type=None):\n self.query = query\n self.select_type = select_type\n\n def get_pymongo(self):\n if self.select_type == \"name\":\n return collection_artist.find({\"name\":self.query})\n\n if self.select_type == \"alias\":\n return collection_artist.find({\"aliases.name\":self.query})\n\n if self.select_type == \"area\":\n return collection_artist.find({\"area\":self.query})\n\n if self.select_type == \"tag\":\n return collection_artist.find({\"tags.value\":self.query})\n\n def sort_pymongo_rating(self, mongo):\n for post in mongo.sort(\"rating.count\", -1).limit(10):\n yield post\n\n def get_info(self, post):\n name = post[\"name\"]\n alias = post.get(\"aliases\")\n area = post.get(\"area\")\n work_type = post.get(\"type\")\n begin = post.get(\"begin\")\n\n if alias:\n alias = ', '.join(dic[\"name\"] for dic in alias)\n\n if begin:\n year = begin.get(\"year\")\n month = begin.get(\"month\")\n date = begin.get(\"date\")\n begin = '/'.join(str(num) for num in [year, month, date] if num)\n\n return (name, alias, area, work_type, begin)\n\n def get_iter_search(self):\n if self.query and self.select_type:\n mongo = self.get_pymongo()\n for post in self.sort_pymongo_rating(mongo):\n yield self.get_info(post)\n\n def get_df(self):\n df = pd.DataFrame((i for i in searcher.get_iter_search()),\n columns=['name','alias','area','type','begin'])\n return df\n\n\n\napp = Flask(__name__)\n\nclient = MongoClient('localhost', 27017)\ndb_artist = client.database_artist\ncollection_artist = db_artist.collection_artist\n\nsearcher = Artist_searcher()\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/post', methods=['GET', 'POST'])\ndef search():\n select_type = request.form['select_type']\n query = request.form['query']\n searcher.set_info(query=query, select_type=select_type)\n df = searcher.get_df().to_html(classes='books')\n\n return render_template('index.html',\n select_type=select_type,\n query=query,\n data_frame=df)\n\nif __name__ == \"__main__\":\n app.debug=True\n app.run()","sub_path":"chapter07/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"283792117","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 12 21:18:41 2017\n\n@author: xiaoling\n\"\"\"\n\ndef label9_9():\n for j in range(1,10):\n for i in range(1,10):\n if i < j:\n print(i,\"*\",j, \"=\",i*j,\" \", end = '')\n if i == j:\n print(i,\"*\",j, \"=\",i*j)\n continue \nlabel9_9()\n ","sub_path":"normalPractise/py_function.py","file_name":"py_function.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"20996714","text":"\"\"\"\nTest data aquisition from the sensors in a loop.\n\"\"\"\n\nimport time\nimport mpu6500\nimport ak8963\n\ninterval = 0.5\n\nimu = mpu6500.MPU6500()\nmag = ak8963.AK8963()\n\nfor _ in range(100):\n t_start = time.time()\n acc = imu.acceleration\n rot = imu.gyro\n temp = imu.temperature\n t_imu_end = time.time()\n mfield = mag.magnetic\n t_mag_end = t_end = time.time()\n\n print(\"Acceleration:\", acc)\n print(\"Rotation :\", rot)\n print(\"Temperature :\", temp)\n print(\"Duration IMU:\", t_imu_end - t_start)\n print(\"Magnetic :\", mfield)\n print(\"Duration MAG:\", t_mag_end - t_imu_end)\n print()\n\n t_end = time.time()\n remaining = max(0, interval - (t_end - t_start))\n time.sleep(remaining)\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"193366760","text":"import MeCab\nfrom pymongo import MongoClient, DESCENDING\n\ndef setup_mongo(db_name):\n connection = MongoClient()\n db = connection[db_name]\n print('mongoDB ready')\n return db\n\ndef setup_mecab(dic_path):\n mecab = MeCab.Tagger('-d ' + dic_path)\n mecab.parse('')\n print('mecab ready')\n return mecab\n","sub_path":"_endo/s_lib.py","file_name":"s_lib.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"451725938","text":"\"\"\" This module \"understands\" the input format of wlcsim.exe \"\"\"\nfrom __future__ import print_function\n\nimport re\nimport os\nfrom pathlib import Path\nfrom enum import Enum\n\n# def __init__(self, sim_dir):\n# input_dir = os.path.join(sim_dir, 'input')\n# input_file = os.path.join(input_dir, 'input')\n# if not os.path.isdir(sim_dir) \\\n# or not os.path.isdir(input_dir) \\\n# or not os.path.isfile(input_file):\n# raise IOError('Simulation directory ' + sim_dir + ' does not'\n# ' contain input/input')\n\nclass InputFormat(Enum):\n ORIGINAL=1\n LENA=2\n DEFINES=3\n\nrenamer = {'COL_TYPE': 'COLLISIONDETECTIONTYPE', 'COLTYPE': 'COLLISIONDETECTIONTYPE', 'FPT_DIST': 'COLLISIONRADIUS',\n 'INTON': 'INTERPBEADLENNARDJONES', 'N': 'NB', 'INDMAX': 'NUMSAVEPOINTS'}\n\ndef correct_param_name(name):\n \"\"\"Takes messy param names from different generations of the simulator and\n converts them to their newest forms so that simulations from across\n different years can be tabulated together.\"\"\"\n name = name.upper()\n if name not in renamer:\n return name\n else:\n return renamer[name]\n\ndef brown_to_codename(name, value):\n new_name = 'CODENAME'\n if int(value) == 1:\n return (new_name, 'bruno')\n else:\n return (new_name, 'brad')\n# for each old param name that needs to go through correct_param_value, the\n# function that will convert its value. recall all \"values\" are strings at this\n# point\nrevalueer = {'BROWN': brown_to_codename}\n\ndef correct_param_value(name, value):\n \"\"\"Some old param names also have new types. This takes messy param names\n from different generations of the simulator and converts their names and\n values to their newest forms so that simulations from across different\n years can be tabulated together.\"\"\"\n if name in revalueer:\n return revalueer[name](name, value)\n else:\n return (name, value)\n\nclass ParsedInput(object):\n \"\"\"Knows how to handle various input file types used by wlcsim simulator\n over the years, and transparently converts into new parameter naming\n conventions.\n\n input = ParsedInput(file_name)\n print(input.ordered_param_names) # see params in order defined\n print(input.ordered_param_values) # to see values\n input.write(outfile_name) # write clone of input file\n\n \"\"\"\n\n def __init__(self, input_file=None, params=None):\n \"\"\"Can be constructed from an input file or from params directly. If an\n input file is provided, params are just ignored if passed in.\"\"\"\n self.params = {}\n self.ordered_param_names = []\n self.file_format = InputFormat.DEFINES\n self.input_file = Path(input_file)\n if input_file is not None:\n # if we get the sim dir or the input dir, resolve to the actual input file\n if not os.path.isfile(input_file) and os.path.isdir(input_file):\n input_file = os.path.join(input_file, 'input')\n if not os.path.isfile(input_file) and os.path.isdir(input_file):\n input_file = os.path.join(input_file, 'input')\n self.decide_input_format()\n self.parse_params_file()\n elif params is not None:\n for name, value in params.items():\n self.append_param(name, value)\n else:\n Warning('ParsedInput: no params or input file provided!')\n\n def __repr__(self):\n return str(self.params)\n\n @property\n def ordered_param_values(self):\n return [self.params[name] for name in self.ordered_param_names]\n\n def append_param(self, name, value):\n name = correct_param_name(name)\n name, value = correct_param_value(name, value)\n self.ordered_param_names.append(name)\n self.params.update({name: value})\n\n def write(self, output_file_name):\n \"\"\" writes out a valid input file for wlcsim.exe given parameters\n in the format returned by read_file \"\"\"\n with open(output_file_name, 'w') as f:\n if self.file_format == InputFormat.ORIGINAL:\n # write the three garbage lines\n f.write('!\\n!\\n\\n')\n for i,name in enumerate(self.ordered_param_names):\n f.write('!-Record ' + str(i) + '\\n! ' + name + '\\n')\n f.write(str(self.params[name]) + '\\n\\n')\n elif self.file_format == InputFormat.LENA:\n for name in self.ordered_param_names:\n f.write(str(name) + ' ' + str(self.params[name]) + '\\n')\n elif self.file_format == InputFormat.DEFINES:\n for name in self.ordered_param_names:\n f.write('#define WLC_P__' + str(name) + ' ' +\n str(self.params[name]) + '\\n')\n else:\n raise ValueError('wlcsim.input: attempt to print a ParsedInput'\n ' with unknown file_format.')\n\n def decide_input_format(self):\n \"\"\"Decide between the two input formats we know of.\n Not too hard, since one uses Fortran-style comments, which we can look\n out for, and the other uses bash style comments. Further, the former\n specifies param names and values on separate lines, while the latter\n specifies them on the same line.\"\"\"\n # first see if the file has the expected name for the defines file\n if self.input_file.name == 'defines.inc':\n self.input_format = InputFormat.DEFINES\n return\n # then see if there are any comment lines. if so, we immediately know\n # the file type\n with open(self.input_file) as f:\n for line in f:\n if not line:\n continue\n elif re.match('\\s*!', line):\n self.input_format = InputFormat.ORIGINAL\n return\n elif line[0] == '#':\n self.input_format = InputFormat.LENA\n return\n else:\n continue\n # if there are no comments, then for now, it must in fact be Lena's\n # intput file type, otherwise, we would not be able to infer the param\n # names, since these are in comment lines in the original-type input\n # files\n self.input_format = InputFormat.LENA\n return\n\n\n def parse_params_file(self):\n \"\"\"Parse and populate ParsedInput's params, ordered_param_names\n This parser currently understands three file formats:\n 1) \"ORIGINAL\" is the input method understood by Andy's hardcoded\n input reader in the original code used the Spakowitz lab was\n founded.\n 2) \"LENA\" is a spec using slightly more general input reader\n written by Elena Koslover while Andy's student.\n 3) \"DEFINES\" is the format of the src/defines.inc file.\n \"\"\"\n if self.input_format == InputFormat.ORIGINAL:\n self.parse_original_params_file()\n elif self.input_format == InputFormat.LENA:\n self.parse_lena_params_file()\n elif self.input_format == InputFormat.DEFINES:\n self.parse_defines_params_file()\n\n def parse_lena_params_file(self):\n \"\"\"Lena-style input files have comment lines starting with a \"#\". Any\n other non-blank lines must be of the form\n \"[identifier][whitespace][value]\",\n where an identifier is of the form \"[_a-zA-Z][_a-zA-Z0-9]*\", and a\n value can be a boolean, float, int or string. They will always be\n stored as strings in the params dictionary for downstream parsing as\n needed.\n\n Identifiers, like fortran variables, are interpreted in a\n case-insensitive manner by the wlcsim program, and so will be store in\n all-caps within the ParsedInput to signify this.\"\"\"\n name_value_re = re.compile('([_A-Za-z][_A-Za-z0-9]*)\\s*(.*)\\s*')\n with open(self.input_file) as f:\n for line in f:\n if not line or line[0] == '#':\n continue\n match = name_value_re.match(line)\n if match is None:\n continue\n name, value = match.groups()\n self.append_param(name, value)\n\n\n def parse_defines_params_file(self):\n \"\"\"Parse file in the format of src/defines.inc. Each line begins with\n #define WLC_P__[PARAM_NAME] [_a-zA-Z0-9]\n where WLC_P__[A-Z]* is the parameter name and the piece after the space is the value of\n the parameter.\n\n TODO:test\n \"\"\"\n name_value_re = re.compile('#define WLC_P__([_A-Z]*) ([_a-zA-Z0-9]*)')\n with open(self.input_file) as f:\n for line in f:\n if not line:\n continue\n match = name_value_re.match(line)\n if match is None:\n continue\n name, value = match.groups()\n self.append_param(name, value)\n\n\n def parse_original_params_file(self):\n \"\"\"Original-style input files have three garbage lines at the top used\n for commenting then triplets of lines describing one variable each. The\n first line of the triplet is a counter, for ease of hardcoding input\n reader, the second line contains the variable name (which is not used\n by the input reader) in order to make parsing possible outside of the\n ahrdcoded wlcsim input reader, and the third line contains the value of\n the parameter itself. The first two lines of each triplet have a fixed\n form that we use to extract the record numbers and parameter names, but\n these forms are not used by wlcsim itself, which ignores these lnies\n completely. Thus, it is possible that the user specified a particular\n name for a parameter but that name does not match what wlcsim\n interpreted it as, since wlcsim simply uses the order of the parameters\n in this file to determine their identities.\"\"\"\n record_re = re.compile('!-Record (\\d+)')\n name_re = re.compile('! *([_A-Za-z0-9]+)')\n contains_period_re = re.compile('\\.')\n next_line_is_val = False\n with open(self.input_file) as f:\n # first three lines are garbage\n for i in range(3):\n f.readline()\n for line in f:\n if next_line_is_val:\n if contains_period_re.search(line):\n value = float(line.strip())\n else:\n value = int(line.strip())\n self.append_param(name, value)\n name = None\n record_number = None\n value = None\n next_line_is_val = False\n record_match = record_re.search(line)\n if record_match:\n record_number = int(record_match.groups()[0])\n continue\n name_match = name_re.search(line)\n if name_match:\n name = name_match.groups()[0]\n name = name.upper()\n next_line_is_val = True\n continue\n","sub_path":"wlcsim/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":11251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598705892","text":"\nimport logging\nimport re\nimport pymel.core as pm\nimport pymetanode as meta\nfrom vendor.mayacoretools import preservedSelection\n\nfrom . import colors\nfrom . import joints\nfrom . import links\nfrom . import nodes\n\n__all__ = [\n 'applyMirrorSettings',\n 'cleanupAllMirrorNodes',\n 'counterRotateForMirroredJoint',\n 'counterRotateForNonMirrored',\n 'duplicateAndPairNode',\n 'evalCustomMirrorAttrExp',\n 'getAllMirrorNodes',\n 'getBestMirrorMode',\n 'getCenteredParent',\n 'getMirroredJointMatrices',\n 'getMirroredMatrices',\n 'getMirroredName',\n 'getMirroredOrCenteredParent',\n 'getMirroredParent',\n 'getMirroredTransformMatrix',\n 'getMirrorSettings',\n 'getPairedNode',\n 'invertOtherAxes',\n 'isCentered',\n 'isMirrorNode',\n 'MirrorColors',\n 'MirrorCurveShapes',\n 'MirrorLinks',\n 'MirrorNames',\n 'MirrorOperation',\n 'MirrorParenting',\n 'MirrorTransforms',\n 'MirrorUtil',\n 'pairMirrorNodes',\n 'removeMirroringData',\n 'setMirroredMatrices',\n 'setMirroringData',\n 'unpairMirrorNode',\n 'validateMirrorNode',\n]\n\nLOG = logging.getLogger(__name__)\n\nMIRROR_METACLASS = 'pulse_mirror'\nMIRROR_THRESHOLD = 0.0001\n\n\nclass MirrorMode(object):\n \"\"\"\n Contains constants representing the available types of mirroring\n\n Simple:\n a ctl is mirrored across a single axis in the tranditional\n sense, this means the non-mirror axis basis vectors are flipped\n\n Aligned:\n a ctl is mirrored across a single axis in a visual sense,\n but the relationship between the matrices is more complicated.\n The result is an orientation that looks the same on both\n sides of an axis, as if they matched in world space in rest pose\n \"\"\"\n\n Simple = 'simple'\n Aligned = 'aligned'\n\n\n# Nodes\n# -----\n\ndef getAllMirrorNodes():\n \"\"\"\n Return all nodes that have mirroring data\n \"\"\"\n return meta.findMetaNodes(MIRROR_METACLASS)\n\n\ndef isMirrorNode(node):\n \"\"\"\n Return whether a node has mirroring data\n\n Args:\n node: A PyNode, MObject, or node name\n \"\"\"\n return meta.hasMetaClass(node, MIRROR_METACLASS)\n\n\ndef validateMirrorNode(node):\n \"\"\"\n Ensure the node still has a valid mirroring counterpart.\n If it does not, remove the mirror data from the node.\n\n Return:\n True if the node is a valid mirror node\n \"\"\"\n if not isMirrorNode(node):\n return False\n data = meta.getMetaData(node, MIRROR_METACLASS)\n otherNode = data['otherNode']\n if otherNode is None:\n LOG.debug(\"{0} paired node not found, \"\n \"removing mirroring data\".format(node))\n meta.removeMetaData(node, MIRROR_METACLASS)\n return False\n else:\n othersOther = getPairedNode(otherNode, False)\n if othersOther != node:\n LOG.debug(\"{0} pairing is unreciprocated, \"\n \"removing mirror data\".format(node))\n meta.removeMetaData(node, MIRROR_METACLASS)\n return False\n return True\n\n\ndef cleanupAllMirrorNodes():\n \"\"\"\n Remove mirroring meta data from any nodes in the scene\n that are no longer valid (missing their counterpart node).\n \"\"\"\n for node in getAllMirrorNodes():\n validateMirrorNode(node)\n\n\ndef pairMirrorNodes(nodeA, nodeB):\n \"\"\"\n Make both nodes associated as mirrors by adding\n mirroring data and a reference to each other.\n\n Args:\n nodeA: A PyNode, MObject, or node name\n nodeB: A PyNode, MObject, or node name\n \"\"\"\n setMirroringData(nodeA, nodeB)\n setMirroringData(nodeB, nodeA)\n\n\ndef unpairMirrorNode(node):\n \"\"\"\n Unpair the node from any associated mirror node.\n This removes mirroring data from both this\n node and its counterpart.\n\n Args:\n node: A PyNode, MObject, or node name\n \"\"\"\n if isMirrorNode(node):\n otherNode = getPairedNode(node)\n removeMirroringData(node)\n if otherNode:\n removeMirroringData(otherNode)\n\n\ndef duplicateAndPairNode(sourceNode):\n \"\"\"\n Duplicate a node, and pair it with the node that was duplicated.\n\n Returns:\n The newly created node.\n \"\"\"\n with preservedSelection():\n\n destNode = pm.duplicate(\n [sourceNode] + sourceNode.getChildren(s=True), po=True)[0]\n # handle bug in recent maya versions where extra empty\n # transforms will be included in the duplicate\n extra = destNode.listRelatives(typ='transform')\n if extra:\n LOG.debug(\"Deleting extra transforms from \"\n \"mirroring: {0}\".format(sourceNode))\n pm.delete(extra)\n # associate nodes\n pairMirrorNodes(sourceNode, destNode)\n return destNode\n\n\ndef setMirroringData(node, otherNode):\n \"\"\"\n Set the mirroring data for a node\n\n Args:\n node: A node on which to set the mirroring data\n otherNode: The counterpart node to be stored in the mirroring data\n \"\"\"\n data = {\n 'otherNode': otherNode,\n }\n meta.setMetaData(node, MIRROR_METACLASS, data, undoable=True)\n\n\ndef getPairedNode(node, validate=True):\n \"\"\"\n For a node with mirroring data, return the other node.\n\n Args:\n node: A node with mirroring data that references another node\n validate (bool): When true, ensures that the pairing is\n reciprocated by the other node\n \"\"\"\n if isMirrorNode(node):\n data = meta.getMetaData(node, MIRROR_METACLASS)\n if validate:\n otherNode = data['otherNode']\n if otherNode and validate:\n if getPairedNode(otherNode, False) == node:\n return otherNode\n else:\n LOG.debug('{0} pairing not reciprocated'.format(node))\n else:\n return data['otherNode']\n\n\ndef removeMirroringData(node):\n \"\"\"\n Remove mirroring data from a node. This does NOT\n remove mirroring data from the other node, if there\n is one. See `unpairMirrorNode` for removing mirroring\n data from two nodes at once.\n\n Args:\n node: A PyNode, MObject, or node name\n \"\"\"\n meta.removeMetaData(node, MIRROR_METACLASS)\n\n\n# Transformations\n# ---------------\n\ndef isCentered(node, axis=0):\n \"\"\"\n Return True if the node is centered on a specific world axis.\n \"\"\"\n axis = nodes.getAxis(axis)\n absAxisVal = abs(node.getTranslation(space='world')[axis.index])\n return absAxisVal < MIRROR_THRESHOLD\n\n\ndef getCenteredParent(node, axis=0):\n \"\"\"\n Return the closest parent node that is centered.\n If no parent nodes are centered, return the highest parent.\n\n Args:\n node: A PyNode\n \"\"\"\n thisParent = node.getParent()\n if thisParent is None:\n return\n while thisParent is not None:\n if isCentered(thisParent, axis):\n return thisParent\n lastParent = thisParent\n thisParent = lastParent.getParent()\n return lastParent\n\n\ndef getMirroredParent(node):\n \"\"\"\n Return the closest parent node that has mirroring data.\n\n Args:\n node: A PyNode\n \"\"\"\n thisParent = node.getParent()\n if thisParent is None:\n return\n while thisParent is not None:\n if isMirrorNode(thisParent):\n return thisParent\n lastParent = thisParent\n thisParent = lastParent.getParent()\n return lastParent\n\n\ndef getMirroredOrCenteredParent(node, axis=0):\n \"\"\"\n Return the closest parent node that is either centered,\n or already paired with another mirroring node.\n \"\"\"\n center = getCenteredParent(node, axis)\n mirror = getMirroredParent(node)\n if center is None:\n return mirror\n if mirror is None:\n return center\n if center.hasParent(mirror):\n return center\n if mirror.hasParent(center):\n return mirror\n return center\n\n\ndef getBestMirrorMode(nodeA, nodeB):\n \"\"\"\n Given two nodes, return the mirror mode that matches\n their current transform relationship.\n\n Simple performs a loose check to see if the nodes are\n aligned, and if not, returns the Simple mirroring mode.\n \"\"\"\n awm = nodes.getWorldMatrix(nodeA)\n bwm = nodes.getWorldMatrix(nodeB)\n aaxes = nodes.getClosestAlignedAxes(awm)\n baxes = nodes.getClosestAlignedAxes(bwm)\n if aaxes == baxes:\n return MirrorMode.Aligned\n return MirrorMode.Simple\n\n\nclass MirrorOperation(object):\n \"\"\"\n An operation that can be performed when mirroring nodes.\n Receives a call to mirror a sourceNode and targetNode.\n \"\"\"\n\n def __init__(self):\n # the axis to mirror across\n self.axis = 0\n # if set, the custom matrix to use as the base for mirroring\n self.axisMatrix = None\n\n def mirrorNode(self, sourceNode, destNode, isNewNode):\n \"\"\"\n Implement in subclasses to perform the mirroring operation.\n \"\"\"\n raise NotImplementedError\n\n\nclass MirrorParenting(MirrorOperation):\n \"\"\"\n Mirrors the parenting structure of nodes.\n \"\"\"\n\n def __init__(self):\n super(MirrorParenting, self).__init__()\n # when true, will search for centered nodes for joints\n self.findCenteredJoints = True\n\n def mirrorNode(self, sourceNode, destNode, isNewNode):\n \"\"\"\n Change the parent of destNode to match that of sourceNode,\n ensuring the use of paired nodes where possible to preserve\n a mirrored parenting structure.\n\n Handles joint parenting specially by checking for centered\n parents along an axis, as well as connecting inverse scales\n so that segment scale compensate still works.\n \"\"\"\n with preservedSelection():\n # get parent of source node\n if self.findCenteredJoints and isinstance(sourceNode, pm.nt.Joint):\n srcParent = getMirroredOrCenteredParent(sourceNode, self.axis)\n else:\n srcParent = sourceNode.getParent()\n\n if srcParent:\n dstParent = getPairedNode(srcParent)\n if dstParent:\n destNode.setParent(dstParent)\n else:\n destNode.setParent(srcParent)\n else:\n destNode.setParent(None)\n\n # handle joint reparenting\n if isinstance(destNode, pm.nt.Joint):\n p = destNode.getParent()\n if p and isinstance(p, pm.nt.Joint):\n if not pm.isConnected(p.scale, destNode.inverseScale):\n p.scale >> destNode.inverseScale\n\n\nclass MirrorTransforms(MirrorOperation):\n \"\"\"\n Mirrors the transform matrices of nodes.\n Also provides additional functionality for 'flipping' node\n matrices (simultaneous mirroring on both sides).\n \"\"\"\n\n def __init__(self):\n super(MirrorTransforms, self).__init__()\n\n # the type of transformation mirroring to use\n self.mirrorMode = MirrorMode.Simple\n\n self.useNodeSettings = True\n self.excludedNodeSettings = None\n self.mirroredAttrs = []\n self.customMirrorAttrExps = {}\n\n # used when getting mirrored matrices\n self.mirrorTranslate = True\n self.mirrorRotate = True\n\n # used when applying mirrored matrices\n self.setTranslate = True\n self.setRotate = True\n self.setScale = True\n self.setAttrs = True\n\n def _kwargsForGet(self):\n \"\"\"\n Return kwargs for getMirrorSettings calls\n \"\"\"\n keys = [\n 'axis', 'axisMatrix', 'mirrorMode',\n 'useNodeSettings', 'excludedNodeSettings',\n 'mirroredAttrs', 'customMirrorAttrExps',\n ]\n kwargs = dict([(k, getattr(self, k)) for k in keys])\n kwargs['translate'] = self.mirrorTranslate\n kwargs['rotate'] = self.mirrorRotate\n return kwargs\n\n def _kwargsForApply(self):\n \"\"\"\n Return kwargs for applyMirrorSettings calls\n \"\"\"\n return dict(\n translate=self.setTranslate,\n rotate=self.setRotate,\n scale=self.setScale,\n attrs=self.setAttrs,\n )\n\n def mirrorNode(self, sourceNode, destNode, isNewNode):\n \"\"\"\n Move a node to the mirrored position of another node.\n\n Args:\n sourceNode (PyNode): The node whos position will be used\n destNode (PyNode): The node to modify\n isNewNode (bool): Is the destination node newly created?\n \"\"\"\n settings = getMirrorSettings(\n sourceNode, destNode, **self._kwargsForGet())\n if settings:\n applyMirrorSettings(settings, **self._kwargsForApply())\n\n def _prepareFlip(self, sourceNode, destNode):\n \"\"\"\n Return settings gathered in preparation for flipping two nodes.\n \"\"\"\n sourceSettings = getMirrorSettings(\n sourceNode, destNode, **self._kwargsForGet())\n destSettings = getMirrorSettings(\n destNode, sourceNode, **self._kwargsForGet())\n return (sourceSettings, destSettings)\n\n def _applyFlip(self, flipData):\n \"\"\"\n Apply the flip data gathered from `_prepareFlip,` which will\n move the nodes to their flipped locations.\n \"\"\"\n sourceSettings, destSettings = flipData\n if sourceSettings and destSettings:\n applyMirrorSettings(sourceSettings, **self._kwargsForApply())\n applyMirrorSettings(destSettings, **self._kwargsForApply())\n\n def flip(self, sourceNode, destNode):\n \"\"\"\n Flip the transforms of two nodes such that each\n node moves to the mirrored transform of the other.\n \"\"\"\n flipData = self._prepareFlip(sourceNode, destNode)\n self._applyFlip(flipData)\n\n def flipMultiple(self, nodePairs):\n \"\"\"\n Perform `flip` on multiple nodes, by gathering first\n and then applying second, in order to avoid parenting\n and dependency issues.\n\n Args:\n nodePairs (list): A list of 2-tuple PyNodes representing\n (source, dest) node for each pair.\n \"\"\"\n\n flipDataList = []\n for (source, dest) in nodePairs:\n flipData = self._prepareFlip(source, dest)\n flipDataList.append(flipData)\n\n for flipData in flipDataList:\n self._applyFlip(flipData)\n\n def flipCenter(self, nodes):\n \"\"\"\n Move one or more non-mirrored nodes to the mirrored position\n of its current transform. The node list should be in order of\n dependency, where parents are first, followed by children in\n hierarchial order.\n \"\"\"\n settings = []\n\n for n in nodes:\n kwargs = self._kwargsForGet()\n kwargs['mirrorMode'] = MirrorMode.Aligned\n kwargs['excludedNodeSettings'] = ['mirrorMode']\n s = getMirrorSettings(n, n, **kwargs)\n settings.append(s)\n\n # TODO: attempt to automatically handle parent/child relationships\n # to lift the requirement of giving nodes in hierarchical order\n for s in settings:\n applyMirrorSettings(s, **self._kwargsForApply())\n\n\nclass MirrorCurveShapes(MirrorOperation):\n \"\"\"\n Mirrors the NurbsCurve shapes of a node by simply\n flipping them, assuming MirrorTransformations would also\n be run on the mirrored nodes.\n\n Only occurs on new nodes, since the shapes only need\n to be flipped once. Does not copy shape information from\n the source node (TODO: it should...)\n \"\"\"\n\n def __init__(self):\n super(MirrorCurveShapes, self).__init__()\n\n self.mirrorMode = MirrorMode.Simple\n\n def mirrorNode(self, sourceNode, destNode, isNewNode):\n # curve shape mirroring doesn't care about the actual\n # position, its only job is to flip the curve\n # shapes the first time they are mirrored\n if isNewNode:\n MirrorCurveShapes.flipAllCurveShapes(\n destNode, self.axis, self.mirrorMode)\n\n @staticmethod\n def flipAllCurveShapes(node, axis=0, mirrorMode=MirrorMode.Simple):\n \"\"\"\n Flip the position of all cvs in all curve shapes of a node\n in a manner that corresponds to the transformation mirror modes.\n\n Args:\n curveShape (NurbsCurve): The curve to mirror\n axis (int): An axis to mirror across\n mirrorMode: The MirrorMode type to use\n \"\"\"\n shapes = node.getChildren(s=True)\n for shape in shapes:\n if hasattr(shape, \"cv\"):\n MirrorCurveShapes.flipCurveShape(shape, axis, mirrorMode)\n\n @staticmethod\n def flipCurveShape(curveShape, axis=0, mirrorMode=MirrorMode.Simple):\n \"\"\"\n Flip the position of all cvs in a curve shape in a manner that\n corresponds to the transformation mirror modes.\n\n Args:\n curveShape (NurbsCurve): The curve to mirror\n axis (int): An axis to mirror across\n mirrorMode: The MirrorMode type to use\n \"\"\"\n if mirrorMode == MirrorMode.Simple:\n pm.scale(curveShape.cv, [-1, -1, -1])\n elif mirrorMode == MirrorMode.Aligned:\n s = [1, 1, 1]\n s[axis] = -1\n pm.scale(curveShape.cv, s)\n\n\nclass BlueprintMirrorOperation(MirrorOperation):\n \"\"\"\n A MirrorOperation that makes use of a Blueprint config\n \"\"\"\n\n def __init__(self):\n super(BlueprintMirrorOperation, self).__init__()\n # the Blueprint owner of the mirror operation\n self.blueprint = None\n # the Blueprint's config data\n self._config = None\n\n def getConfig(self):\n \"\"\"\n Return the Blueprint's config. Caches the config\n on the first request.\n \"\"\"\n if self._config is None:\n if self.blueprint:\n self._config = self.blueprint.getConfig()\n # if still no config, set to empty dict to prevent repeat check\n if self._config is None:\n self._config = {}\n return self._config\n\n\ndef _createNameReplacement(search, replace):\n \"\"\"\n Return a tuple containing a regex and replacement string.\n Regexes replace prefixes, suffixes, or middles, as long as\n the search is separated with '_' from adjacent characters.\n \"\"\"\n regex = re.compile('(? {1}\".format(attrName, val))\n attr = settings['destNode'].attr(attrName)\n attr.set(val)\n\n\nCUSTOM_EXP_FMT = \"\"\"\\\ndef exp():\n {body}return {lastLine}\nresult = exp()\n\"\"\"\n\n\ndef evalCustomMirrorAttrExp(sourceNode, destNode, attr, exp):\n result = {}\n\n LOG.debug(\"Raw Exp: {0}\".format(repr(exp)))\n _globals = {}\n _globals['node'] = sourceNode\n _globals['dest_node'] = destNode\n if hasattr(sourceNode, attr):\n _globals['value'] = getattr(sourceNode, attr).get()\n else:\n raise KeyError(\n \"{0} missing mirrored attr {1}\".format(sourceNode, attr))\n if hasattr(destNode, attr):\n _globals['dest_value'] = getattr(destNode, attr).get()\n else:\n raise KeyError(\"{0} missing mirrored attr {1}\".format(destNode, attr))\n\n # Add a return to the last line of the expression\n # so we can treat it as a function\n body = [l for l in exp.strip().split('\\n') if l]\n lastLine = body.pop(-1)\n _exp = CUSTOM_EXP_FMT.format(\n body='\\n\\t'.join(body + ['']), lastLine=lastLine)\n\n # TODO: do this without exec\n exec(_exp, _globals)\n result = _globals['result']\n\n return result\n\n\ndef getMirroredMatrices(node,\n axis=0, axisMatrix=None,\n translate=True, rotate=True,\n mirrorMode=MirrorMode.Simple):\n \"\"\"\n Return the mirrored matrix or matrices for the given node\n Automatically handles Transform vs. Joint differences\n\n Args:\n axis (int): An axis to mirror across\n axisMatrix: the matrix in which we should mirror\n translate (bool): If False, the matrix will not be moved\n rotate (bool): If False, the matrix will not be rotated\n mirrorMode: what type of mirroring should be performed, see `MirrorMode`\n \"\"\"\n # build kwargs for both commands\n kwargs = dict(\n axis=axis,\n axisMatrix=axisMatrix,\n translate=translate,\n rotate=rotate,\n mirrorMode=mirrorMode,\n )\n result = {}\n if isinstance(node, pm.nt.Joint):\n result['type'] = 'joint'\n jmatrices = joints.getJointMatrices(node)\n result['matrices'] = getMirroredJointMatrices(*jmatrices, **kwargs)\n else:\n result['type'] = 'node'\n result['matrices'] = [getMirroredTransformMatrix(\n nodes.getWorldMatrix(node), **kwargs)]\n return result\n\n\ndef setMirroredMatrices(node, mirroredMatrices,\n translate=True, rotate=True, scale=True):\n \"\"\"\n Set the world matrix for the given node using the given mirrored matrices\n Automatically interprets Transform vs. Joint matrix settings\n \"\"\"\n if mirroredMatrices['type'] == 'joint':\n LOG.debug(\"Applying Joint Matrices\")\n joints.setJointMatrices(node, *mirroredMatrices['matrices'],\n translate=translate,\n rotate=rotate\n )\n else:\n LOG.debug(\"Applying Transform Matrix\")\n nodes.setWorldMatrix(node, *mirroredMatrices['matrices'],\n translate=translate,\n rotate=rotate,\n scale=scale\n )\n\n\ndef getMirroredTransformMatrix(matrix,\n axis=0, axisMatrix=None,\n translate=True, rotate=True,\n mirrorMode=MirrorMode.Simple):\n \"\"\"\n Return the mirrored version of the given matrix.\n\n Args:\n axis (int): An axis to mirror across\n axisMatrix: A matrix in which we should mirror\n translate (bool): If False, the matrix will not be moved\n rotate (bool): If False, the matrix will not be rotated\n mirrorMode: what type of mirroring should be performed,\n default is MirrorMode.Simple\n \"\"\"\n axis = nodes.getAxis(axis)\n if axisMatrix is not None:\n # remove scale from the axisMatrix\n axisMatrix = nodes.getScaleMatrix(\n axisMatrix).inverse() * axisMatrix\n matrix = matrix * axisMatrix.inverse()\n s = nodes.getScaleMatrix(matrix)\n r = nodes.getRotationMatrix(matrix)\n t = matrix[3]\n if translate:\n # negate translate vector\n t[axis.index] = -t[axis.index]\n if rotate:\n r = invertOtherAxes(r, axis)\n if mirrorMode == MirrorMode.Aligned:\n LOG.debug(\"Counter Rotating because mirror mode is Aligned\")\n r = counterRotateForNonMirrored(r, axis)\n mirror = s * r\n mirror[3] = t\n if axisMatrix is not None:\n mirror = mirror * axisMatrix\n return mirror\n\n\ndef getMirroredJointMatrices(matrix, r, ra, jo,\n axis=0, axisMatrix=None,\n translate=True, rotate=True,\n mirrorMode=MirrorMode.Simple):\n \"\"\"\n Return the given joint matrices mirrored across the given axis.\n Returns the full transformation matrix, rotation, rotation axis,\n and joint orient matrices.\n\n Args:\n axis (int): An axis to mirror across\n axisMatrix: A matrix in which we should mirror\n translate (bool): If False, the matrix will not be moved\n rotate (bool): If False, the matrix will not be rotated\n mirrorMode: what type of mirroring should be performed,\n default is MirrorMode.Simple\n \"\"\"\n LOG.debug(\"Getting Mirrored Joint Matrices\")\n # matches transform orientation\n mirror = getMirroredTransformMatrix(\n matrix, axis, axisMatrix, translate, rotate)\n if rotate:\n if axisMatrix is not None:\n # matches orientation with jo\n invScaleMtx = nodes.getScaleMatrix(axisMatrix).inverse()\n axisMatrix = invScaleMtx * axisMatrix\n jo = jo * axisMatrix.inverse()\n # flips orientation\n jo = invertOtherAxes(jo, axis)\n if mirrorMode == MirrorMode.Aligned:\n LOG.debug(\"Counter Rotating because mirror mode is Aligned\")\n # changes orientation to inverted world\n jo = counterRotateForMirroredJoint(jo)\n if axisMatrix is not None:\n # doesnt seem to do anything\n jo = jo * axisMatrix\n return mirror, r, ra, jo\n\n\ndef invertOtherAxes(matrix, axis=0):\n \"\"\"\n Invert the other axes of the given rotation\n matrix based on rows of the matrix.\n \"\"\"\n axis = nodes.getAxis(axis)\n others = nodes.getOtherAxes(axis)\n x, y, z = matrix[:3]\n for v in (x, y, z):\n for a in others:\n v[a.index] *= -1\n return pm.dt.Matrix(x, y, z)\n\n\ndef counterRotateForNonMirrored(matrix, axis=0):\n \"\"\"\n Essentially rotates 180 on the given axis,\n this is used to create mirroring when ctls\n are setup to not be mirrored at rest pose.\n \"\"\"\n axis = nodes.getAxis(axis)\n others = [o.index for o in nodes.getOtherAxes(axis)]\n x, y, z = matrix[:3]\n for i, row in enumerate((x, y, z)):\n if i in others:\n for col in range(3):\n row[col] *= -1\n return pm.dt.Matrix(x, y, z)\n\n\ndef counterRotateForMirroredJoint(matrix):\n \"\"\"\n Essentially rotates 180 on the given axis,\n this is used to create mirroring when ctls\n are setup to not be mirrored at rest pose.\n \"\"\"\n x, y, z = matrix[:3]\n for row in (x, y, z):\n for col in range(3):\n row[col] *= -1\n return pm.dt.Matrix(x, y, z)\n","sub_path":"src/pulse/scripts/pulse/sym.py","file_name":"sym.py","file_ext":"py","file_size_in_byte":39362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"370527312","text":"# 使用requests发送post请求,进行中英文翻译\n\nimport requests\n\nheaders = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36\"}\ndata = {\n \"from\": \"en\",\n \"to\": \"zh\",\n \"query\": \"centery\",\n \"transtype\": \"translang\",\n \"simple_means_flag\": \"3\",\n \"sign\": \"478596.241333\",\n \"token\": \"64955b584e2756a78633e5c5d533bb92\",\n}\npost_url = \"https://fanyi.baidu.com/v2transapi\"\nresponse = requests.post(post_url, data=data, headers=headers)\nprint(response.content.decode())\n\n# 由于data中的sign是动态变化的,很可能是使用js动态生成的\n# 对于这种类型的数据我们没有暂时没有办法通过验证,可以考虑查看手机版的页面\n# 看手机版是否可以通过传递更少的参数,实现同样的功能\n","sub_path":"001-beginning/006-translate.py","file_name":"006-translate.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"352292196","text":"#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting\nimport os\ntry:\n\tos.chdir(os.path.join(os.getcwd(), 'ML_HW3_Anushree_Desai_Code'))\n\tprint(os.getcwd())\nexcept:\n\tpass\n\n#%%\nimport gzip, pickle\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nimport pandas as pd\nfrom sklearn.metrics import classification_report\nimport seaborn as sn\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\n\nwith gzip.open('mnist_rowmajor.pkl.gz', 'rb') as data_fh:\n data = pickle.load(data_fh, encoding='latin1')\n\ntrain_images = data['images_train']\ntrain_labels = data['labels_train']\n\nimages_train, images_dev, labels_train, labels_dev = train_test_split(train_images, train_labels, test_size=0.20, random_state=4)\nimages_test = data['images_test']\nlabels_test = data['labels_test']\n# print(len(images_train))\n# print(len(images_dev))\n# print(len(labels_train))\n# print(len(labels_dev))\n# print(len(images_test))\n# print(len(labels_test))\n\nTRAIN_LENGTH = len(images_train)\nDEV_LENGTH = len(images_dev)\nTEST_LENGTH = len(images_test)\n\n\n#%%\n# Feature 1: Signing images\nfeature1_training_set = np.empty((TRAIN_LENGTH, 784))\nfor idx, i in enumerate(images_train):\n signed_image_train = list(map((lambda x: 1 if (x > 0) else 0), i))\n feature1_training_set[idx] = signed_image_train\n\nfeature1_dev_set = np.empty((DEV_LENGTH, 784))\nfor idx, i in enumerate(images_dev):\n signed_image_dev = list(map((lambda x: 1 if (x > 0) else 0), i))\n feature1_dev_set[idx] = signed_image_dev\n \n\n\n#%%\nfeature1_test_set = np.zeros((TEST_LENGTH, 784))\nfor idx, i in enumerate(images_test):\n signed_image_test = list(map((lambda x: 1 if (x > 0) else 0), i))\n feature1_test_set[idx] = signed_image_test\n \ncomplete_training = np.zeros((60000, 784))\nfor idx, i in enumerate(train_images):\n temp = list(map((lambda x: 1 if (x > 0) else 0), i))\n complete_training[idx] = temp\n\n\n#%%\n# Feature 2: transform if i,j & p,q > 0\ndef transform(row):\n arr = np.zeros((783))\n for k in range(len(row) - 1):\n if(row[k] > 0 and row[k + 1] > 0):\n arr[k] = 1\n else:\n arr[k] = 0\n return arr\n\nfeature2_training_set = np.zeros((TRAIN_LENGTH, 783))\nfor idx, image in enumerate(images_train):\n image = transform(image)\n feature2_training_set[idx] = image\n\nfeature2_dev_set = np.zeros((DEV_LENGTH, 783))\nfor idx, image in enumerate(images_dev):\n image = transform(image)\n feature2_dev_set[idx] = image\n\n\n#%%\ndef experimentEvaluation(y_correct, y_pred):\n cm = confusion_matrix(y_correct.flatten(), y_pred.flatten())\n df_cm = pd.DataFrame(cm.astype(int), range(10), range(10))\n plt.figure(figsize = (10,10))\n sn.heatmap(df_cm, annot=True, annot_kws={\"size\": 16}, fmt=\"d\")\n plt.xlabel('Predicted label')\n plt.ylabel('True label')\n plt.show()\n accuracy = accuracy_score(y_correct.flatten(), y_pred.flatten())\n print('Accuracy: ', accuracy)\n print(classification_report(y_correct.flatten(), y_pred.flatten()))\n\n\n#%%\n# Configuration 1: feature = signed images, regularization = l1\nlogisticRegression = LogisticRegression(penalty = 'l1')\nlogisticRegression.fit(feature1_training_set, labels_train)\npredictionsConfig1 = logisticRegression.predict(feature1_dev_set)\nexperimentEvaluation(labels_dev, predictionsConfig1)\n\n\n#%%\n# Configuration 2: feature = signed images, regularization = l2\nlogisticRegression = LogisticRegression(penalty = 'l2')\nlogisticRegression.fit(feature1_training_set, labels_train)\npredictionsConfig2 = logisticRegression.predict(feature1_dev_set)\nexperimentEvaluation(labels_dev, predictionsConfig2)\n\n\n#%%\n# Configuration 3: feature = transformed images, regularization = l1\nlogisticRegression = LogisticRegression(penalty = 'l1')\nlogisticRegression.fit(feature2_training_set, labels_train)\npredictionsConfig3 = logisticRegression.predict(feature2_dev_set)\nexperimentEvaluation(labels_dev, predictionsConfig3)\n\n\n#%%\n# Configuration 4: feature = transformed images, regularization = l2\nlogisticRegression = LogisticRegression(penalty = 'l2')\nlogisticRegression.fit(feature2_training_set, labels_train)\npredictionsConfig4 = logisticRegression.predict(feature2_dev_set)\nexperimentEvaluation(labels_dev, predictionsConfig4)\n\n\n#%%\n# Testing on Test Data\ntraining_set = np.concatenate((feature1_training_set, feature1_dev_set), axis=0)\n# print(training_set.shape)\n# print(np.concatenate((labels_train, labels_dev), axis=0).shape)\nlogisticRegression = LogisticRegression(penalty = 'l1')\nlogisticRegression.fit(complete_training, train_labels)\npredictions = logisticRegression.predict(feature1_test_set)\nexperimentEvaluation(labels_test, predictions.reshape((10000, 1)))\n\n\n","sub_path":"ML_HW3_Maxent.py","file_name":"ML_HW3_Maxent.py","file_ext":"py","file_size_in_byte":4877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"374859551","text":"#!/usr/bin/python2\nimport cherrypy\nimport pickle\nimport simplejson\nimport os\n\nMEDIA_DIR = os.path.join(os.path.abspath(\".\"), u\"media\")\n\ndef get_race_by_neighborhood(slug):\n with open(\"../data/%s_race.pickle\" % slug, \"rb\") as f:\n return pickle.load(f)\n\ndef get_age_by_neighborhood(slug):\n with open(\"../data/%s_age.pickle\" % slug, \"rb\") as f:\n return pickle.load(f)\n\ndef get_sex_by_neighborhood(slug):\n with open(\"../data/%s_sex.pickle\" % slug, \"rb\") as f:\n return pickle.load(f)\n\nclass Root(object):\n @cherrypy.expose\n def index(self):\n return open(os.path.join(\"../\", u'index.html'))\n \n @cherrypy.expose\n def neighborhood_race(self, name, slug):\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n ret = []\n d = get_race_by_neighborhood(slug)\n ret.append(\"Race,Population\")\n for key, val in d.items():\n ret.append(\"%s,%s\" % (key,val))\n return \"\\n\".join(ret)\n\n @cherrypy.expose\n def neighborhood_sex(self, name, slug):\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n ret = []\n d = get_sex_by_neighborhood(slug)\n total_count = 0\n male_count = 0\n female_count = 0\n for key, value in d.items():\n if key == \"Male\":\n male_count = value\n elif key == \"Female\":\n female_count = value\n total_count = male_count + female_count\n percent_male = (float(male_count) / float(total_count))*100\n percent_female = (float(female_count) / float(total_count))*100\n ret.append(\"Sex,Population\")\n ret.append(\"Male,%.2f\" % percent_male)\n ret.append(\"Female,%.2f\" % percent_female)\n return \"\\n\".join(ret)\n \n @cherrypy.expose\n def neighborhood_age(self, name, slug):\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n ret = []\n d = get_age_by_neighborhood(slug)\n ret.append(\"Age,Population\")\n for key, val in d.items():\n ret.append(\"%s,%s\" % (key,val))\n return \"\\n\".join(ret)\n \nconfig = {'/media':\n {'tools.staticdir.on': True,\n 'tools.staticdir.dir': MEDIA_DIR,\n }\n }\n\nif __name__ == '__main__':\n cherrypy.server.socket_host = '0.0.0.0'\n cherrypy.quickstart(Root(), '/', config=config)\n \n","sub_path":"py/dhelper.py","file_name":"dhelper.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"563160961","text":"## FUNCIONES DEL NOTEBOK DE SERIES TEMPORALES:\n#------------------------------------------------------------------\n\n#Importamos las librerías\n\n\nimport pandas as pd\nfrom pandas import datetime as dt\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\n\n# Import Statsmodels\nfrom statsmodels.api import tsa\n\nfrom statsmodels.tsa.arima_model import ARIMA\n\nimport statsmodels.api as sm\n#VAR\nfrom statsmodels.tsa.api import VAR\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tools.eval_measures import rmse, aic\n\nfrom statsmodels.tsa.stattools import grangercausalitytests\nfrom statsmodels.tsa.vector_ar.vecm import coint_johansen\nfrom statsmodels.tsa.stattools import acf\n\n#plot sección 2\nimport inspect\n\n\n## SECCIÓN UNO: MODELOS DE SERIES TEMPORALES\n\n#------------------------------------------------------------------\n\n##Función nº 1\ndef preprocesado_pais(covid_vaccine_data,pais):\n \"\"\"\n - covid_vaccine_data: dataframe con todas las vacunas\n - pais: pais que queremos escoger para analizar\n \n return: dataframe preprocesado.\n \"\"\"\n vacc_pais = covid_vaccine_data.loc[covid_vaccine_data.country == pais]\n #print(pais)\n vacc_pais.set_index('date',inplace=True)\n \n \n #crear una funcion de preprocesado\n vacc_pais['daily_vaccinations']= vacc_pais['daily_vaccinations'].interpolate(method='cubicspline')\n vacc_pais['total_vaccinations']= vacc_pais['total_vaccinations'].interpolate(method='cubicspline')\n vacc_pais['people_vaccinated']= vacc_pais['people_vaccinated'].interpolate(method='cubicspline')\n\n vacc_pais['people_fully_vaccinated']= vacc_pais['people_fully_vaccinated'].interpolate(method='cubicspline')\n vacc_pais['total_vaccinations_per_hundred']= vacc_pais['total_vaccinations_per_hundred'].interpolate(method='cubicspline')\n vacc_pais['people_vaccinated_per_hundred']= vacc_pais['people_vaccinated_per_hundred'].interpolate(method='cubicspline')\n\n vacc_pais['people_fully_vaccinated_per_hundred']=vacc_pais['people_fully_vaccinated_per_hundred'].interpolate(method='cubicspline')\n vacc_pais['daily_vaccinations_per_million']= vacc_pais['daily_vaccinations_per_million'].interpolate(method='cubicspline')\n\n vacc_pais = vacc_pais.fillna(vacc_pais.median())\n \n vacc_pais[\"date\"] = vacc_pais.index\n vacc_pais[\"Days\"]=vacc_pais.date - vacc_pais.date.min()\n vacc_pais[\"Days\"]=vacc_pais[\"Days\"].dt.days\n \n population = vacc_pais[\"Population\"][1]\n vacc_pais['percentage_vaccinated'] = (vacc_pais.people_fully_vaccinated/population)*100\n \n return vacc_pais\n\n\n#Función 2, reorganización de los datos\ndef organize_data(to_forecast, window, horizon=1):\n \n shape = to_forecast.shape[:-1] + (to_forecast.shape[-1] - window + 1, window)\n strides = to_forecast.strides + (to_forecast.strides[-1],)\n X = np.lib.stride_tricks.as_strided(to_forecast,\n shape=shape,\n strides=strides)\n y = np.array([X[i+horizon][-1] for i in range(len(X)-horizon)])\n return X[:-horizon], y\n\n\n\n\ndef lr_series(time_series_people,time_series_total,lag,variable1,variable2):\n \"\"\"\n input: dos series:\n - time_series_people, variable 1\n - time_series_total, variable 2\n - lag, el desfase, int\n - variable1, nombre de la variable a predecir ,str\n - variable2, nombre de la variable a predecir, str\n \n return: lista de listas con las prestaciones de los dos modelos de regresión: [[MAE_1,MAE2_1],[MAE_2,MAE2_2]]\n \n \"\"\"\n \n lag = lag\n X_1, y_1 = organize_data(np.array(time_series_people), lag)\n X_2, y_2 = organize_data(np.array(time_series_total), lag)\n \n #variable1\n lr = LinearRegression()\n lr_fit_people = lr.fit(X_1, y_1)\n lr_prediction_people = lr_fit_people.predict(X_1)\n #variable2\n lr_fit_total = lr.fit(X_2, y_2)\n lr_prediction_total = lr_fit_total.predict(X_2)\n \n plt.figure(figsize=(17, 4))\n plt.subplot(121)\n plt.plot(time_series_people.values, '-o', color='teal')\n plt.plot(np.arange(lag, len(time_series_people)), lr_prediction_people, '-o', label='prediction', color='orange')\n plt.title('Linear regression:'+ variable1)\n plt.legend(fontsize=12);\n\n MAE_var1 = mean_absolute_error(time_series_people[lag:], lr_prediction_people)\n MAE2_var1 = mean_absolute_error(time_series_people[-90:], lr_prediction_people[-90:])\n\n print(variable1,': ')\n print('MAE = {0:.3f}'.format(MAE_var1))\n print('MAE2 = {0:.3f}'.format(MAE2_var1)) #for the last 90 days only\n\n print(' \\n ')\n plt.subplot(122)\n plt.plot(time_series_total.values, '-o', color='teal')\n plt.plot(np.arange(lag, len(time_series_total)), lr_prediction_total, '-o', label='prediction', color='orange')\n plt.title('Linear regression model:'+ variable2)\n plt.legend(fontsize=12);\n \n MAE_var2 = mean_absolute_error(time_series_total[lag:], lr_prediction_total)\n MAE2_var2 = mean_absolute_error(time_series_total[-90:], lr_prediction_total[-90:])\n\n print(variable2, ': ')\n print('MAE = {0:.3f}'.format(mean_absolute_error(time_series_total[lag:], lr_prediction_total)))\n print('MAE2 = {0:.3f}'.format(mean_absolute_error(time_series_total[-90:], lr_prediction_total[-90:]))) #for the last 90 days only\n \n return [[MAE_var1, MAE2_var1],[MAE_var2,MAE2_var2]]\n\n\n\n#--------procedimiento de plot -- ----- -- - - - - - -- - - - - - -\n\n##Procedimiento nº1\ndef plot_variables(data, variable1, variable2):\n \"\"\"\n - data = dataframe del país de interés, DataFrame, pandas\n - variable1 = variable que se quiere visualizar, str\n - variable2 = variable que se quiere visualizar, str\n \n \"\"\"\n sns.set_style(\"darkgrid\")\n plt.figure(figsize=(16, 3))\n plt.subplot(121)\n plt.title(variable1)\n sns.lineplot(data=data[variable1])\n #sns.lineplot(data = vacc_Spain['daily_vaccinations'])\n plt.title(variable1,fontsize=15)\n plt.xlabel('Date',fontsize=15)\n plt.ylabel(variable1, fontsize=15)\n\n plt.subplot(122)\n plt.title(variable2)\n sns.lineplot(data=data[variable2])\n plt.title(variable2,fontsize=15)\n plt.xlabel('Date',fontsize=15)\n plt.ylabel(variable2, fontsize=15)\n plt.show()\n\n \n#Procedimiento nº2 #media semanal y mensual\ndef weekly_monthly_avg(vacc_pais,variable1,variable2):\n \"\"\"\n - data = dataframe del país de interés, DataFrame, pandas\n - variable1 = variable que se quiere visualizar, str\n - variable2 = variable que se quiere visualizar, str\n \n \"\"\"\n vacc_weekly_avg = vacc_pais.resample('W').apply(np.mean)\n vacc_monthly_avg = vacc_pais.resample('M').apply(np.mean)\n \n plt.figure(figsize=(10,4))\n plt.subplot(221)\n plt.title('Vaccination week Avg', loc='center')\n plt.plot(vacc_weekly_avg[variable1], \"-o\", markersize=3, color='teal')\n plt.subplot(222)\n plt.title('Vaccination monthly Avg', loc='center')\n plt.plot(vacc_monthly_avg[variable1], \"-o\", markersize=3, color='teal')\n\n plt.subplot(223)\n plt.title('Vaccination week Avg', loc='center')\n plt.plot(vacc_weekly_avg[variable2], \"-o\", markersize=3, color='teal')\n plt.subplot(224)\n plt.title('Vaccination monthly Avg', loc='center')\n plt.plot(vacc_monthly_avg[variable2], \"-o\", markersize=3, color='teal')\n plt.show()\n \n \n \n#Procedimento nº3\ndef rolling_mean(vacc_pais,variable1,variable2):\n \"\"\"\n - info: cálculo y visualización de media móvil\n \n data = dataframe del país de interés, DataFrame, pandas\n variable1 = variable que se quiere visualizar, str\n variable2 = variable que se quiere visualizar, str\n \"\"\"\n rolling_mean_1 = vacc_pais[variable1].rolling(window=7, center=False).mean() #window of 7 (weekly avg) captures our data better \n rolling_mean_2 = vacc_pais[variable2].rolling(window=7, center=False).mean() #window of 7 (weekly avg) captures our data better\n \n plt.figure(figsize=(16,3))\n plt.subplot(121)\n plt.plot(vacc_pais[variable1], color='teal', label = variable1)\n plt.plot(rolling_mean_1, 'red',label = 'media móvil')\n plt.title(variable1)\n plt.xticks(rotation=75)\n plt.legend()\n\n plt.subplot(122)\n plt.plot(vacc_pais[variable2], color='teal', label = variable2)\n plt.plot(rolling_mean_2, 'red',label = 'media móvil')\n plt.title(variable2)\n plt.xticks(rotation=75)\n plt.legend()\n\n \n\n#Procedimento nº4, autocorrelación \ndef autocorrelation(vacc_pais,variable1,variable2):\n lags = np.arange(2,100,3) #elegir desfase\n autocorrs_variable1 = [vacc_pais[variable1].autocorr(lag=lag) \n for lag in lags]\n\n\n plt.figure(figsize=(16, 3))\n plt.subplot(121)\n plt.stem(lags, autocorrs_variable1)\n plt.title(variable1)\n plt.xlabel(\"Lag\", fontsize=12)\n plt.ylabel(\"Autocorrelation\", fontsize=12)\n\n autocorrs_variable2 = [vacc_pais[variable2].autocorr(lag=lag) \n for lag in lags]\n plt.subplot(122)\n plt.stem(lags, autocorrs_variable2)\n plt.title('total_vaccinations')\n plt.xlabel(\"Lag\", fontsize=12)\n plt.ylabel(\"Autocorrelation\", fontsize=12)\n\n plt.show()\n \n \n#Procedimiento nº5, Modelo de series temporal:\n\ndef time_series_model(vacc_pais,time_series_people,time_series_total,optlag_people,optlag_total,model,days):\n \n people_fully_vaccinated = vacc_pais.people_fully_vaccinated\n people_fully_vaccinated_diff =people_fully_vaccinated.diff(2)\n \n total_vaccinations = vacc_pais.total_vaccinations\n total_vaccinations_diff =total_vaccinations.diff(2)\n \n #\n \n #AR, importante hacerlo ahora porque lo voy a utilizar para el ARIMA\n optlag_people = optlag_people\n ar_people = tsa.AR(time_series_people)\n ar_fit_people = ar_people.fit(maxlag=optlag_people)\n ar_forecast_people = ar_fit_people.predict(end=len(time_series_people)+(days-1))[-(days):] \n #ar_forecast_people\n \n optlag_total = optlag_total\n ar_total = tsa.AR(time_series_total)\n ar_fit_total = ar_total.fit(maxlag=optlag_total)\n ar_forecast_total = ar_fit_total.predict(end=len(time_series_total)+(days-1))[-(days):] \n #ar_forecast_total\n \n if model == 'AR':\n \n print('Pronóstico de la primera variable AR: ')\n print(ar_forecast_people)\n print('\\n')\n print('Pronóstico de la segunda variable AR: ')\n print(ar_forecast_total)\n \n #que ploteé el gráfico del pronóstico\n \n #people\n plt.figure(figsize=(17, 4))\n plt.subplot(121)\n plt.plot(time_series_people, '-o', label=\"original data\", color='teal')\n plt.plot(ar_forecast_people, '--o', label='prediction', color='orange')\n plt.title('Forecast AR, primera variable: people fully vaccinated')\n plt.legend(fontsize=12)\n\n #total_vaccinations\n plt.subplot(122)\n plt.plot(time_series_total, '-o', label=\"original data\", color='teal')\n plt.plot(ar_forecast_total, '--o', label='prediction', color='orange')\n plt.title('Forecast AR, segunda variable: total vaccinations')\n plt.legend(fontsize=12)\n \n \n if model == 'ARMA':\n #implementar ARMA\n \n #7 out of sample prediction with ARMA\n #people fully vaccinated\n arma_people = tsa.ARMA(time_series_people, order=(2, 1)) \n arma_people = arma_people.fit()\n arma_forecast_people = arma_people.predict(end=len(time_series_people)+(days-1))[-(days):]\n #arma_forecast_people\n\n #total vaccinations\n arma_total = tsa.ARMA(time_series_total, order=(2, 1)) \n arma_total = arma_total.fit()\n arma_forecast_total = arma_total.predict(end=len(time_series_total)+(days-1))[-(days):]\n #arma_forecast_total\n \n print('Pronóstico de la primera variable ARMA: ')\n print(arma_forecast_people)\n print('\\n')\n print('Pronóstico de la segunda variable ARMA: ')\n print(arma_forecast_total)\n \n #plot de ARMA\n \n #ARMA model's 7 out sample predicitons \n plt.figure(figsize=(16, 4))\n plt.subplot(121)\n plt.plot(time_series_people, '-o', label=\"original data\", color='teal')\n plt.plot(arma_forecast_people, '--o', label='prediction', color='orange')\n plt.legend(fontsize=12)\n plt.title('Forecast ARMA: people_fully_vaccinated')\n\n plt.subplot(122)\n plt.plot(time_series_total, '-o', label=\"original data\", color='teal')\n plt.plot(arma_forecast_total, '--o', label='prediction', color='orange')\n plt.legend(fontsize=12)\n plt.title('Forecast ARMA: total vaccinations')\n\n plt.show()\n \n if model == 'ARIMA':\n \n #ARIMA: people fully vaccinated \n model_people = ARIMA(time_series_people, order=(1,1,1))\n arima_fit_people = model_people.fit()\n arima_fit_people_predict = arima_fit_people.predict(start=days)\n arima_forecast_people= arima_fit_people.forecast(steps=days)[0]\n \n print('prestaciones: people_fully_vaccinated: ')\n print('MAE = {0:.3f}'.format(mean_absolute_error(time_series_people[days:], arima_fit_people_predict)))\n print('MAE2 = {0:.3f}'.format(mean_absolute_error(time_series_people[-90:], arima_fit_people_predict[-90:]))) #error only \n\n print('\\n')\n \n print('ARIMA: total vaccinations')\n print(arima_forecast_people)\n\n #ARIMA: totalvaccinations\n model_total = ARIMA(time_series_total, order=(1,1,1))\n arima_fit_total = model_total.fit()\n arima_fit_total_predict = arima_fit_total.predict(start=days)\n arima_forecast_total= arima_fit_total.forecast(steps=days)[0]\n print('ARIMA, total vaccinations:')\n print(arima_forecast_total)\n print('\\n')\n print('prestaciones: total_vaccinations: ')\n print('MAE = {0:.3f}'.format(mean_absolute_error(time_series_total[days:], arima_fit_total_predict)))\n print('MAE2 = {0:.3f}'.format(mean_absolute_error(time_series_total[-90:], arima_fit_total_predict[-90:]))) #error only \n\n \n \n \n #people\n idx_people = ar_forecast_people.index.values\n forecast_people_fully_vaccinated = []\n lag = 7\n \n #Escogemos el model AR porque tiene un MAE menor que el modelo ARMA \n \n for i, diff in enumerate(ar_forecast_people): \n prev_value_people = people_fully_vaccinated[-(lag)+i:][0]\n forecast_people_fully_vaccinated.append(prev_value_people+diff)\n\n people_fully_vaccinated_forecast = pd.Series(forecast_people_fully_vaccinated, index=idx_people)\n print('Forecast ARIMA: \\n')\n print(people_fully_vaccinated_forecast)\n\n #total_vaccinations\n idx_total = ar_forecast_total.index.values\n forecast_total = []\n\n for i, diff in enumerate(ar_forecast_total): #choosing AR as it produced lower MAE than ARMA model\n prev_value_total = total_vaccinations[-(lag)+i:][0]\n forecast_total.append(prev_value_total+diff)\n\n total_vaccinations_forecast = pd.Series(forecast_total, index=idx_total)\n print('\\n')\n print('Forecast ARIMA: \\n')\n print(total_vaccinations_forecast)\n \n hist_values_people = vacc_pais['people_fully_vaccinated'].append(people_fully_vaccinated_forecast)\n hist_values_total = vacc_pais['total_vaccinations'].append(total_vaccinations_forecast)\n \n #plot de ARIMA\n\n plt.figure(figsize=(17,4))\n plt.subplot(121)\n plt.plot(hist_values_people, '-o', color='teal', alpha=0.5)\n plt.plot(people_fully_vaccinated_forecast, '--o', label='prediction', color='orange')\n plt.legend()\n plt.title('Forecast ARIMA prediction: people_fully_vaccinated')\n plt.xlim('2021-02-25','2021-05-25')\n\n plt.subplot(122)\n plt.plot(hist_values_total, '-o', color='teal', alpha=0.5)\n plt.plot(total_vaccinations_forecast, '--o', label='prediction', color='orange')\n plt.legend()\n plt.title('Forecast ARIMA prediction: total_vaccinations')\n plt.xlim('2021-02-25','2021-05-25')\n \n if model == 'VAR':\n \n return ar_forecast_people\n \n \n \n \n \n#---\n\n\n \n\n#Función, test de Granger\ndef grangers_causation_matrix(data, variables, maxlag,test='ssr_chi2test', verbose=False):\n \"\"\"Compruebe la causalidad de Granger de todas las combinaciones posibles de las series temporales. Las filas son la \n variable de respuesta, las columnas son los predictores. Los valores de la tabla son los valores P. Los valores P \n menores que el nivel de significación (0,05), implican la hipótesis nula de que los coeficientes de los valores \n pasados correspondientes son cero, es decir, que la X no causa la Y puede ser rechazada.\n data : pandas dataframe containing the time series variables\n variables : list containing names of the time series variables. \"\"\"\n df = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables)\n for c in df.columns:\n for r in df.index:\n test_result = grangercausalitytests(data[[r, c]], maxlag=maxlag, verbose=False)\n p_values = [round(test_result[i+1][0][test][1],4) for i in range(maxlag)]\n if verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}')\n min_p_value = np.min(p_values)\n df.loc[r, c] = min_p_value\n df.columns = [var + '_x' for var in variables]\n df.index = [var + '_y' for var in variables]\n return df\n\n\n#Procedimiento, test de Cointegración: \ndef cointegration_test(df, alpha=0.05): \n \n \"\"\"Perform Johanson's Cointegration Test and Report Summary\"\"\"\n \n out = coint_johansen(df,-1,5)\n d = {'0.90':0, '0.95':1, '0.99':2}\n traces = out.lr1\n cvts = out.cvt[:, d[str(1-alpha)]]\n def adjust(val, length= 6): return str(val).ljust(length)\n\n # Summary\n print('Name :: Test Stat > C(95%) => Signif \\n', '--'*20)\n for col, trace, cvt in zip(df.columns, traces, cvts):\n print(adjust(col), ':: ', adjust(round(trace,2), 9), \">\", adjust(cvt, 8), ' => ' , trace > cvt) \n \n\n#Función para comprobar estocionariedad: \ndef adfuller_test(series, signif=0.05, name='', verbose=False):\n \n \"\"\"Perform ADFuller to test for Stationarity of given series and print report\"\"\"\n \n r = adfuller(series, autolag='AIC')\n output = {'test_statistic':round(r[0], 4), 'pvalue':round(r[1], 4), 'n_lags':round(r[2], 4), 'n_obs':r[3]}\n p_value = output['pvalue'] \n def adjust(val, length= 6): return str(val).ljust(length)\n\n # Print Summary\n print(f' Augmented Dickey-Fuller Test on \"{name}\"', \"\\n \", '-'*47)\n print(f' Null Hypothesis: Data has unit root. Non-Stationary.')\n print(f' Significance Level = {signif}')\n print(f' Test Statistic = {output[\"test_statistic\"]}')\n print(f' No. Lags Chosen = {output[\"n_lags\"]}')\n\n for key,val in r[4].items():\n print(f' Critical value {adjust(key)} = {round(val, 3)}')\n\n if p_value <= signif:\n print(f\" => P-Value = {p_value}. Rejecting Null Hypothesis.\")\n print(f\" => Series is Stationary.\")\n else:\n print(f\" => P-Value = {p_value}. Weak evidence to reject the Null Hypothesis.\")\n print(f\" => Series is Non-Stationary.\") \n \n#referencia: https://www.machinelearningplus.com/time-series/vector-autoregression-examples-python/\n \n\n#invertir la diferenciación\n#Función\ndef invert_transformation(df_train, df_forecast, second_diff=False):\n \"\"\"Revert back the differencing to get the forecast to original scale.\"\"\"\n df_fc = df_forecast.copy()\n columns = df_train.columns\n for col in columns: \n # Roll back 2nd Diff\n if second_diff:\n df_fc[str(col)+'_1d'] = (df_train[col].iloc[-1]-df_train[col].iloc[-2]) + df_fc[str(col)+'_2d'].cumsum()\n # Roll back 1st Diff\n df_fc[str(col)+'_forecast'] = df_train[col].iloc[-1] + df_fc[str(col)+'_1d'].cumsum()\n return df_fc\n \n#Funciones accuracy\ndef forecast_accuracy(forecast, actual):\n mape = np.mean(np.abs(forecast - actual)/np.abs(actual)) # MAPE\n me = np.mean(forecast - actual) # ME\n mae = np.mean(np.abs(forecast - actual)) # MAE\n mpe = np.mean((forecast - actual)/actual) # MPE\n rmse = np.mean((forecast - actual)**2)**.5 # RMSE\n corr = np.corrcoef(forecast, actual)[0,1] # corr\n mins = np.amin(np.hstack([forecast[:,None], \n actual[:,None]]), axis=1)\n maxs = np.amax(np.hstack([forecast[:,None], \n actual[:,None]]), axis=1)\n minmax = 1 - np.mean(mins/maxs) # minmax\n return({'mape':mape, 'me':me, 'mae': mae, \n 'mpe': mpe, 'rmse':rmse, 'corr':corr, 'minmax':minmax})\n\n\n\n\n#VAR\n\ndef VAR_model_pais(vacc_Spain,variables,\n time_series_people, time_series_total,optlag_people,optlag_total,pais,model='VAR',days=7):\n \n var_Spain = vacc_Spain[variables]\n \n # Splitting the dataset into training and test data.\n nobs = 7\n df_train, df_test = var_Spain[0:-nobs], var_Spain[-nobs:]\n \n \n # First Differencing\n var_Spain_differenced = var_Spain.diff().dropna()\n #second differencing\n var_Spain_differenced = var_Spain_differenced.diff().dropna()\n \n ar_forecast_people = time_series_model(var_Spain,time_series_people,\n time_series_total,optlag_people,optlag_total,model,days=7)\n \n idx_20 = ar_forecast_people.index.values\n\n forecast_input = var_Spain.values\n \n #MODELO\n model = VAR(var_Spain_differenced)\n maxlags=12\n x = model.select_order(maxlags) ## hacer una variable de entrada el maxlags\n model_fitted = model.fit(maxlags)\n lag_order = model_fitted.k_ar\n forecast_input = var_Spain_differenced.values[-lag_order:]\n\n fc = model_fitted.forecast(y=forecast_input, steps=7)\n df_forecast = pd.DataFrame(fc, index=idx_20, columns=var_Spain.columns + '_2d')\n \n df_results = invert_transformation(var_Spain, df_forecast, second_diff=True) \n \n df_inverted = df_results.loc[:, ['total_vaccinations_forecast', 'people_vaccinated_forecast',\n 'people_fully_vaccinated_forecast', 'daily_vaccinations_forecast']]\n \n \n \n fig, axes = plt.subplots(nrows=int(len(var_Spain.columns)/2), ncols=2, dpi=150, figsize=(7,7))\n for i, (col,ax) in enumerate(zip(var_Spain.columns, axes.flatten())):\n df_results[col+'_forecast'].plot(legend=True, ax=ax).autoscale(axis='x',tight=True)\n df_test[col][-nobs:].plot(legend=True, ax=ax);\n ax.set_title(col + ' ' + pais +\":Forecast vs Actuals\")\n ax.xaxis.set_ticks_position('none')\n ax.yaxis.set_ticks_position('none')\n ax.spines[\"top\"].set_alpha(0)\n ax.tick_params(labelsize=6)\n\n plt.tight_layout();\n \n\n \n###\n\n#Función de varios países\n\ndef VAR_paises(covid_vaccine_data,paises,variables):\n \"\"\"\n covid_vaccine_data: DataFrame con los datos de todos los países\n paises: lista de países de los que queremos saber su pronóstico, lst\n \"\"\"\n for i in paises:\n \n vacc_pais = preprocesado_pais(covid_vaccine_data,i)\n people_fully_vaccinated = vacc_pais.people_fully_vaccinated\n people_fully_vaccinated_diff =people_fully_vaccinated.diff(2)\n\n total_vaccinations = vacc_pais.total_vaccinations\n total_vaccinations_diff =total_vaccinations.diff(2)\n\n time_series_people = people_fully_vaccinated_diff\n time_series_total = total_vaccinations_diff\n\n #time_series, imputamos los NaN, porque quedan los del lag del principio\n time_series_people = time_series_people.fillna(time_series_people.median())\n time_series_total = time_series_total.fillna(time_series_total.median())\n\n #planteamos el modelo AR: people\n ar_people = tsa.AR(time_series_people)\n #calculamos cual es el lag o el desfase adecuado \n optlag_people = ar_people.select_order(20, ic='aic') \n #planteamos el modelo AR: total, \n #porque vamos a utilizar el index, es decir las fechas, para el modelo VAR\n ar_total = tsa.AR(time_series_total)\n #calculamos cual es el lag o el desfase adecuado \n optlag_total = ar_total.select_order(20, ic='aic') \n\n\n #print(i)\n VAR_model_pais(vacc_pais,variables,time_series_people,\n time_series_total,optlag_people,optlag_total,pais=i,model='VAR',days=7)\n\n\n\n## SECCIÓN DOS: AJUSTE DE CURVA DE TENDENCIA\n\n#funciones previas;\nimport inspect\ndef select_df(df, **kwargs):\n attrs = df.attrs\n for k, vs in kwargs.items():\n if vs is None:\n df = df[df.__getitem__(k).isna()]\n elif not isinstance(vs, list):\n df = df[df.__getitem__(k) == vs]\n else:\n df = df[df.__getitem__(k).isin(vs)]\n df.attrs = attrs\n return df\n\n\ndef _augment_df(df, fn, name=None, register=None):\n name = fn.__name__ if name is None else name\n params = list(inspect.signature(fn).parameters.keys())\n# fixed = {p: df.attrs[\"uniq\"][p] for p in params if p not in df.columns}\n# params = [p for p in params if p not in fixed\n# if len(fixed) > 0:\n# fn = functools.partial(fn, **fixed)\n\n def wrapper(row):\n kwargs = {k: row.get(k) for k in params}\n return fn(**kwargs)\n\n df[name] = df.apply(wrapper, axis=1)\n\n if register:\n if not register in df.attrs:\n df.attrs[register] = []\n if name not in df.attrs[register]:\n df.attrs[register].append(name)\n\n\ndef augment_df(df, *fns, register=None):\n for f in fns:\n _augment_df(df, f, register=register)\n \n\n#####----------------------\n\n#curvas de ajuste\n\nfrom scipy.optimize import curve_fit\n\ndef lineal(x, a, b):\n return a*x +b \n\ndef powerlaw(x, a, b, c):\n return c*x**a + b\n\ndef quadratic(x, a, b, c):\n return a*x**2 + b*x + c\n\ndef exp(x, a, b, c):\n return a**(x-c)+b\n\ndef logistic(x, a, b, c, d):\n return a/(1+np.exp(b*(x-c))) + d\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ENTREGA-FINAL-PMD/funciones_ESTIMACION.py","file_name":"funciones_ESTIMACION.py","file_ext":"py","file_size_in_byte":26313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"479813544","text":"from math import *\r\nimport numpy as np\r\n\r\nfrom Color import *\r\nfrom Point3D import *\r\n\r\ndef MatrixE():\r\n\treturn np.eye(4)\r\n\treturn [[\t1, \t0, \t0, \t0],\r\n\t\t\t[\t0, \t1, \t0, \t0],\r\n\t\t\t[\t0, \t0, \t1, \t0],\r\n\t\t\t[\t0,\t0,\t0,\t1]]\r\n\r\ndef getMatrixShift(dx, dy, dz):\r\n\treturn np.matrix([[\t1, \t0, \t0, \t0],\r\n\t\t\t[\t0, \t1, \t0, \t0],\r\n\t\t\t[\t0, \t0, \t1, \t0],\r\n\t\t\t[\tdx, dy, dz, 1],\r\n\t\t\t])\r\n\r\ndef getMatrixScale(kx, ky, kz, C = None):\r\n\tM = np.matrix([[\tkx, 0, \t0, \t0],\r\n\t\t\t[\t0, \tky, 0, \t0],\r\n\t\t\t[\t0, \t0, \tkz, 0],\r\n\t\t\t[\t0, \t0, \t0, \t1],\r\n\t\t\t])\r\n\tif C == None:\r\n\t\treturn M\r\n\tA = getMatrixShift(C.x, C.y, C.z)\r\n\tB = getMatrixShift(-C.x, -C.y, -C.z)\r\n\treturn B @ M @ A\r\n\r\n\t\r\n\tN = getMatrixShift(C.x, C.y, C.z)\r\n\tQ = getMatrixShift(-C.x, -C.y, -C.z)\r\n\tA = matrixMult(Q, M)\r\n\tB = matrixMult(A, N)\r\n\treturn B\r\n\r\ndef getMatrixRotateX(teta, C = None):\r\n\tM =\tnp.matrix([\t[\t1, 0, \t\t 0, \t\t 0],\r\n\t\t\t[\t0, cos(teta), sin(teta), 0],\r\n\t\t\t[\t0, -sin(teta), cos(teta), 0],\r\n\t\t\t[\t0, 0, \t\t 0, \t\t 1],])\r\n\r\n\tif C == None:\r\n\t\treturn M\r\n\tN = getMatrixShift(C.x, C.y, C.z)\r\n\tQ = getMatrixShift(-C.x, -C.y, -C.z)\r\n\treturn Q @ M @ N\r\n\r\n\tA = matrixMult(Q, M)\r\n\tB = matrixMult(A, N)\r\n\treturn B\r\n\r\ndef getMatrixRotateY(teta, C = None):\r\n\tM = np.matrix([\t[\tcos(teta), \t0, \t-sin(teta), 0],\r\n\t\t\t[\t0, \t\t\t1, \t0, \t\t\t0],\r\n\t\t\t[\tsin(teta), \t0, \tcos(teta), \t0],\r\n\t\t\t[\t0, \t\t\t0, \t0, \t\t\t1],])\r\n\tif C == None:\r\n\t\treturn M\r\n\r\n\tN = getMatrixShift(C.x, C.y, C.z)\r\n\tQ = getMatrixShift(-C.x, -C.y, -C.z)\r\n\treturn Q @ M @ N\r\n\r\n\tA = matrixMult(Q, M)\r\n\tB = matrixMult(A, N)\r\n\treturn B\r\n\r\n\t\r\ndef getMatrixRotateZ(teta, C = None):\r\n\tM = np.matrix([\t[cos(teta), sin(teta), 0, 0],\r\n\t\t\t\t\t\t[-sin(teta), cos(teta), 0, 0],\r\n\t\t\t\t\t\t[0, 0, 1, 0],\r\n\t\t\t\t\t\t[0, 0, 0, 1]])\r\n\tif C == None:\r\n\t\treturn M\r\n\r\n\tN = getMatrixShift(C.x, C.y, C.z)\r\n\tQ = getMatrixShift(-C.x, -C.y, -C.z)\r\n\r\n\treturn Q @ M @ N\r\n\r\n\tA = matrixMult(Q, M)\r\n\tB = matrixMult(A, N)\r\n\treturn B\r\n\r\ndef getMatrixRotate(tetaX = 0, tetaY = 0, tetaZ = 0, C = None):\r\n\tMX = getMatrixRotateX(tetaX, C)\r\n\tMY = getMatrixRotateY(tetaY, C)\r\n\tMZ = getMatrixRotateZ(tetaZ, C)\r\n\treturn MX @ MY @ MZ\r\n\treturn matrixMult(matrixMult(MX, MY), MZ)\r\n\r\ndef getMatrixChange(teta, phi, R):\r\n\tcosteta = cos(teta)\r\n\tcosphi = cos(phi)\r\n\tsinteta = sin(teta)\r\n\tsinphi = sin(phi)\r\n\r\n\treturn np.matrix([[-sinteta, -costeta * sinphi, -costeta * sinphi, 0],\r\n\t\t\t[ costeta, -sinteta * cosphi, -sinteta * cosphi, 0],\r\n\t\t\t[ 0, \t\tcosphi, \t\t -sinphi, \t\t\t 0],\r\n\t\t\t[ 0, \t\t0, \t\t\t\t R, \t\t\t\t 1],\r\n\t\t\t])\r\n\r\ndef getMatrixProek(point):\r\n\treturn\r\n\r\ndef matrixFrom(p):\r\n\treturn [p.x, p.y, p.z, 1]\r\n\r\ndef getSize(mat):\r\n\treturn [len(mat), len(mat[0])]\r\n\r\ndef matrixMult1(A, B):\r\n\tM = len(A)\r\n\tN = len(A[0])\r\n\tQ = len(B[0])\r\n\tres = [[0 for i in range(Q)] for j in range(M)]\r\n\tfor i in range(M):\r\n\t\tfor j in range(Q):\r\n\t\t\tfor k in range(N):\r\n\t\t\t\tres[i][j] += A[i][k] * B[k][j]\r\n\t\t\tres[i][j] = res[i][j]\r\n\treturn res\r\n\r\ndef convertToColor(color):\r\n\tred = color // (1000 * 1000)\r\n\tgreen = (color // 1000) % 1000\r\n\tblue = (color % 1000)\r\n\treturn RGBColor(red, green, blue)\r\n\r\ndef colorToInt(color):\r\n\tred = color.red()\r\n\tgreen = color.green()\r\n\tblue = color.blue()\r\n\treturn red * 1000 * 1000 + (green * 1000) + blue","sub_path":"PRAKTIKA 2020/Code Prak/Static_Func.py","file_name":"Static_Func.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"295729876","text":"import math\n\ndef fft(f_list):\n 'y_list is a list of function values, the number of y_list must fit 2^L.'\n \n N = len(f_list)\n if N==1:\n return [f_list[0] + 0j]\n \n M = int(math.log(N, 2))\n c = [a + 0j for a in f_list]\n z = [math.e ** (-2j * k * math.pi / N) for k in range(N)]\n \n for m in range(M):\n d = [0 for i in range(N)]\n for k in range(2**(M-m-1)):\n for j in range(2**m):\n u = c[2**m * k + j]\n v = z[j*2**(M-m-1)] * c[2**m*k+2**(M-1)+j]\n d[2**(m+1)*k+j] = (u+v)\n d[2**(m+1)*k+j+2**m] = (u-v)\n for j in range(N):\n c[j] = d[j]\n return c\n\n\ndef fft_slow(f_list):\n 'y_list is a list of function values, the number of y_list must fit 2^L.'\n \n N = len(f_list)\n if N==1:\n return [f_list[0] + 0j]\n \n N_half = int(N/2)\n F = [0 for i in f_list]\n \n def fft_k(f_list, k):\n \n N = len(f_list) # N = 2^m\n if N == 1:\n return f_list[0], f_list[0]\n \n w = math.e ** (-2j * math.pi / N)\n \n x_list = f_list[::2] # from the first, each 2\n y_list = f_list[1::2] # from the second, each 2\n \n X_k = fft_k(x_list, k)[0]\n Y_k = fft_k(y_list, k)[0]\n tmp = Y_k * w**k\n return X_k + tmp, X_k - tmp\n \n for k in range(N_half):\n F[k], F[k+N_half] = fft_k(f_list, k)\n \n return F\n\n\ndef dft(y_list):\n N = len(y_list)\n c = [0 for i in y_list]\n w = math.e ** (-2j * math.pi / N)\n \n for k in range(N):\n s = y_list[-1]\n x = w**k\n for a in y_list[-2::-1]:\n s = s * x + a\n c[k] = s\n \n return c","sub_path":"numerical_refs/numr_alg/fft.py","file_name":"fft.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"388362863","text":"\"\"\"\nCode with Eager Execution, Run with Graphs\n\nReference:\n https://medium.com/tensorflow/code-with-eager-execution-run-with-graphs-optimizing-your-code-with-revnet-as-an-example-6162333f9b08\n https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/revnet\n\"\"\"\n\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\n\nfrom models.dataset import train_input_fn\nfrom models.encoders import get_encoder\nfrom run import prepare_inputs\nfrom utils.args import get_args\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\n\ndef apply_gradients(optimizer, grads, model, global_step):\n optimizer.apply_gradients(zip(grads, model.variables), global_step=global_step)\n\n\ndef main():\n tf.enable_eager_execution()\n\n params = get_args()\n pub_med_ids, docs, labels, terms, index2word, word2id = prepare_inputs(params)\n\n docs_train, docs_eval, labels_train, labels_eval = train_test_split(\n docs, labels, train_size=params['p'], random_state=42)\n\n model = get_encoder(params)\n global_step = tf.train.get_or_create_global_step()\n optimizer = tf.train.AdamOptimizer(\n params['lr'], params['beta1'], params['beta2'], params['epsilon']\n )\n\n ds_train = train_input_fn(\n docs_train,\n labels_train,\n params['batch_size'],\n params['max_length'],\n params['num_epochs'],\n embedding_mode=params['word_vecs_path'],\n terms=terms\n )\n\n for step, (x, y) in enumerate(ds_train):\n if step > 10:\n break\n true_multi_hot = tf.reduce_sum(tf.one_hot(y['xent'], params['term_size']), axis=1)\n true_multi_hot = tf.cast(true_multi_hot, tf.int32)\n\n train_one_iter(model, x, true_multi_hot, optimizer, global_step=global_step)\n\n\ndef train_one_iter(model, features, labels, optimizer, global_step=None):\n \"\"\"Train for one iteration.\"\"\"\n\n with tf.GradientTape() as tape:\n doc_vec, logits = model(features, training=True)\n model_losses = model.losses\n model_losses_sum = tf.add_n(model_losses) if len(model_losses) > 0 else 0\n xent_loss = tf.losses.sigmoid_cross_entropy(\n labels, logits, reduction=tf.losses.Reduction.MEAN)\n loss = xent_loss + model_losses_sum\n\n grads = tape.gradient(loss, model.variables)\n apply_gradients(optimizer, grads, model, global_step)\n\n print('Step {}, Loss {:.6f}'.format(global_step.numpy(), loss.numpy()))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/run_eager.py","file_name":"run_eager.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"251220037","text":"# -*- coding: utf-8 -*-\n\nfrom modeltranslation.translator import register, TranslationOptions\nfrom .models import CompanyConf, OurTeam, OurCustomers\n\n\n@register(CompanyConf)\nclass CompanyTranslationOptions(TranslationOptions):\n \n\n fields = (\n 'company_small_intro',\n 'company_full_intro',\n )\n\n@register(OurTeam)\nclass PersonTranslationOptions(TranslationOptions):\n \n\n fields = (\n 'short_info',\n 'job_title',\n \n )\n\n\n@register(OurCustomers)\nclass CustomersTranslationOptions(TranslationOptions):\n \n\n fields = ()\n#translator.register(CompanyConf,CompanyTranslationOptions)","sub_path":"kazdentexpo_asia/main_page/translation.py","file_name":"translation.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"347015011","text":"import sys\nimport signal\nimport phonenumbers\nimport colorama\nfrom colorama import Fore\nfrom phonenumbers import geocoder\nfrom phonenumbers import carrier\nfrom phonenumbers import timezone\n\nprint(\"\\n\\n Code By Keerthivasan \\n\\n\")\ndef prRed(skk): print(\"\\033[91m {}\\033[00m\" .format(skk)) \nprRed(\"PRINT THE PHONENUMBER ALONG WITH THE COUNTRYCODE OTHERWISE IT WILL SHOW ERROR !!!\")\ndef sigint_handler(signal, frame):\n print ('BYEBYE')\n sys.exit(0)\nsignal.signal(signal.SIGINT, sigint_handler)\nx = input(Fore.GREEN + \"Enter the PhoneNumber for Gathering INFO'S: \")\nphonenumber = phonenumbers.parse(x)\nCountry = (geocoder.description_for_number(phonenumber,\"en\"))\nCarrier = (carrier.name_for_number(phonenumber,\"en\"))\nTimezone = (timezone.time_zones_for_number(phonenumber))\nvalid = phonenumbers.is_valid_number(phonenumber)\npossible = phonenumbers.is_possible_number(phonenumber) \n\ndef prGreen(skk): print(\"\\033[92m {}\\033[00m\" .format(skk))\ndef prYellow(skk): print(\"\\033[93m {}\\033[00m\" .format(skk)) \nprGreen(x)\nprYellow(Country)\nprYellow(Carrier)\nprYellow(Timezone)\nprYellow(valid)\nprYellow(possible)\n\n\n\n\n","sub_path":"InfoNumber.py","file_name":"InfoNumber.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583155286","text":"#!/usr/bin/env python\n# coding=utf-8\n\nfrom setuptools import setup, find_packages\n\nimport versioneer\n\n\ntests_require = [ \n 'pytest',\n 'pytest-flake8',\n 'deepdiff',\n 'flake8',\n 'hypothesis',\n 'mock',\n 'pep8-naming',\n]\n\n\nsetup(\n name=\"eodatasets\",\n description=\"Packaging, metadata and provenance for GA EO datasets\",\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n packages=find_packages(exclude=('tests', 'tests.*')),\n package_data={\n '': ['*.json'],\n },\n install_requires=[\n 'click',\n 'python-dateutil',\n 'checksumdir',\n 'ciso8601',\n 'gdal',\n 'numpy',\n 'PyYAML!=5.1',\n 'netCDF4',\n 'rasterio',\n 'shapely',\n 'scipy',\n 'structlog',\n ],\n tests_require=tests_require,\n extras_require={\n 'test': tests_require\n },\n entry_points='''\n [console_scripts]\n eod-package=eodatasets.scripts.genpackage:run\n eod-generate-metadata=eodatasets.scripts.genmetadata:run\n eod-generate-browse=eodatasets.scripts.genbrowse:run\n eod-prepare=eodatasets.scripts.genprepare:run\n eod-recompress-tar=eodatasets.scripts.recompress:main\n ''',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"135023962","text":"import os, sys, inspect\nfrom utils_keras_models import *\nfrom model_configs import *\n\n### Get Data ###\nsys_path = 'C:/Users/doyle/Documents/Coding/WaveNet_shannon/'\nsys.path.insert(1, sys_path)\nbase_path= 'C:/Users/doyle/Documents/Coding/WaveNet_shannon/'\ndata_folder= 'data/'\nsub_folder = 'binance_bitcoin_daily' #specifies which data we are using to predict. Can also try the bitstamp data\n\n\n### Define Model Inputs ###\ninput_size=2 # no of features\n# Define Prediction variable\npred_var= 'high'\n#Define conditioning variables\nall_vars= ['low', 'year', 'month_sine', 'month_cosine', 'eth', 'gold'] #add weekday\nlow=True\nyear=False\neth=False\ngold= False\n#Encoding month with sine and cosine value instead of labels\nmonth_sine=False\nmonth_cosine=False\nyear= False\nassert sum([month_sine, month_cosine])== 0 or 2, \"Month sine and cosine should be used together\"\n#specify which variables need to be scaled\nscaler_vars = ['low','eth', 'gold', 'year']\n\n#add selected variables to dictionary\ncond_vars_dict = dict(((k, eval(k)) for k in all_vars))\n\ncond_vars_selected = {k: v for k, v in cond_vars_dict.items() if v is not False}\nno_cond_vars=(sum(value == True for value in cond_vars_dict.values()))\nassert no_cond_vars == input_size-1, \"select the correct no of variables\"\n\nprint(cond_vars_dict)\n\n#set folder name for storing results\n\nif input_size==1:\n input_names= '{}_unconditional'.format(pred_var)\nelse:\n input_names='__'.join(map(str, cond_vars_selected.keys()))\n input_names= '{}_{}'.format(pred_var, input_names)\n\nresults_folder= 'results_{}/'.format(model_type.lower())\nif os.path.exists(base_path + results_folder)==False:\n os.mkdir(base_path + results_folder)\n\nresults_folder= results_folder + '{}/'.format(sub_folder)\nif os.path.exists(base_path + results_folder)==False:\n os.mkdir(base_path + results_folder)\n\nresults_folder= results_folder + input_names +'/'\nif os.path.exists(base_path + results_folder)==False:\n os.mkdir(base_path + results_folder)\n print('created results folder at', base_path + results_folder)\n\nresults_folder = base_path + results_folder","sub_path":"configs_bit.py","file_name":"configs_bit.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643612424","text":"import json\nimport time\nimport boto3\nimport logging\nfrom random import randint\n\ndynamodb = boto3.resource('dynamodb')\ns3 = boto3.client('s3')\nrek = boto3.client('rekognition')\nsns = boto3.client('sns')\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\ndef lambda_handler(event, context):\n name = event['name']\n phoneNumber = event['phone']\n imageId = event['faceId']\n if imageId != \"\":\n response = rek.index_faces(\n CollectionId='hw2collection',\n Image={\n 'S3Object': {\n 'Bucket': 'hw2-b1-photostore',\n 'Name': imageId\n }\n },\n ExternalImageId = name.replace(\" \", \"\"),\n DetectionAttributes = [\n 'DEFAULT',\n ],\n MaxFaces=1,\n QualityFilter='AUTO'\n )\n faceId = (((response['FaceRecords'])[0])['Face'])['FaceId']\n print('FACE ID: ', faceId)\n print('IMAGE ID: ', imageId)\n insert_visitor(faceId, name, phoneNumber, imageId)\n \n otp = randint(100000, 999999)\n print('OTP: ', otp)\n insert_otp(faceId, otp)\n sms_visitor(phoneNumber, str(otp))\n \n return {\n 'statusCode': 200,\n 'body': json.dumps('OTP has been sent to the visitor.')\n }\n else:\n sms_visitor(phoneNumber, \"\")\n return {\n 'statusCode': 200,\n 'body': json.dumps('Visitor has been denied entry.')\n }\n \n\n# Insert new visitor after approval\ndef insert_visitor(faceId, name, phoneNumber, imageId):\n table = dynamodb.Table('hw2-db2-visitor')\n result = table.put_item(\n Item = {\n 'faceId': faceId,\n 'name': name,\n 'phoneNumber': phoneNumber,\n 'photos': [\n {\n 'objectKey': imageId,\n 'bucket': 'hw2-b1-photostore',\n 'createdTimestamp':time.strftime(\"%Y%m%d-%H%M%S\")\n } \n ]\n\n })\n logger.info(name + ' with ' + faceId + ' inserted to visitors table')\n return result\n\n\n# Insert otp for the newly verified user\ndef insert_otp(faceId, otp):\n table = dynamodb.Table('hw2-db1-passcode')\n result = table.put_item(\n Item = {\n 'otp': str(otp),\n 'faceId':faceId,\n 'current_time':int(time.time()),\n 'expiration_time':int(time.time() + 300)\n\n })\n\n\n# SMS Visitor for acceptance or denial of entry\ndef sms_visitor(phoneNumber, otp):\n url = 'http://cc-hw2-visitorportal.s3-website-us-east-1.amazonaws.com/'\n if otp != \"\":\n message = 'Your Smart Door verification code is ' + otp + '.\\n\\nThe code is valid for 5 minutes.\\n\\nEnter here '+ url\n else:\n message = 'Sorry, the owner has denied your request to enter.' \n sns.publish(\n PhoneNumber = '+1'+str(phoneNumber),\n Message = message\n )\n","sub_path":"lambda_functions/hw2-lf2-insert/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"180265120","text":"from util.request_wrapper import requests\nimport usernamepw\nimport json\n\ndef main():\n auth_header = {'Authorization': 'token {}'.format(usernamepw.ACCESSTOKEN)}\n # resp = requests.get('https://api.github.com/orgs/scientificprogramminguos/repos', headers=auth_header)\n with open('cache_file.json', 'r') as cache_file:\n content = json.load(cache_file)['repos']\n\n hws = ['homework0' + str(i) for i in range(1, 9)]\n homework_repos = {}\n for homework in hws:\n homework_repos[homework] = [i for i in content if i['name'].startswith('2019-' + homework)]\n print()\n\nif __name__ == '__main__':\n main()","sub_path":"week09-Debugging/show_debugger/use_requests_third.py","file_name":"use_requests_third.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"566865271","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport os\nfrom collections import deque\nimport pygame\n\nimport traceback\nimport pandas as pd\n\nfrom environment.environment import Environment\nfrom model.model import UnrealModel\nfrom train.experience import ExperienceFrame\nfrom options import get_options\nimport minos.config.sim_config as sim_config\n\nBLUE = (128, 128, 255)\nRED = (255, 192, 192)\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\n\n# get command line args\nflags = get_options(\"display\")\n\nif flags.segnet >= 1:\n flags.use_pixel_change = False\ntf.logging.set_verbosity(tf.logging.DEBUG)\n\n\nclass MovieWriter(object):\n def __init__(self, file_name, frame_size, fps):\n \"\"\"\n frame_size is (w, h)\n \"\"\"\n self._frame_size = frame_size\n fourcc = cv2.VideoWriter_fourcc('m','p', '4', 'v')\n self.vout = cv2.VideoWriter()\n success = self.vout.open(file_name, fourcc, fps, frame_size, True)\n if not success:\n print(\"Create movie failed: {0}\".format(file_name))\n\n def add_frame(self, frame):\n \"\"\"\n frame shape is (h, w, 3), dtype is np.uint8\n \"\"\"\n self.vout.write(frame)\n\n def close(self):\n self.vout.release() \n self.vout = None\n\n\nclass StateHistory(object):\n def __init__(self):\n self._states = deque(maxlen=3)\n\n def add_state(self, state):\n self._states.append(state)\n\n @property\n def is_full(self):\n return len(self._states) >= 3\n\n @property\n def states(self):\n return list(self._states)\n\n\nclass ValueHistory(object):\n def __init__(self):\n self._values = deque(maxlen=100)\n\n def add_value(self, value):\n self._values.append(value)\n\n @property \n def is_empty(self):\n return len(self._values) == 0\n\n @property\n def values(self):\n return self._values\n\n\nclass Display(object):\n def __init__(self, display_size):\n pygame.init()\n \n self.surface = pygame.display.set_mode(display_size, 0, 24)\n name = 'UNREAL' if flags.segnet == 0 else \"A3C ErfNet\"\n pygame.display.set_caption(name)\n\n env_config = sim_config.get(flags.env_name)\n self.image_shape = [env_config.get('height', 88), env_config.get('width', 88)]\n segnet_param_dict = {'segnet_mode': flags.segnet}\n is_training = tf.placeholder(tf.bool, name=\"training\")\n map_file = env_config.get('objecttypes_file', '../../objectTypes.csv')\n self.label_mapping = pd.read_csv(map_file, sep=',', header=0)\n self.get_col_index()\n\n self.action_size = Environment.get_action_size(flags.env_type, flags.env_name)\n self.objective_size = Environment.get_objective_size(flags.env_type, flags.env_name)\n self.global_network = UnrealModel(self.action_size,\n self.objective_size,\n -1,\n flags.use_lstm,\n flags.use_pixel_change,\n flags.use_value_replay,\n flags.use_reward_prediction,\n 0.0,\n 0.0,\n \"/gpu:0\",\n segnet_param_dict=segnet_param_dict,\n image_shape=self.image_shape,\n is_training=is_training,\n n_classes=flags.n_classes,\n segnet_lambda=flags.segnet_lambda,\n dropout=flags.dropout,\n for_display=True)\n self.environment = Environment.create_environment(flags.env_type, flags.env_name, flags.termination_time_sec,\n env_args={'episode_schedule': flags.split,\n 'log_action_trace': flags.log_action_trace,\n 'max_states_per_scene': flags.episodes_per_scene,\n 'episodes_per_scene_test': flags.episodes_per_scene})\n self.font = pygame.font.SysFont(None, 20)\n self.value_history = ValueHistory()\n self.state_history = StateHistory()\n self.episode_reward = 0\n\n def update(self, sess):\n self.surface.fill(BLACK)\n self.process(sess)\n pygame.display.update()\n\n def choose_action(self, pi_values):\n return np.random.choice(range(len(pi_values)), p=pi_values)\n\n def scale_image(self, image, scale):\n return image.repeat(scale, axis=0).repeat(scale, axis=1)\n\n def draw_text(self, str, left, top, color=WHITE):\n text = self.font.render(str, True, color, BLACK)\n text_rect = text.get_rect()\n text_rect.left = left \n text_rect.top = top\n self.surface.blit(text, text_rect) \n\n def draw_center_text(self, str, center_x, top):\n text = self.font.render(str, True, WHITE, BLACK)\n text_rect = text.get_rect()\n text_rect.centerx = center_x\n text_rect.top = top\n self.surface.blit(text, text_rect)\n\n def show_pixel_change(self, pixel_change, left, top, rate, label):\n \"\"\"\n Show pixel change\n \"\"\"\n if \"PC\" in label:\n pixel_change_ = np.clip(pixel_change * 255.0 * rate, 0.0, 255.0)\n data = pixel_change_.astype(np.uint8)\n data = np.stack([data for _ in range(3)], axis=2)\n data = self.scale_image(data, 4)\n #print(\"PC shape\", data.shape)\n image = pygame.image.frombuffer(data, (20*4, 20*4), 'RGB')\n else:\n pixel_change = self.scale_image(pixel_change, 2)\n #print(\"Preds shape\", pixel_change.shape)\n image = pygame.image.frombuffer(pixel_change.astype(np.uint8), (self.image_shape[0]*2, self.image_shape[1]*2), 'RGB')\n self.surface.blit(image, (2*left+16+8, 2*top+16+8))\n self.draw_center_text(label, 2*left + 200/2, 2*top + 200)\n \n\n def show_policy(self, pi):\n \"\"\"\n Show action probability.\n \"\"\"\n start_x = 10\n\n y = 150\n \n for i in range(len(pi)):\n width = pi[i] * 100\n pygame.draw.rect(self.surface, WHITE, (2*start_x, 2*y, 2*width, 2*10))\n y += 20\n self.draw_center_text(\"PI\", 2*50, 2*y)\n \n def show_image(self, state):\n \"\"\"\n Show input image\n \"\"\"\n state_ = state * 255.0\n data = state_.astype(np.uint8)\n data = self.scale_image(data, 2)\n image = pygame.image.frombuffer(data, (self.image_shape[0]*2, self.image_shape[1]*2), 'RGB')\n self.surface.blit(image, (8*2, 8*2))\n self.draw_center_text(\"input\", 2*50, 2*100)\n\n def show_value(self):\n if self.value_history.is_empty:\n return\n\n min_v = float(\"inf\")\n max_v = float(\"-inf\")\n\n values = self.value_history.values\n\n for v in values:\n min_v = min(min_v, v)\n max_v = max(max_v, v)\n\n top = 150*2\n left = 150*2\n width = 100*2\n height = 100*2\n bottom = top + width\n right = left + height\n\n d = max_v - min_v\n last_r = 0.0\n for i,v in enumerate(values):\n r = (v - min_v) / d\n if i > 0:\n x0 = i-1 + left\n x1 = i + left\n y0 = bottom - last_r * height\n y1 = bottom - r * height\n pygame.draw.line(self.surface, BLUE, (x0, y0), (x1, y1), 1)\n last_r = r\n\n pygame.draw.line(self.surface, WHITE, (left, top), (left, bottom), 1)\n pygame.draw.line(self.surface, WHITE, (right, top), (right, bottom), 1)\n pygame.draw.line(self.surface, WHITE, (left, top), (right, top), 1)\n pygame.draw.line(self.surface, WHITE, (left, bottom), (right, bottom), 1)\n\n self.draw_center_text(\"V\", left + width/2, bottom+10)\n\n def show_reward_prediction(self, rp_c, reward):\n start_x = 310\n reward_index = 0\n if reward == 0:\n reward_index = 0\n elif reward > 0:\n reward_index = 1\n elif reward < 0:\n reward_index = 2\n\n y = 150\n\n labels = [\"0\", \"+\", \"-\"]\n \n for i in range(len(rp_c)):\n width = rp_c[i] * 100\n\n if i == reward_index:\n color = RED\n else:\n color = WHITE\n pygame.draw.rect(self.surface, color, (2*start_x+2*15, 2*y, 2*width, 2*10))\n self.draw_text(labels[i], 2*start_x, 2*y-2*1, color)\n y += 20\n \n self.draw_center_text(\"RP\", 2*start_x + 2*100/2, y)\n\n def show_reward(self):\n self.draw_text(\"REWARD: {:.4}\".format(float(self.episode_reward)), 300, 2*10)\n\n def process(self, sess):\n sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])\n #sess.run(tf.initialize_all_variables())\n\n last_action = self.environment.last_action\n last_reward = self.environment.last_reward\n last_action_reward = ExperienceFrame.concat_action_and_reward(last_action, self.action_size,\n last_reward, self.environment.last_state)\n preds=None\n mode = \"segnet\" if flags.segnet >= 2 else \"\"\n mode=\"\" #don't want preds\n if not flags.use_pixel_change:\n pi_values, v_value, preds = self.global_network.run_base_policy_and_value(sess,\n self.environment.last_state,\n last_action_reward, mode=mode)\n else:\n pi_values, v_value, pc_q = self.global_network.run_base_policy_value_pc_q(sess,\n self.environment.last_state,\n last_action_reward)\n\n #print(preds)\n self.value_history.add_value(v_value)\n\n prev_state = self.environment.last_state\n \n action = self.choose_action(pi_values)\n state, reward, terminal, pixel_change = self.environment.process(action)\n self.episode_reward += reward\n \n if terminal:\n self.environment.reset()\n self.episode_reward = 0\n \n self.show_image(state['image'])\n self.show_policy(pi_values)\n self.show_value()\n self.show_reward()\n \n if not flags.use_pixel_change:\n if preds is not None:\n self.show_pixel_change(self.label_to_rgb(preds), 100, 0, 3.0, \"Preds\")\n self.show_pixel_change(self.label_to_rgb(state['objectType']), 200, 0, 0.4, \"Segm Mask\")\n else:\n self.show_pixel_change(pixel_change, 100, 0, 3.0, \"PC\")\n self.show_pixel_change(pc_q[:,:,action], 200, 0, 0.4, \"PC Q\")\n \n if flags.use_reward_prediction:\n if self.state_history.is_full:\n rp_c = self.global_network.run_rp_c(sess, self.state_history.states)\n self.show_reward_prediction(rp_c, reward)\n \n self.state_history.add_state(state)\n\n def get_frame(self):\n data = self.surface.get_buffer().raw\n return data\n\n def get_col_index(self):\n ind_col = self.label_mapping[[\"index\", \"color\"]].values\n index = ind_col[:, 0].astype(np.int)\n self.index, ind = np.unique(index, return_index=True)\n self.col = np.array([[int(x) for x in col.split('_')] for col in ind_col[ind, 1]])\n\n def label_to_rgb(self, labels):\n #print(self.col)\n rgb_img = self.col[np.where(self.index[np.newaxis, :] == labels.ravel()[:, np.newaxis])[1]].reshape(labels.shape + (3,))\n return rgb_img\n\n\ndef main(args):\n # prepare session\n config = tf.ConfigProto(allow_soft_placement=True)\n # log_device_placement = False,\n config.gpu_options.allow_growth = True\n\n sess = tf.Session(config=config)\n try:\n display_size = (440, 300)\n if flags.segnet >= 2:\n display_size = (660, 600)\n display = Display(display_size)\n saver = tf.train.Saver()\n\n if flags.checkpoint:\n saver.restore(sess, os.path.join(flags.checkpoint_dir, flags.checkpoint))\n print(\"Restored from checkpoint!\")\n else:\n checkpoint = tf.train.get_checkpoint_state(flags.checkpoint_dir)\n if checkpoint and checkpoint.model_checkpoint_path:\n if flags.segnet == 0:\n from tensorflow.python import pywrap_tensorflow\n reader = pywrap_tensorflow.NewCheckpointReader(checkpoint.model_checkpoint_path)\n big_var_to_shape_map = reader.get_variable_to_shape_map()\n s = []\n for key in big_var_to_shape_map:\n s += [key]\n # print(\"tensor_name: \", key)\n glob_var_names = [v.name for v in tf.global_variables()]\n endings = [r.split('/')[-1][:-2] for r in glob_var_names]\n old_ckpt_to_new_ckpt = {[k for k in s if endings[i] in k][0]: v for i, v in enumerate(tf.global_variables())}\n saver1 = tf.train.Saver(var_list=old_ckpt_to_new_ckpt)\n saver1.restore(sess, checkpoint.model_checkpoint_path)\n else:\n saver.restore(sess, checkpoint.model_checkpoint_path)\n print(\"checkpoint loaded:\", checkpoint.model_checkpoint_path)\n else:\n print(\"Could not find old checkpoint\")\n # checkpoint_file = tf.train.latest_checkpoint(flags.checkpoint_dir)\n # print(checkpoint_file)\n # if checkpoint_file is None:\n # pass\n # else:\n # saver.restore(sess, checkpoint_file)\n\n clock = pygame.time.Clock()\n\n running = True\n FPS = 15\n\n if flags.recording:\n name = \"out_{}.mov\".format(flags.checkpoint_dir)\n i = 0\n while os.path.exists(name):\n name = \"{}_{}\".format(name, i)\n writer = MovieWriter(name, display_size, FPS)\n\n if flags.frame_saving:\n frame_count = 0\n if not os.path.exists(flags.frame_save_dir):\n os.mkdir(flags.frame_save_dir)\n\n while running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n display.update(sess)\n clock.tick(FPS)\n\n if flags.recording or flags.frame_saving:\n frame_str = display.get_frame()\n d = np.fromstring(frame_str, dtype=np.uint8)\n d = d.reshape((display_size[1], display_size[0], 3))\n if flags.recording:\n writer.add_frame(d)\n else:\n frame_file_path = \"{0}/{1:06d}.png\".format(flags.frame_save_dir, frame_count)\n cv2.imwrite(frame_file_path, d)\n frame_count += 1\n\n if flags.recording:\n writer.close()\n except Exception as e:\n print(traceback.format_exc())\n finally:\n display.environment.stop()\n\n \nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":14320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"133762890","text":"from turtle import Screen,Turtle\r\nfrom ball import Ball\r\nfrom paddle import Paddle\r\nimport time\r\nfrom scoreboard import Scoreboard\r\n\r\nscreen = Screen()\r\nscreen.bgcolor(\"black\")\r\nscreen.setup(width = 800,height = 600)\r\nscreen.title(\"Pong\")\r\nscreen.tracer(0)\r\nscoreboard = Scoreboard()\r\n\r\nr_paddle = Paddle((350,0))\r\nl_paddle = Paddle((-350,0))\r\nscreen.listen()\r\nscreen.onkey(r_paddle.go_up,\"Up\")\r\nscreen.onkey(r_paddle.go_down,\"Down\")\r\n\r\nscreen.onkey(l_paddle.go_up,\"w\")\r\nscreen.onkey(l_paddle.go_down,\"s\")\r\n\r\nball = Ball()\r\n\r\ngame_on = True\r\n\r\nsleeper = 0.1\r\n\r\nwhile game_on:\r\n\r\n time.sleep(sleeper)\r\n screen.update() # had to be called continuously as screen.tracer(0) has been used\r\n ball.change_position()\r\n if ball.ycor()>290 or ball.ycor()<-290:\r\n ball.bounce_y()\r\n if ball.distance(r_paddle)<22 or (ball.xcor()>=338 and ball.distance(r_paddle)<50):\r\n sleeper-= 0.005\r\n ball.bounce_x()\r\n if ball.distance(l_paddle)<22 or (ball.xcor()<=-338 and ball.distance(l_paddle)<50):\r\n sleeper-= 0.005\r\n ball.bounce_x()\r\n if ball.xcor()>365:\r\n scoreboard.l_point()\r\n ball.reset()\r\n sleeper = 0.1\r\n scoreboard.l_point()\r\n elif ball.xcor()<-365:\r\n scoreboard.r_point()\r\n sleeper = 0.1\r\n ball.reset()\r\n \r\n\r\nscreen.exitonclick()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"536276375","text":"# -*- coding: utf-8 -*-\n# @Author : Yanli Zhang\n# @Contact : ylzhang96@163.com\n# @Github : https://github.com/ylzhang96\n# @Project : leetcode-learning\n# @FileName : easy3.py\n# @Time : 2020.02.26\n\nfrom typing import List\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n # Q21 合并两个有序链表 d200227\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n ans = ListNode(0) # 头结点\n l = ans\n while l1 and l2:\n if l1.val <= l2.val:\n l.next = ListNode(l1.val)\n l1 = l1.next\n l = l.next\n else:\n l.next = ListNode(l2.val)\n l2 = l2.next\n l = l.next\n if l1:\n l.next = l1\n if l2:\n l.next = l2\n return ans.next\n\n # Q88 合并两个有序数组 直接合并后排序 O((n+m)lg(n+m)) 从后往前排序 O(n+m) d200227\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n i = m - 1\n j = n - 1\n k = n + m - 1\n while i >= 0 and j >= 0:\n if nums1[i] <= nums2[j]:\n nums1[k] = nums2[j]\n j -= 1\n k -= 1\n else:\n nums1[k] = nums1[i]\n i -= 1\n k -= 1\n # [3,0] 1 [2] 1 可能i先<0 要把nums2没比完的部分移上来 但j<0时不需要动\n nums1[: j + 1] = nums2[: j + 1]\n\n # Q977 有序数组的平方 平方后排序O(nlgn) 240 ms 合并两有序数组 O(n) 268 ms d200227\n def sortedSquares(self, A: List[int]) -> List[int]:\n # A列表分成两段 A1 [-7 -3] B1 [2, 3, 11]\n l = len(A)\n j = 0\n while j < l and A[j] < 0:\n j += 1 # 非负数最小\n i = j - 1 # 负数最大\n ans = []\n while i >= 0 and j < l:\n if A[i] * A[i] <= A[j] * A[j]:\n ans.append(A[i] * A[i])\n i -= 1\n else:\n ans.append(A[j] * A[j])\n j += 1\n if i >= 0:\n ans = ans + [A[k] * A[k] for k in range(i, -1, -1)]\n else:\n ans = ans + [A[k] * A[k] for k in range(j, l, 1)]\n return ans\n\n\n\n\nif __name__ == \"__main__\":\n s = Solution()\n # a1 = ListNode(1)\n # a2 = ListNode(2)\n # a3 = ListNode(4)\n # b1 = ListNode(1)\n # b2 = ListNode(3)\n # b3 = ListNode(4)\n # a1.next = a2\n # a2.next = a3\n # b1.next = b2\n # b2.next = b3\n # ans = s.mergeTwoLists(a1, b1)\n # while ans:\n # print(ans.val, end=\" \")\n # ans = ans.next\n\n # Q88\n # nums1 = [3,0]\n # nums2 = [2]\n # s.merge(nums1, 1, nums2, 1)\n # print(nums1)\n\n print(s.sortedSquares([-7, -3, 2, 3, 11]))\n","sub_path":"easy/easy3.py","file_name":"easy3.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"508812530","text":"# モジュールのインポート\nimport pylab\n\nfile = open(\"001.001.000.sdt\",\"r\")\n\n# あらかじめ1行目を読み込みをしておく\nfile.readline()\n\n# リストを中身空で宣言\nx = []\ny = []\n\n# y軸を-300 ~ -50に限定する\npylab.ylim((-150,-50))\n\n# ファイルを1行ずつ読み込む\nfor line in file:\n\n\t# 空白ずつ区切ってリストに入れる\n\titemList = line.split()\n\n\t# -1が出たらそこまでのx,yでプロットするする\n\n\n\tif itemList[0]==\"-1\" or itemList[2]==\"0\":\n\t\tpylab.plot(x,y,\"r\")\t\n\t\t\n\t\t# リストを中身空で宣言\n\t\tx = []\n\t\ty = []\n\n\n\t# x,yにそれぞれ対応するデータを入れる\n\telse:\n\t\tx = x + [int(itemList[0])]\n\t\ty = y + [-int(itemList[1])]\n\n# 最後のストロークは記述されないのでここでプロット\npylab.plot(x,y,\"r\")\npylab.show()\n\nfile.close()\n\n","sub_path":"SignatureSampleData/SDV_2.py","file_name":"SDV_2.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"30515972","text":"\nimport matplotlib.pyplot as plt\nimport torch\nimport numpy as np\nimport pygame\nimport random\nfrom collections import namedtuple\n\ntransition = namedtuple('transition', ['prev_state', 'prev_action', 'reward', 'state', 'action', 'is_terminal', 'time_step', 'error'])\n# transition = namedtuple('transition', ['prev_state', 'prev_action', 'reward', 'state', 'action'])\n\n\ndef draw_plot(x, y, xlim=None, ylim=None, xlabel=None, ylabel=None, title=None, show=False, label='', std_error=None, sub_plot_num=None, color=None):\n if ylim is not None:\n plt.ylim(ylim[0], ylim[1])\n if xlim is not None:\n plt.xlim(xlim[0], xlim[1])\n\n if xlabel is not None:\n # naming the x axis\n plt.xlabel(xlabel)\n if ylabel is not None:\n # naming the y axis\n plt.ylabel(ylabel)\n if title is not None:\n # giving a title to my graph\n plt.title(title)\n\n # plotting the points\n if std_error is None:\n plt.plot(x, y, label=label)\n else:\n if color is not None:\n plt.errorbar(x, y, yerr=std_error, label=label, color=color)\n else:\n plt.errorbar(x, y, yerr=std_error, label=label)\n\n plt.legend()\n if show:\n # # function to show the plot\n plt.show()\n\ndef draw_grid(grid_size, window_size, state_action_values=None, all_actions=None, obstacles_pos=[]):\n ground_color = [255, 255, 255]\n # agent_color = [i * 255 for i in self._agent_color]\n # ground_color = [i * 255 for i in self._ground_color]\n # obstacle_color = [i * 255 for i in self._obstacle_color]\n text_color = (240,240,10)\n info_color = (200, 50, 50)\n # This sets the WIDTH and HEIGHT of each grid location\n WIDTH = int(window_size[0] / grid_size[1])\n HEIGHT = int(window_size[1] / grid_size[0])\n\n # This sets the margin between each cell\n MARGIN = 1\n\n\n # Initialize pygame\n pygame.init()\n\n # Set the HEIGHT and WIDTH of the screen\n WINDOW_SIZE = [window_size[0], window_size[1]]\n screen = pygame.display.set_mode(WINDOW_SIZE)\n\n # Set title of screen\n pygame.display.set_caption(\"Grid\")\n\n # Used to manage how fast the screen updates\n clock = pygame.time.Clock()\n\n font = pygame.font.Font('freesansbold.ttf', 20)\n info_font = pygame.font.Font('freesansbold.ttf', int(60 / ((grid_size[0]+grid_size[1])/2)) )\n\n\n done = False\n # -------- Main Program Loop -----------\n while not done:\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True\n\n # Set the screen background\n screen.fill((100,100,100))\n\n\n # Draw the grid\n for x in range(grid_size[0]):\n for y in range(grid_size[1]):\n if (x,y) in obstacles_pos:\n continue\n color = ground_color\n # if list(grid[x][y]) == self._agent_color:\n # color = agent_color\n # elif list(grid[x][y]) == self._obstacle_color:\n # color = obstacle_color\n pygame.draw.rect(screen,\n color,\n [(MARGIN + WIDTH) * y + MARGIN,\n (MARGIN + HEIGHT) * x + MARGIN,\n WIDTH,\n HEIGHT])\n if state_action_values is not None:\n # showing values only for 4 basic actions\n up_left_corner = [(MARGIN + WIDTH) * y + MARGIN,\n (MARGIN + HEIGHT) * x + MARGIN]\n up_right_corner = [(MARGIN + WIDTH) * y + MARGIN + WIDTH,\n (MARGIN + HEIGHT) * x + MARGIN]\n down_left_corner = [(MARGIN + WIDTH) * y + MARGIN,\n (MARGIN + HEIGHT) * x + MARGIN + HEIGHT]\n down_right_corner = [(MARGIN + WIDTH) * y + MARGIN + WIDTH,\n (MARGIN + HEIGHT) * x + MARGIN + HEIGHT]\n center = [(up_right_corner[0] + up_left_corner[0]) // 2,\n (up_right_corner[1] + down_right_corner[1]) // 2]\n\n pygame.draw.polygon(screen, info_color,\n [up_left_corner, up_right_corner, center],\n 1)\n pygame.draw.polygon(screen, info_color,\n [up_right_corner, down_right_corner, center],\n 1)\n pygame.draw.polygon(screen, info_color,\n [down_right_corner, down_left_corner, center],\n 1)\n pygame.draw.polygon(screen, info_color,\n [down_left_corner, up_left_corner, center],\n 1)\n for a in all_actions:\n if tuple(a) == (0,1):\n right = info_font.render(str(state_action_values[(x,y), tuple(a)]), True, info_color)\n elif tuple(a) == (1,0):\n down = info_font.render(str(state_action_values[(x,y), tuple(a)]), True, info_color)\n elif tuple(a) == (0,-1):\n left = info_font.render(str(state_action_values[(x,y), tuple(a)]), True, info_color)\n elif tuple(a) == (-1,0):\n up = info_font.render(str(state_action_values[(x,y), tuple(a)]), True, info_color)\n else:\n raise ValueError(\"action cannot be rendered\")\n\n margin = 1\n screen.blit(left,\n (up_left_corner[0] + margin,\n center[1])) #left\n screen.blit(right,\n (up_right_corner[0] - right.get_rect().width,\n center[1])) # right\n screen.blit(up,\n (center[0] - up.get_rect().width // 2,\n up_right_corner[1] + margin)) # up\n screen.blit(down,\n (center[0] - down.get_rect().width // 2,\n down_left_corner[1] - down.get_rect().height - margin)) # down\n\n # Limit to 60 frames per second\n clock.tick(60)\n\n # Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n\ndef reshape_for_grid(img):\n # get a tenser as input with shape B, W, H, C and return a tensor with shape B, C, W, H\n grid_img = torch.cat([img[:, :, :, 0], img[:, :, :, 1], img[:, :, :, 2]]).unsqueeze(0)\n return grid_img\n\ndef calculate_true_values(env, gamma):\n states = env.getAllStates()\n actions = env.getAllActions()\n values = {}\n alpha = 0.1\n max_iter = 10000\n td_differ = 0.1\n for s in states:\n for a in actions:\n pos = env.stateToPos(s)\n values[pos, tuple(a)] = 0\n tderror_sum = 1000\n i = 0\n while tderror_sum > td_differ and i < max_iter:\n tderror_sum = 0\n i += 1\n random.shuffle(states)\n for s in states:\n s = env.stateToPos(s)\n for a in actions:\n next_state, is_terminal, reward = env.fullTransitionFunction(s, a, state_type='coord')\n if not is_terminal:\n next_state_value = 0\n for aa in actions:\n next_state_value += values[next_state, tuple(aa)]\n next_state_value /= len(actions)\n tderror = reward + gamma * next_state_value - values[s, tuple(a)]\n else:\n tderror = reward - values[s, tuple(a)]\n tderror_sum += abs(tderror)\n values[s, tuple(a)] += alpha * tderror\n\n return values\n","sub_path":"Colab/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"50672111","text":"import datetime\nfrom collections import deque\nfrom .config import MULTIPLIER\n\n\nclass RSI:\n def __init__(self, duration=14, candle_duration='minute'):\n self.source = 'open' # can be open, high, low or close\n self.rsi = {\n 'prev_price': None,\n 'gain': deque(),\n 'loss': deque(),\n 'len': duration,\n 'rsi': None\n }\n\n def update(self, price):\n if self.rsi['prev_price'] is not None:\n # calculate loss and gain w.r.t rsi['price']\n gain = 0\n loss = 0\n if self.rsi['prev_price'] < price:\n gain = price - self.rsi['prev_price']\n else:\n loss = self.rsi['prev_price'] - price\n self.rsi['gain'].appendleft(gain)\n self.rsi['loss'].appendleft(loss)\n if len(self.rsi['gain']) == self.rsi['len']:\n loss_sum = sum(self.rsi['loss'])\n gain_sum = sum(self.rsi['gain'])\n if loss_sum == 0:\n self.rsi['rsi'] = 100.0\n else:\n self.rsi['rsi'] = 100.0 - (100.0/(1+(float(gain_sum)/loss_sum)))\n self.rsi['gain'].pop()\n self.rsi['loss'].pop()\n self.rsi['prev_price'] = price\n","sub_path":"websockets/candle_indicators/rsi.py","file_name":"rsi.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"57387861","text":"from django.db import models\nfrom django.contrib.postgres.fields import JSONField, ArrayField\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom utils.models import BaseAbstractModel\nfrom utils.managers import CustomQuerySet, ChannelsQuery\nfrom authentication.models import User\nfrom liveTv.models import Channels\n\n\nclass Archives(BaseAbstractModel):\n \"\"\"This class defines the Categories model\"\"\"\n\n VIDEO_TYPE = (\n ('VD', 'video_on_demand'),\n ('AR', 'archive')\n )\n serial_no = models.IntegerField(default=0)\n name = models.CharField(max_length=255)\n channel = models.ForeignKey(Channels, on_delete=models.CASCADE)\n video_url = models.URLField(max_length=255)\n logo_image = models.FileField(blank=True, null=True)\n num_of_days = models.IntegerField(default=1)\n # video_type = models.CharField(\n # verbose_name='video type', max_length=20, choices=VIDEO_TYPE\n # )\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\n\n objects = models.Manager()\n active_objects = ChannelsQuery.as_manager()\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n \"\"\"Saves all the changes of the Archive model\"\"\"\n super().save(*args, **kwargs)\n\n class Meta:\n verbose_name_plural = \"Archieves\"\n","sub_path":"archives/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"280947950","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\nimport numpy as np\nfrom renom.core import BinOp, Node, get_gpu\nfrom renom.cuda import cuda as cu\n\n\nclass mean_squared_error(BinOp):\n\n @classmethod\n def _oper_cpu(cls, lhs, rhs):\n assert rhs.ndim > 1, \"Input arrays must have no less than 2 dimension.\"\n N = len(lhs)\n return np.sum((lhs - rhs) ** 2) / (N * 2)\n\n @classmethod\n def _oper_gpu(cls, lhs, rhs):\n assert rhs.ndim > 1, \"Input arrays must have no less than 2 dimension.\"\n N = len(lhs)\n return cu.cusum(get_gpu((get_gpu(lhs) - get_gpu(rhs)) ** 2)) / (N * 2)\n\n def _backward_cpu(self, context, dy):\n sub = self.attrs._lhs - self.attrs._rhs\n if isinstance(self.attrs._lhs, Node):\n N = len(self.attrs._lhs)\n self.attrs._lhs._update_diff(context, sub * dy / N)\n\n def _backward_gpu(self, context, dy):\n if isinstance(self.attrs._lhs, Node):\n N = len(self.attrs._lhs)\n sub = get_gpu(self.attrs._lhs) - get_gpu(self.attrs._rhs)\n self.attrs._lhs._update_diff(context, sub * get_gpu(dy) / N)\n\n\nclass MeanSquaredError(object):\n \"\"\"This function evaluates the loss between the target ``y``\n and the output ``x`` using mean squared error.\n\n .. math::\n E(x) = \\\\frac{1}{2N}\\sum_{n}^{N}\\sum_{k}^{K}(x_{nk}-y_{nk})^2\n\n :math:`N` is batch size.\n\n Args:\n x (ndarray,Node): Input array.\n y (ndarray,Node): Target array.\n\n Raises:\n AssertionError: An assertion error will be raised if the given tensor dimension is less than 2.\n\n Example:\n >>> import renom as rm\n >>> import numpy as np\n >>>\n >>> x = np.array([[1, 1]])\n >>> y = np.array([[-1, -1]])\n >>> print(x.shape, y.shape)\n ((1, 2), (1, 2))\n >>> loss = rm.mean_squared_error(x, y)\n >>> print(loss)\n mean_squared_error(4.0)\n\n \"\"\"\n\n def __call__(self, x, y):\n return mean_squared_error(x, y)\n","sub_path":"renom/layers/loss/mean_squared_error.py","file_name":"mean_squared_error.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"585851411","text":"# pandas and numpy restructures data\nimport pandas as pd\nimport numpy as np\nimport matplotlib as plt\nimport tensorflow as tf\n\n# variablizing data files\nGOLD_TRAIN_DATA = 'CSV_Files/Gold Data Last Year.csv'\nGOLD_TEST_DATA = 'CSV_Files/Gold Data Last Month.csv'\n\n# differentiation data usage\ncurrent_train_data = GOLD_TRAIN_DATA\ncurrent_test_data = GOLD_TEST_DATA\n\n# number of data points to retrieve\nNUM_TRAIN_DATA_POINTS = 266\nNUM_TEST_DATA_POINTS = 22\n\n\n# function to load data, correct structure, and make it an array from csv\ndef load_stock_data(stock_name, num_data_points):\n data = pd.read_csv(stock_name,\n skiprows=0,\n nrows=num_data_points,\n usecols=['Price', 'Open', 'Vol.'])\n\n # price at end of each day\n final_prices = data['Price'].astype(str).str.replace(',', '').astype(np.float)\n # price at beginning of each day\n opening_prices = data['Open'].astype(str).str.replace(',', '').astype(np.float)\n # volumes traded through that day\n volumes = data['Vol.'].str.strip('MK').astype(np.float)\n return final_prices, opening_prices, volumes\n\n\ndef calculate_price_differences(final_prices, opening_prices):\n price_differences = []\n for d_i in range(len(final_prices) - 1):\n price_difference = opening_prices[d_i + 1] - final_prices[d_i]\n price_differences.append(price_difference)\n return price_differences\n\n\n# returning correct data structure\nfinals, openings, volumes = load_stock_data(current_test_data, NUM_TEST_DATA_POINTS)\ndifferences = calculate_price_differences(finals, openings)\nprint(differences)\n","sub_path":"Stock_Prediction_model.py","file_name":"Stock_Prediction_model.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"480676129","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nimport torch\nimport torch.nn as nn\nfrom pymic.loss.cls.util import get_soft_label\n\nclass L1Loss(nn.Module):\n \"\"\"\n L1 (MAE) loss for classification\n \"\"\"\n def __init__(self, params):\n super(L1Loss, self).__init__()\n self.l1_loss = nn.L1Loss()\n \n def forward(self, loss_input_dict):\n predict = loss_input_dict['prediction']\n labels = loss_input_dict['ground_truth'][:, None] # reshape to N, 1\n softmax = nn.Softmax(dim = 1)\n predict = softmax(predict)\n num_class = list(predict.size())[1]\n data_type = 'float' if(predict.dtype is torch.float32) else 'double'\n soft_y = get_soft_label(labels, num_class, data_type)\n loss = self.l1_loss(predict, soft_y)\n return loss\n\nclass RectifiedLoss(nn.Module):\n def __init__(self, params):\n super(RectifiedLoss, self).__init__()\n # self.l1_loss = nn.L1Loss()\n \n def forward(self, loss_input_dict):\n predict = loss_input_dict['prediction']\n labels = loss_input_dict['ground_truth'][:, None] # reshape to N, 1\n \n # softmax = nn.Softmax(dim = 1)\n # predict = softmax(predict)\n num_class = list(predict.size())[1]\n data_type = 'float' if(predict.dtype is torch.float32) else 'double'\n soft_y = get_soft_label(labels, num_class, data_type)\n g = 2* soft_y - 1\n loss = torch.exp((g*1.5- predict) * g)\n mask = predict < g \n if (data_type == 'float'):\n mask = mask.float() \n else:\n mask = mask.double() \n w = (mask - 0.5) * g + 0.5 \n loss = w * loss + 0.1*(g - predict) * (g - predict)\n loss = loss.mean()\n # loss = self.l1_loss(predict, soft_y)\n return loss","sub_path":"pymic/loss/cls/l1.py","file_name":"l1.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"389664072","text":"import numpy as np\nimport glob\nimport os\nimport pandas as pd\npath='/fs/project/PAS1263/data/ILSVRC/matconvnet_data/test.csv'\ndf1=pd.read_csv(path)\ndf2=df1['filename'].values.tolist()\ndf3=df1.set_index(\"filename\")\ndflist=set(df2)\nalist=[]\nfor file_name in list(dflist):\n temp=df3.loc[file_name,]\n data=temp.as_matrix()\n if data.ndim!=1:\n result=0;\n for i in range(0,data.shape[0]):\n if data[i,2]=='n03001627' or data[i,2]=='n04379243':\n result=1;\n break;\n if result==1:\n alist.append(file_name);\n else:\n result=0;\n if data[2]=='n03001627' or data[2]=='n04379243':\n result=1;\n if result==1:\n alist.append(file_name);\n\n\nnp.save('../prior/table_chair_list',alist)\n","sub_path":"faster-rcnn-base-model/code/chair_table_list.py","file_name":"chair_table_list.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90809088","text":"fin = file(\"B-large.in\", \"rU\")\r\nfout = file(\"B-large.out\", \"w\")\r\n\r\nnruns = int(fin.readline().strip())\r\nfor i in xrange(nruns):\r\n line = fin.readline().strip()\r\n\r\n if line[0] == \"-\":\r\n flipstate = False #false for sad, true for happy\r\n else:\r\n flipstate = True\r\n\r\n #Go through and compare\r\n flips = 0\r\n\r\n for j in xrange(0, len(line)-1):\r\n #compare prev to curr\r\n if line[j] != line[j+1]:\r\n #flip\r\n flipstate = False if flipstate == True else True\r\n flips += 1\r\n\r\n if flipstate == False:\r\n flips += 1\r\n\r\n result = flips\r\n\r\n strout = \"Case #\" + str(i+1) + \": \" + str(result) + \"\\n\"\r\n #print strout\r\n fout.write(strout)\r\nfin.close()\r\nfout.close()\r\n","sub_path":"codes/CodeJamCrawler/16_0_2/josephsw/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"320254157","text":"import pdb\nfrom ttt2 import Board\nfrom agent2 import Agent\nfrom RandomPlayer import RandomPlayer\nfrom user_tokens import UserTokens as user\nfrom manual import Manual\nimport matplotlib.pyplot as plt\n\n# This method plays a game and checks for a winner\ndef play_game(a1, a2, verbose=False):\n board = Board()\n players = [a1,a2]\n turns = 0\n\n while board.game_status() is user.available:\n player = players[turns % 2]\n board.take_space(player.token, player.next_move(board))\n turns += 1\n if verbose:\n print(board.print_board())\n print(\"\\n\\n\")\n pdb.set_trace()\n\n a1.end_game(board)\n a2.end_game(board)\n\n return board\n\n# The method plays many games and displays graphs of the different\n# winners.\ndef play_games(a1, a2, count, verbose=False, figure_name = 'default.png'):\n \n stats = {\n user.X: 0,\n user.O: 0,\n user.draw: 0\n }\n output_x = []\n output_y = []\n output_d = []\n poutput_x = []\n poutput_y = []\n poutput_d = []\n\n for i in range(count):\n board = play_game(a1,a2, verbose)\n\n stats[board.game_status()] += 1\n\n if i % 10 == 0:\n\n output_x.append(stats[user.X])\n output_y.append(stats[user.O])\n output_d.append(stats[user.draw])\n total = stats[user.X] + stats[user.O] + stats[user.draw]\n print(stats[user.X]/total)\n poutput_x.append(stats[user.X]/total)\n poutput_y.append(stats[user.O]/total)\n poutput_d.append(stats[user.draw]/total)\n\n pl1, = plt.plot(poutput_x, label='X', linewidth=2)\n pl2, = plt.plot(poutput_y, label='Y', linewidth=2)\n pld, = plt.plot(poutput_d, label='draws', linewidth=2)\n plt.legend(handles=[pl1,pl2,pld])\n plt.ylabel('Tic Tac Toe Win Percentages')\n plt.savefig('percentage' + figure_name)\n return stats\n\n\n# This method prints the players statistics\ndef print_stats(stats):\n print(\"X: {}\".format(stats[user.X]))\n print(\"O: {}\".format(stats[user.O]))\n print(\"D: {}\".format(stats[user.draw]))\n\n\n# This method creats the bar graph showing the results for X, O, draw\ndef create_bar_graph(stats, filename):\n\n fig, ax = plt.subplots()\n width = 1/1.5\n y = [stats[user.X],stats[user.O],stats[user.draw]]\n x = range(3)\n b1 = ax.bar(0, [stats[user.X]], width, color='b')\n b2 = ax.bar(1, [stats[user.O]], width, color='r')\n b3 = ax.bar(2, [stats[user.draw]], width, color='g')\n\n plt.xlabel('Player')\n plt.ylabel('Games Won')\n plt.title('Tic Tac Toe Results')\n plt.xticks(x, ('X', 'O', 'Draw'))\n plt.legend()\n\n plt.savefig(filename)\n\na1 = Agent(user.X)\na2 = RandomPlayer(user.O)\na3 = Agent(user.O)\n\na4 = RandomPlayer(user.X)\na5 = Agent(user.O)\n\nmanual = Manual(user.O)\nstats = play_games(a1, a2, 100000, figure_name = 'AgentX_RandY.png')\ncreate_bar_graph(stats, 'agent_rand.png')\nprint_stats(stats)\n\na1.set_learn_rate(0)\n\nstats = play_games(a4, a3, 100000, figure_name = 'AgentX_RandY2.png')\ncreate_bar_graph(stats, 'agent_rand2.png')\nprint_stats(stats)\n\na3.set_learn_rate(0)\n\nstats = play_games(a1, a3, 10000, figure_name = 'AgentX_RandY3.png')\ncreate_bar_graph(stats, 'agent_rand3.png')\nprint_stats(stats)\n","sub_path":"driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"319024296","text":"# Email domain name finder - version 1.\n# ------------------------------------\n\n# Write a function: parseEmail(emailAddress) which takes a single parameter, 'emailAddress'.\n# The parameter should be an email address in the form: username@domain.ext\n# Separate the address into two components and print each of these separately\n# 1. The username\n# 2. The domain and extension\n \n# (Hint: See if you can find the index of the 'at' symbol)\n\n# What test inputs can you give to your function to make sure it is \n# working as expected?\n\ndef parseEmail(emailAddress):\n index = emailAddress.find(\"@\")\n if (index<0):\n print(\"Wrong email format\")\n return False\n else: \n \n print(\"The user name is: \"+emailAddress[0:index])\n print(\"The domain and extension is \"+ emailAddress[index+1:])\n return True\n\n\n\ndef parseEmailversion2(emailAddress):\n index = emailAddress.find(\"@\")\n if (index<0):\n print(\"Wrong email format\")\n return False\n else: \n EmailAddressAfterAt= emailAddress[index+1:]\n index2 = EmailAddressAfterAt.find(\".\") \n print(index2) \n print(\"The user name is: \"+emailAddress[0:index])\n print(\"The domain is \"+ EmailAddressAfterAt[0:index2])\n print(\"The extension is \"+ EmailAddressAfterAt[index2+1:])\n return True\n\n\n\nparseEmailversion2(\"anna@tim123.gmail\") \n\n\n# Email domain name finder - version 2.\n# ------------------------------------\n\n# Update the parseEmail() function to also separate out the extension segment\n# of the domain.\n\n# What additional tests, if any would you add to test this version of the function.","sub_path":"EmailDomainFinder.py","file_name":"EmailDomainFinder.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"588105765","text":"from torch.utils.data import TensorDataset\nimport torchvision.transforms as transforms\nfrom PIL import Image\nimport glob\nimport pickle\nimport random\nimport numpy as np\nimport os\nimport cv2\n\n# 利用pytorch的TensorDataset类\nclass FaceEmbed(TensorDataset):\n def __init__(self, data_path_list, same_prob=0.8):\n datasets = []\n # embeds = []\n self.N = []\n self.same_prob = same_prob\n for data_path in data_path_list:\n image_list = glob.glob(f'{data_path}/*.*g')\n datasets.append(image_list)\n self.N.append(len(image_list))\n # with open(f'{data_path}/embed.pkl', 'rb') as f:\n # embed = pickle.load(f)\n # embeds.append(embed)\n self.datasets = datasets\n # self.embeds = embeds\n self.transforms = transforms.Compose([\n transforms.ColorJitter(0.2, 0.2, 0.2, 0.01),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n\n def __getitem__(self, item):\n idx = 0\n while item >= self.N[idx]:\n item -= self.N[idx]\n idx += 1\n image_path = self.datasets[idx][item]\n name = os.path.split(image_path)[1]\n # embed = self.embeds[idx][name]\n Xs = cv2.imread(image_path)\n Xs = Image.fromarray(Xs)\n\n if random.random() > self.same_prob:\n image_path = random.choice(self.datasets[random.randint(0, len(self.datasets)-1)])\n Xt = cv2.imread(image_path)\n Xt = Image.fromarray(Xt)\n same_person = 0\n else:\n Xt = Xs.copy()\n same_person = 1\n return self.transforms(Xs), self.transforms(Xt), same_person\n\n def __len__(self):\n return sum(self.N)\n\nclass Faces(TensorDataset):\n def __init__(self, data_path):\n self.datasets = image_list = glob.glob(f'{data_path}/*.*g')\n self.transformers = transforms.Compose([\n transforms.ColorJitter(0.2, 0.2, 0.2, 0.01),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n\n def __getitem__(self, item):\n image_path = self.datasets[item]\n image = cv2.imread(image_path)\n image = Image.fromarray(image)\n \n return self.transformers(image)\n\n def __len__(self):\n return len(self.datasets)\n\nclass cat_dataloaders():\n \"\"\"Class to concatenate multiple dataloaders\"\"\"\n\n def __init__(self, dataloaders, batch_size):\n self.dataloaders = dataloaders\n self.batch_size = batch_size\n len(self.dataloaders)\n\n def __iter__(self):\n self.loader_iter = []\n for i, data_loader in enumerate(self.dataloaders):\n self.loader_iter.append(iter(data_loader))\n return self\n\n def __next__(self):\n out = []\n b = ''\n for data_iter in self.loader_iter:\n a = next(data_iter, None)\n if a is None:\n temp_dataloader = DataLoader(self.dataloaders[0].dataset, batch_size=self.batch_size, shuffle=True)\n a = next(iter(temp_dataloader))\n if b is None:\n return None\n b = None\n out.append(a) # may raise StopIteration\n return tuple(out)","sub_path":"utils/Dataset.py","file_name":"Dataset.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"640218596","text":"def counting_sort(values, max_value):\n \"\"\"Sorts integers using the Counting Sort algorithm.\n\n Args:\n values: iterable, contains the integers to sort\n should be between 0 and max_value\n max_value: maximum value the numbers can take\n\n Returns:\n a sorted list of the numbers\n \"\"\"\n\n counting_list = [0] * (max_value + 1)\n values_sorted = []\n\n for number in values:\n counting_list[number] += 1\n\n for number, amount in enumerate(counting_list):\n for _ in range(amount):\n values_sorted.append(number)\n\n return values_sorted\n\n\nprint(counting_sort([4, 2, 5, 7, 3, 1, 1, 4, 1, 2, 2], 7))\n","sub_path":"2019/07_Good_Practises/counting_sort.py","file_name":"counting_sort.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"540028516","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/10/3 1:45\n# @Author : Run \n# @File : __init__.py.py\n# @Software : PyCharm\n\n\nimport re\nfrom typing import List\nimport math\n\n\ndef equal_split(s: str, width: int) -> List[str]:\n \"\"\"\n Split the string, each split has length `width` except the last one.\n \"\"\"\n num = int(math.ceil(len(s) / width)) # python3\n return [s[i * width: (i + 1) * width] for i in range(num)]\n\n\ndef split_to_words(s: str) -> List[str]:\n \"\"\"\n Break the string into words.\n e.g.\n 1. 'a b' -> ['a', 'b']\n 2. 'a-b' -> ['a', 'b']\n 3. 'a_b' -> ['a', 'b']\n 4. 'AbcDef' -> ['Abc', 'Def']\n \"\"\"\n return re.sub(r'(\\s|_|-)+', ' ', re.sub('([A-Z]+)', r' \\1', s)).split()\n\n\ndef check_brackets(s: str) -> bool:\n \"\"\"\n LeetCode 20: Valid Parentheses\n check if brackets(and parentheses) come in pairs, besides, left should occur before right.\n \"\"\"\n rights = {')', ']', '}'}\n lefts = {'(': ')', '[': ']', '{': '}'}\n l = []\n for i, c in enumerate(s):\n if c in lefts:\n l.append((i, c))\n elif c in rights:\n if len(l) == 0:\n print(\"redundant '{}' at position {}\".format(c, i))\n return False\n i0, c0 = l.pop()\n if lefts[c0] != c:\n print(\"unmatched '{}' at position {} with '{}' at position {}\".format(c0, i0, c, i))\n return False\n if len(l) > 0:\n print(\"redundant parentheses and their positions: {}\".format(l))\n return False\n return True\n\n\ndef count_vowels(target_str: str) -> int:\n return len(re.findall('[aeiou]', target_str, re.IGNORECASE))\n\n\nif __name__ == \"__main__\":\n print(equal_split(\"helloworld\", 5))\n print(equal_split(\"helloworld.\", 5))\n print()\n \n print(split_to_words('HelloWorld I_am-python'))\n print()\n\n print(check_brackets(\"{(a, b): {c, ...}, ...}\"))\n print(check_brackets(\"{\"))\n print(check_brackets(\"{)(}\"))\n print()\n\n print(count_vowels('fooBAar'))\n print(count_vowels('gym'))\n print()","sub_path":"RunToolkit/for_str/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"430505019","text":"input_files = ['1tstamp.csv', 'Data_HR_RRI.csv']\noutput_file = 'dataset.csv'\n\noutput = None\nfor infile in input_files:\n with open(infile, 'r') as fh:\n if output:\n for i, l in enumerate(fh.readlines()):\n output[i] = \"{},{}\".format(output[i].rstrip('\\n'), l)\n else:\n output = fh.readlines()\n\nwith open(output_file, 'w') as fh:\n for line in output:\n fh.write(line) \n","sub_path":"Tests/mergeRows.py","file_name":"mergeRows.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"186805343","text":"import re\n\ndef f_transcript_to_protein(blast_filename):\n \"\"\"\n Load transcript IDs of query sequence (qseqid) and SwissProt IDs of subject\n sequence (sseqid) without version number to the dictionary.\n :param path: input fil path\n :return: transcript_to_protein = {}\n \"\"\"\n transcript_to_protein = {}\n blast_file = open(blast_filename)\n\n for line in blast_file:\n qseqid, sseqid, pident, length, mismatch, gapopen, qstart, qend, sstart, send, evalue, bitscore = line.rstrip().split(\n \"\\t\")\n transcript, isoform = qseqid.split(\"|\")\n gi_type, gi, sp_type, sp, sp_name = sseqid.split(\"|\")\n sp_id, sp_version = sp.split(\".\")\n transcript_to_protein[transcript] = sp_id\n\n blast_file.close()\n return transcript_to_protein\n\ndef f_gene_to_go(gene_to_go_filename):\n \"\"\"\n :param gene_to_go_filename:\n :return:\n \"\"\"\n gene_to_go = {}\n gene_to_go_file = open(gene_to_go_filename)\n # Load protein IDs and corresponding GO terms to the dictionary.\n for line in gene_to_go_file:\n db, object_id, object_symbol, qualifier, go_id, *others = line.split(\"\\t\")\n\n # Check if both protein and GO IDs have a value before adding.\n if object_id and go_id:\n gene_to_go[object_id] = go_id\n gene_to_go_file.close()\n\n return gene_to_go\n\ndef f_go_terms(go_terms_filename):\n go_terms_file = open(go_terms_filename)\n go_to_desc = {}\n # Load GO IDs and their names to the dictionary.\n terms = go_terms_file.read()\n terms = re.findall(r\"\\[Term]\\n(.*?)\\n\\n\", terms, re.DOTALL)\n\n for term in terms:\n go_id = re.search(r\"^id:\\s+(GO:\\d+?)\\n\", term)\n go_name = re.search(r\"^name:\\s+(.+?)\\n\", term, re.M)\n\n # Check if both ID and name have a value before adding.\n if go_id and go_name:\n go_to_desc[go_id.group(1)] = go_name.group(1)\n\n go_terms_file.close()\n return go_to_desc\n\ndef f_diff_exp(diff_exp_filename,report_filename, transcript_to_protein,gene_to_go,go_to_desc):\n \"\"\"\n :param diff_exp_filename:\n :param report_filename:\n :param transcript_to_protein:\n :param gene_to_go:\n :param go_to_desc:\n :return:\n \"\"\"\n diff_exp_file = open(diff_exp_filename)\n report_file = open(report_filename, \"w\")\n # Loop through differential expression file; lookup the protein ID and\n # GO term + GO name; print results to REPORT output.\n diff_exp_file.readline() # skip header\n for line in diff_exp_file:\n transcript, sp_ds, sp_hs, sp_log, sp_plat = line.rstrip().split(\"\\t\")\n\n protein = transcript_to_protein.get(transcript, \"NA\")\n go_id = gene_to_go.get(protein, \"NA\")\n go_desc = go_to_desc.get(go_id, \"NA\")\n\n report_file.write(\"\\t\".join([transcript, protein, sp_ds, sp_hs, sp_log, sp_plat, go_id, go_desc]) + \"\\n\")\n diff_exp_file.close()\n report_file.close()\n\nif __name__ == \"__main__\":\n blast_filename = \"blastp.outfmt6\"\n gene_to_go_filename = \"gene_association_subset.gaf\"\n go_terms_filename = \"go-basic.obo\"\n diff_exp_filename = \"diffExpr.P1e-3_C2.matrix\"\n report_filename = \"old_report_OP.tsv\"\n\n transcript_to_protein = f_transcript_to_protein(blast_filename)\n gene_to_go = f_gene_to_go(gene_to_go_filename)\n go_to_desc = f_go_terms(go_terms_filename)\n f_diff_exp(diff_exp_filename,report_filename, transcript_to_protein,gene_to_go,go_to_desc)","sub_path":"Diff_exp_annotation/diff_exp_annotations-messy.py","file_name":"diff_exp_annotations-messy.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"541704878","text":"from socket import *\nimport time\nip_sort=('127.0.0.1',8000)\nbuffer_size=1024\nudp_client=socket(AF_INET,SOCK_DGRAM)\n\nwhile True:\n\tmsg=input('>>: ')\n\tudp_client.sendto(msg.encode('utf-8'),ip_sort)\n\tdata,addr=udp_client.recvfrom(buffer_size)\n\tprint(data.decode('utf-8'))\n\nudp_client.close()","sub_path":"Month1/NTP_Client.py","file_name":"NTP_Client.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"601242889","text":"import urllib.request\nimport json\n\n\n\ndef getAdvertisement(query_list):\n\n client_id= 'mibzCc7PHbQ0Oyo9rqti'\n client_secret= 'a2HGywvUmd'\n query_list = query_list\n\n adv_results = list()\n for query in query_list:\n\n query = urllib.parse.quote(query)\n print(query)\n\n url = 'https://openapi.naver.com/v1/search/shop.json?query=' + query +'&sort=sim'\n print(url)\n\n request = urllib.request.Request(url)\n request.add_header('X-Naver-Client-Id', client_id)\n request.add_header('X-Naver-Client-Secret', client_secret)\n response = urllib.request.urlopen(request)\n rescode = response.getcode()\n if (rescode == 200):\n response_body= response.read()\n body = response_body.decode('utf-8')\n data = json.loads(body)\n items = data['items']\n\n for item in items:\n adv_results.append({\n\n 'title' : item['title'],\n 'link' : item['link'],\n 'image' : item['image'],\n 'lprice' : item['lprice'],\n 'hprice' : item['hprice']\n })\n break\n\n else:\n print(\"Error Code:\" + rescode)\n\n print('size: ', len(adv_results))\n print('result: ', adv_results)\n\n return adv_results","sub_path":"DetectionApp/naver_ad_api.py","file_name":"naver_ad_api.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"232880546","text":"import pandas as pd\nimport game_simulation\n\ndf = pd.read_csv('season-1819_csv.csv')\n# extract match information\ndata = df.iloc[:, 2:4]\n\nteam = pd.unique(data['HomeTeam'])\nrank_data = pd.DataFrame({'Pts': [0] * team.size}, index=team)\n\nimport random\n\nrandom.seed(19209554)\nrandom.uniform(0, 1)\n\n\ndef res():\n a = game_simulation.res()\n if a[0] > a[1]:\n return 'win'\n elif a[0] == a[1]:\n return 'even'\n else:\n return 'lose'\n\n\nsteps = 0\n\nfor i in range(data.shape[0]):\n if i % 10 == 0:\n print(\"Round %d:\" % (i // 10 + 1))\n match_res = res()\n if match_res == \"win\":\n rank_data.loc[data['HomeTeam'][i],] += 3\n elif match_res == \"even\":\n rank_data.loc[data['HomeTeam'][i],] += 1\n rank_data.loc[data['AwayTeam'][i],] += 1\n else:\n rank_data.loc[data['AwayTeam'][i],] += 3\n\nprint(rank_data.sort_values(by=['Pts'], ascending=False))\n","sub_path":"football/pl_simulation.py","file_name":"pl_simulation.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"501576741","text":"\"\"\"\nPOSTメソッド呼び出しのためのテストファイル\n演習問題用\n\"\"\"\n\nimport requests\nimport json\n\nurl = 'http://ec2-18-176-62-93.ap-northeast-1.compute.amazonaws.com/program'\ndata = {'title':'banana', 'type':'anime'}\nheaders = {'content-type':'application/json'}\n\nresponse = requests.post(url, json.dumps(data), headers=headers)\n\nprint(response.text)","sub_path":"p_test.py","file_name":"p_test.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"9689696","text":"def main():\r\n \r\n # List of string \r\n list1 = ['Hi' , 'hello', 'at', 'this', 'there', 'from']\r\n \r\n # List of string\r\n list2 = ['there' , 'hello', 'Hi']\r\n \r\n ''' \r\n check if list1 contains all elements in list2\r\n '''\r\n result = all(elem in list1 for elem in list2)\r\n \r\n if result:\r\n print(\"Yes, list1 contains all elements in list2\") \r\n else :\r\n print(\"No, list1 does not contains all elements in list2\") \r\n \r\n \r\n ''' \r\n check if list1 contains any elements of list2\r\n '''\r\n result = any(elem in list1 for elem in list2)\r\n \r\n if result:\r\n print(\"Yes, list1 contains any elements of list2\") \r\n else :\r\n print(\"No, list1 contains any elements of list2\") \r\n\r\n \r\nif __name__ == '__main__':\r\n main()","sub_path":"Basics/search_list_in_list.py","file_name":"search_list_in_list.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482592190","text":"# 1951-2010 long term average CRU40\n\n# ### NOTES:\n# - CRU-TS40 data appear to have more strong features on the landscape, even when compared with adjacent CRU40 and 5ModelAvg future scenarios. \n# \t- Therefore, I think to have a spatial output that construes change through time and space, best thing to do would be to make a long-term average of the CRU-TS40 data for 1951-2010, and then do a difference between this baseline average and the future predictions (both processes will be run decadally).\n\nimport rasterio\nimport numpy as np\nimport xarray as xr\nimport os, glob\n\nrcps = ['rcp45','rcp85']\ncru_fn = '/workspace/Shared/Tech_Projects/DOD_Ft_Wainwright/project_data/GIPL/SNAP_modified/frozen_season_length/decadal/gipl2f_frozen_length_5cm_cru40_1km_ak_Interior_LTA_1951-2015.tif'\nar5_files = ['/workspace/Shared/Tech_Projects/DOD_Ft_Wainwright/project_data/GIPL/SNAP_modified/frozen_season_length/decadal/gipl2f_frozen_length_5cm_ar5_5modelAvg_{}_1km_ak_Interior_decadal_2020-2090.tif'.format(rcp) for rcp in rcps]\noutput_filenames = ['/workspace/Shared/Tech_Projects/DOD_Ft_Wainwright/project_data/GIPL/SNAP_modified/frozen_season_length/decadal_diff_from_baseline/freeze_to_thaw_length_decadal_diff_{}_cru_lta_2020-2090.tif'.format(rcp) for rcp in rcps]\n\ncru_lta = rasterio.open( cru_fn ).read( 1 )\ndecades = list(range(2020,2091,10))\nfor ind, rcp in enumerate(rcps):\n\tar5 = rasterio.open(ar5_files[ind]).read()\n\t\n\tar5_deltas = np.array([ (cru_lta - arr) for arr in ar5 ])\n\t_ = [np.place(arr,ar5[0] == -9999, -9999) for arr in ar5_deltas ] # update the mask\n\n\twith rasterio.open( ar5_files[ind] ) as tmp:\n\t\tmeta = tmp.meta.copy()\n\t\tmeta.update( compress='lzw', count=ar5_deltas.shape[0], nodata=-9999 )\n\n\twith rasterio.open( output_filenames[ind], 'w', **meta ) as out:\n\t\tout.write( ar5_deltas.astype(np.float32) )\n\n\tfor idx, decade in enumerate( decades ):\n\t\tout_fn = output_filenames[ind].replace('_2020-2090.tif', '_{}.tif'.format(decade))\n\n\t\tmeta.update( count=1 )\n\t\twith rasterio.open( out_fn, 'w', **meta ) as out:\n\t\t\tout.write( ar5_deltas[idx].astype(np.float32), 1 )","sub_path":"compute_diffs_cru40_ar5_5ModelAvg_GIPL.py","file_name":"compute_diffs_cru40_ar5_5ModelAvg_GIPL.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"301639165","text":"import sys\nsys.path.append('../')\n\nfrom contour import contour\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport efd\nfrom bacteria_model import bacteria_spline\nfrom shapely.geometry import Polygon\n\n# Loda image\nim = np.load('examples/test_bacteria.npy')\n\n# Bacteria values\nr = 0.3309786038590506\nl = 2.9239029503218905\nR = 15.336402399051828\ntheta= 12.032521406278008\nex_wv = 0.8\nem_wv = 0.59\nn_b = 0\n\n# Microscope values\nm = 40\npixel_size = 4.4\npadding = 2\n\n# create bacteria model\ndef spline_fn_curvature(x):\n return np.sqrt(R**2 - (x-l/2)**2) - np.sqrt(R**2-l**2/4)\n\nbacteria = bacteria_spline(r, l, 0.01, spline_fn_curvature, theta, ex_wv, em_wv, n_b)\n\n# Remove blank padding\nrm_indices = np.where(im==0.0)[0]\nim = np.delete(im, rm_indices, axis=0)\n\n# Display contour\ncontour = contour(im, 0.8, bacteria, m, pixel_size, padding)\ncontour_smoothed = Polygon(contour.smoothed_contour)\ncontour_act = Polygon(contour.active_contour)\ncontour_px = Polygon(contour.pixelated_contour)\nbacteria_contour = Polygon(contour.boundary).buffer(0)\ndif = bacteria_contour.symmetric_difference(contour_smoothed)\nplt.plot(*contour_smoothed.exterior.xy, label=\"smoothed\")\ncontour_o = contour_smoothed.buffer(-.55)\nplt.plot(*contour_o.exterior.xy, label = \"optimal\")\ncontour_o = contour_smoothed.buffer(-.3)\nplt.plot(*contour_o.exterior.xy, label = \"contraction\")\ncontour_o = contour_smoothed.buffer(-1.0)\nplt.plot(*contour_o.exterior.xy, label = \"inner outline\")\nplt.plot(*bacteria_contour.exterior.xy, label = \"ground truth\")\nplt.axis('scaled')\nplt.title('Boundary comparison')\nplt.legend(fontsize=6)\nplt.show()\n","sub_path":"shape_comparison.py","file_name":"shape_comparison.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514998156","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis analysis will plot a histogram of close-open over a big period of WINFUT\n\"\"\"\n\nimport pyqtgraph as pg\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport numpy as np\nfrom navala import system as na\nfrom navala import database\nimport datetime\nfrom navala.misc import quoteperiod as qp\n\n_HILO = 0\n_OPCL = 1\n_HIOP = 2\n_CLLO = 3\n\ndef GetData(type_):\n db = na.vala.db\n assert isinstance(db, database.Database)\n q = db.quote_GetData(qp.daily, \"BMF_FUT_WINFUT\", datetime.datetime(2000, 1, 1), datetime.datetime(2015, 1, 1))\n if type_ == _HILO:\n v = q.high-q.low\n elif type_ == _OPCL:\n v = q.close-q.open\n elif type_ == _HIOP:\n v = q.high-q.open\n elif type_ == _CLLO:\n v = q.close-q.low\n return v\n\ndef MakeHistogram(vals_):\n # \"Slips\" boundaries to nearest multiple of STEP (I experienced some cases when values weren't multiples of 5 as they should be)\n # This could be made general using mode(diff(vals_)) instead of STEP\n STEP = 50\n e1 = np.floor(min(vals_)/STEP)*STEP\n e2 = np.ceil(max(vals_)/STEP)*STEP\n\n r = np.arange(e1-STEP/2, e2+STEP*1.01/2, STEP)\n return np.histogram(vals_, r) #, bins=np.linspace(-3, 8, 40))\n\nif __name__ == '__main__':\n na.vala.flagDB = True\n na.vala.flagMaster = True\n na.vala.Startup()\n try:\n app = QApplication([\"aaa\"])\n\n win = pg.GraphicsWindow()\n win.setWindowTitle('pyqtgraph example: Histogram')\n plt1 = win.addPlot(title=\"High - Low\")\n plt2 = win.addPlot(title=\"Close - Open\")\n win.nextRow()\n plt3 = win.addPlot(title=\"High - Open\")\n plt4 = win.addPlot(title=\"Close - Low\")\n\n GetCurve = lambda x, y: pg.PlotCurveItem(x, y, stepMode=True, fillLevel=0, brush=(0, 0, 255, 80))\n\n vals = GetData(_HILO)\n y,x = MakeHistogram(vals)\n ## notice that len(x) == len(y)+1\n ## We are required to use stepMode=True so that PlotCurveItem will interpret this data correctly.\n curve = GetCurve(x, y)\n plt1.addItem(curve)\n\n vals = GetData(_OPCL)\n y,x = MakeHistogram(vals)\n curve = GetCurve(x, y)\n plt2.addItem(curve)\n\n vals = GetData(_HIOP)\n y,x = MakeHistogram(vals)\n curve = GetCurve(x, y)\n plt3.addItem(curve)\n\n vals = GetData(_CLLO)\n y,x = MakeHistogram(vals)\n curve = GetCurve(x, y)\n plt4.addItem(curve)\n\n\n\n win.showMaximized()\n app.exec_()\n finally:\n na.vala.Cleanup()\n","sub_path":"experiments/20130307-/winfut_histograms/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"378707374","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Aug 28 12:01:14 2020\r\n\r\n@author: aparnami\r\n\"\"\"\r\n\r\nfrom itcs4156.datasets.Dataset import Dataset\r\nimport os\r\nimport pandas as pd\r\n\r\nclass HousingDataset(Dataset):\r\n\r\n def __init__(self): \r\n \r\n self.data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"data\")\r\n\r\n self.data = {\r\n \r\n \"urls\" : {\r\n \"train\" : \"https://drive.google.com/uc?export=download&id=1qbFX7dSCVdU8oj5uJVg5DOp-ckcZujGw\",\r\n \"val\" : \"https://drive.google.com/uc?export=download&id=1k_0i6-wAZMPLFjPkk2VFj0P9ksceJvWN\",\r\n \"names\" : \"https://drive.google.com/uc?export=download&id=1zHWoQGrNByAh0yDCskNOAwQ7OARVHmGr\"\r\n },\r\n\r\n \"paths\" : {\r\n\r\n },\r\n\r\n \"columns\" : [\"CRIM\", \"ZN\", \"INDUS\", \"CHAS\", \"NOX\", \"RM\", \"AGE\", \"DIS\", \"RAD\", \"TAX\", \"PTRATIO\", \"B\", \"LSTAT\", \"MEDV\"]\r\n }\r\n\r\n self.init_download()\r\n\r\n def init_download(self):\r\n for key, url in self.data[\"urls\"].items():\r\n data_path = self.download(url, self.data_dir, 'housing.' + key)\r\n self.data[\"paths\"][key] = data_path\r\n\r\n def load(self):\r\n\r\n df_train = pd.read_csv(self.data[\"paths\"][\"train\"], delim_whitespace=True, \r\n header=None, names=self.data[\"columns\"])\r\n\r\n df_val = pd.read_csv(self.data[\"paths\"][\"val\"], delim_whitespace=True, \r\n header=None, names=self.data[\"columns\"])\r\n\r\n return df_train, df_val\r\n \r\n\r\nif __name__ == \"__main__\":\r\n HousingDataset()","sub_path":"datasets/HousingDataset.py","file_name":"HousingDataset.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"92224337","text":"from math import sin, cos, radians\n\nclass Customer:\n EARTH_RADIUS = 6371.0\n # {\"latitude\": \"52.833502\", \"user_id\": 25, \"name\": \"David Behan\", \"longitude\": \"-8.522366\"}\n def __init__(self, latitude=None, longitude=None, user_id=None, name=None):\n self.latitude = latitude\n self.longitude = longitude\n self.user_id = user_id\n self.name = name\n \n if self.latitude and self.longitude:\n self.lat_radians = radians(self.latitude)\n self.lon_radians = radians(self.longitude)\n \n \n def create(self, customer_data):\n customers = []\n for meta_data in customer_data:\n \n customers.append(Customer(\n float(meta_data['latitude']),\n float(meta_data['longitude']),\n meta_data['user_id'],\n meta_data['name']\n ))\n \n\n return customers\n \n def filter_by_distance(self, o_lat, o_lon, all_customers, distance):\n if distance < 0. or len(all_customers) == 0:\n return []\n \n import numpy as np\n office_latitude = radians(o_lat)\n office_longitude = radians(o_lon)\n \n filtered_data = []\n for customer in all_customers:\n delta_lon = office_longitude - customer.lon_radians\n \n sin_prod = sin(office_latitude) * sin(customer.lat_radians)\n cos_prod = cos(office_latitude) * cos(customer.lat_radians) * cos(delta_lon)\n \n delta = np.arccos(sin_prod + cos_prod)\n \n delta_distance = self.EARTH_RADIUS * delta\n \n if delta_distance < distance:\n filtered_data.append(customer.to_json())\n \n return sorted(filtered_data, key = lambda i: i['user_id'])\n \n \n def to_json(self):\n return {\n \"user_id\": self.user_id,\n \"name\": self.name\n }\n ","sub_path":"project/app/models/customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"554298198","text":"\"\"\"\nCopyright (c) 2018 Cisco Systems, Inc.\n\nAuthor:\n Christian Oeien \n\"\"\"\nfrom tng.api import runner\nfrom tng.device.endpoint.synergylite_3pcc import BigEasyVideo3pcc\nfrom tng_sl.contrib.pitstop_helper import PitstopTestCase\nfrom pitstop.exp import (\n Send, Receive, Command, Poll, Wait, LocalOffer, RemoteAnswer,\n Sift, Assist, Flag)\n\n\nclass Test(PitstopTestCase):\n\n required_caps = ['video']\n\n def test_rfc5168_request_idr_when_no_rtcpfb_in_sdp(self):\n '''\n have DUT receive a video call. Wait for video sequence to contain\n non-IDR(*) NAL-units. Inject packet loss in the video-stream and\n expect an INFO request specified in RFC 5168, picture fast update\n (*) IDR: picture encoded with no dependency to the prior sequence\n '''\n\n def non_idr(rtp):\n return 1 == (ord(rtp.payload[0]) & 0x1f)\n\n class LossBurst:\n def __init__(self, count):\n self.count = count\n\n def __call__(self, rtp):\n if self.count:\n self.count -= 1\n return True # yes; drop\n lossburst = LossBurst(9)\n\n self.spec.update({\n \"test\": [\n Wait(\"idle\").then([]),\n Poll(self.dut.is_registered).then([\n LocalOffer(\"a\", \"m=audio\\nm=video\\n!a=rtcp-fb:\"),\n Send(\"INVITE\", {\"\\n\": \"$a\"}, transaction_label=\"i\")]),\n Receive(\"18.\", {}, on_transaction=\"i\").then([\n Command(self.dut.accept_call)]),\n Receive(\n \"200\", {}, on_transaction=\"i\", dialog_label=\"d\",\n captures={\"A\": \"\\n(^v=0.+)\"}).then([\n RemoteAnswer(\"$A\"),\n Send(\"ACK\", {}, in_dialog=\"d\")]),\n Sift(non_idr, \"video\").then([\n Assist(lossburst, \"video\")]),\n Receive(\"INFO\", {\n \"Content-Type\": \"application/media_control[+]xml\",\n \"\\n\": \"picture_fast_update\"},\n in_dialog=\"d\", transaction_label=\"x\").then([\n Send(\"200\", {}, on_transaction=\"x\"),\n Command(self.dut.end_call)]),\n Receive(\"BYE\", {}, in_dialog=\"d\", transaction_label=\"q\").then([\n Send(\"200\", {}, on_transaction=\"q\")]),\n Poll(self.dut.is_line_idle).then([Flag(\"idle\")])]})\n\n self.pitstop(timer=70)\n\n\ndef main():\n runner()\n","sub_path":"pitstop_tests/video/_rfc5168_request_idr_when_no_rtcpfb_in_sdp.py","file_name":"_rfc5168_request_idr_when_no_rtcpfb_in_sdp.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"379904481","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 16 11:39:18 2019\n\n@author: WEI\n\"\"\"\n\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\nimport shapely.geometry as sgeom\n\nimport cartopy.crs as ccrs\nimport cartopy.io.shapereader as shpreader\n\n\n\nfig = plt.figure()\nax = fig.add_axes([0, 0, 1, 1], projection=ccrs.LambertConformal())\n\nax.set_extent([-125, -66.5, 20, 50], ccrs.Geodetic())\n\n#shapename = 'admin_1_states_provinces_lakes_shp'\n#states_shp = shpreader.natural_earth(resolution='110m', category='cultural', name=shapename)\n\n# the download site https://www.naturalearthdata.com/downloads/110m-cultural-vectors/110m-admin-1-states-provinces/\n# is down\n# get the shape files from GitHub\n# https://github.com/nvkelso/natural-earth-vector/blob/master/110m_cultural/ne_110m_admin_1_states_provinces.shp\n# the files above do not work\n\n# the above do not work\n#Get map from https://www.arcgis.com/home/item.html?id=f7f805eb65eb4ab787a0a3e1116ca7e5\n\nstates_shp = \"../data/states_21basic/states.shp\"\nshapes = shpreader.Reader(states_shp)\ncountries = shapes.records()\ncountry = next(countries)\nprint (type(country.attributes))\nprint (sorted(country.attributes.keys()))\n\n\nlen(shapes)\nrecords = list(shapes.records())\nprint(', '.join(str(r) for r in sorted(records[0].attributes.keys())))\n #comment, ... name, name_alt, ... region, ...\nprint(records[0].attributes['STATE_NAME'])\n\n\ngeoms = list(shapes.geometries())\nprint(type(geoms[0]))\n\npopulation = lambda country: country.attributes['STATE_NAME']\ncountries_by_pop = sorted(shapes.records(), key=population)[:51]\n', '.join([str(country.attributes['STATE_NAME'])\n for country in countries_by_pop])\n\n#lons, lats = sample_data()\n\n# to get the effect of having just the states without a map \"background\"\n# turn off the outline and background patches\nax.background_patch.set_visible(False)\nax.outline_patch.set_visible(False)\n\nax.set_title('US States')\n\n# turn the lons and lats into a shapely LineString\n#track = sgeom.LineString(zip(lons, lats))\n\n# buffer the linestring by two degrees (note: this is a non-physical\n# distance)\n#track_buffer = track.buffer(2)\n\ndef colorize_state(geometry):\n facecolor = (0.9375, 0.9375, 0.859375)\n #print(geometry)\n # if geometry.intersects(track):\n # facecolor = 'red'\n # elif geometry.intersects(track_buffer):\n # facecolor = '#FF7E00'\n return {'facecolor': facecolor, 'edgecolor': 'black'}\n\n\nprint(shpreader.Reader(states_shp).records)\n\nax.add_geometries(\n shpreader.Reader(states_shp).geometries(),\n ccrs.PlateCarree(),\n styler=colorize_state\n )\n\n # ax.add_geometries([track_buffer], ccrs.PlateCarree(),\n # facecolor='#C8A2C8', alpha=0.5)\n # ax.add_geometries([track], ccrs.PlateCarree(),\n # facecolor='none', edgecolor='k')\n\n# make two proxy artists to add to a legend\nlabel1_m = mpatches.Rectangle((0, 0), 1, 1, facecolor=\"red\")\nlabel2_m = mpatches.Rectangle((0, 0), 1, 1, facecolor=\"#FF7E00\")\nlabels = ['Lable 1 text', 'Lable 2 text']\nax.legend([label1_m, label2_m], labels,\n loc='lower left', bbox_to_anchor=(0.025, -0.1), fancybox=True)\n\nplt.show()\n\n\nimport matplotlib as mpl\nimport matplotlib.cm as cm\n\nnorm = mpl.colors.Normalize(vmin=-20, vmax=10)\ncmap = cm.hot\nx = 0.3\n\nm = cm.ScalarMappable(norm=norm, cmap=cmap)\nprint (m.to_rgba(x))\n\n\nprint (cm.hot(0.3))\n\n\n\nimport pandas as pd\nimport numpy as np\nmydata= pd.read_csv(\"..\\\\data\\\\murders.csv\")\n\nmydata.shape\n\nmydata.head(60)\n\nmydata['m_ratio'] = mydata['total']/mydata['population'] *100000\n\nmydata_t = mydata[['state', 'm_ratio']]\n\n\n\n\nmydata_t.head(20)\n\nmydata_d = mydata_t.set_index('state')\n\n\nmydata_d\nmydata_d.loc['Wisconsin', 'm_ratio']\n\n\n\nfig = plt.figure()\nax = fig.add_axes([0, 0, 1, 1], projection=ccrs.LambertConformal())\n\nax.set_extent([-125, -66.5, 20, 50], ccrs.Geodetic())\n\nfor astate in shapes.records():\n\n ### You want to replace the following code with code that sets the\n ### facecolor as a gradient based on the population density above\n #facecolor = [0.9375, 0.9375, 0.859375]\n\n edgecolor = 'black'\n\n # use the name of this state to get pop_density\n state_dens = mydata_d.loc[ astate.attributes['STATE_NAME'], 'm_ratio' ]\n\n\n\n # simple scheme to assign color to each state\n if state_dens < 1:\n facecolor = \"lightyellow\"\n elif state_dens > 4:\n facecolor = \"red\"\n else:\n facecolor = \"pink\"\n\n # `astate.geometry` is the polygon to plot\n ax.add_geometries([astate.geometry], ccrs.PlateCarree(),\n facecolor=facecolor, edgecolor=edgecolor)\n \nplt.show()","sub_path":"Python/SimpleMap.py","file_name":"SimpleMap.py","file_ext":"py","file_size_in_byte":4610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"424144909","text":"# -*- coding: utf-8 -*-\n'''\nCreated on Feb 16, 2019\n\n@author: cob19\n'''\n\nfrom biblebooks.paths.paths import txt_paths\nimport re\nimport os\n#import sys\n\npath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n# sys.path.insert(0,path)\n\n\nclass ContentManagementTextFiles:\n '''\n This class will be used for everything related to the text files used by the application,\n methods that manage content in the files are implemented, as well as managing the text files\n for their creation, deletion, change of names, etc. .\n '''\n\n def create_bible_dictionary(self):\n '''\n To create a object of the type dictionary, that save the old and new testament, with their respective books, chapters and contents.\n books_chapters_old_t_dictionary is the dictionary return in the create_books_chapters_dictionary function\n '''\n books_chapters_new_t_dictionary = self.create_books_chapters_dictionary(\n 'NT')\n books_chapters_old_t_dictionary = self.create_books_chapters_dictionary(\n 'AT')\n bible_dictionary = {\n 'AT': books_chapters_old_t_dictionary, 'NT': books_chapters_new_t_dictionary}\n\n return bible_dictionary\n\n def create_books_chapters_dictionary(self, testament=\"AT\"):\n '''\n Create a dictionary type object, which according to the \"testament\" parameter, which is passed to the function,\n will return a data structure of the new or the old testament with all the books, its chapters,\n and the content of each chapter with a structure hierarchical.\n The returned object books_chapters_dictionary will have the following format:\n books_chapters_dictionary={\n title_book1 : chapter_content_verse_book1,\n title_book2 : chapter_content_verse_book2,\n ...\n title_book3 : chapter_content_verse_book3,\n }\n The chapter_content_verse_book objects would be the object returned in the create_chapter_content_verse() function\n '''\n books_chapters_dictionary = {}\n file_names_and_titles_books = {}\n\n if(testament == 'AT'):\n file_names_and_titles_books = self.management_file_name_title_book(\n txt_paths['path_titles_o_t_books_txt'])\n book_route_txt_format = txt_paths['path_o_t_books']\n else:\n file_names_and_titles_books = self.management_file_name_title_book(\n txt_paths['path_titles_n_t_books_txt'])\n book_route_txt_format = txt_paths['path_n_t_books']\n\n for (file, title) in file_names_and_titles_books.items():\n\n title_n_l = title.rstrip()\n title_n_l = title_n_l.replace('° de', '')\n title_n_l = title_n_l.replace('ª a los', '')\n title_n_l = title_n_l.replace('ª a', '')\n title_n_l = title_n_l.replace('ª de', '')\n title_n_l = title_n_l.replace('Los Salmos', 'Salmo')\n title_n_l = title_n_l.replace('El Cantar de los ', '')\n title_n_l = title_n_l.replace(\n 'Lamentaciones de Jeremías', 'Lamentaciones')\n title_n_l = title_n_l.replace('Los ', '')\n\n txt_book_path = book_route_txt_format + file.rstrip() + '.txt'\n chapters_contents_dict = self.manage_complete_content_book(\n title_n_l, txt_book_path)\n chapter_content_verse = self.create_chapter_content_verse(\n chapters_contents_dict)\n books_chapters_dictionary[title_n_l] = chapter_content_verse\n return books_chapters_dictionary\n\n def create_chapter_content_verse(self, chapters_contents_dict):\n '''\n This method manages the contents of a book and the positions of each number of the verses in the content.\n Returns a chapter_content_verse object of the dictionary type that contains all the chapters and their contents.\n Each chapter will be the key and the value will be a tuple with the biblical content of each chapter and a dictionary with the verse and its position.\n The returned object chapter_content_verse will have the following format:\n chapter_content_verse={\n chapter1:[content,{verse:(positionStart,positionEnd)}],\n chapter2:[...],\n chapter3:[...],\n }\n '''\n chapter_content_verse = {}\n for chapter in chapters_contents_dict:\n verses = {}\n content = {}\n content['otherHeader'] = re.split(\n chapter, chapters_contents_dict[chapter])[0]\n content['titleChapter'] = chapter\n content['desarrollo'] = re.split(\n chapter + '
    ', chapters_contents_dict[chapter])[1]\n regeditReferences = re.compile(\n \"\\((([0-9]+ )|())([a-zA-Z]+)\\. [0-9]+\\.[0-9]+((-[0-9]+)|())(((; [0-9]+\\.[0-9]+((-[0-9]+)|()))+)|())(((; (([0-9]+ )|())([a-zA-Z]+)\\. [0-9]+\\.[0-9]+((-[0-9]+)|())(((; [0-9]+\\.[0-9]+((-[0-9]+)|()))+)|()))+)|())\\)\")\n b = content['desarrollo']\n for reference in regeditReferences.finditer(content['desarrollo']):\n repl = ''\n for character in range(len(reference.group(0))-2):\n repl += '@'\n b = re.sub(reference.group(0), repl, b)\n versesList = []\n for m in re.finditer(\"\\d+\", b):\n versesList.append(m.span()[0])\n verses[m.group(0)] = [m.span()[0], len(b)-1]\n if(int(m.group(0)) > 1):\n verses[str(int(m.group(0))-1)][1] = m.span()[0]\n chapter_content_verse[chapter] = [content, verses]\n\n return chapter_content_verse\n\n def manage_complete_content_book(self, book_name, book_route_txt_format):\n '''\n This method manages the content of a book in the text file according to the route passed as a parameter. \n Returns a chapters_contents_dict object of the dictionary type which contains all the chapters and their contents. \n Each chapter will be the key and the content will be the value.\n '''\n chapters_contents_dict = {}\n file = open(book_route_txt_format, encoding='windows-1252')\n content = file.readlines()\n book_name = book_name.upper()\n line_break = '
    '\n key = \"\"\n value = \"\"\n #chapters_contents_dict[key] = \"\"\n for line in content:\n y = re.search(\"\\A&\", line)\n if(y != None):\n value = line.replace('&', '').strip().replace(\n '\\n', '') + line_break\n key = \"\"\n else:\n line = line.strip().replace('\\n', '')\n if(line != ''):\n value += line + line_break\n x = re.search(book_name+\" \\d+\", line)\n if(x != None):\n key = x.string.rstrip().replace('&', '')\n if(key != \"\"):\n chapters_contents_dict[key] = value\n file.close()\n return chapters_contents_dict\n\n def management_file_name_title_book(self, path_file_titles_books):\n '''\n It manages the names of the files of each book as well as the title of the book in a more literary way. \n This management will be based on a text file, which must have related to each other the titles of each \n biblical book and its respective name of the text file. It will return a dictionary with the names of \n the files as keys and the titles as the values\n '''\n file = open(path_file_titles_books, encoding='windows-1252')\n content = file.readlines()\n fragmented_line = ()\n file_names_and_titles_books = {}\n\n for title in content:\n fragmented_line = title.split(\" \")\n counter = 0\n file_name_dictionary_key = fragmented_line[len(fragmented_line)-1]\n title_book_dictionary_value = \"\"\n while counter < (len(fragmented_line)-1):\n title_book_dictionary_value += (fragmented_line[counter]+\" \")\n counter += 1\n file_names_and_titles_books[file_name_dictionary_key] = title_book_dictionary_value\n file.close()\n return file_names_and_titles_books\n\n\na = ContentManagementTextFiles()\nb = a.create_books_chapters_dictionary()\nprint(b['Génesis']['GÉNESIS 1'][1])\nprint(b['Génesis']['GÉNESIS 1'][0])\n","sub_path":"biblebooks/content/ContentManagementTextFiles.py","file_name":"ContentManagementTextFiles.py","file_ext":"py","file_size_in_byte":8566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"506247833","text":"\nfrom django.conf.urls import patterns, url\n\nfrom steam_auth import views\n\nurlpatterns = patterns(\"\",\n\turl(r\"^login$\", views.auth_start, name=\"login\"),\n\turl(r\"^logout$\", views.logout_, name=\"logout\"),\n\turl(r\"^handle$\", views.auth_return),\n\turl(r\"^settings$\", views.manage_settings, name=\"settings.handler\"),\n)\n","sub_path":"steam_auth/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"215576121","text":"import curses\nfrom functions_curses import *\nfrom player18 import *\nfrom room import Room\n\ndef main():\n global instances\n ## Curses normal init sequence\n stdscr = curses.initscr()\n\n if not curses.has_colors():\n print(\"Your terminal emulator needs to have colors.\")\n return 0\n\n curses.noecho() # no echo, but we still see the cursor\n curses.curs_set(False) #turns off the cursor drawing\n stdscr.keypad(True) # allows special keys and arrow keys\n \n try:\n curses.start_color()\n\n stdscr_h, stdscr_w = stdscr.getmaxyx()\n world = Room(0, 0, stdscr_h, stdscr_w, \"~\", curses.COLOR_BLACK, curses.COLOR_BLACK)\n level_room = Room(2,3, 30, 10, \"~\", curses.COLOR_BLACK, curses.COLOR_BLUE, curses.A_BOLD)\n level_room2 = Room(8,10, 50, 10, \"~\", curses.COLOR_YELLOW, curses.COLOR_MAGENTA, curses.A_BOLD)\n avatar = Player(stdscr, \"@\", curses.COLOR_RED, curses.COLOR_BLACK, curses.A_BOLD)\n\n instances += [world, avatar, level_room, level_room2]\n\n avatar.correct_background()\n\n\n\n\n while True:\n key = stdscr.getch()\n\n avatar.move(key)\n\n if key == 27:\n break\n\n except Exception as e:\n stdscr.addstr(0,0,str(e))\n stdscr.getch()\n finally:\n \n curses.endwin()\n \n return 0\n\nif __name__ == '__main__':\n main()","sub_path":"unicurses19.py","file_name":"unicurses19.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"358230957","text":"from socket import *\nfrom time import ctime\n\nHOST = \"\"\nPORT = 10086\nADDR = (HOST,PORT)\nBUSIZE = 1024\n\nUdpSevSock = socket(AF_INET,SOCK_DGRAM)\nUdpSevSock.bind(ADDR)\n\nwhile True:\n\tprint(\"waiting for message...\")\n\tdata,addr = UdpSevSock.recvfrom(BUSIZE)\n\tUdpSevSock.sendto((\"[%s] %s\" %(ctime(),data)).encode(),addr)\n\tprint(\"...received from and returned to : \",addr)\n\nUdpSevSock.close()\n","sub_path":"Socket_Programming/UdpSocket/UdpSever.py","file_name":"UdpSever.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"135883094","text":"import os.path\nfrom os import path\nfrom sys import argv\nimport python_second_assignment as myList\n\n# A. first function takes a path to a folder and writes all filenames in the folder to a specified output file\n\n#folderpath = \"/Users/robin/Desktop/semester_4/python/myPythonCode/week 2\"\n#def read_folder(foldername, filename):\n# myList.write_list_to_file(filename, os.listdir())\n#read_folder(argv[1], argv[2])\n\nlst=[]\ndef read_folder_recursive(folderpath):\n entries = os.listdir(folderpath)\n for entry in entries:\n if os.path.isdir(entry):\n read_folder_recursive(entry)\n else:\n lst.append(entry)\n\n myList.write_list_to_file(argv[2], lst)\n\nread_folder_recursive(argv[1])\n\n# 3. third takes a list of filenames and print the first line of each\ndef read_first_line(*files):\n with open(file) as file_object:\n content = file_object.readline()\n print(content)\n for line in content:\n print(line.rstrip())\n","sub_path":"week 2/.history/utils_20200207101312.py","file_name":"utils_20200207101312.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"448208446","text":"from pyvdp.visadirect.models import VisaDirectTransactionModel, VisaDirectTransactionBatchModel\n\n\nclass PullFundsTransactionsModel(VisaDirectTransactionModel):\n \"\"\"VisaDirect FundsTransfer PullFunds data object model.\n\n :param int systemsTraceAuditNumber: **Required**. Systems trace audit number. 6 digits integer.\n :param int acquiringBin: **Required**. Bank identification number (BIN) for VisaDirect acquiring. 6-11 digits\n integer.\n :param int acquirerCountryCode: **Required**. \n `ISO country code `_ for acquiring institution.\n :param float amount: **Required**. Transaction amount nnn.mmm.\n :param str senderPrimaryAccountNumber: **Required**. Sender PAN (Primary Account Number), 13-19 characters.\n :param str senderCardExpiryDate: **Required**. Sender card expiration date, *YYYY-MM*, e.g. 2018-02.\n :param str senderCurrencyCode: **Required**. Sender currency code, 3 characters \n `ISO currency code `_.\n :param str businessApplicationId: **Required**. \n `Program business application type `_.\n 2 characters string.\n :param CardAcceptorModel cardAcceptor: **Required**. Instance of :func:`~pyvdp.visadirect.CardAcceptorModel`.\n :param int merchantCategoryCode: **Conditional**. Merchant category code (MCC). If provided, overrides the one \n present in onboarding data. If missing in onboarding, then this value is required. Max 4 digits integer.\n :param float surcharge: **Optional**. Sender surcharge, as assessed by originator. It must be the same currency and\n format as defined by **sender_currency_code**. Float 12 digits, max 3 fractions.\n :param string cavv: **Optional**. Cardholder Authentication Verification Value (CAVV), generated by ACS.\n Hexbin string, max 40 characters.\n :param str cardCvv2Value: **Optional**. Card CVV2 value for **sender_pan**. 3-4 characters string.\n :param float foreignExchangeFeeTransaction: Exchange fee on top of Visa exchange rate. Must be in the same\n currency and format as **amount**. Float 12 digits, max 3 fractions.\n :param MagneticStripeData magneticStripeData: **Optional**. \n Instance of :func:`~pyvdp.visadirect.MagneticStripeData`.\n :param PointOfServiceDataModel pointOfServiceData: **Conditional**. \n Instance of :func:`~pyvdp.visadirect.PointOfServiceDataModel`.\n Required for CardPresent transactions.\n :param PointOfServiceCapability: pointOfServiceCapability: **Conditional**. \n Instance of :func:`~pyvdp.visadirect.PointOfServiceCapabilityModel`.\n Required for CardPresent transactions.\n :param PinData pinData: **Optional**. Instance of :func:`~pyvdp.visadirect.PinData`.\n :param str feeProgramIndicator: **Optional**. You probably don't need it.\n :param str merchantPseudoAbaNumber: **Optional**. Unique ID for originator when transaction is sent via PPGS.\n 9 characters string.\n :param str sharingGroupCode: **Optional**. Used by PPG participants to specify network access priority.\n See `Sharing Group Code `_\n :param MerchantVerificationValueModel merchantVerificationValue: **Optional**. \n Instance of :func:`~pyvdp.visadirect.MerchantVerificationValueModel`.\n :param bool multi: **Conditional**. If True, this transaction is a part of batch. \n See :func:`~pyvdp.visadirect.fundstransfer.MultiPullFundsTransactionsModel`\n\n **Request:**\n \n .. code:: json\n\n {\n \"acquirerCountryCode\": 840,\n \"acquiringBin\": 408999,\n \"amount\": 124.02,\n \"businessApplicationId\": \"AA\",\n \"cardAcceptor\": {\n \"address\": {\n \"country\": \"USA\",\n \"county\": \"San Mateo\",\n \"state\": \"CA\",\n \"zipCode\": \"94404\"\n },\n \"idCode\": \"ABCD1234ABCD123\",\n \"name\": \"Visa Inc. USA-Foster City\",\n \"terminalId\": \"ABCD1234\"\n },\n \"cavv\": \"0700100038238906000013405823891061668252\",\n \"foreignExchangeFeeTransaction\": \"11.99\",\n \"localTransactionDateTime\": \"2017-03-17T08:20:42\",\n \"retrievalReferenceNumber\": \"330000550000\",\n \"senderCardExpiryDate\": \"2015-10\",\n \"senderCurrencyCode\": \"USD\",\n \"senderPrimaryAccountNumber\": \"4895142232120006\",\n \"surcharge\": \"11.99\",\n \"systemsTraceAuditNumber\": \"451001\"\n }\n\n **Response:**\n \n .. code:: json\n \n {\n \"transactionIdentifier\": 587010322176104,\n \"actionCode\": \"00\",\n \"approvalCode\": \"98765X\",\n \"responseCode\": \"5\",\n \"transmissionDateTime\": \"2017-04-20T04:41:12.000Z\",\n \"cavvResultCode\": \"8\"\n } \n \"\"\"\n ATTRS = [\n 'acquiringBin',\n 'acquirerCountryCode',\n 'amount',\n 'senderPrimaryAccountNumber',\n 'senderCardExpiryDate',\n 'senderCurrencyCode',\n 'businessApplicationId',\n 'cardAcceptor',\n 'cavv',\n 'surcharge',\n 'cardCvv2Value',\n 'foreignExchangeFeeTransaction',\n 'merchantCategoryCode',\n 'magneticStripeData',\n 'pointOfServiceData',\n 'pointOfServiceCapability',\n 'pinData',\n 'feeProgramIndicator',\n 'merchantPseudoAbaNumber',\n 'sharingGroupCode',\n 'merchantVerificationValue'\n ]\n\n def __init__(self, **kwargs):\n super(PullFundsTransactionsModel, self).__init__(**kwargs)\n for attr, value in kwargs.items():\n if attr in self.ATTRS and value:\n self.__setattr__(attr, value)\n\n\nclass MultiPullFundsTransactionsModel(VisaDirectTransactionBatchModel):\n \"\"\"VisaDirect FundsTransfer MultiPullFunds data object model.\n\n It is container object, which incorporate PullFundsTransactionsModel objects under the same acquirer\n credentials.\n \n .. note::\n \n When instance of PullFundsTransactionsModel incorporated in MultiPullFundsTransactionsModel, \n attributes `acquirerBin`, `acquiringCountryCode` and `businessApplicationId` are migrating from \n PullFundsTransactionsModel to MultiPullFundsTransactionsModel level. \n\n :param int acquiringBin: **Required**. Bank identification number (BIN) for VisaDirect acquiring. 6-11 digits\n integer.\n :param int acquirerCountryCode: **Required**. \n `ISO country code `_ for acquiring institution.\n :param str businessApplicationId: **Required**. `Program business application type \n `_. 2 characters string.\n :param list request: **Required**. List of :func:`~pyvdp.visadirect.fundstransfer.PullFundsTransactionsModel`\n objects. \n\n **Request:**\n \n .. code:: json\n\n {\n \"acquirerCountryCode\": \"608\",\n \"acquiringBin\": \"408999\",\n \"businessApplicationId\": \"AA\",\n \"localTransactionDateTime\": \"2017-03-17T09:11:08\",\n \"merchantCategoryCode\": \"6012\",\n \"request\": [\n {\n \"amount\": \"100.00\",\n \"cardAcceptor\": {\n \"address\": {\n \"country\": \"USA\",\n \"county\": \"00\",\n \"state\": \"CA\",\n \"zipCode\": \"94454\"\n },\n \"idCode\": \"5678\",\n \"name\": \"Mr Smith\",\n \"terminalId\": \"1234\"\n },\n \"cavv\": \"0700020718799100000002980179911000000000\",\n \"localTransactionDateTime\": \"2017-03-17T09:11:08\",\n \"retrievalReferenceNumber\": \"401010101011\",\n \"senderCardExpiryDate\": \"2020-12\",\n \"senderCurrencyCode\": \"USD\",\n \"senderPrimaryAccountNumber\": \"4895140000066666\",\n \"systemsTraceAuditNumber\": \"101011\"\n },\n {\n \"amount\": \"100.00\",\n \"cardAcceptor\": {\n \"address\": {\n \"country\": \"USA\",\n \"county\": \"00\",\n \"state\": \"CA\",\n \"zipCode\": \"94454\"\n },\n \"idCode\": \"5678\",\n \"name\": \"Mr Smith\",\n \"terminalId\": \"1234\"\n },\n \"cavv\": \"0700020718799100000002980179911000000000\",\n \"localTransactionDateTime\": \"2017-03-17T09:11:08\",\n \"retrievalReferenceNumber\": \"401010101011\",\n \"senderCardExpiryDate\": \"2020-12\",\n \"senderCurrencyCode\": \"USD\",\n \"senderPrimaryAccountNumber\": \"4895140000066666\",\n \"systemsTraceAuditNumber\": \"101011\"\n }\n ]\n }\n \n **Response:**\n \n .. code:: text\n \n \"1492665372_866_68_l73c002_VDP_ARM\"\n \n \"\"\"\n ATTRS = [\n 'acquiringBin',\n 'acquirerCountryCode',\n 'businessApplicationId',\n 'request'\n ]\n\n def __init__(self, **kwargs):\n super(MultiPullFundsTransactionsModel, self).__init__(request=kwargs['request'])\n for attr, value in kwargs.items():\n if attr in self.ATTRS and value:\n self.__setattr__(attr, value)\n\n\nclass PushFundsTransactionsModel(VisaDirectTransactionModel):\n \"\"\"VisaDirect FundsTransfer PushFundsTransactions data object model.\n\n :param int systemsTraceAuditNumber: **Required**. Systems trace audit number. 6 digits integer.\n :param int acquiringBin: **Required**. Bank identification number (BIN) for VisaDirect acquiring.\n 6-11 digits integer.\n :param int acquirerCountryCode: **Required**. \n `ISO country code `_ for acquiring institution.\n :param str transactionCurrencyCode: **Required**. \n `ISO currency code `_.\n Recommended to use value from :func:`~pyvdp.paai.fundstransferattinq.cardattributes.fundstransferinquiry.send`\n unless prohibited by local law. 3 characters string.\n :param str recipientPrimaryAccountNumber: **Required**. Recipient primary account number (PAN). \n 13-19 characters string.\n :param float amount: **Required**. Transaction amount. 12 digits, 3 fractions.\n :param businessApplicationId: **Required**. \n `Business application type `_ for \n VisaNet processing. 2 characters string.\n :param CardAcceptorModel cardAcceptor: **Required**. Instance of :func:`~pyvdp.visadirect.CardAcceptorModel`.\n :param str senderReference: **Conditional**. Required, if transaction is money transfer, pre-paid load, credit card\n bill pay and if sender is funding with a non financial instrument (cash). Required if funds disbursement.\n Required if **senderAccountNumber** is not set. Max 16 characters string.\n :param str senderAccountNumber: **Conditional**. If the transaction is a money transfer, pre-paid load, or\n credit card bill pay, and if the sender intends to fund the transaction with a financial instrument (for\n example, debit card), this field is required and must contain the sender's account number. If the transaction\n is a funds disbursement, the field is not required. Max 34 characters string.\n :param str senderAddress: **Conditional**. Sender address. Max 35 characters string.\n :param str senderCountryCode: **Conditional**. \n Sender `ISO country code `_.\n Required for cross-border and US domestic money transfers. 2-3 characters string.\n :param str senderName: **Conditional**. Required for cross-border and US domestic money transfers. Max 30\n characters string.\n :param str senderCity: **Conditional**. Required for cross-border and US domestic money transfers. Max 25\n characters string.\n :param str senderStateCode: **Conditional**. Required if **senderCountryCode** is 124(CAN) or 840(USA). 2 characters\n string.\n :param str recipientName: **Conditional**. Required for cross-border. Max 30 characters string.\n :param int merchantCategoryCode: **Conditional**. Merchant category code. Overrides the one provided with \n onboarding data. Required if not provided during onboarding. 4 digits integer.\n :param int transactionIdentifier: **Conditional**. VisaNet transaction ID. Provide if OCT preceeded by AFT.\n Should be populated with value, returned with AFT. 15 digits integer.\n :param str sourceOfFundsCode: **Conditional**. \n Refer to `sourceOfFundsCode `_ codes\n :param str recipientCardExpiryDate: **Optional**. Recipient card expiration for **recipient_pan**, YYYY-MM.\n :param str accountType: **Optional**. Used to define account type of the sender PAN. Default '00' (Not applicable).\n :param str feeProgramIndicator: **Optional**.\n :param str senderDateOfBirth: **Optional**. Sender's date of birth, YYYY-MM-DD.\n :param PointOfServiceDataModel pointOfServiceData: **Conditional**. \n Instance of :func:`~pyvdp.visadirect.PointOfServiceDataModel`. Required for CardPresent transactions.\n :param float surcharge: **Optional**. Sender's surcharge as assessed by originator. Must be in the same format\n and currency as **amount**. 12 digits, 3 fractions float.\n :param str merchantPseudoAbaNumber: **Optional**. Uniquely identifies originator with PPGS. 9 characters string.\n :param str sharingGroupCode: **Optional**. Used by PPG participants to specify network priority. 30 characters\n string.\n :param MerchantVerificationValueModel merchantVerificationValue: **Optional**. \n Instance of :func:`~pyvdp.visadirect.MerchantVerificationValueModel`.\n\n **Request:**\n \n .. code:: json\n\n {\n \"acquirerCountryCode\": \"840\",\n \"acquiringBin\": \"408999\",\n \"amount\": \"124.05\",\n \"businessApplicationId\": \"AA\",\n \"cardAcceptor\": {\n \"address\": {\n \"country\": \"USA\",\n \"county\": \"San Mateo\",\n \"state\": \"CA\",\n \"zipCode\": \"94404\"\n },\n \"idCode\": \"CA-IDCode-77765\",\n \"name\": \"Visa Inc. USA-Foster City\",\n \"terminalId\": \"TID-9999\"\n },\n \"localTransactionDateTime\": \"2017-03-17T09:01:14\",\n \"merchantCategoryCode\": \"6012\",\n \"pointOfServiceData\": {\n \"motoECIIndicator\": \"0\",\n \"panEntryMode\": \"90\",\n \"posConditionCode\": \"00\"\n },\n \"recipientName\": \"rohan\",\n \"recipientPrimaryAccountNumber\": \"4957030420210462\",\n \"retrievalReferenceNumber\": \"412770451018\",\n \"senderAccountNumber\": \"4957030420210454\",\n \"senderAddress\": \"901 Metro Center Blvd\",\n \"senderCity\": \"Foster City\",\n \"senderCountryCode\": \"124\",\n \"senderName\": \"Mohammed Qasim\",\n \"senderReference\": \"\",\n \"senderStateCode\": \"CA\",\n \"sourceOfFundsCode\": \"05\",\n \"systemsTraceAuditNumber\": \"451018\",\n \"transactionCurrencyCode\": \"USD\",\n \"transactionIdentifier\": \"381228649430015\"\n }\n \n **Response:**\n \n .. code:: json\n \n {\n \"transactionIdentifier\": 587010322176105,\n \"actionCode\": \"00\",\n \"approvalCode\": \"21324K\",\n \"responseCode\": \"5\",\n \"transmissionDateTime\": \"2017-04-21T03:47:49.000Z\"\n } \n \"\"\"\n ATTRS = [\n 'amount',\n 'acquiringBin',\n 'acquirerCountryCode',\n 'transactionCurrencyCode',\n 'recipientPrimaryAccountNumber',\n 'businessApplicationId',\n 'cardAcceptor',\n 'senderReference',\n 'senderAccountNumber',\n 'senderAddress',\n 'senderCountryCode',\n 'senderName',\n 'senderCity',\n 'senderStateCode',\n 'recipientName',\n 'merchantCategoryCode',\n 'transactionIdentifier',\n 'sourceOfFundsCode',\n 'recipientCardExpiryDate',\n 'accountType',\n 'feeProgramIndicator',\n 'senderDateOfBirth',\n 'pointOfServiceData',\n 'surcharge',\n 'merchantPseudoAbaNumber',\n 'sharingGroupCode',\n 'merchantVerificationValue'\n ]\n\n def __init__(self, **kwargs):\n super(PushFundsTransactionsModel, self).__init__(**kwargs)\n for attr, value in kwargs.items():\n if attr in self.ATTRS and value:\n self.__setattr__(attr, value)\n\n\nclass MultiPushFundsTransactionsModel(VisaDirectTransactionBatchModel):\n \"\"\"VisaDirect FundsTransfer MultiPushFundsTransactions data object model.\n\n It is container object, which incorporate PushFundsTransactionsModel objects under the same acquirer\n credentials. \n \n .. note::\n \n When instance of PushFundsTransactionsModel incorporated in MultiPushFundsTransactionsModel, attributes \n `acquirerBin`, `acquiringCountryCode` and `businessApplicationId` are migrating from \n PushFundsTransactionsModel to MultiPushFundsTransactionsModel level.\n\n :param int acquiringBin: **Required**. Bank identification number (BIN) for VisaDirect acquiring. 6-11 digits\n integer.\n :param int acquirerCountryCode: **Required**. \n `ISO country code `_ for acquiring institution.\n :param str businessApplicationId: **Required**. \n `Program business application type `_.\n 2 characters string.\n :param list request: **Required**. List of :func:`~pyvdp.visadirect.fundstransfer.PushFundsTransactionsModel`\n instances. \n\n **Request:**\n \n .. code:: json\n\n {\n \"acquirerCountryCode\": \"840\",\n \"acquiringBin\": \"408999\",\n \"businessApplicationId\": \"AA\",\n \"localTransactionDateTime\": \"2017-03-17T09:12:46\",\n \"merchantCategoryCode\": \"6012\",\n \"request\": [\n {\n \"amount\": \"100.00\",\n \"cardAcceptor\": {\n \"address\": {\n \"country\": \"USA\",\n \"county\": \"00\",\n \"state\": \"CA\",\n \"zipCode\": \"94454\"\n },\n \"idCode\": \"5678\",\n \"name\": \"Mr Smith\",\n \"terminalId\": \"1234\"\n },\n \"feeProgramIndicator\": \"123\",\n \"localTransactionDateTime\": \"2017-03-17T09:12:46\",\n \"recipientName\": \"Akhila\",\n \"recipientPrimaryAccountNumber\": \"4957030420210454\",\n \"retrievalReferenceNumber\": \"401010101011\",\n \"senderAccountNumber\": \"4005520000011126\",\n \"senderAddress\": \"My Address\",\n \"senderCity\": \"My City\",\n \"senderCountryCode\": \"USA\",\n \"senderName\": \"Mr Name\",\n \"senderReference\": \"\",\n \"senderStateCode\": \"CA\",\n \"sourceOfFundsCode\": \"01\",\n \"systemsTraceAuditNumber\": \"101011\",\n \"transactionCurrencyCode\": \"USD\",\n \"transactionIdentifier\": \"234234234234234\"\n },\n { ... }\n ]\n }\n \n **Response:**\n \n .. code:: text\n \n \"1492746769_916_89_l73c001_VDP_ARM\"\n \n \"\"\"\n ATTRS = [\n 'acquiringBin',\n 'acquirerCountryCode',\n 'businessApplicationId',\n 'request'\n ]\n\n def __init__(self, **kwargs):\n super(MultiPushFundsTransactionsModel, self).__init__(request=kwargs['request'])\n for attr, value in kwargs.items():\n if attr in self.ATTRS and value:\n self.__setattr__(attr, value)\n\n\nclass ReverseFundsTransactionsModel(PullFundsTransactionsModel):\n \"\"\"VisaDirect FundsTransfer ReverseFundsTransactions data object model.\n\n :param int systemsTraceAuditNumber: **Required**. Systems trace audit number. 6 digits integer.\n :param int transactionIdentifier: **Required**. VisaNet transaction ID. This field must be populated with\n `transactionIdentifier` from initial AFT.\n :param int acquiringBin: **Required**. Bank identification number (BIN) for VisaDirect acquiring.\n 6-11 digits integer.\n :param int acquirerCountryCode: **Required**. \n `ISO country code `_ for acquiring institution.\n :param str senderPrimaryAccountNumber: **Required**. Primary account number of the sender. 13-19 characters string.\n :param str senderCardExpiryDate: **Optional**. Sender card expiration date, YYYY-MM.\n :param str senderCurrencyCode: **Required**. \n `ISO currency code `_. 3 characters string.\n :param float amount: **Required**. Transaction amount. 12 digits, 3 fractions.\n :param float surcharge: **Optional**. Sender's surcharge as assessed by originator. Must be in the same format\n and currency as **amount**. 12 digits, 3 fractions float.\n :param float foreignExchangeFeeTransaction: **Optional**. Foreign exchange markup fee, on top of VisaNet\n exchange rate. 12 digist, 3 fractions float.\n :param OriginalDataElementsModel originalDataElements: **Required**. \n Instance of :func:`~pyvdp.visadirect.OriginalDataElementsModel`.\n :param CardAcceptorModel cardAcceptor: **Required**. Instance of :func:`~pyvdp.visadirect.CardAcceptorModel`.\n :param PointOfServiceDataModel pointOfServiceData: **Optional**. \n Instance of :func:`~pyvdp.visadirect.PointOfServiceDataModel`.\n :param PointOfServiceCapabilityModel pointOfServiceCapability: **Optional**. \n Instance of :func:`~pyvdp.visadirect.PointOfServiceCapabilityModel`.\n :param str feeProgramIndicator: **Optional**.\n :param str merchantPseudoAbaNumber: **Optional**. Uniquely identifies originator with PPGS. 9 characters string.\n :param str sharingGroupCode: **Optional**. Used by PPG participants to specify network priority. 30 characters\n string.\n :param int networkId: **Optional**. Code, that specifies network for transmission. \n Refer to `Network ID `_. 2 digits \n integer.\n :param MerchantVerificationValueModel merchantVerificationValue: **Optional**. \n Instance of :func:`~pyvdp.visadirect.MerchantVerificationValueModel`.\n\n **Request:**\n \n .. code:: json\n \n {\n \"acquirerCountryCode\": \"608\",\n \"acquiringBin\": \"408999\",\n \"amount\": \"24.01\",\n \"cardAcceptor\": {\n \"address\": {\n \"country\": \"USA\",\n \"county\": \"San Mateo\",\n \"state\": \"CA\",\n \"zipCode\": \"94404\"\n },\n \"idCode\": \"VMT200911026070\",\n \"name\": \"Visa Inc. USA-Foster City\",\n \"terminalId\": \"365539\"\n },\n \"localTransactionDateTime\": \"2017-04-21T03:53:39\",\n \"originalDataElements\": {\n \"acquiringBin\": \"408999\",\n \"approvalCode\": \"20304B\",\n \"systemsTraceAuditNumber\": \"897825\",\n \"transmissionDateTime\": \"2017-04-21T03:53:39\"\n },\n \"pointOfServiceCapability\": {\n \"posTerminalEntryCapability\": \"2\",\n \"posTerminalType\": \"4\"\n },\n \"pointOfServiceData\": {\n \"motoECIIndicator\": \"0\",\n \"panEntryMode\": \"90\",\n \"posConditionCode\": \"00\"\n },\n \"retrievalReferenceNumber\": \"330000550000\",\n \"senderCardExpiryDate\": \"2015-10\",\n \"senderCurrencyCode\": \"USD\",\n \"senderPrimaryAccountNumber\": \"4895100000055127\",\n \"systemsTraceAuditNumber\": \"451050\",\n \"transactionIdentifier\": \"381228649430011\"\n } \n\n **Response:**\n \n .. code:: json\n \n {\n \"transactionIdentifier\": 587010322176103,\n \"approvalCode\": \"23456M\",\n \"actionCode\": \"00\",\n \"responseCode\": \"5\",\n \"transmissionDateTime\": \"2017-04-21T03:54:36.000Z\"\n } \n \"\"\"\n ATTRS = [\n 'transactionIdentifier',\n 'acquiringBin',\n 'acquirerCountryCode',\n 'senderPrimaryAccountNumber',\n 'senderCardExpiryDate',\n 'senderCurrencyCode',\n 'amount',\n 'surcharge',\n 'foreignExchangeFeeTransaction',\n 'originalDataElements',\n 'cardAcceptor',\n 'pointOfServiceData',\n 'pointOfServiceCapability',\n 'feeProgramIndicator',\n 'merchantPseudoAbaNumber',\n 'sharingGroupCode',\n 'networkId',\n 'merchantVerificationValue'\n ]\n\n def __init__(self, **kwargs):\n super(ReverseFundsTransactionsModel, self).__init__(**kwargs)\n for attr, value in kwargs.items():\n if attr in self.ATTRS and value:\n self.__setattr__(attr, value)\n\n\nclass MultiReverseFundsTransactionsModel(MultiPullFundsTransactionsModel):\n \"\"\"VisaDirect FundsTransfer MultiReverseFundsTransactions data object model.\n\n It is container object, which incorporate ReverseFundsTransactionsModel objects under the same acquirer credentials.\n\n :param int acquiringBin: **Required**. Bank identification number (BIN) for VisaDirect acquiring. 6-11 digits\n integer.\n :param int acquirerCountryCode: **Required**. \n `ISO country code `_ for acquiring institution.\n :param list request: **Required**. List of :func:`~pyvdp.visadirect.fundstransfer.ReverseFundsTransactionsModel`\n instances. \n \n **Request:**\n \n .. code:: json\n\n {\n \"acquirerCountryCode\": \"840\",\n \"acquiringBin\": \"408999\",\n \"localTransactionDateTime\": \"2017-04-21T03:56:17\",\n \"request\": [\n {\n \"amount\": \"100.00\",\n \"cardAcceptor\": {\n \"address\": {\n \"country\": \"USA\",\n \"county\": \"00\",\n \"state\": \"CA\",\n \"zipCode\": \"94454\"\n },\n \"idCode\": \"5678\",\n \"name\": \"Mr Smith\",\n \"terminalId\": \"1234\"\n },\n \"localTransactionDateTime\": \"2017-04-21T03:56:17\",\n \"originalDataElements\": {\n \"acquiringBin\": \"408999\",\n \"approvalCode\": \"1ABCDE\",\n \"systemsTraceAuditNumber\": \"228112\",\n \"transmissionDateTime\": \"2017-04-21T03:56:17\"\n },\n \"retrievalReferenceNumber\": \"401010101011\",\n \"senderCardExpiryDate\": \"2020-12\",\n \"senderCurrencyCode\": \"USD\",\n \"senderPrimaryAccountNumber\": \"4485810000000131\",\n \"systemsTraceAuditNumber\": \"101011\",\n \"transactionIdentifier\": \"101010101010\"\n },\n { ... }\n ]\n }\n \n **Response:**\n \n .. code:: text\n \n \"1492747084_010_78_l73c037_VDP_ARM\"\n \n \"\"\"\n ATTRS = [\n 'acquiringBin',\n 'acquirerCountryCode',\n 'request'\n ]\n\n def __init__(self, **kwargs):\n super(MultiReverseFundsTransactionsModel, self).__init__(request=kwargs['request'])\n for attr, value in kwargs.items():\n if attr in self.ATTRS and value:\n self.__setattr__(attr, value)\n","sub_path":"pyvdp/visadirect/fundstransfer/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":28972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"78605560","text":"from __future__ import print_function\n\nimport sys\nimport os\nimport time\n\nimport numpy as np\nnp.random.seed(1234) # for reproducibility?\n\n# specifying the gpu to use\n# import theano.sandbox.cuda\n# theano.sandbox.cuda.use('gpu1') \nimport theano\nimport theano.tensor as T\n\nimport lasagne\n\nimport cPickle as pickle\nimport gzip\nimport glob\nfrom scipy import misc\n\nimport binary_net\nimport cnv\n\nfrom pylearn2.datasets.zca_dataset import ZCA_Dataset \nfrom pylearn2.datasets.cifar10 import CIFAR10 \nfrom pylearn2.utils import serial\n\nfrom collections import OrderedDict\n\ndef loaddata():\n '''\n Loads the NIST SD19 Character dataset, which must can be downloaded from https://www.nist.gov/srd/nist-special-database-19\n Assumes dataset is downloaded in the current directory (..../bnn/src/training) and ordered by class.\n '''\n\n #classes = [\"30\", \"31\", \"32\", \"33\", \"34\", \"35\", \"36\", \"37\", \"38\", \"39\", #Digits\n#\"41\", \"42\", \"43\", \"44\", \"45\", \"46\", \"47\", \"48\", \"49\", \"4a\", \"4b\", \"4c\", \"4d\", \"4e\", \"4f\", \"50\", \"51\", \"52\", \"53\", \"54\", \"55\", \"56\", \"57\", \"58\", \"59\", \"5a\", #Upper case\n#\"61\", \"62\", \"63\", \"64\", \"65\", \"66\", \"67\", \"68\", \"69\", \"6a\", \"6b\", \"6c\", \"6d\", \"6e\", \"6f\", \"70\", \"71\", \"72\", \"73\", \"74\", \"75\", \"76\", \"77\", \"78\", \"79\", \"7a\"] #Lower case\n path = \"/home/cp612sh/dataset/train_set\"\n classes = os.listdir(path)\n #classes = [\"daisy\", \"dandelion\",\"roses\", \"sunflowers\", \"tulips\"]\n\n NumImagesPerClassTrain = 1500\n NumImagesPerClassValidation = 400\n NumImagesPerClassTest = 100\n\n # NumImagesPerClassTrain = 300\n # NumImagesPerClassTest = 100\n # NumImagesPerClassValidation = 50\n\n pngTrain = []\n pngTest = []\n pngValidation = []\n labelsTrain = []\n labelsTest = []\n labelsValidation = []\n\n for glyph in classes:\n i = 0\n print(\"Loading Glyph code: \"+glyph)\n for image_path in glob.glob( path + \"/\" + glyph+\"/*.jpg\"):\n #for image_path in glob.glob(\"./by_class/\"+glyph+\"/train_\"+glyph+\"/*.png\"):\n if (i < NumImagesPerClassTrain):\n pic_train = misc.imread(image_path)\n picture_train = misc.imresize(pic_train, (32,32))\n #misc.imshow(picture_train)\n pngTrain.append(picture_train) \n labelsTrain.append(classes.index(glyph))\n i=i+1\n elif(i < (NumImagesPerClassTrain + NumImagesPerClassValidation)):\n pic_valid = misc.imread(image_path)\n picture_valid = misc.imresize(pic_valid, (32,32))\n pngValidation.append(picture_valid) \n labelsValidation.append(classes.index(glyph))\n i=i+1\n elif(i < (NumImagesPerClassTrain + NumImagesPerClassValidation + NumImagesPerClassTest)):\n pic_test = misc.imread(image_path)\n picture_test = misc.imresize(pic_test, (32,32))\n pngTest.append(picture_test) \n labelsTest.append(classes.index(glyph))\n i=i+1\n else:\n break\n # k = 0\n # for image_path in glob.glob(\"/home/cp612sh/wsy/BNN-PYNQ-master/dataset/test/\"+glyph+\"/*.jpg\"):\n # #for image_path in glob.glob(\"./by_class/\"+glyph+\"/hsf_4/*.png\"):\n # if (k < NumImagesPerClassTest):\n # pic_test = misc.imread(image_path)\n # picture_test = misc.imresize(pic_test, (32,32))\n # pngTest.append(picture_test) \n # labelsTest.append(classes.index(glyph))\n # k=k+1\n # else:\n # break\n\n pngTrain = np.reshape(np.subtract(np.multiply(2./255.,pngTrain),1.),(-1,3,32,32))\n pngValidation = np.reshape(np.subtract(np.multiply(2./255.,pngValidation),1.),(-1,3,32,32))\n pngTest = np.reshape(np.subtract(np.multiply(2./255.,pngTest),1.),(-1,3,32,32))\n\n \n return (pngTrain, labelsTrain, pngTest, labelsTest, pngValidation, labelsValidation)\n\n \n\n\nif __name__ == \"__main__\":\n \n learning_parameters = OrderedDict()\n # BN parameters\n batch_size = 50\n print(\"batch_size = \"+str(batch_size))\n # alpha is the exponential moving average factor\n learning_parameters.alpha = .1\n print(\"alpha = \"+str(learning_parameters.alpha))\n learning_parameters.epsilon = 1e-4\n print(\"epsilon = \"+str(learning_parameters.epsilon))\n \n # W_LR_scale = 1. \n learning_parameters.W_LR_scale = \"Glorot\" # \"Glorot\" means we are using the coefficients from Glorot's paper\n print(\"W_LR_scale = \"+str(learning_parameters.W_LR_scale))\n \n # Training parameters\n num_epochs = 500\n print(\"num_epochs = \"+str(num_epochs))\n \n # Decaying LR \n LR_start = 0.001\n print(\"LR_start = \"+str(LR_start))\n LR_fin = 0.0000003\n print(\"LR_fin = \"+str(LR_fin))\n LR_decay = (LR_fin/LR_start)**(1./num_epochs)\n print(\"LR_decay = \"+str(LR_decay))\n # BTW, LR decay might good for the BN moving average...\n \n save_path = \"clothes_parameters.npz\"\n print(\"save_path = \"+str(save_path))\n \n shuffle_parts = 1\n print(\"shuffle_parts = \"+str(shuffle_parts))\n \n print('Loading clothes dataset...')\n train_setX, train_sety, test_setX, test_sety, valid_setX, valid_sety = loaddata()\n \n # bc01 format\n # Inputs in the range [-1,+1]\n # print(\"Inputs in the range [-1,+1]\")\n train_sety = np.hstack(train_sety)\n valid_sety = np.hstack(valid_sety)\n test_sety = np.hstack(test_sety)\n \n # Onehot the targets\n train_sety = np.float32(np.eye(30)[train_sety]) \n valid_sety = np.float32(np.eye(30)[valid_sety])\n test_sety = np.float32(np.eye(30)[test_sety])\n \n # for hinge loss\n train_sety = 2* train_sety - 1.\n valid_sety = 2* valid_sety - 1.\n test_sety = 2* test_sety - 1.\n\n print('Building the CNN...') \n \n # Prepare Theano variables for inputs and targets\n input = T.tensor4('inputs')\n target = T.matrix('targets')\n LR = T.scalar('LR', dtype=theano.config.floatX)\n\n cnn = cnv.genCnv(input, 30, learning_parameters)\n\n train_output = lasagne.layers.get_output(cnn, deterministic=False)\n \n # squared hinge loss\n loss = T.mean(T.sqr(T.maximum(0.,1.-target*train_output)))\n \n # W updates\n W = lasagne.layers.get_all_params(cnn, binary=True)\n W_grads = binary_net.compute_grads(loss,cnn)\n updates = lasagne.updates.adam(loss_or_grads=W_grads, params=W, learning_rate=LR)\n updates = binary_net.clipping_scaling(updates,cnn)\n \n # other parameters updates\n params = lasagne.layers.get_all_params(cnn, trainable=True, binary=False)\n updates = OrderedDict(updates.items() + lasagne.updates.adam(loss_or_grads=loss, params=params, learning_rate=LR).items())\n\n test_output = lasagne.layers.get_output(cnn, deterministic=True)\n test_loss = T.mean(T.sqr(T.maximum(0.,1.-target*test_output)))\n test_err = T.mean(T.neq(T.argmax(test_output, axis=1), T.argmax(target, axis=1)),dtype=theano.config.floatX)\n \n # Compile a function performing a training step on a mini-batch (by giving the updates dictionary) \n # and returning the corresponding training loss:\n train_fn = theano.function([input, target, LR], loss, updates=updates)\n\n # Compile a second function computing the validation loss and accuracy:\n val_fn = theano.function([input, target], [test_loss, test_err])\n\n print('Training...')\n \n binary_net.train(\n train_fn,val_fn,\n cnn,\n batch_size,\n LR_start,LR_decay,\n num_epochs,\n train_setX,train_sety,\n valid_setX,valid_sety,\n test_setX,test_sety,\n save_path=save_path,\n shuffle_parts=shuffle_parts)\n","sub_path":"bnn/src/training/my_train.py","file_name":"my_train.py","file_ext":"py","file_size_in_byte":7672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482576630","text":"import functools\n\nfrom flask import current_app\nfrom flask import g\nfrom flask import session\n\nfrom info import constants\nfrom info.models import News, Category\n\n\ndef do_index_class(index):\n \"\"\"自定义过滤器,过滤点击排序html的class\"\"\"\n if index == 0:\n return \"first\"\n elif index == 1:\n return \"second\"\n elif index == 2:\n return \"third\"\n else:\n return \"\"\n\n\ndef user_login_data(f):\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n # 获取到当前登录用户的id\n user_id = session.get(\"user_id\")\n # 通过id获取到用户信息\n user = None\n if user_id:\n from info.models import User\n user = User.query.get(user_id)\n\n g.user = user\n return f(*args,**kwargs)\n return wrapper\n\n\ndef new_rank_list(f):\n @functools.wraps(f)\n def wrapper(*args,**kwargs):\n news_list = None\n try:\n news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)\n except Exception as e:\n current_app.logger.error(e)\n\n click_news_list = []\n for news in news_list if news_list else []:\n click_news_list.append(news.to_basic_dict())\n\n # 获取新闻分类数据\n categories = Category.query.all()\n # 定义列表保存分类数据\n categories_dicts = []\n for category in categories:\n # 拼接内容\n categories_dicts.append(category.to_dict())\n\n g.click_news_list = click_news_list\n return f(*args,**kwargs)\n return wrapper","sub_path":"info/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"614511374","text":"import os\nimport tool\n\ndef code_front(fop,dirPath):\n \"sss\"\n os.chdir(dirPath)\n output = os.popen('find . -name \"*.ts\" -or -name \"*.html\" -or -name \"*.css\"| xargs grep -v \"^$\" | wc -l')\n fop.write(\"iportal front code lines: \" + output.read())\n \ndef code_end(fop,dirPath):\n \"sss\"\n os.chdir(dirPath)\n output = os.popen('find . -name \"*.js\" | xargs grep -v \"^$\" | wc -l')\n fop.write(\"iportal end code lines: \" + output.read())\n \ndef code_end_unitTest(fop,dirPath):\n \"ssss\" \n os.chdir(dirPath)\n output = os.popen('find . -name \"*.scala\" | xargs grep -v \"^$\" | wc -l')\n fop.write(\"iportal end unit test lines: \" + output.read()) \n \ndef is_dir_exist(logger,strWorkSpace):\n flag = True\n infoStr = \"code_stat: code dir not exist = \"\n if (not os.path.exists(tool.get_som_front_code_ts(strWorkSpace))):\n logger.debug(infoStr + tool.get_som_front_code_ts(strWorkSpace))\n flag = False\n # if (not os.path.exists(tool.get_som_end_code_scala(strWorkSpace))):\n # logger.debug(infoStr + tool.get_som_end_code_scala(strWorkSpace))\n # flag = False\n # if (not os.path.exists(tool.get_som_end_code_unitTest(strWorkSpace))):\n # logger.debug(infoStr + tool.get_som_end_code_unitTest(strWorkSpace))\n # flag = False\n return flag \n \ndef code_Statistic(logger, versionDir):\n if(not is_dir_exist(logger,versionDir)):\n logger.debug(\"Error: code_stat end\")\n return\n \n if (os.path.isfile(\"code_stat.txt\")):\n logger.debug(\"rm code_stat.txt\")\n os.popen(\"rm -rf code_stat.txt\")\n \n fop = open('code_stat.txt', 'w+')\n logger.debug(\"-->front code stat\") \n code_front(fop,tool.get_som_front_code_ts(versionDir))\n logger.debug(\"<--front code stat\")\n \n # logger.debug(\"-->end code stat\")\n # code_end(fop,tool.get_som_end_code_scala(versionDir))\n # logger.debug(\"<--end code stat\")\n \n # logger.debug(\"-->end unit test code stat\")\n # code_end_unitTest(fop,tool.get_som_end_code_unitTest(versionDir))\n # logger.debug(\"<--end unit test code stat\")\n fop.close()\n\n \nif __name__ == '__main__':\n from logger import get_logger\n logger = get_logger('.')\n code_Statistic(logger, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))","sub_path":"grs-docker/code_stat.py","file_name":"code_stat.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"453124342","text":"# -*- codeing = utf-8 -*-\n# @Time:2021/2/20 17:24\n# @Author:谭洋\n# @File:opencv-io-test.py\n\nimport cv2\n\n\nimg=cv2.imread(\"img.jpg\") #读取一张图片\ncv2.imshow(\"input\",img) #打开一个窗口并且展示一张图片\ncv2.waitKey(1000) #窗口停留时间,参数表示停留时间,0一直打开\n\n\n\n","sub_path":"Opencv-python_Test/opencv-io-test/cvtest.py","file_name":"cvtest.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"592225226","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nimport io\n\n\n\ndef getdriver(url):\n\tdriver = webdriver.Chrome(\"E:/2345Downloads/chromedriver_win32/chromedriver.exe\")#创建Chrome浏览器驱动实例\n\tdriver.implicitly_wait(15)#设置隐式等待时间\n\tdriver.maximize_window()#全屏窗口\n\tdriver.get(url)\n\treturn driver\n\ndef getelement(driver,mode,address):#确定用户元素定位方式\n\tif mode == \"id\":\n\t\telement = driver.find_element_by_id(address)\n\telif mode == \"classname\":\n\t\telement = driver.find_element_by_class_name(address)\n\telif mode == \"name\":\n\t\telement = driver.find_element_by_name(address)\n\telif mode == \"tagname\":\n\t\telement = driver.find_element_by_tag_name(address)\n\telif mode == 'linktext':\n\t\telement = driver.find_element_by_link_text(address)\n\telif mode == 'partialtext':\n\t\telement = driver.find_element_by_partial_link_text(address)\n\telif mode == 'xpath':\n\t\telement = driver.find_element_by_xpath(address)\n\telif mode == 'css':\n\t\telement = driver.find_element_by_css_selector(address)\n\telse:\n\t\tprint (\"元素定位方式输入错误,请修改后重试!\" + str(mode))\n\treturn element\n\ndef getevent(driver,event,element,string,xpath):\n\tif event == \"click\":\n\t\telement.click()\n\telif event == \"sendkeys\":\n\t\telement.send_keys(string)\n\telif event == \"asserttest\":\n\t\tasserttest(driver,xpath,string)\n\telif event == \"infarme\":\n\t\tdriver.switch_to.frame(element)\n\telif event == 'clear':\n\t\telement.clear()\n\telif event == 'select':\n\t\tselect(element).select_by_visible_text(string)\n\telse:\n\t\tprint (\"操作方式输入错误,请按规范输入!\"+ str(event))\n\ndef getevents(event,driver,string,i):\n\tif event == 'quit':\n\t\tdriver.quit()\n\telif event == 'sleep':\n\t\ttime.sleep(int(string))\n\telif event == 'outfarme':\n\t\tdriver.switch_to.default_content()\n\telif event == 'screenshot':\n\t\tfilephoto = \"D:/\" + str(i) + \".png\"\n\t\tcapture(driver,filephoto)\n\telse:\n\t\tprint(\"操作方式输入错误,请按规范输入!\" + str(event))\n\ndef asserttest(driver,xpath,string):\n\ttry:\n\t\tassert driver.find_element_by_xpath(xpath).text == string\n\texcept AssertionError:\n\t\tprint (\"error!\")\n\n\ndef capture(driver,filephoto): #截取屏幕\n\tdriver.execute_script(\"\"\"\n\t\t (function () {\n\t\t var y = 0;\n\t\t var step = 100;\n\t\t window.scroll(0, 0);\n\t\t function f() {\n\t\t if (y < document.body.scrollHeight) {\n\t\t y += step;\n\t\t window.scroll(0, y);\n\t\t setTimeout(f, 50);\n\t\t } else {\n\t\t window.scroll(0, 0);\n\t\t document.title += \"scroll-done\";\n\t\t }\n\t\t }\n\t\t setTimeout(f, 1000);\n\t\t })();\n\t\t \"\"\")\n\tfor i in range(30):\n\t\tif \"scroll-done\" in driver.title:\n\t\t\tbreak\n\t\ttime.sleep(1)\n\tbeg = time.time()\n\tfor i in range(10):\n\t\tdriver.save_screenshot(filephoto)\n\tend = time.time()\n\tprint(\"截屏操作时间:\")\n\tprint(end - beg)\n\ndef tag_name(driver,event,string):#无论如何都找不到元素时,可以使用此方法\n\telements = driver.find_element_by_tag_name(event)\n\tfor i in elements:\n\t\tif i.text == string:\n\t\t\ti.click()\n\t\t\tbreak\n\treturn i","sub_path":"selenium_UI/test/common/selenium.py","file_name":"selenium.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"430508452","text":"import torch\nfrom ts.torch_handler.base_handler import BaseHandler\nimport io\n\n\nclass TextHandler(BaseHandler):\n\n def preprocess(self, data):\n \"\"\"\n Override to customize the pre-processing\n :param data: Python list of data items\n :return: input tensor on a device\n \"\"\"\n byte_data = io.BytesIO(data[0]['body'])\n tensor = torch.load(byte_data)\n byte_data.close()\n return tensor\n\n def handle(self, data, context):\n \"\"\"\n Entry point for default handler\n \"\"\"\n\n # It can be used for pre or post processing if needed as additional request\n # information is available in context\n self.context = context\n\n image_tensor = self.preprocess(data)\n data = self.inference(image_tensor)\n data = self.postprocess(data)\n return data\n\n def postprocess(self, data):\n \"\"\"\n Override to customize the post-processing\n :param data: Torch tensor, containing prediction output from the model\n :return: Python list\n \"\"\"\n buffer = io.BytesIO()\n torch.save(data, buffer)\n return_data = [buffer.getvalue()]\n return return_data\n","sub_path":"torchserve/text_handler.py","file_name":"text_handler.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"229444447","text":"from django.views.generic import TemplateView\nfrom braces.views import LoginRequiredMixin, MultiplePermissionsRequiredMixin\nfrom django.conf import settings\nfrom django.shortcuts import redirect\n# Create your views here.\n\n\n#------------------------------------ REPORTES --------------------------------------\n\nclass ReportesView(LoginRequiredMixin,\n MultiplePermissionsRequiredMixin,\n TemplateView):\n \"\"\"\n \"\"\"\n permissions = {\n \"all\": [\"usuarios.reportes.ver\"]\n }\n login_url = settings.LOGIN_URL\n template_name = 'reportes/lista.html'\n\n\n def get_context_data(self, **kwargs):\n kwargs['title'] = \"reportes\"\n kwargs['url_datatable'] = '/rest/v1.0/reportes/'\n return super(ReportesView,self).get_context_data(**kwargs)\n\n#------------------------------------------------------------------------------------","sub_path":"sican_2018/reportes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"97828848","text":"try:\n from PySide2 import QtCore\n from PySide2 import QtWidgets as QtGui\nexcept:\n try:\n from PySide import QtCore, QtGui\n except:\n from PyQt4 import QtCore, QtGui\n\n\nfrom dsk.base.lib.default_path import DefaultPath\nfrom dsk.base.resources import browser_signal as confsig\nfrom dsk.base.resources.browser_constant import CASH_SHOW_GEN\nfrom dsk.base.db_helper.db_cache import DbCache\nfrom dsk.base.lib.msg_arg import MsgAssetChange\n#from dsk.base.utils.msg_utils import MsgUtils as log\n\n\nclass AssetSelectCombo(QtGui.QComboBox):\n def __init__(self,parent):\n super(AssetSelectCombo,self).__init__(parent)\n self.filtertype = set()\n # a optional filter see set_filtering\n self._hasfiltering = None\n\n ############### APPLICATION SIGNAL \n def signalsDestroy(self,effectEditor):\n if effectEditor != None:\n self.__actionSignal(effectEditor.request_disconnect)\n\n def signalsCreate(self,effectEditor):\n if effectEditor != None:\n self.__actionSignal(effectEditor.request_connect)\n\n def __actionSignal(self,act):\n act(self,confsig.INIT_FIRST_TIME.name, False, self.initFirstTime)\n act(self,confsig.CHANGE_SHOW.name, False, self.refresh_show)\n act(self,confsig.CHANGE_ASSET.name, True, self.refresh_curasset)\n\n def connectLocalSignal(self):\n self.connect(self, QtCore.SIGNAL(\"activated(int)\"),self.selectassetchange)\n\n def disconnectLocalSignal(self):\n self.disconnect(self, QtCore.SIGNAL(\"activated(int)\"),self.selectassetchange)\n\n ###############\n def initFirstTime(self, msg):\n if self != msg.widgetFrom() and msg.isAppLevel() == False:\n return\n\n if self._hasfiltering != None:\n self.set_filter_type(self._hasfiltering.get_filter_list())\n self.init_asset(msg.getGroup())\n\n def set_filter_type(self,filterlist):\n if isinstance(filterlist,str):\n filterlist = [filterlist]\n self.filtertype = set(filterlist)\n\n def set_filtering(self, filterobject):\n self._hasfiltering = filterobject\n\n def init_asset(self,groupData):\n db = groupData.find(CASH_SHOW_GEN,justChild = True)\n self.disconnectLocalSignal()\n if isinstance(db,DbCache):\n self.clear()\n curshow = db.get_current_show_obj()\n if curshow == None:\n return\n curasset = curshow.get_current_asset()\n allasset = curshow.get_assets().getChildren()\n allassetname = [x.getName() for x in allasset]\n\n if len(self.filtertype) == 0:\n for i,n in enumerate(allassetname):\n self.addItem(self.tr(str(n)))\n if curasset == n:\n self.setCurrentIndex(i) # because of the blank\n else:\n allassetype = [x.get_asset_type() for x in allasset]\n index = 0\n for i,n in enumerate(allassetname):\n if allassetype[i] in self.filtertype:\n self.addItem(self.tr(str(n)))\n if curasset == n:\n self.setCurrentIndex(index) # because of the blank\n index += 1\n\n self.connectLocalSignal()\n\n def refresh_show(self,msg):\n if msg.succeed():\n self.init_asset(msg.getGroup())\n\n def refresh_curasset(self,msg):\n if msg.succeed() and msg.widgetFrom() != self:\n self.init_asset(msg.getGroup())\n\n def selectassetchange(self):\n item = self.currentText()\n if item:\n msg = MsgAssetChange(self,None,str(item))\n self.emit(QtCore.SIGNAL(confsig.CHANGE_ASSET.signature),msg)\n\n # direct query\n def get_data(self):\n return str(self.currentText())","sub_path":"dsk/base/widgets/asset_select_combo.py","file_name":"asset_select_combo.py","file_ext":"py","file_size_in_byte":3825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"414741523","text":"import re\r\nimport os\r\nfrom flask import Blueprint,request,render_template,redirect,url_for,jsonify,session\r\n\r\nfrom App.models import db,User\r\nfrom utils import status_code\r\nfrom utils.setting import UPLOAD_DIR\r\nfrom utils.functions import is_login\r\n\r\nuser_blueprint = Blueprint('user',__name__)\r\n\r\n@user_blueprint.route('/')\r\ndef hello():\r\n return 'hello'\r\n\r\n@user_blueprint.route('/create_db/')\r\n@is_login\r\ndef create_db():\r\n db.create_all()\r\n return '创建成功'\r\n\r\n@user_blueprint.route('/register/',methods=['GET'])\r\ndef register_g():\r\n return render_template('register.html')\r\n\r\n@user_blueprint.route('/register/',methods=['POST'])\r\ndef register_p():\r\n mobile = request.form.get('mobile')\r\n pwd1 = request.form.get('password1')\r\n pwd2 = request.form.get('password2')\r\n # 验证数据填写的完整性\r\n if not all([mobile,pwd1,pwd2]):\r\n return jsonify(status_code.USER_REGISTER_DATA_NOT_NULL)\r\n # 验证手机号码的正确性\r\n if not re.match(r'^1[34578]\\d{9}$',mobile):\r\n return jsonify(status_code.USER_REGISTER_MOBILE_ERROR)\r\n # 验证密码\r\n if pwd1 != pwd2:\r\n return jsonify(status_code.USER_REGISTER_PASSWORD_IS_NOT_VALID)\r\n # 保存用户数据\r\n user = User.query.filter_by(phone=mobile).first()\r\n if user:\r\n return jsonify(status_code.USER_REGISTER_MOBILE_EXSITS)\r\n else:\r\n user = User()\r\n user.phone = mobile\r\n user.password = pwd1\r\n user.name = mobile\r\n user.add_update()\r\n return jsonify(status_code.MSG_OK)\r\n\r\n@user_blueprint.route('/login/',methods=['GET'])\r\ndef login_g():\r\n return render_template('login.html')\r\n\r\n@user_blueprint.route('/login/',methods=['POST'])\r\ndef login_p():\r\n mobile = request.form.get('mobile')\r\n pwd = request.form.get('password')\r\n #1.验证数据完整性\r\n if not all([mobile,pwd]):\r\n return jsonify(status_code.USER_REGISTER_DATA_NOT_NULL)\r\n #2.验证手机正确性\r\n if not re.match(r'^1[34578]\\d{9}$', mobile):\r\n return jsonify(status_code.USER_REGISTER_MOBILE_ERROR)\r\n #3.验证用户是否存在\r\n user = User.query.filter_by(phone=mobile).first()\r\n if user:\r\n if not user.check_pwd(pwd):\r\n return jsonify(status_code.USER_LOGIN_PASSWORD_IS_NOT_VALID)\r\n # 验证用户成功\r\n session['user_id'] = user.id\r\n return jsonify(status_code.MSG_OK)\r\n else:\r\n return jsonify(status_code.USER_LOGIN_USER_NOT_EXSITS)\r\n\r\n\r\n@user_blueprint.route('/logout/',methods=['GET'])\r\ndef logout():\r\n session.clear()\r\n return redirect(url_for('user.login_g'))\r\n\r\n\r\n@user_blueprint.route('/my/',methods=['GET'])\r\n@is_login\r\ndef my():\r\n return render_template('my.html')\r\n\r\n@user_blueprint.route('/profile/',methods=['GET'])\r\n@is_login\r\ndef profile_g():\r\n return render_template('profile.html')\r\n\r\n\r\n@user_blueprint.route('/profile/',methods=['PATCH'])\r\ndef profile_p_i():\r\n file = request.files.get('avatar')\r\n # 校验上传图片格式的正确性\r\n if not re.match(r'image/.*',file.mimetype):\r\n return jsonify(status_code.USER_CHANGE_PROFILE_IMAGES)\r\n # 保存\r\n image_path = os.path.join(UPLOAD_DIR,file.filename)\r\n file.save(image_path)\r\n\r\n user = User.query.get(session['user_id'])\r\n avatar_path = os.path.join('upload',file.filename)\r\n user.avatar = avatar_path\r\n try:\r\n user.add_update()\r\n except Exception as e:\r\n db.session.rollback()\r\n return jsonify(status_code.DATABASE_ERROR)\r\n return jsonify(code=status_code.MSG_OK,image_url=avatar_path)\r\n\r\n\r\n@user_blueprint.route('/profile_n/',methods=['POST'])\r\n@is_login\r\ndef profile_n():\r\n u_name = request.form.get('username')\r\n user = User.query.filter_by(name=u_name).first()\r\n if user:\r\n # 该用户名已经存在,不允许修改\r\n return jsonify(status_code.USER_CHANGE_PRONAME_IS_INVALID)\r\n else:\r\n user = User.query.get(session['user_id'])\r\n user.name = u_name\r\n try:\r\n user.add_update()\r\n except Exception as e:\r\n db.session.rollback()\r\n return jsonify(status_code.DATABASE_ERROR)\r\n return jsonify(code=status_code.MSG_OK)\r\n\r\n@user_blueprint.route('/user/',methods=['GET'])\r\n@is_login\r\ndef user_info():\r\n user = User.query.get(session['user_id'])\r\n return jsonify(code=status_code.MSG_OK,data=user.to_basic_dict())\r\n\r\n# 实名认证\r\n@user_blueprint.route('/auth/',methods=['GET'])\r\n@is_login\r\ndef auth_g():\r\n return render_template('auth.html')\r\n\r\n@user_blueprint.route('/auth/',methods=['PATCH'])\r\n@is_login\r\ndef user_auth():\r\n real_name = request.form.get('real_name')\r\n id_card = request.form.get('id_card')\r\n if not all([real_name,id_card]):\r\n return jsonify(status_code.USER_AUTH_DATA_IS_NOT_NULL)\r\n if not re.match(r'^[1-9]\\d{17}$',id_card):\r\n return jsonify(status_code.USER_AUTH_ID_CARD_ID_NOT_VALID)\r\n user = User.query.get(session['user_id'])\r\n user.id_name = real_name\r\n user.id_card = id_card\r\n try:\r\n user.add_update()\r\n except:\r\n db.session.rollback()\r\n return jsonify(status_code.DATABASE_ERROR)\r\n return jsonify(status_code.MSG_OK)\r\n\r\n@user_blueprint.route('/auths/',methods=['GET'])\r\n@is_login\r\ndef user_auths():\r\n user = User.query.get(session['user_id'])\r\n return jsonify(code=status_code.MSG_OK,data=user.to_auth_dict())","sub_path":"aj/App/user_views.py","file_name":"user_views.py","file_ext":"py","file_size_in_byte":5403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"443825023","text":"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"A Transform takes a list of `Series` and returns a namedtuple of `Series`.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom abc import ABCMeta\nfrom abc import abstractmethod\nfrom abc import abstractproperty\n\nimport collections\n\nfrom .series import Series\nfrom .series import TransformedSeries\n\nfrom tensorflow.python.util import tf_inspect\n\n\ndef _make_list_of_series(x):\n \"\"\"Converts `x` into a list of `Series` if possible.\n\n Args:\n x: a `Series`, a list of `Series` or `None`.\n\n Returns:\n `x` if it is a list of Series, `[x]` if `x` is a `Series`, `[]` if x is\n `None`.\n\n Raises:\n TypeError: `x` is not a `Series` a list of `Series` or `None`.\n \"\"\"\n if x is None:\n return []\n elif isinstance(x, Series):\n return [x]\n elif isinstance(x, collections.Iterable):\n for i, y in enumerate(x):\n if not isinstance(y, Series):\n raise TypeError(\n \"Expected a tuple or list of Series; entry %s has type %s.\" %\n (i, type(y).__name__))\n return list(x)\n raise TypeError(\"Expected a Series or list of Series; got %s\" %\n type(x).__name__)\n\n\ndef _make_tuple_of_string(x):\n \"\"\"Converts `x` into a list of `str` if possible.\n\n Args:\n x: a `str`, a list of `str`, a tuple of `str`, or `None`.\n\n Returns:\n `x` if it is a tuple of str, `tuple(x)` if it is a list of str,\n `(x)` if `x` is a `str`, `()` if x is `None`.\n\n Raises:\n TypeError: `x` is not a `str`, a list or tuple of `str`, or `None`.\n \"\"\"\n if x is None:\n return ()\n elif isinstance(x, str):\n return (x,)\n elif isinstance(x, collections.Iterable):\n for i, y in enumerate(x):\n if not isinstance(y, str):\n raise TypeError(\n \"Expected a tuple or list of strings; entry %s has type %s.\" %\n (i, type(y).__name__))\n return x\n raise TypeError(\"Expected a string or list of strings or tuple of strings; \" +\n \"got %s\" % type(x).__name__)\n\n\ndef parameter(func):\n \"\"\"Tag functions annotated with `@parameter` for later retrieval.\n\n Note that all `@parameter`s are automatically `@property`s as well.\n\n Args:\n func: the getter function to tag and wrap\n\n Returns:\n A `@property` whose getter function is marked with is_parameter = True\n \"\"\"\n func.is_parameter = True\n return property(func)\n\n\nclass Transform(object):\n \"\"\"A function from a list of `Series` to a namedtuple of `Series`.\n\n Transforms map zero or more Series of a DataFrame to new Series.\n \"\"\"\n\n __metaclass__ = ABCMeta\n\n def __init__(self):\n self._return_type = None\n\n @abstractproperty\n def name(self):\n \"\"\"Name of the transform.\"\"\"\n raise NotImplementedError()\n\n def parameters(self):\n \"\"\"A dict of names to values of properties marked with `@parameter`.\"\"\"\n property_param_names = [name\n for name, func in tf_inspect.getmembers(type(self))\n if (hasattr(func, \"fget\") and hasattr(\n getattr(func, \"fget\"), \"is_parameter\"))]\n return {name: getattr(self, name) for name in property_param_names}\n\n @abstractproperty\n def input_valency(self):\n \"\"\"The number of `Series` that the `Transform` should expect as input.\n\n `None` indicates that the transform can take a variable number of inputs.\n\n This function should depend only on `@parameter`s of this `Transform`.\n\n Returns:\n The number of expected inputs.\n \"\"\"\n raise NotImplementedError()\n\n @property\n def output_names(self):\n \"\"\"The names of `Series` output by the `Transform`.\n\n This function should depend only on `@parameter`s of this `Transform`.\n\n Returns:\n A tuple of names of outputs provided by this Transform.\n \"\"\"\n return _make_tuple_of_string(self._output_names)\n\n @abstractproperty\n def _output_names(self):\n \"\"\"The names of `Series` output by the `Transform`.\n\n This function should depend only on `@parameter`s of this `Transform`.\n\n Returns:\n Names of outputs provided by this Transform, as a string, tuple, or list.\n \"\"\"\n raise NotImplementedError()\n\n @property\n def return_type(self):\n \"\"\"Provides a namedtuple type which will be used for output.\n\n A Transform generates one or many outputs, named according to\n _output_names. This method creates (and caches) a namedtuple type using\n those names as the keys. The Transform output is then generated by\n instantiating an object of this type with corresponding values.\n\n Note this output type is used both for `__call__`, in which case the\n values are `TransformedSeries`, and for `apply_transform`, in which case\n the values are `Tensor`s.\n\n Returns:\n A namedtuple type fixing the order and names of the outputs of this\n transform.\n \"\"\"\n if self._return_type is None:\n # TODO(soergel): pylint 3 chokes on this, but it is legit and preferred.\n # return_type_name = \"%sReturnType\" % type(self).__name__\n return_type_name = \"ReturnType\"\n self._return_type = collections.namedtuple(return_type_name,\n self.output_names)\n return self._return_type\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n parameters_sorted = [\"%s: %s\" % (repr(k), repr(v))\n for k, v in sorted(self.parameters().items())]\n parameters_joined = \", \".join(parameters_sorted)\n\n return \"%s({%s})\" % (self.name, parameters_joined)\n\n def __call__(self, input_series=None):\n \"\"\"Apply this `Transform` to the provided `Series`, producing 'Series'.\n\n Args:\n input_series: None, a `Series`, or a list of input `Series`, acting as\n positional arguments.\n\n Returns:\n A namedtuple of the output `Series`.\n\n Raises:\n ValueError: `input_series` does not have expected length\n \"\"\"\n input_series = _make_list_of_series(input_series)\n if len(input_series) != self.input_valency:\n raise ValueError(\"Expected %s input Series but received %s.\" %\n (self.input_valency, len(input_series)))\n output_series = self._produce_output_series(input_series)\n\n # pylint: disable=not-callable\n return self.return_type(*output_series)\n\n @abstractmethod\n def _produce_output_series(self, input_series):\n \"\"\"Applies the transformation to the `transform_input`.\n\n Args:\n input_series: a list of Series representing the input to\n the Transform.\n\n Returns:\n A list of Series representing the transformed output, in order\n corresponding to `_output_names`.\n \"\"\"\n raise NotImplementedError()\n\n\nclass TensorFlowTransform(Transform):\n \"\"\"A function from a list of `Series` to a namedtuple of `Series`.\n\n Transforms map zero or more Series of a DataFrame to new Series.\n \"\"\"\n\n __metaclass__ = ABCMeta\n\n def _check_output_tensors(self, output_tensors):\n \"\"\"Helper for `build(...)`; verifies the output of `_build_transform`.\n\n Args:\n output_tensors: value returned by a call to `_build_transform`.\n\n Raises:\n TypeError: `transform_output` is not a list.\n ValueError: `transform_output` does not match `output_names`.\n \"\"\"\n if not isinstance(output_tensors, self.return_type):\n raise TypeError(\n \"Expected a NamedTuple of Tensors with elements %s; got %s.\" %\n (self.output_names, type(output_tensors).__name__))\n\n def _produce_output_series(self, input_series=None):\n \"\"\"Apply this `Transform` to the provided `Series`, producing `Series`.\n\n Args:\n input_series: None, a `Series`, or a list of input `Series`, acting as\n positional arguments.\n\n Returns:\n A namedtuple of the output `Series`.\n \"\"\"\n return [TransformedSeries(input_series, self, output_name)\n for output_name in self.output_names]\n\n def build_transitive(self, input_series, cache=None, **kwargs):\n \"\"\"Apply this `Transform` to the provided `Series`, producing 'Tensor's.\n\n Args:\n input_series: None, a `Series`, or a list of input `Series`, acting as\n positional arguments.\n cache: a dict from Series reprs to Tensors.\n **kwargs: Additional keyword arguments, unused here.\n\n Returns:\n A namedtuple of the output Tensors.\n\n Raises:\n ValueError: `input_series` does not have expected length\n \"\"\"\n # pylint: disable=not-callable\n if cache is None:\n cache = {}\n\n if len(input_series) != self.input_valency:\n raise ValueError(\"Expected %s input Series but received %s.\" %\n (self.input_valency, len(input_series)))\n input_tensors = [series.build(cache, **kwargs) for series in input_series]\n\n # Note we cache each output individually, not just the entire output\n # tuple. This allows using the graph as the cache, since it can sensibly\n # cache only individual Tensors.\n output_reprs = [TransformedSeries.make_repr(input_series, self, output_name)\n for output_name in self.output_names]\n output_tensors = [cache.get(output_repr) for output_repr in output_reprs]\n\n if None in output_tensors:\n result = self._apply_transform(input_tensors, **kwargs)\n for output_name, output_repr in zip(self.output_names, output_reprs):\n cache[output_repr] = getattr(result, output_name)\n else:\n result = self.return_type(*output_tensors)\n\n self._check_output_tensors(result)\n return result\n\n @abstractmethod\n def _apply_transform(self, input_tensors, **kwargs):\n \"\"\"Applies the transformation to the `transform_input`.\n\n Args:\n input_tensors: a list of Tensors representing the input to\n the Transform.\n **kwargs: Additional keyword arguments, unused here.\n\n Returns:\n A namedtuple of Tensors representing the transformed output.\n \"\"\"\n raise NotImplementedError()\n","sub_path":"Tensorflow_LightGBM_Scipy_nightly/source/tensorflow/contrib/learn/python/learn/dataframe/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":10559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"302558894","text":"#!/usr/bin/env python\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# -*- coding: utf-8 -*-\n\n\"\"\"\n gui_propagator.py\n Auteur : Alexis Petit, PhD Student, Namur University\n Date : 2017 02 25\n\n This script generate an interface to use NIMASTEP/SYMPLEC.\n V1.01\n\"\"\"\n\nimport Tkinter as tk\nfrom tkFileDialog import *\nfrom tkMessageBox import *\nimport sys\nimport os\nfrom gui_windows import *\n\n\n__all__ = [\n 'Frame_opening',\n 'App_tk',\n 'Menu_bar'\n]\n\n\nclass Frame_opening(tk.Frame):\n \"\"\" This create a frame for the opening\n \"\"\"\n\n def __init__(self,master):\n\n tk.Frame.__init__(self,master)\n self.master = master\n self.photo = tk.PhotoImage(file=\"tools/debris.png\")\n self.canvas = tk.Canvas(self,width=500, height=400)\n self.canvas.create_image(0,0,anchor=tk.NW,image=self.photo)\n self.canvas.pack()\n\n \nclass App_tk(tk.Tk):\n \"\"\" Interface GUI to use NIMASTEP/SYMPLEC\n \"\"\"\n\n def __init__(self,parent):\n\n tk.Tk.__init__(self,parent)\n self.parent = parent\n self.mode = tk.IntVar()\n self.mode.set(0) \n self.initialize()\n\n def initialize(self): \n \"\"\" This module create all elements.\n \"\"\"\n\n #Menu\n self.menubar = Menu_bar(self,self)\n self.config(menu=self.menubar)\n\n # Frames\n self.frame_b = tk.Frame(self,borderwidth=0,width=500,height=200)\n self.frame_b.pack(side=tk.BOTTOM)\n self.frame_0 = Frame_opening(self)\n self.frame_main = self.frame_0\n self.frame_main.pack()\n\n # Buttons\n self.b_launch = tk.Button(self.frame_b,text='Go',width = 25,command=self.calculations)\n self.b_launch.pack()\n self.b_reset = tk.Button(self.frame_b,text='Reset',width = 25,command=self.reset)\n self.b_reset.pack()\n self.b_quit = tk.Button(self.frame_b,text='Quit',width = 25,command=self.close_windows)\n self.b_quit.pack()\n\n\n def set_mode(self,mode,path_tle_file_name):\n \"\"\" Load the frame to select the parameters of the propagation.\n \n INPUT\n -----\n \n mode: interger\n The mode selected.\n path_tle_file_name:\n \n \"\"\"\n\n self.mode = int(mode)\n self.frame_main.pack_forget() \n self.frame_main = Frame_mode(self,self.mode,path_tle_file_name) \n self.frame_main.pack()\n\n \n def close_windows(self):\n \"\"\" Necessary to close the window\n \"\"\"\n \n self.destroy()\n\n\n def reset(self):\n \"\"\" Reset all paramets\n \"\"\"\n\n self.frame_main.reset()\n \n \n def calculations(self):\n \"\"\" Compute the ephemerides\n \"\"\"\n \n # Mode 1: propagate the orbit \n if (self.mode==1):\n\n self.frame_main.launch_propagator() \n \n # Mode 2: propgate the orbit and compare the ephemerides with observations\n elif (self.mode==2):\n\n pass\n #self.Frame_main.modify_ic_file()\n #self.Frame_main.modify_parser()\n #self.launch_propagator() \n\n\nclass Menu_bar(tk.Menu):\n \"\"\" This class build a menu for the interface.\n \"\"\"\n \n def __init__(self,parent,app):\n\n tk.Menu.__init__(self,parent)\n self.initialize()\n self.app = app\n\n \n def initialize(self):\n \"\"\" Build the menu\n \"\"\"\n\n # To manage simulation\n menu_file = tk.Menu(self,tearoff=0)\n menu_file.add_command(label=\"New\", command=self.open_file)\n menu_file.add_command(label=\"Open\", command=self.quit)\n menu_file.add_command(label=\"Save\", command=self.quit)\n menu_file.add_command(label=\"Save as\", command=self.quit) \n menu_file.add_command(label=\"Close\", command=self.quit)\n menu_file.add_command(label=\"Quit\", command=self.quit)\n\n # To manage data\n menu_update = tk.Menu(self, tearoff=0)\n menu_update.add_command(label=\"Space Weather\",command=self.open_space_weather)\n\n # Informations\n menu_info = tk.Menu(self, tearoff=0)\n menu_info.add_command(label=\"About\", command=self.quit)\n \n self.add_cascade(label=\"File\", menu=menu_file)\n self.add_cascade(label=\"Update\", menu=menu_update)\n self.add_cascade(label=\"Help\", menu=menu_info)\n\n \n def open_file(self):\n \"\"\" Create a new environment for a new simulation\n \"\"\"\n\n self.win = Project_win(None,self.app)\n self.win.title('New project')\n self.win.mainloop()\n\n \n def open_space_weather(self):\n \"\"\" Update the space weather data\n \"\"\"\n\n pass\n #self.win = space_weather_win(None,app)\n #self.win.title('Update Space weather')\n #self.win.mainloop()\n\n\n","sub_path":"celestialpy/gui_propagator.py","file_name":"gui_propagator.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"89397774","text":"from utils.LFHelper import ok,fail,deleteKeys\nfrom trump.query import get_items\nasync def ls(app,request):\n params = request.args\n if not params.get(\"id\"):return fail(\"没有小区id\")\n params[\"xq_id\"] = params.pop(\"id\")\n total,res = await get_items(app.pool,\"sx_xqdeal\",args=params,with_total=True,pager=True)\n for index,item in enumerate(res):\n houseInfo = dict()\n houseInfo[\"struc\"] = item.pop(\"struc\")\n houseInfo[\"high\"] = item.pop(\"high\")\n houseInfo[\"face\"] = item.pop(\"face\")\n item[\"house_info\"] = houseInfo\n res[index] = deleteKeys(item, [\"create_at\", \"update_at\"])\n return ok((total,res))\n","sub_path":"spider_xiaoqu/sxbank_xiaoqu/xiaoqu/pre_process/sx_xqdeal.py","file_name":"sx_xqdeal.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"59436425","text":"#!/usr/bin/env python\n\nfrom zeeguu.core.model import RSSFeed, Url, Language, RSSFeedRegistration\nimport zeeguu.core\n\nsession = zeeguu.core.db.session\n\nname = input(\"Feed name: \" )\n\nall_feeds = RSSFeed.query.all()\nfor feed in all_feeds:\n if feed.title == name:\n\n print (feed.title)\n print (feed.description)\n print (feed.language.code)\n print (feed.url.as_string())\n print (feed.image_url.as_string())\n\n for reg in RSSFeedRegistration.query.all():\n if reg.rss_feed_id == feed.id:\n print(\"... registraion by user \" + reg.user.name)\n \n","sub_path":"tools/feed_info.py","file_name":"feed_info.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"80447347","text":"# -*- coding: utf-8 -*- \nimport cv2,sys,os,csv,datetime\nfrom pathlib import Path,WindowsPath\nimport numpy as np\nfrom PIL import Image,ImageFont,ImageDraw\nfrom time import sleep\nimport tkinter as tk\nfrom tkinter import simpledialog,messagebox\n\nclass FaceCheck:\n def __init__(self):\n self.workPath=Path(sys.path[0])\n \"\"\"工作路径\"\"\"\n self.dataPath=self.workPath/\"data\"\n self.classifierFile=self.workPath/\"haarcascade_frontalface_default.xml\"\n self.face_detector = cv2.CascadeClassifier(str(self.classifierFile.resolve()))\n self.userFile=self.dataPath/\"member.csv\"\n self.names=[]\n self.cap=None\n self.loadUser()\n def loadUser(self):\n \"\"\"加载识别人列表\"\"\"\n if self.userFile.exists():\n with open(self.userFile,\"r\",encoding='UTF-8') as csv_file:\n reader = csv.reader(csv_file)\n for item in reader:\n self.names.append(item[0])\n def data_collection(self):\n \"\"\"数据录入\"\"\"\n if(not self.dataPath.exists()):\n self.dataPath.mkdir()\n # 调用笔记本内置摄像头,所以参数为0,如果有其他的摄像头可以调整参数为1,2\n cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)#cv2.CAP_DSHOW是作为open调用的一部分传递标志,还有许多其它的参数,而这个CAP_DSHOW是微软特有的。\n face_name=tk.simpledialog.askstring('输入','请输入需要识别者的名字:')\n if not face_name:\n print(\"输入名字位空\")\n return\n with open(self.userFile,'a',newline=\"\",encoding='UTF-8')as f:\n writer = csv.writer(f)\n writer.writerow([face_name])\n self.names.append(face_name)\n print('数据初始化中,请直视摄像机录入数据....')\n count = 0\n _output = sys.stdout\n while True:\n # 从摄像头读取图片\n sucess, img = cap.read()\n # 转为灰度图片\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # 检测人脸\n faces = self.face_detector.detectMultiScale(gray, 1.3, 5)#1.image表示的是要检测的输入图像# 2.objects表示检测到的人脸目标序列# 3.scaleFactor表示每次图像尺寸减小的比例\n face_id=len(self.names)\n datapath=str(self.dataPath.resolve())\n for (x, y, w, h) in faces:\n #画矩形\n cv2.rectangle(img, (x, y), (x + w, y + w), (255, 0, 0))\n count += 1\n # 保存图像\n cv2.imwrite(datapath+\"/Member.\" + str(face_id) + '.' + str(count) + '.jpg', gray[y: y + h, x: x + w])\n cv2.imshow('data collection', img)\n _output.write(f'\\r获取数据:{count:.0f}')\n # 将标准输出一次性刷新\n _output.flush()\n # 保持画面的持续。\n k = cv2.waitKey(1)\n if k == 27: # 通过esc键退出\n break\n elif count >= 200: # 得到n个样本后退出摄像\n break\n cap.release()\n cv2.destroyAllWindows()\n tk.messagebox.showinfo(\"提示\",\"收集完毕\")\n def face_training(self):\n \"\"\"数据训练\"\"\"\n recognizer = cv2.face.LBPHFaceRecognizer_create()\n #LBP是一种特征提取方式,能提取出图像的局部的纹理特征\n def get_images_and_labels(path):\n if not path.exists():\n path.mkdir()\n return\n faceSamples = []\n ids = []\n # 遍历图片路径,导入图片和id,添加到list\n for imagePath in path.glob(\"*.jpg\"):\n PIL_img = Image.open(imagePath).convert('L') #通过图片路径并将其转换为灰度图片。\n img_numpy = np.array(PIL_img, 'uint8')\n id = int(os.path.split(imagePath)[-1].split(\".\")[1])\n faces = self.face_detector.detectMultiScale(img_numpy)\n for (x, y, w, h) in faces:\n faceSamples.append(img_numpy[y:y + h, x: x + w])\n ids.append(id)\n return faceSamples, ids\n\n faces, ids = get_images_and_labels(self.dataPath)\n if len(ids)==0:\n tk.messagebox.showinfo(\"提示\",\"先录入脸部数据\")\n return\n print('数据训练中')\n recognizer.train(faces, np.array(ids))\n recognizer.write(str(self.dataPath/'trainer.yml'))\n tk.messagebox.showinfo(\"提示\",\"训练完成\")\n def face_check(self):\n cap = cv2.VideoCapture(0)\n recognizer = cv2.face.LBPHFaceRecognizer_create()\n \n recognizer.read(str(self.dataPath/'trainer.yml'))\n faceCascade = cv2.CascadeClassifier(str(self.classifierFile))\n idnum = 0\n cam = cv2.VideoCapture(0)\n #设置大小\n minW = 0.1 * cam.get(3)\n minH = 0.1 * cam.get(4)\n\n while True:\n ret, img = cam.read()\n #图像灰度处理\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \n # 将人脸用vector保存各个人脸的坐标、大小(用矩形表示)\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.2,#表示在前后两次相继的扫描中,搜索窗口的比例系数\n minNeighbors=5,#表示构成检测目标的相邻矩形的最小个数(默认为3个)\n minSize=(int(minW), int(minH))#minSize和maxSize用来限制得到的目标区域的范围\n )\n \n for (x, y, w, h) in faces:\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n # 返回侦测到的人脸的id和近似度conf(数字越大和训练数据越不像)\n idnum, confidence = recognizer.predict(gray[y:y + h, x:x + w])\n\n if confidence<80:\n cap.release()\n cv2.destroyAllWindows()\n print(\"校验成功\")\n return \"success\"\n k = cv2.waitKey(1)\n if k == 27: # 通过esc键退出\n print(\"校验失败,手动退出\")\n break\n def face_ientification(self):\n \"\"\"脸部识别\"\"\"\n if len(self.names)==0:\n tk.messagebox.showinfo(\"提示\",\"先录入脸部数据\")\n return\n cap = cv2.VideoCapture(0)\n recognizer = cv2.face.LBPHFaceRecognizer_create()\n \n recognizer.read(str(self.dataPath/'trainer.yml'))\n faceCascade = cv2.CascadeClassifier(str(self.classifierFile))\n font = ImageFont.truetype(\"simsun.ttc\",30)\n\n idnum = 0\n cam = cv2.VideoCapture(0)\n #设置大小\n minW = 0.1 * cam.get(3)\n minH = 0.1 * cam.get(4)\n def zh_ch(string):\n return string.encode('GBK').decode(errors='ignore')\n\n while True:\n ret, img = cam.read()\n #图像灰度处理\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \n # 将人脸用vector保存各个人脸的坐标、大小(用矩形表示)\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.2,#表示在前后两次相继的扫描中,搜索窗口的比例系数\n minNeighbors=5,#表示构成检测目标的相邻矩形的最小个数(默认为3个)\n minSize=(int(minW), int(minH))#minSize和maxSize用来限制得到的目标区域的范围\n )\n namess=\"\"\n confidence=None\n for (x, y, w, h) in faces:\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n # 返回侦测到的人脸的id和近似度conf(数字越大和训练数据越不像)\n idnum, confidence = recognizer.predict(gray[y:y + h, x:x + w])\n idnum-=1\n if confidence < 100:\n namess = self.names[idnum]\n confidence = \"{0}%\".format(round(100 - confidence))\n else:\n namess = \"unknown\"\n confidence = \"{0}%\".format(round(100 - confidence))\n if (isinstance(img, np.ndarray)): # 判断是否OpenCV图片类型\n img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n draw = ImageDraw.Draw(img)\n draw.text((x + 5, y - 6), str(namess), font=font, fill=(0, 0, 255))\n img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)\n cv2.putText(img, str(confidence), (x + 5, y + h - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 1)#输出置信度\n\n cv2.imshow(zh_ch('image'), img)\n k = cv2.waitKey(5)\n if k == 13:#回车\n theTime = datetime.datetime.now()\n strings = [str(self.names[idnum]),str(confidence),str(theTime)]\n print(strings)\n with open(self.dataPath/\"log.csv\", \"a\",newline=\"\",encoding='UTF-8') as csvFile:\n writer = csv.writer(csvFile)\n writer.writerow([str(self.names[idnum]),str(confidence),str(theTime)])\n elif k==27:#ESC退出\n cap.release()\n cv2.destroyAllWindows()\n break\n def face_clean(self):\n \"\"\"清除数据\"\"\"\n if(self.dataPath.exists()):\n if not hasattr(WindowsPath,'clean'):\n def clean(self):\n \"\"\"递归删除目录\"\"\"\n for item in self.iterdir():\n if item.is_file():\n item.unlink()\n continue\n if item.iterdir():\n abs_path = self.joinpath(item.name)\n abs_path.clean()\n item.rmdir()\n WindowsPath.clean=clean\n self.dataPath.clean()\n self.__init__()\n return\n def listUser(self):\n tk.messagebox.showinfo(\"提示\",\"\".join([str(i+1)+\". \"+x for i,x in enumerate(self.names)]))\n def panel(self):\n \"\"\"界面选择\"\"\"\n self.root = tk.Tk()\n self.root.wm_attributes('-topmost',1)\n self.root.title('脸部识别')\n list = tk.Button(self.root, text =\"查看录入列表\", command = self.listUser)\n collection = tk.Button(self.root, text =\"录入人脸\", command = self.data_collection)\n training = tk.Button(self.root, text =\"训练模型\", command = self.face_training)\n ientification = tk.Button(self.root, text =\"脸部识别(ESC退出 Enter打印日志)\", command = self.face_ientification)\n check = tk.Button(self.root, text =\"脸部校验(ESC退出)\", command = self.face_check)\n clean = tk.Button(self.root, text =\"清除数据\", command = self.face_clean)\n \n list.pack()\n collection.pack()\n training.pack()\n ientification.pack()\n check.pack()\n clean.pack()\n # self.root.protocol('WM_DELETE_WINDOW', on_closing)\n self.root.mainloop()\ndef open_check():\n return FaceCheck().face_check()\nif __name__ == '__main__':\n FaceCheck().panel()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"170237621","text":"#Ejercicio3\n# Los arrays `u` y `v` representan dos series en funcion del tiempo `t`.\n# Grafique las dos series de datos en una misma imagen 'serie.png'\n# Calcule la covarianza entre `u` y `v` e imprima su valor.\n\nimport numpy as np\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nt = np.array([0.,0.1,0.2,0.3,0.4,0.5,0.6, 0.8, 0.9])\nu = np.array([12.,45.,6.,78.,34.,22.,-10.,31.,-27.])\nv = np.array([3.,11.,1.3,37.,11.,6.,-23.,7.,7.])\n\nplt.plot(u,t)\nplt.plot(v,t)\nplt.savefig(\"serie.png\")\n\ndef desviacion(t):\n des=0\n for i in range(len(t)):\n \n des+= (t[i]-t[i-1])**2/len(t)\n \n return des\ndest = desviacion(t)\ndesu= desviacion(u)\ndesv = desviacion(v)\n\nvarianza_t = dest*dest\nvarianza_u=desu*desu\nvarianza_v=desv*desv\n \n","sub_path":"ejercicio3.py","file_name":"ejercicio3.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"635607822","text":"import math\nfrom scipy.integrate import quad\n\nZ = 1\nm = 938.3\nE = 1.9e-3\nr0 = 2 * .87\nr1 = Z*Z * 197/137 / E\n\ndef func(r):\n\treturn 2 / 197 * math.sqrt(m*(-E + Z*Z * 197/137 / r))\n\nres, err = quad(func, r0, r1)\n\nprint(Z, m, r0/2, r1)\nprint(res, err)\n","sub_path":"py/tunneling.py","file_name":"tunneling.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"216303650","text":"from __future__ import print_function\nfrom time import gmtime, strftime\nimport os\nimport sys\nimport time\nimport logging\nimport tempfile\nimport colorlog\nimport traceback\nimport subprocess\nimport discord\n\ntmpfile = tempfile.TemporaryFile('w+', encoding='utf8')\nlog = logging.getLogger('launcher')\nlog.setLevel(logging.DEBUG)\n\nsh = logging.StreamHandler(stream=sys.stdout)\nsh.setFormatter(logging.Formatter(\n fmt=\"[%(levelname)s] %(name)s: %(message)s\"\n))\n\nsh.setLevel(logging.INFO)\nlog.addHandler(sh)\n\ntfh = logging.StreamHandler(stream=tmpfile)\ntfh.setFormatter(logging.Formatter(\n fmt=\"[%(levelname)s] %(name)s: %(message)s\"\n))\ntfh.setLevel(logging.DEBUG)\nlog.addHandler(tfh)\n\n\ndef finalize_logging():\n pass\n\n with open(\"logs/bot.log\", 'w', encoding='utf8') as f:\n tmpfile.seek(0)\n f.write(tmpfile.read())\n tmpfile.close()\n\n f.write('\\n')\n f.write(\" PRE-RUN SANITY CHECKS PASSED \".center(80, '#'))\n f.write('\\n\\n\\n')\n\n global tfh\n log.removeHandler(tfh)\n del tfh\n\n fh = logging.FileHandler(\"logs/bot.log\", mode='a')\n fh.setFormatter(logging.Formatter(\n fmt=\"[%(levelname)s]: %(message)s\"\n ))\n fh.setLevel(logging.DEBUG)\n log.addHandler(fh)\n\n sh.setLevel(logging.INFO)\n\n dlog = logging.getLogger('discord')\n dlog.setLevel(logging.WARNING)\n dlh = logging.StreamHandler(stream=sys.stdout)\n dlh.terminator = ''\n dlh.setFormatter(logging.Formatter('.'))\n dlog.addHandler(dlh)\n\n\ndef pyexec(pycom, *args, pycom2=None):\n pycom2 = pycom2 or pycom\n os.execlp(pycom, pycom2, *args)\n\n\ndef restart(*args):\n pyexec(sys.executable, *args, *sys.argv, pycom2='python')\n\n\ndef main():\n from code import Helix\n h = Helix()\n log.info(\"Connecting\\n\")\n h.run()\n log.info(\"All done.\")\n\nif __name__ == '__main__':\n # try:\n main()\n # except Exception as e:\n # log.fatal(\"Bot runtime has been terminated\")\n # log.fatal(e)\n # #os.execl(sys.executable, sys.executable, *sys.argv)","sub_path":"boot.py","file_name":"boot.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"343221583","text":"T = eval(input())\nwhile T > 0:\n a = eval(input()); s = input();\n num = list(int(n) for n in s.split())\n cnt = 0\n for i in range(a-1):\n for j in range(a-1-i):\n if num[j] > num[j+1]:\n num[j], num[j+1] = num[j+1], num[j]\n cnt += 1\n print(\"Optimal train swapping takes \",cnt,\" swaps.\", sep = '')\n T -= 1\n","sub_path":"UVA-299.py","file_name":"UVA-299.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"60792074","text":"\"\"\" создаем файл JSON записываем в него и читаем из него \"\"\"\n\nimport json\n\nfilename = 'text_files/username.json'\nsquares = [1, 4, 9, 16, 25, 36]\n\ntry:\n with open(filename) as f_obj:\n username = json.load(f_obj)\nexcept FileNotFoundError:\n username = input(\"Как ваше имя? \")\n with open(filename, 'w') as f_obj:\n json.dump(username, f_obj)\n print(\"Мы запомнили Ваше имя \" + username + \"!\")\nelse:\n print(\"С возвращением, \" + username + \"!\")","sub_path":"metiz_206_remember_me.py","file_name":"metiz_206_remember_me.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"155118577","text":"from __future__ import unicode_literals\n\nimport django\nfrom django.test import RequestFactory\nfrom django.http import HttpResponse\n\n\nclass TestNewStyleMiddlewareMixin(object):\n middleware_factory = NotImplemented\n\n if django.VERSION >= (1, 10):\n def test_new_style(self):\n payload = b'Test'\n def get_response(request):\n return HttpResponse(payload)\n request = RequestFactory().get('/')\n\n callable_middleware = self.middleware_factory(get_response)\n self.assertEqual(callable_middleware(request).content,\n payload)\n","sub_path":"testproject/fiber_test/tests/test_utils/test_middleware.py","file_name":"test_middleware.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"485688602","text":"import numpy as np\nimport sys\nfrom config import *\n\ndef parse_embedding(embed_filename):\n\n print(\"Parsing embedding file\")\n embed_file = open(embed_filename)\n embedding = dict()\n for line in embed_file:\n values = line.split()\n values.append(1.0)\n embedding[values[0]] = np.array(values[1:]).astype(np.float)\n\n embedding[''] = np.random.uniform(-1,0,EMBEDDING_DIM)\n embedding[''] = np.random.uniform(-1,0,EMBEDDING_DIM)\n \n return embedding\n\n# Fake embeddings. We use this function if not character embeddings \n# are available \ndef parse_embedding_fake(embed_filename):\n \n print(\"Generating random embeddings\")\n embedding = dict()\n embedding[''] = np.random.uniform(-1,0,EMBEDDING_DIM)\n embedding[''] = np.random.uniform(-1,0,EMBEDDING_DIM)\n for i in range(sys.maxunicode): \n try:\n embedding[chr(i)] = np.random.uniform(-1,0,EMBEDDING_DIM)\n except:\n continue\n\n #embedding = dict()\n #for line in embed_file:\n # values = line.split()\n # values.append(1.0)\n # embedding[values[0]] = np.array(values[1:]).astype(np.float)\n return embedding\n\ndef parse_file(train_filename, embedding, use_max_len=True):\n print(\"Parsing UD file...\")\n train_file = open(train_filename)\n sentences = []\n sentences_chars = []\n labels = []\n label = []\n sentence = \"\"\n label_sum = 0\n for line in train_file:\n if line.startswith(\"# text = \"):\n sentence = line[9:].strip().replace(\" \", \"\")\n N = len(sentence)\n if use_max_len:\n max_len = MAX_SENTENCE_LEN\n else:\n max_len = N\n sentence_vec = np.zeros((max_len, EMBEDDING_DIM))\n for i in range(min(N, max_len)):\n c = sentence[i]\n if c in \"0123456789\":\n sentence_vec[i, :] = embedding[\"\"]\n elif c in embedding:\n sentence_vec[i, :] = embedding[c]\n else:\n sentence_vec[i, :] = embedding[\"\"]\n sentences.append(sentence_vec)\n sentences_chars.append(c)\n\n elif not line.startswith(\"#\"):\n parts = line.split()\n N = len(sentence)\n if use_max_len:\n max_len = MAX_SENTENCE_LEN\n else:\n max_len = N\n \n if len(parts) < 4:\n if len(sentence) != 0:\n while label_sum < max_len:\n label_len = 1\n label_sum += label_len\n label.append(('BLANK', label_len))\n labels.append((label, sentence))\n label = []\n label_sum = 0\n sentence = \"\"\n else:\n if (label_sum + len(parts[1])) <= max_len:\n label_sum += len(parts[1])\n label.append((parts[3], len(parts[1])))\n else:\n label_len = max_len - label_sum\n if label_len > 0:\n label.append((parts[3], label_len))\n label_sum = max_len\n\n print(\"Sentences:\",sentences[:2])\n print(\"Labels:\",labels[:2])\n return sentences, labels\n\ndef parse_morph_langid_file(train_filename, embedding, use_max_len=True):\n print(\"Parsing morphology/langid file...\")\n train_file = open(train_filename)\n sentences = []\n labels = []\n\n for line in train_file:\n if not line:\n continue\n\n line = line.split('\\t')\n\n tags = line[2].split()\n segs = line[1].split()\n\n if len(tags) != len(segs):\n print(\"ERROR:\", tags, segs)\n continue\n \n if len(tags) > 1:\n pass\n #print(segs, tags)\n\n labs = list()\n\n for tag, seg in zip(tags,segs):\n labs.append((tag.rstrip(),len(seg)))\n\n\n labels.append((labs, line[0]))\n\n N = len(line[0])\n if use_max_len:\n max_len = MAX_SENTENCE_LEN\n else:\n max_len = N\n sentence_vec = np.zeros((max_len, EMBEDDING_DIM))\n for i in range(min(N, max_len)):\n c = line[0][i]\n if c in embedding:\n sentence_vec[i, :] = embedding[c]\n elif c in \"0123456789\":\n sentence_vec[i, :] = embedding[\"\"]\n else:\n sentence_vec[i, :] = embedding[\"\"]\n sentences.append(sentence_vec)\n\n print(\"Sentences:\",sentences[0])\n print(\"Labels:\",labels[0])\n \n return sentences, labels\n\n\n","sub_path":"preproc.py","file_name":"preproc.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"248957710","text":"import os\nimport h5py\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch.autograd import Variable\nfrom torch.utils.data import Dataset\n\n\nclass GloveDataset(Dataset):\n\n def __init__(self, args, phase):\n self.args = args\n self.phase = phase\n\n data = []\n label = []\n\n for idx_obj in range(args.n_obj):\n obj_name = args.object_list[idx_obj]\n\n file_path_prefix = os.path.join(args.data_path, '%s' % obj_name)\n\n touch = []\n for idx_round in range(args.n_round):\n file_path = os.path.join(file_path_prefix, '%s_%d.hdf5'% (obj_name, idx_round + 1))\n f = h5py.File(file_path, 'r')\n fc = f['frame_count'][0]\n touch_seq = np.array(f['pressure'][:fc - 100]).astype(np.float32)\n\n # subsample the touch sequence\n if args.subsample > 1:\n subsample = args.subsample\n for x in range(0, touch_seq.shape[1], subsample):\n for y in range(0, touch_seq.shape[2], subsample):\n v = np.mean(touch_seq[:, x:x+subsample, y:y+subsample], (1, 2))\n touch_seq[:, x:x+subsample, y:y+subsample] = v.reshape(-1, 1, 1)\n\n for idx_data in range(0, touch_seq.shape[0] - args.input_window_size + 1, args.skip):\n touch.append(touch_seq[idx_data:idx_data + args.input_window_size])\n\n touch = np.stack(touch)\n n_reserve = args.n_valid_per_obj + args.n_test_per_obj\n n_train = touch.shape[0] - n_reserve\n\n if phase == 'train':\n print(obj_name, touch.shape)\n idx = np.random.choice(n_train, args.n_train_per_obj)\n touch = touch[idx]\n elif phase == 'valid':\n touch = touch[n_train:n_train + args.n_valid_per_obj]\n elif phase == 'test':\n touch = touch[-args.n_test_per_obj:]\n\n data.append(touch)\n label.append([idx_obj] * touch.shape[0])\n\n data = np.concatenate(data, 0)\n label = np.concatenate(label, 0)\n\n print(phase, 'data:', data.shape, 'label:', label.shape)\n print(np.min(data), np.max(data), np.mean(data), np.std(data))\n\n min_ = 48.0\n max_ = 1023.0\n mean_ = 525.35846\n std_ = 14.988879\n\n # data = ((data - min_) / (max_ - min_) - 0.5) * 2.\n data = (data - mean_) / std_\n\n self.data = torch.FloatTensor(data)\n self.label = torch.LongTensor(label)\n\n def __len__(self):\n return self.data.size(0)\n\n def __getitem__(self, idx):\n data = self.data[idx]\n\n # augment the training set\n if self.phase == 'train':\n noise = (np.random.randn(data.shape[0], data.shape[1], data.shape[2]) - 0.5) * 0.5\n data = data + torch.FloatTensor(noise)\n\n return data, self.label[idx]\n\n","sub_path":"classification/object_classification/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"8540862","text":"# Definition for a Node.\nclass Node:\n def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n self.val = int(x)\n self.next = next\n self.random = random\n\n\nclass Solution:\n def doCopyRandomList(self, head: 'Node', mapping: dict):\n if not head:\n return None\n elif head in mapping:\n return mapping.get(head)\n\n newHead = Node(head.val, None, None)\n mapping[head] = newHead\n newHead.next = self.doCopyRandomList(head.next, mapping)\n newHead.random = self.doCopyRandomList(head.random, mapping)\n return newHead\n\n def copyRandomList(self, head: 'Node') -> 'Node':\n return self.doCopyRandomList(head, {})","sub_path":"剑指offer系列/剑指 Offer 35. 复杂链表的复制/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"563348776","text":"'''\nCreated on April 13, 2014\n\n@author: Xi\n'''\nimport datetime\nfrom django import forms\nfrom django.forms import ModelForm\nfrom Messages.models import Message\nfrom django.contrib.auth.models import User\nclass Message_Form(forms.Form):\n\tsender = forms.CharField(max_length=50,label='FROM')\n\trecipient = forms.CharField(max_length=255,label='TO')\n\tsubject = forms.CharField(max_length=255,label='SUBJECT')\n\ttext = forms.CharField(label='MESSAGE',\n widget=forms.Textarea(attrs={'rows': '12', 'cols':'90'}))\n\t#message save function get the recipient and save each message.\n\n\tdef save(self,sender_parent_msg=None,recipient_parent_msg=None):\n\t\trecipients = self.cleaned_data['recipient']\n\t\tsender = self.cleaned_data['sender']\n\t\tsubject = self.cleaned_data['subject']\n\t\ttext = self.cleaned_data['text']\n\t\tmsg_list = []\n\t\tfor r in recipients.split(','):\n\t\t\tsender_from = User.objects.get(username = sender)\n\t\t\trecipient_to = User.objects.get(username = r)\n\t\t\tcompany = sender_from.companyname\n\t\t\tmsg_sender = Message(owner=sender_from,sender=sender_from,recipient=recipient_to,subject=subject,text=text,sender_company = company)\n\t\t\tmsg_recipient = Message(owner=recipient_to,sender=sender_from,recipient=recipient_to,subject=subject,text=text,sender_company = company)\n\t\t\tmsg_sender.sent_at = datetime.datetime.now()\n\t\t\tmsg_recipient.sent_at = datetime.datetime.now()\n\t\t\t#if it is a replied message, set parent msg as the message id\n\t\t\tif sender_parent_msg is not None or recipient_parent_msg is not None:\n\t\t\t\tmsg_sender.parent_msg = sender_parent_msg\n\t\t\t\tmsg_recipient.parent_msg = recipient_parent_msg\n\t\t\t\tmsg_sender.replied_at = datetime.datetime.now()\n\t\t\tmsg_sender.save()\n\t\t\tmsg_recipient.save()\n\t\t\tmsg_list.append(msg_sender)\n\t\t\tmsg_list.append(msg_recipient)\n\t\treturn msg_list\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Messages/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"50323456","text":"from typing import List\n\nfrom fastapi import APIRouter, Query\nfrom obspy import UTCDateTime\n\nfrom ...metadata import Metadata, MetadataCategory, MetadataQuery\nfrom ..db.common import database\nfrom ..db import MetadataDatabaseFactory\n\nrouter = APIRouter()\n\n\n@router.get(\n \"/metadata\",\n description=\"Search metadata records with query parameters(excludes id and metadata id)\",\n response_model=List[Metadata],\n)\nasync def get_metadata(\n category: MetadataCategory = None,\n starttime: UTCDateTime = None,\n endtime: UTCDateTime = None,\n network: str = None,\n station: str = None,\n channel: str = None,\n location: str = None,\n data_valid: bool = None,\n status: List[str] = Query(None),\n):\n query = MetadataQuery(\n category=category,\n starttime=starttime,\n endtime=endtime,\n network=network,\n station=station,\n channel=channel,\n location=location,\n data_valid=data_valid,\n status=status,\n )\n metas = await MetadataDatabaseFactory(database=database).get_metadata(\n **query.datetime_dict(exclude={\"id\", \"metadata_id\"})\n )\n return metas\n","sub_path":"geomagio/api/ws/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"288492981","text":"import sys \n\nclass Stack:\n\tdef __init__(self):\n\t\tself.stack = []\n\tdef isEmpty():\n\t\treturn self.stack == []\n\tdef push(self,data):\n\t\tself.stack.append(data)\n\tdef pop(self):\n\t\treturn self.stack.pop() \n\tdef peek(self):\n\t\treturn self.stack[len(self.stack) - 1]\n\tdef size(self):\n\t\treturn len(self.stack)\n\nclass Queue:\n\tDEFAULT_CAPACITY = 10\n\n\tdef __init__(self):\n\t\tself._data = [None] * Queue.DEFAULT_CAPACITY\n\t\tself._size = 0\n\t\tself._front = 0\n\n\tdef __len__(self):\n\t\treturn self._size\n\n\tdef is_empty(self):\n\t\treturn self._size == 0\n\n\tdef first(self):\n\t\tif self.is_empty():\n\t\t\traise Empty('Queue is empty')\n\t\treturn self._data[self._front]\n\n\tdef dequeue(self):\n\t\tif self.is_empty():\n\t\t\traise Empty('Queue is empty')\n\t\tres = self._data[self._front]\n\t\tself._data[self._front] = None \n\t\tself._front = (self._front + 1) % len(self._data)\n\t\tself._size -= 1\n\t\treturn res \n\n\tdef enqueue(self, e):\n\t\tif self._size == len(self._data):\n\t\t\tself._resize(2 * len(self._data))\n\t\tavail = (self._front + self._size) % len(self._data)\n\t\tself._data[avail] = e\n\t\tself._size += 1\n\n\tdef _resize(self, cap):\n\t\told = self._data \n\t\tself._data = [None] * cap \n\t\tcur = self._front \n\t\tfor k in range(self._size):\n\t\t\tself._data[k] = old[cur]\n\t\t\tcur = (cur + 1) % len(old)\n\t\tself._front = 0\n\n\nclass Node:\n\tdef __init__(self,val):\n\t\tself.val = val \n\t\tself.next = None\n\nclass LinkedList:\n\tdef __init__(self):\n\t\tself._head = None \n\t\tself._tail = None \n\t\n\tdef insert_head(self,data):\n\t\tnew_Node = Node(self,data)\n\t\tnew_Node.next = self._head \n\t\tself._head = new_Node\n\n\tdef print_list(self):\n\t\tif self.__head == None:\n\t\t\tprint(\"Empty List\")\n\t\telse:\n\t\t\tp = self.__head \n\t\t\twhile p is not None:\n\t\t\t\tprint(n.val, \" \")\n\t\t\t\tp = p.next \n\n\ndef max(arr):\n\tlength = len(arr)\n\tfor i in range(0,length - 1):\n\t\tif arr[i] > arr[i+1]:\n\t\t\ttmp = arr[i]\n\t\t\tarr[i] = arr[i + 1]\n\t\t\tarr[i+1] = tmp \n\tmaxVal = arr[length - 1]\n\treturn maxVal\n\ndef min(arr):\n\tlength = len(arr)\n\tfor i in range(0,length - 1):\n\t\tif arr[i] < arr[i+1]:\n\t\t\ttmp = arr[i]\n\t\t\tarr[i] = arr[i + 1]\n\t\t\tarr[i+1] = tmp \n\tminVal = arr[length - 1]\n\treturn minVal\n\ndef bubble_sort(arr):\n\tlength = len(arr)\n\tfor i in range(0, length - 1):\n\t\tfor j in range(0, length - i - 1):\n\t\t\tif arr[j] > arr[j + 1]:\n\t\t\t\ttmp = arr[j]\n\t\t\t\tarr[j] = arr[j + 1]\n\t\t\t\tarr[j + 1] = tmp\n\ndef reverse(arr):\n\tlength = len(arr)\n\tfor i in range(0, int(length / 2)):\n\t\ttmp = arr[i]\n\t\tarr[i] = arr[length - i - 1]\n\t\tarr[length - i - 1] = tmp \n\ndef binary_search(arr, target):\n\tlength = len(arr)\n\tlow = 0 \n\thigh = length - 1 \n\twhile low <= high:\n\t\tmid = low + (high - low) // 2\n\t\tif arr[mid] == target:\n\t\t\treturn mid \n\t\telif target < arr[mid]:\n\t\t\thigh = mid - 1\n\t\telif target > arr[mid]: \n\t\t\tlow = mid + 1\n\n\treturn -1 \n\n\n\ndef main():\n\tscores = [60,50,89,105,70]\n\tmaxVal = max(scores)\n\tprint(\"Max value of the list is: \", maxVal)\n\tminVal = min(scores)\n\tprint(\"Max value of the list is: \", minVal)\n\tprint(\"Sorting list using bubble sort . . .\")\n\tbubble_sort(scores)\n\tfor score in scores:\n\t\tprint(score)\n\tprint(\"Reversing list . . .\")\n\treverse(scores)\n\tfor score in scores:\n\t\tprint(score)\n\tprint(\"Searching for the value 50 using binary search . . .\")\n\ttarget = binary_search(scores, 50)\n\tprint(\"Result: \", scores[target])\n\n\tprint(\"Constructing a list . . .\")\n\ts = Stack()\n\ts.push(10)\n\ts.push(20)\n\ts.push(30)\n\ts.push(40)\n\tfor i in range(1, s.size()):\n\t\tprint(s.pop(), \" \")\n\t\n\n\tq = Queue()\n\tfor k in range(1,10):\n\t\tq.enqueue(k)\n\twhile q.is_empty() != True:\n\t\tprint(q.dequeue(), \" \")\n\t\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"575451547","text":"from error_models.base_error_model import BaseErrorModel\nfrom pycparser.c_ast import Decl,For,While,DoWhile,Node,If,FuncDef,Compound,Assignment\nfrom pycparser.c_generator import CGenerator\nimport random\n\nclass BlockErrorModel(BaseErrorModel):\n def __init__(self,ast):\n super().__init__(ast)\n self.block_item_list = []\n self.assignment_list = []\n self._coll_block_items()\n\n\n def generate_error(self, block_items):\n for item in block_items:\n result = self._find_injection_point(item)\n if result[0]:\n self._generate_swap_error(result[1],item)\n return self.ast\n\n def _generate_swap_error(self,swap_list,block_item):\n block_item.remove(swap_list[0])\n assignment_1 = swap_list[1]\n assignment_2 = swap_list[2]\n assignment_2.rvalue = assignment_1.lvalue\n\n def generate_error_default(self):\n ast = self.generate_error(self.block_item_list)\n return ast\n\n def generate_error_random(self):\n random_block_item_list = []\n for i in self.block_item_list:\n n = random.randint(0,1)\n if n == 0:\n random_block_item_list.append(i)\n ast = self.generate_error(random_block_item_list)\n return ast\n\n\n def _coll_block_items(self):\n for node in self.node_list:\n if isinstance(node, Compound):\n self.block_item_list.append(node.block_items)\n\n def _find_injection_point(self,block):\n n = 0\n m = False\n swap_list = []\n for i in block:\n if (isinstance(i,Decl) | isinstance(i,Assignment)) & (not m):\n n += 1\n m = True\n swap_list.append(i)\n elif isinstance(i,Assignment) & m:\n n += 1\n swap_list.append(i)\n else:\n m = False\n swap_list.clear()\n n = 0\n if n == 3:\n if(self._check_is_swap(swap_list)):\n return (True,swap_list)\n else:\n swap_list.clear()\n m = False\n n = 0\n return (False,[])\n\n\n def _check_is_swap(self, block_list):\n c_generate = CGenerator()\n node_0 = block_list[0]\n node_0_left,node_0_right = c_generate.visit(node_0).split('=')\n if isinstance(node_0,Decl):\n node_0_left = node_0_left.split(' ')[1]\n assignment_1 = block_list[1]\n assignment_2 = block_list[2]\n assignment_1_code = c_generate.visit(assignment_1)\n assignment_2_code = c_generate.visit(assignment_2)\n print(assignment_1_code)\n assignment_1_code_left,assignment_1_code_right = assignment_1_code.split('=')\n assignment_2_code_left, assignment_2_code_right = assignment_2_code.split('=')\n if (self.check_equal(node_0_right, assignment_1_code_left) & self.check_equal(assignment_1_code_right, assignment_2_code_left) & self.check_equal(assignment_2_code_right, node_0_left)):\n return True\n return False\n\n def check_equal(self, left, right):\n r = (left.strip() == right.strip())\n return r\n","sub_path":"error_models/block_error_model.py","file_name":"block_error_model.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"107151519","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404\nfrom django.views import View\nfrom django.views.generic import TemplateView\nfrom django.views.generic import DetailView, ListView\nfrom django.db.models import Q, F\nfrom django.core.cache import cache\n\nfrom .models import Tag, Category, Post\nfrom config.models import SlideBar, Link\nfrom comment.forms import CommentForm\nfrom comment.models import Comment\n\nfrom datetime import date\n\n\n# Create your views here.\ndef post_list(request, category_id=None, tag_id=None):\n tag = None\n category = None\n if tag_id:\n posts_list, tag = Post.get_by_tag(tag_id)\n elif category_id:\n posts_list, category = Post.get_by_category(category_id)\n else:\n print(\"显示所有正常状态的文章列表\")\n posts_list = Post.latest_posts()\n context = {\n 'tag': tag,\n 'category': category,\n 'posts_list': posts_list,\n 'slidebars': SlideBar.get_all(),\n }\n context.update(Category.get_nav())\n print(context)\n print(type(posts_list))\n print(posts_list)\n return render(request, 'django_blog_app/post_list.html', context=context)\n\n\nclass CommonViewMixin:\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context.update({\n 'slidebars': SlideBar.get_all()\n })\n context.update(Category.get_nav())\n return context\n\n\nclass IndexView(CommonViewMixin, ListView):\n # 分页的总记录数\n queryset = Post.latest_posts()\n # 每页2个数据\n paginate_by = 4\n # 同模板中的变量名保持一致\n context_object_name = \"posts_list\"\n # 模板名称\n template_name = 'django_blog_app/post_list_demo.html'\n\n\nclass CategoryView(IndexView):\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n category_id = self.kwargs.get(\"category_id\")\n print(\"category_id is %s\" % category_id)\n category = get_object_or_404(Category, pk=category_id)\n context.update({\n 'category': category\n })\n return context\n\n def get_queryset(self):\n \"\"\"重写queryset方法,根据分类过滤\"\"\"\n queryset = super().get_queryset()\n category_id = self.kwargs.get(\"category_id\")\n return queryset.filter(category_id=category_id)\n\n\nclass TagView(IndexView):\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n tag_id = self.kwargs.get(\"tag_id\")\n tag = get_object_or_404(Tag, pk=tag_id)\n context.update({\n 'tag': tag\n })\n return context\n\n def get_queryset(self):\n \"\"\"重写queryset方法,根据标签过滤\"\"\"\n queryset = super().get_queryset()\n tag_id = self.kwargs.get(\"tag_id\")\n return queryset.filter(category_id=tag_id)\n\n\nclass PostListView(ListView):\n model = Post\n # 分页的总记录数\n queryset = Post.latest_posts()\n # 每页2个数据\n paginate_by = 6\n context_object_name = \"posts_list\"\n template_name = 'django_blog_app/post_list_demo.html'\n\n\nclass SearchView(IndexView):\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n keyword = self.request.GET.get('keyword')\n context.update({\n 'keyword': keyword\n })\n return context\n\n def get_queryset(self):\n \"\"\"重写queryset方法,根据文章标题或者摘要过滤\"\"\"\n queryset = super().get_queryset()\n # 获取前台输入的keyword参数\n keyword = self.request.GET.get('keyword')\n if not keyword:\n return queryset\n return queryset.filter(Q(title__icontains=keyword) | Q(desc__icontains=keyword))\n\n\nclass AuthorView(IndexView):\n def get_queryset(self):\n \"\"\"重写queryset方法,根据过滤\"\"\"\n queryset = super().get_queryset()\n # 获取url中的owner_id参数\n owner_id = self.kwargs.get(\"owner_id\")\n return queryset.filter(owner_id=owner_id)\n\n\ndef post_detail(request, post_id):\n try:\n posts_detail = Post.objects.get(id=post_id)\n except Post.DoesNotExist:\n posts_detail = None\n context = {'posts_detail': posts_detail,\n }\n context.update(Category.get_nav())\n return render(request, 'django_blog_app/post_detail.html', context=context)\n\n\nclass PostDetailView(CommonViewMixin, DetailView):\n queryset = Post.latest_posts()\n template_name = 'django_blog_app/post_detail_demo.html'\n context_object_name = \"posts_detail\"\n pk = \"post_id\"\n\n def get(self, request, *args, **kwargs):\n response = super().get(request, *args, **kwargs)\n self.handle_visited()\n return response\n\n def handle_visited(self):\n increase_pv = False\n increase_uv = False\n # 该uid是在组件中给request对象添加的一个属性\n uid = self.request.uid\n pv_key = \"pv:%s:%s\" % (uid, self.request.path)\n # date.today()生成访问文章当天的日期\n uv_key = \"uv:%s:%s:%s\" % (uid, str(date.today()), self.request.path)\n if not cache.get(pv_key):\n increase_pv = True\n cache.set(pv_key, 1, 1*60) # 1分钟有效\n if not cache.get(uv_key):\n increase_uv = True\n cache.set(pv_key, 1, 24 * 60 * 60) # 24小时有效\n if increase_pv and increase_uv:\n Post.objects.filter(pk=self.object.id).update(pv=F('pv') + 1, uv=F('uv') + 1)\n if increase_pv:\n Post.objects.filter(pk=self.object.id).update(pv=F('pv') + 1)\n if increase_uv:\n Post.objects.filter(pk=self.object.id).update(uv=F('uv') + 1)\n\n\ndef my_view(request):\n if request.method == \"GET\":\n return HttpResponse(\"http使用的是get方法请求\")\n\n\n# 继承View基类的view类\nclass MyView(View):\n def get(self, request):\n return HttpResponse(\"http使用的是View基类的get方法请求\")\n\n\n\n\n\n\n\n\n\n","sub_path":"django_blog/django_blog_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"489186587","text":"import time\n\ndef secondsToDuration(input):\n\t\"\"\"Formats the seconds to a duration string as used by XBMC.\n\n\tKeyword arguments:\n\tinput -- the duration in seconds\n\n\t\"\"\"\n\thours = input / 3600\n\tminutes = (input % 3600) / 60\n\tseconds = (input % 3600) % 60 \n\n\treturn \"%02d:%02d:%02d\" % (hours, minutes, seconds)\n","sub_path":"script.module.danishaddons/danishaddons/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"508376590","text":"import os\nimport requests\nimport argparse\nfrom time_util import time_limit\n\n# Define arguments\nparser = argparse.ArgumentParser(description='Web scraping arg parser')\nparser.add_argument('--output_dir', type=str, help='Directory to store output raw data')\nparser.add_argument('--num_images', type=int, help='Number of images per class')\nargs = parser.parse_args()\n\n# Get arguments from parser\noutput_dir = args.output_dir\nnum_images = args.num_images\n\n# Set search headers and URL\nheaders = requests.utils.default_headers()\nheaders['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'\n\n# Define API endpoints\nsubscription_key = os.environ['BING_SEARCH_V7_SUBSCRIPTION_KEY']\nendpoint = os.environ['BING_SEARCH_V7_ENDPOINT']\nsearch_url = endpoint + \"v7.0/images/search\"\n\n# Define classes\nclasses = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n\n# Make query for each class and download images\nfor name in classes:\n\n dir_name = os.path.join(output_dir, name)\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n \n counter = 0\n num_searches = int(num_images/150)+1\n\n for i in range(num_searches):\n \n response = requests.get(\n search_url, \n headers = {\n 'Ocp-Apim-Subscription-Key' : subscription_key\n }, \n params = {\n 'q': name, \n 'imageType': 'photo',\n 'count': 150,\n 'offset': i*150\n })\n response.raise_for_status()\n results = response.json()[\"value\"]\n\n for image in results:\n if counter > num_images:\n break\n if image['encodingFormat'] == 'jpeg':\n print('Writing image {} for {}...'.format(counter, name))\n filename = '{}/{}.jpg'.format(dir_name, counter)\n try:\n with time_limit(5):\n with open(filename, 'wb') as file:\n download = requests.get(image['contentUrl'], headers=headers)\n file.write(download.content)\n counter += 1\n except:\n print('Skipping {} due to download error:'.format(filename))\n\n","sub_path":"modules/ingestion/data_ingestion.py","file_name":"data_ingestion.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"550092367","text":"from itertools import cycle\n\"\"\"function may have default parameters(no need to define it by user), but in order to make function work each of\nthe parameters must be passed (with the certain value) as for example : def func(x, y):, it will not work if x and y are\nnot defined (default def func(x = 1, y = 2):)... or not defined when the function is called(func(1, 2) or \nfunc(x = 1, y = 2))\"\"\"\ngame = [[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]\nfor i in game:\n print(i)\n\n\ndef game_board(game_map, player, row, column):\n try:\n print(\" a b c\")\n game_map[row][column] = player\n \"\"\" game_map[row][column] = player, places the number player wants to play into the certain \n location of the game list(based on the function parameters)\"\"\"\n for count, row in enumerate(game): # enumerate - iterates each row(next list) in game list\n print(count, row)\n return game_map\n except Exception as e:\n print(\"Something went wrong:\", e)\n\n\ndef win(current_game):\n def all_same(l):\n if l.count(l[0]) == len(l) and l[0] != 0:\n return True\n else:\n return False\n for col in range(len(game)):\n check = []\n for x in game:\n check.append(x[col])\n if all_same(check):\n print(\"Winner by column\")\n return True\n\n for row in game:\n print(row)\n if all_same(row):\n print(\"Winner by row\")\n return True\n mat = []\n for row_index, ix in enumerate(game):\n mat.append(ix[row_index])\n if all_same(mat):\n print(\"Winner by diagonal\")\n return True\n m = []\n for col, c in enumerate(reversed(range(len(game)))):\n m.append(game[col][c])\n if all_same(m):\n print(\"winner by diagonal\")\n return True\n return False\n\n\nplay = True\nwhile play:\n game = [[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]\n game_won = False\n player_choice = cycle([1, 2])\n while not game_won:\n current_player = next(player_choice)\n played = False\n while not played:\n column_choice = int(input(\"What column do you want to play?: \"))\n row_choice = int(input(\"What row do you want to play?: \"))\n game_board(game, current_player, row_choice, column_choice)\n\n if win(game):\n game_won = True\n again = input(\"The game is over, would you like to play again?(y/n) \")\n if again.lower() == \"y\":\n print(\"restarting\")\n elif again.lower() == \"n\":\n print(\"bye\")\n play = False\n else:\n print(\"invalid input\")\n play = False\n\n","sub_path":"sentdex.py","file_name":"sentdex.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"15874361","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport oscar_vat_moss.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('order', '0003_auto_20150113_1629'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='billingaddress',\n name='vatin',\n field=oscar_vat_moss.fields.VATINField(help_text='Required if you are associated with a business registered for VAT in the European Union.', verbose_name='VAT Identification Number (VATIN)', blank=True),\n ),\n migrations.AddField(\n model_name='shippingaddress',\n name='vatin',\n field=oscar_vat_moss.fields.VATINField(help_text='Required if you are associated with a business registered for VAT in the European Union.', verbose_name='VAT Identification Number (VATIN)', blank=True),\n ),\n ]\n","sub_path":"oscar_vat_moss/order/migrations/0004_auto_20160114_2244.py","file_name":"0004_auto_20160114_2244.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"305477533","text":"# encoding=utf-8\nimport json\nimport operator\nimport os\nimport re\nimport sys\nfrom abc import ABCMeta, abstractmethod\n\nimport pandas as pd\nsys.path.append(os.path.join(os.path.dirname(__file__), '../../..'))\n\nfrom src.entity.processor.entity_info import EntityAttribute, EntityGroup\nfrom src.util.jieba_parser import JiebaParser\n\n\ndef getProjectRootPath():\n return os.path.abspath(os.path.dirname(__file__)) + '/../../../'\n\n\ndef load_parser():\n parser = JiebaParser()\n return parser\n\n\njieba_parser = load_parser()\n\n\ndef load_addr_attr_names():\n path = os.path.abspath(getProjectRootPath() +\n 'data/attributes/addr/addr_attr_names.csv')\n with open(path, 'r') as f:\n names = [n.strip() for n in f.readlines()]\n return names\n\n\n_AddrAttrNames = load_addr_attr_names()\n\n\ndef load_addr_prefixes():\n path = os.path.abspath(getProjectRootPath() +\n 'data/attributes/addr/addr_prefixes.csv')\n with open(path, 'r') as f:\n names = [n.strip() for n in f.readlines()]\n return list(set(names))\n\n\n_AddrPrefixes = load_addr_prefixes()\n\n\nclass AddrAttribute(EntityAttribute):\n def column_name_cleanse(self):\n cleansed = re.sub(r'\\(|\\)|(|)|\\/|、', '', self.fullname)\n cleansed = cleansed.strip()\n return cleansed\n\n def find_attrs(self, column_name):\n \"\"\"\n 找到所有可以作为属性名的连续词组的候选集合。\n 首先根据词表匹配所有可以作为属性名的单词。\n 然后根据动态规划找到所有可能的属性名组合。\n \"\"\"\n matches = {}\n for n in _AddrAttrNames:\n if n in column_name:\n matches[n] = column_name.index(n)\n\n merged = []\n n = len(column_name)\n # 初始化所有动态规划所需二维数组。merged[i, j]=True表示fullname[i:j]对应的文本可以由词表连续组成。\n for i in range(n):\n merged.append([])\n for j in range(n):\n merged[i].append(False)\n for m in matches.keys():\n start = matches[m]\n end = start + len(m) - 1\n merged[start][end] = True\n # 动态规划按照长度算出所有可以由词表中的词组成的更长词组。算法复杂度O(n^3).没有任何优化。\n for l in range(n):\n for i in range(n - l):\n for k in range(l):\n if merged[i][i + k] and merged[i + k + 1][i + l]:\n merged[i][i + l] = True\n break\n attrs = []\n for i in range(n):\n for j in range(n):\n # if merged[i][j] and fullname[i:j+1] not in matches:\n if merged[i][j]:\n attrs.append(column_name[i:j + 1])\n return attrs\n\n def extract(self, fullname=None):\n if fullname is None:\n fullname = self.fullname\n fullname = self.column_name_cleanse()\n all_attrs = self.find_attrs(fullname)\n\n # 选长度最长的且更靠后的词组作为属性名称。\n longest_name = ''\n end_idx = -1\n for res in all_attrs:\n idx = fullname.index(res)\n if len(res) > len(longest_name) or (len(res) == len(longest_name) and idx + len(res) > end_idx):\n longest_name = res\n end_idx = idx + len(res)\n prefix = fullname[0: fullname.index(longest_name)]\n if longest_name == '':\n # if match the whole column expect the number suffix.\n remove_numeric_suffix = re.sub(r'\\d', '', fullname)\n if remove_numeric_suffix in _AddrPrefixes:\n self.prefix = fullname\n self.name = ''\n self.suffix = ''\n return (self.prefix, self.name, self.suffix)\n # try to find longest prefix matched\n longest_matched = ''\n for p in _AddrPrefixes:\n if fullname.startswith(p) and len(p) > len(longest_matched):\n longest_matched = p\n if longest_matched != '':\n prefix = longest_matched\n attribute = fullname[len(prefix):]\n suffix = ''\n self.prefix = prefix\n self.name = attribute\n self.suffix = suffix\n return\n else:\n # print('no match', self)\n return (self.prefix, self.name, self.suffix)\n\n # 根据前缀去调整\n if prefix != '':\n if prefix in _AddrPrefixes:\n self.name = longest_name\n self.prefix = prefix\n self.suffix = fullname[end_idx:]\n else:\n # try to find longest prefix matched\n longest_matched = ''\n for p in _AddrPrefixes:\n if prefix.startswith(p) and len(p) > len(longest_matched):\n longest_matched = p\n if longest_matched != '':\n prefix = longest_matched\n attribute = fullname[len(prefix): end_idx]\n suffix = fullname[end_idx:]\n else:\n prefix = ''\n attribute = fullname[:end_idx]\n suffix = fullname[end_idx:]\n self.prefix = prefix\n self.name = attribute\n self.suffix = suffix\n else:\n self.prefix = prefix\n self.name = longest_name\n self.suffix = fullname[end_idx:]\n # trim掉前后的特殊字符\n self.prefix = self.prefix.strip(' _-')\n self.name = self.name.strip(' _-')\n self.suffix = self.suffix.strip(' _-')\n return (self.prefix, self.name, self.suffix)\n\n\n\nclass AddrGroup(EntityGroup):\n def __init__(self):\n self.prefixes = {}\n self.attributes = {}\n self.suffixes = {}\n\n @property\n def entity_label(self):\n return '地点'\n\n def get_entity_related_rows(self):\n rows = self.table_data[self.table_data['ENTITY'] == self.entity_label]\n return rows\n\n def get_attr(self, attr_column):\n attr = AddrAttribute(attr_column)\n attr.extract()\n return (attr.prefix, attr.name, attr.suffix)\n\n def group(self):\n for _, row in self.table_data.iterrows():\n table_name = row[self.col_tablename]\n column_name = row[self.col_columnname]\n label_attr_name = row[self.col_l_attr]\n label_entity = row[self.col_l_entity]\n if label_entity != self.entity_label:\n continue\n attr_groups = self.get_attr(label_attr_name)\n prefix = attr_groups[0]\n name = attr_groups[1]\n suffix = attr_groups[2]\n\n if prefix is None:\n continue\n self.prefixes[prefix] = self.prefixes.get(prefix, 0) + 1\n self.attributes[name] = self.attributes.get(name, 0) + 1\n self.suffixes[suffix] = self.suffixes.get(suffix, 0) + 1\n\n need_group = True\n if need_group:\n append_dict = self.attrs_mapping_grouped\n self.grouped_attrs.append({\n 'tableName': table_name,\n 'columnName': column_name\n })\n else:\n append_dict = self.attrs_mapping_ungrouped\n self.ungrouped_attrs.append({\n 'tableName': table_name,\n 'columnName': column_name\n })\n\n if table_name not in append_dict.keys():\n append_dict[table_name] = {}\n if prefix not in append_dict[table_name].keys():\n append_dict[table_name][prefix] = []\n append_dict[table_name][prefix].append(\n {\n 'groupedAttrName': name + suffix,\n 'columnLabel': label_attr_name,\n 'groupedFullAttrName': prefix + name + suffix,\n 'groupedNamePart': name,\n 'groupedSuffixPart': suffix,\n 'groupedPrefixPart': prefix,\n 'columnName': column_name,\n 'tableName': table_name\n }\n )\n\n def generate_prefixes(self):\n pass\n\n\ndef extract_test():\n g = AddrGroup()\n g.load_table()\n for _, row in g.get_entity_related_rows().iterrows():\n print(row['COLUMN_NAME'], row['PROPERTY'],\n row['ENTITY'], g.get_attr(row['PROPERTY']))\n\n\ndef main():\n g = AddrGroup()\n g.load_table()\n g.group()\n with open('/Users/zhumuyao/data/stats/addr_attr.csv', 'w') as f:\n f.writelines([p[0] + ',' + str(p[1]) + '\\n' for p in sorted(\n g.attributes.items(), key=operator.itemgetter(1), reverse=True)])\n with open('/Users/zhumuyao/data/stats/addr_prefixes.csv', 'w') as f:\n f.writelines([p[0] + ',' + str(p[1]) + '\\n' for p in sorted(\n g.prefixes.items(), key=operator.itemgetter(1), reverse=True)])\n with open('/Users/zhumuyao/data/grouped_addr.json', 'w') as f:\n f.write(json.dumps(g.attrs_mapping_grouped, ensure_ascii=False))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/entity/processor/addr_processor.py","file_name":"addr_processor.py","file_ext":"py","file_size_in_byte":9269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"355242991","text":"log = __import__(\"logging\").getLogger(\"bungeni.core.workspace\")\nimport os\nfrom lxml import etree\n\nfrom zope.interface import implements\nfrom zope.app.publication.traversers import SimpleComponentTraverser\nfrom zope.security.proxy import removeSecurityProxy\nfrom zope.component import getUtility\nfrom zope.app.publisher.browser import getDefaultViewName\nfrom zope.publisher.interfaces import NotFound\nfrom zope.component import queryMultiAdapter\nfrom bungeni.utils.capi import capi\nfrom bungeni.models.workspace import stringKey\nfrom bungeni.core.interfaces import IWorkspaceTabsUtility\nfrom bungeni.models import domain\n\n\n# Tabs that are available in the workspace\n# All logged in users get a workspace with these tabs\nTABS = [\"draft\", \"inbox\", \"sent\", \"archive\"]\n\nclass WorkspaceContainerTraverser(SimpleComponentTraverser):\n \"\"\"Traverser for workspace containers\"\"\"\n\n def __init__(self, context, request):\n self.context = context \n self.request = request\n\n def publishTraverse(self, request, name):\n \"\"\"First checks if the name refers to a view of this container, \n then checks if the name refers to an item in this container, \n else raises a NotFound\n \"\"\"\n workspace = removeSecurityProxy(self.context)\n view = queryMultiAdapter((workspace, request), name=name)\n if view:\n return view\n ob = workspace.get(name) \n if ob:\n return ob \n raise NotFound(workspace, name) \n \nclass WorkspaceTabsUtility():\n \"\"\"This is utility stores the workflow configuration\n \"\"\"\n implements(IWorkspaceTabsUtility)\n \n workspaces = {}\n domain_type = {}\n \n def getDomainAndStatuses(self, role, tab):\n \"\"\"Returns a dictionary with the domain classes as keys. the value for \n each key is a dictionary of applicable statuses\"\"\"\n if role in self.workspaces.keys():\n if tab in self.workspaces[role].keys():\n return self.workspaces[role][tab]\n return None \n \n def setContent(self, role, tab, domain_class, status):\n \"\"\" Sets the \n \"\"\"\n if role not in self.workspaces:\n self.workspaces[role] = {}\n if tab not in self.workspaces[role]:\n self.workspaces[role][tab] = {}\n if domain_class not in self.workspaces[role][tab]:\n self.workspaces[role][tab][domain_class] = []\n self.workspaces[role][tab][domain_class].append(status)\n\n def registerItemType(self, domain_class, item_type):\n \"\"\" Stores domain_class -> item_type and vice versa in a dictionary eg.\n domain.Bill -> bill. Used by the Workspace Container to set the \n contained object names and to retrieve the contained objects given \n a name.\n \"\"\"\n if item_type in self.domain_type.keys():\n raise ValueError(\"Multiple workspace declarations with same name - %s\", item_type)\n if domain_class in self.domain_type.keys():\n raise ValueError(\"Multiple workspace domain classes with same name - %s\", item_type)\n self.domain_type[item_type] = domain_class\n self.domain_type[domain_class] = item_type \n \n def getDomainOrType(self, key):\n \"\"\"Passed either a domain_class or an item type, returns an item_type\n or domain_class respectively\"\"\"\n if key in self.domain_type:\n return self.domain_type[key]\n return None\n \ndef load_workspace(file_name, domain_class):\n \"\"\"Loads the workspace configuration for each documemnt\"\"\"\n workspace_tabs = getUtility(IWorkspaceTabsUtility)\n path = capi.get_path_for(\"workspace\")\n file_path = os.path.join(path, file_name)\n item_type = file_name.split(\".\")[0]\n workspace_tabs.registerItemType(domain_class, item_type)\n workspace = etree.fromstring(open(file_path).read())\n for state in workspace.iterchildren(\"state\"):\n for tab in state.iterchildren():\n if tab.get(\"id\") in TABS:\n if tab.get(\"roles\"):\n roles = tab.get(\"roles\").split()\n for role in roles:\n workspace_tabs.setContent(role, tab.get(\"id\"), domain_class, state.get(\"id\"))\n else:\n raise ValueError(\"Invalid tab - %s\", tab.get(\"id\"))\n \ndef load_workspaces(application, event):\n load_workspace(\"bill.xml\", domain.Bill)\n load_workspace(\"tableddocument.xml\", domain.TabledDocument)\n load_workspace(\"agendaitem.xml\", domain.AgendaItem)\n load_workspace(\"motion.xml\", domain.Motion)\n load_workspace(\"question.xml\", domain.Question) \n","sub_path":"bungeni.main/branches/sterch-issue712/bungeni/core/workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":4696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"421166978","text":"import sys\r\n#Matricies given in the file must be on just one line for this to work\r\ndef getData(path):\r\n '''\r\n Converts the data from the file into useable matricies\r\n If the matrix is like the one given as an example but not in the correct order, it will put it in the correct order\r\n '''\r\n #Each line of a file is a matrix\r\n f = [line for line in open(path, 'r')]\r\n #Iterates over each matrix, splitting it up into arrays which just contain [a,b,weight]\r\n data = []\r\n for matrix in f:\r\n #Splits each line on the opening square bracket\r\n matrix = matrix.split('[')\r\n m = []\r\n for element in matrix:\r\n e = []\r\n for char in element:\r\n #Removes all useless characters except commas as these are used to separate items in each element\r\n if char!=\"'\" and char!=\"]\" and char!=' ' and char!='\\n':\r\n e.append(char)\r\n #Turns e into an array containing [a,b,weight]\r\n e = ''.join(e)\r\n e = [i for i in e.split(',') if i!='']\r\n #Checks for empty arrays and removes from the new matrix if present\r\n if e!=[]:\r\n m.append(e)\r\n #By sorting the matrix, each column is grouped together - allowing matrices to be given in any order\r\n m.sort()\r\n data.append(m)\r\n return data\r\n\r\ndef getN(data, index):\r\n '''Counts the number of times which the first element occurs and so the value of n for the matrix'''\r\n matrix = data[index]\r\n n = 0\r\n firstElement = matrix[0][0]\r\n for element in matrix:\r\n if element[0]==firstElement:\r\n n+=1\r\n return n\r\n\r\ndef displayTables(data):\r\n '''Iterates over all of the matricies stored in the file, printing out the table of weights for each'''\r\n for index in range(len(data)):\r\n #Gets the value of n for each n*n matrix\r\n N = getN(data, index)\r\n\r\n #Sets the current matrix to be displayed\r\n matrix = data[index]\r\n #Generates the header for the table and prints it\r\n header = [matrix[e][0] for e in range(len(matrix)) if e%N==0]\r\n print(' ', end=' | ')\r\n for i in header:\r\n print(i, end=' | ')\r\n print()\r\n for r in range(1, N+1):\r\n #Gets the name of the row using the header\r\n name = header[r-1]\r\n #Gets the weights for this row\r\n row = [matrix[e][2] for e in range(N*(r-1),len(matrix)) if e<(N*r)]\r\n #Inserts the name at the start of the row\r\n row.insert(0,name)\r\n #Iterates over the row, printing it\r\n for i in row:\r\n print(i, end=' | ')\r\n print()\r\n print()\r\n\r\n'''\r\ndef HTMLTable(data):\r\n f = open('Table.HTML', 'w+')\r\n f.write('')\r\n for index in range(len(data)):\r\n #Gets the value of n for each n*n matrix\r\n N = getN(data, index)\r\n\r\n #Sets the current matrix to be displayed\r\n matrix = data[index]\r\n #Generates the header for the table and prints it\r\n header = [matrix[e][0] for e in range(len(matrix)) if e%N==0]\r\n header.insert(0,' ')\r\n f.write('')\r\n for i in header:\r\n line = ''\r\n f.write(line)\r\n f.write('')\r\n for r in range(1, N+1):\r\n f.write('')\r\n #Gets the name of the row using the header\r\n name = header[r-1]\r\n #Gets the weights for this row\r\n row = [matrix[e][2] for e in range(N*(r-1),len(matrix)) if e<(N*r)]\r\n #Inserts the name at the start of the row\r\n row.insert(0,name)\r\n for i in row:\r\n '''\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n #Iterates over all of the paths given as arguments, displaying the tables for each\r\n #sys.argv starts at the name of the python script when running from terminal using 'python MatrixRepresentation.py '\r\n for i in range(1, len(sys.argv)):\r\n path = sys.argv[i]\r\n try:\r\n #Checks if the path contains a file\r\n open(path, 'r')\r\n #If it does then continues the program\r\n displayTables(getData(path))\r\n except FileNotFoundError:\r\n #If it doesnt exist then print an error and dont run\r\n print('No such file: ', path)\r\n","sub_path":"MatrixRepresentation.py","file_name":"MatrixRepresentation.py","file_ext":"py","file_size_in_byte":4479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"35900159","text":"import download\nimport func\nimport hybrid\nimport programinfo\nimport searchhistory\nimport stream\nimport var\nimport xbmc\nimport xbmcgui\n\ndef switch_to_page():\n if var.guiSearch == None:\n var.guiSearch = Gui('vod.xml', var.addonpath, 'default', '720p')\n var.guiSearch.show()\n\ndef close_the_page():\n if var.guiSearch != None:\n #Close the shown window\n var.guiSearch.close()\n var.guiSearch = None\n\nclass Gui(xbmcgui.WindowXML):\n def onInit(self):\n #Load search history\n searchhistory.search_json_load()\n\n #Prepare the search page\n func.updateLabelText(self, 2, \"Zoeken\")\n self.buttons_add_navigation()\n listcontainer = self.getControl(1000)\n if listcontainer.size() == 0:\n if var.SearchDownloadResultJson == []:\n self.search_program()\n else:\n self.search_list(var.SearchDownloadResultJson)\n\n def onClick(self, clickId):\n clickedControl = self.getControl(clickId)\n if clickId == 1000:\n listItemSelected = clickedControl.getSelectedItem()\n listItemAction = listItemSelected.getProperty('Action')\n if listItemAction == 'play_stream':\n stream.play_stream_program(listItemSelected, False)\n elif clickId == 1001:\n listItemSelected = clickedControl.getSelectedItem()\n listItemAction = listItemSelected.getProperty('Action')\n if listItemAction == 'go_back':\n close_the_page()\n elif listItemAction == 'search_program':\n self.search_program()\n elif listItemAction == 'search_history':\n self.search_history()\n elif listItemAction == 'search_result':\n self.search_result()\n elif clickId == 9000:\n if xbmc.Player().isPlayingVideo():\n var.PlayerCustom.Fullscreen(True)\n else:\n listcontainer = self.getControl(1001)\n self.setFocus(listcontainer)\n xbmc.sleep(100)\n elif clickId == 3001:\n close_the_page()\n\n def onAction(self, action):\n actionId = action.getId()\n if (actionId == var.ACTION_PREVIOUS_MENU or actionId == var.ACTION_BACKSPACE):\n close_the_page()\n elif actionId == var.ACTION_NEXT_ITEM:\n xbmc.executebuiltin('Action(PageDown)')\n elif actionId == var.ACTION_PREV_ITEM:\n xbmc.executebuiltin('Action(PageUp)')\n elif actionId == var.ACTION_SEARCH_FUNCTION:\n self.search_program()\n\n def buttons_add_navigation(self):\n listcontainer = self.getControl(1001)\n if listcontainer.size() > 0: return True\n\n listitem = xbmcgui.ListItem('Ga een stap terug')\n listitem.setProperty('Action', 'go_back')\n listitem.setArt({'thumb': func.path_resources('resources/skins/default/media/common/back.png'), 'icon': func.path_resources('resources/skins/default/media/common/back.png')})\n listcontainer.addItem(listitem)\n\n listitem = xbmcgui.ListItem(\"Zoek programma\")\n listitem.setProperty('Action', 'search_program')\n listitem.setArt({'thumb': func.path_resources('resources/skins/default/media/common/search.png'), 'icon': func.path_resources('resources/skins/default/media/common/search.png')})\n listcontainer.addItem(listitem)\n\n listitem = xbmcgui.ListItem('Zoekgeschiedenis')\n listitem.setProperty('Action', 'search_history')\n listitem.setArt({'thumb': func.path_resources('resources/skins/default/media/common/searchhistory.png'), 'icon': func.path_resources('resources/skins/default/media/common/searchhistory.png')})\n listcontainer.addItem(listitem)\n\n listitem = xbmcgui.ListItem(\"Zoek in resultaat\")\n listitem.setProperty('Action', 'search_result')\n listitem.setArt({'thumb': func.path_resources('resources/skins/default/media/common/searchresult.png'), 'icon': func.path_resources('resources/skins/default/media/common/searchresult.png')})\n listcontainer.addItem(listitem)\n\n def search_result(self):\n #Check if search result is available\n if var.SearchDownloadResultJson == []:\n notificationIcon = func.path_resources('resources/skins/default/media/common/searchresult.png')\n xbmcgui.Dialog().notification(var.addonname, 'Geen zoek resultaten.', notificationIcon, 2500, False)\n return\n\n #Keyboard enter filter term\n keyboard = xbmc.Keyboard('default', 'heading')\n keyboard.setHeading('Zoek in resultaat')\n keyboard.setDefault('')\n keyboard.setHiddenInput(False)\n keyboard.doModal()\n if keyboard.isConfirmed() == True:\n var.SearchFilterTerm = keyboard.getText()\n self.search_list(var.SearchDownloadResultJson)\n var.SearchFilterTerm = ''\n\n def search_program(self):\n #Keyboard enter search term\n keyboard = xbmc.Keyboard('default', 'heading')\n keyboard.setHeading('Zoek naar programma')\n keyboard.setDefault('')\n keyboard.setHiddenInput(False)\n keyboard.doModal()\n if keyboard.isConfirmed() == True:\n searchProgramName = keyboard.getText()\n else:\n func.updateLabelText(self, 1, 'Geen zoek term')\n listcontainer = self.getControl(1001)\n self.setFocus(listcontainer)\n xbmc.sleep(100)\n listcontainer.selectItem(1)\n xbmc.sleep(100)\n return False\n\n #Check the search term\n if func.string_isnullorempty(searchProgramName) == True:\n func.updateLabelText(self, 1, 'Leeg zoek term')\n listcontainer = self.getControl(1001)\n self.setFocus(listcontainer)\n xbmc.sleep(100)\n listcontainer.selectItem(1)\n xbmc.sleep(100)\n return False\n\n #Add search history to Json\n searchhistory.search_add(searchProgramName)\n\n #Download the search programs\n func.updateLabelText(self, 1, \"Aan het zoeken\")\n downloadResult = download.download_search_program(searchProgramName)\n if downloadResult == None:\n func.updateLabelText(self, 1, 'Zoeken mislukt')\n listcontainer = self.getControl(1001)\n self.setFocus(listcontainer)\n xbmc.sleep(100)\n listcontainer.selectItem(0)\n xbmc.sleep(100)\n return False\n\n #Update the search result\n var.SearchDownloadSearchTerm = searchProgramName\n var.SearchDownloadResultJson = downloadResult\n\n #List the search results\n self.search_list(var.SearchDownloadResultJson)\n\n def search_history(self):\n #Get search term\n searchProgramName = searchhistory.search_dialog()\n\n #Check search term\n if func.string_isnullorempty(searchProgramName) == True:\n return\n\n #Add search history to Json\n searchhistory.search_add(searchProgramName)\n\n #Download the search programs\n func.updateLabelText(self, 1, \"Aan het zoeken\")\n downloadResult = download.download_search_program(searchProgramName)\n if downloadResult == None:\n func.updateLabelText(self, 1, 'Zoeken mislukt')\n listcontainer = self.getControl(1001)\n self.setFocus(listcontainer)\n xbmc.sleep(100)\n listcontainer.selectItem(0)\n xbmc.sleep(100)\n return False\n\n #Update the search result\n var.SearchDownloadSearchTerm = searchProgramName\n var.SearchDownloadResultJson = downloadResult\n\n #List the search results\n self.search_list(var.SearchDownloadResultJson)\n\n def search_list(self, downloadResult=None):\n #Get and check the list container\n listcontainer = self.getControl(1000)\n listcontainer.reset()\n\n #Add programs to the list\n for program in downloadResult['resultObj']['containers']:\n try:\n ExternalId = str(program['channel']['externalChannelId'])\n ProgramId = str(program['metadata']['contentId'])\n ProgramName = programinfo.programtitle_from_json_metadata(program)\n EpisodeTitle = programinfo.episodetitle_from_json_metadata(program)\n ProgramTimeStartDateTime = func.datetime_from_ticks(int(program['metadata']['airingStartTime']))\n ProgramTimeStartDateTime = func.datetime_remove_seconds(ProgramTimeStartDateTime)\n ProgramTimeStartStringTime = ProgramTimeStartDateTime.strftime('%H:%M')\n ProgramTimeStartStringDate = ProgramTimeStartDateTime.strftime('%a, %d %B %Y')\n except:\n continue\n\n #Check if there are search results\n if var.SearchFilterTerm != '':\n searchResultFound = var.SearchFilterTerm.lower() in ProgramName.lower() or var.SearchFilterTerm.lower() in EpisodeTitle.lower()\n if searchResultFound == False:\n continue\n\n #Generate program details\n ProgramYear = programinfo.programyear_from_json_metadata(program)\n ProgramSeason = programinfo.programseason_from_json_metadata(program)\n ProgramEpisode = programinfo.episodenumber_from_json_metadata(program)\n ProgramAgeRating = programinfo.programagerating_from_json_metadata(program)\n ProgramDuration = programinfo.programdurationstring_from_json_metadata(program, False)\n\n #Combine program description\n ProgramDescription = 'Begon om ' + ProgramTimeStartStringTime + ' op ' + ProgramTimeStartStringDate + ' en duurde ' + ProgramDuration\n\n #Combine program details\n stringJoin = [ EpisodeTitle, ProgramYear, ProgramSeason, ProgramEpisode, ProgramAgeRating ]\n ProgramDetails = ' '.join(filter(None, stringJoin))\n if func.string_isnullorempty(ProgramDetails):\n ProgramDetails = '(?)'\n\n #Update program name string\n ProgramName += ' [COLOR gray]' + ProgramDetails + '[/COLOR]'\n\n #Add search program\n listitem = xbmcgui.ListItem()\n listitem.setProperty('Action', 'play_stream')\n listitem.setProperty('ProgramId', ProgramId)\n listitem.setProperty(\"ProgramName\", ProgramName)\n listitem.setProperty('ProgramDescription', ProgramDescription)\n listitem.setInfo('video', {'Genre': 'Zoeken', 'Plot': ProgramDescription})\n listitem.setArt({'thumb': func.path_icon_television(ExternalId), 'icon': func.path_icon_television(ExternalId)})\n listcontainer.addItem(listitem)\n\n #Update the status\n self.count_search(True)\n\n #Update the status\n def count_search(self, resetSelect=False):\n listcontainer = self.getControl(1000)\n if listcontainer.size() > 0:\n func.updateLabelText(self, 1, str(listcontainer.size()) + \" zoek resultaten\")\n func.updateLabelText(self, 3, \"Zoek resultaten voor \" + var.SearchDownloadSearchTerm + \" [COLOR gray]\" + var.SearchFilterTerm + \"[/COLOR]\")\n if resetSelect == True:\n self.setFocus(listcontainer)\n xbmc.sleep(100)\n listcontainer.selectItem(0)\n xbmc.sleep(100)\n else:\n func.updateLabelText(self, 1, \"Geen zoek resultaten\")\n func.updateLabelText(self, 3, \"Geen zoek resultaten voor \" + var.SearchDownloadSearchTerm + \" [COLOR gray]\" + var.SearchFilterTerm + \"[/COLOR]\")\n listcontainer = self.getControl(1001)\n self.setFocus(listcontainer)\n xbmc.sleep(100)\n if var.SearchFilterTerm != '':\n listcontainer.selectItem(3)\n xbmc.sleep(100)\n else:\n listcontainer.selectItem(1)\n xbmc.sleep(100)\n","sub_path":"Kodi/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":11971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"628601800","text":"import json\nimport os\nimport shutil\nfrom urllib import request\nfrom zipfile import ZipFile\n\nfrom pkg_resources import parse_version\n\n\ndef versions(pkg_name):\n url = f'https://pypi.python.org/pypi/{pkg_name}/json'\n response = json.loads(request.urlopen(url).read())\n print(json.dumps(response))\n releases = response['releases']\n latest_versions = sorted(releases, key=parse_version, reverse=True)[0]\n for x in releases[latest_versions]:\n print(x[\"url\"])\n file_name = x[\"url\"]\n new_file_name = \"new/{}\".format(file_name.split(\"/\")[-1])\n if new_file_name.endswith(\".tar.gz\"):\n continue\n request.urlretrieve(file_name, new_file_name)\n\n z = ZipFile(new_file_name)\n x_list = [y for y in z.namelist() if y.endswith(\".pyd\") or y.endswith(\".so\")]\n print(x_list)\n\n if not x_list:\n continue\n\n with z.open(x_list[0]) as myfile:\n # print(myfile.read())\n with open(\"bin/{}\".format(str(x_list[0]).split(\"/\")[-1]), \"bw\") as f:\n f.write(myfile.read())\n\n return True\n\n\ndef build_wheel():\n print(os.listdir(os.path.abspath(\"bin\")))\n dist_path = [x for x in os.listdir(os.path.abspath(\"dist\")) if x.endswith(\".whl\")][0]\n with ZipFile(\"dist/{}\".format(dist_path), mode='a') as bz:\n for x in tuple(os.listdir(os.path.abspath(\"bin\"))):\n bz.write(\"bin/{}\".format(x), arcname=\"psycopg2/{}\".format(x))\n\n return True\n\n\nif __name__ == '__main__':\n if not os.path.exists('new'):\n os.makedirs('new')\n if not os.path.exists('bin'):\n os.makedirs('bin')\n\n versions(\"psycopg2-binary\")\n # versions(\"psycopg2\")\n build_wheel()\n # shutil.rmtree(\"new\")\n","sub_path":"compile_and_build.py","file_name":"compile_and_build.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"552296256","text":"from django.conf.urls import url\nfrom yaml import load_all\nfrom squealy.views import SqlApiView\nfrom rest_framework.authentication import *\nfrom rest_framework.permissions import *\n\nclass ApiGenerator():\n\n @staticmethod\n def generate_urls_from_yaml(file_path):\n urlpatterns = []\n with open(file_path) as f:\n api_configs = load_all(f)\n for config in api_configs:\n apiview_class = ApiGenerator._generate_api_view(config)\n if config.get(\"authentication_classes\"):\n apiview_class.authentication_classes = []\n for authentication_class_as_str in config.get(\"authentication_classes\"):\n apiview_class.authentication_classes.append(eval(authentication_class_as_str))\n if config.get(\"permission_classes\"):\n apiview_class.permission_classes = []\n for permission_class_as_str in config.get(\"permission_classes\"):\n apiview_class.permission_classes.append(eval(permission_class_as_str))\n\n urlpatterns.append(url(r'^'+config['url'], apiview_class.as_view()))\n\n return urlpatterns\n\n @staticmethod\n def _generate_api_view(config):\n return type(config['id'], (SqlApiView, ), config)\n","sub_path":"squealy/apigenerator.py","file_name":"apigenerator.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439448057","text":"# -*- coding: utf-8 -*-\n'''\n封装HTTP请求操作\nhttp_request是主方法,直接供外部调用\n__http_get, __http_post是实际底层分类调用的方法\n'''\n# review 190926\n\nimport requests, logging, sys\nsys.path.append('../')\nfrom common import opmysql\nfrom public import config\n\nclass RequestInterface(object):\n def __new_param(self, param):\n try:\n if isinstance(param, str) and param.startswith('{'):\n new_param = eval(param)\n elif param == None:\n new_param = ''\n else:\n new_param = param\n except Exception as error:\n new_param = ''\n logging.basicConfig(filename = config.src_path + '/log/syserror.log', \n level = logging.DEBUG, \n format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s')\n logger = logging.getLogger(__name__)\n logger.exception(error) \n return new_param\n \n def __http_post(self, interface_url, headerdata, interface_param):\n try:\n if interface_url != '':\n temp_interface_param = self.__new_param(interface_param)\n response = requests.post(url=interface_url,\n headers=headerdata,\n data=temp_interface_param,\n verify=False,\n timeout=10)\n if response.status_code == 200:\n# durtime = (response.elapsed.microseconds) / 1000\n result = {'code': '0000', 'message':'Success!', 'data':response.text}\n else:\n result = {'code': '2004', 'message':'Interface State Error!', 'data':[]}\n elif interface_url == '':\n result = {'code': '2002', 'message':'Interface Address Param is None', 'data':[]}\n else:\n result = {'code': '2003', 'message':'Interface Address Error', 'data':[]}\n except Exception as error:\n result = {'code': '9999', 'message':'Systerm Abnormal', 'data':[]}\n logging.basicConfig(filename = config.src_path + '/log/syserror.log', \n level = logging.DEBUG, \n format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s')\n logger = logging.getLogger(__name__)\n logger.exception(error) \n return result\n\n \n def __http_get(self, interface_url, headerdata, interface_param):\n try:\n if interface_url != '':\n temp_interface_param = self.__new_param(interface_param)\n if interface_url.endswith('?'):\n requrl = interface_url + temp_interface_param\n else:\n requrl = interface_url + '?' + temp_interface_param\n response = requests.get(url=requrl)\n print('HTTP GET RESULT ---> %s' % response)\n if response.status_code == 200:\n# durtime = (response.elapsed.microseconds) / 1000\n result = {'code': '0000', 'message':'Success!', 'data':response.text}\n else:\n result = {'code': '3004', 'message':'Interface State Error!', 'data':[]}\n elif interface_url == '':\n result = {'code': '3002', 'message':'Interface Address Param is None', 'data':[]}\n else:\n result = {'code': '3003', 'message':'Interface Address Error', 'data':[]}\n except Exception as error:\n result = {'code': '9999', 'message':'Systerm Abnormal', 'data':[]}\n logging.basicConfig(filename = config.src_path + '/log/syserror.log', \n level = logging.DEBUG, \n format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s')\n logger = logging.getLogger(__name__)\n logger.exception(error) \n return result\n \n def http_request(self, interface_url, headerdata, interface_param, request_type):\n try:\n if request_type == 'get' or request_type == 'GET':\n result = self.__http_get(interface_url, headerdata, interface_param)\n elif request_type == 'post' or request_type == 'POST':\n result = self.__http_post(interface_url, headerdata, interface_param)\n else:\n result = {'code':'1000', 'message':'Request Type Error. Type is Neighter GET nor POST.', 'data': request_type}\n except Exception as error:\n result = {'code': '9999', 'message':'Systerm Abnormal', 'data':[]}\n logging.basicConfig(filename = config.src_path + '/log/syserror.log', \n level = logging.DEBUG, \n format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s')\n logger = logging.getLogger(__name__)\n logger.exception(error) \n return result\n\nif __name__ == '__main__':\n test_interface = RequestInterface()\n test_db = opmysql.OperationDbInterface(host_db='127.0.0.1',\n user_db='root',\n passwd_db='123456',\n name_db='test_interface',\n port_db=3306, link_type=0)\n sen_sql = 'select exe_mode, url_interface, header_interface, params_interface from case_interface where id=1'\n params_interface = test_db.select_one(sen_sql)\n if params_interface['code'] == '0000':\n url_interface=params_interface['data']['url_interface']\n temp=params_interface['data']['header_interface']\n headerdata=eval(params_interface['data']['header_interface'])#unicode转换成字典\n param_interface=params_interface['data']['params_interface']\n type_interface=params_interface['data']['exe_mode']\n if url_interface !='' and headerdata !='' and param_interface !='' and type_interface !='':\n result=test_interface.http_request(interface_url=url_interface,\n headerdata=headerdata,\n interface_param=param_interface,\n request_type=type_interface)\n if result['code']=='0000':\n result_resp=result['data']\n test_db.op_sql(\"UPDATE case_interface SET result_interface='%s' WHERE id=1\" % result_resp)\n print(\"处理http请求成功,返回数据是:%s\" % result_resp)\n else:\n print(\"处理http请求失败\")\n else:\n print(\"测试用例数据中有空值\")\n else:\n print(\"获取接口测试用例数据失败\") \n","sub_path":"Desktop/myself/Project/autotest_interface_36/common/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":6970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"352809721","text":"import unittest\nimport tempfile\nimport os\n\nfrom file_encryptor import key_generators\n\nclass TestKeyGenerators(unittest.TestCase):\n def setUp(self):\n self.directory = tempfile.mkdtemp()\n\n self.sample1 = os.path.join(self.directory, \"super1.txt\")\n self.sample2 = os.path.join(self.directory, \"super2.txt\")\n self.sample3 = os.path.join(self.directory, \"frowny.txt\")\n\n with open(self.sample1, \"wb\") as f:\n f.write(\"Superstar!\\n\".encode())\n\n with open(self.sample2, \"wb\") as f:\n f.write(\"Superstar!\\n\".encode())\n\n with open(self.sample3, \"wb\") as f:\n f.write(\"Frowny face :(\\n\".encode())\n\n def tearDown(self):\n os.remove(self.sample1)\n os.remove(self.sample2)\n os.remove(self.sample3)\n os.rmdir(self.directory)\n\n def test_key_generation(self):\n key_generators.key_from_file(self.sample1, None)\n\n def test_deterministic_key_generation(self):\n self.assertEqual(\n key_generators.key_from_file(self.sample1, None),\n key_generators.key_from_file(self.sample2, None))\n\n def test_passphrase_does_something(self):\n self.assertNotEqual(\n key_generators.key_from_file(self.sample1, \"Shh!\"),\n key_generators.key_from_file(self.sample2, \"Hello\"))\n\n def test_different_files_yield_different_keys(self):\n self.assertNotEqual(\n key_generators.key_from_file(self.sample1, None),\n key_generators.key_from_file(self.sample3, None))\n","sub_path":"file_encryptor/test_key_generators.py","file_name":"test_key_generators.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"122504245","text":"# Import our pymongo library, which lets us connect our Flask app to our Mongo database.\r\nimport pymongo\r\nimport pandas as pd\r\n\r\n# Create connection variable\r\nconn = 'mongodb://localhost:27017'\r\n\r\n# Pass connection to the pymongo instance.\r\nclient = pymongo.MongoClient(conn)\r\n\r\n# Connect to a database. Will create one if not already available.\r\ndb = client.primary_completion_db\r\n# Drops collection if available to remove duplicates\r\ndb.primary_completion.drop()\r\n\r\n# Creates a collection in the database and inserts two documents\r\ndf_primary_completion = pd.read_csv('https://raw.githubusercontent.com/DavidMoon-184/Roosters_Project_2/main/FLASK/datasets/primary_completion_world.csv')\r\n\r\ndef insert_db():\r\n for i, row in df_primary_completion.iterrows():\r\n doc = {\r\n '_id': f'doc_{i}',\r\n 'Country Name': row[\"Country Name\"],\r\n 'Country Code': row[\"Country Code\"],\r\n 'time': row[\"time\"],\r\n 'primary_completion_rate_total_percent_of_relevant_age_group': row[\"primary_completion_rate_total_percent_of_relevant_age_group\"],\r\n 'Numeric code': row[\"Numeric code\"]\r\n }\r\n db.primary_completion.insert_one(doc)\r\n\r\n print(\"collection created\")\r\n\r\ninsert_db()","sub_path":"FLASK/datasets/munging/db_primary_school.py","file_name":"db_primary_school.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"617595208","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 12 12:42:05 2020\n\n@author: licciar\n\"\"\"\n\n\n# These functions are used before training to split the train/va/test sets\n# As this is done preprocess is applied and statistics are calculated.\n# Workflow:\n # 1) \n\n\nimport numpy as np\nimport h5py\nfrom scipy import signal\nimport random\n#COMPUTE STATISTICS OF TRAIN SET\n\ndef update(count, mean, M2, newValue):\n# (count, mean, M2) = existingAggregate\n count += 1\n delta = newValue - mean\n mean += delta / count\n delta2 = newValue - mean\n M2 += delta * delta2\n\n return (count, mean, M2)\n\n# Retrieve the mean, variance and sample variance from an aggregate\ndef finalize(count, mean, M2):\n# (count, mean, M2) = existingAggregate\n if count < 2:\n return float('nan')\n else:\n (mean, variance, sampleVariance) = (mean, M2 / count, M2 / (count - 1))\n return (mean, variance, sampleVariance)\n\n\n\ndef preprocess_databases(pegs_db_path,\n noise_db_path,\n out_db_name,\n idx_train,\n idx_val,\n idx_test,\n active_idx, \n sort_idx,\n sos1,\n sos2):\n \n # INPUTS:\n \n # pegs_db_path\n # noise_db_path\n # idx_train\n # idx_val\n # idx_test\n # active_idx\n # sort_idx\n \n # sos1\n # sos2\n \n # Workflow:\n \n # 1) Split database of pegs in train, val, test sets\n # for each daabase:\n # 2) Select active stations and sort them as provided\n # 3) Select noise traces at random for each entry\n # 4) Filter PEGS and NOISE using provided filters\n # 5) Add NOISE to PEGS\n # 6) Compute statistcs for train set for standardization/normalization in training\n # 7) Save dataset\n \n # OUTPUTS\n # This function saves three datasets in hdf5 format\n \n \n buffer = 1000\n t_len = 350\n\n ncomp = 3\n #nsamp = 3\n countt = 0\n \n \n \n ############################## CREATE EMPTY DATABASE ###################\n ntotsamp = len(idx_test) + len(idx_train) + len(idx_val)\n n_stations = len(active_idx)\n # out_db_name = \"../DATABASES/run_db.hdf5\"\n with h5py.File(out_db_name, 'w') as f:\n \n # Get the dimensions right and create the four datasets\n pegs_dim = ((ntotsamp, n_stations, t_len, ncomp))\n f.create_dataset(\"pegs_w_noise\", pegs_dim, dtype = 'float64' ) \n f.create_dataset(\"pegs_w_noise_clip\", pegs_dim, dtype = 'float64' ) \n f.create_dataset(\"noise\", pegs_dim, dtype = 'float64' ) \n f.create_dataset(\"ptime\", (ntotsamp, n_stations), dtype = 'float32' ) \n f.create_dataset(\"eq_params\", (ntotsamp, 5), dtype = 'float32' ) \n f.create_dataset(\"clip\", (n_stations,ncomp,3), dtype = 'float64' )\n \n \n tkw = signal.tukey(t_len+buffer*2,0.05)\n \n for dataset in ['train', 'val', 'test']:\n \n if dataset == 'train':\n indic = idx_train\n elif dataset =='val':\n indic = idx_val\n else:\n indic = idx_test\n \n \n \n nsamp = len(indic)\n\n maxi = np.zeros((n_stations,ncomp,3))\n maxi[:,:,0] += 1000.0\n \n \n if (dataset == 'train'):\n massi = np.zeros(ncomp)\n mini = np.zeros(ncomp) + 10000.0\n \n meant = np.zeros(ncomp)\n M2t = np.zeros(ncomp)\n countt = np.zeros(ncomp)\n newval = np.zeros(ncomp)\n \n MEAN = np.zeros(ncomp)\n VAR = np.zeros(ncomp)\n SAMPVAR = np.zeros(ncomp)\n\n \n for i in range(nsamp):\n \n if(i%1000 == 0 ):\n print (dataset + ' dataset. Working on sample ' + str(i) + '/' + str(nsamp))\n \n \n ####################################### GET PEGS #################### \n with h5py.File(pegs_db_path, 'r') as f:\n labels = np.array(f['eq_params'][indic[i],]) \n # Use the following for noise free pegs\n temp = np.array(f['pegs'][indic[i], ]) \n X = temp[active_idx,:,:ncomp]\n temp = np.array(f['ptime'][indic[i], :])\n pwav = temp[active_idx]\n # pwav = np.array(f['ptime'][ind,:]) \n \n # Replace first zeros with next value\n X[:,0,:] = X[:,1,:]\n # Sort\n X = X[sort_idx,:,:] \n pwav = pwav[sort_idx] \n \n #adjust depth label\n if(labels[4] == 30.0):\n labels[4] = 1\n else:\n labels[4] = 0\n\n ################################ GET NOISE AT RANDOM #################### \n with h5py.File(noise_db_path, 'r') as f:\n tmp = f[\"noise_traces\"]\n noise_nsamp = tmp.shape[0]\n \n noise_idx = np.random.randint (low=0, high=noise_nsamp)\n \n \n with h5py.File(noise_db_path, 'r') as f:\n temp = np.array(f[\"noise_traces\"][noise_idx, ])\n X_noise = temp[active_idx,:,:ncomp]\n temp = np.array(f[\"tables\"][noise_idx, ])\n noise_tables = temp[active_idx]\n noise_means = np.array(f[\"statistics\"][noise_idx,:,:ncomp,0 ])\n clip = np.array(f[\"clip\"][noise_idx,:,:ncomp])\n \n # Sort Stations\n X_noise = X_noise[sort_idx, :,:]\n # Sort Tables\n noise_tables = noise_tables[sort_idx]\n # Sort clip valuess\n clip = clip[sort_idx,:]\n \n \n X_noise_filt = signal.detrend(X_noise, axis=1, type='constant')\n # X_noise_filt = signal.detrend(X_noise_filt, axis=1)\n \n X_noise_filt = signal.sosfilt(sos1, X_noise,axis=1)\n X_noise_filt = signal.sosfilt(sos2, X_noise_filt,axis=1)\n \n # noise_means_filt = signal.detrend(noise_means, axis=0, type='constant')\n # noise_means_filt = signal.detrend(noise_means_filt, axis=0)\n noise_means_filt = signal.sosfilt(sos1, noise_means,axis=0)\n noise_means_filt = signal.sosfilt(sos2, noise_means_filt,axis=0)\n \n # Cut 350 seconds at random\n start_noise = np.random.randint(low=buffer, high=3600-t_len-buffer) # Index of starting noise\n t1 = start_noise #- buffer\n t2 = start_noise + t_len # + buffer\n \n noise = X_noise_filt[:, t1:t2, :]\n \n meanflag = False\n if meanflag:\n # noise = signal.detrend(noise, axis=0, type='linear')\n noise = signal.detrend(noise, axis=0, type='constant')\n \n means = noise_means_filt[t1:t2, :]\n ########################################################################## \n \n X1 = np.zeros(X.shape)\n NOISE = np.zeros(X.shape)\n # MUting 5% of stations\n mutfac = 0.05\n num_muted = np.int(np.ceil(X.shape[0] *mutfac))\n idx_muted = random.sample(range(X.shape[0]), num_muted)\n \n # LOOP OVER STATIONS\n for j in range(X.shape[0]):\n \n # P-Wave arrival\n indP = np.array(np.floor(pwav[j]), dtype=int)\n # LOOP OVER COMPONENT\n for comp in range(ncomp):\n #\n # # Add noise\n ntrace = noise[j,:,comp].copy()\n \n # # Check if we have only zeros for this noise segment\n # if not noise_tables[j]: \n # # If it's a vector of zeros replace with overall mean\n \n # # print(j, 'replacing zeros with mean')\n # # if(i==0 and comp==0):\n # # with open(\"./log.txt\",\"a\") as f:\n # # f.write(str(self.sort_stat_idx[j]) + \"\\n\")\n # ntrace = means[:,comp].copy()\n \n \n \n # # ntrace = signal.detrend(ntrace)\n # # ntrace = signal.detrend(ntrace,type='constant')\n # # ntrace *= tkw\n # ntrace = signal.sosfilt(sos1, ntrace)\n # ntrace = signal.sosfilt(sos2, ntrace)\n \n X[j, :, comp] = signal.sosfilt(sos1, X[j,:,comp])\n X[j, :, comp] = signal.sosfilt(sos2, X[j,:,comp])\n \n X[j, :, comp ] += ntrace#[buffer : t_len+buffer]\n \n X1[j,:,comp] = X[j, :, comp ] \n NOISE[j,:,comp] = ntrace\n \n \n ############### SET capping based on P-WAVE ARRIVAL ###############\n # Set everything after P-wave arrival -2s to val\n # Val is the value at P-wave arrival -2s\n val = X[j, indP, comp]\n X1[j, indP:,comp] = val\n \n\n \n \n # If this station has to be muted\n if j in idx_muted:\n X1[j, :, comp] = 0.0\n \n #Check if we have only zeros for this noise segment\n if not noise_tables[j]: \n # # If there isn't noise data set trace to zero\n # if all(v == 0.0 for v in ntrace):\n X1[j, :, comp] = 0.0\n \n else: \n \n if(dataset=='train'):\n val = np.std(ntrace)#[buffer : t_len+buffer])\n # Store std for mean calculations\n \n maxi[j,comp,2] += val\n # Find minimum std \n if valmaxi[j,comp,1]:\n maxi[j,comp,1] = val\n \n \n \n\n \n \n \n \n # \n\n \n # # Cap amplitudes\n # cap = 10.0 * clip[j,comp] #np.std(ntrace[buffer:self.dim2+buffer])\n \n # for k in range(X.shape[1]):\n # val = X[j, k, comp]\n \n # if (np.abs(val) > cap):\n # X[j, k:, comp ] = cap\n # if (val>0.0):\n # X[j, k:, comp ] = cap\n # else:\n # X[j, k:, comp ] = -1.0 * cap\n # break\n \n \n \n # # COmpute statistics of trainset per channel\n # if (dataset == 'train'):\n # valmax = X1.max()\n # valmin = X1.min() \n # if valmax > massi:\n # massi = valmax\n # if valmin < mini:\n # mini = valmin\n \n # # COmpute running mean and variance \n # if i == 0:\n # meant = X1.copy()\n # M2t = np.zeros((X.shape))\n # countt = 1\n # else: \n # newval = X1.copy()\n # countt, meant, M2t = update(countt, meant, M2t, newval) \n \n \n # COmpute running mean and variance \n # if i == 0:\n # meant[comp] = X1.mean(axis=(0,1))[comp]\n # M2t[comp] = 0.0#X1.var(axis=(0,1))[comp]\n # countt[comp] = 1\n # else: \n # newval[comp] = X1.mean(axis=(0,1))[comp]\n # countt[comp], meant[comp], M2t[comp] = update(countt[comp],\n # meant[comp],\n # M2t[comp], \n # newval[comp]) \n\n \n # print (\"Computing stats for sample: \" + str(i) + \"and comp: \" + str(comp) )\n # print(\"massi[comp]: \" + str(massi[comp]))\n # print(\"mini[comp]: \" + str(mini[comp]) )\n # print(\"meant[comp]: \" + str(meant[comp]) )\n # print(\"count[comp]: \" + str(countt[comp]) )\n # FILL NEW DATABASE\n with h5py.File(out_db_name, 'a') as f:\n # SAVE EQ PARAMS\n f[\"eq_params\"][indic[i], ] = labels\n f[\"pegs_w_noise\"][indic[i], ] = X\n f[\"pegs_w_noise_clip\"][indic[i], ] = X1\n f[\"noise\"][indic[i], ] = NOISE\n f[\"ptime\"][indic[i], ] = pwav \n \n if (dataset == 'train'): \n for comp in range(ncomp):\n # COmpute statistics of trainset per channel\n # Update min, max\n valmax = X1.max(axis=(0,1))[comp]\n valmin = X1.min(axis=(0,1))[comp] \n if valmax > massi[comp]:\n massi[comp] = valmax\n if valmin < mini[comp]:\n mini[comp] = valmin \n \n if(i==0):\n CUM1 = np.zeros(X.shape)\n CUM2 = np.zeros(X.shape)\n CUM3 = 0.0\n CUM4 = 0.0\n N = nsamp #* X.size/3\n N1 = N * X.size/3\n CUM3 += X1.sum(axis=(0,1))\n CUM4 += np.sum(X1**2, axis=(0,1))\n CUM1 += X1\n CUM2 += X1**2 \n \n \n\n \n \n # if (dataset=='train'):\n # MEAN[0], VAR[0], SAMPVAR[0] = finalize (countt[0],meant[0],M2t[0])\n \n # MEAN[1], VAR[1], SAMPVAR[1] = finalize (countt[1],meant[1],M2t[1])\n \n # MEAN[2], VAR[2], SAMPVAR[2] = finalize (countt[2],meant[2],M2t[2])\n \n \n # print (\"Finalized mean for comp: 0 \" + str(MEAN[0] ))\n # print (\"Finalized mean for comp: 1 \" + str(MEAN[1] ))\n # print (\"Finalized mean for comp: 2 \" + str(MEAN[2] ))\n if (dataset=='train'): \n # Compute mean std for each station and component \n maxi[:,:,2] /= nsamp\n \n with h5py.File(out_db_name,'a') as f:\n # Save clipping values\n f[\"clip\"][:] = maxi\n \n # return MEAN, np.sqrt(SAMPVAR), mini, massi \n # N = X.size/ncomp\n MEAN_image = CUM1/N\n VAR_image = 1.0/(N*(N-1)) * (N* CUM2 - (CUM1)**2)\n MEAN = CUM3/N1\n VAR= 1.0/(N1*(N1-1)) * (N1* CUM4 - (CUM3)**2)\n return MEAN_image, np.sqrt(VAR_image), MEAN, np.sqrt(VAR), mini, massi \n\n \n \n \n \n \n \n \n \n \n \n \n# \n# \n# \n# \n# \n# \n# \n# \n# nsamp = len(list_train) \n# # We can't load the whole database at once so I work with batches\n# nbatch = np.int(nsamp/batchsize)\n# \n# \n# massi = 0.0\n# mini = 1000.0\n# \n# for i in range(nbatch):\n# \n# print ('Working on batch ' + str(i+1) + '/' + str(nbatch))\n# ind0 = i*batchsize\n# ind1 = (i+1)*batchsize\n# # print (ind0, ind1)\n# \n# # Load data\n# with h5py.File(databasepath,'r') as f:\n# X = f['pegs'][ind0:ind1]\n# # X1 = f['pegs_w_noise'][ind0:ind1]\n# valmax = X.max()\n# valmin = X.min() \n# if valmax > massi:\n# massi = valmax\n# if valmin < mini:\n# mini = valmin\n# \n# if i == 0:\n# meant = np.mean(X)\n# countt= 1\n# M2t = 0.0\n# else: \n# newval = np.mean(X)\n# countt, meant, M2t = update(countt, meant, M2t, newval)\n# \n# MEAN, VAR, SAMPVAR = finalize(countt, meant, M2t)\n# \n# return MEAN, np.sqrt(VAR) , mini, massi \n\n","sub_path":"DVAE_WSC_TORCH_THEO/preprocess_databases.py","file_name":"preprocess_databases.py","file_ext":"py","file_size_in_byte":17188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"312772767","text":"# coding: utf-8\nfrom DTOdefault import *\n\n#Importe pour faire un message box\nimport ctypes \n\n'''\n\tClasse DTO qui donne accès aux valeurs de la balance\n\t\n'''\n\n\nclass DTO():\n\tdef __init__(self):\n\t\tself.speed_chars = ()\n\t\tself.speed_rotation_chars = ()\n\t\tself.points_vie_chars = ()\n\t\tself.time_move_blocs = ()\n\t\tself.canon_speed_ball = ()\n\t\tself.canon_load_time = ()\n\t\tself.mitrail_speed_ball = ()\n\t\tself.mitrail_load_time = ()\n\t\tself.grenade_speed_init_ball = ()\n\t\tself.grenade_load_time = ()\n\t\tself.shotgun_speed_ball = ()\n\t\tself.shotgun_load_time = ()\n\t\tself.shotgun_ouverture_fusil = ()\n\t\tself.piege_speed_ball = ()\n\t\tself.piege_load_time = ()\n\t\tself.missile_speed_ball = ()\n\t\tself.missile_load_time = ()\n\t\tself.spring_speed_init_jump = ()\n\t\tself.spring_load_time = ()\n\t\tself.size_explode_ball = ()\n\t\tself.mess_accueil_content = ()\n\t\tself.mess_accueil_time = ()\n\t\tself.mess_countdown_time = ()\n\t\tself.mess_startGame_content = ()\n\t\tself.mess_endGame_content = ()\n\n\tdef verifier(self):\n\n\t\tDTOdef = DTOdefault()\n\n\t\tfor key, value in self.__dict__.items():\n\t\t\tif(key == 'mess_accueil_content' or key == 'mess_startGame_content' or key == 'mess_endGame_content'):\n\t\t\t\tif(value[0] is None or value[1] is None):\n\t\t\t\t\tself.__dict__[key] = DTOdef.__dict__[key]\n\t\t\t\t\tctypes.windll.user32.MessageBoxA(0, \"Le message ne respect pas les criteres ! Il prend les valeurs par défaut\", \"Valeur incorrecte !\", 0)\n\t\t\telse:\n\t\t\t\tif(value[0] is None and value[1] is None and value[2] is None):\n\t\t\t\t\tself.__dict__[key] = DTOdef.__dict__[key]\n\t\t\t\t\tctypes.windll.user32.MessageBoxA(0, \"Le message ne respect pas les criteres ! Il prend les valeurs par défaut\", \"Valeur incorrecte !\", 0)\n\t\t\t\tif(value[2] < value[0] ):\n\t\t\t\t\tself.__dict__[key] = (value[0], value[1], value[0])\n\t\t\t\t\tctypes.windll.user32.MessageBoxA(0, \"La valeur est plus petit que le minimum !\", \"Valeur incorrecte !\", 0)\t\t\t\t\t\n\t\t\t\tif(value[2] > value[1]):\n\t\t\t\t\tself.__dict__[key] = (value[0], value[1], value[1])\n\t\t\t\t\tctypes.windll.user32.MessageBoxA(0, \"La valeur est plus grand que le maximum !\", \"Valeur incorrecte !\", 0)\t\t\t\n\t\t\t\tif (value[0] > value[1]):\n\t\t\t\t\tvalueMin = value[0]\n\t\t\t\t\tvalue[0] = value[1]\n\t\t\t\t\tvalue[1] = valueMin\n\t\t\t\t\tctypes.windll.user32.MessageBoxA(0, \"Le minimum est plus grand que le maximum !\", \"Valeur incorrecte !\", 0)\n","sub_path":"tankem/Tankem/src/DTO/DTO.py","file_name":"DTO.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"546396708","text":"import os\nimport SimpleITK\nimport dicom\nimport numpy as np\nimport cv2\nimport glob\nfrom tqdm import tqdm\nimport itk\nImageType2dC=itk.Image[itk.UC,2]\nImageType2dS=itk.Image[itk.SS,2]\nImageType2dF=itk.Image[itk.F,2]\n\n\ndef body_slice(image):\n # get target mask for removing background noise\n \n image=itk.GetImageFromArray(image.astype(np.float32))\n\n ctBackgroundRange=5\n ctBackgroundValue=-200\n #morphlogicalCloseRadius=20\n\n#  sigmoid function to increase the contrast near ctBackgroundValue\n sigmoidImageFilter=itk.SigmoidImageFilter[ImageType2dF,ImageType2dF].New()\n sigmoidImageFilter.SetInput(image)\n sigmoidImageFilter.SetAlpha(-ctBackgroundRange)\n sigmoidImageFilter.SetBeta(ctBackgroundValue)\n sigmoidImageFilter.SetOutputMaximum(1)\n sigmoidImageFilter.SetOutputMinimum(1e-3)\n\n\n # fast marching begin form the four corners\n fastMarchingFilter=itk.FastMarchingImageFilter[ImageType2dF,ImageType2dF].New()\n\n fastMarchingFilter.SetInput(sigmoidImageFilter.GetOutput())\n # define four nodes\n size=image.GetLargestPossibleRegion().GetSize()\n spacing=image.GetSpacing()\n points=[(0,0),(0,size[1]-1),(size[0]-1,0),(size[0]-1,size[1]-1)]\n NodeType=itk.LevelSetNode.F2\n NodeContainer=itk.VectorContainer[itk.UI,NodeType]\n container=NodeContainer.New()\n container.Initialize()\n for i,p in enumerate(points):\n node=NodeType()\n node.SetIndex(p)\n node.SetValue(0.0)\n container.InsertElement(i,node)\n fastMarchingFilter.SetTrialPoints(container)\n # get the binary mask\n thresholdFilter=itk.BinaryThresholdImageFilter[ImageType2dF,ImageType2dC].New()\n thresholdFilter.SetInput(fastMarchingFilter.GetOutput())\n thresholdFilter.SetLowerThreshold(0)\n thresholdFilter.SetUpperThreshold(10000)\n thresholdFilter.SetOutsideValue(1)\n thresholdFilter.SetInsideValue(0)\n maskBody=itk.GetArrayFromImage(thresholdFilter.GetOutput())\n return maskBody\ndef normalize_hu(image):\n '''\n 将输入图像的像素值(-1000 ~ 400)归一化到0~1之间\n :param image 输入的图像数组\n :return: 归一化处理后的图像数组\n '''\n\n MIN_BOUND = -1000.0\n MAX_BOUND = 400.0\n #image[image < -1000] = 0.\n image = (image - MIN_BOUND)/(MAX_BOUND - MIN_BOUND)\n image[image > 1] = 1.\n image[image < 0] = 0.\n return image\ndef ospath(root):\n dataset = glob.glob(os.path.join('%s' % root, '*'))\n dataset.sort()\n dataset = dataset[:10000]\n return dataset\ndef itk_image_series_reader(dicom_path):\n image_type = itk.Image[itk.F, 2]\n reader = itk.ImageFileReader[image_type].New()\n reader.SetFileName(dicom_path)\n reader.Update()\n itk_image = reader.GetOutput()\n return itk_image\nif __name__ == '__main__':\n dicom_dir = 'E:/data-101/CT_dim/'\n dataset = ospath(dicom_dir)\n count = 0\n \n for i in tqdm(range(len(dataset))):\n img_path = \"E:/data-101/CT_png/\" + str(count).rjust(5, '0') + \".png\"\n ds = itk_image_series_reader(dataset[i]) # read dicom\n ds = itk.GetArrayFromImage(ds) #get array \n org_img = normalize_hu(ds) # normalization\n maskbody = body_slice(ds) # get mask (0,1)\n final_img = (org_img*255)*maskbody #Target Segmentation\n cv2.imwrite(img_path, final_img) # write png\n count +=1\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"131863651","text":"import time\nimport logging\n\nimport numpy as np\n\nfrom multiprocessing import Pool\nfrom recommender.base import BaseRecommender, RecommenderNotTrainedError\nfrom sklearn.cluster import AffinityPropagation\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass UserIntersection(BaseRecommender):\n \"\"\"\n Constructs a matrix of intersections of user_ids among high and frequently\n ranked books, then performs a dimensionality reduction to find which\n books form groups liked by similar users.\n\n Parameters\n ----------\n\n min_book_rating : minimal rating for a user to be included in the group\n\n min_ratings_count: minimal number of rantings for a book to be included \n in the intersection matrix\n\n min_ratings_mean: minimal mean rating for a book to be included in \n the intersection matrix\n\n min_neighbours: minimal number of books for a group found by the affinity \n propagation algorithm to be considered\n \"\"\"\n\n def __init__(self,\n min_book_rating=7,\n min_ratings_count=10,\n min_ratings_mean=6,\n min_neighbours=10):\n super().__init__()\n\n self.expected_keys = [\n 'books',\n 'users',\n 'ratings'\n ]\n\n self.min_book_rating = min_book_rating\n self.min_ratings_count = min_ratings_count\n self.min_ratings_mean = min_ratings_mean\n self.min_neighbours = min_neighbours\n\n self.explicit_rating_counts = None\n self.explicit_rating_means = None\n\n self._high_ranking_users = {}\n\n self.matrix_isbns = None\n self.intersection_matrix = None\n\n self.book_groups = {}\n\n def train(self,\n data: dict):\n \"\"\"\n Prepares a model for the recommendation algorithm.\n\n Parameters\n ----------\n\n data : a dict of the form:\n\n {\n 'books': pandas.DataFrame,\n 'users': pandas.DataFrame,\n 'ratings': pandas.DataFrame\n }\n \"\"\"\n self.data = data\n\n self._get_explicit_rating_features()\n self._get_user_intersection_matrix()\n\n self._cluster()\n\n def _get_explicit_rating_features(self):\n \"\"\"\n Agregates count and mean of ratings for each book.\n \"\"\"\n logging.info(\n 'aggregating explicit book ratings'\n )\n\n explicit_ratings = self.data['ratings'].loc[self.data['ratings'].rating != 0]\n\n self.explicit_rating_counts = explicit_ratings.groupby('ISBN')[\n 'rating'].count()\n\n self.explicit_rating_means = explicit_ratings.groupby('ISBN')[\n 'rating'].mean()\n\n def _get_user_intersection_matrix(self):\n \"\"\"\n Prepares a matrix of user \n intersection ratios among these books.\n \"\"\"\n logging.info(\n 'constructing the user intersection matrix'\n )\n\n high_rated_isbns = np.intersect1d(\n self.explicit_rating_counts[self.explicit_rating_counts >\n self.min_ratings_count].index.values,\n self.explicit_rating_means[self.explicit_rating_means >\n self.min_ratings_mean].index.values\n )\n\n high_rating_user_df = self.data['ratings'].loc[\n (self.data['ratings'].rating > self.min_book_rating) &\n self.data['ratings'].ISBN.isin(high_rated_isbns)\n ][['ISBN', 'user_id']]\n\n groupped = high_rating_user_df.groupby('ISBN')\n\n self.matrix_isbns = high_rating_user_df.ISBN.unique()\n\n for isbn, group in groupped:\n self._high_ranking_users[isbn] = group.user_id.unique()\n\n prior = time.time()\n\n with Pool(processes=12) as pool:\n res = pool.map(self._get_single_row, self.matrix_isbns)\n\n final_dict = {}\n\n for r in res:\n final_dict.update(r)\n\n self.intersection_matrix = np.array(\n [final_dict[isbn] for isbn in self.matrix_isbns]\n )\n\n # remove self intersections:\n self.intersection_matrix[self.intersection_matrix == 1.0] = 0\n\n logging.info(\n 'intersection_matrix constructed in %.2e seconds' % (\n time.time() - prior)\n )\n\n def _get_single_row(self,\n isbn):\n \"\"\"\n Calculates a single row of the intersection matrix.\n \"\"\"\n return {\n isbn: [\n np.isin(self._high_ranking_users[isbn], self._high_ranking_users[isbn_other]).sum(\n ) / len(self._high_ranking_users[isbn])\n for isbn_other in self.matrix_isbns\n ]\n }\n\n def _cluster(self):\n \"\"\"\n Applies affinity propagation to find groups of books\n liked by the same users.\n \"\"\"\n clusters = AffinityPropagation().fit(self.intersection_matrix)\n\n labels, label_counts = np.unique(clusters.labels_, return_counts=True)\n\n enough_neighbour_labels = labels[label_counts > self.min_neighbours]\n\n _book_groups = {}\n\n for isbn, label in zip(self.matrix_isbns, clusters.labels_):\n if label not in enough_neighbour_labels:\n continue\n\n try:\n _book_groups[label]['isbns'].append(isbn)\n _book_groups[label]['users'].append(\n self._high_ranking_users[isbn]\n )\n\n except KeyError:\n _book_groups[label] = {\n 'isbns': [isbn],\n 'users': [self._high_ranking_users[isbn]]\n }\n\n for label in _book_groups:\n self.book_groups[label] = {\n 'isbns': np.array(_book_groups[label]['isbns']),\n 'users': np.concatenate(_book_groups[label]['users'])\n }\n\n def predict(self,\n user_isbns: np.ndarray) -> np.ndarray:\n \"\"\"\n Selects users who liked user_isbns and finds their\n intersections with book_groups.\n Finds ISBNs of books within a group which \n has the largest intersection.\n\n PARAMETERS\n ----------\n\n user_isbns : an array of ISBNS liked by the user\n\n RETURNS\n -------\n\n similar_isbns : ISBNs from the group with the largest intersection, \n None if all intersections are zero\n \"\"\"\n if len(self.book_groups) == 0:\n raise RecommenderNotTrainedError(\n 'Method train must be called first'\n )\n\n prior = time.time()\n\n similar_user_group = self.data['ratings'].loc[\n self.data['ratings'].ISBN.isin(user_isbns) &\n (self.data['ratings'].rating > self.min_ratings_mean)\n ].user_id.unique()\n\n logging.info(\n 'Similar user group found in %.2e seconds' % (time.time() - prior)\n )\n\n intersections = np.zeros(len(self.book_groups))\n group_ids = np.zeros(len(self.book_groups))\n\n for i, book_group_id in enumerate(self.book_groups):\n intersections[i] = np.isin(\n similar_user_group,\n self.book_groups[book_group_id]['users']\n ).sum() / len(similar_user_group)\n\n group_ids[i] = book_group_id\n\n if intersections.sum() == 0:\n return None\n\n return self.book_groups[group_ids[np.argmax(\n intersections)]]['isbns']\n","sub_path":"recommender/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":7521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"278686628","text":"'''\nCreated on May 5, 2021\n\n@author: kivag\n'''\n\nclass Triangle():\n number_of_sides = 3\n\n def __init__(self, angle1, angle2, angle3):\n # self.number_of_sides = 3\n \n self.angle1 = angle1\n self.angle2 = angle2\n self.angle3 = angle3\n \n def check_angles(self):\n if self.angle1 + self.angle2 + self.angle3 == 180:\n return True\n else:\n return False\n\n\nif __name__ == '__main__':\n my_triangle = Triangle(45, 45, 90)\n \n print(my_triangle.number_of_sides, my_triangle.check_angles())\n ","sub_path":"oop/geometry/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"83365233","text":"import pytest\n\n\ndef pytest_addoption(parser):\n \"\"\"Add a command line option to skip tests that require installation.\"\"\"\n parser.addoption(\n \"--installation\",\n action=\"store_true\",\n default=False,\n help=\"run tests that require installation\")\n\n\ndef pytest_collection_modifyitems(config, items):\n \"\"\"Select tests to run based on command line options.\"\"\"\n if config.getoption(\"--installation\"):\n return\n skip_install = pytest.mark.skip(reason=\"need --installation option to run\")\n for item in items:\n if \"install\" in item.keywords:\n item.add_marker(skip_install)\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"498215351","text":"import scipy.integrate as spi\nfrom iterative_solution import compute_true_avg as cta\nfrom iterative_solution import compute_true_avg_alternate as ctaa\nfrom multivariate_chebpoly import multi_var_chebpoly as mvc\nfrom multivariate_chebpoly import vectorized_mvc as vmvc\n\n# from sobol_lib import i4_sobol # for QMC points\n# import mcint # for automated MC method\n\nimport numpy as np\nimport math\n\nimport os.path\n\n\nfrom mpmath import *\n\ndef coefs_nquad_wrapper(a_nu): \n return spi.nquad(lambda x0,x1,x2,x3,x4,x5: ctaa([np.array([x0,x1,x2,x3,x4,x5])], 1.0, 1.0/6.0, 5.0 )*mvc([x0,x1,x2,x3,x4,x5],a_nu),[[-1,1]]*6)\n\ndef coefs_mpmath_wrapper(a_nu): # seems like there is no way to use mpmath for more than 3 dimensions :( \n mp.dps = 10 # 10 digits of accuracy should be more than enough.\n return quad(lambda x0,x1,x2,x3,x4,x5: ctaa([np.array([x0,x1,x2,x3,x4,x5])], 1.0, 1.0/6.0, 5.0 )*mvc([x0,x1,x2,x3,x4,x5],a_nu),[-1,1],[-1,1],[-1,1],[-1,1],[-1,1],[-1,1], method='tanh-sinh') # tanh-sinh tends to be more accurate when dealing with singularities\n\n\n# def coefs_dbltpl_wrapper(a_nu): # Will work only for the 6 dimensional case\n # return spi.tplquad(secondIntegrals, -1., 1., fun_mone, fun_one, fun_mone, fun_one, args=a_nu)\n\ndef coefs_dbltpl_wrapper(nu0,nu1,nu2,nu3,nu4,nu5): # Will work only for the 6 dimensional case\n return spi.tplquad(secondIntegrals, -1., 1., fun_mone, fun_one, fun_mone, fun_one, args=(nu0,nu1,nu2,nu3,nu4,nu5))\n\ndef coefs_MC_wrapper(nb_samples, a_nu, with_cheb_weights = False, rhs = 1., variability = 1./6., abar = 5.): \n domainsize = 1. # math.pow(2,6)\n np.random.seed(1)\n loc_integrand = lambda x0, x1, x2, x3, x4, x5: integrand(x0,x1,x2,x3,x4,x5, a_nu[0],a_nu[1],a_nu[2],a_nu[3],a_nu[4],a_nu[5], with_cheb_weights, rhs, variability, abar)\n result, error = mcint.integrate(loc_integrand, sampler(), measure=domainsize, n=nb_samples)\n return result\n\ndef coefs_QMCSobol_wrapper(nb_samples, a_nu): # note that a lot of calculations will be repeated by doing this. We need to be smarter!\n int_val = 0\n seed = 0\n dim = 6\n for one_sample in xrange(0,nb_samples): \n [sample, new_seed] = i4_sobol(6, seed)\n int_val = int_val + ctaa(sample, 1.0,1.0/6,5.)*mvc(sample,a_nu)\n seed = new_seed\n return int_val/nb_samples\n\ndef faster_QMC_computations(nb_samples, nus): # note that a lot of calculations will be repeated by doing this. We need to be smarter!\n # first find the highest degree considered in the list of nu's\n # then go through the samples, one at a time, and everytime we see a new value, we add to the dictionary together with the T_j(value)\n max_degree = np.max(nus)\n cheb_evals = {}\n weights_eval = {}\n int_val = 0 # as for integral value\n seed = 0 # required for the sobol index\n dim = 6 # that hurts!\n for one_sample in xrange(0,nb_samples): \n [sample, new_seed] = i4_sobol(6, seed)\n sample = sample*2 -1 # To set the anchor at (-1,-1,-1 ...) instead of the usual (0,0,...) for QMC methods\n not_computed = [a_param for a_param in one_sample if a_param not in cheb_evals] # contains the values that we have not precomputed before\n for to_compute in not_computed:\n # add these guys to the dictionary. \n to_add_to_dict = [1]\n for one_deg in xrange(1,max_degree+1): \n to_add_to_dict.append(np.polynomial.chebyshev.chebval(to_compute, np.hstack( (np.zeros(one_deg),1) )))\n cheb_evals[to_compute] = to_add_to_dict\n weights_eval[to_compute] = np.polynomial.chebyshev.chebweight(to_compute)\n int_val = int_val + ctaa(sample-1, 1.0,1.0/6,5.)*mvc(sample,a_nu)\n seed = new_seed\n return int_val/nb_samples\n\ndef coefs_Smolyak_wrapper():\n return 1\n\ndef integrand(x0,x1,x2,x3,x4,x5,nu0,nu1,nu2,nu3,nu4,nu5, with_weights = True, rhs = 1., variability = 1.0/6., abar = 5.):\n # print ctaa([np.array([x0,x1,x2,x3,x4,x5])], rhs, variability, abar )\n return ctaa([np.array([x0,x1,x2,x3,x4,x5])], rhs, variability, abar )*mvc([x0,x1,x2,x3,x4,x5],np.array([nu0,nu1,nu2,nu3,nu4,nu5]), with_weights)\n# def integrand(x0,x1,x2,x3,x4,x5,a_nu):\n # return ctaa([np.array([x0,x1,x2,x3,x4,x5])], 1.0, 1.0/6.0, 5.0 )*mvc([x0,x1,x2,x3,x4,x5],a_nu)\n\n# def secondIntegrals(x3,x4,x5,a_nu):\n # res, err = spi.tplquad(integrand, -1., 1., fun_mone, fun_one, fun_mone, fun_one, args=(x3,x4,x5,a_nu))\n # return res\n\ndef secondIntegrals(x3,x4,x5,nu0,nu1,nu2,nu3,nu4,nu5):\n res, err = spi.tplquad(integrand, -1., 1., fun_mone, fun_one, fun_mone, fun_one, args=(x3,x4,x5,nu0,nu1,nu2,nu3,nu4,nu5))\n return res\n\ndef mpsecondIntegrals(x3,x4,x5,nu0,nu1,nu2,nu3,nu4,nu5):\n res, err = tplquad(integrand, [-1., 1.], [-1., 1.], [-1., 1.], args=(x3,x4,x5,nu0,nu1,nu2,nu3,nu4,nu5))\n return res\n\ndef fun_one(p1 = 0, p2 = 0): # the boundaries of the tplquad have to be functions of 0, 1, or 2 variables!\n return 1.0\n\ndef fun_mone(p1 = 0, p2 = 0): # the boundaries of the tplquad have to be functions of 0, 1, or 2 variables!\n return -1.0\n\ndef sampler(): # for the Monte-Carlo approach\n while True: # Generates the chebyshev measures via a uniform measure\n x0 = math.cos(np.random.uniform(0,math.pi))\n x1 = math.cos(np.random.uniform(0,math.pi))\n x2 = math.cos(np.random.uniform(0,math.pi))\n x3 = math.cos(np.random.uniform(0,math.pi))\n x4 = math.cos(np.random.uniform(0,math.pi))\n x5 = math.cos(np.random.uniform(0,math.pi))\n yield (x0, x1, x2, x3, x4, x5)\n\ndef vectorized_MC_integration(tot_tests, a_nu, batch_size = 100000, rhs = 1., variability = 1./6., mean_field = 5., regular_saves = True, dump_fname = None): # This can be adapted to make it better for later tests. At the moment, it is implemented fast and dirty for our particular setup\n\n final_avg = 0\n\n # Since lists, nd_arrays are not hashable, we need to create a key (unique) for each nu... \n hashable_nu = '{}'.format(a_nu)\n print('******************* Current nu = ' + hashable_nu)\n\n ## This definitely needs to be done better! \n if dump_fname is None:\n dump_fname = 'MCEstimations_PWLD_6dim_small_var.npy'\n if os.path.isfile(dump_fname) is False:\n dict_results = {hashable_nu: {}} # or load if the file already exists\n batches = range(batch_size, tot_tests + 1, batch_size)\n else:\n dict_results = np.load(dump_fname).item()\n if hashable_nu not in dict_results:\n dict_results[hashable_nu] = {}\n nb_tests = 0\n batches = range(batch_size, tot_tests + 1, batch_size)\n else: \n computed_tests = sorted(dict_results[hashable_nu].keys())\n if tot_tests >= computed_tests[-1]:\n batches = range(computed_tests[-1]+batch_size, tot_tests+1, batch_size)\n nb_tests = computed_tests[-1]\n final_avg = dict_results[hashable_nu][computed_tests[-1]]*computed_tests[-1]\n else:\n nb_tests = computed_tests[[computed_tests[i]-tot_tests >= 0 for i in xrange(0,len(computed_tests))].index(True)-1]\n batches = range(nb_tests+batch_size, tot_tests+1, batch_size)\n final_avg = dict_results[hashable_nu][nb_tests]*nb_tests\n\n\n for a_batch in batches:\n print('\\tCurrent number of test samples: {}'.format(a_batch)) \n if a_batch in dict_results[hashable_nu]: \n # Don't redo the calculation, and load the one already done:\n nb_tests = a_batch\n final_avg = dict_results[hashable_nu][nb_tests]*nb_tests\n else: \n nb_tests = a_batch\n zs = np.cos(np.random.uniform(0,np.pi,[batch_size, 6]))\n ys = ctaa(zs, rhs, variability, mean_field)\n cheb_vals = vmvc(zs,a_nu)\n final_avg = final_avg + sum(ys*cheb_vals)\n dict_results[hashable_nu][nb_tests] = final_avg/nb_tests\n np.save(dump_fname, dict_results) \n\n # one last batch of tests to make sure we have the required number\n remaining_tests = tot_tests - nb_tests\n if remaining_tests > 0:\n nb_tests = nb_tests+remaining_tests\n zs = np.cos(np.random.uniform(0,np.pi,[remaining_tests, 6]))\n ys = ctaa(zs, rhs, variability, mean_field)\n cheb_vals = vmvc(zs,a_nu)\n final_avg = final_avg + sum(ys*cheb_vals)\n dict_results[hashable_nu][nb_tests] = final_avg/nb_tests\n np.save(dump_fname, dict_results) \n\n return final_avg/nb_tests\n","sub_path":"CSPG/num_int.py","file_name":"num_int.py","file_ext":"py","file_size_in_byte":8502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"100305184","text":"import sys, os\nimport numpy as np\nimport pandas as pd\n\n# $3: provided train feature (X_train)\n# $4: provided train label (Y_train)\n# $5: provided test feature (X_test)\n# $6: prediction.csv\n\ndef readTrainData(X_train, Y_train):\n # traing Data\n X_train = pd.read_csv(X_train).as_matrix() #shape: (32561, 106)\n Y_train = pd.read_csv(Y_train).as_matrix() #shape: (32561, 1)\n Y_train = Y_train.reshape(Y_train.shape[0]) #shape: (32561,)\n mean = np.mean(X_train, axis=0) #shape: (106,)\n std = np.std(X_train, axis=0) #shape: (106,)\n X_train = (X_train - mean) / (std + 1e-100)\n\n return X_train, Y_train, mean, std\n\ndef sigmoid(z):\n res = 1 / (1.0 + np.exp(-z))\n return np.clip(res, 0.00000000000001, 0.99999999999999)\n\ndef calculateError(X_train, Y_train, weights, bias):\n f = sigmoid(np.dot(X_train, weights) + bias)\n return Y_train - f, f\n\ndef calculateLoss(Y_train, f):\n return -np.mean(Y_train*np.log(f+1e-100) + (1-Y_train)*np.log(1-f+1e-100))\n\ndef calculateAccuracy(Y_train, f):\n f[f >= 0.5] = 1\n f[f < 0.5] = 0\n acc = Y_train - f #shape: (32561,)\n acc[acc == 0] = 2\n acc[acc != 2] = 0\n return np.sum(acc) * 50 / acc.shape[0]\n\ndef logisticRegression(LEARNING_RATE, ITERATION, X_train, Y_train):\n bias_descent = 0.0 # init bias\n weights_descent = np.ones(X_train.shape[1]) # init weights\n B_lr = 0.0 #Adagrad\n W_lr = np.zeros(X_train.shape[1]) #Adagrad\n\n for index in range(ITERATION):\n error, f = calculateError(X_train, Y_train, weights_descent, bias_descent)\n\n B_grad = -np.sum(error) * 1.0\n W_grad = -np.dot(X_train.T, error) # renew each weights\n\n B_lr += B_grad ** 2\n W_lr += W_grad ** 2\n\n bias_descent = bias_descent - LEARNING_RATE / np.sqrt(B_lr) * B_grad\n weights_descent = weights_descent - LEARNING_RATE / np.sqrt(W_lr) * W_grad\n current_loss = calculateLoss(Y_train, f)\n current_accuracy = calculateAccuracy(Y_train, f)\n print('\\rIteration: {} \\tAccuracy: {} \\tLoss: {}'.format(str(index+1), current_accuracy, current_loss), end='' ,flush=True)\n print()\n return bias_descent, weights_descent\n\ndef main(argv):\n LEARNING_RATE = 0.5\n ITERATION = 3500\n X_train, Y_train, mean, std = readTrainData(argv[1], argv[2])\n final_bias, final_weights = logisticRegression(LEARNING_RATE, ITERATION, X_train, Y_train)\n writeText = \"id,label\\n\"\n X_test = pd.read_csv(argv[3]).as_matrix() #shape: (16281, 106)\n X_test = (X_test - mean) / (std + 1e-100)\n\n predict_income = final_bias + np.dot(X_test, final_weights)\n\n for index, i in enumerate(predict_income):\n result = 0\n if i>=0:\n result = 1\n writeText += str(index+1) + \",\" + str(int(result)) + \"\\n\"\n filename = argv[4]\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n with open(filename, \"w\") as f:\n f.write(writeText)\n\nif __name__ == '__main__':\n main(sys.argv)\n # readTrainData()\n","sub_path":"hw2/hw2_logistic.py","file_name":"hw2_logistic.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608241136","text":"from datetime import datetime\nimport logging\n\nfrom google.appengine.api import users\nfrom google.appengine.api.blobstore.blobstore import BlobKey\nfrom google.appengine.ext import ndb\nfrom handlers import base_handlers\nfrom models import Contact, ContactList, TextMessageEvent\nfrom utils import account_utils, date_utils, message_utils\nfrom google.appengine.ext.webapp import blobstore_handlers\n\n\nclass AccountInfoAction(base_handlers.BaseAction):\n \"\"\"Set account info for this user.\"\"\"\n def handle_post(self, user, account_info):\n account_info.twilio_sid = self.request.get(\"twilio_sid\")\n account_info.twilio_auth_token = self.request.get(\"twilio_auth_token\") \n account_info.twilio_phone_number = self.request.get(\"twilio_phone_number\")\n account_info.auto_response_sms = self.request.get(\"auto_response_sms\")\n account_info.auto_response_voice = self.request.get(\"auto_response_voice\") \n account_info.time_zone = self.request.get(\"time_zone\") \n account_info.signature_text = self.request.get(\"signature_text\")\n account_info.put()\n self.redirect(\"/\")\n\n\nclass InsertContactAction(base_handlers.BaseAction):\n \"\"\"Insert a new contact or update and existing contact.\"\"\"\n def handle_post(self, user, account_info):\n phone_number = self.request.get('phone_number')\n urlsafe_entity_key = self.request.get('contact_entity_key')\n if len(urlsafe_entity_key) > 0:\n contact_key = ndb.Key(urlsafe=urlsafe_entity_key)\n if contact_key.string_id() == phone_number:\n # The phone number is the same, just do a simple edit\n contact = contact_key.get()\n else:\n # The phone number has changed. ugh. Do it the hard way.\n logging.info(\"The phone number changed when editing this contact!\")\n original_contact = contact_key.get()\n contact = Contact(parent=account_utils.get_parent_key(user), id=phone_number)\n contact.list_keys = original_contact.list_keys\n original_contact.key.delete() # Remove the old one to avoid a duplicate contact.\n \n else:\n contact = Contact(parent=account_utils.get_parent_key(user), id=phone_number)\n\n # Update all fields other than the list_keys field. Leave it alone in case this is an edit.\n contact.nickname = self.request.get('nickname')\n contact.phone_number = phone_number\n contact.real_first_name = self.request.get('real_first_name')\n contact.real_last_name = self.request.get('real_last_name')\n contact.email = self.request.get('email')\n contact.other_info = self.request.get('other_info')\n \n contact.put()\n self.redirect(\"/contacts\")\n\n\nclass AddListAction(base_handlers.BaseAction):\n \"\"\"Create a new list and go straight into editing it.\"\"\"\n def handle_post(self, user, account_info):\n new_list = ContactList(parent=account_utils.get_parent_key(user),\n name=self.request.get('name'))\n new_list.put()\n self.redirect(\"/list?list_key=\" + new_list.key.urlsafe())\n\n\nclass UpdateListAction(base_handlers.BaseAction):\n \"\"\"Update the contacts that are in this list.\"\"\"\n def handle_post(self, user, account_info):\n contact_list_name = self.request.get('contact_list_name')\n urlsafe_entity_key = self.request.get('contact_list_entity_key')\n urlsafe_contact_keys_to_add = self.request.get('contact_keys_to_add')\n urlsafe_contact_keys_to_remove = self.request.get('contact_keys_to_remove')\n\n add_to_keys = urlsafe_contact_keys_to_add.split(\",\")\n remove_from_keys = urlsafe_contact_keys_to_remove.split(\",\")\n\n contact_list_key = ndb.Key(urlsafe=urlsafe_entity_key)\n for add_to_key in add_to_keys:\n if len(add_to_key) > 0:\n contact = ndb.Key(urlsafe=add_to_key).get()\n contact.list_keys.append(contact_list_key)\n contact.put()\n for remove_from_key in remove_from_keys:\n if len(remove_from_key) > 0:\n contact = ndb.Key(urlsafe=remove_from_key).get()\n contact.list_keys.remove(contact_list_key)\n contact.put()\n\n # Update the list name if necessary.\n contact_list = contact_list_key.get()\n if contact_list_name != contact_list.name:\n contact_list.name = contact_list_name\n contact_list.put()\n\n self.redirect(\"/lists\")\n\n\nclass InsertTextMessageEventAction(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n user = users.get_current_user()\n \n # If this is an \"edit\" start by deleting the old event and just make a new one from scratch.\n # Note, \"edits\" like this only work if there is no other data saved on the object.\n urlsafe_text_message_event_key = self.request.get(\"urlsafe_text_message_event_key\")\n if urlsafe_text_message_event_key:\n text_message_event_key = ndb.Key(urlsafe=urlsafe_text_message_event_key)\n message_utils.delete_text_message_event(text_message_event_key.get())\n\n # Create a new text message event\n text_message_event = TextMessageEvent(parent=account_utils.get_parent_key(user),\n message_body=self.request.get(\"message_body\"))\n \n # Determine the send_datetime (making sure it's in UTC).\n send_now = False\n if self.request.get(\"when_radio_group\") == \"scheduled\":\n send_datetime = date_utils.get_utc_datetime_from_user_input(account_utils.get_account_info(user).time_zone,\n self.request.get(\"send_date_time\"))\n elif self.request.get(\"when_radio_group\") == \"now\":\n send_datetime = datetime.now()\n send_now = True\n else:\n raise Exception(\"Invalid send time radio selected.\")\n text_message_event.send_datetime = send_datetime\n \n # Determine who the text message is to\n if self.request.get(\"to_radio_group\") == \"list\":\n text_message_event.recipient_type = TextMessageEvent.RecipientType.LIST\n text_message_event.recipient_list_key = ndb.Key(urlsafe=self.request.get(\"to_list\"))\n elif self.request.get(\"to_radio_group\") == \"individual\":\n text_message_event.recipient_type = TextMessageEvent.RecipientType.INDIVIDUAL\n text_message_event.recipient_contact_key = ndb.Key(urlsafe=self.request.get(\"to_individual\"))\n elif self.request.get(\"to_radio_group\") == \"all\":\n text_message_event.recipient_type = TextMessageEvent.RecipientType.ALL\n else:\n raise Exception(\"Invalid recipient type\")\n \n if self.get_uploads() and len(self.get_uploads()) == 1:\n logging.info(\"Received an image blob with this text message event.\")\n media_blob = self.get_uploads()[0]\n text_message_event.media_blob_key = media_blob.key()\n else:\n # There is a chance this is an edit in which case we should check for an existing blob key.\n original_blob_key = self.request.get(\"original_blob_key\")\n if original_blob_key:\n logging.info(\"Attaching original blob key (this must have been an edit or duplicate)\")\n text_message_event.media_blob_key = BlobKey(original_blob_key)\n else:\n logging.info(\"This message is an SMS without an image attachment.\")\n\n \n # TODO: Send the message, schedule the message, or do nothing (if it is too far away).\n # Note, each path should perform a .put() on the text message event (at the time of its choosing).\n if send_now:\n message_utils.send_message_now(text_message_event)\n else:\n if date_utils.is_within_next_24_hours(text_message_event.send_datetime):\n message_utils.add_text_message_event_to_task_queue(text_message_event)\n else: \n logging.info(\"Text message event saved, but not added to the task queue because it is not within the next 24 hours.\")\n text_message_event.put()\n text_message_event.put() # For now just make sure the event is saved without doing any sending\n \n self.redirect(\"/text-messages\")\n","sub_path":"gae-project/handlers/insert_handlers.py","file_name":"insert_handlers.py","file_ext":"py","file_size_in_byte":8577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"540162979","text":"# -*- coding: utf-8 -*-\n__author__ = \"Konstantin Klementiev\"\n__date__ = \"17 Nov 2018\"\n# !!! SEE CODERULES.TXT !!!\n\nimport numpy as np\nfrom silx.gui import qt\n\ncolorCycle1 = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',\n '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'] # mpl\ncolorCycle2 = ['#0000ff', '#00ee00', '#ff0000', '#00ffff', '#ff00ff',\n '#ffff00', '#aaaaaa', '#000000']\n\nCOLOR_POLICY_INDIVIDUAL, COLOR_POLICY_LOOP1, COLOR_POLICY_LOOP2,\\\n COLOR_POLICY_GRADIENT = range(4)\nCOLOR_POLICY_NAMES = 'individual', 'loop1', 'loop2', 'gradient'\n\nCOLOR_HDF5_HEAD = '#2299F0'\nCOLOR_FS_COLUMN_FILE = '#32AA12'\nCOLOR_LOAD_CAN = '#44C044'\nCOLOR_LOAD_CANNOT = '#C04444'\n\n\ndef makeGradientCollection(color1, color2, ncolor=8):\n c1 = np.array(qt.QColor(color1).getHsvF())\n c2 = np.array(qt.QColor(color2).getHsvF())\n c1[c1 < 0] = 0 # for gray, getHsvF returns hue=-1 that is not accepted by fromHsv # noqa\n c2[c2 < 0] = 0\n t = np.linspace(0, 1, ncolor)[:, np.newaxis]\n colors = c1*(1-t) + c2*t\n res = []\n for i in range(ncolor):\n res.append(qt.QColor.fromHsvF(*colors[i]))\n return res\n\n\ndef getColorName(color):\n return qt.QColor(color).name()\n","sub_path":"gui/gcommons.py","file_name":"gcommons.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"615589419","text":"# coding: utf-8\nimport logging\nimport re\nimport uuid\nfrom multiprocessing import Process, current_process, Manager, cpu_count\nfrom queue import Empty\n\nimport os\nimport boto3\nimport click\nimport xml.etree.ElementTree as ET\nimport json\n\nimport datacube\nfrom datacube.index.hl import Doc2Dataset\nfrom datacube.utils import changes\n\n#### THESE NEED TO BE ADAPTED ##################################################\n\n# Tuple of product band name, resolution and band names:\n# 1. name of the band, as defined in product description yaml\n# 2. resolution (as in /tiles/32/A/BC/2020/2/21/0/{resolution}/{band}.jp2)\n# 3. band (as in /tiles/32/A/BC/2020/2/21/0/{resolution}/{band}.jp2)\n\nbands_of_interest = [\n('B02_10m', 'R10m', 'B02'),\n('B03_10m', 'R10m', 'B03'),\n('B04_10m', 'R10m', 'B04'),\n('B08_10m', 'R10m', 'B08'),\n('B02_20m', 'R20m', 'B02'),\n('B03_20m', 'R20m', 'B03'),\n('B04_20m', 'R20m', 'B04'),\n('B05_20m', 'R20m', 'B05'),\n('B06_20m', 'R20m', 'B06'),\n('B07_20m', 'R20m', 'B07'),\n('B8A_20m', 'R20m', 'B8A'),\n('B11_20m', 'R20m', 'B11'),\n('B12_20m', 'R20m', 'B12'),\n('SCL_20m', 'R20m', 'SCL'),\n('B01_60m', 'R60m', 'B01'),\n('B02_60m', 'R60m', 'B02'),\n('B03_60m', 'R60m', 'B03'),\n('B04_60m', 'R60m', 'B04'),\n('B05_60m', 'R60m', 'B05'),\n('B06_60m', 'R60m', 'B06'),\n('B07_60m', 'R60m', 'B07'),\n('B8A_60m', 'R60m', 'B8A'),\n('B09_60m', 'R60m', 'B09'),\n('B11_60m', 'R60m', 'B11'),\n('B12_60m', 'R60m', 'B12'),\n\n]\n\n################################################################################\n\nIMAGE_FILE_ENDINGS = '.jp2'\nPRODUCT_META_FILE_NAME = 'metadata.xml'\nTILE_META_FILE_NAME = 'tileInfo.json'\nGUARDIAN = \"GUARDIAN_QUEUE_EMPTY\"\n\n################################################################################\n\ndef get_extent_coords(ext_pos_list_string):\n \"\"\"Rertrieve the coordinates of the tile's footprint\n \n :param ext_pos_list_string: Raw string from granule's XML element 'EXT_POS_LIST'\n :type ext_pos_list_string: str\n :return: Dictionary of boundary coordinates\n :rtype: dict[str:str]\n \"\"\"\n ext_pos_list_string = ext_pos_list_string.split(' ')\n return {\n 'ul': {'lat': ext_pos_list_string[0], 'lon': ext_pos_list_string[1]},\n 'ur': {'lat': ext_pos_list_string[2], 'lon': ext_pos_list_string[3]},\n 'lr': {'lat': ext_pos_list_string[4], 'lon': ext_pos_list_string[5]},\n 'll': {'lat': ext_pos_list_string[6], 'lon': ext_pos_list_string[7]},\n }\n\n\ndef generate_band_paths(bucket_name, tile_base_path, bands_of_interest, \n image_file_ending):\n \n band_dict = {}\n band_path = 's3://{bucket_name}/{tile_base_path}/{resolution}/{band}{image_file_ending}'\n\n for name, resolution, band in bands_of_interest:\n band_dict[name] = {\n 'layer': 1,\n 'path': band_path.format(bucket_name=bucket_name, band=band, \n tile_base_path=tile_base_path,\n resolution=resolution, \n image_file_ending=image_file_ending)\n }\n return band_dict\n\n\ndef get_s3_url(bucket_name, obj_key):\n return 's3://{bucket_name}/{obj_key}'.format(\n bucket_name=bucket_name, obj_key=obj_key)\n\n\ndef extract_product_meta(raw_product_meta_file, bucket_name, object_key):\n \"\"\"Extract product metadata\n \n :param raw_product_meta_file: File stream for product metadata file\n :type raw_product_meta_file: botocore.response.StreamingBody\n :param bucket_name: bucket name\n :type bucket_name: str\n :param object_key: S3 object key for product metadata file\n :type object_key: str\n :return: Dictionary with datacube releavnt product metadata\n :rtype: dict\n \"\"\"\n tree = ET.parse(raw_product_meta_file)\n root = tree.getroot()\n\n level = root.findall('.//Product_Info/PROCESSING_LEVEL')[0].text\n product_type = root.findall('.//Product_Info/PRODUCT_TYPE')[0].text\n creation_dt = root.findall('.//Product_Info/GENERATION_TIME')[0].text\n sensing_dt = root.findall('.//Product_Info/PRODUCT_START_TIME')[0].text\n satellite = root.findall('.//SPACECRAFT_NAME')[0].text\n instrument = 'MSI'\n coordinates = get_extent_coords(root.findall(\n './/Product_Footprint/Product_Footprint/Global_Footprint/EXT_POS_LIST'\n )[0].text)\n image_format = root.findall('.//Granule_List/')[0].attrib['imageFormat']\n\n dataset_doc_part = {\n 'id': str(uuid.uuid5(uuid.NAMESPACE_URL, \n get_s3_url(bucket_name, object_key))),\n 'processing_level': level,\n 'product_type': product_type,\n 'creation_dt': creation_dt,\n 'platform': {'code': satellite},\n 'instrument': {'name': instrument},\n 'extent': {\n 'from_dt': sensing_dt,\n 'to_dt': sensing_dt,\n 'center_dt': sensing_dt,\n 'coord': coordinates,\n },\n 'format': {'name': image_format},\n 'lineage': {'source_datasets': {}},\n }\n return dataset_doc_part\n\n\ndef extract_tile_meta(raw_tile_meta_file):\n \"\"\"Extract product definition path, CRS and geo reference points from \n given tile metadata file\n \n :param tile_meta_path: Path to tile metadata file\n :type tile_meta_path: str\n :return: Dictionary with CRS and dictionary of geo reference points.\n :rtype: dict['crs_epsg': str, 'geo_ref_points': dict[str:int]]\n \"\"\" \n tile_meta = json.loads(raw_tile_meta_file)\n\n product_path = tile_meta['productPath']\n\n crs_epsg = tile_meta['tileGeometry']['crs']['properties']['name'].split(':')[-1]\n crs_epsg = 'EPSG:' + crs_epsg\n\n ul = tile_meta['tileGeometry']['coordinates'][0][0]\n ur = tile_meta['tileGeometry']['coordinates'][0][1]\n lr = tile_meta['tileGeometry']['coordinates'][0][2]\n ll = tile_meta['tileGeometry']['coordinates'][0][3]\n\n geo_ref_points = {\n 'ul': {'x': ul[0], 'y': ul[1]},\n 'ur': {'x': ur[0], 'y': ur[1]},\n 'lr': {'x': lr[0], 'y': lr[1]},\n 'll': {'x': ll[0], 'y': ll[1]},\n }\n\n return({'product_path': product_path, 'crs_epsg': crs_epsg, \n 'geo_ref_points': geo_ref_points})\n\n\n\ndef archive_document(doc, uri, index, sources_policy):\n \"\"\"Archive dataset\n \n :param doc: Dict of parameters that reference the dataset\n :type doc: dict\n :param uri: URI to metadata file for the tile\n :type uri: str\n :param index: Datacube index\n :type index: datacube.index\n :param sources_policy: Source policy \n :type sources_policy: str\n \"\"\"\n def get_ids(dataset):\n ds = index.datasets.get(dataset.id, include_sources=True)\n for source in ds.sources.values():\n yield source.id\n yield dataset.id\n\n resolver = Doc2Dataset(index)\n dataset, err = resolver(doc, uri)\n index.datasets.archive(get_ids(dataset))\n logging.info(\"Archiving %s and all sources of %s\", dataset.id, dataset.id)\n\n\ndef add_dataset(doc, uri, index, sources_policy):\n \"\"\"Add dataset documentation to datacube\n \n :param doc: Dict of parameters to index\n :type doc: dict\n :param uri: URI to metadata file for the tile\n :type uri: str\n :param index: Datacube index\n :type index: datacube.index\n :param sources_policy: Source policy \n :type sources_policy: str\n :return: dataset or error\n :rtype: dataset or error\n \"\"\"\n \n logging.info(\"Adding %s to index\", uri)\n\n resolver = Doc2Dataset(index)\n dataset, err = resolver(doc, uri)\n\n if err is not None:\n logging.error(\"%s\", err)\n else:\n try:\n index.datasets.add(dataset, sources_policy=sources_policy)\n except changes.DocumentMismatchError as e:\n index.datasets.update(dataset, {tuple(): changes.allow_any})\n except Exception as e:\n err = e\n logging.error(\"Unhandled exception %s\", e)\n\n return dataset, err\n\n\n\ndef worker(config, bucket_name, prefix, func, sources_policy, queue, request_payer):\n dc = datacube.Datacube(config=config)\n index = dc.index\n s3 = boto3.resource(\"s3\")\n\n while True:\n try:\n key = queue.get(timeout=60)\n if key == GUARDIAN:\n break\n\n logging.info(\"Processing %s %s\", key, current_process())\n\n tile_base_path = '/'.join(key.split('/')[:-1]) \n\n tile_meta_obj = s3.Object(bucket_name, key)\\\n .get(ResponseCacheControl='no-cache', RequestPayer=request_payer)\n raw_tile_meta_file = tile_meta_obj['Body'].read()\n tile_meta = extract_tile_meta(raw_tile_meta_file)\n\n spatial_doc_part = {\n 'grid_spatial': {\n 'projection': {\n 'geo_ref_points': tile_meta['geo_ref_points'],\n 'spatial_reference': tile_meta['crs_epsg']\n }\n }\n }\n\n product_meta_path = tile_meta['product_path'] + '/' + PRODUCT_META_FILE_NAME\n product_meta_obj = s3.Object(bucket_name, product_meta_path)\\\n .get(ResponseCacheControl='no-cache', RequestPayer=request_payer)\n raw_product_meta_file = product_meta_obj['Body']\n\n product_doc_part = extract_product_meta(raw_product_meta_file, \n bucket_name, \n product_meta_path)\n \n bands_paths = generate_band_paths(bucket_name, tile_base_path, \n bands_of_interest, IMAGE_FILE_ENDINGS)\n\n image_doc_part = {'image': {'bands': bands_paths}}\n\n dataset_doc = {**product_doc_part, **spatial_doc_part, ** image_doc_part}\n\n uri = get_s3_url(bucket_name, key)\n func(dataset_doc, uri, index, sources_policy)\n queue.task_done()\n \n except Empty:\n break\n except EOFError:\n break\n\n\ndef iterate_datasets(bucket_name, config, prefix, func, \n sources_policy, request_payer):\n manager = Manager()\n queue = manager.Queue()\n\n s3 = boto3.resource('s3')\n bucket = s3.Bucket(bucket_name)\n logging.info(\"Starting indexing for: bucket: '%s', with key prefix: '%s'\", \n bucket_name, str(prefix))\n worker_count = cpu_count() # * 2\n\n processess = []\n for i in range(worker_count):\n proc = Process(target=worker, args=(config, bucket_name, prefix, \n func, sources_policy, queue,\n request_payer))\n processess.append(proc)\n proc.start()\n\n for obj in bucket.objects.filter(Prefix=str(prefix), \n RequestPayer=request_payer):\n if obj.key.endswith(TILE_META_FILE_NAME):\n queue.put(obj.key)\n\n for i in range(worker_count):\n queue.put(GUARDIAN)\n\n for proc in processess:\n proc.join()\n\n\n@click.command(help=\"Enter Bucket name. Optional to enter configuration file to\\\n access a different ODC database.\")\n@click.argument('bucket_name')\n@click.option('--config', '-c', help=\" Pass the configuration file to access the database\",\n type=click.Path(exists=True))\n@click.option('--prefix', '-p', help=\"Pass the prefix of the object to the bucket\")\n@click.option('--archive', is_flag=True,\n help=\"If true, datasets found in the specified bucket and\\\n prefix will be archived\")\n@click.option('--sources_policy', default=\"verify\", help=\"verify, ensure, skip\")\n@click.option('--requester_pays', is_flag=True,\n help=\"Needs to be passed when indexing requester-pays S3 buckets\\\n (e.g. arn:aws:s3:::sentinel-s2-l2a)\")\ndef main(bucket_name, config, prefix, archive, sources_policy, requester_pays):\n logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO)\n action = archive_document if archive else add_dataset\n request_payer = 'requester' if requester_pays else 'owner'\n iterate_datasets(bucket_name, config, prefix, action, sources_policy, request_payer)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"scripts/index_s2_l2a_from_opendata_s3_bucket.py","file_name":"index_s2_l2a_from_opendata_s3_bucket.py","file_ext":"py","file_size_in_byte":12185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"214622454","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom ast import literal_eval\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n\n\ndef visualization_list_data(data, columns, replace_value = [], max_feature = 20, extracte_data = 'name'):\n print(f'Visualization of the value of feature {columns}')\n data = dealing_null_value(data, columns, replace_value)\n gerner_count = Counter([j.get(extracte_data) for i in data[columns] for j in i])\n if len(gerner_count) > 20:\n print(f'total availabe different values of {columns} are {len(gerner_count)}. We will print top 20 values')\n gerner_count = gerner_count.most_common(max_feature)\n gerner_count = dict(gerner_count)\n sns.set(rc={'figure.figsize':(15,9)})\n sns.barplot(list(gerner_count.values()), list(gerner_count.keys()))\n plt.xlabel(f'count of {columns}')\n plt.ylabel(f'{columns}')\n plt.show()\n \ndef visualization_value_count(data, columns, replace_value = [], figure_size=None):\n print(f\"per movie number of {columns} value\")\n data =dealing_null_value(data, columns, replace_value)\n temp = data[columns].apply(lambda x: len(x) if isinstance(x,list) else 0).value_counts().reset_index()\n if figure_size == None:\n sns.set(rc={'figure.figsize':(11,8)})\n else:\n sns.set(rc={'figure.figsize':figure_size})\n sns.barplot(x='index',y=columns,data=temp)\n plt.xlabel(f'Number of {columns}')\n plt.ylabel('count of the movie')\n plt.show()\n \ndef dealing_null_value(data, columns, replace_value = []):\n data[columns] = data[columns].fillna(0)\n try:\n data[columns] = [literal_eval(i) if i != 0 else replace_value for i in data[columns]]\n except:\n return data\n return data","sub_path":"notebook/utility/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"475320994","text":"'''\nThis modules provide a thread dedicated to handling all i/o manipulation.\n\nWe consider this thread as a in-memory storage and use single thread\non i/o to keep away from using *lock* and race condiction.\n'''\nimport logging\n\nfrom functools import wraps\nfrom hashlib import sha256\nfrom six import StringIO\nfrom threading import Thread\n\nimport zmq\n\n__all__ = ('Link',)\nlog = logging.getLogger('iottalk.csm.storage')\n\n\nclass _IOThread(Thread):\n daemon = True\n\n def run(self):\n while True:\n try:\n self.dispatch()\n except Exception as err:\n log.exception('Unhandled exception in io thread: %r', err)\n self.dispatch_cleanup()\n\n def dispatch(self):\n '''\n Consuming the request from queue and\n\n A subclass should override this method.\n '''\n raise NotImplementedError()\n\n def dispatch_cleanup(self):\n '''\n Cleanup handler for ``dispatch`` got exception.\n\n A subclass should override this method\n '''\n pass\n\n\nclass _ReplyMixin(object):\n '''\n Reply Mixin\n\n create a ``self.rep`` zmq socket for request-reply model\n '''\n\n def __init__(self, *args, **kwargs):\n super(_ReplyMixin, self).__init__(*args, **kwargs)\n self.rep = zmq.Context.instance().socket(zmq.REP)\n\n def __del__(self):\n self.rep.close()\n\n def dispatch_cleanup(self):\n self.rep.send_pyobj(False)\n\n\nclass _LinkThread(_ReplyMixin, _IOThread):\n\n def __init__(self):\n super(type(self), self).__init__()\n\n self.links = {}\n self.rep.bind('inproc://link')\n\n def dispatch(self):\n cmd, args = self.rep.recv_pyobj()\n\n if cmd == 'add':\n self.add(args)\n elif cmd == 'rm':\n self.rm(args)\n elif cmd == 'clear':\n self.clear()\n elif cmd == 'select':\n self.select(args)\n elif cmd == 'pop':\n self.pop(args)\n else:\n raise NotImplementedError()\n\n def add(self, link):\n '''\n :param link: a ``tuple`` of (da_id, feature_name, feature_mode, topic).\n\n :return: True if success. False if conflict.\n '''\n key, topic = link[:-1], link[-1]\n\n if key in self.links:\n self.rep.send_pyobj(False)\n return\n\n self.links[key] = topic\n self.rep.send_pyobj(True)\n\n log.debug('Links: %r', self.links)\n return\n\n def rm(self, key):\n '''\n :param key: ``(da_id, feature_name, feature_mode)``\n\n :return: True if success. False if conflict.\n '''\n if key not in self.links:\n self.rep.send_pyobj(False)\n return\n\n del self.links[key]\n self.rep.send_pyobj(True)\n return\n\n def clear(self):\n '''\n :return: True.\n '''\n self.links.clear()\n self.rep.send_pyobj(True)\n\n def select(self, key=None):\n if not key:\n self.rep.send_pyobj(self.links.copy())\n return\n\n if key not in self.links:\n self.rep.send_pyobj(None)\n else:\n self.rep.send_pyobj(self.links[key])\n\n def pop(self, key):\n '''\n :param key: ``(da_id, feature_name, feature_mode)``\n\n :return: False if failed. ``topic`` if success.\n '''\n if key not in self.links:\n self.rep.send_pyobj(False)\n return\n\n val = self.links.pop(key)\n self.rep.send_pyobj(val)\n return\n\n\nclass _FunctionThread(_ReplyMixin, _IOThread):\n '''\n The table of user defined functions\n\n :key: the sha256 hash of the function string\n :val: (function source, callable object) pair\n '''\n\n def __init__(self):\n super(type(self), self).__init__()\n\n self.funcs = {}\n self.rep.bind('inproc://function')\n\n def __del__(self):\n self.rep.close()\n\n def dispatch(self):\n cmd, args = self.rep.recv_pyobj()\n\n if cmd == 'add':\n self.add(*args)\n elif cmd == 'rm':\n self.rm(args)\n elif cmd == 'clear':\n self.clear()\n elif cmd == 'select':\n self.select(args)\n else:\n raise NotImplementedError()\n\n def add(self, key, src):\n '''\n :param key: the sha256 of function source.\n :param src: function source\n\n :return: False if the key exists.\n True if adding successfully.\n '''\n if key in self.funcs:\n self.rep.send_pyobj(False)\n return\n\n self.funcs[key] = src\n self.rep.send_pyobj(True)\n\n def rm(self, key):\n if key not in self.funcs:\n self.rep.send_pyobj(False)\n return\n\n del self.funcs[key]\n self.rep.send_pyobj(True)\n\n def clear(self):\n self.funcs.clear()\n self.rep.send_pyobj(True)\n\n def select(self, key=None):\n '''\n :return: ``(source, callable object)``\n '''\n if key is None:\n self.rep.send_pyobj(self.funcs.copy())\n else:\n self.rep.send_pyobj(self.funcs.get(key, False))\n\n\ndef _init_threads():\n link_thread = _LinkThread()\n link_thread.start()\n\n func_thread = _FunctionThread()\n func_thread.start()\n\n\ndef _req(url):\n '''\n Decorator factory for connect REQ zmq socket to ``url``\n '''\n def decorator(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n with zmq.Context.instance().socket(zmq.REQ) as req:\n req.connect(url)\n return func(*args, req=req, **kwargs)\n\n return wrapper\n\n return decorator\n\n\nclass Link(object):\n '''\n A link denote a connection from device feature to a MQTT topic.\n\n :key: (da_id, feature_name, feature_mode)\n :value: topic\n '''\n\n @staticmethod\n @_req('inproc://link')\n def add(da_id, feature_name, feature_mode, topic, req):\n '''\n :raise ValueError: if the link conflicts\n '''\n args = (da_id, feature_name, feature_mode, topic)\n req.send_pyobj(('add', args))\n res = req.recv_pyobj()\n\n if not res:\n raise ValueError('link already exists')\n return res\n\n @staticmethod\n @_req('inproc://link')\n def rm(da_id, feature_name, feature_mode, req=None):\n '''\n :raise ValueError: if the link is unknown\n '''\n args = (da_id, feature_name, feature_mode)\n req.send_pyobj(('rm', args))\n res = req.recv_pyobj()\n\n if not res:\n raise ValueError('link unknown')\n return res\n\n @staticmethod\n @_req('inproc://link')\n def clear(req):\n req.send_pyobj(('clear', None))\n return req.recv_pyobj()\n\n @staticmethod\n @_req('inproc://link')\n def select(da_id=None, feature_name=None, feature_mode=None, req=None):\n '''\n Get a snapshot of ``self.links`` or query a specific key\n\n args: ``(da_id, feature_name, feature_mode)``\n '''\n if da_id and feature_name and feature_mode:\n args = (da_id, feature_name, feature_mode)\n else:\n args = None\n req.send_pyobj(('select', args))\n return req.recv_pyobj()\n\n @staticmethod\n @_req('inproc://link')\n def pop(da_id, feature_name, feature_mode, req=None):\n args = (da_id, feature_name, feature_mode)\n req.send_pyobj(('pop', args))\n res = req.recv_pyobj()\n\n if not res:\n raise ValueError('link {!r} unknown'.format(args))\n return res\n\n\nclass UserFunction(object):\n '''\n The user defined functions.\n\n :key: the sha256 hash of the function string\n :val: (function source, callable object) pair\n '''\n\n @classmethod\n @_req('inproc://function')\n def add(cls, key, src, req):\n '''\n :return: False if function already exists. True if successful.\n :raise ValueError: if function hash mismatched or key duplicated.\n '''\n if key != cls._func_key(src):\n raise ValueError('function hash mismatched')\n\n req.send_pyobj(('add', (key, src)))\n res = req.recv_pyobj()\n return res\n\n @staticmethod\n @_req('inproc://function')\n def rm(key, req):\n '''\n :return: False if ``key`` is unknown.\n '''\n req.send_pyobj(('rm', key))\n res = req.recv_pyobj()\n\n return res\n\n @staticmethod\n @_req('inproc://function')\n def clear(req):\n req.send_pyobj(('clear', None))\n return req.recv_pyobj()\n\n @staticmethod\n @_req('inproc://function')\n def select(key=None, req=None):\n req.send_pyobj(('select', key))\n return req.recv_pyobj()\n\n @staticmethod\n def _func_key(src):\n '''\n The the sha256 hash value from a function string\n '''\n return sha256(src.encode('utf-8')).hexdigest()\n\n\n_init_threads()\n","sub_path":"iot/csm/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":8912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"544791485","text":"\"\"\"\nThis script is used to view all the trajectories, including augmented and abnormal ones.\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom scipy import ndimage\nfrom PIL import Image\nimport os.path\n\nnumber_of_images = 400\n\nbackground_image_path = 'background_image.png'\n\noverwrite_background_image = False\n\n# Ref.: https://stackoverflow.com/questions/24731035/python-pil-0-5-opacity-transparency-alpha\nopacity_level = 230 # Opaque is 255, input between 0-255\n\ndef mouse_move(self,event):\n if event.inaxes and event.inaxes.get_navigate():\n s = event.inaxes.format_coord(event.xdata, event.ydata)\n self.set_message(s)\n\ndef make_image_transparent(image):\n \"\"\"\n Makes the image transparent.\n Re.: https://stackoverflow.com/questions/24731035/python-pil-0-5-opacity-transparency-alpha\n :param image: opened image\n :return: transformed image\n \"\"\"\n image2 = image.convert('RGBA')\n data_array = image2.getdata()\n\n newData = []\n for item in data_array:\n if item[0] == 0 and item[1] == 0 and item[2] == 0:\n newData.append((0, 0, 0, opacity_level))\n else:\n newData.append(item)\n\n image2.putdata(newData)\n return image2\n\ndef generate_background_image(input_raw_image_frame_path):\n image_name_1 = input_raw_image_frame_path + str(1).zfill(8) + '.jpg'\n im1 = Image.open(image_name_1)\n im1 = make_image_transparent(im1)\n\n alpha_value = 1.0 / number_of_images\n\n for i in range(number_of_images):\n image_name_2 = input_raw_image_frame_path + str(i+1).zfill(8) + '.jpg'\n im2 = Image.open(image_name_2)\n im2 = make_image_transparent(im2)\n im1 = Image.blend(im1,im2,alpha_value)\n im1 = make_image_transparent(im1)\n\n im1.save(background_image_path)\n\nclass ImageViewer():\n def __init__(self, input_raw_image_frame_path):\n self.fig = plt.figure()\n self.ax = plt.axes()\n\n if overwrite_background_image or not os.path.isfile(background_image_path):\n generate_background_image(input_raw_image_frame_path)\n\n img_test = plt.imread(background_image_path, format='png')\n self.ax.imshow(ndimage.rotate(img_test, 0))\n\n def format_coord(x,y):\n return \"(x={:.2f}, y={:.2f})\".format(x,y)\n self.ax.format_coord=format_coord\n\n mouse_move_patch = lambda arg: mouse_move(self.fig.canvas.toolbar, arg)\n self.fig.canvas.toolbar._idDrag = self.fig.canvas.mpl_connect('motion_notify_event', mouse_move_patch)\n\n def add_trajectory(self, x_positions, y_positions, line_width=1, line_color='firebrick'):\n self.ax.plot(x_positions, y_positions, '-', linewidth=line_width, color=line_color)\n self.ax.arrow(x_positions[-2], y_positions[-2],\n x_positions[-1] - x_positions[-2], y_positions[-1] - y_positions[-2],\n head_width=5*line_width, head_length=2.5*line_width, fc=line_color, ec=line_color)\n\n def show_image(self):\n plt.show()\n\n def save_image(self, image_path_name):\n plt.xlabel('x')\n plt.ylabel('y')\n plt.savefig(image_path_name)\n\n# Test\n#x = range(100,300)\n#trajectory_image.add_trajectory(x,x)\n#x = range(300,400)\n#trajectory_image.add_trajectory(x,x)\n#x = range(50,100)\n#trajectory_image.add_trajectory(x,x)\n#x = range(20,40)\n#trajectory_image.add_trajectory(x,x)\n\n#plt.show()\n","sub_path":"DAE_Method/trajectory_viewer.py","file_name":"trajectory_viewer.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"242307622","text":"# Definition for a binary tree node.\nfrom collections import deque\n\n\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Codec:\n\n def serialize(self, root):\n \"\"\"Encodes a tree to a single string.\n\n :type root: TreeNode\n :rtype: str\n \"\"\"\n if not root:\n return ''\n Q = deque([root])\n res = []\n while Q:\n tempQ = deque()\n while Q:\n x = Q.popleft()\n if not x:\n res.append(\"null\")\n continue\n res.append(str(x.val))\n tempQ.extend([x.left, x.right])\n Q = tempQ\n return ','.join(res)\n\n def deserialize(self, data):\n \"\"\"Decodes your encoded data to tree.\n\n :type data: str\n :rtype: TreeNode\n \"\"\"\n if data == '':\n return\n res = deque(data.split(','))\n if not res[0]:\n return\n root = TreeNode(int(res.popleft()))\n Q = deque([root])\n while res and Q:\n x = res.popleft()\n node = Q.popleft()\n if x != \"null\":\n node.left = TreeNode(int(x))\n Q.append(node.left)\n if res:\n x = res.popleft()\n if x!='null':\n node.right = TreeNode(int(x))\n Q.append(node.right)\n return root\n\n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.deserialize(codec.serialize(root))\n","sub_path":"Tree/serilize_deserialize_binary_tree_LC297.py","file_name":"serilize_deserialize_binary_tree_LC297.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"47771395","text":"\nimport numpy as np\nimport struct\nimport json\nimport csv\nimport pickle\nimport mayavi.mlab as mlab\n\n\ndef draw_lidar_simple(pc,location, color=None):\n ''' Draw lidar points. simplest set up. '''\n ##############################################33\n\n\n # mlab.points3d(xmid, ymid, zmid, scale_factor=1.0)\n ################################################\n\n fig = mlab.figure(figure=None, bgcolor=(0,0,0), fgcolor=None, engine=None, size=(1600, 1000))\n # fig=draw_gt_boxes3d(1,fig)\n if color is None: color = pc[:,2]\n #draw points\n mlab.points3d(pc[:,0], pc[:,1], pc[:,2], color, color=None, mode='point', colormap = 'gnuplot', scale_factor=1, figure=fig)\n #draw origin\n mlab.points3d(0, 0, 0, color=(1,1,1), mode='sphere', scale_factor=0.2)\n #draw axis\n axes=np.array([\n [2.,0.,0.,0.],\n [0.,2.,0.,0.],\n [0.,0.,2.,0.],\n ],dtype=np.float64)\n mlab.plot3d([0, axes[0,0]], [0, axes[0,1]], [0, axes[0,2]], color=(1,0,0), tube_radius=None, figure=fig)\n mlab.plot3d([0, axes[1,0]], [0, axes[1,1]], [0, axes[1,2]], color=(0,1,0), tube_radius=None, figure=fig)\n mlab.plot3d([0, axes[2,0]], [0, axes[2,1]], [0, axes[2,2]], color=(0,0,1), tube_radius=None, figure=fig)\n mlab.view(azimuth=180, elevation=70, focalpoint=[ 12.0909996 , -1.04700089, -2.03249991], distance=62.0, figure=fig)\n ###################################################3\n location=[13.82,1.65,0.93]\n location=[13,0,0]\n # format is[]\n # location=[0.93,1.65,13.82]\n x_loc = location[0]\n y_loc = location[1]\n z_loc = location[2]\n mlab.points3d(x_loc, y_loc, z_loc, scale_factor=1.0)\n ################################################\n ####################################################3\n mlab.show()\n\n return fig\n\n\ndef draw_gt_boxes3d(gt_boxes3d, fig, color=(1, 1, 1), line_width=1, draw_text=True, text_scale=(1, 1, 1),\n color_list=None):\n gt_boxes3d=np.array([[4.8119, -1.9323, 39.7667],\n [3.0897, -1.9323, 39.6927],\n [3.0897, -0.1503, 39.6927],\n [4.8119, -0.1503, 39.7667],\n [4.6423, -1.9323, 43.7183],\n [2.9200, -1.9323, 43.6443],\n [2.9200, -0.1503, 43.6443],\n [4.6423, -0.1503, 43.7183]])\n ''' Draw 3D bounding boxes\n Args:\n gt_boxes3d: numpy array (n,8,3) for XYZs of the box corners\n fig: mayavi figure handler\n color: RGB value tuple in range (0,1), box line color\n line_width: box line width\n draw_text: boolean, if true, write box indices beside boxes\n text_scale: three number tuple\n color_list: a list of RGB tuple, if not None, overwrite color.\n Returns:\n fig: updated fig\n '''\n gt_boxes3d=np.expand_dims(gt_boxes3d, 0)\n num = len(gt_boxes3d)\n for n in range(num):\n b = gt_boxes3d[n]\n if color_list is not None:\n color = color_list[n]\n if draw_text: mlab.text3d(b[4, 0], b[4, 1], b[4, 2], '%d' % n, scale=text_scale, color=color, figure=fig)\n for k in range(0, 4):\n # http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html\n i, j = k, (k + 1) % 4\n mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=None,\n line_width=line_width, figure=fig)\n\n i, j = k + 4, (k + 1) % 4 + 4\n mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=None,\n line_width=line_width, figure=fig)\n\n i, j = k, k + 4\n mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=None,\n line_width=line_width, figure=fig)\n # mlab.show()\n # mlab.view(azimuth=180, elevation=70, focalpoint=[ 12.0909996 , -1.04700089, -2.03249991], distance=62.0, figure=fig)\n return fig\n#\n# scan = np.fromfile('n008-2018-05-21-11-06-59-0400__LIDAR_TOP__1526915243047392.pcd.bin', dtype=np.float32)\n# scan = np.fromfile('./point_clouds/n008-2018-05-21-11-06-59-0400__LIDAR_TOP__1526915243047392.pcd.bin', dtype=np.float32)\n# scan = np.fromfile('/home/mayanksati/Documents/point_clouds/KITTI_DATASET_ROOT/testing/velodyne/000007.bin', dtype=np.float32)\nscan = np.fromfile('/home/mayanksati/Documents/point_clouds/KITTI_DATASET_ROOT/testing/velodyne_reduced/000003.bin', dtype=np.float32)\n# scan = np.fromfile('/home/mayanksati/Documents/point_clouds/KITTI_DATASET_ROOT/pycharm_work/point_cloud/000001.bin', dtype=np.float32)\n\n\n# points = scan.reshape((-1, 5))[:, :4]\npoints = scan.reshape((-1, 4))\npcd_data = points\nfig = draw_lidar_simple(pcd_data,location=[0,0,13])\n","sub_path":"second/pytorch/mayank_play/lidar_bbox_on_nuscne_Data/draw_x_y_z_on_point_cloud.py","file_name":"draw_x_y_z_on_point_cloud.py","file_ext":"py","file_size_in_byte":4656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134422634","text":"# import the necessary packages\r\nfrom imutils.perspective import four_point_transform\r\nfrom skimage.segmentation import clear_border\r\nimport numpy as np\r\nimport imutils\r\nimport argparse\r\nimport cv2\r\ndef find_map(image, debug=False):\r\n\t# convert the image to grayscale and blur it slightly\r\n\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n\tblurred = cv2.GaussianBlur(gray, (7, 7), 3)\r\n # apply adaptive thresholding and then invert the threshold map\r\n\tthresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)\r\n\tthresh = cv2.bitwise_not(thresh)\r\n\t# check to see if we are visualizing each step of the image\r\n\t# processing pipeline (in this case, thresholding)\r\n\tif debug:\r\n\t\tcv2.imshow(\"Map Thresh\", thresh)\r\n\t\tcv2.waitKey(0)\r\n# find contours in the thresholded image and sort them by size in\r\n\t# descending order\r\n\tcnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,\r\n\t\tcv2.CHAIN_APPROX_SIMPLE)\r\n\tcnts = imutils.grab_contours(cnts)\r\n\tcnts = sorted(cnts, key=cv2.contourArea, reverse=True)\r\n\t# initialize a contour that corresponds to the map outline\r\n\tmapCnt = None\r\n\t# loop over the contours\r\n\tfor c in cnts:\r\n\t\t# approximate the contour\r\n\t\tperi = cv2.arcLength(c, True)\r\n\t\tapprox = cv2.approxPolyDP(c, 0.02 * peri, True)\r\n\t\t# if our approximated contour has four points, then we can\r\n\t\t# assume we have found the outline of the map\r\n\t\tif len(approx) == 4:\r\n\t\t\tmapCnt = approx\r\n\t\t\tbreak\r\n\t# if the map contour is empty then our script could not find\r\n\t# the outline of the map so raise an error\r\n\tif mapCnt is None:\r\n\t\traise Exception((\"Could not find map outline. \"\r\n\t\t\t\"Try debugging your thresholding and contour steps.\"))\r\n\t# check to see if we are visualizing the outline of the detected\r\n\t# map\r\n\tif debug:\r\n\t\t# draw the contour of the map on the image and then display\r\n\t\t# it to our screen for visualization/debugging purposes\r\n\t\toutput = image.copy()\r\n\t\tcv2.drawContours(output, [mapCnt], -1, (0, 255, 0), 2)\r\n\t\tcv2.imshow(\"map Outline\", output)\r\n\t\tcv2.waitKey(0)\r\n \t# apply a four point perspective transform to both the original\r\n\t# image and grayscale image to obtain a top-down bird's eye view\r\n\t# of the map\r\n\tmap = four_point_transform(image, mapCnt.reshape(4, 2))\r\n\twarped = four_point_transform(gray, mapCnt.reshape(4, 2))\r\n\t# check to see if we are visualizing the perspective transform\r\n\tif debug:\r\n\t\t# show the output warped image (again, for debugging purposes)\r\n\t\tcv2.imshow(\"map Transform\", map)\r\n\t\tcv2.waitKey(0)\r\n\t# return a 2-tuple of map in both RGB and grayscale\r\n\treturn (map, warped)\r\n\r\n\r\ndef is_empty(cell, debug=True):\r\n\t# apply automatic thresholding to the cell and then clear any\r\n\t# connected borders that touch the border of the cell\r\n\tthresh = cv2.threshold(cell, 0, 255,\r\n\t\tcv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]\r\n\tthresh = clear_border(thresh)\r\n\r\n\t# check to see if we are visualizing the cell thresholding step\r\n\tif debug:\r\n\t\tcv2.imshow(\"Cell Thresh\", thresh)\r\n\t\tcv2.waitKey(0)\r\n\r\n\t# find contours in the thresholded cell\r\n\t#--NEEDS FIXING, NO NEED FOR LOOKING FOR COUNTROURS JUST LOOK FOR BLACK SQUARES\r\n\tcnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,\r\n\t\tcv2.CHAIN_APPROX_SIMPLE)\r\n\tcnts = imutils.grab_contours(cnts)\r\n\r\n\t# if no contours were found than this is an empty cell\r\n\tif len(cnts) == 0:\r\n\t\treturn True\r\n\telse:\r\n\t\treturn False\r\n\r\n\r\n\r\nimage = 'sudoku_map.jpg'\r\nimage = cv2.imread(image)\r\nimage = imutils.resize(image, width=600)\r\n\r\n(mapImage, warped) = find_map(image, 1)\r\n\r\n\r\n# initialize our 9x9 map board\r\nboard = np.zeros((9, 9), dtype=\"int\")\r\n\r\n# a map is a 9x9 grid (81 individual cells), so we can\r\n# infer the location of each cell by dividing the warped image\r\n# into a 9x9 grid\r\nstepX = warped.shape[1] // 9\r\nstepY = warped.shape[0] // 9\r\n\r\n# initialize a list to store the (x, y)-coordinates of each cell\r\n# location\r\ncellLocs = []\r\n\r\n# loop over the grid locations\r\nfor y in range(0, 9):\r\n\t# initialize the current list of cell locations\r\n\trow = []\r\n\r\n\tfor x in range(0, 9):\r\n\t\t# compute the starting and ending (x, y)-coordinates of the\r\n\t\t# current cell\r\n\t\tstartX = x * stepX\r\n\t\tstartY = y * stepY\r\n\t\tendX = (x + 1) * stepX\r\n\t\tendY = (y + 1) * stepY\r\n\r\n\t\t# add the (x, y)-coordinates to our cell locations list\r\n\t\trow.append((startX, startY, endX, endY))\r\n\r\n\t\t# crop the cell from the warped transform image and then\r\n\t\t# extract the digit from the cell\r\n\t\tcell = warped[startY:endY, startX:endX]\r\n\t\tdigit = is_empty(cell, 0)\r\n\r\n\t\t# verify that the digit is not empty\r\n\t\tif digit == False:\r\n\t\t\tboard[y, x] = 1\r\n\t\telse:\r\n\t\t\tboard[y, x] = 0\r\n\t# add the row to our cell locations\r\n\tcellLocs.append(row)\r\nprint(board)","sub_path":"digitizer.py","file_name":"digitizer.py","file_ext":"py","file_size_in_byte":4652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"127305140","text":"# 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 re\n\nfrom oslo_concurrency import processutils\nfrom oslo_utils import excutils\n\nfrom os_vif.internal.command.ip import api\n\n\ndef _execute_command(*args):\n return processutils.execute(*args)\n\n\nclass ShellIpCommands(object):\n\n def __init__(self, cmd=_execute_command):\n self._execute_command = cmd\n\n def add_device(self, device, dev_type, peer=None, link=None,\n vlan_id=None):\n ret = None\n if 'vlan' == dev_type:\n ret = self._execute_command('ip', 'link', 'add', 'link', link,\n 'name', device, 'type', dev_type,\n 'id', vlan_id)\n elif 'veth' == dev_type:\n ret = self._execute_command('ip', 'link', 'add', device, 'type',\n dev_type, 'peer', 'name', peer)\n elif 'dummy' == dev_type:\n ret = self._execute_command('ip', 'link', 'add', device,\n 'type', dev_type)\n return ret\n\n def del_device(self, device):\n ret = None\n if self.exist_device(device):\n ret = self._execute_command('ip', 'link', 'del', device)\n return ret\n\n def set(self, device, status=None, **kwargs):\n args = ['ip', 'link', 'set', device]\n if status is not None:\n args.append(status)\n temp = [x for x in kwargs.items()]\n for x in temp:\n args += x\n self._execute_command(*args)\n\n def set_status_up(self, device):\n self.set(device, status='up')\n\n def set_status_down(self, device):\n self.set(device, status='down')\n\n def set_device_mtu(self, device, mtu):\n args = {'mtu': mtu}\n self.set(device, args)\n\n def show_device(self, device):\n val, err = _execute_command('ip', 'link', 'show', device)\n return val.splitlines()\n\n def exist_device(self, device):\n try:\n self._execute_command('ip', 'link', 'show', device)\n return True\n except processutils.ProcessExecutionError as e:\n with excutils.save_and_reraise_exception() as saved_exception:\n if e.exit_code == 1:\n saved_exception.reraise = False\n return False\n\n def show_state(self, device):\n regex = re.compile(r\".*state (?P\\w+)\")\n match = regex.match(self.show_device(device)[0])\n if match is None:\n return\n return match.group('state')\n\n def show_promisc(self, device):\n regex = re.compile(r\".*(PROMISC)\")\n match = regex.match(self.show_device(device)[0])\n return True if match else False\n\n def show_mac(self, device):\n exp = r\".*link/ether (?P([0-9A-Fa-f]{2}[:]){5}[0-9A-Fa-f]{2})\"\n regex = re.compile(exp)\n match = regex.match(self.show_device(device)[1])\n if match is None:\n return\n return match.group('mac')\n\n def show_mtu(self, device):\n regex = re.compile(r\".*mtu (?P\\d+)\")\n match = regex.match(self.show_device(device)[0])\n if match is None:\n return\n return int(match.group('mtu'))\n\n\nclass IPTools(api.IpCommand):\n\n def __init__(self, cmd=_execute_command):\n self.ip = ShellIpCommands(cmd=cmd)\n\n def set(self, device, check_exit_code=None, state=None, mtu=None,\n address=None, promisc=None):\n args = {}\n if mtu is not None:\n args['mtu'] = mtu\n if address is not None:\n args['address'] = address\n if promisc is not None:\n args['promisc'] = 'on' if promisc else 'off'\n\n if isinstance(check_exit_code, int):\n check_exit_code = [check_exit_code]\n return self.ip.set(device, status=state, **args)\n\n def add(self, device, dev_type, check_exit_code=None, peer=None, link=None,\n vlan_id=None):\n\n return self.ip.add_device(device, dev_type, peer=peer,\n link=link, vlan_id=vlan_id)\n\n def delete(self, device, check_exit_code=None):\n return self.ip.del_device(device)\n","sub_path":"os_vif/internal/command/ip/impl_shell.py","file_name":"impl_shell.py","file_ext":"py","file_size_in_byte":4706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"455511496","text":"import re\nimport numpy as np\n\nfrom . import export\nfrom .errors import Error, DataNotAvailable\n\ntry:\n import libmsym as msym\nexcept ImportError:\n msym = None\n\n\ntypename = {\n 'f': 'fro',\n 'i': 'ina',\n '1': 'RAS1',\n '2': 'RAS2',\n '3': 'RAS3',\n 's': 'sec',\n 'd': 'del',\n '-': 'NA',\n }\n\n\n@export\nclass OrbitalSet():\n \"\"\"\n Represents a set of orbitals with a common basis set, and keeps track of\n their properties (energy, occupation, type, irrep).\n \"\"\"\n def __init__(self, coefficients, ids=None, types=None,\n irreps=None, energies=None, occupations=None,\n basis_ids=None, basis_set=None):\n\n self.coefficients = np.asarray(coefficients)\n self.n_bas = coefficients.shape[0]\n self.n_orb = coefficients.shape[1]\n\n if irreps is None:\n self.irreps = np.zeros(self.n_bas)\n self.n_irreps = 1\n else:\n self.irreps = irreps\n self.n_irreps = len(np.unique(irreps))\n\n self.n_irreps = len(np.unique(irreps))\n\n if ids is None:\n self.ids = 1 + np.arange(self.n_orb)\n else:\n self.ids = ids\n\n if types is None:\n self.types = np.array(['-'] * self.n_bas)\n else:\n self.types = types\n\n if energies is None:\n self.energies = np.array([np.nan] * self.n_bas)\n else:\n self.energies = energies\n\n if occupations is None:\n self.occupations = np.array([np.nan] * self.n_bas)\n else:\n self.occupations = occupations\n\n if basis_ids is None:\n self.basis_ids = np.arange(self.n_bas)\n else:\n self.basis_ids = basis_ids\n\n self.basis_set = basis_set\n\n def copy(self):\n return self.__class__(\n self.coefficients.copy(),\n ids=self.ids.copy(),\n types=self.types.copy(),\n irreps=self.irreps.copy(),\n energies=self.energies.copy(),\n occupations=self.occupations.copy(),\n basis_ids=self.basis_ids.copy(),\n basis_set=self.basis_set,\n )\n\n def __getitem__(self, index):\n return self.__class__(\n self.coefficients[:,index],\n ids=self.ids[index],\n types=self.types[index],\n irreps=self.irreps[index],\n energies=self.energies[index],\n occupations=self.occupations[index],\n basis_ids=self.basis_ids.copy(),\n basis_set=self.basis_set,\n )\n\n def filter_basis(self, index):\n return self.__class__(\n self.coefficients[index,:],\n ids=self.ids.copy(),\n types=self.types.copy(),\n irreps=self.irreps.copy(),\n energies=self.energies.copy(),\n occupations=self.occupations.copy(),\n basis_ids=self.basis_ids[index],\n basis_set=self.basis_set,\n )\n\n def sort_basis(self, order='molcas'):\n\n try:\n ids = self.basis_set.argsort_ids(self.basis_ids, order=order)\n return self.filter_basis(ids)\n except AttributeError:\n raise DataNotAvailable('A basis set is required to order basis functions')\n\n def limit_basis(self, limit=3):\n\n try:\n ids = self.basis_set.angmom_ids(self.basis_ids, limit=limit)\n return self.filter_basis(ids)\n except AttributeError:\n raise DataNotAvailable('A basis set is required to limit basis functions')\n\n def __str__(self):\n \"\"\"\n returns the Orbital coefficients formatted as columns\n \"\"\"\n\n prefix = '{:16s}'\n int_template = prefix + self.n_orb * '{:10d}'\n float_template = prefix + self.n_orb * '{:10.4f}'\n str_template = prefix + self.n_orb * '{:>10s}'\n\n lines = []\n\n line = int_template.format(\"ID\", *self.ids)\n lines.append(line)\n\n line = str_template.format('', *(['------'] * self.n_orb))\n lines.append(line)\n\n line = int_template.format(\"irrep\", *self.irreps)\n lines.append(line)\n\n line = float_template.format('Occupation', *self.occupations)\n lines.append(line)\n\n line = float_template.format('Energy', *self.energies)\n lines.append(line)\n\n line = str_template.format('Type Index', *[typename[idx] for idx in self.types])\n lines.append(line)\n\n try:\n labels = self.basis_set.labels[self.basis_ids]\n except AttributeError:\n labels = self.basis_ids.astype('U')\n\n lines.append('')\n\n for ibas in range(self.n_bas):\n line = float_template.format(labels[ibas], *np.ravel(self.coefficients[ibas,:]))\n lines.append(line)\n\n lines.append('')\n\n return '\\n'.join(lines)\n\n def show(self, cols=10):\n \"\"\"\n prints the entire orbital set in blocks of cols orbitals\n \"\"\"\n\n if self.n_orb == 0:\n print('no orbitals to show... perhaps you filtered too strictly?')\n\n for offset in range(0, self.n_orb, cols):\n orbitals = self[offset:offset+cols]\n print(orbitals)\n\n def show_by_irrep(self, cols=10):\n\n if self.n_irreps > 1:\n for irrep in range(self.n_irreps):\n print('symmetry {:d}'.format(irrep+1))\n print()\n indices, = np.where(self.irreps == irrep)\n self[indices].sorted(reindex=True).show(cols=cols)\n else:\n self.show(cols=cols)\n\n def show_symmetry_species(self):\n if msym is None:\n raise ImportError('no libmsym installation found')\n bs = self.basis_set\n\n elements = [msym.Element(coordinates = Coord, charge = int(Charge))\n for Coord, Charge in zip(bs.center_coordinates, bs.center_charges)]\n\n basis_functions = [msym.RealSphericalHarmonic(element = elements[element_id-1], n = n + l, l = l, m = m)\n for [element_id, n, l, m] in bs.contracted_ids]\n\n with msym.Context(elements = elements, basis_functions = basis_functions) as ctx:\n point_group = ctx.find_symmetry()\n species_names = [s.name for s in ctx.character_table.symmetry_species]\n coefficients = np.asarray(self.coefficients)\n for offset in range(0,self.n_orb):\n mo = coefficients[:,offset]\n #mo /= np.linalg.norm(mo)\n species_components = ctx.symmetry_species_components(mo)\n print(offset,': ',' + '.join(['%f %s' % k for k in zip(species_components, species_names) if k[0] > 1.0e-6]))\n\n def sorted(self, reindex=False):\n \"\"\"\n returns a new orbitals set sorted first by typeid, then by\n increasing energy, and finally by decreasing occupation.\n \"\"\"\n\n index = np.lexsort((self.energies, -self.occupations))\n\n if reindex:\n ids = None\n else:\n ids = self.ids[index]\n\n return self.__class__(\n self.coefficients[:,index],\n ids=ids,\n types=self.types[index],\n irreps=self.irreps[index],\n energies=self.energies[index],\n occupations=self.occupations[index],\n basis_ids=self.basis_ids.copy(),\n basis_set=self.basis_set,\n )\n\n def type(self, *typeids):\n \"\"\"\n returns a new orbital set with only the requested type ids.\n \"\"\"\n\n mo_indices = []\n for typeid in typeids:\n mo_set, = np.where(self.types == typeid)\n mo_indices.extend(mo_set)\n\n return self[mo_indices]\n\n def erange(self, lo, hi):\n \"\"\"\n returns a new orbital set with orbitals that have an energy\n between lo and hi.\n \"\"\"\n\n return self[(self.energies > lo) & (self.energies < hi)]\n\n def pattern(self, regex):\n \"\"\"\n returns a new orbital set where the basis functions have been\n filtered as those which labels are matching the supplied regex.\n \"\"\"\n matching = [bool(re.search(regex, label)) for label in self.basis_set.labels]\n\n return self.filter_basis(np.asarray(matching))\n\n def sanitize(self):\n \"\"\"\n Sanitize the orbital data, replacing NaN or missing values with safe\n placeholders.\n \"\"\"\n for attribute in ['occupations', 'energies', 'coefficients']:\n array = getattr(self, attribute)\n selection = np.where(np.isnan(array))\n array[selection] = 0.0\n\n selection = np.where(self.types == '-')\n self.types[selection] = 's'\n","sub_path":"molpy/orbitals.py","file_name":"orbitals.py","file_ext":"py","file_size_in_byte":8665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"99321220","text":"import threading\nimport time\nfrom selenium import webdriver\n\nimport requests\nfrom browsermobproxy import Server\nfrom bs4 import BeautifulSoup\n\n\nclass spider_bilibili():\n def __init__(self):\n self.count = 0\n self.all_list = []\n self.thread_count = 0\n\n def start_spider(self, video_link, download_count):\n # 设置网络代理监控\n server = Server(r\"C:\\Users\\Jerry\\Desktop\\browsermob-proxy-2.0-beta-6\\bin\\browsermob-proxy.bat\")\n server.start()\n proxy = server.create_proxy()\n\n # 设置浏览器配置,设置代理\n profile = webdriver.FirefoxProfile(r'C:\\Users\\Jerry\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\5ysei6kr.default')\n profile.set_proxy(proxy.selenium_proxy())\n driver = webdriver.Firefox(firefox_profile=profile)\n\n # 打开本集番剧\n print('第', self.count, '集:', video_link)\n driver.get(video_link)\n\n # 创建监控\n proxy.new_har('fuck_bilibili')\n\n # 分析页面,找到iframe的地址\n soup = BeautifulSoup(driver.page_source, 'lxml')\n iframe = soup.select('iframe')\n iframe_url = 'http:' + iframe[0]['src']\n print('iframe_url:\\n')\n print(iframe_url)\n print('-----------------')\n\n # 判断是否已经抓到视频流量\n while True:\n # 抓到视频流量标记\n get_video_flag = False\n\n # 获得抓到的信息\n content = proxy.har\n\n # 视频链接分析\n video_list = []\n data = content['log']['entries']\n for i in range(len(data)):\n url = data[i]['request']['url']\n if url.find('.flv?expires=') != -1 and '11455913-1' not in url:\n video_list.append(url)\n # 加入all_list是为了后面归纳文件\n self.all_list.append('第' + str(download_count + 1) + '集:' + url)\n print('now download_count is:', download_count)\n # 如果代码能执行到这里,表示视频流量已经抓到\n get_video_flag = True\n\n if get_video_flag:\n break\n\n # 关闭资源\n time.sleep(20)\n server.stop()\n driver.quit()\n\n # 视频链接分析完毕后,将本集的视频源写入单独文件\n with open('第' + str(download_count + 1) + '集.txt', 'w') as f:\n for i in video_list:\n print(i, file=f)\n\n self.thread_count -= 1\n\n def main_run(self):\n url = 'http://bangumi.bilibili.com/anime/3462'\n\n # 获取每集的页面地址\n response = requests.get(url)\n soup = BeautifulSoup(response.text, 'lxml')\n video_links = soup.select('.v1-complete-text')\n\n # 爬视频源地址\n for video_link in video_links:\n video_link = 'http:' + video_link['href']\n if self.thread_count < 3:\n threading.Thread(target=self.start_spider, args=(video_link, self.count)).start()\n self.thread_count += 1\n print('self.thread_count:', self.thread_count)\n time.sleep(5)\n else:\n while True:\n time.sleep(10)\n if self.thread_count < 3:\n threading.Thread(target=self.start_spider, args=(video_link, self.count)).start()\n self.count += 1\n self.thread_count += 1\n print('self.thread_count:', self.thread_count)\n break\n\n # 归纳文件\n with open('fuck_all.txt', 'w') as f:\n for i in range(len(self.all_list)):\n print('第' + str(i + 1) + '集', file=f)\n print(self.all_list[i], file=f)\n print('fuck done')\n\n\nspider = spider_bilibili()\nspider.main_run()\n","sub_path":"fuck_bilibili.py","file_name":"fuck_bilibili.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"76780935","text":"from __future__ import unicode_literals\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom location_field.models.plain import PlainLocationField\n# Create your models here.\nclass UserProfile(models.Model):\n user=models.ForeignKey(User,on_delete=models.CASCADE)\n Name=models.CharField(max_length=150,null=False,blank=False)\n Email=models.EmailField(null=False,blank=False)\n Telephone=models.IntegerField()\n content = models.TextField()\n city = models.CharField(max_length=255)\n location = PlainLocationField(based_fields=['city'], zoom=7)\n updated = models.DateTimeField(auto_now=True, auto_now_add=False)\n timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)\n # location_2 = models.CharField(max_length=254)\n def __unicode__(self):\n return self.Name\n\nclass Category(models.Model):\n user=models.ForeignKey(User,on_delete=models.CASCADE)\n category_title=models.CharField(max_length=120)\n Name=models.CharField(max_length=120)\n Price=models.CharField(max_length=120)\n Name_logo=models.ImageField(upload_to='photos/%Y/%m/%d/', null=True,blank=True)\n updated = models.DateTimeField(auto_now=True, auto_now_add=False)\n timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)\n \n def __unicode__(self):\n return self.category_title\n def get_absolute_url(self):\n return reverse(\"ecommerce:detail\",kwargs={\"id\":self.id})\n \n\n\n\n\n\n\n","sub_path":"ecommerce_web/src/ecommerce/.~c9_invoke_XZ9fpa.py","file_name":".~c9_invoke_XZ9fpa.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"478041991","text":"import json\nimport time\nfrom datetime import date\n\nimport pymsteams\nimport requests\n\ntoday = date.today()\nd1 = today.strftime(\"%d-%m-%Y\")\n\ndistrict_ids = [\"143\", \"146\", \"141\"] # north west delhi, north delhi, central delhi\nwebhook_url = \"MS_TEAMS_WEB_HOOK_URL\"\n\n\ndef check():\n available_centers = []\n for id in district_ids:\n query = {'date': d1, 'district_id': id}\n headers = {\"User-Agent\": \"PostmanRuntime/7.26.10\"}\n url = f\"https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict\"\n\n print(\"query =\", query)\n response = requests.get(url, params=query, headers=headers)\n centers = response.json()[\"centers\"]\n for center in centers:\n name = center[\"name\"]\n address = center[\"address\"]\n pincode = center[\"pincode\"]\n district_name = center[\"district_name\"]\n\n for session in center[\"sessions\"]:\n if session[\"min_age_limit\"] == 18 and session[\"available_capacity\"] > 0:\n c = {'name': name, 'address': address, 'pincode': pincode, 'district_name': district_name,\n \"capacity\": session[\"available_capacity\"], \"date\": session[\"date\"],\n \"vaccine\": session[\"vaccine\"], \"available_capacity_dose1\":session[\"available_capacity_dose1\"],\n \"available_capacity_dose2\":session[\"available_capacity_dose2\"]}\n available_centers.append(c)\n if len(available_centers) > 0:\n print(available_centers)\n myTeamsMessage = pymsteams.connectorcard(webhook_url)\n myTeamsMessage.text(json.dumps(available_centers))\n myTeamsMessage.send()\n\n\nwhile True:\n check()\n time.sleep(300) # 5 mins\n","sub_path":"call_cowin.py","file_name":"call_cowin.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"214343831","text":"# coding=utf-8\n# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport glob\nimport os\n\nfrom pex.executor import Executor\nfrom pex.interpreter import PythonInterpreter\n\nfrom pants.util.contextutil import temporary_dir\nfrom pants.util.process_handler import subprocess\nfrom pants_test.backend.python.interpreter_selection_utils import (PY_3, PY_27,\n skip_unless_python3_present,\n skip_unless_python27_present)\nfrom pants_test.pants_run_integration_test import PantsRunIntegrationTest\n\n\nclass InterpreterSelectionIntegrationTest(PantsRunIntegrationTest):\n\n testproject = 'testprojects/src/python/interpreter_selection'\n\n @classmethod\n def hermetic(cls):\n # We must set as true to ignore `PANTS_PYTHON_SETUP_INTERPRETER_CONSTRAINTS`\n # preconfiguring the interpreter_constraint. For example, in `ci.sh` we set\n # this environment variable to Python 3, which overrides any config defined\n # in the below tests.\n return True\n\n def test_cli_option_wins_compatibility_conflict(self):\n # Tests that targets with compatibility conflicts collide.\n binary_target = '{}:deliberately_conficting_compatibility'.format(self.testproject)\n pants_run = self._build_pex(binary_target)\n self.assert_success(pants_run, 'Failed to build {binary}.'.format(binary=binary_target))\n\n def test_conflict_via_config(self):\n # Tests that targets with compatibility conflict with targets with default compatibility.\n # NB: Passes empty `args` to avoid having the default CLI args override the config.\n config = {\n 'python-setup': {\n 'interpreter_constraints': ['CPython<2.7'],\n }\n }\n binary_target = '{}:echo_interpreter_version'.format(self.testproject)\n pants_run = self._build_pex(binary_target, config=config, args=[])\n self.assert_failure(pants_run,\n 'Unexpected successful build of {binary}.'.format(binary=binary_target))\n self.assertIn('Unable to detect a suitable interpreter for compatibilities',\n pants_run.stdout_data)\n\n @skip_unless_python3_present\n def test_select_3(self):\n self._test_version(PY_3)\n\n @skip_unless_python27_present\n def test_select_27(self):\n self._test_version(PY_27)\n\n def _test_version(self, version):\n echo = self._echo_version(version)\n v = echo.split('.') # E.g., 2.7.13.\n self.assertTrue(len(v) > 2, 'Not a valid version string: {}'.format(v))\n expected_components = version.split('.')\n self.assertEqual(expected_components, v[:len(expected_components)])\n\n def _echo_version(self, version):\n with temporary_dir() as distdir:\n config = {\n 'GLOBAL': {\n 'pants_distdir': distdir\n }\n }\n binary_name = 'echo_interpreter_version_{}'.format(version)\n binary_target = '{}:{}'.format(self.testproject, binary_name)\n pants_run = self._build_pex(binary_target, config, version=version)\n self.assert_success(pants_run, 'Failed to build {binary}.'.format(binary=binary_target))\n\n # Run the built pex.\n exe = os.path.join(distdir, binary_name + '.pex')\n proc = subprocess.Popen([exe], stdout=subprocess.PIPE)\n (stdout_data, _) = proc.communicate()\n return stdout_data.decode('utf-8')\n\n def _build_pex(self, binary_target, config=None, args=None, version=PY_27):\n # By default, Avoid some known-to-choke-on interpreters.\n if version == PY_3:\n constraint = '[\"CPython>=3.4,<4\"]'\n else:\n constraint = '[\"CPython>=2.7,<3\"]'\n args = list(args) if args is not None else [\n '--python-setup-interpreter-constraints={}'.format(constraint)\n ]\n command = ['binary', binary_target] + args\n return self.run_pants(command=command, config=config)\n\n def test_stale_interpreter_purge_integration(self):\n target = '{}:{}'.format(self.testproject, 'echo_interpreter_version')\n config = {\n 'python-setup': {\n 'interpreter_constraints': ['CPython>=2.7,<4'],\n }\n }\n with self.temporary_workdir() as workdir:\n pants_run = self.run_pants_with_workdir(\n [\"run\", target],\n workdir=workdir,\n config=config\n )\n self.assert_success(pants_run)\n\n def _prepend_bad_interpreter_to_interpreter_path_file(path):\n with open(path, 'r') as fp:\n file_data = fp.readlines()\n file_data[0] = '/my/bogus/interpreter/python2.7'\n with open(path, 'w') as fp:\n fp.writelines(file_data)\n\n def _validate_good_interpreter_path_file(path):\n with open(path, 'r') as fp:\n lines = fp.readlines()\n binary = lines[0].strip()\n try:\n interpreter = PythonInterpreter.from_binary(binary)\n return True if interpreter else False\n except Executor.ExecutableNotFound:\n return False\n\n # Mangle interpreter.info.\n for path in glob.glob(os.path.join(workdir, 'pyprep/interpreter/*/interpreter.info')):\n _prepend_bad_interpreter_to_interpreter_path_file(path)\n\n pants_run = self.run_pants_with_workdir(\n [\"run\", target],\n workdir=workdir,\n config=config\n )\n self.assert_success(pants_run)\n for path in glob.glob(os.path.join(workdir, 'pyprep/interpreter/*/interpreter.info')):\n self.assertTrue(\n _validate_good_interpreter_path_file(path),\n 'interpreter.info was not purged and repopulated properly: {}'.format(path)\n )\n","sub_path":"tests/python/pants_test/backend/python/tasks/test_interpreter_selection_integration.py","file_name":"test_interpreter_selection_integration.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"224425750","text":"\"\"\"\n Copyright (c) 2020 Intel Corporation\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\nimport os.path as osp\n\nimport numpy as np\n\nfrom utils.text_preprocessing import text_to_sequence, _symbol_to_id\n\n\nclass ForwardTacotronIE:\n def __init__(self, model_duration, model_forward, ie, device='CPU', verbose=False):\n self.verbose = verbose\n self.device = device\n\n self.ie = ie\n\n self.duration_predictor_net = self.load_network(model_duration)\n self.duration_predictor_exec = self.create_exec_network(self.duration_predictor_net)\n\n self.forward_net = self.load_network(model_forward)\n self.forward_exec = self.create_exec_network(self.forward_net)\n\n # fixed length of the sequence of symbols\n self.duration_len = self.duration_predictor_net.input_info['input_seq'].input_data.shape[1]\n # fixed length of the input embeddings for forward\n self.forward_len = self.forward_net.input_info['data'].input_data.shape[1]\n if self.verbose:\n print('Forward limitations : {0} symbols and {1} embeddings'.format(self.duration_len, self.forward_len))\n self.is_attention = 'pos_mask' in self.forward_net.input_info\n if self.is_attention:\n self.init_pos_mask()\n print(\"Load ForwardTacotron with attention\")\n else:\n self.pos_mask = None\n\n def init_pos_mask(self, mask_sz=6000, window_size=4):\n mask_arr = np.zeros((1, 1, mask_sz, mask_sz), dtype=np.float32)\n width = 2 * window_size + 1\n for i in range(mask_sz - width):\n mask_arr[0][0][i][i:i + width] = 1.0\n\n self.pos_mask = mask_arr\n\n @staticmethod\n def sequence_mask(length, max_length=None):\n if max_length is None:\n max_length = np.max(length)\n x = np.arange(max_length, dtype=length.dtype)\n x = np.expand_dims(x, axis=(0))\n length = np.expand_dims(length, axis=(1))\n return x < length\n\n def seq_to_indexes(self, text):\n res = text_to_sequence(text)\n if self.verbose:\n print(res)\n return res\n\n @staticmethod\n def build_index(duration, x):\n duration[np.where(duration < 0)] = 0\n tot_duration = np.cumsum(duration, 1)\n max_duration = int(tot_duration.max().item())\n index = np.zeros([x.shape[0], max_duration, x.shape[2]], dtype='long')\n\n for i in range(tot_duration.shape[0]):\n pos = 0\n for j in range(tot_duration.shape[1]):\n pos1 = tot_duration[i, j]\n index[i, pos:pos1, :] = j\n pos = pos1\n index[i, pos:, :] = j\n return index\n\n @staticmethod\n def gather(a, dim, index):\n expanded_index = [index if dim == i else np.arange(a.shape[i]).reshape(\n [-1 if i == j else 1 for j in range(a.ndim)]) for i in range(a.ndim)]\n return a[tuple(expanded_index)]\n\n def load_network(self, model_xml):\n model_bin_name = \".\".join(osp.basename(model_xml).split('.')[:-1]) + \".bin\"\n model_bin = osp.join(osp.dirname(model_xml), model_bin_name)\n print(\"Loading network files:\\n\\t{}\\n\\t{}\".format(model_xml, model_bin))\n net = self.ie.read_network(model=model_xml, weights=model_bin)\n return net\n\n def create_exec_network(self, net):\n exec_net = self.ie.load_network(network=net, device_name=self.device)\n return exec_net\n\n def infer_duration(self, sequence, alpha=1.0, non_empty_symbols=None):\n if self.is_attention:\n input_mask = self.sequence_mask(np.array([[non_empty_symbols]]), sequence.shape[1])\n pos_mask = self.pos_mask[:, :, :sequence.shape[1], :sequence.shape[1]]\n out = self.duration_predictor_exec.infer(inputs={\"input_seq\": sequence,\n \"input_mask\": input_mask,\n \"pos_mask\": pos_mask})\n else:\n out = self.duration_predictor_exec.infer(inputs={\"input_seq\": sequence})\n duration = out[\"duration\"] * alpha\n\n duration = (duration + 0.5).astype('int').flatten()\n duration = np.expand_dims(duration, axis=0)\n preprocessed_embeddings = out[\"embeddings\"]\n\n if non_empty_symbols is not None:\n duration = duration[:, :non_empty_symbols]\n preprocessed_embeddings = preprocessed_embeddings[:, :non_empty_symbols]\n indexes = self.build_index(duration, preprocessed_embeddings)\n if self.verbose:\n print(\"Index: {0}, duration: {1}, embeddings: {2}, non_empty_symbols: {3}\"\n .format(indexes.shape, duration.shape, preprocessed_embeddings.shape, non_empty_symbols))\n\n return self.gather(preprocessed_embeddings, 1, indexes)\n\n def infer_mel(self, aligned_emb, non_empty_symbols):\n if self.is_attention:\n data_mask = self.sequence_mask(np.array([[non_empty_symbols]]), aligned_emb.shape[1])\n pos_mask = self.pos_mask[:, :, :aligned_emb.shape[1], :aligned_emb.shape[1]]\n out = self.forward_exec.infer(inputs={\"data\": aligned_emb,\n \"data_mask\": data_mask,\n \"pos_mask\": pos_mask})\n else:\n out = self.forward_exec.infer(inputs={\"data\": aligned_emb})\n return out['mel'][:, :non_empty_symbols]\n\n def find_optimal_delimiters_position(self, sequence, delimiters, idx, window=20):\n res = {d: -1 for d in delimiters}\n for i in range(max(0, idx - window), idx):\n if sequence[i] in delimiters:\n res[sequence[i]] = i + 1\n return res\n\n def forward_duration_prediction_by_delimiters(self, text, alpha):\n sequence = self.seq_to_indexes(text)\n seq_len = len(sequence)\n outputs = []\n\n if seq_len <= self.duration_len:\n non_empty_symbols = len(sequence) + min(1, self.duration_len - seq_len)\n sequence = sequence + [_symbol_to_id[' ']] * (self.duration_len - seq_len)\n sequence = np.array(sequence)\n sequence = np.expand_dims(sequence, axis=0)\n outputs.append(self.infer_duration(sequence, alpha, non_empty_symbols=non_empty_symbols))\n else:\n punctuation = '.!?,;: '\n delimiters = [_symbol_to_id[p] for p in punctuation]\n\n start_idx = 0\n while start_idx < seq_len:\n if start_idx + self.duration_len < seq_len:\n positions = self.find_optimal_delimiters_position(sequence, delimiters,\n start_idx + self.duration_len,\n window=self.duration_len//10)\n else:\n positions = {delimiters[0]: seq_len}\n edge = -1\n for d in delimiters:\n if positions[d] > 0:\n edge = positions[d]\n break\n if edge < 0:\n raise Exception(\"Bad delimiter position {0} for sequence with length {1}\".format(edge, seq_len))\n\n sub_sequence = sequence[start_idx:edge]\n non_empty_symbols = len(sub_sequence) + min(1, self.duration_len - len(sub_sequence))\n sub_sequence += [_symbol_to_id[' ']] * (self.duration_len - len(sub_sequence))\n sub_sequence = np.array(sub_sequence)\n sub_sequence = np.expand_dims(sub_sequence, axis=0)\n outputs.append(self.infer_duration(sub_sequence, alpha, non_empty_symbols=non_empty_symbols))\n start_idx = edge\n\n aligned_emb = np.concatenate(outputs, axis=1)\n return aligned_emb\n\n def forward(self, text, alpha=1.0):\n aligned_emb = self.forward_duration_prediction_by_delimiters(text, alpha)\n\n mels = []\n start_idx = 0\n end_idx = 0\n while start_idx < aligned_emb.shape[1] and end_idx < aligned_emb.shape[1]:\n end_idx = min(start_idx + self.forward_len, aligned_emb.shape[1])\n sub_aligned_emb = aligned_emb[:, start_idx:end_idx, :]\n if sub_aligned_emb.shape[1] < self.forward_len:\n sub_aligned_emb = np.pad(sub_aligned_emb,\n ((0, 0), (0, self.forward_len - sub_aligned_emb.shape[1]), (0, 0)),\n 'constant', constant_values=0)\n if self.verbose:\n print(\"SAEmb shape: {0}\".format(sub_aligned_emb.shape))\n mel = self.infer_mel(sub_aligned_emb, end_idx - start_idx)\n mels.append(mel)\n start_idx += self.forward_len\n\n res = np.concatenate(mels, axis=1)\n if self.verbose:\n print(\"MEL shape :{0}\".format(res.shape))\n\n return res\n","sub_path":"demos/text_to_speech_demo/python/models/forward_tacotron_ie.py","file_name":"forward_tacotron_ie.py","file_ext":"py","file_size_in_byte":9473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"585425131","text":"#!/usr/bin/env python3\n# -*- coding: utf8 -*-\n\n# Gaik Tamazian, 2019\n# mail (at) gtamazian (dot) com\n\n\"\"\"Routines for producing synteny plots.\"\"\"\n\nimport gzip\nimport sys\nfrom functools import reduce\nfrom operator import itemgetter\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import Polygon\nfrom matplotlib.patches import Rectangle\nimport numpy as np\n\nassert sys.version_info >= (3, 5), \"Python 3.5 or higher required\"\n\n\ndef load_ref_config(config_fname):\n \"\"\"\n Load configuration of reference genome chromosomes.\n\n The contiguration file contains five columns:\n\n 1. chromosome name\n 2. chromosome ID\n 3. chromosome length in bp\n 4. start and end positions of a centromere separated by dash, or\n NA if the centromere information is missing\n\n :param config_fname: a name of the reference chromosome\n configuration file\n :returns: a list of 5-tuples representing reference genome\n chromosomes; each tuple contain a chromosome name, ID, length in\n bp, and start and end positions of its centromere\n \"\"\"\n r = []\n with open(config_fname) as config_file:\n for line in config_file:\n line = line.rstrip()\n chr_name, chr_id, chr_len, cent_s, cent_e = \\\n line.split(None, 4)\n chr_len = int(chr_len)\n cent_s = int(cent_s) if cent_s != \"None\" else None\n cent_e = int(cent_e) if cent_e != \"None\" else None\n r.append((chr_name, chr_id, chr_len, cent_s, cent_e))\n\n return r\n\n\ndef build_ref_config_file(chr2acc_fname, agp_fnames):\n \"\"\"\n Build a configuration file of reference genome chromosomes from a\n chr2acc file and a series of AGP files that describe the assembled\n chromosomes.\n\n :param chr2acc_fname: a name of a chr2acc file\n :param agp_fnames: a list of reference chromosome AGP files\n :returns: a list of the configuration file\n \"\"\"\n acc2chr = {}\n with open(chr2acc_fname) as chr2acc_file:\n acc2chr = {x[1]: x[0] for x in\n map(lambda s: s.split('\\t', 1),\n filter(lambda s: not s.startswith('#'),\n map(str.rstrip,\n chr2acc_file.readlines())))}\n\n chr_lengths = {}\n # values of the chr_centromeres dictionary are 2-tuples of start and\n # end positions of a centromere on a chromosome\n chr_centromeres = {}\n\n for k in agp_fnames:\n with gzip.open(k, \"rt\") as agp_file:\n lines = map(lambda x: (x[0], int(x[1]), int(x[2])) +\n tuple(x[3:]),\n map(lambda s: s.split('\\t', 8),\n map(str.rstrip,\n filter(lambda s: not s.startswith('#'),\n agp_file.readlines()))))\n lines = sorted(lines, key=itemgetter(1))\n chr_id = set(map(itemgetter(0), lines))\n assert len(chr_id) == 1, \\\n \"multiple chromosomes in an AGP file\"\n chr_id = chr_id.pop()\n\n centromere = list(filter(lambda x: x[6] == \"centromere\",\n lines))\n if centromere:\n assert len(centromere) == 1, \"multiple centromeres\"\n centromere = centromere[0]\n cent_start, cent_end = centromere[1], centromere[2]\n assert chr_id not in chr_centromeres or \\\n chr_centromeres[chr_id] == (cent_start, cent_end), \\\n \"conflicting centromere records\"\n chr_centromeres[chr_id] = (cent_start, cent_end)\n else:\n chr_centromeres[chr_id] = (None, None)\n\n chr_len = lines[-1][2]\n assert chr_id not in chr_lengths or \\\n chr_lengths[chr_id] == chr_len, \\\n \"conflicting chromosome lengths\"\n\n chr_lengths[chr_id] = chr_len\n\n return [(v, k, chr_lengths[k]) + chr_centromeres[k]\n for k, v in acc2chr.items()]\n\n\ndef plot_frame(ref_chrom_config, p):\n \"\"\"\n Plot a frame of reference chromosomes for synteny blocks based on\n them.\n\n :param ref_chrom_config: a list of 5-tuples describing the reference\n chromosomes as returned by the load_ref_config function.\n :param p: a plotting parameter; its value should be between 10 and\n 100\n :returns: a 2-tuple which first element is the plot frame Figure\n object and the second element is the list of the AxesSubplot\n objects\n \"\"\"\n fig, axes = plt.subplots(ncols=1, nrows=len(ref_chrom_config))\n max_len = reduce(max, map(itemgetter(2), ref_chrom_config))\n shift = max_len / 30\n\n for ax, chrom in zip(axes, ref_chrom_config):\n chr_name, _, chr_len, _, _ = chrom\n ax.set_xlim([-shift, max_len])\n ax.set_ylim([-p, p])\n ax.axis('off')\n ax.text(-shift, 0, chr_name, horizontalalignment=\"right\",\n verticalalignment=\"center\")\n ax.add_line(Line2D([0, chr_len], [0, 0], color=\"black\",\n linewidth=0.5))\n\n return fig, axes\n\n\ndef add_centromeres(fig, ref_chrom_config, p, style):\n \"\"\"\n Add centromeres to a reference chromosome frame.\n\n :param fig: a Figure object of a reference chromosome frame\n :param ref_chrom_config: a list of 5-tuples describing the reference\n chromosomes as returned by the load_ref_config function\n :param p: a plotting parameter; its value should be between 10 and\n 100\n :returns: the Figure object of the reference chromosome frame with\n added centromeres\n \"\"\"\n assert style in {\"triangle\", \"butterfly\"}, \\\n \"incorrect centromere style\"\n\n for ax, chrom in zip(fig.get_axes(), ref_chrom_config):\n _, _, _, cent_s, cent_e = chrom\n if cent_s is not None and cent_e is not None:\n ax.add_patch(Polygon(np.array(\n [[cent_s, p], [cent_e, p],\n [(cent_s + cent_e)/2, p/5]]), color=\"black\"))\n if style == \"butterfly\":\n ax.add_patch(Polygon(np.array(\n [[cent_s, -p], [cent_e, -p],\n [(cent_s + cent_e)/2, -p/5]]), color=\"black\"))\n\n return fig\n\n\n\n\n\ndef extend_frame(axes, p):\n \"\"\"\n Extend a reference chromosome frame to add one more track of\n synteny blocks.\n\n :param axes: a list of the AxesSubplot objects returned by the\n plot_frame function\n :param p: a plotting parameter; its value should be between 150\n and 300\n :returns: the list of the AxesSubplot objects which correspond to\n the extended reference chromosome frame\n \"\"\"\n for ax in axes:\n y_min, y_max = ax.get_ylim()\n y_min -= 2*p\n ax.set_ylim((y_min, y_max))\n\n return axes\n\n\ndef add_synteny_block(ref_chrom_config, axes, chrom, start, end,\n strand, e_color, f_color, p):\n \"\"\"\n Add a synteny block to the reference chromosome frame.\n\n :param ref_chrom_config: a list of 5-tuples describing the reference\n chromosomes as returned by the load_ref_config function\n :param axes: a list of the AxesSubplot objects returned by the\n plot_frame function\n :param chrom: the chromosome a syntenic block is located on\n :param start: the start position of a syntenic block\n :param end: the end position of a syntenic block\n :param strand: the syntenic block orientation ('+', '-', or None)\n :param e_color: color of the block edge\n :param f_color: color the block is filled in\n :param p: a plotting parameter; its value should be between 150 and\n 300\n :returns: the list of the AxesSubplot objects with the added synteny\n block\n \"\"\"\n global_x_max = reduce(max, map(lambda x: x.get_xlim()[1], axes))\n alpha = global_x_max / 100\n\n chr_dict = {v: k for k, v in enumerate(map(itemgetter(1),\n ref_chrom_config))}\n ax = axes[chr_dict[chrom]]\n _, x_max = ax.get_xlim()\n y_min, _ = ax.get_ylim()\n\n assert strand is None or strand in {'+', '-'}, \"incorrect strand\"\n\n l = end - start\n if l < global_x_max / 300:\n return axes\n\n if strand is None:\n r = Rectangle((start, y_min + p/4),\n height=3*p/2, width=end-start,\n edgecolor=e_color, facecolor=f_color,\n fill=True, linewidth=0.5)\n ax.add_patch(r)\n else:\n alpha = x_max/(2*p)\n if strand == '+':\n if l > alpha:\n p = Polygon(np.array([[start, y_min + 7*p/4],\n [end - alpha, y_min + 7*p/4],\n [end, y_min + p],\n [end - alpha, y_min + p/4],\n [start, y_min + p/4]]),\n edgecolor=e_color, facecolor=f_color,\n fill=True, linewidth=0.5)\n else:\n p = Polygon(np.array([[start, y_min + 7*p/4],\n [end, p],\n [start, y_min + p/4]]),\n edgecolor=e_color, facecolor=f_color,\n fill=True, linewidth=0.5)\n else:\n if l > alpha:\n p = Polygon(np.array([[end, y_min + 7*p/4],\n [start + alpha, y_min + 7*p/4],\n [start, y_min + p],\n [start + alpha, y_min + p/4],\n [end, y_min + p/4]]),\n edgecolor=e_color, facecolor=f_color,\n fill=True, linewidth=0.5)\n else:\n p = Polygon(np.array([[end, y_min + 7*p/4],\n [start, y_min + p],\n [end, y_min + p/4]]),\n edgecolor=e_color, facecolor=f_color,\n fill=True, linewidth=0.5)\n ax.add_patch(p)\n\n return axes\n","sub_path":"bioformats/synteny_plot.py","file_name":"synteny_plot.py","file_ext":"py","file_size_in_byte":10165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"375670788","text":"import pandas as pd \nimport numpy as np\nimport os.path\nimport sys\nfrom math import floor\nfrom datetime import datetime, timedelta\nfrom lib.ntlogging import logging\nfrom lib.stox_utils import FILTERED_PRICES_PREFIX, BUY_SELL_RESULTS_PREFIX\n\n# This builds a result row for every trading day in the set.\n# Transactions that are pending sale until the hold period is reached\n# are put into the pending_lst.\n# A sale will close out the first item from the pending list, adjust the shares\n# owned at the sell date by the split coefficients, and append the sale\n# to the results_lst. The final dataframe is built from the results_lst.\n\ndef buy_sell_v3(budget_dollars, fee_dollars, hold_days, low_price_cutoff, yearspan):\n\n prices_input_file = FILTERED_PRICES_PREFIX + str(yearspan) + \"years.csv\"\n\n hold_str = str(hold_days)\n budget_dollars_str = str(int(budget_dollars))\n buy_sell_output_postfix = str(yearspan) + \"years_\" + hold_str + \"days_\" + budget_dollars_str + \"dollars.csv\"\n buy_sell_output_file = BUY_SELL_RESULTS_PREFIX + buy_sell_output_postfix\n\n # clean up the existing output file (ignore !exists error)\n try:\n os.remove(buy_sell_output_file)\n except OSError:\n pass \n\n # load prices and group by symbol\n try:\n logging.info(\"Reading: \" + prices_input_file)\n stox_df = pd.read_table(prices_input_file, sep=',')\n stox_df['date'] = pd.to_datetime(stox_df['date'])\n stox_df = stox_df.groupby('symbol')\n logging.info(\"Found \" + str(len(stox_df)) + \" symbols in price data.\")\n \n except Exception as e:\n logging.warning(\"Not parsed: \" + prices_input_file + \"\\n\" + str(e))\n sys.exit()\n \n \n numsyms = len(stox_df) # total number of symbols\n cant_afford = set() # set of symbols whose unit share price exceeds budget\n penny_stocks = set() # set of low price symbols\n\n results_lst = [] # completed transactions\n write_header = True # results file header (write once flag)\n\n # Loop over each symbol\n symnum = 1 # symbol idx\n \n for symbol, sym_df in stox_df:\n\n max_gain = max_loss = 0.0\n pending_lst = [] # has buy attributes for each buy date\n\n # TODO make sure the sym_df is in date order ascending\n\n row_idx = 0\n for row in sym_df.itertuples():\n\n buy_price, shares_bought, status = buy(row, budget_dollars)\n split_coeff = row.split_coefficient\n\n if status == 'price_high':\n cant_afford.add(symbol) # todo: count these\n elif status == 'price_low':\n penny_stocks.add(symbol) # todo: count these\n \n # add current row to pending sale list\n pending_lst.append([symbol, row_idx, row.date, shares_bought, \n buy_price, split_coeff])\n \n # Once the pending sales list is full, start creating results list\n if row_idx >= hold_days: \n\n result_row = sell_row(row, pending_lst, fee_dollars)\n\n returns = float(result_row[11])\n\n # just for logging\n if returns > max_gain: max_gain = returns\n if returns < max_loss: max_loss = returns\n\n # add the result row to results list\n results_lst.append(result_row)\n \n # remove the sold row \n del pending_lst[0]\n\n row_idx += 1\n\n # peridocially write the results list\n qmax = 100000\n if len(results_lst) >= qmax:\n logging.info(f\"Writing {qmax} results to {buy_sell_output_file}\")\n append_csv(buy_sell_output_file, results_lst, write_header, low_price_cutoff)\n write_header = False\n results_lst = []\n\n symnum += 1 # keep track of how many symbols have been processed\n logging.info(f\"{symbol} \\t\\t[{symnum} of {numsyms}] \\ttrade days: \" +\n f\"{str(len(sym_df))} max_gain: {max_gain:.2f} \" +\n f\"max_loss: {max_loss:.2f}\")\n \n\n # final csv update\n if len(results_lst) > 0:\n logging.info(f\"Writing {len(results_lst)} results to {buy_sell_output_file}\")\n append_csv(buy_sell_output_file, results_lst, write_header, low_price_cutoff)\n \n logging.info(\"Zero shares bought (price exceeds budget): \" + \n str(cant_afford))\n logging.info(\"Zero shares bought (price too low): \" + \n str(penny_stocks))\n\n\n# Drop unwanted rows and update csv\ndef append_csv(csv_file, results_lst, write_header, low_price_cutoff):\n\n # columns for output dataframe\n cols = ['symbol', 'interval', 'trading_days_held', 'cal_days_held',\n 'buy_date', 'shares_bought', 'buy_price', 'sell_date', \n 'shares_sold', 'sell_price', 'fee', 'gain_total']\n\n out_df = pd.DataFrame(results_lst, columns=cols).sort_values(['symbol', \n 'interval'], ascending=True)\n\n # Drop zero-shares transactions\n out_df = out_df[out_df.shares_bought > 0]\n\n # drop penny stock transactions\n out_df = out_df[out_df.buy_price > low_price_cutoff]\n\n with open(csv_file, 'a') as f:\n out_df.to_csv(f, index=False, sep=\",\", float_format='%.3f', \n header=write_header)\n\n\ndef sell_row(row, pending_lst, fee):\n\n sold_row = pending_lst[0]\n symbol = sold_row[0]\n idx = sold_row[1]\n buy_date = sold_row[2]\n shares_bought = sold_row[3]\n buy_price = sold_row[4]\n cost_dollars = shares_bought * buy_price\n\n # update num shares owned \n shares_owned = shares_bought\n split_coeff = 1 # default, shouldnt need\n for pending_row in pending_lst[1:]:\n split_coeff = pending_row[5]\n split_coeff_str = f\"{split_coeff:.1}\" \n if split_coeff_str != \"1e+00\":\n shares_owned = shares_owned * split_coeff\n\n sell_date = row.date\n sell_price = (float(row.open) + float(row.close)) / 2.0\n sold_dollars = shares_owned * sell_price\n\n cal_days = (sell_date - buy_date).days\n trading_days = len(pending_lst) - 1\n gain_total = sold_dollars - cost_dollars - fee\n\n result_row = [symbol, idx, trading_days, cal_days,\n buy_date, shares_bought, buy_price,\n sell_date, shares_owned, sell_price,\n fee, gain_total]\n\n return result_row\n\n \ndef buy(row, budget_dollars):\n \n status = \"ok\" # 'ok' if shares bought\n # 'price_high' if too expensive\n # 'price_low' if too cheap\n\n buy_price = (float(row.open) + float(row.close)) / 2.0\n shares_bought = 0\n\n # share lower price limit\n epsilon = .0001\n if buy_price < epsilon:\n status = \"price_low\"\n else:\n # can only buy whole shares\n shares_bought = floor(budget_dollars / buy_price)\n if shares_bought < 1:\n status = \"price_high\"\n \n return buy_price, shares_bought, status\n \n","sub_path":"src/lib/buy_sell_v3.py","file_name":"buy_sell_v3.py","file_ext":"py","file_size_in_byte":6972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"43014833","text":"import requests\nimport boto3\nimport re\nimport json\n\nfrom yig.bot import listener, RE_MATCH_FLAG\nfrom yig.util import get_state_data\n\nimport yig.config\n\n@listener(r\"init.\", bot.message)\n\n url = matcher.group(1) + \".json\"\n res = requests.get(url)\n request_json = json.loads(res.text)\n param_json = format_param_json(bot, request_json)\n\n s3_client = boto3.resource('s3')\n bucket = s3_client.Bucket(yig.config.AWS_S3_BUCKET_NAME)\n\n key = \"%s/%s.json\" % (param_json[\"user_id\"], param_json[\"pc_id\"])\n obj = bucket.Object(key)\n body = json.dumps(param_json, ensure_ascii=False)\n response = obj.put(\n Body=body.encode('utf-8'),\n ContentEncoding='utf-8',\n ContentType='text/plane'\n )\n\n #todo 力尽きたのであとでいい感じにする\n STATE_FILE_PATH = \"/state.json\"\n key_state = param_json[\"user_id\"] + STATE_FILE_PATH\n dict_state = {\n \"url\": url,\n \"pc_id\": \"%s\" % param_json[\"pc_id\"]\n }\n obj_state = bucket.Object(key_state)\n body_state = json.dumps(dict_state, ensure_ascii=False)\n response = obj_state.put(\n Body=body_state.encode('utf-8'),\n ContentEncoding='utf-8',\n ContentType='text/plane'\n )\n\n return get_status_message(\"INIT CHARA\", param_json, dict_state), yig.config.COLOR_ATTENTION\n\n\n@listener(r\"^(u|update)$\", RE_MATCH_FLAG)\ndef update_charasheet_with_vampire(bot):\n color = yig.config.COLOR_ATTENTION\n state_data = get_state_data(bot.user_id)\n url = state_data[\"url\"]\n res = requests.get(url)\n request_json = json.loads(res.text)\n param_json = format_param_json(bot, request_json)\n\n s3_client = boto3.resource('s3')\n bucket = s3_client.Bucket(yig.config.AWS_S3_BUCKET_NAME)\n\n key = \"%s/%s.json\" % (param_json[\"user_id\"], param_json[\"pc_id\"])\n obj = bucket.Object(key)\n body = json.dumps(param_json, ensure_ascii=False)\n response = obj.put(\n Body=body.encode('utf-8'),\n ContentEncoding='utf-8',\n ContentType='text/plane'\n )\n\n return get_status_message(\"UPDATE\", param_json, state_data), color\n\n\n# todo いい感じにする\ndef get_status_message(message_command, dict_param, dict_state):\n name = dict_param['name']\n\n c_hp = dict_param[\"HP\"]\n if \"HP\" in dict_state:\n t_hp = dict_state[\"HP\"]\n val_hp = eval(f\"{c_hp} + {t_hp}\")\n else:\n val_hp = dict_param[\"HP\"]\n\n c_mp = dict_param[\"MP\"]\n if \"MP\" in dict_state:\n t_mp = dict_state[\"MP\"]\n val_mp = eval(f\"{c_mp} + {t_mp}\")\n else:\n val_mp = dict_param[\"MP\"]\n\n dex = dict_param[\"DEX\"]\n\n c_san = dict_param[\"現在SAN\"]\n if \"SAN\" in dict_state:\n t_san = dict_state[\"SAN\"]\n val_san = eval(f\"{c_san} + {t_san}\")\n else:\n val_san = dict_param[\"現在SAN\"]\n\n return f\"【{name}】{message_command}\\nHP {val_hp}/{c_hp}  MP {val_mp}/{c_mp}  DEX {dex}  SAN {val_san}/{c_san}\"\n\n\n# todo 技能の定義なんとかならないか。。。\ndef format_param_json(bot, request_json):\n param_json = {}\n\n REPLACE_PARAMETER = {\n \"NP1\": \"STR\",\n \"NP2\": \"CON\",\n \"NP3\": \"POW\",\n \"NP4\": \"DEX\",\n \"NP5\": \"APP\",\n \"NP6\": \"SIZ\",\n \"NP7\": \"INT\",\n \"NP8\": \"EDU\",\n \"NP9\": \"HP\",\n \"NP10\": \"MP\",\n \"NP11\": \"初期SAN\",\n \"NP12\": \"アイデア\",\n \"NP13\": \"幸運\",\n \"NP14\": \"知識\"}\n \n tba_replace = [\"回避\",\n \"キック\",\n \"組み付き\",\n \"こぶし(パンチ)\",\n \"頭突き\",\n \"投擲\",\n \"マーシャルアーツ\",\n \"拳銃\",\n \"サブマシンガン\",\n \"ショットガン\",\n \"マシンガン\",\n \"ライフル\"]\n\n tfa_replace = [\"応急手当\",\n \"鍵開け\",\n \"隠す\",\n \"隠れる\",\n \"聞き耳\",\n \"忍び歩き\",\n \"写真術\",\n \"精神分析\",\n \"追跡\",\n \"登攀\",\n \"図書館\",\n \"目星\"]\n\n taa_replace = [\"運転\",\n \"機械修理\",\n \"重機械操作\",\n \"乗馬\",\n \"水泳\",\n \"製作\",\n \"操縦\",\n \"跳躍\",\n \"電気修理\",\n \"ナビゲート\",\n \"変装\"]\n\n tca_replace = [\"言いくるめ\",\n \"信用\",\n \"説得\",\n \"値切り\",\n \"母国語\"]\n tka_replace = [\"医学\",\n \"オカルト\",\n \"化学\",\n \"クトゥルフ神話\",\n \"芸術\",\n \"経理\",\n \"考古学\",\n \"コンピューター\",\n \"心理学\",\n \"人類学\",\n \"生物学\",\n \"地質学\",\n \"電子工学\",\n \"天文学\",\n \"博物学\",\n \"物理学\",\n \"法律\",\n \"薬学\",\n \"歴史\"]\n\n for key, param in REPLACE_PARAMETER.items():\n param_json[param] = request_json[key]\n \n def replace_role_param(key, lst_key_roles):\n return_data = {}\n if f\"{key}Name\" in request_json:\n for custom_added_name in request_json[f\"{key}Name\"]:\n lst_key_roles.append(custom_added_name)\n \n for idx, param in enumerate(lst_key_roles):\n lst = []\n lst.append(request_json[f\"{key}D\"][idx])\n lst.append(request_json[f\"{key}S\"][idx])\n lst.append(request_json[f\"{key}K\"][idx])\n lst.append(request_json[f\"{key}A\"][idx])\n lst.append(request_json[f\"{key}O\"][idx])\n lst.append(request_json[f\"{key}P\"][idx])\n return_data[param] = [i if i != \"\" else 0 for i in lst]\n return return_data\n \n param_json.update(replace_role_param(\"TBA\", tba_replace))\n param_json.update(replace_role_param(\"TFA\", tfa_replace))\n param_json.update(replace_role_param(\"TAA\", taa_replace))\n param_json.update(replace_role_param(\"TCA\", tca_replace))\n param_json.update(replace_role_param(\"TKA\", tka_replace))\n \n def add_spec_param(spec_param, name):\n param = request_json[spec_param]\n return {f\"{name}({param})\": param_json[name]}\n\n param_json.update(add_spec_param(\"unten_bunya\", \"運転\"))\n param_json.update(add_spec_param(\"seisaku_bunya\", \"製作\"))\n param_json.update(add_spec_param(\"main_souju_norimono\", \"操縦\"))\n param_json.update(add_spec_param(\"mylang_name\", \"母国語\"))\n param_json.update(add_spec_param(\"geijutu_bunya\", \"芸術\"))\n\n param_json[\"現在SAN\"] = request_json[\"SAN_Left\"]\n param_json[\"最大SAN\"] = request_json[\"SAN_Max\"]\n\n param_json[\"user_id\"] = bot.user_id\n param_json[\"name\"] = request_json[\"pc_name\"]\n param_json[\"pc_id\"] = request_json[\"data_id\"]\n param_json[\"DB\"] = request_json[\"dmg_bonus\"]\n param_json[\"memo\"] = request_json[\"pc_making_memo\"]\n\n return param_json\n","sub_path":"yig/plugins/charasheet.py","file_name":"charasheet.py","file_ext":"py","file_size_in_byte":7543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"218557753","text":"import requests\nimport pandas as pd\n# Time\nimport globals\nfrom datetime import datetime, timedelta\nfrom dateutil.parser import parse\nimport pytz # for timeZones\n\n# constant to convert knots to km/h\nknToKmph = 1.852\n\n# for wind data. the angle is where the wind is coming from, measured anti-c from N\n# e.g. westerly 'W' means heading east (pointing -90deg anti-c from N)\ndirectionDict = { \n 'NE': 135, 'NNE': 157.5, 'N': 180, 'NNW': -157.5, 'NW': -135,\n 'WNW': -112.5, 'W': -90, 'WSW': -67.5,\n 'SW': -45, 'SSW': -22.5, 'S': 0, 'SSE': 22.5, 'SE': 45,\n 'ESE': 67.5, 'E': 90, 'ENE': 112.5,\n 'CALM': -90\n}\n\n# pandas dataframes for: wind/swell obswervation/forecast\ndef getDataFrames():\n frames = {}\n frames['WindObservation'] = initObservationWind()\n frames['WindForecast'] = initForecastWind()\n frames['SwellObservation'], frames['SwellForecast'] = initSwell()\n frames['Daylight'] = initDaylight()\n return frames\n\ndef initObservationWind():\n try:\n # from http://www.bom.gov.au/products/IDN60801/IDN60801.95745.shtml#other_formats under JSON link\n r = requests.get(url = \"http://www.bom.gov.au/fwo/IDN60701/IDN60701.95745.json\")\n data = r.json() \n dataList = data['observations']['data']\n \n dates = []\n speeds = []\n directions = []\n \n for pnt in dataList:\n date = parse(pnt['local_date_time_full'])\n if(globals.startTime <= date and date <= globals.finishTime):\n dates.append(date)\n speeds.append(pnt['wind_spd_kt'] * knToKmph)\n directions.append(directionDict[pnt['wind_dir']])\n \n df = pd.DataFrame(index=dates)\n df['speed'] = speeds # km/h\n df['direction'] = directions # towards anti-c +ve from N in degrees\n return df\n \n except requests.exceptions.RequestException as e:\n print('ERROR with requests.get() :\\n' + str(e))\n\ndef initForecastWind():\n try:\n # from https://github.com/tonyallan/weather-au use the first two links under 'Weather API'\n r = requests.get(url = \"https://api.weather.bom.gov.au/v1/locations/r3g7cg/forecasts/3-hourly\")\n data = r.json() \n dataList = data['data']\n \n dates = []\n speeds = []\n directions = []\n for pnt in dataList:\n date = parse(pnt['time']).replace(tzinfo=None)\n if(globals.currentTime <= date and date <= globals.finishTime):\n dates.append(date)\n speeds.append(pnt['wind']['speed_kilometre'])\n directions.append(directionDict[pnt['wind']['direction']])\n \n df = pd.DataFrame(index=dates)\n df['speed'] = speeds # km/h\n df['direction'] = directions # towards anti-c +ve from N in degrees\n return df\n \n except requests.exceptions.RequestException as e:\n print('ERROR with requests.get() :\\n' + str(e))\n\ndef initSwell():\n # 3000876 is the location coming into port kembla main beach @30m depth\n url = 'https://forecast.waves.nsw.gov.au/?page=series&id=3000876'\n \n response = requests.get(url)\n itemList = response.text.split(\"\\n\")\n \n DateObserved = []\n DateForecast = []\n Hsm = []\n # Tpm = [] # T is period (might need later)\n Dirm = []\n Hsf = []\n # Tpf = []\n Dirf = []\n \n itemList.pop(0) # pops heading: Date,Hsm,Tpm,Dirm,Hsf,Tpf,Dirf\n for x in itemList: \n row = x.split(\",\")\n if len(row) != 7:\n continue\n \n if row[1] != '': # observed height exists\n DateObserved.append(parse(row[0]))\n Hsm.append(float(row[1]))\n Dirm.append(180 - float(row[3]))\n if row[4] != '': # forecast height exists\n DateForecast.append(parse(row[0]))\n Hsf.append(float(row[4]))\n Dirf.append(180 - float(row[6]))\n \n dfObserved = pd.DataFrame(index=DateObserved)\n dfObserved['height'] = Hsm # Nearshore significant wave height tranformation from measured (m)\n dfObserved['direction'] = Dirm # Nearshore wave direction transformation from measured (° TNorth)\n \n dfForecast = pd.DataFrame(index=DateForecast)\n dfForecast['height'] = Hsf # Nearshore significant wave height tranformation from forecast (m)\n dfForecast['direction'] = Dirf # Nearshore wave direction transformation from forecast (° TNorth)\n \n return dfObserved, dfForecast\n\ndef initDaylight():\n day = '#FFFA4F' # day yellow colour for da sun :)\n night = '#7733FF' # puple night colour\n current = 'c' # cyan color to indicate the current time. Included in last df row\n \n # Thanks to the devs at Sunrise - Sunset. See https://sunrise-sunset.org/api\n r = requests.get(url = \"https://api.sunrise-sunset.org/json?lat=-34.5&lng=150.9&formatted=0\")\n data = r.json() \n \n # civil_twilight_begin/civil_twilight_end is civil_dawn/civil_dusk or firstlight/lastlight\n # civil_dawn/civil_dusk is rougly the time needed where \n # artificial light should be used for outdoor activities\n firstLightRaw = parse(data['results']['civil_twilight_begin'])\n lastLightRaw = parse(data['results']['civil_twilight_end'])\n\n firstLight = firstLightRaw.astimezone(globals.tzAus).replace(tzinfo=None)\n lastLight = lastLightRaw.astimezone(globals.tzAus).replace(tzinfo=None)\n\n fL_hour = firstLight.hour\n fL_min = firstLight.minute\n lL_hour = lastLight.hour\n lL_min = lastLight.minute\n\n day_delta = lastLight - firstLight\n night_delta = timedelta(hours=24) - day_delta\n\n df = pd.DataFrame()\n firstTime = globals.startTime # first time before start where day/night transition occurs\n if ((not isBeforeTime(globals.startTime, fL_hour, fL_min)) and isBeforeTime(globals.startTime, lL_hour, lL_min)): # day light\n firstTime = globals.startTime.replace(hour=fL_hour, minute=fL_min)\n df['lightColor'] = [day, night, day, current]\n df['lightStartTime'] = [ \n firstTime, \n firstTime + day_delta,\n firstTime + day_delta + night_delta,\n globals.currentTime - timedelta(minutes=5)\n ]\n df['lightFinishTime'] = [\n firstTime + day_delta, # the first interval is day so add the daylight duration\n firstTime + day_delta + night_delta,\n firstTime + day_delta + night_delta + day_delta,\n globals.currentTime + timedelta(minutes=5)\n ]\n else:\n if((not isBeforeTime(globals.startTime, lL_hour, lL_min)) and isBeforeTime(globals.startTime, 24, 0)): # arvo night\n firstTime = globals.startTime.replace(hour=lL_hour, minute=lL_min)\n else: # early hours\n firstTime = globals.startTime - timedelta(hours=fL_hour, minutes=fL_min)\n firstTime = firstTime.replace(hour=lL_hour, minute=lL_min)\n df['lightColor'] = [night, day, night, current]\n df['lightStartTime'] = [ \n firstTime, \n firstTime + night_delta,\n firstTime + night_delta + day_delta,\n globals.currentTime - timedelta(minutes=5)\n ]\n df['lightFinishTime'] = [\n firstTime + night_delta, # the first interval is night so add the night duration\n firstTime + night_delta + day_delta,\n firstTime + night_delta + day_delta + night_delta,\n globals.currentTime + timedelta(minutes=5)\n ]\n return df\n\ndef isBeforeTime(date, hour, minute):\n return (date.hour < hour) or (date.hour == hour and date.minute < minute)","sub_path":"repl/retrieve.py","file_name":"retrieve.py","file_ext":"py","file_size_in_byte":6984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514408738","text":"import zstackwoodpecker.test_state as ts_header\nimport os\nTestAction = ts_header.TestAction\ndef path():\n\n return dict(repeat=1, initial_formation=\"template5\", path_list=[\n [TestAction.create_mini_vm, \"vm1\", 'data_volume=false', 'cpu=2', 'memory=2', 'provisiong=thick'],\n [TestAction.create_volume, \"volume1\", \"=scsi,thin\"],\n [TestAction.attach_volume, \"vm1\", \"volume1\"],\n [TestAction.change_vm_ha, \"vm1\"],\n [TestAction.create_mini_vm, \"vm2\", 'data_volume=false', 'cpu=2', 'memory=2', 'provisiong=thin'],\n [TestAction.change_vm_ha, \"vm2\"],\n [TestAction.create_volume, \"volume2\", \"=scsi,thick\"],\n [TestAction.attach_volume, \"vm2\", \"volume2\"]] + [[TestAction.reboot_host, \"all\", \"soft_crash\"]]*5000)\n","sub_path":"integrationtest/vm/mini/paths/path106.py","file_name":"path106.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"428821002","text":"from random import randint\n\nfrom animat_sprite import AnimatSprite\nfrom hostile import HostileAnimat\nfrom peaceful import PeacefulAnimat\n\n\nclass Sheep(AnimatSprite, PeacefulAnimat):\n\n def __init__(self, *args, **kwargs):\n super(Sheep, self).__init__(*args, **kwargs)\n\n self.width, self.height = 65, 65\n self.image = \"sheep\"\n self.movement = \"sheep_bounce\"\n self.speed = 0.6\n\n self.health = 8\n\n self.wander()\n\n self.schedule(randint(4, 12))\n\n def get_drops(self):\n return [\"f5\"]\n\n def _on_event(self):\n self.make_sound(\"bleat\")\n self.schedule(randint(4, 12))\n\n\nclass Wolf(AnimatSprite, HostileAnimat):\n\n def __init__(self, *args, **kwargs):\n super(Wolf, self).__init__(*args, **kwargs)\n\n self.width, self.height = 65, 65\n self.image = \"wolf\"\n self.speed = 0.90\n\n self.health = 24\n\n self.wander()\n\n def get_prefix(self):\n return \"%swolf_\" % super(Wolf, self).get_prefix()\n\n def on_player_range(self, guid, distance):\n \"\"\"\n This keeps wolves from just up and attacking each other pointlessly.\n \"\"\"\n if guid.startswith(self.get_prefix()) and guid != self.chasing:\n return\n\n super(Wolf, self).on_player_range(guid, distance)\n\n","sub_path":"internals/entities/animals.py","file_name":"animals.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"142158161","text":"\n\nfrom xai.brain.wordbase.nouns._chilean import _CHILEAN\n\n#calss header\nclass _CHILEANS(_CHILEAN, ):\n\tdef __init__(self,): \n\t\t_CHILEAN.__init__(self)\n\t\tself.name = \"CHILEANS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"chilean\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_chileans.py","file_name":"_chileans.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"531842162","text":"from django.http import JsonResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.http import require_http_methods\nfrom django.views.decorators.csrf import csrf_exempt, csrf_protect\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.authentication import (\n\tSessionAuthentication, BasicAuthentication\n)\nfrom rest_framework.decorators import (\n\tapi_view, permission_classes,\n\tauthentication_classes\n)\nfrom rest_framework_simplejwt.serializers import TokenObtainPairSerializer\nfrom rest_framework_simplejwt.views import TokenObtainPairView\nfrom rest_framework_simplejwt.authentication import JWTAuthentication\n\nimport os\nimport json\nimport logging\nimport datetime as dt\nfrom datetime import datetime\nimport mysql.connector as mysql\n\nconfig = {\n 'host': 'bgplatformdb1.mysql.database.azure.com',\n 'user': 'bg37hayysoftadmin',\n 'password': 'DoNotHack2021',\n 'database': 'bluguarddb',\n # 'client_flags': [mysql.ClientFlag.SSL],\n # 'ssl_ca': 'C:/Users/User/Desktop/backup/Employment/Hayysoft Systems/MYSQL Server/DigiCertGlobalRootCA.crt.pem',\n 'port': '3306'\n}\n\n\ndef Create_Connector_To_DB():\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\tCursor.execute('SET GLOBAL connect_timeout = 10')\n\n\treturn Cursor\n\n\ndef dictfetchall(cursor):\n\tcolumns = [col[0] for col in cursor.description]\n\treturn [\n\t\tdict(zip(columns, row)) for row in cursor.fetchall()\n\t]\n\n\ndef Process_Files_For_Discharded_Users(Device_Mac, Patient_Tag):\n\tos.chdir('C:/Users/hayysoft/Documents/Scripts/interview/media')\n\ttry:\n\t\tos.rename(f'C:/Users/hayysoft/Documents/Scripts/interview/media/{Device_Mac}.json', f'C:/Users/hayysoft/Documents/Scripts/interview/media/Discharged_Patients/{Patient_Tag}.json')\n\texcept FileNotFoundError:\n\t\tpass\n\n\ndef Get_Device_ID_For_Symptom_Check_In(Wearer_ID):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''\n\t\tSELECT Device_ID,\n\t\t\tCONCAT(Device_Last_Updated_Date, ' ',\n Device_Last_Updated_Time) AS Datetime\n\t\tFROM TBL_Device\n\t\tWHERE Wearer_ID = %s\n\t'''\n\tparameter = (Wearer_ID,)\n\tCursor.execute(query, parameter)\n\tresults = Cursor.fetchall()\n\ttry:\n\t\tDevice_IDs = [row[0] for row in results]\n\t\tDatetimes = [row[1] for row in results]\n\texcept Exception:\n\t\treturn None, None\n\n\treturn Device_IDs, Datetimes\n\n\n\n# @require_http_methods(['POST'])\n# @csrf_exempt\ndef Crest_CR03_Symptoms_Check_In(request):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\tquery = '''\n\t\tSELECT Daily_Survey_Q2_Y1,\n\t\t\t Daily_Survey_Q2_Y2, Daily_Survey_Q2_Y3,\n\t\t\t Daily_Survey_Q2_Y4, Daily_Survey_Q2_Y5,\n\t\t\t Wearer_ID\n\t\tFROM tbl_daily_survey\n\t'''\n\tCursor.execute(query)\n\tresults = Cursor.fetchall()\n\tdata = [\n\t\t{\n\t\t\t'subject_id': 0,\n\t\t\t'device_id': 0,\n\t\t\t'datetime': '',\n\t\t\t'fever': row[0],\n\t\t\t'breathing': row[1],\n\t\t\t'coughing': row[2],\n\t\t\t'eating': row[3],\n\t\t\t'tiredness': row[4],\n\t\t\t'doctor': '',\n\t\t\t'photo': '',\n\t\t\t'cough_sound': ''\n\t\t} for row in results\n\t]\n\tWearer_IDs = [row[5] for row in results]\n\t# print(Wearer_IDs)\n\n\tDevice_IDs = []\n\tfor wearer_id in Wearer_IDs:\n\t\tresults = Get_Device_ID_For_Symptom_Check_In(wearer_id)\n\t\tDevice_ID = results[0]\n\t\tDatetimes = results[1]\n\t\tDevice_IDs.append((Device_ID, Datetimes))\n\n\tfor index, values in enumerate(Device_IDs):\n\t\tdata[index]['device_id'] = values[0]\n\t\tdata[index]['datetime'] = values[1]\n\n\treturn JsonResponse({\n\t\t'symptom': data\n\t})\n\n\n# @api_view(['POST'])\n# @permission_classes([IsAuthenticated])\n# @authentication_classes([JWTAuthentication])\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Crest_CR03_Check_Out_Patient(request):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tdata = json.loads(request.body)\n\tPatient_Tag = data['Patient_Tag']\n\n\tquery = '''\n\t\tSELECT COUNT(*) FROM TBL_Crest_Patient\n\t\tWHERE Patient_Tag = %s AND\n\t\t\t Patient_Discharged = %s\n\t'''\n\tparameters = (Patient_Tag, 0)\n\tCursor.execute(query, parameters)\n\tresults = dictfetchall(Cursor)\n\n\tif len(results) == 0:\n\t\treturn JsonResponse({\n\t\t\t'response': 'Patient ID does not exists OR already discharged'\n\t\t})\n\n\tquery = '''SELECT Wearer_ID, Patient_ID FROM TBL_Crest_Patient\n\t\t\t\tWHERE Patient_Tag = %s\n\t\t\t'''\n\tparameter = (Patient_Tag,)\n\tCursor.execute(query, parameter)\n\tresults = dictfetchall(Cursor)\n\ttry:\n\t\tWearer_ID = results[0]['Wearer_ID']\n\t\tPatient_ID = results[0]['Patient_ID']\n\n\t\tquery = '''UPDATE TBL_Wearer\n\t\t\t\t\tSET Status = %s\n\t\t\t\t\tWHERE Wearer_ID = %s\n\t\t\t\t'''\n\t\tparameters = ('Unassigned', Wearer_ID)\n\t\tCursor.execute(query, parameters)\n\t\tConnector.commit()\n\n\t\tquery = '''UPDATE TBL_Crest_Patient\n\t\t\t\t\tSET Patient_Discharged = %s\n\t\t\t\t\tWHERE Patient_ID = %s\n\t\t\t\t'''\n\t\tparameters = (1, Patient_ID)\n\t\tCursor.execute(query, parameters)\n\t\tConnector.commit()\n\n\t\tquery = '''SELECT Device_Mac FROM TBL_Device\n\t\t\t\t\tWHERE Wearer_ID = %s'''\n\t\tparameter = (Wearer_ID,)\n\t\tCursor.execute(query, parameter)\n\t\tresults = dictfetchall(Cursor)\n\t\tDevice_Mac = results[0]['Device_Mac']\n\t\tprint(f'Device_Mac = {Device_Mac}')\n\n\t\tProcess_Files_For_Discharded_Users(\n\t\t\tDevice_Mac, Patient_Tag\n\t\t)\n\texcept (LookupError, IndexError):\n\t\tpass\n\n\tlogger = logging.getLogger('Crest CR03 Check Out Patient')\n\tlogger.setLevel(logging.INFO)\n\n\tfile_handler = logging.FileHandler('C:/Users/hayysoft/Documents/LogFiles/Crest_CR03_Check_Out_Patient.log')\n\tformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\tfile_handler.setFormatter(formatter)\n\tlogger.addHandler(file_handler)\n\tlogger.info('\\nProgram started!')\n\tlogger.info(f'Patient_Tag = {Patient_Tag}')\n\tlogger.info('\\nProgram Finished!\\n\\n')\n\n\treturn JsonResponse({\n\t\t'response': 'Successfull'\n\t})\n\n\n\ndef Get_Patient_Tag_Checkout_Status(request, Wearer_ID):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\tquery = '''\n\t\tSELECT Patient_Tag, Patient_Discharged\n\t\tFROM TBL_Crest_Patient\n\t\tWHERE Wearer_ID = %s\n\t'''\n\tparameter = (Wearer_ID,)\n\tCursor.execute(query, parameter)\n\tresults = Cursor.fetchall()\n\tdata = [\n\t\t{\n\t\t\t'Patient_Tag': row[0],\n\t\t\t'Patient_Discharged': row[1]\n\t\t} for row in results\n\t]\n\ttry:\n\t\tdata = data[0]\n\texcept Exception:\n\t\tpass\n\n\treturn JsonResponse({\n\t\t'checkout_status': data\n\t})\n\n\n\n# @authentication_classes([JWTAuthentication])\n@permission_classes([IsAuthenticated])\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Post_Creat_Device_Alert(request):\n\tdata = json.loads(request.body)\n\tprint(data)\n\n\treturn JsonResponse({\n\t\t'data': data\n\t})\n\n\n\n# @authentication_classes([JWTAuthentication])\n@permission_classes([IsAuthenticated])\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Post_Creat_Checkin_Api(request):\n\tdata = json.loads(request.body)\n\tprint(json.dumps(data, indent=4))\n\n\treturn JsonResponse({\n\t\t'data': data\n\t})\n\n\n\ndef Fetch_Crest_TBL_Patient():\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = 'SELECT * FROM Crest_TBL_Patient'\n\tCursor.execute(query)\n\trows = Cursor.fetchall()\n\n\tfor row in rows:\n\t query = '''\n\t SELECT * FROM tbl_device WHERE\n\t Device_Tag = %s\n\t '''\n\t Device_Tag = row[3]\n\t parameter = (Device_Tag,)\n\t Cursor.execute(query, parameter)\n\t results = Cursor.fetchall()\n\t for result in results:\n\t Subject_ID = row[0]\n\t Device_ID = result[0]\n\t Gateway_Mac = result[-4]\n\t query = '''\n\t SELECT * FROM tbl_gateway\n\t WHERE Gateway_Mac = %s\n\t '''\n\t parameter = (Gateway_Mac,)\n\t Cursor.execute(query, parameter)\n\t gateway_results = Cursor.fetchall()\n\t for gateway in gateway_results:\n\t Latitude = gateway[6]\n\t Longitude = gateway[7]\n\t Datetime = datetime.now().time()\n\t Device_Temp = result[8]\n\t Device_HR = result[9]\n\t Device_O2 = result[10]\n\t Respiratory_Rate = 0\n\t Data_To_Submit = {\n\t 'subject_id': Subject_ID,\n\t 'device_id': Device_ID,\n\t 'datetime': str(Datetime),\n\t 'latitude': str(Latitude),\n\t 'longitude': Longitude,\n\t 'temperature': Device_Temp,\n\t 'SpO2': Device_O2,\n\t 'heartrate': Device_HR,\n\t 'respiratory_rate': Respiratory_Rate\n\t }\n\n\n\n\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Post_Data_To_API(request):\n data = json.loads(request.body)\n\n return JsonResponse(data)\n\n\n\n\ndef Check_Device_Tag(Device_Tag):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''SELECT COUNT(*) FROM TBL_Wearer\n WHERE Status = %s AND Wearer_ID IN (\n \tSELECT Wearer_ID FROM TBL_Device\n \tWHERE Device_Tag = %s\n )'''\n\tparameter = ('Unassigned', Device_Tag)\n\tCursor.execute(query, parameter)\n\tresults = Cursor.fetchall()\n\n\tif results[0][0] != 0:\n\t return 1\n\n\treturn 0\n\n\n# @api_view(['POST'])\n@require_http_methods(['POST'])\n@csrf_exempt\n# @permission_classes([IsAuthenticated])\n# @authentication_classes([JWTAuthentication])\ndef Post_CR03_Registration(request):\n\tdata = json.loads(request.body)\n\tPatient_Tag = data['Patient_Tag']\n\tDevice_Tag = data['Device_Tag']\n\n\tband_tag_check = Check_Device_Tag(Device_Tag)\n\tresults = None\n\n\tif band_tag_check == 0:\n\t\tresults = 0\n\telse:\n\t\tConnector = mysql.connect(**config)\n\t\tCursor = Connector.cursor()\n\n\t\tquery = '''\n\t\t\tUPDATE TBL_Wearer\n\t\t\tSET Status = %s\n\t\t\tWHERE Wearer_ID IN (\n\t\t\t\tSELECT Wearer_ID FROM TBL_Device\n\t\t\t\tWHERE Device_Tag = %s\n\t\t\t)\n\t\t'''\n\t\tprint(f'Device_Tag = {Device_Tag}')\n\t\tparameters = ('Assigned', Device_Tag)\n\t\tCursor.execute(query, parameters)\n\t\tConnector.commit()\n\n\t\tquery = '''\n\t\tINSERT INTO TBL_Crest_Patient\n\t\t (Patient_ID, Patient_Tag, Device_Tag,\n\t\t Created_Date, Created_Time, Wearer_ID,\n\t\t Patient_Discharged)\n\t\tVALUES ((SELECT Create_PK(\"PID\")), %s, %s, CURDATE(),\n\t\t CURTIME(), (\n\t\t SELECT Wearer_ID FROM tbl_wearer\n\t\t WHERE Wearer_ID = (\n\t\t SELECT Wearer_ID FROM tbl_device\n\t\t WHERE Device_Tag = %s\n\t\t )\n\t\t ), %s)\n\n\t\t'''\n\t\tparameters = (Patient_Tag, Device_Tag, Device_Tag, 0)\n\t\tCursor.execute(query, parameters)\n\t\tConnector.commit()\n\t\tresults = 1\n\n\tlogger = logging.getLogger('Post CR03 Registration')\n\tlogger.setLevel(logging.INFO)\n\n\tfile_handler = logging.FileHandler('C:/Users/hayysoft/Documents/LogFiles/Post_CR03_Registration.log')\n\tformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\tfile_handler.setFormatter(formatter)\n\tlogger.addHandler(file_handler)\n\tlogger.info('\\nProgram started!')\n\tlogger.info(f'Patient_Tag = {Patient_Tag}')\n\tlogger.info(f'Device_Tag = {Device_Tag}')\n\tlogger.info('Program Finished!\\n\\n')\n\n\n\treturn JsonResponse({\n \t'results': results\n })\n\n\n\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Post_Wearer_Login(request):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tdata = json.loads(request.body)\n\tUser_LogIn = data['Wearer_Nick']\n\tUser_Pwd = data['Wearer_Pwd']\n\n\tquery = '''\n\t\tSELECT * FROM tbl_user\n\t\tWHERE User_LogIn = %s AND\n\t\t\t User_Pwd = %s\n\t'''\n\tparameters = (User_LogIn, User_Pwd)\n\tCursor.execute(query, parameters)\n\tresults = Cursor.fetchall()\n\n\tdata = [\n\t\t{\n\t\t\t'Wearer_ID': row[0],\n\t\t\t'Wearer_Nick': row[1],\n\t\t\t'Wearer_Pwd': row[2]\n\t\t} for row in results\n\t]\n\n\ttry:\n\t\tdata = data[0]\n\texcept Exception:\n\t\tdata = data\n\n\treturn JsonResponse({\n\t\t'Wearer_Data': data\n\t})\n\n\n\n\ndef Get_Wearer_All_Devices(request, Wearer_ID):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''\n\t\tSELECT * FROM tbl_device\n\t\tWHERE Wearer_ID = %s\n\t'''\n\tparameter = (Wearer_ID,)\n\tCursor.execute(query, parameter)\n\tresults = Cursor.fetchall()\n\n\tdata = [\n\t\t{\n\t\t\t'Device_ID': row[0],\n\t\t\t'Device_Type': row[1],\n\t\t\t'Device_Serial_No': row[2],\n\t\t\t'Device_Mac': row[3],\n\t\t\t'Device_Bat_Level': row[4],\n\t\t\t'Device_Last_Updated_Date': row[5],\n\t\t\t'Device_Last_Update_Time': row[6],\n\t\t\t'Wearer_ID': row[7],\n\t\t\t'Device_Temp': row[8],\n\t\t\t'Device_HR': row[9],\n\t\t\t'Device_O2': row[10],\n\t\t\t'Incoming_ID': row[11],\n\t\t\t'Device_RSSI': row[12],\n\t\t\t'Gateway_Mac': row[13],\n\t\t\t'Incorrect_Data_Flag': row[14],\n\t\t\t'Device_Status': row[13],\n\t\t\t'Device_Tag': row[15],\n\t\t} for row in results\n\t]\n\n\treturn JsonResponse({\n\t\t'Wearer_Data': data\n\t})\n\n\n\n\n\ndef Get_Wearer_Alert(request, Wearer_ID):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''\n\t\tSELECT Alert_ID, Alert_Code, Alert_Datetime,\n\t\t\t Device_ID, Alert_Reading\n\t\tFROM TBL_Alert\n\t\tWHERE Device_ID IN\n\t\t\t(SELECT Device_ID FROM tbl_device\n\t\t\tWHERE Wearer_ID = %s)\n\t'''\n\tparameter = (Wearer_ID,)\n\tCursor.execute(query, parameter)\n\tresults = Cursor.fetchall()\n\n\tdata = [\n\t\t{\n\t\t\t'Alert_ID': row[0],\n\t\t\t'Alert_Code': row[1],\n\t\t\t'Alert_Date': row[2].date(),\n\t\t\t'Alert_Time': row[2].time(),\n\t\t\t'Device_ID': row[3],\n\t\t\t'Alert_Reading': row[4]\n\t\t} for row in results\n\t]\n\n\treturn JsonResponse({\n\t\t'Wearer_Alert': data\n\t})\n\n\n\ndef Get_Wearer_Message(request, Wearer_ID):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''\n\t\tSELECT * FROM TBL_Message\n\t\tWHERE Wearer_ID = %s OR\n\t\tWearer_ID = 'ALL'\n\t'''\n\tparameter = (Wearer_ID,)\n\tCursor.execute(query, parameter)\n\tresults = Cursor.fetchall()\n\n\tdata = [\n\t\t{\n\t\t\t'Message_ID': row[0],\n\t\t\t'Message_Description': row[1],\n\t\t\t'Message_Date': row[2],\n\t\t\t'Message_Time': row[3],\n\t\t\t'Message_Type': row[4],\n\t\t\t'User_ID': row[5],\n\t\t\t'Wearer_ID': row[6]\n\t\t} for row in results\n\t]\n\n\treturn JsonResponse({\n\t\t'Wearer_Alert': data\n\t})\n\n\n\n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef Get_All_Users_Data(request):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = 'SELECT * FROM tbl_user';\n\tCursor.execute(query)\n\tresults = Cursor.fetchall()\n\tdata = [\n\t\t{'User_ID': row[0]} for row in results\n\t]\n\n\treturn JsonResponse({\n\t\t'User_IDs': data\n\t})\n\n\n\ndef Get_Wearer_Survey(request, Daily_Survey_Session, Wearer_ID):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''\n\t\tSELECT * FROM TBL_Daily_Survey\n\t\tWHERE Daily_Survey_Session = %s AND Wearer_ID = %s\n\t'''\n\tparameters = (Daily_Survey_Session, Wearer_ID)\n\tCursor.execute(query, parameters)\n\tresults = Cursor.fetchall()\n\tdata = [\n\t\t{\n\t\t\t'Daily_Survey_ID': row[0],\n\t\t\t'Daily_Survey_Q1': row[1],\n\t\t\t'Daily_Survey_Q2_Y1': row[2],\n\t\t\t'Daily_Survey_Q2_Y2': row[3],\n\t\t\t'Daily_Survey_Q2_Y3': row[4],\n\t\t\t'Daily_Survey_Q2_Y4': row[5],\n\t\t\t'Daily_Survey_Q2_Y5': row[6],\n\t\t\t# 'Daily_Survey_Q2_N': row[7],\n\t\t\t'Daily_Survey_Q3': row[7],\n\t\t\t'Daily_Survey_Date': row[8],\n\t\t\t'Daily_Survey_Time': row[9],\n\t\t\t'Daily_Survey_Session': row[10],\n\t\t\t'Wearer_ID': row[11]\n\t\t} for row in results\n\t]\n\n\treturn JsonResponse({\n\t\t'Wearer_Survey': data\n\t})\n\n\n\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Post_Wearer_Survey(request):\n\tdata = json.loads(request.body)\n\n\tDaily_Survey_Q1 = data['Daily_Survey_Q1']\n\tDaily_Survey_Q2_Y1 = data['Daily_Survey_Q2_Y1']\n\tDaily_Survey_Q2_Y2 = data['Daily_Survey_Q2_Y2']\n\tDaily_Survey_Q2_Y3 = data['Daily_Survey_Q2_Y3']\n\tDaily_Survey_Q2_Y4 = data['Daily_Survey_Q2_Y4']\n\tDaily_Survey_Q2_Y5 = data['Daily_Survey_Q2_Y5']\n\t# Daily_Survey_Q2_N = data['Daily_Survey_Q2_N']\n\tDaily_Survey_Q3 = data['Daily_Survey_Q3']\n\tDaily_Survey_Date = data['Daily_Survey_Date']\n\tDaily_Survey_Time = data['Daily_Survey_Time']\n\tDaily_Survey_Session = data['Daily_Survey_Session']\n\tWearer_ID = data['Wearer_ID']\n\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''\n\tINSERT INTO TBL_Daily_Survey (\n\t\tDaily_Survey_ID,\n\t\tDaily_Survey_Q1,\n\t\tDaily_Survey_Q2_Y1,\n\t\tDaily_Survey_Q2_Y2,\n\t\tDaily_Survey_Q2_Y3,\n\t\tDaily_Survey_Q2_Y4,\n\t\tDaily_Survey_Q2_Y5,\n\t\tDaily_Survey_Q3,\n\t\tDaily_Survey_Date,\n\t\tDaily_Survey_Time,\n\t\tDaily_Survey_Session,\n\t\tWearer_ID\n\t) VALUES (\n\t\t(SELECT Create_PK(\"SVY\")),\n\t\t%s,\n\t\t%s,\n\t\t%s,\n\t\t%s,\n\t\t%s,\n\t\t%s,\n\t\t%s,\n\t\t%s,\n\t\t%s,\n\t\t%s,\n\t\t%s\n\t)\n\t'''\n\tparameters = (\n\t\tDaily_Survey_Q1,\n\t\tDaily_Survey_Q2_Y1,\n\t\tDaily_Survey_Q2_Y2,\n\t\tDaily_Survey_Q2_Y3,\n\t\tDaily_Survey_Q2_Y4,\n\t\tDaily_Survey_Q2_Y5,\n\t\tDaily_Survey_Q3,\n\t\tDaily_Survey_Date,\n\t\tDaily_Survey_Time,\n\t\tDaily_Survey_Session,\n\t\tWearer_ID\n\t)\n\tCursor.execute(query, parameters)\n\tConnector.commit()\n\n\n\treturn JsonResponse({\n\t\t'message': 'Daily_Survey was inserted successfully!'\n\t})\n\n\n\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Delete_Message(request):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tdata = json.loads(request.body)\n\tMessage_ID = data['Message_ID']\n\n\tquery = '''\n\t\tDELETE FROM tbl_message\n\t\tWHERE Message_ID = %s\n\t'''\n\tparameter = (Message_ID,)\n\tCursor.execute(query, parameter)\n\tConnector.commit()\n\n\treturn JsonResponse({\n\t\t'message': f'Message_ID = {Message_ID} was successfully deleted!'\n\t})\n\n\n\ndef Get_All_Users(request):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = 'SELECT User_ID, User_Name FROM tbl_user';\n\tCursor.execute(query)\n\tresults = Cursor.fetchall()\n\tdata = [\n\t\t{\n\t\t\t'User_ID': row[0],\n\t\t\t'User_Name': row[1],\n\t\t\t'Device_ID': ''\n\t\t} for row in results\n\t]\n\n\tdata = []\n\tfor row in results:\n\t\tUser_ID = row[0]\n\t\tquery = '''\n\t\t\tSELECT Device_ID FROM TBL_Device\n\t\t\t\tWHERE Wearer_ID IN (\n\t\t\t\t\tSELECT Wearer_ID FROM TBL_Wearer\n\t\t\t\t\t\tWHERE User_ID = %s\n\t\t\t\t)\n\t\t'''\n\t\tparameter = (User_ID,)\n\t\tCursor.execute(query, parameter)\n\t\tresults_ = dictfetchall(Cursor)\n\t\ttry:\n\t\t\tDevice_ID = results_[0]['Device_ID']\n\t\texcept:\n\t\t\tDevice_ID = ''\n\n\t\tdata.append({\n\t\t\t'User_ID': User_ID,\n\t\t\t'User_Name': row[1],\n\t\t\t'Device_ID': Device_ID\n\t\t})\n\n\n\n\treturn JsonResponse({\n\t\t'User_IDs': data\n\t})\n\n\n\ndef Fetch_One_Or_Many(field, tablename, query):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tif field == 'NULL':\n\t\tCursor.execute(f'SELECT * FROM {tablename}')\n\telse:\n\t\tparameter = (field,)\n\t\tCursor.execute(query, parameter)\n\n\treturn Cursor\n\n\ndef Get_Alert(request, Wearer_ID='NULL'):\n\t# Cursor = Fetch_One_Or_Many(Wearer_ID, 'TBL_Alert',\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\tquery = '''SELECT * FROM TBL_Alert\n\t\t\t\tWHERE Device_ID IN\n\t\t\t\t(SELECT Device_ID FROM tbl_device\n\t\t\t\tWHERE Wearer_ID = %s)\n\t\t\t\tORDER BY Device_ID DESC LIMIT 5\n\t'''\n\tparameter = (Wearer_ID,)\n\tCursor.execute(query, parameter)\n\n\ttry:\n\t\tresults = dictfetchall(Cursor)\n\t\tdata = [\n\t\t\t{\n\t\t\t\t'Alert_ID': row['Alert_ID'],\n\t\t\t\t'Alert_Code': row['Alert_Code'],\n\t\t\t\t'Alert_Date': row['Alert_Datetime'].date(),\n\t\t\t\t'Alert_Time': row['Alert_Datetime'].time(),\n\t\t\t\t'Device_ID': row['Device_ID'],\n\t\t\t\t'Alert_Datetime': row['Alert_Datetime']\n\t\t\t} for row in results\n\t\t]\n\texcept Exception:\n\t\tdata = []\n\n\treturn JsonResponse({\n\t\t'Alert': data\n\t})\n\n\n\ndef Get_User_Message(request, User_id):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = \"\"\"SELECT * FROM TBL_Message\n\t\tWHERE User_ID = %s OR\n\t\tUser_ID = 'ALL'\"\"\"\n\tparameter = (User_id,)\n\tCursor.execute(query, parameter)\n\n\n\tresults = Cursor.fetchall()\n\tdata = [\n\t\t{\n\t\t\t'Message_ID': row[0],\n\t\t\t'Message_Description': row[1],\n\t\t\t'Message_Date': row[2],\n\t\t\t'Mesage_Time': row[3],\n\t\t\t'Message_Type': row[4],\n\t\t\t'User_ID': row[5]\n\t\t} for row in results\n\t]\n\n\treturn JsonResponse({\n\t\t'Message': data\n\t})\n\n\n\ndef Fetch_One(field, query):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tparameter = (field,)\n\tCursor.execute(query, parameter)\n\n\treturn Cursor\n\n\ndef Get_User_Password(request, User_id):\n\tCursor = Fetch_One(User_id,\n\t\t\t\t '''SELECT User_Pwd FROM tbl_user\n\t\t\t\t\t WHERE User_ID = %s''')\n\n\ttry:\n\t\tresults = Cursor.fetchone()[0]\n\texcept (IndexError, TypeError):\n\t\tresults = ''\n\n\treturn JsonResponse({\n\t\t'User_Pwd': results\n\t})\n\n\n\ndef Get_User_ID(request, User_Login):\n\tCursor = Fetch_One(User_Login,\n\t\t\t\t '''SELECT * FROM tbl_user\n\t\t\t\t\t WHERE User_LogIn = %s''')\n\n\ttry:\n\t\tresults = Cursor.fetchone()\n\t\tdata = [\n\t\t\t{'User_ID': results[0],\n\t\t\t 'User_Name': results[1],\n\t\t\t 'User_Email': results[2],\n\t\t\t 'User_Login': results[3],\n\t\t\t 'User_Pwd': results[4],\n\t\t\t 'Org_ID': results[5]}\n\t\t]\n\t\tresults = data\n\texcept (IndexError, TypeError):\n\t\tresults = ''\n\n\treturn JsonResponse({\n\t\t'User': results\n\t})\n\n\n\ndef Get_Subscribed_Device(request, User_id='NULL'):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tif User_id == 'NULL':\n\t\tCursor.execute(f'SELECT * FROM tbl_subscription')\n\telse:\n\t\tquery = '''SELECT Device_ID FROM tbl_subscription\n\t\t\t\t\t WHERE User_ID = %s'''\n\t\tparameter = (User_id,)\n\t\tCursor.execute(query, parameter)\n\n\t# Cursor = Fetch_One(User_id,\n\t# \t\t\t '''SELECT Device_ID FROM tbl_subscription\n\t# \t\t\t\t WHERE User_ID = %s''')\n\n\tresults = Cursor.fetchall()\n\tvalues = []\n\tfor result in results:\n\t\tvalues.append({f'Device_ID': result[0]})\n\tresults = values\n\n\treturn JsonResponse({\n\t\t'Device': results\n\t})\n\n\ndef Get_All_Unsubscribed_Device(request):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''SELECT * FROM TBL_Device\n\t\t\t WHERE Device_ID NOT IN\n\t\t\t (SELECT Device_ID FROM tbl_subscription)'''\n\tCursor.execute(query)\n\tresults = Cursor.fetchall()\n\n\tdata = [\n\t\t{\n\t\t\t'Device_ID': row[0],\n\t\t\t'Device_Type': row[1],\n\t\t\t'Device_Serial_No': row[2],\n\t\t\t'Device_Mac': row[3],\n\t\t\t'Device_Bat_Level': row[4],\n\t\t\t'Device_Last_Updated_Date': row[5],\n\t\t\t'Device_Last_Update_Time': row[6],\n\t\t\t'Wearer_ID': row[7],\n\t\t\t'Device_Temp': row[8],\n\t\t\t'Device_HR': row[9],\n\t\t\t'Device_O2': row[10],\n\t\t\t'Incoming_ID': row[11]\n\t\t} for row in results\n\t]\n\tresults = data\n\n\treturn JsonResponse({\n\t\t'Device': results\n\t})\n\n\ndef Get_Unsubscribed_Device(request, User_id='NULL'):\n\tCursor = Fetch_One(User_id,\n\t\t\t\t '''SELECT Device_ID FROM TBL_Device\n\t\t\t\t\t WHERE Device_ID NOT IN\n\t\t\t\t\t (SELECT Device_ID FROM tbl_subscription\n\t\t\t\t\t WHERE User_ID = %s)''')\n\n\tresults = Cursor.fetchall()\n\tx = 1\n\tvalues = []\n\tfor result in results:\n\t\tvalues.append({f'Device_ID': result[0]})\n\tresults = values\n\n\treturn JsonResponse({\n\t\t'Device_ID': results\n\t})\n\n\ndef Get_All_Device(request):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = 'SELECT Device_ID FROM tbl_device'\n\tCursor.execute(query)\n\n\tresults = Cursor.fetchall()\n\tx = 1\n\tdata = {}\n\tfor result in results:\n\t\tdata[f'Device_ID_{x}'] = result[0]\n\t\tx += 1\n\tresults = data\n\n\treturn JsonResponse({\n\t\t'Device_ID': results\n\t})\n\n\ndef Get_Wearer(request, Device_ID='NULL'):\n\tCursor = Fetch_One(Device_ID,\n\t\t\t '''SELECT * FROM tbl_wearer\n\t\t\t\t WHERE Wearer_ID IN\n\t\t\t\t (SELECT Wearer_ID FROM TBL_Device\n\t\t\t \t WHERE Device_ID = %s)''')\n\n\tresults = Cursor.fetchall()\n\tdata = [\n\t\t{\n\t\t\t'Wearer_ID': row[0],\n\t\t\t'Wearer_Nick': row[1]\n\t\t} for row in results\n\t]\n\tresults = data\n\n\treturn JsonResponse({\n\t\t'Wearer': results[0]\n\t})\n\n\n\ndef Get_Device_Vital(request, Device_ID='NULL'):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''SELECT Device_Temp, Device_HR, Device_O2\n\tFROM TBL_Device WHERE Device_ID = %s'''\n\n\tparameter = (Device_ID,)\n\tCursor.execute(query, parameter)\n\tresults = Cursor.fetchall()\n\tdata = [\n\t\t{\n\t\t\t'Device_Temp': row[0],\n\t\t\t'Device_HR': row[1],\n\t\t\t'Device_O2': row[2]\n\t\t} for row in results\n\t]\n\n\ttry:\n\t\tresults = data[0]\n\texcept Exception:\n\t\tresults = []\n\n\treturn JsonResponse({\n\t\t'Device_Vital': results\n\t})\n\n\n\ndef Get_Ack(request, Alert_ID):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''SELECT * FROM TBL_Acknowledgement\n\t\t\t WHERE Alert_ID = %s'''\n\tparameter = (Alert_ID,)\n\tCursor.execute(query, parameter)\n\tresults = Cursor.fetchall()\n\n\ttry:\n\t\tdata = [\n\t\t\t{\n\t\t\t\t'Ack_ID': row[0],\n\t\t\t\t'User_ID': row[1],\n\t\t\t\t'Ack_Date': row[2],\n\t\t\t\t'Ack_Time': row[3],\n\t\t\t\t'Alert_ID': row[4]\n\t\t\t} for row in results\n\t\t]\n\t\tresults = data[0]\n\texcept IndexError:\n\t\tresults = []\n\n\treturn JsonResponse({\n\t\t'Ack': results\n\t})\n\n\ndef Post_Update_Values(field1, field2, query):\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tif field1 == 'NULL' or field2 == 'NULL':\n\t\tresults = 0\n\telse:\n\t\tparameter = (field1, field2,)\n\t\tCursor.execute(query, parameter)\n\t\tConnector.commit()\n\t\tresults = 1\n\n\treturn results\n\n\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Post_Add_Subscription(request):\n\tdata = json.loads(request.body)\n\tUser_ID = data['User_ID']\n\tWearer_ID = data['Wearer_ID']\n\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''SELECT Device_ID FROM TBL_Device\n\t\t\t WHERE Wearer_ID = %s'''\n\tparameter = (Wearer_ID,)\n\tCursor.execute(query, parameter)\n\tresults = Cursor.fetchall()\n\tfor row in results:\n\t\tquery = '''INSERT INTO tbl_subscription\n\t\t\t\t\t\tVALUES ((SELECT Create_PK(\"SUBS\")), %s, %s,\n\t\t\t\t\t\t\t CURRENT_DATE(), CURRENT_TIME())'''\n\t\tparameter = (User_ID, row[0],)\n\t\tCursor.execute(query, parameter)\n\t\tConnector.commit()\n\n\treturn JsonResponse({\n\t\t'Add_Subscription': results\n\t})\n\n\n\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Post_Change_Password_Wearer(request):\n\tdata = json.loads(request.body)\n\tUser_LogIn = data['Wearer_ID']\n\tUser_Pwd = data['Wearer_Pwd']\n\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''UPDATE tbl_user\n\t\t\t\tSET User_Pwd = %s\n\t\t\t\tWHERE User_LogIn = %s\n\t'''\n\tparameter = (User_Pwd, User_LogIn)\n\tCursor.execute(query, parameter)\n\tConnector.commit()\n\n\n\treturn JsonResponse({\n\t\t'Change_Password-Tbl-Wearer': f'Password for User_LogIn = {User_LogIn} changed successfully!'\n\t})\n\n\n\n\n\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Post_Change_Password(request):\n\tdata = json.loads(request.body)\n\tUser_ID = data['User_ID']\n\tNew_Password = data['New_Password']\n\n\tif User_ID == 'NULL' or New_Password == 'NULL':\n\t\tresults = 0\n\telse:\n\t\tConnector = mysql.connect(**config)\n\n\t\tCursor = Connector.cursor()\n\n\t\tquery = '''SELECT * FROM tbl_user\n\t\t\tWHERE User_ID = %s'''\n\t\tparameter = (User_ID,)\n\t\tCursor.execute(query, parameter)\n\t\tresults = Cursor.fetchone()\n\t\tif results is None:\n\t\t\tresults = 0\n\t\telse:\n\t\t\tquery = '''UPDATE tbl_user\n\t\t\t\tSET User_Pwd = %s\n\t\t\t\tWHERE User_ID = %s'''\n\t\t\tparameter = (New_Password, User_ID)\n\t\t\tCursor.execute(query, parameter)\n\t\t\tConnector.commit()\n\t\t\tresults = 1\n\n\treturn JsonResponse({\n\t\t'Change_Password-Tbl-User': results\n\t})\n\n\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Post_Change_Email(request):\n\tdata = json.loads(request.body)\n\tUser_ID = data['User_ID']\n\tNew_Email = data['New_Email']\n\n\tif User_ID == 'NULL' or New_Email == 'NULL':\n\t\tresults = 0\n\telse:\n\t\tConnector = mysql.connect(**config)\n\n\t\tCursor = Connector.cursor()\n\t\tquery = '''SELECT * FROM tbl_user\n\t\t\tWHERE User_ID = %s'''\n\t\tparameter = (User_ID,)\n\t\tCursor.execute(query, parameter)\n\t\tresults = Cursor.fetchone()\n\t\tif results is None:\n\t\t\tresults = 0\n\t\telse:\n\t\t\tquery = '''UPDATE tbl_user\n\t\t\t\tSET User_Email = %s\n\t\t\t\tWHERE User_ID = %s'''\n\t\t\tparameter = (New_Email, User_ID)\n\t\t\tCursor.execute(query, parameter)\n\t\t\tConnector.commit()\n\t\t\tresults = 1\n\n\treturn JsonResponse({\n\t\t'Change_Email': results\n\t})\n\n\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Post_Acknowledgement_Alert(request):\n\tdata = json.loads(request.body)\n\tUser_ID = data['User_ID']\n\tAlert_ID = data['Alert_ID']\n\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''INSERT INTO TBL_Acknowledgement\n\t\t\t\t(Ack_ID, User_ID, Ack_Date,\n\t\t\t\t Ack_Time, Alert_ID)\n\t\t\t\tVALUES ((SELECT Create_PK(\"ACK\")), %s,\n\t\t\t\t\t\t CURRENT_DATE(), CURRENT_TIME(),\n\t\t\t\t\t\t %s)'''\n\tparameter = (User_ID, Alert_ID,)\n\tCursor.execute(query, parameter)\n\tConnector.commit()\n\n\treturn JsonResponse({\n\t\t'Add_Subscription': \"Data inserted successfully!\"\n\t})\n\n\n\n\n@require_http_methods(['POST'])\n@csrf_exempt\ndef Post_User_Login(request):\n\tdata = json.loads(request.body)\n\tusername = data.get('User_Name')\n\tpassword = data.get('User_Pwd')\n\n\tConnector = mysql.connect(**config)\n\tCursor = Connector.cursor()\n\n\tquery = '''SELECT * FROM tbl_user\n\t\t\t WHERE User_Name = %s AND User_Pwd = %s'''\n\tparameters = (username, password,)\n\tCursor.execute(query, parameters)\n\tresults = Cursor.fetchall()\n\tdata = [\n\t\t{'User_ID': row[0],\n\t\t 'User_Name': row[1],\n\t\t 'User_Email': row[2],\n\t\t 'User_LogIn': row[3],\n\t\t 'User_Pwd': row[4]\n\t\t } for row in results\n\t]\n\ttry:\n\t\tresults = data[0]\n\t\treturn JsonResponse({\n\t\t\t'User_Info': results\n\t\t}, status=200)\n\texcept IndexError:\n\t\treturn JsonResponse({\n\t\t\t'User_Info': results\n\t\t}, status=204)\n\n\t# return JsonResponse({\n\t# \t'User_Info': results\n\t# })\n\n\n","sub_path":"apiapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":28134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"125986632","text":"#!/usr/bin/env python\nfrom pyaib.components import component_class\n\n\n@component_class(\"acl\")\nclass ACL(object):\n def __init__(self, context, config):\n self.permissions = config.get(\"permissions\", {})\n\n def allowed(self, trigger, chan, nick):\n channel = self.permissions.get(chan, {})\n cmd = channel.get(trigger, {})\n\n denied_nicks = set(cmd.get(\"deny\", []))\n if any([(nick in denied_nicks), ('*' in denied_nicks)]):\n return False\n\n allowed_nicks = set(cmd.get(\"allow\", []))\n if any([(nick in allowed_nicks), ('*' in allowed_nicks)]):\n return True\n\n return False if cmd else True\n","sub_path":"dinbot/components/acl.py","file_name":"acl.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}
    '+i+'